@unisim/sdk 0.185.0 → 0.187.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.
Files changed (44) hide show
  1. package/README.md +36 -93
  2. package/dist/SignInDialog.d.ts.map +1 -1
  3. package/dist/SignInDialog.js +37 -12
  4. package/dist/SignInDialog.js.map +1 -1
  5. package/dist/SuiteSwitcher.d.ts +3 -2
  6. package/dist/SuiteSwitcher.d.ts.map +1 -1
  7. package/dist/SuiteSwitcher.js +5 -1
  8. package/dist/SuiteSwitcher.js.map +1 -1
  9. package/dist/UniversalNavBar.d.ts +2 -2
  10. package/dist/UniversalNavBar.d.ts.map +1 -1
  11. package/dist/UniversalNavBar.js +8 -16
  12. package/dist/UniversalNavBar.js.map +1 -1
  13. package/dist/UserCountBreakdown.d.ts +9 -18
  14. package/dist/UserCountBreakdown.d.ts.map +1 -1
  15. package/dist/UserCountBreakdown.js +9 -403
  16. package/dist/UserCountBreakdown.js.map +1 -1
  17. package/dist/UserCountLine.d.ts +9 -49
  18. package/dist/UserCountLine.d.ts.map +1 -1
  19. package/dist/UserCountLine.js +8 -218
  20. package/dist/UserCountLine.js.map +1 -1
  21. package/dist/UserProfile.d.ts +4 -4
  22. package/dist/UserProfile.d.ts.map +1 -1
  23. package/dist/UserProfile.js +2 -3
  24. package/dist/UserProfile.js.map +1 -1
  25. package/dist/i18n.d.ts.map +1 -1
  26. package/dist/i18n.js +0 -223
  27. package/dist/i18n.js.map +1 -1
  28. package/dist/index.d.ts +2 -1
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +2 -1
  31. package/dist/index.js.map +1 -1
  32. package/dist/presence.d.ts +76 -147
  33. package/dist/presence.d.ts.map +1 -1
  34. package/dist/presence.js +156 -500
  35. package/dist/presence.js.map +1 -1
  36. package/dist/provider.d.ts +20 -10
  37. package/dist/provider.d.ts.map +1 -1
  38. package/dist/provider.js +39 -20
  39. package/dist/provider.js.map +1 -1
  40. package/dist/recentApp.d.ts +8 -0
  41. package/dist/recentApp.d.ts.map +1 -0
  42. package/dist/recentApp.js +42 -0
  43. package/dist/recentApp.js.map +1 -0
  44. package/package.json +3 -2
package/dist/presence.js CHANGED
@@ -1,113 +1,108 @@
1
1
  // ──────────────────────────────────────────────────────────────────────────────
2
- // "There are X total users (Y live)" — the data half.
2
+ // The suite user count is RETIRED (0.187.0) — and what replaced it.
3
3
  //
4
- // James, 2026-09-17: every Assess and Universal app, current and future, shows
5
- // how many people use it and how many are using it right now, across every
6
- // platform and counting guests. Bipolar Bear did the same on Firestore; this
7
- // is the Supabase version (migration 0175):
4
+ // James, 2026-10-12, on the suite privacy audit: "we only need an indication
5
+ // of how many live where it matters e.g. bipolar anonymous which we have in a
6
+ // non invasive way. For the rest it doesn't really matter. Any stats we can
7
+ // collect in friendlier ways is better."
8
8
  //
9
- // * `app_presence_beat(product, install_id, platform)` — this install is
10
- // here. Called on the first INTERACTION on the web (see below), when a
11
- // native app opens, on sign-in / sign-out, and every 45 s while visible.
12
- // Signed in, the server adds auth.uid() itself; nothing else is sent.
13
- // * `app_user_counts(product)` — `{ total, live, web, native }`. "Live" is a
14
- // beat within two minutes. The dedupe rules (an account is one person
15
- // across devices; a guest install somebody signed in on is that account)
16
- // live in SQL.
17
- // * `suite_user_counts()` — the same figures across every product
18
- // (migration 0177), which the line switches to when tapped. An account is
19
- // one person suite-wide; a guest is one person per browser origin.
20
- // * `suite_user_counts_by_product()` — the same figures PER product
21
- // (migration 0184), which the line shows in a popup on a long press. The
22
- // rows deliberately do not add up to the suite total: one account using
23
- // four apps is four rows here and one person there.
9
+ // So the "X users (Y live)" line, its breakdown popup and the presence beat
10
+ // behind them (0.145.0 – 0.186.0: an install id in localStorage, a beat every
11
+ // 45 s, linked to the account when signed in) are gone:
12
+ // * no beat is sent, whatever `presence` says — `startPresence` /
13
+ // `beatPresence` are no-ops kept so callers (Universal Family, Universal
14
+ // AI) still compile;
15
+ // * the read functions answer null / nothing, and the components render
16
+ // nothing;
17
+ // * the permanent `unisim:install-id` and the cached figures are DELETED
18
+ // from the browser on load (`forgetLegacyInstallId`);
19
+ // * server side, migration 0276 makes `app_presence_beat` a no-op for every
20
+ // SDK already shipped, and empties app_presence.
24
21
  //
