@ezychat/web 0.1.75 → 0.1.76

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.
@@ -0,0 +1,90 @@
1
+ // Runtime caching rules of the service worker (sw.ts). Pure: no workbox import and no service
2
+ // worker globals, so the rules can be unit-tested and the page can share the cache names.
3
+ // Only contact photos and message files are kept; API JSON never goes through these caches.
4
+
5
+ /** Contact and group member photos. */
6
+ export const AVATAR_CACHE = 'ezy-avatars-v1';
7
+ /** Message files (`/api/media/:id`). */
8
+ export const MEDIA_CACHE = 'ezy-media-v1';
9
+ /** Every version of the per-user caches: removed on sign-out and when another user signs in. */
10
+ export const USER_CACHE_PREFIXES = ['ezy-avatars-', 'ezy-media-'] as const;
11
+ /** Message the page posts to the service worker to remove the per-user caches. */
12
+ export const CLEAR_USER_CACHES = 'clear-user-caches';
13
+
14
+ const DAY_SECONDS = 24 * 60 * 60;
15
+ export const AVATAR_LIMITS = { maxEntries: 1000, maxAgeSeconds: 7 * DAY_SECONDS };
16
+ export const MEDIA_LIMITS = { maxEntries: 300, maxAgeSeconds: 30 * DAY_SECONDS };
17
+
18
+ /** `/api/chats/:jid/avatar` and `/api/chats/:groupJid/members/:member/avatar`. */
19
+ const AVATAR_PATH = /^\/api\/chats\/[^/]+\/(?:members\/[^/]+\/)?avatar$/;
20
+ /** `/api/media/:id` only (not `…/redownload`). */
21
+ const MEDIA_PATH = /^\/api\/media\/[^/]+$/;
22
+
23
+ type RouteRequest = Pick<Request, 'method' | 'cache' | 'headers'>;
24
+
25
+ /** A same-origin GET that does not ask to skip caches (`fetch(…, { cache: 'no-store' })`). */
26
+ function cacheableGet(url: URL, request: RouteRequest, origin: string): boolean {
27
+ return (
28
+ url.origin === origin &&
29
+ request.method === 'GET' &&
30
+ request.cache !== 'no-store' &&
31
+ request.cache !== 'reload'
32
+ );
33
+ }
34
+
35
+ export function isAvatarRequest(url: URL, request: RouteRequest, origin: string): boolean {
36
+ return cacheableGet(url, request, origin) && AVATAR_PATH.test(url.pathname);
37
+ }
38
+
39
+ /**
40
+ * Byte-range requests (audio and video players) stay on the network: a cached whole file cannot
41
+ * answer them, and a partial (206) answer is never stored.
42
+ */
43
+ export function isMediaRequest(url: URL, request: RouteRequest, origin: string): boolean {
44
+ return (
45
+ cacheableGet(url, request, origin) &&
46
+ MEDIA_PATH.test(url.pathname) &&
47
+ !request.headers.has('range')
48
+ );
49
+ }
50
+
51
+ /** Workbox plugin: never store a response the server marked `no-store` (e.g. a flagged file). */
52
+ export const noStorePlugin = {
53
+ cacheWillUpdate: ({ response }: { response: Response }): Promise<Response | null> =>
54
+ Promise.resolve(
55
+ /(^|[\s,])no-store($|[\s,;])/i.test(response.headers.get('cache-control') ?? '')
56
+ ? null
57
+ : response,
58
+ ),
59
+ };
60
+
61
+ /** Largest message file the phone keeps: one long video must not fill the phone's storage. */
62
+ export const MEDIA_MAX_BYTES = 20 * 1024 * 1024;
63
+
64
+ /** Workbox plugin for message files: never store one larger than MEDIA_MAX_BYTES. */
65
+ export const mediaSizePlugin = {
66
+ cacheWillUpdate: ({ response }: { response: Response }): Promise<Response | null> =>
67
+ Promise.resolve(
68
+ Number(response.headers.get('content-length') ?? 0) > MEDIA_MAX_BYTES ? null : response,
69
+ ),
70
+ };
71
+
72
+ export function isClearUserCachesMessage(data: unknown): boolean {
73
+ return (
74
+ typeof data === 'object' &&
75
+ data !== null &&
76
+ (data as { type?: unknown }).type === CLEAR_USER_CACHES
77
+ );
78
+ }
79
+
80
+ export function isUserCacheName(name: string): boolean {
81
+ return USER_CACHE_PREFIXES.some((prefix) => name.startsWith(prefix));
82
+ }
83
+
84
+ /** Removes the photo and file caches; the app's own precache stays. */
85
+ export async function deleteUserCaches(
86
+ storage: Pick<CacheStorage, 'keys' | 'delete'>,
87
+ ): Promise<void> {
88
+ const names = await storage.keys();
89
+ await Promise.all(names.filter(isUserCacheName).map((name) => storage.delete(name)));
90
+ }
package/dist-lib/sw.ts CHANGED
@@ -1,6 +1,22 @@
1
1
  /// <reference lib="webworker" />
