chirkle 0.1.0 → 0.3.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 (82) hide show
  1. package/README.md +23 -4
  2. package/package.json +2 -1
  3. package/pb_hooks/federation/messages.js +48 -2
  4. package/pb_hooks/lib/anonymous.js +10 -6
  5. package/pb_hooks/lib/bulk.js +2 -0
  6. package/pb_hooks/lib/files.js +39 -47
  7. package/pb_hooks/lib/handles.js +337 -0
  8. package/pb_hooks/lib/http.js +35 -23
  9. package/pb_hooks/lib/inbox.js +383 -0
  10. package/pb_hooks/lib/lists.js +8 -2
  11. package/pb_hooks/lib/live.js +137 -0
  12. package/pb_hooks/lib/messages.js +4 -0
  13. package/pb_hooks/lib/reactions.js +2 -0
  14. package/pb_hooks/lib/reads.js +3 -1
  15. package/pb_hooks/lib/site.js +1 -1
  16. package/pb_hooks/lib/stats.js +252 -0
  17. package/pb_hooks/lib/users.js +6 -1
  18. package/pb_hooks/main.pb.js +104 -27
  19. package/pb_hooks/telegram/api.js +3 -2
  20. package/pb_hooks/telegram/inbound.js +6 -1
  21. package/pb_hooks/telegram/outbound.js +35 -6
  22. package/pb_hooks/telegram/people.js +4 -0
  23. package/pb_hooks/telegram/reactions.js +193 -0
  24. package/pb_hooks/telegram/worker.js +1 -0
  25. package/pb_migrations/1760000043_telegram_reactions.js +21 -0
  26. package/pb_migrations/1760000044_stats.js +70 -0
  27. package/pb_migrations/1760000045_mentions.js +187 -0
  28. package/pb_migrations/1760000046_reserved_handles.js +29 -0
  29. package/pb_public/assets/access-GUDTDXIP.js +2 -0
  30. package/pb_public/assets/access-GUDTDXIP.js.map +7 -0
  31. package/pb_public/assets/app-3WX5JYL2.js +3 -0
  32. package/pb_public/assets/app-3WX5JYL2.js.map +7 -0
  33. package/pb_public/assets/app-WAFKVN2H.css +2 -0
  34. package/pb_public/assets/app-WAFKVN2H.css.map +7 -0
  35. package/pb_public/assets/collections-DHJEOLHW.css +2 -0
  36. package/pb_public/assets/collections-DHJEOLHW.css.map +7 -0
  37. package/pb_public/assets/{emoji-WSTVXAW5.css → emoji-VA2WCEAC.css} +2 -2
  38. package/pb_public/assets/{emoji-WSTVXAW5.css.map → emoji-VA2WCEAC.css.map} +2 -2
  39. package/pb_public/assets/{emoji-picker-QYRX6NYL.js → emoji-picker-65VVVGYW.js} +2 -2
  40. package/pb_public/assets/forward-66PELNWT.js +2 -0
  41. package/pb_public/assets/forward-66PELNWT.js.map +7 -0
  42. package/pb_public/assets/inbox-3FSOPY2T.css +2 -0
  43. package/pb_public/assets/inbox-3FSOPY2T.css.map +7 -0
  44. package/pb_public/assets/inbox-TZJWPRTG.js +2 -0
  45. package/pb_public/assets/inbox-TZJWPRTG.js.map +7 -0
  46. package/pb_public/assets/{lazy-SCCVSUZO.js → lazy-4CXRBHHM.js} +2 -2
  47. package/pb_public/assets/lazy-4CXRBHHM.js.map +7 -0
  48. package/pb_public/assets/login-G7Y44CJ7.js +2 -0
  49. package/pb_public/assets/login-G7Y44CJ7.js.map +7 -0
  50. package/pb_public/assets/{media-L3EYTHKT.css → media-7TCBG7WM.css} +2 -2
  51. package/pb_public/assets/{media-L3EYTHKT.css.map → media-7TCBG7WM.css.map} +2 -2
  52. package/pb_public/assets/media-FPRU2QH5.js +2 -0
  53. package/pb_public/assets/media-FPRU2QH5.js.map +7 -0
  54. package/pb_public/assets/mention-suggest-R7MXUH6R.js +2 -0
  55. package/pb_public/assets/mention-suggest-R7MXUH6R.js.map +7 -0
  56. package/pb_public/assets/notify-RQ6ZLR46.js +2 -0
  57. package/pb_public/assets/notify-RQ6ZLR46.js.map +7 -0
  58. package/pb_public/assets/profile-2CNVT2KX.js +2 -0
  59. package/pb_public/assets/profile-2CNVT2KX.js.map +7 -0
  60. package/pb_public/assets/stats-A2TBRUI6.css +2 -0
  61. package/pb_public/assets/stats-A2TBRUI6.css.map +7 -0
  62. package/pb_public/assets/stats-JX52AQCO.js +2 -0
  63. package/pb_public/assets/stats-JX52AQCO.js.map +7 -0
  64. package/pb_public/assets/user-search-7GNEIXMN.js +2 -0
  65. package/pb_public/assets/user-search-7GNEIXMN.js.map +7 -0
  66. package/pb_public/index.html +3 -3
  67. package/pb_public/stats.html +25 -0
  68. package/pb_public/sw.js +1 -1
  69. package/pb_public/assets/access-ALBW2MT2.js +0 -2
  70. package/pb_public/assets/access-ALBW2MT2.js.map +0 -7
  71. package/pb_public/assets/app-ECR34OBK.css +0 -2
  72. package/pb_public/assets/app-ECR34OBK.css.map +0 -7
  73. package/pb_public/assets/app-SILEBEXB.js +0 -3
  74. package/pb_public/assets/app-SILEBEXB.js.map +0 -7
  75. package/pb_public/assets/collections-VEOIOCAW.css +0 -2
  76. package/pb_public/assets/collections-VEOIOCAW.css.map +0 -7
  77. package/pb_public/assets/lazy-SCCVSUZO.js.map +0 -7
  78. package/pb_public/assets/media-DH7ECZSF.js +0 -2
  79. package/pb_public/assets/media-DH7ECZSF.js.map +0 -7
  80. package/pb_public/assets/notify-L6GERFNO.js +0 -2
  81. package/pb_public/assets/notify-L6GERFNO.js.map +0 -7
  82. /package/pb_public/assets/{emoji-picker-QYRX6NYL.js.map → emoji-picker-65VVVGYW.js.map} +0 -0
