birdclaw 0.3.0 → 0.4.1

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.
@@ -0,0 +1,428 @@
1
+ import { getNativeDb } from "./db";
2
+ import { lookupProfileViaBird, lookupProfilesViaBird } from "./bird";
3
+ import { readSyncCache, writeSyncCache } from "./sync-cache";
4
+ import {
5
+ hydrateProfileAffiliationOrganizations,
6
+ type ProfileAffiliationHydrationResult,
7
+ } from "./profile-affiliation-hydration";
8
+ import type { ProfileRecord, XurlMentionUser } from "./types";
9
+ import { getExternalUserId, upsertProfileFromXUser } from "./x-profile";
10
+ import { lookupUsersByIds } from "./xurl";
11
+
12
+ const PROFILE_CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
13
+ const PROFILE_NEGATIVE_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
14
+
15
+ type ProfileLookupStatus = "hit" | "miss" | "error";
16
+ type ProfileLookupSource = "local" | "cache" | "bird" | "xurl";
17
+
18
+ interface CachedProfileLookup {
19
+ status: ProfileLookupStatus;
20
+ source: Exclude<ProfileLookupSource, "local" | "cache">;
21
+ user?: XurlMentionUser;
22
+ error?: string;
23
+ }
24
+
25
+ export interface ResolveProfilesOptions {
26
+ refresh?: boolean;
27
+ maxAgeMs?: number;
28
+ negativeMaxAgeMs?: number;
29
+ xurlFallback?: boolean;
30
+ }
31
+
32
+ export interface ProfileResolveResult {
33
+ profileId: string;
34
+ externalUserId: string | null;
35
+ status: ProfileLookupStatus;
36
+ source: ProfileLookupSource | "negative-cache";
37
+ profile?: ProfileRecord;
38
+ affiliationHydration?: ProfileAffiliationHydrationResult;
39
+ error?: string;
40
+ }
41
+
42
+ function toProfile(row: Record<string, unknown>): ProfileRecord {
43
+ const followingCount = Number(row.following_count ?? 0);
44
+ let entities: Record<string, unknown> | undefined;
45
+ if (typeof row.entities_json === "string" && row.entities_json.length > 0) {
46
+ try {
47
+ const parsed = JSON.parse(row.entities_json) as unknown;
48
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
49
+ entities = parsed as Record<string, unknown>;
50
+ }
51
+ } catch {
52
+ entities = undefined;
53
+ }
54
+ }
55
+ return {
56
+ id: String(row.id),
57
+ handle: String(row.handle),
58
+ displayName: String(row.display_name),
59
+ bio: String(row.bio),
60
+ followersCount: Number(row.followers_count),
61
+ ...(Number.isFinite(followingCount) ? { followingCount } : {}),
62
+ avatarHue: Number(row.avatar_hue),
63
+ avatarUrl:
64
+ typeof row.avatar_url === "string" ? String(row.avatar_url) : undefined,
65
+ ...(typeof row.location === "string" && row.location.length > 0
66
+ ? { location: row.location }
67
+ : {}),
68
+ ...(typeof row.url === "string" && row.url.length > 0
69
+ ? { url: row.url }
70
+ : {}),
71
+ ...(typeof row.verified_type === "string" && row.verified_type.length > 0
72
+ ? { verifiedType: row.verified_type }
73
+ : {}),
74
+ ...(entities ? { entities } : {}),
75
+ createdAt: String(row.created_at),
76
+ };
77
+ }
78
+
79
+ function getProfile(profileId: string) {
80
+ const row = getNativeDb()
81
+ .prepare(
82
+ `
83
+ select id, handle, display_name, bio, followers_count, following_count,
84
+ avatar_hue, avatar_url, location, url, verified_type, entities_json, created_at
85
+ from profiles
86
+ where id = ?
87
+ `,
88
+ )
89
+ .get(profileId) as Record<string, unknown> | undefined;
90
+
91
+ return row ? toProfile(row) : null;
92
+ }
93
+
94
+ function isPlaceholderProfile(profile: ProfileRecord) {
95
+ const externalUserId = getExternalUserId(profile.id);
96
+ if (!externalUserId) {
97
+ return false;
98
+ }
99
+ return (
100
+ profile.handle === `id${externalUserId}` ||
101
+ profile.handle === `user_${externalUserId}` ||
102
+ profile.displayName === `id${externalUserId}` ||
103
+ profile.displayName === `user_${externalUserId}` ||
104
+ profile.bio === `Imported from archive user ${externalUserId}` ||
105
+ (profile.followersCount === 0 &&
106
+ profile.bio.startsWith("Imported from archive user "))
107
+ );
108
+ }
109
+
110
+ function isFresh(updatedAt: string, maxAgeMs: number) {
111
+ return Date.now() - new Date(updatedAt).getTime() <= maxAgeMs;
112
+ }
113
+
114
+ function cacheKeyForUserId(externalUserId: string) {
115
+ return `profile:lookup:user-id:${externalUserId}`;
116
+ }
117
+
118
+ function writeProfileLookupCache(
119
+ externalUserId: string,
120
+ value: CachedProfileLookup,
121
+ ) {
122
+ writeSyncCache(cacheKeyForUserId(externalUserId), value);
123
+ }
124
+
125
+ function updateConversationTitles(profile: ProfileRecord) {
126
+ getNativeDb()
127
+ .prepare(
128
+ `
129
+ update dm_conversations
130
+ set title = ?
131
+ where participant_profile_id = ?
132
+ `,
133
+ )
134
+ .run(profile.displayName || profile.handle, profile.id);
135
+ }
136
+
137
+ async function lookupViaXurl(externalUserId: string) {
138
+ const [user] = await lookupUsersByIds([externalUserId]);
139
+ return user ?? null;
140
+ }
141
+
142
+ async function fetchProfileUser(
143
+ externalUserId: string,
144
+ xurlFallback: boolean,
145
+ ): Promise<CachedProfileLookup> {
146
+ try {
147
+ const birdUser = await lookupProfileViaBird(externalUserId);
148
+ if (birdUser) {
149
+ return { status: "hit", source: "bird", user: birdUser };
150
+ }
151
+ } catch (error) {
152
+ if (!xurlFallback) {
153
+ return {
154
+ status: "error",
155
+ source: "bird",
156
+ error: error instanceof Error ? error.message : String(error),
157
+ };
158
+ }
159
+ }
160
+
161
+ if (!xurlFallback) {
162
+ return { status: "miss", source: "bird" };
163
+ }
164
+
165
+ try {
166
+ const xurlUser = await lookupViaXurl(externalUserId);
167
+ return xurlUser
168
+ ? { status: "hit", source: "xurl", user: xurlUser }
169
+ : { status: "miss", source: "xurl" };
170
+ } catch (error) {
171
+ return {
172
+ status: "error",
173
+ source: "xurl",
174
+ error: error instanceof Error ? error.message : String(error),
175
+ };
176
+ }
177
+ }
178
+
179
+ async function fetchProfileUsers(
180
+ externalUserIds: string[],
181
+ xurlFallback: boolean,
182
+ ) {
183
+ const uniqueIds = Array.from(new Set(externalUserIds));
184
+ const results = new Map<string, CachedProfileLookup>();
185
+ let unresolved = uniqueIds;
186
+
187
+ try {
188
+ const birdResults = await lookupProfilesViaBird(uniqueIds);
189
+ for (const result of birdResults) {
190
+ const externalUserId = result.target;
191
+ if (result.user) {
192
+ results.set(externalUserId, {
193
+ status: "hit",
194
+ source: "bird",
195
+ user: result.user,
196
+ });
197
+ } else if (result.error && !xurlFallback) {
198
+ results.set(externalUserId, {
199
+ status: "error",
200
+ source: "bird",
201
+ error: result.error,
202
+ });
203
+ }
204
+ }
205
+ unresolved = uniqueIds.filter((id) => !results.has(id));
206
+ } catch (error) {
207
+ if (!xurlFallback) {
208
+ for (const externalUserId of uniqueIds) {
209
+ results.set(externalUserId, {
210
+ status: "error",
211
+ source: "bird",
212
+ error: error instanceof Error ? error.message : String(error),
213
+ });
214
+ }
215
+ return results;
216
+ }
217
+ }
218
+
219
+ if (unresolved.length === 0) {
220
+ return results;
221
+ }
222
+ if (!xurlFallback) {
223
+ for (const externalUserId of unresolved) {
224
+ results.set(externalUserId, { status: "miss", source: "bird" });
225
+ }
226
+ return results;
227
+ }
228
+
229
+ try {
230
+ const xurlUsers = await lookupUsersByIds(unresolved);
231
+ const usersById = new Map(xurlUsers.map((user) => [String(user.id), user]));
232
+ for (const externalUserId of unresolved) {
233
+ const user = usersById.get(externalUserId);
234
+ results.set(
235
+ externalUserId,
236
+ user
237
+ ? { status: "hit", source: "xurl", user }
238
+ : { status: "miss", source: "xurl" },
239
+ );
240
+ }
241
+ } catch (error) {
242
+ for (const externalUserId of unresolved) {
243
+ results.set(externalUserId, {
244
+ status: "error",
245
+ source: "xurl",
246
+ error: error instanceof Error ? error.message : String(error),
247
+ });
248
+ }
249
+ }
250
+
251
+ return results;
252
+ }
253
+
254
+ export async function resolveProfilesForIds(
255
+ profileIds: string[],
256
+ options: ResolveProfilesOptions = {},
257
+ ): Promise<ProfileResolveResult[]> {
258
+ const maxAgeMs = options.maxAgeMs ?? PROFILE_CACHE_TTL_MS;
259
+ const negativeMaxAgeMs =
260
+ options.negativeMaxAgeMs ?? PROFILE_NEGATIVE_CACHE_TTL_MS;
261
+ const xurlFallback = options.xurlFallback ?? true;
262
+ const ordered: Array<
263
+ | { kind: "ready"; result: ProfileResolveResult }
264
+ | { kind: "pending"; profileId: string; externalUserId: string }
265
+ > = [];
266
+
267
+ for (const profileId of Array.from(new Set(profileIds))) {
268
+ const externalUserId = getExternalUserId(profileId);
269
+ if (!externalUserId) {
270
+ ordered.push({
271
+ kind: "ready",
272
+ result: {
273
+ profileId,
274
+ externalUserId: null,
275
+ status: "miss",
276
+ source: "local",
277
+ },
278
+ });
279
+ continue;
280
+ }
281
+
282
+ const localProfile = getProfile(profileId);
283
+ if (
284
+ localProfile &&
285
+ !options.refresh &&
286
+ !isPlaceholderProfile(localProfile)
287
+ ) {
288
+ ordered.push({
289
+ kind: "ready",
290
+ result: {
291
+ profileId,
292
+ externalUserId,
293
+ status: "hit",
294
+ source: "local",
295
+ profile: localProfile,
296
+ },
297
+ });
298
+ continue;
299
+ }
300
+
301
+ const cached = readSyncCache<CachedProfileLookup>(
302
+ cacheKeyForUserId(externalUserId),
303
+ );
304
+ if (cached && !options.refresh) {
305
+ const maxAge =
306
+ cached.value.status === "hit" ? maxAgeMs : negativeMaxAgeMs;
307
+ if (isFresh(cached.updatedAt, maxAge)) {
308
+ if (cached.value.status === "hit" && cached.value.user) {
309
+ const resolved = upsertProfileFromXUser(
310
+ getNativeDb(),
311
+ cached.value.user,
312
+ );
313
+ updateConversationTitles(resolved.profile);
314
+ ordered.push({
315
+ kind: "ready",
316
+ result: {
317
+ profileId: resolved.profile.id,
318
+ externalUserId,
319
+ status: "hit",
320
+ source: "cache",
321
+ profile: resolved.profile,
322
+ },
323
+ });
324
+ continue;
325
+ }
326
+ ordered.push({
327
+ kind: "ready",
328
+ result: {
329
+ profileId,
330
+ externalUserId,
331
+ status: cached.value.status,
332
+ source: "negative-cache",
333
+ error: cached.value.error,
334
+ },
335
+ });
336
+ continue;
337
+ }
338
+ }
339
+
340
+ ordered.push({ kind: "pending", profileId, externalUserId });
341
+ }
342
+
343
+ const pendingExternalIds = ordered.flatMap((item) =>
344
+ item.kind === "pending" ? [item.externalUserId] : [],
345
+ );
346
+ const fetchedByExternalId =
347
+ pendingExternalIds.length > 1
348
+ ? await fetchProfileUsers(pendingExternalIds, xurlFallback)
349
+ : new Map<string, CachedProfileLookup>();
350
+
351
+ const results: ProfileResolveResult[] = [];
352
+ for (const item of ordered) {
353
+ if (item.kind === "ready") {
354
+ results.push(item.result);
355
+ continue;
356
+ }
357
+ const fetched =
358
+ fetchedByExternalId.get(item.externalUserId) ??
359
+ (await fetchProfileUser(item.externalUserId, xurlFallback));
360
+ writeProfileLookupCache(item.externalUserId, fetched);
361
+ if (fetched.status === "hit" && fetched.user) {
362
+ const resolved = upsertProfileFromXUser(getNativeDb(), fetched.user);
363
+ const affiliationHydration = await hydrateProfileAffiliationOrganizations(
364
+ getNativeDb(),
365
+ resolved.profile.id,
366
+ );
367
+ updateConversationTitles(resolved.profile);
368
+ results.push({
369
+ profileId: resolved.profile.id,
370
+ externalUserId: item.externalUserId,
371
+ status: "hit",
372
+ source: fetched.source,
373
+ profile: resolved.profile,
374
+ ...(affiliationHydration.checked > 0 ? { affiliationHydration } : {}),
375
+ });
376
+ continue;
377
+ }
378
+ results.push({
379
+ profileId: item.profileId,
380
+ externalUserId: item.externalUserId,
381
+ status: fetched.status,
382
+ source: fetched.source,
383
+ error: fetched.error,
384
+ });
385
+ }
386
+
387
+ return results;
388
+ }
389
+
390
+ export async function resolvePlaceholderProfiles(
391
+ options: ResolveProfilesOptions & { limit?: number } = {},
392
+ ) {
393
+ const db = getNativeDb();
394
+ const rows = db
395
+ .prepare(
396
+ `
397
+ select id
398
+ from profiles
399
+ where id like 'profile_user_%'
400
+ and (
401
+ followers_count = 0
402
+ or bio like 'Imported from archive user %'
403
+ or handle like 'id%'
404
+ or handle like 'user_%'
405
+ )
406
+ order by id asc
407
+ limit ?
408
+ `,
409
+ )
410
+ .all(options.limit ?? 500) as Array<{ id: string }>;
411
+
412
+ const results = await resolveProfilesForIds(
413
+ rows.map((row) => row.id),
414
+ options,
415
+ );
416
+ return {
417
+ ok: true,
418
+ requestedProfiles: rows.length,
419
+ hydratedProfiles: results.filter((result) => result.status === "hit")
420
+ .length,
421
+ results,
422
+ };
423
+ }
424
+
425
+ export const __test__ = {
426
+ isPlaceholderProfile,
427
+ cacheKeyForUserId,
428
+ };