@alexsun-top/opencode-chat-room 0.8.2 → 0.8.3

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 (92) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +18 -62
  3. package/README.zh-CN.md +25 -69
  4. package/dist/cli.js +466 -188
  5. package/package.json +8 -5
  6. package/packages/chat-room-channeld/README.md +25 -3
  7. package/packages/chat-room-channeld/dist/mock-adapter.js +5 -5
  8. package/packages/chat-room-channeld/src/adapter.ts +5 -0
  9. package/packages/chat-room-channeld/src/cli.ts +72 -5
  10. package/packages/chat-room-channeld/src/host.ts +17 -2
  11. package/packages/chat-room-channeld/src/pg/database.ts +187 -0
  12. package/packages/chat-room-channeld/src/pg/migrate.ts +150 -0
  13. package/packages/chat-room-channeld/src/pg/schema.ts +60 -0
  14. package/packages/chat-room-channeld/src/pg/sql.mjs +175 -0
  15. package/packages/chat-room-channeld/src/pg/sqlite.ts +100 -0
  16. package/packages/chat-room-channeld/src/pg/worker.mjs +133 -0
  17. package/packages/chat-room-channeld/src/protocol.ts +1 -0
  18. package/packages/chat-room-channeld/src/state.ts +73 -97
  19. package/packages/chat-room-channeld/src/stats.ts +140 -109
  20. package/server/assets/base.css +3 -1
  21. package/server/assets/chat/admin-badge.js +32 -30
  22. package/server/assets/chat/admin.js +198 -161
  23. package/server/assets/chat/announcements.js +295 -208
  24. package/server/assets/chat/attachment-store.js +106 -75
  25. package/server/assets/chat/attachments.js +686 -441
  26. package/server/assets/chat/chat-background.js +185 -156
  27. package/server/assets/chat/clipboard.js +44 -25
  28. package/server/assets/chat/confirm-dialog.js +36 -33
  29. package/server/assets/chat/copy-action.js +40 -40
  30. package/server/assets/chat/create-room-dialog.js +50 -47
  31. package/server/assets/chat/diagram-viewer.js +293 -234
  32. package/server/assets/chat/doc-preview.js +507 -441
  33. package/server/assets/chat/editor.js +423 -335
  34. package/server/assets/chat/events.js +637 -510
  35. package/server/assets/chat/files.js +476 -430
  36. package/server/assets/chat/history-loader.js +79 -73
  37. package/server/assets/chat/icons.js +9 -11
  38. package/server/assets/chat/image-zoom.js +239 -176
  39. package/server/assets/chat/index.js +2 -3
  40. package/server/assets/chat/install-prompt.js +86 -66
  41. package/server/assets/chat/integration-account-schema.js +88 -86
  42. package/server/assets/chat/integration-editor.js +162 -153
  43. package/server/assets/chat/integration-values.js +109 -100
  44. package/server/assets/chat/integrations.js +689 -622
  45. package/server/assets/chat/join-requests.js +408 -358
  46. package/server/assets/chat/locales/de.js +193 -194
  47. package/server/assets/chat/locales/es.js +193 -194
  48. package/server/assets/chat/locales/fr.js +193 -194
  49. package/server/assets/chat/locales/index.js +1 -2
  50. package/server/assets/chat/locales/it.js +193 -194
  51. package/server/assets/chat/locales/ja.js +193 -193
  52. package/server/assets/chat/locales/ko.js +193 -193
  53. package/server/assets/chat/markdown-footnotes.js +134 -102
  54. package/server/assets/chat/markdown.js +547 -403
  55. package/server/assets/chat/members.js +236 -197
  56. package/server/assets/chat/mentions.js +157 -133
  57. package/server/assets/chat/message-cache.js +40 -33
  58. package/server/assets/chat/message-polling.js +280 -227
  59. package/server/assets/chat/message-window.js +74 -55
  60. package/server/assets/chat/messages.js +552 -480
  61. package/server/assets/chat/office-preview.js +46 -45
  62. package/server/assets/chat/palette.js +450 -417
  63. package/server/assets/chat/panels.js +94 -78
  64. package/server/assets/chat/pwa.js +144 -73
  65. package/server/assets/chat/questions.js +372 -302
  66. package/server/assets/chat/recall.js +320 -273
  67. package/server/assets/chat/receipts.js +149 -121
  68. package/server/assets/chat/reminders.js +331 -214
  69. package/server/assets/chat/replies.js +165 -130
  70. package/server/assets/chat/resource-format.js +59 -62
  71. package/server/assets/chat/room-list.js +58 -55
  72. package/server/assets/chat/room-watcher.js +72 -50
  73. package/server/assets/chat/rooms.js +623 -500
  74. package/server/assets/chat/search.js +136 -114
  75. package/server/assets/chat/settings.js +223 -200
  76. package/server/assets/chat/shiki.js +61 -62
  77. package/server/assets/chat/shortcuts.js +212 -187
  78. package/server/assets/chat/side-pane.js +160 -150
  79. package/server/assets/chat/state.js +849 -735
  80. package/server/assets/chat/system-events.js +45 -43
  81. package/server/assets/chat/system-messages.js +57 -56
  82. package/server/assets/chat/task-form.js +178 -182
  83. package/server/assets/chat/task-row.js +158 -155
  84. package/server/assets/chat/tasks.js +653 -587
  85. package/server/assets/chat/viewport.js +32 -29
  86. package/server/assets/chat/window-controls.js +32 -32
  87. package/server/assets/conversation.css +10 -4
  88. package/server/chat-server.ts +9 -1
  89. package/server/chat.html +2 -1
  90. package/server/routes/pages.ts +7 -5
  91. package/server/sw.js +346 -268
  92. package/src/web/integration-rules-editor.ts +2 -0