package/README.md CHANGED
@@ -10,6 +10,9 @@ A small, fast, real-time group chat. One [PocketBase](https://pocketbase.io) bin
10
10
  <img alt="A room in Chirkle: the room list with unread counts on the left; messages with avatars, a reply, a photo and emoji reactions on the right" src="docs/screenshot-light.png">
11
11
  </picture>
12
12
 
13
+ - Runs on a $5 VPS (1 vCPU, 1 GB of RAM): about 500 people online at a normal pace, or 100 chatting nonstop
14
+ (measured, [PERF.md §8](docs/PERF.md#8-2026-11-09-a-5-vps-one-cpu)); past 100–200 clients, everyone
15
+ reconnecting at once can still swamp it
13
16
  - Public rooms anyone can create; hide rooms you don't care about; creators archive rooms (read-only, history kept)
14
17
  - Room access, chosen by each room's creator: **Private** (only the people they add), **Public** (everyone with an account) or **Open Air** (anyone can read it, no account needed; the home page shows these rooms to guests, who log in or sign up to join in); and who can post: everyone who can read it, or only the people they choose (the others read and react)
15
18
  - Live messages, edits and deletes (deleted messages leave a placeholder)
@@ -29,7 +32,7 @@ A small, fast, real-time group chat. One [PocketBase](https://pocketbase.io) bin
29
32
  a room with unread messages opens at the first of them, under a "New" line
30
33
  - What you were typing is kept per room, even across a reload; "Jump to latest" whenever you are scrolled up
31
34
  - Your own branding (title and logo) and, if you like, invite-only signups: set by the admin in PocketBase
32
- - Telegram bridge (optional): link rooms to Telegram groups through a bot; messages, replies, edits and files go both ways (deletes from Chirkle to Telegram), Telegram people show under stand-in accounts with their names and pictures — see [Telegram integration](#telegram-integration)
35
+ - Telegram bridge (optional): link rooms to Telegram groups through a bot; messages, replies, edits, files and (with the bot an admin) reactions go both ways (deletes from Chirkle to Telegram), Telegram people show under stand-in accounts with their names and pictures — see [Telegram integration](#telegram-integration)
33
36
  - Fast room switching: each room's latest messages are kept in the browser (IndexedDB) and shown at once while the
34
37
  server answers; unread rooms are fetched ahead. Attachment thumbnails are kept by the service worker, so going back
35
38
  to a room (or reloading) doesn't download them again. All of it is cleared on logout
@@ -41,6 +44,11 @@ A small, fast, real-time group chat. One [PocketBase](https://pocketbase.io) bin
41
44
  - A native Android app (Kotlin, Jetpack Compose) with the same features, notifications and a 3 MB download — see
42
45
  [Android app](#android-app)
43
46
 
47
+ <picture>
48
+ <source media="(prefers-color-scheme: dark)" srcset="docs/collections-dark.png">
49
+ <img alt="A collection in Chirkle: the private Moodboard's pictures by month, with Upload, Rename and Make public; the sidebar lists your collections with their counts and a followed one with 3 new" src="docs/collections-light.png">
50
+ </picture>
51
+
44
52
  Design: [`docs/DESIGN.md`](docs/DESIGN.md) · Android app: [`docs/ANDROID.md`](docs/ANDROID.md) · QA: [`docs/QA.md`](docs/QA.md) · Refactoring plan: [`docs/REFACTOR.md`](docs/REFACTOR.md) · Archived plans: [MVP build](docs/history/BUILD_PLAN.md), [avatars, DMs, attachments](docs/history/NEXT_FEATURES_PLAN.md)
45
53
 
46
54
  ## Requirements
@@ -90,6 +98,7 @@ The PocketBase admin UI is at http://127.0.0.1:8090/_/ (create a superuser with
90
98
  | `npm start` | Production build, then the server (`scripts/start.mjs`, the package's `chirkle` command): PocketBase on http://127.0.0.1:8090 with `pb_data/` |
91
99
  | `npm run dev` | Unminified watch build into `pb_public/` + `pocketbase serve --dev` |
92
100
  | `npm run build` | Production build (hashed assets) into `pb_public/`; fails if over the size budget |
101
+ | `npm run release -- <version>` | Gives the npm package and the Android app the next version and starts the app's changelog; then publish a GitHub Release tagged `v<version>` ([Releasing](#releasing)) |
93
102
  | `npm run typecheck` | `tsc` (strict) for the frontend, tests and scripts, plus `pb_hooks/` + `pb_migrations/` against PocketBase's generated types (`types/pocketbase.d.ts`, written by `scripts/pb-types.sh`) |
94
103
  | `npm run lint` | Biome: formatting, lint rules, import order (`npm run format` applies the fixes) |
95
104
  | `npm run lint:sinks` | Fails if frontend code uses `innerHTML` & co. (XSS guard) |
@@ -98,7 +107,7 @@ The PocketBase admin UI is at http://127.0.0.1:8090/_/ (create a superuser with
98
107
  | `npm run test:int` | Integration tests: schema, API rules, hooks, realtime, pagination |
99
108
  | `npm run test:e2e` | Playwright end-to-end tests against the production build |
100
109
  | `npm run schema:snapshot` | Rewrite `docs/schema.snapshot.json` (every collection's API rules, fields and indexes, and the rate limits) after a migration changes them; `test:int` fails while it is out of date |
101
- | `npm run screenshots` | Rewrite the README screenshots (`docs/screenshot-*.png`): a throwaway server with made-up people and messages, photographed in Chromium after `npm run build` |
110
+ | `npm run screenshots` | Rewrite the README screenshots (`docs/screenshot-*.png`, `docs/collections-*.png`): a throwaway server with made-up people, messages and collections, photographed in Chromium after `npm run build` |
102
111
  | `npm run check` | typecheck + lint + lint:sinks + test + test:int + build (what CI runs before e2e) |
103
112
 
104
113
  Every test run starts its own PocketBase on a free port with a temp data dir — nothing to clean up, and no fakes
@@ -235,6 +244,15 @@ set (`/.well-known/assetlinks.json`; `ANDROID_APP_ID` only for a build with anot
235
244
  `min_android_version` on the site record to make older apps ask for an update. What is built and what isn't yet:
236
245
  [`docs/ANDROID.md` §16](docs/ANDROID.md#16-implementation-2026-10-18), and [`android/PARITY.md`](android/PARITY.md).
237
246
 
247
+ ## Releasing
248
+
249
+ One version for the npm package and the Android app. `npm run release -- 0.2.0` sets it in `package.json` and
250
+ `android/app/build.gradle.kts` (versionCode + 1) and creates `fastlane/…/changelogs/<versionCode>.txt` to fill in.
251
+ Commit, push, then publish a GitHub Release with the new tag `v0.2.0`. The Release workflow
252
+ (`.github/workflows/release.yml`) checks the versions, attaches the signed APK and
253
+ stages `chirkle@0.2.0` on npm; approve it on npmjs.com (2FA) to publish it. Setup and details:
254
+ [`docs/ANDROID.md` §28.7](docs/ANDROID.md#287-one-release-for-the-app-and-the-npm-package-2026-11-08).
255
+
238
256
  ## Link previews
239
257
 
240
258
  Messages show a line under them for each link: the page's favicon and title ([`docs/DESIGN.md` §28](docs/DESIGN.md)).
@@ -252,7 +270,7 @@ go without: videos then show their first frame in the room as before, and plain
252
270
 
253
271
  An optional bridge between rooms and Telegram groups ([`docs/DESIGN.md` §26](docs/DESIGN.md)). A bot sits in your
254
272
  groups; once a group is linked to a room, messages, replies, edits and files go both ways (deletes only from Chirkle
255
- to Telegram). Telegram people show in the room under stand-in users ("Ann Lee (TG)") with their names and pictures;
273
+ to Telegram), and reactions too where the bot is a group admin. Telegram people show in the room under stand-in users ("Ann Lee (TG)") with their names and pictures;
256
274
  the bot posts Chirkle messages with the author's name above them.
257
275
 
258
276
  **Setup**
@@ -266,7 +284,8 @@ the bot posts Chirkle messages with the author's name above them.
266
284
 
267
285
  With Dokku: `dokku config:set chirkle TELEGRAM_BOT_TOKEN='…' TELEGRAM_WEBHOOK_URL='https://chat.example.com/api/telegram/webhook'`.
268
286
  3. Add the bot to a Telegram group. A row for it appears in the admin UI under *Collections → tg_links*: pick the
269
- room and tick `enabled`. `/chatid` in the group says whether it is linked. Tick `anonymous` too to repost the
287
+ room and tick `enabled`. `/chatid` in the group says whether it is linked. Make the bot a group admin to bring
288
+ reactions over: Telegram tells only admins about them. Tick `anonymous` too to repost the
270
289
  room's messages to that group without their authors' names.
271
290
 
272
291
  To make a room **anonymous**, tick `anonymous` on its row under *Collections → rooms* in the admin UI. Messages
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chirkle",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "A small, fast, real-time group chat: one PocketBase server, a vanilla TypeScript web app",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "repository": {
@@ -41,6 +41,7 @@
41
41
  "start": "node scripts/start.mjs",
42
42
  "prepack": "npm run build",
43
43
  "setup": "sh scripts/fetch-pocketbase.sh",
44
+ "release": "node scripts/release.mjs",
44
45
  "dev": "node scripts/dev.mjs",
45
46
  "build": "node scripts/build.mjs",
46
47
  "typecheck": "sh scripts/pb-types.sh && tsc --noEmit && tsc --noEmit -p tsconfig.server.json",
@@ -8,6 +8,7 @@
8
8
  const { reactionsOf, setReaction } = require(`${__hooks}/lib/reactions.js`);
9
9
  /** @typedef {{ emoji: string, users: string[] }} Reaction */
10
10
  const { isReactionEmoji } = require(`${__hooks}/lib/emoji.js`);
11
+ const { accessOf, canSee } = require(`${__hooks}/lib/access.js`);
11
12
  const { enqueue, enqueueWork, fromPeer, gid, isMine, jsonOf, newId, originOf, peerById, peerHost, splitGid } = require(
12
13
  `${__hooks}/federation/config.js`,
13
14
  );
@@ -83,6 +84,7 @@ function messageEvent(app, rec, peer) {
83
84
  const author = rec.getString("author");
84
85
  const from = rec.getString("forwarded_from");
85
86
  const reactions = reactionsOf(rec);
87
+ const mentions = rec.getStringSlice("mentions");
86
88
  return {
87
89
  type: "message",
88
90
  room: roomGid(room),
@@ -95,8 +97,9 @@ function messageEvent(app, rec, peer) {
95
97
  created: rec.getString("created"),
96
98
  files,
97
99
  reactions: reactionsOut(app, rec),
100
+ mentions: mentions.map((u) => gidOf(app, u)),
98
101
  },
99
- people: peopleFor(app, peer, [author, from, ...reactions.flatMap((/** @type {Reaction} */ r) => r.users)]),
102
+ people: peopleFor(app, peer, [author, from, ...mentions, ...reactions.flatMap((/** @type {Reaction} */ r) => r.users)]),
100
103
  };
101
104
  }
102
105
 
@@ -186,7 +189,16 @@ function messageChanged(app, rec, was) {
186
189
  enqueue(
187
190
  app,
188
191
  peerId,
189
- deleted ? { type: "delete", room: rg, message: g } : { type: "edit", room: rg, message: g, text: rec.getString("text") },
192
+ deleted
193
+ ? { type: "delete", room: rg, message: g }
194
+ : {
195
+ type: "edit",
196
+ room: rg,
197
+ message: g,
198
+ text: rec.getString("text"),
199
+ mentions: rec.getStringSlice("mentions").map((u) => gidOf(app, u)),
200
+ people: peerById(app, peerId) ? peopleFor(app, peerById(app, peerId), rec.getStringSlice("mentions")) : {},
201
+ },
190
202
  );
191
203
  }
192
204
  }
@@ -285,6 +297,7 @@ function applyMessage(app, sender, ev, files) {
285
297
  if (from) rec.set("forwarded_from", from);
286
298
  }
287
299
  if (files?.length) require(`${__hooks}/lib/files.js`).attachUploads(app, rec, files);
300
+ rec.set("mentions", mentionsIn(app, sender, room, author, m.mentions, people));
288
301
  if (ev.backfill && typeof m.created === "string" && /^\d{4}-\d\d-\d\d[ T]\d\d:\d\d:\d\d/.test(m.created)) {
289
302
  rec.setRaw("created", m.created);
290
303
  rec.setRaw("updated", m.created);
@@ -295,6 +308,35 @@ function applyMessage(app, sender, ev, files) {
295
308
  if (list.length) setReactions(app, sender, rec, list, people);
296
309
  }
297
310
 
311
+ /**
312
+ * Who a peer's message mentions (§41): the people its event names by global id (its text's "@handle"s are the sender's
313
+ * handles, not ours) who can see the room here, but not its author. An instance from before mentions sends none.
314
+ * @param {core.App} app
315
+ * @param {core.Record} sender
316
+ * @param {core.Record} room
317
+ * @param {string} author
318
+ * @param {unknown} list
319
+ * @param {Record<string, any>} people
320
+ * @returns {string[]}
321
+ */
322
+ function mentionsIn(app, sender, room, author, list, people) {
323
+ if (!Array.isArray(list)) return [];
324
+ const access = accessOf(room);
325
+ const out = new Set();
326
+ for (const g of list.slice(0, 20)) {
327
+ const id = userOf(app, sender, g, people);
328
+ if (id && id !== author && canSee(access, id)) out.add(id);
329
+ }
330
+ return [...out];
331
+ }
332
+
333
+ /**
334
+ * Is this save of a message a linked instance's (it then says whom the message mentions, mentionsIn)?
335
+ * @param {core.App} app
336
+ * @param {core.Record} rec
337
+ */
338
+ const isFromPeer = (app, rec) => !!originOf(app, rec.id);
339
+
298
340
  /**
299
341
  * Set a message's reactions from a list naming people by global id.
300
342
  * @param {core.App} app
@@ -348,6 +390,9 @@ function applyEdit(app, sender, ev) {
348
390
  const text = String(ev.text || "").slice(0, 2000);
349
391
  if (text === rec.getString("text")) return;
350
392
  rec.set("text", text);
393
+ const { room } = roomOf(app, sender, ev);
394
+ const people = ev.people && typeof ev.people === "object" ? ev.people : {};
395
+ rec.set("mentions", mentionsIn(app, sender, room, rec.getString("author"), ev.mentions, people));
351
396
  saveFor(app, rec, sender);
352
397
  }
353
398
 
@@ -417,4 +462,5 @@ module.exports = {
417
462
  applyDelete,
418
463
  applyReact,
419
464
  applyReactions,
465
+ isFromPeer,
420
466
  };
@@ -144,15 +144,19 @@ function probes(q, me) {
144
144
  const REFUSAL = "Messages can't be filtered, sorted or grouped by who wrote them.";
145
145
 
146
146
  /**
147
- * Every request: refused when its query filters, sorts or groups by author (the records API's ?filter, ?sort, ?expand,
148
- * on any collection, as a relation or back-relation can reach messages from any of them). Superusers may.
147
+ * A request refused when its query filters, sorts or groups by author (the records API's ?filter, ?sort, ?expand, on any
148
+ * collection, as a relation or back-relation can reach messages from any of them; our routes' ?expand). Called by the
149
+ * record request hooks (main.pb.js) and by each route that enriches records. Superusers may.
149
150
  * @param {core.RequestEvent} e
150
151
  */
151
152
  function refuseProbes(e) {
152
- const q = e.request?.url?.query();
153
- if (!q || (!q.has("filter") && !q.has("sort") && !q.has("expand"))) return;
154
- if (!probes({ filter: q.get("filter"), sort: q.get("sort"), expand: q.get("expand") }, e.auth?.id ?? "")) return;
155
- if (e.hasSuperuserAuth()) return;
153
+ // requestInfo, not e.request: the record request hooks' events have no `request` in JS. Its values are decoded
154
+ // (%61uthor is "author").
155
+ const info = e.requestInfo();
156
+ const q = { filter: info.query.filter ?? "", sort: info.query.sort ?? "", expand: info.query.expand ?? "" };
157
+ if (!/author|forwarded_from/i.test(`${q.filter} ${q.sort} ${q.expand}`)) return;
158
+ if (!probes(q, info.auth?.id ?? "")) return;
159
+ if (info.auth?.isSuperuser()) return;
156
160
  throw new BadRequestError(REFUSAL);
157
161
  }
158
162
 
@@ -148,6 +148,8 @@ function originalOf(app, m) {
148
148
  * @param {core.RequestEvent} e
149
149
  */
150
150
  function forward(e) {
151
+ // As the records API's (main.pb.js): this page's ?expand mustn't group messages by author (§35).
152
+ require(`${__hooks}/lib/anonymous.js`).refuseProbes(e);
151
153
  const me = e.auth;
152
154
  if (!me) throw new UnauthorizedError("The request requires a logged-in user.");
153
155
  const what = "Failed to forward the messages.";
@@ -5,8 +5,8 @@
5
5
  //
6
6
  // - A message's `files` and an item's `file` hold stored names, as they did when they were file fields, so clients
7
7
  // build the same URLs: /api/files/messages/{message}/{name} and /api/files/collection_items/{item}/{name}. serve()
8
- // answers those with the shared file (PocketBase's own handler, the path pointed at the `files` row), checking only
9
- // that the message or item still has it. No file token: whoever has the URL has the file (§37.3).
8
+ // (routes of their own, by collection name) answers those with the shared file, as PocketBase's handler would,
9
+ // checking only that the message or item still has it. No file token: whoever has the URL has the file (§37.3).
10
10
  // - `refs` counts the messages and items that name a file. link() and unlink() keep it in the same save; a file named
11
11
  // by nothing is deleted, and PocketBase deletes what is stored once that is committed.
12
12
  // - The media worker (lib/media.js) makes each file's thumbnails and video poster once, whoever names it.
@@ -286,64 +286,56 @@ function shownBy(app, collection, id, name) {
286
286
  return shows ? byName(app, name) : null;
287
287
  }
288
288
 
289
+ /** The images PocketBase makes thumbnails of, and the size it makes for any file field besides the field's own. */
290
+ const THUMB_EXT = ["jpg", "jpeg", "png", "gif", "webp"];
291
+ const DEFAULT_THUMB = "100x100";
292
+
289
293
  /**
290
- * GET /api/files/{collection}/{record}/{name} (a router middleware, before PocketBase's own route): a message's or a
291
- * collection item's file is served from its `files` row, by PocketBase's handler (thumbnails, ranges, the headers that
292
- * keep it from running as a page), the path pointed at that row. The token clients still send is ignored. 404 when
293
- * the message or item doesn't show it (deleted, taken out). The `files` rows themselves only through these. True when
294
- * it has answered (a file not moved yet), false to go on to PocketBase's route.
294
+ * GET /api/files/messages/{recordId}/{filename} and /api/files/collection_items/{recordId}/{filename}: a message's or
295
+ * a collection item's file, served from its `files` row (§37). Routes of their own, more specific than PocketBase's
296
+ * /api/files/{collection}/…, so no other request runs JS for this: a router middleware would hold a JS runtime for every
297
+ * request, realtime connections and file downloads too (docs/PERF.md §6). As PocketBase's handler does: `thumb` (one of
298
+ * the field's sizes, or 100x100) serves that thumbnail of an image, made when first asked for; `download` makes it an
299
+ * attachment; ranges, and the headers that keep a file from running as a page (fs.serve). The token clients still
300
+ * send is ignored. 404 when the message or item doesn't show it (deleted, taken out). A file not moved to its row's
301
+ * folder yet is served from its old place (`src`), with a thumbnail only if one is there already: those folders have
302
+ * the ones that were ever asked for. The `files` rows themselves are served only through these (main.pb.js).
295
303
  * @param {core.RequestEvent} e
296
- * @returns {boolean}
304
+ * @param {"messages" | "collection_items"} collection
297
305
  */
298
- function serve(e) {
306
+ function serve(e, collection) {
299
307
  const req = e.request;
300
- if (!req || (req.method !== "GET" && req.method !== "HEAD")) return false;
301
- const collection = req.pathValue("collection");
302
- const id = req.pathValue("recordId");
303
- const name = req.pathValue("filename");
304
- if (!collection || !id || !name) return false;
305
- let coll;
306
- try {
307
- coll = e.app.findCachedCollectionByNameOrId(collection);
308
- } catch {
309
- return false; // PocketBase answers 404
310
- }
311
- if (coll.name === "files") throw new NotFoundError();
312
- if (coll.name !== "messages" && coll.name !== "collection_items") return false;
313
- const row = shownBy(e.app, coll.name, id, name);
308
+ const id = req?.pathValue("recordId") ?? "";
309
+ const name = req?.pathValue("filename") ?? "";
310
+ const row = shownBy(e.app, collection, id, name);
314
311
  if (!row) throw new NotFoundError();
315
- if (row.getString("src")) {
316
- serveUnmoved(e, row);
317
- return true;
318
- }
319
- req.setPathValue("collection", row.collection().id);
320
- req.setPathValue("recordId", row.id);
321
- return false;
322
- }
323
-
324
- /**
325
- * A file not moved to its folder yet, served from its old place (src): a thumbnail asked for if it is there (the old
326
- * folders have those that were ever asked for), else the file itself. PocketBase's handler would make a missing one,
327
- * but serves only a file field's own files. As it does, `download` makes it an attachment.
328
- * @param {core.RequestEvent} e
329
- * @param {core.Record} row
330
- */
331
- function serveUnmoved(e, row) {
332
- const key = row.getString("src");
333
- const name = row.getString("file");
334
- const q = e.request?.url?.query();
312
+ const moved = !row.getString("src");
313
+ const key = keyOf(row);
314
+ const file = row.getString("file");
315
+ const q = req?.url?.query();
335
316
  const thumb = q?.get("thumb") ?? "";
336
317
  const sizes = /** @type {any} */ (row.collection().fields.getByName("file")).thumbs ?? [];
337
318
  const fs = e.app.newFilesystem();
338
319
  try {
339
320
  let served = key;
340
- if (thumb && sizes.includes(thumb) && isImage(name) && fs.exists(thumbKeyOf(key, thumb))) served = thumbKeyOf(key, thumb);
341
- else if (!fs.exists(key)) throw new NotFoundError();
321
+ if (thumb && (thumb === DEFAULT_THUMB || sizes.includes(thumb)) && THUMB_EXT.includes(ext(file))) {
322
+ const at = thumbKeyOf(key, thumb);
323
+ if (fs.exists(at)) served = at;
324
+ else if (moved && fs.exists(key)) {
325
+ try {
326
+ fs.createThumb(key, at, thumb);
327
+ served = at;
328
+ } catch {
329
+ served = key; // as PocketBase does: the file itself when it can't make one
330
+ }
331
+ }
332
+ }
333
+ if (served === key && !fs.exists(key)) throw new NotFoundError();
342
334
  const download = q?.get("download") ?? "";
343
335
  if (download && download !== "0" && download !== "false") {
344
- e.response.header().set("Content-Disposition", `attachment; filename=${name}`);
336
+ e.response.header().set("Content-Disposition", `attachment; filename=${file}`);
345
337
  }
346
- fs.serve(e.response, /** @type {any} */ (e.request), served, name);
338
+ fs.serve(e.response, /** @type {any} */ (req), served, file);
347
339
  } finally {
348
340
  fs.close();
349
341
  }