@zextras/carbonio-ws-collaboration-ui-sdk 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client/writeQueue.ts","../src/domain/inbox.ts","../src/client/delete.ts","../src/client/edit.ts","../src/client/forward.ts","../src/domain/presence.ts","../src/client/presence.ts","../src/http/queryString.ts","../src/client/inbox.ts","../src/client/messages.ts","../src/domain/pinRows.ts","../src/client/pin.ts","../src/client/reactions.ts","../src/client/read.ts","../src/domain/search.ts","../src/client/search.ts","../src/client/systemLines.ts","../src/domain/timeline.ts","../src/client/timeline.ts","../src/client/typing.ts","../src/client/createClient.ts","../src/http/errors.ts","../src/http/httpClient.ts"],"sourcesContent":["/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\n/**\n * Per-room FIFO queue for REST writes (send/edit/delete/forward). XMPP\n * serialized outgoing stanzas implicitly on its single stream; concurrent\n * fetches can instead complete out of order and swap two sends (plan §7.4).\n * One queue instance lives per client, one chain per room.\n */\nexport type WriteQueue = Map<string, Promise<unknown>>;\n\nexport function createWriteQueue(): WriteQueue {\n\treturn new Map();\n}\n\n/**\n * Chains `task` after the room's pending writes. A failed task rejects its own\n * caller but never poisons the chain: the next write still runs. The room\n * entry is dropped once the chain drains, so idle rooms do not leak.\n */\nexport function enqueueWrite<T>(\n\tqueue: WriteQueue,\n\troomId: string,\n\ttask: () => Promise<T>\n): Promise<T> {\n\tconst previous = queue.get(roomId) ?? Promise.resolve();\n\tconst run = previous.then(task, task);\n\tconst tail = run.then(\n\t\t() => undefined,\n\t\t() => undefined\n\t);\n\tqueue.set(roomId, tail);\n\ttail.then(() => {\n\t\tif (queue.get(roomId) === tail) {\n\t\t\tqueue.delete(roomId);\n\t\t}\n\t});\n\treturn run;\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport type {\n\tWireInboxEntry,\n\tWireReadMarker,\n\tWireSystemEvent,\n\tWireTimelineItem,\n\tWireTimelineMessage\n} from '../types/api';\nimport type {\n\tStoreAttachment,\n\tStoreConfigurationMessage,\n\tStoreMarker,\n\tStoreMessage,\n\tStoreOperationType,\n\tStoreTextMessage\n} from '../types/store';\n\nexport type PresenceUpdate = {\n\tuserId: string;\n\tonline: boolean;\n\t/** Milliseconds since epoch; only present for offline users with a known last session. */\n\tlastActivity?: number;\n};\n\nexport type MappedInboxEntry = {\n\troomId: string;\n\tlastMessage?: StoreMessage;\n\tmarkers: Array<StoreMarker>;\n\tunreadCount: number;\n\tpresence: Array<PresenceUpdate>;\n};\n\nexport function toTimestamp(date: string | undefined): number {\n\tconst parsed = date ? Date.parse(date) : NaN;\n\treturn Number.isNaN(parsed) ? 0 : parsed;\n}\n\n/**\n * Wire attachment -> store attachment. `area` (the image layout hint the\n * sender declared on upload) is nullable on the timeline and events, and\n * absent as a key on the inbox when null: only a non-empty value is kept.\n */\nfunction mapWireAttachment(\n\tattachment: NonNullable<WireTimelineMessage['attachment']>\n): StoreAttachment {\n\tconst { id, name, mimeType, size, area } = attachment;\n\treturn { id, name, mimeType, size, ...(area ? { area } : {}) };\n}\n\n/**\n * Wire message -> store TextMessage, preserving the dual-id invariant with\n * `id = stanzaId = server UUID`. Deleted/edited messages arrive already\n * materialized (`deletedInfo`/`editedInfo`), so they map to the legacy\n * booleans the store and the UI understand — no fastening machinery needed\n * on the inbox path.\n *\n * `withQuote` maps the embedded `repliedMessage` through this same mapper,\n * once: the quote is depth-1 by contract, so its own `repliedMessage` (never\n * sent) is ignored.\n */\nfunction mapMessage(message: WireTimelineMessage, withQuote: boolean): StoreTextMessage {\n\tconst deleted = message.deletedInfo !== undefined;\n\treturn {\n\t\tid: message.id,\n\t\tstanzaId: message.id,\n\t\troomId: message.roomId,\n\t\tdate: toTimestamp(message.createdAt),\n\t\ttype: 'text',\n\t\tfrom: message.senderId,\n\t\ttext: deleted ? '' : message.text,\n\t\tread: 'unread',\n\t\t...(deleted ? { deleted: true } : {}),\n\t\t...(message.editedInfo ? { edited: true } : {}),\n\t\t...(message.replyToId ? { replyTo: message.replyToId } : {}),\n\t\t// A quote without its replyToId must never turn a plain message into a\n\t\t// reply bubble (same guard as the façade-resolved quotes)\n\t\t...(withQuote && message.replyToId && message.repliedMessage\n\t\t\t? { repliedMessage: mapMessage(message.repliedMessage, false) }\n\t\t\t: {}),\n\t\t// A forward of an own message reads as a plain message, as the v1 clients decoded it\n\t\t...(message.forwardedInfo && message.forwardedInfo.originalSenderId !== message.senderId\n\t\t\t? {\n\t\t\t\t\tforwarded: {\n\t\t\t\t\t\t// v2 dropped the archive id and the forward counter (open question\n\t\t\t\t\t\t// §5.7 of the plan); map best-effort onto the legacy shape.\n\t\t\t\t\t\tid: '',\n\t\t\t\t\t\tdate: toTimestamp(message.forwardedInfo.originalSentAt),\n\t\t\t\t\t\tfrom: message.forwardedInfo.originalSenderId,\n\t\t\t\t\t\tcount: 1\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t: {}),\n\t\t...(message.attachment ? { attachment: mapWireAttachment(message.attachment) } : {})\n\t};\n}\n\n/**\n * Wire message -> store TextMessage. On a reply the embedded `repliedMessage`\n * becomes the quoted TextMessage the bubble's reply section renders — in v1\n * that hydration cost an archive query per reply not already in store. When\n * the original is not visible to the caller (cleared, pre-join, removed) the\n * wire carries only `replyToId`: the message keeps `replyTo` and no quote,\n * and the reply section does not render.\n */\nexport function mapWireMessageToStoreMessage(message: WireTimelineMessage): StoreTextMessage {\n\treturn mapMessage(message, true);\n}\n\nconst SYSTEM_EVENT_TO_OPERATION: Record<string, StoreOperationType> = {\n\tROOM_CREATED: 'roomCreation',\n\tROOM_NAME_CHANGED: 'roomNameChanged',\n\tROOM_DESCRIPTION_CHANGED: 'roomDescriptionChanged',\n\tROOM_PICTURE_UPDATED: 'roomPictureUpdated',\n\tROOM_PICTURE_DELETED: 'roomPictureDeleted',\n\tROOM_HISTORY_CLEARED: 'roomHistoryCleared',\n\tMEMBER_ADDED: 'memberAdded',\n\tMEMBER_REMOVED: 'memberRemoved',\n\tMESSAGE_PINNED: 'messagePinned',\n\tMESSAGE_UNPINNED: 'messageUnpinned',\n\tMEETING_STARTED: 'meetingStarted',\n\tMEETING_ENDED: 'meetingEnded',\n\tMEETING_DECLINED: 'meetingDeclined'\n};\n\n/**\n * Value extraction per system event type. Field names validated against\n * the backend implementation (frontend spike, plan §7.2) — the event catalog\n * is not in asyncapi.yaml yet. The author is `actorId`, not part of `content`.\n */\nfunction extractValue(type: string, content: Record<string, unknown> | undefined): string {\n\tconst str = (key: string): string => {\n\t\tconst raw = content?.[key];\n\t\treturn typeof raw === 'string' ? raw : '';\n\t};\n\tswitch (type) {\n\t\t// The new name or description, the v1 row value; an empty description is a removal\n\t\tcase 'ROOM_NAME_CHANGED':\n\t\t\treturn str('name');\n\t\tcase 'ROOM_DESCRIPTION_CHANGED':\n\t\t\treturn str('description');\n\t\tcase 'MEMBER_ADDED': {\n\t\t\tconst added = content?.addedUserIds;\n\t\t\treturn Array.isArray(added) && typeof added[0] === 'string' ? added[0] : '';\n\t\t}\n\t\tcase 'MEMBER_REMOVED':\n\t\t\treturn str('removedUserId');\n\t\tcase 'MESSAGE_PINNED':\n\t\tcase 'MESSAGE_UNPINNED':\n\t\t\treturn str('messageId');\n\t\tcase 'MEETING_ENDED': {\n\t\t\t// The call duration in seconds, the v1 row value the \"Call ended\" line shows\n\t\t\tconst duration = content?.durationSec;\n\t\t\treturn typeof duration === 'number' ? String(duration) : '';\n\t\t}\n\t\tdefault:\n\t\t\treturn '';\n\t}\n}\n\nexport function mapSystemEventToStoreMessage(\n\tevent: WireSystemEvent,\n\troomId: string\n): StoreConfigurationMessage | undefined {\n\tconst operation = SYSTEM_EVENT_TO_OPERATION[event.type];\n\tif (!operation) {\n\t\treturn undefined;\n\t}\n\tconst value = extractValue(event.type, event.content);\n\treturn {\n\t\tid: event.id,\n\t\troomId,\n\t\tdate: toTimestamp(event.createdAt),\n\t\ttype: 'configuration',\n\t\toperation,\n\t\tvalue,\n\t\tfrom: event.actorId,\n\t\tread: 'read'\n\t};\n}\n\n/**\n * Id of the history row a v2 read marker lands on: the newest row dated at or\n * before `itemCreatedAt`.\n *\n * The backend stamps `itemCreatedAt` with the `createdAt` of the item marked\n * through `PUT /read` (message or system event) and never moves it back, so\n * the match is normally exact — hence the inclusive bound. When the marked\n * item is not a row (a system event type the mapper skips) the marker lands\n * on the row just before it, which every consumer reads the same way: the\n * apps compare dates, and no row sits between the two.\n *\n * Only rows that stay in the history qualify: text and configuration rows,\n * not optimistic placeholders (replaced on confirmation by a row with another\n * id, which would leave the marker dangling). Same-instant rows resolve to\n * the last one in input order, so both count as read.\n *\n * Returns '' when no row qualifies (marker older than the loaded history, or\n * nothing loaded yet): every consumer then falls back to `markerDate`, like a\n * v1 marker pointing outside the loaded history.\n */\nexport function resolveMarkedMessageId(\n\titemCreatedAt: number,\n\trows: ReadonlyArray<StoreMessage>\n): string {\n\tlet marked: StoreMessage | undefined;\n\trows.forEach((row) => {\n\t\tif (row.type !== 'text' && row.type !== 'configuration') {\n\t\t\treturn;\n\t\t}\n\t\tif (row.read === 'pending' || row.date > itemCreatedAt) {\n\t\t\treturn;\n\t\t}\n\t\tif (!marked || row.date >= marked.date) {\n\t\t\tmarked = row;\n\t\t}\n\t});\n\treturn marked?.id ?? '';\n}\n\n/**\n * v2 read marker -> store marker, without changing the store shape: the wire\n * carries only `{userId, itemCreatedAt}` while the store consumers key on a\n * message id. `markerDate` is `itemCreatedAt` itself — the instant the consumers\n * fall back to when the id is not in store — and `messageId` is resolved\n * against `rows`, the room history the marker will be read against.\n */\nexport function mapWireMarkerToStoreMarker(\n\tmarker: WireReadMarker,\n\trows: ReadonlyArray<StoreMessage>\n): StoreMarker {\n\tconst itemCreatedAt = toTimestamp(marker.itemCreatedAt);\n\treturn {\n\t\tfrom: marker.userId,\n\t\tmessageId: resolveMarkedMessageId(itemCreatedAt, rows),\n\t\tmarkerDate: itemCreatedAt,\n\t\ttype: 'displayed'\n\t};\n}\n\n/**\n * Timeline item -> the room's last message in the chat list: a message, or a\n * system event mapped to a configuration row; undefined for a system event\n * type the mapper skips.\n */\nexport function mapLastItem(\n\titem: WireTimelineItem | undefined,\n\troomId: string\n): StoreMessage | undefined {\n\tif (item?.itemType === 'message') {\n\t\treturn mapWireMessageToStoreMessage(item.message);\n\t}\n\tif (item?.itemType === 'system_event') {\n\t\treturn mapSystemEventToStoreMessage(item.systemEvent, roomId);\n\t}\n\treturn undefined;\n}\n\n/**\n * Maps one inbox entry to its store writes. Mirrors the v1 inbox semantics:\n * - `lastItem` becomes the room's last message: a message, or a system event\n * mapped to a configuration row like in the v1 XMPP inbox; a room without\n * visible items has none;\n * - a last message at or before the user's `clearedAt` is dropped (the v1\n * handler applies the same filter on the XMPP inbox result);\n * - members' presence is extracted from the inbox room (v2 replaces the\n * roster/last-activity XMPP queries).\n *\n * Markers resolve against `knownRows` (the room history already in store)\n * plus the last message: until the timeline loads, the last message is the\n * only row the inbox knows, and the most common target of a marker.\n */\nexport function mapInboxEntry(\n\tentry: WireInboxEntry,\n\tknownRows: ReadonlyArray<StoreMessage> = []\n): MappedInboxEntry {\n\tconst clearedAt = toTimestamp(entry.room.userSettings?.clearedAt);\n\n\tlet lastMessage = mapLastItem(entry.lastItem, entry.roomId);\n\tif (lastMessage && clearedAt > 0 && lastMessage.date <= clearedAt) {\n\t\tlastMessage = undefined;\n\t}\n\n\tconst rows = lastMessage ? [...knownRows, lastMessage] : knownRows;\n\tconst presence: Array<PresenceUpdate> = (entry.room.members ?? []).map((member) => ({\n\t\tuserId: member.userId,\n\t\tonline: member.online,\n\t\t...(member.lastActivity ? { lastActivity: toTimestamp(member.lastActivity) } : {})\n\t}));\n\n\treturn {\n\t\troomId: entry.roomId,\n\t\tlastMessage,\n\t\tmarkers: (entry.markers ?? []).map((marker) => mapWireMarkerToStoreMarker(marker, rows)),\n\t\tunreadCount: entry.unreadCount,\n\t\tpresence\n\t};\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport type { MessagesDeps } from './messages';\nimport { enqueueWrite } from './writeQueue';\nimport { toTimestamp } from '../domain/inbox';\nimport type { WireMessageDeletedEvent } from '../types/events';\nimport type { StoreMessageFastening, StoreTextMessage } from '../types/store';\n\n/**\n * The v1 wire retraction, synthesized client-side. A message is deleted once,\n * so the deterministic id needs no timestamp — `d_{messageId}` matches across\n * echoes and replays by construction (no serialization-drift concern like the\n * edit's). No `value`: the v1 retract fastening carried none and the\n * projection reads none for DELETE.\n */\nfunction buildDeleteFastening(\n\troomId: string,\n\tmessageId: string,\n\tfrom: string,\n\tdeletedAt: string\n): StoreMessageFastening {\n\tconst id = `d_${messageId}`;\n\treturn {\n\t\tid,\n\t\tstanzaId: id,\n\t\troomId,\n\t\tdate: toTimestamp(deletedAt),\n\t\ttype: 'fastening',\n\t\taction: 'delete',\n\t\toriginalStanzaId: messageId,\n\t\tfrom\n\t};\n}\n\n/**\n * `DELETE /rooms/{roomId}/messages/{messageId}` — serialized through the same\n * per-room FIFO write queue as the sends and edits (plan §7.4).\n *\n * Confirmation is echo-only, unlike the edit's two-way scheme: the 204 has no\n * body, hence no server timestamp to date the fastening with. A client-side\n * now() could lose against a fresher server editedAt in the projection\n * (latest EDIT/DELETE by date) and the slice dedup would then drop the echo's\n * corrective fastening — so the REST path writes nothing, exactly like the v1\n * retraction that only confirmed through the MUC echo.\n */\nexport function deleteMessage(\n\t{ http, queue }: MessagesDeps,\n\troomId: string,\n\tmessageId: string\n): Promise<void> {\n\treturn enqueueWrite(queue, roomId, async () => {\n\t\tawait http.request<void>(\n\t\t\t`rooms/${encodeURIComponent(roomId)}/messages/${encodeURIComponent(messageId)}`,\n\t\t\t'DELETE'\n\t\t);\n\t});\n}\n\n/**\n * `MessageDeleted` push event — every deleter, own echo included (v1 MUC\n * parity, like the edits: no unread bump, no notifications). The fastening\n * write is shared; the sidebar update only happens when the deletion hits the\n * room's last message — the app router resolves that (fresh) and passes it\n * here. History needs none of this: timeline/inbox DTOs arrive already\n * materialized (`deletedInfo` -> the `deleted` boolean, step 3).\n */\nexport function handleMessageDeleted(\n\t{ bridge }: MessagesDeps,\n\tevent: WireMessageDeletedEvent,\n\tlastMessage?: StoreTextMessage\n): void {\n\tbridge.addFastening([\n\t\tbuildDeleteFastening(event.roomId, event.messageId, event.deletedBy, event.deletedAt)\n\t]);\n\tif (lastMessage) {\n\t\t// The v1 handler's merge, verbatim: deleted flagged, text emptied,\n\t\t// attachment and reply reference cleared\n\t\tbridge.setLastMessage(event.roomId, {\n\t\t\t...lastMessage,\n\t\t\tdeleted: true,\n\t\t\ttext: '',\n\t\t\tattachment: undefined,\n\t\t\treplyTo: undefined\n\t\t});\n\t}\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport type { MessagesDeps } from './messages';\nimport { enqueueWrite } from './writeQueue';\nimport { toTimestamp } from '../domain/inbox';\nimport type { WireMessage } from '../types/api';\nimport type { WireMessageEditedEvent } from '../types/events';\nimport type { StoreMessageFastening, StoreTextMessage } from '../types/store';\n\nexport type EditMessageParams = {\n\troomId: string;\n\t/** Server id of the message to edit (v2: stable across edits, id === stanzaId). */\n\tmessageId: string;\n\t/** The full new text, not a delta. */\n\ttext: string;\n};\n\n/**\n * Deterministic fastening id: the REST confirmation and the `MessageEdited`\n * echo describe the same edit with the same timestamp (one DB column), so\n * both paths synthesize the same id and the slice dedup makes whichever lands\n * second a no-op — the send flow's idempotence, keyed like the planned\n * reaction ids (plan §3). Were the two serializations ever to differ, the\n * duplicate fastening would carry the same value and the projection (latest\n * by date) would still render the same text.\n */\nfunction editFasteningId(messageId: string, editedAt: string): string {\n\treturn `e_${messageId}_${editedAt}`;\n}\n\n/**\n * The v1 wire fastening, synthesized client-side. In v1 the correction was\n * itself a stanza with its own archive id; here id and stanzaId share the\n * deterministic value (stanzaId's only v1 consumer — the XEP-0422 parent-id\n * of a follow-up edit — has no v2 counterpart).\n */\nfunction buildEditFastening(\n\troomId: string,\n\tmessageId: string,\n\tfrom: string,\n\ttext: string,\n\teditedAt: string\n): StoreMessageFastening {\n\tconst id = editFasteningId(messageId, editedAt);\n\treturn {\n\t\tid,\n\t\tstanzaId: id,\n\t\troomId,\n\t\tdate: toTimestamp(editedAt),\n\t\ttype: 'fastening',\n\t\taction: 'edit',\n\t\toriginalStanzaId: messageId,\n\t\tfrom,\n\t\tvalue: text\n\t};\n}\n\n/**\n * `PUT /rooms/{roomId}/messages/{messageId}/edit` — serialized through the\n * same per-room FIFO write queue as the sends, so an edit issued right after\n * a send keeps the wire order (plan §7.4). No optimistic write: v1 sent the\n * correction stanza and waited for the MUC echo; here the 200 already\n * confirms, one hop earlier.\n *\n * The response only synthesizes the fastening (bubble text + \"edited\" label\n * via the apps' projection). The sidebar's lastMessage update stays with the\n * event path on purpose: it needs the CURRENT last message, and a value\n * resolved before the PUT could regress the sidebar if another message lands\n * in between — the echo's router lookup is always fresh.\n */\nexport function editMessage(\n\t{ http, bridge, queue }: MessagesDeps,\n\tparams: EditMessageParams\n): Promise<void> {\n\tconst { roomId, messageId, text } = params;\n\treturn enqueueWrite(queue, roomId, async () => {\n\t\tconst response = await http.request<WireMessage>(\n\t\t\t`rooms/${encodeURIComponent(roomId)}/messages/${encodeURIComponent(messageId)}/edit`,\n\t\t\t'PUT',\n\t\t\t{ text }\n\t\t);\n\t\t// Same DB timestamp as the echo's editedAt, so the deterministic id matches\n\t\tconst editedAt = response?.editedInfo?.editedAt;\n\t\tif (editedAt) {\n\t\t\t// The 200 is the edited `Message`: sender and text are server-authoritative\n\t\t\tbridge.addFastening([\n\t\t\t\tbuildEditFastening(roomId, messageId, response.senderId, response.text, editedAt)\n\t\t\t]);\n\t\t}\n\t\t// 200 without an edit timestamp (or the legacy 204, no body): no\n\t\t// deterministic id to build — the MessageEdited echo confirms instead,\n\t\t// exactly like an incomplete 201 on the send path.\n\t});\n}\n\n/**\n * `MessageEdited` push event — every editor, own echo included (no self-skip:\n * v1 corrections came back through the MUC to everyone, the sender too). The\n * fastening write is shared by all editors; the sidebar update only happens\n * when the edit hits the room's last message — the app router owns the store,\n * resolves that (fresh) and passes it here, same layering as the pinned\n * message. No unread bump, no notifications: v1 parity, an edit is not a new\n * message.\n *\n * The event names no editor: only the author can edit, so the fastening's\n * `from` is the edited message's sender when the room history has it loaded,\n * empty otherwise. The projections read the fastening's value and date, not\n * its `from`.\n */\nexport function handleMessageEdited(\n\t{ bridge }: MessagesDeps,\n\tevent: WireMessageEditedEvent,\n\tlastMessage?: StoreTextMessage\n): void {\n\tconst edited = bridge.getRoomMessages(event.roomId).find((row) => row.id === event.messageId);\n\tbridge.addFastening([\n\t\tbuildEditFastening(\n\t\t\tevent.roomId,\n\t\t\tevent.messageId,\n\t\t\tedited?.from ?? '',\n\t\t\tevent.text,\n\t\t\tevent.editedAt\n\t\t)\n\t]);\n\tif (lastMessage) {\n\t\t// The v1 handler's merge, verbatim: text swapped, edited flagged, the\n\t\t// rest (attachment included) preserved by the spread\n\t\tbridge.setLastMessage(event.roomId, { ...lastMessage, edited: true, text: event.text });\n\t}\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport type { MessagesDeps } from './messages';\nimport { enqueueWrite } from './writeQueue';\nimport { mapWireMessageToStoreMessage } from '../domain/inbox';\nimport type { WireMessageForwardedEvent } from '../types/events';\nimport type { StoreMessage } from '../types/store';\n\nexport type ForwardMessageRef = {\n\t/** The room the message currently lives in. */\n\tsourceRoomId: string;\n\t/** Server id of the message to forward. */\n\tmessageId: string;\n};\n\n/**\n * `POST /rooms/{toRoomId}/forward` — one bulk request per destination room,\n * serialized through that room's FIFO write queue (a forward is a write into\n * the DESTINATION timeline). Forwarding is by reference: the v1 hybrid — one\n * MAM fetch per message to rebuild the original stanza XML, body swapped\n * with the projected text, the serialized XML posted to the legacy endpoint\n * — dissolves entirely.\n *\n * Fire-and-forget on success: the 201 is one `Message` per forward, but with\n * the cloned attachment as a bare `attachmentId` (no name, type or size).\n * The `MessageForwarded` echo carries the full timeline message, so it stays\n * the only store write: a write from the 201 landing after the echo would\n * degrade the attachment to a stub. There is no placeholder to promote —\n * forwards were never optimistic in v1 either. Errors still propagate.\n */\nexport function forwardMessages(\n\t{ http, queue }: MessagesDeps,\n\ttoRoomId: string,\n\tmessages: Array<ForwardMessageRef>\n): Promise<void> {\n\treturn enqueueWrite(queue, toRoomId, async () => {\n\t\tawait http.request(`rooms/${encodeURIComponent(toRoomId)}/forward`, 'POST', { messages });\n\t});\n}\n\n/**\n * `MessageForwarded` push event — the delivery of a forwarded message, the\n * forwarder's own echo included. To the receiving room this IS a new\n * message: the store writes mirror `handleMessageReceived` (append + inbox\n * row) and the me/others split (unread, notifications) stays in the app\n * router, exactly like v1 where a forward landed through the plain message\n * handler. Returns the mapped message for those app-side effects.\n *\n * The event carries the full `TimelineMessage`: `forwardedInfo` becomes the\n * v1 forwarded badge, and the attachment is the server-side clone, which\n * reaches the destination only through this echo.\n */\nexport function handleMessageForwarded(\n\t{ bridge }: MessagesDeps,\n\tevent: WireMessageForwardedEvent\n): StoreMessage {\n\tconst message = mapWireMessageToStoreMessage(event.message);\n\tbridge.newMessage(message);\n\tbridge.setInboxMessages([message]);\n\treturn message;\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport { toTimestamp } from './inbox';\nimport type { PresenceUpdate } from './inbox';\nimport type { WirePresenceStatus } from '../types/api';\n\n/** One `POST /presence/batch` entry -> the same update shape the inbox produces. */\nexport function mapPresenceStatus(status: WirePresenceStatus): PresenceUpdate {\n\treturn {\n\t\tuserId: status.userId,\n\t\tonline: status.online,\n\t\t...(status.lastActivity ? { lastActivity: toTimestamp(status.lastActivity) } : {})\n\t};\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport type { PresenceUpdate } from '../domain/inbox';\nimport { toTimestamp } from '../domain/inbox';\nimport { mapPresenceStatus } from '../domain/presence';\nimport type { HttpClient } from '../http/httpClient';\nimport type { WirePresenceStatus } from '../types/api';\nimport type { StoreBridge } from '../types/bridge';\nimport type { WirePresenceChangedEvent } from '../types/events';\n\nexport type PresenceDeps = {\n\thttp: HttpClient;\n\tbridge: StoreBridge;\n};\n\nconst PRESENCE_BATCH_LIMIT = 100;\n\n/**\n * The one presence write rule, shared by the inbox and batch hydrations: the\n * online flag always lands, and so does the last activity when present. It is\n * the last time the user went offline, returned also while online; the UI\n * shows \"last seen\" only for offline users.\n */\nexport function applyPresenceUpdates(bridge: StoreBridge, updates: Array<PresenceUpdate>): void {\n\tupdates.forEach((update) => {\n\t\tbridge.setUserPresence(update.userId, update.online);\n\t\tif (update.lastActivity !== undefined) {\n\t\t\tbridge.setUserLastActivity(update.userId, update.lastActivity);\n\t\t}\n\t});\n}\n\n/**\n * `POST /presence/batch` — presence + last activity for N users: the v2\n * replacement for the v1 per-contact `jabber:iq:last` queries (the roster\n * boot loop is already covered by `GET /inbox`). The ids are deduplicated and\n * sent in chunks of 100, the backend limit (400 above). A failed chunk does not\n * stop the next ones: the first error is rethrown once every chunk has run.\n */\nexport async function fetchPresence(\n\t{ http, bridge }: PresenceDeps,\n\tuserIds: Array<string>\n): Promise<void> {\n\tconst uniqueIds = [...new Set(userIds)];\n\tconst errors: Array<unknown> = [];\n\tfor (let i = 0; i < uniqueIds.length; i += PRESENCE_BATCH_LIMIT) {\n\t\ttry {\n\t\t\t// eslint-disable-next-line no-await-in-loop\n\t\t\tconst statuses = await http.request<Array<WirePresenceStatus>>('presence/batch', 'POST', {\n\t\t\t\tuserIds: uniqueIds.slice(i, i + PRESENCE_BATCH_LIMIT)\n\t\t\t});\n\t\t\tapplyPresenceUpdates(bridge, (statuses ?? []).map(mapPresenceStatus));\n\t\t} catch (error) {\n\t\t\terrors.push(error);\n\t\t}\n\t}\n\tif (errors.length > 0) {\n\t\tthrow errors[0];\n\t}\n}\n\n/**\n * `PresenceChanged` push event: the online flag lands immediately, together\n * with `lastActivity` (last time the user went offline, sent on both online\n * and offline events, same value as the snapshots) when present. No batch\n * refresh is needed. The backend never sends a user their own presence; the\n * app routers filter it anyway, like in v1 where it never reached the store.\n */\nexport function handlePresenceChanged(\n\t{ bridge }: PresenceDeps,\n\tevent: WirePresenceChangedEvent\n): Promise<void> {\n\tbridge.setUserPresence(event.userId, event.online);\n\tif (event.lastActivity) {\n\t\tbridge.setUserLastActivity(event.userId, toTimestamp(event.lastActivity));\n\t}\n\treturn Promise.resolve();\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\n// Plain string building instead of URLSearchParams: on React Native the URL APIs\n// require a polyfill, and the SDK must stay runtime-agnostic with zero dependencies.\nexport function buildQueryString(\n\tparams: Record<string, string | number | boolean | undefined | null>\n): string {\n\tconst parts: Array<string> = [];\n\tObject.entries(params).forEach(([key, value]) => {\n\t\tif (value !== undefined && value !== null) {\n\t\t\tparts.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);\n\t\t}\n\t});\n\treturn parts.length > 0 ? `?${parts.join('&')}` : '';\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport { applyPresenceUpdates } from './presence';\nimport { mapInboxEntry, mapLastItem } from '../domain/inbox';\nimport type { HttpClient } from '../http/httpClient';\nimport { buildQueryString } from '../http/queryString';\nimport type { WireInboxResponse, WireTimeline } from '../types/api';\nimport type { StoreBridge } from '../types/bridge';\nimport type { WireRoomCreatedEvent } from '../types/events';\nimport type { StoreMessage } from '../types/store';\n\nexport type InboxDeps = {\n\thttp: HttpClient;\n\tbridge: StoreBridge;\n};\n\n/**\n * `GET /inbox` — one round-trip carrying, per room: the last message, the\n * server-side unread count, every member's read marker and presence.\n * Replaces the XMPP boot sequence (XEP-0430 inbox + smart markers + roster).\n *\n * Write order mirrors the v1 flow: last messages first (`setInboxMessages`),\n * then markers (the slice recomputes read statuses), then unread counters,\n * then presence.\n */\nexport async function fetchInbox({ http, bridge }: InboxDeps): Promise<void> {\n\tconst response = await http.request<WireInboxResponse>('inbox', 'GET');\n\tconst entries = (response?.conversations ?? []).map((entry) =>\n\t\tmapInboxEntry(entry, bridge.getRoomMessages(entry.roomId))\n\t);\n\n\tconst lastMessages = entries\n\t\t.map((entry) => entry.lastMessage)\n\t\t.filter((message): message is StoreMessage => message !== undefined);\n\tif (lastMessages.length > 0) {\n\t\tbridge.setInboxMessages(lastMessages);\n\t}\n\n\tentries.forEach((entry) => {\n\t\tif (entry.markers.length > 0) {\n\t\t\tbridge.updateReadStatus(entry.roomId, entry.markers);\n\t\t}\n\t});\n\n\tentries.forEach((entry) => {\n\t\tbridge.setUnreadCount(entry.roomId, entry.unreadCount);\n\t});\n\n\tconst presenceByUser = new Map(\n\t\tentries.flatMap((entry) => entry.presence).map((update) => [update.userId, update])\n\t);\n\tapplyPresenceUpdates(bridge, Array.from(presenceByUser.values()));\n}\n\n/**\n * `RoomCreated` push event: the newest timeline item becomes the new room's\n * last message, the row `GET /inbox` returns as `lastItem` on a reload. The\n * event carries only the room id and the creation lines are not announced, so\n * without it the room would sink to the bottom of the chat list until its\n * first message; v1 got those lines live as XMPP affiliation messages.\n *\n * A row newer than the item, landed live while the request was in flight,\n * keeps its place. The unread count is not touched: creation lines never\n * count as unread.\n */\nexport async function handleRoomCreated(\n\t{ http, bridge }: InboxDeps,\n\tevent: WireRoomCreatedEvent\n): Promise<void> {\n\tconst { roomId } = event;\n\tconst response = await http.request<WireTimeline>(\n\t\t`rooms/${encodeURIComponent(roomId)}/timeline${buildQueryString({ limit: 1 })}`,\n\t\t'GET'\n\t);\n\tconst [newestItem] = response.items ?? [];\n\tconst lastMessage = mapLastItem(newestItem, roomId);\n\tif (!lastMessage) {\n\t\treturn;\n\t}\n\tif (bridge.getRoomMessages(roomId).some((row) => row.date > lastMessage.date)) {\n\t\treturn;\n\t}\n\tbridge.setInboxMessages([lastMessage]);\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport { enqueueWrite } from './writeQueue';\nimport type { WriteQueue } from './writeQueue';\nimport { mapWireMessageToStoreMessage } from '../domain/inbox';\nimport type { HttpClient } from '../http/httpClient';\nimport type { WireMessage } from '../types/api';\nimport type { StoreBridge } from '../types/bridge';\nimport type { WireMessageReceivedEvent } from '../types/events';\nimport type { StoreAttachment, StoreMessage, StoreTextMessage } from '../types/store';\n\nexport type MessagesDeps = {\n\thttp: HttpClient;\n\tbridge: StoreBridge;\n\tqueue: WriteQueue;\n};\n\nexport type SendMessageParams = {\n\troomId: string;\n\ttext: string;\n\t/** Client-generated id: the placeholder's `id` and the self-echo correlation key. */\n\ttempId: string;\n\t/** Server id of the quoted message when this send is a reply. */\n\treplyToId?: string;\n\t/**\n\t * The quoted message, resolved from the store by the façade (the SDK never\n\t * reads the store): keeps the reply section rendered when the REST\n\t * confirmation replaces the hydrated placeholder.\n\t */\n\trepliedMessage?: StoreTextMessage;\n};\n\nexport type ConfirmAttachmentUploadParams = {\n\troomId: string;\n\t/** The placeholder's id, sent as the upload's `tempId` form field. */\n\ttempId: string;\n\t/** The upload's 201: the created `Message`, naming the file only by `attachmentId`. */\n\tresponse: WireMessage;\n\t/** The metadata of the uploaded file, which the 201 does not repeat. */\n\tattachment: Omit<StoreAttachment, 'id'>;\n\t/** The quoted message on a reply, resolved from the store like the send's. */\n\trepliedMessage?: StoreTextMessage;\n};\n\n/**\n * Writes one confirmed message: placeholder out, message in, inbox row\n * updated. Called from BOTH confirmation paths (REST response and\n * `MessageReceived` self-echo): whichever lands first promotes the\n * placeholder, the other is a no-op — `removePlaceholderMessage` on a gone id\n * removes nothing and `newMessage` dedups by id (plan §3).\n */\nfunction confirmMessage(bridge: StoreBridge, tempId: string, confirmed: StoreMessage): void {\n\tbridge.removePlaceholderMessage(confirmed.roomId, tempId);\n\tbridge.newMessage(confirmed);\n\tbridge.setInboxMessages([confirmed]);\n}\n\n/**\n * `POST /rooms/{roomId}/messages` — one outgoing text message, serialized\n * through the per-room FIFO write queue (plan §7.4). The optimistic\n * placeholder is the app's concern (the façade calls the existing\n * `setPlaceholderMessage` before invoking this, like v1 did before sending\n * the stanza).\n *\n * Confirmation is idempotent from both ways (REST response here, self-echo in\n * `handleMessageReceived`). On a definitive send error the placeholder is\n * removed — the v1 stanza just vanished leaving an eternal PENDING; the REST\n * failure is at least observable (plan §3, minimal proposal) — and the error\n * propagates to the façade.\n */\nexport function sendMessage(\n\t{ http, bridge, queue }: MessagesDeps,\n\tparams: SendMessageParams\n): Promise<void> {\n\tconst { roomId, text, tempId, replyToId, repliedMessage } = params;\n\treturn enqueueWrite(queue, roomId, async () => {\n\t\tlet response: WireMessage;\n\t\ttry {\n\t\t\tresponse = await http.request<WireMessage>(\n\t\t\t\t`rooms/${encodeURIComponent(roomId)}/messages`,\n\t\t\t\t'POST',\n\t\t\t\t{ text, tempId, ...(replyToId ? { replyToId } : {}) }\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tbridge.removePlaceholderMessage(roomId, tempId);\n\t\t\tthrow error;\n\t\t}\n\t\tif (response?.id && response.createdAt) {\n\t\t\t// The 201 is the created `Message`, server-authoritative; the room\n\t\t\t// stays the one the placeholder was written under\n\t\t\tconst confirmed = mapWireMessageToStoreMessage({ ...response, roomId });\n\t\t\t// The `Message` DTO embeds no quote: keep the one the façade resolved.\n\t\t\t// Same guard as the mapper's embedded quote: a quoted message without\n\t\t\t// its replyToId must never turn a plain send into a fake reply bubble\n\t\t\tif (confirmed.replyTo && repliedMessage) {\n\t\t\t\tconfirmed.repliedMessage = repliedMessage;\n\t\t\t}\n\t\t\tconfirmMessage(bridge, tempId, confirmed);\n\t\t}\n\t\t// Incomplete 201 (id or createdAt missing): the MessageReceived self-echo\n\t\t// confirms instead. Building a date client-side would risk regressing the\n\t\t// server timestamp when the echo landed first (newMessage assigns in place).\n\t});\n}\n\n/**\n * Confirms an attachment upload from its 201. The apps own the\n * `POST /rooms/{roomId}/attachments` multipart, whose body is\n * platform-specific; the SDK owns the store writes, with the send's\n * idempotent confirmation: whichever of this and the `MessageReceived`\n * self-echo lands first promotes the placeholder. `newMessage` merges in\n * place, so an echo landing second overwrites the attachment with the\n * server's metadata, and one landing first keeps its embedded quote (the 201\n * has none).\n *\n * The 201 names the file only by `attachmentId`: the attachment is the\n * uploaded file's metadata under the server id. Returns the confirmed\n * message, or nothing on an incomplete 201, which leaves the confirmation to\n * the echo like the send's.\n */\nexport function confirmAttachmentUpload(\n\t{ bridge }: MessagesDeps,\n\tparams: ConfirmAttachmentUploadParams\n): StoreMessage | undefined {\n\tconst { roomId, tempId, response, attachment, repliedMessage } = params;\n\tif (!response?.id || !response.createdAt || !response.attachmentId) {\n\t\treturn undefined;\n\t}\n\tconst confirmed = mapWireMessageToStoreMessage({ ...response, roomId });\n\tconfirmed.attachment = { ...attachment, id: response.attachmentId };\n\tif (confirmed.replyTo && repliedMessage) {\n\t\tconfirmed.repliedMessage = repliedMessage;\n\t}\n\tconfirmMessage(bridge, tempId, confirmed);\n\treturn confirmed;\n}\n\n/**\n * `MessageReceived` push event — every message of every sender, own echo\n * included. The SDK performs the store writes shared by all senders; the\n * me/others split (unread counter, custom events, browser notifications)\n * stays in the app router, which owns the session — same layering as the v1\n * handler. Returns the mapped message for those app-side effects.\n *\n * The event carries the full `TimelineMessage`, so it maps like a timeline\n * row: attachment and quote come from the wire, no store lookup (v1 hydrated\n * the quote from the store, with an archive query as fallback).\n *\n * `tempId` promotes the optimistic placeholder. It reaches every member, but\n * only the sender holds a placeholder under that id: for the others the\n * removal is a no-op and the write is a plain append.\n */\nexport function handleMessageReceived(\n\t{ bridge }: MessagesDeps,\n\tevent: WireMessageReceivedEvent\n): StoreMessage {\n\tconst message = mapWireMessageToStoreMessage(event.message);\n\tif (event.tempId) {\n\t\tconfirmMessage(bridge, event.tempId, message);\n\t\treturn message;\n\t}\n\tbridge.newMessage(message);\n\tbridge.setInboxMessages([message]);\n\treturn message;\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport type { StoreConfigurationMessage, StoreMessage } from '../types/store';\n\nexport type PinOperation = 'messagePinned' | 'messageUnpinned';\n\n/**\n * Widest gap between the live pin row and the backend's row for the same\n * change. A pin event carries the `pinnedAt` of the system event, in\n * nanoseconds where the database keeps microseconds, so the two can still\n * round to different milliseconds; an unpin event is stamped `now()` at\n * broadcast, a few ms after the system event's `createdAt` (plan §5.15).\n * Two distinct changes of one message by one user need a round trip of\n * clicks, far wider than this.\n */\nconst SAME_PIN_CHANGE_WINDOW_MS = 5_000;\n\n/**\n * Deterministic on the event fields: double deliveries of one push event\n * dedup in the slice, distinct re-pins of the same message stay distinct.\n */\nexport function pinRowId(operation: PinOperation, messageId: string, date: number): string {\n\tconst prefix = operation === 'messagePinned' ? 'pin' : 'unpin';\n\treturn `${prefix}_${messageId}_${date}`;\n}\n\nfunction isPinRow(\n\trow: StoreMessage\n): row is StoreConfigurationMessage & { operation: PinOperation } {\n\treturn (\n\t\trow.type === 'configuration' &&\n\t\t(row.operation === 'messagePinned' || row.operation === 'messageUnpinned')\n\t);\n}\n\n/** A pin row synthesized from a push event that carried no `systemEventId`. */\nfunction isLivePinRow(row: StoreMessage): boolean {\n\treturn isPinRow(row) && row.id === pinRowId(row.operation, row.value, row.date);\n}\n\n/** Same pin change: same operation, target and actor, dated within the window. */\nfunction isSamePinChange(a: StoreMessage, b: StoreMessage): boolean {\n\treturn (\n\t\tisPinRow(a) &&\n\t\tisPinRow(b) &&\n\t\ta.operation === b.operation &&\n\t\ta.value === b.value &&\n\t\ta.from === b.from &&\n\t\tMath.abs(a.date - b.date) <= SAME_PIN_CHANGE_WINDOW_MS\n\t);\n}\n\n/**\n * The live pin rows in `knownRows` that a timeline page restates under the\n * backend's own id. The backend's row wins: it is the one `PUT /read` accepts\n * and every later history load returns.\n */\nexport function findSupersededLivePinRows(\n\tpageRows: ReadonlyArray<StoreMessage>,\n\tknownRows: ReadonlyArray<StoreMessage>\n): Array<StoreMessage> {\n\tconst serverPinRows = pageRows.filter((row) => isPinRow(row) && !isLivePinRow(row));\n\tif (serverPinRows.length === 0) {\n\t\treturn [];\n\t}\n\treturn knownRows.filter(\n\t\t(row) => isLivePinRow(row) && serverPinRows.some((serverRow) => isSamePinChange(row, serverRow))\n\t);\n}\n\n/**\n * True when the backend's row for this live pin change is already loaded. A\n * live row that carries the backend's id (`systemEventId`) is matched by id:\n * two quick pins by one user are distinct changes.\n */\nexport function hasServerPinRow(\n\tliveRow: StoreMessage,\n\tknownRows: ReadonlyArray<StoreMessage>\n): boolean {\n\tif (!isLivePinRow(liveRow)) {\n\t\treturn knownRows.some((row) => row.id === liveRow.id);\n\t}\n\treturn knownRows.some((row) => !isLivePinRow(row) && isSamePinChange(row, liveRow));\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport type { MessagesDeps } from './messages';\nimport { enqueueWrite } from './writeQueue';\nimport { mapWireMessageToStoreMessage, toTimestamp } from '../domain/inbox';\nimport { hasServerPinRow, pinRowId } from '../domain/pinRows';\nimport type { PinOperation } from '../domain/pinRows';\nimport type { WirePinnedMessage } from '../types/api';\nimport type { WireMessagePinnedEvent, WireMessageUnpinnedEvent } from '../types/events';\nimport type { StoreConfigurationMessage, StoreTextMessage } from '../types/store';\n\n/** Resolves the full pinned message from the caller's store, when loaded. */\nexport type FindPinnedMessage = (messageId: string) => StoreTextMessage | undefined;\n\n/**\n * The v1 \"message pinned/unpinned\" configuration row, synthesized from the\n * push event. In v1 the row was a real MUC broadcast persisted in MAM; in v2\n * the backend persists an equivalent timeline SystemEvent and the push event\n * carries its id (`systemEventId`), which becomes the row id. Without it the\n * synthesized id is deterministic on the event fields (`pinRowId`), and when a\n * timeline page restates the change under the backend's id, the backend's row\n * replaces this one (`timeline.ts`). Dated with the system event's `createdAt`\n * when the event carries it, like the other live lines (`systemLines.ts`).\n */\nfunction buildPinConfigMessage(\n\toperation: PinOperation,\n\troomId: string,\n\tmessageId: string,\n\tfrom: string,\n\ttimestamp: string,\n\tsystemEventId?: string\n): StoreConfigurationMessage {\n\tconst date = toTimestamp(timestamp);\n\treturn {\n\t\tid: systemEventId ?? pinRowId(operation, messageId, date),\n\t\troomId,\n\t\tdate,\n\t\ttype: 'configuration',\n\t\toperation,\n\t\tvalue: messageId,\n\t\tfrom,\n\t\tread: 'read'\n\t};\n}\n\n/**\n * `PUT /rooms/{roomId}/messages/{messageId}/pin` — serialized through the\n * same per-room FIFO write queue as the other message writes. Confirmation is\n * echo-only (the 204 has no body): the store is not touched here, exactly\n * like the v1 pin IQ that only surfaced through the MUC config broadcast.\n */\nexport function pinMessage(\n\t{ http, queue }: MessagesDeps,\n\troomId: string,\n\tmessageId: string\n): Promise<void> {\n\treturn enqueueWrite(queue, roomId, async () => {\n\t\tawait http.request<void>(\n\t\t\t`rooms/${encodeURIComponent(roomId)}/messages/${encodeURIComponent(messageId)}/pin`,\n\t\t\t'PUT'\n\t\t);\n\t});\n}\n\n/**\n * `DELETE /rooms/{roomId}/messages/{messageId}/pin` — echo-only like the PUT.\n * The v1 façade removed the banner optimistically on unpin (and only on\n * unpin): that stays in the app façades, which own the store reads.\n */\nexport function unpinMessage(\n\t{ http, queue }: MessagesDeps,\n\troomId: string,\n\tmessageId: string\n): Promise<void> {\n\treturn enqueueWrite(queue, roomId, async () => {\n\t\tawait http.request<void>(\n\t\t\t`rooms/${encodeURIComponent(roomId)}/messages/${encodeURIComponent(messageId)}/pin`,\n\t\t\t'DELETE'\n\t\t);\n\t});\n}\n\n/**\n * `GET /rooms/{roomId}/pin` — hydrates the room's pinned-message banner (the\n * v2 replacement for the v1 pin IQ + archive-by-id round-trip). The banner\n * prefers the full message resolved from the caller's store (attachment and\n * reply section included); off-window targets fall back to the DTO's\n * `TimelineMessage`, dated with the message's own `createdAt`.\n *\n * The endpoint returns a list; the current pin is the latest by `pinnedAt`\n * (the spike's read, pending the §5.15 answer on PUT replace-vs-accumulate).\n * An empty list CLEARS the banner — a deliberate self-healing improvement\n * over the v1 no-op, which could leave a stale banner after an unpin missed\n * while offline.\n */\nexport async function fetchPinnedMessage(\n\t{ http, bridge }: MessagesDeps,\n\troomId: string,\n\tfindMessage?: FindPinnedMessage\n): Promise<void> {\n\tconst pins = await http.request<Array<WirePinnedMessage>>(\n\t\t`rooms/${encodeURIComponent(roomId)}/pin`,\n\t\t'GET'\n\t);\n\tif (!pins || pins.length === 0) {\n\t\tbridge.removePinnedMessage(roomId);\n\t\treturn;\n\t}\n\tconst latest = pins.reduce((current, pin) =>\n\t\ttoTimestamp(pin.pinnedAt) > toTimestamp(current.pinnedAt) ? pin : current\n\t);\n\tconst resolved = findMessage?.(latest.messageId);\n\tbridge.setPinnedMessage(roomId, resolved ?? mapWireMessageToStoreMessage(latest.message));\n}\n\n/**\n * Lands the live row unless a timeline page already brought the backend's\n * row for the same change (a page fetched while the event was in flight).\n * Either way the row becomes the room's last message in the chat list, like\n * every v1 configuration row.\n */\nfunction landPinRow(bridge: MessagesDeps['bridge'], row: StoreConfigurationMessage): void {\n\tif (!hasServerPinRow(row, bridge.getRoomMessages(row.roomId))) {\n\t\tbridge.newMessage(row);\n\t}\n\tbridge.setInboxMessages([row]);\n}\n\n/**\n * `MessagePinned` push event — every pinner, own echo included (the only\n * confirmation path). Two v1-parity writes: the configuration row lands in\n * the timeline, and the banner is set: with the target the caller resolved\n * from its store, else with the event's own `message`. Returns the row for\n * the router's me/others effects (app events).\n */\nexport function handleMessagePinned(\n\t{ bridge }: MessagesDeps,\n\tevent: WireMessagePinnedEvent,\n\tpinnedMessage?: StoreTextMessage\n): StoreConfigurationMessage {\n\tconst row = buildPinConfigMessage(\n\t\t'messagePinned',\n\t\tevent.roomId,\n\t\tevent.messageId,\n\t\tevent.pinnedBy,\n\t\tevent.systemEventCreatedAt ?? event.timestamp,\n\t\tevent.systemEventId\n\t);\n\tlandPinRow(bridge, row);\n\tbridge.setPinnedMessage(\n\t\tevent.roomId,\n\t\tpinnedMessage ?? mapWireMessageToStoreMessage(event.message)\n\t);\n\treturn row;\n}\n\n/**\n * `MessageUnpinned` push event — configuration row plus banner removal (a\n * no-op for the unpinner, whose façade already removed it optimistically\n * like in v1). The removal is unconditional like the v1 handler. It cannot\n * clear a fresh banner: the backend keeps one pin per room and replaces it\n * with a lone `MessagePinned`, no `MessageUnpinned` for the old one.\n * Returns the row for the router's effects.\n */\nexport function handleMessageUnpinned(\n\t{ bridge }: MessagesDeps,\n\tevent: WireMessageUnpinnedEvent\n): StoreConfigurationMessage {\n\tconst row = buildPinConfigMessage(\n\t\t'messageUnpinned',\n\t\tevent.roomId,\n\t\tevent.messageId,\n\t\tevent.unpinnedBy,\n\t\tevent.systemEventCreatedAt ?? event.timestamp,\n\t\tevent.systemEventId\n\t);\n\tlandPinRow(bridge, row);\n\tbridge.removePinnedMessage(event.roomId);\n\treturn row;\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport type { MessagesDeps } from './messages';\nimport { enqueueWrite } from './writeQueue';\nimport { toTimestamp } from '../domain/inbox';\nimport type { WireReactionChangedEvent } from '../types/events';\nimport type { StoreMessageFastening } from '../types/store';\n\nlet lastReactionInstant = 0;\n\n/**\n * Date of a live reaction fastening: the event's `sentDate`, kept strictly\n * increasing. The projections pick a user's latest reaction BY DATE, so:\n * - the server clock is what orders a live reaction after the history's\n * (the timeline dates those at the message's `createdAt` + 1ms): a client\n * clock running behind could date a live removal before them;\n * - replacing an emoji emits `removed` + `added` back-to-back, which can\n * share a millisecond once parsed, and the mobile reducer breaks date ties\n * in favor of the first fastening: the removal would win. The backend\n * publishes the two in order, so the arrival order breaks the tie.\n * `sentDate` is required on the wire; the client clock only covers a\n * malformed one.\n */\nfunction reactionInstant(sentDate: string): number {\n\tconst sent = toTimestamp(sentDate) || Date.now();\n\tlastReactionInstant = Math.max(sent, lastReactionInstant + 1);\n\treturn lastReactionInstant;\n}\n\nfunction reactionPath(roomId: string, messageId: string, reaction: string): string {\n\tconst room = encodeURIComponent(roomId);\n\tconst message = encodeURIComponent(messageId);\n\t// Multi-codepoint emojis (ZWJ sequences, variation selectors) must travel\n\t// percent-encoded in the path, as the spec mandates\n\treturn `rooms/${room}/messages/${message}/reactions/${encodeURIComponent(reaction)}`;\n}\n\n/**\n * `POST /rooms/{roomId}/messages/{messageId}/reactions/{reaction}` —\n * serialized through the per-room FIFO write queue (plan §7.4). Confirmation\n * is echo-only, like the deletion: the 204 has no body, the store moves on\n * the `ReactionChanged` echo (v1 parity — the reaction stanza confirmed\n * through the MUC echo).\n */\nexport function sendReaction(\n\t{ http, queue }: MessagesDeps,\n\troomId: string,\n\tmessageId: string,\n\treaction: string\n): Promise<void> {\n\treturn enqueueWrite(queue, roomId, async () => {\n\t\tawait http.request<void>(reactionPath(roomId, messageId, reaction), 'POST');\n\t});\n}\n\n/**\n * `DELETE /rooms/{roomId}/messages/{messageId}/reactions/{reaction}` — the\n * caller passes the emoji to remove: v1 removed with an empty-valued\n * reaction stanza, v2 keys the removal on the specific emoji, so the façade\n * resolves the user's current one from the store (the same selector the\n * reaction pickers already read).\n */\nexport function removeReaction(\n\t{ http, queue }: MessagesDeps,\n\troomId: string,\n\tmessageId: string,\n\treaction: string\n): Promise<void> {\n\treturn enqueueWrite(queue, roomId, async () => {\n\t\tawait http.request<void>(reactionPath(roomId, messageId, reaction), 'DELETE');\n\t});\n}\n\n/**\n * `ReactionChanged` push event — every reactor, own echo included (the only\n * confirmation path). Reactions are repeatable toggles, so unlike edits the\n * fastening id embeds the write instant: add -> remove -> add again must\n * produce three distinct fastenings (a deduped id would swallow the re-add),\n * exactly like the v1 stanzas that each carried their own archive id. A\n * removal is a fastening with an empty value: the projection (latest per\n * user by date) reads it as \"no active reaction\" — the v1 semantics\n * verbatim. No unread bump and no sidebar update: v1 parity, the app router\n * owns the me/others effects (animation, browser notification). Returns the\n * fastening for those effects.\n */\nexport function handleReactionChanged(\n\t{ bridge }: MessagesDeps,\n\tevent: WireReactionChangedEvent\n): StoreMessageFastening {\n\tconst date = reactionInstant(event.sentDate);\n\tconst id = `r_${event.messageId}_${event.userId}_${event.reaction}_${date}`;\n\tconst fastening: StoreMessageFastening = {\n\t\tid,\n\t\tstanzaId: id,\n\t\troomId: event.roomId,\n\t\tdate,\n\t\ttype: 'fastening',\n\t\taction: 'reaction',\n\t\toriginalStanzaId: event.messageId,\n\t\tfrom: event.userId,\n\t\tvalue: event.operation === 'added' ? event.reaction : ''\n\t};\n\tbridge.addFastening([fastening]);\n\treturn fastening;\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport { mapWireMarkerToStoreMarker } from '../domain/inbox';\nimport type { HttpClient } from '../http/httpClient';\nimport type { WireReadMarker } from '../types/api';\nimport type { StoreBridge } from '../types/bridge';\nimport type { WireReadUpdatedEvent } from '../types/events';\n\nexport type ReadDeps = {\n\thttp: HttpClient;\n\tbridge: StoreBridge;\n};\n\n/**\n * `PUT /rooms/{roomId}/read` — moves the caller's read marker up to\n * `itemId` (204, no body): a message or a system event id (persisted ids\n * only), whose `createdAt` becomes the marker's `itemCreatedAt`. The server ignores a marker\n * that would move back. The v2 replacement for the XEP-0333 `displayed`\n * groupchat stanza. The v1 guards (message present in store, marker not\n * already past it) stay in the app façades, which own the store; the store\n * write happens when the own `ReadUpdated` echo comes back, like in v1 where\n * the displayed stanza echoed through the MUC.\n */\nexport async function markAsRead(\n\t{ http }: ReadDeps,\n\troomId: string,\n\titemId: string\n): Promise<void> {\n\tawait http.request<unknown>(`rooms/${encodeURIComponent(roomId)}/read`, 'PUT', { itemId });\n}\n\n/**\n * `GET /rooms/{roomId}/read` — every member's read marker in one shot: the v2\n * replacement for the v1 smart-markers IQ (`lastMarkers`), with the markers'\n * ids resolved against the room history in store. No v1 call-site survives\n * on v2 (the post-history round-trip died with the inline timeline markers),\n * so this stays an on-demand tool — e.g. for the reconnection catch-up (plan\n * §4 step 17).\n */\nexport async function fetchRoomReadMarkers(\n\t{ http, bridge }: ReadDeps,\n\troomId: string\n): Promise<void> {\n\tconst markers = await http.request<Array<WireReadMarker>>(\n\t\t`rooms/${encodeURIComponent(roomId)}/read`,\n\t\t'GET'\n\t);\n\tconst rows = bridge.getRoomMessages(roomId);\n\tconst mapped = (markers ?? []).map((marker) => mapWireMarkerToStoreMarker(marker, rows));\n\tif (mapped.length > 0) {\n\t\tbridge.updateReadStatus(roomId, mapped);\n\t}\n}\n\n/**\n * `ReadUpdated` push event. One write for every sender, own echo included:\n * `updateReadStatus` already recomputes both the messages' read statuses (for\n * other members' markers) and the unread counter (for the own marker), so the\n * v1 single-path `onDisplayedMessageStanza` behavior is preserved as-is.\n *\n * The event carries the marker itself, `{userId, itemCreatedAt}`: it maps like\n * the inbox and timeline markers, the id resolved against the room history in\n * store and dated `itemCreatedAt` — the server instant, where v1 stamped the\n * arrival time.\n */\nexport function handleReadUpdated({ bridge }: ReadDeps, event: WireReadUpdatedEvent): void {\n\tbridge.updateReadStatus(event.roomId, [\n\t\tmapWireMarkerToStoreMarker(event, bridge.getRoomMessages(event.roomId))\n\t]);\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport { toTimestamp } from './inbox';\nimport type { WireMessage } from '../types/api';\nimport type { StoreAttachment, StoreTextMessage } from '../types/store';\n\n/**\n * The search DTO carries the attachment as a bare `attachmentId`, without\n * name, type or size: a stub keeps the \"has an attachment\" signal.\n */\nfunction stubSearchAttachment(attachmentId: string): StoreAttachment {\n\treturn { id: attachmentId, name: '', mimeType: 'application/octet-stream', size: 0 };\n}\n\n/**\n * Search result -> store TextMessage.\n *\n * - `deleted` comes from `deletedInfo`; a deleted result maps with an empty\n * text like everywhere else (whether the backend returns deleted messages\n * at all is a smoke-test question, plan §5.17).\n * - `edited` comes from `editedInfo`.\n * - a reply keeps only `replyTo`: the search DTO embeds no quoted message.\n * - reactions and pins are not part of the search DTO: the search panel\n * renders sender/date/text only, and results never enter the room history.\n *\n * Returns undefined for results without an id: unusable downstream (the\n * panel keys on it, the jump targets it).\n */\nexport function mapSearchMessageToStoreMessage(\n\tmessage: WireMessage,\n\troomId: string\n): StoreTextMessage | undefined {\n\tif (!message.id) {\n\t\treturn undefined;\n\t}\n\tconst deleted = message.deletedInfo !== undefined;\n\tconst edited = message.editedInfo !== undefined;\n\treturn {\n\t\tid: message.id,\n\t\tstanzaId: message.id,\n\t\troomId: message.roomId ?? roomId,\n\t\tdate: toTimestamp(message.createdAt),\n\t\ttype: 'text',\n\t\tfrom: message.senderId ?? '',\n\t\ttext: deleted ? '' : (message.text ?? ''),\n\t\tread: 'read',\n\t\t...(deleted ? { deleted: true } : {}),\n\t\t...(edited ? { edited: true } : {}),\n\t\t...(message.replyToId ? { replyTo: message.replyToId } : {}),\n\t\t...(message.attachmentId ? { attachment: stubSearchAttachment(message.attachmentId) } : {})\n\t};\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport { mapSearchMessageToStoreMessage } from '../domain/search';\nimport type { HttpClient } from '../http/httpClient';\nimport { buildQueryString } from '../http/queryString';\nimport type { WireMessageSearchResult } from '../types/api';\nimport type { StoreBridge } from '../types/bridge';\nimport type { StoreTextMessage } from '../types/store';\n\nexport type SearchDeps = {\n\thttp: HttpClient;\n\tbridge: StoreBridge;\n};\n\nexport type SearchMessagesOptions = {\n\t/**\n\t * Return results strictly older than this instant (ms since epoch) — the\n\t * server's pagination cursor. Unused by the apps today (the v1 panel has\n\t * no load-more), exposed for the future one.\n\t */\n\tbefore?: number;\n\t/**\n\t * Drop results strictly before this instant (ms since epoch) — the v1\n\t * MAM `start` bound (`clearedAt ?? createdAt`), inclusive like the\n\t * timeline's. The backend applies the user's `clearedAt` itself (since\n\t * 20656f0a); the client-side bound stays as a second line of defense.\n\t */\n\tnotBefore?: number;\n\t/** Page size; defaults to the spike's search page. */\n\tlimit?: number;\n};\n\nexport type SearchMessagesResult = {\n\tmessages: Array<StoreTextMessage>;\n\t/** More results exist beyond this page (server truth, unaffected by the notBefore filter). */\n\thasMore: boolean;\n};\n\n/** The spike's search page size (the v1 MAM search was server-bounded instead). */\nconst DEFAULT_SEARCH_PAGE_SIZE = 50;\n\n/**\n * `GET /rooms/{roomId}/messages/search` — full-text search within one room,\n * the v2 replacement of the v1 MAM `full-text-search` form. A read, so no\n * write queue. The mapped page REPLACES the room's search results (v1\n * semantics: one shot per submitted query; pagination composition is the\n * future caller's concern, the slice is replace-only).\n *\n * Results are rendered by the search panel only — they never enter the room\n * history, so unmappable entries (no id) are dropped and cleared-history\n * results are filtered by the caller-provided `notBefore` bound.\n */\nexport async function searchMessages(\n\t{ http, bridge }: SearchDeps,\n\troomId: string,\n\tquery: string,\n\toptions: SearchMessagesOptions = {}\n): Promise<SearchMessagesResult> {\n\tconst queryString = buildQueryString({\n\t\tq: query,\n\t\tlimit: options.limit ?? DEFAULT_SEARCH_PAGE_SIZE,\n\t\tbefore: options.before !== undefined ? new Date(options.before).toISOString() : undefined\n\t});\n\tconst response = await http.request<WireMessageSearchResult>(\n\t\t`rooms/${encodeURIComponent(roomId)}/messages/search${queryString}`,\n\t\t'GET'\n\t);\n\n\tconst messages = (response.messages ?? [])\n\t\t.map((message) => mapSearchMessageToStoreMessage(message, roomId))\n\t\t.filter((message): message is StoreTextMessage => message !== undefined)\n\t\t.filter((message) => options.notBefore === undefined || message.date >= options.notBefore);\n\n\tbridge.setSearchResults(roomId, messages);\n\treturn { messages, hasMore: response.hasMore === true };\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport { toTimestamp } from '../domain/inbox';\nimport type { StoreBridge } from '../types/bridge';\nimport type {\n\tWireMeetingDeclinedEvent,\n\tWireMeetingStartedEvent,\n\tWireMeetingStoppedEvent,\n\tWireRoomHistoryClearedEvent,\n\tWireRoomMemberAddedEvent,\n\tWireRoomMemberRemovedEvent,\n\tWireRoomPictureChangedEvent,\n\tWireRoomPictureDeletedEvent,\n\tWireRoomUpdatedEvent\n} from '../types/events';\nimport type { StoreConfigurationMessage, StoreOperationType } from '../types/store';\n\nexport type SystemLinesDeps = {\n\tbridge: StoreBridge;\n};\n\n/**\n * The v1 configuration row of a member or meeting change, synthesized from\n * the push event. In v1 the row was a MUC broadcast; in v2 the backend\n * persists a timeline system event and the push event carries its id, which\n * becomes the row id: a timeline page restating the line replaces this row,\n * and `PUT /read` accepts it. Dated with the system event's `createdAt`\n * (`systemEventCreatedAt`), the instant a read marker on the line gets, like\n * the timeline row. Backends before `66cd8cb8` send only `sentDate`, a few ms\n * later: the line then stays after the own read marker until a timeline page\n * replaces it.\n */\nfunction buildSystemLine(\n\toperation: StoreOperationType,\n\troomId: string,\n\tsystemEventId: string,\n\tfrom: string,\n\tcreatedAt: string,\n\tvalue = ''\n): StoreConfigurationMessage {\n\treturn {\n\t\tid: systemEventId,\n\t\troomId,\n\t\tdate: toTimestamp(createdAt),\n\t\ttype: 'configuration',\n\t\toperation,\n\t\tvalue,\n\t\tfrom,\n\t\tread: 'read'\n\t};\n}\n\nfunction isKnownLine(bridge: StoreBridge, row: StoreConfigurationMessage): boolean {\n\treturn bridge.getRoomMessages(row.roomId).some((known) => known.id === row.id);\n}\n\n/**\n * Like every v1 configuration row, the line lands in the timeline and\n * becomes the room's last message in the chat list. A timeline page fetched\n * while the event was in flight may have brought it already.\n */\nfunction landSystemLine(bridge: StoreBridge, row: StoreConfigurationMessage): void {\n\tif (!isKnownLine(bridge, row)) {\n\t\tbridge.newMessage(row);\n\t}\n\tbridge.setInboxMessages([row]);\n}\n\n/**\n * `RoomMemberAdded` push event: lands the `memberAdded` line, whose value is\n * the added member. Returns the row for the router's me/others effects, or\n * undefined when the event announces no line or the line is already in the\n * room: a bulk add sends one event per member for its single line, which\n * lands with the first event, like the timeline that shows the first added\n * member.\n */\nexport function handleRoomMemberAdded(\n\t{ bridge }: SystemLinesDeps,\n\tevent: WireRoomMemberAddedEvent\n): StoreConfigurationMessage | undefined {\n\tif (!event.systemEventId) {\n\t\treturn undefined;\n\t}\n\tconst row = buildSystemLine(\n\t\t'memberAdded',\n\t\tevent.roomId,\n\t\tevent.systemEventId,\n\t\tevent.addedBy,\n\t\tevent.systemEventCreatedAt ?? event.sentDate,\n\t\tevent.userId\n\t);\n\tif (isKnownLine(bridge, row)) {\n\t\treturn undefined;\n\t}\n\tlandSystemLine(bridge, row);\n\treturn row;\n}\n\n/**\n * `RoomMemberRemoved` push event: lands the `memberRemoved` line, whose value\n * is the removed member. Returns the row, or undefined when the event\n * announces no line (an automatic removal on backends before `ec635ad1`).\n */\nexport function handleRoomMemberRemoved(\n\t{ bridge }: SystemLinesDeps,\n\tevent: WireRoomMemberRemovedEvent\n): StoreConfigurationMessage | undefined {\n\tif (!event.systemEventId || !event.removedBy) {\n\t\treturn undefined;\n\t}\n\tconst row = buildSystemLine(\n\t\t'memberRemoved',\n\t\tevent.roomId,\n\t\tevent.systemEventId,\n\t\tevent.removedBy,\n\t\tevent.systemEventCreatedAt ?? event.sentDate,\n\t\tevent.userId\n\t);\n\tlandSystemLine(bridge, row);\n\treturn row;\n}\n\n/**\n * `RoomUpdated` push event: lands the `roomNameChanged` and\n * `roomDescriptionChanged` lines the update wrote, name first like the\n * backend, valued with the new name and description like the v1 rows.\n * Returns the landed rows, none when the update changed neither field.\n */\nexport function handleRoomUpdated(\n\t{ bridge }: SystemLinesDeps,\n\tevent: WireRoomUpdatedEvent\n): Array<StoreConfigurationMessage> {\n\tconst rows: Array<StoreConfigurationMessage> = [];\n\tif (event.nameSystemEventId) {\n\t\trows.push(\n\t\t\tbuildSystemLine(\n\t\t\t\t'roomNameChanged',\n\t\t\t\tevent.roomId,\n\t\t\t\tevent.nameSystemEventId,\n\t\t\t\tevent.updatedBy,\n\t\t\t\tevent.nameSystemEventCreatedAt ?? event.sentDate,\n\t\t\t\tevent.name\n\t\t\t)\n\t\t);\n\t}\n\tif (event.descriptionSystemEventId) {\n\t\trows.push(\n\t\t\tbuildSystemLine(\n\t\t\t\t'roomDescriptionChanged',\n\t\t\t\tevent.roomId,\n\t\t\t\tevent.descriptionSystemEventId,\n\t\t\t\tevent.updatedBy,\n\t\t\t\tevent.descriptionSystemEventCreatedAt ?? event.sentDate,\n\t\t\t\tevent.description\n\t\t\t)\n\t\t);\n\t}\n\trows.forEach((row) => landSystemLine(bridge, row));\n\treturn rows;\n}\n\n/**\n * `RoomPictureChanged` push event: lands the `roomPictureUpdated` line.\n * Returns the row, or undefined when the event announces no line.\n */\nexport function handleRoomPictureChanged(\n\t{ bridge }: SystemLinesDeps,\n\tevent: WireRoomPictureChangedEvent\n): StoreConfigurationMessage | undefined {\n\tif (!event.systemEventId) {\n\t\treturn undefined;\n\t}\n\tconst row = buildSystemLine(\n\t\t'roomPictureUpdated',\n\t\tevent.roomId,\n\t\tevent.systemEventId,\n\t\tevent.updatedBy,\n\t\tevent.systemEventCreatedAt ?? event.sentDate\n\t);\n\tlandSystemLine(bridge, row);\n\treturn row;\n}\n\n/**\n * `RoomPictureDeleted` push event: lands the `roomPictureDeleted` line.\n * Returns the row, or undefined when the event announces no line.\n */\nexport function handleRoomPictureDeleted(\n\t{ bridge }: SystemLinesDeps,\n\tevent: WireRoomPictureDeletedEvent\n): StoreConfigurationMessage | undefined {\n\tif (!event.systemEventId) {\n\t\treturn undefined;\n\t}\n\tconst row = buildSystemLine(\n\t\t'roomPictureDeleted',\n\t\tevent.roomId,\n\t\tevent.systemEventId,\n\t\tevent.deletedBy,\n\t\tevent.systemEventCreatedAt ?? event.sentDate\n\t);\n\tlandSystemLine(bridge, row);\n\treturn row;\n}\n\n/**\n * `RoomHistoryCleared` push event: lands the `roomHistoryCleared` line of a\n * temporary room cleared for everyone. The app still clears the conversation\n * at `clearedAt`; its v1 clear keeps the newest clear line. Returns the row,\n * or undefined on the per-user clear, which has no line.\n */\nexport function handleRoomHistoryCleared(\n\t{ bridge }: SystemLinesDeps,\n\tevent: WireRoomHistoryClearedEvent\n): StoreConfigurationMessage | undefined {\n\tif (!event.systemEventId || !event.clearedBy) {\n\t\treturn undefined;\n\t}\n\tconst row = buildSystemLine(\n\t\t'roomHistoryCleared',\n\t\tevent.roomId,\n\t\tevent.systemEventId,\n\t\tevent.clearedBy,\n\t\tevent.systemEventCreatedAt ?? event.sentDate\n\t);\n\tlandSystemLine(bridge, row);\n\treturn row;\n}\n\n/**\n * `MeetingStarted` push event: lands the `meetingStarted` line in the\n * meeting's room, which the app resolves from its meetings. Returns the row,\n * or undefined when the room has no line (group meetings).\n */\nexport function handleMeetingStarted(\n\t{ bridge }: SystemLinesDeps,\n\tevent: WireMeetingStartedEvent,\n\troomId: string\n): StoreConfigurationMessage | undefined {\n\tif (!event.systemEventId) {\n\t\treturn undefined;\n\t}\n\tconst row = buildSystemLine(\n\t\t'meetingStarted',\n\t\troomId,\n\t\tevent.systemEventId,\n\t\tevent.starterUser,\n\t\tevent.systemEventCreatedAt ?? event.sentDate\n\t);\n\tlandSystemLine(bridge, row);\n\treturn row;\n}\n\n/**\n * `MeetingStopped` push event: lands the `meetingEnded` line, whose value is\n * the call duration in seconds, as in the system event. The event carries\n * none: it is measured from `startedAt`, the start the app knows, to the\n * event's `sentDate`, so it can exceed the backend's by a second until a\n * timeline page replaces the row. Without `startedAt` the line has no\n * duration. Returns the row, or undefined when the room has no line.\n */\nexport function handleMeetingStopped(\n\t{ bridge }: SystemLinesDeps,\n\tevent: WireMeetingStoppedEvent,\n\troomId: string,\n\tstartedAt?: string\n): StoreConfigurationMessage | undefined {\n\tif (!event.systemEventId) {\n\t\treturn undefined;\n\t}\n\tconst durationSec = startedAt\n\t\t? Math.max(0, Math.floor((toTimestamp(event.sentDate) - toTimestamp(startedAt)) / 1000))\n\t\t: undefined;\n\tconst row = buildSystemLine(\n\t\t'meetingEnded',\n\t\troomId,\n\t\tevent.systemEventId,\n\t\tevent.endedBy,\n\t\tevent.systemEventCreatedAt ?? event.sentDate,\n\t\tdurationSec === undefined ? '' : String(durationSec)\n\t);\n\tlandSystemLine(bridge, row);\n\treturn row;\n}\n\n/**\n * `MeetingDeclined` push event: lands the `meetingDeclined` line, authored by\n * the decliner. Returns the row, or undefined when the room has no line.\n */\nexport function handleMeetingDeclined(\n\t{ bridge }: SystemLinesDeps,\n\tevent: WireMeetingDeclinedEvent,\n\troomId: string\n): StoreConfigurationMessage | undefined {\n\tif (!event.systemEventId) {\n\t\treturn undefined;\n\t}\n\tconst row = buildSystemLine(\n\t\t'meetingDeclined',\n\t\troomId,\n\t\tevent.systemEventId,\n\t\tevent.userId,\n\t\tevent.systemEventCreatedAt ?? event.sentDate\n\t);\n\tlandSystemLine(bridge, row);\n\treturn row;\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport {\n\tmapSystemEventToStoreMessage,\n\tmapWireMarkerToStoreMarker,\n\tmapWireMessageToStoreMessage,\n\ttoTimestamp\n} from './inbox';\nimport type { WireTimeline, WireTimelineItem, WireTimelineMessage } from '../types/api';\nimport type { StoreMarker, StoreMessage, StoreMessageFastening } from '../types/store';\n\nexport type MappedTimelinePage = {\n\t/** Store-ready messages, filtered by the lower bound; the slice orders and dedups. */\n\tmessages: Array<StoreMessage>;\n\t/**\n\t * Reaction fastenings synthesized from the messages' `ReactionGroup[]`\n\t * (current aggregated state, unlike the v1 MAM which carried the stanza\n\t * history). Deterministic ids (`r_{messageId}_{userId}_{emoji}`) keep\n\t * refetches idempotent through the slice dedup; dated 1ms after their\n\t * message so any live fastening (dated now) wins the projection.\n\t */\n\tfastenings: Array<StoreMessageFastening>;\n\tmarkers: Array<StoreMarker>;\n\t/** Raw item count before mapping/filtering: an empty page means the history is over (v1 rule). */\n\titemCount: number;\n\t/**\n\t * True when the page contains items strictly before the lower bound. The v1\n\t * MAM query bounded `start` with `clearedAt ?? createdAt` and XEP-0313 makes\n\t * `start` inclusive, so only items older than that instant are out of range:\n\t * crossing it is the client-side equivalent of the server's `complete` flag.\n\t */\n\treachedLowerBound: boolean;\n\t/**\n\t * Cursor of the oldest raw item in the page, whatever its type: the retry\n\t * anchor when a page maps to zero store messages (see `fetchTimeline`).\n\t * Undefined on empty pages.\n\t */\n\toldestItem?: { date: number; id?: string };\n};\n\nfunction timelineItemId(item: WireTimelineItem): string | undefined {\n\tif (item.itemType === 'message') {\n\t\treturn item.message.id;\n\t}\n\tif (item.itemType === 'system_event') {\n\t\treturn item.systemEvent.id;\n\t}\n\t// Future item types are skipped by the mapper but must still anchor pagination\n\treturn undefined;\n}\n\n/**\n * Fastenings from one message's aggregated reaction state. The projections\n * pick a user's latest reaction by date, so the synthesized instant sits 1ms\n * after the message: deterministic across refetches (the id dedups anyway)\n * and always older than any live `ReactionChanged` fastening, which is what\n * lets the live state win. Assumes one reaction per user per message (the v1\n * model the pickers enforce); the aggregated DTO carries no per-reaction\n * timestamp to order two same-user groups with.\n */\nfunction mapReactionGroupsToFastenings(message: WireTimelineMessage): Array<StoreMessageFastening> {\n\tconst fastenings: Array<StoreMessageFastening> = [];\n\tconst date = toTimestamp(message.createdAt) + 1;\n\t(message.reactions ?? []).forEach((group) => {\n\t\tgroup.userIds.forEach((userId) => {\n\t\t\tconst id = `r_${message.id}_${userId}_${group.reaction}`;\n\t\t\tfastenings.push({\n\t\t\t\tid,\n\t\t\t\tstanzaId: id,\n\t\t\t\troomId: message.roomId,\n\t\t\t\tdate,\n\t\t\t\ttype: 'fastening',\n\t\t\t\taction: 'reaction',\n\t\t\t\toriginalStanzaId: message.id,\n\t\t\t\tfrom: userId,\n\t\t\t\tvalue: group.reaction\n\t\t\t});\n\t\t});\n\t});\n\treturn fastenings;\n}\n\n/**\n * One timeline page -> store writes. Messages and known system events map to\n * the same store shapes the v1 history produced; unknown system event types\n * are skipped. Reactions arrive\n * as aggregated `ReactionGroup[]` on each message and are synthesized into\n * the v1 per-user fastenings — in v1 they traveled as separate MAM stanzas.\n *\n * Markers resolve against `knownRows` (the room history already in store)\n * plus this page: the response repeats the current markers on every page, so\n * an older page alone would anchor a recent marker on its own newest row.\n */\nexport function mapTimelinePage(\n\tpage: WireTimeline,\n\troomId: string,\n\tnotBefore?: number,\n\tknownRows: ReadonlyArray<StoreMessage> = []\n): MappedTimelinePage {\n\tconst items = page.items ?? [];\n\tconst lowerBound = notBefore ?? 0;\n\n\tconst messages: Array<StoreMessage> = [];\n\tconst fastenings: Array<StoreMessageFastening> = [];\n\tlet reachedLowerBound = false;\n\tlet oldestItem: MappedTimelinePage['oldestItem'];\n\titems.forEach((item) => {\n\t\tconst date = toTimestamp(item.createdAt);\n\t\tif (!oldestItem || date < oldestItem.date) {\n\t\t\tconst id = timelineItemId(item);\n\t\t\toldestItem = { date, ...(id !== undefined ? { id } : {}) };\n\t\t}\n\t\t// Strictly before: XEP-0313 `start` is inclusive, so an item exactly at\n\t\t// the bound (e.g. ROOM_CREATED sharing the room's createdAt) stays in.\n\t\tif (lowerBound > 0 && date < lowerBound) {\n\t\t\treachedLowerBound = true;\n\t\t\treturn;\n\t\t}\n\t\tif (item.itemType === 'message') {\n\t\t\tmessages.push(mapWireMessageToStoreMessage(item.message));\n\t\t\tfastenings.push(...mapReactionGroupsToFastenings(item.message));\n\t\t\treturn;\n\t\t}\n\t\tif (item.itemType === 'system_event') {\n\t\t\tconst mapped = mapSystemEventToStoreMessage(item.systemEvent, roomId);\n\t\t\tif (mapped) {\n\t\t\t\tmessages.push(mapped);\n\t\t\t}\n\t\t}\n\t});\n\n\tconst rows = [...knownRows, ...messages];\n\treturn {\n\t\tmessages,\n\t\tfastenings,\n\t\tmarkers: (page.markers ?? []).map((marker) => mapWireMarkerToStoreMarker(marker, rows)),\n\t\titemCount: items.length,\n\t\treachedLowerBound,\n\t\t...(oldestItem ? { oldestItem } : {})\n\t};\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport { findSupersededLivePinRows } from '../domain/pinRows';\nimport { mapTimelinePage } from '../domain/timeline';\nimport type { HttpClient } from '../http/httpClient';\nimport { buildQueryString } from '../http/queryString';\nimport type { WireTimeline } from '../types/api';\nimport type { StoreBridge } from '../types/bridge';\n\nexport type TimelineDeps = {\n\thttp: HttpClient;\n\tbridge: StoreBridge;\n};\n\nexport type FetchTimelineOptions = {\n\t/** Return items strictly older than this instant (ms since epoch) — the v1 MAM `end` bound. */\n\tbefore?: number;\n\t/**\n\t * Id of the message anchoring the page boundary together with `before`: the\n\t * server paginates on the composite cursor (createdAt, id) so messages that\n\t * share the same millisecond are not skipped across pages.\n\t */\n\tbeforeId?: string;\n\t/**\n\t * Drop items strictly before this instant (ms since epoch) and stop\n\t * paginating there — the v1 MAM `start` bound (`clearedAt ?? createdAt` in\n\t * both apps), inclusive per XEP-0313: an item exactly at the bound stays in.\n\t */\n\tnotBefore?: number;\n\t/** Page size; defaults to the v1 MAM quantity. */\n\tlimit?: number;\n};\n\n/** The v1 default MAM page size (`requestHistory(roomId, end, quantity = 50)`). */\nconst DEFAULT_PAGE_SIZE = 50;\n\n/**\n * Parity cap from the v1 mobile fork (`XMPPClient.requestHistoryRange`): a\n * reconnection gap wider than this many pages is abandoned mid-fill — the\n * missing middle heals on the next full history load.\n */\nconst MAX_GAP_PAGES = 20;\n\n/** One mapped page -> store, in the v1 handleHistory write order. */\nfunction writeMappedPage(\n\tbridge: StoreBridge,\n\troomId: string,\n\tpage: ReturnType<typeof mapTimelinePage>\n): void {\n\t// Fastenings first, like the v1 handleHistory write order\n\tif (page.fastenings.length > 0) {\n\t\tbridge.addFastening(page.fastenings);\n\t}\n\tif (page.messages.length > 0) {\n\t\t// A live pin row the page restates gives way to the backend's row: the\n\t\t// reconnection gap-fill pages back over the rows landed before the gap\n\t\tfindSupersededLivePinRows(page.messages, bridge.getRoomMessages(roomId)).forEach((row) => {\n\t\t\tbridge.removePlaceholderMessage(roomId, row.id);\n\t\t});\n\t\tbridge.updateHistory(roomId, page.messages);\n\t}\n\tif (page.markers.length > 0) {\n\t\tbridge.updateReadStatus(roomId, page.markers);\n\t}\n}\n\n/**\n * `GET /rooms/{roomId}/timeline` — one backward history page: messages and\n * system events land in the room history, and the read markers carried by the\n * response replace the v1 post-page `lastMarkers` round-trip.\n *\n * History becomes fully loaded when any of the v1 conditions holds:\n * - the server has nothing older (`hasMoreBefore` false — the MAM `complete` flag),\n * - the page is empty (v1 treated an empty result as a cleared history),\n * - the page crossed the `notBefore` lower bound.\n * On fully loaded the creation message is synthesized exactly like in v1; the\n * slice self-guards, so nothing is added when the backend already delivered\n * `ROOM_CREATED` in the timeline.\n *\n * `hasMoreAfter` is deliberately unused: every consumer paginates backwards —\n * the UI from the live edge, the search-jump walk and the reconnection\n * gap-fill (`fetchTimelineGap`) on the same axis.\n */\nexport async function fetchTimeline(\n\tdeps: TimelineDeps,\n\troomId: string,\n\toptions: FetchTimelineOptions = {}\n): Promise<void> {\n\tconst { http, bridge } = deps;\n\tconst query = buildQueryString({\n\t\tbefore: options.before !== undefined ? new Date(options.before).toISOString() : undefined,\n\t\tbeforeId: options.beforeId,\n\t\tlimit: options.limit ?? DEFAULT_PAGE_SIZE\n\t});\n\tconst response = await http.request<WireTimeline>(\n\t\t`rooms/${encodeURIComponent(roomId)}/timeline${query}`,\n\t\t'GET'\n\t);\n\n\tconst page = mapTimelinePage(response, roomId, options.notBefore, bridge.getRoomMessages(roomId));\n\twriteMappedPage(bridge, roomId, page);\n\n\tconst fullyLoaded =\n\t\tresponse.hasMoreBefore === false || page.itemCount === 0 || page.reachedLowerBound;\n\tif (fullyLoaded) {\n\t\tbridge.setHistoryIsFullyLoaded(roomId);\n\t\tbridge.addCreateRoomMessage(roomId);\n\t\treturn;\n\t}\n\n\t// v1 parity: a page holding only unmappable items (unknown system event\n\t// types today, reactions until the fastenings step) must still advance the\n\t// cursor, otherwise the UI would re-request the same page forever — v1 did\n\t// the same when a MAM page carried only fastenings. Terminates because each\n\t// hop anchors strictly further back in time.\n\tif (page.messages.length === 0 && page.oldestItem) {\n\t\tawait fetchTimeline(deps, roomId, {\n\t\t\t...options,\n\t\t\tbefore: page.oldestItem.date,\n\t\t\t// The caller's beforeId anchored the page just consumed: replace it, or\n\t\t\t// drop it when the oldest item carries no id.\n\t\t\tbeforeId: page.oldestItem.id\n\t\t});\n\t}\n}\n\nexport type FetchTimelineGapOptions = {\n\t/**\n\t * Upper bound of the gap (exclusive, like the plain timeline cursor): pass\n\t * `newestKnown.date + 1` to include the newest known message itself — the\n\t * v1 mobile range query did the same (`end = beforeDate + 1`) and the store\n\t * dedup absorbs the overlap.\n\t */\n\tbefore: number;\n\t/** Composite-cursor id for the upper bound, when it anchors a known message. */\n\tbeforeId?: string;\n\t/**\n\t * Lower bound of the gap: the newest instant already in store, capped by the\n\t * caller with `clearedAt`/`createdAt` like the v1 mobile `effectiveStart`.\n\t * Inclusive per the shared mapper rule (an item exactly at the bound stays).\n\t */\n\tnotBefore: number;\n\t/** Page size; defaults to the v1 MAM quantity. */\n\tlimit?: number;\n};\n\n/**\n * Fill a bounded hole in a room's loaded history — the reconnection catch-up\n * counterpart of the v1 mobile `requestHistoryRange`: page backwards from\n * `before` until the gap closes on `notBefore`, writing messages, fastenings\n * and markers exactly like `fetchTimeline`, but WITHOUT ever touching\n * `setHistoryIsFullyLoaded`/`addCreateRoomMessage` — older history still\n * exists below the gap, those semantics belong to the full-room loader.\n *\n * Stops when the lower bound is crossed, the server has nothing older, the\n * page is empty, the cursor stalls, or after MAX_GAP_PAGES pages (v1 cap): an\n * unfilled remainder heals on the next full history load.\n */\nexport async function fetchTimelineGap(\n\tdeps: TimelineDeps,\n\troomId: string,\n\toptions: FetchTimelineGapOptions\n): Promise<void> {\n\tconst { http, bridge } = deps;\n\tlet { before } = options;\n\tlet { beforeId } = options;\n\tfor (let pageCount = 0; pageCount < MAX_GAP_PAGES; pageCount += 1) {\n\t\t// The cursor reached the bound: the gap is closed — the v1 early exit\n\t\t// (`currentEnd <= effectiveStart`), which also spares the extra request\n\t\t// when a page ends exactly at the bound\n\t\tif (before <= options.notBefore) {\n\t\t\treturn;\n\t\t}\n\t\tconst query = buildQueryString({\n\t\t\tbefore: new Date(before).toISOString(),\n\t\t\tbeforeId,\n\t\t\tlimit: options.limit ?? DEFAULT_PAGE_SIZE\n\t\t});\n\t\t// eslint-disable-next-line no-await-in-loop\n\t\tconst response = await http.request<WireTimeline>(\n\t\t\t`rooms/${encodeURIComponent(roomId)}/timeline${query}`,\n\t\t\t'GET'\n\t\t);\n\n\t\tconst page = mapTimelinePage(\n\t\t\tresponse,\n\t\t\troomId,\n\t\t\toptions.notBefore,\n\t\t\tbridge.getRoomMessages(roomId)\n\t\t);\n\t\twriteMappedPage(bridge, roomId, page);\n\n\t\t// Gap closed (bound crossed), server exhausted, or empty page\n\t\tif (page.reachedLowerBound || response.hasMoreBefore === false || page.itemCount === 0) {\n\t\t\treturn;\n\t\t}\n\t\t// Defensive stall guard: a page that does not move the cursor strictly\n\t\t// backwards would loop forever against a buggy backend\n\t\tif (!page.oldestItem || page.oldestItem.date >= before) {\n\t\t\treturn;\n\t\t}\n\t\tbefore = page.oldestItem.date;\n\t\tbeforeId = page.oldestItem.id;\n\t}\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport type { StoreBridge } from '../types/bridge';\nimport type { WireTypingEvent } from '../types/events';\n\n// The SDK compiles against pure ES libs (no DOM, no Node types — portability\n// by construction): the host timers every target provides (browser, React\n// Native, Node) are ambient-typed here with the minimal shared shape.\ndeclare const setTimeout: (handler: () => void, timeout: number) => unknown;\ndeclare const clearTimeout: (handle: unknown) => void;\n\n/**\n * Safety-net expiry for a typing indicator that never receives its `stopped`\n * (lost event, killed app): the v1 handlers used the same 7s window.\n */\nexport const TYPING_EXPIRE_MS = 7000;\n\n/** One auto-expire timer per (room, user) pair, owned by the client instance. */\nexport type TypingTimers = Map<string, unknown>;\n\nexport function createTypingTimers(): TypingTimers {\n\treturn new Map();\n}\n\nexport type TypingDeps = {\n\tbridge: StoreBridge;\n\ttimers: TypingTimers;\n};\n\n/**\n * `Typing` push event — the only chat traffic the client also SENDS on the\n * socket, but the outbound action stays in the apps (they own the /events\n * WebSocket until plan §4 step 18); the SDK owns the receive path. Anything\n * but `stopped` means `started`, the backend's own normalization. Timers are\n * keyed per (room, user): the v1 web handler shared a single debounce across\n * every pair — two concurrent writers could orphan an indicator — while the\n * v1 mobile fork already tracked pairs; the SDK standardizes on the correct\n * variant. The backend relays the event to everyone but the typist, and the\n * app routers filter the own one anyway (v1 parity).\n */\nexport function handleTyping({ bridge, timers }: TypingDeps, event: WireTypingEvent): void {\n\tconst key = `${event.roomId}:${event.userId}`;\n\tconst existing = timers.get(key);\n\tif (existing) {\n\t\tclearTimeout(existing);\n\t\ttimers.delete(key);\n\t}\n\tconst started = event.status !== 'stopped';\n\tbridge.setIsWriting(event.roomId, event.userId, started);\n\tif (started) {\n\t\ttimers.set(\n\t\t\tkey,\n\t\t\tsetTimeout(() => {\n\t\t\t\ttimers.delete(key);\n\t\t\t\tbridge.setIsWriting(event.roomId, event.userId, false);\n\t\t\t}, TYPING_EXPIRE_MS)\n\t\t);\n\t}\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport { deleteMessage, handleMessageDeleted } from './delete';\nimport { editMessage, handleMessageEdited } from './edit';\nimport type { EditMessageParams } from './edit';\nimport { forwardMessages, handleMessageForwarded } from './forward';\nimport type { ForwardMessageRef } from './forward';\nimport { fetchInbox, handleRoomCreated } from './inbox';\nimport { confirmAttachmentUpload, handleMessageReceived, sendMessage } from './messages';\nimport type { ConfirmAttachmentUploadParams, SendMessageParams } from './messages';\nimport {\n\tfetchPinnedMessage,\n\thandleMessagePinned,\n\thandleMessageUnpinned,\n\tpinMessage,\n\tunpinMessage\n} from './pin';\nimport type { FindPinnedMessage } from './pin';\nimport { fetchPresence, handlePresenceChanged } from './presence';\nimport { handleReactionChanged, removeReaction, sendReaction } from './reactions';\nimport { fetchRoomReadMarkers, handleReadUpdated, markAsRead } from './read';\nimport { searchMessages } from './search';\nimport type { SearchMessagesOptions, SearchMessagesResult } from './search';\nimport {\n\thandleMeetingDeclined,\n\thandleMeetingStarted,\n\thandleMeetingStopped,\n\thandleRoomHistoryCleared,\n\thandleRoomMemberAdded,\n\thandleRoomMemberRemoved,\n\thandleRoomPictureChanged,\n\thandleRoomPictureDeleted,\n\thandleRoomUpdated\n} from './systemLines';\nimport { fetchTimeline, fetchTimelineGap } from './timeline';\nimport type { FetchTimelineGapOptions, FetchTimelineOptions } from './timeline';\nimport { createTypingTimers, handleTyping } from './typing';\nimport { createWriteQueue } from './writeQueue';\nimport type { HttpClient } from '../http/httpClient';\nimport type { StoreBridge } from '../types/bridge';\nimport type {\n\tWireMeetingDeclinedEvent,\n\tWireMeetingStartedEvent,\n\tWireMeetingStoppedEvent,\n\tWireMessageDeletedEvent,\n\tWireMessageEditedEvent,\n\tWireMessageForwardedEvent,\n\tWireMessagePinnedEvent,\n\tWireMessageReceivedEvent,\n\tWireMessageUnpinnedEvent,\n\tWirePresenceChangedEvent,\n\tWireReactionChangedEvent,\n\tWireReadUpdatedEvent,\n\tWireRoomCreatedEvent,\n\tWireRoomHistoryClearedEvent,\n\tWireRoomMemberAddedEvent,\n\tWireRoomMemberRemovedEvent,\n\tWireRoomPictureChangedEvent,\n\tWireRoomPictureDeletedEvent,\n\tWireRoomUpdatedEvent,\n\tWireTypingEvent\n} from '../types/events';\nimport type {\n\tStoreConfigurationMessage,\n\tStoreMessage,\n\tStoreMessageFastening,\n\tStoreTextMessage\n} from '../types/store';\n\nexport type WscClientDeps = {\n\thttp: HttpClient;\n\tbridge: StoreBridge;\n};\n\nexport type WscClient = {\n\t/** `GET /inbox`: hydrates last messages, unread counts, markers and presence. */\n\tfetchInbox: () => Promise<void>;\n\t/** `GET /rooms/{roomId}/timeline`: hydrates one backward history page and its markers. */\n\tfetchTimeline: (roomId: string, options?: FetchTimelineOptions) => Promise<void>;\n\t/**\n\t * Reconnection catch-up: fills a bounded hole in a room's loaded history by\n\t * paging backwards from `before` to `notBefore`, without ever marking the\n\t * history as fully loaded (the v1 mobile `requestHistoryRange` parity).\n\t */\n\tfetchTimelineGap: (roomId: string, options: FetchTimelineGapOptions) => Promise<void>;\n\t/**\n\t * `GET /rooms/{roomId}/messages/search`: full-text search in one room.\n\t * Replaces the room's search results and returns the mapped page with the\n\t * server's `hasMore` (the caller owns pagination composition, if any).\n\t */\n\tsearchMessages: (\n\t\troomId: string,\n\t\tquery: string,\n\t\toptions?: SearchMessagesOptions\n\t) => Promise<SearchMessagesResult>;\n\t/** `POST /presence/batch`: hydrates presence + last activity for N users at once. */\n\tfetchPresence: (userIds: Array<string>) => Promise<void>;\n\t/** `PresenceChanged` push event: online flag now, last activity refresh on offline. */\n\thandlePresenceChanged: (event: WirePresenceChangedEvent) => Promise<void>;\n\t/** `PUT /rooms/{roomId}/read`: moves the caller's read marker up to itemId (message or system event). */\n\tmarkAsRead: (roomId: string, itemId: string) => Promise<void>;\n\t/** `GET /rooms/{roomId}/read`: hydrates every member's read marker for one room. */\n\tfetchRoomReadMarkers: (roomId: string) => Promise<void>;\n\t/**\n\t * `ReadUpdated` push event: one member's marker moved (own echo included),\n\t * resolved against the room history in store like the inbox and timeline\n\t * markers.\n\t */\n\thandleReadUpdated: (event: WireReadUpdatedEvent) => void;\n\t/** `POST /rooms/{roomId}/messages`: one outgoing text, FIFO-serialized per room. */\n\tsendMessage: (params: SendMessageParams) => Promise<void>;\n\t/**\n\t * `MessageReceived` push event: store writes for every sender, the\n\t * placeholder promoted on `tempId`; returns the mapped message. Quote and\n\t * attachment come from the event's `TimelineMessage`.\n\t */\n\thandleMessageReceived: (event: WireMessageReceivedEvent) => StoreMessage;\n\t/**\n\t * Confirms an attachment upload from its 201 (`POST /rooms/{roomId}/attachments`,\n\t * a multipart the app sends): the placeholder promoted like a send's,\n\t * idempotent with the `MessageReceived` echo. Returns the confirmed\n\t * message, nothing on an incomplete 201.\n\t */\n\tconfirmAttachmentUpload: (params: ConfirmAttachmentUploadParams) => StoreMessage | undefined;\n\t/** `PUT /rooms/{roomId}/messages/{messageId}/edit`: FIFO-serialized with the room's sends. */\n\teditMessage: (params: EditMessageParams) => Promise<void>;\n\t/**\n\t * `MessageEdited` push event: synthesizes the EDIT fastening for every\n\t * editor (own echo included), attributed to the edited message's sender\n\t * from the room history. When the edit hits the room's last message the\n\t * app resolves it fresh from its store and passes it here for the sidebar\n\t * update.\n\t */\n\thandleMessageEdited: (event: WireMessageEditedEvent, lastMessage?: StoreTextMessage) => void;\n\t/** `DELETE /rooms/{roomId}/messages/{messageId}`: FIFO-serialized, echo-confirmed (204 has no body). */\n\tdeleteMessage: (roomId: string, messageId: string) => Promise<void>;\n\t/**\n\t * `MessageDeleted` push event: synthesizes the DELETE fastening for every\n\t * deleter (own echo included — the only confirmation path). Same\n\t * lastMessage contract as handleMessageEdited.\n\t */\n\thandleMessageDeleted: (event: WireMessageDeletedEvent, lastMessage?: StoreTextMessage) => void;\n\t/** `POST …/reactions/{reaction}`: FIFO-serialized, echo-confirmed (204 has no body). */\n\tsendReaction: (roomId: string, messageId: string, reaction: string) => Promise<void>;\n\t/**\n\t * `DELETE …/reactions/{reaction}` — the caller passes the emoji to remove\n\t * (v1 removed with an empty value; the façade resolves the current one\n\t * from the store).\n\t */\n\tremoveReaction: (roomId: string, messageId: string, reaction: string) => Promise<void>;\n\t/**\n\t * `ReactionChanged` push event: synthesizes the per-user reaction\n\t * fastening (removals carry an empty value) for every reactor, own echo\n\t * included — the only confirmation path. Returns the fastening for the\n\t * app router's me/others effects (animation, browser notification).\n\t */\n\thandleReactionChanged: (event: WireReactionChangedEvent) => StoreMessageFastening;\n\t/**\n\t * `POST /rooms/{toRoomId}/forward`: one bulk request per destination,\n\t * FIFO-serialized on the destination room. Fire-and-forget: the\n\t * MessageForwarded echo is the only store write.\n\t */\n\tforwardMessages: (toRoomId: string, messages: Array<ForwardMessageRef>) => Promise<void>;\n\t/**\n\t * `MessageForwarded` push event: to the receiving room this is a new\n\t * message — store writes like handleMessageReceived, the me/others split\n\t * stays in the app router. Returns the mapped message for those effects.\n\t */\n\thandleMessageForwarded: (event: WireMessageForwardedEvent) => StoreMessage;\n\t/** `PUT …/messages/{messageId}/pin`: FIFO-serialized, echo-confirmed (204 has no body). */\n\tpinMessage: (roomId: string, messageId: string) => Promise<void>;\n\t/** `DELETE …/messages/{messageId}/pin`: FIFO-serialized, echo-confirmed (204 has no body). */\n\tunpinMessage: (roomId: string, messageId: string) => Promise<void>;\n\t/**\n\t * `GET /rooms/{roomId}/pin`: hydrates the banner with the latest pin —\n\t * the full store message when the caller resolves it, the DTO's\n\t * message otherwise. An empty list clears the banner.\n\t */\n\tfetchPinnedMessage: (roomId: string, findMessage?: FindPinnedMessage) => Promise<void>;\n\t/**\n\t * `MessagePinned` push event: synthesizes the v1 configuration row for\n\t * every pinner (own echo included — the only confirmation path) and sets\n\t * the banner with the target the app resolved from its store, else with the\n\t * event's message. Returns the row for the router's me/others effects.\n\t */\n\thandleMessagePinned: (\n\t\tevent: WireMessagePinnedEvent,\n\t\tpinnedMessage?: StoreTextMessage\n\t) => StoreConfigurationMessage;\n\t/**\n\t * `MessageUnpinned` push event: configuration row plus banner removal\n\t * (idempotent over the unpinner's optimistic remove). Returns the row.\n\t */\n\thandleMessageUnpinned: (event: WireMessageUnpinnedEvent) => StoreConfigurationMessage;\n\t/**\n\t * `RoomCreated` push event: `GET /rooms/{roomId}/timeline` for the newest\n\t * item, which becomes the new room's last message in the chat list.\n\t */\n\thandleRoomCreated: (event: WireRoomCreatedEvent) => Promise<void>;\n\t/**\n\t * `RoomMemberAdded` push event: lands the `memberAdded` line in the\n\t * timeline and the chat list. Returns the row, or undefined when the event\n\t * announces no line or a previous event of the same bulk add landed it.\n\t */\n\thandleRoomMemberAdded: (event: WireRoomMemberAddedEvent) => StoreConfigurationMessage | undefined;\n\t/**\n\t * `RoomMemberRemoved` push event: lands the `memberRemoved` line. Returns\n\t * the row, or undefined when the event announces no line.\n\t */\n\thandleRoomMemberRemoved: (\n\t\tevent: WireRoomMemberRemovedEvent\n\t) => StoreConfigurationMessage | undefined;\n\t/**\n\t * `RoomUpdated` push event: lands the `roomNameChanged` and\n\t * `roomDescriptionChanged` lines the update wrote, name first. Returns the\n\t * rows, none when the update changed neither field. The app still applies\n\t * the new name and description to the room.\n\t */\n\thandleRoomUpdated: (event: WireRoomUpdatedEvent) => Array<StoreConfigurationMessage>;\n\t/**\n\t * `RoomPictureChanged` push event: lands the `roomPictureUpdated` line.\n\t * Returns the row, or undefined when the event announces no line.\n\t */\n\thandleRoomPictureChanged: (\n\t\tevent: WireRoomPictureChangedEvent\n\t) => StoreConfigurationMessage | undefined;\n\t/**\n\t * `RoomPictureDeleted` push event: lands the `roomPictureDeleted` line.\n\t * Returns the row, or undefined when the event announces no line.\n\t */\n\thandleRoomPictureDeleted: (\n\t\tevent: WireRoomPictureDeletedEvent\n\t) => StoreConfigurationMessage | undefined;\n\t/**\n\t * `RoomHistoryCleared` push event: lands the `roomHistoryCleared` line of a\n\t * temporary room cleared for everyone. Returns the row, or undefined on the\n\t * per-user clear. The app still clears the conversation.\n\t */\n\thandleRoomHistoryCleared: (\n\t\tevent: WireRoomHistoryClearedEvent\n\t) => StoreConfigurationMessage | undefined;\n\t/**\n\t * `MeetingStarted` push event: lands the `meetingStarted` line in the\n\t * meeting's room, resolved by the app. Returns the row, or undefined when\n\t * the room has no line (group meetings).\n\t */\n\thandleMeetingStarted: (\n\t\tevent: WireMeetingStartedEvent,\n\t\troomId: string\n\t) => StoreConfigurationMessage | undefined;\n\t/**\n\t * `MeetingStopped` push event: lands the `meetingEnded` line, with the call\n\t * duration measured from the meeting's `startedAt` the app knows. Returns\n\t * the row, or undefined when the room has no line.\n\t */\n\thandleMeetingStopped: (\n\t\tevent: WireMeetingStoppedEvent,\n\t\troomId: string,\n\t\tstartedAt?: string\n\t) => StoreConfigurationMessage | undefined;\n\t/**\n\t * `MeetingDeclined` push event: lands the `meetingDeclined` line. Returns\n\t * the row, or undefined when the room has no line.\n\t */\n\thandleMeetingDeclined: (\n\t\tevent: WireMeetingDeclinedEvent,\n\t\troomId: string\n\t) => StoreConfigurationMessage | undefined;\n\t/**\n\t * `Typing` push event: flips the member's indicator with a 7s auto-expire\n\t * per (room, user). The own echo is filtered by the app routers; the\n\t * outbound action stays app-side (the apps own the socket until step 18).\n\t */\n\thandleTyping: (event: WireTypingEvent) => void;\n};\n\n/**\n * Aggregates the per-API client modules behind a single injected-deps entry\n * point. One method lands per migration step (plan §4).\n */\nexport function createWscClient(deps: WscClientDeps): WscClient {\n\tconst messagesDeps = { ...deps, queue: createWriteQueue() };\n\tconst typingDeps = { bridge: deps.bridge, timers: createTypingTimers() };\n\treturn {\n\t\tfetchInbox: () => fetchInbox(deps),\n\t\tfetchTimeline: (roomId, options) => fetchTimeline(deps, roomId, options),\n\t\tfetchTimelineGap: (roomId, options) => fetchTimelineGap(deps, roomId, options),\n\t\tsearchMessages: (roomId, query, options) => searchMessages(deps, roomId, query, options),\n\t\tfetchPresence: (userIds) => fetchPresence(deps, userIds),\n\t\thandlePresenceChanged: (event) => handlePresenceChanged(deps, event),\n\t\tmarkAsRead: (roomId, itemId) => markAsRead(deps, roomId, itemId),\n\t\tfetchRoomReadMarkers: (roomId) => fetchRoomReadMarkers(deps, roomId),\n\t\thandleReadUpdated: (event) => handleReadUpdated(deps, event),\n\t\tsendMessage: (params) => sendMessage(messagesDeps, params),\n\t\thandleMessageReceived: (event) => handleMessageReceived(messagesDeps, event),\n\t\tconfirmAttachmentUpload: (params) => confirmAttachmentUpload(messagesDeps, params),\n\t\teditMessage: (params) => editMessage(messagesDeps, params),\n\t\thandleMessageEdited: (event, lastMessage) =>\n\t\t\thandleMessageEdited(messagesDeps, event, lastMessage),\n\t\tdeleteMessage: (roomId, messageId) => deleteMessage(messagesDeps, roomId, messageId),\n\t\thandleMessageDeleted: (event, lastMessage) =>\n\t\t\thandleMessageDeleted(messagesDeps, event, lastMessage),\n\t\tsendReaction: (roomId, messageId, reaction) =>\n\t\t\tsendReaction(messagesDeps, roomId, messageId, reaction),\n\t\tremoveReaction: (roomId, messageId, reaction) =>\n\t\t\tremoveReaction(messagesDeps, roomId, messageId, reaction),\n\t\thandleReactionChanged: (event) => handleReactionChanged(messagesDeps, event),\n\t\tforwardMessages: (toRoomId, messages) => forwardMessages(messagesDeps, toRoomId, messages),\n\t\thandleMessageForwarded: (event) => handleMessageForwarded(messagesDeps, event),\n\t\tpinMessage: (roomId, messageId) => pinMessage(messagesDeps, roomId, messageId),\n\t\tunpinMessage: (roomId, messageId) => unpinMessage(messagesDeps, roomId, messageId),\n\t\tfetchPinnedMessage: (roomId, findMessage) =>\n\t\t\tfetchPinnedMessage(messagesDeps, roomId, findMessage),\n\t\thandleMessagePinned: (event, pinnedMessage) =>\n\t\t\thandleMessagePinned(messagesDeps, event, pinnedMessage),\n\t\thandleMessageUnpinned: (event) => handleMessageUnpinned(messagesDeps, event),\n\t\thandleRoomCreated: (event) => handleRoomCreated(deps, event),\n\t\thandleRoomMemberAdded: (event) => handleRoomMemberAdded(deps, event),\n\t\thandleRoomMemberRemoved: (event) => handleRoomMemberRemoved(deps, event),\n\t\thandleRoomUpdated: (event) => handleRoomUpdated(deps, event),\n\t\thandleRoomPictureChanged: (event) => handleRoomPictureChanged(deps, event),\n\t\thandleRoomPictureDeleted: (event) => handleRoomPictureDeleted(deps, event),\n\t\thandleRoomHistoryCleared: (event) => handleRoomHistoryCleared(deps, event),\n\t\thandleMeetingStarted: (event, roomId) => handleMeetingStarted(deps, event, roomId),\n\t\thandleMeetingStopped: (event, roomId, startedAt) =>\n\t\t\thandleMeetingStopped(deps, event, roomId, startedAt),\n\t\thandleMeetingDeclined: (event, roomId) => handleMeetingDeclined(deps, event, roomId),\n\t\thandleTyping: (event) => handleTyping(typingDeps, event)\n\t};\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nexport class WscApiError extends Error {\n\tpublic readonly status: number;\n\n\tpublic readonly endpoint: string;\n\n\tpublic constructor(status: number, endpoint: string) {\n\t\tsuper(`WSC API error ${status} on ${endpoint}`);\n\t\tthis.name = 'WscApiError';\n\t\tthis.status = status;\n\t\tthis.endpoint = endpoint;\n\t}\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport { WscApiError } from './errors';\nimport type { HttpMethod, HttpPorts } from '../types/ports';\n\nexport const WSC_API_VERSION_HEADER = 'X-WSC-API-VERSION';\nconst CONTENT_TYPE_HEADER = 'Content-Type';\nconst MAX_VERSION_MISMATCH_RETRIES = 3;\n\nexport type JsonBody = Record<string, unknown> | Array<unknown>;\n\nexport type HttpClient = {\n\trequest: <T>(endpoint: string, method: HttpMethod, body?: JsonBody) => Promise<T>;\n};\n\n/**\n * Joins base and endpoint tolerating any slash combination, so the `baseUrl`\n * port contract is \"any well-formed prefix\" rather than \"must end with `/`\".\n */\nfunction joinUrl(baseUrl: string, endpoint: string): string {\n\treturn `${baseUrl.replace(/\\/+$/, '')}/${endpoint.replace(/^\\/+/, '')}`;\n}\n\n/**\n * REST core shared by web and mobile. Reproduces the semantics of the two\n * existing `FetchUtils.ts` (unified — the mobile copy never incremented the\n * 422 retry counter) on top of injected ports:\n *\n * - stamps `X-WSC-API-VERSION` with the client's negotiated version;\n * - on 422, adopts the server version when it is supported and retries\n * (bounded), mirroring the in-production renegotiation;\n * - decodes JSON / image blobs, returns the raw response otherwise.\n */\nexport function createHttpClient(ports: HttpPorts): HttpClient {\n\tasync function doRequest<T>(\n\t\tendpoint: string,\n\t\tmethod: HttpMethod,\n\t\tbody: JsonBody | undefined,\n\t\tversionRetries: number,\n\t\tauthRetried: boolean\n\t): Promise<T> {\n\t\tconst headers: Record<string, string> = { ...ports.getExtraHeaders?.() };\n\t\tconst clientVersion = ports.versionStore.getApiVersion();\n\t\tif (clientVersion) {\n\t\t\theaders[WSC_API_VERSION_HEADER] = clientVersion;\n\t\t}\n\t\tconst hasBody = body !== undefined;\n\t\tif (hasBody) {\n\t\t\theaders[CONTENT_TYPE_HEADER] = 'application/json';\n\t\t}\n\n\t\tconst baseUrl = typeof ports.baseUrl === 'function' ? ports.baseUrl() : ports.baseUrl;\n\t\tconst response = await ports.fetch(joinUrl(baseUrl, endpoint), {\n\t\t\tmethod,\n\t\t\theaders,\n\t\t\t...(hasBody ? { body: JSON.stringify(body) } : {})\n\t\t});\n\n\t\tconst serverVersion = response.headers.get(WSC_API_VERSION_HEADER);\n\t\tif (serverVersion) {\n\t\t\tports.onServerVersion?.(serverVersion);\n\t\t}\n\n\t\tif (!response.ok) {\n\t\t\tif (\n\t\t\t\tresponse.status === 422 &&\n\t\t\t\t!!serverVersion &&\n\t\t\t\tserverVersion !== clientVersion &&\n\t\t\t\tports.versionStore.getSupportedVersions().includes(serverVersion) &&\n\t\t\t\tversionRetries < MAX_VERSION_MISMATCH_RETRIES\n\t\t\t) {\n\t\t\t\tports.logger?.warn(\n\t\t\t\t\t`WSC API version mismatch on ${endpoint}: adopting server version ${serverVersion} (was ${clientVersion ?? 'unset'})`\n\t\t\t\t);\n\t\t\t\tports.versionStore.setApiVersion(serverVersion);\n\t\t\t\treturn doRequest(endpoint, method, body, versionRetries + 1, authRetried);\n\t\t\t}\n\t\t\tif (response.status === 401 && !authRetried && ports.onUnauthorized) {\n\t\t\t\tconst shouldRetry = await ports.onUnauthorized();\n\t\t\t\tif (shouldRetry) {\n\t\t\t\t\treturn doRequest(endpoint, method, body, versionRetries, true);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow new WscApiError(response.status, endpoint);\n\t\t}\n\n\t\tconst contentType = response.headers.get(CONTENT_TYPE_HEADER);\n\t\tif (contentType?.includes('application/json')) {\n\t\t\treturn response.json() as Promise<T>;\n\t\t}\n\t\tif (contentType?.includes('image/')) {\n\t\t\treturn response.blob() as Promise<T>;\n\t\t}\n\t\treturn response as T;\n\t}\n\n\treturn {\n\t\trequest: <T>(endpoint: string, method: HttpMethod, body?: JsonBody): Promise<T> =>\n\t\t\tdoRequest(endpoint, method, body, 0, false)\n\t};\n}\n"],"mappings":";AAcO,SAAS,mBAA+B;AAC9C,SAAO,oBAAI,IAAI;AAChB;AAOO,SAAS,aACf,OACA,QACA,MACa;AACb,QAAM,WAAW,MAAM,IAAI,MAAM,KAAK,QAAQ,QAAQ;AACtD,QAAM,MAAM,SAAS,KAAK,MAAM,IAAI;AACpC,QAAM,OAAO,IAAI;AAAA,IAChB,MAAM;AAAA,IACN,MAAM;AAAA,EACP;AACA,QAAM,IAAI,QAAQ,IAAI;AACtB,OAAK,KAAK,MAAM;AACf,QAAI,MAAM,IAAI,MAAM,MAAM,MAAM;AAC/B,YAAM,OAAO,MAAM;AAAA,IACpB;AAAA,EACD,CAAC;AACD,SAAO;AACR;;;ACJO,SAAS,YAAY,MAA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AACA,cAAM,aAAa,cAAc,aAAa;AAC9C,eAAO,UAAU,UAAU,QAAQ,MAAM,iBAAiB,GAAG,WAAW;AAAA,MACzE;AACA,UAAI,SAAS,WAAW,OAAO,CAAC,eAAe,MAAM,gBAAgB;AACpE,cAAM,cAAc,MAAM,MAAM,eAAe;AAC/C,YAAI,aAAa;AAChB,iBAAO,UAAU,UAAU,QAAQ,MAAM,gBAAgB,IAAI;AAAA,QAC9D;AAAA,MACD;AACA,YAAM,IAAI,YAAY,SAAS,QAAQ,QAAQ;AAAA,IAChD;AAEA,UAAM,cAAc,SAAS,QAAQ,IAAI,mBAAmB;AAC5D,QAAI,aAAa,SAAS,kBAAkB,GAAG;AAC9C,aAAO,SAAS,KAAK;AAAA,IACtB;AACA,QAAI,aAAa,SAAS,QAAQ,GAAG;AACpC,aAAO,SAAS,KAAK;AAAA,IACtB;AACA,WAAO;AAAA,EACR;AAEA,SAAO;AAAA,IACN,SAAS,CAAI,UAAkB,QAAoB,SAClD,UAAU,UAAU,QAAQ,MAAM,GAAG,KAAK;AAAA,EAC5C;AACD;","names":[]}
1
+ {"version":3,"sources":["../src/client/writeQueue.ts","../src/domain/time.ts","../src/domain/inbox.ts","../src/client/delete.ts","../src/client/edit.ts","../src/client/forward.ts","../src/domain/presence.ts","../src/client/presence.ts","../src/client/systemLines.ts","../src/http/queryString.ts","../src/client/inbox.ts","../src/client/messages.ts","../src/domain/pinRows.ts","../src/client/pin.ts","../src/client/reactions.ts","../src/client/read.ts","../src/domain/search.ts","../src/client/search.ts","../src/domain/timeline.ts","../src/client/timeline.ts","../src/client/typing.ts","../src/client/createClient.ts","../src/http/errors.ts","../src/http/httpClient.ts"],"sourcesContent":["/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\n/**\n * Per-room FIFO queue for REST writes (send/edit/delete/forward). XMPP\n * serialized outgoing stanzas implicitly on its single stream; concurrent\n * fetches can instead complete out of order and swap two sends (plan §7.4).\n * One queue instance lives per client, one chain per room.\n */\nexport type WriteQueue = Map<string, Promise<unknown>>;\n\nexport function createWriteQueue(): WriteQueue {\n\treturn new Map();\n}\n\n/**\n * Chains `task` after the room's pending writes. A failed task rejects its own\n * caller but never poisons the chain: the next write still runs. The room\n * entry is dropped once the chain drains, so idle rooms do not leak.\n */\nexport function enqueueWrite<T>(\n\tqueue: WriteQueue,\n\troomId: string,\n\ttask: () => Promise<T>\n): Promise<T> {\n\tconst previous = queue.get(roomId) ?? Promise.resolve();\n\tconst run = previous.then(task, task);\n\tconst tail = run.then(\n\t\t() => undefined,\n\t\t() => undefined\n\t);\n\tqueue.set(roomId, tail);\n\ttail.then(() => {\n\t\tif (queue.get(roomId) === tail) {\n\t\t\tqueue.delete(roomId);\n\t\t}\n\t});\n\treturn run;\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nconst ISO_WITH_FRACTION = /^(.*T\\d{2}:\\d{2}:\\d{2})\\.(\\d+)(.*)$/;\n\nexport function parseIsoMicros(iso: string | undefined): number {\n\tif (!iso) {\n\t\treturn 0;\n\t}\n\tconst match = ISO_WITH_FRACTION.exec(iso);\n\tif (!match) {\n\t\tconst parsed = Date.parse(iso);\n\t\treturn Number.isNaN(parsed) ? 0 : parsed;\n\t}\n\tconst [, head, fraction = '', tail] = match;\n\tconst digits = fraction.slice(0, 6).padEnd(6, '0');\n\tconst parsed = Date.parse(`${head}.${digits.slice(0, 3)}${tail}`);\n\treturn Number.isNaN(parsed) ? 0 : parsed + Number(digits.slice(3)) / 1000;\n}\n\nexport function toIsoMicros(ms: number): string {\n\tlet wholeMs = Math.floor(ms);\n\tlet micros = Math.round((ms - wholeMs) * 1000);\n\tif (micros >= 1000) {\n\t\twholeMs += 1;\n\t\tmicros -= 1000;\n\t}\n\treturn `${new Date(wholeMs).toISOString().slice(0, -1)}${String(micros).padStart(3, '0')}Z`;\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport { parseIsoMicros } from './time';\nimport type {\n\tWireInboxEntry,\n\tWireReadMarker,\n\tWireSystemEvent,\n\tWireTimelineItem,\n\tWireTimelineMessage\n} from '../types/api';\nimport type {\n\tStoreAttachment,\n\tStoreConfigurationMessage,\n\tStoreMarker,\n\tStoreMessage,\n\tStoreOperationType,\n\tStoreTextMessage\n} from '../types/store';\n\nexport type PresenceUpdate = {\n\tuserId: string;\n\tonline: boolean;\n\t/** Milliseconds since epoch: the last time the user went offline, absent when never offline; also present while online. */\n\tlastActivity?: number;\n};\n\nexport type MappedInboxEntry = {\n\troomId: string;\n\tlastMessage?: StoreMessage;\n\tmarkers: Array<StoreMarker>;\n\tunreadCount: number;\n\tpresence: Array<PresenceUpdate>;\n};\n\nexport function toTimestamp(date: string | undefined): number {\n\treturn parseIsoMicros(date);\n}\n\n/**\n * Wire attachment -> store attachment. `area` (the image layout hint the\n * sender declared on upload) is nullable on the timeline and events, and\n * absent as a key on the inbox when null: only a non-empty value is kept.\n */\nfunction mapWireAttachment(\n\tattachment: NonNullable<WireTimelineMessage['attachment']>\n): StoreAttachment {\n\tconst { id, name, mimeType, size, area } = attachment;\n\treturn { id, name, mimeType, size, ...(area ? { area } : {}) };\n}\n\n/**\n * Wire message -> store TextMessage, preserving the dual-id invariant with\n * `id = stanzaId = server UUID`. Deleted/edited messages arrive already\n * materialized (`deletedInfo`/`editedInfo`), so they map to the legacy\n * booleans the store and the UI understand — no fastening machinery needed\n * on the inbox path.\n *\n * `withQuote` maps the embedded `repliedMessage` through this same mapper,\n * once: the quote is depth-1 by contract, so its own `repliedMessage` (never\n * sent) is ignored.\n */\nfunction mapMessage(message: WireTimelineMessage, withQuote: boolean): StoreTextMessage {\n\tconst deleted = message.deletedInfo !== undefined;\n\treturn {\n\t\tid: message.id,\n\t\tstanzaId: message.id,\n\t\troomId: message.roomId,\n\t\tdate: toTimestamp(message.createdAt),\n\t\ttype: 'text',\n\t\tfrom: message.senderId,\n\t\ttext: deleted ? '' : message.text,\n\t\tread: 'unread',\n\t\t...(deleted ? { deleted: true } : {}),\n\t\t...(message.editedInfo ? { edited: true } : {}),\n\t\t...(message.replyToId ? { replyTo: message.replyToId } : {}),\n\t\t// A quote without its replyToId must never turn a plain message into a\n\t\t// reply bubble (same guard as the façade-resolved quotes)\n\t\t...(withQuote && message.replyToId && message.repliedMessage\n\t\t\t? { repliedMessage: mapMessage(message.repliedMessage, false) }\n\t\t\t: {}),\n\t\t// A forward of an own message reads as a plain message, as the v1 clients decoded it\n\t\t...(message.forwardedInfo && message.forwardedInfo.originalSenderId !== message.senderId\n\t\t\t? {\n\t\t\t\t\tforwarded: {\n\t\t\t\t\t\t// v2 dropped the archive id and the forward counter (open question\n\t\t\t\t\t\t// §5.7 of the plan); map best-effort onto the legacy shape.\n\t\t\t\t\t\tid: '',\n\t\t\t\t\t\tdate: toTimestamp(message.forwardedInfo.originalSentAt),\n\t\t\t\t\t\tfrom: message.forwardedInfo.originalSenderId,\n\t\t\t\t\t\tcount: 1\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t: {}),\n\t\t...(message.attachment ? { attachment: mapWireAttachment(message.attachment) } : {})\n\t};\n}\n\n/**\n * Wire message -> store TextMessage. On a reply the embedded `repliedMessage`\n * becomes the quoted TextMessage the bubble's reply section renders — in v1\n * that hydration cost an archive query per reply not already in store. When\n * the original is not visible to the caller (cleared, pre-join, removed) the\n * wire carries only `replyToId`: the message keeps `replyTo` and no quote,\n * and the reply section does not render.\n */\nexport function mapWireMessageToStoreMessage(message: WireTimelineMessage): StoreTextMessage {\n\treturn mapMessage(message, true);\n}\n\nconst SYSTEM_EVENT_TO_OPERATION: Record<string, StoreOperationType> = {\n\tROOM_CREATED: 'roomCreation',\n\tROOM_NAME_CHANGED: 'roomNameChanged',\n\tROOM_DESCRIPTION_CHANGED: 'roomDescriptionChanged',\n\tROOM_PICTURE_UPDATED: 'roomPictureUpdated',\n\tROOM_PICTURE_DELETED: 'roomPictureDeleted',\n\tROOM_HISTORY_CLEARED: 'roomHistoryCleared',\n\tMEMBER_ADDED: 'memberAdded',\n\tMEMBER_REMOVED: 'memberRemoved',\n\tMESSAGE_PINNED: 'messagePinned',\n\tMESSAGE_UNPINNED: 'messageUnpinned',\n\tMEETING_STARTED: 'meetingStarted',\n\tMEETING_ENDED: 'meetingEnded',\n\tMEETING_DECLINED: 'meetingDeclined'\n};\n\n/**\n * Value extraction per system event type. Field names validated against\n * the backend implementation (frontend spike, plan §7.2) — the event catalog\n * is not in asyncapi.yaml yet. The author is `actorId`, not part of `content`.\n */\nfunction extractValue(type: string, content: Record<string, unknown> | undefined): string {\n\tconst str = (key: string): string => {\n\t\tconst raw = content?.[key];\n\t\treturn typeof raw === 'string' ? raw : '';\n\t};\n\tswitch (type) {\n\t\t// The new name or description, the v1 row value; an empty description is a removal\n\t\tcase 'ROOM_NAME_CHANGED':\n\t\t\treturn str('name');\n\t\tcase 'ROOM_DESCRIPTION_CHANGED':\n\t\t\treturn str('description');\n\t\tcase 'MEMBER_ADDED': {\n\t\t\tconst added = content?.addedUserIds;\n\t\t\treturn Array.isArray(added) && typeof added[0] === 'string' ? added[0] : '';\n\t\t}\n\t\tcase 'MEMBER_REMOVED':\n\t\t\treturn str('removedUserId');\n\t\tcase 'MESSAGE_PINNED':\n\t\tcase 'MESSAGE_UNPINNED':\n\t\t\treturn str('messageId');\n\t\tcase 'MEETING_ENDED': {\n\t\t\t// The call duration in seconds, the v1 row value the \"Call ended\" line shows\n\t\t\tconst duration = content?.durationSec;\n\t\t\treturn typeof duration === 'number' ? String(duration) : '';\n\t\t}\n\t\tdefault:\n\t\t\treturn '';\n\t}\n}\n\nexport function mapSystemEventToStoreMessage(\n\tevent: WireSystemEvent,\n\troomId: string\n): StoreConfigurationMessage | undefined {\n\tconst operation = SYSTEM_EVENT_TO_OPERATION[event.type];\n\tif (!operation) {\n\t\treturn undefined;\n\t}\n\tconst value = extractValue(event.type, event.content);\n\treturn {\n\t\tid: event.id,\n\t\troomId,\n\t\tdate: toTimestamp(event.createdAt),\n\t\ttype: 'configuration',\n\t\toperation,\n\t\tvalue,\n\t\tfrom: event.actorId,\n\t\tread: 'read'\n\t};\n}\n\n/**\n * Id of the history row a v2 read marker lands on: the newest row dated at or\n * before `itemCreatedAt`.\n *\n * The backend stamps `itemCreatedAt` with the `createdAt` of the item marked\n * through `PUT /read` (message or system event) and never moves it back, so\n * the match is normally exact — hence the inclusive bound. When the marked\n * item is not a row (a system event type the mapper skips) the marker lands\n * on the row just before it, which every consumer reads the same way: the\n * apps compare dates, and no row sits between the two.\n *\n * Only rows that stay in the history qualify: text and configuration rows,\n * not optimistic placeholders (replaced on confirmation by a row with another\n * id, which would leave the marker dangling). Same-instant rows resolve to\n * the last one in input order, so both count as read.\n *\n * Returns '' when no row qualifies (marker older than the loaded history, or\n * nothing loaded yet): every consumer then falls back to `markerDate`, like a\n * v1 marker pointing outside the loaded history.\n */\nexport function resolveMarkedMessageId(\n\titemCreatedAt: number,\n\trows: ReadonlyArray<StoreMessage>\n): string {\n\tlet marked: StoreMessage | undefined;\n\trows.forEach((row) => {\n\t\tif (row.type !== 'text' && row.type !== 'configuration') {\n\t\t\treturn;\n\t\t}\n\t\tif (row.read === 'pending' || row.date > itemCreatedAt) {\n\t\t\treturn;\n\t\t}\n\t\tif (!marked || row.date >= marked.date) {\n\t\t\tmarked = row;\n\t\t}\n\t});\n\treturn marked?.id ?? '';\n}\n\n/**\n * v2 read marker -> store marker, without changing the store shape: the wire\n * carries only `{userId, itemCreatedAt}` while the store consumers key on a\n * message id. `markerDate` is `itemCreatedAt` itself — the instant the consumers\n * fall back to when the id is not in store — and `messageId` is resolved\n * against `rows`, the room history the marker will be read against.\n */\nexport function mapWireMarkerToStoreMarker(\n\tmarker: WireReadMarker,\n\trows: ReadonlyArray<StoreMessage>\n): StoreMarker {\n\tconst itemCreatedAt = toTimestamp(marker.itemCreatedAt);\n\treturn {\n\t\tfrom: marker.userId,\n\t\tmessageId: resolveMarkedMessageId(itemCreatedAt, rows),\n\t\tmarkerDate: itemCreatedAt,\n\t\ttype: 'displayed'\n\t};\n}\n\n/**\n * Timeline item -> the room's last message in the chat list: a message, or a\n * system event mapped to a configuration row; undefined for a system event\n * type the mapper skips.\n */\nexport function mapLastItem(\n\titem: WireTimelineItem | undefined,\n\troomId: string\n): StoreMessage | undefined {\n\tif (item?.itemType === 'message') {\n\t\treturn mapWireMessageToStoreMessage(item.message);\n\t}\n\tif (item?.itemType === 'system_event') {\n\t\treturn mapSystemEventToStoreMessage(item.systemEvent, roomId);\n\t}\n\treturn undefined;\n}\n\n/**\n * Maps one inbox entry to its store writes. Mirrors the v1 inbox semantics:\n * - `lastItem` becomes the room's last message: a message, or a system event\n * mapped to a configuration row like in the v1 XMPP inbox; a room without\n * visible items has none;\n * - a last message at or before the user's `clearedAt` is dropped (the v1\n * handler applies the same filter on the XMPP inbox result);\n * - members' presence is extracted from the inbox room (v2 replaces the\n * roster/last-activity XMPP queries).\n *\n * Markers resolve against `knownRows` (the room history already in store)\n * plus the last message: until the timeline loads, the last message is the\n * only row the inbox knows, and the most common target of a marker.\n */\nexport function mapInboxEntry(\n\tentry: WireInboxEntry,\n\tknownRows: ReadonlyArray<StoreMessage> = []\n): MappedInboxEntry {\n\tconst clearedAt = toTimestamp(entry.room.userSettings?.clearedAt);\n\n\tlet lastMessage = mapLastItem(entry.lastItem, entry.roomId);\n\tif (lastMessage && clearedAt > 0 && lastMessage.date <= clearedAt) {\n\t\tlastMessage = undefined;\n\t}\n\n\tconst rows = lastMessage ? [...knownRows, lastMessage] : knownRows;\n\tconst presence: Array<PresenceUpdate> = (entry.room.members ?? []).map((member) => ({\n\t\tuserId: member.userId,\n\t\tonline: member.online,\n\t\t...(member.lastActivity ? { lastActivity: toTimestamp(member.lastActivity) } : {})\n\t}));\n\n\treturn {\n\t\troomId: entry.roomId,\n\t\tlastMessage,\n\t\tmarkers: (entry.markers ?? []).map((marker) => mapWireMarkerToStoreMarker(marker, rows)),\n\t\tunreadCount: entry.unreadCount,\n\t\tpresence\n\t};\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport type { MessagesDeps } from './messages';\nimport { enqueueWrite } from './writeQueue';\nimport { toTimestamp } from '../domain/inbox';\nimport type { WireMessageDeletedEvent } from '../types/events';\nimport type { StoreMessageFastening, StoreTextMessage } from '../types/store';\n\n/**\n * The v1 wire retraction, synthesized client-side. A message is deleted once,\n * so the deterministic id needs no timestamp — `d_{messageId}` matches across\n * echoes and replays by construction (no serialization-drift concern like the\n * edit's). No `value`: the v1 retract fastening carried none and the\n * projection reads none for DELETE.\n */\nfunction buildDeleteFastening(\n\troomId: string,\n\tmessageId: string,\n\tfrom: string,\n\tdeletedAt: string\n): StoreMessageFastening {\n\tconst id = `d_${messageId}`;\n\treturn {\n\t\tid,\n\t\tstanzaId: id,\n\t\troomId,\n\t\tdate: toTimestamp(deletedAt),\n\t\ttype: 'fastening',\n\t\taction: 'delete',\n\t\toriginalStanzaId: messageId,\n\t\tfrom\n\t};\n}\n\n/**\n * `DELETE /rooms/{roomId}/messages/{messageId}` — serialized through the same\n * per-room FIFO write queue as the sends and edits (plan §7.4).\n *\n * Confirmation is echo-only, unlike the edit's two-way scheme: the 204 has no\n * body, hence no server timestamp to date the fastening with. A client-side\n * now() could lose against a fresher server editedAt in the projection\n * (latest EDIT/DELETE by date) and the slice dedup would then drop the echo's\n * corrective fastening — so the REST path writes nothing, exactly like the v1\n * retraction that only confirmed through the MUC echo.\n */\nexport function deleteMessage(\n\t{ http, queue }: MessagesDeps,\n\troomId: string,\n\tmessageId: string\n): Promise<void> {\n\treturn enqueueWrite(queue, roomId, async () => {\n\t\tawait http.request<void>(\n\t\t\t`rooms/${encodeURIComponent(roomId)}/messages/${encodeURIComponent(messageId)}`,\n\t\t\t'DELETE'\n\t\t);\n\t});\n}\n\n/**\n * `MessageDeleted` push event — every deleter, own echo included (v1 MUC\n * parity, like the edits: no unread bump, no notifications). The fastening\n * write is shared; the sidebar update only happens when the deletion hits the\n * room's last message — the app router resolves that (fresh) and passes it\n * here. History needs none of this: timeline/inbox DTOs arrive already\n * materialized (`deletedInfo` -> the `deleted` boolean, step 3).\n */\nexport function handleMessageDeleted(\n\t{ bridge }: MessagesDeps,\n\tevent: WireMessageDeletedEvent,\n\tlastMessage?: StoreTextMessage\n): void {\n\tbridge.addFastening([\n\t\tbuildDeleteFastening(event.roomId, event.messageId, event.deletedBy, event.deletedAt)\n\t]);\n\tif (lastMessage) {\n\t\t// The v1 handler's merge, verbatim: deleted flagged, text emptied,\n\t\t// attachment and reply reference cleared\n\t\tbridge.setLastMessage(event.roomId, {\n\t\t\t...lastMessage,\n\t\t\tdeleted: true,\n\t\t\ttext: '',\n\t\t\tattachment: undefined,\n\t\t\treplyTo: undefined\n\t\t});\n\t}\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport type { MessagesDeps } from './messages';\nimport { enqueueWrite } from './writeQueue';\nimport { toTimestamp } from '../domain/inbox';\nimport type { WireMessage } from '../types/api';\nimport type { WireMessageEditedEvent } from '../types/events';\nimport type { StoreMessageFastening, StoreTextMessage } from '../types/store';\n\nexport type EditMessageParams = {\n\troomId: string;\n\t/** Server id of the message to edit (v2: stable across edits, id === stanzaId). */\n\tmessageId: string;\n\t/** The full new text, not a delta. */\n\ttext: string;\n};\n\n/**\n * Deterministic fastening id: the REST confirmation and the `MessageEdited`\n * echo describe the same edit with the same timestamp (one DB column), so\n * both paths synthesize the same id and the slice dedup makes whichever lands\n * second a no-op — the send flow's idempotence, keyed like the planned\n * reaction ids (plan §3). Were the two serializations ever to differ, the\n * duplicate fastening would carry the same value and the projection (latest\n * by date) would still render the same text.\n */\nfunction editFasteningId(messageId: string, editedAt: string): string {\n\treturn `e_${messageId}_${editedAt}`;\n}\n\n/**\n * The v1 wire fastening, synthesized client-side. In v1 the correction was\n * itself a stanza with its own archive id; here id and stanzaId share the\n * deterministic value (stanzaId's only v1 consumer — the XEP-0422 parent-id\n * of a follow-up edit — has no v2 counterpart).\n */\nfunction buildEditFastening(\n\troomId: string,\n\tmessageId: string,\n\tfrom: string,\n\ttext: string,\n\teditedAt: string\n): StoreMessageFastening {\n\tconst id = editFasteningId(messageId, editedAt);\n\treturn {\n\t\tid,\n\t\tstanzaId: id,\n\t\troomId,\n\t\tdate: toTimestamp(editedAt),\n\t\ttype: 'fastening',\n\t\taction: 'edit',\n\t\toriginalStanzaId: messageId,\n\t\tfrom,\n\t\tvalue: text\n\t};\n}\n\n/**\n * `PUT /rooms/{roomId}/messages/{messageId}/edit` — serialized through the\n * same per-room FIFO write queue as the sends, so an edit issued right after\n * a send keeps the wire order (plan §7.4). No optimistic write: v1 sent the\n * correction stanza and waited for the MUC echo; here the 200 already\n * confirms, one hop earlier.\n *\n * The response only synthesizes the fastening (bubble text + \"edited\" label\n * via the apps' projection). The sidebar's lastMessage update stays with the\n * event path on purpose: it needs the CURRENT last message, and a value\n * resolved before the PUT could regress the sidebar if another message lands\n * in between — the echo's router lookup is always fresh.\n */\nexport function editMessage(\n\t{ http, bridge, queue }: MessagesDeps,\n\tparams: EditMessageParams\n): Promise<void> {\n\tconst { roomId, messageId, text } = params;\n\treturn enqueueWrite(queue, roomId, async () => {\n\t\tconst response = await http.request<WireMessage>(\n\t\t\t`rooms/${encodeURIComponent(roomId)}/messages/${encodeURIComponent(messageId)}/edit`,\n\t\t\t'PUT',\n\t\t\t{ text }\n\t\t);\n\t\t// Same DB timestamp as the echo's editedAt, so the deterministic id matches\n\t\tconst editedAt = response?.editedInfo?.editedAt;\n\t\tif (editedAt) {\n\t\t\t// The 200 is the edited `Message`: sender and text are server-authoritative\n\t\t\tbridge.addFastening([\n\t\t\t\tbuildEditFastening(roomId, messageId, response.senderId, response.text, editedAt)\n\t\t\t]);\n\t\t}\n\t\t// 200 without an edit timestamp (or the legacy 204, no body): no\n\t\t// deterministic id to build — the MessageEdited echo confirms instead,\n\t\t// exactly like an incomplete 201 on the send path.\n\t});\n}\n\n/**\n * `MessageEdited` push event — every editor, own echo included (no self-skip:\n * v1 corrections came back through the MUC to everyone, the sender too). The\n * fastening write is shared by all editors; the sidebar update only happens\n * when the edit hits the room's last message — the app router owns the store,\n * resolves that (fresh) and passes it here, same layering as the pinned\n * message. No unread bump, no notifications: v1 parity, an edit is not a new\n * message.\n *\n * The event names no editor: only the author can edit, so the fastening's\n * `from` is the edited message's sender when the room history has it loaded,\n * empty otherwise. The projections read the fastening's value and date, not\n * its `from`.\n */\nexport function handleMessageEdited(\n\t{ bridge }: MessagesDeps,\n\tevent: WireMessageEditedEvent,\n\tlastMessage?: StoreTextMessage\n): void {\n\tconst edited = bridge.getRoomMessages(event.roomId).find((row) => row.id === event.messageId);\n\tbridge.addFastening([\n\t\tbuildEditFastening(\n\t\t\tevent.roomId,\n\t\t\tevent.messageId,\n\t\t\tedited?.from ?? '',\n\t\t\tevent.text,\n\t\t\tevent.editedAt\n\t\t)\n\t]);\n\tif (lastMessage) {\n\t\t// The v1 handler's merge, verbatim: text swapped, edited flagged, the\n\t\t// rest (attachment included) preserved by the spread\n\t\tbridge.setLastMessage(event.roomId, { ...lastMessage, edited: true, text: event.text });\n\t}\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport type { MessagesDeps } from './messages';\nimport { enqueueWrite } from './writeQueue';\nimport { mapWireMessageToStoreMessage } from '../domain/inbox';\nimport type { WireMessageForwardedEvent } from '../types/events';\nimport type { StoreMessage } from '../types/store';\n\nexport type ForwardMessageRef = {\n\t/** The room the message currently lives in. */\n\tsourceRoomId: string;\n\t/** Server id of the message to forward. */\n\tmessageId: string;\n};\n\n/**\n * `POST /rooms/{toRoomId}/forward` — one bulk request per destination room,\n * serialized through that room's FIFO write queue (a forward is a write into\n * the DESTINATION timeline). Forwarding is by reference: the v1 hybrid — one\n * MAM fetch per message to rebuild the original stanza XML, body swapped\n * with the projected text, the serialized XML posted to the legacy endpoint\n * — dissolves entirely.\n *\n * Fire-and-forget on success: the 201 is one `Message` per forward, but with\n * the cloned attachment as a bare `attachmentId` (no name, type or size).\n * The `MessageForwarded` echo carries the full timeline message, so it stays\n * the only store write: a write from the 201 landing after the echo would\n * degrade the attachment to a stub. There is no placeholder to promote —\n * forwards were never optimistic in v1 either. Errors still propagate.\n */\nexport function forwardMessages(\n\t{ http, queue }: MessagesDeps,\n\ttoRoomId: string,\n\tmessages: Array<ForwardMessageRef>\n): Promise<void> {\n\treturn enqueueWrite(queue, toRoomId, async () => {\n\t\tawait http.request(`rooms/${encodeURIComponent(toRoomId)}/forward`, 'POST', { messages });\n\t});\n}\n\n/**\n * `MessageForwarded` push event — the delivery of a forwarded message, the\n * forwarder's own echo included. To the receiving room this IS a new\n * message: the store writes mirror `handleMessageReceived` (append + inbox\n * row) and the me/others split (unread, notifications) stays in the app\n * router, exactly like v1 where a forward landed through the plain message\n * handler. Returns the mapped message for those app-side effects.\n *\n * The event carries the full `TimelineMessage`: `forwardedInfo` becomes the\n * v1 forwarded badge, and the attachment is the server-side clone, which\n * reaches the destination only through this echo.\n */\nexport function handleMessageForwarded(\n\t{ bridge }: MessagesDeps,\n\tevent: WireMessageForwardedEvent\n): StoreMessage {\n\tconst message = mapWireMessageToStoreMessage(event.message);\n\tbridge.newMessage(message);\n\tbridge.setInboxMessages([message]);\n\treturn message;\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport { toTimestamp } from './inbox';\nimport type { PresenceUpdate } from './inbox';\nimport type { WirePresenceStatus } from '../types/api';\n\n/** One `POST /presence/batch` entry -> the same update shape the inbox produces. */\nexport function mapPresenceStatus(status: WirePresenceStatus): PresenceUpdate {\n\treturn {\n\t\tuserId: status.userId,\n\t\tonline: status.online,\n\t\t...(status.lastActivity ? { lastActivity: toTimestamp(status.lastActivity) } : {})\n\t};\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport type { PresenceUpdate } from '../domain/inbox';\nimport { toTimestamp } from '../domain/inbox';\nimport { mapPresenceStatus } from '../domain/presence';\nimport type { HttpClient } from '../http/httpClient';\nimport type { WirePresenceStatus } from '../types/api';\nimport type { StoreBridge } from '../types/bridge';\nimport type { WirePresenceChangedEvent } from '../types/events';\n\n/**\n * Per user, the `(lastActivity, online)` pair of the last presence applied. The backend reads\n * `lastActivity` in the same transaction as the transition, so the pair totally orders a user's\n * states (offline@T1 < online@T1 < offline@T2 < online@T2; no `lastActivity` is -infinity).\n */\nexport type PresenceGuard = Map<string, { activity: number; online: number }>;\n\nexport function createPresenceGuard(): PresenceGuard {\n\treturn new Map();\n}\n\nexport function resetPresenceGuard(guard: PresenceGuard): void {\n\tguard.clear();\n}\n\nexport type PresenceDeps = {\n\thttp: HttpClient;\n\tbridge: StoreBridge;\n\tpresence: PresenceGuard;\n};\n\nconst PRESENCE_BATCH_LIMIT = 100;\n\n/**\n * The one presence write rule, shared by the inbox and batch hydrations and the push event: an\n * update lands unless its `(lastActivity, online)` pair is strictly older than the user's last\n * applied one: an equal pair writes again (idempotent), which re-hydrates a store the app wiped on\n * a reconnection while the SDK kept its ordering. The online flag always lands with it, and so\n * does the last activity when present: the last time the user went offline, returned also while\n * online; the UI shows \"last seen\" only for offline users.\n */\nexport function applyPresenceUpdates(\n\t{ bridge, presence }: Pick<PresenceDeps, 'bridge' | 'presence'>,\n\tupdates: Array<PresenceUpdate>\n): void {\n\tupdates.forEach((update) => {\n\t\tconst activity = update.lastActivity ?? Number.NEGATIVE_INFINITY;\n\t\tconst online = update.online ? 1 : 0;\n\t\tconst stored = presence.get(update.userId);\n\t\tif (\n\t\t\tstored &&\n\t\t\t(activity < stored.activity || (activity === stored.activity && online < stored.online))\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tpresence.set(update.userId, { activity, online });\n\t\tbridge.setUserPresence(update.userId, update.online);\n\t\tif (update.lastActivity !== undefined) {\n\t\t\tbridge.setUserLastActivity(update.userId, update.lastActivity);\n\t\t}\n\t});\n}\n\nexport async function requestPresence(deps: PresenceDeps, userIds: Array<string>): Promise<void> {\n\tconst errors: Array<unknown> = [];\n\tfor (let i = 0; i < userIds.length; i += PRESENCE_BATCH_LIMIT) {\n\t\ttry {\n\t\t\t// eslint-disable-next-line no-await-in-loop\n\t\t\tconst statuses = await deps.http.request<Array<WirePresenceStatus>>(\n\t\t\t\t'presence/batch',\n\t\t\t\t'POST',\n\t\t\t\t{ userIds: userIds.slice(i, i + PRESENCE_BATCH_LIMIT) }\n\t\t\t);\n\t\t\tapplyPresenceUpdates(deps, (statuses ?? []).map(mapPresenceStatus));\n\t\t} catch (error) {\n\t\t\terrors.push(error);\n\t\t}\n\t}\n\tif (errors.length > 0) {\n\t\tthrow errors[0];\n\t}\n}\n\n/**\n * `POST /presence/batch` — presence + last activity for N users: the v2\n * replacement for the v1 per-contact `jabber:iq:last` queries (the roster\n * boot loop is already covered by `GET /inbox`). The ids are deduplicated and\n * sent in chunks of 100, the backend limit (400 above). A failed chunk does not\n * stop the next ones: the first error is rethrown once every chunk has run.\n */\nexport function fetchPresence(deps: PresenceDeps, userIds: Array<string>): Promise<void> {\n\treturn requestPresence(deps, [...new Set(userIds)]);\n}\n\n/**\n * `PresenceChanged` push event: lands through the same `(lastActivity, online)` ordering as the\n * snapshots, so a late or inverted event never overwrites a newer state. The backend never sends a\n * user their own presence; the app routers filter it anyway, like in v1 where it never reached the\n * store.\n */\nexport function handlePresenceChanged(\n\tdeps: PresenceDeps,\n\tevent: WirePresenceChangedEvent\n): Promise<void> {\n\tapplyPresenceUpdates(deps, [\n\t\t{\n\t\t\tuserId: event.userId,\n\t\t\tonline: event.online,\n\t\t\t...(event.lastActivity ? { lastActivity: toTimestamp(event.lastActivity) } : {})\n\t\t}\n\t]);\n\treturn Promise.resolve();\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport { toTimestamp } from '../domain/inbox';\nimport type { StoreBridge } from '../types/bridge';\nimport type {\n\tWireMeetingDeclinedEvent,\n\tWireMeetingStartedEvent,\n\tWireMeetingStoppedEvent,\n\tWireRoomDescriptionChangedEvent,\n\tWireRoomHistoryClearedEvent,\n\tWireRoomMemberAddedEvent,\n\tWireRoomMemberRemovedEvent,\n\tWireRoomNameChangedEvent,\n\tWireRoomPictureChangedEvent,\n\tWireRoomPictureDeletedEvent\n} from '../types/events';\nimport type { StoreConfigurationMessage, StoreOperationType } from '../types/store';\n\nexport type SystemLinesDeps = {\n\tbridge: StoreBridge;\n};\n\n/**\n * Per room and field (`name`, `description`), the time and value of the newest change seen: a\n * change's `systemEventCreatedAt` or a REST room's `updatedAt`. Two quick changes published by\n * different nodes can arrive inverted: the older one still lands its line, but must not overwrite\n * the newer value.\n */\nexport type RoomFieldVersions = Map<string, { time: number; value: string | undefined }>;\n\nexport type RoomFieldDeps = SystemLinesDeps & { roomFieldVersions: RoomFieldVersions };\n\nexport type RoomFieldEventResult = { row: StoreConfigurationMessage; applied: boolean };\n\nfunction claimRoomField(\n\tversions: RoomFieldVersions,\n\troomId: string,\n\tfield: 'name' | 'description',\n\ttime: number,\n\tvalue: string | undefined\n): boolean {\n\tconst key = `${roomId}:${field}`;\n\tconst current = versions.get(key);\n\tif (current !== undefined && time <= current.time) {\n\t\treturn false;\n\t}\n\tversions.set(key, { time, value });\n\treturn true;\n}\n\nfunction newestRoomField(\n\tversions: RoomFieldVersions,\n\troomId: string,\n\tfield: 'name' | 'description',\n\ttime: number,\n\tvalue: string | undefined\n): string | undefined {\n\treturn claimRoomField(versions, roomId, field, time, value)\n\t\t? value\n\t\t: versions.get(`${roomId}:${field}`)?.value;\n}\n\n/**\n * The v1 configuration row of a member or meeting change, synthesized from\n * the push event. In v1 the row was a MUC broadcast; in v2 the backend\n * persists a timeline system event and the push event carries its id, which\n * becomes the row id: a timeline page restating the line replaces this row,\n * and `PUT /read` accepts it. Dated with the system event's `createdAt`\n * (`systemEventCreatedAt`), the instant a read marker on the line gets, like\n * the timeline row. An event without `systemEventCreatedAt` announces no line.\n */\nfunction buildSystemLine(\n\toperation: StoreOperationType,\n\troomId: string,\n\tsystemEventId: string,\n\tfrom: string,\n\tcreatedAt: string,\n\tvalue = ''\n): StoreConfigurationMessage {\n\treturn {\n\t\tid: systemEventId,\n\t\troomId,\n\t\tdate: toTimestamp(createdAt),\n\t\ttype: 'configuration',\n\t\toperation,\n\t\tvalue,\n\t\tfrom,\n\t\tread: 'read'\n\t};\n}\n\nfunction isKnownLine(bridge: StoreBridge, row: StoreConfigurationMessage): boolean {\n\treturn bridge.getRoomMessages(row.roomId).some((known) => known.id === row.id);\n}\n\n/**\n * Like every v1 configuration row, the line lands in the timeline and\n * becomes the room's last message in the chat list. A timeline page fetched\n * while the event was in flight may have brought it already.\n */\nfunction landSystemLine(bridge: StoreBridge, row: StoreConfigurationMessage): void {\n\tif (!isKnownLine(bridge, row)) {\n\t\tbridge.newMessage(row);\n\t}\n\tbridge.setInboxMessages([row]);\n}\n\n/**\n * `RoomMemberAdded` push event: lands the `memberAdded` line, whose value is\n * the added member. Returns the row for the router's me/others effects, or\n * undefined when the event announces no line or the line is already in the\n * room. A bulk add writes one line and sends one event for each added member.\n */\nexport function handleRoomMemberAdded(\n\t{ bridge }: SystemLinesDeps,\n\tevent: WireRoomMemberAddedEvent\n): StoreConfigurationMessage | undefined {\n\tif (!event.systemEventId || !event.systemEventCreatedAt) {\n\t\treturn undefined;\n\t}\n\tconst row = buildSystemLine(\n\t\t'memberAdded',\n\t\tevent.roomId,\n\t\tevent.systemEventId,\n\t\tevent.addedBy,\n\t\tevent.systemEventCreatedAt,\n\t\tevent.userId\n\t);\n\tif (isKnownLine(bridge, row)) {\n\t\treturn undefined;\n\t}\n\tlandSystemLine(bridge, row);\n\treturn row;\n}\n\n/**\n * `RoomMemberRemoved` push event: lands the `memberRemoved` line, whose value\n * is the removed member. Returns the row, or undefined when the event\n * announces no line (an automatic removal on backends before `ec635ad1`).\n */\nexport function handleRoomMemberRemoved(\n\t{ bridge }: SystemLinesDeps,\n\tevent: WireRoomMemberRemovedEvent\n): StoreConfigurationMessage | undefined {\n\tif (!event.systemEventId || !event.systemEventCreatedAt || !event.removedBy) {\n\t\treturn undefined;\n\t}\n\tconst row = buildSystemLine(\n\t\t'memberRemoved',\n\t\tevent.roomId,\n\t\tevent.systemEventId,\n\t\tevent.removedBy,\n\t\tevent.systemEventCreatedAt,\n\t\tevent.userId\n\t);\n\tlandSystemLine(bridge, row);\n\treturn row;\n}\n\n/**\n * A room read from REST (`GET /rooms`, `GET /rooms/{id}`) carries `updatedAt`, written by the\n * database clock in the update that changes the name or the description, before that change's line.\n * Returns the name and description to store: the snapshot's when it is newer than the newest change\n * seen (its `updatedAt` becomes the version), otherwise that newer change's value, also when the\n * room was not stored yet.\n */\nexport function resolveRoomSnapshot(\n\t{ roomFieldVersions }: Pick<RoomFieldDeps, 'roomFieldVersions'>,\n\troomId: string,\n\tsnapshot: { updatedAt: string; name?: string; description?: string }\n): { name: string | undefined; description: string | undefined } {\n\tconst time = toTimestamp(snapshot.updatedAt);\n\treturn {\n\t\tname: newestRoomField(roomFieldVersions, roomId, 'name', time, snapshot.name),\n\t\tdescription: newestRoomField(\n\t\t\troomFieldVersions,\n\t\t\troomId,\n\t\t\t'description',\n\t\t\ttime,\n\t\t\tsnapshot.description\n\t\t)\n\t};\n}\n\n/**\n * `RoomNameChanged` push event: lands the `roomNameChanged` line, valued with\n * the new name like the v1 rows. A change of both name and description sends\n * this event first, then `RoomDescriptionChanged`. Returns the row and\n * `applied`: false when a newer name change was already applied, so the app\n * keeps the newer name.\n */\nexport function handleRoomNameChanged(\n\t{ bridge, roomFieldVersions }: RoomFieldDeps,\n\tevent: WireRoomNameChangedEvent\n): RoomFieldEventResult {\n\tconst row = buildSystemLine(\n\t\t'roomNameChanged',\n\t\tevent.roomId,\n\t\tevent.systemEventId,\n\t\tevent.updatedBy,\n\t\tevent.systemEventCreatedAt,\n\t\tevent.name\n\t);\n\tlandSystemLine(bridge, row);\n\treturn {\n\t\trow,\n\t\tapplied: claimRoomField(roomFieldVersions, event.roomId, 'name', row.date, event.name)\n\t};\n}\n\n/**\n * `RoomDescriptionChanged` push event: lands the `roomDescriptionChanged`\n * line, valued with the new description like the v1 rows (empty when it was\n * cleared). Returns the row and `applied`, as for the name.\n */\nexport function handleRoomDescriptionChanged(\n\t{ bridge, roomFieldVersions }: RoomFieldDeps,\n\tevent: WireRoomDescriptionChangedEvent\n): RoomFieldEventResult {\n\tconst row = buildSystemLine(\n\t\t'roomDescriptionChanged',\n\t\tevent.roomId,\n\t\tevent.systemEventId,\n\t\tevent.updatedBy,\n\t\tevent.systemEventCreatedAt,\n\t\tevent.description\n\t);\n\tlandSystemLine(bridge, row);\n\treturn {\n\t\trow,\n\t\tapplied: claimRoomField(\n\t\t\troomFieldVersions,\n\t\t\tevent.roomId,\n\t\t\t'description',\n\t\t\trow.date,\n\t\t\tevent.description\n\t\t)\n\t};\n}\n\n/**\n * `RoomPictureChanged` push event: lands the `roomPictureUpdated` line.\n * Returns the row, or undefined when the event announces no line.\n */\nexport function handleRoomPictureChanged(\n\t{ bridge }: SystemLinesDeps,\n\tevent: WireRoomPictureChangedEvent\n): StoreConfigurationMessage | undefined {\n\tif (!event.systemEventId || !event.systemEventCreatedAt) {\n\t\treturn undefined;\n\t}\n\tconst row = buildSystemLine(\n\t\t'roomPictureUpdated',\n\t\tevent.roomId,\n\t\tevent.systemEventId,\n\t\tevent.updatedBy,\n\t\tevent.systemEventCreatedAt\n\t);\n\tlandSystemLine(bridge, row);\n\treturn row;\n}\n\n/**\n * `RoomPictureDeleted` push event: lands the `roomPictureDeleted` line.\n * Returns the row, or undefined when the event announces no line.\n */\nexport function handleRoomPictureDeleted(\n\t{ bridge }: SystemLinesDeps,\n\tevent: WireRoomPictureDeletedEvent\n): StoreConfigurationMessage | undefined {\n\tif (!event.systemEventId || !event.systemEventCreatedAt) {\n\t\treturn undefined;\n\t}\n\tconst row = buildSystemLine(\n\t\t'roomPictureDeleted',\n\t\tevent.roomId,\n\t\tevent.systemEventId,\n\t\tevent.deletedBy,\n\t\tevent.systemEventCreatedAt\n\t);\n\tlandSystemLine(bridge, row);\n\treturn row;\n}\n\n/**\n * `RoomHistoryCleared` push event: lands the `roomHistoryCleared` line of a\n * temporary room cleared for everyone. The app still clears the conversation\n * at `clearedAt`; its v1 clear keeps the newest clear line. Returns the row,\n * or undefined on the per-user clear, which has no line.\n */\nexport function handleRoomHistoryCleared(\n\t{ bridge }: SystemLinesDeps,\n\tevent: WireRoomHistoryClearedEvent\n): StoreConfigurationMessage | undefined {\n\tif (!event.systemEventId || !event.systemEventCreatedAt || !event.clearedBy) {\n\t\treturn undefined;\n\t}\n\tconst row = buildSystemLine(\n\t\t'roomHistoryCleared',\n\t\tevent.roomId,\n\t\tevent.systemEventId,\n\t\tevent.clearedBy,\n\t\tevent.systemEventCreatedAt\n\t);\n\tlandSystemLine(bridge, row);\n\treturn row;\n}\n\n/**\n * `MeetingStarted` push event: lands the `meetingStarted` line in the\n * meeting's room, which the app resolves from its meetings. Returns the row,\n * or undefined when the room has no line (group meetings).\n */\nexport function handleMeetingStarted(\n\t{ bridge }: SystemLinesDeps,\n\tevent: WireMeetingStartedEvent,\n\troomId: string\n): StoreConfigurationMessage | undefined {\n\tif (!event.systemEventId || !event.systemEventCreatedAt) {\n\t\treturn undefined;\n\t}\n\tconst row = buildSystemLine(\n\t\t'meetingStarted',\n\t\troomId,\n\t\tevent.systemEventId,\n\t\tevent.starterUser,\n\t\tevent.systemEventCreatedAt\n\t);\n\tlandSystemLine(bridge, row);\n\treturn row;\n}\n\n/**\n * `MeetingStopped` push event: lands the `meetingEnded` line, whose value is\n * the call duration in seconds, `durationSec` (present exactly when\n * `systemEventId` is; an empty value otherwise). Returns the row, or undefined\n * when the room has no line.\n */\nexport function handleMeetingStopped(\n\t{ bridge }: SystemLinesDeps,\n\tevent: WireMeetingStoppedEvent,\n\troomId: string\n): StoreConfigurationMessage | undefined {\n\tif (!event.systemEventId || !event.systemEventCreatedAt) {\n\t\treturn undefined;\n\t}\n\tconst row = buildSystemLine(\n\t\t'meetingEnded',\n\t\troomId,\n\t\tevent.systemEventId,\n\t\tevent.endedBy,\n\t\tevent.systemEventCreatedAt,\n\t\tevent.durationSec === undefined ? '' : String(event.durationSec)\n\t);\n\tlandSystemLine(bridge, row);\n\treturn row;\n}\n\n/**\n * `MeetingDeclined` push event: lands the `meetingDeclined` line, authored by\n * the decliner. Returns the row, or undefined when the room has no line.\n */\nexport function handleMeetingDeclined(\n\t{ bridge }: SystemLinesDeps,\n\tevent: WireMeetingDeclinedEvent,\n\troomId: string\n): StoreConfigurationMessage | undefined {\n\tif (!event.systemEventId || !event.systemEventCreatedAt) {\n\t\treturn undefined;\n\t}\n\tconst row = buildSystemLine(\n\t\t'meetingDeclined',\n\t\troomId,\n\t\tevent.systemEventId,\n\t\tevent.userId,\n\t\tevent.systemEventCreatedAt\n\t);\n\tlandSystemLine(bridge, row);\n\treturn row;\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\n// Plain string building instead of URLSearchParams: on React Native the URL APIs\n// require a polyfill, and the SDK must stay runtime-agnostic with zero dependencies.\nexport function buildQueryString(\n\tparams: Record<string, string | number | boolean | undefined | null>\n): string {\n\tconst parts: Array<string> = [];\n\tObject.entries(params).forEach(([key, value]) => {\n\t\tif (value !== undefined && value !== null) {\n\t\t\tparts.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);\n\t\t}\n\t});\n\treturn parts.length > 0 ? `?${parts.join('&')}` : '';\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport { applyPresenceUpdates } from './presence';\nimport type { PresenceDeps } from './presence';\nimport { resolveRoomSnapshot } from './systemLines';\nimport type { RoomFieldDeps } from './systemLines';\nimport { mapInboxEntry, mapLastItem } from '../domain/inbox';\nimport type { HttpClient } from '../http/httpClient';\nimport { buildQueryString } from '../http/queryString';\nimport type { WireInboxResponse, WireTimeline } from '../types/api';\nimport type { StoreBridge } from '../types/bridge';\nimport type { WireRoomCreatedEvent } from '../types/events';\nimport type { StoreMessage } from '../types/store';\n\nexport type InboxDeps = {\n\thttp: HttpClient;\n\tbridge: StoreBridge;\n};\n\n/**\n * `GET /inbox` — one round-trip carrying, per room: the last message, the\n * server-side unread count, every member's read marker and presence.\n * Replaces the XMPP boot sequence (XEP-0430 inbox + smart markers + roster).\n *\n * The room names and descriptions land first, resolved against the newest change seen: the inbox\n * refresh after a reconnection brings the changes whose events were missed meanwhile.\n *\n * Write order mirrors the v1 flow: last messages first (`setInboxMessages`),\n * then markers (the slice recomputes read statuses), then unread counters,\n * then presence, ordered like `fetchPresence`'s.\n */\nexport async function fetchInbox(\n\tdeps: PresenceDeps & Pick<RoomFieldDeps, 'roomFieldVersions'>\n): Promise<void> {\n\tconst { http, bridge } = deps;\n\tconst response = await http.request<WireInboxResponse>('inbox', 'GET');\n\t(response?.conversations ?? []).forEach((entry) => {\n\t\tif (entry.room) {\n\t\t\tbridge.setRoomFields(entry.roomId, resolveRoomSnapshot(deps, entry.roomId, entry.room));\n\t\t}\n\t});\n\tconst entries = (response?.conversations ?? []).map((entry) =>\n\t\tmapInboxEntry(entry, bridge.getRoomMessages(entry.roomId))\n\t);\n\n\tconst lastMessages = entries\n\t\t.map((entry) => entry.lastMessage)\n\t\t.filter((message): message is StoreMessage => message !== undefined);\n\tif (lastMessages.length > 0) {\n\t\tbridge.setInboxMessages(lastMessages);\n\t}\n\n\tentries.forEach((entry) => {\n\t\tif (entry.markers.length > 0) {\n\t\t\tbridge.updateReadStatus(entry.roomId, entry.markers);\n\t\t}\n\t});\n\n\tentries.forEach((entry) => {\n\t\tbridge.setUnreadCount(entry.roomId, entry.unreadCount);\n\t});\n\n\tconst presenceByUser = new Map(\n\t\tentries.flatMap((entry) => entry.presence).map((update) => [update.userId, update])\n\t);\n\tapplyPresenceUpdates(deps, Array.from(presenceByUser.values()));\n}\n\n/**\n * `RoomCreated` push event: the newest timeline item becomes the new room's\n * last message, the row `GET /inbox` returns as `lastItem` on a reload. The\n * event carries only the room id and the creation lines are not announced, so\n * without it the room would sink to the bottom of the chat list until its\n * first message; v1 got those lines live as XMPP affiliation messages.\n *\n * A row newer than the item, landed live while the request was in flight,\n * keeps its place. The unread count is not touched: creation lines never\n * count as unread.\n */\nexport async function handleRoomCreated(\n\t{ http, bridge }: InboxDeps,\n\tevent: WireRoomCreatedEvent\n): Promise<void> {\n\tconst { roomId } = event;\n\tconst response = await http.request<WireTimeline>(\n\t\t`rooms/${encodeURIComponent(roomId)}/timeline${buildQueryString({ limit: 1 })}`,\n\t\t'GET'\n\t);\n\tconst [newestItem] = response.items ?? [];\n\tconst lastMessage = mapLastItem(newestItem, roomId);\n\tif (!lastMessage) {\n\t\treturn;\n\t}\n\tif (bridge.getRoomMessages(roomId).some((row) => row.date > lastMessage.date)) {\n\t\treturn;\n\t}\n\tbridge.setInboxMessages([lastMessage]);\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport { enqueueWrite } from './writeQueue';\nimport type { WriteQueue } from './writeQueue';\nimport { mapWireMessageToStoreMessage } from '../domain/inbox';\nimport type { HttpClient } from '../http/httpClient';\nimport type { WireMessage } from '../types/api';\nimport type { StoreBridge } from '../types/bridge';\nimport type { WireMessageReceivedEvent } from '../types/events';\nimport type { AbortSignalLike } from '../types/ports';\nimport type { StoreAttachment, StoreMessage, StoreTextMessage } from '../types/store';\n\ndeclare const setTimeout: (handler: () => void, timeout: number) => unknown;\ndeclare const clearTimeout: (handle: unknown) => void;\ndeclare const AbortController: new () => { readonly signal: AbortSignalLike; abort: () => void };\n\nconst TEXT_BACKOFF = { baseMs: 2000, maxMs: 60_000 };\n// Every upload attempt sends the whole file again\nconst UPLOAD_BACKOFF = { baseMs: 30_000, maxMs: 10 * 60_000 };\n// The backend deduplicates a tempId for 1 hour: stop well before a retry could create a duplicate\nconst RETRY_WINDOW_MS = 50 * 60_000;\nconst SEND_TIMEOUT_MS = 30_000;\n// 409s that outlast a slow first upload mean a claim the server left stuck for 1 hour\nconst MAX_UPLOAD_CONFLICTS = 3;\nconst BEHIND_EARLIER_SEND = Symbol('behind an earlier pending send of the lane');\n\nexport type MessagesDeps = {\n\thttp: HttpClient;\n\tbridge: StoreBridge;\n\tqueue: WriteQueue;\n};\n\ntype PendingSend = {\n\troomId: string;\n\ttempId: string;\n\tqueued: boolean;\n\tlane: string;\n\tbackoff: { baseMs: number; maxMs: number };\n\tmaxConflicts: number;\n\tattempt: (signal: AbortSignalLike) => Promise<WireMessage>;\n\tconfirm: (response: WireMessage) => StoreMessage | undefined;\n\trun: () => void;\n\tresolve: (message: StoreMessage | undefined) => void;\n\treject: (error: unknown) => void;\n\tcontroller: { readonly signal: AbortSignalLike; abort: () => void };\n\tdeadline: number;\n\tstate: {\n\t\tinFlight: boolean;\n\t\tconflicts: number;\n\t\tlastError?: unknown;\n\t\tdeadlineTimer?: unknown;\n\t\tdetachSignal?: () => void;\n\t\tonFirstAttemptSettled?: (outcome: FirstAttemptOutcome) => void;\n\t};\n\tplaceholder?: StoreMessage;\n};\n\nexport type FirstAttemptOutcome = 'confirmed' | 'pending' | 'rejected';\n\nexport type SendRetries = {\n\tsends: Map<string, PendingSend>;\n\tlanes: Map<string, { failures: number; timer?: unknown }>;\n};\n\nexport function createSendRetries(): SendRetries {\n\treturn { sends: new Map(), lanes: new Map() };\n}\n\nexport type SendDeps = MessagesDeps & { retries: SendRetries };\n\nexport type SendMessageParams = {\n\troomId: string;\n\ttext: string;\n\t/** Client-generated id: the placeholder's `id` and the self-echo correlation key. */\n\ttempId: string;\n\t/** Server id of the quoted message when this send is a reply. */\n\treplyToId?: string;\n\t/**\n\t * The quoted message, resolved from the store by the façade (the SDK never\n\t * reads the store): keeps the reply section rendered when the REST\n\t * confirmation replaces the hydrated placeholder.\n\t */\n\trepliedMessage?: StoreTextMessage;\n};\n\nexport type SendAttachmentParams = Omit<ConfirmAttachmentUploadParams, 'response'> & {\n\t/**\n\t * One attempt of the app's multipart upload with the placeholder's `tempId`,\n\t * resolving with its 201; called again with the same `tempId` on every\n\t * retry. Pass `signal` to the fetch: the SDK aborts it when it gives up.\n\t * Reject with the HTTP `status`.\n\t *\n\t * The SDK sets no timeout on an attempt: bounding it is the app's job (a\n\t * stall timeout fits files of any size). An attempt that never settles\n\t * holds back its retries, `retryPendingSends` included, until the upload\n\t * gives up 50 minutes after the send. Reject a timed-out attempt with an\n\t * error not named `AbortError` (`AbortSignal.timeout` gives a\n\t * `TimeoutError`) to have it retried: an `AbortError` is a cancel and gives\n\t * the upload up.\n\t */\n\tupload: (signal: AbortSignalLike) => Promise<WireMessage>;\n\t/** The caller's cancel: aborting it gives the upload up at once. */\n\tsignal?: AbortSignalLike;\n\t/**\n\t * Called once, before the promise handlers, when the first attempt settles:\n\t * `pending` means retries are scheduled. Never called after `reset()`.\n\t */\n\tonFirstAttemptSettled?: (outcome: FirstAttemptOutcome) => void;\n};\n\nexport type ConfirmAttachmentUploadParams = {\n\troomId: string;\n\t/** The placeholder's id, sent as the upload's `tempId` form field. */\n\ttempId: string;\n\t/** The upload's 201: the created `Message`, naming the file only by `attachmentId`. */\n\tresponse: WireMessage;\n\t/** The metadata of the uploaded file, which the 201 does not repeat. */\n\tattachment: Omit<StoreAttachment, 'id'>;\n\t/** The quoted message on a reply, resolved from the store like the send's. */\n\trepliedMessage?: StoreTextMessage;\n};\n\n/**\n * Writes one confirmed message: placeholder out, message in, inbox row\n * updated. Called from BOTH confirmation paths (REST response and\n * `MessageReceived` self-echo): whichever lands first promotes the\n * placeholder, the other is a no-op — `removePlaceholderMessage` on a gone id\n * removes nothing and `newMessage` dedups by id (plan §3).\n */\nfunction confirmMessage(bridge: StoreBridge, tempId: string, confirmed: StoreMessage): void {\n\tbridge.removePlaceholderMessage(confirmed.roomId, tempId);\n\tbridge.newMessage(confirmed);\n\t// A retry can confirm with the original message, older than the room's newest row\n\tconst hasNewerRow = bridge\n\t\t.getRoomMessages(confirmed.roomId)\n\t\t.some(\n\t\t\t(row) =>\n\t\t\t\trow.id !== tempId &&\n\t\t\t\trow.id !== confirmed.id &&\n\t\t\t\trow.read !== 'pending' &&\n\t\t\t\trow.date > confirmed.date\n\t\t);\n\tif (!hasNewerRow) {\n\t\tbridge.setInboxMessages([confirmed]);\n\t}\n}\n\nfunction isCertainFailure(error: unknown): boolean {\n\tconst { status, name } = (error ?? {}) as { status?: unknown; name?: unknown };\n\tif (typeof status === 'number') {\n\t\treturn status >= 400 && status < 500 && status !== 408 && status !== 409 && status !== 429;\n\t}\n\treturn name === 'AbortError';\n}\n\nfunction isConflict(error: unknown): boolean {\n\treturn ((error ?? {}) as { status?: unknown }).status === 409;\n}\n\nfunction isPending({ retries }: SendDeps, send: PendingSend): boolean {\n\treturn retries.sends.get(send.tempId) === send;\n}\n\nfunction textLane(roomId: string): string {\n\treturn `text:${roomId}`;\n}\n\nfunction laneSends({ retries }: SendDeps, lane: string): Array<PendingSend> {\n\treturn [...retries.sends.values()].filter((send) => send.lane === lane);\n}\n\nfunction forgetSend(deps: SendDeps, send: PendingSend): void {\n\tconst { retries } = deps;\n\tretries.sends.delete(send.tempId);\n\tclearTimeout(send.state.deadlineTimer);\n\tsend.state.detachSignal?.();\n\tif (laneSends(deps, send.lane).length === 0) {\n\t\tclearTimeout(retries.lanes.get(send.lane)?.timer);\n\t\tretries.lanes.delete(send.lane);\n\t}\n}\n\nfunction reportFirstAttempt(send: PendingSend, outcome: FirstAttemptOutcome): void {\n\tconst { state } = send;\n\tconst report = state.onFirstAttemptSettled;\n\tstate.onFirstAttemptSettled = undefined;\n\treport?.(outcome);\n}\n\nfunction confirmSend(deps: SendDeps, send: PendingSend, message: StoreMessage | undefined): void {\n\tforgetSend(deps, send);\n\tsend.resolve(message);\n\treportFirstAttempt(send, 'confirmed');\n}\n\nfunction giveUp(deps: SendDeps, send: PendingSend, error: unknown): void {\n\tforgetSend(deps, send);\n\tsend.controller.abort();\n\tdeps.bridge.removePlaceholderMessage(send.roomId, send.tempId);\n\tsend.reject(error);\n\treportFirstAttempt(send, 'rejected');\n}\n\nfunction namedError(name: string, message: string): Error {\n\treturn Object.assign(new Error(message), { name });\n}\n\nfunction retrySends(deps: SendDeps, sends: Array<PendingSend>): void {\n\tsends\n\t\t.filter((send) => !send.state.inFlight)\n\t\t.forEach((send) => {\n\t\t\tif (Date.now() >= send.deadline) {\n\t\t\t\tgiveUp(deps, send, send.state.lastError);\n\t\t\t} else {\n\t\t\t\tsend.run();\n\t\t\t}\n\t\t});\n}\n\nfunction scheduleRetry(deps: SendDeps, send: PendingSend): void {\n\tconst lane = deps.retries.lanes.get(send.lane) ?? { failures: 0 };\n\tdeps.retries.lanes.set(send.lane, lane);\n\tif (lane.timer !== undefined) {\n\t\treturn;\n\t}\n\tconst delay = Math.min(send.backoff.baseMs * 2 ** lane.failures, send.backoff.maxMs);\n\tlane.failures += 1;\n\tlane.timer = setTimeout(() => {\n\t\tlane.timer = undefined;\n\t\tretrySends(deps, laneSends(deps, send.lane));\n\t}, delay);\n}\n\nfunction waitsForEarlierSend(deps: SendDeps, send: PendingSend): boolean {\n\treturn laneSends(deps, send.lane)[0] !== send;\n}\n\nfunction isFinalFailure(send: PendingSend, error: unknown): boolean {\n\tconst { state } = send;\n\tstate.conflicts = isConflict(error) ? state.conflicts + 1 : 0;\n\treturn (\n\t\tisCertainFailure(error) || state.conflicts >= send.maxConflicts || Date.now() >= send.deadline\n\t);\n}\n\nfunction failAttempt(deps: SendDeps, send: PendingSend, error: unknown): void {\n\tif (error !== BEHIND_EARLIER_SEND) {\n\t\tif (isFinalFailure(send, error)) {\n\t\t\tgiveUp(deps, send, error);\n\t\t\treturn;\n\t\t}\n\t\tconst { state } = send;\n\t\tstate.lastError = error;\n\t}\n\tscheduleRetry(deps, send);\n\treportFirstAttempt(send, 'pending');\n}\n\nfunction runAttempt(deps: SendDeps, send: PendingSend): void {\n\tconst { state } = send;\n\tstate.inFlight = true;\n\tconst task = (): Promise<StoreMessage | undefined> => {\n\t\tif (!isPending(deps, send)) {\n\t\t\treturn Promise.resolve(undefined);\n\t\t}\n\t\tif (waitsForEarlierSend(deps, send)) {\n\t\t\treturn Promise.reject(BEHIND_EARLIER_SEND);\n\t\t}\n\t\treturn send\n\t\t\t.attempt(send.controller.signal)\n\t\t\t.then((response) => (isPending(deps, send) ? send.confirm(response) : undefined));\n\t};\n\tconst attempt = send.queued ? enqueueWrite(deps.queue, send.roomId, task) : task();\n\tattempt.then(\n\t\t(message) => {\n\t\t\tstate.inFlight = false;\n\t\t\tif (isPending(deps, send)) {\n\t\t\t\tconfirmSend(deps, send, message);\n\t\t\t}\n\t\t},\n\t\t(error: unknown) => {\n\t\t\tstate.inFlight = false;\n\t\t\tif (isPending(deps, send)) {\n\t\t\t\tfailAttempt(deps, send, error);\n\t\t\t}\n\t\t}\n\t);\n}\n\nfunction trackSend(\n\tdeps: SendDeps,\n\tsend: Pick<PendingSend, 'roomId' | 'tempId' | 'queued' | 'attempt' | 'confirm'>,\n\tsignal?: AbortSignalLike,\n\tonFirstAttemptSettled?: (outcome: FirstAttemptOutcome) => void\n): Promise<StoreMessage | undefined> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst pending: PendingSend = {\n\t\t\t...send,\n\t\t\tlane: send.queued ? textLane(send.roomId) : `upload:${send.tempId}`,\n\t\t\tbackoff: send.queued ? TEXT_BACKOFF : UPLOAD_BACKOFF,\n\t\t\tmaxConflicts: send.queued ? Infinity : MAX_UPLOAD_CONFLICTS,\n\t\t\trun: () => runAttempt(deps, pending),\n\t\t\tresolve,\n\t\t\treject,\n\t\t\tcontroller: new AbortController(),\n\t\t\tdeadline: Date.now() + RETRY_WINDOW_MS,\n\t\t\tstate: { inFlight: false, conflicts: 0, onFirstAttemptSettled },\n\t\t\tplaceholder: deps.bridge\n\t\t\t\t.getRoomMessages(send.roomId)\n\t\t\t\t.find((message) => message.id === send.tempId)\n\t\t};\n\t\tdeps.retries.sends.set(send.tempId, pending);\n\t\tconst abort = (): void => {\n\t\t\tif (isPending(deps, pending)) {\n\t\t\t\tgiveUp(deps, pending, namedError('AbortError', 'Send aborted'));\n\t\t\t}\n\t\t};\n\t\tif (signal?.aborted) {\n\t\t\tabort();\n\t\t\treturn;\n\t\t}\n\t\tsignal?.addEventListener('abort', abort);\n\t\tpending.state.detachSignal = (): void => signal?.removeEventListener?.('abort', abort);\n\t\tpending.state.deadlineTimer = setTimeout(() => {\n\t\t\tif (isPending(deps, pending)) {\n\t\t\t\tgiveUp(\n\t\t\t\t\tdeps,\n\t\t\t\t\tpending,\n\t\t\t\t\tpending.state.lastError ?? namedError('TimeoutError', 'Send not confirmed in time')\n\t\t\t\t);\n\t\t\t}\n\t\t}, RETRY_WINDOW_MS);\n\t\tpending.run();\n\t});\n}\n\nexport function retryPendingSends(deps: SendDeps): void {\n\tconst { bridge, retries } = deps;\n\tconst pending = [...retries.sends.values()];\n\tpending.forEach(({ roomId, tempId, deadline, placeholder }) => {\n\t\tif (\n\t\t\tplaceholder &&\n\t\t\tDate.now() < deadline &&\n\t\t\t!bridge.getRoomMessages(roomId).some((message) => message.id === tempId)\n\t\t) {\n\t\t\tbridge.newMessage(placeholder);\n\t\t}\n\t});\n\tretries.lanes.forEach((lane) => clearTimeout(lane.timer));\n\tretries.lanes.clear();\n\tretrySends(deps, pending);\n}\n\nexport function resetSends({ queue, retries }: SendDeps): void {\n\tretries.sends.forEach((send) => {\n\t\tclearTimeout(send.state.deadlineTimer);\n\t\tsend.state.detachSignal?.();\n\t\tsend.controller.abort();\n\t});\n\tretries.sends.clear();\n\tretries.lanes.forEach((lane) => clearTimeout(lane.timer));\n\tretries.lanes.clear();\n\tqueue.clear();\n}\n\n/**\n * `POST /rooms/{roomId}/messages` — one outgoing text message, serialized\n * through the per-room FIFO write queue (plan §7.4). The optimistic\n * placeholder is the app's concern (the façade calls the existing\n * `setPlaceholderMessage` before invoking this, like v1 did before sending\n * the stanza).\n *\n * Confirmation is idempotent from both ways (REST response here, self-echo in\n * `handleMessageReceived`); failures follow the rules of `WscClient.sendMessage`.\n */\nexport function sendMessage(deps: SendDeps, params: SendMessageParams): Promise<void> {\n\tconst { http, bridge } = deps;\n\tconst { roomId, text, tempId, replyToId, repliedMessage } = params;\n\tconst attempt = (): Promise<WireMessage> =>\n\t\thttp.request<WireMessage>(\n\t\t\t`rooms/${encodeURIComponent(roomId)}/messages`,\n\t\t\t'POST',\n\t\t\t{ text, tempId, ...(replyToId ? { replyToId } : {}) },\n\t\t\t{ timeoutMs: SEND_TIMEOUT_MS }\n\t\t);\n\tconst confirm = (response: WireMessage): StoreMessage | undefined => {\n\t\t// Incomplete 201 (id or createdAt missing): the MessageReceived self-echo\n\t\t// confirms instead. Building a date client-side would risk regressing the\n\t\t// server timestamp when the echo landed first (newMessage assigns in place).\n\t\tif (!response?.id || !response.createdAt) {\n\t\t\treturn undefined;\n\t\t}\n\t\t// The 201 is the created `Message`, server-authoritative; the room\n\t\t// stays the one the placeholder was written under\n\t\tconst confirmed = mapWireMessageToStoreMessage({ ...response, roomId });\n\t\t// The `Message` DTO embeds no quote: keep the one the façade resolved.\n\t\t// Same guard as the mapper's embedded quote: a quoted message without\n\t\t// its replyToId must never turn a plain send into a fake reply bubble\n\t\tif (confirmed.replyTo && repliedMessage) {\n\t\t\tconfirmed.repliedMessage = repliedMessage;\n\t\t}\n\t\tconfirmMessage(bridge, tempId, confirmed);\n\t\treturn confirmed;\n\t};\n\tretrySends(deps, laneSends(deps, textLane(roomId)));\n\treturn trackSend(deps, { roomId, tempId, queued: true, attempt, confirm }).then(() => undefined);\n}\n\n/**\n * Confirms an attachment upload from its 201. The apps own the\n * `POST /rooms/{roomId}/attachments` multipart, whose body is\n * platform-specific; the SDK owns the store writes, with the send's\n * idempotent confirmation: whichever of this and the `MessageReceived`\n * self-echo lands first promotes the placeholder. `newMessage` merges in\n * place, so an echo landing second overwrites the attachment with the\n * server's metadata, and one landing first keeps its embedded quote (the 201\n * has none).\n *\n * The 201 names the file only by `attachmentId`: the attachment is the\n * uploaded file's metadata under the server id. Returns the confirmed\n * message, or nothing on an incomplete 201, which leaves the confirmation to\n * the echo like the send's.\n */\nexport function confirmAttachmentUpload(\n\t{ bridge }: MessagesDeps,\n\tparams: ConfirmAttachmentUploadParams\n): StoreMessage | undefined {\n\tconst { roomId, tempId, response, attachment, repliedMessage } = params;\n\tif (!response?.id || !response.createdAt || !response.attachmentId) {\n\t\treturn undefined;\n\t}\n\tconst confirmed = mapWireMessageToStoreMessage({ ...response, roomId });\n\tconfirmed.attachment = { ...attachment, id: response.attachmentId };\n\tif (confirmed.replyTo && repliedMessage) {\n\t\tconfirmed.repliedMessage = repliedMessage;\n\t}\n\tconfirmMessage(bridge, tempId, confirmed);\n\treturn confirmed;\n}\n\nexport function sendAttachment(\n\tdeps: SendDeps,\n\tparams: SendAttachmentParams\n): Promise<StoreMessage | undefined> {\n\tconst { roomId, tempId, upload, signal, onFirstAttemptSettled, ...rest } = params;\n\tconst confirm = (response: WireMessage): StoreMessage | undefined =>\n\t\tconfirmAttachmentUpload(deps, { roomId, tempId, response, ...rest });\n\treturn trackSend(\n\t\tdeps,\n\t\t{ roomId, tempId, queued: false, attempt: upload, confirm },\n\t\tsignal,\n\t\tonFirstAttemptSettled\n\t);\n}\n\n/**\n * `MessageReceived` push event — every message of every sender, own echo\n * included. The SDK performs the store writes shared by all senders; the\n * me/others split (unread counter, custom events, browser notifications)\n * stays in the app router, which owns the session — same layering as the v1\n * handler. Returns the mapped message for those app-side effects.\n *\n * The event carries the full `TimelineMessage`, so it maps like a timeline\n * row: attachment and quote come from the wire, no store lookup (v1 hydrated\n * the quote from the store, with an archive query as fallback).\n *\n * `tempId` promotes the optimistic placeholder. It reaches every member, but\n * only the sender holds a placeholder under that id: for the others the\n * removal is a no-op and the write is a plain append. For the sender it also\n * confirms the pending send of that tempId and stops its retries.\n */\nexport function handleMessageReceived(\n\tdeps: SendDeps,\n\tevent: WireMessageReceivedEvent\n): StoreMessage {\n\tconst { bridge, retries } = deps;\n\tconst message = mapWireMessageToStoreMessage(event.message);\n\tif (event.tempId) {\n\t\tconfirmMessage(bridge, event.tempId, message);\n\t\tconst pending = retries.sends.get(event.tempId);\n\t\tif (pending?.roomId === message.roomId) {\n\t\t\tconfirmSend(deps, pending, message);\n\t\t}\n\t\treturn message;\n\t}\n\tbridge.newMessage(message);\n\tbridge.setInboxMessages([message]);\n\treturn message;\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport type { StoreConfigurationMessage, StoreMessage } from '../types/store';\n\nexport type PinOperation = 'messagePinned' | 'messageUnpinned';\n\n/**\n * Widest gap between the live pin row and the backend's row for the same\n * change. A pin event carries the `pinnedAt` of the system event, in\n * nanoseconds where the database keeps microseconds, so the two can still\n * round to different milliseconds; an unpin event is stamped `now()` at\n * broadcast, a few ms after the system event's `createdAt` (plan §5.15).\n * Two distinct changes of one message by one user need a round trip of\n * clicks, far wider than this.\n */\nconst SAME_PIN_CHANGE_WINDOW_MS = 5_000;\n\n/**\n * Deterministic on the event fields: double deliveries of one push event\n * dedup in the slice, distinct re-pins of the same message stay distinct.\n */\nexport function pinRowId(operation: PinOperation, messageId: string, date: number): string {\n\tconst prefix = operation === 'messagePinned' ? 'pin' : 'unpin';\n\treturn `${prefix}_${messageId}_${date}`;\n}\n\nexport function isPinRow(\n\trow: StoreMessage\n): row is StoreConfigurationMessage & { operation: PinOperation } {\n\treturn (\n\t\trow.type === 'configuration' &&\n\t\t(row.operation === 'messagePinned' || row.operation === 'messageUnpinned')\n\t);\n}\n\n/** A pin row synthesized from a push event that carried no `systemEventId`. */\nfunction isLivePinRow(row: StoreMessage): boolean {\n\treturn isPinRow(row) && row.id === pinRowId(row.operation, row.value, row.date);\n}\n\n/** Same pin change: same operation, target and actor, dated within the window. */\nfunction isSamePinChange(a: StoreMessage, b: StoreMessage): boolean {\n\treturn (\n\t\tisPinRow(a) &&\n\t\tisPinRow(b) &&\n\t\ta.operation === b.operation &&\n\t\ta.value === b.value &&\n\t\ta.from === b.from &&\n\t\tMath.abs(a.date - b.date) <= SAME_PIN_CHANGE_WINDOW_MS\n\t);\n}\n\n/**\n * The live pin rows in `knownRows` that a timeline page restates under the\n * backend's own id. The backend's row wins: it is the one `PUT /read` accepts\n * and every later history load returns.\n */\nexport function findSupersededLivePinRows(\n\tpageRows: ReadonlyArray<StoreMessage>,\n\tknownRows: ReadonlyArray<StoreMessage>\n): Array<StoreMessage> {\n\tconst serverPinRows = pageRows.filter((row) => isPinRow(row) && !isLivePinRow(row));\n\tif (serverPinRows.length === 0) {\n\t\treturn [];\n\t}\n\treturn knownRows.filter(\n\t\t(row) => isLivePinRow(row) && serverPinRows.some((serverRow) => isSamePinChange(row, serverRow))\n\t);\n}\n\n/**\n * True when the backend's row for this live pin change is already loaded. A\n * live row that carries the backend's id (`systemEventId`) is matched by id:\n * two quick pins by one user are distinct changes.\n */\nexport function hasServerPinRow(\n\tliveRow: StoreMessage,\n\tknownRows: ReadonlyArray<StoreMessage>\n): boolean {\n\tif (!isLivePinRow(liveRow)) {\n\t\treturn knownRows.some((row) => row.id === liveRow.id);\n\t}\n\treturn knownRows.some((row) => !isLivePinRow(row) && isSamePinChange(row, liveRow));\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport type { MessagesDeps } from './messages';\nimport { enqueueWrite } from './writeQueue';\nimport { mapWireMessageToStoreMessage, toTimestamp } from '../domain/inbox';\nimport { hasServerPinRow, isPinRow, pinRowId } from '../domain/pinRows';\nimport type { PinOperation } from '../domain/pinRows';\nimport type { WirePinnedMessage } from '../types/api';\nimport type { WireMessagePinnedEvent, WireMessageUnpinnedEvent } from '../types/events';\nimport type { StoreConfigurationMessage, StoreMessage, StoreTextMessage } from '../types/store';\n\n/**\n * Per room, the time of the last banner write (a pin or unpin event time, or the `pinnedAt` of a\n * `GET /pin` reply) and a count of the banner writes. All times are on the database clock.\n * `fromPage`: the time comes from a pin or unpin line of a timeline page, which writes no banner, so\n * the event or reply of that same change still applies; an empty `GET /pin` reply agrees with an\n * unpin line.\n */\ntype PinVersion = { time: number; writes: number; localUnpins?: number; fromPage?: PinOperation };\n\nexport type PinVersions = Map<string, PinVersion>;\n\nexport function createPinVersions(): PinVersions {\n\treturn new Map();\n}\n\nexport type PinDeps = MessagesDeps & { pinVersions: PinVersions };\n\nexport type PinEventResult = { row: StoreConfigurationMessage; bannerApplied: boolean };\n\nfunction isNewer(current: PinVersion | undefined, time: number): boolean {\n\treturn (\n\t\tcurrent === undefined ||\n\t\ttime > current.time ||\n\t\t(time === current.time && current.fromPage !== undefined)\n\t);\n}\n\nfunction claimBanner(versions: PinVersions, roomId: string, time: number): boolean {\n\tconst current = versions.get(roomId);\n\tif (!isNewer(current, time)) {\n\t\treturn false;\n\t}\n\tversions.set(roomId, {\n\t\t...current,\n\t\ttime,\n\t\twrites: (current?.writes ?? 0) + 1,\n\t\tfromPage: undefined\n\t});\n\treturn true;\n}\n\n/** Resolves the full pinned message from the caller's store, when loaded. */\nexport type FindPinnedMessage = (messageId: string) => StoreTextMessage | undefined;\n\n/**\n * The v1 \"message pinned/unpinned\" configuration row, synthesized from the\n * push event. In v1 the row was a real MUC broadcast persisted in MAM; in v2\n * the backend persists an equivalent timeline SystemEvent and the push event\n * carries its id (`systemEventId`), which becomes the row id. Without it the\n * synthesized id is deterministic on the event fields (`pinRowId`), and when a\n * timeline page restates the change under the backend's id, the backend's row\n * replaces this one (`timeline.ts`). Dated with the system event's `createdAt`\n * when the event carries it, like the other live lines (`systemLines.ts`).\n */\nfunction buildPinConfigMessage(\n\toperation: PinOperation,\n\troomId: string,\n\tmessageId: string,\n\tfrom: string,\n\ttimestamp: string,\n\tsystemEventId?: string\n): StoreConfigurationMessage {\n\tconst date = toTimestamp(timestamp);\n\treturn {\n\t\tid: systemEventId ?? pinRowId(operation, messageId, date),\n\t\troomId,\n\t\tdate,\n\t\ttype: 'configuration',\n\t\toperation,\n\t\tvalue: messageId,\n\t\tfrom,\n\t\tread: 'read'\n\t};\n}\n\n/**\n * `PUT /rooms/{roomId}/messages/{messageId}/pin` — serialized through the\n * same per-room FIFO write queue as the other message writes. Confirmation is\n * echo-only (the 204 has no body): the store is not touched here, exactly\n * like the v1 pin IQ that only surfaced through the MUC config broadcast.\n */\nexport function pinMessage(\n\t{ http, queue }: MessagesDeps,\n\troomId: string,\n\tmessageId: string\n): Promise<void> {\n\treturn enqueueWrite(queue, roomId, async () => {\n\t\tawait http.request<void>(\n\t\t\t`rooms/${encodeURIComponent(roomId)}/messages/${encodeURIComponent(messageId)}/pin`,\n\t\t\t'PUT'\n\t\t);\n\t});\n}\n\nfunction isReplySuperseded(\n\tcurrent: PinVersion | undefined,\n\twritesBefore: number,\n\tlocalUnpinsBefore: number,\n\tlatest: WirePinnedMessage | undefined\n): boolean {\n\tif ((current?.localUnpins ?? 0) !== localUnpinsBefore) {\n\t\treturn true;\n\t}\n\tconst untouched = (current?.writes ?? 0) === writesBefore;\n\treturn (\n\t\t!untouched &&\n\t\t!(latest\n\t\t\t? isNewer(current, toTimestamp(latest.pinnedAt))\n\t\t\t: current?.fromPage === 'messageUnpinned')\n\t);\n}\n\n/**\n * `GET /rooms/{roomId}/pin` — hydrates the room's pinned-message banner (the\n * v2 replacement for the v1 pin IQ + archive-by-id round-trip). The banner\n * prefers the full message resolved from the caller's store (attachment and\n * reply section included); off-window targets fall back to the DTO's\n * `TimelineMessage`, dated with the message's own `createdAt`.\n *\n * The endpoint returns a list; the current pin is the latest by `pinnedAt`\n * (the spike's read, pending the §5.15 answer on PUT replace-vs-accumulate).\n * An empty list CLEARS the banner — a deliberate self-healing improvement\n * over the v1 no-op, which could leave a stale banner after an unpin missed\n * while offline.\n *\n * The write is skipped when a live pin or unpin touched the banner while the\n * request was in flight and the reply is not newer than it, and always when\n * the user unpinned meanwhile (the reply may predate the unpin, whose echo\n * settles the banner). Known gap: an\n * empty reply followed by a stale late `MessagePinned` cannot be told apart\n * (it would need the unpin time from the backend).\n */\nexport async function fetchPinnedMessage(\n\t{ http, bridge, pinVersions }: PinDeps,\n\troomId: string,\n\tfindMessage?: FindPinnedMessage\n): Promise<void> {\n\tconst writesBefore = pinVersions.get(roomId)?.writes ?? 0;\n\tconst localUnpinsBefore = pinVersions.get(roomId)?.localUnpins ?? 0;\n\tconst pins = await http.request<Array<WirePinnedMessage>>(\n\t\t`rooms/${encodeURIComponent(roomId)}/pin`,\n\t\t'GET'\n\t);\n\tconst latest = pins?.length\n\t\t? pins.reduce((current, pin) =>\n\t\t\t\ttoTimestamp(pin.pinnedAt) > toTimestamp(current.pinnedAt) ? pin : current\n\t\t\t)\n\t\t: undefined;\n\tconst current = pinVersions.get(roomId);\n\tif (isReplySuperseded(current, writesBefore, localUnpinsBefore, latest)) {\n\t\treturn;\n\t}\n\tpinVersions.set(roomId, {\n\t\t...current,\n\t\ttime: Math.max(latest ? toTimestamp(latest.pinnedAt) : -Infinity, current?.time ?? -Infinity),\n\t\twrites: (current?.writes ?? 0) + 1,\n\t\tfromPage: undefined\n\t});\n\tif (!latest) {\n\t\tbridge.removePinnedMessage(roomId);\n\t\treturn;\n\t}\n\tconst resolved = findMessage?.(latest.messageId);\n\tbridge.setPinnedMessage(roomId, resolved ?? mapWireMessageToStoreMessage(latest.message));\n}\n\n/**\n * `DELETE /rooms/{roomId}/messages/{messageId}/pin` — echo-only like the PUT.\n * The v1 façade removed the banner optimistically on unpin (and only on\n * unpin): that stays in the app façades, which own the store reads. When the\n * DELETE fails, `GET /pin` runs again: the optimistic removal and a reply\n * dropped while the DELETE was in flight would otherwise leave the banner\n * empty for a pin that still exists. `findMessage` resolves the banner of that\n * `GET /pin`, as in `fetchPinnedMessage`.\n */\nexport function unpinMessage(\n\tdeps: PinDeps,\n\troomId: string,\n\tmessageId: string,\n\tfindMessage?: FindPinnedMessage\n): Promise<void> {\n\tconst { http, queue, pinVersions } = deps;\n\tconst current = pinVersions.get(roomId);\n\tpinVersions.set(roomId, {\n\t\t...current,\n\t\ttime: current?.time ?? -Infinity,\n\t\twrites: (current?.writes ?? 0) + 1,\n\t\tlocalUnpins: (current?.localUnpins ?? 0) + 1\n\t});\n\treturn enqueueWrite(queue, roomId, async () => {\n\t\tawait http.request<void>(\n\t\t\t`rooms/${encodeURIComponent(roomId)}/messages/${encodeURIComponent(messageId)}/pin`,\n\t\t\t'DELETE'\n\t\t);\n\t}).catch((error: unknown) => {\n\t\tfetchPinnedMessage(deps, roomId, findMessage).catch(() => undefined);\n\t\tthrow error;\n\t});\n}\n\n/**\n * Lands the live row unless a timeline page already brought the backend's\n * row for the same change (a page fetched while the event was in flight).\n * Either way the row becomes the room's last message in the chat list, like\n * every v1 configuration row.\n */\nfunction landPinRow(bridge: MessagesDeps['bridge'], row: StoreConfigurationMessage): void {\n\tif (!hasServerPinRow(row, bridge.getRoomMessages(row.roomId))) {\n\t\tbridge.newMessage(row);\n\t}\n\tbridge.setInboxMessages([row]);\n}\n\n/**\n * `MessagePinned` push event — every pinner, own echo included (the only\n * confirmation path). Two v1-parity writes: the configuration row lands in\n * the timeline, and the banner is set: with the target the caller resolved\n * from its store, else with the event's own `message`. The banner is\n * written only when the event `timestamp` (the system event time, the REST\n * `pinnedAt`) is newer than the room's last banner write: `bannerApplied` is\n * false for a stale event, whose row still lands. Returns the row and that\n * flag for the router's me/others effects (app events).\n */\nexport function handleMessagePinned(\n\t{ bridge, pinVersions }: PinDeps,\n\tevent: WireMessagePinnedEvent,\n\tpinnedMessage?: StoreTextMessage\n): PinEventResult {\n\tconst row = buildPinConfigMessage(\n\t\t'messagePinned',\n\t\tevent.roomId,\n\t\tevent.messageId,\n\t\tevent.pinnedBy,\n\t\tevent.systemEventCreatedAt ?? event.timestamp,\n\t\tevent.systemEventId\n\t);\n\tlandPinRow(bridge, row);\n\tconst bannerApplied = claimBanner(pinVersions, event.roomId, toTimestamp(event.timestamp));\n\tif (bannerApplied) {\n\t\tbridge.setPinnedMessage(\n\t\t\tevent.roomId,\n\t\t\tpinnedMessage ?? mapWireMessageToStoreMessage(event.message)\n\t\t);\n\t}\n\treturn { row, bannerApplied };\n}\n\n/**\n * `MessageUnpinned` push event — configuration row plus banner removal (a\n * no-op for the unpinner, whose façade already removed it optimistically\n * like in v1). The removal is ordered like the pin by the event `timestamp`:\n * a stale unpin leaves the banner (`bannerApplied` false) and its row still\n * lands. Returns the row and that flag for the router's effects.\n */\nexport function handleMessageUnpinned(\n\t{ bridge, pinVersions }: PinDeps,\n\tevent: WireMessageUnpinnedEvent\n): PinEventResult {\n\tconst row = buildPinConfigMessage(\n\t\t'messageUnpinned',\n\t\tevent.roomId,\n\t\tevent.messageId,\n\t\tevent.unpinnedBy,\n\t\tevent.systemEventCreatedAt ?? event.timestamp,\n\t\tevent.systemEventId\n\t);\n\tlandPinRow(bridge, row);\n\tconst bannerApplied = claimBanner(pinVersions, event.roomId, toTimestamp(event.timestamp));\n\tif (bannerApplied) {\n\t\tbridge.removePinnedMessage(event.roomId);\n\t}\n\treturn { row, bannerApplied };\n}\n\n/**\n * A temporary room's history clear also removes its pin. The clear time becomes the banner version,\n * so a pin event older than the clear, delivered late, does not bring the banner back. Returns\n * whether the banner was removed (false when a newer pin was already applied).\n */\nexport function clearPinnedBanner(\n\t{ bridge, pinVersions }: PinDeps,\n\troomId: string,\n\tclearedAt: string\n): boolean {\n\tif (!claimBanner(pinVersions, roomId, toTimestamp(clearedAt))) {\n\t\treturn false;\n\t}\n\tbridge.removePinnedMessage(roomId);\n\treturn true;\n}\n\n/**\n * A timeline page carries the room's pin and unpin lines, dated like the pin events. The newest one\n * becomes the banner version, so a pin event or `GET /pin` reply older than it, delivered late, is\n * ignored, while the event of that same change still applies (`fromPage`). It counts as a write, so a\n * `GET /pin` reply in flight is ordered against it. When it is an unpin newer than a known banner\n * version, the banner shows a stale pin (a late event applied while an empty `GET /pin` reply could\n * not be ordered against it) and is removed. With no version the banner content is unknown (after\n * `reset()` it may show a pin newer than an older page), so nothing is removed; an empty `GET /pin`\n * reply in flight still removes it when that line is an unpin.\n */\nexport function applyPagePinLines(\n\t{ bridge, pinVersions }: Pick<PinDeps, 'bridge' | 'pinVersions'>,\n\troomId: string,\n\trows: Array<StoreMessage>\n): void {\n\tconst latest = rows\n\t\t.filter(isPinRow)\n\t\t.reduce<StoreConfigurationMessage | undefined>(\n\t\t\t(acc, row) => (!acc || row.date > acc.date ? row : acc),\n\t\t\tundefined\n\t\t);\n\tconst current = pinVersions.get(roomId);\n\tif (!latest || (current !== undefined && latest.date <= current.time)) {\n\t\treturn;\n\t}\n\tif (current !== undefined && latest.operation === 'messageUnpinned') {\n\t\tclaimBanner(pinVersions, roomId, latest.date);\n\t\tbridge.removePinnedMessage(roomId);\n\t\treturn;\n\t}\n\tpinVersions.set(roomId, {\n\t\t...current,\n\t\ttime: latest.date,\n\t\twrites: (current?.writes ?? 0) + 1,\n\t\tfromPage: latest.operation === 'messageUnpinned' ? 'messageUnpinned' : 'messagePinned'\n\t});\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport { enqueueWrite } from './writeQueue';\nimport type { WriteQueue } from './writeQueue';\nimport { toTimestamp } from '../domain/inbox';\nimport type { HttpClient } from '../http/httpClient';\nimport type { StoreBridge } from '../types/bridge';\nimport type { WireReactionChangedEvent } from '../types/events';\nimport type { StoreMessageFastening } from '../types/store';\n\n/**\n * Latest reaction date applied per `messageId|userId`. Live events and\n * history pages are dated with the same database clock, so anything dated\n * below the stored maximum is a stale state and is never written. Lives as\n * long as the client (it survives a chat registry reset and a reconnection);\n * only `reset()` clears it.\n */\nexport type ReactionVersions = Map<string, number>;\n\nexport type ReactionDeps = {\n\thttp: HttpClient;\n\tbridge: StoreBridge;\n\tqueue: WriteQueue;\n\treactionVersions: ReactionVersions;\n};\n\nexport function createReactionVersions(): ReactionVersions {\n\treturn new Map();\n}\n\ntype ReactionOrder = 'newer' | 'same' | 'older';\n\nfunction acceptReactionDate(\n\tversions: ReactionVersions,\n\tmessageId: string,\n\tuserId: string,\n\tdate: number\n): ReactionOrder {\n\tconst key = `${messageId}|${userId}`;\n\tconst stored = versions.get(key);\n\tif (stored !== undefined && date < stored) {\n\t\treturn 'older';\n\t}\n\tversions.set(key, date);\n\treturn stored === date ? 'same' : 'newer';\n}\n\n/** History fastenings that are not older than what the client already applied for their user. */\nexport function acceptHistoryReactions(\n\tversions: ReactionVersions,\n\tfastenings: Array<StoreMessageFastening>\n): Array<StoreMessageFastening> {\n\treturn fastenings.filter(\n\t\t(fastening) =>\n\t\t\tfastening.action !== 'reaction' ||\n\t\t\tacceptReactionDate(versions, fastening.originalStanzaId, fastening.from, fastening.date) !==\n\t\t\t\t'older'\n\t);\n}\n\nfunction reactionPath(roomId: string, messageId: string): string {\n\treturn `rooms/${encodeURIComponent(roomId)}/messages/${encodeURIComponent(messageId)}/reaction`;\n}\n\n/**\n * `PUT /rooms/{roomId}/messages/{messageId}/reaction` with `{reaction}` —\n * sets or replaces the user's single reaction on the message. Serialized\n * through the per-room FIFO write queue (plan §7.4). Confirmation is\n * echo-only, like the deletion: the 204 has no body, the store moves on the\n * `ReactionChanged` echo (v1 parity — the reaction stanza confirmed through\n * the MUC echo).\n */\nexport function sendReaction(\n\t{ http, queue }: ReactionDeps,\n\troomId: string,\n\tmessageId: string,\n\treaction: string\n): Promise<void> {\n\treturn enqueueWrite(queue, roomId, async () => {\n\t\tawait http.request<void>(reactionPath(roomId, messageId), 'PUT', { reaction });\n\t});\n}\n\n/**\n * `DELETE /rooms/{roomId}/messages/{messageId}/reaction` — removes the user's\n * reaction on the message, whatever emoji it is. Same queue and echo-only\n * confirmation as `sendReaction`.\n */\nexport function removeReaction(\n\t{ http, queue }: ReactionDeps,\n\troomId: string,\n\tmessageId: string\n): Promise<void> {\n\treturn enqueueWrite(queue, roomId, async () => {\n\t\tawait http.request<void>(reactionPath(roomId, messageId), 'DELETE');\n\t});\n}\n\n/**\n * `ReactionChanged` push event — every reactor, own echo included (the only\n * confirmation path). One event per write: `added` and `updated` (an emoji\n * replacement, in one event) become a fastening valued with the new\n * `reaction` dated `updatedAt`; `removed` an empty-valued one dated\n * `deletedAt`, which the projection (latest per user by date) reads as \"no\n * active reaction\" — the v1 semantics verbatim. The id embeds the date:\n * add -> remove -> add again must produce distinct fastenings.\n *\n * Events are ordered per `messageId|userId` by those dates. There is one\n * event per write, so a date equal to the latest applied is the same write\n * delivered twice (or already shown by a history page): it is applied\n * idempotently (same id) but `undefined` is returned, and a date below it is\n * stale and dropped (not written, `undefined`). Only a strictly newer write\n * returns the fastening: the app router owns the me/others effects\n * (animation, browser notification) and must skip them on `undefined`. An\n * event missing the time it needs (`updatedAt` / `deletedAt`) is ignored.\n * No unread bump and no sidebar update: v1 parity.\n */\nexport function handleReactionChanged(\n\t{ bridge, reactionVersions }: ReactionDeps,\n\tevent: WireReactionChangedEvent\n): StoreMessageFastening | undefined {\n\tconst removed = event.operation === 'removed';\n\tconst time = removed ? event.deletedAt : event.updatedAt;\n\tif (!time) {\n\t\treturn undefined;\n\t}\n\tconst date = toTimestamp(time);\n\tconst order = acceptReactionDate(reactionVersions, event.messageId, event.userId, date);\n\tif (order === 'older') {\n\t\treturn undefined;\n\t}\n\tconst id = `r_${event.messageId}_${event.userId}_${event.reaction}_${date}`;\n\tconst fastening: StoreMessageFastening = {\n\t\tid,\n\t\tstanzaId: id,\n\t\troomId: event.roomId,\n\t\tdate,\n\t\ttype: 'fastening',\n\t\taction: 'reaction',\n\t\toriginalStanzaId: event.messageId,\n\t\tfrom: event.userId,\n\t\tvalue: removed ? '' : event.reaction\n\t};\n\tbridge.addFastening([fastening]);\n\treturn order === 'newer' ? fastening : undefined;\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport { mapWireMarkerToStoreMarker } from '../domain/inbox';\nimport type { HttpClient } from '../http/httpClient';\nimport type { WireReadMarker } from '../types/api';\nimport type { StoreBridge } from '../types/bridge';\nimport type { WireReadUpdatedEvent } from '../types/events';\n\nexport type ReadDeps = {\n\thttp: HttpClient;\n\tbridge: StoreBridge;\n};\n\n/**\n * `PUT /rooms/{roomId}/read` — moves the caller's read marker up to\n * `itemId` (204, no body): a message or a system event id (persisted ids\n * only), whose `createdAt` becomes the marker's `itemCreatedAt`. The server ignores a marker\n * that would move back. The v2 replacement for the XEP-0333 `displayed`\n * groupchat stanza. The v1 guards (message present in store, marker not\n * already past it) stay in the app façades, which own the store; the store\n * write happens when the own `ReadUpdated` echo comes back, like in v1 where\n * the displayed stanza echoed through the MUC.\n */\nexport async function markAsRead(\n\t{ http }: ReadDeps,\n\troomId: string,\n\titemId: string\n): Promise<void> {\n\tawait http.request<unknown>(`rooms/${encodeURIComponent(roomId)}/read`, 'PUT', { itemId });\n}\n\n/**\n * `GET /rooms/{roomId}/read` — every member's read marker in one shot: the v2\n * replacement for the v1 smart-markers IQ (`lastMarkers`), with the markers'\n * ids resolved against the room history in store. No v1 call-site survives\n * on v2 (the post-history round-trip died with the inline timeline markers),\n * so this stays an on-demand tool — e.g. for the reconnection catch-up (plan\n * §4 step 17).\n */\nexport async function fetchRoomReadMarkers(\n\t{ http, bridge }: ReadDeps,\n\troomId: string\n): Promise<void> {\n\tconst markers = await http.request<Array<WireReadMarker>>(\n\t\t`rooms/${encodeURIComponent(roomId)}/read`,\n\t\t'GET'\n\t);\n\tconst rows = bridge.getRoomMessages(roomId);\n\tconst mapped = (markers ?? []).map((marker) => mapWireMarkerToStoreMarker(marker, rows));\n\tif (mapped.length > 0) {\n\t\tbridge.updateReadStatus(roomId, mapped);\n\t}\n}\n\n/**\n * `ReadUpdated` push event. One write for every sender, own echo included:\n * `updateReadStatus` already recomputes both the messages' read statuses (for\n * other members' markers) and the unread counter (for the own marker), so the\n * v1 single-path `onDisplayedMessageStanza` behavior is preserved as-is.\n *\n * The event carries the marker itself, `{userId, itemCreatedAt}`: it maps like\n * the inbox and timeline markers, the id resolved against the room history in\n * store and dated `itemCreatedAt` — the server instant, where v1 stamped the\n * arrival time.\n */\nexport function handleReadUpdated({ bridge }: ReadDeps, event: WireReadUpdatedEvent): void {\n\tbridge.updateReadStatus(event.roomId, [\n\t\tmapWireMarkerToStoreMarker(event, bridge.getRoomMessages(event.roomId))\n\t]);\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport { toTimestamp } from './inbox';\nimport type { WireMessage } from '../types/api';\nimport type { StoreAttachment, StoreTextMessage } from '../types/store';\n\n/**\n * The search DTO carries the attachment as a bare `attachmentId`, without\n * name, type or size: a stub keeps the \"has an attachment\" signal.\n */\nfunction stubSearchAttachment(attachmentId: string): StoreAttachment {\n\treturn { id: attachmentId, name: '', mimeType: 'application/octet-stream', size: 0 };\n}\n\n/**\n * Search result -> store TextMessage.\n *\n * - `deleted` comes from `deletedInfo`; a deleted result maps with an empty\n * text like everywhere else (whether the backend returns deleted messages\n * at all is a smoke-test question, plan §5.17).\n * - `edited` comes from `editedInfo`.\n * - a reply keeps only `replyTo`: the search DTO embeds no quoted message.\n * - reactions and pins are not part of the search DTO: the search panel\n * renders sender/date/text only, and results never enter the room history.\n *\n * Returns undefined for results without an id: unusable downstream (the\n * panel keys on it, the jump targets it).\n */\nexport function mapSearchMessageToStoreMessage(\n\tmessage: WireMessage,\n\troomId: string\n): StoreTextMessage | undefined {\n\tif (!message.id) {\n\t\treturn undefined;\n\t}\n\tconst deleted = message.deletedInfo !== undefined;\n\tconst edited = message.editedInfo !== undefined;\n\treturn {\n\t\tid: message.id,\n\t\tstanzaId: message.id,\n\t\troomId: message.roomId ?? roomId,\n\t\tdate: toTimestamp(message.createdAt),\n\t\ttype: 'text',\n\t\tfrom: message.senderId ?? '',\n\t\ttext: deleted ? '' : (message.text ?? ''),\n\t\tread: 'read',\n\t\t...(deleted ? { deleted: true } : {}),\n\t\t...(edited ? { edited: true } : {}),\n\t\t...(message.replyToId ? { replyTo: message.replyToId } : {}),\n\t\t...(message.attachmentId ? { attachment: stubSearchAttachment(message.attachmentId) } : {})\n\t};\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport { mapSearchMessageToStoreMessage } from '../domain/search';\nimport { toIsoMicros } from '../domain/time';\nimport type { HttpClient } from '../http/httpClient';\nimport { buildQueryString } from '../http/queryString';\nimport type { WireMessageSearchResult } from '../types/api';\nimport type { StoreBridge } from '../types/bridge';\nimport type { StoreTextMessage } from '../types/store';\n\nexport type SearchDeps = {\n\thttp: HttpClient;\n\tbridge: StoreBridge;\n};\n\nexport type SearchMessagesOptions = {\n\t/**\n\t * Return results strictly older than this instant (ms since epoch) — the\n\t * server's pagination cursor. Unused by the apps today (the v1 panel has\n\t * no load-more), exposed for the future one.\n\t */\n\tbefore?: number;\n\t/** Id of the oldest result of the previous page: with `before` the cursor becomes (createdAt, id). */\n\tbeforeId?: string;\n\t/**\n\t * Drop results strictly before this instant (ms since epoch) — the v1\n\t * MAM `start` bound (`clearedAt ?? createdAt`), inclusive like the\n\t * timeline's. The backend applies the user's `clearedAt` itself (since\n\t * 20656f0a); the client-side bound stays as a second line of defense.\n\t */\n\tnotBefore?: number;\n\t/** Page size; defaults to the spike's search page. */\n\tlimit?: number;\n};\n\nexport type SearchMessagesResult = {\n\tmessages: Array<StoreTextMessage>;\n\t/** More results exist beyond this page (server truth, unaffected by the notBefore filter). */\n\thasMore: boolean;\n};\n\n/** The spike's search page size (the v1 MAM search was server-bounded instead). */\nconst DEFAULT_SEARCH_PAGE_SIZE = 50;\n\n/**\n * `GET /rooms/{roomId}/messages/search` — full-text search within one room,\n * the v2 replacement of the v1 MAM `full-text-search` form. A read, so no\n * write queue. The mapped page REPLACES the room's search results (v1\n * semantics: one shot per submitted query; pagination composition is the\n * future caller's concern, the slice is replace-only).\n *\n * Results are rendered by the search panel only — they never enter the room\n * history, so unmappable entries (no id) are dropped and cleared-history\n * results are filtered by the caller-provided `notBefore` bound.\n */\nexport async function searchMessages(\n\t{ http, bridge }: SearchDeps,\n\troomId: string,\n\tquery: string,\n\toptions: SearchMessagesOptions = {}\n): Promise<SearchMessagesResult> {\n\tconst queryString = buildQueryString({\n\t\tq: query,\n\t\tlimit: options.limit ?? DEFAULT_SEARCH_PAGE_SIZE,\n\t\tbefore: options.before !== undefined ? toIsoMicros(options.before) : undefined,\n\t\tbeforeId: options.beforeId\n\t});\n\tconst response = await http.request<WireMessageSearchResult>(\n\t\t`rooms/${encodeURIComponent(roomId)}/messages/search${queryString}`,\n\t\t'GET'\n\t);\n\n\tconst messages = (response.messages ?? [])\n\t\t.map((message) => mapSearchMessageToStoreMessage(message, roomId))\n\t\t.filter((message): message is StoreTextMessage => message !== undefined)\n\t\t.filter((message) => options.notBefore === undefined || message.date >= options.notBefore);\n\n\tbridge.setSearchResults(roomId, messages);\n\treturn { messages, hasMore: response.hasMore === true };\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport {\n\tmapSystemEventToStoreMessage,\n\tmapWireMarkerToStoreMarker,\n\tmapWireMessageToStoreMessage,\n\ttoTimestamp\n} from './inbox';\nimport type { WireTimeline, WireTimelineItem, WireTimelineMessage } from '../types/api';\nimport type { StoreMarker, StoreMessage, StoreMessageFastening } from '../types/store';\n\nexport type MappedTimelinePage = {\n\t/** Store-ready messages, filtered by the lower bound; the slice orders and dedups. */\n\tmessages: Array<StoreMessage>;\n\t/**\n\t * Reaction fastenings synthesized from the messages' `ReactionGroup[]`\n\t * (current aggregated state, unlike the v1 MAM which carried the stanza\n\t * history). Ids (`r_{messageId}_{userId}_{emoji}_{date}`, as the live ones) keep\n\t * refetches idempotent through the slice dedup; dated with each user's\n\t * reaction `updatedAt`.\n\t */\n\tfastenings: Array<StoreMessageFastening>;\n\tmarkers: Array<StoreMarker>;\n\t/** Raw item count before mapping/filtering: an empty page means the history is over (v1 rule). */\n\titemCount: number;\n\t/**\n\t * True when the page contains items strictly before the lower bound. The v1\n\t * MAM query bounded `start` with `clearedAt ?? createdAt` and XEP-0313 makes\n\t * `start` inclusive, so only items older than that instant are out of range:\n\t * crossing it is the client-side equivalent of the server's `complete` flag.\n\t */\n\treachedLowerBound: boolean;\n\t/**\n\t * Cursor of the oldest raw item in the page, whatever its type: the retry\n\t * anchor when a page maps to zero store messages (see `fetchTimeline`).\n\t * Undefined on empty pages.\n\t */\n\toldestItem?: { date: number; id?: string };\n};\n\nfunction timelineItemId(item: WireTimelineItem): string | undefined {\n\tif (item.itemType === 'message') {\n\t\treturn item.message.id;\n\t}\n\tif (item.itemType === 'system_event') {\n\t\treturn item.systemEvent.id;\n\t}\n\t// Future item types are skipped by the mapper but must still anchor pagination\n\treturn undefined;\n}\n\n/**\n * Fastenings from one message's aggregated reaction state: one per user,\n * dated with that user's stored `updatedAt`, on the same clock as the live\n * `ReactionChanged` dates, with the live id format: a page and a live event\n * for the same write share one id (refetches stay idempotent), a later state\n * of the same emoji gets a new one.\n */\nfunction mapReactionGroupsToFastenings(message: WireTimelineMessage): Array<StoreMessageFastening> {\n\treturn (message.reactions ?? []).flatMap((group) =>\n\t\tgroup.users.map((user) => {\n\t\t\tconst date = toTimestamp(user.updatedAt);\n\t\t\tconst id = `r_${message.id}_${user.userId}_${group.reaction}_${date}`;\n\t\t\treturn {\n\t\t\t\tid,\n\t\t\t\tstanzaId: id,\n\t\t\t\troomId: message.roomId,\n\t\t\t\tdate,\n\t\t\t\ttype: 'fastening' as const,\n\t\t\t\taction: 'reaction' as const,\n\t\t\t\toriginalStanzaId: message.id,\n\t\t\t\tfrom: user.userId,\n\t\t\t\tvalue: group.reaction\n\t\t\t};\n\t\t})\n\t);\n}\n\n/**\n * One timeline page -> store writes. Messages and known system events map to\n * the same store shapes the v1 history produced; unknown system event types\n * are skipped. Reactions arrive\n * as aggregated `ReactionGroup[]` on each message and are synthesized into\n * the v1 per-user fastenings — in v1 they traveled as separate MAM stanzas.\n *\n * Markers resolve against `knownRows` (the room history already in store)\n * plus this page: the response repeats the current markers on every page, so\n * an older page alone would anchor a recent marker on its own newest row.\n */\nexport function mapTimelinePage(\n\tpage: WireTimeline,\n\troomId: string,\n\tnotBefore?: number,\n\tknownRows: ReadonlyArray<StoreMessage> = []\n): MappedTimelinePage {\n\tconst items = page.items ?? [];\n\tconst lowerBound = notBefore ?? 0;\n\n\tconst messages: Array<StoreMessage> = [];\n\tconst fastenings: Array<StoreMessageFastening> = [];\n\tlet reachedLowerBound = false;\n\tlet oldestItem: MappedTimelinePage['oldestItem'];\n\titems.forEach((item) => {\n\t\tconst date = toTimestamp(item.createdAt);\n\t\tif (!oldestItem || date < oldestItem.date) {\n\t\t\tconst id = timelineItemId(item);\n\t\t\toldestItem = { date, ...(id !== undefined ? { id } : {}) };\n\t\t}\n\t\t// Strictly before: XEP-0313 `start` is inclusive, so an item exactly at\n\t\t// the bound (e.g. ROOM_CREATED sharing the room's createdAt) stays in.\n\t\tif (lowerBound > 0 && date < lowerBound) {\n\t\t\treachedLowerBound = true;\n\t\t\treturn;\n\t\t}\n\t\tif (item.itemType === 'message') {\n\t\t\tmessages.push(mapWireMessageToStoreMessage(item.message));\n\t\t\tfastenings.push(...mapReactionGroupsToFastenings(item.message));\n\t\t\treturn;\n\t\t}\n\t\tif (item.itemType === 'system_event') {\n\t\t\tconst mapped = mapSystemEventToStoreMessage(item.systemEvent, roomId);\n\t\t\tif (mapped) {\n\t\t\t\tmessages.push(mapped);\n\t\t\t}\n\t\t}\n\t});\n\n\tconst rows = [...knownRows, ...messages];\n\treturn {\n\t\tmessages,\n\t\tfastenings,\n\t\tmarkers: (page.markers ?? []).map((marker) => mapWireMarkerToStoreMarker(marker, rows)),\n\t\titemCount: items.length,\n\t\treachedLowerBound,\n\t\t...(oldestItem ? { oldestItem } : {})\n\t};\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport { applyPagePinLines } from './pin';\nimport type { PinVersions } from './pin';\nimport { acceptHistoryReactions } from './reactions';\nimport type { ReactionVersions } from './reactions';\nimport { findSupersededLivePinRows } from '../domain/pinRows';\nimport { toIsoMicros } from '../domain/time';\nimport { mapTimelinePage } from '../domain/timeline';\nimport type { HttpClient } from '../http/httpClient';\nimport { buildQueryString } from '../http/queryString';\nimport type { WireTimeline } from '../types/api';\nimport type { StoreBridge } from '../types/bridge';\n\nexport type TimelineDeps = {\n\thttp: HttpClient;\n\tbridge: StoreBridge;\n\treactionVersions: ReactionVersions;\n\tpinVersions: PinVersions;\n};\n\nexport type FetchTimelineOptions = {\n\t/** Return items strictly older than this instant (ms since epoch) — the v1 MAM `end` bound. */\n\tbefore?: number;\n\t/**\n\t * Id of the message anchoring the page boundary together with `before`: the\n\t * server paginates on the composite cursor (createdAt, id) so messages that\n\t * share the same millisecond are not skipped across pages.\n\t */\n\tbeforeId?: string;\n\t/**\n\t * Drop items strictly before this instant (ms since epoch) and stop\n\t * paginating there — the v1 MAM `start` bound (`clearedAt ?? createdAt` in\n\t * both apps), inclusive per XEP-0313: an item exactly at the bound stays in.\n\t */\n\tnotBefore?: number;\n\t/** Page size; defaults to the v1 MAM quantity. */\n\tlimit?: number;\n};\n\n/** The v1 default MAM page size (`requestHistory(roomId, end, quantity = 50)`). */\nconst DEFAULT_PAGE_SIZE = 50;\n\n/**\n * Parity cap from the v1 mobile fork (`XMPPClient.requestHistoryRange`): a\n * reconnection gap wider than this many pages is abandoned mid-fill — the\n * missing middle heals on the next full history load.\n */\nconst MAX_GAP_PAGES = 20;\n\n/** One mapped page -> store, in the v1 handleHistory write order. */\nfunction writeMappedPage(\n\t{ bridge, reactionVersions, pinVersions }: TimelineDeps,\n\troomId: string,\n\tpage: ReturnType<typeof mapTimelinePage>\n): void {\n\t// Fastenings first, like the v1 handleHistory write order\n\tconst fastenings = acceptHistoryReactions(reactionVersions, page.fastenings);\n\tif (fastenings.length > 0) {\n\t\tbridge.addFastening(fastenings);\n\t}\n\tif (page.messages.length > 0) {\n\t\t// A live pin row the page restates gives way to the backend's row: the\n\t\t// reconnection gap-fill pages back over the rows landed before the gap\n\t\tfindSupersededLivePinRows(page.messages, bridge.getRoomMessages(roomId)).forEach((row) => {\n\t\t\tbridge.removePlaceholderMessage(roomId, row.id);\n\t\t});\n\t\tbridge.updateHistory(roomId, page.messages);\n\t\tapplyPagePinLines({ bridge, pinVersions }, roomId, page.messages);\n\t}\n\tif (page.markers.length > 0) {\n\t\tbridge.updateReadStatus(roomId, page.markers);\n\t}\n}\n\n/**\n * `GET /rooms/{roomId}/timeline` — one backward history page: messages and\n * system events land in the room history, and the read markers carried by the\n * response replace the v1 post-page `lastMarkers` round-trip.\n *\n * History becomes fully loaded when any of the v1 conditions holds:\n * - the server has nothing older (`hasMoreBefore` false — the MAM `complete` flag),\n * - the page is empty (v1 treated an empty result as a cleared history),\n * - the page crossed the `notBefore` lower bound.\n * On fully loaded the creation message is synthesized exactly like in v1; the\n * slice self-guards, so nothing is added when the backend already delivered\n * `ROOM_CREATED` in the timeline.\n *\n * `hasMoreAfter` is deliberately unused: every consumer paginates backwards —\n * the UI from the live edge, the search-jump walk and the reconnection\n * gap-fill (`fetchTimelineGap`) on the same axis.\n */\nexport async function fetchTimeline(\n\tdeps: TimelineDeps,\n\troomId: string,\n\toptions: FetchTimelineOptions = {}\n): Promise<void> {\n\tconst { http, bridge } = deps;\n\tconst query = buildQueryString({\n\t\tbefore: options.before !== undefined ? toIsoMicros(options.before) : undefined,\n\t\tbeforeId: options.beforeId,\n\t\tlimit: options.limit ?? DEFAULT_PAGE_SIZE\n\t});\n\tconst response = await http.request<WireTimeline>(\n\t\t`rooms/${encodeURIComponent(roomId)}/timeline${query}`,\n\t\t'GET'\n\t);\n\n\tconst page = mapTimelinePage(response, roomId, options.notBefore, bridge.getRoomMessages(roomId));\n\twriteMappedPage(deps, roomId, page);\n\n\tconst fullyLoaded =\n\t\tresponse.hasMoreBefore === false || page.itemCount === 0 || page.reachedLowerBound;\n\tif (fullyLoaded) {\n\t\tbridge.setHistoryIsFullyLoaded(roomId);\n\t\tbridge.addCreateRoomMessage(roomId);\n\t\treturn;\n\t}\n\n\t// v1 parity: a page holding only unmappable items (unknown system event\n\t// types today, reactions until the fastenings step) must still advance the\n\t// cursor, otherwise the UI would re-request the same page forever — v1 did\n\t// the same when a MAM page carried only fastenings. Terminates because each\n\t// hop anchors strictly further back in time.\n\tif (page.messages.length === 0 && page.oldestItem) {\n\t\tawait fetchTimeline(deps, roomId, {\n\t\t\t...options,\n\t\t\tbefore: page.oldestItem.date,\n\t\t\t// The caller's beforeId anchored the page just consumed: replace it, or\n\t\t\t// drop it when the oldest item carries no id.\n\t\t\tbeforeId: page.oldestItem.id\n\t\t});\n\t}\n}\n\nexport type FetchTimelineGapOptions = {\n\t/**\n\t * Upper bound of the gap (exclusive, like the plain timeline cursor): pass\n\t * `newestKnown.date + 1` to include the newest known message itself — the\n\t * v1 mobile range query did the same (`end = beforeDate + 1`) and the store\n\t * dedup absorbs the overlap.\n\t */\n\tbefore: number;\n\t/** Composite-cursor id for the upper bound, when it anchors a known message. */\n\tbeforeId?: string;\n\t/**\n\t * Lower bound of the gap: the newest instant already in store, capped by the\n\t * caller with `clearedAt`/`createdAt` like the v1 mobile `effectiveStart`.\n\t * Inclusive per the shared mapper rule (an item exactly at the bound stays).\n\t */\n\tnotBefore: number;\n\t/** Page size; defaults to the v1 MAM quantity. */\n\tlimit?: number;\n};\n\n/**\n * Fill a bounded hole in a room's loaded history — the reconnection catch-up\n * counterpart of the v1 mobile `requestHistoryRange`: page backwards from\n * `before` until the gap closes on `notBefore`, writing messages, fastenings\n * and markers exactly like `fetchTimeline`, but WITHOUT ever touching\n * `setHistoryIsFullyLoaded`/`addCreateRoomMessage` — older history still\n * exists below the gap, those semantics belong to the full-room loader.\n *\n * Stops when the lower bound is crossed, the server has nothing older, the\n * page is empty, the cursor stalls, or after MAX_GAP_PAGES pages (v1 cap): an\n * unfilled remainder heals on the next full history load.\n */\nexport async function fetchTimelineGap(\n\tdeps: TimelineDeps,\n\troomId: string,\n\toptions: FetchTimelineGapOptions\n): Promise<void> {\n\tconst { http, bridge } = deps;\n\tlet { before } = options;\n\tlet { beforeId } = options;\n\tfor (let pageCount = 0; pageCount < MAX_GAP_PAGES; pageCount += 1) {\n\t\t// The cursor reached the bound: the gap is closed — the v1 early exit\n\t\t// (`currentEnd <= effectiveStart`), which also spares the extra request\n\t\t// when a page ends exactly at the bound\n\t\tif (before <= options.notBefore) {\n\t\t\treturn;\n\t\t}\n\t\tconst query = buildQueryString({\n\t\t\tbefore: toIsoMicros(before),\n\t\t\tbeforeId,\n\t\t\tlimit: options.limit ?? DEFAULT_PAGE_SIZE\n\t\t});\n\t\t// eslint-disable-next-line no-await-in-loop\n\t\tconst response = await http.request<WireTimeline>(\n\t\t\t`rooms/${encodeURIComponent(roomId)}/timeline${query}`,\n\t\t\t'GET'\n\t\t);\n\n\t\tconst page = mapTimelinePage(\n\t\t\tresponse,\n\t\t\troomId,\n\t\t\toptions.notBefore,\n\t\t\tbridge.getRoomMessages(roomId)\n\t\t);\n\t\twriteMappedPage(deps, roomId, page);\n\n\t\t// Gap closed (bound crossed), server exhausted, or empty page\n\t\tif (page.reachedLowerBound || response.hasMoreBefore === false || page.itemCount === 0) {\n\t\t\treturn;\n\t\t}\n\t\t// Defensive stall guard: a page that does not move the cursor strictly\n\t\t// backwards would loop forever against a buggy backend\n\t\tif (!page.oldestItem || page.oldestItem.date >= before) {\n\t\t\treturn;\n\t\t}\n\t\tbefore = page.oldestItem.date;\n\t\tbeforeId = page.oldestItem.id;\n\t}\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport type { StoreBridge } from '../types/bridge';\nimport type { WireTypingEvent } from '../types/events';\n\n// The SDK compiles against pure ES libs (no DOM, no Node types — portability\n// by construction): the host timers every target provides (browser, React\n// Native, Node) are ambient-typed here with the minimal shared shape.\ndeclare const setTimeout: (handler: () => void, timeout: number) => unknown;\ndeclare const clearTimeout: (handle: unknown) => void;\n\n/**\n * Safety-net expiry for a typing indicator that never receives its `stopped`\n * (lost event, killed app): the v1 handlers used the same 7s window.\n */\nexport const TYPING_EXPIRE_MS = 7000;\n\n/** One auto-expire timer per (room, user) pair, owned by the client instance. */\nexport type TypingTimers = Map<string, unknown>;\n\nexport function createTypingTimers(): TypingTimers {\n\treturn new Map();\n}\n\nexport function clearTypingTimers(timers: TypingTimers): void {\n\ttimers.forEach((timer) => clearTimeout(timer));\n\ttimers.clear();\n}\n\nexport type TypingDeps = {\n\tbridge: StoreBridge;\n\ttimers: TypingTimers;\n};\n\n/**\n * `Typing` push event — the only chat traffic the client also SENDS on the\n * socket, but the outbound action stays in the apps (they own the /events\n * WebSocket until plan §4 step 18); the SDK owns the receive path. Anything\n * but `stopped` means `started`, the backend's own normalization. Timers are\n * keyed per (room, user): the v1 web handler shared a single debounce across\n * every pair — two concurrent writers could orphan an indicator — while the\n * v1 mobile fork already tracked pairs; the SDK standardizes on the correct\n * variant. The backend relays the event to everyone but the typist, and the\n * app routers filter the own one anyway (v1 parity).\n */\nexport function handleTyping({ bridge, timers }: TypingDeps, event: WireTypingEvent): void {\n\tconst key = `${event.roomId}:${event.userId}`;\n\tconst existing = timers.get(key);\n\tif (existing) {\n\t\tclearTimeout(existing);\n\t\ttimers.delete(key);\n\t}\n\tconst started = event.status !== 'stopped';\n\tbridge.setIsWriting(event.roomId, event.userId, started);\n\tif (started) {\n\t\ttimers.set(\n\t\t\tkey,\n\t\t\tsetTimeout(() => {\n\t\t\t\ttimers.delete(key);\n\t\t\t\tbridge.setIsWriting(event.roomId, event.userId, false);\n\t\t\t}, TYPING_EXPIRE_MS)\n\t\t);\n\t}\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport { deleteMessage, handleMessageDeleted } from './delete';\nimport { editMessage, handleMessageEdited } from './edit';\nimport type { EditMessageParams } from './edit';\nimport { forwardMessages, handleMessageForwarded } from './forward';\nimport type { ForwardMessageRef } from './forward';\nimport { fetchInbox, handleRoomCreated } from './inbox';\nimport {\n\tconfirmAttachmentUpload,\n\tcreateSendRetries,\n\thandleMessageReceived,\n\tresetSends,\n\tretryPendingSends,\n\tsendAttachment,\n\tsendMessage\n} from './messages';\nimport type {\n\tConfirmAttachmentUploadParams,\n\tSendAttachmentParams,\n\tSendMessageParams\n} from './messages';\nimport {\n\tclearPinnedBanner,\n\tcreatePinVersions,\n\tfetchPinnedMessage,\n\thandleMessagePinned,\n\thandleMessageUnpinned,\n\tpinMessage,\n\tunpinMessage\n} from './pin';\nimport type { FindPinnedMessage, PinEventResult } from './pin';\nimport {\n\tcreatePresenceGuard,\n\tfetchPresence,\n\thandlePresenceChanged,\n\tresetPresenceGuard\n} from './presence';\nimport {\n\tcreateReactionVersions,\n\thandleReactionChanged,\n\tremoveReaction,\n\tsendReaction\n} from './reactions';\nimport { fetchRoomReadMarkers, handleReadUpdated, markAsRead } from './read';\nimport { searchMessages } from './search';\nimport type { SearchMessagesOptions, SearchMessagesResult } from './search';\nimport {\n\thandleMeetingDeclined,\n\thandleMeetingStarted,\n\thandleMeetingStopped,\n\tresolveRoomSnapshot,\n\thandleRoomDescriptionChanged,\n\thandleRoomHistoryCleared,\n\thandleRoomMemberAdded,\n\thandleRoomMemberRemoved,\n\thandleRoomNameChanged,\n\thandleRoomPictureChanged,\n\thandleRoomPictureDeleted\n} from './systemLines';\nimport type { RoomFieldEventResult, RoomFieldVersions } from './systemLines';\nimport { fetchTimeline, fetchTimelineGap } from './timeline';\nimport type { FetchTimelineGapOptions, FetchTimelineOptions } from './timeline';\nimport { clearTypingTimers, createTypingTimers, handleTyping } from './typing';\nimport { createWriteQueue } from './writeQueue';\nimport type { HttpClient } from '../http/httpClient';\nimport type { StoreBridge } from '../types/bridge';\nimport type {\n\tWireMeetingDeclinedEvent,\n\tWireMeetingStartedEvent,\n\tWireMeetingStoppedEvent,\n\tWireMessageDeletedEvent,\n\tWireMessageEditedEvent,\n\tWireMessageForwardedEvent,\n\tWireMessagePinnedEvent,\n\tWireMessageReceivedEvent,\n\tWireMessageUnpinnedEvent,\n\tWirePresenceChangedEvent,\n\tWireReactionChangedEvent,\n\tWireReadUpdatedEvent,\n\tWireRoomCreatedEvent,\n\tWireRoomDescriptionChangedEvent,\n\tWireRoomHistoryClearedEvent,\n\tWireRoomMemberAddedEvent,\n\tWireRoomMemberRemovedEvent,\n\tWireRoomNameChangedEvent,\n\tWireRoomPictureChangedEvent,\n\tWireRoomPictureDeletedEvent,\n\tWireTypingEvent\n} from '../types/events';\nimport type {\n\tStoreConfigurationMessage,\n\tStoreMessage,\n\tStoreMessageFastening,\n\tStoreTextMessage\n} from '../types/store';\n\nexport type WscClientDeps = {\n\thttp: HttpClient;\n\tbridge: StoreBridge;\n};\n\nexport type WscClient = {\n\t/** `GET /inbox`: hydrates last messages, unread counts, markers and presence. */\n\tfetchInbox: () => Promise<void>;\n\t/** `GET /rooms/{roomId}/timeline`: hydrates one backward history page and its markers. */\n\tfetchTimeline: (roomId: string, options?: FetchTimelineOptions) => Promise<void>;\n\t/**\n\t * Reconnection catch-up: fills a bounded hole in a room's loaded history by\n\t * paging backwards from `before` to `notBefore`, without ever marking the\n\t * history as fully loaded (the v1 mobile `requestHistoryRange` parity).\n\t */\n\tfetchTimelineGap: (roomId: string, options: FetchTimelineGapOptions) => Promise<void>;\n\t/**\n\t * `GET /rooms/{roomId}/messages/search`: full-text search in one room.\n\t * Replaces the room's search results and returns the mapped page with the\n\t * server's `hasMore` (the caller owns pagination composition, if any).\n\t */\n\tsearchMessages: (\n\t\troomId: string,\n\t\tquery: string,\n\t\toptions?: SearchMessagesOptions\n\t) => Promise<SearchMessagesResult>;\n\t/** `POST /presence/batch`: hydrates presence + last activity for N users at once. */\n\tfetchPresence: (userIds: Array<string>) => Promise<void>;\n\t/** `PresenceChanged` push event: online flag now, last activity refresh on offline. */\n\thandlePresenceChanged: (event: WirePresenceChangedEvent) => Promise<void>;\n\t/** `PUT /rooms/{roomId}/read`: moves the caller's read marker up to itemId (message or system event). */\n\tmarkAsRead: (roomId: string, itemId: string) => Promise<void>;\n\t/** `GET /rooms/{roomId}/read`: hydrates every member's read marker for one room. */\n\tfetchRoomReadMarkers: (roomId: string) => Promise<void>;\n\t/**\n\t * `ReadUpdated` push event: one member's marker moved (own echo included),\n\t * resolved against the room history in store like the inbox and timeline\n\t * markers.\n\t */\n\thandleReadUpdated: (event: WireReadUpdatedEvent) => void;\n\t/**\n\t * `POST /rooms/{roomId}/messages`: one outgoing text, FIFO-serialized per\n\t * room. Resolves once confirmed (201 or echo). A certain rejection (4xx but\n\t * 408, 409, 429) removes the placeholder and rejects; any other failure,\n\t * no answer within 30 s included, keeps it pending and retries the same\n\t * tempId (2 s to 60 s, at once on `retryPendingSends`) for 50 minutes,\n\t * then removes it and rejects.\n\t */\n\tsendMessage: (params: SendMessageParams) => Promise<void>;\n\t/**\n\t * Attachment upload through the app's multipart (`upload`), confirmed and\n\t * retried like `sendMessage` but with a 30 s to 10 minutes backoff, and\n\t * given up at the third 409 in a row (a claim the server left stuck answers\n\t * 409 for 1 hour: send again with a new tempId); the attempt in flight is\n\t * aborted when the SDK gives up. Resolves with the confirmed message.\n\t */\n\tsendAttachment: (params: SendAttachmentParams) => Promise<StoreMessage | undefined>;\n\t/**\n\t * Retries the pending sends and uploads at once, in send order per room,\n\t * restarting their backoff, after writing back the placeholders missing\n\t * from the store. Call it on every `WebsocketConnected`, after any store\n\t * reset of the reconnection.\n\t */\n\tretryPendingSends: () => void;\n\t/**\n\t * `MessageReceived` push event: store writes for every sender, the\n\t * placeholder promoted on `tempId`, which also confirms the pending send\n\t * with that tempId; returns the mapped message. Quote and attachment come\n\t * from the event's `TimelineMessage`.\n\t */\n\thandleMessageReceived: (event: WireMessageReceivedEvent) => StoreMessage;\n\t/**\n\t * Confirms an attachment upload from its 201 (`POST /rooms/{roomId}/attachments`,\n\t * a multipart the app sends): the placeholder promoted like a send's,\n\t * idempotent with the `MessageReceived` echo. Returns the confirmed\n\t * message, nothing on an incomplete 201.\n\t */\n\tconfirmAttachmentUpload: (params: ConfirmAttachmentUploadParams) => StoreMessage | undefined;\n\t/** `PUT /rooms/{roomId}/messages/{messageId}/edit`: FIFO-serialized with the room's sends. */\n\teditMessage: (params: EditMessageParams) => Promise<void>;\n\t/**\n\t * `MessageEdited` push event: synthesizes the EDIT fastening for every\n\t * editor (own echo included), attributed to the edited message's sender\n\t * from the room history. When the edit hits the room's last message the\n\t * app resolves it fresh from its store and passes it here for the sidebar\n\t * update.\n\t */\n\thandleMessageEdited: (event: WireMessageEditedEvent, lastMessage?: StoreTextMessage) => void;\n\t/** `DELETE /rooms/{roomId}/messages/{messageId}`: FIFO-serialized, echo-confirmed (204 has no body). */\n\tdeleteMessage: (roomId: string, messageId: string) => Promise<void>;\n\t/**\n\t * `MessageDeleted` push event: synthesizes the DELETE fastening for every\n\t * deleter (own echo included — the only confirmation path). Same\n\t * lastMessage contract as handleMessageEdited.\n\t */\n\thandleMessageDeleted: (event: WireMessageDeletedEvent, lastMessage?: StoreTextMessage) => void;\n\t/**\n\t * `PUT …/messages/{messageId}/reaction`: sets or replaces the user's single\n\t * reaction; FIFO-serialized, echo-confirmed (204 has no body).\n\t */\n\tsendReaction: (roomId: string, messageId: string, reaction: string) => Promise<void>;\n\t/**\n\t * `DELETE …/messages/{messageId}/reaction`: removes the user's reaction,\n\t * whatever the emoji; FIFO-serialized, echo-confirmed.\n\t */\n\tremoveReaction: (roomId: string, messageId: string) => Promise<void>;\n\t/**\n\t * `ReactionChanged` push event: synthesizes the per-user reaction\n\t * fastening (removals carry an empty value) for every reactor, own echo\n\t * included — the only confirmation path. Returns the fastening for the\n\t * app router's me/others effects (animation, browser notification), or\n\t * undefined when the event is not newer than the latest applied for that\n\t * user and message (a duplicate, applied again idempotently, or stale and\n\t * dropped): the router must skip its effects.\n\t */\n\thandleReactionChanged: (event: WireReactionChangedEvent) => StoreMessageFastening | undefined;\n\t/**\n\t * `POST /rooms/{toRoomId}/forward`: one bulk request per destination,\n\t * FIFO-serialized on the destination room. Fire-and-forget: the\n\t * MessageForwarded echo is the only store write.\n\t */\n\tforwardMessages: (toRoomId: string, messages: Array<ForwardMessageRef>) => Promise<void>;\n\t/**\n\t * `MessageForwarded` push event: to the receiving room this is a new\n\t * message — store writes like handleMessageReceived, the me/others split\n\t * stays in the app router. Returns the mapped message for those effects.\n\t */\n\thandleMessageForwarded: (event: WireMessageForwardedEvent) => StoreMessage;\n\t/** `PUT …/messages/{messageId}/pin`: FIFO-serialized, echo-confirmed (204 has no body). */\n\tpinMessage: (roomId: string, messageId: string) => Promise<void>;\n\t/**\n\t * `DELETE …/messages/{messageId}/pin`: FIFO-serialized, echo-confirmed (204 has no body). When\n\t * it fails, `GET /pin` runs again, with `findMessage` as in `fetchPinnedMessage`.\n\t */\n\tunpinMessage: (\n\t\troomId: string,\n\t\tmessageId: string,\n\t\tfindMessage?: FindPinnedMessage\n\t) => Promise<void>;\n\t/**\n\t * `GET /rooms/{roomId}/pin`: hydrates the banner with the latest pin —\n\t * the full store message when the caller resolves it, the DTO's\n\t * message otherwise. An empty list clears the banner.\n\t */\n\tfetchPinnedMessage: (roomId: string, findMessage?: FindPinnedMessage) => Promise<void>;\n\t/**\n\t * `MessagePinned` push event: synthesizes the v1 configuration row for\n\t * every pinner (own echo included — the only confirmation path) and sets\n\t * the banner with the target the app resolved from its store, else with the\n\t * event's message, both only when the event is newer than the room's last\n\t * banner write (`bannerApplied`). Returns the row and that flag for the\n\t * router's me/others effects.\n\t */\n\thandleMessagePinned: (\n\t\tevent: WireMessagePinnedEvent,\n\t\tpinnedMessage?: StoreTextMessage\n\t) => PinEventResult;\n\t/**\n\t * `MessageUnpinned` push event: configuration row plus banner removal\n\t * (idempotent over the unpinner's optimistic remove), ordered by the event\n\t * time like the pin. Returns the row and `bannerApplied`.\n\t */\n\thandleMessageUnpinned: (event: WireMessageUnpinnedEvent) => PinEventResult;\n\t/**\n\t * A temporary room's history clear removes its pin banner, versioned by `clearedAt`. Returns\n\t * false when a newer pin was already applied.\n\t */\n\tclearPinnedBanner: (roomId: string, clearedAt: string) => boolean;\n\t/**\n\t * `RoomCreated` push event: `GET /rooms/{roomId}/timeline` for the newest\n\t * item, which becomes the new room's last message in the chat list.\n\t */\n\thandleRoomCreated: (event: WireRoomCreatedEvent) => Promise<void>;\n\t/**\n\t * `RoomMemberAdded` push event: lands the `memberAdded` line in the\n\t * timeline and the chat list. Returns the row, or undefined when the event\n\t * announces no line or the line is already in the room.\n\t */\n\thandleRoomMemberAdded: (event: WireRoomMemberAddedEvent) => StoreConfigurationMessage | undefined;\n\t/**\n\t * `RoomMemberRemoved` push event: lands the `memberRemoved` line. Returns\n\t * the row, or undefined when the event announces no line.\n\t */\n\thandleRoomMemberRemoved: (\n\t\tevent: WireRoomMemberRemovedEvent\n\t) => StoreConfigurationMessage | undefined;\n\t/**\n\t * `RoomNameChanged` push event: lands the `roomNameChanged` line. Returns\n\t * the row and `applied`; the app applies the new name to the room only\n\t * when `applied` is true.\n\t */\n\thandleRoomNameChanged: (event: WireRoomNameChangedEvent) => RoomFieldEventResult;\n\t/**\n\t * A room read from REST: the name and description to store, the snapshot's or a newer change's\n\t * already seen (`updatedAt` against the line times).\n\t */\n\tresolveRoomSnapshot: (\n\t\troomId: string,\n\t\tsnapshot: { updatedAt: string; name?: string; description?: string }\n\t) => { name: string | undefined; description: string | undefined };\n\t/**\n\t * `RoomDescriptionChanged` push event: lands the `roomDescriptionChanged`\n\t * line. Returns the row and `applied`, as for the name.\n\t */\n\thandleRoomDescriptionChanged: (event: WireRoomDescriptionChangedEvent) => RoomFieldEventResult;\n\t/**\n\t * `RoomPictureChanged` push event: lands the `roomPictureUpdated` line.\n\t * Returns the row, or undefined when the event announces no line.\n\t */\n\thandleRoomPictureChanged: (\n\t\tevent: WireRoomPictureChangedEvent\n\t) => StoreConfigurationMessage | undefined;\n\t/**\n\t * `RoomPictureDeleted` push event: lands the `roomPictureDeleted` line.\n\t * Returns the row, or undefined when the event announces no line.\n\t */\n\thandleRoomPictureDeleted: (\n\t\tevent: WireRoomPictureDeletedEvent\n\t) => StoreConfigurationMessage | undefined;\n\t/**\n\t * `RoomHistoryCleared` push event: lands the `roomHistoryCleared` line of a\n\t * temporary room cleared for everyone. Returns the row, or undefined on the\n\t * per-user clear. The app still clears the conversation.\n\t */\n\thandleRoomHistoryCleared: (\n\t\tevent: WireRoomHistoryClearedEvent\n\t) => StoreConfigurationMessage | undefined;\n\t/**\n\t * `MeetingStarted` push event: lands the `meetingStarted` line in the\n\t * meeting's room, resolved by the app. Returns the row, or undefined when\n\t * the room has no line (group meetings).\n\t */\n\thandleMeetingStarted: (\n\t\tevent: WireMeetingStartedEvent,\n\t\troomId: string\n\t) => StoreConfigurationMessage | undefined;\n\t/**\n\t * `MeetingStopped` push event: lands the `meetingEnded` line, with the\n\t * event's `durationSec` as value. Returns the row, or undefined when the\n\t * room has no line.\n\t */\n\thandleMeetingStopped: (\n\t\tevent: WireMeetingStoppedEvent,\n\t\troomId: string\n\t) => StoreConfigurationMessage | undefined;\n\t/**\n\t * `MeetingDeclined` push event: lands the `meetingDeclined` line. Returns\n\t * the row, or undefined when the room has no line.\n\t */\n\thandleMeetingDeclined: (\n\t\tevent: WireMeetingDeclinedEvent,\n\t\troomId: string\n\t) => StoreConfigurationMessage | undefined;\n\t/**\n\t * `Typing` push event: flips the member's indicator with a 7s auto-expire\n\t * per (room, user). The own echo is filtered by the app routers; the\n\t * outbound action stays app-side (the apps own the socket until step 18).\n\t */\n\thandleTyping: (event: WireTypingEvent) => void;\n\t/**\n\t * Drops the session state: pending sends (left unsettled, their retries,\n\t * deadlines and uploads cancelled), the write queue, typing timers, the\n\t * presence, reaction, pin and room name/description ordering. Call it on logout or session teardown.\n\t */\n\treset: () => void;\n};\n\n/**\n * Aggregates the per-API client modules behind a single injected-deps entry\n * point. One method lands per migration step (plan §4).\n */\nexport function createWscClient(deps: WscClientDeps): WscClient {\n\tconst reactionVersions = createReactionVersions();\n\tconst messagesDeps = {\n\t\t...deps,\n\t\tqueue: createWriteQueue(),\n\t\tretries: createSendRetries()\n\t};\n\tconst reactionDeps = {\n\t\t...deps,\n\t\tqueue: messagesDeps.queue,\n\t\treactionVersions\n\t};\n\tconst pinVersions = createPinVersions();\n\tconst pinDeps = { ...messagesDeps, pinVersions };\n\tconst timelineDeps = { ...deps, reactionVersions, pinVersions };\n\tconst presenceDeps = { ...deps, presence: createPresenceGuard() };\n\tconst typingDeps = { bridge: deps.bridge, timers: createTypingTimers() };\n\tconst roomFieldVersions: RoomFieldVersions = new Map();\n\tconst roomFieldDeps = { ...deps, roomFieldVersions };\n\treturn {\n\t\tfetchInbox: () => fetchInbox({ ...presenceDeps, roomFieldVersions }),\n\t\tfetchTimeline: (roomId, options) => fetchTimeline(timelineDeps, roomId, options),\n\t\tfetchTimelineGap: (roomId, options) => fetchTimelineGap(timelineDeps, roomId, options),\n\t\tsearchMessages: (roomId, query, options) => searchMessages(deps, roomId, query, options),\n\t\tfetchPresence: (userIds) => fetchPresence(presenceDeps, userIds),\n\t\thandlePresenceChanged: (event) => handlePresenceChanged(presenceDeps, event),\n\t\tmarkAsRead: (roomId, itemId) => markAsRead(deps, roomId, itemId),\n\t\tfetchRoomReadMarkers: (roomId) => fetchRoomReadMarkers(deps, roomId),\n\t\thandleReadUpdated: (event) => handleReadUpdated(deps, event),\n\t\tsendMessage: (params) => sendMessage(messagesDeps, params),\n\t\tsendAttachment: (params) => sendAttachment(messagesDeps, params),\n\t\tretryPendingSends: () => retryPendingSends(messagesDeps),\n\t\thandleMessageReceived: (event) => handleMessageReceived(messagesDeps, event),\n\t\tconfirmAttachmentUpload: (params) => confirmAttachmentUpload(messagesDeps, params),\n\t\teditMessage: (params) => editMessage(messagesDeps, params),\n\t\thandleMessageEdited: (event, lastMessage) =>\n\t\t\thandleMessageEdited(messagesDeps, event, lastMessage),\n\t\tdeleteMessage: (roomId, messageId) => deleteMessage(messagesDeps, roomId, messageId),\n\t\thandleMessageDeleted: (event, lastMessage) =>\n\t\t\thandleMessageDeleted(messagesDeps, event, lastMessage),\n\t\tsendReaction: (roomId, messageId, reaction) =>\n\t\t\tsendReaction(reactionDeps, roomId, messageId, reaction),\n\t\tremoveReaction: (roomId, messageId) => removeReaction(reactionDeps, roomId, messageId),\n\t\thandleReactionChanged: (event) => handleReactionChanged(reactionDeps, event),\n\t\tforwardMessages: (toRoomId, messages) => forwardMessages(messagesDeps, toRoomId, messages),\n\t\thandleMessageForwarded: (event) => handleMessageForwarded(messagesDeps, event),\n\t\tpinMessage: (roomId, messageId) => pinMessage(messagesDeps, roomId, messageId),\n\t\tunpinMessage: (roomId, messageId, findMessage) =>\n\t\t\tunpinMessage(pinDeps, roomId, messageId, findMessage),\n\t\tfetchPinnedMessage: (roomId, findMessage) => fetchPinnedMessage(pinDeps, roomId, findMessage),\n\t\thandleMessagePinned: (event, pinnedMessage) =>\n\t\t\thandleMessagePinned(pinDeps, event, pinnedMessage),\n\t\thandleMessageUnpinned: (event) => handleMessageUnpinned(pinDeps, event),\n\t\tclearPinnedBanner: (roomId, clearedAt) => clearPinnedBanner(pinDeps, roomId, clearedAt),\n\t\thandleRoomCreated: (event) => handleRoomCreated(deps, event),\n\t\thandleRoomMemberAdded: (event) => handleRoomMemberAdded(deps, event),\n\t\thandleRoomMemberRemoved: (event) => handleRoomMemberRemoved(deps, event),\n\t\thandleRoomNameChanged: (event) => handleRoomNameChanged(roomFieldDeps, event),\n\t\tresolveRoomSnapshot: (roomId, snapshot) => resolveRoomSnapshot(roomFieldDeps, roomId, snapshot),\n\t\thandleRoomDescriptionChanged: (event) => handleRoomDescriptionChanged(roomFieldDeps, event),\n\t\thandleRoomPictureChanged: (event) => handleRoomPictureChanged(deps, event),\n\t\thandleRoomPictureDeleted: (event) => handleRoomPictureDeleted(deps, event),\n\t\thandleRoomHistoryCleared: (event) => handleRoomHistoryCleared(deps, event),\n\t\thandleMeetingStarted: (event, roomId) => handleMeetingStarted(deps, event, roomId),\n\t\thandleMeetingStopped: (event, roomId) => handleMeetingStopped(deps, event, roomId),\n\t\thandleMeetingDeclined: (event, roomId) => handleMeetingDeclined(deps, event, roomId),\n\t\thandleTyping: (event) => handleTyping(typingDeps, event),\n\t\treset: (): void => {\n\t\t\tresetSends(messagesDeps);\n\t\t\tclearTypingTimers(typingDeps.timers);\n\t\t\tresetPresenceGuard(presenceDeps.presence);\n\t\t\treactionVersions.clear();\n\t\t\tpinVersions.clear();\n\t\t\troomFieldVersions.clear();\n\t\t}\n\t};\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nexport class WscApiError extends Error {\n\tpublic readonly status: number;\n\n\tpublic readonly endpoint: string;\n\n\tpublic constructor(status: number, endpoint: string) {\n\t\tsuper(`WSC API error ${status} on ${endpoint}`);\n\t\tthis.name = 'WscApiError';\n\t\tthis.status = status;\n\t\tthis.endpoint = endpoint;\n\t}\n}\n","/*\n * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com>\n *\n * SPDX-License-Identifier: AGPL-3.0-only\n */\n\nimport { WscApiError } from './errors';\nimport type {\n\tAbortSignalLike,\n\tHttpMethod,\n\tHttpPorts,\n\tRequestInitLike,\n\tResponseLike\n} from '../types/ports';\n\ndeclare const setTimeout: (handler: () => void, timeout: number) => unknown;\ndeclare const clearTimeout: (handle: unknown) => void;\ndeclare const AbortController: new () => { readonly signal: AbortSignalLike; abort: () => void };\n\nexport const WSC_API_VERSION_HEADER = 'X-WSC-API-VERSION';\nconst CONTENT_TYPE_HEADER = 'Content-Type';\nconst MAX_VERSION_MISMATCH_RETRIES = 3;\n\nexport type JsonBody = Record<string, unknown> | Array<unknown>;\n\nexport type RequestOptions = {\n\t/** Aborts the request and rejects with a `TimeoutError` when no response came in time. */\n\ttimeoutMs?: number;\n};\n\nexport type HttpClient = {\n\trequest: <T>(\n\t\tendpoint: string,\n\t\tmethod: HttpMethod,\n\t\tbody?: JsonBody,\n\t\toptions?: RequestOptions\n\t) => Promise<T>;\n};\n\n/**\n * Joins base and endpoint tolerating any slash combination, so the `baseUrl`\n * port contract is \"any well-formed prefix\" rather than \"must end with `/`\".\n */\nfunction joinUrl(baseUrl: string, endpoint: string): string {\n\treturn `${baseUrl.replace(/\\/+$/, '')}/${endpoint.replace(/^\\/+/, '')}`;\n}\n\nfunction parseVersion(version: string): [number, number, number] | undefined {\n\tconst match = /^(\\d+)\\.(\\d+)\\.(\\d+)$/.exec(version.trim());\n\treturn match ? [Number(match[1]), Number(match[2]), Number(match[3])] : undefined;\n}\n\nfunction compareVersions(a: [number, number, number], b: [number, number, number]): number {\n\treturn a[0] - b[0] || a[1] - b[1] || a[2] - b[2];\n}\n\nfunction renegotiatedVersion(\n\tserverVersion: string | null,\n\tsupportedVersions: ReadonlyArray<string>\n): string | undefined {\n\tconst server = serverVersion ? parseVersion(serverVersion) : undefined;\n\tif (!server) {\n\t\treturn undefined;\n\t}\n\tlet best: { version: string; parsed: [number, number, number] } | undefined;\n\tsupportedVersions.forEach((version) => {\n\t\tconst parsed = parseVersion(version);\n\t\tif (\n\t\t\tparsed &&\n\t\t\tcompareVersions(parsed, server) <= 0 &&\n\t\t\t(!best || compareVersions(parsed, best.parsed) > 0)\n\t\t) {\n\t\t\tbest = { version, parsed };\n\t\t}\n\t});\n\treturn best?.version;\n}\n\nfunction versionToRetry(\n\tresponse: ResponseLike,\n\tclientVersion: string | undefined,\n\tsupportedVersions: ReadonlyArray<string>,\n\tversionRetries: number\n): string | undefined {\n\tif (response.status !== 422 || versionRetries >= MAX_VERSION_MISMATCH_RETRIES) {\n\t\treturn undefined;\n\t}\n\tconst version = renegotiatedVersion(\n\t\tresponse.headers.get(WSC_API_VERSION_HEADER),\n\t\tsupportedVersions\n\t);\n\treturn version === clientVersion ? undefined : version;\n}\n\n// The timeout settles the request even when the fetch port ignores the signal\nfunction fetchWithTimeout(\n\tports: HttpPorts,\n\turl: string,\n\tinit: RequestInitLike,\n\tendpoint: string,\n\ttimeoutMs: number | undefined\n): Promise<ResponseLike> {\n\tif (timeoutMs === undefined) {\n\t\treturn ports.fetch(url, init);\n\t}\n\tconst controller = new AbortController();\n\tconst signalled: RequestInitLike & { signal: AbortSignalLike } = {\n\t\t...init,\n\t\tsignal: controller.signal\n\t};\n\tconst request = ports.fetch(url, signalled);\n\treturn new Promise<ResponseLike>((resolve, reject) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\tcontroller.abort();\n\t\t\treject(\n\t\t\t\tObject.assign(new Error(`WSC API request timed out on ${endpoint}`), {\n\t\t\t\t\tname: 'TimeoutError'\n\t\t\t\t})\n\t\t\t);\n\t\t}, timeoutMs);\n\t\trequest.then(\n\t\t\t(response) => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve(response);\n\t\t\t},\n\t\t\t(error: unknown) => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\treject(error);\n\t\t\t}\n\t\t);\n\t});\n}\n\n/**\n * REST core shared by web and mobile. Reproduces the semantics of the two\n * existing `FetchUtils.ts` (unified — the mobile copy never incremented the\n * 422 retry counter) on top of injected ports:\n *\n * - stamps `X-WSC-API-VERSION` with the client's negotiated version;\n * - on 422, adopts the highest supported version not above the server's and\n * retries (bounded), mirroring the in-production renegotiation;\n * - times out a request on demand (`timeoutMs`), aborting its fetch;\n * - decodes JSON / image blobs, returns the raw response otherwise.\n */\nexport function createHttpClient(ports: HttpPorts): HttpClient {\n\tasync function doRequest<T>(\n\t\tendpoint: string,\n\t\tmethod: HttpMethod,\n\t\tbody: JsonBody | undefined,\n\t\ttimeoutMs: number | undefined,\n\t\tversionRetries: number,\n\t\tauthRetried: boolean\n\t): Promise<T> {\n\t\tconst headers: Record<string, string> = { ...ports.getExtraHeaders?.() };\n\t\tconst clientVersion = ports.versionStore.getApiVersion();\n\t\tif (clientVersion) {\n\t\t\theaders[WSC_API_VERSION_HEADER] = clientVersion;\n\t\t}\n\t\tconst hasBody = body !== undefined;\n\t\tif (hasBody) {\n\t\t\theaders[CONTENT_TYPE_HEADER] = 'application/json';\n\t\t}\n\n\t\tconst baseUrl = typeof ports.baseUrl === 'function' ? ports.baseUrl() : ports.baseUrl;\n\t\tconst response = await fetchWithTimeout(\n\t\t\tports,\n\t\t\tjoinUrl(baseUrl, endpoint),\n\t\t\t{ method, headers, ...(hasBody ? { body: JSON.stringify(body) } : {}) },\n\t\t\tendpoint,\n\t\t\ttimeoutMs\n\t\t);\n\n\t\tconst serverVersion = response.headers.get(WSC_API_VERSION_HEADER);\n\t\tif (serverVersion) {\n\t\t\tports.onServerVersion?.(serverVersion);\n\t\t}\n\n\t\tif (!response.ok) {\n\t\t\tconst retryVersion = versionToRetry(\n\t\t\t\tresponse,\n\t\t\t\tclientVersion,\n\t\t\t\tports.versionStore.getSupportedVersions(),\n\t\t\t\tversionRetries\n\t\t\t);\n\t\t\tif (retryVersion) {\n\t\t\t\tports.logger?.warn(\n\t\t\t\t\t`WSC API version mismatch on ${endpoint}: adopting ${retryVersion} for server version ${serverVersion} (was ${clientVersion ?? 'unset'})`\n\t\t\t\t);\n\t\t\t\tports.versionStore.setApiVersion(retryVersion);\n\t\t\t\treturn doRequest(endpoint, method, body, timeoutMs, versionRetries + 1, authRetried);\n\t\t\t}\n\t\t\tif (response.status === 401 && !authRetried && ports.onUnauthorized) {\n\t\t\t\tconst shouldRetry = await ports.onUnauthorized();\n\t\t\t\tif (shouldRetry) {\n\t\t\t\t\treturn doRequest(endpoint, method, body, timeoutMs, versionRetries, true);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow new WscApiError(response.status, endpoint);\n\t\t}\n\n\t\tconst contentType = response.headers.get(CONTENT_TYPE_HEADER);\n\t\tif (contentType?.includes('application/json')) {\n\t\t\treturn response.json() as Promise<T>;\n\t\t}\n\t\tif (contentType?.includes('image/')) {\n\t\t\treturn response.blob() as Promise<T>;\n\t\t}\n\t\treturn response as T;\n\t}\n\n\treturn {\n\t\trequest: <T>(\n\t\t\tendpoint: string,\n\t\t\tmethod: HttpMethod,\n\t\t\tbody?: JsonBody,\n\t\t\toptions?: RequestOptions\n\t\t): Promise<T> => doRequest(endpoint, method, body, options?.timeoutMs, 0, false)\n\t};\n}\n"],"mappings":";AAcO,SAAS,mBAA+B;AAC9C,SAAO,oBAAI,IAAI;AAChB;AAOO,SAAS,aACf,OACA,QACA,MACa;AACb,QAAM,WAAW,MAAM,IAAI,MAAM,KAAK,QAAQ,QAAQ;AACtD,QAAM,MAAM,SAAS,KAAK,MAAM,IAAI;AACpC,QAAM,OAAO,IAAI;AAAA,IAChB,MAAM;AAAA,IACN,MAAM;AAAA,EACP;AACA,QAAM,IAAI,QAAQ,IAAI;AACtB,OAAK,KAAK,MAAM;AACf,QAAI,MAAM,IAAI,MAAM,MAAM,MAAM;AAC/B,YAAM,OAAO,MAAM;AAAA,IACpB;AAAA,EACD,CAAC;AACD,SAAO;AACR;;;ACnCA,IAAM,oBAAoB;AAEnB,SAAS,eAAe,KAAiC;AAC/D,MAAI,CAAC,KAAK;AAC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