-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwebsocket.zod.ts
More file actions
572 lines (501 loc) · 20.3 KB
/
websocket.zod.ts
File metadata and controls
572 lines (501 loc) · 20.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { z } from 'zod';
import { EventNameSchema } from '../shared/identifiers.zod';
import { PresenceStatus } from './realtime-shared.zod';
// Re-export shared PresenceStatus for backward compatibility
export { PresenceStatus } from './realtime-shared.zod';
/**
* WebSocket Event Protocol
*
* Defines the schema for WebSocket-based real-time communication in ObjectStack.
* Supports event subscriptions, filtering, presence tracking, and collaborative editing.
*
* Industry alignment: Firebase Realtime Database, Socket.IO, Pusher
*/
// ==========================================
// Message Types
// ==========================================
/**
* WebSocket Message Type Enum
* Defines the types of messages that can be sent over WebSocket
*/
export const WebSocketMessageType = z.enum([
'subscribe', // Client subscribes to events
'unsubscribe', // Client unsubscribes from events
'event', // Server sends event to client
'ping', // Keepalive ping
'pong', // Keepalive pong response
'ack', // Acknowledgment of message receipt
'error', // Error message
'presence', // Presence update (user status)
'cursor', // Cursor position update (collaborative editing)
'edit', // Document edit operation (collaborative editing)
]);
export type WebSocketMessageType = z.infer<typeof WebSocketMessageType>;
// ==========================================
// Event Subscription
// ==========================================
/**
* Event Filter Operator Enum
* SQL-like filter operators for event filtering
*/
export const FilterOperator = z.enum([
'eq', // Equal
'ne', // Not equal
'gt', // Greater than
'gte', // Greater than or equal
'lt', // Less than
'lte', // Less than or equal
'in', // In array
'nin', // Not in array
'contains', // String contains
'startsWith', // String starts with
'endsWith', // String ends with
'exists', // Field exists
'regex', // Regex match
]);
export type FilterOperator = z.infer<typeof FilterOperator>;
/**
* Event Filter Condition
* Defines a single filter condition for event filtering
*/
export const EventFilterCondition = z.object({
field: z.string().describe('Field path to filter on (supports dot notation, e.g., "user.email")'),
operator: FilterOperator.describe('Comparison operator'),
value: z.unknown().optional().describe('Value to compare against (not needed for "exists" operator)'),
});
export type EventFilterCondition = z.infer<typeof EventFilterCondition>;
/**
* Event Filter Schema
* Logical combination of filter conditions
*/
export const EventFilterSchema: z.ZodType<{
conditions?: EventFilterCondition[];
and?: EventFilter[];
or?: EventFilter[];
not?: EventFilter;
}> = z.object({
conditions: z.array(EventFilterCondition).optional().describe('Array of filter conditions'),
and: z.lazy(() => z.array(EventFilterSchema)).optional().describe('AND logical combination of filters'),
or: z.lazy(() => z.array(EventFilterSchema)).optional().describe('OR logical combination of filters'),
not: z.lazy(() => EventFilterSchema).optional().describe('NOT logical negation of filter'),
});
export type EventFilter = z.infer<typeof EventFilterSchema>;
/**
* Event Pattern Schema
* Event name pattern that supports wildcards for subscriptions
*/
export const EventPatternSchema = z
.string()
.min(1)
.regex(/^[a-z*][a-z0-9_.*]*$/, {
message: 'Event pattern must be lowercase and may contain letters, numbers, underscores, dots, or wildcards (e.g., "record.*", "*.created", "user.login")',
})
.describe('Event pattern (supports wildcards like "record.*" or "*.created")');
export type EventPattern = z.infer<typeof EventPatternSchema>;
/**
* Event Subscription Config
* Configuration for subscribing to specific events
*/
export const EventSubscriptionSchema = z.object({
subscriptionId: z.string().uuid().describe('Unique subscription identifier'),
events: z.array(EventPatternSchema).describe('Event patterns to subscribe to (supports wildcards, e.g., "record.*", "user.created")'),
objects: z.array(z.string()).optional().describe('Object names to filter events by (e.g., ["account", "contact"])'),
filters: EventFilterSchema.optional().describe('Advanced filter conditions for event payloads'),
channels: z.array(z.string()).optional().describe('Channel names for scoped subscriptions'),
});
export type EventSubscription = z.infer<typeof EventSubscriptionSchema>;
/**
* Unsubscribe Request
* Request to unsubscribe from events
*/
export const UnsubscribeRequestSchema = z.object({
subscriptionId: z.string().uuid().describe('Subscription ID to unsubscribe from'),
});
export type UnsubscribeRequest = z.infer<typeof UnsubscribeRequestSchema>;
// ==========================================
// Presence Tracking
// ==========================================
/**
* Presence Status Enum
* Re-exported from realtime-shared.zod.ts for backward compatibility
*/
export const WebSocketPresenceStatus = PresenceStatus;
export type WebSocketPresenceStatus = z.infer<typeof WebSocketPresenceStatus>;
/**
* Presence State Schema
* Tracks real-time user presence and activity
*/
export const PresenceStateSchema = z.object({
userId: z.string().describe('User identifier'),
sessionId: z.string().uuid().describe('Unique session identifier'),
status: WebSocketPresenceStatus.describe('Current presence status'),
lastSeen: z.string().datetime().describe('ISO 8601 datetime of last activity'),
currentLocation: z.string().optional().describe('Current page/route user is viewing'),
device: z.enum(['desktop', 'mobile', 'tablet', 'other']).optional().describe('Device type'),
customStatus: z.string().optional().describe('Custom user status message'),
metadata: z.record(z.string(), z.unknown()).optional().describe('Additional custom presence data'),
});
export type PresenceState = z.infer<typeof PresenceStateSchema>;
/**
* Presence Update Request
* Client request to update presence status
*/
export const PresenceUpdateSchema = z.object({
status: WebSocketPresenceStatus.optional().describe('Updated presence status'),
currentLocation: z.string().optional().describe('Updated current location'),
customStatus: z.string().optional().describe('Updated custom status message'),
metadata: z.record(z.string(), z.unknown()).optional().describe('Updated metadata'),
});
export type PresenceUpdate = z.infer<typeof PresenceUpdateSchema>;
// ==========================================
// Collaborative Editing Protocol
// ==========================================
/**
* Cursor Position Schema
* Represents a cursor position in a document
*/
export const CursorPositionSchema = z.object({
userId: z.string().describe('User identifier'),
sessionId: z.string().uuid().describe('Session identifier'),
documentId: z.string().describe('Document identifier being edited'),
position: z.object({
line: z.number().int().nonnegative().describe('Line number (0-indexed)'),
column: z.number().int().nonnegative().describe('Column number (0-indexed)'),
}).optional().describe('Cursor position in document'),
selection: z.object({
start: z.object({
line: z.number().int().nonnegative(),
column: z.number().int().nonnegative(),
}),
end: z.object({
line: z.number().int().nonnegative(),
column: z.number().int().nonnegative(),
}),
}).optional().describe('Selection range (if text is selected)'),
color: z.string().optional().describe('Cursor color for visual representation'),
userName: z.string().optional().describe('Display name of user'),
lastUpdate: z.string().datetime().describe('ISO 8601 datetime of last cursor update'),
});
export type CursorPosition = z.infer<typeof CursorPositionSchema>;
/**
* Edit Operation Type Enum
* Types of edit operations for collaborative editing
*/
export const EditOperationType = z.enum([
'insert', // Insert text at position
'delete', // Delete text from range
'replace', // Replace text in range
]);
export type EditOperationType = z.infer<typeof EditOperationType>;
/**
* Edit Operation Schema
* Represents a single edit operation on a document
* Supports Operational Transformation (OT) for conflict resolution
*/
export const EditOperationSchema = z.object({
operationId: z.string().uuid().describe('Unique operation identifier'),
documentId: z.string().describe('Document identifier'),
userId: z.string().describe('User who performed the edit'),
sessionId: z.string().uuid().describe('Session identifier'),
type: EditOperationType.describe('Type of edit operation'),
position: z.object({
line: z.number().int().nonnegative().describe('Line number (0-indexed)'),
column: z.number().int().nonnegative().describe('Column number (0-indexed)'),
}).describe('Starting position of the operation'),
endPosition: z.object({
line: z.number().int().nonnegative(),
column: z.number().int().nonnegative(),
}).optional().describe('Ending position (for delete/replace operations)'),
content: z.string().optional().describe('Content to insert/replace'),
version: z.number().int().nonnegative().describe('Document version before this operation'),
timestamp: z.string().datetime().describe('ISO 8601 datetime when operation was created'),
baseOperationId: z.string().uuid().optional().describe('Previous operation ID this builds upon (for OT)'),
});
export type EditOperation = z.infer<typeof EditOperationSchema>;
/**
* Document State Schema
* Represents the current state of a collaborative document
*/
export const DocumentStateSchema = z.object({
documentId: z.string().describe('Document identifier'),
version: z.number().int().nonnegative().describe('Current document version'),
content: z.string().describe('Current document content'),
lastModified: z.string().datetime().describe('ISO 8601 datetime of last modification'),
activeSessions: z.array(z.string().uuid()).describe('Active editing session IDs'),
checksum: z.string().optional().describe('Content checksum for integrity verification'),
});
export type DocumentState = z.infer<typeof DocumentStateSchema>;
// ==========================================
// WebSocket Messages
// ==========================================
/**
* Base WebSocket Message
* All WebSocket messages extend this base structure
*/
const BaseWebSocketMessage = z.object({
messageId: z.string().uuid().describe('Unique message identifier'),
type: WebSocketMessageType.describe('Message type'),
timestamp: z.string().datetime().describe('ISO 8601 datetime when message was sent'),
});
/**
* Subscribe Message
* Client sends this to subscribe to events
*/
export const SubscribeMessageSchema = BaseWebSocketMessage.extend({
type: z.literal('subscribe'),
subscription: EventSubscriptionSchema.describe('Subscription configuration'),
});
export type SubscribeMessage = z.infer<typeof SubscribeMessageSchema>;
/**
* Unsubscribe Message
* Client sends this to unsubscribe from events
*/
export const UnsubscribeMessageSchema = BaseWebSocketMessage.extend({
type: z.literal('unsubscribe'),
request: UnsubscribeRequestSchema.describe('Unsubscribe request'),
});
export type UnsubscribeMessage = z.infer<typeof UnsubscribeMessageSchema>;
/**
* Event Message
* Server sends this when a subscribed event occurs
*/
export const EventMessageSchema = BaseWebSocketMessage.extend({
type: z.literal('event'),
subscriptionId: z.string().uuid().describe('Subscription ID this event belongs to'),
eventName: EventNameSchema.describe('Event name'),
object: z.string().optional().describe('Object name the event relates to'),
payload: z.unknown().describe('Event payload data'),
userId: z.string().optional().describe('User who triggered the event'),
});
export type EventMessage = z.infer<typeof EventMessageSchema>;
/**
* Presence Message
* Presence update message
*/
export const PresenceMessageSchema = BaseWebSocketMessage.extend({
type: z.literal('presence'),
presence: PresenceStateSchema.describe('Presence state'),
});
export type PresenceMessage = z.infer<typeof PresenceMessageSchema>;
/**
* Cursor Message
* Cursor position update for collaborative editing
*/
export const CursorMessageSchema = BaseWebSocketMessage.extend({
type: z.literal('cursor'),
cursor: CursorPositionSchema.describe('Cursor position'),
});
export type CursorMessage = z.infer<typeof CursorMessageSchema>;
/**
* Edit Message
* Document edit operation for collaborative editing
*/
export const EditMessageSchema = BaseWebSocketMessage.extend({
type: z.literal('edit'),
operation: EditOperationSchema.describe('Edit operation'),
});
export type EditMessage = z.infer<typeof EditMessageSchema>;
/**
* Acknowledgment Message
* Server acknowledges receipt of a message
*/
export const AckMessageSchema = BaseWebSocketMessage.extend({
type: z.literal('ack'),
ackMessageId: z.string().uuid().describe('ID of the message being acknowledged'),
success: z.boolean().describe('Whether the operation was successful'),
error: z.string().optional().describe('Error message if operation failed'),
});
export type AckMessage = z.infer<typeof AckMessageSchema>;
/**
* Error Message
* Server sends error information
*/
export const ErrorMessageSchema = BaseWebSocketMessage.extend({
type: z.literal('error'),
code: z.string().describe('Error code'),
message: z.string().describe('Error message'),
details: z.unknown().optional().describe('Additional error details'),
});
export type ErrorMessage = z.infer<typeof ErrorMessageSchema>;
/**
* Ping Message
* Keepalive ping from client or server
*/
export const PingMessageSchema = BaseWebSocketMessage.extend({
type: z.literal('ping'),
});
export type PingMessage = z.infer<typeof PingMessageSchema>;
/**
* Pong Message
* Keepalive pong response
*/
export const PongMessageSchema = BaseWebSocketMessage.extend({
type: z.literal('pong'),
pingMessageId: z.string().uuid().optional().describe('ID of ping message being responded to'),
});
export type PongMessage = z.infer<typeof PongMessageSchema>;
/**
* WebSocket Message Union
* Discriminated union of all WebSocket message types
*/
export const WebSocketMessageSchema = z.discriminatedUnion('type', [
SubscribeMessageSchema,
UnsubscribeMessageSchema,
EventMessageSchema,
PresenceMessageSchema,
CursorMessageSchema,
EditMessageSchema,
AckMessageSchema,
ErrorMessageSchema,
PingMessageSchema,
PongMessageSchema,
]);
export type WebSocketMessage = z.infer<typeof WebSocketMessageSchema>;
// ==========================================
// Connection Configuration
// ==========================================
/**
* WebSocket Connection Config
* Configuration for WebSocket connections
*/
export const WebSocketConfigSchema = z.object({
url: z.string().url().describe('WebSocket server URL'),
protocols: z.array(z.string()).optional().describe('WebSocket sub-protocols'),
reconnect: z.boolean().optional().default(true).describe('Enable automatic reconnection'),
reconnectInterval: z.number().int().positive().optional().default(1000).describe('Reconnection interval in milliseconds'),
maxReconnectAttempts: z.number().int().positive().optional().default(5).describe('Maximum reconnection attempts'),
pingInterval: z.number().int().positive().optional().default(30000).describe('Ping interval in milliseconds'),
timeout: z.number().int().positive().optional().default(5000).describe('Message timeout in milliseconds'),
headers: z.record(z.string(), z.string()).optional().describe('Custom headers for WebSocket handshake'),
});
export type WebSocketConfig = z.infer<typeof WebSocketConfigSchema>;
// ==========================================
// Simplified Collaboration API
// ==========================================
/**
* Simplified WebSocket Event Schema
*
* A simplified event schema for basic WebSocket communication.
* Complements the comprehensive WebSocketMessageSchema above for simpler use cases.
*
* @example Subscribe to channel
* ```typescript
* {
* type: 'subscribe',
* channel: 'record.account.123',
* payload: { events: ['created', 'updated'] },
* timestamp: Date.now()
* }
* ```
*
* @example Data change notification
* ```typescript
* {
* type: 'data-change',
* channel: 'record.account.123',
* payload: { id: '123', action: 'updated', data: {...} },
* timestamp: Date.now()
* }
* ```
*/
export const WebSocketEventSchema = z.object({
type: z.enum([
'subscribe', // Client subscribes to channel
'unsubscribe', // Client unsubscribes from channel
'data-change', // Data modification event
'presence-update', // User presence change
'cursor-update', // Cursor position change (collaborative editing)
'error', // Error message
]).describe('Event type'),
channel: z.string().describe('Channel identifier (e.g., "record.account.123", "user.456")'),
payload: z.unknown().describe('Event payload data'),
timestamp: z.number().describe('Unix timestamp in milliseconds'),
});
export type WebSocketEvent = z.infer<typeof WebSocketEventSchema>;
/**
* Simplified Presence State Schema
*
* A simplified presence schema for basic user presence tracking.
* Complements the comprehensive PresenceStateSchema for simpler integrations.
*
* Use this for basic presence features. For advanced features like device tracking,
* custom status, and session management, use the comprehensive PresenceStateSchema above.
*
* @example User online
* ```typescript
* {
* userId: 'user123',
* userName: 'John Doe',
* status: 'online',
* lastSeen: Date.now(),
* metadata: { currentPage: '/dashboard' }
* }
* ```
*/
export const SimplePresenceStateSchema = z.object({
userId: z.string().describe('User identifier'),
userName: z.string().describe('User display name'),
status: z.enum(['online', 'away', 'offline']).describe('User presence status'),
lastSeen: z.number().describe('Unix timestamp of last activity in milliseconds'),
metadata: z.record(z.string(), z.unknown()).optional().describe('Additional presence metadata (e.g., current page, custom status)'),
});
export type SimplePresenceState = z.infer<typeof SimplePresenceStateSchema>;
/**
* Simplified Cursor Position Schema
*
* A simplified cursor position schema for basic collaborative editing.
* Complements the comprehensive CursorPositionSchema for simpler use cases.
*
* Use this for basic cursor sharing. For advanced features like selections,
* color coding, and document versioning, use the comprehensive CursorPositionSchema above.
*
* @example Cursor in text field
* ```typescript
* {
* userId: 'user123',
* recordId: 'account_456',
* fieldName: 'description',
* position: 42,
* selection: { start: 42, end: 57 }
* }
* ```
*/
export const SimpleCursorPositionSchema = z.object({
userId: z.string().describe('User identifier'),
recordId: z.string().describe('Record identifier being edited'),
fieldName: z.string().describe('Field name being edited'),
position: z.number().describe('Cursor position (character offset from start)'),
selection: z.object({
start: z.number().describe('Selection start position'),
end: z.number().describe('Selection end position'),
}).optional().describe('Text selection range (if text is selected)'),
});
export type SimpleCursorPosition = z.infer<typeof SimpleCursorPositionSchema>;
/**
* WebSocket Server Configuration Schema
*
* Server-side configuration for WebSocket services.
* Controls features like presence tracking, cursor sharing, and connection management.
*
* @example Production configuration
* ```typescript
* {
* enabled: true,
* path: '/ws',
* heartbeatInterval: 30000,
* reconnectAttempts: 5,
* presence: true,
* cursorSharing: true
* }
* ```
*/
export const WebSocketServerConfigSchema = z.object({
enabled: z.boolean().default(false).describe('Enable WebSocket server'),
path: z.string().default('/ws').describe('WebSocket endpoint path'),
heartbeatInterval: z.number().default(30000).describe('Heartbeat interval in milliseconds'),
reconnectAttempts: z.number().default(5).describe('Maximum reconnection attempts for clients'),
presence: z.boolean().default(false).describe('Enable presence tracking'),
cursorSharing: z.boolean().default(false).describe('Enable collaborative cursor sharing'),
});
export type WebSocketServerConfig = z.infer<typeof WebSocketServerConfigSchema>;