birdclaw 0.8.2 → 0.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (247) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +10 -8
  3. package/bin/birdclaw.mjs +4 -66
  4. package/dist/cli/birdclaw.js +28165 -0
  5. package/dist/client/assets/AvatarChip-DLoqM5xD.js +1 -0
  6. package/dist/client/assets/ProfilePreview-BejAuYsJ.js +1 -0
  7. package/dist/client/assets/SavedTimelineView-BIS7HKpp.js +1 -0
  8. package/dist/client/assets/SmartTimestamp-BR0-9se2.js +1 -0
  9. package/dist/client/assets/TimelineRouteFrame-CyGPj0eM.js +1 -0
  10. package/dist/client/assets/blocks-7UDKQp8H.js +1 -0
  11. package/dist/client/assets/bookmarks-CbBkMvXk.js +1 -0
  12. package/dist/client/assets/chunk-C0phanGV.js +1 -0
  13. package/dist/client/assets/circle-check-C_Vq3ElD.js +1 -0
  14. package/dist/client/assets/client-stream-contracts-ys3XhWG4.js +5 -0
  15. package/dist/client/assets/createLucideIcon-JV8isFFR.js +1 -0
  16. package/dist/client/assets/data-sources-Cm2bpNvg.js +1 -0
  17. package/dist/client/assets/discuss-DTjaOugw.js +1 -0
  18. package/dist/client/assets/dms-CGd6Eogq.js +1 -0
  19. package/dist/client/assets/inbox-BHlGuOy2.js +1 -0
  20. package/dist/client/assets/index-CEIG7S6s.js +31 -0
  21. package/dist/client/assets/index-bpFrQ5yG.css +1 -0
  22. package/dist/client/assets/likes-cLrcAQem.js +1 -0
  23. package/dist/client/assets/links-CM9QO1LC.js +1 -0
  24. package/dist/client/assets/mapbox-BxTlqXt9.js +2 -0
  25. package/dist/client/assets/mapbox-gl-dgf_hX3a.js +3215 -0
  26. package/dist/client/assets/mentions-CxKCgzIf.js +1 -0
  27. package/dist/client/assets/network-map-B5a3whqj.js +2 -0
  28. package/dist/client/assets/profile-analyze-CRtNEwlb.js +1 -0
  29. package/dist/client/assets/profile-hydration-client-YEtJsNTv.js +1 -0
  30. package/dist/client/assets/profiles._handle-C82_HoKX.js +1 -0
  31. package/dist/client/assets/query-client-fYu2rzRC.js +17 -0
  32. package/dist/client/assets/rate-limits-ScaEwdVK.js +1 -0
  33. package/dist/client/assets/react-dom-DHl6Ug7F.js +1 -0
  34. package/dist/client/assets/react-nBylq1U5.js +1 -0
  35. package/dist/client/assets/repeat-2-xCwHM9hD.js +1 -0
  36. package/dist/client/assets/routes-q7ZaW4En.js +1 -0
  37. package/dist/client/assets/schemas-I9r6F6ya.js +64 -0
  38. package/dist/client/assets/search-Dq5kYsxA.js +1 -0
  39. package/dist/client/assets/sparkles-CQVlvHsZ.js +1 -0
  40. package/dist/client/assets/styles-B8s3tt3r.css +2 -0
  41. package/dist/client/assets/today-CeG1O7Py.js +1 -0
  42. package/dist/client/assets/triangle-alert-CBL7s2pf.js +1 -0
  43. package/dist/client/assets/useTimelineRouteData-1HsqgvUi.js +1 -0
  44. package/dist/client/assets/users-CHbKlqUr.js +1 -0
  45. package/dist/server/assets/AvatarChip-zUDAEmjL.js +105 -0
  46. package/dist/server/assets/FeedState-ntW0Q2GB.js +214 -0
  47. package/dist/server/assets/ProfileAnalysisStream-BFvhVdhn.js +198 -0
  48. package/dist/server/assets/ProfilePreview-C6gAor_j.js +752 -0
  49. package/dist/server/assets/SavedTimelineView-BG1jnBp1.js +64 -0
  50. package/dist/server/assets/SmartTimestamp-DfwE1NGf.js +45 -0
  51. package/dist/server/assets/SyncNowButton-BOn_IBXS.js +76 -0
  52. package/dist/server/assets/TimelineRouteFrame-CU7ilM7U.js +85 -0
  53. package/dist/server/assets/TweetRichText-DhCVv1-6.js +74 -0
  54. package/dist/server/assets/_tanstack-start-manifest_v-C-ZRnG_n.js +148 -0
  55. package/dist/server/assets/account-selection-CTdFGWRk.js +44 -0
  56. package/dist/server/assets/blocks-C1mgGTB3.js +299 -0
  57. package/dist/server/assets/blocks-DSgQghqP.js +17 -0
  58. package/dist/server/assets/bookmarks-BJN8tykY.js +14 -0
  59. package/dist/server/assets/client-stream-contracts-C2xbWVjm.js +769 -0
  60. package/dist/server/assets/data-sources-BnA1Q94p.js +180 -0
  61. package/dist/server/assets/discuss-CJ1dau1j.js +15 -0
  62. package/dist/server/assets/discuss-QTo08NCN.js +338 -0
  63. package/dist/server/assets/dms-BuLj4bp8.js +368 -0
  64. package/dist/server/assets/dms-DAyQrVM2.js +240 -0
  65. package/dist/server/assets/empty-plugin-adapters-DzrEkdBF.js +5 -0
  66. package/dist/server/assets/inbox-CkGOaW1q.js +214 -0
  67. package/dist/server/assets/inbox-DpWd1EzC.js +146 -0
  68. package/dist/server/assets/likes-DBOAtsJU.js +14 -0
  69. package/dist/server/assets/links-DAhSjynu.js +240 -0
  70. package/dist/server/assets/links-DmH5lxHO.js +468 -0
  71. package/dist/server/assets/mentions-BH2MzKtB.js +26 -0
  72. package/dist/server/assets/network-map-D3CzRcC4.js +224 -0
  73. package/dist/server/assets/network-map-D5DoLOwR.js +582 -0
  74. package/dist/server/assets/profile-analyze-BP65PED0.js +90 -0
  75. package/dist/server/assets/profile-analyze-C1NoM0tV.js +9 -0
  76. package/dist/server/assets/profile-hydration-client-GJ4kwJS8.js +133 -0
  77. package/dist/server/assets/profiles._handle-DjwlN_ac.js +184 -0
  78. package/dist/server/assets/profiles._handle-DsLNj2Ca.js +12 -0
  79. package/dist/server/assets/query-client-BdauHBgd.js +923 -0
  80. package/dist/server/assets/rate-limits-VAr2qzYD.js +262 -0
  81. package/dist/server/assets/route-search-BUlQ5lGM.js +117 -0
  82. package/dist/server/assets/router-DqkwSPiM.js +17026 -0
  83. package/dist/server/assets/routes-A9c9ZhwN.js +26 -0
  84. package/dist/server/assets/start-FaDOTmto.js +4 -0
  85. package/dist/server/assets/today-B5hVM57Z.js +17 -0
  86. package/dist/server/assets/today-fvGiZ7ud.js +303 -0
  87. package/dist/server/assets/ui-qbmcMSSX.js +137 -0
  88. package/{src/components/useDebouncedValue.ts → dist/server/assets/useDebouncedValue-DOnA6Xcy.js} +4 -4
  89. package/dist/server/assets/useTimelineRouteData-27cxynxa.js +1101 -0
  90. package/dist/server/server.js +5520 -0
  91. package/package.json +27 -34
  92. package/playwright.config.ts +0 -35
  93. package/scripts/browser-perf.mjs +0 -427
  94. package/scripts/build-docs-site.mjs +0 -967
  95. package/scripts/docs-site-assets.mjs +0 -311
  96. package/scripts/run-vitest.mjs +0 -21
  97. package/scripts/sanitize-node-options.mjs +0 -23
  98. package/scripts/start-test-server.mjs +0 -42
  99. package/src/cli-moderation.ts +0 -210
  100. package/src/cli.ts +0 -2336
  101. package/src/components/AccountSwitcher.tsx +0 -186
  102. package/src/components/AppNav.tsx +0 -118
  103. package/src/components/AvatarChip.tsx +0 -58
  104. package/src/components/BrandMark.tsx +0 -67
  105. package/src/components/ConversationThread.tsx +0 -131
  106. package/src/components/DmWorkspace.tsx +0 -286
  107. package/src/components/EmbeddedTweetCard.tsx +0 -55
  108. package/src/components/FeedState.tsx +0 -147
  109. package/src/components/FloatingPreview.tsx +0 -382
  110. package/src/components/InboxCard.tsx +0 -152
  111. package/src/components/LinkPreviewCard.tsx +0 -292
  112. package/src/components/MarkdownViewer.tsx +0 -777
  113. package/src/components/ProfileAnalysisStream.tsx +0 -428
  114. package/src/components/ProfilePreview.tsx +0 -129
  115. package/src/components/SavedTimelineView.tsx +0 -155
  116. package/src/components/SmartTimestamp.tsx +0 -72
  117. package/src/components/SyncNowButton.tsx +0 -140
  118. package/src/components/ThemeSlider.tsx +0 -80
  119. package/src/components/TimelineCard.tsx +0 -533
  120. package/src/components/TimelineRouteFrame.tsx +0 -186
  121. package/src/components/TweetArticleCard.tsx +0 -66
  122. package/src/components/TweetMediaGrid.tsx +0 -185
  123. package/src/components/TweetRichText.tsx +0 -159
  124. package/src/components/account-selection.ts +0 -64
  125. package/src/components/useTimelineRouteData.ts +0 -323
  126. package/src/lib/account-sync-job.ts +0 -666
  127. package/src/lib/actions-transport.ts +0 -300
  128. package/src/lib/api-client.ts +0 -419
  129. package/src/lib/archive-finder.ts +0 -185
  130. package/src/lib/archive-import.ts +0 -2764
  131. package/src/lib/authored-live.ts +0 -1072
  132. package/src/lib/avatar-cache.ts +0 -349
  133. package/src/lib/backup.ts +0 -2741
  134. package/src/lib/bird-actions.ts +0 -294
  135. package/src/lib/bird-command.ts +0 -130
  136. package/src/lib/bird.ts +0 -1140
  137. package/src/lib/blocklist.ts +0 -136
  138. package/src/lib/blocks-write.ts +0 -167
  139. package/src/lib/blocks.ts +0 -389
  140. package/src/lib/bookmark-sync-job.ts +0 -536
  141. package/src/lib/client-cache.ts +0 -109
  142. package/src/lib/config.ts +0 -224
  143. package/src/lib/conversation-surface.ts +0 -205
  144. package/src/lib/data-sources.ts +0 -219
  145. package/src/lib/db.ts +0 -1135
  146. package/src/lib/dms-live.ts +0 -933
  147. package/src/lib/effect-runtime.ts +0 -45
  148. package/src/lib/follow-graph.ts +0 -1097
  149. package/src/lib/geocoding.ts +0 -296
  150. package/src/lib/http-effect.ts +0 -222
  151. package/src/lib/identity-search-index.ts +0 -369
  152. package/src/lib/inbox.ts +0 -241
  153. package/src/lib/link-index.ts +0 -641
  154. package/src/lib/link-insights.ts +0 -860
  155. package/src/lib/link-preview-metadata.ts +0 -754
  156. package/src/lib/location.ts +0 -137
  157. package/src/lib/media-fetch.ts +0 -860
  158. package/src/lib/media-includes.ts +0 -165
  159. package/src/lib/mention-threads-live.ts +0 -917
  160. package/src/lib/mentions-export.ts +0 -147
  161. package/src/lib/mentions-live.ts +0 -1238
  162. package/src/lib/moderation-target.ts +0 -216
  163. package/src/lib/moderation-write.ts +0 -131
  164. package/src/lib/mutes-write.ts +0 -167
  165. package/src/lib/mutes.ts +0 -84
  166. package/src/lib/ndjson-stream.ts +0 -106
  167. package/src/lib/network-map.ts +0 -382
  168. package/src/lib/openai.ts +0 -117
  169. package/src/lib/period-digest.ts +0 -1552
  170. package/src/lib/present.ts +0 -118
  171. package/src/lib/profile-affiliation-hydration.ts +0 -228
  172. package/src/lib/profile-affiliations.ts +0 -262
  173. package/src/lib/profile-analysis.ts +0 -1272
  174. package/src/lib/profile-bio-entities.ts +0 -318
  175. package/src/lib/profile-history.ts +0 -164
  176. package/src/lib/profile-hydration.ts +0 -180
  177. package/src/lib/profile-replies.ts +0 -77
  178. package/src/lib/profile-resolver.ts +0 -650
  179. package/src/lib/queries.ts +0 -2381
  180. package/src/lib/research.ts +0 -652
  181. package/src/lib/search-discussion.ts +0 -1016
  182. package/src/lib/seed.ts +0 -613
  183. package/src/lib/sqlite.ts +0 -147
  184. package/src/lib/sync-cache.ts +0 -65
  185. package/src/lib/theme-transition.ts +0 -113
  186. package/src/lib/theme.tsx +0 -165
  187. package/src/lib/timeline-collections-live.ts +0 -581
  188. package/src/lib/timeline-live.ts +0 -452
  189. package/src/lib/tweet-account-edges.ts +0 -48
  190. package/src/lib/tweet-lookup.ts +0 -46
  191. package/src/lib/tweet-render.ts +0 -430
  192. package/src/lib/tweet-search-live.ts +0 -566
  193. package/src/lib/types.ts +0 -723
  194. package/src/lib/ui.ts +0 -529
  195. package/src/lib/url-expansion-store.ts +0 -110
  196. package/src/lib/url-expansion.ts +0 -343
  197. package/src/lib/url-safety.ts +0 -220
  198. package/src/lib/web-sync.ts +0 -516
  199. package/src/lib/whois.ts +0 -1079
  200. package/src/lib/x-profile.ts +0 -365
  201. package/src/lib/x-web.ts +0 -199
  202. package/src/lib/xurl-rate-limits.ts +0 -267
  203. package/src/lib/xurl.ts +0 -1677
  204. package/src/routeTree.gen.ts +0 -723
  205. package/src/router.tsx +0 -20
  206. package/src/routes/__root.tsx +0 -79
  207. package/src/routes/api/action.tsx +0 -147
  208. package/src/routes/api/avatar.tsx +0 -50
  209. package/src/routes/api/blocks.tsx +0 -35
  210. package/src/routes/api/conversation.tsx +0 -45
  211. package/src/routes/api/data-sources.tsx +0 -24
  212. package/src/routes/api/inbox.tsx +0 -43
  213. package/src/routes/api/link-insights.tsx +0 -85
  214. package/src/routes/api/link-preview.tsx +0 -47
  215. package/src/routes/api/network-map.tsx +0 -55
  216. package/src/routes/api/period-digest.tsx +0 -101
  217. package/src/routes/api/profile-analysis.tsx +0 -97
  218. package/src/routes/api/profile-hydrate.tsx +0 -54
  219. package/src/routes/api/query.tsx +0 -115
  220. package/src/routes/api/search-discussion.tsx +0 -113
  221. package/src/routes/api/status.tsx +0 -28
  222. package/src/routes/api/sync.tsx +0 -105
  223. package/src/routes/api/xurl-rate-limits.tsx +0 -24
  224. package/src/routes/blocks.tsx +0 -377
  225. package/src/routes/bookmarks.tsx +0 -18
  226. package/src/routes/data-sources.tsx +0 -257
  227. package/src/routes/discuss.tsx +0 -419
  228. package/src/routes/dms.tsx +0 -432
  229. package/src/routes/inbox.tsx +0 -226
  230. package/src/routes/index.tsx +0 -32
  231. package/src/routes/likes.tsx +0 -18
  232. package/src/routes/links.tsx +0 -994
  233. package/src/routes/mentions.tsx +0 -32
  234. package/src/routes/network-map.tsx +0 -1035
  235. package/src/routes/profile-analyze.tsx +0 -112
  236. package/src/routes/profiles.$handle.tsx +0 -228
  237. package/src/routes/rate-limits.tsx +0 -309
  238. package/src/routes/today.tsx +0 -511
  239. package/src/styles.css +0 -257
  240. package/tsconfig.json +0 -29
  241. package/vite.config.ts +0 -29
  242. /package/{public → dist/client}/birdclaw-mark.png +0 -0
  243. /package/{public → dist/client}/favicon.ico +0 -0
  244. /package/{public → dist/client}/logo192.png +0 -0
  245. /package/{public → dist/client}/logo512.png +0 -0
  246. /package/{public → dist/client}/manifest.json +0 -0
  247. /package/{public → dist/client}/robots.txt +0 -0