25
- // The install id is a random UUID in this origin's localStorage, so web,
26
- // Capacitor and Electron all get one with no native code.
22
+ // ── The friendlier figure: a daily open count with no identifier ─────────────
23
+ // `countDailyOpen(supabase, product)` adds ONE to today's total for this
24
+ // product and kind of device (web / ios / android / windows / macos / linux),
25
+ // the first time the app is opened that UTC day on this device. The "already
26
+ // counted today" note — `unisim:opened:<product>` = the date — stays in this
27
+ // browser and is never sent. The RPC (`app_open_count`, 0276) takes the
28
+ // product and the platform and nothing else; the server keeps per-day totals
29
+ // only, which identify nobody. God mode reads them.
27
30
  //
28
- // ── Web counts from an INTERACTION, not a page load (0.158.0) ────────────────
29
- // James, 2026-09-21: "I also want the web count to be from the point of an
30
- // interaction and not just a page load if possible". So on the web the first
31
- // beat waits for a pointer, key, touch, wheel or scroll event — a visitor who
32
- // lands and leaves without touching anything is not a user of the app, and
33
- // used to be one. In an installed app (Capacitor, Electron) the beat goes at
34
- // once: somebody chose that icon and waited for it to open, which is a good
35
- // deal more deliberate than arriving at a URL.
31
+ // Same rules as before for what counts: our own traffic (test browsers, dev
32
+ // servers) is left out, and on the web the count waits for the first real
33
+ // interaction — a load on its own is not an open. An installed app counts when
34
+ // it starts.
36
35
  //
37
- // ⚠️ The "has interacted" flag is per PAGE, not per call — `startPresence` is
38
- // restarted whenever the account changes, and a signed-in person who has
39
- // already clicked must not be made to click again to keep counting.
40
- //
41
- // ── web / native (0.158.0, migration 0187) ───────────────────────────────────
42
- // Each beat says which kind of device it came from, and the count functions
43
- // put each PERSON in one bucket — the platform of their most recent beat — so
44
- // web + native is at most the total rather than counting a phone-and-laptop
45
- // person twice. Anyone last seen before 0.158.0 shipped is in neither bucket,
46
- // so the two can add up to less than the total; the popup's "How we count a
47
- // user" fold says so. `null` means the figure is not available at all: an
48
- // older database, or a row whose total comes from an app's own account count
49
- // (migration 0185).
50
- //
51
- // ⚠️ Nothing React in this file, on purpose: Universal AI (Svelte) and Universal
52
- // Family (no <UniversalProvider>) call these directly. The provider starts
53
- // presence for every other app — see `presence` in UniversalConfig.
36
+ // ⚠️ Nothing React in this file, on purpose: Universal AI (Svelte) and
37
+ // Universal Family (no <UniversalProvider>) call it directly. The provider
38
+ // counts for every other app — see `openCount` in UniversalConfig.
54
39
  // ──────────────────────────────────────────────────────────────────────────────
55
- import { t } from './i18n.js';
56
40
  import { capacitorPlatform, isNativeShell } from './sessionStorage.js';
57
- /** localStorage key holding this install's random id. */
41
+ /** ⚠️ Legacy: the permanent per-browser id SDKs before 0.187.0 kept. Deleted on load. */
58
42
  export const INSTALL_ID_KEY = 'unisim:install-id';
59
- /** How often an open, visible app beats. Well inside the server's 2-min window. */
60
- export const PRESENCE_BEAT_MS = 45_000;
61
- /** ⚠️ **Legacy, and only ever deleted now.** It used to remember whichever
62
- * figure a viewer last switched the line to, which meant one tap made every
63
- * app on that browser open on its own figure for ever. The line now always
64
- * opens on the SUITE figure; `forgetStoredScope` in UserCountLine.tsx clears
65
- * this on mount. Kept exported (and cleared) so browsers that stored a choice
66
- * do not carry a dead key around. */
43
+ /** ⚠️ Legacy: kept only so it can be cleared. */
67
44
  export const COUNT_SCOPE_KEY = 'unisim:user-count-scope';
