diff --git a/packages/bsky/src/api/app/bsky/feed/getPostThread.ts b/packages/bsky/src/api/app/bsky/feed/getPostThread.ts index 1480e54ac1a..0e31107d052 100644 --- a/packages/bsky/src/api/app/bsky/feed/getPostThread.ts +++ b/packages/bsky/src/api/app/bsky/feed/getPostThread.ts @@ -255,11 +255,15 @@ const getThreadData = async ( .orderBy('sortAt', 'desc') .execute(), ]) - const parentsByUri = parents.reduce((acc, parent) => { - return Object.assign(acc, { [parent.postUri]: parent }) + // prevent self-referential loops + const includedPosts = new Set([uri]) + const parentsByUri = parents.reduce((acc, post) => { + return Object.assign(acc, { [post.uri]: post }) }, {} as Record) const childrenByParentUri = children.reduce((acc, child) => { if (!child.replyParent) return acc + if (includedPosts.has(child.uri)) return acc + includedPosts.add(child.uri) acc[child.replyParent] ??= [] acc[child.replyParent].push(child) return acc @@ -269,7 +273,12 @@ const getThreadData = async ( return { post, parent: post.replyParent - ? getParentData(parentsByUri, post.replyParent, parentHeight) + ? getParentData( + parentsByUri, + includedPosts, + post.replyParent, + parentHeight, + ) : undefined, replies: getChildrenData(childrenByParentUri, uri, depth), } @@ -277,16 +286,19 @@ const getThreadData = async ( const getParentData = ( postsByUri: Record, + includedPosts: Set, uri: string, depth: number, ): PostThread | ParentNotFoundError | undefined => { if (depth < 1) return undefined + if (includedPosts.has(uri)) return undefined + includedPosts.add(uri) const post = postsByUri[uri] if (!post) return new ParentNotFoundError(uri) return { post, parent: post.replyParent - ? getParentData(postsByUri, post.replyParent, depth - 1) + ? getParentData(postsByUri, includedPosts, post.replyParent, depth - 1) : undefined, replies: [], }