@rpcbase/client 0.435.0 → 0.437.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/dist/index.js CHANGED
@@ -2255,6 +2255,20 @@ const markNotificationRead = async (notificationId) => {
2255
2255
  throw new Error(result?.error || "Failed to mark notification read");
2256
2256
  }
2257
2257
  };
2258
+ const markNotificationsReadByUrl = async (url) => {
2259
+ const normalizedUrl = url.trim();
2260
+ if (!normalizedUrl) throw new Error("url is required");
2261
+ const result = await apiClient.post("/api/rb/notifications/mark-read-by-url", {
2262
+ url: normalizedUrl
2263
+ });
2264
+ if (!result?.ok) {
2265
+ throw new Error(result?.error || "Failed to mark notifications read");
2266
+ }
2267
+ return {
2268
+ matchedCount: Number.isFinite(result.matchedCount) ? Math.max(0, Math.floor(result.matchedCount ?? 0)) : 0,
2269
+ modifiedCount: Number.isFinite(result.modifiedCount) ? Math.max(0, Math.floor(result.modifiedCount ?? 0)) : 0
2270
+ };
2271
+ };
2258
2272
  const archiveNotification = async (notificationId) => {
2259
2273
  const id = notificationId.trim();
2260
2274
  if (!id) throw new Error("notificationId is required");
@@ -2303,6 +2317,17 @@ const runNotificationDigest = async ({
2303
2317
  skippedReason: result.skippedReason
2304
2318
  };
2305
2319
  };
2320
+ const NEW_NOTIFICATION_START_TOLERANCE_MS = 5e3;
2321
+ const NATIVE_NOTIFICATION_TAG_PREFIX = "rb-notification";
2322
+ const ACTIVE_TAB_HEARTBEAT_MS = 5e3;
2323
+ const ACTIVE_TAB_TTL_MS = 15e3;
2324
+ const DELIVERY_TTL_MS = 10 * 60 * 1e3;
2325
+ const FALLBACK_DELIVERY_LOCK_TTL_MS = 2e3;
2326
+ const TAB_STATE_KEY_PREFIX = "rb:notifications:tab:";
2327
+ const DELIVERY_KEY_PREFIX = "rb:notifications:delivery:";
2328
+ const DELIVERY_LOCK_PREFIX = "rb-notifications-delivery:";
2329
+ const FALLBACK_DELIVERY_LOCK_KEY_PREFIX = "rb:notifications:delivery-lock:";
2330
+ const NOTIFICATION_TAB_ID = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
2306
2331
  const NotificationsRealtimeContext = createContext(null);
2307
2332
  const toIso = (value) => {
2308
2333
  if (value instanceof Date) return value.toISOString();
@@ -2337,8 +2362,267 @@ const buildDisabledTopics = (settings) => {
2337
2362
  return pref.inApp === false ? topic : null;
2338
2363
  }).filter((topic) => Boolean(topic));
2339
2364
  };
