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,1072 +0,0 @@
1
- import type { Database } from "./sqlite";
2
- import { Effect } from "effect";
3
- import { getNativeDb } from "./db";
4
- import { runEffectPromise, tryPromise } from "./effect-runtime";
5
- import { readSyncCache, writeSyncCache } from "./sync-cache";
6
- import { tweetEntitiesFromXurl } from "./tweet-render";
7
- import type {
8
- TweetEntities,
9
- TweetMediaItem,
10
- XurlMedia,
11
- XurlMentionData,
12
- XurlMentionUser,
13
- XurlTweetData,
14
- XurlTweetIncludes,
15
- XurlUserTweet,
16
- XurlUserTweetsResponse,
17
- } from "./types";
18
- import { upsertTweetAccountEdge } from "./tweet-account-edges";
19
- import {
20
- buildExternalProfileId,
21
- ensureStubProfileForXUser,
22
- upsertProfileFromXUser,
23
- } from "./x-profile";
24
- import {
25
- getTransportStatus,
26
- listUserTweets,
27
- lookupAuthenticatedUser,
28
- } from "./xurl";
29
-
30
- export type AuthoredSyncMode = "xurl";
31
-
32
- export interface SyncAuthoredTweetsOptions {
33
- account?: string;
34
- mode?: AuthoredSyncMode;
35
- limit?: number;
36
- maxPages?: number;
37
- sinceId?: string;
38
- untilId?: string;
39
- }
40
-
41
- export class AuthoredSyncError extends Error {
42
- constructor(
43
- message: string,
44
- public readonly exitCode: number,
45
- ) {
46
- super(message);
47
- this.name = "AuthoredSyncError";
48
- }
49
- }
50
-
51
- // sync_cache JSON shapes:
52
- // { state: "committed", sinceId }
53
- // { state: "pending-forward", sinceId, token, pendingNewestId }
54
- // { state: "pending-until", sinceId, token, untilId, requestedSinceId }
55
- type AuthoredCursorState =
56
- | { state: "committed"; sinceId: string | null }
57
- | {
58
- state: "pending-forward";
59
- sinceId: string | null;
60
- token: string;
61
- pendingNewestId: string | null;
62
- }
63
- | {
64
- state: "pending-until";
65
- sinceId: string | null;
66
- token: string;
67
- untilId: string;
68
- requestedSinceId?: string | null;
69
- };
70
-
71
- interface AuthoredPayload {
72
- data: XurlMentionData[];
73
- includes?: XurlTweetIncludes;
74
- meta: {
75
- result_count: number;
76
- page_count: number;
77
- next_token: string | null;
78
- newest_id?: string;
79
- oldest_id?: string;
80
- };
81
- }
82
-
83
- const MIN_XURL_LIMIT = 5;
84
- const MAX_XURL_LIMIT = 100;
85
- const DEFAULT_LIMIT = 100;
86
- const AUTHORED_CURSOR_PREFIX = "authored:xurl";
87
- const AUTHORED_TWEET_FIELDS = [
88
- "author_id",
89
- "created_at",
90
- "conversation_id",
91
- "entities",
92
- "attachments",
93
- "public_metrics",
94
- "referenced_tweets",
95
- ];
96
- const AUTHORED_EXPANSIONS = [
97
- "author_id",
98
- "referenced_tweets.id",
99
- "referenced_tweets.id.author_id",
100
- "attachments.media_keys",
101
- ];
102
- const AUTHORED_USER_FIELDS = [
103
- "description",
104
- "entities",
105
- "location",
106
- "public_metrics",
107
- "profile_image_url",
108
- "url",
109
- "created_at",
110
- "verified",
111
- "verified_type",
112
- ];
113
- const AUTHORED_MEDIA_FIELDS = [
114
- "media_key",
115
- "type",
116
- "url",
117
- "preview_image_url",
118
- "width",
119
- "height",
120
- "alt_text",
121
- ];
122
-
123
- function toError(error: unknown) {
124
- return error instanceof Error ? error : new Error(String(error));
125
- }
126
-
127
- function trySync<T>(try_: () => T) {
128
- return Effect.try({
129
- try: try_,
130
- catch: toError,
131
- });
132
- }
133
-
134
- function assertXurlLimit(limit: number) {
135
- if (
136
- !Number.isFinite(limit) ||
137
- limit < MIN_XURL_LIMIT ||
138
- limit > MAX_XURL_LIMIT
139
- ) {
140
- throw new Error("xurl mode requires --limit between 5 and 100");
141
- }
142
- return Math.floor(limit);
143
- }
144
-
145
- function parseMaxPages(value?: number) {
146
- if (value === undefined) {
147
- return null;
148
- }
149
- if (!Number.isFinite(value) || value < 1) {
150
- throw new Error("--max-pages must be at least 1");
151
- }
152
- return Math.floor(value);
153
- }
154
-
155
- function cursorKey(accountId: string) {
156
- return `${AUTHORED_CURSOR_PREFIX}:${accountId}:cursor`;
157
- }
158
-
159
- function normalizeCursor(value: unknown): AuthoredCursorState {
160
- if (!value || typeof value !== "object") {
161
- return { state: "committed", sinceId: null };
162
- }
163
- const record = value as Record<string, unknown>;
164
- const sinceId = typeof record.sinceId === "string" ? record.sinceId : null;
165
- if (record.state === "pending-forward" && typeof record.token === "string") {
166
- return {
167
- state: "pending-forward",
168
- sinceId,
169
- token: record.token,
170
- pendingNewestId:
171
- typeof record.pendingNewestId === "string"
172
- ? record.pendingNewestId
173
- : null,
174
- };
175
- }
176
- if (
177
- record.state === "pending-until" &&
178
- typeof record.token === "string" &&
179
- typeof record.untilId === "string"
180
- ) {
181
- const requestedSinceId =
182
- "requestedSinceId" in record
183
- ? typeof record.requestedSinceId === "string"
184
- ? record.requestedSinceId
185
- : null
186
- : undefined;
187
- return {
188
- state: "pending-until",
189
- sinceId,
190
- token: record.token,
191
- untilId: record.untilId,
192
- ...(requestedSinceId !== undefined ? { requestedSinceId } : {}),
193
- };
194
- }
195
- const legacyToken =
196
- typeof record.paginationToken === "string" ? record.paginationToken : null;
197
- if (legacyToken) {
198
- return {
199
- state: "pending-forward",
200
- sinceId,
201
- token: legacyToken,
202
- pendingNewestId:
203
- typeof record.pendingNewestId === "string"
204
- ? record.pendingNewestId
205
- : null,
206
- };
207
- }
208
- return { state: "committed", sinceId };
209
- }
210
-
211
- function readAuthoredCursor(db: Database, accountId: string) {
212
- return normalizeCursor(readSyncCache(cursorKey(accountId), db)?.value);
213
- }
214
-
215
- function writeAuthoredCursor(
216
- db: Database,
217
- accountId: string,
218
- state: AuthoredCursorState,
219
- ) {
220
- writeSyncCache(cursorKey(accountId), state, db);
221
- }
222
-
223
- function writeCommittedCursor(
224
- db: Database,
225
- accountId: string,
226
- sinceId: string | null,
227
- ) {
228
- writeAuthoredCursor(db, accountId, { state: "committed", sinceId });
229
- }
230
-
231
- function writePendingForwardCursor(
232
- db: Database,
233
- accountId: string,
234
- {
235
- sinceId,
236
- token,
237
- pendingNewestId,
238
- }: {
239
- sinceId: string | null;
240
- token: string;
241
- pendingNewestId: string | null;
242
- },
243
- ) {
244
- writeAuthoredCursor(db, accountId, {
245
- state: "pending-forward",
246
- sinceId,
247
- token,
248
- pendingNewestId,
249
- });
250
- }
251
-
252
- function writePendingUntilCursor(
253
- db: Database,
254
- accountId: string,
255
- {
256
- sinceId,
257
- token,
258
- untilId,
259
- requestedSinceId,
260
- }: {
261
- sinceId: string | null;
262
- token: string;
263
- untilId: string;
264
- requestedSinceId: string | null;
265
- },
266
- ) {
267
- writeAuthoredCursor(db, accountId, {
268
- state: "pending-until",
269
- sinceId,
270
- token,
271
- untilId,
272
- requestedSinceId,
273
- });
274
- }
275
-
276
- // Archive seeds stay archive-only because backups can contain live edges without sync_cache.
277
- function findArchiveAuthoredSinceSeed(db: Database, accountId: string) {
278
- const row = db
279
- .prepare(
280
- `
281
- select t.id
282
- from tweets t
283
- join accounts a on a.id = ?
284
- where t.id glob '[0-9]*'
285
- and t.id not glob '*[^0-9]*'
286
- and (
287
- exists (
288
- select 1
289
- from tweet_account_edges e
290
- where e.account_id = ?
291
- and e.tweet_id = t.id
292
- and e.kind = 'authored'
293
- and e.source = 'archive'
294
- )
295
- or (
296
- t.kind = 'home'
297
- and exists (
298
- select 1
299
- from tweet_account_edges e2
300
- where e2.account_id = ?
301
- and e2.tweet_id = t.id
302
- and e2.source = 'archive'
303
- and e2.kind = 'home'
304
- )
305
- and t.author_profile_id in ('profile_me', 'profile_user_' || a.external_user_id)
306
- )
307
- )
308
- order by length(t.id) desc, t.id desc
309
- limit 1
310
- `,
311
- )
312
- .get(accountId, accountId, accountId) as { id: string } | undefined;
313
- return row?.id ?? null;
314
- }
315
-
316
- function compareTweetIds(
317
- left: string | null | undefined,
318
- right: string | null | undefined,
319
- ) {
320
- if (!left && !right) {
321
- return 0;
322
- }
323
- if (!left) {
324
- return -1;
325
- }
326
- if (!right) {
327
- return 1;
328
- }
329
- try {
330
- const leftBigInt = BigInt(left);
331
- const rightBigInt = BigInt(right);
332
- return leftBigInt === rightBigInt ? 0 : leftBigInt > rightBigInt ? 1 : -1;
333
- } catch {
334
- if (left.length !== right.length) {
335
- return left.length > right.length ? 1 : -1;
336
- }
337
- return left.localeCompare(right);
338
- }
339
- }
340
-
341
- function maxTweetId(...ids: Array<string | null | undefined>) {
342
- return ids.reduce<string | null>((current, next) => {
343
- if (!next) {
344
- return current;
345
- }
346
- return compareTweetIds(next, current) > 0 ? next : current;
347
- }, null);
348
- }
349
-
350
- function getNewestTweetId(tweets: XurlMentionData[]) {
351
- return maxTweetId(...tweets.map((tweet) => tweet.id));
352
- }
353
-
354
- function getOldestTweetId(tweets: XurlMentionData[]) {
355
- return tweets.reduce<string | null>((current, tweet) => {
356
- if (!current) {
357
- return tweet.id;
358
- }
359
- return compareTweetIds(tweet.id, current) < 0 ? tweet.id : current;
360
- }, null);
361
- }
362
-
363
- function resolveAccount(db: Database, accountId?: string) {
364
- const row = accountId
365
- ? (db
366
- .prepare(
367
- "select id, handle, external_user_id from accounts where id = ?",
368
- )
369
- .get(accountId) as
370
- | { id: string; handle: string; external_user_id: string | null }
371
- | undefined)
372
- : (db
373
- .prepare(
374
- `
375
- select id, handle, external_user_id
376
- from accounts
377
- order by is_default desc, created_at asc
378
- limit 1
379
- `,
380
- )
381
- .get() as
382
- | { id: string; handle: string; external_user_id: string | null }
383
- | undefined);
384
-
385
- if (!row) {
386
- throw new Error(`Unknown account: ${accountId ?? "default"}`);
387
- }
388
-
389
- return {
390
- accountId: row.id,
391
- username: row.handle.replace(/^@/, ""),
392
- externalUserId:
393
- typeof row.external_user_id === "string" &&
394
- row.external_user_id.length > 0
395
- ? row.external_user_id
396
- : undefined,
397
- };
398
- }
399
-
400
- function normalizeUsername(value: string) {
401
- return value.replace(/^@/, "").trim().toLowerCase();
402
- }
403
-
404
- function persistAccountExternalUserId(
405
- db: Database,
406
- accountId: string,
407
- externalUserId: string,
408
- ) {
409
- db.prepare(
410
- `
411
- update accounts
412
- set external_user_id = ?
413
- where id = ?
414
- and (external_user_id is null or external_user_id = '')
415
- `,
416
- ).run(externalUserId, accountId);
417
- }
418
-
419
- function userFromAuthenticatedPayload(
420
- payload: Record<string, unknown> | null,
421
- ): XurlMentionUser | undefined {
422
- if (!payload || typeof payload.id !== "string") {
423
- return undefined;
424
- }
425
- const username =
426
- typeof payload.username === "string"
427
- ? payload.username.replace(/^@/, "")
428
- : "";
429
- if (!username) {
430
- return undefined;
431
- }
432
- return {
433
- id: payload.id,
434
- username,
435
- name: typeof payload.name === "string" ? payload.name : username,
436
- };
437
- }
438
-
439
- function resolveAuthoredIdentityEffect({
440
- account,
441
- db,
442
- }: {
443
- account?: string;
444
- db: Database;
445
- }) {
446
- return Effect.gen(function* () {
447
- const status = yield* tryPromise(() => getTransportStatus());
448
- if (status.availableTransport !== "xurl") {
449
- return yield* Effect.fail(new AuthoredSyncError(status.statusText, 4));
450
- }
451
-
452
- const resolvedAccount = yield* trySync(() => resolveAccount(db, account));
453
- if (resolvedAccount.externalUserId) {
454
- return {
455
- ...resolvedAccount,
456
- userId: resolvedAccount.externalUserId,
457
- authenticatedUser: undefined,
458
- };
459
- }
460
-
461
- const authenticated = yield* tryPromise(() => lookupAuthenticatedUser());
462
- const authenticatedUser = userFromAuthenticatedPayload(authenticated);
463
- if (!authenticatedUser?.id) {
464
- return yield* Effect.fail(
465
- new AuthoredSyncError(
466
- "Could not resolve authenticated Twitter user id",
467
- 4,
468
- ),
469
- );
470
- }
471
-
472
- if (
473
- normalizeUsername(authenticatedUser.username) !==
474
- normalizeUsername(resolvedAccount.username)
475
- ) {
476
- return yield* Effect.fail(
477
- new AuthoredSyncError(
478
- `xurl is authenticated as @${authenticatedUser.username}, but selected account ${resolvedAccount.accountId} is @${resolvedAccount.username}. Link the account external_user_id or switch xurl login before syncing authored tweets.`,
479
- 4,
480
- ),
481
- );
482
- }
483
-
484
- yield* trySync(() =>
485
- persistAccountExternalUserId(
486
- db,
487
- resolvedAccount.accountId,
488
- authenticatedUser.id,
489
- ),
490
- );
491
-
492
- return {
493
- ...resolvedAccount,
494
- userId: authenticatedUser.id,
495
- authenticatedUser,
496
- };
497
- });
498
- }
499
-
500
- function toFallbackUser({
501
- userId,
502
- username,
503
- authenticatedUser,
504
- }: {
505
- userId: string;
506
- username: string;
507
- authenticatedUser?: XurlMentionUser;
508
- }): XurlMentionUser {
509
- if (authenticatedUser?.id === userId) {
510
- return authenticatedUser;
511
- }
512
- return {
513
- id: userId,
514
- username: username || `user_${userId}`,
515
- name: username || `user_${userId}`,
516
- };
517
- }
518
-
519
- function toMentionData(tweet: XurlUserTweet, fallbackAuthorId: string) {
520
- return {
521
- ...tweet,
522
- author_id: tweet.author_id ?? fallbackAuthorId,
523
- } satisfies XurlMentionData;
524
- }
525
-
526
- function toLocalEntities(tweet: XurlMentionData): TweetEntities {
527
- return tweetEntitiesFromXurl(tweet.entities);
528
- }
529
-
530
- function toMediaType(type: string): TweetMediaItem["type"] {
531
- if (type === "photo" || type === "image") {
532
- return "image";
533
- }
534
- if (type === "animated_gif" || type === "gif") {
535
- return "gif";
536
- }
537
- return type === "video" ? "video" : "unknown";
538
- }
539
-
540
- function toLocalMedia(
541
- tweet: XurlMentionData,
542
- mediaByKey: Map<string, XurlMedia>,
543
- ) {
544
- const mediaKeys = tweet.attachments?.media_keys ?? [];
545
- const seen = new Set<string>();
546
- return mediaKeys
547
- .map((mediaKey) => mediaByKey.get(mediaKey))
548
- .filter((media): media is XurlMedia => Boolean(media))
549
- .map((media) => {
550
- const url = media.url ?? media.preview_image_url ?? "";
551
- const thumbnailUrl = media.preview_image_url ?? media.url ?? "";
552
- return {
553
- url,
554
- type: toMediaType(media.type),
555
- ...(typeof media.alt_text === "string"
556
- ? { altText: media.alt_text }
557
- : {}),
558
- ...(typeof media.width === "number" ? { width: media.width } : {}),
559
- ...(typeof media.height === "number" ? { height: media.height } : {}),
560
- ...(thumbnailUrl ? { thumbnailUrl } : {}),
561
- };
562
- })
563
- .filter((media) => {
564
- const key = media.url || media.thumbnailUrl;
565
- if (!key || seen.has(key)) {
566
- return false;
567
- }
568
- seen.add(key);
569
- return true;
570
- });
571
- }
572
-
573
- function getMediaCount(tweet: XurlMentionData, media: TweetMediaItem[]) {
574
- if (media.length > 0) {
575
- return media.length;
576
- }
577
- if (tweet.attachments?.media_keys?.length) {
578
- return tweet.attachments.media_keys.length;
579
- }
580
- const urls = Array.isArray(tweet.entities?.urls) ? tweet.entities.urls : [];
581
- return urls.filter(
582
- (url) =>
583
- url &&
584
- typeof url === "object" &&
585
- typeof (url as Record<string, unknown>).media_key === "string",
586
- ).length;
587
- }
588
-
589
- function getReferencedTweetId(tweet: XurlMentionData, type: string) {
590
- return (
591
- tweet.referenced_tweets?.find((item) => item.type === type)?.id ?? null
592
- );
593
- }
594
-
595
- function replaceTweetFts(db: Database, tweetId: string, text: string) {
596
- db.prepare("delete from tweets_fts where tweet_id = ?").run(tweetId);
597
- db.prepare("insert into tweets_fts (tweet_id, text) values (?, ?)").run(
598
- tweetId,
599
- text,
600
- );
601
- }
602
-
603
- function findExistingProfileIdForUser(db: Database, user: XurlMentionUser) {
604
- const username = String(user.username ?? "").replace(/^@/, "");
605
- const row = db
606
- .prepare(
607
- `
608
- select id
609
- from profiles
610
- where id = ? or handle = ?
611
- limit 1
612
- `,
613
- )
614
- .get(buildExternalProfileId(user.id), username) as
615
- | { id: string }
616
- | undefined;
617
- return row?.id ?? null;
618
- }
619
-
620
- function mergeAuthoredPayloadIntoLocalStore({
621
- db,
622
- accountId,
623
- payload,
624
- sourceUser,
625
- }: {
626
- db: Database;
627
- accountId: string;
628
- payload: AuthoredPayload;
629
- sourceUser: XurlMentionUser;
630
- }) {
631
- const usersById = new Map(
632
- (payload.includes?.users ?? []).map((user) => [user.id, user]),
633
- );
634
- const fallbackUserIds = new Set<string>();
635
- if (!usersById.has(sourceUser.id)) {
636
- usersById.set(sourceUser.id, sourceUser);
637
- fallbackUserIds.add(sourceUser.id);
638
- }
639
- const mediaByKey = new Map(
640
- (payload.includes?.media ?? []).map((media) => [media.media_key, media]),
641
- );
642
- const upsertTweet = db.prepare(
643
- `
644
- insert into tweets (
645
- id, account_id, author_profile_id, kind, text, created_at,
646
- is_replied, reply_to_id, like_count, media_count, bookmarked, liked,
647
- entities_json, media_json, quoted_tweet_id
648
- ) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
649
- on conflict(id) do update set
650
- account_id = tweets.account_id,
651
- author_profile_id = excluded.author_profile_id,
652
- kind = case
653
- when tweets.kind in ('home', 'mention', 'authored') then tweets.kind
654
- when excluded.kind in ('home', 'mention', 'authored') then excluded.kind
655
- else coalesce(nullif(tweets.kind, ''), excluded.kind)
656
- end,
657
- text = excluded.text,
658
- created_at = excluded.created_at,
659
- like_count = excluded.like_count,
660
- media_count = excluded.media_count,
661
- entities_json = excluded.entities_json,
662
- media_json = excluded.media_json,
663
- is_replied = max(tweets.is_replied, excluded.is_replied),
664
- reply_to_id = coalesce(excluded.reply_to_id, tweets.reply_to_id),
665
- quoted_tweet_id = coalesce(excluded.quoted_tweet_id, tweets.quoted_tweet_id),
666
- bookmarked = tweets.bookmarked,
667
- liked = tweets.liked
668
- `,
669
- );
670
-
671
- const writeTweet = (tweet: XurlMentionData, kind: "authored" | "thread") => {
672
- const author =
673
- usersById.get(tweet.author_id) ??
674
- ({
675
- id: tweet.author_id,
676
- username: `user_${tweet.author_id}`,
677
- name: `user_${tweet.author_id}`,
678
- } as const);
679
- const profileId =
680
- usersById.has(tweet.author_id) && !fallbackUserIds.has(tweet.author_id)
681
- ? upsertProfileFromXUser(db, author).profile.id
682
- : ((fallbackUserIds.has(tweet.author_id)
683
- ? findExistingProfileIdForUser(db, author)
684
- : null) ??
685
- ensureStubProfileForXUser(db, tweet.author_id).profile.id);
686
- const replyToId = getReferencedTweetId(tweet, "replied_to");
687
- const quotedTweetId = getReferencedTweetId(tweet, "quoted");
688
- const media = toLocalMedia(tweet, mediaByKey);
689
- upsertTweet.run(
690
- tweet.id,
691
- accountId,
692
- profileId,
693
- kind,
694
- tweet.text,
695
- tweet.created_at,
696
- replyToId ? 1 : 0,
697
- replyToId,
698
- Number(tweet.public_metrics?.like_count ?? 0),
699
- getMediaCount(tweet, media),
700
- 0,
701
- 0,
702
- JSON.stringify(toLocalEntities(tweet)),
703
- JSON.stringify(media),
704
- quotedTweetId,
705
- );
706
- replaceTweetFts(db, tweet.id, tweet.text);
707
- };
708
-
709
- db.transaction(() => {
710
- const seenAt = new Date().toISOString();
711
- for (const includedTweet of payload.includes?.tweets ?? []) {
712
- writeTweet(includedTweet, "thread");
713
- }
714
- for (const tweet of payload.data) {
715
- writeTweet(tweet, "authored");
716
- upsertTweetAccountEdge(db, {
717
- accountId,
718
- tweetId: tweet.id,
719
- kind: "authored",
720
- source: "xurl",
721
- seenAt,
722
- rawJson: JSON.stringify(tweet),
723
- });
724
- }
725
- })();
726
- }
727
-
728
- function appendUniqueById<T extends { id: string }>(
729
- target: T[],
730
- seenIds: Set<string>,
731
- items: T[] | undefined,
732
- ) {
733
- for (const item of items ?? []) {
734
- if (seenIds.has(item.id)) {
735
- continue;
736
- }
737
- seenIds.add(item.id);
738
- target.push(item);
739
- }
740
- }
741
-
742
- function appendUniqueMedia(
743
- target: XurlMedia[],
744
- seenIds: Set<string>,
745
- items: XurlMedia[] | undefined,
746
- ) {
747
- for (const item of items ?? []) {
748
- if (seenIds.has(item.media_key)) {
749
- continue;
750
- }
751
- seenIds.add(item.media_key);
752
- target.push(item);
753
- }
754
- }
755
-
756
- function mergePages({
757
- pages,
758
- userId,
759
- nextToken,
760
- }: {
761
- pages: XurlUserTweetsResponse[];
762
- userId: string;
763
- nextToken: string | null;
764
- }): AuthoredPayload {
765
- const tweets: XurlMentionData[] = [];
766
- const users: XurlMentionUser[] = [];
767
- const includedTweets: XurlTweetData[] = [];
768
- const media: XurlMedia[] = [];
769
- const seenTweetIds = new Set<string>();
770
- const seenUserIds = new Set<string>();
771
- const seenIncludedTweetIds = new Set<string>();
772
- const seenMediaKeys = new Set<string>();
773
-
774
- for (const page of pages) {
775
- for (const tweet of page.items) {
776
- const normalized = toMentionData(tweet, userId);
777
- if (seenTweetIds.has(normalized.id)) {
778
- continue;
779
- }
780
- seenTweetIds.add(normalized.id);
781
- tweets.push(normalized);
782
- }
783
- appendUniqueById(users, seenUserIds, page.includes?.users);
784
- appendUniqueById(
785
- includedTweets,
786
- seenIncludedTweetIds,
787
- page.includes?.tweets,
788
- );
789
- appendUniqueMedia(media, seenMediaKeys, page.includes?.media);
790
- }
791
-
792
- const newestId = getNewestTweetId(tweets);
793
- const oldestId = getOldestTweetId(tweets);
794
- const includes = {
795
- ...(users.length > 0 ? { users } : {}),
796
- ...(includedTweets.length > 0 ? { tweets: includedTweets } : {}),
797
- ...(media.length > 0 ? { media } : {}),
798
- };
799
-
800
- return {
801
- data: tweets,
802
- ...(Object.keys(includes).length > 0 ? { includes } : {}),
803
- meta: {
804
- result_count: tweets.length,
805
- page_count: pages.length,
806
- next_token: nextToken,
807
- ...(newestId ? { newest_id: newestId } : {}),
808
- ...(oldestId ? { oldest_id: oldestId } : {}),
809
- },
810
- };
811
- }
812
-
813
- function formatError(error: unknown) {
814
- return error instanceof Error ? error.message : String(error);
815
- }
816
-
817
- function buildResult({
818
- accountId,
819
- userId,
820
- effectiveSinceId,
821
- nextSinceId,
822
- nextToken,
823
- pageCount,
824
- payload,
825
- partial,
826
- error,
827
- }: {
828
- accountId: string;
829
- userId: string;
830
- effectiveSinceId: string | null;
831
- nextSinceId: string | null;
832
- nextToken: string | null;
833
- pageCount: number;
834
- payload: AuthoredPayload;
835
- partial: boolean;
836
- error?: string;
837
- }) {
838
- return {
839
- ok: !partial,
840
- kind: "authored" as const,
841
- source: "xurl" as const,
842
- accountId,
843
- userId,
844
- count: payload.data.length,
845
- pages: pageCount,
846
- sinceId: effectiveSinceId,
847
- nextSinceId,
848
- nextToken,
849
- partial,
850
- ...(error ? { error } : {}),
851
- cursor: {
852
- sinceId: nextSinceId,
853
- paginationToken: nextToken,
854
- pending: Boolean(nextToken),
855
- },
856
- payload,
857
- };
858
- }
859
-
860
- export function syncAuthoredTweetsEffect({
861
- account,
862
- mode = "xurl",
863
- limit = DEFAULT_LIMIT,
864
- maxPages,
865
- sinceId,
866
- untilId,
867
- }: SyncAuthoredTweetsOptions) {
868
- return Effect.gen(function* () {
869
- if (mode !== "xurl") {
870
- return yield* Effect.fail(
871
- new Error("authored sync only supports --mode xurl"),
872
- );
873
- }
874
-
875
- const pageLimit = yield* trySync(() => assertXurlLimit(limit));
876
- const parsedMaxPages = yield* trySync(() => parseMaxPages(maxPages));
877
- const db = yield* trySync(() => getNativeDb());
878
- const identity = yield* resolveAuthoredIdentityEffect({ account, db });
879
- const cursor = yield* trySync(() =>
880
- readAuthoredCursor(db, identity.accountId),
881
- );
882
- const usePersistedForward =
883
- sinceId === undefined && !untilId && cursor.state === "pending-forward";
884
- const usePersistedUntil =
885
- sinceId === undefined &&
886
- Boolean(untilId) &&
887
- cursor.state === "pending-until" &&
888
- cursor.untilId === untilId;
889
- const shouldSeedFromArchive =
890
- !usePersistedForward &&
891
- !cursor.sinceId &&
892
- sinceId === undefined &&
893
- !untilId;
894
- const archiveSinceSeed = shouldSeedFromArchive
895
- ? yield* trySync(() =>
896
- findArchiveAuthoredSinceSeed(db, identity.accountId),
897
- )
898
- : null;
899
- if (shouldSeedFromArchive && !archiveSinceSeed) {
900
- console.error(
901
- "birdclaw sync authored: no archive baseline found; starting a full backwards scan",
902
- );
903
- }
904
- const persistedUntilSinceId: string | null = usePersistedUntil
905
- ? (("requestedSinceId" in cursor
906
- ? cursor.requestedSinceId
907
- : cursor.sinceId) ?? null)
908
- : null;
909
- const effectiveSinceId: string | null =
910
- sinceId ??
911
- archiveSinceSeed ??
912
- (untilId ? persistedUntilSinceId : cursor.sinceId) ??
913
- null;
914
- let nextToken = usePersistedForward
915
- ? cursor.token
916
- : usePersistedUntil
917
- ? cursor.token
918
- : undefined;
919
- let newestSeenId = usePersistedForward
920
- ? maxTweetId(cursor.sinceId, cursor.pendingNewestId)
921
- : cursor.sinceId;
922
- const pages: XurlUserTweetsResponse[] = [];
923
- const sourceUser = toFallbackUser({
924
- userId: identity.userId,
925
- username: identity.username,
926
- authenticatedUser: identity.authenticatedUser,
927
- });
928
- let pageCount = 0;
929
-
930
- while (parsedMaxPages === null || pageCount < parsedMaxPages) {
931
- const fetched = yield* tryPromise(() =>
932
- listUserTweets(identity.userId, {
933
- maxResults: pageLimit,
934
- paginationToken: nextToken,
935
- excludeRetweets: false,
936
- sinceId: effectiveSinceId ?? undefined,
937
- untilId,
938
- tweetFields: AUTHORED_TWEET_FIELDS,
939
- expansions: AUTHORED_EXPANSIONS,
940
- userFields: AUTHORED_USER_FIELDS,
941
- mediaFields: AUTHORED_MEDIA_FIELDS,
942
- auth: "oauth2",
943
- username: identity.username,
944
- }),
945
- ).pipe(
946
- Effect.map((page) => ({ ok: true as const, page })),
947
- Effect.catchAll((error) =>
948
- Effect.succeed({ ok: false as const, error }),
949
- ),
950
- );
951
-
952
- if (!fetched.ok) {
953
- if (pages.length === 0) {
954
- return yield* Effect.fail(fetched.error);
955
- }
956
- const payload = mergePages({
957
- pages,
958
- userId: identity.userId,
959
- nextToken: nextToken ?? null,
960
- });
961
- return buildResult({
962
- accountId: identity.accountId,
963
- userId: identity.userId,
964
- effectiveSinceId,
965
- nextSinceId: untilId ? cursor.sinceId : effectiveSinceId,
966
- nextToken: nextToken ?? null,
967
- pageCount,
968
- payload,
969
- partial: true,
970
- error: formatError(fetched.error),
971
- });
972
- }
973
-
974
- const page = fetched.page;
975
- const pagePayload = mergePages({
976
- pages: [page],
977
- userId: identity.userId,
978
- nextToken: page.nextToken,
979
- });
980
- yield* trySync(() =>
981
- mergeAuthoredPayloadIntoLocalStore({
982
- db,
983
- accountId: identity.accountId,
984
- payload: pagePayload,
985
- sourceUser,
986
- }),
987
- );
988
- pages.push(page);
989
- pageCount += 1;
990
- newestSeenId = maxTweetId(newestSeenId, pagePayload.meta.newest_id);
991
- nextToken = page.nextToken ?? undefined;
992
-
993
- const pendingToken = nextToken;
994
- if (pendingToken && untilId) {
995
- yield* trySync(() =>
996
- writePendingUntilCursor(db, identity.accountId, {
997
- sinceId: cursor.sinceId,
998
- token: pendingToken,
999
- untilId,
1000
- requestedSinceId: effectiveSinceId,
1001
- }),
1002
- );
1003
- } else if (pendingToken) {
1004
- yield* trySync(() =>
1005
- writePendingForwardCursor(db, identity.accountId, {
1006
- sinceId: effectiveSinceId,
1007
- token: pendingToken,
1008
- pendingNewestId: newestSeenId,
1009
- }),
1010
- );
1011
- }
1012
-
1013
- if (!nextToken) {
1014
- break;
1015
- }
1016
- }
1017
-
1018
- const capped = Boolean(nextToken);
1019
- const nextSinceId = untilId
1020
- ? cursor.sinceId
1021
- : capped
1022
- ? effectiveSinceId
1023
- : maxTweetId(newestSeenId, effectiveSinceId, cursor.sinceId);
1024
- if (untilId && capped && nextToken) {
1025
- yield* trySync(() =>
1026
- writePendingUntilCursor(db, identity.accountId, {
1027
- sinceId: cursor.sinceId,
1028
- token: nextToken,
1029
- untilId,
1030
- requestedSinceId: effectiveSinceId,
1031
- }),
1032
- );
1033
- } else if (untilId) {
1034
- yield* trySync(() =>
1035
- writeCommittedCursor(db, identity.accountId, cursor.sinceId),
1036
- );
1037
- } else if (capped && nextToken) {
1038
- yield* trySync(() =>
1039
- writePendingForwardCursor(db, identity.accountId, {
1040
- sinceId: nextSinceId,
1041
- token: nextToken,
1042
- pendingNewestId: newestSeenId,
1043
- }),
1044
- );
1045
- } else {
1046
- yield* trySync(() =>
1047
- writeCommittedCursor(db, identity.accountId, nextSinceId),
1048
- );
1049
- }
1050
-
1051
- const payload = mergePages({
1052
- pages,
1053
- userId: identity.userId,
1054
- nextToken: nextToken ?? null,
1055
- });
1056
- return buildResult({
1057
- accountId: identity.accountId,
1058
- userId: identity.userId,
1059
- effectiveSinceId,
1060
- nextSinceId,
1061
- nextToken: nextToken ?? null,
1062
- pageCount,
1063
- payload,
1064
- partial: capped,
1065
- ...(capped ? { error: "max pages reached before sync completed" } : {}),
1066
- });
1067
- });
1068
- }
1069
-
1070
- export function syncAuthoredTweets(options: SyncAuthoredTweetsOptions) {
1071
- return runEffectPromise(syncAuthoredTweetsEffect(options));
1072
- }