68
- const countsKey = (product) => `unisim:user-counts:${product}`;
69
- /** The last breakdown this origin read, so the popup paints before the read lands. */
70
- const BREAKDOWN_KEY = 'unisim:user-counts:by-product';
71
- function randomUuid() {
72
- const c = globalThis.crypto;
73
- if (c && typeof c.randomUUID === 'function')
74
- return c.randomUUID();
75
- // RFC 4122 v4 from getRandomValues, or Math.random as a last resort — the id
76
- // only has to be unlikely to collide, not unguessable.
77
- const b = new Uint8Array(16);
78
- if (c && typeof c.getRandomValues === 'function')
79
- c.getRandomValues(b);
80
- else
81
- for (let i = 0; i < 16; i++)
82
- b[i] = Math.floor(Math.random() * 256);
83
- b[6] = (b[6] & 0x0f) | 0x40;
84
- b[8] = (b[8] & 0x3f) | 0x80;
85
- const h = Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');
86
- return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
87
- }
88
- const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
45
+ /** ⚠️ Retired with the beat; kept for compatibility. */
46
+ export const PRESENCE_BEAT_MS = 45_000;
47
+ /** localStorage key prefix for "this app was counted today" — the date only. */
48
+ export const OPENED_KEY_PREFIX = 'unisim:opened:';
49
+ const LEGACY_KEYS = [
50
+ INSTALL_ID_KEY,
51
+ COUNT_SCOPE_KEY,
52
+ 'unisim:presence-day-id',
53
+ 'unisim:user-counts:by-product',
54
+ 'unisim:user-counts:universal-ids',
55
+ ];
89
56
  /**
90
- * This install's id, created on first call. `null` where there is no
91
- * localStorage at all (SSR) — a private window that throws on write still gets
92
- * a per-page id, and simply counts as a new install next time.
57
+ * Delete everything the retired user count left in this browser: the
58
+ * permanent install id and the cached figures. The provider calls it on
59
+ * mount in every app. Safe to call anywhere, any number of times.
93
60
  */