@@ -1,1238 +0,0 @@
1
- import type { Database } from "./sqlite";
2
- import { Effect } from "effect";
3
- import {
4
- getAuthenticatedBirdAccountEffect,
5
- listMentionsViaBirdEffect,
6
- } from "./bird";
7
- import type { MentionsDataSource } from "./config";
8
- import { getNativeDb } from "./db";
9
- import { runEffectPromise, tryPromise } from "./effect-runtime";
10
- import { buildMediaJsonFromIncludes, countTweetMedia } from "./media-includes";
11
- import { serializeMentionItemsAsXurlCompatible } from "./mentions-export";
12
- import { listTimelineItems } from "./queries";
13
- import { deleteSyncCache, readSyncCache, writeSyncCache } from "./sync-cache";
14
- import { tweetEntitiesFromXurl } from "./tweet-render";
15
- import type {
16
- ReplyFilter,
17
- TweetEntities,
18
- XurlMentionData,
19
- XurlMentionsResponse,
20
- XurlMediaItem,
21
- XurlMentionUser,
22
- } from "./types";
23
- import { upsertTweetAccountEdge } from "./tweet-account-edges";
24
- import { ensureStubProfileForXUser, upsertProfileFromXUser } from "./x-profile";
25
- import { listMentionsViaXurl, lookupUsersByHandles } from "./xurl";
26
-
27
- export const DEFAULT_MENTIONS_CACHE_TTL_MS = 2 * 60_000;
28
- const MIN_XURL_MENTIONS_LIMIT = 5;
29
- const MAX_XURL_MENTIONS_LIMIT = 100;
30
- type MentionSyncMode = Exclude<MentionsDataSource, "birdclaw">;
31
- type MentionLiveSource = Exclude<MentionSyncMode, "auto">;
32
- export interface MentionsProgress {
33
- source: "bird" | "xurl" | "cache";
34
- fetched: number;
35
- total?: number;
36
- page?: number;
37
- maxPages?: number;
38
- pageSize?: number;
39
- done: boolean;
40
- }
41
- export interface SyncMentionsOptions {
42
- account?: string;
43
- mode?: string;
44
- limit?: number;
45
- maxPages?: number;
46
- refresh?: boolean;
47
- cacheTtlMs?: number;
48
- sinceId?: string;
49
- startTime?: string;
50
- onProgress?: (progress: MentionsProgress) => void;
51
- }
52
- interface ExportMentionsViaCachedLiveSourceOptions {
53
- mode: MentionSyncMode;
54
- account?: string;
55
- search?: string;
56
- replyFilter?: ReplyFilter;
57
- limit?: number;
58
- all?: boolean;
59
- maxPages?: number;
60
- refresh?: boolean;
61
- cacheTtlMs?: number;
62
- }
63
- type MentionScanBoundary =
64
- | { kind: "auto" }
65
- | { kind: "since"; sinceId: string }
66
- | { kind: "start"; startTime: string }
67
- | { kind: "unbounded" };
68
- interface MentionScanShape {
69
- endpoint: "mentions";
70
- mode: MentionLiveSource;
71
- accountId: string;
72
- pageSize: number;
73
- boundary: MentionScanBoundary;
74
- }
75
- interface MentionCursorValue extends XurlMentionsResponse {
76
- birdclaw?: {
77
- boundary?: MentionScanBoundary;
78
- pendingNewestId?: string | null;
79
- };
80
- }
81
- interface MentionHighWaterValue {
82
- sinceId: string;
83
- }
84
-
85
- function toError(error: unknown) {
86
- return error instanceof Error ? error : new Error(String(error));
87
- }
88
-
89
- function trySync<T>(try_: () => T) {
90
- return Effect.try({
91
- try: try_,
92
- catch: toError,
93
- });
94
- }
95
-
96
- function getMentionsFetchModeKey({
97
- scope,
98
- mode,
99
- accountId,
100
- pageSize,
101
- all,
102
- maxPages,
103
- sinceId,
104
- startTime,
105
- }: {
106
- scope: "sync" | "export";
107
- mode: MentionsDataSource;
108
- accountId: string;
109
- pageSize: number;
110
- all: boolean;
111
- maxPages: number | null;
112
- sinceId: string | null;
113
- startTime: string | null;
114
- }) {
115
- return `mentions:${scope}:${mode}:${accountId}:${String(pageSize)}:${all ? "all" : "single"}:${maxPages === null ? "all-pages" : String(maxPages)}:${sinceId ?? "no-since"}:${startTime ?? "no-start"}`;
116
- }
117
-
118
- function getLegacyMentionsFetchModeKeyWithoutStart({
119
- scope,
120
- mode,
121
- accountId,
122
- pageSize,
123
- all,
124
- maxPages,
125
- sinceId,
126
- }: {
127
- scope: "sync" | "export";
128
- mode: MentionsDataSource;
129
- accountId: string;
130
- pageSize: number;
131
- all: boolean;
132
- maxPages: number | null;
133
- sinceId: string | null;
134
- }) {
135
- return `mentions:${scope}:${mode}:${accountId}:${String(pageSize)}:${all ? "all" : "single"}:${maxPages === null ? "all-pages" : String(maxPages)}:${sinceId ?? "no-since"}`;
136
- }
137
-
138
- function encodeCacheKeyPart(value: string) {
139
- return encodeURIComponent(value);
140
- }
141
-
142
- function getMentionScanBoundaryKey(boundary: MentionScanBoundary) {
143
- switch (boundary.kind) {
144
- case "auto":
145
- return "auto";
146
- case "since":
147
- return `since=${encodeCacheKeyPart(boundary.sinceId)}`;
148
- case "start":
149
- return `start=${encodeCacheKeyPart(boundary.startTime)}`;
150
- case "unbounded":
151
- return "unbounded";
152
- }
153
- }
154
-
155
- function getMentionScanShapeKey(shape: MentionScanShape) {
156
- return [
157
- `endpoint=${shape.endpoint}`,
158
- `mode=${shape.mode}`,
159
- `account=${encodeCacheKeyPart(shape.accountId)}`,
160
- `page=${String(shape.pageSize)}`,
161
- `boundary=${getMentionScanBoundaryKey(shape.boundary)}`,
162
- ].join(":");
163
- }
164
-
165
- function getMentionCursorKey(shape: MentionScanShape) {
166
- return `mentions:sync:cursor:v2:${getMentionScanShapeKey(shape)}`;
167
- }
168
-
169
- function getMentionResultCacheKey({
170
- shape,
171
- all,
172
- maxPages,
173
- }: {
174
- shape: MentionScanShape;
175
- all: boolean;
176
- maxPages: number | null;
177
- }) {
178
- return `mentions:sync:result:v2:${getMentionScanShapeKey(shape)}:${all ? "all" : "single"}:${maxPages === null ? "all-pages" : String(maxPages)}`;
179
- }
180
-
181
- function getMentionHighWaterKey({
182
- mode,
183
- accountId,
184
- }: {
185
- mode: MentionLiveSource;
186
- accountId: string;
187
- }) {
188
- return `mentions:sync:high-water:v1:mode=${mode}:account=${encodeCacheKeyPart(accountId)}`;
189
- }
190
-
191
- function getMentionCursorBoundary({
192
- explicitSinceId,
193
- explicitStartTime,
194
- }: {
195
- explicitSinceId?: string;
196
- explicitStartTime?: string;
197
- }): MentionScanBoundary {
198
- if (explicitSinceId) {
199
- return { kind: "since", sinceId: explicitSinceId };
200
- }
201
- if (explicitStartTime) {
202
- return { kind: "start", startTime: explicitStartTime };
203
- }
204
- return { kind: "auto" };
205
- }
206
-
207
- function getMentionRequestBoundary({
208
- sinceId,
209
- startTime,
210
- }: {
211
- sinceId?: string;
212
- startTime?: string;
213
- }): MentionScanBoundary {
214
- if (sinceId) {
215
- return { kind: "since", sinceId };
216
- }
217
- if (startTime) {
218
- return { kind: "start", startTime };
219
- }
220
- return { kind: "unbounded" };
221
- }
222
-
223
- function getLegacyMentionCursorKeys(shape: MentionScanShape) {
224
- const sinceId =
225
- shape.boundary.kind === "since" ? shape.boundary.sinceId : null;
226
- const startTime =
227
- shape.boundary.kind === "start" ? shape.boundary.startTime : null;
228
- const keys = [
229
- getMentionsFetchModeKey({
230
- scope: "sync",
231
- mode: shape.mode,
232
- accountId: shape.accountId,
233
- pageSize: shape.pageSize,
234
- all: false,
235
- maxPages: null,
236
- sinceId,
237
- startTime,
238
- }),
239
- ];
240
- if (!startTime) {
241
- keys.push(
242
- getLegacyMentionsFetchModeKeyWithoutStart({
243
- scope: "sync",
244
- mode: shape.mode,
245
- accountId: shape.accountId,
246
- pageSize: shape.pageSize,
247
- all: false,
248
- maxPages: null,
249
- sinceId,
250
- }),
251
- );
252
- }
253
- return [...new Set(keys)];
254
- }
255
-
256
- function parseCacheTtlMs(value?: number) {
257
- if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
258
- return DEFAULT_MENTIONS_CACHE_TTL_MS;
259
- }
260
- return Math.floor(value);
261
- }
262
-
263
- function assertXurlLimit(limit: number) {
264
- if (limit < MIN_XURL_MENTIONS_LIMIT || limit > MAX_XURL_MENTIONS_LIMIT) {
265
- throw new Error("xurl mode requires --limit between 5 and 100");
266
- }
267
- }
268
-
269
- function assertBirdLimit(limit: number) {
270
- if (!Number.isFinite(limit) || limit < 1) {
271
- throw new Error("bird mode requires --limit of at least 1");
272
- }
273
- }
274
-
275
- function parseMaxPages(value?: number) {
276
- if (value === undefined) {
277
- return null;
278
- }
279
- if (!Number.isFinite(value) || value < 1) {
280
- throw new Error("--max-pages must be at least 1");
281
- }
282
- return Math.floor(value);
283
- }
284
-
285
- function parseSyncMode(value?: string): MentionSyncMode {
286
- const mode = value ?? "auto";
287
- if (mode !== "auto" && mode !== "bird" && mode !== "xurl") {
288
- throw new Error("--mode must be auto, bird, or xurl");
289
- }
290
- return mode;
291
- }
292
-
293
- function getCachedPaginationToken(
294
- cached?: { value: XurlMentionsResponse } | null,
295
- ) {
296
- return typeof cached?.value.meta?.next_token === "string" &&
297
- cached.value.meta.next_token.length > 0
298
- ? cached.value.meta.next_token
299
- : undefined;
300
- }
301
-
302
- function parseCachedMentionBoundary(
303
- value: MentionCursorValue | XurlMentionsResponse,
304
- fallbackBoundary?: MentionScanBoundary,
305
- ) {
306
- const boundary = (value as MentionCursorValue).birdclaw?.boundary;
307
- if (!boundary || typeof boundary !== "object") {
308
- return fallbackBoundary;
309
- }
310
- if (boundary.kind === "unbounded" || boundary.kind === "auto") {
311
- return boundary;
312
- }
313
- if (boundary.kind === "since" && typeof boundary.sinceId === "string") {
314
- return boundary;
315
- }
316
- if (boundary.kind === "start" && typeof boundary.startTime === "string") {
317
- return boundary;
318
- }
319
- return fallbackBoundary;
320
- }
321
-
322
- function getCachedMentionPendingNewestId(
323
- value: MentionCursorValue | XurlMentionsResponse | undefined,
324
- ) {
325
- const pendingNewestId = (value as MentionCursorValue | undefined)?.birdclaw
326
- ?.pendingNewestId;
327
- return isNumericTweetId(pendingNewestId) ? pendingNewestId : undefined;
328
- }
329
-
330
- function addMentionCursorState(
331
- payload: XurlMentionsResponse,
332
- boundary: MentionScanBoundary,
333
- pendingNewestId: string | undefined,
334
- ): MentionCursorValue {
335
- return {
336
- ...payload,
337
- birdclaw: { boundary, pendingNewestId: pendingNewestId ?? null },
338
- };
339
- }
340
-
341
- function readMentionCursor({
342
- db,
343
- shape,
344
- cursorKey,
345
- legacyCursorKeys,
346
- }: {
347
- db: Database;
348
- shape: MentionScanShape;
349
- cursorKey: string;
350
- legacyCursorKeys: string[];
351
- }) {
352
- const fallbackBoundary =
353
- shape.boundary.kind === "auto" ? undefined : shape.boundary;
354
- const current = readSyncCache<MentionCursorValue>(cursorKey, db);
355
- const currentToken = getCachedPaginationToken(current);
356
- if (current && currentToken) {
357
- return {
358
- key: cursorKey,
359
- token: currentToken,
360
- boundary: parseCachedMentionBoundary(current.value, fallbackBoundary),
361
- pendingNewestId: getCachedMentionPendingNewestId(current.value),
362
- legacyKeys: [] as string[],
363
- };
364
- }
365
-
366
- for (const legacyKey of legacyCursorKeys) {
367
- const legacy = readSyncCache<MentionCursorValue>(legacyKey, db);
368
- const legacyToken = getCachedPaginationToken(legacy);
369
- if (legacy && legacyToken) {
370
- return {
371
- key: legacyKey,
372
- token: legacyToken,
373
- boundary: parseCachedMentionBoundary(legacy.value, fallbackBoundary),
374
- pendingNewestId: getCachedMentionPendingNewestId(legacy.value),
375
- legacyKeys: [legacyKey],
376
- };
377
- }
378
- }
379
-
380
- return undefined;
381
- }
382
-
383
- function isNumericTweetId(value: string | undefined | null): value is string {
384
- return typeof value === "string" && /^[0-9]+$/.test(value);
385
- }
386
-
387
- function maxNumericTweetId(...ids: Array<string | undefined | null>) {
388
- return ids.filter(isNumericTweetId).reduce<string | undefined>((max, id) => {
389
- if (!max) {
390
- return id;
391
- }
392
- if (id.length !== max.length) {
393
- return id.length > max.length ? id : max;
394
- }
395
- return id > max ? id : max;
396
- }, undefined);
397
- }
398
-
399
- function getNewestMentionId(payload: XurlMentionsResponse) {
400
- return maxNumericTweetId(
401
- typeof payload.meta?.newest_id === "string"
402
- ? payload.meta.newest_id
403
- : undefined,
404
- ...payload.data.map((tweet) => tweet.id),
405
- );
406
- }
407
-
408
- function readMentionHighWaterId(
409
- db: Database,
410
- mode: MentionLiveSource,
411
- accountId: string,
412
- ) {
413
- const cached = readSyncCache<MentionHighWaterValue>(
414
- getMentionHighWaterKey({ mode, accountId }),
415
- db,
416
- );
417
- return isNumericTweetId(cached?.value.sinceId)
418
- ? cached.value.sinceId
419
- : undefined;
420
- }
421
-
422
- function writeMentionHighWaterId(
423
- db: Database,
424
- mode: MentionLiveSource,
425
- accountId: string,
426
- sinceId: string | undefined,
427
- ) {
428
- if (!isNumericTweetId(sinceId)) {
429
- return;
430
- }
431
- writeSyncCache(getMentionHighWaterKey({ mode, accountId }), { sinceId }, db);
432
- }
433
-
434
- function resolveAccount(db: Database, accountId?: string) {
435
- const row = accountId
436
- ? (db
437
- .prepare(
438
- "select id, handle, external_user_id from accounts where id = ?",
439
- )
440
- .get(accountId) as
441
- | { id: string; handle: string; external_user_id: string | null }
442
- | undefined)
443
- : (db
444
- .prepare(
445
- `
446
- select id, handle, external_user_id
447
- from accounts
448
- order by is_default desc, created_at asc
449
- limit 1
450
- `,
451
- )
452
- .get() as
453
- | { id: string; handle: string; external_user_id: string | null }
454
- | undefined);
455
-
456
- if (!row) {
457
- throw new Error(`Unknown account: ${accountId ?? "default"}`);
458
- }
459
-
460
- return {
461
- accountId: row.id,
462
- username: row.handle.replace(/^@/, ""),
463
- externalUserId:
464
- typeof row.external_user_id === "string" &&
465
- row.external_user_id.trim().length > 0
466
- ? row.external_user_id.trim()
467
- : undefined,
468
- };
469
- }
470
-
471
- function verifyBirdAccountMatchesEffect({
472
- accountId,
473
- username,
474
- externalUserId,
475
- }: ReturnType<typeof resolveAccount>) {
476
- return Effect.gen(function* () {
477
- const authenticated = yield* getAuthenticatedBirdAccountEffect();
478
- if (
479
- externalUserId &&
480
- authenticated.id &&
481
- authenticated.id === externalUserId
482
- ) {
483
- return;
484
- }
485
- if (externalUserId && authenticated.id) {
486
- return yield* Effect.fail(
487
- new Error(
488
- `bird is authenticated as user ${authenticated.id}; refusing to sync into ${accountId} (${externalUserId})`,
489
- ),
490
- );
491
- }
492
- if (authenticated.username.toLowerCase() !== username.toLowerCase()) {
493
- return yield* Effect.fail(
494
- new Error(
495
- `bird is authenticated as @${authenticated.username}; refusing to sync into ${accountId} (@${username})`,
496
- ),
497
- );
498
- }
499
- });
500
- }
501
-
502
- function findNewestArchiveMentionId(db: Database, accountId: string) {
503
- const row = db
504
- .prepare(
505
- `
506
- select t.id
507
- from tweets t
508
- join tweet_account_edges e
509
- on e.tweet_id = t.id
510
- where e.account_id = ?
511
- and e.kind = 'mention'
512
- and e.source in ('archive', 'legacy')
513
- and length(t.id) > 0
514
- and t.id glob '[0-9]*'
515
- and t.id not glob '*[^0-9]*'
516
- order by length(t.id) desc, t.id desc
517
- limit 1
518
- `,
519
- )
520
- .get(accountId) as { id: string } | undefined;
521
- return row?.id;
522
- }
523
-
524
- function toLocalEntities(tweet: XurlMentionData): TweetEntities {
525
- return tweetEntitiesFromXurl(tweet.entities);
526
- }
527
-
528
- function replaceTweetFts(db: Database, tweetId: string, text: string) {
529
- db.prepare("delete from tweets_fts where tweet_id = ?").run(tweetId);
530
- db.prepare("insert into tweets_fts (tweet_id, text) values (?, ?)").run(
531
- tweetId,
532
- text,
533
- );
534
- }
535
-
536
- function mergeMentionsIntoLocalStore(
537
- db: Database,
538
- accountId: string,
539
- payload: XurlMentionsResponse,
540
- source: MentionsDataSource,
541
- ) {
542
- const usersById = new Map(
543
- (payload.includes?.users ?? []).map((user) => [user.id, user]),
544
- );
545
- const upsertTweet = db.prepare(
546
- `
547
- insert into tweets (
548
- id, account_id, author_profile_id, kind, text, created_at,
549
- is_replied, reply_to_id, like_count, media_count, bookmarked, liked,
550
- entities_json, media_json, quoted_tweet_id
551
- ) values (?, ?, ?, 'mention', ?, ?, 0, null, ?, ?, 0, 0, ?, ?, null)
552
- on conflict(id) do update set
553
- account_id = tweets.account_id,
554
- author_profile_id = excluded.author_profile_id,
555
- kind = case
556
- when tweets.kind in ('authored', 'home', 'mention') then tweets.kind
557
- when excluded.kind in ('authored', 'home', 'mention') then excluded.kind
558
- else excluded.kind
559
- end,
560
- text = excluded.text,
561
- created_at = excluded.created_at,
562
- like_count = excluded.like_count,
563
- media_count = max(tweets.media_count, excluded.media_count),
564
- entities_json = excluded.entities_json,
565
- media_json = case
566
- when excluded.media_json not in ('', '[]', 'null') then excluded.media_json
567
- else tweets.media_json
568
- end,
569
- is_replied = max(tweets.is_replied, excluded.is_replied),
570
- bookmarked = max(tweets.bookmarked, excluded.bookmarked),
571
- liked = max(tweets.liked, excluded.liked)
572
- `,
573
- );
574
-
575
- const writePayload = db.transaction(() => {
576
- const seenAt = new Date().toISOString();
577
- for (const tweet of payload.data) {
578
- const author =
579
- usersById.get(tweet.author_id) ??
580
- ({
581
- id: tweet.author_id,
582
- username: `user_${tweet.author_id}`,
583
- name: `user_${tweet.author_id}`,
584
- } as const);
585
- const profile = usersById.has(tweet.author_id)
586
- ? upsertProfileFromXUser(db, author)
587
- : ensureStubProfileForXUser(db, tweet.author_id);
588
- upsertTweet.run(
589
- tweet.id,
590
- accountId,
591
- profile.profile.id,
592
- tweet.text,
593
- tweet.created_at,
594
- Number(tweet.public_metrics?.like_count ?? 0),
595
- countTweetMedia(tweet),
596
- JSON.stringify(toLocalEntities(tweet)),
597
- buildMediaJsonFromIncludes(tweet, payload.includes?.media),
598
- );
599
- upsertTweetAccountEdge(db, {
600
- accountId,
601
- tweetId: tweet.id,
602
- kind: "mention",
603
- source,
604
- seenAt,
605
- rawJson: JSON.stringify(tweet),
606
- });
607
- replaceTweetFts(db, tweet.id, tweet.text);
608
- }
609
- });
610
-
611
- writePayload();
612
- }
613
-
614
- function shouldReturnFilteredLocalPayload({
615
- search,
616
- replyFilter,
617
- }: {
618
- search?: string;
619
- replyFilter?: ReplyFilter;
620
- }) {
621
- return (
622
- Boolean(search?.trim()) ||
623
- replyFilter === "replied" ||
624
- replyFilter === "unreplied"
625
- );
626
- }
627
-
628
- function readLocalXurlCompatiblePayload({
629
- accountId,
630
- search,
631
- replyFilter,
632
- limit,
633
- }: {
634
- accountId?: string;
635
- search?: string;
636
- replyFilter?: ReplyFilter;
637
- limit: number;
638
- }) {
639
- return serializeMentionItemsAsXurlCompatible(
640
- listTimelineItems({
641
- resource: "mentions",
642
- account: accountId,
643
- search,
644
- replyFilter,
645
- limit,
646
- }),
647
- );
648
- }
649
-
650
- function mergeMentionPayloads(
651
- pages: XurlMentionsResponse[],
652
- ): XurlMentionsResponse {
653
- const tweets: XurlMentionData[] = [];
654
- const seenTweetIds = new Set<string>();
655
- const users: XurlMentionUser[] = [];
656
- const seenUserIds = new Set<string>();
657
- const media: XurlMediaItem[] = [];
658
- const seenMediaKeys = new Set<string>();
659
-
660
- for (const page of pages) {
661
- for (const tweet of page.data) {
662
- if (seenTweetIds.has(tweet.id)) {
663
- continue;
664
- }
665
- seenTweetIds.add(tweet.id);
666
- tweets.push(tweet);
667
- }
668
-
669
- for (const user of page.includes?.users ?? []) {
670
- if (seenUserIds.has(user.id)) {
671
- continue;
672
- }
673
- seenUserIds.add(user.id);
674
- users.push(user);
675
- }
676
-
677
- for (const item of page.includes?.media ?? []) {
678
- if (seenMediaKeys.has(item.media_key)) {
679
- continue;
680
- }
681
- seenMediaKeys.add(item.media_key);
682
- media.push(item);
683
- }
684
- }
685
-
686
- const lastMeta = pages.at(-1)?.meta;
687
- const includes = {
688
- ...(users.length > 0 ? { users } : {}),
689
- ...(media.length > 0 ? { media } : {}),
690
- };
691
- return {
692
- data: tweets,
693
- includes: users.length > 0 || media.length > 0 ? includes : undefined,
694
- meta: {
695
- ...lastMeta,
696
- result_count: tweets.length,
697
- page_count: pages.length,
698
- next_token:
699
- typeof lastMeta?.next_token === "string" ? lastMeta.next_token : null,
700
- },
701
- };
702
- }
703
-
704
- function fetchMentionsViaXurlEffect({
705
- resolvedAccount,
706
- limit,
707
- all,
708
- parsedMaxPages,
709
- sinceId,
710
- startPaginationToken,
711
- startTime,
712
- onProgress,
713
- }: {
714
- resolvedAccount: ReturnType<typeof resolveAccount>;
715
- limit: number;
716
- all: boolean;
717
- parsedMaxPages: number | null;
718
- sinceId?: string;
719
- startPaginationToken?: string;
720
- startTime?: string;
721
- onProgress?: (progress: MentionsProgress) => void;
722
- }) {
723
- return Effect.gen(function* () {
724
- const accountUserId =
725
- resolvedAccount.externalUserId ??
726
- (yield* tryPromise(() =>
727
- lookupUsersByHandles([resolvedAccount.username]),
728
- ).pipe(Effect.map((users) => users[0]?.id)));
729
- if (!accountUserId) {
730
- return yield* Effect.fail(
731
- new Error(
732
- `Could not resolve Twitter user id for @${resolvedAccount.username}`,
733
- ),
734
- );
735
- }
736
-
737
- const pages: XurlMentionsResponse[] = [];
738
- let nextToken: string | undefined = startPaginationToken;
739
- let pageCount = 0;
740
- do {
741
- const payload = yield* tryPromise(() =>
742
- listMentionsViaXurl({
743
- maxResults: limit,
744
- username: resolvedAccount.username,
745
- userId: String(accountUserId),
746
- paginationToken: nextToken,
747
- ...(sinceId ? { sinceId } : {}),
748
- ...(startTime ? { startTime } : {}),
749
- }),
750
- );
751
- pages.push(payload);
752
- const metaNextToken =
753
- typeof payload.meta?.next_token === "string"
754
- ? payload.meta.next_token
755
- : undefined;
756
- nextToken = metaNextToken;
757
- pageCount += 1;
758
- const fetched = pages.reduce((sum, item) => sum + item.data.length, 0);
759
- const done =
760
- !all ||
761
- !nextToken ||
762
- (parsedMaxPages !== null && pageCount >= parsedMaxPages);
763
- yield* Effect.sync(() =>
764
- onProgress?.({
765
- source: "xurl",
766
- fetched,
767
- total: parsedMaxPages === null ? undefined : parsedMaxPages * limit,
768
- page: pageCount,
769
- maxPages: parsedMaxPages ?? undefined,
770
- pageSize: limit,
771
- done,
772
- }),
773
- );
774
- } while (
775
- all &&
776
- nextToken &&
777
- (parsedMaxPages === null || pageCount < parsedMaxPages)
778
- );
779
-
780
- return mergeMentionPayloads(pages);
781
- });
782
- }
783
-
784
- function fetchMentionsViaBirdEffect({ limit }: { limit: number }) {
785
- return listMentionsViaBirdEffect({ maxResults: limit });
786
- }
787
-
788
- function isMaxPagesPartial({
789
- payload,
790
- maxPages,
791
- }: {
792
- payload: XurlMentionsResponse;
793
- maxPages: number | null;
794
- }) {
795
- return (
796
- maxPages !== null &&
797
- typeof payload.meta?.next_token === "string" &&
798
- payload.meta.next_token.length > 0
799
- );
800
- }
801
-
802
- export function syncMentionsEffect({
803
- account,
804
- mode,
805
- limit = 20,
806
- maxPages,
807
- refresh = false,
808
- cacheTtlMs,
809
- sinceId,
810
- startTime,
811
- onProgress,
812
- }: SyncMentionsOptions) {
813
- return Effect.gen(function* () {
814
- const parsedMode = yield* trySync(() => parseSyncMode(mode));
815
- const primaryMode: MentionLiveSource =
816
- parsedMode === "auto" ? "xurl" : parsedMode;
817
- const explicitSinceId = sinceId?.trim() || undefined;
818
- const explicitStartTime = startTime?.trim() || undefined;
819
- if (primaryMode === "bird" && (explicitSinceId || explicitStartTime)) {
820
- return yield* Effect.fail(
821
- new Error("bird mode does not support --since-id or --start-time"),
822
- );
823
- }
824
- if (primaryMode === "xurl") {
825
- yield* trySync(() => assertXurlLimit(limit));
826
- } else {
827
- yield* trySync(() => assertBirdLimit(limit));
828
- }
829
- const parsedMaxPages = yield* trySync(() => parseMaxPages(maxPages));
830
- const fetchAll =
831
- primaryMode === "xurl" &&
832
- (parsedMaxPages !== null ||
833
- Boolean(explicitSinceId || explicitStartTime));
834
- const db = yield* trySync(() => getNativeDb());
835
- const resolvedAccount = yield* trySync(() => resolveAccount(db, account));
836
- const cursorShape: MentionScanShape = {
837
- endpoint: "mentions",
838
- mode: primaryMode,
839
- accountId: resolvedAccount.accountId,
840
- pageSize: limit,
841
- boundary: getMentionCursorBoundary({
842
- explicitSinceId,
843
- explicitStartTime,
844
- }),
845
- };
846
- const cursorKey = getMentionCursorKey(cursorShape);
847
- const legacyCursorKeys = getLegacyMentionCursorKeys(cursorShape);
848
- const cursor =
849
- primaryMode === "xurl"
850
- ? yield* trySync(() =>
851
- readMentionCursor({
852
- db,
853
- shape: cursorShape,
854
- cursorKey,
855
- legacyCursorKeys,
856
- }),
857
- )
858
- : undefined;
859
- const startPaginationToken = cursor?.token;
860
- const cursorSinceId =
861
- cursor?.boundary?.kind === "since" ? cursor.boundary.sinceId : undefined;
862
- const cursorStartTime =
863
- cursor?.boundary?.kind === "start"
864
- ? cursor.boundary.startTime
865
- : undefined;
866
- const committedSinceId =
867
- primaryMode === "xurl" &&
868
- cursorShape.boundary.kind === "auto" &&
869
- !startPaginationToken
870
- ? yield* trySync(() =>
871
- readMentionHighWaterId(db, primaryMode, resolvedAccount.accountId),
872
- )
873
- : undefined;
874
- const seededSinceId =
875
- primaryMode === "xurl" &&
876
- !explicitSinceId &&
877
- !explicitStartTime &&
878
- !startPaginationToken
879
- ? (committedSinceId ??
880
- (yield* trySync(() =>
881
- findNewestArchiveMentionId(db, resolvedAccount.accountId),
882
- )))
883
- : undefined;
884
- const resolvedSinceId = startPaginationToken
885
- ? cursorSinceId
886
- : (explicitSinceId ?? seededSinceId);
887
- const resolvedStartTime = startPaginationToken
888
- ? cursorStartTime
889
- : !resolvedSinceId
890
- ? explicitStartTime
891
- : undefined;
892
- const resultShape: MentionScanShape = {
893
- endpoint: "mentions",
894
- mode: primaryMode,
895
- accountId: resolvedAccount.accountId,
896
- pageSize: limit,
897
- boundary: getMentionRequestBoundary({
898
- sinceId: resolvedSinceId,
899
- startTime: resolvedStartTime,
900
- }),
901
- };
902
- const resultCacheKey = getMentionResultCacheKey({
903
- shape: resultShape,
904
- all: fetchAll,
905
- maxPages: parsedMaxPages,
906
- });
907
- const ttlMs = parseCacheTtlMs(cacheTtlMs);
908
- const cached = startPaginationToken
909
- ? null
910
- : yield* trySync(() =>
911
- readSyncCache<XurlMentionsResponse>(resultCacheKey, db),
912
- );
913
- const cachedPaginationToken = getCachedPaginationToken(cached);
914
- const cacheAgeMs = cached
915
- ? Date.now() - new Date(cached.updatedAt).getTime()
916
- : Number.POSITIVE_INFINITY;
917
-
918
- if (
919
- !startPaginationToken &&
920
- !cachedPaginationToken &&
921
- !refresh &&
922
- cached &&
923
- cacheAgeMs <= ttlMs
924
- ) {
925
- yield* trySync(() =>
926
- mergeMentionsIntoLocalStore(
927
- db,
928
- resolvedAccount.accountId,
929
- cached.value,
930
- primaryMode,
931
- ),
932
- );
933
- yield* Effect.sync(() =>
934
- onProgress?.({
935
- source: "cache",
936
- fetched: cached.value.data.length,
937
- total: parsedMaxPages === null ? undefined : parsedMaxPages * limit,
938
- done: true,
939
- }),
940
- );
941
- return {
942
- ok: true,
943
- source: "cache",
944
- kind: "mentions",
945
- accountId: resolvedAccount.accountId,
946
- count: cached.value.data.length,
947
- partial: isMaxPagesPartial({
948
- payload: cached.value,
949
- maxPages: parsedMaxPages,
950
- }),
951
- payload: cached.value,
952
- };
953
- }
954
-
955
- if (
956
- primaryMode === "xurl" &&
957
- !explicitSinceId &&
958
- !explicitStartTime &&
959
- !startPaginationToken &&
960
- !seededSinceId
961
- ) {
962
- console.error(
963
- "No local mention baseline found; syncing mentions from the newest page backwards.",
964
- );
965
- }
966
-
967
- let source: MentionLiveSource = primaryMode;
968
- const canFallbackToBird =
969
- primaryMode === "xurl" &&
970
- parsedMode === "auto" &&
971
- !explicitSinceId &&
972
- !explicitStartTime &&
973
- !startPaginationToken;
974
- const payload =
975
- primaryMode === "bird"
976
- ? yield* fetchMentionsViaBirdEffect({ limit })
977
- : yield* fetchMentionsViaXurlEffect({
978
- resolvedAccount,
979
- limit,
980
- all: fetchAll,
981
- parsedMaxPages,
982
- sinceId: resolvedSinceId,
983
- startPaginationToken,
984
- startTime: resolvedStartTime,
985
- onProgress,
986
- }).pipe(
987
- Effect.catchAll((error) => {
988
- if (!canFallbackToBird) return Effect.fail(error);
989
- source = "bird";
990
- return verifyBirdAccountMatchesEffect(resolvedAccount).pipe(
991
- Effect.flatMap(() => fetchMentionsViaBirdEffect({ limit })),
992
- );
993
- }),
994
- );
995
- if (source === "bird") {
996
- yield* Effect.sync(() =>
997
- onProgress?.({
998
- source: "bird",
999
- fetched: payload.data.length,
1000
- total: limit,
1001
- done: true,
1002
- }),
1003
- );
1004
- }
1005
- yield* trySync(() =>
1006
- mergeMentionsIntoLocalStore(
1007
- db,
1008
- resolvedAccount.accountId,
1009
- payload,
1010
- source,
1011
- ),
1012
- );
1013
- const payloadPaginationToken = getCachedPaginationToken({ value: payload });
1014
- if (source === "xurl") {
1015
- if (payloadPaginationToken) {
1016
- yield* trySync(() => {
1017
- writeSyncCache(
1018
- cursorKey,
1019
- addMentionCursorState(
1020
- payload,
1021
- getMentionRequestBoundary({
1022
- sinceId: resolvedSinceId,
1023
- startTime: resolvedStartTime,
1024
- }),
1025
- maxNumericTweetId(resolvedSinceId, getNewestMentionId(payload)),
1026
- ),
1027
- db,
1028
- );
1029
- deleteSyncCache(resultCacheKey, db);
1030
- deleteSyncCache(
1031
- getMentionResultCacheKey({
1032
- shape: cursorShape,
1033
- all: fetchAll,
1034
- maxPages: parsedMaxPages,
1035
- }),
1036
- db,
1037
- );
1038
- for (const legacyKey of cursor?.legacyKeys ?? []) {
1039
- deleteSyncCache(legacyKey, db);
1040
- }
1041
- });
1042
- } else {
1043
- yield* trySync(() => {
1044
- deleteSyncCache(cursorKey, db);
1045
- for (const legacyKey of legacyCursorKeys) {
1046
- deleteSyncCache(legacyKey, db);
1047
- }
1048
- if (cursorShape.boundary.kind === "auto") {
1049
- writeMentionHighWaterId(
1050
- db,
1051
- source,
1052
- resolvedAccount.accountId,
1053
- maxNumericTweetId(
1054
- resolvedSinceId,
1055
- cursor?.pendingNewestId,
1056
- getNewestMentionId(payload),
1057
- ),
1058
- );
1059
- }
1060
- });
1061
- }
1062
- }
1063
- if (!payloadPaginationToken && !startPaginationToken) {
1064
- const writeCacheKey =
1065
- source === primaryMode
1066
- ? resultCacheKey
1067
- : getMentionResultCacheKey({
1068
- shape: {
1069
- ...resultShape,
1070
- mode: source,
1071
- },
1072
- all: false,
1073
- maxPages: null,
1074
- });
1075
- yield* trySync(() => writeSyncCache(writeCacheKey, payload, db));
1076
- }
1077
-
1078
- return {
1079
- ok: true,
1080
- source,
1081
- kind: "mentions",
1082
- accountId: resolvedAccount.accountId,
1083
- count: payload.data.length,
1084
- partial: isMaxPagesPartial({ payload, maxPages: parsedMaxPages }),
1085
- payload,
1086
- };
1087
- });
1088
- }
1089
-
1090
- export function syncMentions(options: SyncMentionsOptions) {
1091
- return runEffectPromise(syncMentionsEffect(options));
1092
- }
1093
-
1094
- function exportMentionsViaCachedLiveSourceEffect({
1095
- mode,
1096
- account,
1097
- search,
1098
- replyFilter = "all",
1099
- limit = 20,
1100
- all = false,
1101
- maxPages,
1102
- refresh = false,
1103
- cacheTtlMs,
1104
- }: ExportMentionsViaCachedLiveSourceOptions) {
1105
- return Effect.gen(function* () {
1106
- const primaryMode: MentionLiveSource = mode === "auto" ? "xurl" : mode;
1107
- if (primaryMode === "xurl") {
1108
- yield* trySync(() => assertXurlLimit(limit));
1109
- } else {
1110
- yield* trySync(() => assertBirdLimit(limit));
1111
- }
1112
- const parsedMaxPages = yield* trySync(() => parseMaxPages(maxPages));
1113
- const fetchAll = primaryMode === "xurl" && (all || parsedMaxPages !== null);
1114
-
1115
- const db = yield* trySync(() => getNativeDb());
1116
- const resolvedAccount = yield* trySync(() => resolveAccount(db, account));
1117
- const cacheKey = getMentionsFetchModeKey({
1118
- scope: "export",
1119
- mode,
1120
- accountId: resolvedAccount.accountId,
1121
- pageSize: limit,
1122
- all: fetchAll,
1123
- maxPages: parsedMaxPages,
1124
- sinceId: null,
1125
- startTime: null,
1126
- });
1127
- const ttlMs = parseCacheTtlMs(cacheTtlMs);
1128
- const cached = yield* trySync(() =>
1129
- readSyncCache<XurlMentionsResponse>(cacheKey, db),
1130
- );
1131
- const cacheAgeMs = cached
1132
- ? Date.now() - new Date(cached.updatedAt).getTime()
1133
- : Number.POSITIVE_INFINITY;
1134
- const readFilteredOrRaw = (payload: XurlMentionsResponse) => {
1135
- if (
1136
- shouldReturnFilteredLocalPayload({
1137
- search,
1138
- replyFilter,
1139
- })
1140
- ) {
1141
- return readLocalXurlCompatiblePayload({
1142
- accountId: resolvedAccount.accountId,
1143
- search,
1144
- replyFilter,
1145
- limit: fetchAll ? payload.data.length : limit,
1146
- });
1147
- }
1148
- return payload;
1149
- };
1150
-
1151
- if (!refresh && cached && cacheAgeMs <= ttlMs) {
1152
- return yield* trySync(() => readFilteredOrRaw(cached.value));
1153
- }
1154
-
1155
- let source: MentionLiveSource = primaryMode;
1156
- const liveResult = yield* (
1157
- primaryMode === "bird"
1158
- ? fetchMentionsViaBirdEffect({ limit })
1159
- : fetchMentionsViaXurlEffect({
1160
- resolvedAccount,
1161
- limit,
1162
- all: fetchAll,
1163
- parsedMaxPages,
1164
- })
1165
- ).pipe(
1166
- Effect.catchAll((error) => {
1167
- if (mode !== "auto" || fetchAll) return Effect.fail(error);
1168
- source = "bird";
1169
- return verifyBirdAccountMatchesEffect(resolvedAccount).pipe(
1170
- Effect.flatMap(() => fetchMentionsViaBirdEffect({ limit })),
1171
- );
1172
- }),
1173
- Effect.flatMap((payload) =>
1174
- trySync(() => {
1175
- mergeMentionsIntoLocalStore(
1176
- db,
1177
- resolvedAccount.accountId,
1178
- payload,
1179
- source,
1180
- );
1181
- writeSyncCache(cacheKey, payload, db);
1182
- return readFilteredOrRaw(payload);
1183
- }),
1184
- ),
1185
- Effect.map((payload) => ({ ok: true as const, payload })),
1186
- Effect.catchAll((error) => {
1187
- if (!refresh && cached) {
1188
- return Effect.succeed({ ok: false as const });
1189
- }
1190
- return Effect.fail(error);
1191
- }),
1192
- );
1193
-
1194
- if (!liveResult.ok) {
1195
- if (!cached) {
1196
- return yield* Effect.fail(
1197
- new Error("Mention export failed without cache"),
1198
- );
1199
- }
1200
- return yield* trySync(() => readFilteredOrRaw(cached.value));
1201
- }
1202
-
1203
- return liveResult.payload;
1204
- });
1205
- }
1206
-
1207
- export function exportMentionsViaCachedXurl(
1208
- options: Omit<ExportMentionsViaCachedLiveSourceOptions, "mode">,
1209
- ) {
1210
- return runEffectPromise(
1211
- exportMentionsViaCachedLiveSourceEffect({
1212
- ...options,
1213
- mode: "xurl",
1214
- }),
1215
- );
1216
- }
1217
-
1218
- export function exportMentionsViaCachedBird(
1219
- options: Omit<ExportMentionsViaCachedLiveSourceOptions, "mode">,
1220
- ) {
1221
- return runEffectPromise(
1222
- exportMentionsViaCachedLiveSourceEffect({
1223
- ...options,
1224
- mode: "bird",
1225
- }),
1226
- );
1227
- }
1228
-
1229
- export function exportMentionsViaCachedAuto(
1230
- options: Omit<ExportMentionsViaCachedLiveSourceOptions, "mode">,
1231
- ) {
1232
- return runEffectPromise(
1233
- exportMentionsViaCachedLiveSourceEffect({
1234
- ...options,
1235
- mode: "auto",
1236
- }),
1237
- );
1238
- }