@aria-framework/notify 0.4.0 → 0.6.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/README.md CHANGED
@@ -131,3 +131,130 @@ has:
131
131
 
132
132
  Colours come from @aria-framework/theme's tokens (`--brand-rgb`, `--text`, `--text-faint`), with
133
133
  Bootstrap's variables as the fallback.
134
+
135
+ ## Live pages (0.5.0)
136
+
137
+ A page that should follow a running job or a list as it changes rides the bell's stream — **no new
138
+ connection, no new channel**. It is the entities channel above, with three additions.
139
+
140
+ **Topics.** A stream may watch up to 8 `type:id` keys, not just one record. A topic is an entity key
141
+ that names something wider than a record: `ask-bench:house` (a running job), `work:p3` (partner 3's
142
+ queue), `work:c12` (one customer's). The frame is still `{type, id}` and nothing else.
143
+
144
+ ```js
145
+ // main — the hub with the per-event check (below)
146
+ const hub = notify.createHub({ authorize });
147
+
148
+ // the stream route: topics the app has checked at attach, and the session for the caps
149
+ hub.subscribe(userId, res, { topics: [{ type: 'work', id: 'p3' }], sessionId: req.sessionID, meta: { ctx } });
150
+
151
+ // a write — on the main thread, after db.invoke returned
152
+ hub.publishSoon('work', 'p3'); // coalesced: one frame per topic per 750 ms
153
+ ```
154
+
155
+ **Caps.** 6 LIVE streams (streams watching a topic) per session, 12 per user, 1000 streams of any kind per
156
+ process, 8 topics per stream (`LIMITS`; `createHub({ limits })` changes them, none can be switched off). A
157
+ bell-only stream is not under the live caps, so the bell never loses to a seventh tab; bell-only streams have
158
+ their own cap, 20 per USER (`bellPerUser`), so one user cannot fill the process and starve everyone else — over it
159
+ 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
+ half-open stream a sleeping laptop left behind. Too many topics or a full process refuse the new stream
161
+ (`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
+ topics, so the bell goes on; a bell-only stream that is stopped is not reopened. A stream lives 60 minutes, then
163
+ is told `live-renew` and ended; bell.js reopens it at once, the page catches up, and the new stream is judged
164
+ afresh, so no scope outlives it. `publishSoon` arms nothing for a topic nobody watches.
165
+
166
+ **The per-event check.** `createHub({ authorize })` — `async ({ userId, sessionId, topic, meta }) =>
167
+ true | false | { stop: reason }`. A frame reaches a subscription only when it answered exactly
168
+ `true`; `false` (or anything else) drops that frame; `{stop}` or a throw ends the stream with that
169
+ reason (`check_failed` for a throw). The answer is reused for at most 5 s (`recheckMs`) per
170
+ subscription and topic, so a burst of fifty events costs one session-store read — and a revoked
171
+ session gets at most 5 s of contentless nudges, each of whose re-fetches its own route refuses. The
172
+ app decides what "may still see" means: re-read the STORED session (signed out, idle, session
173
+ version, act-as switched), and the topic's permission at that scope. That is two locks: the check
174
+ decides who is nudged, and the route's RBAC and RLS still decide what they see.
175
+
176
+ **The client.** Load `assets/live.js` after `bell.js`. A region is an element with an `id` and
177
+ `data-live-topic="type:id …"`; on a frame for one of its topics the page is re-fetched **through its own URL**
178
+ (or that region's own `data-live-src`) and the region replaced by the element with the same id in the answer —
179
+ an answer without it (a sign-in page) changes nothing. The re-fetch carries `X-Live-Fragment: 1`, which
180
+ @aria-framework/auth 0.16.0 lets through WITHOUT counting as activity, so a page left open still idles out. A
181
+ region a person is working in is HELD, not swapped: the focus anywhere inside it, an open modal (`.modal.show`), or
182
+ a control or details/dialog open state that differs from the region's BASELINE — its state when live.js started, at
183
+ DOMContentLoaded and load (for a region nobody is in: a page script setting a value is not work) and after every swap.
184
+ Not the HTML defaults: a `<select>` with no `selected` option, a script-set value and a server-drawn
185
+ `<details open>` are not work. It is re-checked every 2 s, and a held region stays held through a submit that did
186
+ not navigate. Every swap is announced as
187
+ `aria:live-swapped` (`{ id, el }`) so scripts can re-bind (@aria-framework/server 0.17.0's pager and bulk select
188
+ listen on the document and need nothing). `data-live-list` makes it a list of `[data-row-id]` rows (the marker may
189
+ sit on the row or its first cell): with `data-live-insert` (draw it on page 1, default sort, no filter) and nothing
190
+ ticked, new rows are put in and marked New; otherwise a bar says "N new. Show them". Every reconnect catches every
191
+ 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 — or, when the app refused the topics with the reason `off` (0.5.1: its installation-wide switch),
193
+ "Live updates are off". Frames that arrive after this page submitted a form are ignored (the mid-navigation trap above)
194
+ until the page navigates — or, for a submit that does not (a download, `target=_blank`), until it is visible again
195
+ or 8 s pass; a submit a script prevented is not a navigation.
196
+
197
+ Still one process: a write in another process (an ingest server, a node server) reaches no stream
198
+ here. Such a page needs a re-check in the web process, or a shared bus — neither is in this module.
199
+
200
+ ## Audiences (0.6.0)
201
+
202
+ A stream carries an **audience**. `staff` is the default — a `subscribe` that passes none is exactly what it was in
203
+ 0.5.1 — and any other audience must be named in `limits.perAudience`, which gives it a cap of its own **inside**
204
+ `perProcess`. The one named by default is `contact`, for a customer portal's contacts:
205
+
206
+ ```js
207
+ // a portal contact's stream: counted under the contact cap, never against staff's reserve
208
+ hub.subscribe(contactKey, res, { topics, sessionId, meta, audience: 'contact' });
209
+ ```
210
+
211
+ **Why.** One process cap shared by everyone lets one audience starve another: at 12 live streams each, about 84
212
+ contacts with tabs open fill 1000 streams, and every staff bell and live page after that is told `busy`. With
213
+ `perAudience: { contact: N }`, contacts can never hold more than N, so staff always keep `perProcess` − N.
214
+
215
+ **The default: 400 of 1000 (40 %).** Staff keep 600 — every staff member's bell plus a handful of live tabs, for well
216
+ over a hundred staff at once, far beyond any team these apps serve — while contacts get 400 streams: at the two or
217
+ three tabs a portal visit actually opens, more than a hundred contacts on the portal at the same moment, and about
218
+ five times the 84 that fill the process today. A hub that sets `perProcess` and not `perAudience` gets the same 40 %
219
+ of its own total (floored: at `perProcess: 2000` contacts get 800; at `perProcess: 2` they get 0). An explicit
220
+ `perAudience` value is merged over the default per audience, and an explicit `0` means that audience is off: every
221
+ stream of it is refused `busy`, exactly as a derived 0 is.
222
+
223
+ **The rules.**
224
+
225
+ - A named audience at its cap is **refused** (`live-stop busy`), like the process cap. It never evicts: the
226
+ per-session and per-user caps evict the OLDEST stream of the SAME session or person, but the streams under an
227
+ audience cap belong to other people — two contacts of two partners — and one's new tab must not end another's.
228
+ - **A person at their own limit is never refused for it.** The per-session and per-user evictions run BEFORE the
229
+ audience and process caps (0.6.0; in 0.5.x they ran after, so a person holding six tabs while the process was
230
+ full was told `busy` instead of losing their oldest). Their own oldest goes, which frees the place the new tab
231
+ takes in the same audience, so a contact at the contact cap or a staff member at a full process keeps working.
232
+ That holds while a user id and a session id each belong to one audience; the hub's contact keys are negative and
233
+ never a staff id.
234
+ - Staff are never refused because of contacts. Staff are refused only when the whole process is full, and that
235
+ needs staff themselves to hold at least `perProcess` − the named caps. Staff may use room a named audience leaves
236
+ idle; a named audience under its own cap is still refused when the process is full.
237
+ - The warn names the audience: `notify: the contact stream cap (400 of 1000 per process) is reached — …` or
238
+ `notify: the stream cap (1000 per process) is reached — … (this one: audience staff; held: staff 600, contact
239
+ 400)`. Each line is logged once a minute per cap and audience, so contacts being refused never hides the line
240
+ that says staff are.
241
+ - Any audience string may be named (`perAudience: { contact: 300, kiosk: 50 }`). `subscribe` **throws** on an
242
+ audience that is neither `staff` nor named — a misspelt `'contacts'` would otherwise be an uncapped stream.
243
+ `createHub` throws when the named caps together are not below `perProcess` (staff would keep no reserve), on a cap
244
+ that is neither 0 nor a positive number, and on `perAudience.staff` (staff is the reserve; `perProcess` caps it).
245
+ - `streamStats()` adds `audiences: { staff, contact, … }` (open streams of each) and `limits.perAudience`.
246
+
247
+ ### Upgrading to 0.6.0
248
+
249
+ - **Nothing changes for a caller that passes no audience**: every stream is `staff`, and staff can still use the
250
+ whole `perProcess` while no contact holds a stream. 0.6.0 also carries 0.5.1's strip wording (`off`), which was
251
+ never published on its own.
252
+ - **An app that serves non-staff streams should pass `audience`** — until it does, those streams are counted as
253
+ staff and the reserve protects no one. The hub's customer portal stream is the one known case
254
+ (`routes/portal.js`, `GET /portal/live/stream`: `audience: 'contact'`).
255
+ - **A live stream at its own per-session or per-user limit now evicts its own oldest even when the process is
256
+ full** (0.5.x refused it `busy`). Callers need do nothing; it only ever ends a stream of the same session or user.
257
+ - **A hub that set `limits: { perProcess }` below 3** now has a contact cap of 0 (40 % floored), so contact streams
258
+ are all refused there; give it an explicit `perAudience` or a larger `perProcess` before passing `'contact'`.
259
+ - **A hub that names its own audiences** must keep their caps (with the default contact one) below `perProcess`, or
260
+ `createHub` throws at boot.
package/assets/bell.css CHANGED
@@ -67,3 +67,9 @@
67
67
  font-family:var(--bs-body-font-family);
68
68
  letter-spacing:0;
69
69
  }
70
+
71
+ /* ── Live page regions (assets/live.js, 0.5.0) ─────────────────────────────────────────────── */
72
+ .live-paused{opacity:.6;transition:opacity .2s;}
73
+ .live-new{background:rgba(var(--brand-rgb, var(--bs-primary-rgb)), .07);transition:background 2s;}
74
+ .live-new-pill{display:inline-block;margin-right:.4em;padding:0 .45em;border-radius:1em;font-size:.72em;font-weight:600;
75
+ background:rgba(var(--brand-rgb, var(--bs-primary-rgb)), .14);color:var(--text, var(--bs-body-color));vertical-align:.1em;}
package/assets/bell.js CHANGED
@@ -25,6 +25,20 @@
25
25
  * somebody is typing. Extra stream query params come from any page element carrying
26
26
  * data-notif-stream-param="key=value" (a ticket page watching itself rides the same connection).
27
27
  *
28
+ * LIVE PAGES (0.5.0) ride the same connection. Every element carrying data-live-topic="type:id …"
29
+ * adds `topic=type:id` to the stream URL (assets/live.js re-fetches those regions), and frames for
30
+ * a topic the page watches are quiet — they are not the bell's business. Two frames are the server
31
+ * speaking to THIS file:
32
+ * live-stop the stream's LIVE part was refused or stopped (a cap, a check, a signed-out session).
33
+ * A stream that asked for topics is closed and reopened ONCE WITHOUT them, so the bell
34
+ * keeps working (bell-only streams are not capped per session or user); the topics are
35
+ * never asked for again on this page. A bell-only stream that is stopped is closed and
36
+ * NOT reopened — the browser's own retry would otherwise ask every 5 s for a stream the
37
+ * server has just refused. A reload, or the next page, asks afresh.
38
+ * live-renew the stream reached its lifetime: reopened at once (a reconnect, so the page's
39
+ * regions catch up), never left to the 5 s retry.
40
+ * A dropped stream is announced as 'aria:sse-down' (assets/live.js shows "Live updates paused").
41
+ *
28
42
  * XSS-safe by construction: rows are createElement/textContent, and only a same-origin PATH may
29
43
  * become a row's href — a link that ever carried attacker-influenced text (javascript: or
30
44
  * //host) would execute or leave the site on click.
@@ -43,6 +57,19 @@
43
57
  var BASE = menu.getAttribute('data-notif-base') || '/notifications';
44
58
  var FILL = menu.getAttribute('data-notif-fill') || 'load';
45
59
  var QUIET = (menu.getAttribute('data-notif-quiet') || '').split(',').map(function (s) { return s.trim(); }).filter(Boolean);
60
+ QUIET.push('live-stop', 'live-renew');
61
+
62
+ /** The topics this page watches (data-live-topic, space-separated `type:id` keys), de-duplicated. */
63
+ function liveTopics() {
64
+ var out = [];
65
+ document.querySelectorAll('[data-live-topic]').forEach(function (el) {
66
+ (el.getAttribute('data-live-topic') || '').split(/\s+/).forEach(function (t) {
67
+ if (t && out.indexOf(t) === -1) out.push(t);
68
+ });
69
+ });
70
+ return out;
71
+ }
72
+ var TOPICS = liveTopics(); // emptied after a live-stop: the bell goes on alone
46
73
  var tokenMeta = document.querySelector('meta[name="csrf-token"]');
47
74
  var csrf = tokenMeta ? tokenMeta.getAttribute('content') : '';
48
75
 
@@ -160,6 +187,7 @@
160
187
  // ── The stream ──────────────────────────────────────────────────────────────────────────────
161
188
  var es = null;
162
189
  var firstOpen = true;
190
+ var stopped = false; // a live-stop: this page does not ask again
163
191
 
164
192
  function streamUrl() {
165
193
  var params = [];
@@ -167,11 +195,12 @@
167
195
  var p = el.getAttribute('data-notif-stream-param');
168
196
  if (p) params.push(p);
169
197
  });
198
+ TOPICS.forEach(function (t) { params.push('topic=' + encodeURIComponent(t)); });
170
199
  return BASE + '/stream' + (params.length ? '?' + params.join('&') : '');
171
200
  }
172
201
 
173
202
  function openStream() {
174
- if (!window.EventSource || es) return;
203
+ if (!window.EventSource || es || stopped) return;
175
204
  try {
176
205
  es = new EventSource(streamUrl());
177
206
  es.onmessage = function (ev) {
@@ -181,7 +210,17 @@
181
210
  // ticket page, a draft indicator, a version-skew banner) ride this connection without
182
211
  // knowing it exists, and without burning a second one.
183
212
  if (d) document.dispatchEvent(new CustomEvent('aria:sse', { detail: d }));
184
- if (!d || QUIET.indexOf(d.type) === -1) sync();
213
+ if (d && d.type === 'live-stop') {
214
+ closeStream();
215
+ if (TOPICS.length) { TOPICS = []; openStream(); } else { stopped = true; }
216
+ return;
217
+ }
218
+ if (d && d.type === 'live-renew') { closeStream(); openStream(); return; }
219
+ var forPage = !!d && d.id != null && TOPICS.indexOf(d.type + ':' + d.id) !== -1;
220
+ if (!forPage && (!d || QUIET.indexOf(d.type) === -1)) sync();
221
+ };
222
+ es.onerror = function () {
223
+ document.dispatchEvent(new CustomEvent('aria:sse-down', { detail: {} }));
185
224
  };
186
225
  es.onopen = function () {
187
226
  sync(); // self-heal the badge on every open, reconnects included
package/assets/live.js ADDED
@@ -0,0 +1,309 @@
1
+ /**
2
+ * @aria-framework/notify — live page regions (0.5.0). Loaded AFTER bell.js, which owns the page's
3
+ * one stream; this file opens nothing. It listens to the DOM events bell.js re-dispatches.
4
+ *
5
+ * MARKUP CONTRACT:
6
+ * <div id="…" data-live-topic="work:p3 work:c12">…</div>
7
+ * A REGION. It must have an id. When a frame for one of its topics arrives (`{type, id}` —
8
+ * contentless), the page is re-fetched THROUGH ITS OWN ROUTE (data-live-src, default the
9
+ * page's own URL) and the region is replaced by the element with the same id in the answer.
10
+ * So the route's RBAC and RLS decide what the region shows, exactly as on a reload. An answer
11
+ * without that element (a sign-in page answers 200 too) changes nothing.
12
+ * data-live-list on a region
13
+ * A LIST: rows are its [data-row-id] elements. Rows the answer has and the page has not are
14
+ * NEW. With data-live-insert on the region (the server draws it on page 1, default sort, no
15
+ * filter) and no checkbox ticked inside it, the region is replaced and the new rows marked
16
+ * `.live-new` with a "New" pill; otherwise the region stays as it is and a bar says
17
+ * "N new. Show them" (a click replaces it). A list a person is working in never moves.
18
+ *
19
+ * WHEN A REGION RE-FETCHES
20
+ * - a frame for one of its topics (coalesced: one fetch however many frames arrive meanwhile);
21
+ * - every RECONNECT (aria:sse-open with firstOpen === false) — all regions, once: a missed event
22
+ * is caught up by reading the state, there is no replay;
23
+ * - never while a field inside it has focus (deferred until it loses it), so a half-typed value
24
+ * is not swapped away.
25
+ *
26
+ * WHAT IT IGNORES: frames that arrive after a form on this page was submitted. A form POST is a
27
+ * navigation, but the browser keeps this page (and its stream) until the answer arrives, so the
28
+ * push written while handling it reaches the very page that caused it (README, "A push reaches the
29
+ * page that CAUSED it"). A submit a script prevented is not a navigation and sets nothing.
30
+ *
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, and
33
+ * "Live updates are off" for `off`, the reason an app gives when it has switched live pages off); the
34
+ * regions are dimmed. It clears on the next open, which also catches the regions up. A hidden tab
35
+ * closes its stream on purpose (bell.js) and shows no strip.
36
+ */
37
+ (function () {
38
+ 'use strict';
39
+
40
+ var REGIONS = [].slice.call(document.querySelectorAll('[data-live-topic][id]'));
41
+ if (!REGIONS.length) return;
42
+
43
+ var leaving = false; // a form on this page was submitted: its own push is not news
44
+ var leavingTimer = null;
45
+ var busy = false;
46
+ var pending = null; // ids of regions due another fetch once the one in flight lands
47
+ var held = []; // ids of regions skipped because a person is working in them
48
+ var heldTimer = null;
49
+ var stopped = null; // the live-stop reason: the stream has no topics any more (bell.js reopens it bell-only)
50
+ var strip = null;
51
+ var LEAVE_MS = 8000; // a submit that has not navigated by then did not navigate (a download, target=_blank)
52
+ var HELD_MS = 2000;
53
+
54
+ function topicsOf(el) {
55
+ return (el.getAttribute('data-live-topic') || '').split(/\s+/).filter(Boolean);
56
+ }
57
+
58
+ document.addEventListener('submit', function (ev) {
59
+ // Read AFTER every handler has run — a document-level confirmation registered after this file (form-ui.js) may
60
+ // still cancel it, and a cancelled submit is not a navigation.
61
+ setTimeout(function () { if (!ev.defaultPrevented) startLeaving(); }, 0);
62
+ });
63
+ function startLeaving() {
64
+ leaving = true;
65
+ // A submit that does not navigate (a download, a form with target=_blank) leaves this page in place:
66
+ // after LEAVE_MS, or when the page is shown again, it is listening again.
67
+ if (leavingTimer) clearTimeout(leavingTimer);
68
+ leavingTimer = setTimeout(function () { leaving = false; leavingTimer = null; }, LEAVE_MS);
69
+ }
70
+ window.addEventListener('pageshow', function (ev) { if (ev.persisted) leaving = false; });
71
+ document.addEventListener('visibilitychange', function () { if (document.visibilityState === 'visible') leaving = false; });
72
+
73
+ // ── The strip ─────────────────────────────────────────────────────────────────────────────
74
+ function showStrip(reason) {
75
+ if (leaving) return;
76
+ if (!strip) {
77
+ strip = document.createElement('div');
78
+ strip.className = 'live-strip alert alert-warning d-flex align-items-center gap-2 py-2 small';
79
+ strip.setAttribute('role', 'status');
80
+ strip.setAttribute('data-live-strip', '');
81
+ var words = document.createElement('span');
82
+ words.className = 'flex-grow-1';
83
+ words.setAttribute('data-live-strip-words', '');
84
+ strip.appendChild(words);
85
+ var btn = document.createElement('button');
86
+ btn.type = 'button';
87
+ btn.className = 'btn btn-sm btn-outline-secondary';
88
+ btn.textContent = 'Refresh';
89
+ btn.addEventListener('click', function () { window.location.reload(); });
90
+ strip.appendChild(btn);
91
+ REGIONS[0].parentNode.insertBefore(strip, REGIONS[0]);
92
+ }
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.';
100
+ strip.hidden = false;
101
+ REGIONS.forEach(function (r) { r.classList.add('live-paused'); });
102
+ }
103
+ function clearStrip() {
104
+ if (strip) strip.hidden = true;
105
+ REGIONS.forEach(function (r) { r.classList.remove('live-paused'); });
106
+ }
107
+
108
+ // ── Re-fetch and swap ─────────────────────────────────────────────────────────────────────
109
+ /**
110
+ * IS A PERSON WORKING IN THIS REGION? Then it is not swapped, and not swapped later behind their back
111
+ * either: it is held until none of these is true, re-checked every HELD_MS.
112
+ * - the focus is anywhere inside it (a field, a button, a link);
113
+ * - a control in it, or a details/dialog's open state, differs from the region's BASELINE (a half-typed
114
+ * value, a changed select or box, a details opened or closed; in a LIST the row boxes are the list's own
115
+ * business: a ticked one shows the "N new" bar instead);
116
+ * - an open modal (.modal.show) is inside it.
117
+ * THE BASELINE is the state as the page had it before anyone could work in it — recorded when this file
118
+ * starts, again at DOMContentLoaded and load for a region nobody is in (a page script that sets a value at
119
+ * load is not a person), and after every swap once aria:live-swapped's listeners have run. Not the HTML
120
+ * defaults: a <select> with no `selected` option has its first one selected but not defaultSelected, a
121
+ * script-set value is not its defaultValue, and a server-drawn <details open> is open — none is work.
122
+ */
123
+ var baseline = {}; // region id -> stateOf(region) as the page had it
124
+
125
+ function stateOf(el) {
126
+ var list = el.hasAttribute('data-live-list');
127
+ var out = [];
128
+ var fields = el.querySelectorAll('input, textarea, select');
129
+ for (var i = 0; i < fields.length; i++) {
130
+ var f = fields[i];
131
+ if (f.tagName === 'SELECT') {
132
+ var sel = [];
133
+ for (var j = 0; j < f.options.length; j++) if (f.options[j].selected) sel.push(j);
134
+ out.push('s' + sel.join('.'));
135
+ } else if (f.type === 'checkbox' || f.type === 'radio') {
136
+ out.push(list && f.type === 'checkbox' ? '-' : (f.checked ? 'c1' : 'c0'));
137
+ } else if (f.type === 'hidden') {
138
+ out.push('-');
139
+ } else {
140
+ out.push('v' + f.value.length + ':' + f.value);
141
+ }
142
+ }
143
+ var opens = el.querySelectorAll('details, dialog');
144
+ for (var k = 0; k < opens.length; k++) out.push(opens[k].hasAttribute('open') ? 'o1' : 'o0');
145
+ return out.join('|');
146
+ }
147
+ function focusIn(el) {
148
+ var a = document.activeElement;
149
+ return !!(a && a !== document.body && el.contains(a));
150
+ }
151
+ function record(el) { baseline[el.id] = stateOf(el); }
152
+ function recordIdle() { REGIONS.forEach(function (r) { if (!focusIn(r) && !r.querySelector('.modal.show')) record(r); }); }
153
+ REGIONS.forEach(record);
154
+ document.addEventListener('DOMContentLoaded', recordIdle);
155
+ window.addEventListener('load', recordIdle);
156
+ function workedIn(el) {
157
+ if (focusIn(el)) return true;
158
+ if (el.querySelector('.modal.show')) return true;
159
+ return stateOf(el) !== baseline[el.id];
160
+ }
161
+
162
+ function hold(ids) {
163
+ ids.forEach(function (id) { if (held.indexOf(id) === -1) held.push(id); });
164
+ if (heldTimer) return;
165
+ heldTimer = setTimeout(function () {
166
+ heldTimer = null;
167
+ var h = held; held = [];
168
+ refresh(h);
169
+ }, HELD_MS);
170
+ }
171
+
172
+ function rowIds(el) {
173
+ return [].slice.call(el.querySelectorAll('[data-row-id]')).map(function (r) { return r.getAttribute('data-row-id'); });
174
+ }
175
+
176
+ function newBar(el, n, fresh) {
177
+ var bar = document.querySelector('[data-live-newbar="' + el.id + '"]');
178
+ if (!bar) {
179
+ bar = document.createElement('div');
180
+ bar.className = 'live-newbar alert alert-info d-flex align-items-center gap-2 py-1 px-2 small';
181
+ bar.setAttribute('data-live-newbar', el.id);
182
+ var words = document.createElement('span');
183
+ words.className = 'flex-grow-1';
184
+ bar.appendChild(words);
185
+ var btn = document.createElement('button');
186
+ btn.type = 'button';
187
+ btn.className = 'btn btn-sm btn-link p-0';
188
+ btn.textContent = 'Show them';
189
+ bar.appendChild(btn);
190
+ el.parentNode.insertBefore(bar, el);
191
+ }
192
+ bar.firstChild.textContent = n + ' new. ';
193
+ bar.lastChild.onclick = function () {
194
+ var cur = document.getElementById(el.id);
195
+ if (cur) swapIn(cur, bar.__fresh, true);
196
+ if (bar.parentNode) bar.parentNode.removeChild(bar);
197
+ };
198
+ bar.__fresh = fresh;
199
+ bar.hidden = false;
200
+ }
201
+
202
+ /** Replace `el` by `fresh`, marking rows `fresh` has that `el` had not. */
203
+ function swapIn(el, fresh, markNew) {
204
+ var before = rowIds(el);
205
+ var clone = document.importNode(fresh, true);
206
+ el.parentNode.replaceChild(clone, el);
207
+ REGIONS[REGIONS.indexOf(el)] = clone;
208
+ // Scripts that bound to the old nodes re-bind here (or listen on the document, as pager.js and
209
+ // bulk-select.js do since @aria-framework/server 0.17.0).
210
+ document.dispatchEvent(new CustomEvent('aria:live-swapped', { detail: { id: clone.id, el: clone } }));
211
+ record(clone); // the new baseline: what the server drew, as its listeners have set it up
212
+ if (markNew && before.length) {
213
+ clone.querySelectorAll('[data-row-id]').forEach(function (r) {
214
+ if (before.indexOf(r.getAttribute('data-row-id')) !== -1) return;
215
+ // The marker may sit on the row or on its first cell (an app whose rows must stay a bare <tr>).
216
+ var tr = (r.closest && r.closest('tr')) || r;
217
+ tr.classList.add('live-new');
218
+ var cell = /^T[DH]$/.test(r.tagName) ? r : (r.querySelector('td, th') || r);
219
+ var pill = document.createElement('span');
220
+ pill.className = 'live-new-pill';
221
+ pill.textContent = 'New';
222
+ cell.insertBefore(pill, cell.firstChild);
223
+ });
224
+ }
225
+ return clone;
226
+ }
227
+
228
+ function apply(el, fresh) {
229
+ if (!el.hasAttribute('data-live-list')) {
230
+ if (el.innerHTML !== fresh.innerHTML) swapIn(el, fresh, false);
231
+ return;
232
+ }
233
+ var have = rowIds(el);
234
+ var added = rowIds(fresh).filter(function (id) { return have.indexOf(id) === -1; });
235
+ var ticked = !!el.querySelector('input[type="checkbox"]:checked');
236
+ if (el.hasAttribute('data-live-insert') && fresh.hasAttribute('data-live-insert') && !ticked) {
237
+ if (el.innerHTML !== fresh.innerHTML) swapIn(el, fresh, true);
238
+ return;
239
+ }
240
+ if (added.length) newBar(el, added.length, fresh);
241
+ }
242
+
243
+ function srcOf(el) { return el.getAttribute('data-live-src') || window.location.href; }
244
+
245
+ function refresh(ids) {
246
+ // A submit that may not navigate (a download): a HELD region stays held — it is caught up once listening again.
247
+ if (leaving) { hold(ids); return; }
248
+ if (busy) {
249
+ pending = pending || [];
250
+ ids.forEach(function (id) { if (pending.indexOf(id) === -1) pending.push(id); });
251
+ return;
252
+ }
253
+ var targets = REGIONS.filter(function (r) { return ids.indexOf(r.id) !== -1; });
254
+ var worked = targets.filter(workedIn);
255
+ targets = targets.filter(function (r) { return !workedIn(r); });
256
+ if (worked.length) hold(worked.map(function (r) { return r.id; }));
257
+ if (!targets.length) return;
258
+ // One fetch per source: a region with its own data-live-src is read from there, the rest from this page.
259
+ var bySrc = {};
260
+ targets.forEach(function (r) { (bySrc[srcOf(r)] = bySrc[srcOf(r)] || []).push(r); });
261
+ busy = true;
262
+ Promise.all(Object.keys(bySrc).map(function (src) {
263
+ // X-Live-Fragment marks the page's own re-fetch: @aria-framework/auth 0.16.0 lets it through without
264
+ // counting it as activity, so a page left open still idles out.
265
+ return fetch(src, { credentials: 'same-origin', headers: { 'X-Requested-With': 'fetch', 'X-Live-Fragment': '1' } })
266
+ .then(function (r) { return r.ok ? r.text() : null; })
267
+ .then(function (html) {
268
+ if (html == null) return;
269
+ if (leaving) { hold(bySrc[src].map(function (el) { return el.id; })); return; }
270
+ var doc = new DOMParser().parseFromString(html, 'text/html');
271
+ bySrc[src].forEach(function (el) {
272
+ var cur = document.getElementById(el.id) || el;
273
+ var fresh = doc.getElementById(el.id);
274
+ // No such element in the answer: not this page (a sign-in page is a 200 too). Nothing changes.
275
+ if (!fresh || !fresh.hasAttribute('data-live-topic')) return;
276
+ // Someone started working in it while the answer was on its way: hold it, never swap.
277
+ if (workedIn(cur)) { hold([cur.id]); return; }
278
+ apply(cur, fresh);
279
+ });
280
+ })
281
+ .catch(function () { /* the next frame or reconnect tries again */ });
282
+ })).then(function () {
283
+ busy = false;
284
+ if (pending) { var p = pending; pending = null; refresh(p); }
285
+ });
286
+ }
287
+
288
+ document.addEventListener('aria:sse', function (ev) {
289
+ var d = ev.detail || {};
290
+ if (d.type === 'live-stop') { stopped = d.reason || 'stopped'; showStrip(stopped); return; }
291
+ if (d.id == null || leaving) return;
292
+ var t = d.type + ':' + d.id;
293
+ var ids = REGIONS.filter(function (r) { return topicsOf(r).indexOf(t) !== -1; }).map(function (r) { return r.id; });
294
+ if (ids.length) refresh(ids);
295
+ });
296
+ document.addEventListener('aria:sse-down', function () {
297
+ if (document.visibilityState === 'hidden') return;
298
+ showStrip('down');
299
+ });
300
+ document.addEventListener('aria:sse-open', function (ev) {
301
+ // After a live-stop bell.js keeps the BELL open without topics: this page is still not live.
302
+ if (stopped) return;
303
+ clearStrip();
304
+ // A reconnect: whatever was missed while down is caught up by reading the state once.
305
+ if (ev.detail && ev.detail.firstOpen === false) refresh(REGIONS.map(function (r) { return r.id; }));
306
+ });
307
+
308
+ window.ariaLive = { refresh: function () { refresh(REGIONS.map(function (r) { return r.id; })); } };
309
+ })();
package/hub.js CHANGED
@@ -19,15 +19,103 @@
19
19
  * The second is not a nicety. Pushes on the first channel go to recipients, so someone reading
20
20
  * a record they do not watch is told nothing — which is the ordinary state of an unassigned
21
21
  * ticket or an unowned invoice, and exactly the one most likely to be open when it changes.
22
+ *
23
+ * 0.5.0 — LIVE PAGES ON THE SAME ENTITY CHANNEL (three additions, nothing new underneath):
24
+ *
25
+ * TOPICS a stream may watch up to `topicsPerStream` `type:id` keys, not just one record —
26
+ * a list ("work:p3"), a running job ("ask-bench:house"). A topic IS an entity key;
27
+ * the frame is still `{type, id}` and nothing else.
28
+ * CAPS per session and per user on LIVE streams (those watching a topic; a bell-only stream is
29
+ * not counted, so the bell never loses to a seventh tab), per process on every stream,
30
+ * topics per stream, and a stream lifetime. Over the session or user cap the OLDEST live
31
+ * stream of that session or user is evicted (`live-stop evicted`), never the new one —
32
+ * which also clears a half-open stream a sleeping laptop left behind. A refused stream
33
+ * (too many topics, the process full) is told `live-stop` and ended.
34
+ * AUTHORISE an optional per-event hook. When it is given, an entity frame reaches a
35
+ * subscription only once the hook said that subscription may still see that topic —
36
+ * and the hook's answer is reused for at most `recheckMs`, so a revoked session gets
37
+ * at most that long of contentless nudges (each of whose re-fetches its own route
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).
22
46
  */
23
47
 
24
48
  'use strict';
25
49
 
26
50
  const HEARTBEAT_MS = 25000; // keep idle connections alive through proxies
27
51
 
28
- function createHub({ heartbeatMs = HEARTBEAT_MS } = {}) {
52
+ /**
53
+ * The default caps (the live-updates plan's D5, approved 30 Oct 2026). Each can be lowered or
54
+ * raised per hub; none can be switched off, because a cap that is not there is the case it exists
55
+ * for — a tab left open forever, or a script opening streams in a loop.
56
+ */
57
+ const LIMITS = Object.freeze({
58
+ perSession: 6, // LIVE streams (tabs watching a topic) one session may hold
59
+ perUser: 12, // LIVE streams one user may hold, over all their sessions and devices
60
+ bellPerUser: 20, // BELL-ONLY streams one user may hold (counted apart: a bell is never evicted for a live tab)
61
+ perProcess: 1000, // streams this process holds in all
62
+ topicsPerStream: 8, // `type:id` keys one stream may watch
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 })
67
+ });
68
+ const DEFAULT_AUDIENCE = 'staff';
69
+ const RECHECK_MS = 5000; // an authorise answer is reused for at most this long
70
+ const COALESCE_MS = 750; // publishSoon(): one frame per topic per this window
71
+
72
+ const frame = (obj) => `data: ${JSON.stringify(obj)}\n\n`;
73
+
74
+ function positive(v, name) {
75
+ const n = Number(v);
76
+ if (!Number.isFinite(n) || n < 1) throw new Error(`notify: createHub limit ${name} must be a positive number (got ${JSON.stringify(v)})`);
77
+ return n;
78
+ }
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
+
101
+ function createHub({
102
+ heartbeatMs = HEARTBEAT_MS, limits = {}, authorize = null, recheckMs = RECHECK_MS,
103
+ coalesceMs = COALESCE_MS, now = () => Date.now(), logger = console
104
+ } = {}) {
105
+ const L = {};
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);
108
+ if (authorize !== null && typeof authorize !== 'function') throw new Error('notify: authorize must be a function');
109
+ const RECHECK = Math.max(0, Number(recheckMs) || 0);
110
+
29
111
  const users = new Map(); // userId -> Set(res)
30
112
  const entities = new Map(); // "type:id" -> Set(res)
113
+ const subs = new Map(); // res -> subscription (every open stream; a refused one never)
114
+ const sessions = new Map(); // session id -> Set(res) live streams only, oldest first
115
+ const liveUsers = new Map(); // userId -> Set(res) live streams only, oldest first
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
118
+ const soon = new Map(); // "type:id" -> coalescing timer
31
119
  let heartbeat = null;
32
120
 
33
121
  const key = (type, id) => `${type}:${id}`;
@@ -64,29 +152,138 @@ function createHub({ heartbeatMs = HEARTBEAT_MS } = {}) {
64
152
  if (!set.size) map.delete(k);
65
153
  };
66
154
 
155
+ /** Tell a stream why it gets no more frames, and end it. bell.js does not reconnect after it. */
156
+ function stopRes(res, reason) {
157
+ try { res.write(frame({ type: 'live-stop', reason })); } catch (_) { /* gone */ }
158
+ try { res.end(); } catch (_) { /* gone */ }
159
+ }
160
+
161
+ /** The keys a subscription asks for: the one `entity` (0.4.0) and `topics` (0.5.0), de-duplicated. */
162
+ function keysOf(opts) {
163
+ const out = [];
164
+ const take = (e) => {
165
+ if (!e || e.type == null || e.id == null) return;
166
+ const k = key(e.type, e.id);
167
+ if (!out.includes(k)) out.push(k);
168
+ };
169
+ take(opts.entity);
170
+ for (const t of (Array.isArray(opts.topics) ? opts.topics : [])) take(t);
171
+ return out;
172
+ }
173
+
174
+ /** Stop an existing stream (the oldest, over a cap): told why, ended, forgotten. */
175
+ function evict(res) {
176
+ const sub = subs.get(res);
177
+ stopRes(res, 'evicted');
178
+ if (sub && sub.unsubscribe) sub.unsubscribe();
179
+ }
180
+
181
+ function refused(res, reason) {
182
+ stopRes(res, reason);
183
+ const noop = function unsubscribe() {};
184
+ noop.refused = reason;
185
+ return noop;
186
+ }
187
+
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 */ }
202
+ }
203
+
67
204
  /**
68
205
  * Register an open SSE response.
69
206
  *
70
207
  * @param {number} userId
71
208
  * @param {object} res
72
- * @param {{entity?: {type: string, id: number|string}}} [opts] also watch one record
73
- * @returns {function} unsubscribe — removes from BOTH maps
209
+ * @param {{entity?: {type, id}, topics?: {type, id}[], sessionId?: string, meta?: any, audience?: string}} [opts]
210
+ * `entity` and `topics` are both entity keys; `sessionId` is counted for the per-session
211
+ * cap and handed to `authorize`, as is `meta` (whatever the app needs to re-judge — the
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.
216
+ * @returns {function} unsubscribe — removes from EVERY map. When the stream was refused (a cap)
217
+ * it has been told `live-stop` and ended, and the function is a no-op carrying `.refused`.
74
218
  *
75
- * ONE unsubscribe covering both maps, deliberately: two functions is two chances for a
76
- * caller to wire up only one, and an entry left behind holds a dead response that the
77
- * heartbeat then writes to forever.
219
+ * ONE unsubscribe covering every map, deliberately: two functions is two chances for a caller to
220
+ * wire up only one, and an entry left behind holds a dead response that the heartbeat then
221
+ * writes to forever.
78
222
  */
79
223
  function subscribe(userId, res, opts = {}) {
80
224
  const uid = Number(userId);
225
+ const keys = keysOf(opts);
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
+ }
231
+ if (keys.length > L.topicsPerStream) return refused(res, 'too_many_topics');
232
+ const isLive = keys.length > 0;
233
+ // A BELL-ONLY stream is capped per USER (never per session: the bell is per person), before the process cap, so one
234
+ // user opening bells in a loop evicts their own oldest instead of filling the process and starving everyone else.
235
+ if (!isLive) while ((bellUsers.get(uid) || new Set()).size >= L.bellPerUser) evict(bellUsers.get(uid).values().next().value);
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).
241
+ if (isLive) {
242
+ if (sid) while ((sessions.get(sid) || new Set()).size >= L.perSession) evict(sessions.get(sid).values().next().value);
243
+ while ((liveUsers.get(uid) || new Set()).size >= L.perUser) evict(liveUsers.get(uid).values().next().value);
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
+ }
255
+
256
+ const sub = { userId: uid, sessionId: sid, audience, keys, meta: opts.meta, verdicts: new Map(), closed: false, timer: null, unsubscribe: null };
257
+ subs.set(res, sub);
81
258
  add(users, uid, res);
82
- const e = opts.entity;
83
- const ek = e && e.type != null && e.id != null ? key(e.type, e.id) : null;
84
- if (ek) add(entities, ek, res);
259
+ add(audiences, audience, res);
260
+ for (const k of keys) add(entities, k, res);
261
+ if (isLive && sid) add(sessions, sid, res);
262
+ if (isLive) add(liveUsers, uid, res); else add(bellUsers, uid, res);
85
263
  ensureHeartbeat();
86
- return function unsubscribe() {
264
+
265
+ function unsubscribe() {
266
+ if (sub.closed) return;
267
+ sub.closed = true;
268
+ if (sub.timer) { clearTimeout(sub.timer); sub.timer = null; }
269
+ subs.delete(res);
87
270
  remove(users, uid, res);
88
- if (ek) remove(entities, ek, res);
89
- };
271
+ remove(audiences, audience, res);
272
+ for (const k of keys) remove(entities, k, res);
273
+ if (isLive && sid) remove(sessions, sid, res);
274
+ if (isLive) remove(liveUsers, uid, res); else remove(bellUsers, uid, res);
275
+ }
276
+ sub.unsubscribe = unsubscribe;
277
+
278
+ // THE LIFETIME: renewed, not refused. The client reconnects at once and catches up (bell.js
279
+ // on `live-renew`), and the new stream is judged afresh — a scope cannot outlive it.
280
+ sub.timer = setTimeout(() => {
281
+ try { res.write(frame({ type: 'live-renew' })); } catch (_) { /* gone */ }
282
+ try { res.end(); } catch (_) { /* gone */ }
283
+ unsubscribe();
284
+ }, L.lifetimeMs);
285
+ if (sub.timer.unref) sub.timer.unref();
286
+ return unsubscribe;
90
287
  }
91
288
 
92
289
  const write = (set, payload) => {
@@ -107,35 +304,115 @@ function createHub({ heartbeatMs = HEARTBEAT_MS } = {}) {
107
304
  }
108
305
 
109
306
  /**
110
- * Tell everyone VIEWING a record that it changed.
307
+ * ONE SUBSCRIPTION, ONE TOPIC: may this frame go out? Resolves true only when `authorize` said
308
+ * exactly `true`. Its answer is reused for `recheckMs` (one call however many events arrive in
309
+ * that window — a burst of fifty touches is one session-store read, not fifty); a `{stop}`
310
+ * answer or a throw ends the stream with that reason.
311
+ */
312
+ function allowed(res, k, topic) {
313
+ const sub = subs.get(res);
314
+ if (!sub || sub.closed) return Promise.resolve(false);
315
+ const hit = sub.verdicts.get(k);
316
+ if (hit && now() - hit.at < RECHECK) return hit.p;
317
+ const p = Promise.resolve()
318
+ .then(() => authorize({ userId: sub.userId, sessionId: sub.sessionId, topic, meta: sub.meta }))
319
+ .catch((e) => {
320
+ try { logger.error(`notify: authorize failed for ${k} — ${(e && e.message) || e} — the stream is stopped`); } catch (_) { /* noop */ }
321
+ return { stop: 'check_failed' };
322
+ })
323
+ .then((v) => {
324
+ if (v === true) return true;
325
+ if (v && typeof v === 'object' && typeof v.stop === 'string') {
326
+ stopRes(res, v.stop);
327
+ if (sub.unsubscribe) sub.unsubscribe();
328
+ }
329
+ return false;
330
+ });
331
+ sub.verdicts.set(k, { at: now(), p });
332
+ return p;
333
+ }
334
+
335
+ /**
336
+ * Tell everyone VIEWING a record (or watching a topic) that it changed — and, with `authorize`,
337
+ * only those it still allows. Resolves the number of frames written.
111
338
  *
112
339
  * The event carries the type and id and NOTHING ELSE by default. The client re-fetches
113
340
  * through the normal permission-checked route, so this channel cannot leak content even if a
114
341
  * subscription were wrong, and the app's own view permission stays the single place access is
115
342
  * decided.
343
+ */
344
+ function publish(type, id, extra = {}) {
345
+ const k = key(type, id);
346
+ const set = entities.get(k);
347
+ if (!set || !set.size) return Promise.resolve(0);
348
+ const payload = frame({ type, id, ...extra });
349
+ if (!authorize) return Promise.resolve(write(set, payload));
350
+ return Promise.all([...set].map((res) => allowed(res, k, { type, id }).then((ok) => {
351
+ if (!ok) return 0;
352
+ const sub = subs.get(res);
353
+ if (!sub || sub.closed) return 0;
354
+ try { res.write(payload); return 1; } catch (_) { return 0; }
355
+ }))).then((ns) => ns.reduce((a, b) => a + b, 0));
356
+ }
357
+
358
+ /**
359
+ * pushEntity — the 0.4.0 call, unchanged without `authorize` (it writes and returns how many).
360
+ * With `authorize` it goes through publish() and returns how many subscriptions were CANDIDATES;
361
+ * the frames follow once each is allowed.
116
362
  *
117
363
  * One consumer briefly included an `actorUserId` "so a viewer can ignore its own action". No
118
364
  * client ever read it, so its only effect was disclosing one staffer's user id to every other
119
365
  * viewer on every reply. A field nothing consumes is not a feature waiting to be used.
120
366
  */
121
367
  function pushEntity(type, id, extra = {}) {
122
- const payload = `data: ${JSON.stringify({ type, id, ...extra })}\n\n`;
123
- return write(entities.get(key(type, id)), payload);
368
+ const set = entities.get(key(type, id));
369
+ if (!authorize) return write(set, frame({ type, id, ...extra }));
370
+ publish(type, id, extra).catch(() => {});
371
+ return set ? set.size : 0;
124
372
  }
125
373
 
374
+ /**
375
+ * publish(), coalesced: every call for one topic within `coalesceMs` becomes ONE frame, sent at
376
+ * the end of the window. For a writer that touches a topic in a loop (a job's progress, a batch
377
+ * of events) — one re-fetch per open page per window, however many writes. Fire and forget.
378
+ */
379
+ function publishSoon(type, id) {
380
+ const k = key(type, id);
381
+ if (soon.has(k) || !entities.has(k)) return; // nobody watching: no timer, no work
382
+ const t = setTimeout(() => {
383
+ soon.delete(k);
384
+ publish(type, id).catch(() => {});
385
+ }, coalesceMs);
386
+ if (t.unref) t.unref();
387
+ soon.set(k, t);
388
+ }
389
+
390
+ /** Is anybody watching this topic? (A writer may skip the work of finding out what changed.) */
391
+ const watched = (type, id) => entities.has(key(type, id));
392
+
126
393
  function stats() {
127
394
  return { users: users.size, entities: entities.size };
128
395
  }
129
396
 
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. */
398
+ function streamStats() {
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 } };
403
+ }
404
+
130
405
  /**
131
406
  * End every open response and stop the heartbeat.
132
407
  *
133
408
  * Wire this into graceful shutdown. An SSE response is a request that never finishes, so
134
- * server.close() waits for a drain that will never come — both maps, because a subscription
135
- * left open on either one is enough to hold the process.
409
+ * server.close() waits for a drain that will never come — every map, because a subscription
410
+ * left open on any one is enough to hold the process.
136
411
  */
137
412
  function closeAll() {
138
413
  if (heartbeat) { clearInterval(heartbeat); heartbeat = null; }
414
+ for (const t of soon.values()) clearTimeout(t);
415
+ soon.clear();
139
416
  const ended = new Set();
140
417
  for (const map of [users, entities]) {
141
418
  for (const set of map.values()) {
@@ -148,9 +425,15 @@ function createHub({ heartbeatMs = HEARTBEAT_MS } = {}) {
148
425
  }
149
426
  map.clear();
150
427
  }
428
+ for (const sub of subs.values()) { sub.closed = true; if (sub.timer) clearTimeout(sub.timer); }
429
+ subs.clear();
430
+ sessions.clear();
431
+ liveUsers.clear();
432
+ bellUsers.clear();
433
+ audiences.clear();
151
434
  }
152
435
 
153
- return { subscribe, pushUsers, pushEntity, stats, closeAll };
436
+ return { subscribe, pushUsers, pushEntity, publish, publishSoon, watched, stats, streamStats, closeAll };
154
437
  }
155
438
 
156
- module.exports = { createHub, HEARTBEAT_MS };
439
+ module.exports = { createHub, HEARTBEAT_MS, LIMITS, DEFAULT_AUDIENCE, RECHECK_MS, COALESCE_MS };
package/index.js CHANGED
@@ -27,6 +27,7 @@ module.exports = {
27
27
  // views/notify/bell.ejs is the markup half, shipped together so the hook names cannot drift.
28
28
  // staticDirs.push({ mount: '/js/notify', dir: notify.assetsDir })
29
29
  // viewDirs.push(notify.viewsDir)
30
+ // 0.5.0 — assets/live.js (live page regions) ships in the same assets dir; load it after bell.js.
30
31
  assetsDir: path.join(__dirname, 'assets'),
31
32
  viewsDir: path.join(__dirname, 'views')
32
33
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@aria-framework/notify",
3
- "version": "0.4.0",
4
- "description": "Aria App Framework \u2014 notify module. In-app notifications: ownership-scoped rows, a per-process SSE hub for live delivery, and a fire-and-forget emitter that needs no request and no actor, so a scheduler can raise one.",
3
+ "version": "0.6.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": {
@@ -24,8 +24,11 @@
24
24
  "optional": true
25
25
  }
26
26
  },
27
+ "devDependencies": {
28
+ "jsdom": "^30.0.1"
29
+ },
27
30
  "scripts": {
28
- "test": "node test/store.js && node test/schema-parity.js && node test/hub.js && node test/emit.js && node test/bell.js",
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",
29
32
  "prepublishOnly": "node ../../test/packaging.js notify"
30
33
  }
31
34
  }