@ceedcv-maya/shared-realtime-react 0.5.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.
- package/LICENSE +21 -0
- package/package.json +38 -0
- package/src/createEcho.ts +114 -0
- package/src/index.ts +11 -0
- package/src/useRealtimeNotifications.ts +67 -0
- package/tsconfig.json +14 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Maya-AQSS
|
|
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/package.json
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@ceedcv-maya/shared-realtime-react",
|
|
3
|
+
"version": "0.5.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"main": "src/index.ts",
|
|
6
|
+
"types": "src/index.ts",
|
|
7
|
+
"peerDependencies": {
|
|
8
|
+
"@tanstack/react-query": "^5.0.0",
|
|
9
|
+
"laravel-echo": "^2.0.0",
|
|
10
|
+
"pusher-js": "^8.0.0",
|
|
11
|
+
"react": "^18.0.0 || ^19.0.0"
|
|
12
|
+
},
|
|
13
|
+
"devDependencies": {
|
|
14
|
+
"@tanstack/react-query": "^5.100.0",
|
|
15
|
+
"@types/react": "^19.0.0",
|
|
16
|
+
"laravel-echo": "^2.2.0",
|
|
17
|
+
"pusher-js": "^8.4.0",
|
|
18
|
+
"react": "^19.0.0",
|
|
19
|
+
"typescript": "^5.6.0"
|
|
20
|
+
},
|
|
21
|
+
"scripts": {
|
|
22
|
+
"build": "tsc --noEmit",
|
|
23
|
+
"test": "echo \"no tests yet\" && exit 0",
|
|
24
|
+
"typecheck": "tsc --noEmit",
|
|
25
|
+
"lint": "echo \"no linter configured\""
|
|
26
|
+
},
|
|
27
|
+
"license": "MIT",
|
|
28
|
+
"repository": {
|
|
29
|
+
"type": "git",
|
|
30
|
+
"url": "git+https://github.com/Maya-AQSS/maya_platform.git",
|
|
31
|
+
"directory": "packages/js/shared-realtime-react"
|
|
32
|
+
},
|
|
33
|
+
"publishConfig": {
|
|
34
|
+
"access": "public"
|
|
35
|
+
},
|
|
36
|
+
"description": "Reverb/Echo realtime client for the Maya ecosystem: createEcho() factory + useRealtimeNotifications hook.",
|
|
37
|
+
"sideEffects": false
|
|
38
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import Echo from 'laravel-echo';
|
|
2
|
+
import Pusher from 'pusher-js';
|
|
3
|
+
|
|
4
|
+
declare global {
|
|
5
|
+
interface Window {
|
|
6
|
+
Pusher: typeof Pusher;
|
|
7
|
+
Echo: Echo<'reverb'> | undefined;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface ReverbBootstrapConfig {
|
|
12
|
+
/** Reverb app key — VITE_REVERB_APP_KEY. Required. */
|
|
13
|
+
appKey: string;
|
|
14
|
+
/** Reverb host the browser connects to (Traefik-fronted hostname). */
|
|
15
|
+
host: string;
|
|
16
|
+
/** Public TLS port — typically 443 in production, 8080 in plain dev. */
|
|
17
|
+
port: number;
|
|
18
|
+
/** 'http' falls back to ws://, 'https' to wss://. */
|
|
19
|
+
scheme: 'http' | 'https';
|
|
20
|
+
/** Absolute URL to POST /broadcasting/auth at — must include /api/v1 prefix. */
|
|
21
|
+
authEndpoint: string;
|
|
22
|
+
/**
|
|
23
|
+
* Resolver for the bearer JWT sent to authEndpoint. Called per authorize
|
|
24
|
+
* request so the client always sends a fresh token (handles silent refresh).
|
|
25
|
+
* Return null to deny the channel without making the request.
|
|
26
|
+
*/
|
|
27
|
+
getBearerToken: () => string | null | undefined;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
let instance: Echo<'reverb'> | null = null;
|
|
31
|
+
let pusherInstalled = false;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Build (or return) the singleton Echo client wired to a Reverb server.
|
|
35
|
+
*
|
|
36
|
+
* Singleton on purpose: every component that needs realtime in the same app
|
|
37
|
+
* shares the same WebSocket. Call disconnectEcho() on full logout/teardown
|
|
38
|
+
* if you want to drop the connection.
|
|
39
|
+
*
|
|
40
|
+
* Channel authorization uses the bearer token from getBearerToken() because
|
|
41
|
+
* the Maya ecosystem authenticates against Keycloak JWT (Authorization
|
|
42
|
+
* header) and the default Echo authorizer assumes a session cookie.
|
|
43
|
+
*/
|
|
44
|
+
export function createEcho(config: ReverbBootstrapConfig): Echo<'reverb'> {
|
|
45
|
+
if (instance) return instance;
|
|
46
|
+
|
|
47
|
+
if (!config.appKey?.trim()) {
|
|
48
|
+
throw new Error('createEcho: appKey is required to bootstrap the Reverb client');
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if (!pusherInstalled) {
|
|
52
|
+
window.Pusher = Pusher;
|
|
53
|
+
pusherInstalled = true;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
instance = new Echo({
|
|
57
|
+
broadcaster: 'reverb',
|
|
58
|
+
key: config.appKey,
|
|
59
|
+
wsHost: config.host,
|
|
60
|
+
wsPort: config.port,
|
|
61
|
+
wssPort: config.port,
|
|
62
|
+
forceTLS: config.scheme === 'https',
|
|
63
|
+
enabledTransports: ['ws', 'wss'],
|
|
64
|
+
authEndpoint: config.authEndpoint,
|
|
65
|
+
auth: {
|
|
66
|
+
headers: {
|
|
67
|
+
Accept: 'application/json',
|
|
68
|
+
},
|
|
69
|
+
},
|
|
70
|
+
authorizer: (channel) => ({
|
|
71
|
+
authorize: (socketId, callback) => {
|
|
72
|
+
const token = config.getBearerToken();
|
|
73
|
+
if (!token) {
|
|
74
|
+
callback(new Error('no_bearer_token'), null);
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
fetch(config.authEndpoint, {
|
|
78
|
+
method: 'POST',
|
|
79
|
+
headers: {
|
|
80
|
+
Accept: 'application/json',
|
|
81
|
+
'Content-Type': 'application/json',
|
|
82
|
+
Authorization: `Bearer ${token}`,
|
|
83
|
+
},
|
|
84
|
+
body: JSON.stringify({ socket_id: socketId, channel_name: channel.name }),
|
|
85
|
+
})
|
|
86
|
+
.then(async (response) => {
|
|
87
|
+
if (!response.ok) {
|
|
88
|
+
callback(new Error(`broadcasting_auth_${response.status}`), null);
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
callback(null, await response.json());
|
|
92
|
+
})
|
|
93
|
+
.catch((err: unknown) => {
|
|
94
|
+
callback(err instanceof Error ? err : new Error('broadcasting_auth_failed'), null);
|
|
95
|
+
});
|
|
96
|
+
},
|
|
97
|
+
}),
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
window.Echo = instance;
|
|
101
|
+
return instance;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function getEchoInstance(): Echo<'reverb'> | null {
|
|
105
|
+
return instance;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function disconnectEcho(): void {
|
|
109
|
+
if (instance) {
|
|
110
|
+
instance.disconnect();
|
|
111
|
+
instance = null;
|
|
112
|
+
window.Echo = undefined;
|
|
113
|
+
}
|
|
114
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export {
|
|
2
|
+
createEcho,
|
|
3
|
+
disconnectEcho,
|
|
4
|
+
getEchoInstance,
|
|
5
|
+
type ReverbBootstrapConfig,
|
|
6
|
+
} from './createEcho';
|
|
7
|
+
export {
|
|
8
|
+
useRealtimeNotifications,
|
|
9
|
+
type RealtimeNotificationPayload,
|
|
10
|
+
type UseRealtimeNotificationsOptions,
|
|
11
|
+
} from './useRealtimeNotifications';
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { useEffect } from 'react';
|
|
2
|
+
import { useQueryClient } from '@tanstack/react-query';
|
|
3
|
+
import { getEchoInstance } from './createEcho';
|
|
4
|
+
|
|
5
|
+
export interface RealtimeNotificationPayload {
|
|
6
|
+
id?: number;
|
|
7
|
+
app?: string;
|
|
8
|
+
type?: string;
|
|
9
|
+
title?: string;
|
|
10
|
+
body?: string;
|
|
11
|
+
metadata?: Record<string, unknown>;
|
|
12
|
+
is_critical?: boolean;
|
|
13
|
+
scope?: 'user' | 'dashboard' | 'both';
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface UseRealtimeNotificationsOptions {
|
|
17
|
+
/** Keycloak UUID of the listening user. When null/undefined the hook is a no-op. */
|
|
18
|
+
userId: string | null | undefined;
|
|
19
|
+
/** TanStack Query keys to invalidate when a notification arrives. */
|
|
20
|
+
queryKeys?: ReadonlyArray<readonly unknown[]>;
|
|
21
|
+
/** Optional side-effect callback (toast, sound, etc.). */
|
|
22
|
+
onNotification?: (payload: RealtimeNotificationPayload) => void;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const DEFAULT_QUERY_KEYS: ReadonlyArray<readonly unknown[]> = [['notifications']];
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Subscribe the current user to their private notifications channel.
|
|
29
|
+
*
|
|
30
|
+
* Listens for the canonical 'notification.created' broadcast and invalidates
|
|
31
|
+
* the configured TanStack Query keys so paginated lists / badges refetch
|
|
32
|
+
* immediately. The dot prefix on .listen() tells Echo to match the raw
|
|
33
|
+
* broadcast name (set by broadcastAs() in the backend event), not the PHP
|
|
34
|
+
* class name.
|
|
35
|
+
*
|
|
36
|
+
* Requires createEcho() to have been called at app boot — usually in the
|
|
37
|
+
* top-level layout component once the user is authenticated.
|
|
38
|
+
*/
|
|
39
|
+
export function useRealtimeNotifications({
|
|
40
|
+
userId,
|
|
41
|
+
queryKeys = DEFAULT_QUERY_KEYS,
|
|
42
|
+
onNotification,
|
|
43
|
+
}: UseRealtimeNotificationsOptions): void {
|
|
44
|
+
const queryClient = useQueryClient();
|
|
45
|
+
|
|
46
|
+
useEffect(() => {
|
|
47
|
+
if (!userId) return;
|
|
48
|
+
const echo = getEchoInstance();
|
|
49
|
+
if (!echo) return;
|
|
50
|
+
|
|
51
|
+
const channelName = `notifications.${userId}`;
|
|
52
|
+
const channel = echo.private(channelName);
|
|
53
|
+
const handler = (payload: RealtimeNotificationPayload): void => {
|
|
54
|
+
for (const queryKey of queryKeys) {
|
|
55
|
+
queryClient.invalidateQueries({ queryKey: [...queryKey] });
|
|
56
|
+
}
|
|
57
|
+
onNotification?.(payload);
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
channel.listen('.notification.created', handler);
|
|
61
|
+
|
|
62
|
+
return () => {
|
|
63
|
+
channel.stopListening('.notification.created');
|
|
64
|
+
echo.leave(channelName);
|
|
65
|
+
};
|
|
66
|
+
}, [userId, queryClient, queryKeys, onNotification]);
|
|
67
|
+
}
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "ES2023",
|
|
4
|
+
"lib": ["ES2023", "DOM", "DOM.Iterable"],
|
|
5
|
+
"module": "ESNext",
|
|
6
|
+
"moduleResolution": "bundler",
|
|
7
|
+
"jsx": "react-jsx",
|
|
8
|
+
"strict": true,
|
|
9
|
+
"skipLibCheck": true,
|
|
10
|
+
"verbatimModuleSyntax": true,
|
|
11
|
+
"noEmit": true
|
|
12
|
+
},
|
|
13
|
+
"include": ["src"]
|
|
14
|
+
}
|