2
2
  // Service worker (built by vite-plugin-pwa, strategies: 'injectManifest').
3
3
  import { cleanupOutdatedCaches, precacheAndRoute } from 'workbox-precaching';
4
+ import { registerRoute } from 'workbox-routing';
5
+ import { CacheFirst } from 'workbox-strategies';
6
+ import { ExpirationPlugin } from 'workbox-expiration';
7
+ import { CacheableResponsePlugin } from 'workbox-cacheable-response';
8
+ import {
9
+ AVATAR_CACHE,
10
+ AVATAR_LIMITS,
11
+ MEDIA_CACHE,
12
+ MEDIA_LIMITS,
13
+ deleteUserCaches,
14
+ isAvatarRequest,
15
+ isClearUserCachesMessage,
16
+ isMediaRequest,
17
+ mediaSizePlugin,
18
+ noStorePlugin,
19
+ } from './sw-routes';
4
20
 
5
21
  declare let self: ServiceWorkerGlobalScope & {
6
22
  __WB_MANIFEST: Array<string | { url: string; revision: string | null }>;
@@ -17,6 +33,30 @@ interface PushPayload {
17
33
  cleanupOutdatedCaches();
18
34
  precacheAndRoute(self.__WB_MANIFEST);
19
35
 
36
+ // Contact photos and message files are kept on the device (rules in sw-routes.ts). API JSON is
37
+ // never cached here. Only full 200 answers are stored, never one marked no-store.
38
+ const keptAnswers = (limits: { maxEntries: number; maxAgeSeconds: number }) => [
39
+ noStorePlugin,
40
+ new CacheableResponsePlugin({ statuses: [200] }),
41
+ new ExpirationPlugin({ ...limits, purgeOnQuotaError: true }),
42
+ ];
43
+ registerRoute(
44
+ ({ url, request }) => isAvatarRequest(url, request, self.location.origin),
45
+ new CacheFirst({ cacheName: AVATAR_CACHE, plugins: keptAnswers(AVATAR_LIMITS) }),
46
+ );
47
+ registerRoute(
48
+ ({ url, request }) => isMediaRequest(url, request, self.location.origin),
49
+ new CacheFirst({
50
+ cacheName: MEDIA_CACHE,
51
+ plugins: [mediaSizePlugin, ...keptAnswers(MEDIA_LIMITS)],
52
+ }),
53
+ );
54
+
55
+ // Sign-out or another user signing in: the page asks to remove the photos and files.
56
+ self.addEventListener('message', (event) => {
57
+ if (isClearUserCachesMessage(event.data)) event.waitUntil(deleteUserCaches(self.caches));
58
+ });
59
+
20
60
  // registerType 'autoUpdate': activate new versions immediately.
21
61
  self.addEventListener('install', () => {
22
62
  void self.skipWaiting();
@@ -126,7 +126,14 @@ export declare function useChangePassword(): import("@tanstack/react-query").Use
126
126
  currentPassword: string;
127
127
  newPassword: string;
128
128
  }, unknown>;
129
- export declare function useChats(filters: ChatFilters): import("@tanstack/react-query").UseInfiniteQueryResult<InfiniteData<{
129
+ /**
130
+ * `holdCached`: while true, a list that is already on screen (kept from the last visit or loaded
131
+ * earlier) does not refresh; a list with nothing to show still loads at once. The realtime
132
+ * connection sets it until it joins, because joining reloads every list (one load, not two).
133
+ */
134
+ export declare function useChats(filters: ChatFilters, opts?: {
135
+ holdCached?: boolean;
136
+ }): import("@tanstack/react-query").UseInfiniteQueryResult<InfiniteData<{
130
137
  chats: {
131
138
  jid: string;
132
139
  inboxId: number;
@@ -0,0 +1,3 @@
1
+ import { QueryClient } from '@tanstack/react-query';
2
+ /** The app's one QueryClient (tests use it too, so they run with the real defaults). */
3
+ export declare function createQueryClient(): QueryClient;
@@ -0,0 +1,43 @@
1
+ import { type QueryClient, type QueryKey } from '@tanstack/react-query';
2
+ export type KeyValueStorage = Pick<Storage, 'getItem' | 'setItem' | 'removeItem' | 'key' | 'length'>;
3
+ /** A saved copy older than this is not shown. */
4
+ export declare const PERSIST_MAX_AGE_MS: number;
5
+ /** Saves are grouped: at most one write per this delay. */
6
+ export declare const SAVE_DELAY_MS = 1000;
7
+ /** The id of the last user seen on this device (to notice a different user signing in). */
8
+ export declare const LAST_USER_KEY = "ezy.last-user";
9
+ interface QueryLike {
10
+ queryKey: QueryKey;
11
+ state: {
12
+ status: string;
13
+ data: unknown;
14
+ };
15
+ }
16
+ /** `localStorage`, or null where the browser refuses it. */
17
+ export declare function browserStorage(): KeyValueStorage | null;
18
+ /** The first screen only: user, setup status, inboxes, settings and chat lists without a search. */
19
+ export declare function shouldPersistQuery(query: QueryLike): boolean;
20
+ /**
21
+ * Before the first render: puts the last user's saved copy into the cache, marked stale so every
22
+ * kept query loads again as soon as it is used. A copy that is too old, from another build or not
23
+ * this user's is removed instead.
24
+ */
25
+ export declare function restorePersistedQueries(qc: QueryClient, { storage, buster, now, }: {
26
+ storage: KeyValueStorage | null;
27
+ buster: string;
28
+ now?: number;
29
+ }): void;
30
+ /**
31
+ * Saves the kept queries of the signed-in user while the app runs. When the session ends (sign-out,
32
+ * a 401 for a disabled user or a revoked session) the saved copy is removed and `clearCaches` runs
33
+ * (it removes the photo and file caches); when a different user signs in, the earlier user's data
34
+ * also leaves memory. `clearCaches` runs once per user who leaves.
35
+ */
36
+ export declare function startQueryPersistence(qc: QueryClient, { storage, buster, clearCaches, }: {
37
+ storage: KeyValueStorage | null;
38
+ buster: string;
39
+ clearCaches: () => void;
40
+ }): () => void;
41
+ /** Removes every user's saved copy (sign-out). */
42
+ export declare function dropPersistedQueries(storage: KeyValueStorage | null): void;
43
+ export {};
@@ -7,9 +7,17 @@ export interface TypingEntry {
7
7
  }
8
8
  export interface RealtimeValue {
9
9
  connected: boolean;
10
+ /**
11
+ * Lists may refresh now: the live connection is up (or there is none to wait for, or it did not
12
+ * come within SOCKET_WAIT_MS). While it is down, a list already on screen waits for it: the
13
+ * connection reloads every list when it joins, so loading before would load twice.
14
+ */
15
+ refreshReady: boolean;
10
16
  typing: Record<string, TypingEntry[]>;
11
17
  emitTyping(jid: string): void;
12
18
  }
19
+ /** How long a kept chat list waits for the live connection before it loads anyway. */
20
+ export declare const SOCKET_WAIT_MS = 4000;
13
21
  /**
14
22
  * When a load of `queryKey` is running, load it again after it ends: that load was answered before
15
23
  * the event that called this, so its result would hide the event's change. (React Query reuses a
@@ -7,7 +7,7 @@ export declare function useVoiceStatus(): import("@tanstack/react-query").UseQue
7
7
  state: "error" | "not_installed" | "downloading" | "installed";
8
8
  receivedBytes: number;
9
9
  totalBytes: number;
10
- error: "network" | "unknown" | "write" | "disk_space" | "verification" | "redirect" | null;
10
+ error: "network" | "redirect" | "unknown" | "write" | "disk_space" | "verification" | null;
11
11
  };
12
12
  cloudAvailable: boolean;
13
13
  }, Error>;
@@ -27,7 +27,7 @@ export declare function useVoiceAction(): import("@tanstack/react-query").UseMut
27
27
  state: "error" | "not_installed" | "downloading" | "installed";
28
28
  receivedBytes: number;
29
29
  totalBytes: number;
30
- error: "network" | "unknown" | "write" | "disk_space" | "verification" | "redirect" | null;
30
+ error: "network" | "redirect" | "unknown" | "write" | "disk_space" | "verification" | null;
31
31
  };
32
32
  cloudAvailable: boolean;
33
33
  }, Error, VoiceAction, unknown>;
@@ -0,0 +1,2 @@
1
+ /** Never throws or hangs: sign-out must finish even where the browser refuses storage or caches. */
2
+ export declare function clearUserCaches(): Promise<void>;
@@ -1,5 +1,4 @@
1
- /** One connection generation shared by every photo, including list and conversation copies. */
1
+ /** Photos load only while WhatsApp is connected; shared by list and conversation copies. */
2
2
  export declare const ProfileImageContext: import("react").Context<{
3
3
  ready: boolean;
4
- revision: number;
5
4
  }>;
@@ -0,0 +1,42 @@
1
+ /** Contact and group member photos. */
2
+ export declare const AVATAR_CACHE = "ezy-avatars-v1";
3
+ /** Message files (`/api/media/:id`). */
4
+ export declare const MEDIA_CACHE = "ezy-media-v1";
5
+ /** Every version of the per-user caches: removed on sign-out and when another user signs in. */
6
+ export declare const USER_CACHE_PREFIXES: readonly ["ezy-avatars-", "ezy-media-"];
7
+ /** Message the page posts to the service worker to remove the per-user caches. */
8
+ export declare const CLEAR_USER_CACHES = "clear-user-caches";
9
+ export declare const AVATAR_LIMITS: {
10
+ maxEntries: number;
11
+ maxAgeSeconds: number;
12
+ };
13
+ export declare const MEDIA_LIMITS: {
14
+ maxEntries: number;
15
+ maxAgeSeconds: number;
16
+ };
17
+ type RouteRequest = Pick<Request, 'method' | 'cache' | 'headers'>;
18
+ export declare function isAvatarRequest(url: URL, request: RouteRequest, origin: string): boolean;
19
+ /**
20
+ * Byte-range requests (audio and video players) stay on the network: a cached whole file cannot
21
+ * answer them, and a partial (206) answer is never stored.
22
+ */
23
+ export declare function isMediaRequest(url: URL, request: RouteRequest, origin: string): boolean;
24
+ /** Workbox plugin: never store a response the server marked `no-store` (e.g. a flagged file). */
25
+ export declare const noStorePlugin: {
26
+ cacheWillUpdate: ({ response }: {
27
+ response: Response;
28
+ }) => Promise<Response | null>;
29
+ };
30
+ /** Largest message file the phone keeps: one long video must not fill the phone's storage. */
31
+ export declare const MEDIA_MAX_BYTES: number;
32
+ /** Workbox plugin for message files: never store one larger than MEDIA_MAX_BYTES. */
33
+ export declare const mediaSizePlugin: {
34
+ cacheWillUpdate: ({ response }: {
35
+ response: Response;
36
+ }) => Promise<Response | null>;
37
+ };
38
+ export declare function isClearUserCachesMessage(data: unknown): boolean;
39
+ export declare function isUserCacheName(name: string): boolean;
40
+ /** Removes the photo and file caches; the app's own precache stays. */
41
+ export declare function deleteUserCaches(storage: Pick<CacheStorage, 'keys' | 'delete'>): Promise<void>;
42
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ezychat/web",
3
- "version": "0.1.75",
3
+ "version": "0.1.76",
4
4
  "type": "module",
5
5
  "description": "EzyChat core: the team inbox web app (React) as a library, with createInboxApp and its extension API.",
6
6
  "license": "MIT",
@@ -40,7 +40,7 @@
40
40
  "build:lib": "node ../../scripts/build-web-lib.mjs"
41
41
  },
42
42
  "dependencies": {
43
- "@ezychat/shared": "0.1.75",
43
+ "@ezychat/shared": "0.1.76",
44
44
  "@fontsource-variable/inter": "^5.3.0",
45
45
  "@tanstack/react-query": "^5.105.0",
46
46
  "@types/react": "^19.3.0",
@@ -81,7 +81,11 @@
81
81
  "tailwindcss": "^4.3.3",
82
82
  "vite": "^8.3.5",
83
83
  "vite-plugin-pwa": "^2.0.0",
84
+ "workbox-cacheable-response": "^7.4.1",
85
+ "workbox-expiration": "^7.4.1",
84
86
  "workbox-precaching": "^7.4.1",
87
+ "workbox-routing": "^7.4.1",
88
+ "workbox-strategies": "^7.4.1",
85
89
  "workbox-window": "^7.4.1"
86
90
  }
87
91
  }