@20baht/live 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +142 -2
- package/dist/browser.d.ts +164 -0
- package/dist/browser.js +404 -0
- package/dist/elysia.d.ts +332 -0
- package/dist/elysia.js +131 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/live.d.ts +81 -0
- package/dist/live.js +393 -0
- package/dist/pg.d.ts +81 -0
- package/dist/pg.js +214 -0
- package/dist/protocol.d.ts +112 -0
- package/dist/protocol.js +122 -0
- package/dist/source.d.ts +17 -0
- package/dist/source.js +24 -0
- package/dist/topics.d.ts +10 -0
- package/dist/topics.js +25 -0
- package/package.json +86 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Nattapong Promthong
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,143 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @20baht/live
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Server-authoritative live queries for Elysia, over server-sent events.
|
|
4
|
+
|
|
5
|
+
A route you already have becomes live with one option. Whoever reads it keeps getting what it
|
|
6
|
+
answers **now**: when the data under it changes, in the database (any writer, a person in a SQL
|
|
7
|
+
client too) or in your server's code, the server runs the route again and pushes the new answer,
|
|
8
|
+
or only the rows that changed. The browser never polls and never decides what the answer is. An
|
|
9
|
+
edit of its own shows at once and gives way to the server's answer when it arrives.
|
|
10
|
+
|
|
11
|
+
Spec: [`spec/09-live.md`](../../../spec/09-live.md).
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
bun add @20baht/live
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
| Entry | What it holds |
|
|
18
|
+
| --- | --- |
|
|
19
|
+
| `@20baht/live` | `createLive` (the hub of one process), `memorySource`, topics, the frame protocol |
|
|
20
|
+
| `@20baht/live/elysia` | `livePlugin` (once, at the root: the option, `POST /live`, `GET /live/health`), `liveMacro` (the option alone, for modules), `liveRoute`, `bindLive` |
|
|
21
|
+
| `@20baht/live/pg` | `liveTriggers` (the SQL for a migration), `pgSource`, `postgresJsListener`, `pgliteListener`, `changed` |
|
|
22
|
+
| `@20baht/live/browser` | `liveClient` / `createLiveClient`, `typedLive`, `guess`, `rebase` |
|
|
23
|
+
|
|
24
|
+
`elysia` and `drizzle-orm` are optional peers. Angular: `liveSignal` in `@20baht/angular/live`.
|
|
25
|
+
|
|
26
|
+
## Server
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
import postgres from 'postgres';
|
|
30
|
+
import { Elysia } from 'elysia';
|
|
31
|
+
import { createLive } from '@20baht/live';
|
|
32
|
+
import { bindLive, liveMacro, livePlugin, liveRoute } from '@20baht/live/elysia';
|
|
33
|
+
import { pgSource, postgresJsListener } from '@20baht/live/pg';
|
|
34
|
+
|
|
35
|
+
// once per process, at the root: one LISTEN connection, one hub, one run table
|
|
36
|
+
const live = createLive({
|
|
37
|
+
source: pgSource(postgresJsListener(postgres(process.env.DATABASE_URL!, { max: 1 }))),
|
|
38
|
+
// who a stream is for: asked when it opens and every 5 minutes
|
|
39
|
+
caller: async (headers) => (await session(headers))?.user ?? null,
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
// a module: liveMacro adds the `live` option and no route
|
|
43
|
+
const boards = new Elysia({ prefix: '/boards' })
|
|
44
|
+
.use(liveMacro(live))
|
|
45
|
+
.get('/:id/issues', ({ params }) => issuesOf(params.id), {
|
|
46
|
+
// worked out on the server; a browser names a route, never a topic
|
|
47
|
+
live: liveRoute(live, {
|
|
48
|
+
topics: ({ params }) => [`board_issues@board_id=${params.id}`, 'board_assignees'],
|
|
49
|
+
key: 'id', // frames after the first are patches of the rows that changed
|
|
50
|
+
}),
|
|
51
|
+
})
|
|
52
|
+
.post('/tickets/search', ({ body }) => search(body), {
|
|
53
|
+
...tableRoute(ticketsTable),
|
|
54
|
+
live: liveRoute(live, {
|
|
55
|
+
topics: ({ caller }) => [`tickets@org_id=${caller.orgId}`],
|
|
56
|
+
key: 'id',
|
|
57
|
+
rows: 'rows',
|
|
58
|
+
}),
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
// the root: livePlugin adds the option and POST /live + GET /live/health, once
|
|
62
|
+
export const app = new Elysia().use(livePlugin(live)).use(boards);
|
|
63
|
+
bindLive(live, app);
|
|
64
|
+
process.on('SIGTERM', () => live.close());
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
- Write the option through `liveRoute(live, …)`: it types `caller` from the hub, and a callback
|
|
68
|
+
placed directly in a route's options would stop TypeScript inferring the route's own `query`,
|
|
69
|
+
`body` and `params` types.
|
|
70
|
+
- A run goes through `app.handle` with the stream's own `cookie` and `authorization` headers
|
|
71
|
+
(`forward`), so the route's guard and handler are the ones a fetch would meet. A route not
|
|
72
|
+
marked `live` is never run for a stream.
|
|
73
|
+
- Changes are gathered for `settleMs` (100) before a run; at most `concurrency` (8) runs at once.
|
|
74
|
+
- Subscriptions share a run when their request and caller are the same. `share: ({ caller }) =>
|
|
75
|
+
caller.orgId` shares across callers. Use it only when the answer really is the same for
|
|
76
|
+
everyone with that key.
|
|
77
|
+
- A run answering 401 ends the stream (`end: unauthorized`); a 403 ends that subscription.
|
|
78
|
+
|
|
79
|
+
### Postgres
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
// drizzle/0042_live.sql, a migration of your own
|
|
83
|
+
import { liveTriggers } from '@20baht/live/pg';
|
|
84
|
+
console.log(liveTriggers([
|
|
85
|
+
{ table: boardIssues, scope: [boardIssues.boardId, boardIssues.status] },
|
|
86
|
+
{ table: boardAssignees },
|
|
87
|
+
]));
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Every insert, update, delete or truncate then sends the table's topics: `board_issues`,
|
|
91
|
+
`board_issues:<key>` and `board_issues@board_id=<old and new value>`. A notification goes out when
|
|
92
|
+
its transaction commits and never when it rolls back. Postgres is also the bus between server
|
|
93
|
+
processes: each one LISTENs.
|
|
94
|
+
|
|
95
|
+
From code, for what a write changes beyond the tracked tables:
|
|
96
|
+
|
|
97
|
+
```ts
|
|
98
|
+
await db.transaction(async (tx) => {
|
|
99
|
+
await tx.insert(payments).values(payment);
|
|
100
|
+
await changed(tx, [`report:${payment.month}`]); // heard on commit
|
|
101
|
+
});
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Without Postgres: `memorySource()` and `live.emit(topics)` (one process).
|
|
105
|
+
|
|
106
|
+
## Browser
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
import { liveClient, typedLive, guess } from '@20baht/live/browser';
|
|
110
|
+
import type { App } from '../server';
|
|
111
|
+
|
|
112
|
+
const live = typedLive<App>(liveClient({ url: '/live', headers: async () => ({ authorization: `Bearer ${await token()}` }) }));
|
|
113
|
+
|
|
114
|
+
const board = live.subscribe('GET', '/boards/:id/issues', { params: { id } });
|
|
115
|
+
board.listen(({ status, data, error, pending }) => render(data)); // data: the route's own type
|
|
116
|
+
|
|
117
|
+
await live.mutate(
|
|
118
|
+
{ method: 'PATCH', path: `/issues/${issue.id}`, body: { status: 'done' } },
|
|
119
|
+
{ optimistic: [guess(board, (issues) => issues.map((i) => (i.id === issue.id ? { ...i, status: 'done' } : i)))] },
|
|
120
|
+
);
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
- One stream per page: `liveClient` is one client per URL, kept on `globalThis`, so federated
|
|
124
|
+
remotes with their own copy of this package share it.
|
|
125
|
+
- It reconnects with backoff, sending the version it holds; an answer that did not change costs an
|
|
126
|
+
`unchanged` frame. Without a stream it tries again when the page is shown again or the network is
|
|
127
|
+
back, never on a timer.
|
|
128
|
+
- A mutation carries an `Idempotency-Key` (`@20baht/elysia-idempotency`). Its guess stays until a
|
|
129
|
+
frame follows the write's answer (or `settleMs`, 5 s); a refused write takes it off at once and
|
|
130
|
+
throws `LiveMutationError` with the status and body.
|
|
131
|
+
- `rebase(base, local, incoming)` for a record being edited: untouched fields follow the server,
|
|
132
|
+
the page's edits stay, and fields both changed come back as `conflicts`.
|
|
133
|
+
|
|
134
|
+
## Protocol
|
|
135
|
+
|
|
136
|
+
`POST /live` `{ subscriptions: [{ id, method, path, query?, body?, version? }] }` answers
|
|
137
|
+
`text/event-stream` with frames `snapshot`, `patch`, `unchanged`, `error` and `end`. It is read
|
|
138
|
+
with `fetch` (a body and an `Authorization` header), not `EventSource`. `GET /live/health`
|
|
139
|
+
answers `{ source, streams, runs }`.
|
|
140
|
+
|
|
141
|
+
## Licence
|
|
142
|
+
|
|
143
|
+
MIT
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { type LiveMethod, type LiveRequest } from './protocol.js';
|
|
2
|
+
export type LiveStatus = 'connecting' | 'live' | 'error' | 'offline';
|
|
3
|
+
/** What a subscription shows: the server's answer with the page's own pending edits over it. */
|
|
4
|
+
export interface LiveState<T> {
|
|
5
|
+
status: LiveStatus;
|
|
6
|
+
/** The answer, undefined until the first one arrives. */
|
|
7
|
+
data: T | undefined;
|
|
8
|
+
/** The last error frame (a run answering other than 2xx), cleared by the next answer. */
|
|
9
|
+
error: {
|
|
10
|
+
status: number;
|
|
11
|
+
body: unknown;
|
|
12
|
+
} | undefined;
|
|
13
|
+
/** Whether an edit of the page's own is showing over the server's answer. */
|
|
14
|
+
pending: boolean;
|
|
15
|
+
}
|
|
16
|
+
export interface LiveSubscription<T> {
|
|
17
|
+
readonly state: () => LiveState<T>;
|
|
18
|
+
/** Hear every change of state; returns how to stop. */
|
|
19
|
+
readonly listen: (listener: (state: LiveState<T>) => void) => () => void;
|
|
20
|
+
readonly close: () => void;
|
|
21
|
+
}
|
|
22
|
+
/** What the browser parts the client needs, so a test can stand in for them. */
|
|
23
|
+
export interface LiveEnvironment {
|
|
24
|
+
fetch: (url: string, init: RequestInit) => Promise<Response>;
|
|
25
|
+
setTimeout: (run: () => void, ms: number) => unknown;
|
|
26
|
+
clearTimeout: (handle: unknown) => void;
|
|
27
|
+
/** Hear `online` and the page being shown again; returns how to stop. */
|
|
28
|
+
onWake: (wake: () => void) => () => void;
|
|
29
|
+
/** A fresh id for a mutation's `Idempotency-Key`. */
|
|
30
|
+
uuid: () => string;
|
|
31
|
+
}
|
|
32
|
+
export interface LiveClientOptions {
|
|
33
|
+
/** The stream's URL: `/live`, or `https://api.example.com/live`. */
|
|
34
|
+
url: string;
|
|
35
|
+
/** Where mutations go. Default: `url` without its last path segment. */
|
|
36
|
+
base?: string | undefined;
|
|
37
|
+
/** Headers for the stream and mutations (a bearer token), asked each time one is sent. */
|
|
38
|
+
headers?: (() => HeadersInit | Promise<HeadersInit>) | undefined;
|
|
39
|
+
/** Default `include`: the session cookie goes along, cross-origin too. */
|
|
40
|
+
credentials?: RequestCredentials | undefined;
|
|
41
|
+
/** Called when the server says the credentials ran out, before connecting again. */
|
|
42
|
+
onUnauthorized?: (() => unknown) | undefined;
|
|
43
|
+
/** How long the subscription set must hold still before the stream is opened again. Default 20 ms. */
|
|
44
|
+
debounceMs?: number | undefined;
|
|
45
|
+
/** How long an edit's guess stays when no frame follows its answer. Default 5 s. */
|
|
46
|
+
settleMs?: number | undefined;
|
|
47
|
+
environment?: Partial<LiveEnvironment> | undefined;
|
|
48
|
+
}
|
|
49
|
+
/** A write a mutation sends: any method, the same shape as a subscription's request. */
|
|
50
|
+
export type LiveWrite = Omit<LiveRequest, 'method'> & {
|
|
51
|
+
method: 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
52
|
+
};
|
|
53
|
+
/** A write the server refused: its status and body (a 422's `issues`, say). */
|
|
54
|
+
export declare class LiveMutationError extends Error {
|
|
55
|
+
readonly status: number;
|
|
56
|
+
readonly body: unknown;
|
|
57
|
+
constructor(status: number, body: unknown);
|
|
58
|
+
}
|
|
59
|
+
export interface LiveClient {
|
|
60
|
+
subscribe: <T = unknown>(request: LiveRequest, listener?: (state: LiveState<T>) => void) => LiveSubscription<T>;
|
|
61
|
+
/**
|
|
62
|
+
* Send a write. `optimistic` pairs subscriptions with the guess of what the write does to each:
|
|
63
|
+
* shown at once, over the server's answer, until a frame follows the write's answer (or
|
|
64
|
+
* `settleMs` passes); taken off at once if the write fails.
|
|
65
|
+
*/
|
|
66
|
+
mutate: <T = unknown>(request: LiveWrite, options?: {
|
|
67
|
+
optimistic?: readonly Guess[] | undefined;
|
|
68
|
+
}) => Promise<T>;
|
|
69
|
+
/** Stop the stream and every subscription. */
|
|
70
|
+
close: () => void;
|
|
71
|
+
}
|
|
72
|
+
declare const GUESS: unique symbol;
|
|
73
|
+
/** A subscription paired with what a write is expected to do to it: made by `guess`. */
|
|
74
|
+
export interface Guess {
|
|
75
|
+
readonly [GUESS]: {
|
|
76
|
+
handle: object;
|
|
77
|
+
apply: (current: unknown) => unknown;
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
/** What `mutate` should show on `subscription` until the server answers: typed by its data. */
|
|
81
|
+
export declare function guess<T>(subscription: LiveSubscription<T>, apply: (current: T) => T): Guess;
|
|
82
|
+
export declare function createLiveClient(options: LiveClientOptions): LiveClient;
|
|
83
|
+
/**
|
|
84
|
+
* The page's client for `options.url`: made by the first caller, found by every later one, even
|
|
85
|
+
* one from another copy of this package (a federated remote with its own), so the page keeps one
|
|
86
|
+
* stream. Options after the first are ignored.
|
|
87
|
+
*/
|
|
88
|
+
export declare function liveClient(options: LiveClientOptions): LiveClient;
|
|
89
|
+
/** A field both the page and the server changed: the page's value kept, the server's beside it. */
|
|
90
|
+
export interface Conflict {
|
|
91
|
+
key: string;
|
|
92
|
+
local: unknown;
|
|
93
|
+
server: unknown;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* A record the page is editing meets a newer one from the server (spec 09 §8). Fields the page
|
|
97
|
+
* did not touch take the server's value; fields only the page changed keep the page's; fields
|
|
98
|
+
* both changed keep the page's and are returned as conflicts. The new `base` is the server's.
|
|
99
|
+
*/
|
|
100
|
+
export declare function rebase<T extends Record<string, unknown>>(base: T, local: T, incoming: T): {
|
|
101
|
+
value: T;
|
|
102
|
+
base: T;
|
|
103
|
+
conflicts: Conflict[];
|
|
104
|
+
};
|
|
105
|
+
type RoutesOf<App> = App extends {
|
|
106
|
+
'~Routes': infer R;
|
|
107
|
+
} ? R : never;
|
|
108
|
+
type Segments<P extends string> = P extends `/${infer Rest}` ? Rest extends '' ? [] : Rest extends `${infer Head}/${infer Tail}` ? [Head, ...Segments<`/${Tail}`>] : [Rest] : never;
|
|
109
|
+
type Walk<R, S extends readonly string[]> = S extends [
|
|
110
|
+
infer Head extends string,
|
|
111
|
+
...infer Tail extends string[]
|
|
112
|
+
] ? Head extends keyof R ? Walk<R[Head], Tail> : never : R;
|
|
113
|
+
/** The paths of an app's routes answering `method`, as written (`/boards/:id/issues`). */
|
|
114
|
+
export type LivePaths<App, M extends LiveMethod> = PathsIn<RoutesOf<App>, Lowercase<M>>;
|
|
115
|
+
type PathsIn<R, M extends string, P extends string = ''> = {
|
|
116
|
+
[K in keyof R & string]: K extends M ? P extends '' ? '/' : P : R[K] extends object ? PathsIn<R[K], M, `${P}/${K}`> : never;
|
|
117
|
+
}[keyof R & string];
|
|
118
|
+
type RouteOf<App, M extends LiveMethod, P extends string> = Walk<RoutesOf<App>, Segments<P>>[Lowercase<M> & keyof Walk<RoutesOf<App>, Segments<P>>];
|
|
119
|
+
/** What a route answers with a 200. */
|
|
120
|
+
export type LiveAnswerOf<App, M extends LiveMethod, P extends string> = RouteOf<App, M, P> extends {
|
|
121
|
+
response: {
|
|
122
|
+
200: infer A;
|
|
123
|
+
};
|
|
124
|
+
} ? A : unknown;
|
|
125
|
+
/** The body a route takes. */
|
|
126
|
+
export type LiveBodyOf<App, M extends LiveMethod, P extends string> = RouteOf<App, M, P> extends {
|
|
127
|
+
body: infer B;
|
|
128
|
+
} ? B : unknown;
|
|
129
|
+
/** A path's `:name` parameters. */
|
|
130
|
+
export type PathParams<P extends string> = P extends `${string}:${infer Name}/${infer Rest}` ? Record<Name | keyof PathParams<`/${Rest}`>, string> : P extends `${string}:${infer Name}` ? Record<Name, string> : Record<never, string>;
|
|
131
|
+
/** The rest of a typed request: the route's parameters, a query, and the route's body. */
|
|
132
|
+
export type TypedInput<App, M extends LiveMethod, P extends string> = {
|
|
133
|
+
query?: Record<string, string> | undefined;
|
|
134
|
+
} & (keyof PathParams<P> extends never ? {
|
|
135
|
+
params?: undefined;
|
|
136
|
+
} : {
|
|
137
|
+
params: PathParams<P>;
|
|
138
|
+
}) & (M extends 'POST' ? {
|
|
139
|
+
body: LiveBodyOf<App, M, P>;
|
|
140
|
+
} : {
|
|
141
|
+
body?: undefined;
|
|
142
|
+
});
|
|
143
|
+
/** A route's path with its parameters filled in, each encoded. */
|
|
144
|
+
export declare function fillPath(path: string, params?: Record<string, string>): string;
|
|
145
|
+
/** The client, typed by the server's app (`typedLive`). */
|
|
146
|
+
export interface TypedLive<App, Get extends string = LivePaths<App, 'GET'>, Post extends string = LivePaths<App, 'POST'>> {
|
|
147
|
+
/** Subscribe to a route; `.listen(fn)` on the result hears its changes. */
|
|
148
|
+
subscribe<P extends Get>(method: 'GET', path: P, input?: TypedInput<App, 'GET', NoInfer<P>>): LiveSubscription<LiveAnswerOf<App, 'GET', P>>;
|
|
149
|
+
subscribe<P extends Post>(method: 'POST', path: P, input: TypedInput<App, 'POST', NoInfer<P>>): LiveSubscription<LiveAnswerOf<App, 'POST', P>>;
|
|
150
|
+
/** The plain request, for a binding that takes one. */
|
|
151
|
+
request<P extends Get>(method: 'GET', path: P, input?: TypedInput<App, 'GET', NoInfer<P>>): LiveRequest;
|
|
152
|
+
request<P extends Post>(method: 'POST', path: P, input: TypedInput<App, 'POST', NoInfer<P>>): LiveRequest;
|
|
153
|
+
mutate: LiveClient['mutate'];
|
|
154
|
+
close: LiveClient['close'];
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* The client, typed by the server's app: a path must be one of its routes, the parameters and the
|
|
158
|
+
* body are the route's, and the answer is what it returns.
|
|
159
|
+
*
|
|
160
|
+
* const live = typedLive<App>(liveClient({ url: '/live' }))
|
|
161
|
+
* live.subscribe('GET', '/boards/:id/issues', { params: { id } }).listen((state) => …)
|
|
162
|
+
*/
|
|
163
|
+
export declare function typedLive<App>(client: LiveClient): TypedLive<App>;
|
|
164
|
+
export {};
|