@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
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
export type LiveMethod = 'GET' | 'POST';
|
|
2
|
+
/** A route and its input, as a fetch of it would send them. */
|
|
3
|
+
export interface LiveRequest {
|
|
4
|
+
method: LiveMethod;
|
|
5
|
+
/** The path with its parameters filled in, starting with `/`, without a query. */
|
|
6
|
+
path: string;
|
|
7
|
+
query?: Record<string, string> | undefined;
|
|
8
|
+
body?: unknown;
|
|
9
|
+
}
|
|
10
|
+
/** One subscription in `POST /live`'s body: its id on this stream, the route, what the client holds. */
|
|
11
|
+
export type Subscription = LiveRequest & {
|
|
12
|
+
id: string;
|
|
13
|
+
version?: string | undefined;
|
|
14
|
+
};
|
|
15
|
+
export type RowKey = string | number;
|
|
16
|
+
export type Frame = {
|
|
17
|
+
event: 'snapshot';
|
|
18
|
+
data: {
|
|
19
|
+
id: string;
|
|
20
|
+
version: string;
|
|
21
|
+
body: unknown;
|
|
22
|
+
};
|
|
23
|
+
} | {
|
|
24
|
+
event: 'patch';
|
|
25
|
+
data: {
|
|
26
|
+
id: string;
|
|
27
|
+
version: string;
|
|
28
|
+
/** The row key the patch is keyed by. */
|
|
29
|
+
key: string;
|
|
30
|
+
/** The answer's key holding the rows; absent when the answer is the list. */
|
|
31
|
+
rows?: string;
|
|
32
|
+
upsert: unknown[];
|
|
33
|
+
remove: RowKey[];
|
|
34
|
+
/** Every row's key, in order: sent only when the order changed. */
|
|
35
|
+
order?: RowKey[];
|
|
36
|
+
/** The answer's other keys, when its rows sit under `rows`. */
|
|
37
|
+
rest?: Record<string, unknown>;
|
|
38
|
+
};
|
|
39
|
+
} | {
|
|
40
|
+
event: 'unchanged';
|
|
41
|
+
data: {
|
|
42
|
+
id: string;
|
|
43
|
+
version: string;
|
|
44
|
+
};
|
|
45
|
+
} | {
|
|
46
|
+
event: 'error';
|
|
47
|
+
data: {
|
|
48
|
+
id: string;
|
|
49
|
+
status: number;
|
|
50
|
+
body: unknown;
|
|
51
|
+
};
|
|
52
|
+
} | {
|
|
53
|
+
event: 'end';
|
|
54
|
+
data: {
|
|
55
|
+
reason: EndReason;
|
|
56
|
+
};
|
|
57
|
+
};
|
|
58
|
+
export type EndReason = 'unauthorized' | 'signed-out' | 'caller-changed' | 'shutdown' | 'too-many';
|
|
59
|
+
/** One frame as server-sent event text. */
|
|
60
|
+
export declare const encodeFrame: (frame: Frame) => string;
|
|
61
|
+
/** The most subscriptions one stream may hold, unless the server says otherwise. */
|
|
62
|
+
export declare const MAX_SUBSCRIPTIONS = 50;
|
|
63
|
+
/**
|
|
64
|
+
* `POST /live`'s body, checked: a list of subscriptions with unique ids, each a `GET` or `POST`
|
|
65
|
+
* of a path on this server. Returns a message for the 400 instead when it is not.
|
|
66
|
+
*/
|
|
67
|
+
export declare function parseSubscriptions(body: unknown, max?: number): {
|
|
68
|
+
ok: true;
|
|
69
|
+
subscriptions: Subscription[];
|
|
70
|
+
} | {
|
|
71
|
+
ok: false;
|
|
72
|
+
message: string;
|
|
73
|
+
};
|
|
74
|
+
/** The URL path and query of a request, in a stable order. */
|
|
75
|
+
export declare function requestTarget(request: LiveRequest): string;
|
|
76
|
+
/** A name for a request: two subscriptions with the same one ask the same thing. */
|
|
77
|
+
export declare const requestKey: (request: LiveRequest) => string;
|
|
78
|
+
/** JSON with object keys sorted, so the same value always writes the same text. */
|
|
79
|
+
export declare function stableJson(value: unknown): string;
|
|
80
|
+
/**
|
|
81
|
+
* An answer's version: a 64-bit FNV-1a hash of its stable JSON, as 16 hex digits. Not a secret
|
|
82
|
+
* and not a guard, only a way to say "this is the answer you already hold".
|
|
83
|
+
*/
|
|
84
|
+
export declare function versionOf(body: unknown): string;
|
|
85
|
+
/** Where a keyed answer's rows are: the answer itself, or one of its keys. */
|
|
86
|
+
export interface RowsAt {
|
|
87
|
+
key: string;
|
|
88
|
+
rows?: string | undefined;
|
|
89
|
+
}
|
|
90
|
+
/** The rows of `body` and its other keys, or null when they are not where `at` says. */
|
|
91
|
+
export declare function rowsOf(body: unknown, at: RowsAt): {
|
|
92
|
+
rows: Record<string, unknown>[];
|
|
93
|
+
rest: Record<string, unknown> | undefined;
|
|
94
|
+
} | null;
|
|
95
|
+
/**
|
|
96
|
+
* What turns the answer `before` into `after`, both keyed lists of rows: the rows new or changed,
|
|
97
|
+
* the keys gone, and the order when it is no longer the one left by those changes.
|
|
98
|
+
*/
|
|
99
|
+
export declare function diffRows(before: readonly Record<string, unknown>[], after: readonly Record<string, unknown>[], key: string): {
|
|
100
|
+
upsert: Record<string, unknown>[];
|
|
101
|
+
remove: RowKey[];
|
|
102
|
+
order?: RowKey[];
|
|
103
|
+
};
|
|
104
|
+
/**
|
|
105
|
+
* `rows` with a patch applied: removed keys go, a changed row stays in its place, a new one is
|
|
106
|
+
* added at the end; then `order`, when given, puts them in its order.
|
|
107
|
+
*/
|
|
108
|
+
export declare function applyPatch<Row extends Record<string, unknown>>(rows: readonly Row[], patch: {
|
|
109
|
+
upsert: readonly unknown[];
|
|
110
|
+
remove: readonly RowKey[];
|
|
111
|
+
order?: readonly RowKey[];
|
|
112
|
+
}, key: string): Row[];
|
package/dist/protocol.js
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
export const encodeFrame = (frame) => `event: ${frame.event}\ndata: ${JSON.stringify(frame.data)}\n\n`;
|
|
2
|
+
export const MAX_SUBSCRIPTIONS = 50;
|
|
3
|
+
const ID = /^[\w.:-]{1,64}$/;
|
|
4
|
+
export function parseSubscriptions(body, max = MAX_SUBSCRIPTIONS) {
|
|
5
|
+
const list = body?.subscriptions;
|
|
6
|
+
if (!Array.isArray(list))
|
|
7
|
+
return { ok: false, message: 'subscriptions must be a list' };
|
|
8
|
+
if (list.length > max)
|
|
9
|
+
return { ok: false, message: `at most ${max} subscriptions` };
|
|
10
|
+
const ids = new Set();
|
|
11
|
+
const subscriptions = [];
|
|
12
|
+
for (const [index, item] of list.entries()) {
|
|
13
|
+
const sub = item;
|
|
14
|
+
const problem = problemOf(sub, ids);
|
|
15
|
+
if (problem !== undefined)
|
|
16
|
+
return { ok: false, message: `subscriptions[${index}].${problem}` };
|
|
17
|
+
const ok = sub;
|
|
18
|
+
ids.add(ok.id);
|
|
19
|
+
subscriptions.push({
|
|
20
|
+
id: ok.id,
|
|
21
|
+
method: ok.method,
|
|
22
|
+
path: ok.path,
|
|
23
|
+
...(ok.query === undefined ? {} : { query: ok.query }),
|
|
24
|
+
...(ok.body === undefined ? {} : { body: ok.body }),
|
|
25
|
+
...(ok.version === undefined ? {} : { version: ok.version }),
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
return { ok: true, subscriptions };
|
|
29
|
+
}
|
|
30
|
+
function problemOf(sub, ids) {
|
|
31
|
+
if (typeof sub?.id !== 'string' || !ID.test(sub.id) || ids.has(sub.id)) {
|
|
32
|
+
return 'id must be a unique name of 1 to 64 characters';
|
|
33
|
+
}
|
|
34
|
+
if (sub.method !== 'GET' && sub.method !== 'POST')
|
|
35
|
+
return 'method must be GET or POST';
|
|
36
|
+
if (!isPath(sub.path))
|
|
37
|
+
return 'path must be a path on this server';
|
|
38
|
+
if (sub.query !== undefined && !isStringRecord(sub.query))
|
|
39
|
+
return 'query must map names to strings';
|
|
40
|
+
if (sub.version !== undefined && typeof sub.version !== 'string')
|
|
41
|
+
return 'version must be a string';
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
function isPath(path) {
|
|
45
|
+
return (typeof path === 'string' &&
|
|
46
|
+
path.startsWith('/') &&
|
|
47
|
+
!path.startsWith('//') &&
|
|
48
|
+
path.length <= 2048 &&
|
|
49
|
+
!/[?#\s]/.test(path));
|
|
50
|
+
}
|
|
51
|
+
function isStringRecord(value) {
|
|
52
|
+
return (typeof value === 'object' &&
|
|
53
|
+
value !== null &&
|
|
54
|
+
!Array.isArray(value) &&
|
|
55
|
+
Object.values(value).every((v) => typeof v === 'string'));
|
|
56
|
+
}
|
|
57
|
+
export function requestTarget(request) {
|
|
58
|
+
const query = Object.entries(request.query ?? {}).sort(([a], [b]) => (a < b ? -1 : 1));
|
|
59
|
+
return query.length === 0 ? request.path : `${request.path}?${new URLSearchParams(query)}`;
|
|
60
|
+
}
|
|
61
|
+
export const requestKey = (request) => `${request.method} ${requestTarget(request)} ${request.body === undefined ? '' : stableJson(request.body)}`;
|
|
62
|
+
export function stableJson(value) {
|
|
63
|
+
return JSON.stringify(value ?? null, (_key, inner) => inner !== null && typeof inner === 'object' && !Array.isArray(inner)
|
|
64
|
+
? Object.fromEntries(Object.entries(inner).sort(([a], [b]) => (a < b ? -1 : 1)))
|
|
65
|
+
: inner);
|
|
66
|
+
}
|
|
67
|
+
export function versionOf(body) {
|
|
68
|
+
const text = stableJson(body);
|
|
69
|
+
let hi = 0xcbf29ce4;
|
|
70
|
+
let lo = 0x84222325;
|
|
71
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
72
|
+
lo = (lo ^ text.charCodeAt(index)) >>> 0;
|
|
73
|
+
const loMul = lo * 0x1b3;
|
|
74
|
+
const carry = Math.floor(loMul / 0x100000000);
|
|
75
|
+
hi = (Math.imul(hi, 0x1b3) + Math.imul(lo, 0x100) + carry) >>> 0;
|
|
76
|
+
lo = loMul >>> 0;
|
|
77
|
+
}
|
|
78
|
+
return hi.toString(16).padStart(8, '0') + lo.toString(16).padStart(8, '0');
|
|
79
|
+
}
|
|
80
|
+
export function rowsOf(body, at) {
|
|
81
|
+
const list = at.rows === undefined ? body : body?.[at.rows];
|
|
82
|
+
if (!Array.isArray(list) || !list.every((row) => keyOf(row, at.key) !== undefined))
|
|
83
|
+
return null;
|
|
84
|
+
if (at.rows === undefined)
|
|
85
|
+
return { rows: list, rest: undefined };
|
|
86
|
+
const { [at.rows]: _rows, ...rest } = body;
|
|
87
|
+
return { rows: list, rest };
|
|
88
|
+
}
|
|
89
|
+
function keyOf(row, key) {
|
|
90
|
+
const value = row?.[key];
|
|
91
|
+
return typeof value === 'string' || typeof value === 'number' ? value : undefined;
|
|
92
|
+
}
|
|
93
|
+
export function diffRows(before, after, key) {
|
|
94
|
+
const old = new Map(before.map((row) => [keyOf(row, key), stableJson(row)]));
|
|
95
|
+
const keys = after.map((row) => keyOf(row, key));
|
|
96
|
+
const kept = new Set(keys);
|
|
97
|
+
const upsert = after.filter((row) => old.get(keyOf(row, key)) !== stableJson(row));
|
|
98
|
+
const remove = [...old.keys()].filter((k) => !kept.has(k));
|
|
99
|
+
const patched = applyPatch(before, { upsert, remove }, key);
|
|
100
|
+
const sameOrder = patched.length === keys.length && patched.every((row, i) => keyOf(row, key) === keys[i]);
|
|
101
|
+
return sameOrder ? { upsert, remove } : { upsert, remove, order: keys };
|
|
102
|
+
}
|
|
103
|
+
export function applyPatch(rows, patch, key) {
|
|
104
|
+
const gone = new Set(patch.remove);
|
|
105
|
+
const changed = new Map(patch.upsert.map((row) => [keyOf(row, key), row]));
|
|
106
|
+
const next = [];
|
|
107
|
+
for (const row of rows) {
|
|
108
|
+
const k = keyOf(row, key);
|
|
109
|
+
if (gone.has(k))
|
|
110
|
+
continue;
|
|
111
|
+
next.push(changed.get(k) ?? row);
|
|
112
|
+
changed.delete(k);
|
|
113
|
+
}
|
|
114
|
+
next.push(...changed.values());
|
|
115
|
+
if (patch.order === undefined)
|
|
116
|
+
return next;
|
|
117
|
+
const byKey = new Map(next.map((row) => [keyOf(row, key), row]));
|
|
118
|
+
return patch.order.flatMap((k) => {
|
|
119
|
+
const row = byKey.get(k);
|
|
120
|
+
return row === undefined ? [] : [row];
|
|
121
|
+
});
|
|
122
|
+
}
|
package/dist/source.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** What a source's connection is doing, for `/live/health`. */
|
|
2
|
+
export type SourceStatus = 'connecting' | 'connected' | 'reconnecting';
|
|
3
|
+
export interface ChangeSource {
|
|
4
|
+
/** Start hearing changes; returns how to stop. Called once per `createLive`. */
|
|
5
|
+
listen: (onChange: (topics: string[]) => void, onReset: () => void) => () => void;
|
|
6
|
+
/** Raise `topics` from code, through the source's bus. */
|
|
7
|
+
emit: (topics: readonly string[]) => Promise<void>;
|
|
8
|
+
status: () => SourceStatus;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* One process, no bus: `emit` calls the listeners. For tests, and for an app whose changes all
|
|
12
|
+
* come from its own code in one process.
|
|
13
|
+
*/
|
|
14
|
+
export declare function memorySource(): ChangeSource & {
|
|
15
|
+
/** Say that changes may have been missed, as a dropped connection would. */
|
|
16
|
+
reset: () => void;
|
|
17
|
+
};
|
package/dist/source.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export function memorySource() {
|
|
2
|
+
const changes = new Set();
|
|
3
|
+
const resets = new Set();
|
|
4
|
+
return {
|
|
5
|
+
listen(onChange, onReset) {
|
|
6
|
+
changes.add(onChange);
|
|
7
|
+
resets.add(onReset);
|
|
8
|
+
return () => {
|
|
9
|
+
changes.delete(onChange);
|
|
10
|
+
resets.delete(onReset);
|
|
11
|
+
};
|
|
12
|
+
},
|
|
13
|
+
emit(topics) {
|
|
14
|
+
for (const listener of [...changes])
|
|
15
|
+
listener([...topics]);
|
|
16
|
+
return Promise.resolve();
|
|
17
|
+
},
|
|
18
|
+
status: () => 'connected',
|
|
19
|
+
reset() {
|
|
20
|
+
for (const listener of [...resets])
|
|
21
|
+
listener();
|
|
22
|
+
},
|
|
23
|
+
};
|
|
24
|
+
}
|
package/dist/topics.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** The longest topic kept; a longer one is dropped where it is raised. */
|
|
2
|
+
export declare const MAX_TOPIC_LENGTH = 200;
|
|
3
|
+
/** Every insert, update or delete in `table`. */
|
|
4
|
+
export declare const tableTopic: (table: string) => string;
|
|
5
|
+
/** A change to one row of `table`; a composite key is its parts joined by `,`. */
|
|
6
|
+
export declare const rowTopic: (table: string, key: unknown) => string;
|
|
7
|
+
/** A change to a row of `table` whose `column` held `value` before or after. */
|
|
8
|
+
export declare const scopeTopic: (table: string, column: string, value: unknown) => string;
|
|
9
|
+
/** The topics worth keeping: strings, not empty, at most `MAX_TOPIC_LENGTH`, each once. */
|
|
10
|
+
export declare function cleanTopics(topics: readonly unknown[]): string[];
|
package/dist/topics.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export const MAX_TOPIC_LENGTH = 200;
|
|
2
|
+
export const tableTopic = (table) => table;
|
|
3
|
+
export const rowTopic = (table, key) => `${table}:${Array.isArray(key) ? key.map(cell).join(',') : cell(key)}`;
|
|
4
|
+
export const scopeTopic = (table, column, value) => `${table}@${column}=${cell(value)}`;
|
|
5
|
+
function cell(value) {
|
|
6
|
+
if (value === null || value === undefined)
|
|
7
|
+
return '';
|
|
8
|
+
if (value instanceof Date)
|
|
9
|
+
return value.toISOString();
|
|
10
|
+
if (typeof value === 'string')
|
|
11
|
+
return value;
|
|
12
|
+
if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
|
|
13
|
+
return String(value);
|
|
14
|
+
}
|
|
15
|
+
return JSON.stringify(value);
|
|
16
|
+
}
|
|
17
|
+
export function cleanTopics(topics) {
|
|
18
|
+
const kept = new Set();
|
|
19
|
+
for (const topic of topics) {
|
|
20
|
+
if (typeof topic === 'string' && topic !== '' && topic.length <= MAX_TOPIC_LENGTH) {
|
|
21
|
+
kept.add(topic);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return [...kept];
|
|
25
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,88 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@20baht/live",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"engines": {
|
|
6
|
+
"node": ">=20.19.0"
|
|
7
|
+
},
|
|
8
|
+
"description": "Server-authoritative live queries for Elysia over server-sent events: a route marked live runs again when the data under it changes (Postgres triggers, or the server's own code) and every viewer gets the new answer, as a snapshot or a keyed patch. Optimistic edits in the browser settle against it.",
|
|
9
|
+
"license": "MIT",
|
|
10
|
+
"author": "Nattapong Promthong",
|
|
11
|
+
"repository": {
|
|
12
|
+
"type": "git",
|
|
13
|
+
"url": "git+https://github.com/bank20baht/20baht.git",
|
|
14
|
+
"directory": "packages/core/live"
|
|
15
|
+
},
|
|
16
|
+
"homepage": "https://github.com/bank20baht/20baht/tree/main/packages/core/live#readme",
|
|
17
|
+
"bugs": {
|
|
18
|
+
"url": "https://github.com/bank20baht/20baht/issues"
|
|
19
|
+
},
|
|
20
|
+
"keywords": [
|
|
21
|
+
"live-query",
|
|
22
|
+
"realtime",
|
|
23
|
+
"sse",
|
|
24
|
+
"server-sent-events",
|
|
25
|
+
"elysia",
|
|
26
|
+
"postgres",
|
|
27
|
+
"listen-notify",
|
|
28
|
+
"drizzle",
|
|
29
|
+
"optimistic-update"
|
|
30
|
+
],
|
|
31
|
+
"publishConfig": {
|
|
32
|
+
"access": "public"
|
|
33
|
+
},
|
|
34
|
+
"files": [
|
|
35
|
+
"dist"
|
|
36
|
+
],
|
|
37
|
+
"exports": {
|
|
38
|
+
".": {
|
|
39
|
+
"types": "./dist/index.d.ts",
|
|
40
|
+
"import": "./dist/index.js",
|
|
41
|
+
"default": "./dist/index.js"
|
|
42
|
+
},
|
|
43
|
+
"./elysia": {
|
|
44
|
+
"types": "./dist/elysia.d.ts",
|
|
45
|
+
"import": "./dist/elysia.js",
|
|
46
|
+
"default": "./dist/elysia.js"
|
|
47
|
+
},
|
|
48
|
+
"./pg": {
|
|
49
|
+
"types": "./dist/pg.d.ts",
|
|
50
|
+
"import": "./dist/pg.js",
|
|
51
|
+
"default": "./dist/pg.js"
|
|
52
|
+
},
|
|
53
|
+
"./browser": {
|
|
54
|
+
"types": "./dist/browser.d.ts",
|
|
55
|
+
"import": "./dist/browser.js",
|
|
56
|
+
"default": "./dist/browser.js"
|
|
57
|
+
},
|
|
58
|
+
"./package.json": "./package.json"
|
|
59
|
+
},
|
|
60
|
+
"scripts": {
|
|
61
|
+
"build": "rm -rf dist && tsc -p tsconfig.json --removeComments && tsc -p tsconfig.json --emitDeclarationOnly",
|
|
62
|
+
"test": "vitest run",
|
|
63
|
+
"test:watch": "vitest",
|
|
64
|
+
"test:coverage": "vitest run --coverage"
|
|
65
|
+
},
|
|
66
|
+
"devDependencies": {
|
|
67
|
+
"@electric-sql/pglite": "^0.3.0",
|
|
68
|
+
"drizzle-orm": "^0.44.0",
|
|
69
|
+
"elysia": "^1.4.0",
|
|
70
|
+
"typescript": "^5.9.3",
|
|
71
|
+
"vitest": "^3.2.4"
|
|
72
|
+
},
|
|
73
|
+
"peerDependencies": {
|
|
74
|
+
"drizzle-orm": ">=0.44.0 <1.0.0",
|
|
75
|
+
"elysia": ">=1.4.0 <2.0.0"
|
|
76
|
+
},
|
|
77
|
+
"peerDependenciesMeta": {
|
|
78
|
+
"drizzle-orm": {
|
|
79
|
+
"optional": true
|
|
80
|
+
},
|
|
81
|
+
"elysia": {
|
|
82
|
+
"optional": true
|
|
83
|
+
}
|
|
84
|
+
},
|
|
85
|
+
"main": "./dist/index.js",
|
|
86
|
+
"types": "./dist/index.d.ts",
|
|
87
|
+
"sideEffects": false
|
|
88
|
+
}
|