birdclaw 0.8.3 → 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 (284) hide show
  1. package/CHANGELOG.md +17 -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 +26 -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/command-context.ts +0 -17
  100. package/src/cli/register-analysis.ts +0 -500
  101. package/src/cli/register-compose.ts +0 -40
  102. package/src/cli/register-graph.ts +0 -132
  103. package/src/cli/register-inbox.ts +0 -41
  104. package/src/cli/register-storage.ts +0 -106
  105. package/src/cli-moderation.ts +0 -210
  106. package/src/cli.ts +0 -1616
  107. package/src/components/AccountSwitcher.tsx +0 -178
  108. package/src/components/AppNav.tsx +0 -118
  109. package/src/components/AvatarChip.tsx +0 -58
  110. package/src/components/AvatarPreload.ts +0 -149
  111. package/src/components/BrandMark.tsx +0 -67
  112. package/src/components/ConversationThread.tsx +0 -131
  113. package/src/components/DmWorkspace.tsx +0 -286
  114. package/src/components/EmbeddedTweetCard.tsx +0 -55
  115. package/src/components/FeedState.tsx +0 -147
  116. package/src/components/FloatingPreview.tsx +0 -382
  117. package/src/components/InboxCard.tsx +0 -152
  118. package/src/components/LinkPreviewCard.tsx +0 -292
  119. package/src/components/MarkdownCitations.tsx +0 -680
  120. package/src/components/MarkdownViewer.tsx +0 -111
  121. package/src/components/ProfileAnalysisClient.ts +0 -191
  122. package/src/components/ProfileAnalysisStream.tsx +0 -259
  123. package/src/components/ProfilePreview.tsx +0 -131
  124. package/src/components/SavedTimelineView.tsx +0 -155
  125. package/src/components/SmartTimestamp.tsx +0 -72
  126. package/src/components/SyncNowButton.tsx +0 -140
  127. package/src/components/ThemeSlider.tsx +0 -80
  128. package/src/components/TimelineCard.tsx +0 -533
  129. package/src/components/TimelineRouteFrame.tsx +0 -186
  130. package/src/components/TweetArticleCard.tsx +0 -66
  131. package/src/components/TweetMediaGrid.tsx +0 -185
  132. package/src/components/TweetRichText.tsx +0 -159
  133. package/src/components/account-selection.ts +0 -64
  134. package/src/components/links-controller.ts +0 -162
  135. package/src/components/links-model.ts +0 -198
  136. package/src/components/network-map-controller.ts +0 -84
  137. package/src/components/network-map-model.ts +0 -255
  138. package/src/components/useTimelineRouteData.ts +0 -193
  139. package/src/lib/account-sync-job.ts +0 -666
  140. package/src/lib/actions-transport.ts +0 -300
  141. package/src/lib/analysis-runtime.ts +0 -238
  142. package/src/lib/api-client.ts +0 -220
  143. package/src/lib/api-contracts.ts +0 -328
  144. package/src/lib/archive-finder.ts +0 -185
  145. package/src/lib/archive-import-plan.ts +0 -102
  146. package/src/lib/archive-import.ts +0 -2695
  147. package/src/lib/authored-live.ts +0 -1027
  148. package/src/lib/avatar-cache.ts +0 -349
  149. package/src/lib/backup.ts +0 -2652
  150. package/src/lib/bird-actions.ts +0 -294
  151. package/src/lib/bird-command.ts +0 -130
  152. package/src/lib/bird.ts +0 -1140
  153. package/src/lib/blocklist.ts +0 -136
  154. package/src/lib/blocks-write.ts +0 -171
  155. package/src/lib/blocks.ts +0 -387
  156. package/src/lib/bookmark-sync-job.ts +0 -536
  157. package/src/lib/config.ts +0 -224
  158. package/src/lib/conversation-surface.ts +0 -205
  159. package/src/lib/data-sources.ts +0 -219
  160. package/src/lib/database-metrics.ts +0 -88
  161. package/src/lib/database-migrations.ts +0 -34
  162. package/src/lib/database-schema.ts +0 -312
  163. package/src/lib/database-writer.ts +0 -69
  164. package/src/lib/db.ts +0 -889
  165. package/src/lib/dm-read-model.ts +0 -533
  166. package/src/lib/dms-live.ts +0 -870
  167. package/src/lib/effect-runtime.ts +0 -45
  168. package/src/lib/follow-graph.ts +0 -1087
  169. package/src/lib/geocoding.ts +0 -296
  170. package/src/lib/http-effect.ts +0 -222
  171. package/src/lib/identity-search-index.ts +0 -369
  172. package/src/lib/import-repository.ts +0 -138
  173. package/src/lib/inbox.ts +0 -242
  174. package/src/lib/link-index.ts +0 -641
  175. package/src/lib/link-insights.ts +0 -860
  176. package/src/lib/link-preview-metadata.ts +0 -754
  177. package/src/lib/live-sync-engine.ts +0 -209
  178. package/src/lib/live-transport-gateway.ts +0 -128
  179. package/src/lib/location.ts +0 -137
  180. package/src/lib/media-fetch.ts +0 -860
  181. package/src/lib/media-includes.ts +0 -165
  182. package/src/lib/mention-threads-live.ts +0 -830
  183. package/src/lib/mentions-export.ts +0 -147
  184. package/src/lib/mentions-live.ts +0 -1114
  185. package/src/lib/moderation-target.ts +0 -227
  186. package/src/lib/moderation-write.ts +0 -131
  187. package/src/lib/mutes-write.ts +0 -171
  188. package/src/lib/mutes.ts +0 -84
  189. package/src/lib/ndjson-stream.ts +0 -106
  190. package/src/lib/network-map.ts +0 -382
  191. package/src/lib/openai-response-runtime.ts +0 -251
  192. package/src/lib/openai.ts +0 -117
  193. package/src/lib/paginated-sync.ts +0 -93
  194. package/src/lib/period-digest.ts +0 -1364
  195. package/src/lib/present.ts +0 -118
  196. package/src/lib/profile-affiliation-hydration.ts +0 -228
  197. package/src/lib/profile-affiliations.ts +0 -262
  198. package/src/lib/profile-analysis.ts +0 -1198
  199. package/src/lib/profile-bio-entities.ts +0 -318
  200. package/src/lib/profile-history.ts +0 -164
  201. package/src/lib/profile-hydration.ts +0 -180
  202. package/src/lib/profile-replies.ts +0 -77
  203. package/src/lib/profile-resolver.ts +0 -650
  204. package/src/lib/queries.ts +0 -6
  205. package/src/lib/query-actions.ts +0 -437
  206. package/src/lib/query-client.tsx +0 -47
  207. package/src/lib/query-read-model-shared.ts +0 -52
  208. package/src/lib/query-read-models.ts +0 -5
  209. package/src/lib/query-resource.ts +0 -41
  210. package/src/lib/query-status.ts +0 -164
  211. package/src/lib/research.ts +0 -652
  212. package/src/lib/runtime-services.ts +0 -20
  213. package/src/lib/search-discussion.ts +0 -812
  214. package/src/lib/seed.ts +0 -613
  215. package/src/lib/server-runtime-services.ts +0 -30
  216. package/src/lib/sqlite.ts +0 -183
  217. package/src/lib/streaming-ingestion.ts +0 -240
  218. package/src/lib/sync-cache.ts +0 -70
  219. package/src/lib/sync-plan.ts +0 -175
  220. package/src/lib/theme-transition.ts +0 -113
  221. package/src/lib/theme.tsx +0 -165
  222. package/src/lib/timeline-collections-live.ts +0 -407
  223. package/src/lib/timeline-live.ts +0 -302
  224. package/src/lib/timeline-read-model.ts +0 -1191
  225. package/src/lib/tweet-account-edges.ts +0 -48
  226. package/src/lib/tweet-lookup.ts +0 -46
  227. package/src/lib/tweet-render.ts +0 -430
  228. package/src/lib/tweet-repository.ts +0 -156
  229. package/src/lib/tweet-search-live.ts +0 -462
  230. package/src/lib/types.ts +0 -723
  231. package/src/lib/ui.ts +0 -529
  232. package/src/lib/url-expansion-store.ts +0 -110
  233. package/src/lib/url-expansion.ts +0 -343
  234. package/src/lib/url-safety.ts +0 -220
  235. package/src/lib/web-sync.ts +0 -533
  236. package/src/lib/whois.ts +0 -1080
  237. package/src/lib/x-profile.ts +0 -365
  238. package/src/lib/x-web.ts +0 -199
  239. package/src/lib/xurl-rate-limits.ts +0 -267
  240. package/src/lib/xurl.ts +0 -1677
  241. package/src/routeTree.gen.ts +0 -723
  242. package/src/router.tsx +0 -20
  243. package/src/routes/__root.tsx +0 -82
  244. package/src/routes/api/action.tsx +0 -147
  245. package/src/routes/api/avatar.tsx +0 -50
  246. package/src/routes/api/blocks.tsx +0 -35
  247. package/src/routes/api/conversation.tsx +0 -45
  248. package/src/routes/api/data-sources.tsx +0 -24
  249. package/src/routes/api/inbox.tsx +0 -43
  250. package/src/routes/api/link-insights.tsx +0 -85
  251. package/src/routes/api/link-preview.tsx +0 -47
  252. package/src/routes/api/network-map.tsx +0 -55
  253. package/src/routes/api/period-digest.tsx +0 -101
  254. package/src/routes/api/profile-analysis.tsx +0 -97
  255. package/src/routes/api/profile-hydrate.tsx +0 -54
  256. package/src/routes/api/query.tsx +0 -121
  257. package/src/routes/api/search-discussion.tsx +0 -113
  258. package/src/routes/api/status.tsx +0 -30
  259. package/src/routes/api/sync.tsx +0 -108
  260. package/src/routes/api/xurl-rate-limits.tsx +0 -24
  261. package/src/routes/blocks.tsx +0 -343
  262. package/src/routes/bookmarks.tsx +0 -18
  263. package/src/routes/data-sources.tsx +0 -249
  264. package/src/routes/discuss.tsx +0 -419
  265. package/src/routes/dms.tsx +0 -415
  266. package/src/routes/inbox.tsx +0 -232
  267. package/src/routes/index.tsx +0 -32
  268. package/src/routes/likes.tsx +0 -18
  269. package/src/routes/links.tsx +0 -631
  270. package/src/routes/mentions.tsx +0 -32
  271. package/src/routes/network-map.tsx +0 -732
  272. package/src/routes/profile-analyze.tsx +0 -112
  273. package/src/routes/profiles.$handle.tsx +0 -228
  274. package/src/routes/rate-limits.tsx +0 -305
  275. package/src/routes/today.tsx +0 -511
  276. package/src/styles.css +0 -257
  277. package/tsconfig.json +0 -29
  278. package/vite.config.ts +0 -29
  279. /package/{public → dist/client}/birdclaw-mark.png +0 -0
  280. /package/{public → dist/client}/favicon.ico +0 -0
  281. /package/{public → dist/client}/logo192.png +0 -0
  282. /package/{public → dist/client}/logo512.png +0 -0
  283. /package/{public → dist/client}/manifest.json +0 -0
  284. /package/{public → dist/client}/robots.txt +0 -0