package/server/sw.js CHANGED
@@ -1,40 +1,40 @@
1
+ "use strict";
1
2
  // The server fills in {{version}} so a release installs a worker that replaces the old cache.
2
3
  const VERSION = "{{version}}";
3
4
  const CACHE = `oc-chat-${VERSION}`;
4
5
  const SHELL = "/chat";
5
6
  const STATIC = [
6
- "/assets/base.css",
7
- "/assets/icons.css",
8
- "/assets/fluent-icons.svg",
9
- "/assets/settings.css",
10
- "/assets/conversation.css",
11
- "/assets/recall.css",
12
- "/assets/attachments.css",
13
- "/assets/responsive.css",
14
- "/assets/window-controls.css",
15
- "/assets/code-highlight.css",
16
- "/assets/room-create.css",
17
- "/assets/edit-room.css",
18
- "/assets/palette.css",
19
- "/assets/files.css",
20
- "/assets/tasks.css",
21
- "/assets/doc-preview.css",
22
- "/assets/diagram-viewer.css",
23
- "/assets/chat/office-preview.js",
24
- "/assets/office/docx.bundle.js",
25
- "/assets/office/xlsx.bundle.js",
26
- "/assets/office/pptx.bundle.js",
27
- "/assets/marked-18.0.4.js",
28
- "/assets/dompurify-3.4.7.js",
29
- "/assets/mermaid-11.12.2.min.js",
30
- "/assets/icons/icon-192.png",
31
- "/assets/icons/icon-512.png",
32
- "/assets/icons/apple-touch-icon.png",
33
- "/manifest.webmanifest",
7
+ "/assets/base.css",
8
+ "/assets/icons.css",
9
+ "/assets/fluent-icons.svg",
10
+ "/assets/settings.css",
11
+ "/assets/conversation.css",
12
+ "/assets/recall.css",
13
+ "/assets/attachments.css",
14
+ "/assets/responsive.css",
15
+ "/assets/window-controls.css",
16
+ "/assets/code-highlight.css",
17
+ "/assets/room-create.css",
18
+ "/assets/edit-room.css",
19
+ "/assets/palette.css",
20
+ "/assets/files.css",
21
+ "/assets/tasks.css",
22
+ "/assets/doc-preview.css",
23
+ "/assets/diagram-viewer.css",
24
+ "/assets/chat/office-preview.js",
25
+ "/assets/office/docx.bundle.js",
26
+ "/assets/office/xlsx.bundle.js",
27
+ "/assets/office/pptx.bundle.js",
28
+ "/assets/marked-18.0.4.js",
29
+ "/assets/dompurify-3.4.7.js",
30
+ "/assets/mermaid-11.12.2.min.js",
31
+ "/assets/icons/icon-192.png",
32
+ "/assets/icons/icon-512.png",
33
+ "/assets/icons/apple-touch-icon.png",
34
+ "/manifest.webmanifest",
34
35
  ];
35
36
  const VERSIONED = new Set(STATIC.filter((path) => path.endsWith(".css") || /^\/assets\/(?:marked|dompurify|mermaid)-/.test(path)));
36
37
  const versioned = (path) => `${path}?v=${VERSION}`;
37
-
38
38
  // Recently viewed images live in their own cache: a release upgrades CACHE, but a photo
39
39
  // should survive until the person changes identity, it ages out, or the caps evict it.
40
40
  const MEDIA_CACHE = "oc-chat-media";
