Repository navigation
feat: Rewrite Bluesky implementation and Bluesky API - #1902
Conversation
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughAdds a dedicated Bluesky API realm and routes, introduces BLUESKY_API_HOST_LIST, implements a full Bluesky client/processing/provider stack and schemas/types, renames provider identifiers from Bsky→Bluesky, updates routing/caching/transcode behavior, removes legacy bsky modules, and adds extensive tests and fixtures. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Worker as Worker (getPath)
participant Router as Bluesky API Router
participant Handler as API Handler
participant Provider as Bluesky Provider
participant XRPC as Bluesky XRPC API
Client->>Worker: GET /2/status/{handle}/{rkey} (host in BLUESKY_API_HOST_LIST)
Worker->>Worker: select realm = 'blueskyapi'
Worker->>Router: forward to /blueskyapi
Router->>Handler: blueskyStatusAPIRequest (validate)
Handler->>Provider: constructBlueskyThread / buildAPIBlueskyPost
Provider->>XRPC: fetchXrpc(app.bsky.feed.getPostThread)
XRPC-->>Provider: ThreadResponse
Provider->>Provider: process facets, embeds, quotes
Provider-->>Handler: APIBlueskyStatus payload
Handler-->>Client: JSON { code: 200, status }
sequenceDiagram
participant Client
participant Handler as Conversation Handler
participant ConvProv as Conversation Provider
participant ClientLib as Bluesky Client
participant Batcher as Profiles Batcher
participant XRPC as Bluesky XRPC API
Client->>Handler: GET /2/conversation/{handle}/{rkey}?cursor=...
Handler->>Handler: decode cursor
Handler->>ConvProv: constructBlueskyConversation(...)
ConvProv->>ClientLib: fetchPostThread(post, author)
ClientLib->>XRPC: app.bsky.feed.getPostThread
XRPC-->>ClientLib: ThreadResponse
ClientLib-->>ConvProv: BlueskyThreadResponse
ConvProv->>ConvProv: collect posts, sort, slice pagination
ConvProv->>Batcher: fetchProfilesDetailedBatched(dids)
Batcher->>XRPC: app.bsky.actor.getProfiles (batched)
XRPC-->>Batcher: profiles
Batcher-->>ConvProv: Map<did,profile>
ConvProv-->>Handler: SocialConversationBluesky + cursor
Handler-->>Client: JSON { ok:true, data }
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 7
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/helpers/linkFixer.ts (1)
30-33:⚠️ Potential issue | 🟠 MajorRemove facet debug logs from request path.
Line 30 and Line 32 log full facet payloads, which can leak user content/links into logs and add noisy high-volume output.
Diff suggestion
export const linkFixerBluesky = (facets: BlueskyFacet[], text: string): string => { let offset = 0; if (Array.isArray(facets) && facets.length) { - console.log('facets', facets); facets.forEach((facet: BlueskyFacet) => { - console.log('facet', facet); for (const feature of facet.features) { if (feature.$type === 'app.bsky.richtext.facet#link' && feature.uri) {🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/helpers/linkFixer.ts` around lines 30 - 33, Remove the two console.log calls that print full facet payloads in the facets iteration (the console.log('facets', facets) before facets.forEach and console.log('facet', facet) inside the loop). Instead, either remove logging entirely from the request path or replace with a non-sensitive, low-volume log (e.g., logger.debug/trace) that only emits safe identifiers (such as facet id or feature count) — target the facets variable, the BlueskyFacet objects iterated in facets.forEach, and the for (const feature of facet.features) loop when applying the change.
🧹 Nitpick comments (19)
.env.example (1)
17-17: Consider addressing the static analysis hints.The linter flags two style issues:
- Spaces around the equal sign (if this file's convention is no spaces)
- Key ordering -
BLUESKY_API_HOST_LISTshould alphabetically come beforeDIRECT_MEDIA_DOMAINSThese are minor style nits that could be addressed for consistency.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In @.env.example at line 17, Adjust the .env.example to satisfy linting: remove the spaces around the assignment for BLUESKY_API_HOST_LIST so it follows the file's no-space convention (e.g., BLUESKY_API_HOST_LIST="api.fxbsky.app") and reorder the keys so BLUESKY_API_HOST_LIST appears alphabetically before DIRECT_MEDIA_DOMAINS; update the file entry for BLUESKY_API_HOST_LIST accordingly.src/helpers/utils.ts (1)
105-110: Normalize hostname before whitelist check to avoid self-domain false negatives.Line 109 does exact hostname matching, so URLs like
www.fxtwitter.comwill be treated as foreign and wrapped unnecessarily.Diff suggestion
export const wrapForeignLinks = (url: string, apiHost: string): string => { let unwrap = false; const whitelistedDomains = ['fxtwitter.com', 'fixupx.com', 'fxbsky.app']; try { const urlObj = new URL(url); + const normalizedHost = urlObj.hostname.toLowerCase().replace(/^www\./, ''); - if (!whitelistedDomains.includes(urlObj.hostname)) { + if (!whitelistedDomains.includes(normalizedHost)) { unwrap = true; } } catch (_e) { unwrap = true; }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/helpers/utils.ts` around lines 105 - 110, The whitelist check uses urlObj.hostname directly so subdomains like "www.fxtwitter.com" fail; normalize the hostname before checking by stripping common subdomain prefixes (e.g., "www.") or matching only the registered domain, then perform the includes check against whitelistedDomains (symbols: whitelistedDomains, urlObj.hostname, unwrap) and set unwrap accordingly so equivalent hostnames are treated as whitelisted.src/helpers/giftranscode.ts (1)
24-26: Parse request hostname once in transcode guard.Line 24–26 repeatedly constructs
new URL(c.req.url). A single hostname extraction is cleaner and avoids repeated parsing.Diff suggestion
export const shouldTranscodeGif = (c: Context) => { + const hostname = new URL(c.req.url).hostname; return ( experimentCheck(Experiment.TRANSCODE_GIFS, !!Constants.GIF_TRANSCODE_DOMAIN_LIST) && !c.req.header('user-agent')?.includes('TelegramBot') && - !Constants.OLD_EMBED_DOMAINS.includes(new URL(c.req.url).hostname) && - !Constants.API_HOST_LIST.includes(new URL(c.req.url).hostname) && - !Constants.BLUESKY_API_HOST_LIST.includes(new URL(c.req.url).hostname) + !Constants.OLD_EMBED_DOMAINS.includes(hostname) && + !Constants.API_HOST_LIST.includes(hostname) && + !Constants.BLUESKY_API_HOST_LIST.includes(hostname) ); };🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/helpers/giftranscode.ts` around lines 24 - 26, Replace repeated new URL(c.req.url).hostname constructions in the transcode guard with a single extracted hostname variable: compute const host = new URL(c.req.url).hostname once at the start of the guard (or function handling the guard) and then use host in the three checks against Constants.OLD_EMBED_DOMAINS, Constants.API_HOST_LIST, and Constants.BLUESKY_API_HOST_LIST to avoid repeated URL parsing and improve clarity.test/bluesky.schemas.test.ts (1)
4-47: Consider adding additional schema test cases.The test validates a minimal valid payload, which is a good start. For more robust coverage, consider adding:
- A test with an invalid payload to ensure the schema rejects it.
- Assertion on
r.datawhen successful to verify parsed values match input.💡 Example enhancement
test('APIBlueskyStatusSchema parses minimal bluesky-shaped payload', () => { // ... existing sample ... const r = APIBlueskyStatusSchema.safeParse(sample); expect(r.success).toBe(true); + if (r.success) { + expect(r.data.id).toBe('rkey1'); + expect(r.data.provider).toBe('bluesky'); + } }); + +test('APIBlueskyStatusSchema rejects payload missing required fields', () => { + const invalid = { id: 'rkey1' }; // missing most required fields + const r = APIBlueskyStatusSchema.safeParse(invalid); + expect(r.success).toBe(false); +});🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/bluesky.schemas.test.ts` around lines 4 - 47, Add two stronger assertions around APIBlueskyStatusSchema: keep the existing valid-case test but assert the parsed result contents (e.g., check r.success is true and r.data.id, r.data.text, r.data.author.id, and r.data.provider equal the input values) and add a new test that supplies an invalid payload (for example missing required fields like id or author or wrong types) and asserts APIBlueskyStatusSchema.safeParse(invalid).success is false; reference the existing test name and the symbol APIBlueskyStatusSchema to locate where to add these extra expectations and the new negative test.test/bluesky.uris.test.ts (1)
16-19: Test description doesn't match the function name.The test is named
'bskyWebPostUrl'but tests the functionblueskyWebPostUrl. Consider updating the test description to match the actual function name for clarity and consistency with the PR's broader rename from "bsky" to "bluesky".Suggested fix
-test('bskyWebPostUrl', () => { +test('blueskyWebPostUrl constructs post URL', () => { expect(blueskyWebPostUrl('user.bsky.social', '3labc')).toEqual( 'https://bsky.app/profile/user.bsky.social/post/3labc' ); });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/bluesky.uris.test.ts` around lines 16 - 19, The test title incorrectly uses 'bskyWebPostUrl' while the actual function under test is blueskyWebPostUrl; update the test description string in the test case to 'blueskyWebPostUrl' so the test name matches the function being exercised (locate the test block that calls blueskyWebPostUrl and change the test(...) first argument accordingly).src/providers/bluesky/statusReposts.ts (1)
43-44: Deduplicate DIDs beforefetchProfilesDetailedBatched.This cuts redundant profile fetches for repeated actors.
⚡ Suggested refactor
- const dids = repostedBy.map(p => p.did); + const dids = [...new Set(repostedBy.map(p => p.did))]; const detailedByDid = await fetchProfilesDetailedBatched(dids);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/bluesky/statusReposts.ts` around lines 43 - 44, The code collects DIDs from repostedBy into dids and calls fetchProfilesDetailedBatched(dids) without removing duplicates; change the flow to deduplicate DIDs first (e.g., use a Set or Array.from(new Set(...)) on repostedBy.map(p => p.did)) and then pass the deduplicated array to fetchProfilesDetailedBatched so you avoid redundant profile fetches; update any downstream usage that assumes ordering to account for the deduped list if needed.src/caches.ts (1)
39-44: Consolidate duplicated host predicate into one variable.
returnAsJsonandskipReadThroughCacheare currently identical. Reusing one computed boolean avoids future drift.♻️ Suggested refactor
- const returnAsJson = - Constants.API_HOST_LIST.includes(cacheUrl.hostname) || - Constants.BLUESKY_API_HOST_LIST.includes(cacheUrl.hostname); - const skipReadThroughCache = - Constants.API_HOST_LIST.includes(cacheUrl.hostname) || - Constants.BLUESKY_API_HOST_LIST.includes(cacheUrl.hostname); + const isApiHost = + Constants.API_HOST_LIST.includes(cacheUrl.hostname) || + Constants.BLUESKY_API_HOST_LIST.includes(cacheUrl.hostname); + const returnAsJson = isApiHost; + const skipReadThroughCache = isApiHost;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/caches.ts` around lines 39 - 44, Both returnAsJson and skipReadThroughCache compute the same predicate; compute it once and reuse it to avoid drift. Replace the two identical expressions that check Constants.API_HOST_LIST.includes(cacheUrl.hostname) || Constants.BLUESKY_API_HOST_LIST.includes(cacheUrl.hostname) with a single boolean (e.g., isSpecialHost) computed from cacheUrl.hostname and the two Constants lists, then assign returnAsJson = isSpecialHost and skipReadThroughCache = isSpecialHost so both use the single source of truth (referencing returnAsJson, skipReadThroughCache, cacheUrl.hostname, Constants.API_HOST_LIST and Constants.BLUESKY_API_HOST_LIST).src/providers/bluesky/statusLikes.ts (1)
43-44: Deduplicate DIDs before batched profile hydration.This avoids redundant profile lookups when the same actor appears multiple times.
⚡ Suggested refactor
- const dids = likes.map(l => l.actor.did); + const dids = [...new Set(likes.map(l => l.actor.did))]; const detailedByDid = await fetchProfilesDetailedBatched(dids);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/bluesky/statusLikes.ts` around lines 43 - 44, The code constructs dids from likes and calls fetchProfilesDetailedBatched for each DID, which can repeat lookups; before calling fetchProfilesDetailedBatched deduplicate the dids array (e.g., using a Set) so only unique actor DIDs are fetched; update the dids variable used in the fetch call (and keep mapping logic that uses detailedByDid and likes unchanged) to reference the deduplicated list to avoid redundant profile hydration in statusLikes.ts (variables: likes, dids, fetchProfilesDetailedBatched, detailedByDid).src/types/vendor/bluesky.d.ts (2)
32-39: Consider makingmimeTypemore flexible.
BlueskyVideo.mimeTypeis typed as the literal'video/mp4'. While this may be the common case, Bluesky could support other video formats in the future. Consider widening tostringor a union of known formats.declare type BlueskyVideo = { $type: 'app.bsky.embed.video#view'; ref: { $link: string; }; - mimeType: 'video/mp4'; + mimeType: string; size: number; };🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/types/vendor/bluesky.d.ts` around lines 32 - 39, BlueskyVideo currently types mimeType as the literal 'video/mp4', which is too restrictive; update the BlueskyVideo type (the BlueskyVideo declaration and its mimeType property) to allow other video MIME types by widening mimeType to either string or a union of known formats (e.g., 'video/mp4' | 'video/webm' | 'video/ogg' | string) so the type remains compatible with current values while permitting future formats.
97-109: TODO comment indicates incomplete type definition.Line 100 has a TODO for figuring out other values for
allowIncoming. This is acceptable for an initial implementation, but should be addressed when more information is available.Would you like me to open an issue to track completing the
allowIncomingtype definition?🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/types/vendor/bluesky.d.ts` around lines 97 - 109, The BlueskyAuthor type's associated.chat.allowIncoming is currently hardcoded to the literal 'all'; update the type for associated.chat.allowIncoming (referencing BlueskyAuthor -> associated.chat.allowIncoming) to a broader, accurate union or at least string/enum to reflect other possible values (e.g., 'all' | 'none' | 'contacts' or string) and remove or update the TODO; also add a tracking issue or TODO with a link/reference so this schema refinement is addressed when authoritative values are known.src/providers/bluesky/processor.ts (2)
159-170: N+1 query pattern inresolveReplyingTo.Each call to
resolveReplyingTotriggers afetchProfilesByActorscall. When processing many posts (e.g., in search results or timelines), this could result in many individual network requests. Consider batching parent author lookups at the caller level for bulk operations.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/bluesky/processor.ts` around lines 159 - 170, The helper resolveReplyingTo performs a network call via fetchProfilesByActors for each status, causing an N+1 query pattern; change its API so the caller can supply pre-fetched profile data (e.g., accept a Map<string,Profile> or a resolver callback) and update callers that process batches (timeline/search processors) to first collect all parent DIDs, call fetchProfilesByActors once, then pass the resulting profiles map into resolveReplyingTo (or use a new resolveReplyingToWithProfiles variant) to avoid per-status network requests; keep rkeyFromPostAtUri and didFromAtUri usage the same but remove internal fetchProfilesByActors calls.
390-393: Language validation could be more robust.The check
language.length === 2 || language.length === 5is a heuristic for ISO 639-1 (2 chars) or BCP 47 (e.g., "en-US", 5 chars). However, BCP 47 tags can vary in length (e.g., "zh-Hans" is 7 chars). Consider using a more comprehensive validation or a permissive check.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/bluesky/processor.ts` around lines 390 - 393, The current language validation uses a brittle length check on the variable language (and compares to record?.langs?.[0]); replace it with a proper BCP‑47 style validation: either attempt to construct an Intl.Locale(language) in a try/catch (treating successful construction as valid) or validate with a permissive BCP‑47 regex (e.g. start with 2–3 letters then optional subtags separated by hyphens) and keep the existing inequality check against record?.langs?.[0]; update the conditional that references language and record?.langs?.[0] (in the processor.ts validation block) to use the new validation approach so tags like "zh-Hans" pass.src/providers/bluesky/search.ts (1)
8-16: Consider extractingnormalizePostViewto a shared module.This helper is duplicated in
profileStatuses.ts(lines 28-36). Extracting it to a shared utility would reduce duplication and ensure consistent normalization across the codebase.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/bluesky/search.ts` around lines 8 - 16, Extract the duplicate normalizePostView function into a shared utility module (e.g., create a new util file under src/providers/bluesky or a common utils folder), export it, and replace the local implementations in both search.ts and profileStatuses.ts with an import of the shared normalizePostView; ensure the shared module also exports or imports the BlueskyPost type (or re-export it) so both search.ts and profileStatuses.ts keep correct typing and behavior (preserve labels default to [], likeCount/repostCount default to 0, indexedAt default to '').src/providers/bluesky/profileStatuses.ts (1)
28-36: DuplicatenormalizePostViewfunction.This helper is identical to the one in
search.ts(lines 8-16). Consider extracting to a shared utility module.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/bluesky/profileStatuses.ts` around lines 28 - 36, The function normalizePostView is duplicated; extract it into a single shared utility (e.g., a new exported helper module) and have both callers import that one implementation instead of keeping two copies; specifically, move the normalizePostView logic into a shared helper, export it, replace the local normalizePostView in profileStatuses.ts and the identical one in search.ts with imports of the shared function, and update any import statements and tests/linting to ensure behavior remains identical.src/providers/bluesky/client.ts (2)
64-87: Consider refactoring batch functions to use fetchXrpc.
fetchPostsByUrisandfetchProfilesByActorsduplicate the timeout/fetch/error-handling logic fromfetchXrpc. They could be refactored to usefetchXrpcwith an array-style query param builder, reducing code duplication.This is optional since the current implementation works correctly.
Also applies to: 89-124
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/bluesky/client.ts` around lines 64 - 87, The fetchPostsByUris (and similarly fetchProfilesByActors) duplicates fetchXrpc's timeout/fetch/error-handling; refactor these functions to call fetchXrpc instead of reimplementing fetch logic: build the URL params as an array-style query (e.g., multiple 'uris' or 'actors' entries), pass them to fetchXrpc along with the same expected response typing, and return the posts/profiles (defaulting to empty arrays) while preserving current behavior for empty input and error cases; ensure you reference and reuse the fetchXrpc function signature and its abort/timeout semantics so no duplicate fetch/try/catch/timeout code remains.
209-233: Sequential batch requests may be slow for large actor lists.
fetchProfilesDetailedBatchedprocesses chunks sequentially withfor...of. For lists significantly larger than 25 actors, this could result in noticeable latency (e.g., 100 actors = 4 sequential requests × 12s max timeout = 48s worst case).Consider using
Promise.allorPromise.allSettledwith concurrency limiting for better performance, though this is acceptable for typical use cases.♻️ Parallel chunked fetching example
export const fetchProfilesDetailedBatched = async ( actors: string[] ): Promise<Map<string, BlueskyProfileViewDetailed>> => { const out = new Map<string, BlueskyProfileViewDetailed>(); if (!actors.length) return out; const unique = [...new Set(actors)]; const chunks: string[][] = []; for (let i = 0; i < unique.length; i += GET_PROFILES_MAX_ACTORS) { chunks.push(unique.slice(i, i + GET_PROFILES_MAX_ACTORS)); } const results = await Promise.allSettled( chunks.map(async (chunk) => { const qs = new URLSearchParams(); for (const a of chunk) qs.append('actors', a); const url = `${Constants.BLUESKY_API_ROOT}/xrpc/app.bsky.actor.getProfiles?${qs.toString()}`; const ac = new AbortController(); const t = setTimeout(() => ac.abort(), DEFAULT_TIMEOUT_MS); try { const res = await fetch(url, { signal: ac.signal, headers: { Accept: 'application/json' } }); clearTimeout(t); if (!res.ok) return []; const j = (await res.json()) as { profiles?: BlueskyProfileViewDetailed[] }; return j.profiles ?? []; } catch { clearTimeout(t); return []; } }) ); for (const result of results) { if (result.status === 'fulfilled') { for (const p of result.value) { if (p?.did) out.set(p.did, p); } } } return out; };🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/bluesky/client.ts` around lines 209 - 233, The current fetchProfilesDetailedBatched implementation runs chunked requests sequentially, causing high latency for large actor lists; update it to fire chunk requests in parallel (using Promise.allSettled or a small concurrency limiter like p-map) instead of the for-loop over unique chunks, preserving the AbortController/timeout logic for each request, collecting each fulfilled result's profiles and merging them into the existing out Map (keyed by p.did), and keeping the existing error/empty-result handling so non-OK or failed requests are ignored.src/realms/bluesky-api/handlers.ts (2)
46-48: Consider extracting header-setting logic into a helper.The pattern
for (const [header, value] of Object.entries(Constants.API_RESPONSE_HEADERS)) { c.header(header, value); }is repeated 14 times. A small helper would reduce duplication.♻️ Suggested helper
const setApiHeaders = (c: Context) => { for (const [header, value] of Object.entries(Constants.API_RESPONSE_HEADERS)) { c.header(header, value); } };Also applies to: 63-65, 80-82, 92-94, 112-114, 120-122, 131-133, 148-150, 165-167, 182-184, 205-207, 228-230, 267-269, 275-277
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/realms/bluesky-api/handlers.ts` around lines 46 - 48, Extract the repeated header-setting loop that iterates over Constants.API_RESPONSE_HEADERS and calls c.header(header, value) into a single helper (e.g., setApiHeaders(c: Context)), then replace each occurrence in handlers.ts (the blocks currently using for (const [header, value] of Object.entries(Constants.API_RESPONSE_HEADERS)) { c.header(header, value); }) with a call to setApiHeaders(c); ensure the helper accepts the same Context type used by the handler functions and is imported/defined near the top of the file so all handler functions can call it.
37-38: Timestamp threshold may misclassify edge cases.The threshold
1_000_000_000_000(Sep 2001 in ms, or year ~33658 in seconds) works for typical modern timestamps, but Unix timestamps from before 2001 expressed in milliseconds (e.g.,946684800000for Jan 2000) would be incorrectly treated as seconds. This is likely acceptable for this use case since Bluesky didn't exist then.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/realms/bluesky-api/handlers.ts` around lines 37 - 38, The unixTimestampParamToMs helper can misclassify pre-2001 millisecond timestamps; update unixTimestampParamToMs to first check broad magnitude and then resolve ambiguous 11–12 digit values by comparing to the current time: if unix < 1e11 treat as seconds (multiply by 1000); if unix >= 1e13 treat as milliseconds (return as-is); for unix in [1e11,1e13) compare against Date.now()—if unix <= Date.now() return unix (it's ms), otherwise return unix * 1000 (it's seconds).src/providers/bluesky/conversation.ts (1)
82-96: Potential unbounded recursion in reply chain traversal.The
while (chain.length > 0)loop incollectProcessedThreadPostsfetches additional threads recursively. While this follows reply chains correctly, a maliciously crafted or exceptionally long self-thread could cause many sequential network requests. The depth is implicitly bounded by the chain ending, but there's no explicit limit.Consider adding a maximum iteration guard to prevent excessive API calls in edge cases.
🛡️ Suggested safeguard
+const MAX_CHAIN_ITERATIONS = 50; + const collectProcessedThreadPosts = async ( thread: BlueskyThread, author: string ): Promise<BlueskyPost[]> => { const bucket: BlueskyPost[] = []; // ... parent collection ... bucket.push(thread.post); if (thread.replies?.length) { let threadPiece: BlueskyThread = thread; let chain = followReplyChain(threadPiece); const accumulated: BlueskyPost[] = [...chain]; + let iterations = 0; - while (chain.length > 0) { + while (chain.length > 0 && iterations < MAX_CHAIN_ITERATIONS) { + iterations++; const last = chain[chain.length - 1]; // ... rest of loop ... }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/bluesky/conversation.ts` around lines 82 - 96, The reply-chain loop in collectProcessedThreadPosts can run unbounded; add a max-iteration guard (e.g., MAX_CHAIN_DEPTH) and an iteration counter inside the while (chain.length > 0) loop that breaks when reached to prevent excessive fetchBlueskyThread calls; apply this guard around the loop that uses chain, last, fetchBlueskyThread and followReplyChain, and surface/log a clear warning or return early if the max depth is exceeded.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/embed/activity.ts`:
- Around line 277-281: When handling DataProvider.Bluesky in the switch that
sets baseHashtagUrl/baseSymbolUrl/baseMentionUrl, fix baseSymbolUrl so it
doesn't point to Constants.TWITTER_ROOT; either set it to a Bluesky search URL
under Constants.BLUESKY_ROOT (e.g., the Bluesky search path for symbols) or
clear/omit cashtag handling for Bluesky by setting baseSymbolUrl to an empty
string. Update the case for DataProvider.Bluesky where baseSymbolUrl is assigned
to reference Constants.BLUESKY_ROOT or an empty value and ensure downstream code
that uses baseSymbolUrl (in this module) can handle the empty/Bluesky-specific
URL.
In `@src/providers/bluesky/conversation.ts`:
- Around line 265-271: The formatting for the conditional call assigning raw
violates ESLint: collapse the multi-line arguments so each fetchPostThread
invocation is on a single line; update the ternary to call fetchPostThread with
its parameters inline (e.g., fetchPostThread(focalUri, CONVERSATION_PAGE_DEPTH,
CONVERSATION_PAGE_PARENT_HEIGHT) and fetchPostThread(focalUri,
THREAD_FETCH_DEPTH, THREAD_PARENT_HEIGHT_FIRST_PAGE)) while keeping the existing
isContinuation condition and the raw variable assignment unchanged.
In `@src/providers/bluesky/facets.ts`:
- Around line 21-23: When converting facet byte offsets to UTF-16 indices in
src/providers/bluesky/facets.ts (using utf8ByteOffsetToUtf16Index for
facet.index.byteStart and byteEnd), skip any facet whose converted range is
invalid (i.e., end <= start) before iterating facet.features or emitting API
facets; add a guard after computing start and end to continue/ignore the facet
when end <= start so you never produce facets with bad indices.
In `@src/providers/bluesky/uris.ts`:
- Around line 15-20: The didFromAtUri function currently returns any identifier
after "at://" even if it's not a DID; update didFromAtUri to validate that the
extracted identifier (variable did from rest.split('/')[0]) begins with "did:"
(or matches a DID regex) and return null if it does not, so only proper
DID-formatted identifiers are returned; adjust function logic to check the
prefix (or regex) before returning did.
In `@src/realms/bluesky-api/router.ts`:
- Line 85: Change the route registration that currently calls
blueskyApi.get('*', ...) to use blueskyApi.all('*', ...) so the JSON 404
response is returned for any HTTP method (GET/POST/PUT/DELETE/etc.); update the
handler attached to the wildcard route (the existing anonymous async c =>
c.json({ code: 404, message: 'Not found' }, 404)) to be used with
blueskyApi.all('*', ...) to ensure consistent JSON 404s across all methods.
In `@src/realms/bluesky-api/routes.ts`:
- Around line 213-227: ESLint flags formatting on the `ranking_mode` and `count`
schema lines; fix by breaking chained calls and long property values onto
separate lines so each method in the chain is on its own line (e.g., split
z.enum(...).optional().openapi(...) into z.enum(...)\n .optional()\n
.openapi(...)), and apply the same treatment to `count`
(z.coerce.number().int().min(1).max(100).optional().openapi(...)); keep the
property keys `ranking_mode`, `count` and the spread `...langQuery.shape` intact
and preserve their descriptions/defaults.
In `@src/worker.ts`:
- Around line 49-51: Constants.BLUESKY_API_HOST_LIST can be undefined at runtime
causing split() to throw; update the initialization in the Constants module (the
BLUESKY_API_HOST_LIST symbol) to use a safe fallback (e.g., default to '' or an
empty array before calling split) or validate and throw a clear startup error if
the env var is required, and align the env type (env.d.ts) to allow undefined or
reflect the default; ensure any code that uses Constants.BLUESKY_API_HOST_LIST
(such as the realm check in worker.ts) works correctly when the list is empty.
---
Outside diff comments:
In `@src/helpers/linkFixer.ts`:
- Around line 30-33: Remove the two console.log calls that print full facet
payloads in the facets iteration (the console.log('facets', facets) before
facets.forEach and console.log('facet', facet) inside the loop). Instead, either
remove logging entirely from the request path or replace with a non-sensitive,
low-volume log (e.g., logger.debug/trace) that only emits safe identifiers (such
as facet id or feature count) — target the facets variable, the BlueskyFacet
objects iterated in facets.forEach, and the for (const feature of
facet.features) loop when applying the change.
---
Nitpick comments:
In @.env.example:
- Line 17: Adjust the .env.example to satisfy linting: remove the spaces around
the assignment for BLUESKY_API_HOST_LIST so it follows the file's no-space
convention (e.g., BLUESKY_API_HOST_LIST="api.fxbsky.app") and reorder the keys
so BLUESKY_API_HOST_LIST appears alphabetically before DIRECT_MEDIA_DOMAINS;
update the file entry for BLUESKY_API_HOST_LIST accordingly.
In `@src/caches.ts`:
- Around line 39-44: Both returnAsJson and skipReadThroughCache compute the same
predicate; compute it once and reuse it to avoid drift. Replace the two
identical expressions that check
Constants.API_HOST_LIST.includes(cacheUrl.hostname) ||
Constants.BLUESKY_API_HOST_LIST.includes(cacheUrl.hostname) with a single
boolean (e.g., isSpecialHost) computed from cacheUrl.hostname and the two
Constants lists, then assign returnAsJson = isSpecialHost and
skipReadThroughCache = isSpecialHost so both use the single source of truth
(referencing returnAsJson, skipReadThroughCache, cacheUrl.hostname,
Constants.API_HOST_LIST and Constants.BLUESKY_API_HOST_LIST).
In `@src/helpers/giftranscode.ts`:
- Around line 24-26: Replace repeated new URL(c.req.url).hostname constructions
in the transcode guard with a single extracted hostname variable: compute const
host = new URL(c.req.url).hostname once at the start of the guard (or function
handling the guard) and then use host in the three checks against
Constants.OLD_EMBED_DOMAINS, Constants.API_HOST_LIST, and
Constants.BLUESKY_API_HOST_LIST to avoid repeated URL parsing and improve
clarity.
In `@src/helpers/utils.ts`:
- Around line 105-110: The whitelist check uses urlObj.hostname directly so
subdomains like "www.fxtwitter.com" fail; normalize the hostname before checking
by stripping common subdomain prefixes (e.g., "www.") or matching only the
registered domain, then perform the includes check against whitelistedDomains
(symbols: whitelistedDomains, urlObj.hostname, unwrap) and set unwrap
accordingly so equivalent hostnames are treated as whitelisted.
In `@src/providers/bluesky/client.ts`:
- Around line 64-87: The fetchPostsByUris (and similarly fetchProfilesByActors)
duplicates fetchXrpc's timeout/fetch/error-handling; refactor these functions to
call fetchXrpc instead of reimplementing fetch logic: build the URL params as an
array-style query (e.g., multiple 'uris' or 'actors' entries), pass them to
fetchXrpc along with the same expected response typing, and return the
posts/profiles (defaulting to empty arrays) while preserving current behavior
for empty input and error cases; ensure you reference and reuse the fetchXrpc
function signature and its abort/timeout semantics so no duplicate
fetch/try/catch/timeout code remains.
- Around line 209-233: The current fetchProfilesDetailedBatched implementation
runs chunked requests sequentially, causing high latency for large actor lists;
update it to fire chunk requests in parallel (using Promise.allSettled or a
small concurrency limiter like p-map) instead of the for-loop over unique
chunks, preserving the AbortController/timeout logic for each request,
collecting each fulfilled result's profiles and merging them into the existing
out Map (keyed by p.did), and keeping the existing error/empty-result handling
so non-OK or failed requests are ignored.
In `@src/providers/bluesky/conversation.ts`:
- Around line 82-96: The reply-chain loop in collectProcessedThreadPosts can run
unbounded; add a max-iteration guard (e.g., MAX_CHAIN_DEPTH) and an iteration
counter inside the while (chain.length > 0) loop that breaks when reached to
prevent excessive fetchBlueskyThread calls; apply this guard around the loop
that uses chain, last, fetchBlueskyThread and followReplyChain, and surface/log
a clear warning or return early if the max depth is exceeded.
In `@src/providers/bluesky/processor.ts`:
- Around line 159-170: The helper resolveReplyingTo performs a network call via
fetchProfilesByActors for each status, causing an N+1 query pattern; change its
API so the caller can supply pre-fetched profile data (e.g., accept a
Map<string,Profile> or a resolver callback) and update callers that process
batches (timeline/search processors) to first collect all parent DIDs, call
fetchProfilesByActors once, then pass the resulting profiles map into
resolveReplyingTo (or use a new resolveReplyingToWithProfiles variant) to avoid
per-status network requests; keep rkeyFromPostAtUri and didFromAtUri usage the
same but remove internal fetchProfilesByActors calls.
- Around line 390-393: The current language validation uses a brittle length
check on the variable language (and compares to record?.langs?.[0]); replace it
with a proper BCP‑47 style validation: either attempt to construct an
Intl.Locale(language) in a try/catch (treating successful construction as valid)
or validate with a permissive BCP‑47 regex (e.g. start with 2–3 letters then
optional subtags separated by hyphens) and keep the existing inequality check
against record?.langs?.[0]; update the conditional that references language and
record?.langs?.[0] (in the processor.ts validation block) to use the new
validation approach so tags like "zh-Hans" pass.
In `@src/providers/bluesky/profileStatuses.ts`:
- Around line 28-36: The function normalizePostView is duplicated; extract it
into a single shared utility (e.g., a new exported helper module) and have both
callers import that one implementation instead of keeping two copies;
specifically, move the normalizePostView logic into a shared helper, export it,
replace the local normalizePostView in profileStatuses.ts and the identical one
in search.ts with imports of the shared function, and update any import
statements and tests/linting to ensure behavior remains identical.
In `@src/providers/bluesky/search.ts`:
- Around line 8-16: Extract the duplicate normalizePostView function into a
shared utility module (e.g., create a new util file under src/providers/bluesky
or a common utils folder), export it, and replace the local implementations in
both search.ts and profileStatuses.ts with an import of the shared
normalizePostView; ensure the shared module also exports or imports the
BlueskyPost type (or re-export it) so both search.ts and profileStatuses.ts keep
correct typing and behavior (preserve labels default to [],
likeCount/repostCount default to 0, indexedAt default to '').
In `@src/providers/bluesky/statusLikes.ts`:
- Around line 43-44: The code constructs dids from likes and calls
fetchProfilesDetailedBatched for each DID, which can repeat lookups; before
calling fetchProfilesDetailedBatched deduplicate the dids array (e.g., using a
Set) so only unique actor DIDs are fetched; update the dids variable used in the
fetch call (and keep mapping logic that uses detailedByDid and likes unchanged)
to reference the deduplicated list to avoid redundant profile hydration in
statusLikes.ts (variables: likes, dids, fetchProfilesDetailedBatched,
detailedByDid).
In `@src/providers/bluesky/statusReposts.ts`:
- Around line 43-44: The code collects DIDs from repostedBy into dids and calls
fetchProfilesDetailedBatched(dids) without removing duplicates; change the flow
to deduplicate DIDs first (e.g., use a Set or Array.from(new Set(...)) on
repostedBy.map(p => p.did)) and then pass the deduplicated array to
fetchProfilesDetailedBatched so you avoid redundant profile fetches; update any
downstream usage that assumes ordering to account for the deduped list if
needed.
In `@src/realms/bluesky-api/handlers.ts`:
- Around line 46-48: Extract the repeated header-setting loop that iterates over
Constants.API_RESPONSE_HEADERS and calls c.header(header, value) into a single
helper (e.g., setApiHeaders(c: Context)), then replace each occurrence in
handlers.ts (the blocks currently using for (const [header, value] of
Object.entries(Constants.API_RESPONSE_HEADERS)) { c.header(header, value); })
with a call to setApiHeaders(c); ensure the helper accepts the same Context type
used by the handler functions and is imported/defined near the top of the file
so all handler functions can call it.
- Around line 37-38: The unixTimestampParamToMs helper can misclassify pre-2001
millisecond timestamps; update unixTimestampParamToMs to first check broad
magnitude and then resolve ambiguous 11–12 digit values by comparing to the
current time: if unix < 1e11 treat as seconds (multiply by 1000); if unix >=
1e13 treat as milliseconds (return as-is); for unix in [1e11,1e13) compare
against Date.now()—if unix <= Date.now() return unix (it's ms), otherwise return
unix * 1000 (it's seconds).
In `@src/types/vendor/bluesky.d.ts`:
- Around line 32-39: BlueskyVideo currently types mimeType as the literal
'video/mp4', which is too restrictive; update the BlueskyVideo type (the
BlueskyVideo declaration and its mimeType property) to allow other video MIME
types by widening mimeType to either string or a union of known formats (e.g.,
'video/mp4' | 'video/webm' | 'video/ogg' | string) so the type remains
compatible with current values while permitting future formats.
- Around line 97-109: The BlueskyAuthor type's associated.chat.allowIncoming is
currently hardcoded to the literal 'all'; update the type for
associated.chat.allowIncoming (referencing BlueskyAuthor ->
associated.chat.allowIncoming) to a broader, accurate union or at least
string/enum to reflect other possible values (e.g., 'all' | 'none' | 'contacts'
or string) and remove or update the TODO; also add a tracking issue or TODO with
a link/reference so this schema refinement is addressed when authoritative
values are known.
In `@test/bluesky.schemas.test.ts`:
- Around line 4-47: Add two stronger assertions around APIBlueskyStatusSchema:
keep the existing valid-case test but assert the parsed result contents (e.g.,
check r.success is true and r.data.id, r.data.text, r.data.author.id, and
r.data.provider equal the input values) and add a new test that supplies an
invalid payload (for example missing required fields like id or author or wrong
types) and asserts APIBlueskyStatusSchema.safeParse(invalid).success is false;
reference the existing test name and the symbol APIBlueskyStatusSchema to locate
where to add these extra expectations and the new negative test.
In `@test/bluesky.uris.test.ts`:
- Around line 16-19: The test title incorrectly uses 'bskyWebPostUrl' while the
actual function under test is blueskyWebPostUrl; update the test description
string in the test case to 'blueskyWebPostUrl' so the test name matches the
function being exercised (locate the test block that calls blueskyWebPostUrl and
change the test(...) first argument accordingly).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 999bfc3d-8417-4c9f-b86b-81c45f60d54d
📒 Files selected for processing (65)
.env.example.github/workflows/deploy.ymlesbuild.config.mjssrc/caches.tssrc/constants.tssrc/embed/activity.tssrc/embed/status.tssrc/enum.tssrc/helpers/giftranscode.tssrc/helpers/linkFixer.tssrc/helpers/mosaic.tssrc/helpers/transcode.tssrc/helpers/utils.tssrc/providers/bluesky/client.tssrc/providers/bluesky/conversation.tssrc/providers/bluesky/facets.tssrc/providers/bluesky/processor.tssrc/providers/bluesky/profile.tssrc/providers/bluesky/profileFollowers.tssrc/providers/bluesky/profileStatuses.tssrc/providers/bluesky/search.tssrc/providers/bluesky/statusLikes.tssrc/providers/bluesky/statusReposts.tssrc/providers/bluesky/uris.tssrc/providers/bsky/conversation.tssrc/providers/bsky/processor.tssrc/realms/api/schemas.tssrc/realms/bluesky-api/handlers.tssrc/realms/bluesky-api/router.tssrc/realms/bluesky-api/routes.tssrc/realms/bluesky/router.tssrc/realms/bluesky/routes/activity.tssrc/realms/bluesky/routes/oembed.tssrc/realms/bluesky/routes/redirects.tssrc/realms/bluesky/routes/status.tssrc/realms/twitter/routes/profile.tssrc/render/instantview.tssrc/render/video.tssrc/types/apiStatus.tssrc/types/env.d.tssrc/types/vendor/bluesky.d.tssrc/types/vendor/bsky.d.tssrc/worker.tstest/bluesky.api.test.tstest/bluesky.facets.test.tstest/bluesky.schemas.test.tstest/bluesky.uris.test.tstest/fixtures/bluesky/author-feed.jsontest/fixtures/bluesky/conversation-thread.jsontest/fixtures/bluesky/followers-profiles-batch.jsontest/fixtures/bluesky/following-profiles-batch.jsontest/fixtures/bluesky/get-followers.jsontest/fixtures/bluesky/get-follows.jsontest/fixtures/bluesky/get-likes.jsontest/fixtures/bluesky/get-reposted-by.jsontest/fixtures/bluesky/likers-profiles-batch.jsontest/fixtures/bluesky/profile-detail.jsontest/fixtures/bluesky/reposters-profiles-batch.jsontest/fixtures/bluesky/search-posts.jsontest/fixtures/bluesky/thread-multi-image.jsontest/fixtures/bluesky/thread-quote-notfound.jsontest/fixtures/bluesky/thread-single.jsontsconfig.jsonvitest.config.mtsworker.js
💤 Files with no reviewable changes (3)
- src/types/vendor/bsky.d.ts
- src/providers/bsky/conversation.ts
- src/providers/bsky/processor.ts
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
src/realms/bluesky-api/routes.ts (1)
88-91: Colocate the documented defaults in the schema.
.openapi({ default: ... })only changes the generated spec. Unless the handlers coalesce these values manually,count,ranking_mode, andfeedstill arrive asundefinedat runtime. Using.default(...)here would keep the public contract and the validated query in sync; the same applies to the othercountdefaults in this file.Also applies to: 214-217, 263-270
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/realms/bluesky-api/routes.ts` around lines 88 - 91, The schema uses .openapi({ default: ... }) which only affects the spec, so update the Zod schemas to set actual runtime defaults (e.g. change count: z.coerce.number().int().min(1).max(100).optional().openapi({default:20}) to use .default(20) instead of .optional() — e.g. z.coerce.number().int().min(1).max(100).default(20).openapi({ default: 20 })), and apply the same change for the other occurrences mentioned (the ranking_mode and feed query schemas and the other count instances) so validated inputs receive the documented defaults at runtime.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/realms/bluesky-api/routes.ts`:
- Around line 12-17: The langQuery schema's lang property and every cursor
string schema currently defined as z.string().optional() should reject blank
strings by adding .min(1); update the langQuery definition (lang) and every
cursor schema instance (the repeated "cursor" fields used across the Bluesky API
routes) to use z.string().optional().min(1) so empty strings are invalid while
preserving optionality and existing openapi metadata.
- Around line 537-540: The current "since" Zod schema uses z.coerce.number()
which coerces an empty string to 0 so a query like ?since= is treated as 0;
update the "since" schema definition in src/realms/bluesky-api/routes.ts to
explicitly reject blank strings before coercion (e.g., use z.string() with a
refine or preprocess that fails on empty/whitespace-only input, then
transform/pipe to Number and apply finite().min(0).optional().openapi(...)) so
that blank ?since= returns a validation 400 instead of being treated as 0; keep
the same description and optional semantics so the handler's check (sinceParam
!== undefined) behaves correctly.
---
Nitpick comments:
In `@src/realms/bluesky-api/routes.ts`:
- Around line 88-91: The schema uses .openapi({ default: ... }) which only
affects the spec, so update the Zod schemas to set actual runtime defaults (e.g.
change count:
z.coerce.number().int().min(1).max(100).optional().openapi({default:20}) to use
.default(20) instead of .optional() — e.g.
z.coerce.number().int().min(1).max(100).default(20).openapi({ default: 20 })),
and apply the same change for the other occurrences mentioned (the ranking_mode
and feed query schemas and the other count instances) so validated inputs
receive the documented defaults at runtime.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 85af3a1c-0690-481d-94b9-00f6690cd703
📒 Files selected for processing (10)
README.mdbranding.example.jsonsrc/providers/bluesky/conversation.tssrc/realms/bluesky-api/routes.tstest/bluesky.api.test.tstest/fixtures/bluesky/conversation-thread.jsontest/helpers/harness.tstest/mocks/FollowGraph/783214.jsontest/syndicationFeeds.test.tstest/twitter.feeds.test.ts
✅ Files skipped from review due to trivial changes (8)
- test/twitter.feeds.test.ts
- test/mocks/FollowGraph/783214.json
- README.md
- branding.example.json
- test/helpers/harness.ts
- test/syndicationFeeds.test.ts
- test/fixtures/bluesky/conversation-thread.json
- src/providers/bluesky/conversation.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- test/bluesky.api.test.ts
| const langQuery = z.object({ | ||
| lang: z.string().optional().openapi({ | ||
| description: 'Target language (ISO 639-1 or BCP 47) for inline translation when available', | ||
| example: 'es' | ||
| }) | ||
| }); |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
cat -n src/realms/bluesky-api/routes.ts | head -100Repository: FxEmbed/FxEmbed
Length of output: 4204
🏁 Script executed:
# Search for all cursor definitions in the file
rg -n "cursor" src/realms/bluesky-api/routes.tsRepository: FxEmbed/FxEmbed
Length of output: 5589
🏁 Script executed:
# Check Zod version to understand optional() behavior
rg -A2 -B2 "z\.string\(\)" src/realms/bluesky-api/routes.ts | head -30Repository: FxEmbed/FxEmbed
Length of output: 1017
Tighten lang and cursor validation to reject blank strings.
The schema z.string().optional() accepts empty strings as valid values, despite documentation indicating lang should be ISO 639-1 or BCP 47 and cursor should come from a prior response's cursor.bottom. Add .min(1) to reject blanks on both fields.
The same unvalidated cursor pattern appears on lines 140–143, 219–222, 272–275, 351–354, 395–398, 439–442, 484–487, and 533–536.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/realms/bluesky-api/routes.ts` around lines 12 - 17, The langQuery
schema's lang property and every cursor string schema currently defined as
z.string().optional() should reject blank strings by adding .min(1); update the
langQuery definition (lang) and every cursor schema instance (the repeated
"cursor" fields used across the Bluesky API routes) to use
z.string().optional().min(1) so empty strings are invalid while preserving
optionality and existing openapi metadata.
| since: z.coerce.number().finite().min(0).optional().openapi({ | ||
| description: | ||
| 'Unix timestamp (seconds, or ms if ≥ 1e12). Without `cursor`, 204 if no post is strictly newer than this time.' | ||
| }), |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
cat -n src/realms/bluesky-api/routes.ts | sed -n '530,550p'Repository: FxEmbed/FxEmbed
Length of output: 972
🌐 Web query:
Zod z.coerce.number() empty string blank input behavior
💡 Result:
z.coerce.number coerces an empty string ("") or blank input to the number 0 using JavaScript's Number function. This is the expected behavior as Number("") === 0 in JavaScript. For form inputs where empty strings should be treated as undefined/null instead of 0, use preprocess, transform, or pipe with checks for empty strings, as discussed in the official GitHub issues.
Citations:
- 1: z.coerce.number() defaults empty strings to 0 colinhacks/zod#2461
- 2: z.coerce.number() defaults empty strings to 0 colinhacks/zod#2814
- 3: https://www.mintlify.com/colinhacks/zod/api/utilities/coerce
- 4: https://tecktol.com/zod-coerce/
🏁 Script executed:
cat -n src/realms/bluesky-api/routes.ts | sed -n '1,50p'Repository: FxEmbed/FxEmbed
Length of output: 1995
🏁 Script executed:
rg -i "query\|request\|parse" src/realms/bluesky-api/routes.ts -A 2 -B 2 | head -60Repository: FxEmbed/FxEmbed
Length of output: 41
🏁 Script executed:
grep -n "z\.coerce\.number()" src/realms/bluesky-api/routes.tsRepository: FxEmbed/FxEmbed
Length of output: 831
🏁 Script executed:
cat -n src/realms/bluesky-api/routes.ts | sed -n '500,600p'Repository: FxEmbed/FxEmbed
Length of output: 3562
🏁 Script executed:
rg "optional" src/realms/bluesky-api/routes.ts | head -20Repository: FxEmbed/FxEmbed
Length of output: 1062
🏁 Script executed:
fd -e ts -e js src/realms/bluesky-api/ | head -20Repository: FxEmbed/FxEmbed
Length of output: 456
🏁 Script executed:
rg -A 30 "blueskyProfileStatusesV2Route" src/realms/bluesky-api/ | head -60Repository: FxEmbed/FxEmbed
Length of output: 3870
🏁 Script executed:
fd . src/realms/bluesky-api/ --type fRepository: FxEmbed/FxEmbed
Length of output: 159
🏁 Script executed:
rg -A 50 "blueskyProfileStatusesAPIRequest" src/realms/bluesky-api/handlers.ts | head -100Repository: FxEmbed/FxEmbed
Length of output: 1459
🏁 Script executed:
cat -n src/realms/bluesky-api/handlers.ts | head -150Repository: FxEmbed/FxEmbed
Length of output: 6628
Add validation to reject empty since parameter instead of coercing to 0.
z.coerce.number() coerces empty strings to 0 (standard JavaScript behavior), so ?since= passes validation as since=0 rather than returning a 400 error. The handler checks sinceParam !== undefined, which is true for 0, causing empty input to be treated as an explicit timestamp. Use preprocess or refine before coercion to reject blank strings:
Example fix
since: z
.string()
.transform(val => val.trim())
.refine(val => val.length > 0 || val === '', { message: 'since must not be empty' })
.pipe(z.coerce.number())
.finite()
.min(0)
.optional()
.openapi({ description: '...' })Or more concisely:
since: z
.string()
.refine(val => val.length > 0, { message: 'since must not be empty' })
.transform(val => Number(val))
.finite()
.min(0)
.optional()
.openapi({ description: '...' })🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/realms/bluesky-api/routes.ts` around lines 537 - 540, The current "since"
Zod schema uses z.coerce.number() which coerces an empty string to 0 so a query
like ?since= is treated as 0; update the "since" schema definition in
src/realms/bluesky-api/routes.ts to explicitly reject blank strings before
coercion (e.g., use z.string() with a refine or preprocess that fails on
empty/whitespace-only input, then transform/pipe to Number and apply
finite().min(0).optional().openapi(...)) so that blank ?since= returns a
validation 400 instead of being treated as 0; keep the same description and
optional semantics so the handler's check (sinceParam !== undefined) behaves
correctly.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/embed/activity.ts`:
- Around line 332-334: The symbol URL is built with an extra "/" causing URLs
like "%24/AAPL"; in the newFacet assignment replace the concatenation
`${baseSymbolUrl}/${facet.original}` with a direct join that omits the slash
(e.g. `${baseSymbolUrl}${facet.original}`) so the encoded dollar sign in
baseSymbolUrl and facet.original form `%24AAPL`; update the newFacet expression
where baseSymbolUrl and facet.original are used.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 7d2d62d2-11be-4156-a099-049fda5c704e
📒 Files selected for processing (6)
src/constants.tssrc/embed/activity.tssrc/providers/bluesky/facets.tssrc/providers/bluesky/uris.tssrc/realms/bluesky-api/router.tstest/bluesky.uris.test.ts
✅ Files skipped from review due to trivial changes (2)
- test/bluesky.uris.test.ts
- src/providers/bluesky/uris.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- src/constants.ts
- src/realms/bluesky-api/router.ts
- src/providers/bluesky/facets.ts
| newFacet = baseSymbolUrl | ||
| ? `<a href="${baseSymbolUrl}/${facet.original}">$${facet.original}</a>` | ||
| : `$${facet.original}`; |
There was a problem hiding this comment.
Symbol URL construction includes incorrect / separator.
The URL template uses ${baseSymbolUrl}/${facet.original}, but baseSymbolUrl already ends with %24 (the URL-encoded $). This produces URLs like https://bsky.app/search?q=%24/AAPL instead of the correct https://bsky.app/search?q=%24AAPL.
🐛 Proposed fix — remove the slash separator for symbol URLs
case 'symbol':
newFacet = baseSymbolUrl
- ? `<a href="${baseSymbolUrl}/${facet.original}">$${facet.original}</a>`
+ ? `<a href="${baseSymbolUrl}${facet.original}">$${facet.original}</a>`
: `$${facet.original}`;
text = text.slice(0, start) + newFacet + text.slice(end);
offset += newFacet.length - oldLen;
break;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| newFacet = baseSymbolUrl | |
| ? `<a href="${baseSymbolUrl}/${facet.original}">$${facet.original}</a>` | |
| : `$${facet.original}`; | |
| newFacet = baseSymbolUrl | |
| ? `<a href="${baseSymbolUrl}${facet.original}">$${facet.original}</a>` | |
| : `$${facet.original}`; |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/embed/activity.ts` around lines 332 - 334, The symbol URL is built with
an extra "/" causing URLs like "%24/AAPL"; in the newFacet assignment replace
the concatenation `${baseSymbolUrl}/${facet.original}` with a direct join that
omits the slash (e.g. `${baseSymbolUrl}${facet.original}`) so the encoded dollar
sign in baseSymbolUrl and facet.original form `%24AAPL`; update the newFacet
expression where baseSymbolUrl and facet.original are used.
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
test/bluesky.api.test.ts (1)
4-4: Usetest.skipor remove this tombstone case instead of commenting it out.The commented block at Lines 52-74 leaves
threadQuoteNotfounddead at Line 4 and makes this behavior easy to forget while the implementation is in flux.test.skip(...)keeps the expected contract visible without stale commented code.Also applies to: 52-74
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/bluesky.api.test.ts` at line 4, The file imports the fixture threadQuoteNotfound but the corresponding test is commented out; either restore the test as a skipped spec or delete the import and commented tombstone to avoid dead code. Replace the commented test block with test.skip('description', async () => { ... }) preserving the original assertions and using threadQuoteNotfound inside that skipped test (or if you choose removal, delete the import threadQuoteNotfound and the commented block entirely), ensuring the test suite shows the expected contract without leaving unused fixtures.src/providers/bluesky/processor.ts (1)
159-169: Avoid one profile fetch per reply.Lines 167-168 turn every reply post into its own
getProfilesround-trip. In feed/search timelines that becomes an N+1 upstream pattern and makes reply-heavy pages much more fragile. Prefer batching parent DIDs once per request, or reuse parent author data when it is already present.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/bluesky/processor.ts` around lines 159 - 169, resolveReplyingTo currently does a fetchProfilesByActors(parentDid) for each reply which creates an N+1 fetch pattern; change it to accept (or rely on) a pre-fetched profiles map and only fetch missing DIDs in batch. Specifically, update the resolveReplyingTo function signature (and its callers) to accept an optional Map<string, Profile> or profiles lookup, use rkeyFromPostAtUri and didFromAtUri as now to extract parentDid, and return early if the provided profiles already contains parentDid; if not present, collect missing DIDs across the request and call fetchProfilesByActors once to populate the map, then use that map to derive handle/parentRkey rather than calling fetchProfilesByActors per parent.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/providers/bluesky/processor.ts`:
- Around line 127-157: Remove the temporary "tombstone" path: delete the
buildUnavailableQuote helper and any branches that call it (the notFound/blocked
quote handling around the notFound logic currently returning undefined in the
processor) so the dead tombstone code and its dependency tombstoneAuthor are not
present; alternatively, if easier, replace callers of buildUnavailableQuote (and
any code that sets embed_card or constructs an APIStatus for unavailable posts)
to always return undefined for unavailable/blocked quotes until the tombstone
behavior is fully reintroduced. Ensure references to buildUnavailableQuote and
tombstoneAuthor are eliminated so the processor no longer builds or imports the
stub tombstone objects.
- Around line 397-420: The translation block incorrectly reapplies original post
`facets` to the translated text and lowercases `source_lang` without guarding
for null; update both translation assignments (the ones produced from
translateStatus and translateStatusAI in this file) to stop passing `facets`
into linkFixerBluesky (or pass an empty/neutral value) when preparing
translation.text so indices from the original text aren’t reused, and change any
`.toLowerCase()` calls on `translatePolyglot?.source_lang` and `apiStatus.lang`
to safely guard first (e.g., use `(translatePolyglot?.source_lang ??
'en').toLowerCase()` and `(apiStatus.lang ?? 'en').toLowerCase()`) before
lowercasing; reference the translateStatus/translateStatusAI result handling,
apiStatus.translation construction, and linkFixerBluesky/facets usage to locate
and fix the spots.
---
Nitpick comments:
In `@src/providers/bluesky/processor.ts`:
- Around line 159-169: resolveReplyingTo currently does a
fetchProfilesByActors(parentDid) for each reply which creates an N+1 fetch
pattern; change it to accept (or rely on) a pre-fetched profiles map and only
fetch missing DIDs in batch. Specifically, update the resolveReplyingTo function
signature (and its callers) to accept an optional Map<string, Profile> or
profiles lookup, use rkeyFromPostAtUri and didFromAtUri as now to extract
parentDid, and return early if the provided profiles already contains parentDid;
if not present, collect missing DIDs across the request and call
fetchProfilesByActors once to populate the map, then use that map to derive
handle/parentRkey rather than calling fetchProfilesByActors per parent.
In `@test/bluesky.api.test.ts`:
- Line 4: The file imports the fixture threadQuoteNotfound but the corresponding
test is commented out; either restore the test as a skipped spec or delete the
import and commented tombstone to avoid dead code. Replace the commented test
block with test.skip('description', async () => { ... }) preserving the original
assertions and using threadQuoteNotfound inside that skipped test (or if you
choose removal, delete the import threadQuoteNotfound and the commented block
entirely), ensuring the test suite shows the expected contract without leaving
unused fixtures.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 1384837c-c0a5-4539-a595-7850cfcb7078
📒 Files selected for processing (2)
src/providers/bluesky/processor.tstest/bluesky.api.test.ts
| const buildUnavailableQuote = (uri: string, reason: 'not_found' | 'blocked'): APIStatus => { | ||
| const rkey = rkeyFromPostAtUri(uri) ?? ''; | ||
| const did = didFromAtUri(uri); | ||
| const profileRef = did ?? 'unknown'; | ||
| const label = reason === 'blocked' ? 'Unavailable (blocked)' : 'Deleted post'; | ||
| const base: APIStatus = { | ||
| id: rkey || 'unavailable', | ||
| cid: undefined, | ||
| at_uri: uri, | ||
| url: rkey | ||
| ? blueskyWebPostUrl(profileRef, rkey) | ||
| : `${Constants.BLUESKY_ROOT}/profile/${profileRef}`, | ||
| text: label, | ||
| raw_text: { text: label, facets: [] }, | ||
| created_at: new Date(0).toISOString(), | ||
| created_timestamp: 0, | ||
| likes: 0, | ||
| reposts: 0, | ||
| quotes: 0, | ||
| replies: 0, | ||
| author: tombstoneAuthor(profileRef), | ||
| media: {}, | ||
| lang: null, | ||
| possibly_sensitive: false, | ||
| replying_to: null, | ||
| source: 'Bluesky Social', | ||
| embed_card: 'tweet', | ||
| provider: DataProvider.Bluesky | ||
| }; | ||
| return base; | ||
| }; |
There was a problem hiding this comment.
Delete the tombstone stub path until it is reintroduced for real.
Lines 127-157 are dead once Lines 308-319 always return undefined for notFound/blocked quotes, and Line 309 is already tripping formatting. Either wire tombstones back up or remove this helper/branch for now so CI passes cleanly.
Also applies to: 308-319
🧰 Tools
🪛 GitHub Check: ESLint
[failure] 127-127: Disallow unused variables
'buildUnavailableQuote' is assigned a value but never used. Allowed unused vars must match /^_/u.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/providers/bluesky/processor.ts` around lines 127 - 157, Remove the
temporary "tombstone" path: delete the buildUnavailableQuote helper and any
branches that call it (the notFound/blocked quote handling around the notFound
logic currently returning undefined in the processor) so the dead tombstone code
and its dependency tombstoneAuthor are not present; alternatively, if easier,
replace callers of buildUnavailableQuote (and any code that sets embed_card or
constructs an APIStatus for unavailable posts) to always return undefined for
unavailable/blocked quotes until the tombstone behavior is fully reintroduced.
Ensure references to buildUnavailableQuote and tombstoneAuthor are eliminated so
the processor no longer builds or imports the stub tombstone objects.
Implements #1850, make Bluesky support more reliable in general and implement public API
Summary by CodeRabbit
New Features
Improvements
Tests