@aria-framework/notify 0.5.0 → 0.7.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/CHANGELOG.md +36 -0
- package/README.md +143 -4
- package/assets/bell.css +18 -0
- package/assets/bell.js +103 -19
- package/assets/live.js +9 -4
- package/hub.js +84 -19
- package/package.json +5 -4
- package/store.js +56 -5
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# @aria-framework/notify
|
|
2
|
+
|
|
3
|
+
Older releases are recorded in the README's "Upgrading to …" sections; this file starts at 0.7.0.
|
|
4
|
+
|
|
5
|
+
## 0.7.0 — 2026-11-04
|
|
6
|
+
|
|
7
|
+
Carries 0.6.0 (per-audience stream caps), which was merged but never published: **publish 0.7.0 only**.
|
|
8
|
+
|
|
9
|
+
**Every app's bell changes, with no code change on the app's side:**
|
|
10
|
+
|
|
11
|
+
- **The time is short and sits on the right of the title**: `now`, `3m`, `2h`, `1d` — no longer
|
|
12
|
+
`just now`, `3m ago`, `2h ago`, `1d ago` on a line of its own.
|
|
13
|
+
- **`body` now shows in the bell**: whitespace collapsed, one line, cut with an ellipsis, under the
|
|
14
|
+
title. Before 0.7.0 the bell never showed `body`. An app that stores something in `body` it does
|
|
15
|
+
not want in the dropdown should check what it writes there.
|
|
16
|
+
- **`context` shows when the app's `/recent` items carry it** (one line, cut with an ellipsis).
|
|
17
|
+
- **A click marks the row read at once** (class, badge −1, regroup), POSTs `/:id/read` with
|
|
18
|
+
`keepalive`, then re-syncs. A link to the page already open hides the dropdown and fires
|
|
19
|
+
`aria:notif-goto` `{ href }` on `document` — not for a ctrl / cmd / shift / alt or non-primary
|
|
20
|
+
click, which opens elsewhere (the row is still marked read).
|
|
21
|
+
- **Security: the row href guard is now an origin check.** "Starts with one slash" let `/\evil.com`,
|
|
22
|
+
`/<TAB>/evil.com` and `/<LF>/evil.com` through, and browsers resolve all three to `//evil.com`. A
|
|
23
|
+
link must now hold no control character, space or backslash and must resolve to the page's own
|
|
24
|
+
origin; anything else becomes the notifications page. (The weakness predates 0.7.0.)
|
|
25
|
+
|
|
26
|
+
**Store (additive):**
|
|
27
|
+
|
|
28
|
+
- `createMany` also returns `rows: [{ userId, id }]`, in `userIds` order.
|
|
29
|
+
- `extendUnread(id, userId, { appendTitle, sep = ', ', at })` grows an unread row's title and
|
|
30
|
+
moves its time (owner- and unread-guarded, one statement). `TITLE_MAX` = 500 characters: past it,
|
|
31
|
+
nothing changes and the answer is `false`. `at` (UTC text, `YYYY-MM-DD HH:MM:SS`) is for a test's
|
|
32
|
+
clock; the default is the database's.
|
|
33
|
+
|
|
34
|
+
**Pin `^0.7.0`.** An app that calls `extendUnread`, reads `rows`, listens for `aria:notif-goto` or
|
|
35
|
+
passes `context` needs 0.7.0; under a `^0.6.0` or older range it can resolve to a version without
|
|
36
|
+
them, and the bell then silently does none of it.
|
package/README.md
CHANGED
|
@@ -50,6 +50,25 @@ the same answer as an id that does not exist, so it leaks nothing either. There
|
|
|
50
50
|
permission check to forget, and **moving that scope to a caller-side `if` would be a silent
|
|
51
51
|
privilege escalation rather than a visible break.** Read it as a constraint on future edits.
|
|
52
52
|
|
|
53
|
+
### Growing an unread row (0.7.0)
|
|
54
|
+
|
|
55
|
+
`createMany` returns `{ userIds, rows: [{ userId, id }] }` — each recipient's new row id, so a
|
|
56
|
+
caller can find its row again without reading it back (`userIds` is unchanged).
|
|
57
|
+
|
|
58
|
+
`extendUnread(id, userId, { appendTitle, sep = ', ', at })` appends to that row's title and moves its
|
|
59
|
+
`created_at` to now — "changed status to open" becomes "changed status to open, changed priority
|
|
60
|
+
from medium to high". It is one `UPDATE … WHERE id = ? AND user_id = ? AND is_read = 0`: scoped
|
|
61
|
+
like everything else, and a row its reader has already seen is never rewritten. It returns `true`
|
|
62
|
+
when the row changed and `false` otherwise (not yours, read, gone, nothing to append, or too long).
|
|
63
|
+
`at` (optional, UTC text `YYYY-MM-DD HH:MM:SS`) sets the new time for a test's clock; without it
|
|
64
|
+
the database's clock is used. A malformed `at` throws.
|
|
65
|
+
|
|
66
|
+
**The title is capped at `TITLE_MAX` = 500 characters** (exported). When the grown title would be
|
|
67
|
+
longer, nothing changes and the answer is `false` — the same as for a read row, so a caller's one
|
|
68
|
+
fallback ("write a new row for the follow-up") covers both. It never cuts a title. Which rows to
|
|
69
|
+
grow, and when to stop, is the app's rule (the desk's: field changes by one person on one ticket
|
|
70
|
+
inside its 2-minute email hold).
|
|
71
|
+
|
|
53
72
|
## Two channels
|
|
54
73
|
|
|
55
74
|
- **users** — "tell these RECIPIENTS something happened". The bell.
|
|
@@ -129,8 +148,46 @@ has:
|
|
|
129
148
|
<a class="list-group-item notif-row is-read" href="…">…</a>
|
|
130
149
|
```
|
|
131
150
|
|
|
132
|
-
Colours come from @aria-framework/theme's tokens (`--brand-rgb`, `--text`, `--text-
|
|
133
|
-
Bootstrap's variables as the fallback.
|
|
151
|
+
Colours come from @aria-framework/theme's tokens (`--brand-rgb`, `--text`, `--text-soft`,
|
|
152
|
+
`--text-faint`, `--font-mono`), with Bootstrap's variables as the fallback.
|
|
153
|
+
|
|
154
|
+
### A row's lines (0.7.0)
|
|
155
|
+
|
|
156
|
+
| line | from | shape |
|
|
157
|
+
|---|---|---|
|
|
158
|
+
| `.notif-head` | `.notif-line` (`.notif-who` = `actor_name`, `.notif-what` = `title`) and `.notif-time` | the title at most two lines; the time on the right, short: `now`, `3m`, `2h`, `1d` |
|
|
159
|
+
| `.notif-context` | `item.context`, when present | one line, cut with … |
|
|
160
|
+
| `.notif-body` | `item.body`, whitespace collapsed | one line, cut with …; no line when empty |
|
|
161
|
+
|
|
162
|
+
`context` is not a stored column: an app adds it to the items its `/recent` route returns (the
|
|
163
|
+
desk: `"<tracking id> · <subject>"` for a ticket row, read at render so a renamed subject shows
|
|
164
|
+
its new name). Everything is set with `textContent`, so neither line can carry markup.
|
|
165
|
+
`.notif-who` / `.notif-what` keep their names because an app's decorator may read them. An app
|
|
166
|
+
that wraps a row's children in its own flex box (the desk's avatars) must give that wrapper
|
|
167
|
+
`min-width: 0`, or the ellipsis never engages. A wider bell is the include's `notifWidth`
|
|
168
|
+
(default still `340px`; the desk passes `420px`).
|
|
169
|
+
|
|
170
|
+
### Clicking a row (0.7.0)
|
|
171
|
+
|
|
172
|
+
An unread row turns read **at once**: `is-unread` → `is-read`, the badge drops by one, and the
|
|
173
|
+
list regroups (New → Earlier). Then `POST /:id/read`, then a re-sync for the server's word.
|
|
174
|
+
|
|
175
|
+
When the row links to the page already open (same path and query; only the hash may differ —
|
|
176
|
+
`/tickets/7#msg-3` on `/tickets/7`), the dropdown is hidden (Bootstrap's instance on the toggle,
|
|
177
|
+
when there is one) and the document receives the event below. A ctrl / cmd / shift / alt or
|
|
178
|
+
non-primary click opens elsewhere, so it does neither (the row is still marked read). The read
|
|
179
|
+
POST is sent with `keepalive`, so a click that navigates away does not cancel it.
|
|
180
|
+
|
|
181
|
+
```js
|
|
182
|
+
document.addEventListener('aria:notif-goto', (e) => scrollToMessage(e.detail.href));
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
That event is the page's only signal for a click on the hash it already has, which fires no
|
|
186
|
+
`hashchange`. Read the target from `detail.href`, not `location.hash`. A page that also listens
|
|
187
|
+
for `hashchange` may see both for a new hash; scrolling twice to one target is harmless.
|
|
188
|
+
|
|
189
|
+
Before 0.7.0 the click only POSTed. On a hash jump nothing reloaded, the server sends no frame
|
|
190
|
+
on read, and `data-bs-auto-close="outside"` kept the menu open — the row stayed under New.
|
|
134
191
|
|
|
135
192
|
## Live pages (0.5.0)
|
|
136
193
|
|
|
@@ -158,7 +215,7 @@ bell-only stream is not under the live caps, so the bell never loses to a sevent
|
|
|
158
215
|
their own cap, 20 per USER (`bellPerUser`), so one user cannot fill the process and starve everyone else — over it
|
|
159
216
|
that user's OLDEST bell stream is evicted. Over the session or user cap the OLDEST live stream is evicted (`live-stop evicted`), never the new one — which also clears a
|
|
160
217
|
half-open stream a sleeping laptop left behind. Too many topics or a full process refuse the new stream
|
|
161
|
-
(`too_many_topics`, `busy`). After a `live-stop` bell.js closes the stream and reopens it ONCE without its
|
|
218
|
+
(`too_many_topics`, `busy`; 0.6.0: a named audience over its own cap is `busy` too, see Audiences). After a `live-stop` bell.js closes the stream and reopens it ONCE without its
|
|
162
219
|
topics, so the bell goes on; a bell-only stream that is stopped is not reopened. A stream lives 60 minutes, then
|
|
163
220
|
is told `live-renew` and ended; bell.js reopens it at once, the page catches up, and the new stream is judged
|
|
164
221
|
afresh, so no scope outlives it. `publishSoon` arms nothing for a topic nobody watches.
|
|
@@ -189,9 +246,91 @@ listen on the document and need nothing). `data-live-list` makes it a list of `[
|
|
|
189
246
|
sit on the row or its first cell): with `data-live-insert` (draw it on page 1, default sort, no filter) and nothing
|
|
190
247
|
ticked, new rows are put in and marked New; otherwise a bar says "N new. Show them". Every reconnect catches every
|
|
191
248
|
region up once (there is no replay). When the stream drops or is stopped, a strip says "Live updates paused" with a
|
|
192
|
-
Refresh button
|
|
249
|
+
Refresh button — or, when the app refused the topics with the reason `off` (0.5.1: its installation-wide switch),
|
|
250
|
+
"Live updates are off". Frames that arrive after this page submitted a form are ignored (the mid-navigation trap above)
|
|
193
251
|
until the page navigates — or, for a submit that does not (a download, `target=_blank`), until it is visible again
|
|
194
252
|
or 8 s pass; a submit a script prevented is not a navigation.
|
|
195
253
|
|
|
196
254
|
Still one process: a write in another process (an ingest server, a node server) reaches no stream
|
|
197
255
|
here. Such a page needs a re-check in the web process, or a shared bus — neither is in this module.
|
|
256
|
+
|
|
257
|
+
## Audiences (0.6.0)
|
|
258
|
+
|
|
259
|
+
A stream carries an **audience**. `staff` is the default — a `subscribe` that passes none is exactly what it was in
|
|
260
|
+
0.5.1 — and any other audience must be named in `limits.perAudience`, which gives it a cap of its own **inside**
|
|
261
|
+
`perProcess`. The one named by default is `contact`, for a customer portal's contacts:
|
|
262
|
+
|
|
263
|
+
```js
|
|
264
|
+
// a portal contact's stream: counted under the contact cap, never against staff's reserve
|
|
265
|
+
hub.subscribe(contactKey, res, { topics, sessionId, meta, audience: 'contact' });
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
**Why.** One process cap shared by everyone lets one audience starve another: at 12 live streams each, about 84
|
|
269
|
+
contacts with tabs open fill 1000 streams, and every staff bell and live page after that is told `busy`. With
|
|
270
|
+
`perAudience: { contact: N }`, contacts can never hold more than N, so staff always keep `perProcess` − N.
|
|
271
|
+
|
|
272
|
+
**The default: 400 of 1000 (40 %).** Staff keep 600 — every staff member's bell plus a handful of live tabs, for well
|
|
273
|
+
over a hundred staff at once, far beyond any team these apps serve — while contacts get 400 streams: at the two or
|
|
274
|
+
three tabs a portal visit actually opens, more than a hundred contacts on the portal at the same moment, and about
|
|
275
|
+
five times the 84 that fill the process today. A hub that sets `perProcess` and not `perAudience` gets the same 40 %
|
|
276
|
+
of its own total (floored: at `perProcess: 2000` contacts get 800; at `perProcess: 2` they get 0). An explicit
|
|
277
|
+
`perAudience` value is merged over the default per audience, and an explicit `0` means that audience is off: every
|
|
278
|
+
stream of it is refused `busy`, exactly as a derived 0 is.
|
|
279
|
+
|
|
280
|
+
**The rules.**
|
|
281
|
+
|
|
282
|
+
- A named audience at its cap is **refused** (`live-stop busy`), like the process cap. It never evicts: the
|
|
283
|
+
per-session and per-user caps evict the OLDEST stream of the SAME session or person, but the streams under an
|
|
284
|
+
audience cap belong to other people — two contacts of two partners — and one's new tab must not end another's.
|
|
285
|
+
- **A person at their own limit is never refused for it.** The per-session and per-user evictions run BEFORE the
|
|
286
|
+
audience and process caps (0.6.0; in 0.5.x they ran after, so a person holding six tabs while the process was
|
|
287
|
+
full was told `busy` instead of losing their oldest). Their own oldest goes, which frees the place the new tab
|
|
288
|
+
takes in the same audience, so a contact at the contact cap or a staff member at a full process keeps working.
|
|
289
|
+
That holds while a user id and a session id each belong to one audience; the hub's contact keys are negative and
|
|
290
|
+
never a staff id.
|
|
291
|
+
- Staff are never refused because of contacts. Staff are refused only when the whole process is full, and that
|
|
292
|
+
needs staff themselves to hold at least `perProcess` − the named caps. Staff may use room a named audience leaves
|
|
293
|
+
idle; a named audience under its own cap is still refused when the process is full.
|
|
294
|
+
- The warn names the audience: `notify: the contact stream cap (400 of 1000 per process) is reached — …` or
|
|
295
|
+
`notify: the stream cap (1000 per process) is reached — … (this one: audience staff; held: staff 600, contact
|
|
296
|
+
400)`. Each line is logged once a minute per cap and audience, so contacts being refused never hides the line
|
|
297
|
+
that says staff are.
|
|
298
|
+
- Any audience string may be named (`perAudience: { contact: 300, kiosk: 50 }`). `subscribe` **throws** on an
|
|
299
|
+
audience that is neither `staff` nor named — a misspelt `'contacts'` would otherwise be an uncapped stream.
|
|
300
|
+
`createHub` throws when the named caps together are not below `perProcess` (staff would keep no reserve), on a cap
|
|
301
|
+
that is neither 0 nor a positive number, and on `perAudience.staff` (staff is the reserve; `perProcess` caps it).
|
|
302
|
+
- `streamStats()` adds `audiences: { staff, contact, … }` (open streams of each) and `limits.perAudience`.
|
|
303
|
+
|
|
304
|
+
### Upgrading to 0.6.0
|
|
305
|
+
|
|
306
|
+
- **Nothing changes for a caller that passes no audience**: every stream is `staff`, and staff can still use the
|
|
307
|
+
whole `perProcess` while no contact holds a stream. 0.6.0 also carries 0.5.1's strip wording (`off`), which was
|
|
308
|
+
never published on its own.
|
|
309
|
+
- **An app that serves non-staff streams should pass `audience`** — until it does, those streams are counted as
|
|
310
|
+
staff and the reserve protects no one. The hub's customer portal stream is the one known case
|
|
311
|
+
(`routes/portal.js`, `GET /portal/live/stream`: `audience: 'contact'`).
|
|
312
|
+
- **A live stream at its own per-session or per-user limit now evicts its own oldest even when the process is
|
|
313
|
+
full** (0.5.x refused it `busy`). Callers need do nothing; it only ever ends a stream of the same session or user.
|
|
314
|
+
- **A hub that set `limits: { perProcess }` below 3** now has a contact cap of 0 (40 % floored), so contact streams
|
|
315
|
+
are all refused there; give it an explicit `perAudience` or a larger `perProcess` before passing `'contact'`.
|
|
316
|
+
- **A hub that names its own audiences** must keep their caps (with the default contact one) below `perProcess`, or
|
|
317
|
+
`createHub` throws at boot.
|
|
318
|
+
|
|
319
|
+
### Upgrading to 0.7.0
|
|
320
|
+
|
|
321
|
+
- **0.7.0 carries 0.6.0**, which was merged but never published: publish 0.7.0 only. It stands as
|
|
322
|
+
its own minor rather than folding into 0.6.0 because it adds API (`extendUnread`, `TITLE_MAX`,
|
|
323
|
+
`createMany`'s `rows`) and changes the bell's look, while the repo's todo.md already names 0.6.0
|
|
324
|
+
for the audience caps alone; reusing the number would change what it means. The hub's pending
|
|
325
|
+
`audience: 'contact'` change needs 0.6.0's code, which 0.7.0 has.
|
|
326
|
+
- **Nothing is required of a caller.** `createMany`'s `userIds` is unchanged; `rows` is new.
|
|
327
|
+
- **Every app's bell looks different without a code change**: the time reads `now` / `3m` / `1d`
|
|
328
|
+
(not `just now` / `3m ago`), and a row's `body` now shows under the title. CHANGELOG.md has the
|
|
329
|
+
list, including the href guard's fix (`/\evil.com` and friends). **Pin `^0.7.0`** in an app that
|
|
330
|
+
uses any of the new API or `aria:notif-goto`.
|
|
331
|
+
- **The bell's row changed shape**: `.notif-what` now sits in `.notif-head > .notif-line` with
|
|
332
|
+
`.notif-time` beside it, where it used to be a plain `div.small` followed by a time `div`. An
|
|
333
|
+
app's CSS or script that reached into the old shape by position (not by `.notif-who` /
|
|
334
|
+
`.notif-what`) should be checked. The time reads `1d`, not `1d ago`.
|
|
335
|
+
- **An app that wants the ticket line** adds `context` to the items `/recent` returns; without it
|
|
336
|
+
the row is as before plus the body's first line.
|
package/assets/bell.css
CHANGED
|
@@ -15,6 +15,11 @@
|
|
|
15
15
|
* .notif-row.is-unread tint + edge + dot + strong text
|
|
16
16
|
* .notif-row.is-read faded text
|
|
17
17
|
* .notif-section the "New" / "Earlier" label; .notif-section-count is the pill on "New"
|
|
18
|
+
*
|
|
19
|
+
* The row's lines (0.7.0): .notif-head holds .notif-line (who + what, at most two lines) and
|
|
20
|
+
* .notif-time ("1d", on the right); then .notif-context and .notif-body, ONE line each, cut with
|
|
21
|
+
* an ellipsis. An app that wraps the row's children in a flex box (an avatar decorator) must give
|
|
22
|
+
* that wrapper min-width:0, or the ellipsis never engages — direct div children get it here.
|
|
18
23
|
*/
|
|
19
24
|
.notif-row{
|
|
20
25
|
position:relative;
|
|
@@ -68,6 +73,19 @@
|
|
|
68
73
|
letter-spacing:0;
|
|
69
74
|
}
|
|
70
75
|
|
|
76
|
+
/* ── The row's lines (0.7.0) ───────────────────────────────────────────────────────────────── */
|
|
77
|
+
.notif-row > div{min-width:0;}
|
|
78
|
+
.notif-head{display:flex;justify-content:space-between;align-items:baseline;gap:.5rem;}
|
|
79
|
+
.notif-line{min-width:0;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2;line-clamp:2;overflow:hidden;}
|
|
80
|
+
.notif-time{flex:0 0 auto;white-space:nowrap;font-size:.72rem;color:var(--text-faint, var(--bs-secondary-color));}
|
|
81
|
+
.notif-context,
|
|
82
|
+
.notif-body{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-top:.15rem;
|
|
83
|
+
color:var(--text-soft, var(--bs-secondary-color));}
|
|
84
|
+
.notif-context{font-family:var(--font-mono, var(--bs-font-monospace));font-size:.72rem;}
|
|
85
|
+
.notif-body{font-size:.8rem;}
|
|
86
|
+
.notif-row.is-read .notif-context,
|
|
87
|
+
.notif-row.is-read .notif-body{color:var(--text-faint, var(--bs-secondary-color));}
|
|
88
|
+
|
|
71
89
|
/* ── Live page regions (assets/live.js, 0.5.0) ─────────────────────────────────────────────── */
|
|
72
90
|
.live-paused{opacity:.6;transition:opacity .2s;}
|
|
73
91
|
.live-new{background:rgba(var(--brand-rgb, var(--bs-primary-rgb)), .07);transition:background 2s;}
|
package/assets/bell.js
CHANGED
|
@@ -20,6 +20,14 @@
|
|
|
20
20
|
* refreshes belong on reconnect only (firstOpen === false), because the first
|
|
21
21
|
* open lands right after the page rendered.
|
|
22
22
|
*
|
|
23
|
+
* And one this file raises itself (0.7.0):
|
|
24
|
+
* 'aria:notif-goto' detail = { href } — a bell row was clicked whose link is THIS page (path and
|
|
25
|
+
* query equal; only the hash may differ). The dropdown is hidden and the row
|
|
26
|
+
* marked read in place; the page scrolls to / highlights the target. Read the
|
|
27
|
+
* target from detail.href, not location.hash: the event fires a task after the
|
|
28
|
+
* click, and whether the hash has moved by then is the browser's business. Needed
|
|
29
|
+
* because a click on the hash the page already has fires no 'hashchange'.
|
|
30
|
+
*
|
|
23
31
|
* Frame types listed in data-notif-quiet (comma-separated, e.g. "ticket,draft") do NOT re-sync
|
|
24
32
|
* the bell — a ticket reply cannot change the notification list, and draft frames fire while
|
|
25
33
|
* somebody is typing. Extra stream query params come from any page element carrying
|
|
@@ -40,8 +48,11 @@
|
|
|
40
48
|
* A dropped stream is announced as 'aria:sse-down' (assets/live.js shows "Live updates paused").
|
|
41
49
|
*
|
|
42
50
|
* XSS-safe by construction: rows are createElement/textContent, and only a same-origin PATH may
|
|
43
|
-
* become a row's href — a link that ever carried attacker-influenced text
|
|
44
|
-
*
|
|
51
|
+
* become a row's href — a link that ever carried attacker-influenced text would otherwise execute
|
|
52
|
+
* (javascript:) or leave the site on click. "Starts with one slash" is NOT that test: browsers
|
|
53
|
+
* read a backslash as a slash and drop tab/CR/LF while parsing, so /\evil.com, /<TAB>/evil.com
|
|
54
|
+
* and /<LF>/evil.com are all //evil.com. 0.7.0: the raw link may hold no control character,
|
|
55
|
+
* space or backslash, and it must RESOLVE to this page's origin.
|
|
45
56
|
*/
|
|
46
57
|
(function () {
|
|
47
58
|
'use strict';
|
|
@@ -73,8 +84,11 @@
|
|
|
73
84
|
var tokenMeta = document.querySelector('meta[name="csrf-token"]');
|
|
74
85
|
var csrf = tokenMeta ? tokenMeta.getAttribute('content') : '';
|
|
75
86
|
|
|
76
|
-
|
|
77
|
-
|
|
87
|
+
/** keepalive (the read POST): a click that navigates away must not cancel the request. */
|
|
88
|
+
function post(url, keepalive) {
|
|
89
|
+
var o = { method: 'POST', headers: { 'x-csrf-token': csrf }, credentials: 'same-origin' };
|
|
90
|
+
if (keepalive) o.keepalive = true;
|
|
91
|
+
return fetch(url, o);
|
|
78
92
|
}
|
|
79
93
|
|
|
80
94
|
function setBadge(n) {
|
|
@@ -83,21 +97,58 @@
|
|
|
83
97
|
}
|
|
84
98
|
|
|
85
99
|
function safeHref(link) {
|
|
86
|
-
|
|
100
|
+
if (typeof link !== 'string' || !/^\/(?!\/)/.test(link) || /[\x00-\x20\\]/.test(link)) return BASE;
|
|
101
|
+
try {
|
|
102
|
+
if (new URL(link, location.origin).origin !== location.origin) return BASE;
|
|
103
|
+
} catch (_) { return BASE; }
|
|
104
|
+
return link;
|
|
87
105
|
}
|
|
88
106
|
|
|
89
|
-
/**
|
|
107
|
+
/**
|
|
108
|
+
* "3m" over SQLite's UTC datetime('now') strings — the trailing Z is load-bearing. Short form
|
|
109
|
+
* since 0.7.0: it sits to the right of the title, so "now" / "3m" / "2h" / "1d".
|
|
110
|
+
*/
|
|
90
111
|
function relTime(iso) {
|
|
91
112
|
if (!iso) return '';
|
|
92
113
|
var t = Date.parse(String(iso).includes('T') ? iso : String(iso).replace(' ', 'T') + 'Z');
|
|
93
114
|
if (!Number.isFinite(t)) return '';
|
|
94
115
|
var s = Math.max(0, (Date.now() - t) / 1000);
|
|
95
|
-
if (s < 60) return '
|
|
96
|
-
if (s < 3600) return Math.floor(s / 60) + 'm
|
|
97
|
-
if (s < 86400) return Math.floor(s / 3600) + 'h
|
|
98
|
-
return Math.floor(s / 86400) + 'd
|
|
116
|
+
if (s < 60) return 'now';
|
|
117
|
+
if (s < 3600) return Math.floor(s / 60) + 'm';
|
|
118
|
+
if (s < 86400) return Math.floor(s / 3600) + 'h';
|
|
119
|
+
return Math.floor(s / 86400) + 'd';
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** One line of text: whitespace (newlines included) collapsed, trimmed, bounded. '' when empty. */
|
|
123
|
+
function oneLine(v) {
|
|
124
|
+
if (v == null) return '';
|
|
125
|
+
return String(v).replace(/\s+/g, ' ').trim().slice(0, 300);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function line(cls, text) {
|
|
129
|
+
var el = document.createElement('div');
|
|
130
|
+
el.className = cls;
|
|
131
|
+
el.textContent = text;
|
|
132
|
+
return el;
|
|
99
133
|
}
|
|
100
134
|
|
|
135
|
+
var current = null; // the last list rendered — a click marks its item read and re-renders
|
|
136
|
+
|
|
137
|
+
/** The dropdown, hidden — only when Bootstrap is there and owns an instance for the toggle. */
|
|
138
|
+
function hideMenu() {
|
|
139
|
+
var toggle = menu.querySelector('[data-bs-toggle="dropdown"]');
|
|
140
|
+
var bs = window.bootstrap;
|
|
141
|
+
var inst = toggle && bs && bs.Dropdown && bs.Dropdown.getInstance ? bs.Dropdown.getInstance(toggle) : null;
|
|
142
|
+
if (inst) inst.hide();
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Row shape (0.7.0):
|
|
147
|
+
* .notif-head .notif-line (.notif-who actor, .notif-what title) | .notif-time "1d"
|
|
148
|
+
* .notif-context item.context — one line, cut with an ellipsis (an app's "TBL-4821 · subject")
|
|
149
|
+
* .notif-body item.body, whitespace collapsed — one line, cut; absent when there is none
|
|
150
|
+
* .notif-who / .notif-what keep their names: an app's decorator may read them.
|
|
151
|
+
*/
|
|
101
152
|
function row(item) {
|
|
102
153
|
var a = document.createElement('a');
|
|
103
154
|
a.href = safeHref(item.link);
|
|
@@ -105,8 +156,10 @@
|
|
|
105
156
|
// that remaps .bg-light in dark mode made the tint the dropdown's own colour.
|
|
106
157
|
a.className = 'dropdown-item py-2 border-bottom notif-row ' + (item.is_read ? 'is-read' : 'is-unread');
|
|
107
158
|
|
|
159
|
+
var head = document.createElement('div');
|
|
160
|
+
head.className = 'notif-head';
|
|
108
161
|
var top = document.createElement('div');
|
|
109
|
-
top.className = 'small';
|
|
162
|
+
top.className = 'small notif-line';
|
|
110
163
|
if (item.actor_name) {
|
|
111
164
|
var who = document.createElement('span');
|
|
112
165
|
who.className = 'notif-who';
|
|
@@ -117,21 +170,52 @@
|
|
|
117
170
|
what.className = 'notif-what';
|
|
118
171
|
what.textContent = item.title || '';
|
|
119
172
|
top.appendChild(what);
|
|
120
|
-
|
|
173
|
+
head.appendChild(top);
|
|
174
|
+
var when = document.createElement('span');
|
|
175
|
+
when.className = 'notif-time';
|
|
176
|
+
when.textContent = relTime(item.created_at);
|
|
177
|
+
head.appendChild(when);
|
|
178
|
+
a.appendChild(head);
|
|
121
179
|
|
|
122
|
-
var
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
a.appendChild(meta);
|
|
180
|
+
var context = oneLine(item.context);
|
|
181
|
+
if (context) a.appendChild(line('notif-context', context));
|
|
182
|
+
var body = oneLine(item.body);
|
|
183
|
+
if (body) a.appendChild(line('notif-body', body));
|
|
127
184
|
|
|
128
|
-
a.addEventListener('click', function () {
|
|
129
|
-
if (!item.is_read) {
|
|
185
|
+
a.addEventListener('click', function (ev) {
|
|
186
|
+
if (!item.is_read) {
|
|
187
|
+
// At once, in the list: the server sends no frame on read, and a link to the page already
|
|
188
|
+
// open (/tickets/7#msg-3) is a hash jump — no reload — so without this the row stays
|
|
189
|
+
// under New. Then the POST, then a sync for the server's own word.
|
|
190
|
+
item.is_read = 1;
|
|
191
|
+
a.classList.remove('is-unread');
|
|
192
|
+
a.classList.add('is-read');
|
|
193
|
+
if (current) {
|
|
194
|
+
current.unread = Math.max(0, (Number(current.unread) || 0) - 1);
|
|
195
|
+
setBadge(current.unread);
|
|
196
|
+
}
|
|
197
|
+
post(BASE + '/' + item.id + '/read', true).then(sync).catch(function () {});
|
|
198
|
+
}
|
|
199
|
+
// A modified or non-primary click opens a new tab or window (or downloads): this page stays
|
|
200
|
+
// where it is, so the menu stays open and the page is not told to jump. Read still applies.
|
|
201
|
+
var plain = !(ev && (ev.ctrlKey || ev.metaKey || ev.shiftKey || ev.altKey || ev.button));
|
|
202
|
+
var samePage = plain && a.pathname === location.pathname && a.search === location.search;
|
|
203
|
+
if (samePage) hideMenu();
|
|
204
|
+
// A task later (navigation continues; the clicked element must still be in the list while
|
|
205
|
+
// the browser follows it): regroup the list, and tell the page which link was followed.
|
|
206
|
+
// A same-hash click fires no hashchange, so 'aria:notif-goto' is the page's only signal.
|
|
207
|
+
setTimeout(function () {
|
|
208
|
+
if (current) render(current);
|
|
209
|
+
if (samePage) {
|
|
210
|
+
document.dispatchEvent(new CustomEvent('aria:notif-goto', { detail: { href: a.getAttribute('href') } }));
|
|
211
|
+
}
|
|
212
|
+
}, 0);
|
|
130
213
|
});
|
|
131
214
|
return a;
|
|
132
215
|
}
|
|
133
216
|
|
|
134
217
|
function render(data) {
|
|
218
|
+
current = data;
|
|
135
219
|
setBadge(data.unread || 0);
|
|
136
220
|
list.textContent = '';
|
|
137
221
|
if (!data.items || !data.items.length) {
|
package/assets/live.js
CHANGED
|
@@ -29,7 +29,8 @@
|
|
|
29
29
|
* page that CAUSED it"). A submit a script prevented is not a navigation and sets nothing.
|
|
30
30
|
*
|
|
31
31
|
* "LIVE UPDATES PAUSED": a strip above the first region, with a Refresh button, when the stream
|
|
32
|
-
* drops (aria:sse-down) or is stopped (a live-stop frame — "too many open tabs" for too_many
|
|
32
|
+
* drops (aria:sse-down) or is stopped (a live-stop frame — "too many open tabs" for too_many, and
|
|
33
|
+
* "Live updates are off" for `off`, the reason an app gives when it has switched live pages off); the
|
|
33
34
|
* regions are dimmed. It clears on the next open, which also catches the regions up. A hidden tab
|
|
34
35
|
* closes its stream on purpose (bell.js) and shows no strip.
|
|
35
36
|
*/
|
|
@@ -89,9 +90,13 @@
|
|
|
89
90
|
strip.appendChild(btn);
|
|
90
91
|
REGIONS[0].parentNode.insertBefore(strip, REGIONS[0]);
|
|
91
92
|
}
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
93
|
+
// 'off' (0.5.1): the APP switched live updates off (an installation-wide switch, the live-updates plan's D8) and
|
|
94
|
+
// refused the page's topics for that reason — nothing is paused that will resume, so the strip says so.
|
|
95
|
+
strip.querySelector('[data-live-strip-words]').textContent = reason === 'off'
|
|
96
|
+
? 'Live updates are off. Refresh to see changes.'
|
|
97
|
+
: (reason === 'too_many' || reason === 'evicted')
|
|
98
|
+
? 'Live updates paused: too many open tabs. Close one and refresh, or refresh to see changes.'
|
|
99
|
+
: 'Live updates paused. Refresh to see changes.';
|
|
95
100
|
strip.hidden = false;
|
|
96
101
|
REGIONS.forEach(function (r) { r.classList.add('live-paused'); });
|
|
97
102
|
}
|
package/hub.js
CHANGED
|
@@ -36,6 +36,13 @@
|
|
|
36
36
|
* and the hook's answer is reused for at most `recheckMs`, so a revoked session gets
|
|
37
37
|
* at most that long of contentless nudges (each of whose re-fetches its own route
|
|
38
38
|
* refuses). Anything but `true` is no frame; a throw is a stop.
|
|
39
|
+
*
|
|
40
|
+
* 0.6.0 — AUDIENCES. A stream carries an audience: `staff` (the default — every caller from before
|
|
41
|
+
* 0.6.0) or one named in `limits.perAudience` (`contact`, a customer portal's contacts). A named
|
|
42
|
+
* audience has a cap of its own INSIDE `perProcess` (default `contact`: 40 % of it, 400 of 1000), so
|
|
43
|
+
* however many contacts open tabs, staff keep `perProcess` − the named caps in reserve. Over its cap a
|
|
44
|
+
* new stream of that audience is refused `busy`, like the process cap — never another audience's
|
|
45
|
+
* stream evicted (two contacts of two partners are strangers; one's tab must not end the other's).
|
|
39
46
|
*/
|
|
40
47
|
|
|
41
48
|
'use strict';
|
|
@@ -53,8 +60,12 @@ const LIMITS = Object.freeze({
|
|
|
53
60
|
bellPerUser: 20, // BELL-ONLY streams one user may hold (counted apart: a bell is never evicted for a live tab)
|
|
54
61
|
perProcess: 1000, // streams this process holds in all
|
|
55
62
|
topicsPerStream: 8, // `type:id` keys one stream may watch
|
|
56
|
-
lifetimeMs: 60 * 60 * 1000
|
|
63
|
+
lifetimeMs: 60 * 60 * 1000, // a stream is renewed after this, so a scope cannot live forever
|
|
64
|
+
// Caps for the named audiences (0.6.0), each INSIDE perProcess. A hub that does not set one gets it as the same
|
|
65
|
+
// SHARE of its own perProcess (contact: 40 % — so a hub that raises perProcess raises both halves).
|
|
66
|
+
perAudience: Object.freeze({ contact: 400 })
|
|
57
67
|
});
|
|
68
|
+
const DEFAULT_AUDIENCE = 'staff';
|
|
58
69
|
const RECHECK_MS = 5000; // an authorise answer is reused for at most this long
|
|
59
70
|
const COALESCE_MS = 750; // publishSoon(): one frame per topic per this window
|
|
60
71
|
|
|
@@ -66,12 +77,34 @@ function positive(v, name) {
|
|
|
66
77
|
return n;
|
|
67
78
|
}
|
|
68
79
|
|
|
80
|
+
/**
|
|
81
|
+
* The named audiences' caps. Each given value must be positive, or 0 for "this audience off"; a default not given is the default's share of this hub's
|
|
82
|
+
* perProcess (floored — at a perProcess of 2 the contact cap is 0, i.e. no contact stream at all). The named caps
|
|
83
|
+
* together must leave the default audience at least one stream, or the reserve this exists for is not there.
|
|
84
|
+
*/
|
|
85
|
+
function audienceCaps(given, perProcess) {
|
|
86
|
+
if (given !== undefined && (given === null || typeof given !== 'object' || Array.isArray(given))) {
|
|
87
|
+
throw new Error(`notify: createHub limit perAudience must be an object of audience: cap (got ${JSON.stringify(given)})`);
|
|
88
|
+
}
|
|
89
|
+
const out = {};
|
|
90
|
+
for (const [a, n] of Object.entries(LIMITS.perAudience)) out[a] = Math.floor(perProcess * n / LIMITS.perProcess);
|
|
91
|
+
for (const [a, n] of Object.entries(given || {})) {
|
|
92
|
+
if (a === DEFAULT_AUDIENCE) throw new Error(`notify: createHub limit perAudience.${a} — ${DEFAULT_AUDIENCE} is the reserve the other caps protect, and is capped only by perProcess`);
|
|
93
|
+
if (n === undefined) continue;
|
|
94
|
+
out[a] = n === 0 ? 0 : positive(n, `perAudience.${a}`); // 0: that audience off (no stream), as a derived 0 is
|
|
95
|
+
}
|
|
96
|
+
const named = Object.values(out).reduce((x, y) => x + y, 0);
|
|
97
|
+
if (named >= perProcess) throw new Error(`notify: createHub limits perAudience (${named} in all) must be below perProcess (${perProcess}), so ${DEFAULT_AUDIENCE} keep a reserve`);
|
|
98
|
+
return Object.freeze(out);
|
|
99
|
+
}
|
|
100
|
+
|
|
69
101
|
function createHub({
|
|
70
102
|
heartbeatMs = HEARTBEAT_MS, limits = {}, authorize = null, recheckMs = RECHECK_MS,
|
|
71
103
|
coalesceMs = COALESCE_MS, now = () => Date.now(), logger = console
|
|
72
104
|
} = {}) {
|
|
73
105
|
const L = {};
|
|
74
|
-
for (const k of Object.keys(LIMITS)) L[k] = positive(limits[k] === undefined ? LIMITS[k] : limits[k], k);
|
|
106
|
+
for (const k of Object.keys(LIMITS)) if (k !== 'perAudience') L[k] = positive(limits[k] === undefined ? LIMITS[k] : limits[k], k);
|
|
107
|
+
L.perAudience = audienceCaps(limits.perAudience, L.perProcess);
|
|
75
108
|
if (authorize !== null && typeof authorize !== 'function') throw new Error('notify: authorize must be a function');
|
|
76
109
|
const RECHECK = Math.max(0, Number(recheckMs) || 0);
|
|
77
110
|
|
|
@@ -81,6 +114,7 @@ function createHub({
|
|
|
81
114
|
const sessions = new Map(); // session id -> Set(res) live streams only, oldest first
|
|
82
115
|
const liveUsers = new Map(); // userId -> Set(res) live streams only, oldest first
|
|
83
116
|
const bellUsers = new Map(); // userId -> Set(res) bell-only streams, oldest first
|
|
117
|
+
const audiences = new Map(); // audience -> Set(res) every open stream, by audience
|
|
84
118
|
const soon = new Map(); // "type:id" -> coalescing timer
|
|
85
119
|
let heartbeat = null;
|
|
86
120
|
|
|
@@ -151,12 +185,20 @@ function createHub({
|
|
|
151
185
|
return noop;
|
|
152
186
|
}
|
|
153
187
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
188
|
+
const held = (a) => (audiences.get(a) || new Set()).size;
|
|
189
|
+
const heldAll = () => [DEFAULT_AUDIENCE, ...Object.keys(L.perAudience)].map((a) => `${a} ${held(a)}`).join(', ');
|
|
190
|
+
|
|
191
|
+
// Once a minute PER CAP AND AUDIENCE, not once per refusal: a client retrying in a loop must not fill the log — and
|
|
192
|
+
// contacts refused at their own cap must not hide the line that says staff are being refused too.
|
|
193
|
+
const busyLogged = new Map();
|
|
194
|
+
function logBusy(which, audience) {
|
|
195
|
+
const k = `${which}:${audience}`;
|
|
196
|
+
if (now() - (busyLogged.has(k) ? busyLogged.get(k) : -Infinity) < 60000) return;
|
|
197
|
+
busyLogged.set(k, now());
|
|
198
|
+
const msg = which === 'audience'
|
|
199
|
+
? `notify: the ${audience} stream cap (${L.perAudience[audience]} of ${L.perProcess} per process) is reached — new ${audience} streams are refused; other audiences are unaffected (held: ${heldAll()})`
|
|
200
|
+
: `notify: the stream cap (${L.perProcess} per process) is reached — new streams are refused (this one: audience ${audience}; held: ${heldAll()})`;
|
|
201
|
+
try { logger.warn(msg); } catch (_) { /* noop */ }
|
|
160
202
|
}
|
|
161
203
|
|
|
162
204
|
/**
|
|
@@ -164,10 +206,13 @@ function createHub({
|
|
|
164
206
|
*
|
|
165
207
|
* @param {number} userId
|
|
166
208
|
* @param {object} res
|
|
167
|
-
* @param {{entity?: {type, id}, topics?: {type, id}[], sessionId?: string, meta?: any}} [opts]
|
|
209
|
+
* @param {{entity?: {type, id}, topics?: {type, id}[], sessionId?: string, meta?: any, audience?: string}} [opts]
|
|
168
210
|
* `entity` and `topics` are both entity keys; `sessionId` is counted for the per-session
|
|
169
211
|
* cap and handed to `authorize`, as is `meta` (whatever the app needs to re-judge — the
|
|
170
|
-
* scope the page was rendered for, say). Neither is ever sent to the client.
|
|
212
|
+
* scope the page was rendered for, say). Neither is ever sent to the client. `audience`
|
|
213
|
+
* (0.6.0) is `staff` when absent, else must name a `limits.perAudience` cap — an unknown one
|
|
214
|
+
* THROWS, because a misspelt `'contacts'` counted as nobody's would be the uncapped stream
|
|
215
|
+
* the cap exists to stop.
|
|
171
216
|
* @returns {function} unsubscribe — removes from EVERY map. When the stream was refused (a cap)
|
|
172
217
|
* it has been told `live-stop` and ended, and the function is a no-op carrying `.refused`.
|
|
173
218
|
*
|
|
@@ -179,24 +224,39 @@ function createHub({
|
|
|
179
224
|
const uid = Number(userId);
|
|
180
225
|
const keys = keysOf(opts);
|
|
181
226
|
const sid = opts.sessionId == null || opts.sessionId === '' ? null : String(opts.sessionId);
|
|
227
|
+
const audience = opts.audience == null ? DEFAULT_AUDIENCE : opts.audience;
|
|
228
|
+
if (audience !== DEFAULT_AUDIENCE && !Object.prototype.hasOwnProperty.call(L.perAudience, audience)) {
|
|
229
|
+
throw new Error(`notify: subscribe audience ${JSON.stringify(audience)} is neither ${DEFAULT_AUDIENCE} nor one of limits.perAudience (${Object.keys(L.perAudience).join(', ')})`);
|
|
230
|
+
}
|
|
182
231
|
if (keys.length > L.topicsPerStream) return refused(res, 'too_many_topics');
|
|
183
232
|
const isLive = keys.length > 0;
|
|
184
233
|
// A BELL-ONLY stream is capped per USER (never per session: the bell is per person), before the process cap, so one
|
|
185
234
|
// user opening bells in a loop evicts their own oldest instead of filling the process and starving everyone else.
|
|
186
235
|
if (!isLive) while ((bellUsers.get(uid) || new Set()).size >= L.bellPerUser) evict(bellUsers.get(uid).values().next().value);
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
236
|
+
// A LIVE stream likewise evicts the OLDEST of its own session and user BEFORE the caps below (0.6.0; in 0.5.x it came
|
|
237
|
+
// after them): never refuse the newest — the tab a person just opened is the one they are looking at — and a person
|
|
238
|
+
// at their own limit frees the place their new tab takes, so a full audience or process does not refuse them busy.
|
|
239
|
+
// Each evicted stream is the same person's, so it frees a place in the same audience — which holds as long as a user
|
|
240
|
+
// id and a session id each belong to ONE audience (the hub's contact keys are negative; staff ids are not).
|
|
191
241
|
if (isLive) {
|
|
192
|
-
// EVICT THE OLDEST, never refuse the newest: the tab a person just opened is the one they are looking at.
|
|
193
242
|
if (sid) while ((sessions.get(sid) || new Set()).size >= L.perSession) evict(sessions.get(sid).values().next().value);
|
|
194
243
|
while ((liveUsers.get(uid) || new Set()).size >= L.perUser) evict(liveUsers.get(uid).values().next().value);
|
|
195
244
|
}
|
|
245
|
+
// A NAMED AUDIENCE AT ITS CAP is refused, never served by evicting a stream of someone else in it. Checked before the
|
|
246
|
+
// process cap so the log names the cap that actually refused it. The default audience has no cap of its own here.
|
|
247
|
+
if (audience !== DEFAULT_AUDIENCE && held(audience) >= L.perAudience[audience]) {
|
|
248
|
+
logBusy('audience', audience);
|
|
249
|
+
return refused(res, 'busy');
|
|
250
|
+
}
|
|
251
|
+
if (subs.size >= L.perProcess) {
|
|
252
|
+
logBusy('process', audience);
|
|
253
|
+
return refused(res, 'busy');
|
|
254
|
+
}
|
|
196
255
|
|
|
197
|
-
const sub = { userId: uid, sessionId: sid, keys, meta: opts.meta, verdicts: new Map(), closed: false, timer: null, unsubscribe: null };
|
|
256
|
+
const sub = { userId: uid, sessionId: sid, audience, keys, meta: opts.meta, verdicts: new Map(), closed: false, timer: null, unsubscribe: null };
|
|
198
257
|
subs.set(res, sub);
|
|
199
258
|
add(users, uid, res);
|
|
259
|
+
add(audiences, audience, res);
|
|
200
260
|
for (const k of keys) add(entities, k, res);
|
|
201
261
|
if (isLive && sid) add(sessions, sid, res);
|
|
202
262
|
if (isLive) add(liveUsers, uid, res); else add(bellUsers, uid, res);
|
|
@@ -208,6 +268,7 @@ function createHub({
|
|
|
208
268
|
if (sub.timer) { clearTimeout(sub.timer); sub.timer = null; }
|
|
209
269
|
subs.delete(res);
|
|
210
270
|
remove(users, uid, res);
|
|
271
|
+
remove(audiences, audience, res);
|
|
211
272
|
for (const k of keys) remove(entities, k, res);
|
|
212
273
|
if (isLive && sid) remove(sessions, sid, res);
|
|
213
274
|
if (isLive) remove(liveUsers, uid, res); else remove(bellUsers, uid, res);
|
|
@@ -333,9 +394,12 @@ function createHub({
|
|
|
333
394
|
return { users: users.size, entities: entities.size };
|
|
334
395
|
}
|
|
335
396
|
|
|
336
|
-
/** The live layer's counts (0.5.0), beside stats(): open streams, sessions holding one, and the caps. */
|
|
397
|
+
/** The live layer's counts (0.5.0), beside stats(): open streams, sessions holding one, streams by audience (0.6.0), and the caps. */
|
|
337
398
|
function streamStats() {
|
|
338
|
-
|
|
399
|
+
const byAudience = {};
|
|
400
|
+
for (const a of [DEFAULT_AUDIENCE, ...Object.keys(L.perAudience)]) byAudience[a] = held(a);
|
|
401
|
+
return { streams: subs.size, sessions: sessions.size, topics: entities.size, audiences: byAudience,
|
|
402
|
+
limits: { ...L, perAudience: { ...L.perAudience }, recheckMs: RECHECK } };
|
|
339
403
|
}
|
|
340
404
|
|
|
341
405
|
/**
|
|
@@ -366,9 +430,10 @@ function createHub({
|
|
|
366
430
|
sessions.clear();
|
|
367
431
|
liveUsers.clear();
|
|
368
432
|
bellUsers.clear();
|
|
433
|
+
audiences.clear();
|
|
369
434
|
}
|
|
370
435
|
|
|
371
436
|
return { subscribe, pushUsers, pushEntity, publish, publishSoon, watched, stats, streamStats, closeAll };
|
|
372
437
|
}
|
|
373
438
|
|
|
374
|
-
module.exports = { createHub, HEARTBEAT_MS, LIMITS, RECHECK_MS, COALESCE_MS };
|
|
439
|
+
module.exports = { createHub, HEARTBEAT_MS, LIMITS, DEFAULT_AUDIENCE, RECHECK_MS, COALESCE_MS };
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aria-framework/notify",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Aria App Framework — notify module. In-app notifications: ownership-scoped rows, a per-process SSE hub for live delivery (with topics, caps and a per-event authorise hook for live pages), and a fire-and-forget emitter that needs no request and no actor, so a scheduler can raise one.",
|
|
3
|
+
"version": "0.7.0",
|
|
4
|
+
"description": "Aria App Framework — notify module. In-app notifications: ownership-scoped rows, a per-process SSE hub for live delivery (with topics, caps per session, user, audience and process, and a per-event authorise hook for live pages), and a fire-and-forget emitter that needs no request and no actor, so a scheduler can raise one.",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"private": false,
|
|
7
7
|
"publishConfig": {
|
|
@@ -14,7 +14,8 @@
|
|
|
14
14
|
"hub.js",
|
|
15
15
|
"emit.js",
|
|
16
16
|
"assets/",
|
|
17
|
-
"views/"
|
|
17
|
+
"views/",
|
|
18
|
+
"CHANGELOG.md"
|
|
18
19
|
],
|
|
19
20
|
"peerDependencies": {
|
|
20
21
|
"better-sqlite3": ">=11"
|
|
@@ -28,7 +29,7 @@
|
|
|
28
29
|
"jsdom": "^30.0.1"
|
|
29
30
|
},
|
|
30
31
|
"scripts": {
|
|
31
|
-
"test": "node test/store.js && node test/schema-parity.js && node test/hub.js && node test/live-hub.js && node test/emit.js && node test/bell.js && node test/live-client.js",
|
|
32
|
+
"test": "node test/store.js && node test/schema-parity.js && node test/hub.js && node test/live-hub.js && node test/emit.js && node test/bell.js && node test/bell-rows.js && node test/live-client.js",
|
|
32
33
|
"prepublishOnly": "node ../../test/packaging.js notify"
|
|
33
34
|
}
|
|
34
35
|
}
|
package/store.js
CHANGED
|
@@ -60,6 +60,9 @@ function schemaFor(dialect) {
|
|
|
60
60
|
/** The SQLite schema, unchanged, for consumers that predate schemaFor(). */
|
|
61
61
|
const SCHEMA = schemaFor(null);
|
|
62
62
|
|
|
63
|
+
/** The longest title extendUnread() will make (characters). Longer: it changes nothing. */
|
|
64
|
+
const TITLE_MAX = 500;
|
|
65
|
+
|
|
63
66
|
/**
|
|
64
67
|
* @param {Function} getDb returns the better-sqlite3 handle. A function, not a handle, because
|
|
65
68
|
* the worker opens the database after modules are required.
|
|
@@ -108,6 +111,7 @@ function createStore(opts = {}) {
|
|
|
108
111
|
return {
|
|
109
112
|
SCHEMA,
|
|
110
113
|
schemaFor,
|
|
114
|
+
TITLE_MAX,
|
|
111
115
|
table: T,
|
|
112
116
|
|
|
113
117
|
/**
|
|
@@ -116,25 +120,72 @@ function createStore(opts = {}) {
|
|
|
116
120
|
* Returns the ids actually written so the caller can hand them to the hub. De-duplicated,
|
|
117
121
|
* because "the assignee" and "a collaborator" are frequently the same person and two bells
|
|
118
122
|
* for one event reads as a bug.
|
|
123
|
+
*
|
|
124
|
+
* 0.7.0: also `rows: [{ userId, id }]`, each recipient's NEW row id, in `userIds` order — so a
|
|
125
|
+
* caller that later wants to extendUnread() its row has the id without reading it back.
|
|
126
|
+
* Additive: `userIds` is unchanged.
|
|
119
127
|
*/
|
|
120
128
|
async createMany(userIds, p = {}) {
|
|
121
129
|
const ids = [...new Set((userIds || []).filter((v) => v != null).map(Number))]
|
|
122
130
|
.filter((n) => Number.isInteger(n));
|
|
123
131
|
// A notification with no type or no title has nothing to show; refusing quietly is right
|
|
124
132
|
// because the caller is fire-and-forget and must not learn about this through a throw.
|
|
125
|
-
if (!ids.length || !p.type || !p.title) return { userIds: [] };
|
|
133
|
+
if (!ids.length || !p.type || !p.title) return { userIds: [], rows: [] };
|
|
126
134
|
|
|
135
|
+
const rows = [];
|
|
127
136
|
await driver.transaction(async (tx) => {
|
|
128
137
|
for (const uid of ids) {
|
|
129
|
-
|
|
138
|
+
// returning('id') is empty on SQLite (the id arrives out of band) and RETURNING "id" on
|
|
139
|
+
// Postgres; either way the driver reports it as lastId.
|
|
140
|
+
const r = await tx.run(
|
|
130
141
|
`INSERT INTO ${T} (user_id, type, title, body, link, actor_name, entity_type, entity_id)
|
|
131
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
142
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)${d().returning('id')}`,
|
|
132
143
|
[uid, p.type, p.title, p.body || null, p.link || null,
|
|
133
144
|
p.actor_name || null, p.entity_type || null, p.entity_id || null]
|
|
134
145
|
);
|
|
146
|
+
rows.push({ userId: uid, id: Number(r.lastId) });
|
|
135
147
|
}
|
|
136
148
|
});
|
|
137
|
-
return { userIds: ids };
|
|
149
|
+
return { userIds: ids, rows };
|
|
150
|
+
},
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Grow an UNREAD row's title — "changed status to open" becomes "changed status to open,
|
|
154
|
+
* changed priority from medium to high" — and move its time up to now (0.7.0).
|
|
155
|
+
*
|
|
156
|
+
* ONE statement, guarded three ways: the row must be `id`, belong to `userId` (the
|
|
157
|
+
* ownership scope — see the top of this file) and still be unread. A row read a moment ago
|
|
158
|
+
* is never touched, so a caller cannot rewrite something its reader has already seen.
|
|
159
|
+
*
|
|
160
|
+
* THE TITLE IS CAPPED at TITLE_MAX (500) characters: when the grown title would be longer,
|
|
161
|
+
* nothing changes and this returns false — exactly as for a read row, so the caller's
|
|
162
|
+
* fallback (write a new row for the follow-up) covers both. A title is never cut mid-word.
|
|
163
|
+
*
|
|
164
|
+
* `opts.at` (optional, for a test's clock): the new created_at as UTC text,
|
|
165
|
+
* 'YYYY-MM-DD HH:MM:SS' — the format the column holds. Default: the database's clock
|
|
166
|
+
* (dialect now()). Anything else throws: a wrong-format time would sort wrongly, silently.
|
|
167
|
+
*
|
|
168
|
+
* Returns true when a row changed, false otherwise (not yours, read, gone, too long, or
|
|
169
|
+
* nothing to append). Both engines: `||`, CAST(? AS TEXT) and LENGTH() are common SQL; the
|
|
170
|
+
* casts are there because Postgres cannot type a bare parameter inside LENGTH().
|
|
171
|
+
*/
|
|
172
|
+
async extendUnread(id, userId, opts = {}) {
|
|
173
|
+
opts = opts || {};
|
|
174
|
+
const more = opts.appendTitle == null ? '' : String(opts.appendTitle);
|
|
175
|
+
const sep = opts.sep == null ? ', ' : String(opts.sep);
|
|
176
|
+
if (!more.trim()) return false;
|
|
177
|
+
if (!Number.isInteger(Number(id)) || !Number.isInteger(Number(userId))) return false;
|
|
178
|
+
const at = opts.at == null ? null : String(opts.at);
|
|
179
|
+
if (at !== null && !/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(at)) {
|
|
180
|
+
throw new TypeError("notify: extendUnread opts.at must be UTC text 'YYYY-MM-DD HH:MM:SS'");
|
|
181
|
+
}
|
|
182
|
+
const r = await driver.run(
|
|
183
|
+
`UPDATE ${T} SET title = title || CAST(? AS TEXT) || CAST(? AS TEXT),
|
|
184
|
+
created_at = ${at === null ? d().now() : 'CAST(? AS TEXT)'}
|
|
185
|
+
WHERE id = ? AND user_id = ? AND is_read = 0
|
|
186
|
+
AND LENGTH(title) + LENGTH(CAST(? AS TEXT)) + LENGTH(CAST(? AS TEXT)) <= ${TITLE_MAX}`,
|
|
187
|
+
[sep, more, ...(at === null ? [] : [at]), Number(id), Number(userId), sep, more]);
|
|
188
|
+
return Number(r.changes) === 1;
|
|
138
189
|
},
|
|
139
190
|
|
|
140
191
|
unreadCount,
|
|
@@ -179,4 +230,4 @@ function createStore(opts = {}) {
|
|
|
179
230
|
};
|
|
180
231
|
}
|
|
181
232
|
|
|
182
|
-
module.exports = { createStore, SCHEMA, schemaFor };
|
|
233
|
+
module.exports = { createStore, SCHEMA, schemaFor, TITLE_MAX };
|