@@ -1,77 +0,0 @@
1
- import { Effect } from "effect";
2
-
3
- import { runEffectPromise, tryPromise } from "./effect-runtime";
4
- import { resolveProfile } from "./moderation-target";
5
- import type { ProfileRepliesResponse, XurlReferencedTweet } from "./types";
6
- import { listUserTweets } from "./xurl";
7
-
8
- function getReplyTargetId(references?: XurlReferencedTweet[]) {
9
- return references?.find((item) => item.type === "replied_to")?.id;
10
- }
11
-
12
- function getScanSize(limit: number) {
13
- return Math.min(Math.max(limit * 3, 20), 100);
14
- }
15
-
16
- export function inspectProfileReplies(
17
- query: string,
18
- { limit = 12 }: { limit?: number } = {},
19
- ): Promise<ProfileRepliesResponse> {
20
- return runEffectPromise(inspectProfileRepliesEffect(query, { limit }));
21
- }
22
-
23
- export function inspectProfileRepliesEffect(
24
- query: string,
25
- { limit = 12 }: { limit?: number } = {},
26
- ): Effect.Effect<ProfileRepliesResponse, unknown> {
27
- return Effect.gen(function* () {
28
- const resolved = yield* tryPromise(() => resolveProfile(query));
29
- const externalUserId = resolved.externalUserId;
30
- if (!externalUserId) {
31
- return yield* Effect.fail(
32
- new Error(`Profile has no external Twitter user id: ${query}`),
33
- );
34
- }
35
-
36
- const timeline = yield* tryPromise(() =>
37
- listUserTweets(externalUserId, {
38
- maxResults: getScanSize(limit),
39
- excludeRetweets: true,
40
- }),
41
- );
42
- const items = timeline.items
43
- .map((tweet) => {
44
- const replyToTweetId = getReplyTargetId(tweet.referenced_tweets);
45
- if (!replyToTweetId) {
46
- return null;
47
- }
48
-
49
- return {
50
- id: tweet.id,
51
- text: tweet.text,
52
- createdAt: tweet.created_at,
53
- conversationId: tweet.conversation_id,
54
- replyToTweetId,
55
- likeCount: Number(tweet.public_metrics?.like_count ?? 0),
56
- replyCount: Number(tweet.public_metrics?.reply_count ?? 0),
57
- retweetCount: Number(tweet.public_metrics?.retweet_count ?? 0),
58
- quoteCount: Number(tweet.public_metrics?.quote_count ?? 0),
59
- bookmarkCount: Number(tweet.public_metrics?.bookmark_count ?? 0),
60
- impressionCount: Number(tweet.public_metrics?.impression_count ?? 0),
61
- };
62
- })
63
- .filter((item): item is NonNullable<typeof item> => item !== null)
64
- .slice(0, limit);
65
-
66
- return {
67
- profile: resolved.profile,
68
- externalUserId,
69
- items,
70
- meta: {
71
- scannedCount: timeline.items.length,
72
- returnedCount: items.length,
73
- nextToken: timeline.nextToken,
74
- },
75
- };
76
- });
77
- }
@@ -1,650 +0,0 @@
1
- import { Effect } from "effect";
2
-
3
- import { getNativeDb } from "./db";
4
- import {
5
- lookupProfileViaBirdEffect,
6
- lookupProfilesViaBirdEffect,
7
- } from "./bird";
8
- import { runEffectPromise, tryPromise } from "./effect-runtime";
9
- import { readSyncCache, writeSyncCache } from "./sync-cache";
10
- import {
11
- hydrateProfileAffiliationOrganizationsEffect,
12
- type ProfileAffiliationHydrationResult,
13
- } from "./profile-affiliation-hydration";
14
- import type { ProfileRecord, XurlMentionUser } from "./types";
15
- import { getExternalUserId, upsertProfileFromXUser } from "./x-profile";
16
- import { lookupUsersByHandles, lookupUsersByIds } from "./xurl";
17
-
18
- const PROFILE_CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
19
- const PROFILE_NEGATIVE_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
20
-
21
- type ProfileLookupStatus = "hit" | "miss" | "error";
22
- type ProfileLookupSource = "local" | "cache" | "bird" | "xurl";
23
-
24
- interface CachedProfileLookup {
25
- status: ProfileLookupStatus;
26
- source: Exclude<ProfileLookupSource, "local" | "cache">;
27
- user?: XurlMentionUser;
28
- error?: string;
29
- }
30
-
31
- function toError(error: unknown) {
32
- return error instanceof Error ? error : new Error(String(error));
33
- }
34
-
35
- function trySync<T>(try_: () => T) {
36
- return Effect.try({
37
- try: try_,
38
- catch: toError,
39
- });
40
- }
41
-
42
- export interface ResolveProfilesOptions {
43
- refresh?: boolean;
44
- maxAgeMs?: number;
45
- negativeMaxAgeMs?: number;
46
- xurlFallback?: boolean;
47
- }
48
-
49
- export interface ProfileResolveResult {
50
- profileId: string;
51
- externalUserId: string | null;
52
- status: ProfileLookupStatus;
53
- source: ProfileLookupSource | "negative-cache";
54
- profile?: ProfileRecord;
55
- affiliationHydration?: ProfileAffiliationHydrationResult;
56
- error?: string;
57
- }
58
-
59
- export interface HandleProfileResolveResult {
60
- handle: string;
61
- status: ProfileLookupStatus;
62
- source: Exclude<ProfileLookupSource, "local">;
63
- profile?: ProfileRecord;
64
- error?: string;
65
- }
66
-
67
- function toProfile(row: Record<string, unknown>): ProfileRecord {
68
- const followingCount = Number(row.following_count ?? 0);
69
- let entities: Record<string, unknown> | undefined;
70
- if (typeof row.entities_json === "string" && row.entities_json.length > 0) {
71
- try {
72
- const parsed = JSON.parse(row.entities_json) as unknown;
73
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
74
- entities = parsed as Record<string, unknown>;
75
- }
76
- } catch {
77
- entities = undefined;
78
- }
79
- }
80
- return {
81
- id: String(row.id),
82
- handle: String(row.handle),
83
- displayName: String(row.display_name),
84
- bio: String(row.bio),
85
- followersCount: Number(row.followers_count),
86
- ...(Number.isFinite(followingCount) ? { followingCount } : {}),
87
- avatarHue: Number(row.avatar_hue),
88
- avatarUrl:
89
- typeof row.avatar_url === "string" ? String(row.avatar_url) : undefined,
90
- ...(typeof row.location === "string" && row.location.length > 0
91
- ? { location: row.location }
92
- : {}),
93
- ...(typeof row.url === "string" && row.url.length > 0
94
- ? { url: row.url }
95
- : {}),
96
- ...(typeof row.verified_type === "string" && row.verified_type.length > 0
97
- ? { verifiedType: row.verified_type }
98
- : {}),
99
- ...(entities ? { entities } : {}),
100
- createdAt: String(row.created_at),
101
- };
102
- }
103
-
104
- function getProfile(profileId: string) {
105
- const row = getNativeDb()
106
- .prepare(
107
- `
108
- select id, handle, display_name, bio, followers_count, following_count,
109
- avatar_hue, avatar_url, location, url, verified_type, entities_json, created_at
110
- from profiles
111
- where id = ?
112
- `,
113
- )
114
- .get(profileId) as Record<string, unknown> | undefined;
115
-
116
- return row ? toProfile(row) : null;
117
- }
118
-
119
- function isPlaceholderProfile(profile: ProfileRecord) {
120
- const externalUserId = getExternalUserId(profile.id);
121
- if (!externalUserId) {
122
- return false;
123
- }
124
- return (
125
- profile.handle === `id${externalUserId}` ||
126
- profile.handle === `user_${externalUserId}` ||
127
- profile.displayName === `id${externalUserId}` ||
128
- profile.displayName === `user_${externalUserId}` ||
129
- profile.bio === `Imported from archive user ${externalUserId}` ||
130
- (profile.followersCount === 0 &&
131
- profile.bio.startsWith("Imported from archive user "))
132
- );
133
- }
134
-
135
- function isFresh(updatedAt: string, maxAgeMs: number) {
136
- return Date.now() - new Date(updatedAt).getTime() <= maxAgeMs;
137
- }
138
-
139
- function cacheKeyForUserId(externalUserId: string) {
140
- return `profile:lookup:user-id:${externalUserId}`;
141
- }
142
-
143
- function writeProfileLookupCache(
144
- externalUserId: string,
145
- value: CachedProfileLookup,
146
- ) {
147
- writeSyncCache(cacheKeyForUserId(externalUserId), value);
148
- }
149
-
150
- function updateConversationTitles(profile: ProfileRecord, db = getNativeDb()) {
151
- db.prepare(
152
- `
153
- update dm_conversations
154
- set title = ?
155
- where participant_profile_id = ?
156
- `,
157
- ).run(profile.displayName || profile.handle, profile.id);
158
- }
159
-
160
- function lookupViaXurlEffect(externalUserId: string) {
161
- return Effect.gen(function* () {
162
- const [user] = yield* tryPromise(() => lookupUsersByIds([externalUserId]));
163
- return user ?? null;
164
- });
165
- }
166
-
167
- function normalizeHandle(value: string) {
168
- return value.trim().replace(/^@/, "").toLowerCase();
169
- }
170
-
171
- function fetchProfileUserEffect(
172
- externalUserId: string,
173
- xurlFallback: boolean,
174
- ): Effect.Effect<CachedProfileLookup, never> {
175
- return Effect.gen(function* () {
176
- const birdResult = yield* lookupProfileViaBirdEffect(externalUserId).pipe(
177
- Effect.map((user) => ({ ok: true as const, user })),
178
- Effect.catchAll((error) => Effect.succeed({ ok: false as const, error })),
179
- );
180
- if (birdResult.ok) {
181
- const birdUser = birdResult.user;
182
- if (birdUser) {
183
- return { status: "hit", source: "bird", user: birdUser };
184
- }
185
- } else if (!xurlFallback) {
186
- return {
187
- status: "error",
188
- source: "bird",
189
- error:
190
- birdResult.error instanceof Error
191
- ? birdResult.error.message
192
- : String(birdResult.error),
193
- };
194
- }
195
-
196
- if (!xurlFallback) {
197
- return { status: "miss", source: "bird" };
198
- }
199
-
200
- const xurlResult = yield* lookupViaXurlEffect(externalUserId).pipe(
201
- Effect.map((user) => ({ ok: true as const, user })),
202
- Effect.catchAll((error) => Effect.succeed({ ok: false as const, error })),
203
- );
204
- if (xurlResult.ok) {
205
- const xurlUser = xurlResult.user;
206
- return xurlUser
207
- ? { status: "hit", source: "xurl", user: xurlUser }
208
- : { status: "miss", source: "xurl" };
209
- }
210
- return {
211
- status: "error",
212
- source: "xurl",
213
- error:
214
- xurlResult.error instanceof Error
215
- ? xurlResult.error.message
216
- : String(xurlResult.error),
217
- };
218
- });
219
- }
220
-
221
- function fetchProfileUsersEffect(
222
- externalUserIds: string[],
223
- xurlFallback: boolean,
224
- ) {
225
- return Effect.gen(function* () {
226
- const uniqueIds = Array.from(new Set(externalUserIds));
227
- const results = new Map<string, CachedProfileLookup>();
228
- let unresolved = uniqueIds;
229
-
230
- const birdResult = yield* lookupProfilesViaBirdEffect(uniqueIds).pipe(
231
- Effect.map((items) => ({ ok: true as const, items })),
232
- Effect.catchAll((error) => Effect.succeed({ ok: false as const, error })),
233
- );
234
- if (birdResult.ok) {
235
- const birdResults = birdResult.items;
236
- for (const result of birdResults) {
237
- const externalUserId = result.target;
238
- if (result.user) {
239
- results.set(externalUserId, {
240
- status: "hit",
241
- source: "bird",
242
- user: result.user,
243
- });
244
- } else if (result.error && !xurlFallback) {
245
- results.set(externalUserId, {
246
- status: "error",
247
- source: "bird",
248
- error: result.error,
249
- });
250
- }
251
- }
252
- unresolved = uniqueIds.filter((id) => !results.has(id));
253
- } else if (!xurlFallback) {
254
- for (const externalUserId of uniqueIds) {
255
- results.set(externalUserId, {
256
- status: "error",
257
- source: "bird",
258
- error:
259
- birdResult.error instanceof Error
260
- ? birdResult.error.message
261
- : String(birdResult.error),
262
- });
263
- }
264
- return results;
265
- }
266
-
267
- if (unresolved.length === 0) {
268
- return results;
269
- }
270
- if (!xurlFallback) {
271
- for (const externalUserId of unresolved) {
272
- results.set(externalUserId, { status: "miss", source: "bird" });
273
- }
274
- return results;
275
- }
276
-
277
- const xurlResult = yield* tryPromise(() =>
278
- lookupUsersByIds(unresolved),
279
- ).pipe(
280
- Effect.map((users) => ({ ok: true as const, users })),
281
- Effect.catchAll((error) => Effect.succeed({ ok: false as const, error })),
282
- );
283
- if (xurlResult.ok) {
284
- const xurlUsers = xurlResult.users;
285
- const usersById = new Map(
286
- xurlUsers.map((user) => [String(user.id), user]),
287
- );
288
- for (const externalUserId of unresolved) {
289
- const user = usersById.get(externalUserId);
290
- results.set(
291
- externalUserId,
292
- user
293
- ? { status: "hit", source: "xurl", user }
294
- : { status: "miss", source: "xurl" },
295
- );
296
- }
297
- } else {
298
- for (const externalUserId of unresolved) {
299
- results.set(externalUserId, {
300
- status: "error",
301
- source: "xurl",
302
- error:
303
- xurlResult.error instanceof Error
304
- ? xurlResult.error.message
305
- : String(xurlResult.error),
306
- });
307
- }
308
- }
309
-
310
- return results;
311
- });
312
- }
313
-
314
- export function resolveProfilesForIdsEffect(
315
- profileIds: string[],
316
- options: ResolveProfilesOptions = {},
317
- ): Effect.Effect<ProfileResolveResult[], unknown> {
318
- return Effect.gen(function* () {
319
- const db = yield* trySync(() => getNativeDb());
320
- const maxAgeMs = options.maxAgeMs ?? PROFILE_CACHE_TTL_MS;
321
- const negativeMaxAgeMs =
322
- options.negativeMaxAgeMs ?? PROFILE_NEGATIVE_CACHE_TTL_MS;
323
- const xurlFallback = options.xurlFallback ?? true;
324
- const ordered: Array<
325
- | { kind: "ready"; result: ProfileResolveResult }
326
- | { kind: "pending"; profileId: string; externalUserId: string }
327
- > = [];
328
-
329
- for (const profileId of Array.from(new Set(profileIds))) {
330
- const externalUserId = getExternalUserId(profileId);
331
- if (!externalUserId) {
332
- ordered.push({
333
- kind: "ready",
334
- result: {
335
- profileId,
336
- externalUserId: null,
337
- status: "miss",
338
- source: "local",
339
- },
340
- });
341
- continue;
342
- }
343
-
344
- const localProfile = yield* trySync(() => getProfile(profileId));
345
- if (
346
- localProfile &&
347
- !options.refresh &&
348
- !isPlaceholderProfile(localProfile)
349
- ) {
350
- ordered.push({
351
- kind: "ready",
352
- result: {
353
- profileId,
354
- externalUserId,
355
- status: "hit",
356
- source: "local",
357
- profile: localProfile,
358
- },
359
- });
360
- continue;
361
- }
362
-
363
- const cached = yield* trySync(() =>
364
- readSyncCache<CachedProfileLookup>(cacheKeyForUserId(externalUserId)),
365
- );
366
- if (cached && !options.refresh) {
367
- const maxAge =
368
- cached.value.status === "hit" ? maxAgeMs : negativeMaxAgeMs;
369
- if (isFresh(cached.updatedAt, maxAge)) {
370
- if (cached.value.status === "hit" && cached.value.user) {
371
- const resolved = yield* trySync(() => {
372
- const resolved = upsertProfileFromXUser(db, cached.value.user!);
373
- updateConversationTitles(resolved.profile, db);
374
- return resolved;
375
- });
376
- ordered.push({
377
- kind: "ready",
378
- result: {
379
- profileId: resolved.profile.id,
380
- externalUserId,
381
- status: "hit",
382
- source: "cache",
383
- profile: resolved.profile,
384
- },
385
- });
386
- continue;
387
- }
388
- ordered.push({
389
- kind: "ready",
390
- result: {
391
- profileId,
392
- externalUserId,
393
- status: cached.value.status,
394
- source: "negative-cache",
395
- error: cached.value.error,
396
- },
397
- });
398
- continue;
399
- }
400
- }
401
-
402
- ordered.push({ kind: "pending", profileId, externalUserId });
403
- }
404
-
405
- const pendingExternalIds = ordered.flatMap((item) =>
406
- item.kind === "pending" ? [item.externalUserId] : [],
407
- );
408
- const fetchedByExternalId =
409
- pendingExternalIds.length > 1
410
- ? yield* fetchProfileUsersEffect(pendingExternalIds, xurlFallback)
411
- : new Map<string, CachedProfileLookup>();
412
-
413
- const results: ProfileResolveResult[] = [];
414
- for (const item of ordered) {
415
- if (item.kind === "ready") {
416
- results.push(item.result);
417
- continue;
418
- }
419
- const fetched =
420
- fetchedByExternalId.get(item.externalUserId) ??
421
- (yield* fetchProfileUserEffect(item.externalUserId, xurlFallback));
422
- yield* trySync(() =>
423
- writeProfileLookupCache(item.externalUserId, fetched),
424
- );
425
- if (fetched.status === "hit" && fetched.user) {
426
- const resolved = yield* trySync(() =>
427
- upsertProfileFromXUser(db, fetched.user!),
428
- );
429
- const affiliationHydration =
430
- yield* hydrateProfileAffiliationOrganizationsEffect(
431
- db,
432
- resolved.profile.id,
433
- );
434
- yield* trySync(() => updateConversationTitles(resolved.profile, db));
435
- results.push({
436
- profileId: resolved.profile.id,
437
- externalUserId: item.externalUserId,
438
- status: "hit",
439
- source: fetched.source,
440
- profile: resolved.profile,
441
- ...(affiliationHydration.checked > 0 ? { affiliationHydration } : {}),
442
- });
443
- continue;
444
- }
445
- results.push({
446
- profileId: item.profileId,
447
- externalUserId: item.externalUserId,
448
- status: fetched.status,
449
- source: fetched.source,
450
- error: fetched.error,
451
- });
452
- }
453
-
454
- return results;
455
- });
456
- }
457
-
458
- export function resolveProfilesForIds(
459
- profileIds: string[],
460
- options: ResolveProfilesOptions = {},
461
- ): Promise<ProfileResolveResult[]> {
462
- return runEffectPromise(resolveProfilesForIdsEffect(profileIds, options));
463
- }
464
-
465
- export function resolveProfilesForHandlesEffect(
466
- handles: string[],
467
- options: Pick<ResolveProfilesOptions, "xurlFallback"> = {},
468
- ): Effect.Effect<HandleProfileResolveResult[], unknown> {
469
- return Effect.gen(function* () {
470
- const db = yield* trySync(() => getNativeDb());
471
- const xurlFallback = options.xurlFallback ?? true;
472
- const targets = Array.from(
473
- new Set(
474
- handles.map(normalizeHandle).filter((handle) => handle.length > 0),
475
- ),
476
- );
477
- if (targets.length === 0) {
478
- return [];
479
- }
480
-
481
- const results = new Map<string, HandleProfileResolveResult>();
482
- let unresolved = targets;
483
-
484
- const birdResult = yield* lookupProfilesViaBirdEffect(targets).pipe(
485
- Effect.map((items) => ({ ok: true as const, items })),
486
- Effect.catchAll((error) => Effect.succeed({ ok: false as const, error })),
487
- );
488
- if (birdResult.ok) {
489
- const birdResults = birdResult.items;
490
- for (const item of birdResults) {
491
- const handle = normalizeHandle(item.target);
492
- if (item.user) {
493
- const resolved = yield* trySync(() => {
494
- const resolved = upsertProfileFromXUser(db, item.user!);
495
- updateConversationTitles(resolved.profile, db);
496
- return resolved;
497
- });
498
- results.set(handle, {
499
- handle,
500
- status: "hit",
501
- source: "bird",
502
- profile: resolved.profile,
503
- });
504
- } else if (item.error && !xurlFallback) {
505
- results.set(handle, {
506
- handle,
507
- status: "error",
508
- source: "bird",
509
- error: item.error,
510
- });
511
- }
512
- }
513
- unresolved = targets.filter((handle) => !results.has(handle));
514
- } else if (!xurlFallback) {
515
- for (const handle of targets) {
516
- results.set(handle, {
517
- handle,
518
- status: "error",
519
- source: "bird",
520
- error:
521
- birdResult.error instanceof Error
522
- ? birdResult.error.message
523
- : String(birdResult.error),
524
- });
525
- }
526
- unresolved = [];
527
- }
528
-
529
- if (unresolved.length > 0 && xurlFallback) {
530
- const xurlResult = yield* tryPromise(() =>
531
- lookupUsersByHandles(unresolved),
532
- ).pipe(
533
- Effect.map((users) => ({ ok: true as const, users })),
534
- Effect.catchAll((error) =>
535
- Effect.succeed({ ok: false as const, error }),
536
- ),
537
- );
538
- if (xurlResult.ok) {
539
- const users = xurlResult.users;
540
- const usersByHandle = new Map(
541
- users.map((user) => [
542
- normalizeHandle(String(user.username ?? "")),
543
- user,
544
- ]),
545
- );
546
- for (const handle of unresolved) {
547
- const user = usersByHandle.get(handle);
548
- if (user) {
549
- const resolved = yield* trySync(() => {
550
- const resolved = upsertProfileFromXUser(db, user);
551
- updateConversationTitles(resolved.profile, db);
552
- return resolved;
553
- });
554
- results.set(handle, {
555
- handle,
556
- status: "hit",
557
- source: "xurl",
558
- profile: resolved.profile,
559
- });
560
- } else {
561
- results.set(handle, {
562
- handle,
563
- status: "miss",
564
- source: "xurl",
565
- });
566
- }
567
- }
568
- } else {
569
- for (const handle of unresolved) {
570
- results.set(handle, {
571
- handle,
572
- status: "error",
573
- source: "xurl",
574
- error:
575
- xurlResult.error instanceof Error
576
- ? xurlResult.error.message
577
- : String(xurlResult.error),
578
- });
579
- }
580
- }
581
- }
582
-
583
- return targets.map(
584
- (handle) =>
585
- results.get(handle) ?? {
586
- handle,
587
- status: "miss",
588
- source: "bird",
589
- },
590
- );
591
- });
592
- }
593
-
594
- export function resolveProfilesForHandles(
595
- handles: string[],
596
- options: Pick<ResolveProfilesOptions, "xurlFallback"> = {},
597
- ): Promise<HandleProfileResolveResult[]> {
598
- return runEffectPromise(resolveProfilesForHandlesEffect(handles, options));
599
- }
600
-
601
- export function resolvePlaceholderProfilesEffect(
602
- options: ResolveProfilesOptions & { limit?: number } = {},
603
- ) {
604
- return Effect.gen(function* () {
605
- const db = yield* trySync(() => getNativeDb());
606
- const rows = yield* trySync(
607
- () =>
608
- db
609
- .prepare(
610
- `
611
- select id
612
- from profiles
613
- where id like 'profile_user_%'
614
- and (
615
- followers_count = 0
616
- or bio like 'Imported from archive user %'
617
- or handle like 'id%'
618
- or handle like 'user_%'
619
- )
620
- order by id asc
621
- limit ?
622
- `,
623
- )
624
- .all(options.limit ?? 500) as Array<{ id: string }>,
625
- );
626
-
627
- const results = yield* resolveProfilesForIdsEffect(
628
- rows.map((row) => row.id),
629
- options,
630
- );
631
- return {
632
- ok: true,
633
- requestedProfiles: rows.length,
634
- hydratedProfiles: results.filter((result) => result.status === "hit")
635
- .length,
636
- results,
637
- };
638
- });
639
- }
640
-
641
- export function resolvePlaceholderProfiles(
642
- options: ResolveProfilesOptions & { limit?: number } = {},
643
- ) {
644
- return runEffectPromise(resolvePlaceholderProfilesEffect(options));
645
- }
646
-
647
- export const __test__ = {
648
- isPlaceholderProfile,
649
- cacheKeyForUserId,
650
- };