@itrocks/sync 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.
Files changed (156) hide show
  1. package/LICENSE +165 -0
  2. package/README.md +249 -2
  3. package/config.yaml +2 -0
  4. package/demo/src/demo.css +458 -0
  5. package/dist/client/author-background.d.ts +2 -0
  6. package/dist/client/author-background.js +28 -0
  7. package/dist/client/clock.d.ts +10 -0
  8. package/dist/client/clock.js +30 -0
  9. package/dist/client/collections/order.d.ts +10 -0
  10. package/dist/client/collections/order.js +77 -0
  11. package/dist/client/collections/reorder-nodes.d.ts +2 -0
  12. package/dist/client/collections/reorder-nodes.js +67 -0
  13. package/dist/client/collections/row-changes.d.ts +12 -0
  14. package/dist/client/collections/row-changes.js +26 -0
  15. package/dist/client/collections/row-history.d.ts +16 -0
  16. package/dist/client/collections/row-history.js +61 -0
  17. package/dist/client/collections/table-columns.d.ts +19 -0
  18. package/dist/client/collections/table-columns.js +200 -0
  19. package/dist/client/collections.d.ts +54 -0
  20. package/dist/client/collections.js +262 -0
  21. package/dist/client/discovery.d.ts +1 -0
  22. package/dist/client/discovery.js +57 -0
  23. package/dist/client/field-address.d.ts +38 -0
  24. package/dist/client/field-address.js +225 -0
  25. package/dist/client/field-value.d.ts +7 -0
  26. package/dist/client/field-value.js +105 -0
  27. package/dist/client/form-identity.d.ts +1 -0
  28. package/dist/client/form-identity.js +43 -0
  29. package/dist/client/form-session.d.ts +53 -0
  30. package/dist/client/form-session.js +218 -0
  31. package/dist/client/identity.d.ts +3 -0
  32. package/dist/client/identity.js +27 -0
  33. package/dist/client/index.d.ts +43 -0
  34. package/dist/client/index.js +109 -0
  35. package/dist/client/journal.d.ts +13 -0
  36. package/dist/client/journal.js +59 -0
  37. package/dist/client/lifecycle.d.ts +26 -0
  38. package/dist/client/lifecycle.js +112 -0
  39. package/dist/client/observation.d.ts +11 -0
  40. package/dist/client/observation.js +46 -0
  41. package/dist/client/outbox.d.ts +15 -0
  42. package/dist/client/outbox.js +71 -0
  43. package/dist/client/plugin.d.ts +42 -0
  44. package/dist/client/plugin.js +1 -0
  45. package/dist/client/plugins/column-order/apply.d.ts +2 -0
  46. package/dist/client/plugins/column-order/apply.js +30 -0
  47. package/dist/client/plugins/column-order/colgroups.d.ts +2 -0
  48. package/dist/client/plugins/column-order/colgroups.js +78 -0
  49. package/dist/client/plugins/column-order/index.d.ts +2 -0
  50. package/dist/client/plugins/column-order/index.js +98 -0
  51. package/dist/client/plugins/cursor/editable.d.ts +16 -0
  52. package/dist/client/plugins/cursor/editable.js +67 -0
  53. package/dist/client/plugins/cursor/geometry.d.ts +16 -0
  54. package/dist/client/plugins/cursor/geometry.js +122 -0
  55. package/dist/client/plugins/cursor/index.d.ts +4 -0
  56. package/dist/client/plugins/cursor/index.js +13 -0
  57. package/dist/client/plugins/cursor/indicators.d.ts +31 -0
  58. package/dist/client/plugins/cursor/indicators.js +144 -0
  59. package/dist/client/plugins/cursor/local-selection.d.ts +19 -0
  60. package/dist/client/plugins/cursor/local-selection.js +234 -0
  61. package/dist/client/plugins/cursor/selection.d.ts +9 -0
  62. package/dist/client/plugins/cursor/selection.js +49 -0
  63. package/dist/client/plugins/cursor/text-presence.d.ts +15 -0
  64. package/dist/client/plugins/cursor/text-presence.js +95 -0
  65. package/dist/client/plugins/fields/author.d.ts +7 -0
  66. package/dist/client/plugins/fields/author.js +22 -0
  67. package/dist/client/plugins/fields/index.d.ts +4 -0
  68. package/dist/client/plugins/fields/index.js +192 -0
  69. package/dist/client/plugins/fields/writes.d.ts +19 -0
  70. package/dist/client/plugins/fields/writes.js +51 -0
  71. package/dist/client/plugins/focus/index.d.ts +9 -0
  72. package/dist/client/plugins/focus/index.js +92 -0
  73. package/dist/client/plugins/focus/indicators.d.ts +19 -0
  74. package/dist/client/plugins/focus/indicators.js +163 -0
  75. package/dist/client/plugins/naming/algorithm.d.ts +7 -0
  76. package/dist/client/plugins/naming/algorithm.js +65 -0
  77. package/dist/client/plugins/naming/attributes.d.ts +16 -0
  78. package/dist/client/plugins/naming/attributes.js +195 -0
  79. package/dist/client/plugins/naming/index.d.ts +5 -0
  80. package/dist/client/plugins/naming/index.js +185 -0
  81. package/dist/client/plugins/range/index.d.ts +4 -0
  82. package/dist/client/plugins/range/index.js +15 -0
  83. package/dist/client/plugins/reconciliation/index.d.ts +6 -0
  84. package/dist/client/plugins/reconciliation/index.js +282 -0
  85. package/dist/client/plugins/reconciliation/matching.d.ts +12 -0
  86. package/dist/client/plugins/reconciliation/matching.js +37 -0
  87. package/dist/client/plugins/reconciliation/proposals.d.ts +11 -0
  88. package/dist/client/plugins/reconciliation/proposals.js +32 -0
  89. package/dist/client/plugins/row-order/index.d.ts +2 -0
  90. package/dist/client/plugins/row-order/index.js +99 -0
  91. package/dist/client/plugins/rows/clone.d.ts +2 -0
  92. package/dist/client/plugins/rows/clone.js +123 -0
  93. package/dist/client/plugins/rows/index.d.ts +2 -0
  94. package/dist/client/plugins/rows/index.js +191 -0
  95. package/dist/client/plugins/rows/materialize.d.ts +4 -0
  96. package/dist/client/plugins/rows/materialize.js +43 -0
  97. package/dist/client/plugins/rows/remove.d.ts +1 -0
  98. package/dist/client/plugins/rows/remove.js +13 -0
  99. package/dist/client/plugins/rows/template.d.ts +2 -0
  100. package/dist/client/plugins/rows/template.js +21 -0
  101. package/dist/client/transport.d.ts +23 -0
  102. package/dist/client/transport.js +128 -0
  103. package/dist/client/user-colour.d.ts +3 -0
  104. package/dist/client/user-colour.js +11 -0
  105. package/dist/server/acknowledgments.d.ts +3 -0
  106. package/dist/server/acknowledgments.js +8 -0
  107. package/dist/server/broadcast.d.ts +3 -0
  108. package/dist/server/broadcast.js +7 -0
  109. package/dist/server/cli.d.ts +2 -0
  110. package/dist/server/cli.js +44 -0
  111. package/dist/server/clock.d.ts +2 -0
  112. package/dist/server/clock.js +3 -0
  113. package/dist/server/configuration.d.ts +3 -0
  114. package/dist/server/configuration.js +7 -0
  115. package/dist/server/connection.d.ts +13 -0
  116. package/dist/server/connection.js +1 -0
  117. package/dist/server/express.d.ts +2 -0
  118. package/dist/server/express.js +1 -0
  119. package/dist/server/fastify.d.ts +10 -0
  120. package/dist/server/fastify.js +15 -0
  121. package/dist/server/index.d.ts +7 -0
  122. package/dist/server/index.js +1 -0
  123. package/dist/server/journal.d.ts +7 -0
  124. package/dist/server/journal.js +16 -0
  125. package/dist/server/messages.d.ts +4 -0
  126. package/dist/server/messages.js +106 -0
  127. package/dist/server/participants.d.ts +9 -0
  128. package/dist/server/participants.js +7 -0
  129. package/dist/server/receipts.d.ts +13 -0
  130. package/dist/server/receipts.js +28 -0
  131. package/dist/server/recovery.d.ts +3 -0
  132. package/dist/server/recovery.js +9 -0
  133. package/dist/server/server.d.ts +34 -0
  134. package/dist/server/server.js +189 -0
  135. package/dist/server/sessions.d.ts +16 -0
  136. package/dist/server/sessions.js +37 -0
  137. package/dist/server/standalone.d.ts +9 -0
  138. package/dist/server/standalone.js +12 -0
  139. package/dist/server/transactions.d.ts +15 -0
  140. package/dist/server/transactions.js +50 -0
  141. package/dist/server/websocket-connection.d.ts +3 -0
  142. package/dist/server/websocket-connection.js +38 -0
  143. package/dist/server/websocket.d.ts +11 -0
  144. package/dist/server/websocket.js +26 -0
  145. package/dist/shared/field-update.d.ts +12 -0
  146. package/dist/shared/field-update.js +18 -0
  147. package/dist/shared/journal-entries.d.ts +9 -0
  148. package/dist/shared/journal-entries.js +33 -0
  149. package/dist/shared/protocol.d.ts +105 -0
  150. package/dist/shared/protocol.js +15 -0
  151. package/docs/dependencies.md +130 -0
  152. package/docs/spec-addendum-dependencies.md +10 -0
  153. package/docs/spec-addendum.md +717 -0
  154. package/docs/spec.md +1165 -0
  155. package/docs/testing.md +39 -0
  156. package/package.json +96 -5
