@haatlabs-core/templates 0.19.0 → 0.21.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/package.json +3 -3
- package/starter/apps/api/package.json.tmpl +1 -0
- package/starter/apps/api/src/app.module.ts +36 -0
- package/starter/apps/api/src/notifications.int.test.ts +210 -0
- package/starter/apps/api/src/security-sweep.int.test.ts +63 -10
- package/starter/apps/api/src/seed.ts +16 -3
- package/starter/apps/web/public/notifications-sw.js +47 -0
- package/starter/apps/worker/package.json.tmpl +2 -0
- package/starter/apps/worker/src/handlers/notifications.handler.ts +63 -0
- package/starter/apps/worker/src/runtime.ts +52 -26
- package/starter/dot-env.example +16 -0
- package/starter/packages/config/src/config.test.ts +26 -0
- package/starter/packages/config/src/config.ts +11 -2
- package/starter/packages/contracts/package.json.tmpl +3 -1
- package/starter/packages/contracts/src/notifications.ts +38 -0
- package/starter/packages/database/drizzle/0009_notifications.sql +87 -0
- package/starter/packages/database/drizzle/meta/0009_snapshot.json +2446 -0
- package/starter/packages/database/drizzle/meta/_journal.json +7 -0
- package/starter/packages/database/package.json.tmpl +1 -0
- package/starter/packages/database/src/index.ts +1 -0
- package/starter/packages/database/src/repositories/notification.repository.ts +65 -0
- package/starter/packages/database/src/schema/index.ts +1 -0
- package/starter/packages/database/src/schema/notifications.ts +37 -0
- package/starter/packages/database/src/schema-tables.int.test.ts +10 -0
- package/starter/packages/queue/src/topology.test.ts +1 -0
- package/starter/packages/queue/src/topology.ts +3 -0
- package/starter/packages/web-ui/package.json.tmpl +1 -0
- package/starter/packages/web-ui/src/App.test.tsx +51 -2
- package/starter/packages/web-ui/src/App.tsx +84 -8
- package/starter/packages/web-ui/src/api-client.test.ts +204 -1
- package/starter/packages/web-ui/src/api-client.ts +207 -1
- package/starter/packages/web-ui/src/components/Logo.tsx +5 -0
- package/starter/packages/web-ui/src/pages/NotificationSettingsPage.tsx +24 -0
- package/starter/packages/web-ui/src/pages/NotificationsPage.tsx +19 -0
- package/starter/packages/web-ui/src/styles.css +21 -0
- package/starter/packages/web-ui/src/testing/fake-client.ts +15 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { describe, expect, it, vi } from 'vitest';
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
2
2
|
import { ApiError, createApiClient, readCookie } from './api-client';
|
|
3
3
|
|
|
4
4
|
const STORE_ID = '7f2c1d5e-8a43-4b6f-9c1d-2e3f4a5b6c7d';
|
|
@@ -256,3 +256,206 @@ describe('readCookie', () => {
|
|
|
256
256
|
expect(readCookie('@@name@@_csrf', '')).toBeNull();
|
|
257
257
|
});
|
|
258
258
|
});
|
|
259
|
+
|
|
260
|
+
describe('the notifications client', () => {
|
|
261
|
+
const ITEM = {
|
|
262
|
+
id: '3b7e1f7a-4c1d-4e5f-9a8b-1c2d3e4f5a6b',
|
|
263
|
+
event: 'account.welcome',
|
|
264
|
+
title: 'Welcome',
|
|
265
|
+
body: 'Hello',
|
|
266
|
+
link: '/home',
|
|
267
|
+
readAt: null,
|
|
268
|
+
createdAt: '2026-11-22T10:00:00.000Z',
|
|
269
|
+
};
|
|
270
|
+
/** A response that streams `chunks`, then ends. */
|
|
271
|
+
const eventStream = (chunks: string[]): Response =>
|
|
272
|
+
new Response(
|
|
273
|
+
new ReadableStream<Uint8Array>({
|
|
274
|
+
start(controller) {
|
|
275
|
+
for (const chunk of chunks) controller.enqueue(new TextEncoder().encode(chunk));
|
|
276
|
+
controller.close();
|
|
277
|
+
},
|
|
278
|
+
}),
|
|
279
|
+
{ headers: { 'content-type': 'text/event-stream' } },
|
|
280
|
+
);
|
|
281
|
+
|
|
282
|
+
afterEach(() => {
|
|
283
|
+
vi.unstubAllGlobals();
|
|
284
|
+
vi.useRealTimers();
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
it('reads the inbox and marks items read on the notification routes', async () => {
|
|
288
|
+
const fetch = vi
|
|
289
|
+
.fn()
|
|
290
|
+
.mockResolvedValueOnce(Response.json({ items: [ITEM], nextCursor: null }))
|
|
291
|
+
.mockResolvedValueOnce(Response.json({ unread: 3 }))
|
|
292
|
+
.mockResolvedValueOnce(Response.json({ unread: 2 }))
|
|
293
|
+
.mockResolvedValueOnce(Response.json({ unread: 0 }));
|
|
294
|
+
const { notifications } = cookieClient(fetch);
|
|
295
|
+
expect(await notifications.list({ unread: true, cursor: 'abc' })).toEqual({
|
|
296
|
+
items: [ITEM],
|
|
297
|
+
nextCursor: null,
|
|
298
|
+
});
|
|
299
|
+
expect(await notifications.unreadCount()).toBe(3);
|
|
300
|
+
expect(await notifications.markRead([ITEM.id])).toBe(2);
|
|
301
|
+
expect(await notifications.markAllRead()).toBe(0);
|
|
302
|
+
expect(fetch.mock.calls.map((call) => (call as FetchCall)[0])).toEqual([
|
|
303
|
+
'/api/v1/notifications?unread=true&cursor=abc',
|
|
304
|
+
'/api/v1/notifications/unread-count',
|
|
305
|
+
'/api/v1/notifications/read',
|
|
306
|
+
'/api/v1/notifications/read-all',
|
|
307
|
+
]);
|
|
308
|
+
const [, read] = callAt(fetch, 2) as unknown as [string, { body: string }];
|
|
309
|
+
expect(JSON.parse(read.body)).toEqual({ ids: [ITEM.id] });
|
|
310
|
+
});
|
|
311
|
+
|
|
312
|
+
it('streams the unread count and new items with the bearer token, then waits as the server says', async () => {
|
|
313
|
+
vi.useFakeTimers();
|
|
314
|
+
const fetch = vi
|
|
315
|
+
.fn()
|
|
316
|
+
.mockResolvedValueOnce(
|
|
317
|
+
eventStream([
|
|
318
|
+
'retry: 2000\n\n: ping\n\nevent: unr',
|
|
319
|
+
'ead\ndata: {"unread":4}\n\n',
|
|
320
|
+
`event: notification\ndata: ${JSON.stringify(ITEM)}\n\n`,
|
|
321
|
+
]),
|
|
322
|
+
);
|
|
323
|
+
const client = createApiClient({
|
|
324
|
+
credentials: { kind: 'bearer', getToken: async () => 'session-token' },
|
|
325
|
+
fetch: fetch as never,
|
|
326
|
+
});
|
|
327
|
+
const events: unknown[] = [];
|
|
328
|
+
let done = false;
|
|
329
|
+
const streamed = client.notifications.stream?.(new AbortController().signal, (event) => {
|
|
330
|
+
events.push(event);
|
|
331
|
+
});
|
|
332
|
+
void streamed?.then(() => {
|
|
333
|
+
done = true;
|
|
334
|
+
});
|
|
335
|
+
await vi.advanceTimersByTimeAsync(1_999);
|
|
336
|
+
expect(events).toEqual([
|
|
337
|
+
{ kind: 'unread', unread: 4 },
|
|
338
|
+
{ kind: 'notification', item: ITEM },
|
|
339
|
+
]);
|
|
340
|
+
expect(done).toBe(false);
|
|
341
|
+
await vi.advanceTimersByTimeAsync(1);
|
|
342
|
+
expect(done).toBe(true);
|
|
343
|
+
const [url, init] = callAt(fetch, 0);
|
|
344
|
+
expect(url).toBe('/api/v1/notifications/stream');
|
|
345
|
+
expect(init.headers.authorization).toBe('Bearer session-token');
|
|
346
|
+
expect(init.credentials).toBe('omit');
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
it('keeps a CRLF split across chunks as one line break, and joins multi-line data', async () => {
|
|
350
|
+
const fetch = vi
|
|
351
|
+
.fn()
|
|
352
|
+
.mockResolvedValueOnce(
|
|
353
|
+
eventStream([
|
|
354
|
+
'retry: 0\r\n\r\nevent: unread\r',
|
|
355
|
+
'\ndata: {"unread":\r',
|
|
356
|
+
'\ndata: 7}\r\n\r\n',
|
|
357
|
+
]),
|
|
358
|
+
);
|
|
359
|
+
const events: unknown[] = [];
|
|
360
|
+
await cookieClient(fetch).notifications.stream?.(new AbortController().signal, (event) => {
|
|
361
|
+
events.push(event);
|
|
362
|
+
});
|
|
363
|
+
expect(events).toEqual([{ kind: 'unread', unread: 7 }]);
|
|
364
|
+
});
|
|
365
|
+
|
|
366
|
+
it('stops the stream at once when it is aborted, and fails on a refused one', async () => {
|
|
367
|
+
const fetch = vi
|
|
368
|
+
.fn()
|
|
369
|
+
.mockImplementationOnce(
|
|
370
|
+
async () =>
|
|
371
|
+
new Response(
|
|
372
|
+
new ReadableStream<Uint8Array>({
|
|
373
|
+
start(controller) {
|
|
374
|
+
controller.enqueue(new TextEncoder().encode('retry: 60000\n\n'));
|
|
375
|
+
},
|
|
376
|
+
}),
|
|
377
|
+
),
|
|
378
|
+
)
|
|
379
|
+
.mockResolvedValueOnce(
|
|
380
|
+
Response.json(
|
|
381
|
+
{ error: { code: 'UNAUTHENTICATED', message: 'Sign in', requestId: 'r1' } },
|
|
382
|
+
{ status: 401 },
|
|
383
|
+
),
|
|
384
|
+
);
|
|
385
|
+
const { notifications } = cookieClient(fetch);
|
|
386
|
+
const controller = new AbortController();
|
|
387
|
+
const streamed = notifications.stream?.(controller.signal, () => undefined);
|
|
388
|
+
controller.abort();
|
|
389
|
+
await expect(streamed).resolves.toBeUndefined();
|
|
390
|
+
await expect(
|
|
391
|
+
notifications.stream?.(new AbortController().signal, () => undefined),
|
|
392
|
+
).rejects.toMatchObject({ status: 401, code: 'UNAUTHENTICATED' });
|
|
393
|
+
});
|
|
394
|
+
|
|
395
|
+
it('turns push on with the server’s key and saves the subscription, and off by its endpoint', async () => {
|
|
396
|
+
const subscription = {
|
|
397
|
+
endpoint: 'https://push.example/device-1',
|
|
398
|
+
options: { applicationServerKey: null },
|
|
399
|
+
toJSON: () => ({ keys: { p256dh: 'p256', auth: 'auth' } }),
|
|
400
|
+
unsubscribe: vi.fn().mockResolvedValue(true),
|
|
401
|
+
};
|
|
402
|
+
const pushManager = {
|
|
403
|
+
getSubscription: vi.fn().mockResolvedValueOnce(null).mockResolvedValue(subscription),
|
|
404
|
+
subscribe: vi.fn().mockResolvedValue(subscription),
|
|
405
|
+
};
|
|
406
|
+
const serviceWorker = {
|
|
407
|
+
register: vi.fn(),
|
|
408
|
+
ready: Promise.resolve({ pushManager }),
|
|
409
|
+
getRegistration: vi.fn().mockResolvedValue({ pushManager }),
|
|
410
|
+
};
|
|
411
|
+
vi.stubGlobal('window', { top: null, self: null });
|
|
412
|
+
vi.stubGlobal('navigator', { userAgent: 'Firefox', serviceWorker });
|
|
413
|
+
vi.stubGlobal('PushManager', function PushManager() {});
|
|
414
|
+
vi.stubGlobal('Notification', { requestPermission: async () => 'granted' });
|
|
415
|
+
const fetch = vi
|
|
416
|
+
.fn()
|
|
417
|
+
.mockResolvedValueOnce(Response.json({ webPush: 'BEl6' }))
|
|
418
|
+
.mockResolvedValueOnce(new Response(null, { status: 204 }))
|
|
419
|
+
.mockResolvedValueOnce(new Response(null, { status: 204 }));
|
|
420
|
+
const { notifications } = cookieClient(fetch);
|
|
421
|
+
expect(notifications.push?.support()).toBe('supported');
|
|
422
|
+
expect(await notifications.push?.enable()).toBe('subscribed');
|
|
423
|
+
expect(serviceWorker.register).toHaveBeenCalledWith('/notifications-sw.js');
|
|
424
|
+
// The settings page asks, to offer turning it off.
|
|
425
|
+
expect(await notifications.push?.isSubscribed?.()).toBe(true);
|
|
426
|
+
await notifications.push?.disable();
|
|
427
|
+
expect(subscription.unsubscribe).toHaveBeenCalled();
|
|
428
|
+
const calls = fetch.mock.calls as [
|
|
429
|
+
string,
|
|
430
|
+
{ method: string; headers: Record<string, string>; body: string },
|
|
431
|
+
][];
|
|
432
|
+
expect(calls.map(([url, init]) => `${init.method} ${url}`)).toEqual([
|
|
433
|
+
'GET /api/v1/notifications/push/key',
|
|
434
|
+
'POST /api/v1/notifications/push/subscriptions',
|
|
435
|
+
'DELETE /api/v1/notifications/push/subscriptions',
|
|
436
|
+
]);
|
|
437
|
+
expect(JSON.parse(calls[1]?.[1].body ?? '')).toEqual({
|
|
438
|
+
kind: 'webpush',
|
|
439
|
+
endpoint: 'https://push.example/device-1',
|
|
440
|
+
keys: { p256dh: 'p256', auth: 'auth' },
|
|
441
|
+
});
|
|
442
|
+
expect(calls[2]?.[1].headers['content-type']).toBe('application/json');
|
|
443
|
+
expect(JSON.parse(calls[2]?.[1].body ?? '')).toEqual({
|
|
444
|
+
endpoint: 'https://push.example/device-1',
|
|
445
|
+
});
|
|
446
|
+
});
|
|
447
|
+
|
|
448
|
+
it('says push is not set up when the server has no key, and leaves push out of the embedded app', async () => {
|
|
449
|
+
vi.stubGlobal('window', { top: null, self: null });
|
|
450
|
+
vi.stubGlobal('navigator', { userAgent: 'Firefox', serviceWorker: {} });
|
|
451
|
+
vi.stubGlobal('PushManager', function PushManager() {});
|
|
452
|
+
vi.stubGlobal('Notification', { requestPermission: async () => 'granted' });
|
|
453
|
+
const fetch = vi.fn().mockResolvedValueOnce(Response.json({ webPush: null }));
|
|
454
|
+
expect(await cookieClient(fetch).notifications.push?.enable()).toBe('unsupported');
|
|
455
|
+
const embedded = createApiClient({
|
|
456
|
+
credentials: { kind: 'bearer', getToken: async () => 't' },
|
|
457
|
+
fetch: vi.fn() as never,
|
|
458
|
+
});
|
|
459
|
+
expect(embedded.notifications.push).toBeUndefined();
|
|
460
|
+
});
|
|
461
|
+
});
|
|
@@ -57,8 +57,24 @@ import type {
|
|
|
57
57
|
CreateExtensionKeyResponse,
|
|
58
58
|
ExtensionKeyListResponse,
|
|
59
59
|
} from '@haatlabs-core/auth-contracts';
|
|
60
|
+
import {
|
|
61
|
+
NotificationItemSchema,
|
|
62
|
+
NotificationListSchema,
|
|
63
|
+
PreferencesSchema,
|
|
64
|
+
PushKeySchema,
|
|
65
|
+
UnreadSchema,
|
|
66
|
+
pushSubscribed,
|
|
67
|
+
pushSupport,
|
|
68
|
+
subscribeToPush,
|
|
69
|
+
unsubscribeFromPush,
|
|
70
|
+
} from '@haatlabs-core/notifications/browser';
|
|
60
71
|
import { ApiError, OkSchema, createTransport } from '@haatlabs-core/ui/client';
|
|
61
|
-
import type {
|
|
72
|
+
import type {
|
|
73
|
+
CredentialStrategy,
|
|
74
|
+
NotificationStreamEvent,
|
|
75
|
+
NotificationsClient,
|
|
76
|
+
Transport,
|
|
77
|
+
} from '@haatlabs-core/ui/client';
|
|
62
78
|
|
|
63
79
|
export type { CredentialStrategy } from '@haatlabs-core/ui/client';
|
|
64
80
|
|
|
@@ -128,6 +144,11 @@ export interface ApiClient {
|
|
|
128
144
|
listStores(): Promise<StoreListResponse>;
|
|
129
145
|
#@end
|
|
130
146
|
cancelRenewal(): Promise<{ cancelled: true }>;
|
|
147
|
+
/**
|
|
148
|
+
* The caller's notifications: the inbox, the live stream and the preferences, and push on
|
|
149
|
+
* this device (left out of the embedded app, whose frame cannot have push).
|
|
150
|
+
*/
|
|
151
|
+
notifications: NotificationsClient;
|
|
131
152
|
#@if standalone
|
|
132
153
|
/** The example page: images for a product name, from the Haatlabs API. */
|
|
133
154
|
findImages(q: string): Promise<FindImagesResponse>;
|
|
@@ -142,6 +163,187 @@ export interface ApiClient {
|
|
|
142
163
|
#@end
|
|
143
164
|
}
|
|
144
165
|
|
|
166
|
+
const NOTIFICATIONS = '/api/v1/notifications';
|
|
167
|
+
/** How long to wait before the stream is opened again, until the server says otherwise. */
|
|
168
|
+
const DEFAULT_STREAM_RETRY_MS = 10_000;
|
|
169
|
+
|
|
170
|
+
/** A route that answers 204 and no body when it is done; otherwise its error. */
|
|
171
|
+
async function noContent(transport: Transport, response: Response): Promise<void> {
|
|
172
|
+
if (response.ok) return;
|
|
173
|
+
throw transport.failure(await response.json().catch(() => null), response.status);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Resolves after `ms`, or at once when `signal` aborts. */
|
|
177
|
+
const wait = (ms: number, signal: AbortSignal): Promise<void> =>
|
|
178
|
+
new Promise((resolve) => {
|
|
179
|
+
if (signal.aborted) return resolve();
|
|
180
|
+
const done = (): void => {
|
|
181
|
+
clearTimeout(timer);
|
|
182
|
+
signal.removeEventListener('abort', done);
|
|
183
|
+
resolve();
|
|
184
|
+
};
|
|
185
|
+
const timer = setTimeout(done, ms);
|
|
186
|
+
signal.addEventListener('abort', done);
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
/** One Server-Sent Events message: what the stream says and, when it says so, how long to wait. */
|
|
190
|
+
function parseEvent(block: string): { event?: NotificationStreamEvent; retryMs?: number } {
|
|
191
|
+
let name = 'message';
|
|
192
|
+
let data = '';
|
|
193
|
+
let retryMs: number | undefined;
|
|
194
|
+
for (const line of block.split('\n')) {
|
|
195
|
+
if (line === '' || line.startsWith(':')) continue;
|
|
196
|
+
const colon = line.indexOf(':');
|
|
197
|
+
const field = colon === -1 ? line : line.slice(0, colon);
|
|
198
|
+
const value = colon === -1 ? '' : line.slice(colon + 1).replace(/^ /, '');
|
|
199
|
+
if (field === 'event') name = value;
|
|
200
|
+
else if (field === 'data') data = data ? `${data}\n${value}` : value;
|
|
201
|
+
else if (field === 'retry' && /^\d+$/.test(value)) retryMs = Number(value);
|
|
202
|
+
}
|
|
203
|
+
if (!data) return { retryMs };
|
|
204
|
+
let payload: unknown;
|
|
205
|
+
try {
|
|
206
|
+
payload = JSON.parse(data);
|
|
207
|
+
} catch {
|
|
208
|
+
return { retryMs };
|
|
209
|
+
}
|
|
210
|
+
if (name === 'unread') {
|
|
211
|
+
const parsed = UnreadSchema.safeParse(payload);
|
|
212
|
+
return { retryMs, event: parsed.success ? { kind: 'unread', ...parsed.data } : undefined };
|
|
213
|
+
}
|
|
214
|
+
if (name === 'notification') {
|
|
215
|
+
const parsed = NotificationItemSchema.safeParse(payload);
|
|
216
|
+
return {
|
|
217
|
+
retryMs,
|
|
218
|
+
event: parsed.success ? { kind: 'notification', item: parsed.data } : undefined,
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
return { retryMs };
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* The notification routes. The stream is read with fetch, not EventSource, so that inside
|
|
226
|
+
* the embedded app it carries the session token as every other request does.
|
|
227
|
+
*/
|
|
228
|
+
function notificationsClient(
|
|
229
|
+
transport: Transport,
|
|
230
|
+
options: { credentials: CredentialStrategy; fetch: typeof fetch },
|
|
231
|
+
): NotificationsClient {
|
|
232
|
+
const { call, queryOf } = transport;
|
|
233
|
+
|
|
234
|
+
async function stream(
|
|
235
|
+
signal: AbortSignal,
|
|
236
|
+
onEvent: (event: NotificationStreamEvent) => void,
|
|
237
|
+
): Promise<void> {
|
|
238
|
+
const { credentials } = options;
|
|
239
|
+
const headers: Record<string, string> = { accept: 'text/event-stream' };
|
|
240
|
+
if (credentials.kind === 'bearer') {
|
|
241
|
+
try {
|
|
242
|
+
headers.authorization = `Bearer ${await credentials.getToken()}`;
|
|
243
|
+
} catch (error) {
|
|
244
|
+
const message = error instanceof Error ? error.message : 'No session token';
|
|
245
|
+
throw new ApiError('UNAUTHENTICATED', message, 401);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
let response: Response;
|
|
249
|
+
try {
|
|
250
|
+
response = await options.fetch(`${transport.baseUrl}${NOTIFICATIONS}/stream`, {
|
|
251
|
+
headers,
|
|
252
|
+
credentials: credentials.kind === 'cookie' ? 'include' : 'omit',
|
|
253
|
+
cache: 'no-store',
|
|
254
|
+
signal,
|
|
255
|
+
});
|
|
256
|
+
} catch (error) {
|
|
257
|
+
if (signal.aborted) return;
|
|
258
|
+
throw error;
|
|
259
|
+
}
|
|
260
|
+
if (!response.ok || !response.body) {
|
|
261
|
+
throw transport.failure(await response.json().catch(() => null), response.status);
|
|
262
|
+
}
|
|
263
|
+
let retryMs = DEFAULT_STREAM_RETRY_MS;
|
|
264
|
+
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
|
|
265
|
+
const stop = (): void => void reader.cancel().catch(() => undefined);
|
|
266
|
+
signal.addEventListener('abort', stop);
|
|
267
|
+
let buffer = '';
|
|
268
|
+
// A '\r' that ends a chunk may be the first half of a '\r\n': held until the next one.
|
|
269
|
+
let held = '';
|
|
270
|
+
try {
|
|
271
|
+
// Aborted while the response was on its way: nothing would fire 'abort' again.
|
|
272
|
+
if (signal.aborted) {
|
|
273
|
+
stop();
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
for (;;) {
|
|
277
|
+
const { done, value } = await reader.read();
|
|
278
|
+
if (done) break;
|
|
279
|
+
let text = held + value;
|
|
280
|
+
held = text.endsWith('\r') ? '\r' : '';
|
|
281
|
+
if (held) text = text.slice(0, -1);
|
|
282
|
+
buffer = (buffer + text).replace(/\r\n?/g, '\n');
|
|
283
|
+
let end = buffer.indexOf('\n\n');
|
|
284
|
+
while (end !== -1) {
|
|
285
|
+
const parsed = parseEvent(buffer.slice(0, end));
|
|
286
|
+
buffer = buffer.slice(end + 2);
|
|
287
|
+
if (parsed.retryMs !== undefined) retryMs = parsed.retryMs;
|
|
288
|
+
if (parsed.event && !signal.aborted) onEvent(parsed.event);
|
|
289
|
+
end = buffer.indexOf('\n\n');
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
} catch (error) {
|
|
293
|
+
if (!signal.aborted) throw error;
|
|
294
|
+
} finally {
|
|
295
|
+
signal.removeEventListener('abort', stop);
|
|
296
|
+
}
|
|
297
|
+
// The server ended the stream: open it again no sooner than it asked.
|
|
298
|
+
await wait(retryMs, signal);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
const push: NotificationsClient['push'] = {
|
|
302
|
+
support: () => pushSupport(),
|
|
303
|
+
enable: async () => {
|
|
304
|
+
const { webPush } = await call('GET', `${NOTIFICATIONS}/push/key`, PushKeySchema);
|
|
305
|
+
// Web Push is not set up on this server (no VAPID keys).
|
|
306
|
+
if (!webPush) return 'unsupported';
|
|
307
|
+
return subscribeToPush({
|
|
308
|
+
vapidPublicKey: webPush,
|
|
309
|
+
save: async (body) =>
|
|
310
|
+
noContent(
|
|
311
|
+
transport,
|
|
312
|
+
await transport.send('POST', `${NOTIFICATIONS}/push/subscriptions`, body),
|
|
313
|
+
),
|
|
314
|
+
});
|
|
315
|
+
},
|
|
316
|
+
isSubscribed: () => pushSubscribed(),
|
|
317
|
+
disable: () =>
|
|
318
|
+
unsubscribeFromPush(async (endpoint) =>
|
|
319
|
+
noContent(
|
|
320
|
+
transport,
|
|
321
|
+
await transport.send('DELETE', `${NOTIFICATIONS}/push/subscriptions`, { endpoint }),
|
|
322
|
+
),
|
|
323
|
+
),
|
|
324
|
+
};
|
|
325
|
+
|
|
326
|
+
return {
|
|
327
|
+
list: (q) =>
|
|
328
|
+
call(
|
|
329
|
+
'GET',
|
|
330
|
+
`${NOTIFICATIONS}${queryOf({ unread: q.unread ? 'true' : undefined, cursor: q.cursor })}`,
|
|
331
|
+
NotificationListSchema,
|
|
332
|
+
),
|
|
333
|
+
unreadCount: async () =>
|
|
334
|
+
(await call('GET', `${NOTIFICATIONS}/unread-count`, UnreadSchema)).unread,
|
|
335
|
+
markRead: async (ids) =>
|
|
336
|
+
(await call('POST', `${NOTIFICATIONS}/read`, UnreadSchema, { ids })).unread,
|
|
337
|
+
markAllRead: async () => (await call('POST', `${NOTIFICATIONS}/read-all`, UnreadSchema)).unread,
|
|
338
|
+
stream,
|
|
339
|
+
preferences: () => call('GET', `${NOTIFICATIONS}/preferences`, PreferencesSchema),
|
|
340
|
+
setPreferences: (changes) =>
|
|
341
|
+
call('PUT', `${NOTIFICATIONS}/preferences`, PreferencesSchema, { changes }),
|
|
342
|
+
// The embedded app (a session token, not a cookie) is framed, and a frame cannot have push.
|
|
343
|
+
...(options.credentials.kind === 'cookie' ? { push } : {}),
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
|
|
145
347
|
export function createApiClient(options: {
|
|
146
348
|
baseUrl?: string;
|
|
147
349
|
credentials: CredentialStrategy;
|
|
@@ -187,6 +389,10 @@ export function createApiClient(options: {
|
|
|
187
389
|
|
|
188
390
|
return {
|
|
189
391
|
admin,
|
|
392
|
+
notifications: notificationsClient(transport, {
|
|
393
|
+
credentials: options.credentials,
|
|
394
|
+
fetch: options.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args)),
|
|
395
|
+
}),
|
|
190
396
|
me: async () => remember(await call('GET', '/api/v1/auth/me', MeResponseSchema)),
|
|
191
397
|
requestSignInCode: async (body) =>
|
|
192
398
|
void (await call('POST', '/api/v1/auth/code', OkSchema, body)),
|
|
@@ -58,6 +58,11 @@ export function Logo(): ReactElement {
|
|
|
58
58
|
);
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
+
/** The mark alone: the collapsed sidebar's brand. */
|
|
62
|
+
export function LogoMark(): ReactElement {
|
|
63
|
+
return <Mark size={SIZE.panel} onDark={false} />;
|
|
64
|
+
}
|
|
65
|
+
|
|
61
66
|
/** The logo in the app header: a link home. */
|
|
62
67
|
export function LogoLink(): ReactElement {
|
|
63
68
|
return (
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { PageHeader } from '@haatlabs-core/ui';
|
|
2
|
+
import { NotificationPreferences } from '@haatlabs-core/ui/client';
|
|
3
|
+
import type { NotificationsClient } from '@haatlabs-core/ui/client';
|
|
4
|
+
import type { ReactElement } from 'react';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Which notifications reach the signed-in person by email and push, and push on this device.
|
|
8
|
+
* Every notification email links here ("Change which emails you get").
|
|
9
|
+
*/
|
|
10
|
+
export function NotificationSettingsPage({
|
|
11
|
+
client,
|
|
12
|
+
}: {
|
|
13
|
+
client: NotificationsClient;
|
|
14
|
+
}): ReactElement {
|
|
15
|
+
return (
|
|
16
|
+
<main className="page">
|
|
17
|
+
<PageHeader
|
|
18
|
+
title="Notification settings"
|
|
19
|
+
subtitle="Everything still reaches your inbox: these choose what also comes by email and push."
|
|
20
|
+
/>
|
|
21
|
+
<NotificationPreferences client={client} />
|
|
22
|
+
</main>
|
|
23
|
+
);
|
|
24
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { PageHeader } from '@haatlabs-core/ui';
|
|
2
|
+
import { NotificationInbox } from '@haatlabs-core/ui/client';
|
|
3
|
+
import type { NotificationsClient } from '@haatlabs-core/ui/client';
|
|
4
|
+
import type { ReactElement } from 'react';
|
|
5
|
+
import { Link, useNavigate } from 'react-router-dom';
|
|
6
|
+
|
|
7
|
+
/** Everything the signed-in person was notified of, newest first; the bell's "See all". */
|
|
8
|
+
export function NotificationsPage({ client }: { client: NotificationsClient }): ReactElement {
|
|
9
|
+
const navigate = useNavigate();
|
|
10
|
+
return (
|
|
11
|
+
<main className="page">
|
|
12
|
+
<PageHeader
|
|
13
|
+
title="Notifications"
|
|
14
|
+
actions={<Link to="/settings/notifications">Choose what you get</Link>}
|
|
15
|
+
/>
|
|
16
|
+
<NotificationInbox client={client} onOpenItem={(link) => void navigate(link)} />
|
|
17
|
+
</main>
|
|
18
|
+
);
|
|
19
|
+
}
|
|
@@ -1294,8 +1294,29 @@ table.compare tfoot button + button {
|
|
|
1294
1294
|
/* The one navigation: quiet tabs above the page. */
|
|
1295
1295
|
#@end
|
|
1296
1296
|
.embedded-nav {
|
|
1297
|
+
display: flex;
|
|
1298
|
+
align-items: center;
|
|
1299
|
+
justify-content: space-between;
|
|
1300
|
+
gap: 8px;
|
|
1297
1301
|
padding: 8px 16px 0;
|
|
1298
1302
|
}
|
|
1303
|
+
/* The bell and the notification pages draw on the dashboard theme's tokens, which are not
|
|
1304
|
+
rendered here: these are the embedded look's colours for them. */
|
|
1305
|
+
.embedded .hl-notify,
|
|
1306
|
+
.embedded .hl-notify-page,
|
|
1307
|
+
.embedded .hl-notify-prefs {
|
|
1308
|
+
--hl-surface: #ffffff;
|
|
1309
|
+
--hl-text: #303030;
|
|
1310
|
+
--hl-muted: #616161;
|
|
1311
|
+
--hl-border: #e3e3e3;
|
|
1312
|
+
--hl-faint: #ebebeb;
|
|
1313
|
+
--hl-accent: #303030;
|
|
1314
|
+
--hl-accent-text: #303030;
|
|
1315
|
+
--hl-on-accent: #ffffff;
|
|
1316
|
+
--hl-danger: #8e1f0b;
|
|
1317
|
+
--hl-radius-card: 12px;
|
|
1318
|
+
--hl-radius-control: 8px;
|
|
1319
|
+
}
|
|
1299
1320
|
.embedded-nav .store-nav {
|
|
1300
1321
|
margin: 0;
|
|
1301
1322
|
gap: 4px;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { ALL_FEATURES_ON } from '@@@name@@/contracts';
|
|
2
2
|
import type { AdminMe, AdminOrganizationList, AdminOverview, MeResponse } from '@@@name@@/contracts';
|
|
3
|
+
import type { NotificationsClient } from '@haatlabs-core/ui/client';
|
|
3
4
|
import { vi } from 'vitest';
|
|
4
5
|
import type { ApiClient } from '../api-client';
|
|
5
6
|
|
|
@@ -83,6 +84,19 @@ export const shopStore = {
|
|
|
83
84
|
};
|
|
84
85
|
#@end
|
|
85
86
|
|
|
87
|
+
/** An empty inbox, no stream (the bell polls) and no push. */
|
|
88
|
+
export const fakeNotifications = (
|
|
89
|
+
overrides: Partial<NotificationsClient> = {},
|
|
90
|
+
): NotificationsClient => ({
|
|
91
|
+
list: vi.fn().mockResolvedValue({ items: [], nextCursor: null }),
|
|
92
|
+
unreadCount: vi.fn().mockResolvedValue(0),
|
|
93
|
+
markRead: vi.fn().mockResolvedValue(0),
|
|
94
|
+
markAllRead: vi.fn().mockResolvedValue(0),
|
|
95
|
+
preferences: vi.fn().mockResolvedValue({ events: [] }),
|
|
96
|
+
setPreferences: vi.fn().mockResolvedValue({ events: [] }),
|
|
97
|
+
...overrides,
|
|
98
|
+
});
|
|
99
|
+
|
|
86
100
|
export const fakeClient = (overrides: Partial<ApiClient> = {}): ApiClient => ({
|
|
87
101
|
me: vi.fn().mockResolvedValue(me),
|
|
88
102
|
requestSignInCode: vi.fn().mockResolvedValue(undefined),
|
|
@@ -117,6 +131,7 @@ export const fakeClient = (overrides: Partial<ApiClient> = {}): ApiClient => ({
|
|
|
117
131
|
listPlans: vi.fn().mockResolvedValue({ plans: [], providers: [] }),
|
|
118
132
|
startCheckout: vi.fn().mockResolvedValue({ url: 'https://pay.example/checkout' }),
|
|
119
133
|
cancelRenewal: vi.fn().mockResolvedValue({ cancelled: true }),
|
|
134
|
+
notifications: fakeNotifications(),
|
|
120
135
|
#@if standalone
|
|
121
136
|
findImages: vi.fn().mockResolvedValue({ configured: false, message: 'Set HAATLABS_API_KEY' }),
|
|
122
137
|
#@end
|