chirkle 0.4.0 → 0.4.1
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/README.md +32 -24
- package/bin/release/darwin-amd64/chirkle-server +2 -2
- package/bin/release/darwin-arm64/chirkle-server +0 -0
- package/bin/release/linux-amd64/chirkle-server +0 -0
- package/bin/release/linux-arm64/chirkle-server +0 -0
- package/package.json +2 -1
- package/pb_hooks/lib/account.js +541 -6
- package/pb_hooks/lib/collections.js +4 -4
- package/pb_hooks/lib/dms.js +1 -1
- package/pb_hooks/lib/inbox.js +1 -1
- package/pb_hooks/lib/invites.js +266 -0
- package/pb_hooks/lib/messages.js +11 -2
- package/pb_hooks/lib/moderation.js +1 -1
- package/pb_hooks/lib/retention.js +3 -0
- package/pb_hooks/lib/site.js +1 -1
- package/pb_hooks/lib/users.js +38 -10
- package/pb_hooks/main.pb.js +26 -1
- package/pb_hooks/telegram/api.js +64 -12
- package/pb_hooks/telegram/inbound.js +106 -15
- package/pb_hooks/telegram/outbound.js +63 -37
- package/pb_hooks/telegram/worker.js +59 -15
- package/pb_migrations/1760000052_deleted_accounts.js +19 -0
- package/pb_migrations/1760000053_account_jobs.js +45 -0
- package/pb_migrations/1760000054_room_invites.js +39 -0
- package/pb_migrations/1760000055_invite_barred.js +16 -0
- package/pb_migrations/1760000056_telegram_fetch.js +21 -0
- package/pb_public/assets/{access-PB77EH4F.css → access-GPRLOZOO.css} +2 -2
- package/pb_public/assets/{access-PB77EH4F.css.map → access-GPRLOZOO.css.map} +2 -2
- package/pb_public/assets/access-UK3L54NR.js +2 -0
- package/pb_public/assets/access-UK3L54NR.js.map +7 -0
- package/pb_public/assets/account-CT2BVMAX.css +2 -0
- package/pb_public/assets/account-CT2BVMAX.css.map +7 -0
- package/pb_public/assets/account-api-J6A6IYVX.js +2 -0
- package/pb_public/assets/account-api-J6A6IYVX.js.map +7 -0
- package/pb_public/assets/app-HB3NZHQ2.js +3 -0
- package/pb_public/assets/app-HB3NZHQ2.js.map +7 -0
- package/pb_public/assets/app-XJ73EU5O.css +2 -0
- package/pb_public/assets/app-XJ73EU5O.css.map +7 -0
- package/pb_public/assets/chunk-AG73QNUN.js +2 -0
- package/pb_public/assets/chunk-AG73QNUN.js.map +7 -0
- package/pb_public/assets/chunk-DCLJRQ53.js +2 -0
- package/pb_public/assets/chunk-DCLJRQ53.js.map +7 -0
- package/pb_public/assets/chunk-N2OFGBCZ.js +2 -0
- package/pb_public/assets/{chunk-PWNJABVI.js.map → chunk-N2OFGBCZ.js.map} +4 -4
- package/pb_public/assets/chunk-OKIIBH7O.js +2 -0
- package/pb_public/assets/chunk-OKIIBH7O.js.map +7 -0
- package/pb_public/assets/chunk-UZDXAORM.js +2 -0
- package/pb_public/assets/chunk-UZDXAORM.js.map +7 -0
- package/pb_public/assets/chunk-WR25F7FU.js +2 -0
- package/pb_public/assets/chunk-WR25F7FU.js.map +7 -0
- package/pb_public/assets/invite-OGT5E2MZ.js +2 -0
- package/pb_public/assets/invite-OGT5E2MZ.js.map +7 -0
- package/pb_public/assets/invite-api-7G7XPXQW.js +2 -0
- package/pb_public/assets/invite-api-7G7XPXQW.js.map +7 -0
- package/pb_public/assets/login-TK6K4WGB.js +2 -0
- package/pb_public/assets/{login-ECFBJP6Q.js.map → login-TK6K4WGB.js.map} +1 -1
- package/pb_public/assets/profile-3R6S5QYS.js +2 -0
- package/pb_public/assets/profile-3R6S5QYS.js.map +7 -0
- package/pb_public/assets/stats-GTO2H6PG.js +2 -0
- package/pb_public/assets/stats-GTO2H6PG.js.map +7 -0
- package/pb_public/index.html +7 -5
- package/pb_public/stats.html +1 -1
- package/scripts/service.mjs +201 -0
- package/scripts/start.mjs +7 -1
- package/pb_public/assets/access-LHPD2EHG.js +0 -2
- package/pb_public/assets/access-LHPD2EHG.js.map +0 -7
- package/pb_public/assets/app-6ETOTHXQ.js +0 -3
- package/pb_public/assets/app-6ETOTHXQ.js.map +0 -7
- package/pb_public/assets/app-ZGHECF33.css +0 -2
- package/pb_public/assets/app-ZGHECF33.css.map +0 -7
- package/pb_public/assets/chunk-GXMWOXBX.js +0 -2
- package/pb_public/assets/chunk-GXMWOXBX.js.map +0 -7
- package/pb_public/assets/chunk-IFQGGTSP.js +0 -2
- package/pb_public/assets/chunk-IFQGGTSP.js.map +0 -7
- package/pb_public/assets/chunk-PWNJABVI.js +0 -2
- package/pb_public/assets/login-ECFBJP6Q.js +0 -2
- package/pb_public/assets/profile-NQQLAEDT.js +0 -2
- package/pb_public/assets/profile-NQQLAEDT.js.map +0 -7
- package/pb_public/assets/stats-ARDU576A.js +0 -2
- package/pb_public/assets/stats-ARDU576A.js.map +0 -7
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../web/src/lib/types.ts", "../../web/src/pb.ts", "../../web/src/lib/cursor.ts", "../../web/src/api.ts", "../../web/src/lib/
|
|
4
|
-
"sourcesContent": ["// Shapes of records as the frontend sees them (DESIGN.md \u00A75, \u00A76).\n\nexport interface User {\n id: string;\n name: string;\n /** Avatar filename (\u00A715); \"\" or absent when the user has none. */\n avatar?: string;\n /** Doesn't take direct messages (\u00A716.7), e.g. a Telegram bridge's stand-in; absent where the server doesn't say. */\n no_dms?: boolean;\n /** Someone on a linked instance (\u00A733.4): its host, e.g. \"b.example\". Absent for this instance's own people. */\n instance?: string;\n /** You are a moderator (\u00A736): only said of the signed-in user. */\n moderator?: boolean;\n /** What \"@handle\" names (\u00A741), without the \"@\"; absent where the server doesn't say. */\n handle?: string;\n}\n\n/**\n * Who else holds a shared room (\u00A733.10): `home`, on a copy of another instance's room (its host); `with`, the other\n * instances that have it; `down`, its home can't be reached right now. Empty for a room that isn't shared.\n */\nexport interface Shared {\n home?: string;\n with?: string[];\n down?: boolean;\n}\n\nexport type RoomKind = \"public\" | \"dm\";\n\n/**\n * Who can see a room (\u00A723.1): its members only, every signed-in user, or anyone at all, even without an account\n * (Open Air). A DM is private to its two members.\n */\nexport type Visibility = \"private\" | \"public\" | \"open\";\n/** Who can post in a room (\u00A723.6): everyone who can read it, or only its writers. */\nexport type Posting = \"everyone\" | \"selected\";\n\nexport interface Room {\n id: string;\n /** \"\" for a DM: its title is the other member's name (lib/rooms.ts). */\n name: string;\n archived: boolean;\n created_by: string;\n /** Absent = \"public\" (\u00A716.1). */\n kind?: RoomKind;\n /** Absent = \"public\" (\u00A723.1). */\n visibility?: Visibility;\n /** A DM's two members, or a private room's (the creator and whoever they added, \u00A723.2); empty otherwise. */\n members?: string[];\n /** Absent = \"everyone\" (\u00A723.6). */\n posting?: Posting;\n /** Who can post when posting is \"selected\": the creator and the people they chose (\u00A723.6); empty otherwise. */\n writers?: string[];\n /** DMs: when the latest message was sent (\"\" before the first). */\n last_message_at?: string;\n created?: string;\n /** Shared with other instances (\u00A733). */\n shared?: Shared | null;\n expand?: { members?: User[]; writers?: User[] };\n}\n\n/** Client-only send state for optimistic messages (\u00A77.5). Absent once the server has the message. */\nexport type SendStatus = \"pending\" | \"failed\";\n\nexport interface Message {\n id: string;\n room: string;\n /** \"\" for a service message (\u00A75.3): the app's own notice in the room, e.g. a Telegram group disconnected. */\n author: string;\n text: string;\n /** PocketBase datetime, e.g. \"2026-10-10 12:34:56.789Z\". */\n created: string;\n updated: string;\n /** \"\" when never edited. */\n edited_at: string;\n deleted: boolean;\n /** Stored attachment names (\u00A717.1); empty or absent when there are none. */\n files?: string[];\n /** Original upload names by stored name, set by the server (QA BUG-28); absent for older messages. */\n file_names?: Record<string, string>;\n /** Stored name \u2192 the collection it was attached from (\u00A731); absent or empty for the others. */\n file_sources?: Record<string, string>;\n /** Stored image or video name \u2192 [width, height] as shown (\u00A717.5), set by the server; absent until it knows. */\n file_dims?: Record<string, [number, number]>;\n /** The message this one replies to (\u00A719); \"\" or absent when it isn't a reply. */\n reply_to?: string;\n /** Emoji reactions (\u00A720), in the order they were first added; empty or absent when there are none. */\n reactions?: Reaction[];\n /** Who first wrote it, when it was forwarded (\u00A721.3); \"\" or absent otherwise. */\n forwarded_from?: string;\n /**\n * The message a forward shows (\u00A721.3): the server answers with its text, attachments and edit stamp, or none once\n * it is deleted. \"\" or absent otherwise, and for forwards made before forwards pointed at their original.\n */\n forward_of?: string;\n /** Who its \"@handle\"s name (\u00A741): user ids, set by the server; empty or absent when none. */\n mentions?: string[];\n /** What its links show (\u00A728), set by the server once it has fetched them; empty or absent until then. */\n previews?: LinkPreview[];\n expand?: { author?: User; reply_to?: Quoted; forwarded_from?: User };\n status?: SendStatus;\n /** Client-only: attachments of a message not (yet) on the server, with local preview URLs (\u00A717.4). */\n localFiles?: LocalFile[];\n}\n\n/** A link's line under a message (\u00A728): the page's title, and its favicon as a data: URL (\"\" when it has none). */\nexport interface LinkPreview {\n url: string;\n title: string;\n icon: string;\n}\n\n/** One image or video in a room's media grid (\u00A730.1): a file of `source`, shown by `message` (a forward, or itself). */\nexport interface MediaItem {\n message: string;\n source: string;\n file: string;\n /** Its place in the source's files. */\n pos: number;\n /** The original upload name, \"\" when the server has none (QA BUG-28). */\n name: string;\n video: boolean;\n /** A video's poster frame is ready (GET /api/chat/posters/{source}/{file}). */\n poster: boolean;\n /** The message's `created`. */\n sent: string;\n /** Who sent the message; null for a service message. */\n author: { id: string; name: string } | null;\n}\n\n/** A page of a room's media, newest first; `more`: there are older ones. */\nexport interface MediaPage {\n items: MediaItem[];\n more: boolean;\n}\n\n/** One emoji on a message and who reacted with it (\u00A720.1). */\nexport interface Reaction {\n emoji: string;\n /** User ids, in the order they reacted. Never empty. */\n users: string[];\n}\n\n/** What a reply shows of the message it answers (\u00A719). */\nexport interface Quoted {\n id: string;\n author: string;\n text: string;\n deleted: boolean;\n files?: string[];\n expand?: { author?: User };\n}\n\nexport interface LocalFile {\n /** For an item from a collection, an empty stand-in named after it. */\n file: File;\n /** Object URL for an image or video preview, \"\" for other files. Revoked once the message no longer needs it. */\n url: string;\n /** Attached from a collection (\u00A731): the item's id, sent for the server to copy, and its collection's. */\n item?: { id: string; collection: string };\n}\n\n/** A collection (\u00A731), as GET /api/chat/collections lists it. */\nexport interface Collection {\n id: string;\n name: string;\n public: boolean;\n items: number;\n last_added: string;\n /** Someone else's that you follow: whose it is, up to when you've seen it, and how many items are new (at most 100). */\n owner?: { id: string; name: string };\n seen_at?: string;\n new?: number;\n}\n\n/** What GET /api/chat/collections answers: yours and those you follow, by name. */\nexport interface Collections {\n mine: Collection[];\n subs: Collection[];\n}\n\n/** A collection item (\u00A731): one image or video. */\nexport interface CollectionItem {\n id: string;\n collection: string;\n file: string;\n /** The original file name. */\n name: string;\n video: boolean;\n /** A video's poster frame is ready (GET /api/chat/posters/items/{id}/{file}). */\n poster: boolean;\n created: string;\n}\n\n/** What a \"from collection\" badge may say (\u00A731): a public one's (or your own) name, \"private\", or null: gone. */\nexport type Badge = { name: string; public: boolean; mine: boolean } | { private: true } | null;\n\n/** The site's branding and signup policy (\u00A724), set by an admin in PocketBase. */\nexport interface Site {\n title: string;\n /** URL of the logo image, or \"\" without one. */\n logo: string;\n /** Signing up needs an invite code. */\n inviteOnly: boolean;\n /** The server emails password reset links: \"Forgot password?\" is offered (\u00A739). */\n passwordReset: boolean;\n}\n\n/** A row of the \"Mentions & replies\" inbox (\u00A741, GET /api/chat/inbox). */\nexport interface InboxItem {\n id: string;\n /** Where the next page starts (`before`). */\n cursor: string;\n kind: \"mention\" | \"reply\" | \"reaction\";\n /** A reaction row's: the actor's emoji on the message, the first five then \" +n\" (\u00A741.4); \"\" otherwise. */\n emoji: string;\n /** A reaction row's emoji, all of them. Missing from servers before 2026-11-11. */\n emojis?: string[];\n created: string;\n /** A mention or reply already read in its room: not new here. Missing from servers before. */\n read?: boolean;\n room: string;\n /** The message: the mention, the reply, or your message reacted to. Its text cut short, how many files it has. */\n message: { id: string; text: string; files: number; created: string };\n /** A reply's: your message it answers (\"\" text and no files once deleted). */\n quote: { id: string; text: string; files: number } | null;\n /** Who did it; in an anonymous room (\u00A735), the room for a mention or reply. */\n actor: User;\n}\n\n/** A row of the inbox added or taken away, told live on `chat/inbox` (\u00A741). */\nexport interface InboxEvent {\n action: \"create\" | \"delete\";\n id: string;\n kind: InboxItem[\"kind\"];\n room: string;\n message: string;\n created: string;\n}\n\n/** What the app shows before (or without) the site record. */\nexport const DEFAULT_SITE: Site = { title: \"Chirkle\", logo: \"\", inviteOnly: false, passwordReset: false };\n", "import * as S from \"./strings/pb.ts\";\n// A minimal PocketBase client: only what api.ts uses (REST requests, the auth store, realtime over SSE, file URLs).\n// It replaces the official JS SDK, whose admin services, OAuth2/OTP/MFA flows and cookie helpers the app never used\n// but always shipped (\u00A77.7). The wire behavior follows SDK 0.28: same storage key, query and realtime protocol.\n\nexport type Query = Record<string, string | number | boolean | undefined>;\n\nexport interface RequestOptions {\n method?: string;\n query?: Query | undefined;\n /** JSON, or multipart when any value is a Blob/File (or an array of them). */\n body?: Record<string, unknown>;\n signal?: AbortSignal | undefined;\n /** How much of a multipart body has been sent, 0 to 1: the request then goes through XHR (fetch can't tell). */\n onUpload?: ((fraction: number) => void) | undefined;\n /** A conditional GET (PERF.md \u00A75): `sent` goes as If-None-Match, the answer's ETag to `got`. A 304 answers undefined. */\n tag?: { sent?: string | undefined; got?: ((tag: string) => void) | undefined } | undefined;\n}\n\nexport interface AuthRecord {\n id: string;\n collectionName?: string;\n [field: string]: unknown;\n}\n\n/** A failed request: `status` 0 for network trouble or an abort. `response` is PocketBase's error body. */\nexport class PbError extends Error {\n readonly status: number;\n readonly response: { message?: string; data?: Record<string, { message?: unknown; code?: unknown }> };\n readonly isAbort: boolean;\n\n constructor(status: number, response: PbError[\"response\"] = {}, isAbort = false) {\n super(response.message || \"Something went wrong.\");\n this.name = \"PbError\";\n this.status = status;\n this.response = response;\n this.isAbort = isAbort;\n }\n}\n\n// ---- auth store ----\n\nexport interface AuthStore {\n readonly token: string;\n readonly record: AuthRecord | null;\n /** There is a token and it hasn't expired. */\n readonly isValid: boolean;\n /** When the token expires (epoch ms), or 0 without a (readable) token. */\n readonly expiresAt: number;\n save(token: string, record: AuthRecord | null): void;\n clear(): void;\n /** Called on every save/clear, including another tab's when the store is backed by localStorage. */\n onChange(fn: () => void): () => void;\n}\n\n/** The SDK's key, so existing sessions survive the switch. */\nconst STORAGE_KEY = \"pocketbase_auth\";\n\n/** The JWT's `exp` (seconds), or 0 when it can't be read. */\nfunction tokenExp(token: string): number {\n try {\n const part = token.split(\".\")[1]!.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\");\n return Number(JSON.parse(atob(part)).exp) || 0;\n } catch {\n return 0;\n }\n}\n\n/** In memory only, or persisted in `storage` (shared with the other tabs of this browser). */\nexport function createAuthStore(storage?: Storage): AuthStore {\n let token = \"\";\n let record: AuthRecord | null = null;\n const listeners = new Set<() => void>();\n\n const load = (raw: string | null) => {\n let data: { token?: string; record?: AuthRecord | null } = {};\n try {\n data = JSON.parse(raw || \"{}\") ?? {};\n } catch {}\n token = data.token || \"\";\n record = data.record || null;\n };\n const set = (t: string, r: AuthRecord | null) => {\n token = t;\n record = r;\n for (const fn of [...listeners]) fn();\n };\n\n if (storage) {\n load(storage.getItem(STORAGE_KEY));\n addEventListener(\"storage\", (e) => {\n if (e.key !== STORAGE_KEY) return;\n load(e.newValue);\n set(token, record);\n });\n }\n\n return {\n get token() {\n return token;\n },\n get record() {\n return record;\n },\n get isValid() {\n return tokenExp(token) > Date.now() / 1000;\n },\n get expiresAt() {\n return tokenExp(token) * 1000;\n },\n save(t, r) {\n storage?.setItem(STORAGE_KEY, JSON.stringify({ token: t, record: r }));\n set(t, r);\n },\n clear() {\n storage?.removeItem(STORAGE_KEY);\n set(\"\", null);\n },\n onChange(fn) {\n listeners.add(fn);\n return () => void listeners.delete(fn);\n },\n };\n}\n\n// ---- client ----\n\nexport type Unsubscribe = () => Promise<void>;\n\nexport interface Realtime {\n /** Connected, with a client id, and no connect in progress. */\n readonly isConnected: boolean;\n /** The connection being made follows one that failed or was lost: events may have been missed meanwhile. */\n readonly recovered: boolean;\n /**\n * Listen to `topic` (e.g. \"messages/*\", or \"PB_CONNECT\" for every (re)connect). Resolves once the server has the\n * subscription, so an event caused after that reaches `fn`. `query` (fields, expand, filter) applies to its events.\n */\n subscribe(topic: string, fn: (data: unknown) => void, query?: Query): Promise<Unsubscribe>;\n /** Drop every subscription and close the connection. */\n unsubscribe(): Promise<void>;\n}\n\nexport interface PbClient {\n readonly authStore: AuthStore;\n readonly realtime: Realtime;\n send<T>(path: string, opts?: RequestOptions): Promise<T>;\n /** Bind `{:name}` placeholders in a filter expression, quoting and escaping the values. */\n filter(expr: string, params: Record<string, string | number | boolean | null>): string;\n /** URL of a record's file (`query`: thumb). */\n fileUrl(collection: string, recordId: string, filename: string, query?: Query): string;\n}\n\nconst qs = (query: Query = {}) => {\n const parts: string[] = [];\n for (const [k, v] of Object.entries(query)) if (v !== undefined) parts.push(`${encodeURIComponent(k)}=${encodeURIComponent(v)}`);\n return parts.length ? `?${parts.join(\"&\")}` : \"\";\n};\n\nconst isFiles = (v: unknown) => v instanceof Blob || (Array.isArray(v) && v.some((x) => x instanceof Blob));\n\n/** A body holding files as multipart: files and strings as fields, anything else in PocketBase's `@jsonPayload`. */\nfunction toFormData(body: Record<string, unknown>): FormData {\n const form = new FormData();\n for (const [k, v] of Object.entries(body)) {\n if (v === undefined) continue;\n if (isFiles(v)) for (const f of [v].flat() as Blob[]) form.append(k, f);\n else if (typeof v === \"string\") form.append(k, v);\n else form.append(\"@jsonPayload\", JSON.stringify({ [k]: v }));\n }\n return form;\n}\n\n/** An XHR answer as fetch gives it: rejects only when nothing came back (an AbortError when aborted). */\nfunction upload(url: string, method: string, headers: Record<string, string>, body: FormData, onUpload: (fraction: number) => void) {\n return new Promise<{ status: number; json: () => Promise<unknown> }>((ok, fail) => {\n const x = new XMLHttpRequest();\n x.open(method, url);\n for (const [k, v] of Object.entries(headers)) x.setRequestHeader(k, v);\n x.upload.onprogress = (e) => e.lengthComputable && e.total && onUpload(e.loaded / e.total);\n x.onload = () => ok({ status: x.status, json: async () => JSON.parse(x.responseText) });\n x.onerror = () => fail(new TypeError(\"Network request failed\"));\n x.onabort = () => fail(new DOMException(\"Aborted\", \"AbortError\"));\n x.send(body);\n });\n}\n\nexport function createClient(baseUrl: string, authStore: AuthStore = createAuthStore()): PbClient {\n const base = baseUrl.replace(/\\/+$/, \"\");\n\n async function send<T>(path: string, { method = \"GET\", query, body, signal, onUpload, tag }: RequestOptions = {}): Promise<T> {\n const headers: Record<string, string> = {};\n if (authStore.token) headers.Authorization = authStore.token;\n // The 304 is ours to read, not the HTTP cache's to answer from (it keeps no copy: no-store).\n if (tag?.sent) Object.assign(headers, { \"If-None-Match\": tag.sent, \"Cache-Control\": \"no-cache\" });\n let payload: BodyInit | undefined;\n if (body) {\n if (Object.values(body).some(isFiles)) payload = toFormData(body);\n else {\n headers[\"Content-Type\"] = \"application/json\";\n payload = JSON.stringify(body);\n }\n }\n const aborted = (e: unknown) => !!signal?.aborted || (e as Error)?.name === \"AbortError\";\n let res: { status: number; json: () => Promise<unknown>; headers?: Headers };\n let data: PbError[\"response\"] = {};\n const url = base + path + qs(query);\n try {\n res =\n onUpload && payload instanceof FormData\n ? await upload(url, method, headers, payload, onUpload)\n : await fetch(url, { method, headers, ...(payload ? { body: payload } : {}), ...(signal ? { signal } : {}) });\n const etag = res.headers?.get(\"ETag\");\n if (etag) tag?.got?.(etag);\n if (res.status === 304) return undefined as T;\n // No body is fine for a 204, or an error the server didn't explain. A success whose body never came (the page\n // navigated away, the connection dropped) is a failure, not `{}`: as a login's answer it saved no session (QA BUG-117).\n data = await (res.json() as Promise<PbError[\"response\"]>).catch((e) => {\n if (aborted(e) || (res.status < 300 && res.status !== 204)) throw e;\n return {};\n });\n } catch (e) {\n throw new PbError(0, {}, aborted(e));\n }\n if (res.status >= 400) throw new PbError(res.status, data ?? {});\n return data as T;\n }\n\n const realtime = createRealtime(`${base}/api/realtime`, send);\n // The server reads who a realtime client is from the token its subscriptions were sent with. A new token (a password\n // change, which revokes the old ones, here or in another tab) must reach it, or nothing more arrives (QA BUG-52).\n // Someone else (or nobody, after a logout) needs a new connection: the server refuses another user's subscriptions on\n // one it knows as someone, and would go on sending that user's events on it (QA BUG-66).\n let token = authStore.token;\n let who = token ? (authStore.record?.id ?? \"\") : \"\";\n authStore.onChange(() => {\n if (authStore.token === token) return;\n token = authStore.token;\n const next = token ? (authStore.record?.id ?? \"\") : \"\";\n if (next === who) return realtime.resubmit();\n who = next;\n realtime.restart();\n });\n\n return {\n authStore,\n realtime,\n send,\n filter: (expr, params) =>\n expr.replace(/\\{:(\\w+)\\}/g, (match, name: string) => {\n if (!Object.hasOwn(params, name)) return match;\n const v = params[name];\n return typeof v === \"string\" ? JSON.stringify(v) : String(v);\n }),\n fileUrl: (collection, recordId, filename, query) =>\n `${base}/api/files/${[collection, recordId, filename].map(encodeURIComponent).join(\"/\")}${qs(query)}`,\n };\n}\n\n// ---- realtime ----\n\n/** Wait before reconnect attempt n (the last value repeats), as the SDK does. */\nconst RECONNECT_MS = [200, 300, 500, 1000, 1200, 1500, 2000];\nconst CONNECT_TIMEOUT_MS = 15_000;\n\ntype Listener = (e: Event) => void;\n\n/**\n * The SDK's realtime protocol: one EventSource; PB_CONNECT carries the client id; the set of subscriptions (each a\n * topic plus its serialized options) is POSTed to /api/realtime whenever it changes, and again after a reconnect.\n */\nfunction createRealtime(url: string, send: PbClient[\"send\"]): Realtime & { resubmit(): void; restart(): void } {\n let es: EventSource | null = null;\n let clientId = \"\";\n /** Subscription key \u2192 listeners. A key is the topic plus its options, and the event name the server uses. */\n const subs = new Map<string, Listener[]>();\n let lastSent: string[] = [];\n let attempts = 0;\n let lost = false;\n let connectTimer: ReturnType<typeof setTimeout> | undefined;\n let reconnectTimer: ReturnType<typeof setTimeout> | undefined;\n let pending: { resolve: () => void; reject: (e: unknown) => void }[] = [];\n /** The in-flight subscriptions POST, aborted on disconnect. */\n let submitting: AbortController | null = null;\n /** Submits run one after another, so an older subscription set never lands after a newer one. */\n let queue: Promise<unknown> = Promise.resolve();\n\n const keys = () => [...subs.keys()];\n const unsent = () => {\n const now = keys();\n return now.length !== lastSent.length || now.some((k) => !lastSent.includes(k));\n };\n /** The keys the current EventSource has a dispatcher for. */\n let bound = new Set<string>();\n /**\n * One dispatcher per key on the EventSource, which calls the key's listeners as `subs` holds them when the event\n * comes: a listener hears events exactly while it is in `subs`, whenever it was added (QA BUG-269 was a listener\n * added at a moment nothing bound it). PB_CONNECT's listeners are called by the connect itself, once subscribed.\n */\n const bind = (key: string) => {\n const source = es;\n if (!source || bound.has(key) || key === \"PB_CONNECT\") return;\n bound.add(key);\n source.addEventListener(key, (e) => {\n if (es === source) for (const fn of subs.get(key) ?? []) fn(e); // a replaced connection's late events: dropped\n });\n };\n\n async function sendSubs(): Promise<void> {\n if (!clientId) return;\n if (!subs.size) return disconnect();\n if (!unsent()) return;\n lastSent = keys();\n submitting = new AbortController();\n try {\n await send(\"/api/realtime\", { method: \"POST\", body: { clientId, subscriptions: lastSent }, signal: submitting.signal });\n } catch (e) {\n if (!(e instanceof PbError && e.isAbort)) throw e;\n }\n }\n\n function submit(): Promise<void> {\n const p = queue.then(sendSubs);\n queue = p.catch(() => {});\n return p;\n }\n\n function connect(): Promise<void> {\n if (attempts > 0) return Promise.resolve(); // a reconnect is scheduled; it sends every subscription\n return new Promise((resolve, reject) => {\n pending.push({ resolve, reject });\n if (pending.length === 1) queueMicrotask(initConnect);\n });\n }\n\n function initConnect() {\n disconnect(true);\n connectTimer = setTimeout(() => connectError(new Error(\"EventSource connect took too long.\")), CONNECT_TIMEOUT_MS);\n const source = new EventSource(url);\n es = source;\n bound = new Set();\n for (const key of subs.keys()) bind(key);\n // A connection closed meanwhile (a restart for another user, a reconnect) must leave the current one alone: its\n // late answers would otherwise settle or fail the new connection's pending subscribes.\n const current = () => es === source;\n source.onerror = () => current() && connectError(new Error(\"Failed to establish realtime connection.\"));\n source.addEventListener(\"PB_CONNECT\", (e) => {\n if (!current()) return;\n clientId = (e as MessageEvent).lastEventId;\n lastSent = [];\n submit()\n .then(async () => {\n for (let tries = 3; current() && unsent() && tries > 0; tries--) await submit();\n if (!current()) return;\n for (const p of pending) p.resolve();\n pending = [];\n attempts = 0;\n clearTimeout(reconnectTimer);\n clearTimeout(connectTimer);\n for (const fn of subs.get(\"PB_CONNECT\") ?? []) fn(e);\n lost = false;\n if (unsent()) await submit();\n })\n .catch((err) => {\n if (!current()) return;\n clientId = \"\";\n lastSent = [];\n connectError(err);\n });\n });\n }\n\n function connectError(err: unknown) {\n clearTimeout(connectTimer);\n clearTimeout(reconnectTimer);\n lost = true;\n if (!clientId && !attempts) {\n // The first connect failed: tell those waiting for it, then go on trying like after a lost connection. Nothing\n // else would try again, and the page would get no live updates at all.\n for (const p of pending) p.reject(err instanceof PbError ? err : new PbError(0));\n pending = [];\n if (!subs.size) return disconnect();\n }\n disconnect(true);\n reconnectTimer = setTimeout(initConnect, RECONNECT_MS[Math.min(attempts, RECONNECT_MS.length - 1)]);\n attempts++;\n }\n\n function disconnect(reconnecting = false) {\n clearTimeout(connectTimer);\n clearTimeout(reconnectTimer);\n submitting?.abort();\n submitting = null;\n es?.close();\n es = null;\n clientId = \"\";\n lastSent = [];\n if (!reconnecting) {\n attempts = 0;\n for (const p of pending) p.resolve();\n pending = [];\n }\n }\n\n return {\n get isConnected() {\n return !!es && !!clientId && !pending.length;\n },\n get recovered() {\n return lost;\n },\n async subscribe(topic, fn, query) {\n const key = query ? `${topic}?options=${encodeURIComponent(JSON.stringify({ query }))}` : topic;\n const listener: Listener = (e) => {\n let data: unknown;\n try {\n data = JSON.parse((e as MessageEvent).data);\n } catch {}\n fn(data || {});\n };\n const fns = subs.get(key) ?? [];\n subs.set(key, [...fns, listener]);\n bind(key);\n if (!es || !clientId || pending.length) await connect();\n else if (!fns.length) await submit();\n\n return async () => {\n const left = (subs.get(key) ?? []).filter((f) => f !== listener);\n if (left.length) subs.set(key, left);\n else subs.delete(key);\n await submit();\n };\n },\n async unsubscribe() {\n subs.clear();\n await submit();\n },\n /** Send the subscriptions again (with the current token), if connected. */\n resubmit() {\n if (!clientId || !subs.size) return;\n lastSent = [];\n // A failure that comes after this connection was replaced (a logout, another user) is the old one's: it must not\n // fail and close the new one, whose subscribes would reject and which would never reconnect (QA BUG-68).\n const source = es;\n submit().catch(() => es === source && connectError(new PbError(0)));\n },\n /** Close the connection and, with subscriptions left, open a new one that sends them all (with the current token). */\n restart() {\n if (!es && !pending.length) return; // not connected: the next subscribe() connects afresh\n disconnect();\n if (subs.size) connect().catch(() => {});\n },\n };\n}\n", "// Keyset pagination over a room's messages, ordered by (created, id) \u2014 DESIGN.md \u00A76, \u00A77.5.\n// Pure: which page to ask GET /api/chat/rooms/{room}/messages for (server/lists.go writes the filter).\n\nexport const PAGE_SIZE = 50;\n\nexport interface Cursor {\n created: string;\n id: string;\n}\n\nexport interface PageQuery {\n room: string;\n /** `latest` and `older` pages come back newest-first; `first` and `newer` oldest-first; `changed` oldest change first. */\n kind: \"latest\" | \"first\" | \"older\" | \"newer\" | \"changed\";\n /** The page's cursor: `created`, `id`; for `changed`, `since`, `from`, `to`. */\n args: Record<string, string>;\n /** Only messages that may have attachments (`withFiles`). */\n files?: true;\n /** Only messages with every word of it (search, \u00A729; with `latest` and `older`). The server folds and escapes them. */\n q?: string;\n}\n\n/** The newest page of a room (newest-first). */\nexport function latest(room: string): PageQuery {\n return { room, kind: \"latest\", args: {} };\n}\n\n/** The oldest page of a room, i.e. \"jump to beginning\" (oldest-first). */\nexport function first(room: string): PageQuery {\n return { room, kind: \"first\", args: {} };\n}\n\n/** The page just before `c`, the oldest loaded message (newest-first). */\nexport function older(room: string, c: Cursor): PageQuery {\n return { room, kind: \"older\", args: { created: c.created, id: c.id } };\n}\n\n/** The page just after `c`, the newest loaded message (oldest-first). */\nexport function newer(room: string, c: Cursor): PageQuery {\n return { room, kind: \"newer\", args: { created: c.created, id: c.id } };\n}\n\n/**\n * Messages from `from` to `to` (inclusive, by `created`) changed after `since` (an `updated` value): edits and\n * deletes a client may have missed while its realtime connection was down (\u00A77.5). Oldest change first.\n */\nexport function changedIn(room: string, since: string, from: Cursor, to: Cursor): PageQuery {\n return { room, kind: \"changed\", args: { since, from: from.created, to: to.created } };\n}\n\n/**\n * Only the messages of `q` that may have attachments (the image viewer pages through those, \u00A717.7): with files of their\n * own, or forwards, whose files are their original's (\u00A721.3). The server can't look at those: the original is\n * usually in a room the reader can't list.\n */\nexport const withFiles = (q: PageQuery): PageQuery => ({ ...q, files: true });\n", "// The only module that talks to PocketBase (\u00A76). Views depend on the `Api` interface, never on the client.\n\nimport { type Cursor, PAGE_SIZE, type PageQuery } from \"./lib/cursor.ts\";\nimport {\n type Badge,\n type CollectionItem,\n type Collections,\n DEFAULT_SITE,\n type InboxEvent,\n type MediaPage,\n type Message,\n type Posting,\n type Room,\n type Site,\n type User,\n type Visibility,\n} from \"./lib/types.ts\";\nimport { type AuthRecord, type PbClient, PbError, type Query, type RequestOptions } from \"./pb.ts\";\nimport * as S from \"./strings/api.ts\";\n\nexport type AvatarSize = 48 | 96;\nexport type Unsubscribe = () => Promise<void>;\nexport type Action = \"create\" | \"update\" | \"delete\";\nexport type RealtimeHandler<T> = (action: Action, record: T) => void;\n\nexport interface HiddenRow {\n id: string;\n room: string;\n}\n\n/** A room_reads row (\u00A718.1): only which room it is about matters to the client. */\nexport type ReadRow = HiddenRow;\n\n/** Unread messages per room id (rooms without any are left out), as of `at` (server time, \u00A718.2). */\nexport interface UnreadCounts {\n at: string;\n rooms: Record<string, number>;\n /** The recent messages these counts account for (QA BUG-106); missing from servers before it. */\n ids?: string[];\n /** Inbox rows not seen yet, at most 100, and each room's unread mentions and replies (\u00A741); missing from servers before. */\n inbox?: number;\n mentions?: Record<string, number>;\n}\n\n/** What the unread counter needs to know about a message event in any room (\u00A718.3). */\nexport type MessageActivity = Pick<Message, \"id\" | \"room\" | \"author\" | \"deleted\" | \"reply_to\" | \"mentions\">;\n\nexport interface NewMessage {\n /** Client-generated (lib/id.ts) so retries can't duplicate (\u00A77.5). */\n id: string;\n room: string;\n text: string;\n /** Attachments (\u00A717.4): sent as multipart. */\n files?: File[];\n /** The message this one replies to (\u00A719). */\n replyTo?: string;\n /** Collection items whose files it attaches, after `files` (\u00A731). */\n items?: string[];\n}\n\n/** A request to the server (`Api.request`). */\nexport interface Request {\n method?: string;\n body?: Record<string, unknown>;\n query?: Query;\n signal?: AbortSignal;\n /** With files in `body`: how much has been sent, 0 to 1. */\n onUpload?: (fraction: number) => void;\n}\n\n/**\n * Reads take an optional AbortSignal: views pass their scope's, so leaving a view cancels its pending requests\n * (they then reject with status 0). Writes take none on purpose: a send or edit should still reach the server\n * if the user navigates away while it is in flight.\n */\nexport interface Api {\n // auth\n currentUser(): User | null;\n /** `inviteCode`: needed while the site is invite-only (\u00A724). */\n signUp(input: { email: string; password: string; name: string; inviteCode?: string }): Promise<User>;\n logIn(email: string, password: string): Promise<User>;\n /** Email a link to set a new password (\u00A739). Resolves the same whether or not the address has an account. */\n requestPasswordReset(email: string): Promise<void>;\n /** Set a new password with the token from that link (one use). Every session of the account is signed out. */\n confirmPasswordReset(token: string, password: string): Promise<void>;\n /** Re-validate the stored session with the server, which renews it. Rejects when it is no longer valid. */\n refreshAuth(): Promise<User>;\n /** When the stored session expires (epoch ms), or 0 without one. */\n sessionExpiry(): number;\n logOut(): void;\n /**\n * A stored session that ran out (the browser was closed past its expiry): forgotten, and the id of the user it was,\n * or \"\" when there is none. Their drafts and cached rooms are then cleared (QA BUG-145).\n */\n forgetExpired(): string;\n /**\n * Called whenever the stored session changes, including from another tab of the same browser (they share\n * it). Read `currentUser()` to see who is logged in now. Returns an unsubscribe function.\n */\n onAuthChange(fn: () => void): () => void;\n /**\n * Called when the server refuses a change sent with the session (400, 401, 403 or 404). Often a plain mistake, but\n * also what a session revoked elsewhere gets (a password change signs out every other device), which only checking\n * the session can tell. Returns an unsubscribe function.\n */\n onRejected(fn: () => void): () => void;\n\n /** The site's branding and signup policy (\u00A724); the defaults when there is no site record. */\n site(signal?: AbortSignal): Promise<Site>;\n\n // profile (\u00A715)\n /** Upload a new avatar (already prepared, \u00A715.3). Resolves to the updated user. */\n setAvatar(file: File): Promise<User>;\n removeAvatar(): Promise<User>;\n rename(name: string): Promise<User>;\n /** Change your handle (\u00A741); refused with the reason on `handle` (taken, not allowed). */\n setHandle(handle: string): Promise<User>;\n /**\n * Change your password (\u00A722.2). The server checks the current one and signs out every other session; this one gets\n * a fresh token. Rejects with field errors on `oldPassword` or `password`.\n */\n changePassword(oldPassword: string, password: string): Promise<User>;\n /** Thumbnail URL of a user's avatar at `size` px (48 or 96), or \"\" when they have none. */\n avatarUrl(user: User, size: AvatarSize): string;\n\n // rooms\n listRooms(signal?: AbortSignal): Promise<Room[]>;\n getRoom(id: string, signal?: AbortSignal): Promise<Room>;\n createRoom(name: string, visibility?: Visibility): Promise<Room>;\n setArchived(id: string, archived: boolean): Promise<Room>;\n /**\n * Who can see the room (\u00A723.2): its visibility, and for a private room its members (user ids; the creator is always\n * one). With `posting`, also who can post (\u00A723.6): for \"selected\", its writers (the creator always is one; in a\n * private room only members count). Only the creator may. Resolves to the room as saved.\n */\n setAccess(id: string, visibility: Visibility, members: readonly string[], posting?: Posting, writers?: readonly string[]): Promise<Room>;\n\n // direct messages (\u00A716)\n /** The DM with `userId`, created on first use; reopens it if you had closed it. */\n openDm(userId: string): Promise<Room>;\n /** Up to 20 other users whose name contains `query` (ignoring case, as names are compared), by name. */\n searchUsers(query: string, signal?: AbortSignal): Promise<User[]>;\n /**\n * Someone on a linked instance by their address, \"ann@b.example\" (\u00A733.5), as a user here: to message them, or with\n * `room` to add them to that shared private room. Refused with the reason (no such person, not linked\u2026).\n */\n remoteUser(address: string, room?: string): Promise<User>;\n /** The users with these ids (at most 50), e.g. to name who reacted (\u00A720.3). Unknown ids are left out. */\n usersById(ids: readonly string[], signal?: AbortSignal): Promise<User[]>;\n\n // hidden rooms\n listHidden(signal?: AbortSignal): Promise<HiddenRow[]>;\n hideRoom(room: string): Promise<HiddenRow>;\n unhideRoom(rowId: string): Promise<void>;\n\n // unread counts (\u00A718)\n /** Unread messages per room, at most 100 each. */\n unreadCounts(signal?: AbortSignal): Promise<UnreadCounts>;\n /** The oldest unread message in a room; its id is \"\" when there is none. */\n firstUnread(room: string, signal?: AbortSignal): Promise<Cursor>;\n /** You have read `room` up to `at` (a message's `created`). The server never moves it back. */\n markRead(room: string, at: string): Promise<void>;\n\n // messages\n /**\n * With `kept`, asked for with the ETag of a copy kept (PERF.md \u00A75): when that copy is still the page, the server sends\n * no body, and the page is `kept.items`. Either way the page's tag goes to `kept.got`.\n */\n page(q: PageQuery, signal?: AbortSignal, kept?: KeptPage): Promise<Message[]>;\n getMessage(id: string, signal?: AbortSignal): Promise<Message>;\n /** Every message matching `q` (not just one page): used for the edits/deletes missed during a disconnect. */\n changes(q: PageQuery, signal?: AbortSignal): Promise<Message[]>;\n /** `onUpload`: how much of its attachments has been sent, 0 to 1 (\u00A717.4). */\n send(m: NewMessage, onUpload?: (fraction: number) => void): Promise<Message>;\n edit(id: string, text: string): Promise<Message>;\n softDelete(id: string): Promise<Message>;\n /** Add (`on`) or remove your `emoji` reaction on a message (\u00A720). Idempotent. */\n react(id: string, emoji: string, on: boolean): Promise<Message>;\n /** Soft-delete several of your messages at once, all or none (\u00A721.2), or a moderator anyone's (\u00A736). Resolves to them, deleted. */\n deleteMany(ids: readonly string[]): Promise<Message[]>;\n /** Is this user banned (\u00A736)? */\n isBanned(user: string, signal?: AbortSignal): Promise<boolean>;\n /** A moderator bans or unbans someone (\u00A736). */\n setBanned(user: string, banned: boolean): Promise<void>;\n /** Copy messages into `room` as yours, saying who first wrote them, all or none (\u00A721.3). Resolves to the copies. */\n forward(ids: readonly string[], room: string): Promise<Message[]>;\n\n // attachments (\u00A717.3, \u00A737.3): a file's URL is all it takes to open it, no file token\n /** URL of an attachment (a thumbnail with `thumb`, e.g. \"480x360\"). */\n fileUrl(m: Message, filename: string, thumb?: string): string;\n /** URL of a video's poster frame (\u00A730.1): 404 until the server has made it. */\n posterUrl(m: Message, filename: string): string;\n\n // media grid (\u00A730.1)\n /** A page of the room's images and videos, newest first, older than `after` (the oldest shown) or the newest. */\n media(room: string, after?: { sent: string; message: string; pos: number }, signal?: AbortSignal): Promise<MediaPage>;\n\n // collections (\u00A731): the rest of their calls are the lazy chunk's (views/collection/calls.ts), through `request`\n collections(signal?: AbortSignal): Promise<Collections>;\n /** You have seen the collection's items up to `at` (an item's `created`; default now). */\n markSeen(collection: string, at?: string): Promise<void>;\n /** What each collection's badge may say. */\n badges(ids: readonly string[], signal?: AbortSignal): Promise<Record<string, Badge>>;\n /** URL of an item's file (a thumbnail with `thumb`), as fileUrl. */\n itemUrl(item: Pick<CollectionItem, \"id\" | \"file\">, thumb?: string): string;\n /** URL of an item's video poster: 404 until there is one. */\n itemPosterUrl(item: Pick<CollectionItem, \"id\" | \"file\">): string;\n /** Changes of these collections (yours, and those you follow), and of your own subscriptions. */\n subscribeCollections(ids: readonly string[], fn: () => void): Promise<Unsubscribe>;\n /** The id of any collection whose badge may say something else now: made public or private, renamed, deleted. */\n subscribeBadges(fn: (id: string) => void): Promise<Unsubscribe>;\n /** Any request to the server, for a lazy chunk (which can't import this module); rejects with ApiError. */\n request<T>(path: string, r?: Request): Promise<T>;\n\n // realtime\n subscribeMessages(room: string, fn: RealtimeHandler<Message>): Promise<Unsubscribe>;\n subscribeRooms(fn: RealtimeHandler<Room>): Promise<Unsubscribe>;\n subscribeHidden(fn: RealtimeHandler<HiddenRow>): Promise<Unsubscribe>;\n /** Every message event in every room you can see, without text or files (\u00A718.3, \u00A734). */\n subscribeAllMessages(fn: RealtimeHandler<MessageActivity>): Promise<Unsubscribe>;\n /** Your inbox's rows as they are added and taken away (\u00A741). */\n subscribeInbox(fn: (e: InboxEvent) => void): Promise<Unsubscribe>;\n /** Your own room_reads rows, e.g. written by another tab or device. */\n subscribeReads(fn: RealtimeHandler<ReadRow>): Promise<Unsubscribe>;\n /** Called on every realtime (re)connect; `reconnect` is false for the first one. */\n onConnect(fn: (reconnect: boolean) => void): () => void;\n unsubscribeAll(): Promise<void>;\n}\n\n/** Normalized error so views never depend on SDK error classes. */\nexport class ApiError extends Error {\n readonly status: number;\n /** Per-field validation messages, e.g. { email: \"Must be a valid email.\" } */\n readonly fields: Record<string, string>;\n /** Per-field validation codes, e.g. { name: \"validation_not_unique\" }. Match on these, not on messages. */\n readonly codes: Record<string, string>;\n\n constructor(message: string, status: number, fields: Record<string, string> = {}, codes: Record<string, string> = {}) {\n super(message);\n this.name = \"ApiError\";\n this.status = status;\n this.fields = fields;\n this.codes = codes;\n }\n}\n\n/**\n * `codes.auth` of a signUp() rejection whose account *was* created but whose automatic login failed\n * (network, rate limit). Retrying the signup would only fail with \"email taken\"; the user should log in.\n */\nexport const SIGNUP_LOGIN_FAILED = \"signup_login_failed\";\n\n/** A sentence to show for a failed request: network trouble, rate limiting, or the server's own message. */\nexport function errorMessage(err: unknown): string {\n if (!(err instanceof ApiError)) return \"Something went wrong. Please try again.\";\n if (err.status === 0) return \"Can't reach the server. Check your connection.\";\n // e.g. PocketBase's default `*:auth` limit (2 requests per 3 seconds) or our messages/signup limits\n if (err.status === 429) return \"Too many attempts. Wait a few seconds and try again.\";\n return err.message;\n}\n\n/** errorMessage, or the server's reason when it gave one (e.g. \"A message was deleted.\" for a forward, \u00A721). */\nexport const reasonOf = (err: unknown): string => (err instanceof ApiError && Object.values(err.fields)[0]) || errorMessage(err);\n\n// ---- PocketBase implementation ----\n\n/** Only what the UI renders; never user emails (\u00A76). */\nexport const MSG_FIELDS =\n \"id,room,text,created,updated,edited_at,deleted,files,file_names,file_sources,file_dims,reactions,previews,author,expand.author.id,expand.author.name,expand.author.avatar,expand.author.no_dms,expand.author.instance,\" +\n \"reply_to,expand.reply_to.id,expand.reply_to.author,expand.reply_to.text,expand.reply_to.deleted,expand.reply_to.files,\" +\n \"expand.reply_to.expand.author.id,expand.reply_to.expand.author.name,\" +\n \"forwarded_from,forward_of,expand.forwarded_from.id,expand.forwarded_from.name,mentions\";\nconst MSG_OPTS = { expand: \"author,reply_to.author,forwarded_from\", fields: MSG_FIELDS } as const;\n/**\n * Live messages (server/live.go, docs/PERF.md \u00A77): the server sends each message once on this topic to everyone who\n * can see its room, expanded with `author` and `forwarded_from` but not the message a reply answers (the room fills the\n * quote in, views/room/controller.ts). A room's subscription and the activity of all rooms both listen to it.\n */\nconst LIVE_TOPIC = \"chat/messages\";\n/** Rooms with their members' public profile (DMs, \u00A716.5); never emails. */\nexport const ROOM_FIELDS =\n \"id,name,archived,created_by,kind,visibility,members,posting,writers,last_message_at,created,shared,\" +\n \"expand.members.id,expand.members.name,expand.members.avatar,expand.members.no_dms,expand.members.instance,\" +\n \"expand.writers.id,expand.writers.name,expand.writers.avatar,expand.writers.no_dms,expand.writers.instance\";\nconst ROOM_OPTS = { expand: \"members,writers\", fields: ROOM_FIELDS } as const;\nexport const HIDDEN_FIELDS = \"id,room\";\n/** The site record (\u00A724); its invite code is hidden from everyone but superusers. */\nconst SITE_FIELDS = \"id,title,logo,invite_only,password_reset\";\ninterface SiteRow {\n id: string;\n title?: string;\n logo?: string;\n invite_only?: boolean;\n /** Not a field: from the server's mail settings (\u00A739). */\n password_reset?: boolean;\n}\n/** reply_to: notifications (\u00A734) look closer at replies only. */\nexport const ACTIVITY_FIELDS = \"id,room,author,deleted,reply_to,mentions\";\n\nfunction toApiError(e: unknown): ApiError {\n if (e instanceof ApiError) return e;\n if (e instanceof PbError) {\n const data = e.response.data ?? {};\n const pick = (key: \"message\" | \"code\") =>\n Object.fromEntries(\n Object.entries(data)\n .filter(([, v]) => v && typeof v[key] === \"string\")\n .map(([k, v]) => [k, v[key] as string]),\n );\n return new ApiError(e.message, e.status, pick(\"message\"), pick(\"code\"));\n }\n return new ApiError(e instanceof Error ? e.message : String(e), 0);\n}\n\nasync function wrap<T>(p: Promise<T>): Promise<T> {\n try {\n return await p;\n } catch (e) {\n throw toApiError(e);\n }\n}\n\nconst toUser = (r: AuthRecord): User => ({\n id: r.id,\n name: r.name as string,\n avatar: (r.avatar as string | undefined) ?? \"\",\n ...(r.no_dms ? { no_dms: true } : {}),\n ...(r.instance ? { instance: r.instance as string } : {}),\n ...(r.moderator ? { moderator: true } : {}),\n ...(r.handle ? { handle: r.handle as string } : {}),\n});\n/** What the profile calls return: never the email, even for yourself. */\nexport const USER_FIELDS = \"id,name,avatar,instance,handle\";\n\n/** The query for GET /api/chat/rooms/{room}/messages (server/lists.go). */\nexport function pageOptions(q: PageQuery, limit = PAGE_SIZE, page = 1) {\n return {\n kind: q.kind,\n ...q.args,\n ...(q.files ? { files: \"1\" } : {}),\n ...(q.q ? { q: q.q } : {}),\n limit,\n ...(page > 1 ? { page } : {}),\n ...MSG_OPTS,\n };\n}\n\n/** Record endpoints of one collection: the part of the SDK's RecordService we use. */\nfunction records(pb: PbClient, collection: string) {\n const path = `/api/collections/${collection}`;\n const one = (id: string) => `${path}/records/${encodeURIComponent(id)}`;\n const list = <T>(page: number, perPage: number, query: Query, signal?: AbortSignal) =>\n pb.send<{ items: T[] }>(`${path}/records`, { query: { page, perPage, ...query }, signal });\n /** Save a fresh auth response, as the SDK does. */\n const auth = async (p: Promise<{ token: string; record: AuthRecord }>) => {\n const { token, record } = await p;\n pb.authStore.save(token, record);\n return record;\n };\n return {\n list,\n /** Every page, `batch` records at a time. */\n async fullList<T>(query: Query, signal?: AbortSignal, batch = 1000): Promise<T[]> {\n const out: T[] = [];\n for (let page = 1; ; page++) {\n const { items } = await list<T>(page, batch, { skipTotal: true, ...query }, signal);\n out.push(...items);\n if (items.length < batch) return out;\n }\n },\n get: <T>(id: string, query: Query, signal?: AbortSignal) => pb.send<T>(one(id), { query, signal }),\n create: <T>(body: Record<string, unknown>, query?: Query, onUpload?: (fraction: number) => void) =>\n pb.send<T>(`${path}/records`, { method: \"POST\", body, query, onUpload }),\n async update<T>(id: string, body: Record<string, unknown>, query: Query): Promise<T> {\n const item = await pb.send<AuthRecord>(one(id), { method: \"PATCH\", body, query });\n // Updating the logged-in user refreshes the stored record (other tabs and onAuthChange see it).\n const r = pb.authStore.record;\n if (r?.id === item.id && r.collectionName === collection) pb.authStore.save(pb.authStore.token, { ...r, ...item });\n return item as T;\n },\n delete: (id: string) => pb.send(one(id), { method: \"DELETE\" }),\n authWithPassword: (identity: string, password: string) =>\n auth(pb.send(`${path}/auth-with-password`, { method: \"POST\", body: { identity, password } })),\n // Saved only over the session it renewed: one ended (a logout) or changed meanwhile stays so.\n authRefresh: async () => {\n const sent = pb.authStore.token;\n const { token, record } = await pb.send<{ token: string; record: AuthRecord }>(`${path}/auth-refresh`, { method: \"POST\" });\n if (pb.authStore.token === sent) pb.authStore.save(token, record);\n return record;\n },\n /** POST to one of the collection's own auth actions (`request-password-reset`, \u2026) that answer 204. */\n action: (name: string, body: Record<string, unknown>) => pb.send(`${path}/${name}`, { method: \"POST\", body }),\n /** A custom route that answers like a login. */\n authAt: (url: string, body: Record<string, unknown>) => auth(pb.send(url, { method: \"POST\", body })),\n };\n}\n\n/** Statuses of a refused change: invalid data, or no (valid) session. */\nconst REFUSED = new Set([400, 401, 403, 404]);\n\n/** A page's copy kept by the caller, and where its tag goes (Api.page). `items` as the page has them, newest first. */\nexport interface KeptPage {\n tag?: string | undefined;\n items: readonly Message[];\n got?: (tag: string) => void;\n}\n\nexport function createApi(client: PbClient): Api {\n const rejected = new Set<() => void>();\n /** The client, telling onRejected listeners about changes refused while the session was sent with them. */\n const pb: PbClient = {\n authStore: client.authStore,\n realtime: client.realtime,\n filter: client.filter,\n fileUrl: client.fileUrl,\n async send<T>(path: string, opts: RequestOptions = {}): Promise<T> {\n const token = client.authStore.token;\n try {\n return await client.send<T>(path, opts);\n } catch (e) {\n const write = (opts.method ?? \"GET\") !== \"GET\" && !path.includes(\"/auth-\"); // a login or refresh says so itself\n if (e instanceof PbError && REFUSED.has(e.status) && write && token && token === client.authStore.token) {\n for (const fn of [...rejected]) fn();\n }\n throw e;\n }\n },\n };\n const users = records(pb, \"users\");\n const rooms = records(pb, \"rooms\");\n const hidden = records(pb, \"hidden_rooms\");\n const messages = records(pb, \"messages\");\n const site = records(pb, \"site\");\n /** Every record event of a collection, narrowed to our Action type. */\n const subscribe = <T>(collection: string, fn: RealtimeHandler<T>, query: Query) =>\n wrap(\n pb.realtime.subscribe(\n `${collection}/*`,\n (e) => {\n const { action, record } = e as { action: Action; record: T };\n fn(action, record);\n },\n query,\n ),\n );\n const live = (fn: (action: Action, m: Message) => void) =>\n wrap(\n pb.realtime.subscribe(LIVE_TOPIC, (e) => {\n const { action, record } = e as { action: Action; record: Message };\n fn(action, record);\n }),\n );\n const me = () => {\n const u = api.currentUser();\n if (!u) throw new ApiError(\"Not logged in.\", 401);\n return u.id;\n };\n\n const api: Api = {\n currentUser() {\n const r = pb.authStore.record;\n return pb.authStore.isValid && r?.collectionName === \"users\" ? toUser(r) : null;\n },\n async signUp({ email, password, name, inviteCode }) {\n const invite = inviteCode ? { invite_code: inviteCode } : {};\n await wrap(users.create({ email, password, passwordConfirm: password, name, ...invite }));\n try {\n return await api.logIn(email, password);\n } catch (e) {\n const err = toApiError(e);\n throw new ApiError(err.message, err.status, {}, { auth: SIGNUP_LOGIN_FAILED });\n }\n },\n async logIn(email, password) {\n return toUser(await wrap(users.authWithPassword(email, password)));\n },\n async requestPasswordReset(email) {\n // In lower case, as emails are stored (QA BUG-47): PocketBase looks the address up as it is sent.\n await wrap(users.action(\"request-password-reset\", { email: email.trim().toLowerCase() }));\n },\n async confirmPasswordReset(token, password) {\n await wrap(users.action(\"confirm-password-reset\", { token, password, passwordConfirm: password }));\n },\n async refreshAuth() {\n if (!api.currentUser()) throw new ApiError(\"Not logged in.\", 401);\n return toUser(await wrap(users.authRefresh()));\n },\n sessionExpiry: () => pb.authStore.expiresAt,\n logOut() {\n pb.authStore.clear();\n },\n forgetExpired() {\n const r = pb.authStore.record;\n if (!r || pb.authStore.isValid) return \"\";\n pb.authStore.clear();\n return r.id;\n },\n onAuthChange(fn) {\n // A localStorage-backed store also fires this when another tab saves or clears the shared session.\n return pb.authStore.onChange(() => fn());\n },\n onRejected(fn) {\n rejected.add(fn);\n return () => void rejected.delete(fn);\n },\n\n // A body holding a File is sent as multipart; update() refreshes the stored auth record from the response.\n async site(signal) {\n const { items } = await wrap(site.list<SiteRow>(1, 1, { sort: \"created\", skipTotal: true, fields: SITE_FIELDS }, signal));\n const row = items[0];\n if (!row) return DEFAULT_SITE;\n return {\n title: row.title || DEFAULT_SITE.title,\n logo: row.logo ? pb.fileUrl(\"site\", row.id, row.logo) : \"\",\n inviteOnly: row.invite_only === true,\n passwordReset: row.password_reset === true,\n };\n },\n\n setAvatar: async (file) => toUser(await wrap(users.update(me(), { avatar: file }, { fields: USER_FIELDS }))),\n removeAvatar: async () => toUser(await wrap(users.update(me(), { avatar: null }, { fields: USER_FIELDS }))),\n rename: async (name) => toUser(await wrap(users.update(me(), { name }, { fields: USER_FIELDS }))),\n setHandle: async (handle) => toUser(await wrap(users.update(me(), { handle }, { fields: USER_FIELDS }))),\n async changePassword(oldPassword, password) {\n me();\n return toUser(await wrap(users.authAt(\"/api/chat/password\", { oldPassword, password })));\n },\n avatarUrl(user, size) {\n if (!user.avatar) return \"\";\n return pb.fileUrl(\"users\", user.id, user.avatar, { thumb: `${size}x${size}` });\n },\n\n listRooms: (signal) => wrap(pb.send<Room[]>(\"/api/chat/rooms\", { query: ROOM_OPTS, signal })),\n getRoom: (id, signal) => wrap(rooms.get<Room>(id, ROOM_OPTS, signal)),\n createRoom: async (name, visibility) =>\n wrap(rooms.create<Room>({ name, created_by: me(), ...(visibility ? { visibility } : {}) }, ROOM_OPTS)),\n setArchived: (id, archived) => wrap(rooms.update<Room>(id, { archived }, ROOM_OPTS)),\n setAccess: (id, visibility, members, posting, writers = []) =>\n wrap(\n rooms.update<Room>(\n id,\n {\n visibility,\n members: visibility === \"private\" ? [...members] : [],\n ...(posting ? { posting, writers: posting === \"selected\" ? [...writers] : [] } : {}),\n },\n ROOM_OPTS,\n ),\n ),\n\n openDm: (userId) => wrap(pb.send<Room>(\"/api/chat/dms\", { method: \"POST\", body: { user: userId } })),\n async searchUsers(query, signal) {\n me();\n // A route, not a filter on `name`: it matches case-insensitively beyond ASCII (\"\u0438\u0432\u0430\u043D\" finds \"\u0418\u0432\u0430\u043D\", QA BUG-55).\n return (await wrap(pb.send<AuthRecord[]>(\"/api/chat/users\", { query: { q: query }, signal }))).map(toUser);\n },\n\n remoteUser: async (address, room) =>\n toUser(await wrap(pb.send<AuthRecord>(\"/api/chat/remote-users\", { method: \"POST\", body: { address, ...(room ? { room } : {}) } }))),\n\n async usersById(ids, signal) {\n const some = ids.slice(0, 50);\n if (!some.length) return [];\n const params = Object.fromEntries(some.map((id, i) => [`u${i}`, id]));\n const opts = { filter: pb.filter(some.map((_, i) => `id = {:u${i}}`).join(\" || \"), params), fields: USER_FIELDS, skipTotal: true };\n return (await wrap(users.list<AuthRecord>(1, some.length, opts, signal))).items.map(toUser);\n },\n\n listHidden: (signal) => wrap(hidden.fullList<HiddenRow>({ fields: HIDDEN_FIELDS }, signal)),\n hideRoom: async (room) => wrap(hidden.create<HiddenRow>({ user: me(), room }, { fields: HIDDEN_FIELDS })),\n unhideRoom: async (rowId) => {\n await wrap(hidden.delete(rowId));\n },\n\n unreadCounts: (signal) => wrap(pb.send<UnreadCounts>(\"/api/chat/unread\", { signal })),\n firstUnread: (room, signal) => wrap(pb.send<Cursor>(`/api/chat/unread/${room}`, { signal })),\n markRead: async (room, at) => {\n await wrap(pb.send(\"/api/chat/reads\", { method: \"POST\", body: { room, at } }));\n },\n\n page: async (q, signal, kept) => {\n const path = `/api/chat/rooms/${encodeURIComponent(q.room)}/messages`;\n const tag = kept && { sent: kept.items.length ? kept.tag : undefined, got: kept.got };\n return (await wrap(pb.send<Message[] | undefined>(path, { query: pageOptions(q), signal, tag }))) ?? [...(kept?.items ?? [])];\n },\n getMessage: (id, signal) => wrap(messages.get<Message>(id, MSG_OPTS, signal)),\n async changes(q, signal) {\n const out: Message[] = [];\n for (let page = 1; ; page++) {\n const path = `/api/chat/rooms/${encodeURIComponent(q.room)}/messages`;\n const some = await wrap(pb.send<Message[]>(path, { query: pageOptions(q, 200, page), signal }));\n out.push(...some);\n if (some.length < 200) return out;\n }\n },\n send: async (m, onUpload) =>\n wrap(\n messages.create<Message>(\n {\n id: m.id,\n room: m.room,\n author: me(),\n text: m.text,\n ...(m.files?.length ? { files: m.files } : {}),\n ...(m.replyTo ? { reply_to: m.replyTo } : {}),\n ...(m.items?.length ? { items: m.items } : {}),\n },\n MSG_OPTS,\n m.files?.length ? onUpload : undefined,\n ),\n ),\n edit: (id, text) => wrap(messages.update<Message>(id, { text }, MSG_OPTS)),\n softDelete: (id) => wrap(messages.update<Message>(id, { deleted: true }, MSG_OPTS)),\n react: (id, emoji, on) =>\n wrap(pb.send<Message>(\"/api/chat/reactions\", { method: \"POST\", body: { message: id, emoji, on }, query: MSG_OPTS })),\n\n deleteMany: (ids) => wrap(pb.send<Message[]>(\"/api/chat/delete\", { method: \"POST\", body: { messages: ids }, query: MSG_OPTS })),\n isBanned: async (user, signal) => !!(await wrap(users.get<AuthRecord>(user, { fields: \"id,banned\" }, signal))).banned,\n setBanned: async (user, banned) => void (await wrap(pb.send(\"/api/chat/ban\", { method: \"POST\", body: { user, banned } }))),\n forward: (ids, room) =>\n wrap(pb.send<Message[]>(\"/api/chat/forward\", { method: \"POST\", body: { messages: ids, room }, query: MSG_OPTS })),\n // A forward's attachments are its original's (\u00A721.3).\n fileUrl: (m, filename, thumb) => pb.fileUrl(\"messages\", m.forward_of || m.id, filename, { thumb }),\n // The file's own URL, on the poster route.\n posterUrl: (m, filename) => api.fileUrl(m, filename).replace(\"/api/files/messages/\", \"/api/chat/posters/\"),\n collections: (signal) => wrap(pb.send<Collections>(\"/api/chat/collections\", { signal })),\n markSeen: async (collection, at) => {\n await wrap(pb.send(\"/api/chat/subs/seen\", { method: \"POST\", body: { collection, ...(at ? { at } : {}) } }));\n },\n badges: (ids, signal) => wrap(pb.send<Record<string, Badge>>(\"/api/chat/badges\", { query: { ids: ids.join(\",\") }, signal })),\n itemUrl: (item, thumb) => pb.fileUrl(\"collection_items\", item.id, item.file, { thumb }),\n itemPosterUrl: (item) => api.itemUrl(item).replace(\"/api/files/collection_items/\", \"/api/chat/posters/items/\"),\n async subscribeCollections(ids, fn) {\n // One topic per collection followed: a filter naming them all could be longer than a topic may be.\n const offs = await Promise.all([\n subscribe(\"collections\", fn, { fields: \"id\", filter: pb.filter(\"owner = {:me}\", { me: me() }) }),\n subscribe(\"collection_subs\", fn, { fields: \"id\" }),\n ...ids.map((id) => wrap(pb.realtime.subscribe(`collections/${id}`, fn, { fields: \"id\" }))),\n ]);\n return async () => {\n await Promise.all(offs.map((off) => off()));\n };\n },\n subscribeBadges: (fn) => wrap(pb.realtime.subscribe(\"chat/badges\", (d) => fn((d as { id: string }).id))),\n request: (path, r) => wrap(pb.send(path, r)),\n media: (room, after, signal) => wrap(pb.send<MediaPage>(`/api/chat/media/${room}`, { query: after, signal })),\n\n subscribeMessages: (room, fn) => live((action, m) => m.room === room && fn(action, m)),\n subscribeRooms: (fn) => subscribe(\"rooms\", fn, ROOM_OPTS),\n subscribeHidden: (fn) => subscribe(\"hidden_rooms\", fn, { fields: HIDDEN_FIELDS }),\n subscribeAllMessages: (fn) =>\n live((action, m) =>\n fn(action, {\n id: m.id,\n room: m.room,\n author: m.author,\n deleted: m.deleted,\n reply_to: m.reply_to ?? \"\",\n mentions: m.mentions ?? [],\n }),\n ),\n subscribeInbox: (fn) => wrap(pb.realtime.subscribe(\"chat/inbox\", (d) => fn(d as InboxEvent))),\n subscribeReads: (fn) => subscribe(\"room_reads\", fn, { fields: HIDDEN_FIELDS }),\n\n onConnect(fn) {\n // PB_CONNECT only reaches listeners for connections made after they subscribe. If we are already\n // connected now, the next PB_CONNECT this listener sees is a reconnect, not the initial connect. So is one that\n // follows a failed first connect: what was loaded meanwhile may have missed events.\n let connected = pb.realtime.isConnected;\n const unsub = pb.realtime.subscribe(\"PB_CONNECT\", () => {\n fn(connected || pb.realtime.recovered);\n connected = true;\n });\n // A failed first connect (offline, server down) rejects it, and the client keeps trying: not an error (QA BUG-85).\n unsub.catch(() => {});\n return () => void unsub.then((off) => off()).catch(() => {});\n },\n unsubscribeAll: () => wrap(pb.realtime.unsubscribe()),\n };\n return api;\n}\n", "// Field limits the UI enforces before the server does. They mirror pb_migrations (the source of truth);\n// tests/integration/schema.test.ts fails if the two drift apart.\n\nexport const LIMITS = {\n /** messages.text max */\n messageText: 2000,\n /** users.name max */\n userName: 32,\n /** rooms.name max */\n roomName: 48,\n /** users password min (PocketBase's auth default) */\n passwordMin: 8,\n /**\n * users password max, in UTF-8 bytes: bcrypt's 72, PocketBase's 71. PocketBase refuses a longer one on signup without\n * saying why (QA BUG-267); the hooks say it for a change or a reset (PASSWORD_MAX_BYTES, lib/users.js).\n */\n passwordMaxBytes: 71,\n /** users.avatar maxSize (\u00A715.1) */\n avatarBytes: 2 * 1024 * 1024,\n /** users.avatar mimeTypes (\u00A715.1) */\n avatarTypes: [\"image/jpeg\", \"image/png\", \"image/webp\", \"image/gif\"],\n /** messages.files maxSelect (\u00A717.1) */\n attachments: 10,\n /** messages.files maxSize, per file (\u00A717.1) */\n attachmentBytes: 20 * 1024 * 1024,\n /** rooms.members maxSelect: a private room's members, its creator included (\u00A723.2) */\n roomMembers: 100,\n} as const;\n\n/** Length as PocketBase counts it for these limits: Unicode code points, not UTF-16 units (an emoji is 1, not 2). */\nexport function textLength(s: string): number {\n let n = 0;\n for (const _ of s) n++;\n return n;\n}\n\n/** Most messages that can be selected, and so deleted or forwarded at once (\u00A721; MAX_MESSAGES in pb_hooks/lib/bulk.js). */\nexport const MAX_SELECTED = 50;\n"],
|
|
5
|
-
"mappings": "AAiPO,IAAMA,EAAqB,CAAE,MAAO,UAAW,KAAM,GAAI,WAAY,GAAO,cAAe,EAAM,ECvNjG,IAAMC,EAAN,cAAsB,KAAM,CACxB,OACA,SACA,QAET,YAAYC,EAAgBC,EA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T,CAGO,IAAME,GAAe",
|
|
6
|
-
"names": ["DEFAULT_SITE", "PbError", "status", "response", "isAbort", "STORAGE_KEY", "tokenExp", "token", "part", "createAuthStore", "storage", "record", "listeners", "load", "raw", "data", "set", "t", "r", "fn", "e", "qs", "query", "parts", "k", "v", "isFiles", "x", "toFormData", "body", "form", "f", "upload", "url", "method", "headers", "onUpload", "ok", "fail", "createClient", "baseUrl", "authStore", "base", "send", "path", "signal", "tag", "payload", "aborted", "res", "etag", "realtime", "createRealtime", "who", "next", "expr", "params", "match", "name", "collection", "recordId", "filename", "RECONNECT_MS", "CONNECT_TIMEOUT_MS", "es", "clientId", "subs", "lastSent", "attempts", "lost", "connectTimer", "reconnectTimer", "pending", "submitting", "queue", "keys", "unsent", "now", "bound", "bind", "key", "source", "sendSubs", "disconnect", "submit", "connect", "resolve", "reject", "initConnect", "connectError", "current", "tries", "p", "err", "reconnecting", "topic", "listener", "fns", "left", "latest", "room", "first", "older", "c", "newer", "changedIn", "since", "from", "to", "withFiles", "q", "ApiError", "message", "status", "fields", "codes", "SIGNUP_LOGIN_FAILED", "errorMessage", "err", "reasonOf", "MSG_FIELDS", "MSG_OPTS", "LIVE_TOPIC", "ROOM_FIELDS", "ROOM_OPTS", "HIDDEN_FIELDS", "SITE_FIELDS", "toApiError", "e", "ApiError", "PbError", "data", "pick", "key", "v", "k", "wrap", "p", "toUser", "r", "USER_FIELDS", "pageOptions", "q", "limit", "page", "MSG_OPTS", "records", "pb", "collection", "path", "one", "id", "list", "perPage", "query", "signal", "auth", "token", "record", "batch", "out", "items", "body", "onUpload", "item", "identity", "password", "sent", "name", "url", "REFUSED", "createApi", "client", "rejected", "opts", "write", "fn", "users", "rooms", "hidden", "messages", "site", "subscribe", "action", "live", "LIVE_TOPIC", "me", "u", "api", "email", "inviteCode", "invite", "err", "SIGNUP_LOGIN_FAILED", "SITE_FIELDS", "row", "DEFAULT_SITE", "file", "handle", "oldPassword", "user", "size", "ROOM_OPTS", "visibility", "archived", "members", "posting", "writers", "userId", "address", "room", "ids", "some", "params", "i", "_", "HIDDEN_FIELDS", "rowId", "at", "kept", "tag", "
|
|
3
|
+
"sources": ["../../web/src/lib/types.ts", "../../web/src/pb.ts", "../../web/src/lib/cursor.ts", "../../web/src/api.ts", "../../web/src/lib/time.ts"],
|
|
4
|
+
"sourcesContent": ["// Shapes of records as the frontend sees them (DESIGN.md \u00A75, \u00A76).\n\nexport interface User {\n id: string;\n name: string;\n /** Avatar filename (\u00A715); \"\" or absent when the user has none. */\n avatar?: string;\n /** Doesn't take direct messages (\u00A716.7), e.g. a Telegram bridge's stand-in; absent where the server doesn't say. */\n no_dms?: boolean;\n /** Someone on a linked instance (\u00A733.4): its host, e.g. \"b.example\". Absent for this instance's own people. */\n instance?: string;\n /** You are a moderator (\u00A736): only said of the signed-in user. */\n moderator?: boolean;\n /** What \"@handle\" names (\u00A741), without the \"@\"; absent where the server doesn't say. */\n handle?: string;\n}\n\n/**\n * Who else holds a shared room (\u00A733.10): `home`, on a copy of another instance's room (its host); `with`, the other\n * instances that have it; `down`, its home can't be reached right now. Empty for a room that isn't shared.\n */\nexport interface Shared {\n home?: string;\n with?: string[];\n down?: boolean;\n}\n\nexport type RoomKind = \"public\" | \"dm\";\n\n/**\n * Who can see a room (\u00A723.1): its members only, every signed-in user, or anyone at all, even without an account\n * (Open Air). A DM is private to its two members.\n */\nexport type Visibility = \"private\" | \"public\" | \"open\";\n/** Who can post in a room (\u00A723.6): everyone who can read it, or only its writers. */\nexport type Posting = \"everyone\" | \"selected\";\n\nexport interface Room {\n id: string;\n /** \"\" for a DM: its title is the other member's name (lib/rooms.ts). */\n name: string;\n archived: boolean;\n created_by: string;\n /** Absent = \"public\" (\u00A716.1). */\n kind?: RoomKind;\n /** Absent = \"public\" (\u00A723.1). */\n visibility?: Visibility;\n /** A DM's two members, or a private room's (the creator and whoever they added, \u00A723.2); empty otherwise. */\n members?: string[];\n /** Absent = \"everyone\" (\u00A723.6). */\n posting?: Posting;\n /** Who can post when posting is \"selected\": the creator and the people they chose (\u00A723.6); empty otherwise. */\n writers?: string[];\n /** DMs: when the latest message was sent (\"\" before the first). */\n last_message_at?: string;\n created?: string;\n /** Shared with other instances (\u00A733). */\n shared?: Shared | null;\n expand?: { members?: User[]; writers?: User[] };\n}\n\n/** Client-only send state for optimistic messages (\u00A77.5). Absent once the server has the message. */\nexport type SendStatus = \"pending\" | \"failed\";\n\nexport interface Message {\n id: string;\n room: string;\n /** \"\" for a service message (\u00A75.3): the app's own notice in the room, e.g. a Telegram group disconnected. */\n author: string;\n text: string;\n /** PocketBase datetime, e.g. \"2026-10-10 12:34:56.789Z\". */\n created: string;\n updated: string;\n /** \"\" when never edited. */\n edited_at: string;\n deleted: boolean;\n /** Stored attachment names (\u00A717.1); empty or absent when there are none. */\n files?: string[];\n /** Original upload names by stored name, set by the server (QA BUG-28); absent for older messages. */\n file_names?: Record<string, string>;\n /** Stored name \u2192 the collection it was attached from (\u00A731); absent or empty for the others. */\n file_sources?: Record<string, string>;\n /** Stored image or video name \u2192 [width, height] as shown (\u00A717.5), set by the server; absent until it knows. */\n file_dims?: Record<string, [number, number]>;\n /** The message this one replies to (\u00A719); \"\" or absent when it isn't a reply. */\n reply_to?: string;\n /** Emoji reactions (\u00A720), in the order they were first added; empty or absent when there are none. */\n reactions?: Reaction[];\n /** Who first wrote it, when it was forwarded (\u00A721.3); \"\" or absent otherwise. */\n forwarded_from?: string;\n /**\n * The message a forward shows (\u00A721.3): the server answers with its text, attachments and edit stamp, or none once\n * it is deleted. \"\" or absent otherwise, and for forwards made before forwards pointed at their original.\n */\n forward_of?: string;\n /** Who its \"@handle\"s name (\u00A741): user ids, set by the server; empty or absent when none. */\n mentions?: string[];\n /** What its links show (\u00A728), set by the server once it has fetched them; empty or absent until then. */\n previews?: LinkPreview[];\n expand?: { author?: User; reply_to?: Quoted; forwarded_from?: User };\n status?: SendStatus;\n /** Client-only: attachments of a message not (yet) on the server, with local preview URLs (\u00A717.4). */\n localFiles?: LocalFile[];\n}\n\n/** A link's line under a message (\u00A728): the page's title, and its favicon as a data: URL (\"\" when it has none). */\nexport interface LinkPreview {\n url: string;\n title: string;\n icon: string;\n}\n\n/** One image or video in a room's media grid (\u00A730.1): a file of `source`, shown by `message` (a forward, or itself). */\nexport interface MediaItem {\n message: string;\n source: string;\n file: string;\n /** Its place in the source's files. */\n pos: number;\n /** The original upload name, \"\" when the server has none (QA BUG-28). */\n name: string;\n video: boolean;\n /** A video's poster frame is ready (GET /api/chat/posters/{source}/{file}). */\n poster: boolean;\n /** The message's `created`. */\n sent: string;\n /** Who sent the message; null for a service message. */\n author: { id: string; name: string } | null;\n}\n\n/** A page of a room's media, newest first; `more`: there are older ones. */\nexport interface MediaPage {\n items: MediaItem[];\n more: boolean;\n}\n\n/** One emoji on a message and who reacted with it (\u00A720.1). */\nexport interface Reaction {\n emoji: string;\n /** User ids, in the order they reacted. Never empty. */\n users: string[];\n}\n\n/** What a reply shows of the message it answers (\u00A719). */\nexport interface Quoted {\n id: string;\n author: string;\n text: string;\n deleted: boolean;\n files?: string[];\n expand?: { author?: User };\n}\n\nexport interface LocalFile {\n /** For an item from a collection, an empty stand-in named after it. */\n file: File;\n /** Object URL for an image or video preview, \"\" for other files. Revoked once the message no longer needs it. */\n url: string;\n /** Attached from a collection (\u00A731): the item's id, sent for the server to copy, and its collection's. */\n item?: { id: string; collection: string };\n}\n\n/** A collection (\u00A731), as GET /api/chat/collections lists it. */\nexport interface Collection {\n id: string;\n name: string;\n public: boolean;\n items: number;\n last_added: string;\n /** Someone else's that you follow: whose it is, up to when you've seen it, and how many items are new (at most 100). */\n owner?: { id: string; name: string };\n seen_at?: string;\n new?: number;\n}\n\n/** What GET /api/chat/collections answers: yours and those you follow, by name. */\nexport interface Collections {\n mine: Collection[];\n subs: Collection[];\n}\n\n/** A collection item (\u00A731): one image or video. */\nexport interface CollectionItem {\n id: string;\n collection: string;\n file: string;\n /** The original file name. */\n name: string;\n video: boolean;\n /** A video's poster frame is ready (GET /api/chat/posters/items/{id}/{file}). */\n poster: boolean;\n created: string;\n}\n\n/** What a \"from collection\" badge may say (\u00A731): a public one's (or your own) name, \"private\", or null: gone. */\nexport type Badge = { name: string; public: boolean; mine: boolean } | { private: true } | null;\n\n/** The site's branding and signup policy (\u00A724), set by an admin in PocketBase. */\nexport interface Site {\n title: string;\n /** URL of the logo image, or \"\" without one. */\n logo: string;\n /** Signing up needs an invite code. */\n inviteOnly: boolean;\n /** The server emails password reset links: \"Forgot password?\" is offered (\u00A739). */\n passwordReset: boolean;\n}\n\n/** A row of the \"Mentions & replies\" inbox (\u00A741, GET /api/chat/inbox). */\nexport interface InboxItem {\n id: string;\n /** Where the next page starts (`before`). */\n cursor: string;\n kind: \"mention\" | \"reply\" | \"reaction\";\n /** A reaction row's: the actor's emoji on the message, the first five then \" +n\" (\u00A741.4); \"\" otherwise. */\n emoji: string;\n /** A reaction row's emoji, all of them. Missing from servers before 2026-11-11. */\n emojis?: string[];\n created: string;\n /** A mention or reply already read in its room: not new here. Missing from servers before. */\n read?: boolean;\n room: string;\n /** The message: the mention, the reply, or your message reacted to. Its text cut short, how many files it has. */\n message: { id: string; text: string; files: number; created: string };\n /** A reply's: your message it answers (\"\" text and no files once deleted). */\n quote: { id: string; text: string; files: number } | null;\n /** Who did it; in an anonymous room (\u00A735), the room for a mention or reply. */\n actor: User;\n}\n\n/** A row of the inbox added or taken away, told live on `chat/inbox` (\u00A741). */\nexport interface InboxEvent {\n action: \"create\" | \"delete\";\n id: string;\n kind: InboxItem[\"kind\"];\n room: string;\n message: string;\n created: string;\n}\n\n/** What the app shows before (or without) the site record. */\nexport const DEFAULT_SITE: Site = { title: \"Chirkle\", logo: \"\", inviteOnly: false, passwordReset: false };\n", "import * as S from \"./strings/pb.ts\";\n// A minimal PocketBase client: only what api.ts uses (REST requests, the auth store, realtime over SSE, file URLs).\n// It replaces the official JS SDK, whose admin services, OAuth2/OTP/MFA flows and cookie helpers the app never used\n// but always shipped (\u00A77.7). The wire behavior follows SDK 0.28: same storage key, query and realtime protocol.\n\nexport type Query = Record<string, string | number | boolean | undefined>;\n\nexport interface RequestOptions {\n method?: string;\n query?: Query | undefined;\n /** JSON, or multipart when any value is a Blob/File (or an array of them). */\n body?: Record<string, unknown>;\n signal?: AbortSignal | undefined;\n /** How much of a multipart body has been sent, 0 to 1: the request then goes through XHR (fetch can't tell). */\n onUpload?: ((fraction: number) => void) | undefined;\n /** A conditional GET (PERF.md \u00A75): `sent` goes as If-None-Match, the answer's ETag to `got`. A 304 answers undefined. */\n tag?: { sent?: string | undefined; got?: ((tag: string) => void) | undefined } | undefined;\n}\n\nexport interface AuthRecord {\n id: string;\n collectionName?: string;\n [field: string]: unknown;\n}\n\n/** A failed request: `status` 0 for network trouble or an abort. `response` is PocketBase's error body. */\nexport class PbError extends Error {\n readonly status: number;\n readonly response: { message?: string; data?: Record<string, { message?: unknown; code?: unknown }> };\n readonly isAbort: boolean;\n\n constructor(status: number, response: PbError[\"response\"] = {}, isAbort = false) {\n super(response.message || \"Something went wrong.\");\n this.name = \"PbError\";\n this.status = status;\n this.response = response;\n this.isAbort = isAbort;\n }\n}\n\n// ---- auth store ----\n\nexport interface AuthStore {\n readonly token: string;\n readonly record: AuthRecord | null;\n /** There is a token and it hasn't expired. */\n readonly isValid: boolean;\n /** When the token expires (epoch ms), or 0 without a (readable) token. */\n readonly expiresAt: number;\n save(token: string, record: AuthRecord | null): void;\n clear(): void;\n /** Called on every save/clear, including another tab's when the store is backed by localStorage. */\n onChange(fn: () => void): () => void;\n}\n\n/** The SDK's key, so existing sessions survive the switch. */\nconst STORAGE_KEY = \"pocketbase_auth\";\n\n/** The JWT's `exp` (seconds), or 0 when it can't be read. */\nfunction tokenExp(token: string): number {\n try {\n const part = token.split(\".\")[1]!.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\");\n return Number(JSON.parse(atob(part)).exp) || 0;\n } catch {\n return 0;\n }\n}\n\n/** In memory only, or persisted in `storage` (shared with the other tabs of this browser). */\nexport function createAuthStore(storage?: Storage): AuthStore {\n let token = \"\";\n let record: AuthRecord | null = null;\n const listeners = new Set<() => void>();\n\n const load = (raw: string | null) => {\n let data: { token?: string; record?: AuthRecord | null } = {};\n try {\n data = JSON.parse(raw || \"{}\") ?? {};\n } catch {}\n token = data.token || \"\";\n record = data.record || null;\n };\n const set = (t: string, r: AuthRecord | null) => {\n token = t;\n record = r;\n for (const fn of [...listeners]) fn();\n };\n\n if (storage) {\n load(storage.getItem(STORAGE_KEY));\n addEventListener(\"storage\", (e) => {\n if (e.key !== STORAGE_KEY) return;\n load(e.newValue);\n set(token, record);\n });\n }\n\n return {\n get token() {\n return token;\n },\n get record() {\n return record;\n },\n get isValid() {\n return tokenExp(token) > Date.now() / 1000;\n },\n get expiresAt() {\n return tokenExp(token) * 1000;\n },\n save(t, r) {\n storage?.setItem(STORAGE_KEY, JSON.stringify({ token: t, record: r }));\n set(t, r);\n },\n clear() {\n storage?.removeItem(STORAGE_KEY);\n set(\"\", null);\n },\n onChange(fn) {\n listeners.add(fn);\n return () => void listeners.delete(fn);\n },\n };\n}\n\n// ---- client ----\n\nexport type Unsubscribe = () => Promise<void>;\n\nexport interface Realtime {\n /** Connected, with a client id, and no connect in progress. */\n readonly isConnected: boolean;\n /** The connection being made follows one that failed or was lost: events may have been missed meanwhile. */\n readonly recovered: boolean;\n /**\n * Listen to `topic` (e.g. \"messages/*\", or \"PB_CONNECT\" for every (re)connect). Resolves once the server has the\n * subscription, so an event caused after that reaches `fn`. `query` (fields, expand, filter) applies to its events.\n */\n subscribe(topic: string, fn: (data: unknown) => void, query?: Query): Promise<Unsubscribe>;\n /** Drop every subscription and close the connection. */\n unsubscribe(): Promise<void>;\n}\n\nexport interface PbClient {\n readonly authStore: AuthStore;\n readonly realtime: Realtime;\n send<T>(path: string, opts?: RequestOptions): Promise<T>;\n /** Bind `{:name}` placeholders in a filter expression, quoting and escaping the values. */\n filter(expr: string, params: Record<string, string | number | boolean | null>): string;\n /** URL of a record's file (`query`: thumb). */\n fileUrl(collection: string, recordId: string, filename: string, query?: Query): string;\n}\n\nconst qs = (query: Query = {}) => {\n const parts: string[] = [];\n for (const [k, v] of Object.entries(query)) if (v !== undefined) parts.push(`${encodeURIComponent(k)}=${encodeURIComponent(v)}`);\n return parts.length ? `?${parts.join(\"&\")}` : \"\";\n};\n\nconst isFiles = (v: unknown) => v instanceof Blob || (Array.isArray(v) && v.some((x) => x instanceof Blob));\n\n/** A body holding files as multipart: files and strings as fields, anything else in PocketBase's `@jsonPayload`. */\nfunction toFormData(body: Record<string, unknown>): FormData {\n const form = new FormData();\n for (const [k, v] of Object.entries(body)) {\n if (v === undefined) continue;\n if (isFiles(v)) for (const f of [v].flat() as Blob[]) form.append(k, f);\n else if (typeof v === \"string\") form.append(k, v);\n else form.append(\"@jsonPayload\", JSON.stringify({ [k]: v }));\n }\n return form;\n}\n\n/** An XHR answer as fetch gives it: rejects only when nothing came back (an AbortError when aborted). */\nfunction upload(url: string, method: string, headers: Record<string, string>, body: FormData, onUpload: (fraction: number) => void) {\n return new Promise<{ status: number; json: () => Promise<unknown> }>((ok, fail) => {\n const x = new XMLHttpRequest();\n x.open(method, url);\n for (const [k, v] of Object.entries(headers)) x.setRequestHeader(k, v);\n x.upload.onprogress = (e) => e.lengthComputable && e.total && onUpload(e.loaded / e.total);\n x.onload = () => ok({ status: x.status, json: async () => JSON.parse(x.responseText) });\n x.onerror = () => fail(new TypeError(\"Network request failed\"));\n x.onabort = () => fail(new DOMException(\"Aborted\", \"AbortError\"));\n x.send(body);\n });\n}\n\nexport function createClient(baseUrl: string, authStore: AuthStore = createAuthStore()): PbClient {\n const base = baseUrl.replace(/\\/+$/, \"\");\n\n async function send<T>(path: string, { method = \"GET\", query, body, signal, onUpload, tag }: RequestOptions = {}): Promise<T> {\n const headers: Record<string, string> = {};\n if (authStore.token) headers.Authorization = authStore.token;\n // The 304 is ours to read, not the HTTP cache's to answer from (it keeps no copy: no-store).\n if (tag?.sent) Object.assign(headers, { \"If-None-Match\": tag.sent, \"Cache-Control\": \"no-cache\" });\n let payload: BodyInit | undefined;\n if (body) {\n if (Object.values(body).some(isFiles)) payload = toFormData(body);\n else {\n headers[\"Content-Type\"] = \"application/json\";\n payload = JSON.stringify(body);\n }\n }\n const aborted = (e: unknown) => !!signal?.aborted || (e as Error)?.name === \"AbortError\";\n let res: { status: number; json: () => Promise<unknown>; headers?: Headers };\n let data: PbError[\"response\"] = {};\n const url = base + path + qs(query);\n try {\n res =\n onUpload && payload instanceof FormData\n ? await upload(url, method, headers, payload, onUpload)\n : await fetch(url, { method, headers, ...(payload ? { body: payload } : {}), ...(signal ? { signal } : {}) });\n const etag = res.headers?.get(\"ETag\");\n if (etag) tag?.got?.(etag);\n if (res.status === 304) return undefined as T;\n // No body is fine for a 204, or an error the server didn't explain. A success whose body never came (the page\n // navigated away, the connection dropped) is a failure, not `{}`: as a login's answer it saved no session (QA BUG-117).\n data = await (res.json() as Promise<PbError[\"response\"]>).catch((e) => {\n if (aborted(e) || (res.status < 300 && res.status !== 204)) throw e;\n return {};\n });\n } catch (e) {\n throw new PbError(0, {}, aborted(e));\n }\n if (res.status >= 400) throw new PbError(res.status, data ?? {});\n return data as T;\n }\n\n const realtime = createRealtime(`${base}/api/realtime`, send);\n // The server reads who a realtime client is from the token its subscriptions were sent with. A new token (a password\n // change, which revokes the old ones, here or in another tab) must reach it, or nothing more arrives (QA BUG-52).\n // Someone else (or nobody, after a logout) needs a new connection: the server refuses another user's subscriptions on\n // one it knows as someone, and would go on sending that user's events on it (QA BUG-66).\n let token = authStore.token;\n let who = token ? (authStore.record?.id ?? \"\") : \"\";\n authStore.onChange(() => {\n if (authStore.token === token) return;\n token = authStore.token;\n const next = token ? (authStore.record?.id ?? \"\") : \"\";\n if (next === who) return realtime.resubmit();\n who = next;\n realtime.restart();\n });\n\n return {\n authStore,\n realtime,\n send,\n filter: (expr, params) =>\n expr.replace(/\\{:(\\w+)\\}/g, (match, name: string) => {\n if (!Object.hasOwn(params, name)) return match;\n const v = params[name];\n return typeof v === \"string\" ? JSON.stringify(v) : String(v);\n }),\n fileUrl: (collection, recordId, filename, query) =>\n `${base}/api/files/${[collection, recordId, filename].map(encodeURIComponent).join(\"/\")}${qs(query)}`,\n };\n}\n\n// ---- realtime ----\n\n/** Wait before reconnect attempt n (the last value repeats), as the SDK does. */\nconst RECONNECT_MS = [200, 300, 500, 1000, 1200, 1500, 2000];\nconst CONNECT_TIMEOUT_MS = 15_000;\n\ntype Listener = (e: Event) => void;\n\n/**\n * The SDK's realtime protocol: one EventSource; PB_CONNECT carries the client id; the set of subscriptions (each a\n * topic plus its serialized options) is POSTed to /api/realtime whenever it changes, and again after a reconnect.\n */\nfunction createRealtime(url: string, send: PbClient[\"send\"]): Realtime & { resubmit(): void; restart(): void } {\n let es: EventSource | null = null;\n let clientId = \"\";\n /** Subscription key \u2192 listeners. A key is the topic plus its options, and the event name the server uses. */\n const subs = new Map<string, Listener[]>();\n let lastSent: string[] = [];\n let attempts = 0;\n let lost = false;\n let connectTimer: ReturnType<typeof setTimeout> | undefined;\n let reconnectTimer: ReturnType<typeof setTimeout> | undefined;\n let pending: { resolve: () => void; reject: (e: unknown) => void }[] = [];\n /** The in-flight subscriptions POST, aborted on disconnect. */\n let submitting: AbortController | null = null;\n /** Submits run one after another, so an older subscription set never lands after a newer one. */\n let queue: Promise<unknown> = Promise.resolve();\n\n const keys = () => [...subs.keys()];\n const unsent = () => {\n const now = keys();\n return now.length !== lastSent.length || now.some((k) => !lastSent.includes(k));\n };\n /** The keys the current EventSource has a dispatcher for. */\n let bound = new Set<string>();\n /**\n * One dispatcher per key on the EventSource, which calls the key's listeners as `subs` holds them when the event\n * comes: a listener hears events exactly while it is in `subs`, whenever it was added (QA BUG-269 was a listener\n * added at a moment nothing bound it). PB_CONNECT's listeners are called by the connect itself, once subscribed.\n */\n const bind = (key: string) => {\n const source = es;\n if (!source || bound.has(key) || key === \"PB_CONNECT\") return;\n bound.add(key);\n source.addEventListener(key, (e) => {\n if (es === source) for (const fn of subs.get(key) ?? []) fn(e); // a replaced connection's late events: dropped\n });\n };\n\n async function sendSubs(): Promise<void> {\n if (!clientId) return;\n if (!subs.size) return disconnect();\n if (!unsent()) return;\n lastSent = keys();\n submitting = new AbortController();\n try {\n await send(\"/api/realtime\", { method: \"POST\", body: { clientId, subscriptions: lastSent }, signal: submitting.signal });\n } catch (e) {\n if (!(e instanceof PbError && e.isAbort)) throw e;\n }\n }\n\n function submit(): Promise<void> {\n const p = queue.then(sendSubs);\n queue = p.catch(() => {});\n return p;\n }\n\n function connect(): Promise<void> {\n if (attempts > 0) return Promise.resolve(); // a reconnect is scheduled; it sends every subscription\n return new Promise((resolve, reject) => {\n pending.push({ resolve, reject });\n if (pending.length === 1) queueMicrotask(initConnect);\n });\n }\n\n function initConnect() {\n disconnect(true);\n connectTimer = setTimeout(() => connectError(new Error(\"EventSource connect took too long.\")), CONNECT_TIMEOUT_MS);\n const source = new EventSource(url);\n es = source;\n bound = new Set();\n for (const key of subs.keys()) bind(key);\n // A connection closed meanwhile (a restart for another user, a reconnect) must leave the current one alone: its\n // late answers would otherwise settle or fail the new connection's pending subscribes.\n const current = () => es === source;\n source.onerror = () => current() && connectError(new Error(\"Failed to establish realtime connection.\"));\n source.addEventListener(\"PB_CONNECT\", (e) => {\n if (!current()) return;\n clientId = (e as MessageEvent).lastEventId;\n lastSent = [];\n submit()\n .then(async () => {\n for (let tries = 3; current() && unsent() && tries > 0; tries--) await submit();\n if (!current()) return;\n for (const p of pending) p.resolve();\n pending = [];\n attempts = 0;\n clearTimeout(reconnectTimer);\n clearTimeout(connectTimer);\n for (const fn of subs.get(\"PB_CONNECT\") ?? []) fn(e);\n lost = false;\n if (unsent()) await submit();\n })\n .catch((err) => {\n if (!current()) return;\n clientId = \"\";\n lastSent = [];\n connectError(err);\n });\n });\n }\n\n function connectError(err: unknown) {\n clearTimeout(connectTimer);\n clearTimeout(reconnectTimer);\n lost = true;\n if (!clientId && !attempts) {\n // The first connect failed: tell those waiting for it, then go on trying like after a lost connection. Nothing\n // else would try again, and the page would get no live updates at all.\n for (const p of pending) p.reject(err instanceof PbError ? err : new PbError(0));\n pending = [];\n if (!subs.size) return disconnect();\n }\n disconnect(true);\n reconnectTimer = setTimeout(initConnect, RECONNECT_MS[Math.min(attempts, RECONNECT_MS.length - 1)]);\n attempts++;\n }\n\n function disconnect(reconnecting = false) {\n clearTimeout(connectTimer);\n clearTimeout(reconnectTimer);\n submitting?.abort();\n submitting = null;\n es?.close();\n es = null;\n clientId = \"\";\n lastSent = [];\n if (!reconnecting) {\n attempts = 0;\n for (const p of pending) p.resolve();\n pending = [];\n }\n }\n\n return {\n get isConnected() {\n return !!es && !!clientId && !pending.length;\n },\n get recovered() {\n return lost;\n },\n async subscribe(topic, fn, query) {\n const key = query ? `${topic}?options=${encodeURIComponent(JSON.stringify({ query }))}` : topic;\n const listener: Listener = (e) => {\n let data: unknown;\n try {\n data = JSON.parse((e as MessageEvent).data);\n } catch {}\n fn(data || {});\n };\n const fns = subs.get(key) ?? [];\n subs.set(key, [...fns, listener]);\n bind(key);\n if (!es || !clientId || pending.length) await connect();\n else if (!fns.length) await submit();\n\n return async () => {\n const left = (subs.get(key) ?? []).filter((f) => f !== listener);\n if (left.length) subs.set(key, left);\n else subs.delete(key);\n await submit();\n };\n },\n async unsubscribe() {\n subs.clear();\n await submit();\n },\n /** Send the subscriptions again (with the current token), if connected. */\n resubmit() {\n if (!clientId || !subs.size) return;\n lastSent = [];\n // A failure that comes after this connection was replaced (a logout, another user) is the old one's: it must not\n // fail and close the new one, whose subscribes would reject and which would never reconnect (QA BUG-68).\n const source = es;\n submit().catch(() => es === source && connectError(new PbError(0)));\n },\n /** Close the connection and, with subscriptions left, open a new one that sends them all (with the current token). */\n restart() {\n if (!es && !pending.length) return; // not connected: the next subscribe() connects afresh\n disconnect();\n if (subs.size) connect().catch(() => {});\n },\n };\n}\n", "// Keyset pagination over a room's messages, ordered by (created, id) \u2014 DESIGN.md \u00A76, \u00A77.5.\n// Pure: which page to ask GET /api/chat/rooms/{room}/messages for (server/lists.go writes the filter).\n\nexport const PAGE_SIZE = 50;\n\nexport interface Cursor {\n created: string;\n id: string;\n}\n\nexport interface PageQuery {\n room: string;\n /** `latest` and `older` pages come back newest-first; `first` and `newer` oldest-first; `changed` oldest change first. */\n kind: \"latest\" | \"first\" | \"older\" | \"newer\" | \"changed\";\n /** The page's cursor: `created`, `id`; for `changed`, `since`, `from`, `to`. */\n args: Record<string, string>;\n /** Only messages that may have attachments (`withFiles`). */\n files?: true;\n /** Only messages with every word of it (search, \u00A729; with `latest` and `older`). The server folds and escapes them. */\n q?: string;\n}\n\n/** The newest page of a room (newest-first). */\nexport function latest(room: string): PageQuery {\n return { room, kind: \"latest\", args: {} };\n}\n\n/** The oldest page of a room, i.e. \"jump to beginning\" (oldest-first). */\nexport function first(room: string): PageQuery {\n return { room, kind: \"first\", args: {} };\n}\n\n/** The page just before `c`, the oldest loaded message (newest-first). */\nexport function older(room: string, c: Cursor): PageQuery {\n return { room, kind: \"older\", args: { created: c.created, id: c.id } };\n}\n\n/** The page just after `c`, the newest loaded message (oldest-first). */\nexport function newer(room: string, c: Cursor): PageQuery {\n return { room, kind: \"newer\", args: { created: c.created, id: c.id } };\n}\n\n/**\n * Messages from `from` to `to` (inclusive, by `created`) changed after `since` (an `updated` value): edits and\n * deletes a client may have missed while its realtime connection was down (\u00A77.5). Oldest change first.\n */\nexport function changedIn(room: string, since: string, from: Cursor, to: Cursor): PageQuery {\n return { room, kind: \"changed\", args: { since, from: from.created, to: to.created } };\n}\n\n/**\n * Only the messages of `q` that may have attachments (the image viewer pages through those, \u00A717.7): with files of their\n * own, or forwards, whose files are their original's (\u00A721.3). The server can't look at those: the original is\n * usually in a room the reader can't list.\n */\nexport const withFiles = (q: PageQuery): PageQuery => ({ ...q, files: true });\n", "// The only module that talks to PocketBase (\u00A76), with account-api.ts, its part only Settings loads (\u00A743), and invite-api.ts (\u00A744). Views depend on the `Api` interface, never on the client.\n\nimport type { AccountApi } from \"./account-api.ts\";\nimport type { InviteApi } from \"./invite-api.ts\";\nimport { type Cursor, PAGE_SIZE, type PageQuery } from \"./lib/cursor.ts\";\nimport {\n type Badge,\n type CollectionItem,\n type Collections,\n DEFAULT_SITE,\n type InboxEvent,\n type MediaPage,\n type Message,\n type Posting,\n type Room,\n type Site,\n type User,\n type Visibility,\n} from \"./lib/types.ts\";\nimport { type AuthRecord, type PbClient, PbError, type Query, type RequestOptions } from \"./pb.ts\";\nimport * as S from \"./strings/api.ts\";\n\nexport type AvatarSize = 48 | 96;\nexport type Unsubscribe = () => Promise<void>;\nexport type Action = \"create\" | \"update\" | \"delete\";\nexport type RealtimeHandler<T> = (action: Action, record: T) => void;\n\nexport interface HiddenRow {\n id: string;\n room: string;\n}\n\n/** A room_reads row (\u00A718.1): only which room it is about matters to the client. */\nexport type ReadRow = HiddenRow;\n\n/** Unread messages per room id (rooms without any are left out), as of `at` (server time, \u00A718.2). */\nexport interface UnreadCounts {\n at: string;\n rooms: Record<string, number>;\n /** The recent messages these counts account for (QA BUG-106); missing from servers before it. */\n ids?: string[];\n /** Inbox rows not seen yet, at most 100, and each room's unread mentions and replies (\u00A741); missing from servers before. */\n inbox?: number;\n mentions?: Record<string, number>;\n}\n\n/** What the unread counter needs to know about a message event in any room (\u00A718.3). */\nexport type MessageActivity = Pick<Message, \"id\" | \"room\" | \"author\" | \"deleted\" | \"reply_to\" | \"mentions\">;\n\nexport interface NewMessage {\n /** Client-generated (lib/id.ts) so retries can't duplicate (\u00A77.5). */\n id: string;\n room: string;\n text: string;\n /** Attachments (\u00A717.4): sent as multipart. */\n files?: File[];\n /** The message this one replies to (\u00A719). */\n replyTo?: string;\n /** Collection items whose files it attaches, after `files` (\u00A731). */\n items?: string[];\n}\n\n/** A request to the server (`Api.request`). */\nexport interface Request {\n method?: string;\n body?: Record<string, unknown>;\n query?: Query;\n signal?: AbortSignal;\n /** With files in `body`: how much has been sent, 0 to 1. */\n onUpload?: (fraction: number) => void;\n}\n\n/**\n * Reads take an optional AbortSignal: views pass their scope's, so leaving a view cancels its pending requests\n * (they then reject with status 0). Writes take none on purpose: a send or edit should still reach the server\n * if the user navigates away while it is in flight.\n */\nexport interface Api {\n // auth\n currentUser(): User | null;\n /** `inviteCode`: needed while the site is invite-only (\u00A724). */\n signUp(input: { email: string; password: string; name: string; inviteCode?: string }): Promise<User>;\n logIn(email: string, password: string): Promise<User>;\n /** Email a link to set a new password (\u00A739). Resolves the same whether or not the address has an account. */\n requestPasswordReset(email: string): Promise<void>;\n /** Set a new password with the token from that link (one use). Every session of the account is signed out. */\n confirmPasswordReset(token: string, password: string): Promise<void>;\n /** Re-validate the stored session with the server, which renews it. Rejects when it is no longer valid. */\n refreshAuth(): Promise<User>;\n /** When the stored session expires (epoch ms), or 0 without one. */\n sessionExpiry(): number;\n logOut(): void;\n /**\n * A stored session that ran out (the browser was closed past its expiry): forgotten, and the id of the user it was,\n * or \"\" when there is none. Their drafts and cached rooms are then cleared (QA BUG-145).\n */\n forgetExpired(): string;\n /**\n * Called whenever the stored session changes, including from another tab of the same browser (they share\n * it). Read `currentUser()` to see who is logged in now. Returns an unsubscribe function.\n */\n onAuthChange(fn: () => void): () => void;\n /**\n * Called when the server refuses a change sent with the session (400, 401, 403 or 404). Often a plain mistake, but\n * also what a session revoked elsewhere gets (a password change signs out every other device), which only checking\n * the session can tell. Returns an unsubscribe function.\n */\n onRejected(fn: () => void): () => void;\n\n /** The site's branding and signup policy (\u00A724); the defaults when there is no site record. */\n site(signal?: AbortSignal): Promise<Site>;\n\n // profile (\u00A715)\n /** Upload a new avatar (already prepared, \u00A715.3). Resolves to the updated user. */\n setAvatar(file: File): Promise<User>;\n removeAvatar(): Promise<User>;\n rename(name: string): Promise<User>;\n /** Change your handle (\u00A741); refused with the reason on `handle` (taken, not allowed). */\n setHandle(handle: string): Promise<User>;\n /**\n * Change your password (\u00A722.2). The server checks the current one and signs out every other session; this one gets\n * a fresh token. Rejects with field errors on `oldPassword` or `password`.\n */\n changePassword(oldPassword: string, password: string): Promise<User>;\n /** Your data and deleting your account (\u00A743): loaded with Settings (account-api.ts), not with the app. */\n account(): Promise<AccountApi>;\n /** Room invite links (\u00A744): loaded with the access dialog and the invite page (invite-api.ts), not with the app. */\n invites(): Promise<InviteApi>;\n /** Thumbnail URL of a user's avatar at `size` px (48 or 96), or \"\" when they have none. */\n avatarUrl(user: User, size: AvatarSize): string;\n\n // rooms\n listRooms(signal?: AbortSignal): Promise<Room[]>;\n getRoom(id: string, signal?: AbortSignal): Promise<Room>;\n createRoom(name: string, visibility?: Visibility): Promise<Room>;\n setArchived(id: string, archived: boolean): Promise<Room>;\n /**\n * Who can see the room (\u00A723.2): its visibility, and for a private room its members (user ids; the creator is always\n * one). With `posting`, also who can post (\u00A723.6): for \"selected\", its writers (the creator always is one; in a\n * private room only members count). Only the creator may. Resolves to the room as saved.\n */\n setAccess(id: string, visibility: Visibility, members: readonly string[], posting?: Posting, writers?: readonly string[]): Promise<Room>;\n\n // direct messages (\u00A716)\n /** The DM with `userId`, created on first use; reopens it if you had closed it. */\n openDm(userId: string): Promise<Room>;\n /** Up to 20 other users whose name contains `query` (ignoring case, as names are compared), by name. */\n searchUsers(query: string, signal?: AbortSignal): Promise<User[]>;\n /**\n * Someone on a linked instance by their address, \"ann@b.example\" (\u00A733.5), as a user here: to message them, or with\n * `room` to add them to that shared private room. Refused with the reason (no such person, not linked\u2026).\n */\n remoteUser(address: string, room?: string): Promise<User>;\n /** The users with these ids (at most 50), e.g. to name who reacted (\u00A720.3). Unknown ids are left out. */\n usersById(ids: readonly string[], signal?: AbortSignal): Promise<User[]>;\n\n // hidden rooms\n listHidden(signal?: AbortSignal): Promise<HiddenRow[]>;\n hideRoom(room: string): Promise<HiddenRow>;\n unhideRoom(rowId: string): Promise<void>;\n\n // unread counts (\u00A718)\n /** Unread messages per room, at most 100 each. */\n unreadCounts(signal?: AbortSignal): Promise<UnreadCounts>;\n /** The oldest unread message in a room; its id is \"\" when there is none. */\n firstUnread(room: string, signal?: AbortSignal): Promise<Cursor>;\n /** You have read `room` up to `at` (a message's `created`). The server never moves it back. */\n markRead(room: string, at: string): Promise<void>;\n\n // messages\n /**\n * With `kept`, asked for with the ETag of a copy kept (PERF.md \u00A75): when that copy is still the page, the server sends\n * no body, and the page is `kept.items`. Either way the page's tag goes to `kept.got`.\n */\n page(q: PageQuery, signal?: AbortSignal, kept?: KeptPage): Promise<Message[]>;\n getMessage(id: string, signal?: AbortSignal): Promise<Message>;\n /** Every message matching `q` (not just one page): used for the edits/deletes missed during a disconnect. */\n changes(q: PageQuery, signal?: AbortSignal): Promise<Message[]>;\n /** `onUpload`: how much of its attachments has been sent, 0 to 1 (\u00A717.4). */\n send(m: NewMessage, onUpload?: (fraction: number) => void): Promise<Message>;\n edit(id: string, text: string): Promise<Message>;\n softDelete(id: string): Promise<Message>;\n /** Add (`on`) or remove your `emoji` reaction on a message (\u00A720). Idempotent. */\n react(id: string, emoji: string, on: boolean): Promise<Message>;\n /** Soft-delete several of your messages at once, all or none (\u00A721.2), or a moderator anyone's (\u00A736). Resolves to them, deleted. */\n deleteMany(ids: readonly string[]): Promise<Message[]>;\n /** Is this user banned (\u00A736)? */\n isBanned(user: string, signal?: AbortSignal): Promise<boolean>;\n /** A moderator bans or unbans someone (\u00A736). */\n setBanned(user: string, banned: boolean): Promise<void>;\n /** Copy messages into `room` as yours, saying who first wrote them, all or none (\u00A721.3). Resolves to the copies. */\n forward(ids: readonly string[], room: string): Promise<Message[]>;\n\n // attachments (\u00A717.3, \u00A737.3): a file's URL is all it takes to open it, no file token\n /** URL of an attachment (a thumbnail with `thumb`, e.g. \"480x360\"). */\n fileUrl(m: Message, filename: string, thumb?: string): string;\n /** URL of a video's poster frame (\u00A730.1): 404 until the server has made it. */\n posterUrl(m: Message, filename: string): string;\n\n // media grid (\u00A730.1)\n /** A page of the room's images and videos, newest first, older than `after` (the oldest shown) or the newest. */\n media(room: string, after?: { sent: string; message: string; pos: number }, signal?: AbortSignal): Promise<MediaPage>;\n\n // collections (\u00A731): the rest of their calls are the lazy chunk's (views/collection/calls.ts), through `request`\n collections(signal?: AbortSignal): Promise<Collections>;\n /** You have seen the collection's items up to `at` (an item's `created`; default now). */\n markSeen(collection: string, at?: string): Promise<void>;\n /** What each collection's badge may say. */\n badges(ids: readonly string[], signal?: AbortSignal): Promise<Record<string, Badge>>;\n /** URL of an item's file (a thumbnail with `thumb`), as fileUrl. */\n itemUrl(item: Pick<CollectionItem, \"id\" | \"file\">, thumb?: string): string;\n /** URL of an item's video poster: 404 until there is one. */\n itemPosterUrl(item: Pick<CollectionItem, \"id\" | \"file\">): string;\n /** Changes of these collections (yours, and those you follow), and of your own subscriptions. */\n subscribeCollections(ids: readonly string[], fn: () => void): Promise<Unsubscribe>;\n /** The id of any collection whose badge may say something else now: made public or private, renamed, deleted. */\n subscribeBadges(fn: (id: string) => void): Promise<Unsubscribe>;\n /** Any request to the server, for a lazy chunk (which can't import this module); rejects with ApiError. */\n request<T>(path: string, r?: Request): Promise<T>;\n\n // realtime\n subscribeMessages(room: string, fn: RealtimeHandler<Message>): Promise<Unsubscribe>;\n subscribeRooms(fn: RealtimeHandler<Room>): Promise<Unsubscribe>;\n subscribeHidden(fn: RealtimeHandler<HiddenRow>): Promise<Unsubscribe>;\n /** Every message event in every room you can see, without text or files (\u00A718.3, \u00A734). */\n subscribeAllMessages(fn: RealtimeHandler<MessageActivity>): Promise<Unsubscribe>;\n /** Your inbox's rows as they are added and taken away (\u00A741). */\n subscribeInbox(fn: (e: InboxEvent) => void): Promise<Unsubscribe>;\n /** Your own room_reads rows, e.g. written by another tab or device. */\n subscribeReads(fn: RealtimeHandler<ReadRow>): Promise<Unsubscribe>;\n /** Called on every realtime (re)connect; `reconnect` is false for the first one. */\n onConnect(fn: (reconnect: boolean) => void): () => void;\n unsubscribeAll(): Promise<void>;\n}\n\n/** Normalized error so views never depend on SDK error classes. */\nexport class ApiError extends Error {\n readonly status: number;\n /** Per-field validation messages, e.g. { email: \"Must be a valid email.\" } */\n readonly fields: Record<string, string>;\n /** Per-field validation codes, e.g. { name: \"validation_not_unique\" }. Match on these, not on messages. */\n readonly codes: Record<string, string>;\n\n constructor(message: string, status: number, fields: Record<string, string> = {}, codes: Record<string, string> = {}) {\n super(message);\n this.name = \"ApiError\";\n this.status = status;\n this.fields = fields;\n this.codes = codes;\n }\n}\n\n/**\n * `codes.auth` of a signUp() rejection whose account *was* created but whose automatic login failed\n * (network, rate limit). Retrying the signup would only fail with \"email taken\"; the user should log in.\n */\nexport const SIGNUP_LOGIN_FAILED = \"signup_login_failed\";\n\n/** A sentence to show for a failed request: network trouble, rate limiting, or the server's own message. */\nexport function errorMessage(err: unknown): string {\n if (!(err instanceof ApiError)) return \"Something went wrong. Please try again.\";\n if (err.status === 0) return \"Can't reach the server. Check your connection.\";\n // e.g. PocketBase's default `*:auth` limit (2 requests per 3 seconds) or our messages/signup limits\n if (err.status === 429) return \"Too many attempts. Wait a few seconds and try again.\";\n return err.message;\n}\n\n/** errorMessage, or the server's reason when it gave one (e.g. \"A message was deleted.\" for a forward, \u00A721). */\nexport const reasonOf = (err: unknown): string => (err instanceof ApiError && Object.values(err.fields)[0]) || errorMessage(err);\n\n// ---- PocketBase implementation ----\n\n/** Only what the UI renders; never user emails (\u00A76). */\nexport const MSG_FIELDS =\n \"id,room,text,created,updated,edited_at,deleted,files,file_names,file_sources,file_dims,reactions,previews,author,expand.author.id,expand.author.name,expand.author.avatar,expand.author.no_dms,expand.author.instance,\" +\n \"reply_to,expand.reply_to.id,expand.reply_to.author,expand.reply_to.text,expand.reply_to.deleted,expand.reply_to.files,\" +\n \"expand.reply_to.expand.author.id,expand.reply_to.expand.author.name,\" +\n \"forwarded_from,forward_of,expand.forwarded_from.id,expand.forwarded_from.name,mentions\";\nconst MSG_OPTS = { expand: \"author,reply_to.author,forwarded_from\", fields: MSG_FIELDS } as const;\n/**\n * Live messages (server/live.go, docs/PERF.md \u00A77): the server sends each message once on this topic to everyone who\n * can see its room, expanded with `author` and `forwarded_from` but not the message a reply answers (the room fills the\n * quote in, views/room/controller.ts). A room's subscription and the activity of all rooms both listen to it.\n */\nconst LIVE_TOPIC = \"chat/messages\";\n/** Rooms with their members' public profile (DMs, \u00A716.5); never emails. */\nexport const ROOM_FIELDS =\n \"id,name,archived,created_by,kind,visibility,members,posting,writers,last_message_at,created,shared,\" +\n \"expand.members.id,expand.members.name,expand.members.avatar,expand.members.no_dms,expand.members.instance,\" +\n \"expand.writers.id,expand.writers.name,expand.writers.avatar,expand.writers.no_dms,expand.writers.instance\";\nconst ROOM_OPTS = { expand: \"members,writers\", fields: ROOM_FIELDS } as const;\nexport const HIDDEN_FIELDS = \"id,room\";\n/** The site record (\u00A724); its invite code is hidden from everyone but superusers. */\nconst SITE_FIELDS = \"id,title,logo,invite_only,password_reset\";\ninterface SiteRow {\n id: string;\n title?: string;\n logo?: string;\n invite_only?: boolean;\n /** Not a field: from the server's mail settings (\u00A739). */\n password_reset?: boolean;\n}\n/** reply_to: notifications (\u00A734) look closer at replies only. */\nexport const ACTIVITY_FIELDS = \"id,room,author,deleted,reply_to,mentions\";\n\nfunction toApiError(e: unknown): ApiError {\n if (e instanceof ApiError) return e;\n if (e instanceof PbError) {\n const data = e.response.data ?? {};\n const pick = (key: \"message\" | \"code\") =>\n Object.fromEntries(\n Object.entries(data)\n .filter(([, v]) => v && typeof v[key] === \"string\")\n .map(([k, v]) => [k, v[key] as string]),\n );\n return new ApiError(e.message, e.status, pick(\"message\"), pick(\"code\"));\n }\n return new ApiError(e instanceof Error ? e.message : String(e), 0);\n}\n\nasync function wrap<T>(p: Promise<T>): Promise<T> {\n try {\n return await p;\n } catch (e) {\n throw toApiError(e);\n }\n}\n\nconst toUser = (r: AuthRecord): User => ({\n id: r.id,\n name: r.name as string,\n avatar: (r.avatar as string | undefined) ?? \"\",\n ...(r.no_dms ? { no_dms: true } : {}),\n ...(r.instance ? { instance: r.instance as string } : {}),\n ...(r.moderator ? { moderator: true } : {}),\n ...(r.handle ? { handle: r.handle as string } : {}),\n});\n/** What the profile calls return: never the email, even for yourself. */\nexport const USER_FIELDS = \"id,name,avatar,instance,handle\";\n\n/** The query for GET /api/chat/rooms/{room}/messages (server/lists.go). */\nexport function pageOptions(q: PageQuery, limit = PAGE_SIZE, page = 1) {\n return {\n kind: q.kind,\n ...q.args,\n ...(q.files ? { files: \"1\" } : {}),\n ...(q.q ? { q: q.q } : {}),\n limit,\n ...(page > 1 ? { page } : {}),\n ...MSG_OPTS,\n };\n}\n\n/** Record endpoints of one collection: the part of the SDK's RecordService we use. */\nfunction records(pb: PbClient, collection: string) {\n const path = `/api/collections/${collection}`;\n const one = (id: string) => `${path}/records/${encodeURIComponent(id)}`;\n const list = <T>(page: number, perPage: number, query: Query, signal?: AbortSignal) =>\n pb.send<{ items: T[] }>(`${path}/records`, { query: { page, perPage, ...query }, signal });\n /** Save a fresh auth response, as the SDK does. */\n const auth = async (p: Promise<{ token: string; record: AuthRecord }>) => {\n const { token, record } = await p;\n pb.authStore.save(token, record);\n return record;\n };\n return {\n list,\n /** Every page, `batch` records at a time. */\n async fullList<T>(query: Query, signal?: AbortSignal, batch = 1000): Promise<T[]> {\n const out: T[] = [];\n for (let page = 1; ; page++) {\n const { items } = await list<T>(page, batch, { skipTotal: true, ...query }, signal);\n out.push(...items);\n if (items.length < batch) return out;\n }\n },\n get: <T>(id: string, query: Query, signal?: AbortSignal) => pb.send<T>(one(id), { query, signal }),\n create: <T>(body: Record<string, unknown>, query?: Query, onUpload?: (fraction: number) => void) =>\n pb.send<T>(`${path}/records`, { method: \"POST\", body, query, onUpload }),\n async update<T>(id: string, body: Record<string, unknown>, query: Query): Promise<T> {\n const item = await pb.send<AuthRecord>(one(id), { method: \"PATCH\", body, query });\n // Updating the logged-in user refreshes the stored record (other tabs and onAuthChange see it).\n const r = pb.authStore.record;\n if (r?.id === item.id && r.collectionName === collection) pb.authStore.save(pb.authStore.token, { ...r, ...item });\n return item as T;\n },\n delete: (id: string) => pb.send(one(id), { method: \"DELETE\" }),\n authWithPassword: (identity: string, password: string) =>\n auth(pb.send(`${path}/auth-with-password`, { method: \"POST\", body: { identity, password } })),\n // Saved only over the session it renewed: one ended (a logout) or changed meanwhile stays so.\n authRefresh: async () => {\n const sent = pb.authStore.token;\n const { token, record } = await pb.send<{ token: string; record: AuthRecord }>(`${path}/auth-refresh`, { method: \"POST\" });\n if (pb.authStore.token === sent) pb.authStore.save(token, record);\n return record;\n },\n /** POST to one of the collection's own auth actions (`request-password-reset`, \u2026) that answer 204. */\n action: (name: string, body: Record<string, unknown>) => pb.send(`${path}/${name}`, { method: \"POST\", body }),\n /** A custom route that answers like a login. */\n authAt: (url: string, body: Record<string, unknown>) => auth(pb.send(url, { method: \"POST\", body })),\n };\n}\n\n/** Statuses of a refused change: invalid data, or no (valid) session. */\nconst REFUSED = new Set([400, 401, 403, 404]);\n\n/** A page's copy kept by the caller, and where its tag goes (Api.page). `items` as the page has them, newest first. */\nexport interface KeptPage {\n tag?: string | undefined;\n items: readonly Message[];\n got?: (tag: string) => void;\n}\n\nexport function createApi(client: PbClient): Api {\n const rejected = new Set<() => void>();\n /** The client, telling onRejected listeners about changes refused while the session was sent with them. */\n const pb: PbClient = {\n authStore: client.authStore,\n realtime: client.realtime,\n filter: client.filter,\n fileUrl: client.fileUrl,\n async send<T>(path: string, opts: RequestOptions = {}): Promise<T> {\n const token = client.authStore.token;\n try {\n return await client.send<T>(path, opts);\n } catch (e) {\n const write = (opts.method ?? \"GET\") !== \"GET\" && !path.includes(\"/auth-\"); // a login or refresh says so itself\n if (e instanceof PbError && REFUSED.has(e.status) && write && token && token === client.authStore.token) {\n for (const fn of [...rejected]) fn();\n }\n throw e;\n }\n },\n };\n const users = records(pb, \"users\");\n const rooms = records(pb, \"rooms\");\n const hidden = records(pb, \"hidden_rooms\");\n const messages = records(pb, \"messages\");\n const site = records(pb, \"site\");\n /** Every record event of a collection, narrowed to our Action type. */\n const subscribe = <T>(collection: string, fn: RealtimeHandler<T>, query: Query) =>\n wrap(\n pb.realtime.subscribe(\n `${collection}/*`,\n (e) => {\n const { action, record } = e as { action: Action; record: T };\n fn(action, record);\n },\n query,\n ),\n );\n const live = (fn: (action: Action, m: Message) => void) =>\n wrap(\n pb.realtime.subscribe(LIVE_TOPIC, (e) => {\n const { action, record } = e as { action: Action; record: Message };\n fn(action, record);\n }),\n );\n const me = () => {\n const u = api.currentUser();\n if (!u) throw new ApiError(\"Not logged in.\", 401);\n return u.id;\n };\n\n const api: Api = {\n currentUser() {\n const r = pb.authStore.record;\n return pb.authStore.isValid && r?.collectionName === \"users\" ? toUser(r) : null;\n },\n async signUp({ email, password, name, inviteCode }) {\n const invite = inviteCode ? { invite_code: inviteCode } : {};\n await wrap(users.create({ email, password, passwordConfirm: password, name, ...invite }));\n try {\n return await api.logIn(email, password);\n } catch (e) {\n const err = toApiError(e);\n throw new ApiError(err.message, err.status, {}, { auth: SIGNUP_LOGIN_FAILED });\n }\n },\n async logIn(email, password) {\n return toUser(await wrap(users.authWithPassword(email, password)));\n },\n async requestPasswordReset(email) {\n // In lower case, as emails are stored (QA BUG-47): PocketBase looks the address up as it is sent.\n await wrap(users.action(\"request-password-reset\", { email: email.trim().toLowerCase() }));\n },\n async confirmPasswordReset(token, password) {\n await wrap(users.action(\"confirm-password-reset\", { token, password, passwordConfirm: password }));\n },\n async refreshAuth() {\n if (!api.currentUser()) throw new ApiError(\"Not logged in.\", 401);\n return toUser(await wrap(users.authRefresh()));\n },\n sessionExpiry: () => pb.authStore.expiresAt,\n logOut() {\n pb.authStore.clear();\n },\n forgetExpired() {\n const r = pb.authStore.record;\n if (!r || pb.authStore.isValid) return \"\";\n pb.authStore.clear();\n return r.id;\n },\n onAuthChange(fn) {\n // A localStorage-backed store also fires this when another tab saves or clears the shared session.\n return pb.authStore.onChange(() => fn());\n },\n onRejected(fn) {\n rejected.add(fn);\n return () => void rejected.delete(fn);\n },\n\n // A body holding a File is sent as multipart; update() refreshes the stored auth record from the response.\n async site(signal) {\n const { items } = await wrap(site.list<SiteRow>(1, 1, { sort: \"created\", skipTotal: true, fields: SITE_FIELDS }, signal));\n const row = items[0];\n if (!row) return DEFAULT_SITE;\n return {\n title: row.title || DEFAULT_SITE.title,\n logo: row.logo ? pb.fileUrl(\"site\", row.id, row.logo) : \"\",\n inviteOnly: row.invite_only === true,\n passwordReset: row.password_reset === true,\n };\n },\n\n setAvatar: async (file) => toUser(await wrap(users.update(me(), { avatar: file }, { fields: USER_FIELDS }))),\n removeAvatar: async () => toUser(await wrap(users.update(me(), { avatar: null }, { fields: USER_FIELDS }))),\n rename: async (name) => toUser(await wrap(users.update(me(), { name }, { fields: USER_FIELDS }))),\n setHandle: async (handle) => toUser(await wrap(users.update(me(), { handle }, { fields: USER_FIELDS }))),\n async changePassword(oldPassword, password) {\n me();\n return toUser(await wrap(users.authAt(\"/api/chat/password\", { oldPassword, password })));\n },\n account: () => import(\"./account-api.ts\").then((m) => m.createAccountApi(pb, wrap)),\n invites: () => import(\"./invite-api.ts\").then((m) => m.createInviteApi(pb, wrap)),\n avatarUrl(user, size) {\n if (!user.avatar) return \"\";\n return pb.fileUrl(\"users\", user.id, user.avatar, { thumb: `${size}x${size}` });\n },\n\n listRooms: (signal) => wrap(pb.send<Room[]>(\"/api/chat/rooms\", { query: ROOM_OPTS, signal })),\n getRoom: (id, signal) => wrap(rooms.get<Room>(id, ROOM_OPTS, signal)),\n createRoom: async (name, visibility) =>\n wrap(rooms.create<Room>({ name, created_by: me(), ...(visibility ? { visibility } : {}) }, ROOM_OPTS)),\n setArchived: (id, archived) => wrap(rooms.update<Room>(id, { archived }, ROOM_OPTS)),\n setAccess: (id, visibility, members, posting, writers = []) =>\n wrap(\n rooms.update<Room>(\n id,\n {\n visibility,\n members: visibility === \"private\" ? [...members] : [],\n ...(posting ? { posting, writers: posting === \"selected\" ? [...writers] : [] } : {}),\n },\n ROOM_OPTS,\n ),\n ),\n\n openDm: (userId) => wrap(pb.send<Room>(\"/api/chat/dms\", { method: \"POST\", body: { user: userId } })),\n async searchUsers(query, signal) {\n me();\n // A route, not a filter on `name`: it matches case-insensitively beyond ASCII (\"\u0438\u0432\u0430\u043D\" finds \"\u0418\u0432\u0430\u043D\", QA BUG-55).\n return (await wrap(pb.send<AuthRecord[]>(\"/api/chat/users\", { query: { q: query }, signal }))).map(toUser);\n },\n\n remoteUser: async (address, room) =>\n toUser(await wrap(pb.send<AuthRecord>(\"/api/chat/remote-users\", { method: \"POST\", body: { address, ...(room ? { room } : {}) } }))),\n\n async usersById(ids, signal) {\n const some = ids.slice(0, 50);\n if (!some.length) return [];\n const params = Object.fromEntries(some.map((id, i) => [`u${i}`, id]));\n const opts = { filter: pb.filter(some.map((_, i) => `id = {:u${i}}`).join(\" || \"), params), fields: USER_FIELDS, skipTotal: true };\n return (await wrap(users.list<AuthRecord>(1, some.length, opts, signal))).items.map(toUser);\n },\n\n listHidden: (signal) => wrap(hidden.fullList<HiddenRow>({ fields: HIDDEN_FIELDS }, signal)),\n hideRoom: async (room) => wrap(hidden.create<HiddenRow>({ user: me(), room }, { fields: HIDDEN_FIELDS })),\n unhideRoom: async (rowId) => {\n await wrap(hidden.delete(rowId));\n },\n\n unreadCounts: (signal) => wrap(pb.send<UnreadCounts>(\"/api/chat/unread\", { signal })),\n firstUnread: (room, signal) => wrap(pb.send<Cursor>(`/api/chat/unread/${room}`, { signal })),\n markRead: async (room, at) => {\n await wrap(pb.send(\"/api/chat/reads\", { method: \"POST\", body: { room, at } }));\n },\n\n page: async (q, signal, kept) => {\n const path = `/api/chat/rooms/${encodeURIComponent(q.room)}/messages`;\n const tag = kept && { sent: kept.items.length ? kept.tag : undefined, got: kept.got };\n return (await wrap(pb.send<Message[] | undefined>(path, { query: pageOptions(q), signal, tag }))) ?? [...(kept?.items ?? [])];\n },\n getMessage: (id, signal) => wrap(messages.get<Message>(id, MSG_OPTS, signal)),\n async changes(q, signal) {\n const out: Message[] = [];\n for (let page = 1; ; page++) {\n const path = `/api/chat/rooms/${encodeURIComponent(q.room)}/messages`;\n const some = await wrap(pb.send<Message[]>(path, { query: pageOptions(q, 200, page), signal }));\n out.push(...some);\n if (some.length < 200) return out;\n }\n },\n send: async (m, onUpload) =>\n wrap(\n messages.create<Message>(\n {\n id: m.id,\n room: m.room,\n author: me(),\n text: m.text,\n ...(m.files?.length ? { files: m.files } : {}),\n ...(m.replyTo ? { reply_to: m.replyTo } : {}),\n ...(m.items?.length ? { items: m.items } : {}),\n },\n MSG_OPTS,\n m.files?.length ? onUpload : undefined,\n ),\n ),\n edit: (id, text) => wrap(messages.update<Message>(id, { text }, MSG_OPTS)),\n softDelete: (id) => wrap(messages.update<Message>(id, { deleted: true }, MSG_OPTS)),\n react: (id, emoji, on) =>\n wrap(pb.send<Message>(\"/api/chat/reactions\", { method: \"POST\", body: { message: id, emoji, on }, query: MSG_OPTS })),\n\n deleteMany: (ids) => wrap(pb.send<Message[]>(\"/api/chat/delete\", { method: \"POST\", body: { messages: ids }, query: MSG_OPTS })),\n isBanned: async (user, signal) => !!(await wrap(users.get<AuthRecord>(user, { fields: \"id,banned\" }, signal))).banned,\n setBanned: async (user, banned) => void (await wrap(pb.send(\"/api/chat/ban\", { method: \"POST\", body: { user, banned } }))),\n forward: (ids, room) =>\n wrap(pb.send<Message[]>(\"/api/chat/forward\", { method: \"POST\", body: { messages: ids, room }, query: MSG_OPTS })),\n // A forward's attachments are its original's (\u00A721.3).\n fileUrl: (m, filename, thumb) => pb.fileUrl(\"messages\", m.forward_of || m.id, filename, { thumb }),\n // The file's own URL, on the poster route.\n posterUrl: (m, filename) => api.fileUrl(m, filename).replace(\"/api/files/messages/\", \"/api/chat/posters/\"),\n collections: (signal) => wrap(pb.send<Collections>(\"/api/chat/collections\", { signal })),\n markSeen: async (collection, at) => {\n await wrap(pb.send(\"/api/chat/subs/seen\", { method: \"POST\", body: { collection, ...(at ? { at } : {}) } }));\n },\n badges: (ids, signal) => wrap(pb.send<Record<string, Badge>>(\"/api/chat/badges\", { query: { ids: ids.join(\",\") }, signal })),\n itemUrl: (item, thumb) => pb.fileUrl(\"collection_items\", item.id, item.file, { thumb }),\n itemPosterUrl: (item) => api.itemUrl(item).replace(\"/api/files/collection_items/\", \"/api/chat/posters/items/\"),\n async subscribeCollections(ids, fn) {\n // One topic per collection followed: a filter naming them all could be longer than a topic may be.\n const offs = await Promise.all([\n subscribe(\"collections\", fn, { fields: \"id\", filter: pb.filter(\"owner = {:me}\", { me: me() }) }),\n subscribe(\"collection_subs\", fn, { fields: \"id\" }),\n ...ids.map((id) => wrap(pb.realtime.subscribe(`collections/${id}`, fn, { fields: \"id\" }))),\n ]);\n return async () => {\n await Promise.all(offs.map((off) => off()));\n };\n },\n subscribeBadges: (fn) => wrap(pb.realtime.subscribe(\"chat/badges\", (d) => fn((d as { id: string }).id))),\n request: (path, r) => wrap(pb.send(path, r)),\n media: (room, after, signal) => wrap(pb.send<MediaPage>(`/api/chat/media/${room}`, { query: after, signal })),\n\n subscribeMessages: (room, fn) => live((action, m) => m.room === room && fn(action, m)),\n subscribeRooms: (fn) => subscribe(\"rooms\", fn, ROOM_OPTS),\n subscribeHidden: (fn) => subscribe(\"hidden_rooms\", fn, { fields: HIDDEN_FIELDS }),\n subscribeAllMessages: (fn) =>\n live((action, m) =>\n fn(action, {\n id: m.id,\n room: m.room,\n author: m.author,\n deleted: m.deleted,\n reply_to: m.reply_to ?? \"\",\n mentions: m.mentions ?? [],\n }),\n ),\n subscribeInbox: (fn) => wrap(pb.realtime.subscribe(\"chat/inbox\", (d) => fn(d as InboxEvent))),\n subscribeReads: (fn) => subscribe(\"room_reads\", fn, { fields: HIDDEN_FIELDS }),\n\n onConnect(fn) {\n // PB_CONNECT only reaches listeners for connections made after they subscribe. If we are already\n // connected now, the next PB_CONNECT this listener sees is a reconnect, not the initial connect. So is one that\n // follows a failed first connect: what was loaded meanwhile may have missed events.\n let connected = pb.realtime.isConnected;\n const unsub = pb.realtime.subscribe(\"PB_CONNECT\", () => {\n fn(connected || pb.realtime.recovered);\n connected = true;\n });\n // A failed first connect (offline, server down) rejects it, and the client keeps trying: not an error (QA BUG-85).\n unsub.catch(() => {});\n return () => void unsub.then((off) => off()).catch(() => {});\n },\n unsubscribeAll: () => wrap(pb.realtime.unsubscribe()),\n };\n return api;\n}\n", "import * as S from \"../strings/lib-time.ts\";\n// Time parsing and display (\u00A77.5, \u00A77.6.1). Intl formatters are created once per locale and reused.\n\n/** \"2026-10-10 12:34:56.789Z\" \u2192 epoch ms (NaN for \"\"). */\nexport function parsePb(s: string): number {\n return s ? Date.parse(s.replace(\" \", \"T\")) : NaN;\n}\n\n/** epoch ms \u2192 PocketBase datetime string. Fixed width, so string order is time order. */\nexport function toPb(ms: number): string {\n return new Date(ms).toISOString().replace(\"T\", \" \");\n}\n\nexport function sameDay(a: number, b: number): boolean {\n const x = new Date(a);\n const y = new Date(b);\n return x.getFullYear() === y.getFullYear() && x.getMonth() === y.getMonth() && x.getDate() === y.getDate();\n}\n\nconst sameYear = (a: number, b: number) => new Date(a).getFullYear() === new Date(b).getFullYear();\n\nconst STYLES = {\n time: { hour: \"numeric\", minute: \"2-digit\" },\n dateTime: { month: \"short\", day: \"numeric\", hour: \"numeric\", minute: \"2-digit\" },\n dateTimeYear: { year: \"numeric\", month: \"short\", day: \"numeric\", hour: \"numeric\", minute: \"2-digit\" },\n day: { weekday: \"long\", month: \"long\", day: \"numeric\" },\n dayYear: { weekday: \"long\", year: \"numeric\", month: \"long\", day: \"numeric\" },\n full: { year: \"numeric\", month: \"short\", day: \"numeric\", hour: \"numeric\", minute: \"2-digit\", second: \"2-digit\" },\n} satisfies Record<string, Intl.DateTimeFormatOptions>;\n\nconst cache = new Map<string, Intl.DateTimeFormat>();\n\nfunction fmt(style: keyof typeof STYLES, locale: string | undefined, ms: number): string {\n const key = `${locale ?? \"\"}|${style}`;\n let f = cache.get(key);\n if (!f) {\n f = new Intl.DateTimeFormat(locale, STYLES[style]);\n cache.set(key, f);\n }\n return f.format(ms);\n}\n\n/** Message timestamp: time only for today, date + time otherwise (year only when it differs). */\nexport function formatTime(ms: number, now = Date.now(), locale?: string): string {\n if (sameDay(ms, now)) return fmt(\"time\", locale, ms);\n return fmt(sameYear(ms, now) ? \"dateTime\" : \"dateTimeYear\", locale, ms);\n}\n\n/** Date divider label: \"Today\", \"Yesterday\", or a weekday + date. */\nexport function dayLabel(ms: number, now = Date.now(), locale?: string): string {\n if (sameDay(ms, now)) return \"Today\";\n const yesterday = new Date(now);\n yesterday.setDate(yesterday.getDate() - 1);\n if (sameDay(ms, yesterday.getTime())) return \"Yesterday\";\n return fmt(sameYear(ms, now) ? \"day\" : \"dayYear\", locale, ms);\n}\n\n/** Full timestamp for tooltips (e.g. the \"(edited)\" marker). */\nexport function formatFull(ms: number, locale?: string): string {\n return fmt(\"full\", locale, ms);\n}\n"],
|
|
5
|
+
"mappings": "AAiPO,IAAMA,EAAqB,CAAE,MAAO,UAAW,KAAM,GAAI,WAAY,GAAO,cAAe,EAAM,ECvNjG,IAAMC,EAAN,cAAsB,KAAM,CACxB,OACA,SACA,QAET,YAAYC,EAAgBC,EAAgC,CAAC,EAAGC,EAAU,GAAO,CAC/E,MAAMD,EAAS,SAAW,uBAAuB,EACjD,KAAK,KAAO,UACZ,KAAK,OAASD,EACd,KAAK,SAAWC,EAChB,KAAK,QAAUC,CACjB,CACF,EAkBMC,EAAc,kBAGpB,SAASC,EAASC,EAAuB,CACvC,GAAI,CACF,IAAMC,EAAOD,EAAM,MAAM,GAAG,EAAE,CAAC,EAAG,WAAW,IAAK,GAAG,EAAE,WAAW,IAAK,GAAG,EAC1E,OAAO,OAAO,KAAK,MAAM,KAAKC,CAAI,CAAC,EAAE,GAAG,GAAK,CAC/C,MAAQ,CACN,MAAO,EACT,CACF,CAGO,SAASC,EAAgBC,EAA8B,CAC5D,IAAIH,EAAQ,GACRI,EAA4B,KAC1BC,EAAY,IAAI,IAEhBC,EAAQC,GAAuB,CACnC,IAAIC,EAAuD,CAAC,EAC5D,GAAI,CACFA,EAAO,KAAK,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"names": ["DEFAULT_SITE", "PbError", "status", "response", "isAbort", "STORAGE_KEY", "tokenExp", "token", "part", "createAuthStore", "storage", "record", "listeners", "load", "raw", "data", "set", "t", "r", "fn", "e", "qs", "query", "parts", "k", "v", "isFiles", "x", "toFormData", "body", "form", "f", "upload", "url", "method", "headers", "onUpload", "ok", "fail", "createClient", "baseUrl", "authStore", "base", "send", "path", "signal", "tag", "payload", "aborted", "res", "etag", "realtime", "createRealtime", "who", "next", "expr", "params", "match", "name", "collection", "recordId", "filename", "RECONNECT_MS", "CONNECT_TIMEOUT_MS", "es", "clientId", "subs", "lastSent", "attempts", "lost", "connectTimer", "reconnectTimer", "pending", "submitting", "queue", "keys", "unsent", "now", "bound", "bind", "key", "source", "sendSubs", "disconnect", "submit", "connect", "resolve", "reject", "initConnect", "connectError", "current", "tries", "p", "err", "reconnecting", "topic", "listener", "fns", "left", "latest", "room", "first", "older", "c", "newer", "changedIn", "since", "from", "to", "withFiles", "q", "ApiError", "message", "status", "fields", "codes", "SIGNUP_LOGIN_FAILED", "errorMessage", "err", "reasonOf", "MSG_FIELDS", "MSG_OPTS", "LIVE_TOPIC", "ROOM_FIELDS", "ROOM_OPTS", "HIDDEN_FIELDS", "SITE_FIELDS", "toApiError", "e", "ApiError", "PbError", "data", "pick", "key", "v", "k", "wrap", "p", "toUser", "r", "USER_FIELDS", "pageOptions", "q", "limit", "page", "MSG_OPTS", "records", "pb", "collection", "path", "one", "id", "list", "perPage", "query", "signal", "auth", "token", "record", "batch", "out", "items", "body", "onUpload", "item", "identity", "password", "sent", "name", "url", "REFUSED", "createApi", "client", "rejected", "opts", "write", "fn", "users", "rooms", "hidden", "messages", "site", "subscribe", "action", "live", "LIVE_TOPIC", "me", "u", "api", "email", "inviteCode", "invite", "err", "SIGNUP_LOGIN_FAILED", "SITE_FIELDS", "row", "DEFAULT_SITE", "file", "handle", "oldPassword", "m", "user", "size", "ROOM_OPTS", "visibility", "archived", "members", "posting", "writers", "userId", "address", "room", "ids", "some", "params", "i", "_", "HIDDEN_FIELDS", "rowId", "at", "kept", "tag", "text", "emoji", "on", "banned", "filename", "thumb", "offs", "off", "d", "after", "connected", "unsub", "parsePb", "s", "toPb", "ms", "sameDay", "a", "b", "x", "y", "sameYear", "STYLES", "cache", "fmt", "style", "locale", "key", "f", "formatTime", "now", "dayLabel", "yesterday", "formatFull"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as o}from"./chunk-UZDXAORM.js";var f=new Set(["jpg","jpeg","png","gif","webp","avif"]),i=e=>e.slice(e.lastIndexOf(".")+1).toLowerCase(),b=e=>e.includes(".")&&f.has(i(e)),j=e=>e.includes(".")&&i(e)==="gif",x=new Set(["mp4","m4v","webm","mov","ogv"]),v=e=>e.includes(".")&&x.has(i(e)),y=new Set(["mp3","m4a","aac","ogg","oga","opus","wav","flac","weba"]),O=e=>e.includes(".")&&y.has(i(e)),_=e=>b(e)||v(e);function T(e){return e.replace(/_[a-z0-9]{10}(\.[^.]*)?$/i,"$1")}function A(e,t){return e.file_names?.[t]||T(t)}function M(e){return e<1024?`${e} B`:e<1024*1024?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(1).replace(/\.0$/,"")} MB`}function D(e,t){let n={accepted:[],rejected:[]};for(let a of t)a.size>o.attachmentBytes?n.rejected.push({name:a.name,reason:`larger than ${M(o.attachmentBytes)}`}):e.length+n.accepted.length>=o.attachments?n.rejected.push({name:a.name,reason:`at most ${o.attachments} files per message`}):n.accepted.push(a);return n}var E=new Set(["image/jpeg","image/png","image/webp"]);function w(e,t,n){let a=Math.min(1,n/Math.max(e,t,1));return{width:Math.max(1,Math.round(e*a)),height:Math.max(1,Math.round(t*a))}}function C(e,t){return typeof OffscreenCanvas=="function"?new OffscreenCanvas(e,t):Object.assign(document.createElement("canvas"),{width:e,height:t})}function I(e,t){return"convertToBlob"in e?e.convertToBlob({type:t,quality:.85}).catch(()=>null):new Promise(n=>e.toBlob(n,t,.85))}async function H(e,t){if(!E.has(e.type)||typeof createImageBitmap!="function")return e;let n;try{n=await createImageBitmap(e);let{width:a,height:s}=w(n.width,n.height,t),u=C(a,s),g=u.getContext("2d");if(!g)return e;g.drawImage(n,0,0,a,s);let r=e.type==="image/png"?"image/png":"image/jpeg",p=await I(u,r);if(p?.type!==r)return e;let d=(r==="image/png"?/\.png$/i.test(e.name):/\.jpe?g$/i.test(e.name))?e.name:`${e.name.replace(/\.[^.]*$/,"")||"image"}.${r==="image/png"?"png":"jpg"}`;return new File([p],d,{type:r,lastModified:e.lastModified})}catch{return e}finally{n?.close()}}var R=["auto","light","dark"],c="chat.theme",S={light:"#f1eefc",dark:"#111214"};function l(){try{return globalThis.localStorage??null}catch{return null}}function h(e=l()){try{let t=e?.getItem(c);return t==="light"||t==="dark"?t:"auto"}catch{return"auto"}}function m(e,t=document){let n=t.documentElement;e==="auto"?delete n.dataset.theme:n.dataset.theme=e;for(let a of t.querySelectorAll('meta[name="theme-color"]')){let s=a.media.includes("dark")?"dark":"light";a.content=S[e==="auto"?s:e]}}function P(e,t=l()){try{e==="auto"?t?.removeItem(c):t?.setItem(c,e)}catch{}m(e)}function X(e=l()){m(h(e));let t=new AbortController;return addEventListener("storage",n=>{(n.key===c||n.key===null)&&m(h(e))},{signal:t.signal}),()=>t.abort()}export{j as a,v as b,O as c,_ as d,A as e,M as f,D as g,H as h,R as i,c as j,h as k,P as l,X as m};
|
|
2
|
+
//# sourceMappingURL=chunk-OKIIBH7O.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../web/src/lib/files.ts", "../../web/src/lib/image.ts", "../../web/src/theme.ts"],
|
|
4
|
+
"sourcesContent": ["// Attachment helpers (\u00A717.4, \u00A717.5). Pure, so the naming and limit rules are unit-tested.\n\nimport * as S from \"../strings/lib-files.ts\";\nimport { LIMITS } from \"./limits.ts\";\n\n/** Extensions shown inline as images (through server thumbnails, except GIFs: see isGif). */\nconst IMAGE_EXT = new Set([\"jpg\", \"jpeg\", \"png\", \"gif\", \"webp\", \"avif\"]);\n\nconst ext = (name: string) => name.slice(name.lastIndexOf(\".\") + 1).toLowerCase();\n\nexport const isImage = (name: string): boolean => name.includes(\".\") && IMAGE_EXT.has(ext(name));\n\n/** A GIF's tile shows the file itself: PocketBase thumbnails a GIF from its first frame only, so it wouldn't play. */\nexport const isGif = (name: string): boolean => name.includes(\".\") && ext(name) === \"gif\";\n\n/** Extensions shown inline as videos: the browser draws their first frame and plays them (there are no server thumbnails). */\nconst VIDEO_EXT = new Set([\"mp4\", \"m4v\", \"webm\", \"mov\", \"ogv\"]);\n\nexport const isVideo = (name: string): boolean => name.includes(\".\") && VIDEO_EXT.has(ext(name));\n\n/** Extensions played inline with an audio player (\u00A717.5). */\nconst AUDIO_EXT = new Set([\"mp3\", \"m4a\", \"aac\", \"ogg\", \"oga\", \"opus\", \"wav\", \"flac\", \"weba\"]);\n\nexport const isAudio = (name: string): boolean => name.includes(\".\") && AUDIO_EXT.has(ext(name));\n\n/** Shown inline (as an image or a video) rather than as a download chip. */\nexport const isMedia = (name: string): boolean => isImage(name) || isVideo(name);\n\n/** \"report_k3j2h1g0f9.pdf\" \u2192 \"report.pdf\": PocketBase adds \"_\" + 10 random characters to stored names. */\nexport function displayName(stored: string): string {\n return stored.replace(/_[a-z0-9]{10}(\\.[^.]*)?$/i, \"$1\");\n}\n\n/** What to call a message's attachment: its original upload name when the server recorded it (QA BUG-28). */\nexport function attachmentName(m: { file_names?: Record<string, string> }, stored: string): string {\n return m.file_names?.[stored] || displayName(stored);\n}\n\nexport function formatBytes(n: number): string {\n if (n < 1024) return `${n} B`;\n if (n < 1024 * 1024) return `${Math.round(n / 1024)} KB`;\n return `${(n / 1024 / 1024).toFixed(1).replace(/\\.0$/, \"\")} MB`;\n}\n\nexport interface FileCheck {\n accepted: File[];\n rejected: { name: string; reason: string }[];\n}\n\n/** Which of `added` fit next to `existing`: at most 10 files per message, each at most 20 MB (LIMITS). */\nexport function checkFiles(existing: readonly File[], added: readonly File[]): FileCheck {\n const out: FileCheck = { accepted: [], rejected: [] };\n for (const f of added) {\n if (f.size > LIMITS.attachmentBytes) {\n out.rejected.push({ name: f.name, reason: `larger than ${formatBytes(LIMITS.attachmentBytes)}` });\n } else if (existing.length + out.accepted.length >= LIMITS.attachments) {\n out.rejected.push({ name: f.name, reason: `at most ${LIMITS.attachments} files per message` });\n } else {\n out.accepted.push(f);\n }\n }\n return out;\n}\n", "// Image preparation before upload (\u00A715.3): scale down and re-encode, which also drops EXIF (GPS location).\n// Best effort: anything that can't be decoded or re-encoded is uploaded as it is, and the server limits decide.\n\n/** Types we re-encode. GIFs are left alone (re-encoding would drop the animation). */\nconst REENCODE = new Set([\"image/jpeg\", \"image/png\", \"image/webp\"]);\n\n/** Size of a `w`\u00D7`h` image scaled down (never up) so its longest edge is at most `maxEdge`. */\nexport function fitWithin(w: number, h: number, maxEdge: number): { width: number; height: number } {\n const scale = Math.min(1, maxEdge / Math.max(w, h, 1));\n return { width: Math.max(1, Math.round(w * scale)), height: Math.max(1, Math.round(h * scale)) };\n}\n\ntype Canvas = OffscreenCanvas | HTMLCanvasElement;\n\nfunction canvas(width: number, height: number): Canvas {\n if (typeof OffscreenCanvas === \"function\") return new OffscreenCanvas(width, height);\n return Object.assign(document.createElement(\"canvas\"), { width, height });\n}\n\nfunction encode(c: Canvas, type: string): Promise<Blob | null> {\n if (\"convertToBlob\" in c) return c.convertToBlob({ type, quality: 0.85 }).catch(() => null);\n return new Promise((ok) => c.toBlob(ok, type, 0.85));\n}\n\n/**\n * `file` scaled to at most `maxEdge` px and re-encoded: PNG as PNG (keeps transparency), the rest as JPEG. Both are\n * formats PocketBase thumbnails in kind; a WebP's thumbnails would be PNGs, often bigger than the image (QA BUG-26).\n */\nexport async function prepareImage(file: File, maxEdge: number): Promise<File> {\n if (!REENCODE.has(file.type) || typeof createImageBitmap !== \"function\") return file;\n let bitmap: ImageBitmap | undefined;\n try {\n bitmap = await createImageBitmap(file);\n const { width, height } = fitWithin(bitmap.width, bitmap.height, maxEdge);\n const c = canvas(width, height);\n const ctx = c.getContext(\"2d\") as OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D | null;\n if (!ctx) return file;\n ctx.drawImage(bitmap, 0, 0, width, height);\n const type = file.type === \"image/png\" ? \"image/png\" : \"image/jpeg\";\n // An encoder that doesn't support a type falls back to PNG: check what we actually got.\n const blob = await encode(c, type);\n if (blob?.type !== type) return file;\n const keepsName = type === \"image/png\" ? /\\.png$/i.test(file.name) : /\\.jpe?g$/i.test(file.name);\n const name = keepsName ? file.name : `${file.name.replace(/\\.[^.]*$/, \"\") || \"image\"}.${type === \"image/png\" ? \"png\" : \"jpg\"}`;\n return new File([blob], name, { type, lastModified: file.lastModified });\n } catch {\n return file;\n } finally {\n bitmap?.close();\n }\n}\n", "// Light, dark or the system's (auto) theme (\u00A77.8): this device's choice, kept in localStorage. index.html's inline\n// script sets <html data-theme> before the first paint; this keeps it, and the browser's bar color, up to date.\n\nexport const THEMES = [\"auto\", \"light\", \"dark\"] as const;\nexport type Theme = (typeof THEMES)[number];\n\n/** Must match index.html's inline script. */\nexport const THEME_KEY = \"chat.theme\";\n\n/** --surface of each theme (tokens.css), for <meta name=\"theme-color\">. */\nconst BAR = { light: \"#f1eefc\", dark: \"#111214\" } as const;\n\nfunction safeLocalStorage(): Storage | null {\n try {\n return globalThis.localStorage ?? null;\n } catch {\n return null;\n }\n}\n\nexport function savedTheme(storage: Storage | null = safeLocalStorage()): Theme {\n try {\n const v = storage?.getItem(THEME_KEY);\n return v === \"light\" || v === \"dark\" ? v : \"auto\";\n } catch {\n return \"auto\";\n }\n}\n\n/** Show `theme` here: the stylesheet goes by <html data-theme>, the browser's bar by the theme-color metas. */\nexport function applyTheme(theme: Theme, doc: Document = document): void {\n const html = doc.documentElement;\n if (theme === \"auto\") delete html.dataset.theme;\n else html.dataset.theme = theme;\n for (const meta of doc.querySelectorAll<HTMLMetaElement>('meta[name=\"theme-color\"]')) {\n // Each meta's own media query says which theme it is for; a chosen theme gives both its color.\n const forTheme = meta.media.includes(\"dark\") ? \"dark\" : \"light\";\n meta.content = BAR[theme === \"auto\" ? forTheme : theme];\n }\n}\n\n/** Save and show `theme`. Storage can throw (private window, quota): the theme still changes for this page. */\nexport function setTheme(theme: Theme, storage: Storage | null = safeLocalStorage()): void {\n try {\n if (theme === \"auto\") storage?.removeItem(THEME_KEY);\n else storage?.setItem(THEME_KEY, theme);\n } catch {}\n applyTheme(theme);\n}\n\n/** Apply the saved theme and follow another tab's changes. Returns a function that stops following. */\nexport function startTheme(storage: Storage | null = safeLocalStorage()): () => void {\n applyTheme(savedTheme(storage));\n const ac = new AbortController();\n addEventListener(\n \"storage\",\n (e) => {\n if (e.key === THEME_KEY || e.key === null) applyTheme(savedTheme(storage));\n },\n { signal: ac.signal },\n );\n return () => ac.abort();\n}\n"],
|
|
5
|
+
"mappings": "wCAMA,IAAMA,EAAY,IAAI,IAAI,CAAC,MAAO,OAAQ,MAAO,MAAO,OAAQ,MAAM,CAAC,EAEjEC,EAAOC,GAAiBA,EAAK,MAAMA,EAAK,YAAY,GAAG,EAAI,CAAC,EAAE,YAAY,EAEnEC,EAAWD,GAA0BA,EAAK,SAAS,GAAG,GAAKF,EAAU,IAAIC,EAAIC,CAAI,CAAC,EAGlFE,EAASF,GAA0BA,EAAK,SAAS,GAAG,GAAKD,EAAIC,CAAI,IAAM,MAG9EG,EAAY,IAAI,IAAI,CAAC,MAAO,MAAO,OAAQ,MAAO,KAAK,CAAC,EAEjDC,EAAWJ,GAA0BA,EAAK,SAAS,GAAG,GAAKG,EAAU,IAAIJ,EAAIC,CAAI,CAAC,EAGzFK,EAAY,IAAI,IAAI,CAAC,MAAO,MAAO,MAAO,MAAO,MAAO,OAAQ,MAAO,OAAQ,MAAM,CAAC,EAE/EC,EAAWN,GAA0BA,EAAK,SAAS,GAAG,GAAKK,EAAU,IAAIN,EAAIC,CAAI,CAAC,EAGlFO,EAA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o", "AUDIO_EXT", "isAudio", "isMedia", "displayName", "stored", "attachmentName", "m", "formatBytes", "n", "checkFiles", "existing", "added", "out", "f", "LIMITS", "REENCODE", "fitWithin", "w", "h", "maxEdge", "scale", "canvas", "width", "height", "encode", "c", "type", "ok", "prepareImage", "file", "bitmap", "ctx", "blob", "name", "THEMES", "THEME_KEY", "BAR", "safeLocalStorage", "savedTheme", "storage", "v", "applyTheme", "theme", "doc", "html", "meta", "forTheme", "setTheme", "startTheme", "ac", "e"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var s={messageText:2e3,userName:32,roomName:48,passwordMin:8,passwordMaxBytes:71,avatarBytes:2097152,avatarTypes:["image/jpeg","image/png","image/webp","image/gif"],attachments:10,attachmentBytes:20971520,roomMembers:100};function o(t){let e=0;for(let a of t)e++;return e}var r=50;export{s as a,o as b,r as c};
|
|
2
|
+
//# sourceMappingURL=chunk-UZDXAORM.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../web/src/lib/limits.ts"],
|
|
4
|
+
"sourcesContent": ["// Field limits the UI enforces before the server does. They mirror pb_migrations (the source of truth);\n// tests/integration/schema.test.ts fails if the two drift apart.\n\nexport const LIMITS = {\n /** messages.text max */\n messageText: 2000,\n /** users.name max */\n userName: 32,\n /** rooms.name max */\n roomName: 48,\n /** users password min (PocketBase's auth default) */\n passwordMin: 8,\n /**\n * users password max, in UTF-8 bytes: bcrypt's 72, PocketBase's 71. PocketBase refuses a longer one on signup without\n * saying why (QA BUG-267); the hooks say it for a change or a reset (PASSWORD_MAX_BYTES, lib/users.js).\n */\n passwordMaxBytes: 71,\n /** users.avatar maxSize (\u00A715.1) */\n avatarBytes: 2 * 1024 * 1024,\n /** users.avatar mimeTypes (\u00A715.1) */\n avatarTypes: [\"image/jpeg\", \"image/png\", \"image/webp\", \"image/gif\"],\n /** messages.files maxSelect (\u00A717.1) */\n attachments: 10,\n /** messages.files maxSize, per file (\u00A717.1) */\n attachmentBytes: 20 * 1024 * 1024,\n /** rooms.members maxSelect: a private room's members, its creator included (\u00A723.2) */\n roomMembers: 100,\n} as const;\n\n/** Length as PocketBase counts it for these limits: Unicode code points, not UTF-16 units (an emoji is 1, not 2). */\nexport function textLength(s: string): number {\n let n = 0;\n for (const _ of s) n++;\n return n;\n}\n\n/** Most messages that can be selected, and so deleted or forwarded at once (\u00A721; MAX_MESSAGES in pb_hooks/lib/bulk.js). */\nexport const MAX_SELECTED = 50;\n"],
|
|
5
|
+
"mappings": "AAGO,IAAMA,EAAS,CAEpB,YAAa,IAEb,SAAU,GAEV,SAAU,GAEV,YAAa,EAKb,iBAAkB,GAElB,YAAa,QAEb,YAAa,CAAC,aAAc,YAAa,aAAc,WAAW,EAElE,YAAa,GAEb,gBAAiB,SAEjB,YAAa,GACf,EAGO,SAASC,EAAWC,EAAmB,CAC5C,IAAIC,EAAI,EACR,QAAWC,KAAKF,EAAGC,IACnB,OAAOA,CACT,CAGO,IAAME,EAAe",
|
|
6
|
+
"names": ["LIMITS", "textLength", "s", "n", "_", "MAX_SELECTED"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{g as v,p as R}from"./chunk-N2OFGBCZ.js";import{c as w,j as x}from"./chunk-DZC4SY4M.js";import{a as h}from"./chunk-RPCBA7VF.js";import{a as s}from"./chunk-VTOUI25E.js";function O(e){let t=e,o=new Set;return{get:()=>t,set(i){let p=typeof i=="function"?i(t):i;if(!Object.keys(p).some(r=>p[r]!==t[r]))return;let a=t;t={...t,...p};for(let r of[...o])r(t,a)},subscribe(i){return o.add(i),()=>o.delete(i)}}}var U=new Map,H=()=>({user:null,rooms:new Map,hidden:new Map,unread:U,mentions:new Map,inbox:0,roomsStatus:"idle",listLoads:0,activeRoomId:null,collections:null,activeCollectionId:null,away:!1,site:v}),J=e=>t=>({listLoads:t.listLoads+e});function N(e){return t=>({rooms:new Map(t.rooms).set(e.id,e)})}function j(e){return t=>{let o=new Map(t.rooms);return o.delete(e),{rooms:o}}}function D(e,t){return o=>({hidden:new Map(o.hidden).set(e,t)})}function F(e){return t=>{if(!t.hidden.has(e))return{};let o=new Map(t.hidden);return o.delete(e),{hidden:o}}}function Y(e){return t=>({hidden:new Map([...t.hidden].filter(([,o])=>o!==e))})}function $(e){return t=>({unread:new Map(t.unread).set(e,(t.unread.get(e)??0)+1)})}function B(e){return t=>{if(!t.unread.has(e)&&!t.mentions.has(e))return{};let o=new Map(t.unread),i=new Map(t.mentions);return o.delete(e),i.delete(e),{unread:o,mentions:i}}}function m(e,t){return t.archived||e.hidden.has(t.id)?0:e.unread.get(t.id)??0}var G=(e,t)=>!!m(e,t)&&!!e.mentions.get(t.id),C=new Intl.Collator(void 0,{sensitivity:"base"}),b=(e,t)=>C.compare(e.name,t.name),E=(e,t)=>{let o=e.last_message_at||e.created||"",i=t.last_message_at||t.created||"";return o<i?1:o>i?-1:e.id.localeCompare(t.id)};function k(e){let t=[],o=[],i=[],p=[];for(let r of e.rooms.values())r.kind==="dm"?(r.last_message_at||r.created_by===e.user?.id||r.id===e.activeRoomId)&&!e.hidden.has(r.id)&&o.push(r):r.archived?p.push(r):e.hidden.has(r.id)?i.push(r):t.push(r);let a=r=>(c,u)=>+!m(e,c)-+!m(e,u)||r(c,u);return{rooms:t.sort(a(b)),dms:o.sort(a(E)),hidden:i.sort(b),archived:p.sort(b)}}var g="chirkle-jump",A={private:"ic i-lock",open:"ic i-globe"};function X(e){let{api:t,store:o,root:i}=e,p,a=new Map,r=n=>{let d=/^[a-z]$/i.test(n.key)?n.key.toLowerCase():n.code;!(n.ctrlKey||n.metaKey)||n.altKey||n.shiftKey||!/^(k|p|KeyK|KeyP)$/.test(d)||(n.preventDefault(),n.repeat||S())},c,u=n=>{if(!(c==null||n.ctrlKey||n.metaKey||n.altKey||n.isComposing)){if(n.key==="Escape")c=null;else if(n.key==="Backspace")c=c.slice(0,-1);else if(n.key.length===1)c+=n.key;else if(n.key!=="Enter")return;n.preventDefault(),n.stopImmediatePropagation()}},S=()=>{p||(c=""),p??=import("./switcher-TFSO45KV.js").then(n=>{let d=n.createSwitcher({state:o.get,sections:k,unread:m,other:x,icon:l=>A[w(l)]??"",avatar:l=>h(l,24,t.avatarUrl),navigate:e.navigate,opened:l=>a.get(l)??""});return i.append(d.el),d},n=>{throw p=void 0,c=void 0,n}),p.then(n=>{let d=c;if(c=void 0,d===null)return;n.toggle();let l=n.el.querySelector("input");!d||!l||(l.value=d,l.dispatchEvent(new Event("input")))},()=>{})},M=o.subscribe((n,d)=>{let l=n.activeRoomId??n.activeCollectionId,y=d.activeRoomId??d.activeCollectionId;if(l!==y)for(let f of[y,l])f&&a.set(f,R(Date.now()));n.user?.id!==d.user?.id&&(a.clear(),p?.then(f=>f.el.close(),()=>{}))});return document.addEventListener("keydown",r),document.addEventListener("keydown",u,!0),document.addEventListener(g,S),()=>{document.removeEventListener("keydown",r),document.removeEventListener("keydown",u,!0),document.removeEventListener(g,S),M()}}var L=e=>`Jump to (${e?"\u2318":"Ctrl+"}K)`;function _(e,t=!1){let{title:o,logo:i}=e,p=i?"brand has-logo":"brand",a=i?s("img",{src:i,alt:"",class:"brand-logo"}):null,r=t?P(e):null;return r?s("div",{class:p},[a,s("span",{class:"brand-name"},[s("a",{href:"/",class:"brand-title"},o),r])]):s("a",{href:"/",class:p},[a,s("span",{class:"brand-title"},o)])}function P({title:e},t="span"){return e.trim().toLowerCase()==="chirkle"?null:s(t,{class:"brand-by"},["chirps on ",s("a",{href:"https://chirkle.com",target:"_blank",rel:"noopener"},"Chirkle")])}function T(e){let t=/Mac|iP/.test(navigator.platform);return s("button",{type:"button",class:e?"jump-button ic i-search":"icon-button ic i-search","aria-label":"Jump to",title:L(t),on:{click:()=>document.dispatchEvent(new Event(g))}},e?[s("span",{},"Jump to\u2026"),s("kbd",{"aria-hidden":"true"},t?"\u2318K":"Ctrl K")]:[])}function oe({api:e,store:t}){let o=s("header",{class:"app-bar"});function i(){let a=t.get().user;o.replaceChildren(_(t.get().site),a?s("div",{class:"bar-end"},[T(!1),s("a",{href:"/me",class:"me-link",title:"Your profile"},[h(a,32,e.avatarUrl),s("span",{class:"who"},a.name)])]):s("nav",{class:"guest-links","aria-label":"Account"},[s("a",{href:"/login",class:"guest-link"},"Log in"),s("a",{href:"/signup",class:"guest-link primary"},"Sign up")]))}let p=t.subscribe((a,r)=>{(a.site!==r.site||a.user!==r.user)&&i()});return i(),{el:o,stop:p}}export{O as a,U as b,H as c,J as d,N as e,j as f,D as g,F as h,Y as i,$ as j,B as k,m as l,G as m,k as n,X as o,_ as p,P as q,T as r,oe as s};
|
|
2
|
+
//# sourceMappingURL=chunk-WR25F7FU.js.map
|