@@ -0,0 +1,106 @@
1
+ function isObject(value) {
2
+ return (typeof value === 'object') && (value !== null);
3
+ }
4
+ function isString(value) {
5
+ return (typeof value === 'string') && (value.length > 0);
6
+ }
7
+ export function readClientMessage(data) {
8
+ let message;
9
+ try {
10
+ message = JSON.parse(data);
11
+ }
12
+ catch {
13
+ return;
14
+ }
15
+ if (!isObject(message))
16
+ return;
17
+ if (message.type === 'ping') {
18
+ if ((typeof message.sent === 'number') && Number.isFinite(message.sent)) {
19
+ return { type: 'ping', sent: message.sent };
20
+ }
21
+ return;
22
+ }
23
+ const { session } = message;
24
+ if (!isString(session))
25
+ return;
26
+ switch (message.type) {
27
+ case 'cursor': {
28
+ const position = (message.position === null) ? null : readCursor(message.position);
29
+ if (position !== undefined) {
30
+ return { type: 'cursor', session, position };
31
+ }
32
+ break;
33
+ }
34
+ case 'focus':
35
+ if ((message.field === null) || isString(message.field)) {
36
+ return { type: 'focus', session, field: message.field };
37
+ }
38
+ break;
39
+ case 'join':
40
+ if (Array.isArray(message.known) && message.known.every(isString)) {
41
+ return { type: 'join', session, known: message.known };
42
+ }
43
+ break;
44
+ case 'leave':
45
+ return { type: 'leave', session };
46
+ case 'push':
47
+ if (Array.isArray(message.transactions)) {
48
+ const transactions = message.transactions.map(readTransaction)
49
+ .filter((transaction) => transaction !== undefined);
50
+ return { type: 'push', session, transactions, detached: message.detached === true };
51
+ }
52
+ break;
53
+ case 'range': {
54
+ const selection = (message.selection === null) ? null : readRange(message.selection);
55
+ if (selection !== undefined) {
56
+ return { type: 'range', session, selection };
57
+ }
58
+ break;
59
+ }
60
+ }
61
+ }
62
+ function readCursor(value) {
63
+ if (!isObject(value))
64
+ return;
65
+ const { field, offset } = value;
66
+ if (isString(field) && isOffset(offset))
67
+ return { field, offset };
68
+ }
69
+ function readRange(value) {
70
+ if (!isObject(value))
71
+ return;
72
+ const { field, ranges } = value;
73
+ if (!isString(field) || !Array.isArray(ranges) || !ranges.length)
74
+ return;
75
+ const validated = [];
76
+ for (const range of ranges) {
77
+ if (!isObject(range))
78
+ return;
79
+ const { start, end } = range;
80
+ if (!isOffset(start) || !isOffset(end) || (start >= end))
81
+ return;
82
+ validated.push({ start, end });
83
+ }
84
+ return { field, ranges: validated };
85
+ }
86
+ function isOffset(value) {
87
+ return (typeof value === 'number') && Number.isSafeInteger(value) && (value >= 0);
88
+ }
89
+ function readTransaction(value) {
90
+ if (!isObject(value))
91
+ return;
92
+ const { client, data, id, proof, timestamp, type, user } = value;
93
+ if (!isString(id) || !isString(client) || !isString(type) || !('data' in value)
94
+ || (typeof timestamp !== 'number') || !Number.isFinite(timestamp)) {
95
+ return;
96
+ }
97
+ const transaction = { client, data, id, timestamp, type };
98
+ if (isString(proof) && (proof.length === 64) && isUser(user)) {
99
+ transaction.proof = proof;
100
+ transaction.user = { id: user.id, name: user.name };
101
+ }
102
+ return transaction;
103
+ }
104
+ export function isUser(value) {
105
+ return isObject(value) && isString(value.id) && isString(value.name);
106
+ }
@@ -0,0 +1,9 @@
1
+ import type { Participant } from '../shared/protocol.js';
2
+ import type { ServerMessage } from '../shared/protocol.js';
3
+ import type { Connection } from './connection.js';
4
+ export type Participants = Map<string, Membership>;
5
+ export interface Membership {
6
+ presence: Participant;
7
+ send: Connection['send'];
8
+ }
9
+ export declare function presence(session: string, participants: Participants): ServerMessage;
@@ -0,0 +1,7 @@
1
+ export function presence(session, participants) {
2
+ return {
3
+ type: 'presence',
4
+ session,
5
+ participants: Array.from(participants.values(), member => member.presence)
6
+ };
7
+ }
@@ -0,0 +1,13 @@
1
+ import type { Transaction } from '../shared/protocol.js';
2
+ import type { User } from '../shared/protocol.js';
3
+ export type ReplaySecret = string | Uint8Array;
4
+ export declare class Receipts {
5
+ private readonly secret;
6
+ constructor(secret?: ReplaySecret);
7
+ accept(session: string, transaction: Transaction, user: User): {
8
+ recovered: boolean;
9
+ transaction: Transaction;
10
+ };
11
+ private sign;
12
+ private verify;
13
+ }
@@ -0,0 +1,28 @@
1
+ import { createHmac } from 'node:crypto';
2
+ import { randomBytes } from 'node:crypto';
3
+ import { timingSafeEqual } from 'node:crypto';
4
+ const processSecret = randomBytes(32);
5
+ export class Receipts {
6
+ secret;
7
+ constructor(secret = processSecret) {
8
+ this.secret = secret;
9
+ }
10
+ accept(session, transaction, user) {
11
+ if (this.verify(session, transaction)) {
12
+ return { recovered: true, transaction };
13
+ }
14
+ const accepted = { ...transaction, user };
15
+ return { recovered: false, transaction: { ...accepted, proof: this.sign(session, accepted) } };
16
+ }
17
+ sign(session, transaction) {
18
+ const { client, data, id, timestamp, type, user } = transaction;
19
+ const content = JSON.stringify([session, id, client, timestamp, type, data, user?.id, user?.name]);
20
+ return createHmac('sha256', this.secret).update(content).digest('hex');
21
+ }
22
+ verify(session, transaction) {
23
+ const { proof, user } = transaction;
24
+ if (!user || !proof || !/^[a-f0-9]{64}$/.test(proof))
25
+ return false;
26
+ return timingSafeEqual(Buffer.from(proof, 'hex'), Buffer.from(this.sign(session, transaction), 'hex'));
27
+ }
28
+ }
@@ -0,0 +1,3 @@
1
+ import type { ServerMessage } from '../shared/protocol.js';
2
+ import type { Journal } from './journal.js';
3
+ export declare function recover(session: string, journal: Journal, known: string[]): ServerMessage;
@@ -0,0 +1,9 @@
1
+ export function recover(session, journal, known) {
2
+ const advertised = new Set(known);
3
+ return {
4
+ type: 'history',
5
+ session,
6
+ transactions: journal.missingFrom(advertised),
7
+ missing: Array.from(advertised).filter(id => !journal.get(id))
8
+ };
9
+ }
@@ -0,0 +1,34 @@
1
+ import type { User } from '../shared/protocol.js';
2
+ import type { ServerSocket } from './connection.js';
3
+ import type { ReplaySecret } from './receipts.js';
4
+ import type { Sessions } from './sessions.js';
5
+ import type { Transactions } from './transactions.js';
6
+ type Awaitable<T> = T | Promise<T>;
7
+ export interface SessionAccess<Request> {
8
+ request: Request;
9
+ session: string;
10
+ user: User;
11
+ }
12
+ export interface SyncOptions<Request> {
13
+ authorizeSession?(access: SessionAccess<Request>): Awaitable<boolean>;
14
+ getUser(request: Request): Awaitable<User | null | undefined>;
15
+ replaySecret?: ReplaySecret;
16
+ }
17
+ export interface SyncServer<Request> {
18
+ close(): void;
19
+ connect(socket: ServerSocket, request: Request): void;
20
+ }
21
+ export declare class SyncEngine<Request> implements SyncServer<Request> {
22
+ private readonly options;
23
+ private readonly sessions;
24
+ private readonly transactions;
25
+ private closed;
26
+ private readonly connections;
27
+ constructor(options: SyncOptions<Request>, sessions: Sessions, transactions: Transactions);
28
+ close(): void;
29
+ connect(socket: ServerSocket, request: Request): void;
30
+ private join;
31
+ private leave;
32
+ private receive;
33
+ }
34
+ export {};
@@ -0,0 +1,189 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { sameCursor } from '../shared/protocol.js';
3
+ import { sameRange } from '../shared/protocol.js';
4
+ import { broadcast } from './broadcast.js';
5
+ import { pong } from './clock.js';
6
+ import { isUser } from './messages.js';
7
+ import { readClientMessage } from './messages.js';
8
+ import { presence } from './participants.js';
9
+ import { recover } from './recovery.js';
10
+ export class SyncEngine {
11
+ options;
12
+ sessions;
13
+ transactions;
14
+ closed = false;
15
+ connections = new Set();
16
+ constructor(options, sessions, transactions) {
17
+ this.options = options;
18
+ this.sessions = sessions;
19
+ this.transactions = transactions;
20
+ }
21
+ close() {
22
+ this.closed = true;
23
+ for (const close of this.connections) {
24
+ close();
25
+ }
26
+ this.sessions.clear();
27
+ }
28
+ connect(socket, request) {
29
+ if (this.closed) {
30
+ socket.close(1001, 'Sync server is closed');
31
+ return;
32
+ }
33
+ const connection = {
34
+ client: randomUUID(),
35
+ closed: false,
36
+ sessions: new Set(),
37
+ send(message) {
38
+ if (connection.closed)
39
+ return;
40
+ try {
41
+ socket.send(JSON.stringify(message));
42
+ }
43
+ catch {
44
+ queueMicrotask(() => close(1011, 'Sync send failed'));
45
+ }
46
+ }
47
+ };
48
+ const disconnect = () => {
49
+ if (connection.closed)
50
+ return;
51
+ connection.closed = true;
52
+ this.connections.delete(shutdown);
53
+ for (const id of connection.sessions) {
54
+ this.leave(connection, id);
55
+ }
56
+ };
57
+ const close = (code, reason) => {
58
+ if (connection.closed)
59
+ return;
60
+ disconnect();
61
+ socket.close(code, reason);
62
+ };
63
+ const shutdown = () => close(1001, 'Sync server is closed');
64
+ this.connections.add(shutdown);
65
+ socket.onClose(disconnect);
66
+ const authenticated = Promise.resolve().then(() => this.options.getUser(request)).then(identified => {
67
+ if (connection.closed)
68
+ return;
69
+ if (!isUser(identified)) {
70
+ close(1008, 'Sync authentication required');
71
+ return;
72
+ }
73
+ const user = { id: identified.id, name: identified.name };
74
+ connection.send({ type: 'hello', client: connection.client, user });
75
+ return user;
76
+ }).catch(() => {
77
+ close(1008, 'Sync authentication failed');
78
+ });
79
+ let queue = Promise.resolve();
80
+ socket.onMessage(data => {
81
+ if (connection.closed)
82
+ return;
83
+ const message = readClientMessage(data);
84
+ if (!message)
85
+ return;
86
+ queue = queue.then(async () => {
87
+ const user = await authenticated;
88
+ if (user && !connection.closed) {
89
+ await this.receive(connection, message, request, user);
90
+ }
91
+ }).catch(() => close(1011, 'Sync message failed'));
92
+ });
93
+ }
94
+ async join(connection, id, known, request, user) {
95
+ const alreadyJoined = connection.sessions.has(id);
96
+ if (!alreadyJoined && this.options.authorizeSession) {
97
+ let allowed = false;
98
+ try {
99
+ allowed = await this.options.authorizeSession({ request, session: id, user });
100
+ }
101
+ catch {
102
+ // Give failed access checks the same response as a refused request.
103
+ }
104
+ if (connection.closed)
105
+ return;
106
+ if (!allowed) {
107
+ connection.send({ type: 'denied', session: id });
108
+ return;
109
+ }
110
+ }
111
+ const session = this.sessions.open(id);
112
+ if (!alreadyJoined) {
113
+ session.participants.set(connection.client, {
114
+ presence: { client: connection.client, field: null, user },
115
+ send: connection.send
116
+ });
117
+ connection.sessions.add(id);
118
+ }
119
+ connection.send(recover(id, session.journal, known));
120
+ if (!alreadyJoined && !connection.closed) {
121
+ broadcast(session.participants, presence(id, session.participants));
122
+ }
123
+ }
124
+ leave(connection, id) {
125
+ const session = this.sessions.get(id);
126
+ if (!session || !session.participants.delete(connection.client))
127
+ return;
128
+ connection.sessions.delete(id);
129
+ this.sessions.removeIfEmpty(session);
130
+ if (!this.closed) {
131
+ broadcast(session.participants, presence(id, session.participants));
132
+ }
133
+ }
134
+ async receive(connection, message, request, user) {
135
+ if (message.type === 'ping') {
136
+ connection.send(pong(message.sent));
137
+ return;
138
+ }
139
+ const { session: id } = message;
140
+ if (message.type === 'join') {
141
+ await this.join(connection, id, message.known, request, user);
142
+ return;
143
+ }
144
+ if (message.type === 'leave') {
145
+ this.leave(connection, id);
146
+ return;
147
+ }
148
+ const session = this.sessions.get(id);
149
+ const member = session?.participants.get(connection.client);
150
+ if (!session || !member)
151
+ return;
152
+ if (message.type === 'push') {
153
+ this.transactions.push(session, connection, user, message);
154
+ return;
155
+ }
156
+ if (message.type === 'cursor') {
157
+ const { position } = message;
158
+ if (sameCursor(member.presence.cursor, position))
159
+ return;
160
+ if (position) {
161
+ member.presence.cursor = position;
162
+ }
163
+ else {
164
+ delete member.presence.cursor;
165
+ }
166
+ const { client } = connection;
167
+ broadcast(session.participants, { type: 'cursor', session: id, client, position }, client);
168
+ return;
169
+ }
170
+ if (message.type === 'range') {
171
+ const { selection } = message;
172
+ if (sameRange(member.presence.range, selection))
173
+ return;
174
+ if (selection) {
175
+ member.presence.range = selection;
176
+ }
177
+ else {
178
+ delete member.presence.range;
179
+ }
180
+ const { client } = connection;
181
+ broadcast(session.participants, { type: 'range', session: id, client, selection }, client);
182
+ return;
183
+ }
184
+ if (member.presence.field !== message.field) {
185
+ member.presence.field = message.field;
186
+ broadcast(session.participants, presence(id, session.participants));
187
+ }
188
+ }
189
+ }
@@ -0,0 +1,16 @@
1
+ import { Journal } from './journal.js';
2
+ import type { Participants } from './participants.js';
3
+ export interface Session {
4
+ deferEviction?: boolean;
5
+ eviction?: ReturnType<typeof setTimeout>;
6
+ id: string;
7
+ journal: Journal;
8
+ participants: Participants;
9
+ }
10
+ export declare class Sessions {
11
+ private readonly sessions;
12
+ clear(): void;
13
+ get(id: string): Session | undefined;
14
+ open(id: string): Session;
15
+ removeIfEmpty(session: Session): void;
16
+ }
@@ -0,0 +1,37 @@
1
+ import { Journal } from './journal.js';
2
+ const detachedJournalGrace = 10_000;
3
+ export class Sessions {
4
+ sessions = new Map();
5
+ clear() {
6
+ for (const session of this.sessions.values()) {
7
+ clearTimeout(session.eviction);
8
+ }
9
+ this.sessions.clear();
10
+ }
11
+ get(id) {
12
+ return this.sessions.get(id);
13
+ }
14
+ open(id) {
15
+ const open = this.sessions.get(id);
16
+ if (open)
17
+ return open;
18
+ const session = { id, journal: new Journal(), participants: new Map() };
19
+ this.sessions.set(id, session);
20
+ return session;
21
+ }
22
+ removeIfEmpty(session) {
23
+ if (session.participants.size)
24
+ return;
25
+ if (session.deferEviction) {
26
+ session.deferEviction = false;
27
+ clearTimeout(session.eviction);
28
+ session.eviction = setTimeout(() => {
29
+ session.eviction = undefined;
30
+ this.removeIfEmpty(session);
31
+ }, detachedJournalGrace).unref();
32
+ }
33
+ else if (!session.eviction) {
34
+ this.sessions.delete(session.id);
35
+ }
36
+ }
37
+ }
@@ -0,0 +1,9 @@
1
+ import type { Server } from 'node:http';
2
+ import type { WebSocketSyncOptions } from './websocket.js';
3
+ export interface StandaloneSyncOptions extends Omit<Partial<WebSocketSyncOptions>, 'server'> {
4
+ server?: Server;
5
+ }
6
+ export declare function createStandaloneServer({ server, getUser, ...options }?: StandaloneSyncOptions): {
7
+ server: Server<typeof import("http").IncomingMessage, typeof import("http").ServerResponse>;
8
+ close: () => void;
9
+ };
@@ -0,0 +1,12 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { createServer } from 'node:http';
3
+ import { sync } from './websocket.js';
4
+ export function createStandaloneServer({ server = createServer((_request, response) => response.writeHead(404).end()), getUser, ...options } = {}) {
5
+ let guests = 0;
6
+ const { close } = sync({
7
+ ...options,
8
+ server,
9
+ getUser: getUser ?? (() => ({ id: randomUUID(), name: 'Guest ' + (++guests) }))
10
+ });
11
+ return { server, close };
12
+ }
@@ -0,0 +1,15 @@
1
+ import type { ClientMessage } from '../shared/protocol.js';
2
+ import type { User } from '../shared/protocol.js';
3
+ import type { Connection } from './connection.js';
4
+ import type { Receipts } from './receipts.js';
5
+ import type { Session } from './sessions.js';
6
+ type Push = Extract<ClientMessage, {
7
+ type: 'push';
8
+ }>;
9
+ export declare class Transactions {
10
+ private readonly receipts;
11
+ constructor(receipts: Receipts);
12
+ push(session: Session, connection: Connection, user: User, { detached, transactions }: Push): void;
13
+ private broadcastBatch;
14
+ }
15
+ export {};
@@ -0,0 +1,50 @@
1
+ import { compareTransactions } from '../shared/protocol.js';
2
+ import { acknowledge } from './acknowledgments.js';
3
+ import { broadcast } from './broadcast.js';
4
+ export class Transactions {
5
+ receipts;
6
+ constructor(receipts) {
7
+ this.receipts = receipts;
8
+ }
9
+ push(session, connection, user, { detached, transactions }) {
10
+ const accepted = new Map();
11
+ const live = [];
12
+ const recovered = [];
13
+ for (const transaction of transactions) {
14
+ if (accepted.has(transaction.id))
15
+ continue;
16
+ const known = session.journal.get(transaction.id);
17
+ if (known) {
18
+ accepted.set(known.id, known);
19
+ continue;
20
+ }
21
+ const receipt = this.receipts.accept(session.id, transaction, user);
22
+ const current = receipt.transaction;
23
+ const batch = receipt.recovered ? recovered : live;
24
+ accepted.set(current.id, current);
25
+ batch.push(current);
26
+ }
27
+ for (const transaction of recovered.concat(live)) {
28
+ session.journal.add(transaction);
29
+ }
30
+ if (accepted.size) {
31
+ if (detached) {
32
+ session.deferEviction = true;
33
+ }
34
+ connection.send(acknowledge(session.id, [...accepted.values()]));
35
+ }
36
+ const retained = (transaction) => session.journal.get(transaction.id) === transaction;
37
+ this.broadcastBatch(session, connection, recovered.filter(retained), true);
38
+ this.broadcastBatch(session, connection, live.filter(retained));
39
+ }
40
+ broadcastBatch(session, connection, transactions, recovered) {
41
+ if (!transactions.length)
42
+ return;
43
+ broadcast(session.participants, {
44
+ type: 'transactions',
45
+ session: session.id,
46
+ transactions: transactions.sort(compareTransactions),
47
+ recovered
48
+ }, connection.client);
49
+ }
50
+ }
@@ -0,0 +1,3 @@
1
+ import { WebSocket } from 'ws';
2
+ import type { SyncServer } from './server.js';
3
+ export declare function connectWebSocket<Request>(server: SyncServer<Request>, socket: WebSocket, request: Request): void;
@@ -0,0 +1,38 @@
1
+ import { WebSocket } from 'ws';
2
+ const heartbeatInterval = 30_000;
3
+ export function connectWebSocket(server, socket, request) {
4
+ let alive = true;
5
+ const heartbeat = setInterval(() => {
6
+ if (!alive) {
7
+ socket.terminate();
8
+ return;
9
+ }
10
+ if (socket.readyState === WebSocket.OPEN) {
11
+ alive = false;
12
+ socket.ping();
13
+ }
14
+ }, heartbeatInterval).unref();
15
+ socket.once('close', () => clearInterval(heartbeat));
16
+ socket.on('error', () => socket.terminate());
17
+ socket.on('pong', () => { alive = true; });
18
+ server.connect({
19
+ close(code, reason) {
20
+ socket.close(code, reason);
21
+ },
22
+ onClose(listener) {
23
+ socket.once('close', listener);
24
+ },
25
+ onMessage(listener) {
26
+ socket.on('message', (data, binary) => {
27
+ if (!binary) {
28
+ listener(data.toString());
29
+ }
30
+ });
31
+ },
32
+ send(message) {
33
+ if (socket.readyState === WebSocket.OPEN) {
34
+ socket.send(message);
35
+ }
36
+ }
37
+ }, request);
38
+ }
@@ -0,0 +1,11 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+ import type { Server } from 'node:http';
3
+ import type { Server as HttpsServer } from 'node:https';
4
+ import type { SyncOptions } from './server.js';
5
+ export interface WebSocketSyncOptions extends SyncOptions<IncomingMessage> {
6
+ path?: string;
7
+ server: Server | HttpsServer;
8
+ }
9
+ export declare function sync({ path, server, ...options }: WebSocketSyncOptions): {
10
+ close: () => void;
11
+ };
@@ -0,0 +1,26 @@
1
+ import { WebSocketServer } from 'ws';
2
+ import { DEFAULT_PATH } from '../shared/protocol.js';
3
+ import { createSyncServer } from './configuration.js';
4
+ import { connectWebSocket } from './websocket-connection.js';
5
+ export function sync({ path = DEFAULT_PATH, server, ...options }) {
6
+ const core = createSyncServer(options);
7
+ const sockets = new WebSocketServer({ noServer: true });
8
+ function close() {
9
+ server.off('upgrade', upgrade);
10
+ server.off('close', close);
11
+ core.close();
12
+ sockets.close();
13
+ }
14
+ function upgrade(request, socket, head) {
15
+ if (request.url?.split('?', 1)[0] !== path) {
16
+ if (server.listenerCount('upgrade') === 1) {
17
+ socket.destroy();
18
+ }
19
+ return;
20
+ }
21
+ sockets.handleUpgrade(request, socket, head, connection => connectWebSocket(core, connection, request));
22
+ }
23
+ server.on('upgrade', upgrade);
24
+ server.once('close', close);
25
+ return { close };
26
+ }
@@ -0,0 +1,12 @@
1
+ export type FieldValue = string | boolean | string[] | null;
2
+ export interface FieldAddress {
3
+ field: string;
4
+ collection?: string;
5
+ row?: string;
6
+ }
7
+ export interface FieldUpdate {
8
+ address: FieldAddress;
9
+ value: FieldValue;
10
+ }
11
+ export declare function addressKey(address: FieldAddress): string;
12
+ export declare function fieldUpdate(data: unknown): FieldUpdate | undefined;
@@ -0,0 +1,18 @@
1
+ export function addressKey(address) {
2
+ return JSON.stringify([address.collection ?? '', address.row ?? '', address.field]);
3
+ }
4
+ export function fieldUpdate(data) {
5
+ if ((typeof data !== 'object') || !data)
6
+ return;
7
+ const update = data;
8
+ const address = update.address;
9
+ const value = update.value;
10
+ if (!address || (typeof address.field !== 'string'))
11
+ return;
12
+ if (((address.collection !== undefined) || (address.row !== undefined))
13
+ && ((typeof address.collection !== 'string') || (typeof address.row !== 'string')))
14
+ return;
15
+ if ((value === null) || (typeof value === 'string') || (typeof value === 'boolean')
16
+ || (Array.isArray(value) && value.every(item => typeof item === 'string')))
17
+ return update;
18
+ }