@marktiderman/genesis-chat 0.11.4 → 0.13.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/README.md +162 -4
- package/dist/{chunk-ZQFREERR.js → chunk-3UNYTK62.js} +3 -3
- package/dist/{chunk-ZQFREERR.js.map → chunk-3UNYTK62.js.map} +1 -1
- package/dist/{chunk-5XYDVUPS.js → chunk-GEEJMKQF.js} +29 -4
- package/dist/chunk-GEEJMKQF.js.map +1 -0
- package/dist/{chunk-D4RPOYB7.js → chunk-H4BRVJJ7.js} +193 -30
- package/dist/chunk-H4BRVJJ7.js.map +1 -0
- package/dist/{chunk-O2QSBRSH.js → chunk-SEMN3S6Q.js} +3 -3
- package/dist/{chunk-O2QSBRSH.js.map → chunk-SEMN3S6Q.js.map} +1 -1
- package/dist/{client-DP7rhJ1U.d.ts → client-DXWyDJ2u.d.ts} +29 -0
- package/dist/index.d.ts +4 -4
- package/dist/index.js +3 -3
- package/dist/native.d.ts +355 -145
- package/dist/native.js +701 -217
- package/dist/native.js.map +1 -1
- package/dist/{outbox-C4LnqpKT.d.ts → outbox-Ctngv6Yz.d.ts} +1 -1
- package/dist/push.d.ts +2 -2
- package/dist/react.d.ts +83 -6
- package/dist/react.js +3 -3
- package/dist/server.d.ts +1 -1
- package/dist/server.js +1 -1
- package/dist/{thread-CSzdqNR_.d.ts → thread-mZsRiIGz.d.ts} +1 -1
- package/dist/web.d.ts +24 -7
- package/dist/web.js +140 -67
- package/dist/web.js.map +1 -1
- package/migrations/0006_genesis_chat_read_receipts.sql +110 -0
- package/migrations/0007_genesis_chat_unread_and_delete_for_me.sql +455 -0
- package/migrations/tests/0006_genesis_chat_read_receipts.test.sql +131 -0
- package/migrations/tests/0007_genesis_chat_unread_and_delete_for_me.test.sql +178 -0
- package/package.json +17 -9
- package/src/__tests__/inbox-row-actions.test.tsx +251 -0
- package/src/__tests__/unread-delete-for-me.test.ts +84 -0
- package/src/__tests__/web.test.tsx +5 -2
- package/src/core/client.ts +30 -1
- package/src/core/types.ts +7 -0
- package/src/native/__tests__/bubble-native-feel.test.tsx +153 -0
- package/src/native/__tests__/composer-attach-menu.test.tsx +47 -0
- package/src/native/__tests__/inbox-screen-actions.test.tsx +131 -0
- package/src/native/__tests__/inbox-screen.test.tsx +29 -1
- package/src/native/__tests__/media-cache-key.test.tsx +21 -0
- package/src/native/__tests__/organise-screens.test.tsx +2 -0
- package/src/native/__tests__/receipts.test.ts +95 -0
- package/src/native/__tests__/review-lows.test.tsx +80 -0
- package/src/native/__tests__/sheets-fit.test.tsx +45 -0
- package/src/native/__tests__/stable-hooks.test.tsx +68 -0
- package/src/native/__tests__/thread-layout.test.ts +2 -2
- package/src/native/__tests__/thread-screen-audit.test.tsx +248 -0
- package/src/native/__tests__/thread-screen.test.tsx +111 -0
- package/src/native/__tests__/thread-title.test.tsx +59 -0
- package/src/native/composer.tsx +61 -26
- package/src/native/copy.ts +47 -10
- package/src/native/emoji-picker.tsx +1 -1
- package/src/native/inbox-screen.tsx +52 -27
- package/src/native/index.ts +7 -2
- package/src/native/media.tsx +7 -1
- package/src/native/message-actions-sheet.tsx +1 -1
- package/src/native/message-bubble.tsx +171 -19
- package/src/native/modules.ts +3 -1
- package/src/native/receipts.ts +102 -0
- package/src/native/schedule-sheet.tsx +8 -3
- package/src/native/stack-options.ts +35 -3
- package/src/native/thread-screen.tsx +243 -17
- package/src/native/thread-times.tsx +89 -0
- package/src/native/thread-title.tsx +111 -0
- package/src/native/typing-bubble.tsx +85 -0
- package/src/react/inbox-actions.ts +121 -0
- package/src/react/index.tsx +172 -23
- package/src/web/inbox.tsx +120 -11
- package/src/web/index.ts +1 -1
- package/src/web/memory-client.ts +40 -7
- package/dist/chunk-5XYDVUPS.js.map +0 -1
- package/dist/chunk-D4RPOYB7.js.map +0 -1
package/README.md
CHANGED
|
@@ -7,11 +7,11 @@ replies, threads, reactions, read state, live updates and push.
|
|
|
7
7
|
| Entry | What it is |
|
|
8
8
|
|---|---|
|
|
9
9
|
| `@marktiderman/genesis-chat` | The headless core: types, `createChatClient`, the send outbox, thread logic, media rules. No React. |
|
|
10
|
-
| `/react` | Hooks for web and native: `ChatProvider`, `useInbox`, `useConversation`, `useMessageActions`, and for 0002 `useTopics`, `useScheduled`, `useAvailability`, `useBroadcast`, `useSearch`, `useLinkPreviews`. |
|
|
10
|
+
| `/react` | Hooks for web and native: `ChatProvider`, `useInbox`, `useInboxActions`, `useConversation`, `useMessageActions`, and for 0002 `useTopics`, `useScheduled`, `useAvailability`, `useBroadcast`, `useSearch`, `useLinkPreviews`. |
|
|
11
11
|
| `/web` | Renderers on genesis-ui: inbox, thread, composer (text, photos, voice, video, emoji, scheduled send), media, topics, search, availability, broadcast, and the chat dock. |
|
|
12
12
|
| `/native` | Beta: screens and parts on genesis-ui-native (inbox, thread, search, availability), voice notes, photos and video, and the push block's glue. See "On native" below. |
|
|
13
13
|
| `/server` | `createChatRunner`: works the outbox (push, transcripts, storage cleanup). |
|
|
14
|
-
| `migrations/0001_genesis_chat.sql` … `
|
|
14
|
+
| `migrations/0001_genesis_chat.sql` … `0006_genesis_chat_read_receipts.sql` | The schema, copied into your app by `genesis add chat` in order, each with its pgTAP test. 0003 makes `search_messages` return a hit's `thread_root_id`; 0004 puts every conversation in a tenant (see Tenants); 0006 records when each member read (see Message status). |
|
|
15
15
|
|
|
16
16
|
## On the web
|
|
17
17
|
|
|
@@ -128,7 +128,7 @@ copy and people) inside `GenesisNativeApp`, then put the screens in your routes:
|
|
|
128
128
|
| Screen | What it is | Main props |
|
|
129
129
|
|---|---|---|
|
|
130
130
|
| `ChatInboxScreen` | The conversations on `InboxPage`: avatars, unread counts, the last message, pull to refresh, Mark read, Pin and Archive. | `onOpen(conversationId)`, `onStart`, `kind` / `kinds` / `excludeKinds`, `archived`, `pageProps` |
|
|
131
|
-
| `ChatThreadScreen` | One conversation: grouped bubbles, day lines, replies, reactions, the composer (text, photos, voice notes, video, emoji, scheduled send), topics and the away line. | `conversationId`, `threadRootId`, `jumpTo` (open at a search result), `topic` / `showTopics`, `scheduling`, `availability`, `onOpenAttachment`, `focused` (the navigator's `useIsFocused()`), `keyboardVerticalOffset` |
|
|
131
|
+
| `ChatThreadScreen` | One conversation: grouped bubbles, day lines, replies, reactions, the composer (text, photos, voice notes, video, emoji, scheduled send), topics and the away line. | `conversationId`, `threadRootId`, `jumpTo` (open at a search result), `topic` / `showTopics`, `scheduling`, `availability`, `onOpenAttachment`, `focused` (the navigator's `useIsFocused()`), `active`, `header`, `accessory`, `videoLimitMs`, `receipts` (`"show"` or `"hide"`), `keyboardVerticalOffset` |
|
|
132
132
|
| `ChatSearchScreen` | Search across your conversations or in one, with matches highlighted and transcripts marked. | `onOpen(hit)`, `conversationId`, `conversationTitle` |
|
|
133
133
|
| `ChatAvailabilityScreen` | Your away message, its end, working hours and time zone. | `onSaved` |
|
|
134
134
|
|
|
@@ -147,10 +147,123 @@ across the app, and the logic under them (`composerReducer`, `buildThreadRows`,
|
|
|
147
147
|
Mark read (`registerChatNotificationActions`, `handleChatPushResponse`, `chatThreadMatch`, also on
|
|
148
148
|
`/push` alone).
|
|
149
149
|
|
|
150
|
+
### Message status and typing
|
|
151
|
+
|
|
152
|
+
Under the last message you sent, `ChatThreadScreen` says where it is, as iMessage does:
|
|
153
|
+
|
|
154
|
+
| It says | When |
|
|
155
|
+
|---|---|
|
|
156
|
+
| Sending… | It is still in the outbox, not yet posted. |
|
|
157
|
+
| Sent | Posted, but the outbox still holds it (a video's bytes are still going up). |
|
|
158
|
+
| Delivered | The server has it, and nobody else has read that far. |
|
|
159
|
+
| Read 9:41 | A direct conversation: the other member's `lastReadSeq` has reached it. The time is their `lastReadAt` (migration 0006): the time today, else the day. Without 0006, "Read" with no time. |
|
|
160
|
+
| Read by 2 / Read by everyone | A group: how many of the other members (observers aside) have read that far. It is a button that opens a sheet of who. |
|
|
161
|
+
|
|
162
|
+
A send that failed shows its failure, Retry and Delete instead, as before. `receipts="hide"` leaves
|
|
163
|
+
the status out (an app that doesn't show read state). The logic is `lastSentReceipt` and
|
|
164
|
+
`receiptText`, exported for a screen of your own, and the words are copy (`receiptSending`,
|
|
165
|
+
`receiptDelivered`, `receiptReadAt` and the rest).
|
|
166
|
+
|
|
167
|
+
Migration 0006 adds `members.last_read_at`, set when a member's read place moves past someone
|
|
168
|
+
else's message (posting your own sets nothing; a hidden or deleted message doesn't count), and
|
|
169
|
+
sends a `read` hint on the conversation's topic, so "Delivered" turns to "Read" while the thread
|
|
170
|
+
is open. The hint is only a cue: the thread reads the members again (once for a burst), never the
|
|
171
|
+
hint's own numbers, and only the database sends it (0006 lets clients broadcast nothing but
|
|
172
|
+
typing and presence on a conversation's topic). Conversations of more than 32 members get no hint:
|
|
173
|
+
there, "Read by N" updates when the thread next reads its members (on opening, on reconnecting).
|
|
174
|
+
An observers-only or hidden message shows no status.
|
|
175
|
+
|
|
176
|
+
Members already see each other's `lastReadSeq`, and with 0006 their `lastReadAt` too: every member
|
|
177
|
+
and observer of a conversation can see when each member last read it. There is no setting yet to
|
|
178
|
+
stop sending read receipts (`receipts="hide"` only hides them on the screen that passes it), so an
|
|
179
|
+
app with a privacy policy should decide before it takes 0006.
|
|
180
|
+
|
|
181
|
+
Someone typing shows as a bubble of three dots at the bottom of the thread (`ChatTypingBubble`),
|
|
182
|
+
with their avatar beside it in a group, read out as "Sam is typing…"; someone recording a voice
|
|
183
|
+
note or video keeps the words.
|
|
184
|
+
|
|
150
185
|
Voice notes show their transcript under the player once the server has made one ("Transcribing…"
|
|
151
186
|
until then), folded to three lines with "Show more"; the bubble reads the whole transcript to
|
|
152
187
|
VoiceOver.
|
|
153
188
|
|
|
189
|
+
### How the thread feels, and what an app adds to it
|
|
190
|
+
|
|
191
|
+
The thread follows iMessage where the platform lets it:
|
|
192
|
+
|
|
193
|
+
- **Bubbles.** A run of one sender's messages reads as one shape: the corners where two bubbles
|
|
194
|
+
meet are tight, and the last (or only) one has a tail on the sender's side (`bubbleCorners`).
|
|
195
|
+
- **Times on demand.** Drag the thread left and every message's time slides in at the trailing
|
|
196
|
+
edge; let go and it slides back. The last message of a run keeps its time under it. VoiceOver
|
|
197
|
+
already reads each time in the bubble's label.
|
|
198
|
+
- **Swipe to reply** runs on react-native-gesture-handler when the app passes its
|
|
199
|
+
`ReanimatedSwipeable` as `GenesisModules.swipeable` (the same module `InboxPage` swipes with),
|
|
200
|
+
so the drag stays on the UI thread; without it, a PanResponder does it.
|
|
201
|
+
- **Sending.** With `GenesisModules.reanimated` (Reanimated 4), a message you just sent rises in
|
|
202
|
+
from the composer (`FadeInDown`); not with Reduce Motion, and not a message left in the outbox
|
|
203
|
+
from an earlier launch. While you hold the mic it follows your finger toward cancel and the lock.
|
|
204
|
+
- **Long press** taps a medium impact and opens the message's actions in a sheet that fits them
|
|
205
|
+
(the attach, emoji and scheduled sheets fit theirs too). The + button's menu opens the picker as
|
|
206
|
+
soon as the menu has gone, with no fixed wait.
|
|
207
|
+
- **Where it opens.** At the first unread, with the "New" line at the top, when that line would be
|
|
208
|
+
above the screen; otherwise at the newest. An unread further back than the first page opens at
|
|
209
|
+
the page's oldest unread, and earlier pages load from there. A row the list can't reach (FlatList
|
|
210
|
+
before it has measured that far) opens at the newest instead. Showing another conversation in
|
|
211
|
+
the same `ChatThreadScreen` opens it at its own first unread. With FlashList (`GenesisModules.list`) the list is
|
|
212
|
+
anchored at the bottom, so a send scrolls once. Scrolled up, a "↓ 3 new messages" pill comes up
|
|
213
|
+
when others write; it goes to the newest.
|
|
214
|
+
- **Connection.** "Waiting for network…" while the app's NetInfo (`modules.netInfo`) says
|
|
215
|
+
offline, "Connecting…" while the live channel is down; when nothing could be read, an error with
|
|
216
|
+
Retry in place of "No messages yet".
|
|
217
|
+
|
|
218
|
+
For a thread of the app's own, without copying the screen:
|
|
219
|
+
|
|
220
|
+
| Prop | What it does |
|
|
221
|
+
|---|---|
|
|
222
|
+
| `active` | `false` keeps the thread mounted (a tab, a split view's other pane) without marking it read, and pauses what it plays; turning `true` marks it read. Default `true`. |
|
|
223
|
+
| `header` | An app's own strip above the messages (who the client is, a booking). |
|
|
224
|
+
| `accessory` | `(context) => ReactNode`: an app's tools over the composer. `context` has `conversationId`, `composer` (write into the draft with `composer.dispatch({ type: "text", text })`) and `canPost`. |
|
|
225
|
+
| `videoLimitMs` | The longest video message. Default: the role's recording limit. |
|
|
226
|
+
|
|
227
|
+
`useChatThreadStackOptions` also takes `avatar` (`{ src, name, id }` or an element), `subtitle`
|
|
228
|
+
(left out with `conversationId`, the away line; `null` for none) and `onPressTitle` (the title
|
|
229
|
+
becomes a button, `titleHint` its VoiceOver hint). The default subtitle reads the conversation
|
|
230
|
+
through `ChatProvider`, so mount it above the navigator, or pass `subtitle` yourself. Show the away
|
|
231
|
+
line there and pass `availability={false}` to the screen so it isn't said twice.
|
|
232
|
+
|
|
233
|
+
```tsx
|
|
234
|
+
import { Stack } from "expo-router";
|
|
235
|
+
import { Text } from "react-native";
|
|
236
|
+
import { ChatThreadScreen, useChatThreadStackOptions, type ChatThreadAccessoryContext } from "@marktiderman/genesis-chat/native";
|
|
237
|
+
|
|
238
|
+
function QuickReplies({ composer, canPost }: ChatThreadAccessoryContext) {
|
|
239
|
+
if (!canPost) return null;
|
|
240
|
+
return <Text onPress={() => composer.dispatch({ type: "text", text: "On my way" })}>On my way</Text>;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export function ThreadRoute({ id, focused, onDetails }: { id: string; focused: boolean; onDetails: () => void }) {
|
|
244
|
+
const options = useChatThreadStackOptions({ headerTitle: "Sam", conversationId: id, avatar: { name: "Sam", id }, onPressTitle: onDetails });
|
|
245
|
+
return (
|
|
246
|
+
<>
|
|
247
|
+
<Stack.Screen options={options} />
|
|
248
|
+
<ChatThreadScreen
|
|
249
|
+
conversationId={id}
|
|
250
|
+
active={focused}
|
|
251
|
+
availability={false}
|
|
252
|
+
header={<Text>Acme · Plan B</Text>}
|
|
253
|
+
accessory={(context) => <QuickReplies {...context} />}
|
|
254
|
+
videoLimitMs={60_000}
|
|
255
|
+
/>
|
|
256
|
+
</>
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
For all of it, pass these in the app's Genesis modules (`GenesisNativeApp modules`), at module
|
|
262
|
+
scope: `list: FlashList` (from `@shopify/flash-list` v2), `swipeable: ReanimatedSwipeable` (from
|
|
263
|
+
`react-native-gesture-handler/ReanimatedSwipeable`, with `GestureHandlerRootView` at the root),
|
|
264
|
+
`reanimated` (`import * as Reanimated from "react-native-reanimated"`), `haptics`, and chat's
|
|
265
|
+
`netInfo` in `ChatNativeProvider modules`.
|
|
266
|
+
|
|
154
267
|
### Your own attachment kinds on native
|
|
155
268
|
|
|
156
269
|
A kind registered in `ChatProvider attachmentKinds` draws as `ChatAttachmentCard` (its title,
|
|
@@ -328,6 +441,51 @@ Apply 0004 after a block's migration that ships a subject resolver (genesis-supp
|
|
|
328
441
|
Replace your copies of the 0001–0003 pgTAP tests with this release's (they now give their own
|
|
329
442
|
people a tenant). If you use genesis-support's chat, apply its 0004 in the same release.
|
|
330
443
|
|
|
444
|
+
## Mark as Unread and Delete for me (migration 0007)
|
|
445
|
+
|
|
446
|
+
As Messages has them, and only for the person who does them:
|
|
447
|
+
|
|
448
|
+
```ts
|
|
449
|
+
// Mark as Unread: counts as one unread (inbox, badges, push badge) until they read it; their read
|
|
450
|
+
// place, what senders see as "Read", never moves back. `markRead` clears it.
|
|
451
|
+
chat.setMySettings(conversationId, { markedUnread: true }): Promise<void>
|
|
452
|
+
|
|
453
|
+
// Delete for me: the conversation leaves their inbox, and its history (with its files, link
|
|
454
|
+
// previews and pins) their thread and search, until a new message they can read arrives, which
|
|
455
|
+
// brings it back with only what came after. Pass the inbox row's `lastSeq` as `seq` (what they
|
|
456
|
+
// saw), so a message that came in meanwhile isn't deleted unseen. Nothing is deleted, and nobody
|
|
457
|
+
// else's inbox, thread or read receipts change.
|
|
458
|
+
chat.deleteConversationForMe(conversationId, seq?): Promise<void>
|
|
459
|
+
```
|
|
460
|
+
|
|
461
|
+
From React, `useInboxActions()` runs them from an inbox row: `toggleUnread(item)`,
|
|
462
|
+
`togglePinned(item)`, `toggleMuted(item, until?)`, `setArchived(item, archived)` and
|
|
463
|
+
`deleteForMe(item)` (up to the row's `lastSeq`). Each refreshes the inbox and badge, and Delete for
|
|
464
|
+
me drops the conversation's cached thread, pins and search results, so the deleted history can't
|
|
465
|
+
show again on that device when a new message brings it back.
|
|
466
|
+
|
|
467
|
+
`inboxRowActions(item, actions, labels, { confirm, onError })` turns them into the row's actions,
|
|
468
|
+
Messages' set: Mark as Unread (or Read) and Pin leading, Hide Alerts and Delete trailing, Archive in
|
|
469
|
+
the menu only; Unread blue, Pin orange, Hide Alerts purple, Delete red. `confirm` is
|
|
470
|
+
`(title, body, label) => Promise<boolean>`: `alertConfirm(cancel)` on the phone, `useConfirmDialog()`
|
|
471
|
+
on the web. `ChatInboxScreen` swipes them and `ChatInbox` lists them in each row's More menu; both
|
|
472
|
+
take `rowActions(item, defaults)` to reshape them, and say so when one fails.
|
|
473
|
+
|
|
474
|
+
```ts
|
|
475
|
+
import { defaultInboxActionLabels, inboxRowActions, type ChatInboxActions } from "@marktiderman/genesis-chat/react";
|
|
476
|
+
import type { ChatInboxItem } from "@marktiderman/genesis-chat";
|
|
477
|
+
|
|
478
|
+
export function actionsFor(item: ChatInboxItem, actions: ChatInboxActions) {
|
|
479
|
+
return inboxRowActions(item, actions, defaultInboxActionLabels, { confirm: async () => true });
|
|
480
|
+
}
|
|
481
|
+
```
|
|
482
|
+
|
|
483
|
+
Both are private to the person: they're kept in `genesis_chat.member_state`, which only they read,
|
|
484
|
+
not on `members`, which everyone in the conversation reads. Both send the person's own devices an
|
|
485
|
+
`inbox` hint. `markedUnread` is sent only when given, so the client keeps working on a database
|
|
486
|
+
before 0007.
|
|
487
|
+
Apply 0007 after 0006 (`genesis migrate`), and copy its pgTAP test beside the others.
|
|
488
|
+
|
|
331
489
|
## Access
|
|
332
490
|
|
|
333
491
|
Members read a conversation; who posts follows its kind and settings (`{"who_posts": "admins"}`
|
|
@@ -338,7 +496,7 @@ reaches nothing. The pgTAP test beside the migration proves each rule.
|
|
|
338
496
|
|
|
339
497
|
## Live updates
|
|
340
498
|
|
|
341
|
-
New and changed messages, reactions and
|
|
499
|
+
New and changed messages, reactions, memberships and read places (0006) are broadcast as hints (ids and read places only) to private
|
|
342
500
|
Realtime topics, `genesis-chat:conv:<id>` and `genesis-chat:user:<id>`; clients fetch through row
|
|
343
501
|
level security, and fetch what they missed every time a channel joins (`onJoin`), the first time included. Typing and recording are broadcast
|
|
344
502
|
by clients and never stored.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { randomId, attachmentKindFor, ChatError } from './chunk-
|
|
1
|
+
import { randomId, attachmentKindFor, ChatError } from './chunk-GEEJMKQF.js';
|
|
2
2
|
|
|
3
3
|
// src/core/thread.ts
|
|
4
4
|
function mergeThread(server, pending) {
|
|
@@ -540,5 +540,5 @@ async function notReadable() {
|
|
|
540
540
|
}
|
|
541
541
|
|
|
542
542
|
export { activityLine, createOutbox, currentActivity, dayLabel, firstUnreadId, itemSender, itemTime, memoryOutboxStore, mergeThread, parseMentions, previewText, releaseObjectUrl, sameDay, startsDay, startsGroup, summarizeReactions, throttle, upsertMessages };
|
|
543
|
-
//# sourceMappingURL=chunk-
|
|
544
|
-
//# sourceMappingURL=chunk-
|
|
543
|
+
//# sourceMappingURL=chunk-3UNYTK62.js.map
|
|
544
|
+
//# sourceMappingURL=chunk-3UNYTK62.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/thread.ts","../src/core/outbox.ts"],"names":[],"mappings":";;;AAiBO,SAAS,WAAA,CAAY,QAAuB,OAAA,EAAyC;AAC1F,EAAA,MAAM,IAAA,uBAAW,GAAA,EAAyB;AAC1C,EAAA,KAAA,MAAW,KAAK,MAAA,EAAQ,IAAA,CAAK,GAAA,CAAI,CAAA,CAAE,IAA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,CAAA;AAAA;AAAA,IAGA,KAAA;AAAA,IAEA,IAAA,EAAM;AAAA,GACR;AACF;AAIA,eAAe,WAAA,GAA8B;AAE3C,EAAA,MAAM,IAAI,SAAA,CAAU,wCAAA,EAA0C,QAAA,EAAU,QAAQ,CAAA;AAClF","file":"chunk-ZQFREERR.js","sourcesContent":["/**\n * @feat:chat\n * Pure thread logic, the same on every platform: merging the server's messages\n * with ones still on their way, grouping a run of messages from one sender,\n * day dividers, the unread line, reactions by emoji, and the typing line.\n */\nimport type { ChatActivity, ChatMessage, PendingMessage } from \"./types\";\n\nexport type ThreadItem =\n | { type: \"message\"; message: ChatMessage; pending?: undefined }\n | { type: \"pending\"; pending: PendingMessage; message?: undefined };\n\n/**\n * The server's messages (by seq), then what is still sending, oldest first. A\n * pending message the server already has (same clientId) is dropped, so a send\n * that landed never shows twice.\n */\nexport function mergeThread(server: ChatMessage[], pending: PendingMessage[]): ThreadItem[] {\n const byId = new Map<string, ChatMessage>();\n for (const m of server) byId.set(m.id, m);\n const sorted = [...byId.values()].sort((a, b) => a.seq - b.seq);\n const landed = new Set(sorted.map((m) => m.clientId));\n const waiting = pending\n .filter((p) => !landed.has(p.clientId))\n .sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n return [\n ...sorted.map((message) => ({ type: \"message\" as const, message })),\n ...waiting.map((p) => ({ type: \"pending\" as const, pending: p })),\n ];\n}\n\n/** Adds or replaces messages in a page, keeping it sorted and free of duplicates. */\nexport function upsertMessages(existing: ChatMessage[], incoming: ChatMessage[]): ChatMessage[] {\n const byId = new Map(existing.map((m) => [m.id, m]));\n for (const m of incoming) byId.set(m.id, m);\n return [...byId.values()].sort((a, b) => a.seq - b.seq);\n}\n\nexport function itemSender(item: ThreadItem): string | null {\n return item.type === \"message\" ? item.message.senderId : item.pending.senderId;\n}\n\nexport function itemTime(item: ThreadItem): string {\n return item.type === \"message\" ? item.message.createdAt : item.pending.createdAt;\n}\n\n/** Runs of one sender within five minutes share a header (name, avatar). */\nexport function startsGroup(items: ThreadItem[], index: number, gapMs = 5 * 60_000): boolean {\n if (index === 0) return true;\n const prev = items[index - 1]!;\n const cur = items[index]!;\n if (cur.type === \"message\" && cur.message.kind === \"system\") return true;\n if (prev.type === \"message\" && prev.message.kind === \"system\") return true;\n if (itemSender(prev) !== itemSender(cur)) return true;\n return Date.parse(itemTime(cur)) - Date.parse(itemTime(prev)) > gapMs || !sameDay(itemTime(prev), itemTime(cur));\n}\n\nexport function sameDay(a: string, b: string): boolean {\n const x = new Date(a);\n const y = new Date(b);\n return x.getFullYear() === y.getFullYear() && x.getMonth() === y.getMonth() && x.getDate() === y.getDate();\n}\n\n/** A day divider goes before this item. */\nexport function startsDay(items: ThreadItem[], index: number): boolean {\n return index === 0 || !sameDay(itemTime(items[index - 1]!), itemTime(items[index]!));\n}\n\n/** \"Today\", \"Yesterday\", \"Monday\", or \"12 Mar 2026\". */\nexport function dayLabel(iso: string, now = new Date(), locale?: string): string {\n const d = new Date(iso);\n const startOf = (x: Date) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime();\n const days = Math.round((startOf(now) - startOf(d)) / 86_400_000);\n if (days === 0) return \"Today\";\n if (days === 1) return \"Yesterday\";\n if (days > 1 && days < 7) return d.toLocaleDateString(locale, { weekday: \"long\" });\n return d.toLocaleDateString(locale, { day: \"numeric\", month: \"short\", year: d.getFullYear() === now.getFullYear() ? undefined : \"numeric\" });\n}\n\n/** The first message after what you had read, from someone else: where \"New\" goes. */\nexport function firstUnreadId(messages: ChatMessage[], lastReadSeq: number, me: string): string | null {\n return messages.find((m) => m.seq > lastReadSeq && m.senderId !== me && !m.deletedAt)?.id ?? null;\n}\n\nexport interface ReactionSummary {\n emoji: string;\n count: number;\n mine: boolean;\n userIds: string[];\n}\n\n/** Reactions by emoji, most first, then in first-used order. */\nexport function summarizeReactions(message: ChatMessage, me: string): ReactionSummary[] {\n const order: string[] = [];\n const by = new Map<string, string[]>();\n for (const r of message.reactions) {\n if (!by.has(r.emoji)) {\n by.set(r.emoji, []);\n order.push(r.emoji);\n }\n by.get(r.emoji)!.push(r.userId);\n }\n return order\n .map((emoji) => ({ emoji, count: by.get(emoji)!.length, mine: by.get(emoji)!.includes(me), userIds: by.get(emoji)! }))\n .sort((a, b) => b.count - a.count || order.indexOf(a.emoji) - order.indexOf(b.emoji));\n}\n\n/** Who is doing what now: activity older than six seconds has stopped. */\nexport function currentActivity(activity: ChatActivity[], now = Date.now(), staleMs = 6000): ChatActivity[] {\n const latest = new Map<string, ChatActivity>();\n for (const a of activity) {\n if (now - a.at > staleMs) continue;\n const prev = latest.get(a.userId);\n if (!prev || prev.at < a.at) latest.set(a.userId, a);\n }\n return [...latest.values()];\n}\n\n/** \"Sam is typing…\", \"Sam and Lee are typing…\", \"Sam is recording a voice message…\". */\nexport function activityLine(activity: ChatActivity[], nameOf: (userId: string) => string): string | null {\n if (activity.length === 0) return null;\n const recording = activity.find((a) => a.activity !== \"typing\");\n if (recording) {\n return `${nameOf(recording.userId)} is recording ${recording.activity === \"recording-video\" ? \"a video\" : \"a voice message\"}…`;\n }\n const names = activity.map((a) => nameOf(a.userId));\n if (names.length === 1) return `${names[0]} is typing…`;\n if (names.length === 2) return `${names[0]} and ${names[1]} are typing…`;\n return \"Several people are typing…\";\n}\n\n/** Sends activity at most once every `everyMs`. */\nexport function throttle(fn: () => void, everyMs = 3000): () => void {\n let last = 0;\n return () => {\n const now = Date.now();\n if (now - last >= everyMs) {\n last = now;\n fn();\n }\n };\n}\n\n/** The ids @mentioned in markdown written as `@[Name](user:<uuid>)`. */\nexport function parseMentions(body: string): string[] {\n const ids = new Set<string>();\n for (const m of body.matchAll(/@\\[[^\\]]{1,80}\\]\\(user:([0-9a-f-]{36})\\)/gi)) ids.add(m[1]!.toLowerCase());\n return [...ids];\n}\n\n/** A one-line preview: text, or what was attached. */\nexport function previewText(body: string, attachment: string | null | undefined, deleted = false): string {\n if (deleted) return \"Message deleted\";\n const text = body.replace(/@\\[([^\\]]+)\\]\\(user:[0-9a-f-]{36}\\)/gi, \"@$1\").replace(/[*_`#>~]/g, \"\").trim();\n if (text) return text.length > 140 ? `${text.slice(0, 139)}…` : text;\n switch (attachment) {\n case \"image\":\n return \"Photo\";\n case \"voice\":\n return \"Voice message\";\n case \"video\":\n return \"Video\";\n case \"file\":\n return \"File\";\n case null:\n case undefined:\n return \"\";\n default:\n return \"Attachment\";\n }\n}\n","/**\n * @feat:chat\n * The send queue: a message shows at once as pending, its files upload, then it\n * is sent with the clientId made when it was written, so a retry (after a lost\n * connection, a closed app) never posts twice. Messages to one conversation go\n * in the order they were written: the first that can't go (a lost file, a refusal)\n * holds back the ones after it. A refusal (not allowed, bad data) is `permanent`\n * and only sent again by hand. `clear()` (sign-out) stops sends in flight: none\n * posts, or saves anything, afterwards. Storage is the platform's (memory by default;\n * localStorage on web, MMKV or SQLite on native), behind OutboxStore.\n *\n * A hosted video (`LocalFile.hosted`, with `hostedUpload`) doesn't wait for its bytes: the\n * upload is started (the provider's upload id minted), the message is sent in its place in the\n * order with the attachment `pending`, and the bytes carry on going up; the provider's webhook\n * marks it ready. The message stays here (hidden from the thread once the server has it) until\n * its bytes are up, so a relaunch carries the upload on (`resume`) and sends the message again\n * with the same clientId, which posts nothing twice.\n */\nimport type { ChatClient } from \"./client\";\nimport { ChatError } from \"./client\";\nimport { attachmentKindFor, randomId } from \"./media\";\nimport type { UploadProgress } from \"./transfer\";\nimport type { AttachmentInput, ChatMessage, HostedAttachment, PendingFile, PendingMessage, SendInput } from \"./types\";\n\n/** A file still on the device, uploaded when its message is sent. */\nexport interface LocalFile {\n /** The bytes, or (native) a file URI the platform reads in `readFile`. */\n data: Blob | ArrayBuffer | string;\n name: string;\n contentType: string;\n /** A preview to show while it uploads (an object URL, a file URI). The outbox owns it from here: see `releasePreview`. */\n previewUrl?: string;\n /** Known up front: a voice note's duration and waveform, a photo's size. */\n meta?: Partial<Omit<AttachmentInput, \"path\" | \"kind\">> & { kind?: AttachmentInput[\"kind\"] };\n /**\n * Send it to the hosted video provider (the outbox's `hostedUpload`) instead of storage: the\n * message goes at once, in order, with the attachment pending, while the bytes go up. Without\n * a `hostedUpload` it goes to storage like any file.\n */\n hosted?: boolean;\n}\n\n/** A hosted upload as the outbox keeps it (saved with the message), so it can be carried on. */\nexport interface HostedUploadRecord {\n provider: HostedAttachment[\"provider\"];\n providerId: string;\n /** Where the bytes go, when the hook returned it: what a resume needs. */\n url?: string;\n /** Every byte is there. */\n uploaded?: boolean;\n}\n\n/** What `hostedUpload` resolves with as soon as the upload exists (before the bytes are up). */\nexport interface HostedUploadStart extends HostedAttachment {\n /** Where the bytes go; kept with the message, handed back as `resume.url`. */\n url?: string;\n /** Settles when every byte is there (rejects when the transfer fails). Absent: already there. */\n done?: Promise<void>;\n}\n\nexport interface HostedUploadOptions {\n /** Aborts when the message is discarded or the outbox cleared. */\n signal?: AbortSignal;\n onProgress?: UploadProgress;\n /**\n * The upload started before (a relaunch, a retry after the transfer failed): carry it on and\n * resolve with the same `providerId`. A message may already be posted with it, so mint a new\n * one only when the old upload is gone; that message's video then stays pending.\n */\n resume?: HostedUploadRecord;\n}\n\n/** Starts (or carries on) a hosted upload; resolves once the provider's upload id exists. */\nexport type HostedUpload = (conversationId: string, file: LocalFile, opts: HostedUploadOptions) => Promise<HostedUploadStart>;\n\n/** Uploads a file to storage and resolves with its path. */\nexport type StorageUpload = (conversationId: string, file: LocalFile, opts?: { signal?: AbortSignal; onProgress?: UploadProgress }) => Promise<string>;\n\nexport interface QueuedMessage extends Omit<PendingMessage, \"files\"> {\n files: LocalFile[];\n /** What each file is, kept with the saved copy (PendingMessage.files). */\n pendingFiles?: PendingFile[];\n /** Files lost on a relaunch (bytes that weren't persisted). */\n lostFiles?: number;\n attempts: number;\n /** Hosted uploads started, by file slot. */\n hosted?: Record<number, HostedUploadRecord>;\n /** Posted (this message's id): it waits here only for its hosted bytes to finish. */\n sentMessageId?: string;\n}\n\nfunction describe(f: LocalFile): PendingFile {\n return {\n name: f.name,\n contentType: f.contentType,\n kind: f.meta?.kind ?? attachmentKindFor(f.contentType),\n meta: f.meta,\n ...(f.hosted ? { hosted: true } : {}),\n };\n}\n\nexport interface OutboxStore {\n load(): Promise<QueuedMessage[]>;\n save(queue: QueuedMessage[]): Promise<void>;\n}\n\nexport const memoryOutboxStore = (): OutboxStore => {\n let saved: QueuedMessage[] = [];\n return { load: async () => saved, save: async (q) => void (saved = q) };\n};\n\nexport interface OutboxOptions {\n client: ChatClient;\n userId: string;\n store?: OutboxStore;\n /** Reads a native file URI into bytes for upload. */\n readFile?: (uri: string) => Promise<Blob | ArrayBuffer>;\n /**\n * Upload hook, e.g. resumable uploads on native. Defaults to client.upload. `signal` aborts\n * when the message is discarded or the outbox cleared; call `onProgress(sent, total)` as bytes\n * go, and the pending bubble shows it (`PendingMessage.files[i].progress`).\n */\n upload?: StorageUpload;\n /**\n * Starts a hosted video upload for a file marked `hosted` and resolves once the provider's\n * upload id exists, with `done` for the bytes. See HostedUpload; without it, hosted files go\n * to storage.\n */\n hostedUpload?: HostedUpload;\n /** Called with every change, for the UI. */\n onChange?: (queue: QueuedMessage[]) => void;\n /** Called when a message lands. */\n onSent?: (message: ChatMessage, clientId: string) => void;\n /** Makes client ids. Default: a random UUID (works where crypto.randomUUID is missing). */\n newId?: () => string;\n /**\n * Keeps a file held as bytes (a pasted image, a recording) between launches: write it\n * somewhere and return a URI `readFile` can read (native: the app's cache directory).\n * Without it, such a file isn't saved, and after a relaunch its message asks for it again.\n */\n persistFile?: (file: LocalFile) => Promise<string>;\n /**\n * Lets go of a file's `previewUrl` once its message has landed, been discarded or cleared.\n * Default: revokes `blob:` object URLs (the web's), and leaves everything else alone.\n */\n releasePreview?: (url: string) => void;\n}\n\n/** Revokes a `blob:` object URL; anything else (a native file URI) is left alone. */\nexport function releaseObjectUrl(url: string) {\n if (!url.startsWith(\"blob:\") || typeof URL === \"undefined\" || typeof URL.revokeObjectURL !== \"function\") return;\n try {\n URL.revokeObjectURL(url);\n } catch {\n // Already gone, or a runtime without object URLs.\n }\n}\n\n\nexport function createOutbox(opts: OutboxOptions) {\n const store = opts.store ?? memoryOutboxStore();\n let queue: QueuedMessage[] = [];\n // Bumped by clear(): work begun under an older generation stops at its next await.\n let generation = 0;\n const running = new Map<string, number>(); // conversationId -> the generation running it\n const aborts = new Map<string, AbortController>(); // clientId -> its uploads' controller\n const uploaded = new Map<string, string>(); // clientId:index -> path\n // Hosted bytes still going up, by clientId:index, and the controller that stops them.\n const transfers = new Map<string, Promise<void>>();\n const hostedAborts = new Map<string, AbortController>();\n\n const release = opts.releasePreview ?? releaseObjectUrl;\n const releasePreviews = (q: QueuedMessage) => {\n for (const url of new Set([...Object.values(q.previews ?? {}), ...q.files.map((f) => f.previewUrl)])) {\n if (typeof url === \"string\" && url) release(url);\n }\n };\n\n const newId = opts.newId ?? randomId;\n\n // Saved copies: a file held as bytes is kept only as a URI (persistFile) or marked lost.\n // `files` holds the files still here, in slot order; `pendingFiles` holds every slot.\n const saveable = (q: QueuedMessage): QueuedMessage => {\n const slots = q.pendingFiles?.length ? q.pendingFiles : q.files.map(describe);\n const here = [...q.files];\n const files: LocalFile[] = [];\n const pendingFiles = slots.map((slot) => {\n if (slot.lost) return slot;\n const f = here.shift();\n if (f && typeof f.data === \"string\") {\n files.push(f);\n return { ...slot, lost: false };\n }\n return { ...slot, lost: true };\n });\n return { ...q, files, pendingFiles };\n };\n\n const emit = () => {\n opts.onChange?.([...queue]);\n void store.save(queue.map(saveable));\n };\n\n /** A file's upload progress, for the UI only (not saved). */\n const setProgress = (q: QueuedMessage, index: number, sent: number, total: number) => {\n const slots = q.pendingFiles;\n if (!slots?.[index] || !queue.includes(q)) return;\n // Whole percents: the bar shows no finer, and each change re-renders every chat hook.\n const progress = total > 0 ? Math.round(Math.min(1, Math.max(0, sent / total)) * 100) / 100 : 0;\n if (slots[index]!.progress === progress) return;\n q.pendingFiles = slots.map((slot, j) => (j === index ? { ...slot, progress } : slot));\n opts.onChange?.([...queue]);\n };\n\n const stopHosted = (clientId: string) => {\n hostedAborts.get(clientId)?.abort();\n hostedAborts.delete(clientId);\n for (const k of [...transfers.keys()]) if (k.startsWith(`${clientId}:`)) transfers.delete(k);\n };\n\n /** Swaps a byte file for a saved URI, so it survives a relaunch. */\n async function persist(q: QueuedMessage) {\n if (!opts.persistFile) return;\n for (let i = 0; i < q.files.length; i++) {\n const f = q.files[i]!;\n if (typeof f.data === \"string\") continue;\n try {\n q.files[i] = { ...f, data: await opts.persistFile(f) };\n } catch {\n // Kept in memory only; a relaunch asks for it again.\n }\n }\n }\n\n /**\n * One load for the outbox's life, which every method awaits. What was saved is merged into\n * the live queue (a send made while the load was in flight stays), deduped by clientId.\n */\n let loading: Promise<void> | null = null;\n function ensureLoaded(): Promise<void> {\n loading ??= (async () => {\n const gen = generation;\n let saved: QueuedMessage[] = [];\n try {\n saved = (await store.load()) ?? [];\n } catch {\n saved = [];\n }\n // Cleared (signed out) while it loaded: what was saved belonged to that session.\n if (gen !== generation) return;\n // A file held as bytes that wasn't persisted doesn't survive a relaunch: its message waits,\n // failed, for the file to be attached again (never sent without it) or discarded.\n const live = new Set(queue.map((q) => q.clientId));\n const restored: QueuedMessage[] = saved\n .filter((q) => !live.has(q.clientId))\n .map((q) => {\n const lost = (q.pendingFiles ?? []).filter((f) => f.lost).length;\n // Posted, its hosted bytes still going up when the app closed: it is sent again (the\n // same clientId posts nothing twice) after its upload is carried on.\n const rest: QueuedMessage = { ...q };\n delete rest.sentMessageId;\n return {\n ...rest,\n status: q.status === \"sending\" || lost > 0 ? \"failed\" : q.status,\n error: lost > 0 ? \"Attach the file again to send\" : (q.error ?? \"Not sent\"),\n files: q.files ?? [],\n attempts: q.attempts ?? 0,\n lostFiles: lost,\n };\n });\n if (restored.length) {\n queue = [...restored, ...queue];\n opts.onChange?.([...queue]);\n }\n })();\n return loading;\n }\n\n async function uploadFile(conversationId: string, file: LocalFile, signal?: AbortSignal, onProgress?: UploadProgress): Promise<string> {\n if (opts.upload) return opts.upload(conversationId, file, { signal, onProgress });\n const data = typeof file.data === \"string\" ? await (opts.readFile ?? notReadable)(file.data) : file.data;\n return opts.client.upload(conversationId, opts.userId, data, { name: file.name, contentType: file.contentType, onProgress, signal });\n }\n\n const isHosted = (f: LocalFile) => Boolean(f.hosted && opts.hostedUpload);\n\n /**\n * The hosted upload for one file slot: the one going up, or a new (or carried-on) one. Resolves\n * once the provider's upload id exists; its bytes go on in `transfers`.\n */\n async function startHosted(q: QueuedMessage, index: number, file: LocalFile): Promise<HostedUploadRecord> {\n const key = `${q.clientId}:${index}`;\n const known = q.hosted?.[index];\n if (known && (known.uploaded || transfers.has(key))) return known;\n let controller = hostedAborts.get(q.clientId);\n if (!controller && typeof AbortController !== \"undefined\") {\n controller = new AbortController();\n hostedAborts.set(q.clientId, controller);\n }\n const started = await opts.hostedUpload!(q.input.conversationId, file, {\n signal: controller?.signal,\n onProgress: (sent, total) => setProgress(q, index, sent, total),\n ...(known ? { resume: known } : {}),\n });\n const record: HostedUploadRecord = { provider: started.provider, providerId: started.providerId, ...(started.url ? { url: started.url } : {}) };\n q.hosted = { ...q.hosted, [index]: record };\n // Saved at once: a relaunch before the message goes carries this upload on, not a new one.\n if (queue.includes(q)) emit();\n const transfer = Promise.resolve(started.done).then(\n () => {\n record.uploaded = true;\n if (transfers.get(key) === transfer) transfers.delete(key);\n setProgress(q, index, 1, 1);\n },\n (e: unknown) => {\n if (transfers.get(key) === transfer) transfers.delete(key);\n throw e;\n },\n );\n transfer.catch(() => undefined);\n transfers.set(key, transfer);\n return record;\n }\n\n /** A posted message's hosted bytes: once they are all up, it leaves; a failed transfer marks it failed (Retry carries it on). */\n async function settleHosted(q: QueuedMessage, gen: number) {\n const waiting = Object.entries(q.hosted ?? {})\n .filter(([, r]) => !r.uploaded)\n .map(([i]) => transfers.get(`${q.clientId}:${i}`) ?? Promise.reject(new ChatError(\"The upload stopped\", undefined, \"upload\")));\n try {\n await Promise.all(waiting);\n } catch (e) {\n if (gen !== generation || !queue.includes(q) || q.status !== \"sending\") return;\n q.attempts += 1;\n q.status = \"failed\";\n q.error = e instanceof ChatError && e.code === \"GSABORT\" ? \"The upload was cancelled\" : \"The video didn't finish uploading\";\n emit();\n return;\n }\n if (gen !== generation || !queue.includes(q)) return;\n // A retry may have started more meanwhile: wait for those too.\n if (Object.values(q.hosted ?? {}).some((r) => !r.uploaded)) return void settleHosted(q, gen);\n queue = queue.filter((x) => x !== q);\n hostedAborts.delete(q.clientId);\n emit();\n releasePreviews(q);\n }\n\n async function run(conversationId: string) {\n const gen = generation;\n if (running.get(conversationId) === gen) return;\n running.set(conversationId, gen);\n // Cleared (signed out) or discarded while we waited: stop, sending and saving nothing.\n const stale = (q: QueuedMessage) => gen !== generation || !queue.includes(q);\n try {\n for (;;) {\n if (gen !== generation) return;\n // In the order written: the first message still here decides. One that failed (a lost\n // file, a refusal, no connection) holds back the ones after it until it is retried.\n // A posted message waiting only for its hosted bytes holds nothing back.\n const next = queue.find((q) => q.input.conversationId === conversationId && !q.sentMessageId);\n if (!next || next.status !== \"sending\") break;\n if ((next.lostFiles ?? 0) > 0) {\n next.status = \"failed\";\n next.error = \"Attach the file again to send\";\n emit();\n break;\n }\n const controller = typeof AbortController !== \"undefined\" ? new AbortController() : null;\n if (controller) aborts.set(next.clientId, controller);\n try {\n const attachments: AttachmentInput[] = [...(next.input.attachments ?? [])];\n for (let i = 0; i < next.files.length; i++) {\n const file = next.files[i]!;\n if (isHosted(file)) {\n const hosted = await startHosted(next, i, file);\n if (stale(next)) return;\n attachments.push({\n ...file.meta,\n kind: file.meta?.kind ?? attachmentKindFor(file.contentType),\n provider: hosted.provider,\n providerId: hosted.providerId,\n status: \"pending\",\n name: file.meta?.name ?? file.name,\n mime: file.contentType,\n });\n continue;\n }\n const key = `${next.clientId}:${i}`;\n let path = uploaded.get(key);\n if (!path) {\n const index = i;\n path = await uploadFile(conversationId, file, controller?.signal, (sent, total) => setProgress(next, index, sent, total));\n if (stale(next)) return;\n uploaded.set(key, path);\n }\n attachments.push({\n ...file.meta,\n kind: file.meta?.kind ?? attachmentKindFor(file.contentType),\n path,\n name: file.meta?.name ?? file.name,\n mime: file.contentType,\n });\n }\n if (stale(next)) return;\n const message = await opts.client.send({ ...next.input, attachments });\n // Posted, but the person signed out meanwhile: the next session must not hear of it.\n if (gen !== generation) return;\n for (let i = 0; i < next.files.length; i++) uploaded.delete(`${next.clientId}:${i}`);\n if (Object.values(next.hosted ?? {}).some((r) => !r.uploaded)) {\n // Posted with its video pending: it stays (out of the thread, which has the server's\n // copy) until the bytes are up, so a relaunch can carry the upload on.\n next.sentMessageId = message.id;\n emit();\n opts.onSent?.(message, next.clientId);\n void settleHosted(next, gen);\n continue;\n }\n queue = queue.filter((q) => q.clientId !== next.clientId);\n hostedAborts.delete(next.clientId);\n emit();\n opts.onSent?.(message, next.clientId);\n // The bubble now draws the stored copy: the local preview can go.\n releasePreviews(next);\n } catch (e) {\n if (stale(next)) return;\n const err = e instanceof ChatError ? e : new ChatError(e instanceof Error ? e.message : String(e), undefined, \"send\");\n next.attempts += 1;\n next.status = \"failed\";\n next.permanent = err.permanent;\n next.error = err.forbidden ? \"You can't post here\" : err.transient ? \"Not sent. Check your connection.\" : err.message;\n emit();\n // Later messages to this conversation wait behind a failed one, so order holds.\n break;\n } finally {\n if (controller && aborts.get(next.clientId) === controller) aborts.delete(next.clientId);\n }\n }\n } finally {\n if (running.get(conversationId) === gen) running.delete(conversationId);\n }\n }\n\n /** Can this failed message go without the person's help (retryAll, coming back online)? */\n const canAutoRetry = (x: QueuedMessage) =>\n !x.permanent &&\n !(x.lostFiles ?? 0) &&\n x.files.every((f) => typeof f.data !== \"string\" || Boolean(isHosted(f) ? opts.hostedUpload : opts.readFile || opts.upload));\n\n /** A failed message goes again: a posted one (its transfer failed) re-sends, idempotently, after carrying its upload on. */\n const requeue = (x: QueuedMessage) => {\n x.status = \"sending\";\n delete x.sentMessageId;\n };\n\n return {\n /** Queues a message; it shows at once and sends in order. Returns its clientId. */\n async send(input: Omit<SendInput, \"clientId\"> & { clientId?: string }, files: LocalFile[] = []): Promise<string> {\n await ensureLoaded();\n const gen = generation;\n const clientId = input.clientId ?? newId();\n const previews: Record<number, string> = {};\n files.forEach((f, i) => {\n if (f.previewUrl) previews[i] = f.previewUrl;\n });\n const queued: QueuedMessage = {\n clientId,\n input: { ...input, clientId },\n senderId: opts.userId,\n createdAt: new Date().toISOString(),\n status: \"sending\",\n previews,\n files: [...files],\n pendingFiles: files.map(describe),\n attempts: 0,\n };\n queue.push(queued);\n opts.onChange?.([...queue]);\n await persist(queued);\n // Cleared or discarded while its files were saved: it goes nowhere.\n if (gen !== generation || !queue.includes(queued)) return clientId;\n emit();\n void run(input.conversationId);\n return clientId;\n },\n\n async retry(clientId: string) {\n await ensureLoaded();\n const q = queue.find((x) => x.clientId === clientId);\n if (!q) return;\n // Retrying one retries everything failed in that conversation, in order, refusals too\n // (a person asked), up to one still waiting for a file.\n for (const x of queue) {\n if (x.input.conversationId !== q.input.conversationId || x.status !== \"failed\") continue;\n if ((x.lostFiles ?? 0) > 0) break;\n requeue(x);\n x.permanent = false;\n }\n emit();\n void run(q.input.conversationId);\n },\n\n /**\n * Gives a message the files it lost on a relaunch and sends it. `files` fill the lost\n * slots in order (`PendingMessage.files[i].lost`); the files that were kept stay. Pass\n * one per lost slot; with fewer, the message keeps waiting for the rest.\n */\n async reattach(clientId: string, files: LocalFile[]) {\n await ensureLoaded();\n const q = queue.find((x) => x.clientId === clientId);\n if (!q) return;\n const slots = q.pendingFiles ?? [];\n const kept = [...q.files];\n const given = [...files];\n const merged: LocalFile[] = [];\n const described: PendingFile[] = [];\n for (const slot of slots) {\n if (slot.lost) {\n const f = given.shift();\n if (f) {\n merged.push(f);\n described.push(describe(f));\n } else {\n described.push(slot);\n }\n } else {\n const f = kept.shift();\n if (f) {\n merged.push(f);\n described.push(slot);\n }\n }\n }\n // A message saved before slots were recorded: the given files are all of them.\n if (slots.length === 0) {\n merged.push(...given);\n described.push(...given.map(describe));\n }\n q.files = merged;\n q.pendingFiles = described;\n q.lostFiles = described.filter((d) => d.lost).length;\n if (q.lostFiles > 0) {\n emit();\n return;\n }\n const gen = generation;\n await persist(q);\n if (gen !== generation || !queue.includes(q)) return;\n requeue(q);\n emit();\n void run(q.input.conversationId);\n },\n\n /**\n * Retries failed messages (after the connection comes back), in order per conversation,\n * stopping at the first that can't go on its own: one waiting for a lost file, or one the\n * server refused (`permanent`, retried only by hand). The ones after it keep waiting.\n */\n async retryAll() {\n await ensureLoaded();\n const conversations = new Set<string>();\n const held = new Set<string>();\n for (const x of queue) {\n const c = x.input.conversationId;\n if (held.has(c) || x.status !== \"failed\") continue;\n if (!canAutoRetry(x)) {\n // A posted one (only its upload failed) holds nothing back.\n if (!x.sentMessageId) held.add(c);\n continue;\n }\n requeue(x);\n conversations.add(c);\n }\n emit();\n for (const c of conversations) void run(c);\n },\n\n /** Forgets every queued message, here and in the store (call it on sign-out). */\n async clear() {\n // At once, before any await: a send in flight stops at its next step and posts nothing.\n generation += 1;\n for (const c of aborts.values()) c.abort();\n aborts.clear();\n for (const c of hostedAborts.values()) c.abort();\n hostedAborts.clear();\n transfers.clear();\n running.clear();\n const gone = queue;\n queue = [];\n uploaded.clear();\n gone.forEach(releasePreviews);\n opts.onChange?.([]);\n await ensureLoaded();\n await store.save([]);\n },\n\n async discard(clientId: string) {\n await ensureLoaded();\n const gone = queue.find((q) => q.clientId === clientId);\n queue = queue.filter((q) => q.clientId !== clientId);\n aborts.get(clientId)?.abort();\n aborts.delete(clientId);\n stopHosted(clientId);\n if (gone) releasePreviews(gone);\n emit();\n },\n\n /**\n * Uploads one file to storage the way the outbox does (the `upload` hook, or `readFile` then\n * the client's upload) and resolves with its path: for files sent outside the queue, such as\n * a scheduled message's.\n */\n uploadFile(conversationId: string, file: LocalFile, o: { signal?: AbortSignal; onProgress?: UploadProgress } = {}): Promise<string> {\n return uploadFile(conversationId, file, o.signal, o.onProgress);\n },\n\n pending(conversationId?: string): PendingMessage[] {\n return queue\n .filter((q) => !conversationId || q.input.conversationId === conversationId)\n .map((q) => ({ ...q, files: q.pendingFiles }));\n },\n\n /** A new client id, made the way this outbox makes them. */\n newId,\n\n load: ensureLoaded,\n };\n}\n\nexport type Outbox = ReturnType<typeof createOutbox>;\n\nasync function notReadable(): Promise<never> {\n // This device's set-up (no readFile), not a refusal: a relaunch that can read it sends it.\n throw new ChatError(\"This file can't be read on this device\", \"GSFILE\", \"upload\");\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/core/thread.ts","../src/core/outbox.ts"],"names":[],"mappings":";;;AAiBO,SAAS,WAAA,CAAY,QAAuB,OAAA,EAAyC;AAC1F,EAAA,MAAM,IAAA,uBAAW,GAAA,EAAyB;AAC1C,EAAA,KAAA,MAAW,KAAK,MAAA,EAAQ,IAAA,CAAK,GAAA,CAAI,CAAA,CAAE,IAAI,CAAC,CAAA;AACxC,EAAA,MAAM,MAAA,GAAS,CAAC,GAAG,IAAA,CAAK,QAAQ,CAAA,CAAE,IAAA,CAAK,CAAC,CAAA,EAAG,CAAA,KAAM,CAAA,CAAE,GAAA,GAAM,EAAE,GAAG,CAAA;AAC9D,EAAA,MAAM,MAAA,GAAS,IAAI,GAAA,CAAI,MAAA,CAAO,IAAI,CAAC,CAAA,KAAM,CAAA,CAAE,QAAQ,CAAC,CAAA;AACpD,EAAA,MAAM,OAAA,GAAU,QACb,MAAA,CAAO,CAAC,MAAM,CAAC,MAAA,CAAO,IAAI,CAAA,CAAE,QAAQ,CAAC,CAAA,CACrC,IAAA,CAAK,CAAC,CAAA,EAAG,CAAA,KAAM,EAAE,SAAA,CAAU,aAAA,CAAc,CAAA,CAAE,SAAS,CAAC,CAAA;AACxD,EAAA,OAAO;AAAA,IACL,GAAG,OAAO,GAAA,CAAI,CAAC,aAAa,EAAE,IAAA,EAAM,SAAA,EAAoB,OAAA,EAAQ,CAAE,CAAA;AAAA,IAClE,GAAG,OAAA,CAAQ,GAAA,CAAI,CAAC,CAAA,MAAO,EAAE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,IAAA,kBAAsB,IAAI,CAAA;AAC9B,MAAA,IAAA,EAAK;AAAA,IACP,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOA,UAAA,CAAW,cAAA,EAAwB,IAAA,EAAiB,CAAA,GAA2D,EAAC,EAAoB;AAClI,MAAA,OAAO,WAAW,cAAA,EAAgB,IAAA,EAAM,CAAA,CAAE,MAAA,EAAQ,EAAE,UAAU,CAAA;AAAA,IAChE,CAAA;AAAA,IAEA,QAAQ,cAAA,EAA2C;AACjD,MAAA,OAAO,KAAA,CACJ,OAAO,CAAC,CAAA,KAAM,CAAC,cAAA,IAAkB,CAAA,CAAE,MAAM,cAAA,KAAmB,cAAc,EAC1E,GAAA,CAAI,CAAC,OAAO,EAAE,GAAG,GAAG,KAAA,EAAO,CAAA,CAAE,cAAa,CAAE,CAAA;AAAA,IACjD,CAAA;AAAA;AAAA,IAGA,KAAA;AAAA,IAEA,IAAA,EAAM;AAAA,GACR;AACF;AAIA,eAAe,WAAA,GAA8B;AAE3C,EAAA,MAAM,IAAI,SAAA,CAAU,wCAAA,EAA0C,QAAA,EAAU,QAAQ,CAAA;AAClF","file":"chunk-3UNYTK62.js","sourcesContent":["/**\n * @feat:chat\n * Pure thread logic, the same on every platform: merging the server's messages\n * with ones still on their way, grouping a run of messages from one sender,\n * day dividers, the unread line, reactions by emoji, and the typing line.\n */\nimport type { ChatActivity, ChatMessage, PendingMessage } from \"./types\";\n\nexport type ThreadItem =\n | { type: \"message\"; message: ChatMessage; pending?: undefined }\n | { type: \"pending\"; pending: PendingMessage; message?: undefined };\n\n/**\n * The server's messages (by seq), then what is still sending, oldest first. A\n * pending message the server already has (same clientId) is dropped, so a send\n * that landed never shows twice.\n */\nexport function mergeThread(server: ChatMessage[], pending: PendingMessage[]): ThreadItem[] {\n const byId = new Map<string, ChatMessage>();\n for (const m of server) byId.set(m.id, m);\n const sorted = [...byId.values()].sort((a, b) => a.seq - b.seq);\n const landed = new Set(sorted.map((m) => m.clientId));\n const waiting = pending\n .filter((p) => !landed.has(p.clientId))\n .sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n return [\n ...sorted.map((message) => ({ type: \"message\" as const, message })),\n ...waiting.map((p) => ({ type: \"pending\" as const, pending: p })),\n ];\n}\n\n/** Adds or replaces messages in a page, keeping it sorted and free of duplicates. */\nexport function upsertMessages(existing: ChatMessage[], incoming: ChatMessage[]): ChatMessage[] {\n const byId = new Map(existing.map((m) => [m.id, m]));\n for (const m of incoming) byId.set(m.id, m);\n return [...byId.values()].sort((a, b) => a.seq - b.seq);\n}\n\nexport function itemSender(item: ThreadItem): string | null {\n return item.type === \"message\" ? item.message.senderId : item.pending.senderId;\n}\n\nexport function itemTime(item: ThreadItem): string {\n return item.type === \"message\" ? item.message.createdAt : item.pending.createdAt;\n}\n\n/** Runs of one sender within five minutes share a header (name, avatar). */\nexport function startsGroup(items: ThreadItem[], index: number, gapMs = 5 * 60_000): boolean {\n if (index === 0) return true;\n const prev = items[index - 1]!;\n const cur = items[index]!;\n if (cur.type === \"message\" && cur.message.kind === \"system\") return true;\n if (prev.type === \"message\" && prev.message.kind === \"system\") return true;\n if (itemSender(prev) !== itemSender(cur)) return true;\n return Date.parse(itemTime(cur)) - Date.parse(itemTime(prev)) > gapMs || !sameDay(itemTime(prev), itemTime(cur));\n}\n\nexport function sameDay(a: string, b: string): boolean {\n const x = new Date(a);\n const y = new Date(b);\n return x.getFullYear() === y.getFullYear() && x.getMonth() === y.getMonth() && x.getDate() === y.getDate();\n}\n\n/** A day divider goes before this item. */\nexport function startsDay(items: ThreadItem[], index: number): boolean {\n return index === 0 || !sameDay(itemTime(items[index - 1]!), itemTime(items[index]!));\n}\n\n/** \"Today\", \"Yesterday\", \"Monday\", or \"12 Mar 2026\". */\nexport function dayLabel(iso: string, now = new Date(), locale?: string): string {\n const d = new Date(iso);\n const startOf = (x: Date) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime();\n const days = Math.round((startOf(now) - startOf(d)) / 86_400_000);\n if (days === 0) return \"Today\";\n if (days === 1) return \"Yesterday\";\n if (days > 1 && days < 7) return d.toLocaleDateString(locale, { weekday: \"long\" });\n return d.toLocaleDateString(locale, { day: \"numeric\", month: \"short\", year: d.getFullYear() === now.getFullYear() ? undefined : \"numeric\" });\n}\n\n/** The first message after what you had read, from someone else: where \"New\" goes. */\nexport function firstUnreadId(messages: ChatMessage[], lastReadSeq: number, me: string): string | null {\n return messages.find((m) => m.seq > lastReadSeq && m.senderId !== me && !m.deletedAt)?.id ?? null;\n}\n\nexport interface ReactionSummary {\n emoji: string;\n count: number;\n mine: boolean;\n userIds: string[];\n}\n\n/** Reactions by emoji, most first, then in first-used order. */\nexport function summarizeReactions(message: ChatMessage, me: string): ReactionSummary[] {\n const order: string[] = [];\n const by = new Map<string, string[]>();\n for (const r of message.reactions) {\n if (!by.has(r.emoji)) {\n by.set(r.emoji, []);\n order.push(r.emoji);\n }\n by.get(r.emoji)!.push(r.userId);\n }\n return order\n .map((emoji) => ({ emoji, count: by.get(emoji)!.length, mine: by.get(emoji)!.includes(me), userIds: by.get(emoji)! }))\n .sort((a, b) => b.count - a.count || order.indexOf(a.emoji) - order.indexOf(b.emoji));\n}\n\n/** Who is doing what now: activity older than six seconds has stopped. */\nexport function currentActivity(activity: ChatActivity[], now = Date.now(), staleMs = 6000): ChatActivity[] {\n const latest = new Map<string, ChatActivity>();\n for (const a of activity) {\n if (now - a.at > staleMs) continue;\n const prev = latest.get(a.userId);\n if (!prev || prev.at < a.at) latest.set(a.userId, a);\n }\n return [...latest.values()];\n}\n\n/** \"Sam is typing…\", \"Sam and Lee are typing…\", \"Sam is recording a voice message…\". */\nexport function activityLine(activity: ChatActivity[], nameOf: (userId: string) => string): string | null {\n if (activity.length === 0) return null;\n const recording = activity.find((a) => a.activity !== \"typing\");\n if (recording) {\n return `${nameOf(recording.userId)} is recording ${recording.activity === \"recording-video\" ? \"a video\" : \"a voice message\"}…`;\n }\n const names = activity.map((a) => nameOf(a.userId));\n if (names.length === 1) return `${names[0]} is typing…`;\n if (names.length === 2) return `${names[0]} and ${names[1]} are typing…`;\n return \"Several people are typing…\";\n}\n\n/** Sends activity at most once every `everyMs`. */\nexport function throttle(fn: () => void, everyMs = 3000): () => void {\n let last = 0;\n return () => {\n const now = Date.now();\n if (now - last >= everyMs) {\n last = now;\n fn();\n }\n };\n}\n\n/** The ids @mentioned in markdown written as `@[Name](user:<uuid>)`. */\nexport function parseMentions(body: string): string[] {\n const ids = new Set<string>();\n for (const m of body.matchAll(/@\\[[^\\]]{1,80}\\]\\(user:([0-9a-f-]{36})\\)/gi)) ids.add(m[1]!.toLowerCase());\n return [...ids];\n}\n\n/** A one-line preview: text, or what was attached. */\nexport function previewText(body: string, attachment: string | null | undefined, deleted = false): string {\n if (deleted) return \"Message deleted\";\n const text = body.replace(/@\\[([^\\]]+)\\]\\(user:[0-9a-f-]{36}\\)/gi, \"@$1\").replace(/[*_`#>~]/g, \"\").trim();\n if (text) return text.length > 140 ? `${text.slice(0, 139)}…` : text;\n switch (attachment) {\n case \"image\":\n return \"Photo\";\n case \"voice\":\n return \"Voice message\";\n case \"video\":\n return \"Video\";\n case \"file\":\n return \"File\";\n case null:\n case undefined:\n return \"\";\n default:\n return \"Attachment\";\n }\n}\n","/**\n * @feat:chat\n * The send queue: a message shows at once as pending, its files upload, then it\n * is sent with the clientId made when it was written, so a retry (after a lost\n * connection, a closed app) never posts twice. Messages to one conversation go\n * in the order they were written: the first that can't go (a lost file, a refusal)\n * holds back the ones after it. A refusal (not allowed, bad data) is `permanent`\n * and only sent again by hand. `clear()` (sign-out) stops sends in flight: none\n * posts, or saves anything, afterwards. Storage is the platform's (memory by default;\n * localStorage on web, MMKV or SQLite on native), behind OutboxStore.\n *\n * A hosted video (`LocalFile.hosted`, with `hostedUpload`) doesn't wait for its bytes: the\n * upload is started (the provider's upload id minted), the message is sent in its place in the\n * order with the attachment `pending`, and the bytes carry on going up; the provider's webhook\n * marks it ready. The message stays here (hidden from the thread once the server has it) until\n * its bytes are up, so a relaunch carries the upload on (`resume`) and sends the message again\n * with the same clientId, which posts nothing twice.\n */\nimport type { ChatClient } from \"./client\";\nimport { ChatError } from \"./client\";\nimport { attachmentKindFor, randomId } from \"./media\";\nimport type { UploadProgress } from \"./transfer\";\nimport type { AttachmentInput, ChatMessage, HostedAttachment, PendingFile, PendingMessage, SendInput } from \"./types\";\n\n/** A file still on the device, uploaded when its message is sent. */\nexport interface LocalFile {\n /** The bytes, or (native) a file URI the platform reads in `readFile`. */\n data: Blob | ArrayBuffer | string;\n name: string;\n contentType: string;\n /** A preview to show while it uploads (an object URL, a file URI). The outbox owns it from here: see `releasePreview`. */\n previewUrl?: string;\n /** Known up front: a voice note's duration and waveform, a photo's size. */\n meta?: Partial<Omit<AttachmentInput, \"path\" | \"kind\">> & { kind?: AttachmentInput[\"kind\"] };\n /**\n * Send it to the hosted video provider (the outbox's `hostedUpload`) instead of storage: the\n * message goes at once, in order, with the attachment pending, while the bytes go up. Without\n * a `hostedUpload` it goes to storage like any file.\n */\n hosted?: boolean;\n}\n\n/** A hosted upload as the outbox keeps it (saved with the message), so it can be carried on. */\nexport interface HostedUploadRecord {\n provider: HostedAttachment[\"provider\"];\n providerId: string;\n /** Where the bytes go, when the hook returned it: what a resume needs. */\n url?: string;\n /** Every byte is there. */\n uploaded?: boolean;\n}\n\n/** What `hostedUpload` resolves with as soon as the upload exists (before the bytes are up). */\nexport interface HostedUploadStart extends HostedAttachment {\n /** Where the bytes go; kept with the message, handed back as `resume.url`. */\n url?: string;\n /** Settles when every byte is there (rejects when the transfer fails). Absent: already there. */\n done?: Promise<void>;\n}\n\nexport interface HostedUploadOptions {\n /** Aborts when the message is discarded or the outbox cleared. */\n signal?: AbortSignal;\n onProgress?: UploadProgress;\n /**\n * The upload started before (a relaunch, a retry after the transfer failed): carry it on and\n * resolve with the same `providerId`. A message may already be posted with it, so mint a new\n * one only when the old upload is gone; that message's video then stays pending.\n */\n resume?: HostedUploadRecord;\n}\n\n/** Starts (or carries on) a hosted upload; resolves once the provider's upload id exists. */\nexport type HostedUpload = (conversationId: string, file: LocalFile, opts: HostedUploadOptions) => Promise<HostedUploadStart>;\n\n/** Uploads a file to storage and resolves with its path. */\nexport type StorageUpload = (conversationId: string, file: LocalFile, opts?: { signal?: AbortSignal; onProgress?: UploadProgress }) => Promise<string>;\n\nexport interface QueuedMessage extends Omit<PendingMessage, \"files\"> {\n files: LocalFile[];\n /** What each file is, kept with the saved copy (PendingMessage.files). */\n pendingFiles?: PendingFile[];\n /** Files lost on a relaunch (bytes that weren't persisted). */\n lostFiles?: number;\n attempts: number;\n /** Hosted uploads started, by file slot. */\n hosted?: Record<number, HostedUploadRecord>;\n /** Posted (this message's id): it waits here only for its hosted bytes to finish. */\n sentMessageId?: string;\n}\n\nfunction describe(f: LocalFile): PendingFile {\n return {\n name: f.name,\n contentType: f.contentType,\n kind: f.meta?.kind ?? attachmentKindFor(f.contentType),\n meta: f.meta,\n ...(f.hosted ? { hosted: true } : {}),\n };\n}\n\nexport interface OutboxStore {\n load(): Promise<QueuedMessage[]>;\n save(queue: QueuedMessage[]): Promise<void>;\n}\n\nexport const memoryOutboxStore = (): OutboxStore => {\n let saved: QueuedMessage[] = [];\n return { load: async () => saved, save: async (q) => void (saved = q) };\n};\n\nexport interface OutboxOptions {\n client: ChatClient;\n userId: string;\n store?: OutboxStore;\n /** Reads a native file URI into bytes for upload. */\n readFile?: (uri: string) => Promise<Blob | ArrayBuffer>;\n /**\n * Upload hook, e.g. resumable uploads on native. Defaults to client.upload. `signal` aborts\n * when the message is discarded or the outbox cleared; call `onProgress(sent, total)` as bytes\n * go, and the pending bubble shows it (`PendingMessage.files[i].progress`).\n */\n upload?: StorageUpload;\n /**\n * Starts a hosted video upload for a file marked `hosted` and resolves once the provider's\n * upload id exists, with `done` for the bytes. See HostedUpload; without it, hosted files go\n * to storage.\n */\n hostedUpload?: HostedUpload;\n /** Called with every change, for the UI. */\n onChange?: (queue: QueuedMessage[]) => void;\n /** Called when a message lands. */\n onSent?: (message: ChatMessage, clientId: string) => void;\n /** Makes client ids. Default: a random UUID (works where crypto.randomUUID is missing). */\n newId?: () => string;\n /**\n * Keeps a file held as bytes (a pasted image, a recording) between launches: write it\n * somewhere and return a URI `readFile` can read (native: the app's cache directory).\n * Without it, such a file isn't saved, and after a relaunch its message asks for it again.\n */\n persistFile?: (file: LocalFile) => Promise<string>;\n /**\n * Lets go of a file's `previewUrl` once its message has landed, been discarded or cleared.\n * Default: revokes `blob:` object URLs (the web's), and leaves everything else alone.\n */\n releasePreview?: (url: string) => void;\n}\n\n/** Revokes a `blob:` object URL; anything else (a native file URI) is left alone. */\nexport function releaseObjectUrl(url: string) {\n if (!url.startsWith(\"blob:\") || typeof URL === \"undefined\" || typeof URL.revokeObjectURL !== \"function\") return;\n try {\n URL.revokeObjectURL(url);\n } catch {\n // Already gone, or a runtime without object URLs.\n }\n}\n\n\nexport function createOutbox(opts: OutboxOptions) {\n const store = opts.store ?? memoryOutboxStore();\n let queue: QueuedMessage[] = [];\n // Bumped by clear(): work begun under an older generation stops at its next await.\n let generation = 0;\n const running = new Map<string, number>(); // conversationId -> the generation running it\n const aborts = new Map<string, AbortController>(); // clientId -> its uploads' controller\n const uploaded = new Map<string, string>(); // clientId:index -> path\n // Hosted bytes still going up, by clientId:index, and the controller that stops them.\n const transfers = new Map<string, Promise<void>>();\n const hostedAborts = new Map<string, AbortController>();\n\n const release = opts.releasePreview ?? releaseObjectUrl;\n const releasePreviews = (q: QueuedMessage) => {\n for (const url of new Set([...Object.values(q.previews ?? {}), ...q.files.map((f) => f.previewUrl)])) {\n if (typeof url === \"string\" && url) release(url);\n }\n };\n\n const newId = opts.newId ?? randomId;\n\n // Saved copies: a file held as bytes is kept only as a URI (persistFile) or marked lost.\n // `files` holds the files still here, in slot order; `pendingFiles` holds every slot.\n const saveable = (q: QueuedMessage): QueuedMessage => {\n const slots = q.pendingFiles?.length ? q.pendingFiles : q.files.map(describe);\n const here = [...q.files];\n const files: LocalFile[] = [];\n const pendingFiles = slots.map((slot) => {\n if (slot.lost) return slot;\n const f = here.shift();\n if (f && typeof f.data === \"string\") {\n files.push(f);\n return { ...slot, lost: false };\n }\n return { ...slot, lost: true };\n });\n return { ...q, files, pendingFiles };\n };\n\n const emit = () => {\n opts.onChange?.([...queue]);\n void store.save(queue.map(saveable));\n };\n\n /** A file's upload progress, for the UI only (not saved). */\n const setProgress = (q: QueuedMessage, index: number, sent: number, total: number) => {\n const slots = q.pendingFiles;\n if (!slots?.[index] || !queue.includes(q)) return;\n // Whole percents: the bar shows no finer, and each change re-renders every chat hook.\n const progress = total > 0 ? Math.round(Math.min(1, Math.max(0, sent / total)) * 100) / 100 : 0;\n if (slots[index]!.progress === progress) return;\n q.pendingFiles = slots.map((slot, j) => (j === index ? { ...slot, progress } : slot));\n opts.onChange?.([...queue]);\n };\n\n const stopHosted = (clientId: string) => {\n hostedAborts.get(clientId)?.abort();\n hostedAborts.delete(clientId);\n for (const k of [...transfers.keys()]) if (k.startsWith(`${clientId}:`)) transfers.delete(k);\n };\n\n /** Swaps a byte file for a saved URI, so it survives a relaunch. */\n async function persist(q: QueuedMessage) {\n if (!opts.persistFile) return;\n for (let i = 0; i < q.files.length; i++) {\n const f = q.files[i]!;\n if (typeof f.data === \"string\") continue;\n try {\n q.files[i] = { ...f, data: await opts.persistFile(f) };\n } catch {\n // Kept in memory only; a relaunch asks for it again.\n }\n }\n }\n\n /**\n * One load for the outbox's life, which every method awaits. What was saved is merged into\n * the live queue (a send made while the load was in flight stays), deduped by clientId.\n */\n let loading: Promise<void> | null = null;\n function ensureLoaded(): Promise<void> {\n loading ??= (async () => {\n const gen = generation;\n let saved: QueuedMessage[] = [];\n try {\n saved = (await store.load()) ?? [];\n } catch {\n saved = [];\n }\n // Cleared (signed out) while it loaded: what was saved belonged to that session.\n if (gen !== generation) return;\n // A file held as bytes that wasn't persisted doesn't survive a relaunch: its message waits,\n // failed, for the file to be attached again (never sent without it) or discarded.\n const live = new Set(queue.map((q) => q.clientId));\n const restored: QueuedMessage[] = saved\n .filter((q) => !live.has(q.clientId))\n .map((q) => {\n const lost = (q.pendingFiles ?? []).filter((f) => f.lost).length;\n // Posted, its hosted bytes still going up when the app closed: it is sent again (the\n // same clientId posts nothing twice) after its upload is carried on.\n const rest: QueuedMessage = { ...q };\n delete rest.sentMessageId;\n return {\n ...rest,\n status: q.status === \"sending\" || lost > 0 ? \"failed\" : q.status,\n error: lost > 0 ? \"Attach the file again to send\" : (q.error ?? \"Not sent\"),\n files: q.files ?? [],\n attempts: q.attempts ?? 0,\n lostFiles: lost,\n };\n });\n if (restored.length) {\n queue = [...restored, ...queue];\n opts.onChange?.([...queue]);\n }\n })();\n return loading;\n }\n\n async function uploadFile(conversationId: string, file: LocalFile, signal?: AbortSignal, onProgress?: UploadProgress): Promise<string> {\n if (opts.upload) return opts.upload(conversationId, file, { signal, onProgress });\n const data = typeof file.data === \"string\" ? await (opts.readFile ?? notReadable)(file.data) : file.data;\n return opts.client.upload(conversationId, opts.userId, data, { name: file.name, contentType: file.contentType, onProgress, signal });\n }\n\n const isHosted = (f: LocalFile) => Boolean(f.hosted && opts.hostedUpload);\n\n /**\n * The hosted upload for one file slot: the one going up, or a new (or carried-on) one. Resolves\n * once the provider's upload id exists; its bytes go on in `transfers`.\n */\n async function startHosted(q: QueuedMessage, index: number, file: LocalFile): Promise<HostedUploadRecord> {\n const key = `${q.clientId}:${index}`;\n const known = q.hosted?.[index];\n if (known && (known.uploaded || transfers.has(key))) return known;\n let controller = hostedAborts.get(q.clientId);\n if (!controller && typeof AbortController !== \"undefined\") {\n controller = new AbortController();\n hostedAborts.set(q.clientId, controller);\n }\n const started = await opts.hostedUpload!(q.input.conversationId, file, {\n signal: controller?.signal,\n onProgress: (sent, total) => setProgress(q, index, sent, total),\n ...(known ? { resume: known } : {}),\n });\n const record: HostedUploadRecord = { provider: started.provider, providerId: started.providerId, ...(started.url ? { url: started.url } : {}) };\n q.hosted = { ...q.hosted, [index]: record };\n // Saved at once: a relaunch before the message goes carries this upload on, not a new one.\n if (queue.includes(q)) emit();\n const transfer = Promise.resolve(started.done).then(\n () => {\n record.uploaded = true;\n if (transfers.get(key) === transfer) transfers.delete(key);\n setProgress(q, index, 1, 1);\n },\n (e: unknown) => {\n if (transfers.get(key) === transfer) transfers.delete(key);\n throw e;\n },\n );\n transfer.catch(() => undefined);\n transfers.set(key, transfer);\n return record;\n }\n\n /** A posted message's hosted bytes: once they are all up, it leaves; a failed transfer marks it failed (Retry carries it on). */\n async function settleHosted(q: QueuedMessage, gen: number) {\n const waiting = Object.entries(q.hosted ?? {})\n .filter(([, r]) => !r.uploaded)\n .map(([i]) => transfers.get(`${q.clientId}:${i}`) ?? Promise.reject(new ChatError(\"The upload stopped\", undefined, \"upload\")));\n try {\n await Promise.all(waiting);\n } catch (e) {\n if (gen !== generation || !queue.includes(q) || q.status !== \"sending\") return;\n q.attempts += 1;\n q.status = \"failed\";\n q.error = e instanceof ChatError && e.code === \"GSABORT\" ? \"The upload was cancelled\" : \"The video didn't finish uploading\";\n emit();\n return;\n }\n if (gen !== generation || !queue.includes(q)) return;\n // A retry may have started more meanwhile: wait for those too.\n if (Object.values(q.hosted ?? {}).some((r) => !r.uploaded)) return void settleHosted(q, gen);\n queue = queue.filter((x) => x !== q);\n hostedAborts.delete(q.clientId);\n emit();\n releasePreviews(q);\n }\n\n async function run(conversationId: string) {\n const gen = generation;\n if (running.get(conversationId) === gen) return;\n running.set(conversationId, gen);\n // Cleared (signed out) or discarded while we waited: stop, sending and saving nothing.\n const stale = (q: QueuedMessage) => gen !== generation || !queue.includes(q);\n try {\n for (;;) {\n if (gen !== generation) return;\n // In the order written: the first message still here decides. One that failed (a lost\n // file, a refusal, no connection) holds back the ones after it until it is retried.\n // A posted message waiting only for its hosted bytes holds nothing back.\n const next = queue.find((q) => q.input.conversationId === conversationId && !q.sentMessageId);\n if (!next || next.status !== \"sending\") break;\n if ((next.lostFiles ?? 0) > 0) {\n next.status = \"failed\";\n next.error = \"Attach the file again to send\";\n emit();\n break;\n }\n const controller = typeof AbortController !== \"undefined\" ? new AbortController() : null;\n if (controller) aborts.set(next.clientId, controller);\n try {\n const attachments: AttachmentInput[] = [...(next.input.attachments ?? [])];\n for (let i = 0; i < next.files.length; i++) {\n const file = next.files[i]!;\n if (isHosted(file)) {\n const hosted = await startHosted(next, i, file);\n if (stale(next)) return;\n attachments.push({\n ...file.meta,\n kind: file.meta?.kind ?? attachmentKindFor(file.contentType),\n provider: hosted.provider,\n providerId: hosted.providerId,\n status: \"pending\",\n name: file.meta?.name ?? file.name,\n mime: file.contentType,\n });\n continue;\n }\n const key = `${next.clientId}:${i}`;\n let path = uploaded.get(key);\n if (!path) {\n const index = i;\n path = await uploadFile(conversationId, file, controller?.signal, (sent, total) => setProgress(next, index, sent, total));\n if (stale(next)) return;\n uploaded.set(key, path);\n }\n attachments.push({\n ...file.meta,\n kind: file.meta?.kind ?? attachmentKindFor(file.contentType),\n path,\n name: file.meta?.name ?? file.name,\n mime: file.contentType,\n });\n }\n if (stale(next)) return;\n const message = await opts.client.send({ ...next.input, attachments });\n // Posted, but the person signed out meanwhile: the next session must not hear of it.\n if (gen !== generation) return;\n for (let i = 0; i < next.files.length; i++) uploaded.delete(`${next.clientId}:${i}`);\n if (Object.values(next.hosted ?? {}).some((r) => !r.uploaded)) {\n // Posted with its video pending: it stays (out of the thread, which has the server's\n // copy) until the bytes are up, so a relaunch can carry the upload on.\n next.sentMessageId = message.id;\n emit();\n opts.onSent?.(message, next.clientId);\n void settleHosted(next, gen);\n continue;\n }\n queue = queue.filter((q) => q.clientId !== next.clientId);\n hostedAborts.delete(next.clientId);\n emit();\n opts.onSent?.(message, next.clientId);\n // The bubble now draws the stored copy: the local preview can go.\n releasePreviews(next);\n } catch (e) {\n if (stale(next)) return;\n const err = e instanceof ChatError ? e : new ChatError(e instanceof Error ? e.message : String(e), undefined, \"send\");\n next.attempts += 1;\n next.status = \"failed\";\n next.permanent = err.permanent;\n next.error = err.forbidden ? \"You can't post here\" : err.transient ? \"Not sent. Check your connection.\" : err.message;\n emit();\n // Later messages to this conversation wait behind a failed one, so order holds.\n break;\n } finally {\n if (controller && aborts.get(next.clientId) === controller) aborts.delete(next.clientId);\n }\n }\n } finally {\n if (running.get(conversationId) === gen) running.delete(conversationId);\n }\n }\n\n /** Can this failed message go without the person's help (retryAll, coming back online)? */\n const canAutoRetry = (x: QueuedMessage) =>\n !x.permanent &&\n !(x.lostFiles ?? 0) &&\n x.files.every((f) => typeof f.data !== \"string\" || Boolean(isHosted(f) ? opts.hostedUpload : opts.readFile || opts.upload));\n\n /** A failed message goes again: a posted one (its transfer failed) re-sends, idempotently, after carrying its upload on. */\n const requeue = (x: QueuedMessage) => {\n x.status = \"sending\";\n delete x.sentMessageId;\n };\n\n return {\n /** Queues a message; it shows at once and sends in order. Returns its clientId. */\n async send(input: Omit<SendInput, \"clientId\"> & { clientId?: string }, files: LocalFile[] = []): Promise<string> {\n await ensureLoaded();\n const gen = generation;\n const clientId = input.clientId ?? newId();\n const previews: Record<number, string> = {};\n files.forEach((f, i) => {\n if (f.previewUrl) previews[i] = f.previewUrl;\n });\n const queued: QueuedMessage = {\n clientId,\n input: { ...input, clientId },\n senderId: opts.userId,\n createdAt: new Date().toISOString(),\n status: \"sending\",\n previews,\n files: [...files],\n pendingFiles: files.map(describe),\n attempts: 0,\n };\n queue.push(queued);\n opts.onChange?.([...queue]);\n await persist(queued);\n // Cleared or discarded while its files were saved: it goes nowhere.\n if (gen !== generation || !queue.includes(queued)) return clientId;\n emit();\n void run(input.conversationId);\n return clientId;\n },\n\n async retry(clientId: string) {\n await ensureLoaded();\n const q = queue.find((x) => x.clientId === clientId);\n if (!q) return;\n // Retrying one retries everything failed in that conversation, in order, refusals too\n // (a person asked), up to one still waiting for a file.\n for (const x of queue) {\n if (x.input.conversationId !== q.input.conversationId || x.status !== \"failed\") continue;\n if ((x.lostFiles ?? 0) > 0) break;\n requeue(x);\n x.permanent = false;\n }\n emit();\n void run(q.input.conversationId);\n },\n\n /**\n * Gives a message the files it lost on a relaunch and sends it. `files` fill the lost\n * slots in order (`PendingMessage.files[i].lost`); the files that were kept stay. Pass\n * one per lost slot; with fewer, the message keeps waiting for the rest.\n */\n async reattach(clientId: string, files: LocalFile[]) {\n await ensureLoaded();\n const q = queue.find((x) => x.clientId === clientId);\n if (!q) return;\n const slots = q.pendingFiles ?? [];\n const kept = [...q.files];\n const given = [...files];\n const merged: LocalFile[] = [];\n const described: PendingFile[] = [];\n for (const slot of slots) {\n if (slot.lost) {\n const f = given.shift();\n if (f) {\n merged.push(f);\n described.push(describe(f));\n } else {\n described.push(slot);\n }\n } else {\n const f = kept.shift();\n if (f) {\n merged.push(f);\n described.push(slot);\n }\n }\n }\n // A message saved before slots were recorded: the given files are all of them.\n if (slots.length === 0) {\n merged.push(...given);\n described.push(...given.map(describe));\n }\n q.files = merged;\n q.pendingFiles = described;\n q.lostFiles = described.filter((d) => d.lost).length;\n if (q.lostFiles > 0) {\n emit();\n return;\n }\n const gen = generation;\n await persist(q);\n if (gen !== generation || !queue.includes(q)) return;\n requeue(q);\n emit();\n void run(q.input.conversationId);\n },\n\n /**\n * Retries failed messages (after the connection comes back), in order per conversation,\n * stopping at the first that can't go on its own: one waiting for a lost file, or one the\n * server refused (`permanent`, retried only by hand). The ones after it keep waiting.\n */\n async retryAll() {\n await ensureLoaded();\n const conversations = new Set<string>();\n const held = new Set<string>();\n for (const x of queue) {\n const c = x.input.conversationId;\n if (held.has(c) || x.status !== \"failed\") continue;\n if (!canAutoRetry(x)) {\n // A posted one (only its upload failed) holds nothing back.\n if (!x.sentMessageId) held.add(c);\n continue;\n }\n requeue(x);\n conversations.add(c);\n }\n emit();\n for (const c of conversations) void run(c);\n },\n\n /** Forgets every queued message, here and in the store (call it on sign-out). */\n async clear() {\n // At once, before any await: a send in flight stops at its next step and posts nothing.\n generation += 1;\n for (const c of aborts.values()) c.abort();\n aborts.clear();\n for (const c of hostedAborts.values()) c.abort();\n hostedAborts.clear();\n transfers.clear();\n running.clear();\n const gone = queue;\n queue = [];\n uploaded.clear();\n gone.forEach(releasePreviews);\n opts.onChange?.([]);\n await ensureLoaded();\n await store.save([]);\n },\n\n async discard(clientId: string) {\n await ensureLoaded();\n const gone = queue.find((q) => q.clientId === clientId);\n queue = queue.filter((q) => q.clientId !== clientId);\n aborts.get(clientId)?.abort();\n aborts.delete(clientId);\n stopHosted(clientId);\n if (gone) releasePreviews(gone);\n emit();\n },\n\n /**\n * Uploads one file to storage the way the outbox does (the `upload` hook, or `readFile` then\n * the client's upload) and resolves with its path: for files sent outside the queue, such as\n * a scheduled message's.\n */\n uploadFile(conversationId: string, file: LocalFile, o: { signal?: AbortSignal; onProgress?: UploadProgress } = {}): Promise<string> {\n return uploadFile(conversationId, file, o.signal, o.onProgress);\n },\n\n pending(conversationId?: string): PendingMessage[] {\n return queue\n .filter((q) => !conversationId || q.input.conversationId === conversationId)\n .map((q) => ({ ...q, files: q.pendingFiles }));\n },\n\n /** A new client id, made the way this outbox makes them. */\n newId,\n\n load: ensureLoaded,\n };\n}\n\nexport type Outbox = ReturnType<typeof createOutbox>;\n\nasync function notReadable(): Promise<never> {\n // This device's set-up (no readFile), not a refusal: a relaunch that can read it sends it.\n throw new ChatError(\"This file can't be read on this device\", \"GSFILE\", \"upload\");\n}\n"]}
|
|
@@ -586,6 +586,7 @@ function createChatClient(supabase, options = {}) {
|
|
|
586
586
|
userId: String(r.user_id),
|
|
587
587
|
role: r.role,
|
|
588
588
|
lastReadSeq: Number(r.last_read_seq ?? 0),
|
|
589
|
+
lastReadAt: r.last_read_at ? String(r.last_read_at) : null,
|
|
589
590
|
joinedAt: String(r.joined_at)
|
|
590
591
|
}));
|
|
591
592
|
},
|
|
@@ -651,6 +652,12 @@ function createChatClient(supabase, options = {}) {
|
|
|
651
652
|
async markRead(conversationId, seq) {
|
|
652
653
|
return rpc("mark_read", { p_conversation_id: conversationId, p_seq: seq ?? null });
|
|
653
654
|
},
|
|
655
|
+
/**
|
|
656
|
+
* Your own settings for a conversation. `markedUnread` (migration 0007) marks it unread for you
|
|
657
|
+
* only, as Messages' Mark as Unread: it counts as one unread until you read it, and your read
|
|
658
|
+
* place (what senders see as "Read") never moves back. It's sent only when given, so an app
|
|
659
|
+
* whose database predates 0007 keeps working.
|
|
660
|
+
*/
|
|
654
661
|
async setMySettings(conversationId, s) {
|
|
655
662
|
await rpc("set_my_settings", {
|
|
656
663
|
p_conversation_id: conversationId,
|
|
@@ -658,7 +665,20 @@ function createChatClient(supabase, options = {}) {
|
|
|
658
665
|
p_notify: s.notify ?? null,
|
|
659
666
|
p_archived: s.archived ?? null,
|
|
660
667
|
p_pinned: s.pinned ?? null,
|
|
661
|
-
p_clear_mute: s.mutedUntil === null
|
|
668
|
+
p_clear_mute: s.mutedUntil === null,
|
|
669
|
+
...s.markedUnread === void 0 ? {} : { p_marked_unread: s.markedUnread }
|
|
670
|
+
});
|
|
671
|
+
},
|
|
672
|
+
/**
|
|
673
|
+
* Delete for me (migration 0007): the conversation leaves your inbox, and its history your
|
|
674
|
+
* thread, until a new message you can read arrives. Nobody else's inbox, thread or read
|
|
675
|
+
* receipts change. `seq` is the latest message you saw (the inbox row's `lastSeq`): a message
|
|
676
|
+
* that came in after it isn't deleted unseen. Without it, everything up to the latest goes.
|
|
677
|
+
*/
|
|
678
|
+
async deleteConversationForMe(conversationId, seq) {
|
|
679
|
+
await rpc("delete_conversation_for_me", {
|
|
680
|
+
p_conversation_id: conversationId,
|
|
681
|
+
...seq === void 0 ? {} : { p_seq: seq }
|
|
662
682
|
});
|
|
663
683
|
},
|
|
664
684
|
async updateConversation(conversationId, s) {
|
|
@@ -874,12 +894,17 @@ function createChatClient(supabase, options = {}) {
|
|
|
874
894
|
"broadcast",
|
|
875
895
|
{ event: "reaction" },
|
|
876
896
|
({ payload }) => handlers.onSignal({ type: "reaction", conversationId, messageId: String(payload?.message_id) })
|
|
877
|
-
).on("broadcast", { event: "members" }, () => handlers.onSignal({ type: "members", conversationId })).on("broadcast", { event: "
|
|
897
|
+
).on("broadcast", { event: "members" }, () => handlers.onSignal({ type: "members", conversationId })).on("broadcast", { event: "read" }, ({ payload }) => {
|
|
898
|
+
if (payload?.user_id && payload.user_id !== me) {
|
|
899
|
+
handlers.onSignal({ type: "read", conversationId, userId: String(payload.user_id), seq: Number(payload.seq ?? 0), at: payload.at ? String(payload.at) : null });
|
|
900
|
+
}
|
|
901
|
+
}).on("broadcast", { event: "conversation" }, () => handlers.onSignal({ type: "conversation", conversationId })).on("broadcast", { event: "activity" }, ({ payload }) => {
|
|
878
902
|
if (payload?.userId && payload.userId !== me) handlers.onActivity?.({ userId: payload.userId, activity: payload.activity, at: Date.now() });
|
|
879
903
|
});
|
|
880
904
|
let joined = false;
|
|
881
905
|
const leave = join(channel, (status) => {
|
|
882
906
|
joined = status === "SUBSCRIBED";
|
|
907
|
+
handlers.onLive?.(joined);
|
|
883
908
|
if (status === "SUBSCRIBED") {
|
|
884
909
|
handlers.onJoin?.();
|
|
885
910
|
if (joinedOnce) handlers.onReconnect?.();
|
|
@@ -965,5 +990,5 @@ function sendBytes(url, body, opts = {}) {
|
|
|
965
990
|
}
|
|
966
991
|
|
|
967
992
|
export { ALLOWED_EXTENSIONS, CHAT_BUCKET, CHAT_LIMITS, CHAT_SCHEMA, ChatError, MAX_RANGES_PER_DAY, PLAYBACK_RATES, WEEKDAYS, attachmentKindFor, awayLine, awaySummary, conversationTopic, createChatClient, fileExtension, formatDuration, hoursSummary, isAllowedExtension, isAway, isWithinWorkingHours, localClock, minutesOf, namesLine, nextPlaybackRate, normalizeHours, randomId, recordingLimitMs, sendBytes, timeZoneLabel, toAttachment, toAvailability, toLinkPreview, toMessage, toScheduled, toSearchHit, toTopic, untilLabel, userTopic, waveformFromMetering, waveformPeaks };
|
|
968
|
-
//# sourceMappingURL=chunk-
|
|
969
|
-
//# sourceMappingURL=chunk-
|
|
993
|
+
//# sourceMappingURL=chunk-GEEJMKQF.js.map
|
|
994
|
+
//# sourceMappingURL=chunk-GEEJMKQF.js.map
|