@@ -46,292 +46,370 @@ const REVALIDATE_MS = 10 * 60 * 1000;
46
46
  const MEDIA_LIMITS = { entries: 80, bytes: 64 * 1024 * 1024, age: 30 * 24 * 60 * 60 * 1000 };
47
47
  // Tests lower these numbers before seeding entries; production keeps the values above.
48
48
  self.__MEDIA_LIMITS__ = MEDIA_LIMITS;
49
-
50
49
  // The page owns the identity (a hash of its token and session ID); this worker only
51
50
  // partitions the cache by it. Unknown identity means network-only.
52
51
  let mediaIdentity;
53
52
  let mediaQueue = Promise.resolve();
54
53
  const queueMedia = (task) => {
55
- const run = mediaQueue.then(task, task);
56
- mediaQueue = run.catch(() => {});
57
- return run;
54
+ const run = mediaQueue.then(task, task);
55
+ mediaQueue = run.catch(() => { });
56
+ return run;
58
57
  };
59
-
60
58
  self.addEventListener("install", (event) => {
61
- event.waitUntil((async () => {
62
- const cache = await caches.open(CACHE);
63
- // Stylesheets and classic scripts carry the release version. A client still
64
- // running an older worker therefore misses its old cache after a deploy instead
65
- // of mixing new HTML with stale styles.
66
- await cache.addAll([SHELL, ...STATIC.map((path) => VERSIONED.has(path) ? versioned(path) : path)]);
67
- // The shell is a module graph, so an offline start needs the imports too. Walk them
68
- // from the entry point instead of keeping a list that drifts with every new module.
69
- const pending = ["/assets/chat/index.js"], seen = new Set();
70
- while (pending.length) {
71
- const url = pending.pop();
72
- if (seen.has(url)) continue;
73
- seen.add(url);
74
- const response = await fetch(url).catch(() => null);
75
- if (!response?.ok) continue;
76
- const source = await response.clone().text();
77
- await cache.put(url, response);
78
- for (const match of source.matchAll(/(?:from\s+"|import\(\s*")(\.\.?\/[^"]+\.js)"/g)) {
79
- pending.push(new URL(match[1], `https://chat.invalid${url}`).pathname);
80
- }
81
- }
82
- // A first install should control immediately. A replacement waits until the page
83
- // asks for it, so an open conversation is never reloaded without consent.
84
- if (!self.registration.active) await self.skipWaiting();
85
- })());
59
+ event.waitUntil((async () => {
60
+ const cache = await caches.open(CACHE);
61
+ const report = async (phase, detail = {}) => {
62
+ const clients = await self.clients.matchAll({ includeUncontrolled: true });
63
+ for (const client of clients)
64
+ client.postMessage({ type: "OC_PRECACHE", phase, ...detail });
65
+ };
66
+ // One bad optional asset must not fail the whole release: try each twice, report
67
+ // it as pending, then let a runtime miss fetch it. The shell and the chat module
68
+ // graph are critical: offline start breaks without them, so they fail the install.
69
+ const grab = async (url) => {
70
+ for (let attempt = 0; attempt < 2; attempt++) {
71
+ try {
72
+ const response = await fetch(url, { cache: "no-store" });
73
+ if (response.ok)
74
+ return response;
75
+ }
76
+ catch { /* Retry once, then leave it to the runtime cache miss. */ }
77
+ }
78
+ return null;
79
+ };
80
+ // Stylesheets and classic scripts carry the release version. A client still
81
+ // running an older worker therefore misses its old cache after a deploy instead
82
+ // of mixing new HTML with stale styles.
83
+ const targets = STATIC.map((path) => VERSIONED.has(path) ? versioned(path) : path);
84
+ await report("downloading", { total: targets.length + 1 });
85
+ try {
86
+ const shell = await grab(SHELL);
87
+ if (!shell)
88
+ throw new Error("precache: shell unavailable");
89
+ await cache.put(SHELL, shell).catch(() => { });
90
+ let pending = 0;
91
+ const pendingPaths = [];
92
+ await Promise.all(targets.map(async (url) => {
93
+ const response = await grab(url);
94
+ if (!response) {
95
+ pending += 1;
96
+ pendingPaths.push(url);
97
+ return;
98
+ }
99
+ await cache.put(url, response).catch(() => { });
100
+ }));
101
+ // The shell is a module graph, so an offline start needs the imports too. Walk them
102
+ // from the entry point instead of keeping a list that drifts with every new module.
103
+ const queue = ["/assets/chat/index.js"], seen = new Set();
104
+ while (queue.length) {
105
+ const url = queue.pop();
106
+ if (seen.has(url))
107
+ continue;
108
+ seen.add(url);
109
+ const response = await grab(url);
110
+ if (!response)
111
+ throw new Error(`precache: module unavailable: ${url}`);
112
+ const source = await response.clone().text();
113
+ await cache.put(url, response).catch(() => { });
114
+ for (const match of source.matchAll(/(?:from\s+"|import\(\s*")(\.\.?\/[^"]+\.js)"/g)) {
115
+ queue.push(new URL(match[1], `https://chat.invalid${url}`).pathname);
116
+ }
117
+ }
118
+ await report("ready", { pending, pendingPaths });
119
+ }
120
+ catch (error) {
121
+ await report("failed");
122
+ throw error;
123
+ }
124
+ // A first install should control immediately. A replacement waits until the page
125
+ // asks for it, so an open conversation is never reloaded without consent.
126
+ if (!self.registration.active)
127
+ await self.skipWaiting();
128
+ })());
86
129
  });
87
-
88
130
  self.addEventListener("message", (event) => {
89
- if (event.data?.type === "SKIP_WAITING") {
90
- event.waitUntil(self.skipWaiting());
91
- return;
92
- }
93
- // The first message is a cheap moment to enforce the age policy even if the worker
94
- // was already active when this release first loaded.
95
- if (!self.__mediaPruned) {
96
- self.__mediaPruned = true;
97
- event.waitUntil(pruneMedia().catch(() => {}));
98
- }
99
- if (event.data?.type === "SET_MEDIA_IDENTITY") event.waitUntil(setMediaIdentity(event.data.identity).catch(() => {}));
100
- else if (event.data?.type === "CLEAR_MEDIA_CACHE") event.waitUntil(clearMedia().catch(() => {}));
131
+ if (event.data?.type === "SKIP_WAITING") {
132
+ event.waitUntil(self.skipWaiting());
133
+ return;
134
+ }
135
+ // The first message is a cheap moment to enforce the age policy even if the worker
136
+ // was already active when this release first loaded.
137
+ if (!self.__mediaPruned) {
138
+ self.__mediaPruned = true;
139
+ event.waitUntil(pruneMedia().catch(() => { }));
140
+ }
141
+ if (event.data?.type === "SET_MEDIA_IDENTITY")
142
+ event.waitUntil(setMediaIdentity(event.data.identity).catch(() => { }));
143
+ else if (event.data?.type === "CLEAR_MEDIA_CACHE")
144
+ event.waitUntil(clearMedia().catch(() => { }));
101
145
  });
102
-
103
146
  self.addEventListener("activate", (event) => {
104
- event.waitUntil((async () => {
105
- for (const key of await caches.keys()) {
106
- if (key !== CACHE && key !== MEDIA_CACHE && key.startsWith("oc-chat-")) await caches.delete(key);
107
- }
108
- await self.clients.claim();
109
- })());
110
- // Housekeeping must never delay or fail activation.
111
- event.waitUntil(pruneMedia().catch(() => {}));
147
+ event.waitUntil((async () => {
148
+ for (const key of await caches.keys()) {
149
+ if (key !== CACHE && key !== MEDIA_CACHE && key.startsWith("oc-chat-"))
150
+ await caches.delete(key);
151
+ }
152
+ await self.clients.claim();
153
+ })());
154
+ // Housekeeping must never delay or fail activation.
155
+ event.waitUntil(pruneMedia().catch(() => { }));
112
156
  });
113
-
114
157
  self.addEventListener("fetch", (event) => {
115
- const request = event.request;
116
- if (request.method !== "GET") return;
117
- const url = new URL(request.url);
118
- if (url.origin !== self.location.origin) return;
119
- if (MEDIA_PATH.test(url.pathname)) {
120
- // Partial responses do not belong in a whole-body cache; leave ranges to the browser.
121
- if (request.headers.has("range")) return;
122
- event.respondWith(mediaResponse(event));
123
- return;
124
- }
125
- // Chat data never comes from a cache: a stale answer would show a room that was deleted
126
- // and messages that were already read.
127
- if (url.pathname !== SHELL && !url.pathname.startsWith("/assets/")) return;
128
- if (url.pathname === SHELL) {
158
+ const request = event.request;
159
+ if (request.method !== "GET")
160
+ return;
161
+ const url = new URL(request.url);
162
+ if (url.origin !== self.location.origin)
163
+ return;
164
+ if (MEDIA_PATH.test(url.pathname)) {
165
+ // Partial responses do not belong in a whole-body cache; leave ranges to the browser.
166
+ if (request.headers.has("range"))
167
+ return;
168
+ event.respondWith(mediaResponse(event));
169
+ return;
170
+ }
171
+ // Chat data never comes from a cache: a stale answer would show a room that was deleted
172
+ // and messages that were already read.
173
+ if (url.pathname !== SHELL && !url.pathname.startsWith("/assets/"))
174
+ return;
175
+ if (url.pathname === SHELL) {
176
+ // A page open must not wait for the server or for a release. This worker's cache
177
+ // holds the HTML of its own version; the next worker precaches the next HTML and
178
+ // only shows an update prompt once that install finished.
179
+ event.respondWith((async () => {
180
+ const cached = await caches.match(SHELL);
181
+ if (cached)
182
+ return cached;
183
+ try {
184
+ const response = await fetch(request);
185
+ if (response.ok)
186
+ await (await caches.open(CACHE)).put(SHELL, response.clone());
187
+ return response;
188
+ }
189
+ catch {
190
+ return Response.error();
191
+ }
192
+ })());
193
+ return;
194
+ }
195
+ // Cache hits are not revalidated in the background: install already stored this
196
+ // version's bytes, and rewriting them while an older page runs would mix releases.
129
197
  event.respondWith((async () => {
130
- try {
131
- const response = await fetch(request);
132
- if (response.ok) await (await caches.open(CACHE)).put(SHELL, response.clone());
133
- return response;
134
- } catch {
135
- return (await caches.match(SHELL)) || Response.error();
136
- }
198
+ const cached = await caches.match(request);
199
+ if (cached)
200
+ return cached;
201
+ try {
202
+ const response = await fetch(request);
203
+ if (response.ok)
204
+ await (await caches.open(CACHE)).put(request, response.clone());
205
+ return response;
206
+ }
207
+ catch {
208
+ return Response.error();
209
+ }
137
210
  })());
138
- return;
139
- }
140
- event.respondWith((async () => {
141
- const cached = await caches.match(request);
142
- const network = fetch(request).then(async (response) => {
143
- if (response.ok) await (await caches.open(CACHE)).put(request, response.clone());
144
- return response;
145
- }).catch(() => cached || Response.error());
146
- return cached || network;
147
- })());
148
211
  });
149
-
150
212
  // Cache Storage drops URL fragments, so the partition rides a reserved query parameter.
151
213
  // The index keeps the readable `${url}#${identity}` form.
152
214
  const mediaBodyKey = (url, identity) => `${url}${url.includes("?") ? "&" : "?"}__media_identity__=${identity}`;
153
215
  const mediaIndexKey = (url, identity) => `${url}#${identity}`;
154
-
155
216
  const isMediaEntry = (item) => Boolean(item)
156
- && typeof item.url === "string" && typeof item.key === "string" && typeof item.identity === "string"
157
- && Number.isFinite(item.size) && item.size >= 0
158
- && Number.isFinite(item.usedAt) && Number.isFinite(item.revalidatedAt);
159
-
217
+ && typeof item.url === "string" && typeof item.key === "string" && typeof item.identity === "string"
218
+ && Number.isFinite(item.size) && item.size >= 0
219
+ && Number.isFinite(item.usedAt) && Number.isFinite(item.revalidatedAt);
160
220
  const isCacheable = (response) => response.status !== 206
161
- && response.ok && response.type === "basic"
162
- && (response.headers.get("content-type") || "").startsWith("image/");
163
-
221
+ && response.ok && response.type === "basic"
222
+ && (response.headers.get("content-type") || "").startsWith("image/");
164
223
  const tagged = (response, state) => {
165
- const headers = new Headers(response.headers);
166
- headers.set("X-Media-Cache", state);
167
- return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
224
+ const headers = new Headers(response.headers);
225
+ headers.set("X-Media-Cache", state);
226
+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
168
227
  };
169
-
170
228
  async function loadMediaIdentity() {
171
- if (mediaIdentity !== undefined) return mediaIdentity;
172
- mediaIdentity = null;
173
- try {
174
- const cache = await caches.open(MEDIA_CACHE);
175
- const response = await cache.match(MEDIA_IDENTITY);
176
- const value = response ? await response.json() : null;
177
- if (typeof value?.identity === "string" && IDENTITY_PATTERN.test(value.identity)) mediaIdentity = value.identity;
178
- } catch { /* No stored identity means network-only media. */ }
179
- return mediaIdentity;
229
+ if (mediaIdentity !== undefined)
230
+ return mediaIdentity;
231
+ mediaIdentity = null;
232
+ try {
233
+ const cache = await caches.open(MEDIA_CACHE);
234
+ const response = await cache.match(MEDIA_IDENTITY);
235
+ const value = response ? await response.json() : null;
236
+ if (typeof value?.identity === "string" && IDENTITY_PATTERN.test(value.identity))
237
+ mediaIdentity = value.identity;
238
+ }
239
+ catch { /* No stored identity means network-only media. */ }
240
+ return mediaIdentity;
180
241
  }
181
-
182
242
  async function saveMediaIdentity(identity) {
183
- const cache = await caches.open(MEDIA_CACHE);
184
- await cache.put(MEDIA_IDENTITY, new Response(JSON.stringify({ identity }), { headers: { "Content-Type": "application/json" } }));
243
+ const cache = await caches.open(MEDIA_CACHE);
244
+ await cache.put(MEDIA_IDENTITY, new Response(JSON.stringify({ identity }), { headers: { "Content-Type": "application/json" } }));
185
245
  }
186
-
187
246
  async function setMediaIdentity(identity) {
188
- if (typeof identity !== "string" || !IDENTITY_PATTERN.test(identity)) return;
189
- await queueMedia(async () => {
190
- const previous = await loadMediaIdentity();
191
- mediaIdentity = identity;
192
- if (previous === identity) {
193
- await saveMediaIdentity(identity);
194
- return;
195
- }
196
- // A different browser identity must never read the previous one's cached images.
197
- await caches.delete(MEDIA_CACHE);
198
- await saveMediaIdentity(identity);
199
- });
247
+ if (typeof identity !== "string" || !IDENTITY_PATTERN.test(identity))
248
+ return;
249
+ await queueMedia(async () => {
250
+ const previous = await loadMediaIdentity();
251
+ mediaIdentity = identity;
252
+ if (previous === identity) {
253
+ await saveMediaIdentity(identity);
254
+ return;
255
+ }
256
+ // A different browser identity must never read the previous one's cached images.
257
+ await caches.delete(MEDIA_CACHE);
258
+ await saveMediaIdentity(identity);
259
+ });
200
260
  }
201
-
202
261
  async function clearMedia() {
203
- await queueMedia(async () => {
204
- const identity = await loadMediaIdentity();
205
- await caches.delete(MEDIA_CACHE);
206
- if (identity) await saveMediaIdentity(identity);
207
- });
262
+ await queueMedia(async () => {
263
+ const identity = await loadMediaIdentity();
264
+ await caches.delete(MEDIA_CACHE);
265
+ if (identity)
266
+ await saveMediaIdentity(identity);
267
+ });
208
268
  }
209
-
210
269
  async function readIndex(cache) {
211
- const response = await cache.match(MEDIA_INDEX);
212
- if (!response) return [];
213
- try {
214
- const value = await response.json();
215
- if (!Array.isArray(value)) throw new Error("invalid index");
216
- return value.filter(isMediaEntry);
217
- } catch {
218
- // A damaged index cannot account for bodies; drop them so the caps stay meaningful.
219
- for (const request of await cache.keys()) {
220
- const path = new URL(request.url).pathname;
221
- if (path !== MEDIA_INDEX && path !== MEDIA_IDENTITY) await cache.delete(request);
270
+ const response = await cache.match(MEDIA_INDEX);
271
+ if (!response)
272
+ return [];
273
+ try {
274
+ const value = await response.json();
275
+ if (!Array.isArray(value))
276
+ throw new Error("invalid index");
277
+ return value.filter(isMediaEntry);
278
+ }
279
+ catch {
280
+ // A damaged index cannot account for bodies; drop them so the caps stay meaningful.
281
+ for (const request of await cache.keys()) {
282
+ const path = new URL(request.url).pathname;
283
+ if (path !== MEDIA_INDEX && path !== MEDIA_IDENTITY)
284
+ await cache.delete(request);
285
+ }
286
+ await cache.delete(MEDIA_INDEX);
287
+ return [];
222
288
  }
223
- await cache.delete(MEDIA_INDEX);
224
- return [];
225
- }
226
289
  }
227
-
228
290
  const writeIndex = (cache, items) => cache.put(MEDIA_INDEX, new Response(JSON.stringify(items), { headers: { "Content-Type": "application/json" } }));
229
-
230
291
  async function applyLimits(cache, items) {
231
- const kept = [...items].sort((a, b) => a.usedAt - b.usedAt);
232
- let bytes = kept.reduce((sum, item) => sum + item.size, 0);
233
- const evicted = [];
234
- while (kept.length > MEDIA_LIMITS.entries || (bytes > MEDIA_LIMITS.bytes && kept.length)) {
235
- const item = kept.shift();
236
- bytes -= item.size;
237
- evicted.push(item);
238
- }
239
- for (const item of evicted) await cache.delete(mediaBodyKey(item.url, item.identity));
240
- await writeIndex(cache, kept);
292
+ const kept = [...items].sort((a, b) => a.usedAt - b.usedAt);
293
+ let bytes = kept.reduce((sum, item) => sum + item.size, 0);
294
+ const evicted = [];
295
+ while (kept.length > MEDIA_LIMITS.entries || (bytes > MEDIA_LIMITS.bytes && kept.length)) {
296
+ const item = kept.shift();
297
+ bytes -= item.size;
298
+ evicted.push(item);
299
+ }
300
+ for (const item of evicted)
301
+ await cache.delete(mediaBodyKey(item.url, item.identity));
302
+ await writeIndex(cache, kept);
241
303
  }
242
-
243
304
  async function storeMedia(url, identity, response) {
244
- const blob = await response.blob();
245
- await queueMedia(async () => {
246
- // An identity switch queued between fetch and put must not resurrect old bytes.
247
- if (mediaIdentity !== identity) return;
248
- const cache = await caches.open(MEDIA_CACHE);
249
- await cache.put(mediaBodyKey(url, identity), new Response(blob, {
250
- status: response.status, statusText: response.statusText, headers: response.headers,
251
- }));
252
- const key = mediaIndexKey(url, identity), now = Date.now();
253
- const items = (await readIndex(cache)).filter((item) => item.key !== key);
254
- items.push({ key, url, identity, size: blob.size, usedAt: now, revalidatedAt: now });
255
- await applyLimits(cache, items);
256
- });
305
+ const blob = await response.blob();
306
+ await queueMedia(async () => {
307
+ // An identity switch queued between fetch and put must not resurrect old bytes.
308
+ if (mediaIdentity !== identity)
309
+ return;
310
+ const cache = await caches.open(MEDIA_CACHE);
311
+ await cache.put(mediaBodyKey(url, identity), new Response(blob, {
312
+ status: response.status, statusText: response.statusText, headers: response.headers,
313
+ }));
314
+ const key = mediaIndexKey(url, identity), now = Date.now();
315
+ const items = (await readIndex(cache)).filter((item) => item.key !== key);
316
+ items.push({ key, url, identity, size: blob.size, usedAt: now, revalidatedAt: now });
317
+ await applyLimits(cache, items);
318
+ });
257
319
  }
258
-
259
320
  const touchMedia = (url, identity) => queueMedia(async () => {
260
- const cache = await caches.open(MEDIA_CACHE);
261
- const items = await readIndex(cache);
262
- const item = items.find((entry) => entry.url === url && entry.identity === identity);
263
- if (!item) return;
264
- item.usedAt = Date.now();
265
- await writeIndex(cache, items);
321
+ const cache = await caches.open(MEDIA_CACHE);
322
+ const items = await readIndex(cache);
323
+ const item = items.find((entry) => entry.url === url && entry.identity === identity);
324
+ if (!item)
325
+ return;
326
+ item.usedAt = Date.now();
327
+ await writeIndex(cache, items);
266
328
  });
267
-
268
329
  const revalidating = new Set();
269
330
  function revalidateMedia(request, url, identity) {
270
- const key = mediaIndexKey(url, identity);
271
- if (revalidating.has(key)) return Promise.resolve();
272
- revalidating.add(key);
273
- return (async () => {
274
- try {
275
- const response = await fetch(request);
276
- if (response.status === 401 || response.status === 403 || response.status === 404) {
277
- await queueMedia(async () => {
278
- const cache = await caches.open(MEDIA_CACHE);
279
- const items = await readIndex(cache);
280
- const kept = items.filter((item) => item.key !== key);
281
- await cache.delete(mediaBodyKey(url, identity));
282
- if (kept.length !== items.length) await writeIndex(cache, kept);
283
- });
284
- } else if (response.status === 200 && isCacheable(response)) {
285
- await storeMedia(url, identity, response);
286
- }
287
- } catch { /* A failed revalidation must not remove a working entry. */ }
288
- finally { revalidating.delete(key); }
289
- })();
331
+ const key = mediaIndexKey(url, identity);
332
+ if (revalidating.has(key))
333
+ return Promise.resolve();
334
+ revalidating.add(key);
335
+ return (async () => {
336
+ try {
337
+ const response = await fetch(request);
338
+ if (response.status === 401 || response.status === 403 || response.status === 404) {
339
+ await queueMedia(async () => {
340
+ const cache = await caches.open(MEDIA_CACHE);
341
+ const items = await readIndex(cache);
342
+ const kept = items.filter((item) => item.key !== key);
343
+ await cache.delete(mediaBodyKey(url, identity));
344
+ if (kept.length !== items.length)
345
+ await writeIndex(cache, kept);
346
+ });
347
+ }
348
+ else if (response.status === 200 && isCacheable(response)) {
349
+ await storeMedia(url, identity, response);
350
+ }
351
+ }
352
+ catch { /* A failed revalidation must not remove a working entry. */ }
353
+ finally {
354
+ revalidating.delete(key);
355
+ }
356
+ })();
290
357
  }
291
-
292
358
  async function pruneMedia() {
293
- await queueMedia(async () => {
294
- const cache = await caches.open(MEDIA_CACHE);
295
- const items = await readIndex(cache);
296
- const cutoff = Date.now() - MEDIA_LIMITS.age;
297
- const fresh = items.filter((item) => item.usedAt >= cutoff);
298
- for (const item of items) if (item.usedAt < cutoff) await cache.delete(mediaBodyKey(item.url, item.identity));
299
- await applyLimits(cache, fresh);
300
- });
359
+ await queueMedia(async () => {
360
+ const cache = await caches.open(MEDIA_CACHE);
361
+ const items = await readIndex(cache);
362
+ const cutoff = Date.now() - MEDIA_LIMITS.age;
363
+ const fresh = items.filter((item) => item.usedAt >= cutoff);
364
+ for (const item of items)
365
+ if (item.usedAt < cutoff)
366
+ await cache.delete(mediaBodyKey(item.url, item.identity));
367
+ await applyLimits(cache, fresh);
368
+ });
301
369
  }
302
-
303
370
  async function mediaResponse(event) {
304
- try {
305
- return await serveMedia(event);
306
- } catch {
307
- // Cache Storage can be unavailable (private modes, quota). Media then stays network-only.
308
- try { return tagged(await fetch(event.request), "bypass"); }
309
- catch { return Response.error(); }
310
- }
371
+ try {
372
+ return await serveMedia(event);
373
+ }
374
+ catch {
375
+ // Cache Storage can be unavailable (private modes, quota). Media then stays network-only.
376
+ try {
377
+ return tagged(await fetch(event.request), "bypass");
378
+ }
379
+ catch {
380
+ return Response.error();
381
+ }
382
+ }
311
383
  }
312
-
313
384
  async function serveMedia(event) {
314
- const request = event.request;
315
- const identity = await loadMediaIdentity();
316
- if (!identity) {
317
- try { return tagged(await fetch(request), "bypass"); }
318
- catch { return Response.error(); }
319
- }
320
- const url = request.url;
321
- const cache = await caches.open(MEDIA_CACHE);
322
- const cached = await cache.match(mediaBodyKey(url, identity));
323
- if (cached) {
324
- event.waitUntil(touchMedia(url, identity).catch(() => {}));
325
- const entry = (await readIndex(cache)).find((item) => item.key === mediaIndexKey(url, identity));
326
- // Serving stale is fine; revalidation is background hygiene for revocation/deletion.
327
- if (!entry || Date.now() - entry.revalidatedAt > REVALIDATE_MS) event.waitUntil(revalidateMedia(request, url, identity).catch(() => {}));
328
- return tagged(cached, "hit");
329
- }
330
- try {
331
- const response = await fetch(request);
332
- if (isCacheable(response)) await storeMedia(url, identity, response.clone()).catch(() => {});
333
- return tagged(response, "miss");
334
- } catch {
335
- return Response.error();
336
- }
337
- }
385
+ const request = event.request;
386
+ const identity = await loadMediaIdentity();
387
+ if (!identity) {
388
+ try {
389
+ return tagged(await fetch(request), "bypass");
390
+ }
391
+ catch {
392
+ return Response.error();
393
+ }
394
+ }
395
+ const url = request.url;
396
+ const cache = await caches.open(MEDIA_CACHE);
397
+ const cached = await cache.match(mediaBodyKey(url, identity));
398
+ if (cached) {
399
+ event.waitUntil(touchMedia(url, identity).catch(() => { }));
400
+ const entry = (await readIndex(cache)).find((item) => item.key === mediaIndexKey(url, identity));
401
+ // Serving stale is fine; revalidation is background hygiene for revocation/deletion.
402
+ if (!entry || Date.now() - entry.revalidatedAt > REVALIDATE_MS)
403
+ event.waitUntil(revalidateMedia(request, url, identity).catch(() => { }));
404
+ return tagged(cached, "hit");
405
+ }
406
+ try {
407
+ const response = await fetch(request);
408
+ if (isCacheable(response))
409
+ await storeMedia(url, identity, response.clone()).catch(() => { });
410
+ return tagged(response, "miss");
411
+ }
412
+ catch {
413
+ return Response.error();
414
+ }
415
+ }