94
- let memoryInstallId = null;
95
- export function getInstallId() {
61
+ export function forgetLegacyInstallId() {
96
62
  if (typeof window === 'undefined')
97
- return null;
63
+ return;
98
64
  try {
99
- const existing = window.localStorage.getItem(INSTALL_ID_KEY);
100
- if (existing && UUID_RE.test(existing))
101
- return existing;
102
- const id = randomUuid();
103
- window.localStorage.setItem(INSTALL_ID_KEY, id);
104
- return id;
105
- }
106
- catch {
107
- memoryInstallId ??= randomUuid();
108
- return memoryInstallId;
65
+ const ls = window.localStorage;
66
+ for (const k of LEGACY_KEYS)
67
+ ls.removeItem(k);
68
+ for (let i = ls.length - 1; i >= 0; i--) {
69
+ const k = ls.key(i);
70
+ if (k && k.startsWith('unisim:user-counts:'))
71
+ ls.removeItem(k);
72
+ }
109
73
  }
74
+ catch { /* ignore */ }
110
75
  }
76
+ /** @deprecated Retired in 0.187.0: there is no install id any more. Always null. */
77
+ export function getInstallId() { return null; }
78
+ /** @deprecated Retired in 0.187.0: sends nothing. */
79
+ export function beatPresence(_supabase, _product) {
80
+ return Promise.resolve(false);
81
+ }
82
+ /** @deprecated Retired in 0.187.0: sends nothing; returns a no-op stop function. */
83
+ export function startPresence(_supabase, _product, _options) {
84
+ return () => { };
85
+ }
86
+ /** @deprecated Retired in 0.187.0: always null. */
87
+ export function cachedUserCounts(_product) { return null; }
88
+ /** @deprecated Retired in 0.187.0: always null. */
89
+ export async function fetchUserCounts(_supabase, _product, _scope = 'app') { return null; }
90
+ /** @deprecated Retired in 0.187.0: always null. */
91
+ export function cachedUserCountsByProduct() { return null; }
92
+ /** @deprecated Retired in 0.187.0: always null. */
93
+ export async function fetchUserCountsByProduct(_supabase) { return null; }
94
+ /** @deprecated Retired in 0.187.0: always null. */
95
+ export function cachedUniversalIdCounts() { return null; }
96
+ /** @deprecated Retired in 0.187.0: always null. */
97
+ export async function fetchUniversalIdCounts(_supabase) { return null; }
98
+ /** @deprecated Retired in 0.187.0: always ''. */
99
+ export function formatUserCounts(_language, _counts, _scope = 'app', _appName) { return ''; }
100
+ /** @deprecated Retired in 0.187.0: always []. */
101
+ export function userCountParts(_language, _counts) { return []; }
102
+ /** @deprecated Retired in 0.187.0: always []. */
103
+ export function universalIdParts(_language, _counts) { return []; }
104
+ /** @deprecated Retired in 0.187.0: always []. */
105
+ export function userCountFigures(_language, _counts) { return []; }
111
106
  // ── Which kind of device this is ─────────────────────────────────────────────
112
107
  /**
113
108
  * True in anything the person INSTALLED — a Capacitor container or an Electron
@@ -184,8 +179,18 @@ export function devicePlatform() {
184
179
  * included. Nobody's own browser has it.
185
180
  * * A web page on localhost, a loopback or private address, or a `.local`
186
181
  * name is a dev server (`vite`, `vite --host` for a phone on the Wi-Fi).
187
- * ⚠️ Only for a page, never an installed app: Capacitor on Android serves
188
- * from `https://localhost`, and that is a real user.
182
+ * * An installed app showing a dev server is us too (0.186.0, James
183
+ * 2026-10-12: Universal PDF's 24 💻 were mostly test runs). Every Electron
184
+ * app loads `dist/index.html` from disk in a release and
185
+ * `ELECTRON_START_URL` (http://localhost:5174 …) only in dev and the
186
+ * desktop e2e specs, which launch through Playwright's `_electron` —
187
+ * and that does NOT set `navigator.webdriver`, so the line above never
188
+ * caught them, and each run's fresh profile was a new "person". A
189
+ * Capacitor app pointed at a live-reload server (http://192.168.x.x:5173)
190
+ * is the same case.
191
+ * ⚠️ A dev host WITH A PORT, never the bare host: Capacitor serves a real
192
+ * install from `https://localhost` (Android) and `capacitor://localhost`
193
+ * (iOS), no port, and that is a real user.
189
194
  *
190
195
  * ⚠️ The SDK's own browser specs run under Playwright on 127.0.0.1, so they
191
196
  * set `window.__UNISIM_COUNT_OWN_TRAFFIC__ = true` to be counted anyway. It
@@ -198,9 +203,10 @@ export function isOwnTraffic() {
198
203
  return false;
199
204
  if (typeof navigator !== 'undefined' && navigator.webdriver === true)
200
205
  return true;
206
+ const loc = window.location;
201
207
  if (isInstalledApp())
202
- return false;
203
- return isDevHost(window.location?.hostname ?? '');
208
+ return !!loc?.port && /^https?:$/.test(loc.protocol ?? '') && isDevHost(loc.hostname ?? '');
209
+ return isDevHost(loc?.hostname ?? '');
204
210
  }
205
211
  function isDevHost(host) {
206
212
  const h = host.toLowerCase().replace(/^\[|\]$/g, '');
@@ -279,427 +285,77 @@ export function onFirstInteraction(fn) {
279
285
  disarmInteraction();
280
286
  };
281
287
  }
282
- // The most recent beat per product. fetchUserCounts waits for it, so the first
283
- // read after opening the app already includes the person reading it.
284
- const pendingBeat = new Map();
285
- const beatLanded = new Set();
286
- let warned = false;
287
- /** Say it once — a refused beat repeats every 45 s. */
288
- function warnOnce(what, err) {
289
- if (warned)
290
- return;
291
- warned = true;
292
- console.warn(`[unisim/sdk] user count: ${what} failed (not retried loudly)`, err);
293
- }
294
- /**
295
- * ⚠️ **The one ordering hazard in this release.** PostgREST resolves an RPC by
296
- * its ARGUMENT NAMES, so sending `p_platform` to a database that has not had
297
- * migration 0187 applied is not ignored — it is "function not found", and every
298
- * beat fails. The SDK ships to npm and reaches apps on their own schedule,
299
- * which is exactly the window where that can happen, so a beat refused for that
300
- * reason is retried WITHOUT the platform and the argument is dropped for the
301
- * rest of the page. The count keeps growing; it simply records no platform
302
- * until the migration lands, which is the same state every pre-0187 row is in.
303
- *
304
- * `null` while nothing has been refused — the check is only worth making once.
305
- */
306
- let sendPlatform = null;
307
- /** PostgREST's "no function with these arguments", and Postgres' own. */
308
- function isUnknownFunction(error) {
309
- const code = error?.code;
310
- return code === 'PGRST202' || code === '42883';
288
+ // ── The daily open count ─────────────────────────────────────────────────────
289
+ /** Today's date in UTC, `YYYY-MM-DD`. */
290
+ function utcDay(now = new Date()) {
291
+ return now.toISOString().slice(0, 10);
311
292
  }
293
+ const counting = new Set();
312
294
  /**
313
- * Report this install as here now. Never throws; resolves whether it landed.
295
+ * Add this open to today's total for `product`, once per UTC day on this
296
+ * device. Never throws; resolves whether a count was sent. See the header for
297
+ * what is (and is not) sent.
314
298
  */
315
- export function beatPresence(supabase, product) {
316
- // Before getInstallId, so a test run does not even mint an id.
299
+ export async function countDailyOpen(supabase, product) {
300
+ if (typeof window === 'undefined' || typeof supabase?.rpc !== 'function')
301
+ return false;
317
302
  if (isOwnTraffic())
318
- return Promise.resolve(false);
319
- const installId = getInstallId();
320
- if (!installId || typeof supabase?.rpc !== 'function')
321
- return Promise.resolve(false);
322
- const base = { p_product: product, p_install_id: installId };
323
- const platform = devicePlatform();
324
- // Left out, rather than sent as null, when this install cannot name itself:
325
- // 0187 keeps whatever platform an earlier beat established, so saying nothing
326
- // costs a record and never erases one.
327
- const withPlatform = platform !== null && sendPlatform !== false;
328
- const send = (args) => Promise.resolve(supabase.rpc('app_presence_beat', args));
329
- const p = send(withPlatform ? { ...base, p_platform: platform } : base)
330
- .then(async ({ error }) => {
331
- if (error && withPlatform && isUnknownFunction(error)) {
332
- // A database on 0175–0185. Say it once, drop the argument, carry on.
333
- sendPlatform = false;
334
- const retry = await send(base);
335
- if (retry.error) {
336
- warnOnce('presence beat', retry.error);
337
- return false;
338
- }
339
- beatLanded.add(product);
340
- return true;
341
- }
342
- if (error) {
343
- warnOnce('presence beat', error);
303
+ return false;
304
+ const key = OPENED_KEY_PREFIX + product;
305
+ const today = utcDay();
306
+ try {
307
+ if (window.localStorage.getItem(key) === today)
308
+ return false;
309
+ }
310
+ catch {
311
+ // No storage at all: counting every load would inflate the figure, so
312
+ // a browser that cannot remember is not counted.
313
+ return false;
314
+ }
315
+ if (counting.has(product))
316
+ return false;
317
+ counting.add(product);
318
+ try {
319
+ const platform = devicePlatform();
320
+ const { error } = await supabase.rpc('app_open_count', { p_product: product, p_platform: platform });
321
+ if (error)
344
322
  return false;
323
+ try {
324
+ window.localStorage.setItem(key, today);
345
325
  }
346
- if (withPlatform)
347
- sendPlatform = true;
348
- beatLanded.add(product);
326
+ catch { /* ignore */ }
349
327
  return true;
350
- }, (err) => { warnOnce('presence beat', err); return false; });
351
- pendingBeat.set(product, p);
352
- return p;
328
+ }
329
+ catch {
330
+ return false;
331
+ }
332
+ finally {
333
+ counting.delete(product);
334
+ }
353
335
  }
354
336
  /**
355
- * Beat now — or, on the web, at the first interaction — then every
356
- * {@link PRESENCE_BEAT_MS} while the page is visible, and straight away when it
357
- * becomes visible again. Returns a stop function.
358
- *
359
- * A hidden page does not beat: a backgrounded tab is not someone using the app,
360
- * and it drops out of "live" within two minutes on its own.
337
+ * Count today's open — on the web at the first interaction, in an installed
338
+ * app straight away — and again if the app is still open (or brought back)
339
+ * after midnight UTC. Returns a stop function.
361
340
  */
362
- export function startPresence(supabase, product, options = {}) {
341
+ export function startOpenCount(supabase, product) {
363
342
  if (typeof window === 'undefined' || isOwnTraffic())
364
343
  return () => { };
365
- const hidden = () => typeof document !== 'undefined' && document.visibilityState === 'hidden';
366
- const tick = () => { if (!hidden())
367
- void beatPresence(supabase, product); };
368
- const onVisible = () => { if (!hidden())
369
- tick(); };
370
- let timer = null;
344
+ const run = () => { void countDailyOpen(supabase, product); };
345
+ const onVisible = () => { if (document.visibilityState !== 'hidden')
346
+ run(); };
347
+ let started = false;
371
348
  const begin = () => {
372
- if (timer !== null)
349
+ if (started)
373
350
  return;
374
- tick();
375
- timer = window.setInterval(tick, PRESENCE_BEAT_MS);
351
+ started = true;
352
+ run();
376
353
  document.addEventListener('visibilitychange', onVisible);
377
354
  };
378
- // An installed app was opened on purpose; a web page has to be touched first.
379
- const wait = options.requireInteraction === false || isInstalledApp()
380
- ? (begin(), () => { })
381
- : onFirstInteraction(begin);
355
+ const wait = isInstalledApp() ? (begin(), () => { }) : onFirstInteraction(begin);
382
356
  return () => {
383
357
  wait();
384
- if (timer !== null) {
385
- window.clearInterval(timer);
386
- timer = null;
387
- }
388
358
  document.removeEventListener('visibilitychange', onVisible);
389
359
  };
390
360
  }
391
- /** A `{ total, live, web, native }` out of anything, or null. The two splits
392
- * are `null` rather than 0 when absent: 0 is a claim ("nobody is on the web"),
393
- * null is the absence of one. */
394
- function readCounts(row) {
395
- const r = row;
396
- const total = Number(r?.total);
397
- const live = Number(r?.live);
398
- if (!Number.isFinite(total) || !Number.isFinite(live))
399
- return null;
400
- return {
401
- total,
402
- live,
403
- web: optionalCount(r?.web),
404
- native: optionalCount(r?.native),
405
- ios: optionalCount(r?.ios),
406
- android: optionalCount(r?.android),
407
- };
408
- }
409
- function optionalCount(value) {
410
- if (value === null || value === undefined)
411
- return null;
412
- const n = Number(value);
413
- return Number.isFinite(n) ? n : null;
414
- }
415
- /** The last counts this origin read for `product` (or, with 'suite', for the
416
- * whole suite), or null. */
417
- export function cachedUserCounts(product) {
418
- if (typeof window === 'undefined')
419
- return null;
420
- try {
421
- // ⚠️ An entry written before 0.158.0 has no web/native in it. readCounts
422
- // answers null for both rather than 0, so the cached figure paints without
423
- // a split and gains one when the fresh read lands.
424
- return readCounts(JSON.parse(window.localStorage.getItem(countsKey(product)) ?? 'null'));
425
- }
426
- catch { /* ignore */ }
427
- return null;
428
- }
429
- /**
430
- * Read `{ total, live, web, native }` for `product`. Waits (up to 3 s) for this
431
- * page's pending beat so the reader is in the figure. Resolves null on any
432
- * failure — the caller hides its line rather than showing a wrong number.
433
- */
434
- export async function fetchUserCounts(supabase, product, scope = 'app') {
435
- if (typeof supabase?.rpc !== 'function')
436
- return null;
437
- const beat = pendingBeat.get(product);
438
- if (beat)
439
- await Promise.race([beat, new Promise((r) => setTimeout(r, 3000))]);
440
- try {
441
- const { data, error } = scope === 'suite'
442
- ? await supabase.rpc('suite_user_counts')
443
- : await supabase.rpc('app_user_counts', { p_product: product });
444
- if (error) {
445
- warnOnce('count read', error);
446
- return null;
447
- }
448
- const read = readCounts(Array.isArray(data) ? data[0] : data);
449
- if (!read)
450
- return null;
451
- // Somebody is reading this, and if their beat landed they are live — a
452
- // count that raced the beat must not tell them "(0 live)".
453
- const self = beatLanded.has(product) ? 1 : 0;
454
- const counts = {
455
- ...read,
456
- live: Math.max(read.live, self),
457
- total: Math.max(read.total, read.live, self),
458
- };
459
- try {
460
- window.localStorage.setItem(countsKey(scope === 'suite' ? 'suite' : product), JSON.stringify(counts));
461
- }
462
- catch { /* ignore */ }
463
- return counts;
464
- }
465
- catch (err) {
466
- warnOnce('count read', err);
467
- return null;
468
- }
469
- }
470
- /** The last breakdown this origin read, or null. Same job as
471
- * {@link cachedUserCounts}: the popup paints the previous answer at once and
472
- * swaps it for the fresh one when it lands, rather than opening empty. */
473
- export function cachedUserCountsByProduct() {
474
- if (typeof window === 'undefined')
475
- return null;
476
- try {
477
- const raw = JSON.parse(window.localStorage.getItem(BREAKDOWN_KEY) ?? 'null');
478
- const rows = Array.isArray(raw) ? raw.map(asProductCounts).filter(isRow) : [];
479
- return rows.length > 0 ? rows : null;
480
- }
481
- catch { /* ignore */ }
482
- return null;
483
- }
484
- function isRow(row) {
485
- return row !== null;
486
- }
487
- function asProductCounts(row) {
488
- const product = row?.product;
489
- if (typeof product !== 'string')
490
- return null;
491
- const counts = readCounts(row);
492
- return counts ? { product, ...counts } : null;
493
- }
494
- /**
495
- * `{ product, total, live, web, native }` for every product anybody has ever
496
- * opened, biggest first — the breakdown behind the suite figure (migration
497
- * 0184).
498
- *
499
- * Resolves null on any failure, exactly like {@link fetchUserCounts}, so a
500
- * caller shows nothing rather than a wrong number. ⚠️ **That includes an app
501
- * running against a database where 0184 has not been applied yet** — the SDK
502
- * ships to npm and reaches consumers on their own schedule, so "the function
503
- * is not there" is a normal state, not an error to shout about. It warns once,
504
- * like every other read here.
505
- *
506
- * ⚠️ The rows do NOT sum to `fetchUserCounts(_, _, 'suite').total`: an account
507
- * using four apps is four rows here and one person there. Never add them up to
508
- * produce a total — the suite figure is the total.
509
- *
510
- * ⚠️ `web`/`native` are null on a row whose total comes from that app's own
511
- * account counter (migration 0185, the Bipolar apps): the counter has no
512
- * platform in it, so a split beside it would describe a different, smaller
513
- * population than the total next to it.
514
- */
515
- export async function fetchUserCountsByProduct(supabase) {
516
- if (typeof supabase?.rpc !== 'function')
517
- return null;
518
- try {
519
- const { data, error } = await supabase.rpc('suite_user_counts_by_product');
520
- if (error) {
521
- warnOnce('count breakdown read', error);
522
- return null;
523
- }
524
- const rows = (Array.isArray(data) ? data : []);
525
- const counts = [];
526
- for (const row of rows) {
527
- const parsed = asProductCounts(row);
528
- if (parsed)
529
- counts.push(parsed);
530
- }
531
- if (counts.length === 0)
532
- return null;
533
- // The server already orders by total; sorting again costs nothing and means
534
- // the popup is right even if a future caller hands rows over unordered.
535
- counts.sort((a, b) => b.total - a.total || a.product.localeCompare(b.product));
536
- try {
537
- window.localStorage.setItem(BREAKDOWN_KEY, JSON.stringify(counts));
538
- }
539
- catch { /* ignore */ }
540
- return counts;
541
- }
542
- catch (err) {
543
- warnOnce('count breakdown read', err);
544
- return null;
545
- }
546
- }
547
- const ID_COUNTS_KEY = 'unisim:user-counts:universal-ids';
548
- function readIdCounts(row) {
549
- const r = row;
550
- const created = Number(r?.created);
551
- const live = Number(r?.live);
552
- if (!Number.isFinite(created) || !Number.isFinite(live))
553
- return null;
554
- return { created, live };
555
- }
556
- /** The last Universal ID counts this origin read, or null. */
557
- export function cachedUniversalIdCounts() {
558
- if (typeof window === 'undefined')
559
- return null;
560
- try {
561
- return readIdCounts(JSON.parse(window.localStorage.getItem(ID_COUNTS_KEY) ?? 'null'));
562
- }
563
- catch { /* ignore */ }
564
- return null;
565
- }
566
- /**
567
- * `{ created, live }` for Universal IDs — the row at the top of the breakdown
568
- * (James, 2026-09-27). Resolves null on any failure, including a database
569
- * without migration 0188, so the popup leaves the row out rather than showing
570
- * a wrong number.
571
- */
572
- export async function fetchUniversalIdCounts(supabase) {
573
- if (typeof supabase?.rpc !== 'function')
574
- return null;
575
- try {
576
- const { data, error } = await supabase.rpc('universal_id_counts');
577
- if (error) {
578
- warnOnce('universal id read', error);
579
- return null;
580
- }
581
- const counts = readIdCounts(Array.isArray(data) ? data[0] : data);
582
- if (!counts)
583
- return null;
584
- try {
585
- window.localStorage.setItem(ID_COUNTS_KEY, JSON.stringify(counts));
586
- }
587
- catch { /* ignore */ }
588
- return counts;
589
- }
590
- catch (err) {
591
- warnOnce('universal id read', err);
592
- return null;
593
- }
594
- }
595
- /** "52 created", "2 live" — the Universal IDs row's figures, as separate
596
- * phrases for the same reason as {@link userCountParts}. */
597
- export function universalIdParts(language, counts) {
598
- const nf = numberFormat(language);
599
- return [
600
- t(language, 'users.part_created').replace('{n}', nf.format(counts.created)),
601
- t(language, 'users.part_live').replace('{n}', nf.format(counts.live)),
602
- ];
603
- }
604
- /**
605
- * "1,234 PDF users (5 live)" — or, for the 'suite' scope, "1,234 UNI·SIM Users
606
- * (5 live)" (James, 2026-09-27) — in `language`, with the numbers grouped the
607
- * way that language groups them.
608
- *
609
- * `appName` is the app's short name ("PDF", "Fire Assess"; see
610
- * `productShortName`). It is passed in because this file imports nothing
611
- * React, and the names live beside the switcher. Without it the app line reads
612
- * "1,234 users (5 live)".
613
- */
614
- export function formatUserCounts(language, counts, scope = 'app', appName) {
615
- const nf = numberFormat(language);
616
- const one = counts.total === 1;
617
- const key = scope === 'suite'
618
- ? (one ? 'users.suite_one' : 'users.suite_other')
619
- : (one ? 'users.count_one' : 'users.count_other');
620
- return t(language, key)
621
- .replace('{total}', nf.format(counts.total))
622
- .replace('{live}', nf.format(counts.live))
623
- .replace('{app}', appName?.trim() || '')
624
- // No name: "1,234 users", "1 234 utilisateurs de (…)". Tidy what the
625
- // empty slot leaves behind rather than keeping a second set of strings.
626
- .replace(/\s{2,}/g, ' ')
627
- .replace(/ (de|di|von) (?=\()/, ' ');
628
- }
629
- /**
630
- * The figures behind one row of the breakdown, as separate phrases — "1,234
631
- * users", "900 web", "334 native", "5 live" — so the caller can lay them out
632
- * and let them WRAP rather than measuring a single string (James, 2026-09-21:
633
- * "show web | native | live if there's enough space").
634
- *
635
- * The split is left out entirely when it is not available, rather than shown as
636
- * "0 web · 0 native": see {@link UserCounts.web}.
637
- */
638
- export function userCountParts(language, counts) {
639
- const nf = numberFormat(language);
640
- const say = (key, n) => t(language, key).replace('{n}', nf.format(n));
641
- return splitFigures(counts).map(([kind, n]) => say(PART_KEYS[kind](n), n));
642
- }
643
- const PART_KEYS = {
644
- total: (n) => (n === 1 ? 'users.part_total_one' : 'users.part_total'),
645
- web: () => 'users.part_web',
646
- native: () => 'users.part_native',
647
- ios: () => 'users.part_ios',
648
- android: () => 'users.part_android',
649
- desktop: () => 'users.part_desktop',
650
- live: () => 'users.part_live',
651
- };
652
- const FIGURE_EMOJI = {
653
- total: '🧑‍🤝‍🧑', web: '🕸️', native: '📱', ios: '🍎', android: '🤖', desktop: '💻', live: '🟢',
654
- };
655
- /**
656
- * Which figures a row shows, in order. The native figure is broken into iOS /
657
- * Android where the database gives that split (0261, 0.180.10) — plus the
658
- * desktop apps, but only when somebody is actually on one, so a row of phone
659
- * apps does not carry a "0 💻" that reads like a missing count.
660
- */
661
- function splitFigures(counts) {
662
- const out = [['total', counts.total]];
663
- if (typeof counts.web === 'number' && typeof counts.native === 'number') {
664
- out.push(['web', counts.web]);
665
- if (typeof counts.ios === 'number' && typeof counts.android === 'number') {
666
- out.push(['ios', counts.ios], ['android', counts.android]);
667
- const desktop = counts.native - counts.ios - counts.android;
668
- if (desktop > 0)
669
- out.push(['desktop', desktop]);
670
- }
671
- else {
672
- out.push(['native', counts.native]);
673
- }
674
- }
675
- out.push(['live', counts.live]);
676
- return out;
677
- }
678
- /**
679
- * James, 2026-09-29: "use emojis to make it more condensed: 57 🧑‍🤝‍🧑 | 51 🕸️ |
680
- * 6 ☎️ | 1 🟢" — and later that day, "replace red telephone counter with
681
- * 📱" (0.168.0). The same figures as {@link userCountParts} (and
682
- * {@link universalIdParts} when `counts` is a Universal ID count), each as a
683
- * number and an emoji, with the worded phrase kept as its spoken label so a
684
- * screen reader still says "51 web" rather than "51 spider web".
685
- */
686
- export function userCountFigures(language, counts) {
687
- const nf = numberFormat(language);
688
- const words = 'created' in counts ? universalIdParts(language, counts) : userCountParts(language, counts);
689
- const figures = 'created' in counts
690
- ? [['🪪', counts.created], ['🟢', counts.live]]
691
- : splitFigures(counts).map(([kind, n]) => [FIGURE_EMOJI[kind], n]);
692
- const emoji = figures.map(([e]) => e);
693
- const numbers = figures.map(([, n]) => n);
694
- const text = (n, i) => `${nf.format(n)} ${emoji[i]}`;
695
- return numbers.map((n, i) => ({ text: text(n, i), label: words[i] ?? text(n, i) }));
696
- }
697
- function numberFormat(language) {
698
- try {
699
- return new Intl.NumberFormat(language ?? undefined);
700
- }
701
- catch {
702
- return new Intl.NumberFormat('en');
703
- }
704
- }
705
361
  //# sourceMappingURL=presence.js.map