2365
+ const getWebpushLink = (item) => {
2366
+ const platformWebpush = item.platform?.webpush;
2367
+ if (!platformWebpush || typeof platformWebpush !== "object" || Array.isArray(platformWebpush)) return "";
2368
+ const fcmOptions = platformWebpush.fcmOptions;
2369
+ if (!fcmOptions || typeof fcmOptions !== "object" || Array.isArray(fcmOptions)) return "";
2370
+ return typeof fcmOptions.link === "string" ? fcmOptions.link : "";
2371
+ };
2372
+ const getScopedUserKey = (userId) => encodeURIComponent(userId);
2373
+ const getTabStateKey = (userId) => `${TAB_STATE_KEY_PREFIX}${getScopedUserKey(userId)}:${NOTIFICATION_TAB_ID}`;
2374
+ const getTabStateKeyPrefix = (userId) => `${TAB_STATE_KEY_PREFIX}${getScopedUserKey(userId)}:`;
2375
+ const getDeliveryKey = (userId, notificationId) => `${DELIVERY_KEY_PREFIX}${getScopedUserKey(userId)}:${encodeURIComponent(notificationId)}`;
2376
+ const getDeliveryLockName = (userId) => `${DELIVERY_LOCK_PREFIX}${getScopedUserKey(userId)}`;
2377
+ const getFallbackDeliveryLockKey = (userId) => `${FALLBACK_DELIVERY_LOCK_KEY_PREFIX}${getScopedUserKey(userId)}`;
2378
+ const getLocalStorage = () => {
2379
+ if (typeof window === "undefined") return null;
2380
+ try {
2381
+ return window.localStorage;
2382
+ } catch {
2383
+ return null;
2384
+ }
2385
+ };
2386
+ const parseJsonRecord = (value) => {
2387
+ if (!value) return null;
2388
+ try {
2389
+ const parsed = JSON.parse(value);
2390
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
2391
+ return parsed;
2392
+ } catch {
2393
+ return null;
2394
+ }
2395
+ };
2396
+ const getLockManager = () => {
2397
+ if (typeof navigator === "undefined") return null;
2398
+ const locks = navigator.locks;
2399
+ return locks && typeof locks.request === "function" ? locks : null;
2400
+ };
2401
+ const isDocumentActive = () => {
2402
+ if (typeof document === "undefined") return false;
2403
+ return document.visibilityState === "visible" && document.hasFocus();
2404
+ };
2405
+ const writeNotificationTabState = (userId) => {
2406
+ const storage = getLocalStorage();
2407
+ if (!storage) return;
2408
+ const state = {
2409
+ tabId: NOTIFICATION_TAB_ID,
2410
+ active: isDocumentActive(),
2411
+ updatedAt: Date.now()
2412
+ };
2413
+ try {
2414
+ storage.setItem(getTabStateKey(userId), JSON.stringify(state));
2415
+ } catch {
2416
+ return;
2417
+ }
2418
+ };
2419
+ const removeNotificationTabState = (userId) => {
2420
+ const storage = getLocalStorage();
2421
+ if (!storage) return;
2422
+ try {
2423
+ storage.removeItem(getTabStateKey(userId));
2424
+ } catch {
2425
+ return;
2426
+ }
2427
+ };
2428
+ const hasActiveNotificationTab = (userId) => {
2429
+ const storage = getLocalStorage();
2430
+ if (!storage) return false;
2431
+ const prefix = getTabStateKeyPrefix(userId);
2432
+ const now = Date.now();
2433
+ try {
2434
+ for (let index = storage.length - 1; index >= 0; index -= 1) {
2435
+ const key = storage.key(index);
2436
+ if (!key?.startsWith(prefix)) continue;
2437
+ const record = parseJsonRecord(storage.getItem(key));
2438
+ const updatedAt = typeof record?.updatedAt === "number" ? record.updatedAt : 0;
2439
+ if (!updatedAt || now - updatedAt > ACTIVE_TAB_TTL_MS) {
2440
+ storage.removeItem(key);
2441
+ continue;
2442
+ }
2443
+ if (record?.active === true) return true;
2444
+ }
2445
+ } catch {
2446
+ return false;
2447
+ }
2448
+ return false;
2449
+ };
2450
+ const claimNotificationDeliveriesFromStorage = (items, userId, mode) => {
2451
+ const storage = getLocalStorage();
2452
+ if (!storage) return items;
2453
+ const now = Date.now();
2454
+ const claimed = [];
2455
+ for (const item of items) {
2456
+ const key = getDeliveryKey(userId, item.id);
2457
+ const current = parseJsonRecord(storage.getItem(key));
2458
+ const deliveredAt = typeof current?.deliveredAt === "number" ? current.deliveredAt : 0;
2459
+ if (deliveredAt && now - deliveredAt < DELIVERY_TTL_MS) continue;
2460
+ const marker = {
2461
+ tabId: NOTIFICATION_TAB_ID,
2462
+ mode,
2463
+ deliveredAt: now
2464
+ };
2465
+ try {
2466
+ storage.setItem(key, JSON.stringify(marker));
2467
+ const stored = parseJsonRecord(storage.getItem(key));
2468
+ if (stored?.tabId === NOTIFICATION_TAB_ID && stored.deliveredAt === now) {
2469
+ claimed.push(item);
2470
+ }
2471
+ } catch {
2472
+ claimed.push(item);
2473
+ }
2474
+ }
2475
+ return claimed;
2476
+ };
2477
+ const acquireFallbackDeliveryLock = (userId) => {
2478
+ const storage = getLocalStorage();
2479
+ if (!storage) {
2480
+ return {
2481
+ token: `${NOTIFICATION_TAB_ID}:memory`,
2482
+ expiresAt: Date.now() + FALLBACK_DELIVERY_LOCK_TTL_MS
2483
+ };
2484
+ }
2485
+ const key = getFallbackDeliveryLockKey(userId);
2486
+ const now = Date.now();
2487
+ try {
2488
+ const current = parseJsonRecord(storage.getItem(key));
2489
+ const currentExpiresAt = typeof current?.expiresAt === "number" ? current.expiresAt : 0;
2490
+ if (currentExpiresAt > now && current?.token !== void 0) return null;
2491
+ const marker = {
2492
+ token: `${NOTIFICATION_TAB_ID}:${now}:${Math.random().toString(36).slice(2)}`,
2493
+ expiresAt: now + FALLBACK_DELIVERY_LOCK_TTL_MS
2494
+ };
2495
+ storage.setItem(key, JSON.stringify(marker));
2496
+ const stored = parseJsonRecord(storage.getItem(key));
2497
+ return stored?.token === marker.token ? marker : null;
2498
+ } catch {
2499
+ return {
2500
+ token: `${NOTIFICATION_TAB_ID}:memory`,
2501
+ expiresAt: now + FALLBACK_DELIVERY_LOCK_TTL_MS
2502
+ };
2503
+ }
2504
+ };
2505
+ const releaseFallbackDeliveryLock = (userId, marker) => {
2506
+ const storage = getLocalStorage();
2507
+ if (!storage) return;
2508
+ const key = getFallbackDeliveryLockKey(userId);
2509
+ try {
2510
+ const stored = parseJsonRecord(storage.getItem(key));
2511
+ if (stored?.token === marker.token) {
2512
+ storage.removeItem(key);
2513
+ }
2514
+ } catch {
2515
+ return;
2516
+ }
2517
+ };
2518
+ const withFallbackDeliveryLock = (userId, callback, fallback) => {
2519
+ const marker = acquireFallbackDeliveryLock(userId);
2520
+ if (!marker) return fallback;
2521
+ try {
2522
+ return callback();
2523
+ } finally {
2524
+ releaseFallbackDeliveryLock(userId, marker);
2525
+ }
2526
+ };
2527
+ const claimNotificationDeliveries = async (items, userId, mode) => {
2528
+ if (items.length === 0) return [];
2529
+ const claim = () => {
2530
+ if (mode === "native" && hasActiveNotificationTab(userId)) return [];
2531
+ return claimNotificationDeliveriesFromStorage(items, userId, mode);
2532
+ };
2533
+ const locks = getLockManager();
2534
+ if (!locks) return withFallbackDeliveryLock(userId, claim, []);
2535
+ try {
2536
+ const claimed = await locks.request(getDeliveryLockName(userId), {
2537
+ mode: "exclusive",
2538
+ ifAvailable: true
2539
+ }, (lock) => {
2540
+ if (!lock) return [];
2541
+ return claim();
2542
+ });
2543
+ return Array.isArray(claimed) ? claimed : [];
2544
+ } catch {
2545
+ return claim();
2546
+ }
2547
+ };
2548
+ const showInAppNotifications = (items) => {
2549
+ if (items.length > 3) {
2550
+ toast(`${items.length} new notifications`, {
2551
+ description: "Open the notifications drawer to view them."
2552
+ });
2553
+ return;
2554
+ }
2555
+ for (const item of items) {
2556
+ toast(item.title, {
2557
+ description: item.body
2558
+ });
2559
+ }
2560
+ };
2561
+ const canShowNativeNotification = () => {
2562
+ if (typeof window === "undefined") return false;
2563
+ if (!("Notification" in window)) return false;
2564
+ return window.Notification.permission === "granted";
2565
+ };
2566
+ const focusNotificationLink = (link) => {
2567
+ window.focus();
2568
+ if (link) {
2569
+ window.location.href = link;
2570
+ }
2571
+ };
2572
+ const showNativeNotification = (item) => {
2573
+ if (!canShowNativeNotification()) return;
2574
+ try {
2575
+ const link = getWebpushLink(item);
2576
+ const browserNotification = new window.Notification(item.title, {
2577
+ body: item.body,
2578
+ icon: item.image,
2579
+ tag: `${NATIVE_NOTIFICATION_TAG_PREFIX}:${item.id}`,
2580
+ data: {
2581
+ ...item.data,
2582
+ notificationId: item.id,
2583
+ link
2584
+ }
2585
+ });
2586
+ browserNotification.onclick = () => focusNotificationLink(link);
2587
+ } catch {
2588
+ return;
2589
+ }
2590
+ };
2591
+ const showNativeNotifications = (items) => {
2592
+ if (!canShowNativeNotification()) return;
2593
+ if (items.length > 3) {
2594
+ try {
2595
+ const browserNotification = new window.Notification(`${items.length} new notifications`, {
2596
+ body: "Open the notifications drawer to view them.",
2597
+ tag: `${NATIVE_NOTIFICATION_TAG_PREFIX}:summary`
2598
+ });
2599
+ browserNotification.onclick = () => focusNotificationLink("");
2600
+ } catch {
2601
+ return;
2602
+ }
2603
+ return;
2604
+ }
2605
+ for (const item of items) {
2606
+ showNativeNotification(item);
2607
+ }
2608
+ };
2609
+ const showNotificationsForCurrentFocusState = async (items, userId) => {
2610
+ writeNotificationTabState(userId);
2611
+ if (isDocumentActive()) {
2612
+ const claimed2 = await claimNotificationDeliveries(items, userId, "in-app");
2613
+ if (claimed2.length > 0) {
2614
+ showInAppNotifications(claimed2);
2615
+ }
2616
+ return;
2617
+ }
2618
+ if (!canShowNativeNotification()) return;
2619
+ const claimed = await claimNotificationDeliveries(items, userId, "native");
2620
+ if (claimed.length > 0) {
2621
+ showNativeNotifications(claimed);
2622
+ }
2623
+ };
2340
2624
  function NotificationsRealtimeProvider(t0) {
2341
- const $ = c(47);
2625
+ const $ = c(52);
2342
2626
  const {
2343
2627
  userId,
2344
2628
  limit: t1,
@@ -2547,8 +2831,47 @@ function NotificationsRealtimeProvider(t0) {
2547
2831
  useEffect(t15, t16);
2548
2832
  let t17;
2549
2833
  let t18;
2550
- if ($[32] !== canUseRts || $[33] !== notifications || $[34] !== notificationsQuery.loading || $[35] !== toastOnNew) {
2834
+ if ($[32] !== canUseRts || $[33] !== trimmedUserId) {
2551
2835
  t17 = () => {
2836
+ if (!canUseRts) {
2837
+ return;
2838
+ }
2839
+ if (typeof window === "undefined" || typeof document === "undefined") {
2840
+ return;
2841
+ }
2842
+ const writeState = () => writeNotificationTabState(trimmedUserId);
2843
+ const removeState = () => removeNotificationTabState(trimmedUserId);
2844
+ writeState();
2845
+ const intervalId = window.setInterval(writeState, ACTIVE_TAB_HEARTBEAT_MS);
2846
+ window.addEventListener("focus", writeState);
2847
+ window.addEventListener("blur", writeState);
2848
+ window.addEventListener("pageshow", writeState);
2849
+ window.addEventListener("pagehide", removeState);
2850
+ document.addEventListener("visibilitychange", writeState);
2851
+ return () => {
2852
+ window.clearInterval(intervalId);
2853
+ window.removeEventListener("focus", writeState);
2854
+ window.removeEventListener("blur", writeState);
2855
+ window.removeEventListener("pageshow", writeState);
2856
+ window.removeEventListener("pagehide", removeState);
2857
+ document.removeEventListener("visibilitychange", writeState);
2858
+ removeState();
2859
+ };
2860
+ };
2861
+ t18 = [canUseRts, trimmedUserId];
2862
+ $[32] = canUseRts;
2863
+ $[33] = trimmedUserId;
2864
+ $[34] = t17;
2865
+ $[35] = t18;
2866
+ } else {
2867
+ t17 = $[34];
2868
+ t18 = $[35];
2869
+ }
2870
+ useEffect(t17, t18);
2871
+ let t19;
2872
+ let t20;
2873
+ if ($[36] !== canUseRts || $[37] !== notifications || $[38] !== notificationsQuery.loading || $[39] !== toastOnNew || $[40] !== trimmedUserId) {
2874
+ t19 = () => {
2552
2875
  if (!toastOnNew) {
2553
2876
  return;
2554
2877
  }
@@ -2561,83 +2884,80 @@ function NotificationsRealtimeProvider(t0) {
2561
2884
  if (!hasSeededToastIds.current) {
2562
2885
  hasSeededToastIds.current = true;
2563
2886
  lastToastIds.current = new Set(notifications.map(_temp5));
2887
+ const eligible = notifications.filter((n_3) => {
2888
+ const createdAtMs = Date.parse(n_3.createdAt);
2889
+ if (!Number.isFinite(createdAtMs)) {
2890
+ return false;
2891
+ }
2892
+ return createdAtMs >= toastStartMs.current - NEW_NOTIFICATION_START_TOLERANCE_MS;
2893
+ });
2894
+ if (eligible.length) {
2895
+ showNotificationsForCurrentFocusState(eligible, trimmedUserId);
2896
+ }
2564
2897
  return;
2565
2898
  }
2566
- const nextNew = notifications.filter((n_3) => !lastToastIds.current.has(n_3.id));
2899
+ const nextNew = notifications.filter((n_4) => !lastToastIds.current.has(n_4.id));
2567
2900
  if (!nextNew.length) {
2568
2901
  return;
2569
2902
  }
2570
- for (const n_4 of nextNew) {
2571
- lastToastIds.current.add(n_4.id);
2903
+ for (const n_5 of nextNew) {
2904
+ lastToastIds.current.add(n_5.id);
2572
2905
  }
2573
- const isTabActive = typeof document !== "undefined" && document.visibilityState === "visible";
2574
- if (!isTabActive) {
2575
- return;
2576
- }
2577
- const eligible = nextNew.filter((n_5) => {
2578
- const createdAtMs = Date.parse(n_5.createdAt);
2579
- if (!Number.isFinite(createdAtMs)) {
2906
+ const eligible_0 = nextNew.filter((n_6) => {
2907
+ const createdAtMs_0 = Date.parse(n_6.createdAt);
2908
+ if (!Number.isFinite(createdAtMs_0)) {
2580
2909
  return true;
2581
2910
  }
2582
- return createdAtMs >= toastStartMs.current;
2911
+ return createdAtMs_0 >= toastStartMs.current;
2583
2912
  });
2584
- if (!eligible.length) {
2913
+ if (!eligible_0.length) {
2585
2914
  return;
2586
2915
  }
2587
- if (eligible.length > 3) {
2588
- toast(`${eligible.length} new notifications`, {
2589
- description: "Open the notifications drawer to view them."
2590
- });
2591
- return;
2592
- }
2593
- for (const n_6 of eligible) {
2594
- toast(n_6.title, {
2595
- description: n_6.body
2596
- });
2597
- }
2916
+ showNotificationsForCurrentFocusState(eligible_0, trimmedUserId);
2598
2917
  };
2599
- t18 = [canUseRts, notifications, notificationsQuery.loading, toastOnNew];
2600
- $[32] = canUseRts;
2601
- $[33] = notifications;
2602
- $[34] = notificationsQuery.loading;
2603
- $[35] = toastOnNew;
2604
- $[36] = t17;
2605
- $[37] = t18;
2918
+ t20 = [canUseRts, notifications, notificationsQuery.loading, toastOnNew, trimmedUserId];
2919
+ $[36] = canUseRts;
2920
+ $[37] = notifications;
2921
+ $[38] = notificationsQuery.loading;
2922
+ $[39] = toastOnNew;
2923
+ $[40] = trimmedUserId;
2924
+ $[41] = t19;
2925
+ $[42] = t20;
2606
2926
  } else {
2607
- t17 = $[36];
2608
- t18 = $[37];
2927
+ t19 = $[41];
2928
+ t20 = $[42];
2609
2929
  }
2610
- useEffect(t17, t18);
2611
- let t19;
2612
- if ($[38] !== notifications || $[39] !== notificationsQuery.error || $[40] !== notificationsQuery.loading || $[41] !== unreadCount || $[42] !== unseenCount) {
2613
- t19 = {
2930
+ useEffect(t19, t20);
2931
+ let t21;
2932
+ if ($[43] !== notifications || $[44] !== notificationsQuery.error || $[45] !== notificationsQuery.loading || $[46] !== unreadCount || $[47] !== unseenCount) {
2933
+ t21 = {
2614
2934
  notifications,
2615
2935
  unreadCount,
2616
2936
  unseenCount,
2617
2937
  loading: notificationsQuery.loading,
2618
2938
  error: notificationsQuery.error
2619
2939
  };
2620
- $[38] = notifications;
2621
- $[39] = notificationsQuery.error;
2622
- $[40] = notificationsQuery.loading;
2623
- $[41] = unreadCount;
2624
- $[42] = unseenCount;
2625
- $[43] = t19;
2940
+ $[43] = notifications;
2941
+ $[44] = notificationsQuery.error;
2942
+ $[45] = notificationsQuery.loading;
2943
+ $[46] = unreadCount;
2944
+ $[47] = unseenCount;
2945
+ $[48] = t21;
2626
2946
  } else {
2627
- t19 = $[43];
2628
- }
2629
- const value = t19;
2630
- const t20 = canUseRts ? value : null;
2631
- let t21;
2632
- if ($[44] !== children || $[45] !== t20) {
2633
- t21 = /* @__PURE__ */ jsx(NotificationsRealtimeContext.Provider, { value: t20, children });
2634
- $[44] = children;
2635
- $[45] = t20;
2636
- $[46] = t21;
2947
+ t21 = $[48];
2948
+ }
2949
+ const value = t21;
2950
+ const t22 = canUseRts ? value : null;
2951
+ let t23;
2952
+ if ($[49] !== children || $[50] !== t22) {
2953
+ t23 = /* @__PURE__ */ jsx(NotificationsRealtimeContext.Provider, { value: t22, children });
2954
+ $[49] = children;
2955
+ $[50] = t22;
2956
+ $[51] = t23;
2637
2957
  } else {
2638
- t21 = $[46];
2958
+ t23 = $[51];
2639
2959
  }
2640
- return t21;
2960
+ return t23;
2641
2961
  }
2642
2962
  function _temp5(n_2) {
2643
2963
  return n_2.id;
@@ -2679,6 +2999,7 @@ export {
2679
2999
  listNotifications,
2680
3000
  markAllNotificationsRead,
2681
3001
  markNotificationRead,
3002
+ markNotificationsReadByUrl,
2682
3003
  peekClientSsrErrorState,
2683
3004
  p as peekHydratedRtsCount,
2684
3005
  b as peekHydratedRtsQueryData,