@motiadev/stream-client-browser 0.0.7-build.20250529212805

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Motia
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 ADDED
@@ -0,0 +1,185 @@
1
+ # @motiadev/stream-client-browser
2
+
3
+ Motia Stream Client Package – Responsible for managing real-time [Motia](https://motia.dev) streams of data in browser environments. This package provides a simple, type-safe interface for subscribing to item and group streams over WebSockets, handling live updates, and managing stream state in your web applications.
4
+
5
+ ## Features
6
+
7
+ - **WebSocket-based streaming** for real-time data updates
8
+ - **Item and group subscriptions** with automatic state management
9
+ - **Change listeners** for reactive UI updates
10
+ - **Custom event handling** for extensibility
11
+ - **TypeScript support** for strong typing and autocompletion
12
+
13
+ ---
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ npm install @motiadev/stream-client-browser
19
+ ```
20
+
21
+ ---
22
+
23
+ ## Usage
24
+
25
+ ### 1. Creating a Stream Connection
26
+
27
+ ```typescript
28
+ import { Stream } from '@motiadev/stream-client-browser'
29
+
30
+ const stream = new Stream('wss://your-stream-server', () => {
31
+ console.log('WebSocket connection established!')
32
+ })
33
+ ```
34
+
35
+ ### 2. Subscribing to an Item Stream
36
+
37
+ ```typescript
38
+ const itemSubscription = stream.subscribeItem<{ id: string; name: string }>('users', 'user-123')
39
+
40
+ itemSubscription.addChangeListener((user) => {
41
+ console.log('User updated:', user)
42
+ })
43
+
44
+ // Listen for custom events
45
+ itemSubscription.onEvent('custom-event', (data) => {
46
+ console.log('Received custom event:', data)
47
+ })
48
+ ```
49
+
50
+ ### 3. Subscribing to a Group Stream
51
+
52
+ ```typescript
53
+ const groupSubscription = stream.subscribeGroup<{ id: string; name: string }>('users', 'group-abc')
54
+
55
+ groupSubscription.addChangeListener((users) => {
56
+ console.log('Group users updated:', users)
57
+ })
58
+ ```
59
+
60
+ ### 4. Cleaning Up
61
+
62
+ ```typescript
63
+ itemSubscription.close()
64
+ groupSubscription.close()
65
+ stream.close()
66
+ ```
67
+
68
+ ---
69
+
70
+ ## API Reference
71
+
72
+ ### `Stream`
73
+
74
+ - **constructor(address: string, onReady: () => void)**
75
+
76
+ - Establishes a WebSocket connection to the given address.
77
+ - Calls `onReady` when the connection is open.
78
+
79
+ - **subscribeItem<T>(streamName: string, id: string): StreamItemSubscription<T>**
80
+
81
+ - Subscribes to a single item in a stream.
82
+ - Returns a `StreamItemSubscription` instance.
83
+
84
+ - **subscribeGroup<T>(streamName: string, groupId: string): StreamGroupSubscription<T>**
85
+
86
+ - Subscribes to a group of items in a stream.
87
+ - Returns a `StreamGroupSubscription` instance.
88
+
89
+ - **close()**
90
+ - Closes the WebSocket connection.
91
+
92
+ ---
93
+
94
+ ### `StreamItemSubscription<T>`
95
+
96
+ - **addChangeListener(listener: (item: T | null) => void)**
97
+
98
+ - Registers a callback for when the item changes.
99
+
100
+ - **removeChangeListener(listener)**
101
+
102
+ - Unregisters a change listener.
103
+
104
+ - **onEvent(type: string, listener: (event: any) => void)**
105
+
106
+ - Registers a custom event listener.
107
+
108
+ - **offEvent(type: string, listener)**
109
+
110
+ - Unregisters a custom event listener.
111
+
112
+ - **getState(): T | null**
113
+
114
+ - Returns the current state of the item.
115
+
116
+ - **close()**
117
+ - Unsubscribes from the item stream and cleans up listeners.
118
+
119
+ ---
120
+
121
+ ### `StreamGroupSubscription<T>`
122
+
123
+ - **addChangeListener(listener: (items: T[]) => void)**
124
+
125
+ - Registers a callback for when the group changes.
126
+
127
+ - **removeChangeListener(listener)**
128
+
129
+ - Unregisters a change listener.
130
+
131
+ - **onEvent(type: string, listener: (event: any) => void)**
132
+
133
+ - Registers a custom event listener.
134
+
135
+ - **offEvent(type: string, listener: (event: any) => void)**
136
+
137
+ - Unregisters a custom event listener.
138
+
139
+ - **getState(): T[]**
140
+
141
+ - Returns the current state of the group.
142
+
143
+ - **close()**
144
+ - Unsubscribes from the group stream and cleans up listeners.
145
+
146
+ ---
147
+
148
+ ### `StreamSubscription` (Base Class)
149
+
150
+ - **onEvent(type: string, listener: (event: any) => void)**
151
+ - **offEvent(type: string, listener: (event: any) => void)**
152
+
153
+ ---
154
+
155
+ ## Types
156
+
157
+ All types are exported from `stream.types.ts` for advanced usage and type safety.
158
+
159
+ ---
160
+
161
+ ## Example
162
+
163
+ ```typescript
164
+ import { Stream } from '@motiadev/stream-client-browser'
165
+
166
+ const stream = new Stream('wss://example.com', () => {
167
+ const userSub = stream.subscribeItem<{ id: string; name: string }>('users', 'user-1')
168
+
169
+ userSub.addChangeListener((user) => {
170
+ // React to user changes
171
+ })
172
+
173
+ const groupSub = stream.subscribeGroup<{ id: string; name: string }>('users', 'group-1')
174
+
175
+ groupSub.addChangeListener((users) => {
176
+ // React to group changes
177
+ })
178
+ })
179
+ ```
180
+
181
+ ---
182
+
183
+ ## License
184
+
185
+ MIT
@@ -0,0 +1,4 @@
1
+ export { Stream } from './src/stream';
2
+ export { StreamItemSubscription } from './src/stream-item';
3
+ export { StreamGroupSubscription } from './src/stream-group';
4
+ export { StreamSubscription } from './src/stream-subscription';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { Stream } from './src/stream';
2
+ export { StreamItemSubscription } from './src/stream-item';
3
+ export { StreamGroupSubscription } from './src/stream-group';
4
+ export { StreamSubscription } from './src/stream-subscription';
@@ -0,0 +1,8 @@
1
+ import { StreamSubscription } from './stream-subscription';
2
+ import { GroupEventMessage, JoinMessage } from './stream.types';
3
+ export declare class StreamGroupSubscription<TData extends {
4
+ id: string;
5
+ }> extends StreamSubscription<TData[], GroupEventMessage<TData>> {
6
+ constructor(sub: JoinMessage);
7
+ listener(message: GroupEventMessage<TData>): void;
8
+ }
@@ -0,0 +1,32 @@
1
+ import { StreamSubscription } from './stream-subscription';
2
+ export class StreamGroupSubscription extends StreamSubscription {
3
+ constructor(sub) {
4
+ super(sub, []);
5
+ }
6
+ listener(message) {
7
+ if (message.event.type === 'sync') {
8
+ this.setState(message.event.data);
9
+ }
10
+ else if (message.event.type === 'create') {
11
+ const id = message.event.data.id;
12
+ const state = this.getState();
13
+ if (!state.find((item) => item.id === id)) {
14
+ this.setState([...state, message.event.data]);
15
+ }
16
+ }
17
+ else if (message.event.type === 'update') {
18
+ const messageData = message.event.data;
19
+ const messageDataId = messageData.id;
20
+ const state = this.getState();
21
+ this.setState(state.map((item) => (item.id === messageDataId ? messageData : item)));
22
+ }
23
+ else if (message.event.type === 'delete') {
24
+ const messageDataId = message.event.data.id;
25
+ const state = this.getState();
26
+ this.setState(state.filter((item) => item.id !== messageDataId));
27
+ }
28
+ else if (message.event.type === 'event') {
29
+ this.onEventReceived(message.event.event);
30
+ }
31
+ }
32
+ }
@@ -0,0 +1,8 @@
1
+ import { StreamSubscription } from './stream-subscription';
2
+ import { ItemEventMessage, JoinMessage } from './stream.types';
3
+ export declare class StreamItemSubscription<TData extends {
4
+ id: string;
5
+ }> extends StreamSubscription<TData | null, ItemEventMessage<TData>> {
6
+ constructor(sub: JoinMessage);
7
+ listener(message: ItemEventMessage<TData>): void;
8
+ }
@@ -0,0 +1,17 @@
1
+ import { StreamSubscription } from './stream-subscription';
2
+ export class StreamItemSubscription extends StreamSubscription {
3
+ constructor(sub) {
4
+ super(sub, null);
5
+ }
6
+ listener(message) {
7
+ if (message.event.type === 'sync' || message.event.type === 'create' || message.event.type === 'update') {
8
+ this.setState(message.event.data);
9
+ }
10
+ else if (message.event.type === 'delete') {
11
+ this.setState(null);
12
+ }
13
+ else if (message.event.type === 'event') {
14
+ this.onEventReceived(message.event.event);
15
+ }
16
+ }
17
+ }
@@ -0,0 +1,36 @@
1
+ import { CustomEvent, JoinMessage, Listener } from './stream.types';
2
+ type CustomEventListener = (event: any) => void;
3
+ export declare abstract class StreamSubscription<TData = unknown, TEventData = unknown> {
4
+ private customEventListeners;
5
+ private closeListeners;
6
+ private onChangeListeners;
7
+ private state;
8
+ readonly sub: JoinMessage;
9
+ constructor(sub: JoinMessage, state: TData);
10
+ abstract listener(message: TEventData): void;
11
+ protected onEventReceived(event: CustomEvent): void;
12
+ /**
13
+ * Add a custom event listener. This listener will be called whenever the custom event is received.
14
+ */
15
+ onEvent(type: string, listener: CustomEventListener): void;
16
+ /**
17
+ * Remove a custom event listener.
18
+ */
19
+ offEvent(type: string, listener: CustomEventListener): void;
20
+ onClose(listener: () => void): void;
21
+ close(): void;
22
+ /**
23
+ * Add a change listener. This listener will be called whenever the state of the group changes.
24
+ */
25
+ addChangeListener(listener: Listener<TData>): void;
26
+ /**
27
+ * Remove a change listener.
28
+ */
29
+ removeChangeListener(listener: Listener<TData>): void;
30
+ /**
31
+ * Get the current state of the group.
32
+ */
33
+ getState(): TData;
34
+ protected setState(state: TData): void;
35
+ }
36
+ export {};
@@ -0,0 +1,59 @@
1
+ export class StreamSubscription {
2
+ constructor(sub, state) {
3
+ this.customEventListeners = new Map();
4
+ this.closeListeners = new Set();
5
+ this.onChangeListeners = new Set();
6
+ this.sub = sub;
7
+ this.state = state;
8
+ }
9
+ onEventReceived(event) {
10
+ const customEventListeners = this.customEventListeners.get(event.type);
11
+ if (customEventListeners) {
12
+ const eventData = event.data;
13
+ customEventListeners.forEach((listener) => listener(eventData));
14
+ }
15
+ }
16
+ /**
17
+ * Add a custom event listener. This listener will be called whenever the custom event is received.
18
+ */
19
+ onEvent(type, listener) {
20
+ const listeners = this.customEventListeners.get(type) || [];
21
+ this.customEventListeners.set(type, [...listeners, listener]);
22
+ }
23
+ /**
24
+ * Remove a custom event listener.
25
+ */
26
+ offEvent(type, listener) {
27
+ const listeners = this.customEventListeners.get(type) || [];
28
+ this.customEventListeners.set(type, listeners.filter((l) => l !== listener));
29
+ }
30
+ onClose(listener) {
31
+ this.closeListeners.add(listener);
32
+ }
33
+ close() {
34
+ this.closeListeners.forEach((listener) => listener());
35
+ this.closeListeners.clear();
36
+ }
37
+ /**
38
+ * Add a change listener. This listener will be called whenever the state of the group changes.
39
+ */
40
+ addChangeListener(listener) {
41
+ this.onChangeListeners.add(listener);
42
+ }
43
+ /**
44
+ * Remove a change listener.
45
+ */
46
+ removeChangeListener(listener) {
47
+ this.onChangeListeners.delete(listener);
48
+ }
49
+ /**
50
+ * Get the current state of the group.
51
+ */
52
+ getState() {
53
+ return this.state;
54
+ }
55
+ setState(state) {
56
+ this.state = state;
57
+ this.onChangeListeners.forEach((listener) => listener(state));
58
+ }
59
+ }
@@ -0,0 +1,36 @@
1
+ import { StreamGroupSubscription } from './stream-group';
2
+ import { StreamItemSubscription } from './stream-item';
3
+ export declare class Stream {
4
+ private address;
5
+ private ws;
6
+ private listeners;
7
+ constructor(address: string);
8
+ createSocket(): WebSocket;
9
+ /**
10
+ * Subscribe to an item in a stream.
11
+ *
12
+ * @argument streamName - The name of the stream to subscribe to.
13
+ * @argument groupId - The id of the group to subscribe to.
14
+ * @argument id - The id of the item to subscribe to.
15
+ */
16
+ subscribeItem<TData extends {
17
+ id: string;
18
+ }>(streamName: string, groupId: string, id: string): StreamItemSubscription<TData>;
19
+ /**
20
+ * Subscribe to a group in a stream.
21
+ *
22
+ * @argument streamName - The name of the stream to subscribe to.
23
+ * @argument groupId - The id of the group to subscribe to.
24
+ */
25
+ subscribeGroup<TData extends {
26
+ id: string;
27
+ }>(streamName: string, groupId: string): StreamGroupSubscription<TData>;
28
+ close(): void;
29
+ private onSocketClose;
30
+ private onSocketOpen;
31
+ messageListener(event: MessageEvent<string>): void;
32
+ private subscribe;
33
+ private join;
34
+ private leave;
35
+ private roomName;
36
+ }
@@ -0,0 +1,100 @@
1
+ import { v4 as uuidv4 } from 'uuid';
2
+ import { StreamGroupSubscription } from './stream-group';
3
+ import { StreamItemSubscription } from './stream-item';
4
+ export class Stream {
5
+ constructor(address) {
6
+ this.address = address;
7
+ this.listeners = {};
8
+ this.ws = this.createSocket();
9
+ }
10
+ createSocket() {
11
+ this.ws = new WebSocket(this.address);
12
+ this.ws.addEventListener('message', (message) => this.messageListener(message));
13
+ this.ws.addEventListener('open', () => this.onSocketOpen());
14
+ this.ws.addEventListener('close', () => this.onSocketClose());
15
+ return this.ws;
16
+ }
17
+ /**
18
+ * Subscribe to an item in a stream.
19
+ *
20
+ * @argument streamName - The name of the stream to subscribe to.
21
+ * @argument groupId - The id of the group to subscribe to.
22
+ * @argument id - The id of the item to subscribe to.
23
+ */
24
+ subscribeItem(streamName, groupId, id) {
25
+ const subscriptionId = uuidv4();
26
+ const sub = { streamName, groupId, id, subscriptionId };
27
+ const subscription = new StreamItemSubscription(sub);
28
+ this.subscribe(subscription);
29
+ return subscription;
30
+ }
31
+ /**
32
+ * Subscribe to a group in a stream.
33
+ *
34
+ * @argument streamName - The name of the stream to subscribe to.
35
+ * @argument groupId - The id of the group to subscribe to.
36
+ */
37
+ subscribeGroup(streamName, groupId) {
38
+ const subscriptionId = uuidv4();
39
+ const sub = { streamName, groupId, subscriptionId };
40
+ const subscription = new StreamGroupSubscription(sub);
41
+ this.subscribe(subscription);
42
+ return subscription;
43
+ }
44
+ close() {
45
+ this.listeners = {}; // clean up all listeners
46
+ this.ws.removeEventListener('message', this.messageListener);
47
+ this.ws.removeEventListener('open', this.onSocketOpen);
48
+ this.ws.removeEventListener('close', this.onSocketClose);
49
+ this.ws.close();
50
+ }
51
+ onSocketClose() {
52
+ // retry to connect
53
+ setTimeout(() => this.createSocket(), 2000);
54
+ }
55
+ onSocketOpen() {
56
+ Object.values(this.listeners).forEach((listeners) => {
57
+ listeners.forEach((subscription) => this.join(subscription));
58
+ });
59
+ }
60
+ messageListener(event) {
61
+ const message = JSON.parse(event.data);
62
+ const room = this.roomName(message);
63
+ this.listeners[room]?.forEach((listener) => listener.listener(message));
64
+ if (message.id) {
65
+ const groupRoom = this.roomName({
66
+ streamName: message.streamName,
67
+ groupId: message.groupId,
68
+ });
69
+ this.listeners[groupRoom]?.forEach((listener) => listener.listener(message));
70
+ }
71
+ }
72
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
73
+ subscribe(subscription) {
74
+ const room = this.roomName(subscription.sub);
75
+ if (!this.listeners[room]) {
76
+ this.listeners[room] = new Set();
77
+ }
78
+ this.listeners[room].add(subscription);
79
+ this.join(subscription);
80
+ subscription.onClose(() => {
81
+ this.listeners[room].delete(subscription);
82
+ this.leave(subscription);
83
+ });
84
+ }
85
+ join(subscription) {
86
+ if (this.ws.readyState === WebSocket.OPEN) {
87
+ this.ws.send(JSON.stringify({ type: 'join', data: subscription.sub }));
88
+ }
89
+ }
90
+ leave(subscription) {
91
+ if (this.ws.readyState === WebSocket.OPEN) {
92
+ this.ws.send(JSON.stringify({ type: 'leave', data: subscription.sub }));
93
+ }
94
+ }
95
+ roomName(message) {
96
+ return message.id
97
+ ? `${message.streamName}:group:${message.groupId}:item:${message.id}`
98
+ : `${message.streamName}:group:${message.groupId}`;
99
+ }
100
+ }
@@ -0,0 +1,55 @@
1
+ export type BaseMessage = {
2
+ streamName: string;
3
+ groupId: string;
4
+ id?: string;
5
+ };
6
+ export type JoinMessage = BaseMessage & {
7
+ subscriptionId: string;
8
+ };
9
+ export type CustomEvent = {
10
+ type: string;
11
+ data: any;
12
+ };
13
+ export type StreamEvent<TData extends {
14
+ id: string;
15
+ }> = {
16
+ type: 'create';
17
+ data: TData;
18
+ } | {
19
+ type: 'update';
20
+ data: TData;
21
+ } | {
22
+ type: 'delete';
23
+ data: TData;
24
+ } | {
25
+ type: 'event';
26
+ event: CustomEvent;
27
+ };
28
+ export type ItemStreamEvent<TData extends {
29
+ id: string;
30
+ }> = StreamEvent<TData> | {
31
+ type: 'sync';
32
+ data: TData;
33
+ };
34
+ export type GroupStreamEvent<TData extends {
35
+ id: string;
36
+ }> = StreamEvent<TData> | {
37
+ type: 'sync';
38
+ data: TData[];
39
+ };
40
+ export type ItemEventMessage<TData extends {
41
+ id: string;
42
+ }> = BaseMessage & {
43
+ event: ItemStreamEvent<TData>;
44
+ };
45
+ export type GroupEventMessage<TData extends {
46
+ id: string;
47
+ }> = BaseMessage & {
48
+ event: GroupStreamEvent<TData>;
49
+ };
50
+ export type Message = {
51
+ type: 'join' | 'leave';
52
+ data: JoinMessage;
53
+ };
54
+ export type Listener<TData> = (state: TData | null) => void;
55
+ export type CustomEventListener<TData> = (event: TData) => void;
@@ -0,0 +1 @@
1
+ export {};
package/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export { Stream } from './src/stream'
2
+ export { StreamItemSubscription } from './src/stream-item'
3
+ export { StreamGroupSubscription } from './src/stream-group'
4
+ export { StreamSubscription } from './src/stream-subscription'
package/package.json ADDED
@@ -0,0 +1,22 @@
1
+ {
2
+ "name": "@motiadev/stream-client-browser",
3
+ "description": "Motia Stream Client Package – Responsible for managing streams of data.",
4
+ "version": "0.0.7-build.20250529212805",
5
+ "license": "MIT",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "dependencies": {
9
+ "uuid": "^11.1.0"
10
+ },
11
+ "devDependencies": {
12
+ "@types/jest": "^29.5.14",
13
+ "@types/ws": "^8.18.1",
14
+ "jest": "^29.7.0",
15
+ "ts-jest": "^29.2.5",
16
+ "typescript": "^5.7.2"
17
+ },
18
+ "scripts": {
19
+ "build": "rm -rf dist && tsc",
20
+ "lint": "eslint --config ../../eslint.config.js"
21
+ }
22
+ }
@@ -0,0 +1,37 @@
1
+ import { StreamSubscription } from './stream-subscription'
2
+ import { GroupEventMessage, JoinMessage } from './stream.types'
3
+
4
+ export class StreamGroupSubscription<TData extends { id: string }> extends StreamSubscription<
5
+ TData[],
6
+ GroupEventMessage<TData>
7
+ > {
8
+ constructor(sub: JoinMessage) {
9
+ super(sub, [])
10
+ }
11
+
12
+ listener(message: GroupEventMessage<TData>): void {
13
+ if (message.event.type === 'sync') {
14
+ this.setState(message.event.data)
15
+ } else if (message.event.type === 'create') {
16
+ const id = message.event.data.id
17
+ const state = this.getState()
18
+
19
+ if (!state.find((item) => item.id === id)) {
20
+ this.setState([...state, message.event.data])
21
+ }
22
+ } else if (message.event.type === 'update') {
23
+ const messageData = message.event.data
24
+ const messageDataId = messageData.id
25
+ const state = this.getState()
26
+
27
+ this.setState(state.map((item) => (item.id === messageDataId ? messageData : item)))
28
+ } else if (message.event.type === 'delete') {
29
+ const messageDataId = message.event.data.id
30
+ const state = this.getState()
31
+
32
+ this.setState(state.filter((item) => item.id !== messageDataId))
33
+ } else if (message.event.type === 'event') {
34
+ this.onEventReceived(message.event.event)
35
+ }
36
+ }
37
+ }
@@ -0,0 +1,21 @@
1
+ import { StreamSubscription } from './stream-subscription'
2
+ import { ItemEventMessage, JoinMessage } from './stream.types'
3
+
4
+ export class StreamItemSubscription<TData extends { id: string }> extends StreamSubscription<
5
+ TData | null,
6
+ ItemEventMessage<TData>
7
+ > {
8
+ constructor(sub: JoinMessage) {
9
+ super(sub, null)
10
+ }
11
+
12
+ listener(message: ItemEventMessage<TData>): void {
13
+ if (message.event.type === 'sync' || message.event.type === 'create' || message.event.type === 'update') {
14
+ this.setState(message.event.data)
15
+ } else if (message.event.type === 'delete') {
16
+ this.setState(null)
17
+ } else if (message.event.type === 'event') {
18
+ this.onEventReceived(message.event.event)
19
+ }
20
+ }
21
+ }
@@ -0,0 +1,84 @@
1
+ import { CustomEvent, JoinMessage, Listener } from './stream.types'
2
+
3
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
4
+ type CustomEventListener = (event: any) => void
5
+
6
+ export abstract class StreamSubscription<TData = unknown, TEventData = unknown> {
7
+ private customEventListeners: Map<string, CustomEventListener[]> = new Map()
8
+ private closeListeners: Set<() => void> = new Set()
9
+
10
+ private onChangeListeners: Set<Listener<TData>> = new Set()
11
+ private state: TData
12
+
13
+ readonly sub: JoinMessage
14
+
15
+ constructor(sub: JoinMessage, state: TData) {
16
+ this.sub = sub
17
+ this.state = state
18
+ }
19
+
20
+ abstract listener(message: TEventData): void
21
+
22
+ protected onEventReceived(event: CustomEvent) {
23
+ const customEventListeners = this.customEventListeners.get(event.type)
24
+
25
+ if (customEventListeners) {
26
+ const eventData = event.data
27
+ customEventListeners.forEach((listener) => listener(eventData))
28
+ }
29
+ }
30
+
31
+ /**
32
+ * Add a custom event listener. This listener will be called whenever the custom event is received.
33
+ */
34
+ onEvent(type: string, listener: CustomEventListener) {
35
+ const listeners = this.customEventListeners.get(type) || []
36
+ this.customEventListeners.set(type, [...listeners, listener])
37
+ }
38
+
39
+ /**
40
+ * Remove a custom event listener.
41
+ */
42
+ offEvent(type: string, listener: CustomEventListener) {
43
+ const listeners = this.customEventListeners.get(type) || []
44
+ this.customEventListeners.set(
45
+ type,
46
+ listeners.filter((l) => l !== listener),
47
+ )
48
+ }
49
+
50
+ onClose(listener: () => void) {
51
+ this.closeListeners.add(listener)
52
+ }
53
+
54
+ close() {
55
+ this.closeListeners.forEach((listener) => listener())
56
+ this.closeListeners.clear()
57
+ }
58
+
59
+ /**
60
+ * Add a change listener. This listener will be called whenever the state of the group changes.
61
+ */
62
+ addChangeListener(listener: Listener<TData>) {
63
+ this.onChangeListeners.add(listener)
64
+ }
65
+
66
+ /**
67
+ * Remove a change listener.
68
+ */
69
+ removeChangeListener(listener: Listener<TData>) {
70
+ this.onChangeListeners.delete(listener)
71
+ }
72
+
73
+ /**
74
+ * Get the current state of the group.
75
+ */
76
+ getState(): TData {
77
+ return this.state
78
+ }
79
+
80
+ protected setState(state: TData) {
81
+ this.state = state
82
+ this.onChangeListeners.forEach((listener) => listener(state))
83
+ }
84
+ }
package/src/stream.ts ADDED
@@ -0,0 +1,130 @@
1
+ import { v4 as uuidv4 } from 'uuid'
2
+ import { StreamGroupSubscription } from './stream-group'
3
+ import { StreamItemSubscription } from './stream-item'
4
+ import { StreamSubscription } from './stream-subscription'
5
+ import { BaseMessage } from './stream.types'
6
+
7
+ export class Stream {
8
+ private ws: WebSocket
9
+ private listeners: { [channelId: string]: Set<StreamSubscription> } = {}
10
+
11
+ constructor(private address: string) {
12
+ this.ws = this.createSocket()
13
+ }
14
+
15
+ createSocket(): WebSocket {
16
+ this.ws = new WebSocket(this.address)
17
+ this.ws.addEventListener('message', (message) => this.messageListener(message))
18
+ this.ws.addEventListener('open', () => this.onSocketOpen())
19
+ this.ws.addEventListener('close', () => this.onSocketClose())
20
+
21
+ return this.ws
22
+ }
23
+
24
+ /**
25
+ * Subscribe to an item in a stream.
26
+ *
27
+ * @argument streamName - The name of the stream to subscribe to.
28
+ * @argument groupId - The id of the group to subscribe to.
29
+ * @argument id - The id of the item to subscribe to.
30
+ */
31
+ subscribeItem<TData extends { id: string }>(
32
+ streamName: string,
33
+ groupId: string,
34
+ id: string,
35
+ ): StreamItemSubscription<TData> {
36
+ const subscriptionId = uuidv4()
37
+ const sub = { streamName, groupId, id, subscriptionId }
38
+ const subscription = new StreamItemSubscription<TData>(sub)
39
+
40
+ this.subscribe(subscription)
41
+
42
+ return subscription
43
+ }
44
+
45
+ /**
46
+ * Subscribe to a group in a stream.
47
+ *
48
+ * @argument streamName - The name of the stream to subscribe to.
49
+ * @argument groupId - The id of the group to subscribe to.
50
+ */
51
+ subscribeGroup<TData extends { id: string }>(streamName: string, groupId: string): StreamGroupSubscription<TData> {
52
+ const subscriptionId = uuidv4()
53
+ const sub = { streamName, groupId, subscriptionId }
54
+ const subscription = new StreamGroupSubscription<TData>(sub)
55
+
56
+ this.subscribe(subscription)
57
+
58
+ return subscription
59
+ }
60
+
61
+ close() {
62
+ this.listeners = {} // clean up all listeners
63
+ this.ws.removeEventListener('message', this.messageListener)
64
+ this.ws.removeEventListener('open', this.onSocketOpen)
65
+ this.ws.removeEventListener('close', this.onSocketClose)
66
+ this.ws.close()
67
+ }
68
+
69
+ private onSocketClose(): void {
70
+ // retry to connect
71
+ setTimeout(() => this.createSocket(), 2000)
72
+ }
73
+
74
+ private onSocketOpen(): void {
75
+ Object.values(this.listeners).forEach((listeners) => {
76
+ listeners.forEach((subscription) => this.join(subscription))
77
+ })
78
+ }
79
+
80
+ messageListener(event: MessageEvent<string>): void {
81
+ const message: BaseMessage = JSON.parse(event.data)
82
+ const room = this.roomName(message)
83
+
84
+ this.listeners[room]?.forEach((listener) => listener.listener(message))
85
+
86
+ if (message.id) {
87
+ const groupRoom = this.roomName({
88
+ streamName: message.streamName,
89
+ groupId: message.groupId,
90
+ })
91
+
92
+ this.listeners[groupRoom]?.forEach((listener) => listener.listener(message))
93
+ }
94
+ }
95
+
96
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
97
+ private subscribe(subscription: StreamSubscription<any, any>): void {
98
+ const room = this.roomName(subscription.sub)
99
+
100
+ if (!this.listeners[room]) {
101
+ this.listeners[room] = new Set()
102
+ }
103
+
104
+ this.listeners[room].add(subscription)
105
+ this.join(subscription)
106
+
107
+ subscription.onClose(() => {
108
+ this.listeners[room].delete(subscription)
109
+ this.leave(subscription)
110
+ })
111
+ }
112
+
113
+ private join(subscription: StreamSubscription): void {
114
+ if (this.ws.readyState === WebSocket.OPEN) {
115
+ this.ws.send(JSON.stringify({ type: 'join', data: subscription.sub }))
116
+ }
117
+ }
118
+
119
+ private leave(subscription: StreamSubscription): void {
120
+ if (this.ws.readyState === WebSocket.OPEN) {
121
+ this.ws.send(JSON.stringify({ type: 'leave', data: subscription.sub }))
122
+ }
123
+ }
124
+
125
+ private roomName(message: BaseMessage): string {
126
+ return message.id
127
+ ? `${message.streamName}:group:${message.groupId}:item:${message.id}`
128
+ : `${message.streamName}:group:${message.groupId}`
129
+ }
130
+ }
@@ -0,0 +1,18 @@
1
+ export type BaseMessage = { streamName: string; groupId: string; id?: string }
2
+ export type JoinMessage = BaseMessage & { subscriptionId: string }
3
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
4
+ export type CustomEvent = { type: string; data: any }
5
+ export type StreamEvent<TData extends { id: string }> =
6
+ | { type: 'create'; data: TData }
7
+ | { type: 'update'; data: TData }
8
+ | { type: 'delete'; data: TData }
9
+ | { type: 'event'; event: CustomEvent }
10
+ export type ItemStreamEvent<TData extends { id: string }> = StreamEvent<TData> | { type: 'sync'; data: TData }
11
+ export type GroupStreamEvent<TData extends { id: string }> = StreamEvent<TData> | { type: 'sync'; data: TData[] }
12
+ export type ItemEventMessage<TData extends { id: string }> = BaseMessage & { event: ItemStreamEvent<TData> }
13
+ export type GroupEventMessage<TData extends { id: string }> = BaseMessage & { event: GroupStreamEvent<TData> }
14
+
15
+ export type Message = { type: 'join' | 'leave'; data: JoinMessage }
16
+
17
+ export type Listener<TData> = (state: TData | null) => void
18
+ export type CustomEventListener<TData> = (event: TData) => void
package/tsconfig.json ADDED
@@ -0,0 +1,23 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2020",
4
+ "module": "ESNext",
5
+ "moduleResolution": "bundler",
6
+ "esModuleInterop": true,
7
+ "strict": true,
8
+ "skipLibCheck": true,
9
+ "forceConsistentCasingInFileNames": true,
10
+ "resolveJsonModule": true,
11
+ "allowJs": true,
12
+ "outDir": "dist",
13
+ "rootDir": ".",
14
+ "baseUrl": ".",
15
+ "declaration": true,
16
+ "lib": ["dom"]
17
+ },
18
+ "include": ["src/*.ts", "index.ts"],
19
+ "exclude": [
20
+ "node_modules",
21
+ "dist"
22
+ ]
23
+ }