@selfhelp/shared 1.3.0 → 1.3.2
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/CHANGELOG.md +349 -341
- package/LICENSE +381 -381
- package/README.md +57 -57
- package/package.json +102 -102
- package/src/api/__tests__/endpoints.test.ts +45 -45
- package/src/api/index.ts +5 -5
- package/src/assets/__tests__/resolveAssetUrl.test.ts +61 -61
- package/src/assets/index.ts +5 -5
- package/src/assets/resolveAssetUrl.ts +44 -44
- package/src/cms-classes/__tests__/classify.test.ts +63 -63
- package/src/cms-classes/allow-list.ts +158 -158
- package/src/cms-classes/classify.ts +90 -90
- package/src/cms-classes/index.ts +7 -7
- package/src/cms-classes/remap.ts +44 -44
- package/src/condition/__tests__/evaluate.test.ts +54 -54
- package/src/condition/evaluate.ts +121 -121
- package/src/condition/index.ts +5 -5
- package/src/index.ts +25 -25
- package/src/interpolation/__tests__/replaceCalcedValues.test.ts +41 -41
- package/src/interpolation/index.ts +5 -5
- package/src/interpolation/replaceCalcedValues.ts +27 -27
- package/src/plugin-sdk/define.ts +89 -89
- package/src/plugin-sdk/index.ts +103 -103
- package/src/plugin-sdk/lock.ts +124 -124
- package/src/plugin-sdk/manifest.ts +307 -307
- package/src/plugin-sdk/realtime.ts +277 -277
- package/src/plugin-sdk/registry.ts +105 -105
- package/src/plugin-sdk/runtime-shim.ts +140 -140
- package/src/plugin-sdk/types.ts +315 -315
- package/src/plugin-sdk/version.ts +209 -209
- package/src/registry/__tests__/registry.test.ts +135 -135
- package/src/registry/index.ts +94 -94
- package/src/registry/styles.registry.ts +295 -295
- package/src/testing/__tests__/testing-kit.test.ts +228 -228
- package/src/testing/index.ts +483 -483
- package/src/theme/index.ts +6 -6
- package/src/theme/tailwind.ts +73 -73
- package/src/theme/tokens.ts +177 -177
- package/src/types/api/envelope.ts +34 -34
- package/src/types/api/forms.ts +76 -76
- package/src/types/api/index.ts +9 -9
- package/src/types/api/language.ts +12 -12
- package/src/types/api/page.ts +9 -9
- package/src/types/index.ts +17 -17
- package/src/types/mantine/common.ts +142 -142
- package/src/types/pages.ts +107 -107
- package/src/types/styles/auth.ts +184 -184
- package/src/types/styles/base.ts +72 -72
- package/src/types/styles/composite.ts +131 -131
- package/src/types/styles/forms.ts +439 -439
- package/src/types/styles/interactive.ts +165 -165
- package/src/types/styles/layout.ts +184 -184
- package/src/types/styles/media.ts +68 -68
- package/src/types/styles/typography.ts +118 -118
- package/src/types/styles/unknown.ts +220 -220
- package/src/utils/__tests__/transformPageData.test.ts +69 -69
- package/src/utils/spacing.ts +64 -64
- package/src/utils/transformPageData.ts +99 -99
|
@@ -1,277 +1,277 @@
|
|
|
1
|
-
/*
|
|
2
|
-
SPDX-FileCopyrightText: 2026 Humdek, University of Bern
|
|
3
|
-
SPDX-License-Identifier: MPL-2.0
|
|
4
|
-
*/
|
|
5
|
-
/**
|
|
6
|
-
* `usePluginRealtime` — universal React hook for plugin Mercure topic
|
|
7
|
-
* subscription.
|
|
8
|
-
*
|
|
9
|
-
* Implements the contract laid out in the plan section 10 "Realtime
|
|
10
|
-
* infrastructure & no-polling policy":
|
|
11
|
-
*
|
|
12
|
-
* const { data, isOnline, lastEventAt, error } = usePluginRealtime<TPayload>({
|
|
13
|
-
* pluginId: 'sh2-shp-survey-js',
|
|
14
|
-
* topic: 'surveys/{surveyId}/responses',
|
|
15
|
-
* topicParams: { surveyId: 42 },
|
|
16
|
-
* });
|
|
17
|
-
*
|
|
18
|
-
* The hook:
|
|
19
|
-
*
|
|
20
|
-
* - opens a same-origin `EventSource` against
|
|
21
|
-
* `/api/plugins/events?pluginId=…&topic=…` (the host BFF route),
|
|
22
|
-
* - listens for messages on the requested topic event-name,
|
|
23
|
-
* - exposes the latest payload + connection state,
|
|
24
|
-
* - reconnects with exponential backoff on transient errors,
|
|
25
|
-
* - is a no-op in environments without `EventSource` (server / RN).
|
|
26
|
-
*
|
|
27
|
-
* Mobile apps must inject their own `react-native-sse`-backed
|
|
28
|
-
* implementation through the optional `transportFactory` argument;
|
|
29
|
-
* this keeps the shared SDK free of React Native imports while still
|
|
30
|
-
* letting the same plugin code re-use the same hook signature on web
|
|
31
|
-
* and on device. The mobile package documents the wrapper.
|
|
32
|
-
*
|
|
33
|
-
* IMPORTANT: this hook never polls. If `EventSource` cannot connect, it
|
|
34
|
-
* surfaces `isOnline = false` and the consumer is expected to show an
|
|
35
|
-
* "offline" banner — not to set up a `setInterval` fallback.
|
|
36
|
-
*/
|
|
37
|
-
|
|
38
|
-
import { useEffect, useRef, useState } from 'react';
|
|
39
|
-
|
|
40
|
-
/**
|
|
41
|
-
* Subset of the WHATWG `EventSource` API the hook actually relies on.
|
|
42
|
-
* Declared inline so the SDK does not pull DOM types into projects that
|
|
43
|
-
* disable `dom` (e.g. some Expo TypeScript setups).
|
|
44
|
-
*/
|
|
45
|
-
export interface IRealtimeTransport {
|
|
46
|
-
addEventListener(type: 'open' | 'error' | string, listener: (evt: unknown) => void): void;
|
|
47
|
-
removeEventListener(type: 'open' | 'error' | string, listener: (evt: unknown) => void): void;
|
|
48
|
-
close(): void;
|
|
49
|
-
readyState: number;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
export type TRealtimeTransportFactory = (url: string) => IRealtimeTransport;
|
|
53
|
-
|
|
54
|
-
export interface IUsePluginRealtimeOptions<TPayload = unknown> {
|
|
55
|
-
/** Plugin id (`plugin.json#id`). */
|
|
56
|
-
pluginId: string;
|
|
57
|
-
/** Topic key as declared in the manifest (e.g. `surveys/{surveyId}/responses`). */
|
|
58
|
-
topic: string;
|
|
59
|
-
/** Values that fill the `{placeholders}` in `topic`. */
|
|
60
|
-
topicParams?: Record<string, string | number>;
|
|
61
|
-
/** Disable subscription without unmounting the consumer. */
|
|
62
|
-
enabled?: boolean;
|
|
63
|
-
/**
|
|
64
|
-
* Override the SSE endpoint. Defaults to `/api/plugins/events`. The
|
|
65
|
-
* host BFF proxies it through to Symfony's per-plugin Mercure
|
|
66
|
-
* bootstrap so the subscriber JWT never reaches the browser.
|
|
67
|
-
*/
|
|
68
|
-
endpoint?: string;
|
|
69
|
-
/**
|
|
70
|
-
* Optional transport factory. Used by the mobile package to plug in
|
|
71
|
-
* `react-native-sse` (or any other SSE-compatible client) without
|
|
72
|
-
* pulling RN imports into the shared SDK.
|
|
73
|
-
*/
|
|
74
|
-
transportFactory?: TRealtimeTransportFactory;
|
|
75
|
-
/** Parser for the event payload. Defaults to `JSON.parse`. */
|
|
76
|
-
parse?: (raw: string) => TPayload;
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
export interface IUsePluginRealtimeResult<TPayload = unknown> {
|
|
80
|
-
/** Latest payload emitted on the topic, or `null` before the first event. */
|
|
81
|
-
data: TPayload | null;
|
|
82
|
-
/** `true` once the SSE handshake has succeeded for the current subscription. */
|
|
83
|
-
isOnline: boolean;
|
|
84
|
-
/** Wall-clock time of the last successful event, or `null`. */
|
|
85
|
-
lastEventAt: Date | null;
|
|
86
|
-
/** Most recent transport-level error, or `null` when healthy. */
|
|
87
|
-
error: Error | null;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
const DEFAULT_ENDPOINT = '/api/plugins/events';
|
|
91
|
-
const MAX_RECONNECT_DELAY_MS = 30_000;
|
|
92
|
-
const INITIAL_RECONNECT_DELAY_MS = 1_000;
|
|
93
|
-
|
|
94
|
-
/**
|
|
95
|
-
* Replace `{placeholders}` in the topic key with the provided params and
|
|
96
|
-
* URL-encode every value. Throws if any placeholder is unresolved so
|
|
97
|
-
* misuse fails loudly rather than subscribing to a wildcard topic.
|
|
98
|
-
*/
|
|
99
|
-
function expandTopic(topic: string, params: Record<string, string | number>): string {
|
|
100
|
-
return topic.replace(/\{([^}]+)\}/g, (_match, name: string) => {
|
|
101
|
-
const value = params[name];
|
|
102
|
-
if (value === undefined) {
|
|
103
|
-
throw new Error(
|
|
104
|
-
`usePluginRealtime: topic "${topic}" references {${name}} but topicParams.${name} was not provided.`,
|
|
105
|
-
);
|
|
106
|
-
}
|
|
107
|
-
return encodeURIComponent(String(value));
|
|
108
|
-
});
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
function buildSseUrl(
|
|
112
|
-
endpoint: string,
|
|
113
|
-
pluginId: string,
|
|
114
|
-
expandedTopic: string,
|
|
115
|
-
): string {
|
|
116
|
-
const params = new URLSearchParams({
|
|
117
|
-
pluginId,
|
|
118
|
-
topic: expandedTopic,
|
|
119
|
-
});
|
|
120
|
-
const separator = endpoint.includes('?') ? '&' : '?';
|
|
121
|
-
return `${endpoint}${separator}${params.toString()}`;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
function isEventSourceAvailable(): boolean {
|
|
125
|
-
return typeof globalThis !== 'undefined' && typeof (globalThis as Record<string, unknown>).EventSource !== 'undefined';
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
function defaultTransportFactory(url: string): IRealtimeTransport {
|
|
129
|
-
const Ctor = (globalThis as Record<string, unknown>).EventSource as new (url: string) => IRealtimeTransport;
|
|
130
|
-
return new Ctor(url);
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
/**
|
|
134
|
-
* Subscribe a React/React-Native component to one Mercure plugin topic
|
|
135
|
-
* and re-render whenever a new payload arrives.
|
|
136
|
-
*
|
|
137
|
-
* Returns `{ data, isOnline, lastEventAt, error }`. Always cleans up on
|
|
138
|
-
* unmount and on prop change.
|
|
139
|
-
*/
|
|
140
|
-
export function usePluginRealtime<TPayload = unknown>(
|
|
141
|
-
options: IUsePluginRealtimeOptions<TPayload>,
|
|
142
|
-
): IUsePluginRealtimeResult<TPayload> {
|
|
143
|
-
const {
|
|
144
|
-
pluginId,
|
|
145
|
-
topic,
|
|
146
|
-
topicParams = {},
|
|
147
|
-
enabled = true,
|
|
148
|
-
endpoint = DEFAULT_ENDPOINT,
|
|
149
|
-
transportFactory,
|
|
150
|
-
parse,
|
|
151
|
-
} = options;
|
|
152
|
-
|
|
153
|
-
const [data, setData] = useState<TPayload | null>(null);
|
|
154
|
-
const [isOnline, setIsOnline] = useState<boolean>(false);
|
|
155
|
-
const [lastEventAt, setLastEventAt] = useState<Date | null>(null);
|
|
156
|
-
const [error, setError] = useState<Error | null>(null);
|
|
157
|
-
|
|
158
|
-
// Stable refs so the effect closures always read the latest callback /
|
|
159
|
-
// parser without forcing a reconnection on every render.
|
|
160
|
-
const parseRef = useRef(parse);
|
|
161
|
-
parseRef.current = parse;
|
|
162
|
-
|
|
163
|
-
// Stringify topicParams once so React effect dependency comparison is
|
|
164
|
-
// deterministic regardless of object identity churn in the caller.
|
|
165
|
-
const topicParamsKey = JSON.stringify(topicParams);
|
|
166
|
-
|
|
167
|
-
useEffect(() => {
|
|
168
|
-
if (!enabled) {
|
|
169
|
-
setIsOnline(false);
|
|
170
|
-
return;
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
const factory = transportFactory ?? (isEventSourceAvailable() ? defaultTransportFactory : null);
|
|
174
|
-
if (factory === null) {
|
|
175
|
-
// No transport available (e.g. SSR or RN without injected
|
|
176
|
-
// `react-native-sse`). Stay quiet — the plan forbids polling
|
|
177
|
-
// here; the consumer must render an offline banner instead.
|
|
178
|
-
setIsOnline(false);
|
|
179
|
-
return;
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
let cancelled = false;
|
|
183
|
-
let transport: IRealtimeTransport | null = null;
|
|
184
|
-
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
|
185
|
-
let reconnectDelay = INITIAL_RECONNECT_DELAY_MS;
|
|
186
|
-
|
|
187
|
-
let expandedTopic: string;
|
|
188
|
-
try {
|
|
189
|
-
expandedTopic = expandTopic(topic, JSON.parse(topicParamsKey) as Record<string, string | number>);
|
|
190
|
-
} catch (err) {
|
|
191
|
-
setError(err instanceof Error ? err : new Error(String(err)));
|
|
192
|
-
setIsOnline(false);
|
|
193
|
-
return;
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
const eventName = `plugin/${pluginId}/${expandedTopic}`;
|
|
197
|
-
const url = buildSseUrl(endpoint, pluginId, expandedTopic);
|
|
198
|
-
|
|
199
|
-
const onOpen = (): void => {
|
|
200
|
-
if (cancelled) return;
|
|
201
|
-
reconnectDelay = INITIAL_RECONNECT_DELAY_MS;
|
|
202
|
-
setIsOnline(true);
|
|
203
|
-
setError(null);
|
|
204
|
-
};
|
|
205
|
-
|
|
206
|
-
const onEvent = (evt: unknown): void => {
|
|
207
|
-
if (cancelled) return;
|
|
208
|
-
const raw = (evt as { data?: string }).data;
|
|
209
|
-
if (typeof raw !== 'string') return;
|
|
210
|
-
try {
|
|
211
|
-
const payload = parseRef.current
|
|
212
|
-
? parseRef.current(raw)
|
|
213
|
-
: (JSON.parse(raw) as TPayload);
|
|
214
|
-
setData(payload);
|
|
215
|
-
setLastEventAt(new Date());
|
|
216
|
-
} catch (parseErr) {
|
|
217
|
-
setError(parseErr instanceof Error ? parseErr : new Error(String(parseErr)));
|
|
218
|
-
}
|
|
219
|
-
};
|
|
220
|
-
|
|
221
|
-
const onError = (evt: unknown): void => {
|
|
222
|
-
if (cancelled || !transport) return;
|
|
223
|
-
setIsOnline(false);
|
|
224
|
-
setError(evt instanceof Error ? evt : new Error('Plugin realtime transport error'));
|
|
225
|
-
// readyState === 2 (CLOSED) means the browser will NOT
|
|
226
|
-
// auto-reconnect (4xx/network); restart manually with backoff.
|
|
227
|
-
if (transport.readyState === 2) {
|
|
228
|
-
try {
|
|
229
|
-
transport.close();
|
|
230
|
-
} catch {
|
|
231
|
-
// ignore — already closed.
|
|
232
|
-
}
|
|
233
|
-
transport = null;
|
|
234
|
-
reconnectTimer = setTimeout(connect, reconnectDelay);
|
|
235
|
-
reconnectDelay = Math.min(reconnectDelay * 2, MAX_RECONNECT_DELAY_MS);
|
|
236
|
-
}
|
|
237
|
-
};
|
|
238
|
-
|
|
239
|
-
const connect = (): void => {
|
|
240
|
-
if (cancelled) return;
|
|
241
|
-
try {
|
|
242
|
-
transport = factory(url);
|
|
243
|
-
} catch (createErr) {
|
|
244
|
-
setError(createErr instanceof Error ? createErr : new Error(String(createErr)));
|
|
245
|
-
setIsOnline(false);
|
|
246
|
-
return;
|
|
247
|
-
}
|
|
248
|
-
transport.addEventListener('open', onOpen);
|
|
249
|
-
transport.addEventListener(eventName, onEvent);
|
|
250
|
-
transport.addEventListener('message', onEvent);
|
|
251
|
-
transport.addEventListener('error', onError);
|
|
252
|
-
};
|
|
253
|
-
|
|
254
|
-
connect();
|
|
255
|
-
|
|
256
|
-
return (): void => {
|
|
257
|
-
cancelled = true;
|
|
258
|
-
if (reconnectTimer !== null) {
|
|
259
|
-
clearTimeout(reconnectTimer);
|
|
260
|
-
}
|
|
261
|
-
if (transport) {
|
|
262
|
-
try {
|
|
263
|
-
transport.removeEventListener('open', onOpen);
|
|
264
|
-
transport.removeEventListener(eventName, onEvent);
|
|
265
|
-
transport.removeEventListener('message', onEvent);
|
|
266
|
-
transport.removeEventListener('error', onError);
|
|
267
|
-
transport.close();
|
|
268
|
-
} catch {
|
|
269
|
-
// ignore — best-effort cleanup.
|
|
270
|
-
}
|
|
271
|
-
transport = null;
|
|
272
|
-
}
|
|
273
|
-
};
|
|
274
|
-
}, [enabled, endpoint, pluginId, topic, topicParamsKey, transportFactory]);
|
|
275
|
-
|
|
276
|
-
return { data, isOnline, lastEventAt, error };
|
|
277
|
-
}
|
|
1
|
+
/*
|
|
2
|
+
SPDX-FileCopyrightText: 2026 Humdek, University of Bern
|
|
3
|
+
SPDX-License-Identifier: MPL-2.0
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* `usePluginRealtime` — universal React hook for plugin Mercure topic
|
|
7
|
+
* subscription.
|
|
8
|
+
*
|
|
9
|
+
* Implements the contract laid out in the plan section 10 "Realtime
|
|
10
|
+
* infrastructure & no-polling policy":
|
|
11
|
+
*
|
|
12
|
+
* const { data, isOnline, lastEventAt, error } = usePluginRealtime<TPayload>({
|
|
13
|
+
* pluginId: 'sh2-shp-survey-js',
|
|
14
|
+
* topic: 'surveys/{surveyId}/responses',
|
|
15
|
+
* topicParams: { surveyId: 42 },
|
|
16
|
+
* });
|
|
17
|
+
*
|
|
18
|
+
* The hook:
|
|
19
|
+
*
|
|
20
|
+
* - opens a same-origin `EventSource` against
|
|
21
|
+
* `/api/plugins/events?pluginId=…&topic=…` (the host BFF route),
|
|
22
|
+
* - listens for messages on the requested topic event-name,
|
|
23
|
+
* - exposes the latest payload + connection state,
|
|
24
|
+
* - reconnects with exponential backoff on transient errors,
|
|
25
|
+
* - is a no-op in environments without `EventSource` (server / RN).
|
|
26
|
+
*
|
|
27
|
+
* Mobile apps must inject their own `react-native-sse`-backed
|
|
28
|
+
* implementation through the optional `transportFactory` argument;
|
|
29
|
+
* this keeps the shared SDK free of React Native imports while still
|
|
30
|
+
* letting the same plugin code re-use the same hook signature on web
|
|
31
|
+
* and on device. The mobile package documents the wrapper.
|
|
32
|
+
*
|
|
33
|
+
* IMPORTANT: this hook never polls. If `EventSource` cannot connect, it
|
|
34
|
+
* surfaces `isOnline = false` and the consumer is expected to show an
|
|
35
|
+
* "offline" banner — not to set up a `setInterval` fallback.
|
|
36
|
+
*/
|
|
37
|
+
|
|
38
|
+
import { useEffect, useRef, useState } from 'react';
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Subset of the WHATWG `EventSource` API the hook actually relies on.
|
|
42
|
+
* Declared inline so the SDK does not pull DOM types into projects that
|
|
43
|
+
* disable `dom` (e.g. some Expo TypeScript setups).
|
|
44
|
+
*/
|
|
45
|
+
export interface IRealtimeTransport {
|
|
46
|
+
addEventListener(type: 'open' | 'error' | string, listener: (evt: unknown) => void): void;
|
|
47
|
+
removeEventListener(type: 'open' | 'error' | string, listener: (evt: unknown) => void): void;
|
|
48
|
+
close(): void;
|
|
49
|
+
readyState: number;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export type TRealtimeTransportFactory = (url: string) => IRealtimeTransport;
|
|
53
|
+
|
|
54
|
+
export interface IUsePluginRealtimeOptions<TPayload = unknown> {
|
|
55
|
+
/** Plugin id (`plugin.json#id`). */
|
|
56
|
+
pluginId: string;
|
|
57
|
+
/** Topic key as declared in the manifest (e.g. `surveys/{surveyId}/responses`). */
|
|
58
|
+
topic: string;
|
|
59
|
+
/** Values that fill the `{placeholders}` in `topic`. */
|
|
60
|
+
topicParams?: Record<string, string | number>;
|
|
61
|
+
/** Disable subscription without unmounting the consumer. */
|
|
62
|
+
enabled?: boolean;
|
|
63
|
+
/**
|
|
64
|
+
* Override the SSE endpoint. Defaults to `/api/plugins/events`. The
|
|
65
|
+
* host BFF proxies it through to Symfony's per-plugin Mercure
|
|
66
|
+
* bootstrap so the subscriber JWT never reaches the browser.
|
|
67
|
+
*/
|
|
68
|
+
endpoint?: string;
|
|
69
|
+
/**
|
|
70
|
+
* Optional transport factory. Used by the mobile package to plug in
|
|
71
|
+
* `react-native-sse` (or any other SSE-compatible client) without
|
|
72
|
+
* pulling RN imports into the shared SDK.
|
|
73
|
+
*/
|
|
74
|
+
transportFactory?: TRealtimeTransportFactory;
|
|
75
|
+
/** Parser for the event payload. Defaults to `JSON.parse`. */
|
|
76
|
+
parse?: (raw: string) => TPayload;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export interface IUsePluginRealtimeResult<TPayload = unknown> {
|
|
80
|
+
/** Latest payload emitted on the topic, or `null` before the first event. */
|
|
81
|
+
data: TPayload | null;
|
|
82
|
+
/** `true` once the SSE handshake has succeeded for the current subscription. */
|
|
83
|
+
isOnline: boolean;
|
|
84
|
+
/** Wall-clock time of the last successful event, or `null`. */
|
|
85
|
+
lastEventAt: Date | null;
|
|
86
|
+
/** Most recent transport-level error, or `null` when healthy. */
|
|
87
|
+
error: Error | null;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const DEFAULT_ENDPOINT = '/api/plugins/events';
|
|
91
|
+
const MAX_RECONNECT_DELAY_MS = 30_000;
|
|
92
|
+
const INITIAL_RECONNECT_DELAY_MS = 1_000;
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Replace `{placeholders}` in the topic key with the provided params and
|
|
96
|
+
* URL-encode every value. Throws if any placeholder is unresolved so
|
|
97
|
+
* misuse fails loudly rather than subscribing to a wildcard topic.
|
|
98
|
+
*/
|
|
99
|
+
function expandTopic(topic: string, params: Record<string, string | number>): string {
|
|
100
|
+
return topic.replace(/\{([^}]+)\}/g, (_match, name: string) => {
|
|
101
|
+
const value = params[name];
|
|
102
|
+
if (value === undefined) {
|
|
103
|
+
throw new Error(
|
|
104
|
+
`usePluginRealtime: topic "${topic}" references {${name}} but topicParams.${name} was not provided.`,
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
return encodeURIComponent(String(value));
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function buildSseUrl(
|
|
112
|
+
endpoint: string,
|
|
113
|
+
pluginId: string,
|
|
114
|
+
expandedTopic: string,
|
|
115
|
+
): string {
|
|
116
|
+
const params = new URLSearchParams({
|
|
117
|
+
pluginId,
|
|
118
|
+
topic: expandedTopic,
|
|
119
|
+
});
|
|
120
|
+
const separator = endpoint.includes('?') ? '&' : '?';
|
|
121
|
+
return `${endpoint}${separator}${params.toString()}`;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function isEventSourceAvailable(): boolean {
|
|
125
|
+
return typeof globalThis !== 'undefined' && typeof (globalThis as Record<string, unknown>).EventSource !== 'undefined';
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function defaultTransportFactory(url: string): IRealtimeTransport {
|
|
129
|
+
const Ctor = (globalThis as Record<string, unknown>).EventSource as new (url: string) => IRealtimeTransport;
|
|
130
|
+
return new Ctor(url);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Subscribe a React/React-Native component to one Mercure plugin topic
|
|
135
|
+
* and re-render whenever a new payload arrives.
|
|
136
|
+
*
|
|
137
|
+
* Returns `{ data, isOnline, lastEventAt, error }`. Always cleans up on
|
|
138
|
+
* unmount and on prop change.
|
|
139
|
+
*/
|
|
140
|
+
export function usePluginRealtime<TPayload = unknown>(
|
|
141
|
+
options: IUsePluginRealtimeOptions<TPayload>,
|
|
142
|
+
): IUsePluginRealtimeResult<TPayload> {
|
|
143
|
+
const {
|
|
144
|
+
pluginId,
|
|
145
|
+
topic,
|
|
146
|
+
topicParams = {},
|
|
147
|
+
enabled = true,
|
|
148
|
+
endpoint = DEFAULT_ENDPOINT,
|
|
149
|
+
transportFactory,
|
|
150
|
+
parse,
|
|
151
|
+
} = options;
|
|
152
|
+
|
|
153
|
+
const [data, setData] = useState<TPayload | null>(null);
|
|
154
|
+
const [isOnline, setIsOnline] = useState<boolean>(false);
|
|
155
|
+
const [lastEventAt, setLastEventAt] = useState<Date | null>(null);
|
|
156
|
+
const [error, setError] = useState<Error | null>(null);
|
|
157
|
+
|
|
158
|
+
// Stable refs so the effect closures always read the latest callback /
|
|
159
|
+
// parser without forcing a reconnection on every render.
|
|
160
|
+
const parseRef = useRef(parse);
|
|
161
|
+
parseRef.current = parse;
|
|
162
|
+
|
|
163
|
+
// Stringify topicParams once so React effect dependency comparison is
|
|
164
|
+
// deterministic regardless of object identity churn in the caller.
|
|
165
|
+
const topicParamsKey = JSON.stringify(topicParams);
|
|
166
|
+
|
|
167
|
+
useEffect(() => {
|
|
168
|
+
if (!enabled) {
|
|
169
|
+
setIsOnline(false);
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const factory = transportFactory ?? (isEventSourceAvailable() ? defaultTransportFactory : null);
|
|
174
|
+
if (factory === null) {
|
|
175
|
+
// No transport available (e.g. SSR or RN without injected
|
|
176
|
+
// `react-native-sse`). Stay quiet — the plan forbids polling
|
|
177
|
+
// here; the consumer must render an offline banner instead.
|
|
178
|
+
setIsOnline(false);
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
let cancelled = false;
|
|
183
|
+
let transport: IRealtimeTransport | null = null;
|
|
184
|
+
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
|
185
|
+
let reconnectDelay = INITIAL_RECONNECT_DELAY_MS;
|
|
186
|
+
|
|
187
|
+
let expandedTopic: string;
|
|
188
|
+
try {
|
|
189
|
+
expandedTopic = expandTopic(topic, JSON.parse(topicParamsKey) as Record<string, string | number>);
|
|
190
|
+
} catch (err) {
|
|
191
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
192
|
+
setIsOnline(false);
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const eventName = `plugin/${pluginId}/${expandedTopic}`;
|
|
197
|
+
const url = buildSseUrl(endpoint, pluginId, expandedTopic);
|
|
198
|
+
|
|
199
|
+
const onOpen = (): void => {
|
|
200
|
+
if (cancelled) return;
|
|
201
|
+
reconnectDelay = INITIAL_RECONNECT_DELAY_MS;
|
|
202
|
+
setIsOnline(true);
|
|
203
|
+
setError(null);
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
const onEvent = (evt: unknown): void => {
|
|
207
|
+
if (cancelled) return;
|
|
208
|
+
const raw = (evt as { data?: string }).data;
|
|
209
|
+
if (typeof raw !== 'string') return;
|
|
210
|
+
try {
|
|
211
|
+
const payload = parseRef.current
|
|
212
|
+
? parseRef.current(raw)
|
|
213
|
+
: (JSON.parse(raw) as TPayload);
|
|
214
|
+
setData(payload);
|
|
215
|
+
setLastEventAt(new Date());
|
|
216
|
+
} catch (parseErr) {
|
|
217
|
+
setError(parseErr instanceof Error ? parseErr : new Error(String(parseErr)));
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
const onError = (evt: unknown): void => {
|
|
222
|
+
if (cancelled || !transport) return;
|
|
223
|
+
setIsOnline(false);
|
|
224
|
+
setError(evt instanceof Error ? evt : new Error('Plugin realtime transport error'));
|
|
225
|
+
// readyState === 2 (CLOSED) means the browser will NOT
|
|
226
|
+
// auto-reconnect (4xx/network); restart manually with backoff.
|
|
227
|
+
if (transport.readyState === 2) {
|
|
228
|
+
try {
|
|
229
|
+
transport.close();
|
|
230
|
+
} catch {
|
|
231
|
+
// ignore — already closed.
|
|
232
|
+
}
|
|
233
|
+
transport = null;
|
|
234
|
+
reconnectTimer = setTimeout(connect, reconnectDelay);
|
|
235
|
+
reconnectDelay = Math.min(reconnectDelay * 2, MAX_RECONNECT_DELAY_MS);
|
|
236
|
+
}
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
const connect = (): void => {
|
|
240
|
+
if (cancelled) return;
|
|
241
|
+
try {
|
|
242
|
+
transport = factory(url);
|
|
243
|
+
} catch (createErr) {
|
|
244
|
+
setError(createErr instanceof Error ? createErr : new Error(String(createErr)));
|
|
245
|
+
setIsOnline(false);
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
transport.addEventListener('open', onOpen);
|
|
249
|
+
transport.addEventListener(eventName, onEvent);
|
|
250
|
+
transport.addEventListener('message', onEvent);
|
|
251
|
+
transport.addEventListener('error', onError);
|
|
252
|
+
};
|
|
253
|
+
|
|
254
|
+
connect();
|
|
255
|
+
|
|
256
|
+
return (): void => {
|
|
257
|
+
cancelled = true;
|
|
258
|
+
if (reconnectTimer !== null) {
|
|
259
|
+
clearTimeout(reconnectTimer);
|
|
260
|
+
}
|
|
261
|
+
if (transport) {
|
|
262
|
+
try {
|
|
263
|
+
transport.removeEventListener('open', onOpen);
|
|
264
|
+
transport.removeEventListener(eventName, onEvent);
|
|
265
|
+
transport.removeEventListener('message', onEvent);
|
|
266
|
+
transport.removeEventListener('error', onError);
|
|
267
|
+
transport.close();
|
|
268
|
+
} catch {
|
|
269
|
+
// ignore — best-effort cleanup.
|
|
270
|
+
}
|
|
271
|
+
transport = null;
|
|
272
|
+
}
|
|
273
|
+
};
|
|
274
|
+
}, [enabled, endpoint, pluginId, topic, topicParamsKey, transportFactory]);
|
|
275
|
+
|
|
276
|
+
return { data, isOnline, lastEventAt, error };
|
|
277
|
+
}
|