Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

feat(bluesky): follow, mute and list people, read notifications and trigger on mentions (#16125)

Odai Ahmadfe761afd4a9d
diff --git a/bun.lock b/bun.lock
index fe270ce8f06..ae65b49df4d 100644
--- a/bun.lock
+++ b/bun.lock
@@ -1268,17 +1268,17 @@
},
"packages/pieces/community/bluesky": {
"name": "@activepieces/piece-bluesky",
- "version": "0.1.8",
+ "version": "0.2.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
"@atproto/api": "0.16.0",
- "dayjs": "1.11.9",
},
"devDependencies": {
"tslib": "^2.3.0",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/bocha-search": {
diff --git a/packages/pieces/community/bluesky/package.json b/packages/pieces/community/bluesky/package.json
index 3826c06e3f3..512927b9bfb 100644
--- a/packages/pieces/community/bluesky/package.json
+++ b/packages/pieces/community/bluesky/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/piece-bluesky",
- "version": "0.1.8",
+ "version": "0.2.0",
"type": "commonjs",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
@@ -8,16 +8,17 @@
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
"@atproto/api": "0.16.0",
- "dayjs": "1.11.9",
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*"
},
"devDependencies": {
- "tslib": "^2.3.0"
+ "tslib": "^2.3.0",
+ "vitest": "3.2.6"
},
"scripts": {
"build": "tsc -p tsconfig.lib.json && cp package.json dist/",
"bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",
- "lint": "eslint 'src/**/*.ts'"
+ "lint": "eslint 'src/**/*.ts'",
+ "test": "vitest run"
}
}
diff --git a/packages/pieces/community/bluesky/src/i18n/translation.json b/packages/pieces/community/bluesky/src/i18n/translation.json
index 79e1ae8919f..d6e2a4d7ec3 100644
--- a/packages/pieces/community/bluesky/src/i18n/translation.json
+++ b/packages/pieces/community/bluesky/src/i18n/translation.json
@@ -1,21 +1,92 @@
{
+ "Decentralized social network built on the AT Protocol.": "Decentralized social network built on the AT Protocol.",
"PDS Host": "PDS Host",
"Identifier": "Identifier",
"Password": "Password",
"The Personal Data Server host. Leave empty for default Bluesky network (https://bsky.social)": "The Personal Data Server host. Leave empty for default Bluesky network (https://bsky.social)",
"Your Bluesky handle or email address": "Your Bluesky handle or email address",
- "Your Bluesky account password or app password": "Your Bluesky account password or app password",
- "\nTo authenticate with Bluesky:\n\n1. **PDS Host**: The Personal Data Server host. Leave empty to use the default Bluesky network (https://bsky.social).\n2. **Identifier**: Your Bluesky handle (e.g., yourhandle.bsky.social) or email address.\n3. **Password**: Your Bluesky account password or app password.\n\nFor enhanced security, consider using an app password from your Bluesky account settings.\n": "\nTo authenticate with Bluesky:\n\n1. **PDS Host**: The Personal Data Server host. Leave empty to use the default Bluesky network (https://bsky.social).\n2. **Identifier**: Your Bluesky handle (e.g., yourhandle.bsky.social) or email address.\n3. **Password**: Your Bluesky account password or app password.\n\nFor enhanced security, consider using an app password from your Bluesky account settings.\n",
+ "A Bluesky app password (recommended) or your account password": "A Bluesky app password (recommended) or your account password",
+ "\nTo connect Bluesky:\n\n1. **PDS Host**: Leave the default (https://bsky.social) unless your account lives on a self-hosted Personal Data Server.\n2. **Identifier**: Your Bluesky handle (for example yourname.bsky.social) or the email address of the account.\n3. **Password**: An **app password**. In Bluesky open **Settings → Privacy and security → App passwords**, click **Add App Password**, give it a name and paste the generated password here. Your main account password also works, but it grants full account ac": "\nTo connect Bluesky:\n\n1. **PDS Host**: Leave the default (https://bsky.social) unless your account lives on a self-hosted Personal Data Server.\n2. **Identifier**: Your Bluesky handle (for example yourname.bsky.social) or the email address of the account.\n3. **Password**: An **app password**. In Bluesky open **Settings → Privacy and security → App passwords**, click **Add App Password**, give it a name and paste the generated password here. Your main account password also works, but it grants full account access, so an app password is strongly recommended.\n\nBluesky limits sign-ins to 30 per 5 minutes and 300 per day per account.\n",
"Create Post": "Create Post",
"Like Post": "Like Post",
"Repost Post": "Repost Post",
"Find Post": "Find Post",
"Find Thread": "Find Thread",
+ "Delete Post": "Delete Post",
+ "Unlike Post": "Unlike Post",
+ "Undo Repost": "Undo Repost",
+ "Get Profile": "Get Profile",
+ "Search Users": "Search Users",
+ "Search Posts": "Search Posts",
+ "Follow User": "Follow User",
+ "Unfollow User": "Unfollow User",
+ "Block User": "Block User",
+ "Unblock User": "Unblock User",
+ "Mute User": "Mute User",
+ "Unmute User": "Unmute User",
+ "Get User's Posts": "Get User's Posts",
+ "Get Home Timeline": "Get Home Timeline",
+ "Get Post Likes": "Get Post Likes",
+ "Get Post Reposts": "Get Post Reposts",
+ "Get Post Quotes": "Get Post Quotes",
+ "List Followers": "List Followers",
+ "List Following": "List Following",
+ "List Notifications": "List Notifications",
+ "Mark Notifications as Seen": "Mark Notifications as Seen",
+ "Update Profile": "Update Profile",
+ "List Lists": "List Lists",
+ "Get List Members": "Get List Members",
+ "Create List": "Create List",
+ "Delete List": "Delete List",
+ "Add User to List": "Add User to List",
+ "Remove User from List": "Remove User from List",
+ "Create Post (AI)": "Create Post (AI)",
+ "Like Post (AI)": "Like Post (AI)",
+ "Repost Post (AI)": "Repost Post (AI)",
+ "Get Posts (AI)": "Get Posts (AI)",
+ "Resolve Handle (AI)": "Resolve Handle (AI)",
+ "Get Unread Notification Count (AI)": "Get Unread Notification Count (AI)",
+ "Custom API Call": "Custom API Call",
"Create a new post on Bluesky": "Create a new post on Bluesky",
"Like a post on Bluesky": "Like a post on Bluesky",
"Share someone else's post to your timeline": "Share someone else's post to your timeline",
"Get detailed information about a specific post": "Get detailed information about a specific post",
"Get a full conversation thread with replies": "Get a full conversation thread with replies",
+ "Permanently delete one of your own posts": "Permanently delete one of your own posts",
+ "Remove your like from a post": "Remove your like from a post",
+ "Remove your repost of a post": "Remove your repost of a post",
+ "Get a Bluesky profile with follower and post counts": "Get a Bluesky profile with follower and post counts",
+ "Search Bluesky accounts by name, handle or bio": "Search Bluesky accounts by name, handle or bio",
+ "Search public Bluesky posts": "Search public Bluesky posts",
+ "Follow a Bluesky account": "Follow a Bluesky account",
+ "Stop following a Bluesky account": "Stop following a Bluesky account",
+ "Block a Bluesky account": "Block a Bluesky account",
+ "Unblock a Bluesky account": "Unblock a Bluesky account",
+ "Mute a Bluesky account (private)": "Mute a Bluesky account (private)",
+ "Unmute a Bluesky account": "Unmute a Bluesky account",
+ "List the latest posts and reposts of one account": "List the latest posts and reposts of one account",
+ "List the posts in your home (Following) timeline": "List the posts in your home (Following) timeline",
+ "List the accounts that liked a post": "List the accounts that liked a post",
+ "List the accounts that reposted a post": "List the accounts that reposted a post",
+ "List the posts that quote a post": "List the posts that quote a post",
+ "List the accounts that follow an account": "List the accounts that follow an account",
+ "List the accounts an account follows": "List the accounts an account follows",
+ "List your notifications (likes, reposts, follows, mentions, replies, quotes)": "List your notifications (likes, reposts, follows, mentions, replies, quotes)",
+ "Mark all notifications up to a time as seen": "Mark all notifications up to a time as seen",
+ "Change your display name, bio or avatar": "Change your display name, bio or avatar",
+ "List the user lists and moderation lists an account created": "List the user lists and moderation lists an account created",
+ "List the accounts on a Bluesky list": "List the accounts on a Bluesky list",
+ "Create a user list or moderation list": "Create a user list or moderation list",
+ "Permanently delete one of your lists and its memberships": "Permanently delete one of your lists and its memberships",
+ "Add an account to one of your lists": "Add an account to one of your lists",
+ "Remove an account from one of your lists": "Remove an account from one of your lists",
+ "Publish one post with optional reply, quote, images, link card, labels and tags": "Publish one post with optional reply, quote, images, link card, labels and tags",
+ "Like a post, or return the existing like": "Like a post, or return the existing like",
+ "Repost a post, or return the existing repost": "Repost a post, or return the existing repost",
+ "Fetch up to 25 posts by link or AT-URI in one call": "Fetch up to 25 posts by link or AT-URI in one call",
+ "Turn a Bluesky handle into its permanent DID": "Turn a Bluesky handle into its permanent DID",
+ "Count unread notifications": "Count unread notifications",
+ "Make a custom XRPC call to your Bluesky PDS, for example /app.bsky.actor.getProfile?actor=bsky.app": "Make a custom XRPC call to your Bluesky PDS, for example /app.bsky.actor.getProfile?actor=bsky.app",
"Post Type": "Post Type",
"Post Text": "Post Text",
"Post Language": "Post Language",
@@ -24,8 +95,10 @@
"Video URL": "Video URL",
"Video Description": "Video Description",
"Video Captions": "Video Captions",
+ "Video Caption Language": "Video Caption Language",
"Link to Share": "Link to Share",
"Reply to Post": "Reply to Post",
+ "Quote Post URL": "Quote Post URL",
"Thread Posts": "Thread Posts",
"Hashtags": "Hashtags",
"Content Warnings": "Content Warnings",
@@ -35,26 +108,127 @@
"Post URL": "Post URL",
"Thread Depth": "Thread Depth",
"Parent Height": "Parent Height",
- "Type of content you're sharing": "Type of content you're sharing",
- "What do you want to post? (Max 300 characters)": "What do you want to post? (Max 300 characters)",
+ "Post": "Post",
+ "Account": "Account",
+ "Search Query": "Search Query",
+ "Limit": "Limit",
+ "Cursor": "Cursor",
+ "Sort": "Sort",
+ "Author": "Author",
+ "Mentions": "Mentions",
+ "Language": "Language",
+ "Link Domain": "Link Domain",
+ "Link URL": "Link URL",
+ "Tags": "Tags",
+ "Since": "Since",
+ "Until": "Until",
+ "Include": "Include",
+ "Include Pinned Post": "Include Pinned Post",
+ "Notification Types": "Notification Types",
+ "Unread Only": "Unread Only",
+ "Seen Up To": "Seen Up To",
+ "Display Name": "Display Name",
+ "Clear Display Name": "Clear Display Name",
+ "Bio": "Bio",
+ "Clear Bio": "Clear Bio",
+ "Avatar Image URL": "Avatar Image URL",
+ "Kind": "Kind",
+ "List": "List",
+ "Name": "Name",
+ "Description": "Description",
+ "Text": "Text",
+ "Languages": "Languages",
+ "Reply To": "Reply To",
+ "Quote Post": "Quote Post",
+ "Image Alt Texts": "Image Alt Texts",
+ "Link Card URL": "Link Card URL",
+ "Content Labels": "Content Labels",
+ "Posts": "Posts",
+ "Handle": "Handle",
+ "Method": "Method",
+ "Headers": "Headers",
+ "Query Parameters": "Query Parameters",
+ "Body Type": "Body Type",
+ "Body": "Body",
+ "Response is Binary": "Response is Binary",
+ "Return Error as Output": "Return Error as Output",
+ "Timeout": "Timeout",
+ "Follow redirects": "Follow redirects",
+ "Informational only. To quote a post, fill in \"Quote Post URL\"; to reply, fill in \"Reply to Post\".": "Informational only. To quote a post, fill in \"Quote Post URL\"; to reply, fill in \"Reply to Post\".",
+ "What do you want to post? (Max 300 characters, counted as visible characters so emoji and non-Latin text count once each)": "What do you want to post? (Max 300 characters, counted as visible characters so emoji and non-Latin text count once each)",
"Language of your post": "Language of your post",
- "Add up to 4 images by URL": "Add up to 4 images by URL",
+ "Add up to 4 images by URL (PNG, JPEG, GIF or WebP, max 1 MB each)": "Add up to 4 images by URL (PNG, JPEG, GIF or WebP, max 1 MB each)",
"Describe each image for accessibility": "Describe each image for accessibility",
- "Link to video file (MP4, max 100MB)": "Link to video file (MP4, max 100MB)",
+ "Link to a video file (MP4, max 50 MB). Bluesky only accepts videos from accounts with a verified email address.": "Link to a video file (MP4, max 50 MB). Bluesky only accepts videos from accounts with a verified email address.",
"Describe the video for accessibility": "Describe the video for accessibility",
- "Caption file URLs (optional)": "Caption file URLs (optional)",
+ "Caption file URLs in WebVTT (.vtt) format (optional)": "Caption file URLs in WebVTT (.vtt) format (optional)",
+ "Language code of the caption files, for example en or de. Defaults to en.": "Language code of the caption files, for example en or de. Defaults to en.",
"URL to share with your post": "URL to share with your post",
"URL of post to reply to": "URL of post to reply to",
- "Create additional connected posts": "Create additional connected posts",
- "Add hashtags (e.g., tech,bluesky)": "Add hashtags (e.g., tech,bluesky)",
- "Add warnings for sensitive content": "Add warnings for sensitive content",
- "Who can see this post": "Who can see this post",
+ "Link or at:// URI of a post to quote (embed) in this post. Works together with images, video or a link.": "Link or at:// URI of a post to quote (embed) in this post. Works together with images, video or a link.",
+ "Create additional connected posts. Each must be 300 characters or fewer.": "Create additional connected posts. Each must be 300 characters or fewer.",
+ "Add hashtags (e.g., tech,bluesky). At most 8.": "Add hashtags (e.g., tech,bluesky). At most 8.",
+ "Self-labels Bluesky shows as content warnings. \"Adult Content\" is sent as Bluesky's Adult (porn) label, \"Violence\" as Graphic Media, \"Sensitive Topic\" as Suggestive (sexual); \"Spam/Promotional\" has no Bluesky label and is ignored.": "Self-labels Bluesky shows as content warnings. \"Adult Content\" is sent as Bluesky's Adult (porn) label, \"Violence\" as Graphic Media, \"Sensitive Topic\" as Suggestive (sexual); \"Spam/Promotional\" has no Bluesky label and is ignored.",
+ "Bluesky posts are always public; this setting has no effect and is kept only for older flows.": "Bluesky posts are always public; this setting has no effect and is kept only for older flows.",
"How to choose the post": "How to choose the post",
- "Choose from your recent timeline posts (only when \"From my timeline\" is selected above)": "Choose from your recent timeline posts (only when \"From my timeline\" is selected above)",
+ "Choose from your 50 most recent timeline posts (only when \"From my timeline\" is selected above)": "Choose from your 50 most recent timeline posts (only when \"From my timeline\" is selected above)",
"Paste the Bluesky post URL": "Paste the Bluesky post URL",
"Paste the Bluesky post URL (e.g., https://bsky.app/profile/username.bsky.social/post/xxx)": "Paste the Bluesky post URL (e.g., https://bsky.app/profile/username.bsky.social/post/xxx)",
"How many levels deep to retrieve replies": "How many levels deep to retrieve replies",
"How many parent posts to retrieve": "How many parent posts to retrieve",
+ "The post link (https://bsky.app/profile/alice.bsky.social/post/3k...) or its at:// URI.": "The post link (https://bsky.app/profile/alice.bsky.social/post/3k...) or its at:// URI.",
+ "Handle (alice.bsky.social), DID or profile link. Leave empty for your own profile.": "Handle (alice.bsky.social), DID or profile link. Leave empty for your own profile.",
+ "Words to search for, for example a name or company.": "Words to search for, for example a name or company.",
+ "How many results to return per page (1-100, default 25).": "How many results to return per page (1-100, default 25).",
+ "Leave empty for the first page. To get the next page, pass the \"cursor\" value returned by the previous run.": "Leave empty for the first page. To get the next page, pass the \"cursor\" value returned by the previous run.",
+ "Words, \"exact phrases\", #hashtags or from:handle. Use * to match everything when you only filter.": "Words, \"exact phrases\", #hashtags or from:handle. Use * to match everything when you only filter.",
+ "Only posts by this handle or DID.": "Only posts by this handle or DID.",
+ "Only posts that mention this handle or DID.": "Only posts that mention this handle or DID.",
+ "Only posts in this language, for example en or ja.": "Only posts in this language, for example en or ja.",
+ "Only posts linking to this domain, for example activepieces.com.": "Only posts linking to this domain, for example activepieces.com.",
+ "Only posts linking to this exact URL.": "Only posts linking to this exact URL.",
+ "Only posts with all of these hashtags (without #).": "Only posts with all of these hashtags (without #).",
+ "Only posts created at or after this time.": "Only posts created at or after this time.",
+ "Only posts created before this time.": "Only posts created before this time.",
+ "Handle (alice.bsky.social), DID or profile link of the account to follow.": "Handle (alice.bsky.social), DID or profile link of the account to follow.",
+ "Handle (alice.bsky.social), DID or profile link of the account to unfollow.": "Handle (alice.bsky.social), DID or profile link of the account to unfollow.",
+ "Handle (alice.bsky.social), DID or profile link of the account to block.": "Handle (alice.bsky.social), DID or profile link of the account to block.",
+ "Handle (alice.bsky.social), DID or profile link of the account to unblock.": "Handle (alice.bsky.social), DID or profile link of the account to unblock.",
+ "Handle (alice.bsky.social), DID or profile link of the account to mute.": "Handle (alice.bsky.social), DID or profile link of the account to mute.",
+ "Handle (alice.bsky.social), DID or profile link of the account to unmute.": "Handle (alice.bsky.social), DID or profile link of the account to unmute.",
+ "Handle (alice.bsky.social), DID or profile link. Leave empty for your own posts.": "Handle (alice.bsky.social), DID or profile link. Leave empty for your own posts.",
+ "Put the pinned post first.": "Put the pinned post first.",
+ "Handle (alice.bsky.social), DID or profile link. Leave empty for your own account.": "Handle (alice.bsky.social), DID or profile link. Leave empty for your own account.",
+ "Only these notification types. Leave empty for all.": "Only these notification types. Leave empty for all.",
+ "Only return notifications that are not yet marked as seen. A page can then hold fewer items than the limit.": "Only return notifications that are not yet marked as seen. A page can then hold fewer items than the limit.",
+ "Notifications up to this time are marked as seen. Leave empty for now.": "Notifications up to this time are marked as seen. Leave empty for now.",
+ "New display name. Leave empty to keep the current one.": "New display name. Leave empty to keep the current one.",
+ "Remove the display name.": "Remove the display name.",
+ "New bio. Leave empty to keep the current one.": "New bio. Leave empty to keep the current one.",
+ "Remove the bio.": "Remove the bio.",
+ "PNG or JPEG, max 1 MB. Leave empty to keep the current avatar.": "PNG or JPEG, max 1 MB. Leave empty to keep the current avatar.",
+ "Handle, DID or profile link of the list owner. Leave empty for your own lists.": "Handle, DID or profile link of the list owner. Leave empty for your own lists.",
+ "The list link (https://bsky.app/profile/alice.bsky.social/lists/3k...) or its at:// URI.": "The list link (https://bsky.app/profile/alice.bsky.social/lists/3k...) or its at:// URI.",
+ "List name (max 64 characters).": "List name (max 64 characters).",
+ "Optional (max 300 characters).": "Optional (max 300 characters).",
+ "Handle (alice.bsky.social), DID or profile link of the account to add.": "Handle (alice.bsky.social), DID or profile link of the account to add.",
+ "Handle (alice.bsky.social), DID or profile link of the account to remove.": "Handle (alice.bsky.social), DID or profile link of the account to remove.",
+ "Post text, at most 300 visible characters. Links, @mentions and #hashtags become clickable.": "Post text, at most 300 visible characters. Links, @mentions and #hashtags become clickable.",
+ "Up to 3 BCP-47 language codes, for example en or pt-BR.": "Up to 3 BCP-47 language codes, for example en or pt-BR.",
+ "Link or at:// URI of the post to reply to.": "Link or at:// URI of the post to reply to.",
+ "Link or at:// URI of a post to quote.": "Link or at:// URI of a post to quote.",
+ "Up to 4 public image URLs (PNG, JPEG, GIF or WebP, max 1 MB each).": "Up to 4 public image URLs (PNG, JPEG, GIF or WebP, max 1 MB each).",
+ "Alt text for each image, in the same order.": "Alt text for each image, in the same order.",
+ "A URL to show as a link preview card. Ignored when images are given.": "A URL to show as a link preview card. Ignored when images are given.",
+ "Up to 8 extra hashtags stored on the post without appearing in the text (without #).": "Up to 8 extra hashtags stored on the post without appearing in the text (without #).",
+ "Up to 25 post links or at:// URIs.": "Up to 25 post links or at:// URIs.",
+ "For example alice.bsky.social, @alice or https://bsky.app/profile/alice.bsky.social.": "For example alice.bsky.social, @alice or https://bsky.app/profile/alice.bsky.social.",
+ "Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.",
+ "Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.",
+ "Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.",
+ "On a failed request, output the error instead of failing the step.": "On a failed request, output the error instead of failing the step.",
+ "Seconds to wait for a response. Empty: up to the flow limit (10 min).": "Seconds to wait for a response. Empty: up to the flow limit (10 min).",
+ "Follow 3xx redirects instead of returning them as the response.": "Follow 3xx redirects instead of returning them as the response.",
"Text Post": "Text Post",
"Photo Post": "Photo Post",
"Link Share": "Link Share",
@@ -80,6 +254,9 @@
"Sensitive Topic": "Sensitive Topic",
"Violence": "Violence",
"Spam/Promotional": "Spam/Promotional",
+ "Suggestive (sexual)": "Suggestive (sexual)",
+ "Nudity": "Nudity",
+ "Adult (porn)": "Adult (porn)",
"Everyone (Public)": "Everyone (Public)",
"Followers only": "Followers only",
"Private/Unlisted": "Private/Unlisted",
@@ -101,34 +278,69 @@
"10 parents": "10 parents",
"20 parents": "20 parents",
"All parents (80 max)": "All parents (80 max)",
+ "Latest": "Latest",
+ "Top": "Top",
+ "Posts and reposts, no replies": "Posts and reposts, no replies",
+ "Posts, reposts and replies": "Posts, reposts and replies",
+ "Only posts with media": "Only posts with media",
+ "Only posts with video": "Only posts with video",
+ "Posts and the author's own threads": "Posts and the author's own threads",
+ "Like": "Like",
+ "Repost": "Repost",
+ "Follow": "Follow",
+ "Mention": "Mention",
+ "Quote": "Quote",
+ "Joined via your starter pack": "Joined via your starter pack",
+ "Like of your repost": "Like of your repost",
+ "Repost of your repost": "Repost of your repost",
+ "Post from an account you subscribed to": "Post from an account you subscribed to",
+ "Verified": "Verified",
+ "Verification removed": "Verification removed",
+ "All lists": "All lists",
+ "User lists (curation)": "User lists (curation)",
+ "Moderation lists": "Moderation lists",
+ "Reference lists (starter packs)": "Reference lists (starter packs)",
+ "User list (curation)": "User list (curation)",
+ "Moderation list": "Moderation list",
+ "Graphic Media": "Graphic Media",
+ "GET": "GET",
+ "POST": "POST",
+ "PATCH": "PATCH",
+ "PUT": "PUT",
+ "DELETE": "DELETE",
+ "HEAD": "HEAD",
"New Posts by Author": "New Posts by Author",
"New Follower on Account": "New Follower on Account",
"New Timeline Posts": "New Timeline Posts",
"New Post (with Search Options)": "New Post (with Search Options)",
+ "New Notification": "New Notification",
+ "New Mention or Reply": "New Mention or Reply",
"Triggers when a selected author creates a new post": "Triggers when a selected author creates a new post",
"Triggers when someone new follows your Bluesky account": "Triggers when someone new follows your Bluesky account",
"Triggers when new posts appear in your timeline": "Triggers when new posts appear in your timeline",
"Triggers when posts match your search criteria": "Triggers when posts match your search criteria",
+ "Triggers when you get a new notification (mention, reply, quote, like, repost, follow and more)": "Triggers when you get a new notification (mention, reply, quote, like, repost, follow and more)",
+ "Triggers when someone mentions you, replies to you or quotes your post": "Triggers when someone mentions you, replies to you or quotes your post",
"How to select author?": "How to select author?",
"Select Author": "Select Author",
"Author Handle": "Author Handle",
"Include Replies": "Include Replies",
"Include Reposts": "Include Reposts",
- "Search Query": "Search Query",
"Language Filter": "Language Filter",
"Filter by Images": "Filter by Images",
"Filter by Videos": "Filter by Videos",
"Sort Order": "Sort Order",
"Choose how to select the author": "Choose how to select the author",
"Choose from accounts you follow": "Choose from accounts you follow",
- "Enter the Bluesky username (e.g., username.bsky.social)": "Enter the Bluesky username (e.g., username.bsky.social)",
+ "Enter the Bluesky username (e.g., username.bsky.social), a DID or a profile link": "Enter the Bluesky username (e.g., username.bsky.social), a DID or a profile link",
"Include reply posts by this author": "Include reply posts by this author",
"Include posts that this author reposted": "Include posts that this author reposted",
"Keywords, hashtags (#example), or mentions (@handle) to find": "Keywords, hashtags (#example), or mentions (@handle) to find",
"Filter by language": "Filter by language",
- "Only posts with/without images": "Only posts with/without images",
- "Only posts with/without videos": "Only posts with/without videos",
+ "When ticked, only posts with images trigger the flow": "When ticked, only posts with images trigger the flow",
+ "When ticked, only posts with a video trigger the flow": "When ticked, only posts with a video trigger the flow",
"How to sort results": "How to sort results",
+ "Which notification types trigger the flow. Leave empty for all types.": "Which notification types trigger the flow. Leave empty for all types.",
"From my following list": "From my following list",
"Enter handle manually": "Enter handle manually",
"Latest First": "Latest First",
diff --git a/packages/pieces/community/bluesky/src/index.ts b/packages/pieces/community/bluesky/src/index.ts
index 0004b578fc8..6e3d20527e6 100644
--- a/packages/pieces/community/bluesky/src/index.ts
+++ b/packages/pieces/community/bluesky/src/index.ts
@@ -1,25 +1,125 @@
-import { createPiece, PieceAuth } from '@activepieces/pieces-framework';
-import { PieceCategory } from '@activepieces/pieces-framework';
+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';
+import { createCustomApiCallAction } from '@activepieces/pieces-common';
import { blueskyAuth } from './lib/common/auth';
+import { blueskyClient } from './lib/common/client';
import { createPost } from './lib/actions/create-post';
import { likePost } from './lib/actions/like-post';
import { repostPost } from './lib/actions/repost';
import { findPost } from './lib/actions/find-post';
import { findThread } from './lib/actions/find-thread';
+import { deletePost } from './lib/actions/delete-post';
+import { unlikePost } from './lib/actions/unlike-post';
+import { undoRepost } from './lib/actions/undo-repost';
+import { getProfile } from './lib/actions/get-profile';
+import { searchUsers } from './lib/actions/search-users';
+import { searchPosts } from './lib/actions/search-posts';
+import { followUser } from './lib/actions/follow-user';
+import { unfollowUser } from './lib/actions/unfollow-user';
+import { blockUser } from './lib/actions/block-user';
+import { unblockUser } from './lib/actions/unblock-user';
+import { muteUser } from './lib/actions/mute-user';
+import { unmuteUser } from './lib/actions/unmute-user';
+import { getAuthorFeed } from './lib/actions/get-author-feed';
+import { getTimeline } from './lib/actions/get-timeline';
+import { getPostLikes } from './lib/actions/get-post-likes';
+import { getPostReposts } from './lib/actions/get-post-reposts';
+import { getPostQuotes } from './lib/actions/get-post-quotes';
+import { listFollowers } from './lib/actions/list-followers';
+import { listFollows } from './lib/actions/list-follows';
+import { listNotifications } from './lib/actions/list-notifications';
+import { markNotificationsSeen } from './lib/actions/mark-notifications-seen';
+import { updateProfile } from './lib/actions/update-profile';
+import { listMyLists } from './lib/actions/list-my-lists';
+import { getListMembers } from './lib/actions/get-list-members';
+import { createList } from './lib/actions/create-list';
+import { deleteList } from './lib/actions/delete-list';
+import { addUserToList } from './lib/actions/add-user-to-list';
+import { removeUserFromList } from './lib/actions/remove-user-from-list';
+import { blueskyCreatePost } from './lib/actions/bluesky-create-post';
+import { blueskyLikePost } from './lib/actions/bluesky-like-post';
+import { blueskyRepostPost } from './lib/actions/bluesky-repost-post';
+import { blueskyGetPosts } from './lib/actions/bluesky-get-posts';
+import { blueskyResolveHandle } from './lib/actions/bluesky-resolve-handle';
+import { blueskyGetUnreadCount } from './lib/actions/bluesky-get-unread-count';
import { newPostsByAuthor } from './lib/triggers/new-posts-by-author';
import { newFollowerOnAccount } from './lib/triggers/new-follower-on-account';
import { newTimelinePosts } from './lib/triggers/new-timeline-posts';
import { newPost } from './lib/triggers/new-post';
-export { blueskyAuth } from './lib/common/auth';
-export { createBlueskyAgent } from './lib/common/client';
+import { newNotification } from './lib/triggers/new-notification';
+import { newMention } from './lib/triggers/new-mention';
export const bluesky = createPiece({
displayName: 'Bluesky',
+ description: 'Decentralized social network built on the AT Protocol.',
auth: blueskyAuth,
- minimumSupportedRelease: '0.36.1',
+ minimumSupportedRelease: '0.88.2',
logoUrl: 'https://cdn.activepieces.com/pieces/bluesky.png',
authors: ['Sanket6652'],
categories: [PieceCategory.COMMUNICATION],
- actions: [createPost, likePost, repostPost, findPost, findThread],
- triggers: [newPostsByAuthor, newFollowerOnAccount, newTimelinePosts, newPost],
+ actions: [
+ createPost,
+ likePost,
+ repostPost,
+ findPost,
+ findThread,
+ deletePost,
+ unlikePost,
+ undoRepost,
+ getProfile,
+ searchUsers,
+ searchPosts,
+ followUser,
+ unfollowUser,
+ blockUser,
+ unblockUser,
+ muteUser,
+ unmuteUser,
+ getAuthorFeed,
+ getTimeline,
+ getPostLikes,
+ getPostReposts,
+ getPostQuotes,
+ listFollowers,
+ listFollows,
+ listNotifications,
+ markNotificationsSeen,
+ updateProfile,
+ listMyLists,
+ getListMembers,
+ createList,
+ deleteList,
+ addUserToList,
+ removeUserFromList,
+ blueskyCreatePost,
+ blueskyLikePost,
+ blueskyRepostPost,
+ blueskyGetPosts,
+ blueskyResolveHandle,
+ blueskyGetUnreadCount,
+ createCustomApiCallAction({
+ auth: blueskyAuth,
+ baseUrl: (auth) => `${blueskyClient.normalizePdsHost(auth?.props.pdsHost)}/xrpc`,
+ description: 'Make a custom XRPC call to your Bluesky PDS, for example /app.bsky.actor.getProfile?actor=bsky.app',
+ authMapping: async (auth, propsValue) => {
+ const pdsHost = blueskyClient.normalizePdsHost(auth.props.pdsHost);
+ blueskyClient.assertSameOrigin({ url: customUrl(propsValue), pdsHost });
+ return { Authorization: `Bearer ${await blueskyClient.freshAccessToken(auth.props)}` };
+ },
+ }),
+ ],
+ triggers: [newPostsByAuthor, newFollowerOnAccount, newTimelinePosts, newPost, newNotification, newMention],
});
+
+function customUrl(propsValue: unknown): unknown {
+ if (typeof propsValue !== 'object' || propsValue === null || !('url' in propsValue)) {
+ return undefined;
+ }
+ const url: unknown = propsValue.url;
+ if (typeof url === 'object' && url !== null && 'url' in url) {
+ return url.url;
+ }
+ return url;
+}
+
+export { blueskyAuth } from './lib/common/auth';
+export { createBlueskyAgent } from './lib/common/client';
diff --git a/packages/pieces/community/bluesky/src/lib/actions/add-user-to-list.ts b/packages/pieces/community/bluesky/src/lib/actions/add-user-to-list.ts
new file mode 100644
index 00000000000..03911d29f03
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/add-user-to-list.ts
@@ -0,0 +1,43 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { addListMemberOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyRefs } from '../common/refs';
+
+export const addUserToList = createAction({
+ auth: blueskyAuth,
+ name: 'add_user_to_list',
+ classification: 'WRITE',
+ displayName: 'Add User to List',
+ description: 'Add an account to one of your lists',
+ audience: 'both',
+ outputSchema: addListMemberOutputSchema,
+ aiMetadata: {
+ description:
+ 'Adds a Bluesky account (handle, DID or profile link) to a list owned by the connected account, given the list\'s link or AT-URI. Use Remove User from List to undo. Not idempotent: calling it twice adds a second membership record for the same account.',
+ idempotent: false,
+ },
+ props: {
+ list: blueskyProps.listInputProperty(),
+ actor: blueskyProps.actorProperty({ description: 'Handle (alice.bsky.social), DID or profile link of the account to add.' }),
+ },
+ async run({ auth, propsValue }) {
+ blueskyRefs.parseListInput(propsValue.list);
+ blueskyRefs.parseActorInput(propsValue.actor);
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'add the account to the list',
+ fn: async (agent) => {
+ const me = blueskyClient.sessionDid(agent);
+ const list = await blueskyRefs.resolveListRef({ agent, input: propsValue.list });
+ if (list.did !== me) {
+ throw new Error('This list belongs to another account. You can only add members to lists owned by the connected account.');
+ }
+ const did = await blueskyRefs.resolveActorDid({ agent, input: propsValue.actor });
+ const response = await agent.app.bsky.graph.listitem.create({ repo: me }, { subject: did, list: list.uri, createdAt: new Date().toISOString() });
+ return { listItemUri: response.uri, listItemCid: response.cid, listUri: list.uri, did };
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/block-user.ts b/packages/pieces/community/bluesky/src/lib/actions/block-user.ts
new file mode 100644
index 00000000000..5423e9c32fd
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/block-user.ts
@@ -0,0 +1,43 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { blockOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyRefs } from '../common/refs';
+
+export const blockUser = createAction({
+ auth: blueskyAuth,
+ name: 'block_user',
+ classification: 'WRITE',
+ displayName: 'Block User',
+ description: 'Block a Bluesky account',
+ audience: 'both',
+ outputSchema: blockOutputSchema,
+ aiMetadata: {
+ description:
+ 'Blocks a Bluesky account given its handle, DID or profile link, so neither side sees or interacts with the other; blocks are public on Bluesky. Use Mute User for a private alternative and Unblock User to undo. Idempotent: an existing block is returned instead of creating another.',
+ idempotent: true,
+ },
+ props: {
+ actor: blueskyProps.actorProperty({ description: 'Handle (alice.bsky.social), DID or profile link of the account to block.' }),
+ },
+ async run({ auth, propsValue }) {
+ blueskyRefs.parseActorInput(propsValue.actor);
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'block the account',
+ fn: async (agent) => {
+ const me = blueskyClient.sessionDid(agent);
+ const profile = await blueskyRefs.fetchProfile({ agent, input: propsValue.actor });
+ if (profile.did === me) {
+ throw new Error('The connected account cannot block itself.');
+ }
+ const existing = profile.viewer?.blocking;
+ const blockUri =
+ existing ??
+ (await agent.app.bsky.graph.block.create({ repo: me }, { subject: profile.did, createdAt: new Date().toISOString() })).uri;
+ return { blockUri, did: profile.did, handle: profile.handle, alreadyBlocked: Boolean(existing) };
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/bluesky-create-post.ts b/packages/pieces/community/bluesky/src/lib/actions/bluesky-create-post.ts
new file mode 100644
index 00000000000..a7b5eae5592
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/bluesky-create-post.ts
@@ -0,0 +1,103 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import type { AppBskyFeedPost } from '@atproto/api';
+import { blueskyAuth } from '../common/auth';
+import { aiCreatePostOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyCompose } from '../common/compose';
+import { blueskyRefs } from '../common/refs';
+
+export const blueskyCreatePost = createAction({
+ auth: blueskyAuth,
+ name: 'bluesky_create_post',
+ classification: 'WRITE',
+ displayName: 'Create Post (AI)',
+ description: 'Publish one post with optional reply, quote, images, link card, labels and tags',
+ audience: 'ai',
+ outputSchema: aiCreatePostOutputSchema,
+ aiMetadata: {
+ description:
+ 'Publishes one new post from the connected Bluesky account: text up to 300 visible characters, with an optional reply target, quoted post, up to 4 image URLs with alt text, a link card, self-labels (sexual, nudity, porn, graphic-media), up to 3 language codes and up to 8 tags. Use for a single post or reply; use Delete Post to remove one. Not idempotent: each call creates a new post.',
+ idempotent: false,
+ },
+ props: {
+ text: Property.LongText({ displayName: 'Text', description: 'Post text, at most 300 visible characters. Links, @mentions and #hashtags become clickable.', required: true }),
+ langs: Property.Array({ displayName: 'Languages', description: 'Up to 3 BCP-47 language codes, for example en or pt-BR.', required: false }),
+ replyTo: Property.ShortText({ displayName: 'Reply To', description: 'Link or at:// URI of the post to reply to.', required: false }),
+ quote: Property.ShortText({ displayName: 'Quote Post', description: 'Link or at:// URI of a post to quote.', required: false }),
+ imageUrls: Property.Array({ displayName: 'Image URLs', description: 'Up to 4 public image URLs (PNG, JPEG, GIF or WebP, max 1 MB each).', required: false }),
+ imageAlts: Property.Array({ displayName: 'Image Alt Texts', description: 'Alt text for each image, in the same order.', required: false }),
+ linkUrl: Property.ShortText({ displayName: 'Link Card URL', description: 'A URL to show as a link preview card. Ignored when images are given.', required: false }),
+ selfLabels: Property.StaticMultiSelectDropdown({
+ displayName: 'Content Labels',
+ required: false,
+ options: {
+ options: [
+ { label: 'Suggestive (sexual)', value: 'sexual' },
+ { label: 'Nudity', value: 'nudity' },
+ { label: 'Adult (porn)', value: 'porn' },
+ { label: 'Graphic Media', value: 'graphic-media' },
+ ],
+ },
+ }),
+ tags: Property.Array({ displayName: 'Tags', description: 'Up to 8 extra hashtags stored on the post without appearing in the text (without #).', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const text = propsValue.text;
+ if (text.trim() === '') {
+ throw new Error('Text is empty.');
+ }
+ blueskyCompose.assertPostLength({ text, label: 'The post text' });
+ const langs = blueskyCompose.normalizeLangs(propsValue.langs ?? []);
+ const tags = blueskyCompose.normalizeTags(propsValue.tags ?? []);
+ const labels = blueskyCompose.selfLabels(blueskyCompose.stringList(propsValue.selfLabels));
+ const alts = Array.isArray(propsValue.imageAlts) ? propsValue.imageAlts : [];
+ const images = blueskyCompose.stringList(propsValue.imageUrls).map((url, index) => ({
+ url,
+ alt: typeof alts[index] === 'string' ? String(alts[index]) : '',
+ }));
+ if (images.length > blueskyCompose.MAX_IMAGES) {
+ throw new Error(`Bluesky allows at most ${blueskyCompose.MAX_IMAGES} images per post; got ${images.length}.`);
+ }
+ if (propsValue.replyTo?.trim()) {
+ blueskyRefs.parsePostInput(propsValue.replyTo);
+ }
+ if (propsValue.quote?.trim()) {
+ blueskyRefs.parsePostInput(propsValue.quote);
+ }
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'create the post',
+ fn: async (agent) => {
+ const richText = await blueskyCompose.buildRichText({ agent, text });
+ const reply = propsValue.replyTo?.trim() ? await blueskyCompose.replyRefs({ agent, input: propsValue.replyTo }) : undefined;
+ const quote = propsValue.quote?.trim() ? await blueskyCompose.quoteRef({ agent, input: propsValue.quote }) : undefined;
+ const media =
+ images.length > 0
+ ? await blueskyCompose.uploadImages({ agent, images })
+ : propsValue.linkUrl?.trim()
+ ? await blueskyCompose.buildLinkCard({ agent, url: propsValue.linkUrl.trim() })
+ : undefined;
+ const record: AppBskyFeedPost.Record = {
+ $type: 'app.bsky.feed.post',
+ text: richText.text,
+ facets: richText.facets,
+ createdAt: new Date().toISOString(),
+ ...(langs.length > 0 ? { langs } : {}),
+ ...(tags.length > 0 ? { tags } : {}),
+ ...(labels ? { labels } : {}),
+ ...(reply ? { reply } : {}),
+ ...(quote || media ? { embed: blueskyCompose.combineEmbed({ quote, media }) } : {}),
+ };
+ const response = await agent.post(record);
+ return {
+ uri: response.uri,
+ cid: response.cid,
+ url: blueskyRefs.postWebUrl({ uri: response.uri, handle: agent.session?.handle }),
+ isReply: reply !== undefined,
+ quotedUri: quote?.uri ?? null,
+ createdAt: record.createdAt,
+ };
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/bluesky-get-posts.ts b/packages/pieces/community/bluesky/src/lib/actions/bluesky-get-posts.ts
new file mode 100644
index 00000000000..b484252126b
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/bluesky-get-posts.ts
@@ -0,0 +1,50 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { getPostsOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyRefs } from '../common/refs';
+import { blueskyMappers } from '../common/mappers';
+import { blueskyCompose } from '../common/compose';
+
+const MAX_POSTS = 25;
+
+export const blueskyGetPosts = createAction({
+ auth: blueskyAuth,
+ name: 'bluesky_get_posts',
+ classification: 'READ',
+ displayName: 'Get Posts (AI)',
+ description: 'Fetch up to 25 posts by link or AT-URI in one call',
+ audience: 'ai',
+ outputSchema: getPostsOutputSchema,
+ aiMetadata: {
+ description:
+ 'Fetches up to 25 Bluesky posts in one call, given their bsky.app links or AT-URIs, with text, author and engagement counts; inputs that are deleted or hidden are listed in notFound. Use Find Thread for replies around a post. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ posts: Property.Array({ displayName: 'Posts', description: 'Up to 25 post links or at:// URIs.', required: true }),
+ },
+ async run({ auth, propsValue }) {
+ const inputs = blueskyCompose.stringList(propsValue.posts);
+ if (inputs.length === 0 || inputs.length > MAX_POSTS) {
+ throw new Error(`Give between 1 and ${MAX_POSTS} posts; got ${inputs.length}.`);
+ }
+ inputs.forEach((input) => blueskyRefs.parsePostInput(input));
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'get the posts',
+ fn: async (agent) => {
+ const refs: { input: string; uri: string }[] = [];
+ for (const input of inputs) {
+ refs.push({ input, uri: (await blueskyRefs.resolvePostRef({ agent, input })).uri });
+ }
+ const response = await agent.getPosts({ uris: [...new Set(refs.map((ref) => ref.uri))] });
+ const found = new Set(response.data.posts.map((post) => post.uri));
+ return {
+ posts: response.data.posts.map((post) => ({ ...blueskyMappers.postBase(post), text: blueskyMappers.recordText(post.record) })),
+ notFound: refs.filter((ref) => !found.has(ref.uri)).map((ref) => ref.input),
+ };
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/bluesky-get-unread-count.ts b/packages/pieces/community/bluesky/src/lib/actions/bluesky-get-unread-count.ts
new file mode 100644
index 00000000000..886a965208c
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/bluesky-get-unread-count.ts
@@ -0,0 +1,30 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { unreadCountOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+
+export const blueskyGetUnreadCount = createAction({
+ auth: blueskyAuth,
+ name: 'bluesky_get_unread_count',
+ classification: 'READ',
+ displayName: 'Get Unread Notification Count (AI)',
+ description: 'Count unread notifications',
+ audience: 'ai',
+ outputSchema: unreadCountOutputSchema,
+ aiMetadata: {
+ description:
+ 'Returns how many notifications of the connected Bluesky account are unread. Use List Notifications to read them and Mark Notifications as Seen to reset the count. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {},
+ async run({ auth }) {
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'count unread notifications',
+ fn: async (agent) => {
+ const response = await agent.countUnreadNotifications();
+ return { count: response.data.count, checkedAt: new Date().toISOString() };
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/bluesky-like-post.ts b/packages/pieces/community/bluesky/src/lib/actions/bluesky-like-post.ts
new file mode 100644
index 00000000000..93923215fed
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/bluesky-like-post.ts
@@ -0,0 +1,44 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { aiLikeOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyRefs } from '../common/refs';
+import { blueskyCompose } from '../common/compose';
+
+export const blueskyLikePost = createAction({
+ auth: blueskyAuth,
+ name: 'bluesky_like_post',
+ classification: 'WRITE',
+ displayName: 'Like Post (AI)',
+ description: 'Like a post, or return the existing like',
+ audience: 'ai',
+ outputSchema: aiLikeOutputSchema,
+ aiMetadata: {
+ description:
+ 'Likes a Bluesky post given its bsky.app link or AT-URI, and returns the existing like if the account already liked it. Use Unlike Post to undo. Idempotent: a repeat call does not create a second like.',
+ idempotent: true,
+ },
+ props: {
+ post: blueskyProps.postInputProperty(),
+ },
+ async run({ auth, propsValue }) {
+ blueskyRefs.parsePostInput(propsValue.post);
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'like the post',
+ fn: async (agent) => {
+ const post = await blueskyCompose.fetchPostView({ agent, input: propsValue.post });
+ const existing = post.viewer?.like;
+ const likeUri = existing ?? (await agent.like(post.uri, post.cid)).uri;
+ return {
+ likeUri,
+ postUri: post.uri,
+ postCid: post.cid,
+ postUrl: blueskyRefs.postWebUrl({ uri: post.uri, handle: post.author.handle }),
+ alreadyLiked: Boolean(existing),
+ };
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/bluesky-repost-post.ts b/packages/pieces/community/bluesky/src/lib/actions/bluesky-repost-post.ts
new file mode 100644
index 00000000000..07f04c18070
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/bluesky-repost-post.ts
@@ -0,0 +1,44 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { aiRepostOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyRefs } from '../common/refs';
+import { blueskyCompose } from '../common/compose';
+
+export const blueskyRepostPost = createAction({
+ auth: blueskyAuth,
+ name: 'bluesky_repost_post',
+ classification: 'WRITE',
+ displayName: 'Repost Post (AI)',
+ description: 'Repost a post, or return the existing repost',
+ audience: 'ai',
+ outputSchema: aiRepostOutputSchema,
+ aiMetadata: {
+ description:
+ 'Reposts a Bluesky post to the connected account given its bsky.app link or AT-URI, and returns the existing repost if it was already reposted. Use Undo Repost to undo; use Create Post with a quote to add a comment. Idempotent: a repeat call does not create a second repost.',
+ idempotent: true,
+ },
+ props: {
+ post: blueskyProps.postInputProperty(),
+ },
+ async run({ auth, propsValue }) {
+ blueskyRefs.parsePostInput(propsValue.post);
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'repost the post',
+ fn: async (agent) => {
+ const post = await blueskyCompose.fetchPostView({ agent, input: propsValue.post });
+ const existing = post.viewer?.repost;
+ const repostUri = existing ?? (await agent.repost(post.uri, post.cid)).uri;
+ return {
+ repostUri,
+ postUri: post.uri,
+ postCid: post.cid,
+ postUrl: blueskyRefs.postWebUrl({ uri: post.uri, handle: post.author.handle }),
+ alreadyReposted: Boolean(existing),
+ };
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/bluesky-resolve-handle.ts b/packages/pieces/community/bluesky/src/lib/actions/bluesky-resolve-handle.ts
new file mode 100644
index 00000000000..990fdf5edab
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/bluesky-resolve-handle.ts
@@ -0,0 +1,37 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { resolveHandleOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyRefs } from '../common/refs';
+
+export const blueskyResolveHandle = createAction({
+ auth: blueskyAuth,
+ name: 'bluesky_resolve_handle',
+ classification: 'READ',
+ displayName: 'Resolve Handle (AI)',
+ description: 'Turn a Bluesky handle into its permanent DID',
+ audience: 'ai',
+ outputSchema: resolveHandleOutputSchema,
+ aiMetadata: {
+ description:
+ 'Resolves a Bluesky handle (or profile link) to the account\'s permanent DID, which stays the same when the handle changes. Use Get Profile when you also need the name, bio or counts. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ handle: Property.ShortText({ displayName: 'Handle', description: 'For example alice.bsky.social, @alice or https://bsky.app/profile/alice.bsky.social.', required: true }),
+ },
+ async run({ auth, propsValue }) {
+ const handle = blueskyRefs.parseActorInput(propsValue.handle);
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'resolve the handle',
+ fn: async (agent) => {
+ if (blueskyRefs.isDid(handle)) {
+ return { handle: null, did: handle };
+ }
+ const did = await blueskyRefs.resolveRepoDid({ agent, repo: handle });
+ return { handle, did };
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/create-list.ts b/packages/pieces/community/bluesky/src/lib/actions/create-list.ts
new file mode 100644
index 00000000000..3c0f63b6193
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/create-list.ts
@@ -0,0 +1,74 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { createListOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyRefs } from '../common/refs';
+import { blueskyCompose } from '../common/compose';
+
+const MAX_LIST_NAME = 64;
+const MAX_LIST_DESCRIPTION = 300;
+
+export const createList = createAction({
+ auth: blueskyAuth,
+ name: 'create_list',
+ classification: 'WRITE',
+ displayName: 'Create List',
+ description: 'Create a user list or moderation list',
+ audience: 'both',
+ outputSchema: createListOutputSchema,
+ aiMetadata: {
+ description:
+ 'Creates a new list owned by the connected Bluesky account: a user (curation) list for feeds and grouping, or a moderation list for bulk mute/block. Use Add User to List afterwards to fill it. Not idempotent: each call creates another list, even with the same name.',
+ idempotent: false,
+ },
+ props: {
+ name: Property.ShortText({ displayName: 'Name', description: `List name (max ${MAX_LIST_NAME} characters).`, required: true }),
+ purpose: Property.StaticDropdown({
+ displayName: 'Kind',
+ required: true,
+ defaultValue: 'app.bsky.graph.defs#curatelist',
+ options: {
+ options: [
+ { label: 'User list (curation)', value: 'app.bsky.graph.defs#curatelist' },
+ { label: 'Moderation list', value: 'app.bsky.graph.defs#modlist' },
+ ],
+ },
+ }),
+ description: Property.LongText({ displayName: 'Description', description: `Optional (max ${MAX_LIST_DESCRIPTION} characters).`, required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const name = propsValue.name.trim();
+ if (name === '' || blueskyCompose.graphemeLength(name) > MAX_LIST_NAME) {
+ throw new Error(`Name must be between 1 and ${MAX_LIST_NAME} characters.`);
+ }
+ const description = propsValue.description?.trim() ?? '';
+ if (blueskyCompose.graphemeLength(description) > MAX_LIST_DESCRIPTION) {
+ throw new Error(`Description must be at most ${MAX_LIST_DESCRIPTION} characters.`);
+ }
+ const purpose = propsValue.purpose;
+ if (purpose !== 'app.bsky.graph.defs#curatelist' && purpose !== 'app.bsky.graph.defs#modlist') {
+ throw new Error('Kind must be a user list or a moderation list.');
+ }
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'create the list',
+ fn: async (agent) => {
+ const me = blueskyClient.sessionDid(agent);
+ const createdAt = new Date().toISOString();
+ const response = await agent.app.bsky.graph.list.create(
+ { repo: me },
+ { name, purpose, createdAt, ...(description !== '' ? { description } : {}) },
+ );
+ return {
+ uri: response.uri,
+ cid: response.cid,
+ url: blueskyRefs.postWebUrl({ uri: response.uri, handle: agent.session?.handle }),
+ name,
+ purpose,
+ description,
+ createdAt,
+ };
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/create-post.ts b/packages/pieces/community/bluesky/src/lib/actions/create-post.ts
index 7ffb712d08b..a9eb218ad9c 100644
--- a/packages/pieces/community/bluesky/src/lib/actions/create-post.ts
+++ b/packages/pieces/community/bluesky/src/lib/actions/create-post.ts
@@ -1,159 +1,11 @@
import { createAction, Property } from '@activepieces/pieces-framework';
+import type { AppBskyFeedPost, AtpAgent } from '@atproto/api';
import { blueskyAuth } from '../common/auth';
import { createPostOutputSchema } from '../output-schemas';
-import { createBlueskyAgent } from '../common/client';
-import { RichText } from '@atproto/api';
-import {
- postTextProperty,
- postTypeDropdown,
- simpleLanguageDropdown,
- imageUrlsProperty,
- imageDescriptionsProperty,
- linkUrlProperty,
- replyToPostProperty,
- contentWarningDropdown,
- audienceDropdown
-} from '../common/props';
-
-const videoUrlProperty = Property.ShortText({
- displayName: 'Video URL',
- description: 'Link to video file (MP4, max 100MB)',
- required: false,
-});
-
-const videoAltTextProperty = Property.LongText({
- displayName: 'Video Description',
- description: 'Describe the video for accessibility',
- required: false,
-});
-
-const videoCaptionsProperty = Property.Array({
- displayName: 'Video Captions',
- description: 'Caption file URLs (optional)',
- required: false,
-});
-
-const threadContentProperty = Property.Array({
- displayName: 'Thread Posts',
- description: 'Create additional connected posts',
- required: false,
-});
-
-const additionalHashtagsProperty = Property.ShortText({
- displayName: 'Hashtags',
- description: 'Add hashtags (e.g., tech,bluesky)',
- required: false,
-});
-
-async function parsePostUrl(url: string, agent: any): Promise<string> {
- if (url.startsWith('at://')) {
- return url;
- }
-
- const urlMatch = url.match(/https?:\/\/bsky\.app\/profile\/([^/]+)\/post\/([^/?]+)/);
- if (urlMatch) {
- const handle = urlMatch[1];
- const postId = urlMatch[2];
-
- const didDoc = await agent.resolveHandle({ handle });
- return `at://${didDoc.data.did}/app.bsky.feed.post/${postId}`;
- }
-
- throw new Error('Invalid post URL format. Please use a valid Bluesky post URL.');
-}
-
-async function getReplyRefs(postUri: string, agent: any): Promise<any> {
- try {
- const postThread = await agent.getPostThread({ uri: postUri });
- const post = postThread.thread.post;
-
- if (!post) {
- throw new Error('Post not found');
- }
-
- const parentReply = post.record.reply;
-
- return {
- root: parentReply?.root || { uri: post.uri, cid: post.cid },
- parent: { uri: post.uri, cid: post.cid },
- };
- } catch (error) {
- throw new Error(`Failed to resolve reply: ${error instanceof Error ? error.message : 'Unknown error'}`);
- }
-}
-
-async function createEnhancedLinkEmbed(url: string, agent: any): Promise<any> {
- try {
- const response = await fetch(url, {
- headers: {
- 'User-Agent': 'Mozilla/5.0 (compatible; Activepieces-Bot/1.0)',
- },
- });
-
- if (!response.ok) {
- throw new Error(`HTTP ${response.status}`);
- }
-
- const html = await response.text();
-
- const titleMatch = html.match(/<meta\s+property="og:title"\s+content="([^"]*)"[^>]*>/i) ||
- html.match(/<title[^>]*>([^<]*)<\/title>/i);
- const title = titleMatch ? titleMatch[1].trim() : url;
-
- const descMatch = html.match(/<meta\s+property="og:description"\s+content="([^"]*)"[^>]*>/i) ||
- html.match(/<meta\s+name="description"\s+content="([^"]*)"[^>]*>/i);
- const description = descMatch ? descMatch[1].trim() : '';
-
- const imageMatch = html.match(/<meta\s+property="og:image"\s+content="([^"]*)"[^>]*>/i);
-
- const external: any = {
- uri: url,
- title: title.length > 0 ? title : url,
- description: description.length > 0 ? description : 'Shared link',
- };
-
- if (imageMatch && imageMatch[1]) {
- try {
- let imageUrl = imageMatch[1];
-
- if (imageUrl.startsWith('/')) {
- const urlObj = new URL(url);
- imageUrl = `${urlObj.protocol}//${urlObj.host}${imageUrl}`;
- } else if (!imageUrl.startsWith('http')) {
- imageUrl = new URL(imageUrl, url).href;
- }
-
- const imageResponse = await fetch(imageUrl);
- if (imageResponse.ok) {
- const imageBlob = await imageResponse.blob();
-
- if (imageBlob.size <= 1000000 && imageBlob.type.startsWith('image/')) {
- const thumbResponse = await agent.uploadBlob(imageBlob, {
- encoding: imageBlob.type,
- });
- external.thumb = thumbResponse.data.blob;
- }
- }
- } catch (thumbError) {
- console.warn('Failed to upload link thumbnail:', thumbError);
- }
- }
-
- return {
- $type: 'app.bsky.embed.external',
- external,
- };
- } catch (error) {
- return {
- $type: 'app.bsky.embed.external',
- external: {
- uri: url,
- title: url,
- description: 'Shared link',
- },
- };
- }
-}
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyCompose } from '../common/compose';
+import { blueskyRefs } from '../common/refs';
export const createPost = createAction({
auth: blueskyAuth,
@@ -161,287 +13,204 @@ export const createPost = createAction({
classification: 'WRITE',
displayName: 'Create Post',
description: 'Create a new post on Bluesky',
- audience: 'both',
+ audience: 'human',
outputSchema: createPostOutputSchema,
aiMetadata: {
- description: 'Publishes a new post to the authenticated Bluesky account, with optional images, video, an external link card, content-warning labels, and chained thread replies. Use to broadcast content on Bluesky; provide the post text (max 300 characters after hashtags/links are expanded). Not idempotent — each call creates a brand-new post.',
+ description:
+ 'Publishes a new post to the authenticated Bluesky account, with optional images, video, an external link card, a quoted post, content-warning labels, and chained thread replies. Use to broadcast content on Bluesky, including threads and video; for a single post prefer Create Post (AI). The post text may be at most 300 visible characters after hashtags are appended, and every thread text is checked before anything is posted. Not idempotent: each call creates a brand-new post.',
idempotent: false,
},
props: {
- postType: postTypeDropdown,
- text: postTextProperty,
- language: simpleLanguageDropdown,
- imageUrls: imageUrlsProperty,
- imageDescriptions: imageDescriptionsProperty,
- videoUrl: videoUrlProperty,
- videoAltText: videoAltTextProperty,
- videoCaptions: videoCaptionsProperty,
- linkUrl: linkUrlProperty,
- replyToPost: replyToPostProperty,
- threadContent: threadContentProperty,
- additionalHashtags: additionalHashtagsProperty,
- contentWarnings: contentWarningDropdown,
- audience: audienceDropdown,
+ postType: blueskyProps.postTypeDropdown,
+ text: blueskyProps.postTextProperty,
+ language: blueskyProps.simpleLanguageDropdown,
+ imageUrls: blueskyProps.imageUrlsProperty,
+ imageDescriptions: blueskyProps.imageDescriptionsProperty,
+ videoUrl: Property.ShortText({
+ displayName: 'Video URL',
+ description: 'Link to a video file (MP4, max 50 MB). Bluesky only accepts videos from accounts with a verified email address.',
+ required: false,
+ }),
+ videoAltText: Property.LongText({
+ displayName: 'Video Description',
+ description: 'Describe the video for accessibility',
+ required: false,
+ }),
+ videoCaptions: Property.Array({
+ displayName: 'Video Captions',
+ description: 'Caption file URLs in WebVTT (.vtt) format (optional)',
+ required: false,
+ }),
+ videoCaptionLanguage: Property.ShortText({
+ displayName: 'Video Caption Language',
+ description: 'Language code of the caption files, for example en or de. Defaults to en.',
+ required: false,
+ defaultValue: 'en',
+ }),
+ linkUrl: blueskyProps.linkUrlProperty,
+ replyToPost: blueskyProps.replyToPostProperty,
+ quotePostUrl: Property.ShortText({
+ displayName: 'Quote Post URL',
+ description: 'Link or at:// URI of a post to quote (embed) in this post. Works together with images, video or a link.',
+ required: false,
+ }),
+ threadContent: Property.Array({
+ displayName: 'Thread Posts',
+ description: 'Create additional connected posts. Each must be 300 characters or fewer.',
+ required: false,
+ }),
+ additionalHashtags: Property.ShortText({
+ displayName: 'Hashtags',
+ description: 'Add hashtags (e.g., tech,bluesky). At most 8.',
+ required: false,
+ }),
+ contentWarnings: blueskyProps.contentWarningDropdown,
+ audience: blueskyProps.audienceDropdown,
},
async run({ auth, propsValue }) {
- const {
- text,
- language,
- imageUrls,
+ const {
+ text,
+ language,
+ imageUrls,
imageDescriptions,
videoUrl,
videoAltText,
videoCaptions,
- linkUrl,
+ videoCaptionLanguage,
+ linkUrl,
replyToPost,
+ quotePostUrl,
threadContent,
additionalHashtags,
contentWarnings,
- audience
} = propsValue;
- try {
- const agent = await createBlueskyAgent(auth.props);
-
- let processedText = text;
- if (additionalHashtags && additionalHashtags.trim()) {
- const hashtags = additionalHashtags
- .split(',')
- .map(tag => tag.trim().startsWith('#') ? tag.trim() : `#${tag.trim()}`)
- .filter(tag => tag.length > 1)
- .join(' ');
-
- if (hashtags) {
- processedText += ` ${hashtags}`;
- }
- }
+ const tags = additionalHashtags ? blueskyCompose.normalizeTags([additionalHashtags]) : [];
+ const fullText = tags.length > 0 ? `${text} ${tags.map((tag) => `#${tag}`).join(' ')}` : text;
+ blueskyCompose.assertPostLength({ text: fullText, label: 'The post text (including hashtags)' });
+ const threadTexts = blueskyCompose.stringList(threadContent);
+ threadTexts.forEach((threadText, index) =>
+ blueskyCompose.assertPostLength({ text: threadText, label: `Thread post ${index + 1}` }),
+ );
+ const labels = blueskyCompose.selfLabels(blueskyCompose.mapContentWarnings(contentWarnings ?? []));
+ const langs = language && language !== 'other' ? [language] : undefined;
+ const images = blueskyCompose.stringList(imageUrls).map((url, index) => ({
+ url,
+ alt: typeof imageDescriptions?.[index] === 'string' ? String(imageDescriptions[index]) : '',
+ }));
+ if (images.length > blueskyCompose.MAX_IMAGES) {
+ throw new Error(`Bluesky allows at most ${blueskyCompose.MAX_IMAGES} images per post; got ${images.length}.`);
+ }
- const richText = new RichText({ text: processedText });
- await richText.detectFacets(agent);
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'create the post',
+ fn: async (agent) => {
+ const richText = await blueskyCompose.buildRichText({ agent, text: fullText });
+ const reply = replyToPost && replyToPost.trim() ? await blueskyCompose.replyRefs({ agent, input: replyToPost }) : undefined;
+ const quote = quotePostUrl && quotePostUrl.trim() ? await blueskyCompose.quoteRef({ agent, input: quotePostUrl }) : undefined;
+ const media = await buildMedia({
+ agent,
+ videoUrl,
+ videoAltText,
+ captionUrls: blueskyCompose.stringList(videoCaptions),
+ captionLanguage: videoCaptionLanguage && videoCaptionLanguage.trim() ? videoCaptionLanguage.trim() : 'en',
+ images,
+ linkUrl,
+ });
+ const postRecord: AppBskyFeedPost.Record = {
+ $type: 'app.bsky.feed.post',
+ text: richText.text,
+ facets: richText.facets,
+ createdAt: new Date().toISOString(),
+ ...(tags.length > 0 ? { tags } : {}),
+ ...(labels ? { labels } : {}),
+ ...(langs ? { langs } : {}),
+ ...(reply ? { reply } : {}),
+ ...(quote || media ? { embed: blueskyCompose.combineEmbed({ quote, media }) } : {}),
+ };
+ const mainPost = await agent.post(postRecord);
+ const thread = await postThread({ agent, root: mainPost, texts: threadTexts, langs, labels });
+ return {
+ success: true,
+ mainPost: { uri: mainPost.uri, cid: mainPost.cid },
+ url: blueskyRefs.postWebUrl({ uri: mainPost.uri, handle: agent.session?.handle }),
+ threadPosts: thread.posted,
+ failedThreadPosts: thread.failed,
+ totalPosts: 1 + thread.posted.length,
+ record: postRecord,
+ };
+ },
+ });
+ },
+});
- if (richText.length > 300) {
- throw new Error('Post text cannot exceed 300 characters');
- }
+async function buildMedia({
+ agent,
+ videoUrl,
+ videoAltText,
+ captionUrls,
+ captionLanguage,
+ images,
+ linkUrl,
+}: {
+ agent: AtpAgent;
+ videoUrl: string | undefined;
+ videoAltText: string | undefined;
+ captionUrls: string[];
+ captionLanguage: string;
+ images: { url: string; alt: string }[];
+ linkUrl: string | undefined;
+}) {
+ if (videoUrl && videoUrl.trim()) {
+ return blueskyCompose.uploadVideo({
+ agent,
+ url: videoUrl.trim(),
+ alt: videoAltText?.trim() || undefined,
+ captions: captionUrls.map((url) => ({ url, lang: captionLanguage })),
+ });
+ }
+ if (images.length > 0) {
+ return blueskyCompose.uploadImages({ agent, images });
+ }
+ if (linkUrl && linkUrl.trim()) {
+ return blueskyCompose.buildLinkCard({ agent, url: linkUrl.trim() });
+ }
+ return undefined;
+}
- const postRecord: any = {
+async function postThread({
+ agent,
+ root,
+ texts,
+ langs,
+ labels,
+}: {
+ agent: AtpAgent;
+ root: { uri: string; cid: string };
+ texts: string[];
+ langs: string[] | undefined;
+ labels: AppBskyFeedPost.Record['labels'];
+}): Promise<{ posted: { uri: string; cid: string }[]; failed: { index: number; error: string }[] }> {
+ const posted: { uri: string; cid: string }[] = [];
+ const failed: { index: number; error: string }[] = [];
+ let parent = root;
+ for (const [index, threadText] of texts.entries()) {
+ try {
+ const richText = await blueskyCompose.buildRichText({ agent, text: threadText });
+ const response = await agent.post({
text: richText.text,
facets: richText.facets,
createdAt: new Date().toISOString(),
- };
-
- if (additionalHashtags && additionalHashtags.trim()) {
- const tagList = additionalHashtags
- .split(',')
- .map(tag => tag.trim().replace(/^#/, ''))
- .filter(tag => tag.length > 0);
-
- if (tagList.length > 0) {
- postRecord.tags = tagList;
- }
- }
-
- if (contentWarnings && contentWarnings.length > 0) {
- postRecord.labels = {
- $type: 'com.atproto.label.defs#selfLabels',
- values: contentWarnings.map((warning: string) => ({ val: warning })),
- };
- }
-
- if (language && language !== 'other') {
- postRecord.langs = [language];
- }
-
- if (replyToPost && replyToPost.trim()) {
- const postUri = await parsePostUrl(replyToPost, agent);
- postRecord.reply = await getReplyRefs(postUri, agent);
- }
-
- if (videoUrl && videoUrl.trim()) {
- try {
- const videoResponse = await fetch(videoUrl);
- if (!videoResponse.ok) {
- throw new Error(`Failed to fetch video from ${videoUrl}`);
- }
-
- const videoBlob = await videoResponse.blob();
-
- if (!videoBlob.type.startsWith('video/')) {
- throw new Error('File must be a video format');
- }
-
- if (videoBlob.size > 100000000) {
- throw new Error(`Video is too large (max 100MB), got ${Math.round(videoBlob.size / 1000000)}MB`);
- }
-
- const videoBlobResponse = await agent.uploadBlob(videoBlob, {
- encoding: videoBlob.type,
- });
-
- const captionObjects = [];
- if (videoCaptions && videoCaptions.length > 0) {
- for (let i = 0; i < videoCaptions.length; i++) {
- const captionUrl = videoCaptions[i] as string;
- try {
- const captionResponse = await fetch(captionUrl);
- if (!captionResponse.ok) continue;
-
- const captionBlob = await captionResponse.blob();
- const captionBlobResponse = await agent.uploadBlob(captionBlob, {
- encoding: 'text/vtt',
- });
-
- captionObjects.push({
- lang: 'en',
- file: captionBlobResponse.data.blob,
- });
- } catch (error) {
- console.warn(`Failed to upload caption ${i + 1}:`, error);
- }
- }
- }
-
- const videoEmbed: any = {
- $type: 'app.bsky.embed.video',
- video: videoBlobResponse.data.blob,
- };
-
- if (videoAltText && videoAltText.trim()) {
- videoEmbed.alt = videoAltText.trim();
- }
-
- if (captionObjects.length > 0) {
- videoEmbed.captions = captionObjects;
- }
-
- postRecord.embed = videoEmbed;
- } catch (error) {
- throw new Error(`Failed to process video: ${error instanceof Error ? error.message : 'Unknown error'}`);
- }
- }
- else if (imageUrls && imageUrls.length > 0) {
- if (imageUrls.length > 4) {
- throw new Error('Maximum of 4 images allowed per post');
- }
-
- const images = [];
- for (let i = 0; i < imageUrls.length; i++) {
- const imageUrl = imageUrls[i] as string;
- const altText = (imageDescriptions?.[i] as string) || '';
-
- try {
- const imageResponse = await fetch(imageUrl);
- if (!imageResponse.ok) {
- throw new Error(`Failed to fetch image from ${imageUrl}`);
- }
-
- const imageBlob = await imageResponse.blob();
-
- if (imageBlob.size > 1000000) {
- throw new Error(`Image at ${imageUrl} is too large (max 1MB)`);
- }
-
- const blobResponse = await agent.uploadBlob(imageBlob, {
- encoding: imageBlob.type,
- });
-
- images.push({
- alt: altText,
- image: blobResponse.data.blob,
- });
- } catch (error) {
- throw new Error(`Failed to upload image ${i + 1}: ${error instanceof Error ? error.message : 'Unknown error'}`);
- }
- }
-
- postRecord.embed = {
- $type: 'app.bsky.embed.images',
- images,
- };
- }
-
- else if (linkUrl && linkUrl.trim()) {
- try {
- const linkEmbed = await createEnhancedLinkEmbed(linkUrl, agent);
- postRecord.embed = linkEmbed;
- } catch (error) {
- console.warn('Failed to fetch link metadata, using basic embed:', error);
- postRecord.embed = {
- $type: 'app.bsky.embed.external',
- external: {
- uri: linkUrl,
- title: linkUrl,
- description: 'Shared link',
- },
- };
- }
- }
-
- const mainPostResponse = await agent.post(postRecord);
- const createdPosts = [mainPostResponse];
-
- if (threadContent && threadContent.length > 0) {
- let previousPost = mainPostResponse;
-
- for (let i = 0; i < threadContent.length; i++) {
- const threadText = threadContent[i] as string;
- if (!threadText || !threadText.trim()) continue;
-
- try {
- const threadRichText = new RichText({ text: threadText });
- await threadRichText.detectFacets(agent);
-
- if (threadRichText.length > 300) {
- console.warn(`Thread post ${i + 1} exceeds 300 characters, skipping`);
- continue;
- }
-
- const threadPostRecord: any = {
- text: threadRichText.text,
- facets: threadRichText.facets,
- createdAt: new Date().toISOString(),
- reply: {
- root: { uri: mainPostResponse.uri, cid: mainPostResponse.cid },
- parent: { uri: previousPost.uri, cid: previousPost.cid },
- },
- };
-
- if (language && language !== 'other') {
- threadPostRecord.langs = [language];
- }
-
- if (contentWarnings && contentWarnings.length > 0) {
- threadPostRecord.labels = {
- $type: 'com.atproto.label.defs#selfLabels',
- values: contentWarnings.map((warning: string) => ({ val: warning })),
- };
- }
-
- const threadResponse = await agent.post(threadPostRecord);
- createdPosts.push(threadResponse);
- previousPost = threadResponse;
-
- await new Promise(resolve => setTimeout(resolve, 100));
- } catch (threadError) {
- console.warn(`Failed to create thread post ${i + 1}:`, threadError);
- }
- }
- }
-
- return {
- success: true,
- mainPost: {
- uri: mainPostResponse.uri,
- cid: mainPostResponse.cid,
- },
- threadPosts: createdPosts.slice(1).map(post => ({
- uri: post.uri,
- cid: post.cid,
- })),
- totalPosts: createdPosts.length,
- record: postRecord,
- };
+ reply: { root: { uri: root.uri, cid: root.cid }, parent: { uri: parent.uri, cid: parent.cid } },
+ ...(langs ? { langs } : {}),
+ ...(labels ? { labels } : {}),
+ });
+ posted.push({ uri: response.uri, cid: response.cid });
+ parent = response;
} catch (error) {
- throw new Error(`Failed to create post: ${error instanceof Error ? error.message : 'Unknown error'}`);
+ failed.push({ index: index + 1, error: blueskyClient.toBlueskyError({ error, action: `create thread post ${index + 1}` }).message });
}
- },
-});
+ }
+ return { posted, failed };
+}
diff --git a/packages/pieces/community/bluesky/src/lib/actions/delete-list.ts b/packages/pieces/community/bluesky/src/lib/actions/delete-list.ts
new file mode 100644
index 00000000000..18ca6ec1633
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/delete-list.ts
@@ -0,0 +1,112 @@
+import { createAction } from '@activepieces/pieces-framework';
+import type { AtpAgent } from '@atproto/api';
+import { blueskyAuth } from '../common/auth';
+import { deleteListOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyRefs } from '../common/refs';
+
+const LISTITEM_COLLECTION = 'app.bsky.graph.listitem';
+const DELETE_BATCH = 100;
+const SCAN_PAGE_SIZE = 100;
+const MAX_SCAN_PAGES = 500;
+
+export const deleteList = createAction({
+ auth: blueskyAuth,
+ name: 'delete_list',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete List',
+ description: 'Permanently delete one of your lists and its memberships',
+ audience: 'both',
+ outputSchema: deleteListOutputSchema,
+ aiMetadata: {
+ description:
+ 'Permanently deletes a list owned by the connected Bluesky account, given its bsky.app link or AT-URI: it first removes every membership record of the list from the account repository, and deletes the list only after all of them are gone; it refuses lists of other accounts. Cannot be undone. Idempotent: running it again finishes any cleanup a failed run left behind, and deleting an already-deleted list succeeds and reports existed=false.',
+ idempotent: true,
+ },
+ props: {
+ list: blueskyProps.listInputProperty(),
+ },
+ async run({ auth, propsValue }) {
+ blueskyRefs.parseListInput(propsValue.list);
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'delete the list',
+ fn: async (agent) => {
+ const me = blueskyClient.sessionDid(agent);
+ const ref = await blueskyRefs.resolveListRef({ agent, input: propsValue.list });
+ if (ref.did !== me) {
+ throw new Error('This list belongs to another account. You can only delete lists owned by the connected account.');
+ }
+ const existed = await blueskyRefs.recordExists({ agent, repo: me, collection: blueskyRefs.LIST_COLLECTION, rkey: ref.rkey });
+ const itemRkeys = await listItemRkeys({ agent, repo: me, listUri: ref.uri });
+ const removed = await deleteItems({ agent, repo: me, rkeys: itemRkeys });
+ if (existed) {
+ await agent.app.bsky.graph.list.delete({ repo: me, rkey: ref.rkey });
+ }
+ return {
+ deleted: true,
+ existed,
+ uri: ref.uri,
+ membersRemoved: removed,
+ membersFailed: 0,
+ membersComplete: true,
+ };
+ },
+ });
+ },
+});
+
+async function listItemRkeys({ agent, repo, listUri }: { agent: AtpAgent; repo: string; listUri: string }): Promise<string[]> {
+ const rkeys: string[] = [];
+ let cursor: string | undefined = undefined;
+ for (let page = 0; page < MAX_SCAN_PAGES; page++) {
+ const response: Awaited<ReturnType<typeof agent.com.atproto.repo.listRecords>> = await agent.com.atproto.repo.listRecords({
+ repo,
+ collection: LISTITEM_COLLECTION,
+ limit: SCAN_PAGE_SIZE,
+ cursor,
+ });
+ for (const record of response.data.records) {
+ const parsed = blueskyRefs.parseAtUri(record.uri);
+ if (parsed && parsed.repo === repo && parsed.collection === LISTITEM_COLLECTION && listOf(record.value) === listUri) {
+ rkeys.push(parsed.rkey);
+ }
+ }
+ const next = response.data.cursor;
+ if (!next || next === cursor || response.data.records.length === 0) {
+ return rkeys;
+ }
+ cursor = next;
+ }
+ throw new Error(
+ `The account has more than ${(MAX_SCAN_PAGES * SCAN_PAGE_SIZE).toLocaleString('en-US')} list membership records, so not every membership of this list could be found. The list was not deleted.`,
+ );
+}
+
+function listOf(value: unknown): string | undefined {
+ if (typeof value === 'object' && value !== null && 'list' in value && typeof value.list === 'string') {
+ return value.list;
+ }
+ return undefined;
+}
+
+async function deleteItems({ agent, repo, rkeys }: { agent: AtpAgent; repo: string; rkeys: string[] }): Promise<number> {
+ const batches = Array.from({ length: Math.ceil(rkeys.length / DELETE_BATCH) }, (_, index) => rkeys.slice(index * DELETE_BATCH, (index + 1) * DELETE_BATCH));
+ let removed = 0;
+ for (const batch of batches) {
+ try {
+ await agent.com.atproto.repo.applyWrites({
+ repo,
+ writes: batch.map((rkey) => ({ $type: 'com.atproto.repo.applyWrites#delete', collection: LISTITEM_COLLECTION, rkey })),
+ });
+ } catch (error) {
+ const reason = blueskyClient.toBlueskyError({ error, action: 'remove list memberships' }).message;
+ throw new Error(
+ `Removed ${removed} of ${rkeys.length} list memberships, then Bluesky refused the next batch. The list was not deleted; run the action again to finish. (${reason})`,
+ );
+ }
+ removed += batch.length;
+ }
+ return removed;
+}
diff --git a/packages/pieces/community/bluesky/src/lib/actions/delete-post.ts b/packages/pieces/community/bluesky/src/lib/actions/delete-post.ts
new file mode 100644
index 00000000000..0128a9118fd
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/delete-post.ts
@@ -0,0 +1,42 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { deletePostOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyRefs } from '../common/refs';
+
+export const deletePost = createAction({
+ auth: blueskyAuth,
+ name: 'delete_post',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Post',
+ description: 'Permanently delete one of your own posts',
+ audience: 'both',
+ outputSchema: deletePostOutputSchema,
+ aiMetadata: {
+ description:
+ 'Permanently deletes a post owned by the connected Bluesky account, given its bsky.app link or AT-URI; it refuses posts by other accounts. The deletion cannot be undone. Idempotent: deleting an already-deleted post succeeds and reports existed=false.',
+ idempotent: true,
+ },
+ props: {
+ post: blueskyProps.postInputProperty(),
+ },
+ async run({ auth, propsValue }) {
+ blueskyRefs.parsePostInput(propsValue.post);
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'delete the post',
+ fn: async (agent) => {
+ const ref = await blueskyRefs.resolvePostRef({ agent, input: propsValue.post });
+ const me = blueskyClient.sessionDid(agent);
+ if (ref.did !== me) {
+ throw new Error('This post belongs to another account. You can only delete posts made by the connected account.');
+ }
+ const existed = await blueskyRefs.recordExists({ agent, repo: me, collection: blueskyRefs.POST_COLLECTION, rkey: ref.rkey });
+ await agent.deletePost(ref.uri);
+ return { deleted: true, existed, uri: ref.uri, deletedAt: new Date().toISOString() };
+ },
+ });
+ },
+});
+
diff --git a/packages/pieces/community/bluesky/src/lib/actions/find-post.ts b/packages/pieces/community/bluesky/src/lib/actions/find-post.ts
index 0f93a283741..24f1caeef94 100644
--- a/packages/pieces/community/bluesky/src/lib/actions/find-post.ts
+++ b/packages/pieces/community/bluesky/src/lib/actions/find-post.ts
@@ -1,8 +1,9 @@
-import { createAction, Property } from '@activepieces/pieces-framework';
+import { createAction } from '@activepieces/pieces-framework';
import { blueskyAuth } from '../common/auth';
import { findPostOutputSchema } from '../output-schemas';
-import { createBlueskyAgent } from '../common/client';
-import { postUrlProperty, extractPostInfoFromUrl } from '../common/props';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyRefs } from '../common/refs';
export const findPost = createAction({
auth: blueskyAuth,
@@ -13,67 +14,44 @@ export const findPost = createAction({
audience: 'both',
outputSchema: findPostOutputSchema,
aiMetadata: {
- description: 'Retrieves a single Bluesky post with its content, author, and engagement counts (likes, reposts, replies, quotes), given a bsky.app post URL or AT-URI. Use to look up the current state or metadata of a known post. Read-only and idempotent.',
+ description:
+ 'Retrieves a single Bluesky post with its content, author, and engagement counts (likes, reposts, replies, quotes), given a bsky.app post URL or AT-URI (handle or DID form). Use to look up the current state or metadata of a known post; use Get Posts to fetch several at once. Read-only and idempotent.',
idempotent: true,
},
props: {
- postUrl: postUrlProperty,
+ postUrl: blueskyProps.postUrlProperty,
},
async run({ auth, propsValue }) {
- const { postUrl } = propsValue;
-
- try {
- const agent = await createBlueskyAgent(auth.props);
-
- const postInfo = extractPostInfoFromUrl(postUrl);
- let atUri = postInfo.uri;
-
- if (!atUri && postInfo.handle && postInfo.postId) {
- const didDoc = await agent.resolveHandle({ handle: postInfo.handle });
-
- if (didDoc.data?.did) {
- atUri = `at://${didDoc.data.did}/app.bsky.feed.post/${postInfo.postId}`;
- } else {
- throw new Error(`Could not resolve handle: ${postInfo.handle}`);
+ blueskyRefs.parsePostInput(propsValue.postUrl);
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'find the post',
+ fn: async (agent) => {
+ const ref = await blueskyRefs.resolvePostRef({ agent, input: propsValue.postUrl });
+ const response = await agent.getPosts({ uris: [ref.uri] });
+ const post = response.data.posts[0];
+ if (!post) {
+ throw new Error('Post not found or not accessible. It may have been deleted, or its author blocks this account.');
}
- }
-
- if (!atUri) {
- throw new Error('Could not parse the post URL. Please make sure you are using a valid Bluesky post URL like: https://bsky.app/profile/username.bsky.social/post/xxx');
- }
-
- if (!atUri.startsWith('at://')) {
- throw new Error('Invalid URI format. Must be an AT-URI starting with "at://" or a valid Bluesky URL');
- }
-
- const response = await agent.getPosts({ uris: [atUri] });
-
- if (!response.data?.posts || response.data.posts.length === 0) {
- throw new Error('Post not found or not accessible');
- }
-
- const post = response.data.posts[0];
-
- return {
- success: true,
- uri: atUri,
- cid: post.cid,
- record: post.record,
- author: post.author,
- indexedAt: post.indexedAt,
- replyCount: post.replyCount || 0,
- repostCount: post.repostCount || 0,
- likeCount: post.likeCount || 0,
- quoteCount: post.quoteCount || 0,
- embed: post.embed,
- labels: post.labels,
- threadgate: post.threadgate,
- viewer: post.viewer,
- retrievedAt: new Date().toISOString(),
- };
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
- throw new Error(`Failed to find post: ${errorMessage}`);
- }
+ return {
+ success: true,
+ uri: ref.uri,
+ url: blueskyRefs.postWebUrl({ uri: post.uri, handle: post.author.handle }),
+ cid: post.cid,
+ record: post.record,
+ author: post.author,
+ indexedAt: post.indexedAt,
+ replyCount: post.replyCount || 0,
+ repostCount: post.repostCount || 0,
+ likeCount: post.likeCount || 0,
+ quoteCount: post.quoteCount || 0,
+ embed: post.embed,
+ labels: post.labels,
+ threadgate: post.threadgate,
+ viewer: post.viewer,
+ retrievedAt: new Date().toISOString(),
+ };
+ },
+ });
},
-});
\ No newline at end of file
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/find-thread.ts b/packages/pieces/community/bluesky/src/lib/actions/find-thread.ts
index 7a56d369056..0d90e3f7e35 100644
--- a/packages/pieces/community/bluesky/src/lib/actions/find-thread.ts
+++ b/packages/pieces/community/bluesky/src/lib/actions/find-thread.ts
@@ -1,8 +1,11 @@
-import { createAction, Property } from '@activepieces/pieces-framework';
+import { createAction } from '@activepieces/pieces-framework';
+import type { AppBskyFeedDefs, AppBskyFeedGetPostThread } from '@atproto/api';
+import { blueskyAtproto } from '../common/atproto';
import { blueskyAuth } from '../common/auth';
import { findThreadOutputSchema } from '../output-schemas';
-import { createBlueskyAgent } from '../common/client';
-import { postUrlProperty, threadDepthDropdown, parentHeightDropdown, extractPostInfoFromUrl } from '../common/props';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyRefs } from '../common/refs';
export const findThread = createAction({
auth: blueskyAuth,
@@ -13,112 +16,98 @@ export const findThread = createAction({
audience: 'both',
outputSchema: findThreadOutputSchema,
aiMetadata: {
- description: 'Retrieves the full conversation thread around a Bluesky post — parent posts and nested replies — given a bsky.app post URL or AT-URI, with configurable reply depth and parent height (each 0-1000). Use to read an entire discussion rather than a single post. Read-only and idempotent.',
+ description:
+ 'Retrieves the full conversation thread around a Bluesky post (parent posts and nested replies) given a bsky.app post URL or AT-URI, with configurable reply depth (default 10) and parent height (default 3), each 0-1000. Use to read an entire discussion rather than a single post. Read-only and idempotent.',
idempotent: true,
},
props: {
- postUrl: postUrlProperty,
- depth: threadDepthDropdown,
- parentHeight: parentHeightDropdown,
+ postUrl: blueskyProps.postUrlProperty,
+ depth: blueskyProps.threadDepthDropdown,
+ parentHeight: blueskyProps.parentHeightDropdown,
},
async run({ auth, propsValue }) {
- const { postUrl, depth = 6, parentHeight = 80 } = propsValue;
-
- try {
- const agent = await createBlueskyAgent(auth.props);
-
- const postInfo = extractPostInfoFromUrl(postUrl);
- let atUri = postInfo.uri;
-
- if (!atUri && postInfo.handle && postInfo.postId) {
- const didDoc = await agent.resolveHandle({ handle: postInfo.handle });
-
- if (didDoc.data?.did) {
- atUri = `at://${didDoc.data.did}/app.bsky.feed.post/${postInfo.postId}`;
- } else {
- throw new Error(`Could not resolve handle: ${postInfo.handle}`);
- }
- }
-
- if (!atUri) {
- throw new Error('Could not parse the post URL. Please make sure you are using a valid Bluesky post URL like: https://bsky.app/profile/username.bsky.social/post/xxx');
- }
-
- if (!atUri.startsWith('at://')) {
- throw new Error('Invalid URI format. Must be an AT-URI starting with "at://" or a valid Bluesky URL');
- }
-
- const depthNum = parseInt(depth.toString(), 10);
- const parentHeightNum = parseInt(parentHeight.toString(), 10);
-
- if (isNaN(depthNum) || depthNum < 0 || depthNum > 1000) {
- throw new Error('Depth must be a number between 0 and 1000');
- }
- if (isNaN(parentHeightNum) || parentHeightNum < 0 || parentHeightNum > 1000) {
- throw new Error('Parent height must be a number between 0 and 1000');
- }
-
- const response = await agent.getPostThread({
- uri: atUri,
- depth: depthNum,
- parentHeight: parentHeightNum,
- });
-
- const stats = {
- totalPosts: 0,
- parentPosts: 0,
- replyPosts: 0,
- notFoundPosts: 0,
- blockedPosts: 0,
- };
-
- const countPosts = (threadPost: any): void => {
- if (!threadPost) return;
+ const { postUrl, depth = '10', parentHeight = '3' } = propsValue;
+ blueskyRefs.parsePostInput(postUrl);
+ const depthNum = parseInt(String(depth), 10);
+ const parentHeightNum = parseInt(String(parentHeight), 10);
+ if (isNaN(depthNum) || depthNum < 0 || depthNum > 1000) {
+ throw new Error('Depth must be a number between 0 and 1000');
+ }
+ if (isNaN(parentHeightNum) || parentHeightNum < 0 || parentHeightNum > 1000) {
+ throw new Error('Parent height must be a number between 0 and 1000');
+ }
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'find the thread',
+ fn: async (agent) => {
+ const ref = await blueskyRefs.resolvePostRef({ agent, input: postUrl });
+ const response = await agent.getPostThread({ uri: ref.uri, depth: depthNum, parentHeight: parentHeightNum });
+ return {
+ success: true,
+ thread: response.data.thread,
+ requestedUri: ref.uri,
+ parameters: { depth: depthNum, parentHeight: parentHeightNum },
+ statistics: threadStatistics(response.data.thread),
+ retrievedAt: new Date().toISOString(),
+ };
+ },
+ });
+ },
+});
- if (threadPost.$type === 'app.bsky.feed.defs#notFoundPost') {
- stats.notFoundPosts++;
- } else if (threadPost.$type === 'app.bsky.feed.defs#blockedPost') {
- stats.blockedPosts++;
- } else if (threadPost.post) {
- stats.totalPosts++;
- }
+function threadStatistics(thread: ThreadRoot): ThreadStatistics {
+ const empty: ThreadStatistics = { totalPosts: 0, parentPosts: 0, replyPosts: 0, notFoundPosts: 0, blockedPosts: 0 };
+ if (!blueskyAtproto.isThreadViewPost(thread)) {
+ return {
+ ...empty,
+ notFoundPosts: blueskyAtproto.isNotFoundPost(thread) ? 1 : 0,
+ blockedPosts: blueskyAtproto.isBlockedPost(thread) ? 1 : 0,
+ };
+ }
+ const parents = countParents(thread.parent);
+ const replies = countReplies(thread.replies ?? []);
+ return {
+ totalPosts: 1 + parents.posts + replies.posts,
+ parentPosts: parents.posts,
+ replyPosts: replies.posts,
+ notFoundPosts: parents.notFound + replies.notFound,
+ blockedPosts: parents.blocked + replies.blocked,
+ };
+}
- if (threadPost.parent) {
- stats.parentPosts++;
- countPosts(threadPost.parent);
- }
+function countParents(node: AppBskyFeedDefs.ThreadViewPost['parent']): NodeCounts {
+ if (blueskyAtproto.isThreadViewPost(node)) {
+ const above = countParents(node.parent);
+ return { ...above, posts: above.posts + 1 };
+ }
+ return {
+ posts: 0,
+ notFound: blueskyAtproto.isNotFoundPost(node) ? 1 : 0,
+ blocked: blueskyAtproto.isBlockedPost(node) ? 1 : 0,
+ };
+}
- if (threadPost.replies && Array.isArray(threadPost.replies)) {
- stats.replyPosts += threadPost.replies.length;
- threadPost.replies.forEach((reply: any) => countPosts(reply));
- }
- };
-
- if (response.data.thread) {
- countPosts(response.data.thread);
- if (
- response.data.thread.$type === 'app.bsky.feed.defs#threadViewPost' &&
- 'post' in response.data.thread &&
- response.data.thread.post
- ) {
- stats.totalPosts = 1;
- }
+function countReplies(nodes: NonNullable<AppBskyFeedDefs.ThreadViewPost['replies']>): NodeCounts {
+ return nodes.reduce<NodeCounts>(
+ (total, node) => {
+ if (blueskyAtproto.isThreadViewPost(node)) {
+ const nested = countReplies(node.replies ?? []);
+ return {
+ posts: total.posts + 1 + nested.posts,
+ notFound: total.notFound + nested.notFound,
+ blocked: total.blocked + nested.blocked,
+ };
}
-
return {
- success: true,
- thread: response.data.thread,
- requestedUri: atUri,
- parameters: {
- depth: depthNum,
- parentHeight: parentHeightNum,
- },
- statistics: stats,
- retrievedAt: new Date().toISOString(),
+ posts: total.posts,
+ notFound: total.notFound + (blueskyAtproto.isNotFoundPost(node) ? 1 : 0),
+ blocked: total.blocked + (blueskyAtproto.isBlockedPost(node) ? 1 : 0),
};
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
- throw new Error(`Failed to find thread: ${errorMessage}`);
- }
- },
-});
\ No newline at end of file
+ },
+ { posts: 0, notFound: 0, blocked: 0 },
+ );
+}
+
+type ThreadRoot = AppBskyFeedGetPostThread.OutputSchema['thread'];
+type NodeCounts = { posts: number; notFound: number; blocked: number };
+type ThreadStatistics = { totalPosts: number; parentPosts: number; replyPosts: number; notFoundPosts: number; blockedPosts: number };
diff --git a/packages/pieces/community/bluesky/src/lib/actions/follow-user.ts b/packages/pieces/community/bluesky/src/lib/actions/follow-user.ts
new file mode 100644
index 00000000000..8a8325baaab
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/follow-user.ts
@@ -0,0 +1,40 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { followOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyRefs } from '../common/refs';
+
+export const followUser = createAction({
+ auth: blueskyAuth,
+ name: 'follow_user',
+ classification: 'WRITE',
+ displayName: 'Follow User',
+ description: 'Follow a Bluesky account',
+ audience: 'both',
+ outputSchema: followOutputSchema,
+ aiMetadata: {
+ description:
+ 'Follows a Bluesky account given its handle, DID or profile link, and returns the existing follow when the account is already followed. Use Unfollow User to undo. Idempotent: a repeat call does not create a second follow.',
+ idempotent: true,
+ },
+ props: {
+ actor: blueskyProps.actorProperty({ description: 'Handle (alice.bsky.social), DID or profile link of the account to follow.' }),
+ },
+ async run({ auth, propsValue }) {
+ blueskyRefs.parseActorInput(propsValue.actor);
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'follow the account',
+ fn: async (agent) => {
+ const profile = await blueskyRefs.fetchProfile({ agent, input: propsValue.actor });
+ if (profile.did === blueskyClient.sessionDid(agent)) {
+ throw new Error('The connected account cannot follow itself.');
+ }
+ const existing = profile.viewer?.following;
+ const followUri = existing ?? (await agent.follow(profile.did)).uri;
+ return { followUri, did: profile.did, handle: profile.handle, alreadyFollowing: Boolean(existing) };
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/get-author-feed.ts b/packages/pieces/community/bluesky/src/lib/actions/get-author-feed.ts
new file mode 100644
index 00000000000..4230d59d0ac
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/get-author-feed.ts
@@ -0,0 +1,64 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { feedListOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyRefs } from '../common/refs';
+import { blueskyMappers } from '../common/mappers';
+
+export const getAuthorFeed = createAction({
+ auth: blueskyAuth,
+ name: 'get_author_feed',
+ classification: 'SEARCH',
+ displayName: "Get User's Posts",
+ description: 'List the latest posts and reposts of one account',
+ audience: 'both',
+ outputSchema: feedListOutputSchema,
+ aiMetadata: {
+ description:
+ 'Lists one Bluesky account\'s own feed, newest first (its posts and reposts), filtered to posts without replies (default), with replies, only media, only video, or author threads, with cursor pagination. Use Search Posts to search across all accounts. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ actor: blueskyProps.optionalActorProperty({ description: 'Handle (alice.bsky.social), DID or profile link. Leave empty for your own posts.' }),
+ filter: Property.StaticDropdown({
+ displayName: 'Include',
+ required: false,
+ defaultValue: 'posts_no_replies',
+ options: {
+ options: [
+ { label: 'Posts and reposts, no replies', value: 'posts_no_replies' },
+ { label: 'Posts, reposts and replies', value: 'posts_with_replies' },
+ { label: 'Only posts with media', value: 'posts_with_media' },
+ { label: 'Only posts with video', value: 'posts_with_video' },
+ { label: 'Posts and the author\'s own threads', value: 'posts_and_author_threads' },
+ ],
+ },
+ }),
+ includePins: Property.Checkbox({ displayName: 'Include Pinned Post', description: 'Put the pinned post first.', required: false, defaultValue: false }),
+ limit: blueskyProps.limitProperty(),
+ cursor: blueskyProps.cursorProperty(),
+ },
+ async run({ auth, propsValue }) {
+ if (propsValue.actor && propsValue.actor.trim() !== '') {
+ blueskyRefs.parseActorInput(propsValue.actor);
+ }
+ const limit = blueskyProps.parseLimit(propsValue.limit);
+ const cursor = blueskyProps.parseCursor(propsValue.cursor);
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: "get the user's posts",
+ fn: async (agent) => {
+ const actor = propsValue.actor && propsValue.actor.trim() !== '' ? blueskyRefs.parseActorInput(propsValue.actor) : blueskyClient.sessionDid(agent);
+ const response = await agent.getAuthorFeed({
+ actor,
+ limit,
+ cursor,
+ filter: propsValue.filter ?? 'posts_no_replies',
+ includePins: propsValue.includePins === true,
+ });
+ return blueskyMappers.pageOf({ items: response.data.feed.map(blueskyMappers.feedItem), cursor: response.data.cursor });
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/get-list-members.ts b/packages/pieces/community/bluesky/src/lib/actions/get-list-members.ts
new file mode 100644
index 00000000000..fc3b8c14676
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/get-list-members.ts
@@ -0,0 +1,47 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { listMembersOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyRefs } from '../common/refs';
+import { blueskyMappers } from '../common/mappers';
+
+export const getListMembers = createAction({
+ auth: blueskyAuth,
+ name: 'get_list_members',
+ classification: 'SEARCH',
+ displayName: 'Get List Members',
+ description: 'List the accounts on a Bluesky list',
+ audience: 'both',
+ outputSchema: listMembersOutputSchema,
+ aiMetadata: {
+ description:
+ 'Returns a Bluesky list\'s details and one page of its member accounts, given the list\'s bsky.app link or AT-URI, with cursor pagination. Use List Lists to find a list first. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ list: blueskyProps.listInputProperty(),
+ limit: blueskyProps.limitProperty(),
+ cursor: blueskyProps.cursorProperty(),
+ },
+ async run({ auth, propsValue }) {
+ blueskyRefs.parseListInput(propsValue.list);
+ const limit = blueskyProps.parseLimit(propsValue.limit);
+ const cursor = blueskyProps.parseCursor(propsValue.cursor);
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'get the list members',
+ fn: async (agent) => {
+ const ref = await blueskyRefs.resolveListRef({ agent, input: propsValue.list });
+ const response = await agent.app.bsky.graph.getList({ list: ref.uri, limit, cursor });
+ return {
+ list: blueskyMappers.listItem(response.data.list),
+ ...blueskyMappers.pageOf({
+ items: response.data.items.map((item) => ({ listItemUri: item.uri, ...blueskyMappers.profileItem(item.subject) })),
+ cursor: response.data.cursor,
+ }),
+ };
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/get-post-likes.ts b/packages/pieces/community/bluesky/src/lib/actions/get-post-likes.ts
new file mode 100644
index 00000000000..10076a9fef7
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/get-post-likes.ts
@@ -0,0 +1,48 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { likeListOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyRefs } from '../common/refs';
+import { blueskyMappers } from '../common/mappers';
+
+export const getPostLikes = createAction({
+ auth: blueskyAuth,
+ name: 'get_post_likes',
+ classification: 'SEARCH',
+ displayName: 'Get Post Likes',
+ description: 'List the accounts that liked a post',
+ audience: 'both',
+ outputSchema: likeListOutputSchema,
+ aiMetadata: {
+ description:
+ 'Lists the accounts that liked a Bluesky post, given its bsky.app link or AT-URI, newest first with cursor pagination. Use Get Post Reposts or Get Post Quotes for other engagement. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ post: blueskyProps.postInputProperty(),
+ limit: blueskyProps.limitProperty(),
+ cursor: blueskyProps.cursorProperty(),
+ },
+ async run({ auth, propsValue }) {
+ blueskyRefs.parsePostInput(propsValue.post);
+ const limit = blueskyProps.parseLimit(propsValue.limit);
+ const cursor = blueskyProps.parseCursor(propsValue.cursor);
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'get the post likes',
+ fn: async (agent) => {
+ const ref = await blueskyRefs.resolvePostRef({ agent, input: propsValue.post });
+ const response = await agent.getLikes({ uri: ref.uri, limit, cursor });
+ return blueskyMappers.pageOf({
+ items: response.data.likes.map((like) => ({
+ ...blueskyMappers.profileItem(like.actor),
+ likedAt: like.createdAt,
+ likeIndexedAt: like.indexedAt,
+ })),
+ cursor: response.data.cursor,
+ });
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/get-post-quotes.ts b/packages/pieces/community/bluesky/src/lib/actions/get-post-quotes.ts
new file mode 100644
index 00000000000..c3af7237982
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/get-post-quotes.ts
@@ -0,0 +1,44 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { postListOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyRefs } from '../common/refs';
+import { blueskyMappers } from '../common/mappers';
+
+export const getPostQuotes = createAction({
+ auth: blueskyAuth,
+ name: 'get_post_quotes',
+ classification: 'SEARCH',
+ displayName: 'Get Post Quotes',
+ description: 'List the posts that quote a post',
+ audience: 'both',
+ outputSchema: postListOutputSchema,
+ aiMetadata: {
+ description:
+ 'Lists the posts that quote (repost with a comment) a Bluesky post, given its bsky.app link or AT-URI, with cursor pagination. Use Get Post Reposts for plain reposts. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ post: blueskyProps.postInputProperty(),
+ limit: blueskyProps.limitProperty(),
+ cursor: blueskyProps.cursorProperty(),
+ },
+ async run({ auth, propsValue }) {
+ blueskyRefs.parsePostInput(propsValue.post);
+ const limit = blueskyProps.parseLimit(propsValue.limit);
+ const cursor = blueskyProps.parseCursor(propsValue.cursor);
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'get the post quotes',
+ fn: async (agent) => {
+ const ref = await blueskyRefs.resolvePostRef({ agent, input: propsValue.post });
+ const response = await agent.app.bsky.feed.getQuotes({ uri: ref.uri, limit, cursor });
+ return blueskyMappers.pageOf({
+ items: response.data.posts.map((post) => ({ ...blueskyMappers.postBase(post), text: blueskyMappers.recordText(post.record) })),
+ cursor: response.data.cursor,
+ });
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/get-post-reposts.ts b/packages/pieces/community/bluesky/src/lib/actions/get-post-reposts.ts
new file mode 100644
index 00000000000..362c8b40723
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/get-post-reposts.ts
@@ -0,0 +1,41 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { profileListOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyRefs } from '../common/refs';
+import { blueskyMappers } from '../common/mappers';
+
+export const getPostReposts = createAction({
+ auth: blueskyAuth,
+ name: 'get_post_reposts',
+ classification: 'SEARCH',
+ displayName: 'Get Post Reposts',
+ description: 'List the accounts that reposted a post',
+ audience: 'both',
+ outputSchema: profileListOutputSchema,
+ aiMetadata: {
+ description:
+ 'Lists the accounts that reposted a Bluesky post, given its bsky.app link or AT-URI, with cursor pagination. Use Get Post Quotes for reposts that added a comment. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ post: blueskyProps.postInputProperty(),
+ limit: blueskyProps.limitProperty(),
+ cursor: blueskyProps.cursorProperty(),
+ },
+ async run({ auth, propsValue }) {
+ blueskyRefs.parsePostInput(propsValue.post);
+ const limit = blueskyProps.parseLimit(propsValue.limit);
+ const cursor = blueskyProps.parseCursor(propsValue.cursor);
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'get the post reposts',
+ fn: async (agent) => {
+ const ref = await blueskyRefs.resolvePostRef({ agent, input: propsValue.post });
+ const response = await agent.getRepostedBy({ uri: ref.uri, limit, cursor });
+ return blueskyMappers.pageOf({ items: response.data.repostedBy.map(blueskyMappers.profileItem), cursor: response.data.cursor });
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/get-profile.ts b/packages/pieces/community/bluesky/src/lib/actions/get-profile.ts
new file mode 100644
index 00000000000..e6f7017bf1a
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/get-profile.ts
@@ -0,0 +1,35 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { profileOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyRefs } from '../common/refs';
+import { blueskyMappers } from '../common/mappers';
+
+export const getProfile = createAction({
+ auth: blueskyAuth,
+ name: 'get_profile',
+ classification: 'READ',
+ displayName: 'Get Profile',
+ description: 'Get a Bluesky profile with follower and post counts',
+ audience: 'both',
+ outputSchema: profileOutputSchema,
+ aiMetadata: {
+ description:
+ 'Returns one Bluesky profile (display name, bio, avatar, follower/following/post counts and the connected account\'s relationship to it) given a handle, DID or profile link; leave the account empty for the connected account itself. Use Search Users when you only have a name. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ actor: blueskyProps.optionalActorProperty({ description: 'Handle (alice.bsky.social), DID or profile link. Leave empty for your own profile.' }),
+ },
+ async run({ auth, propsValue }) {
+ if (propsValue.actor && propsValue.actor.trim() !== '') {
+ blueskyRefs.parseActorInput(propsValue.actor);
+ }
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'get the profile',
+ fn: async (agent) => blueskyMappers.detailedProfile(await blueskyRefs.fetchProfile({ agent, input: propsValue.actor })),
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/get-timeline.ts b/packages/pieces/community/bluesky/src/lib/actions/get-timeline.ts
new file mode 100644
index 00000000000..d13fc7c2b3d
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/get-timeline.ts
@@ -0,0 +1,37 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { feedListOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyMappers } from '../common/mappers';
+
+export const getTimeline = createAction({
+ auth: blueskyAuth,
+ name: 'get_timeline',
+ classification: 'SEARCH',
+ displayName: 'Get Home Timeline',
+ description: 'List the posts in your home (Following) timeline',
+ audience: 'both',
+ outputSchema: feedListOutputSchema,
+ aiMetadata: {
+ description:
+ 'Lists the connected account\'s home timeline (posts and reposts from accounts it follows), newest first, with cursor pagination. Use Get User\'s Posts for one account or Search Posts for a query. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ limit: blueskyProps.limitProperty(),
+ cursor: blueskyProps.cursorProperty(),
+ },
+ async run({ auth, propsValue }) {
+ const limit = blueskyProps.parseLimit(propsValue.limit);
+ const cursor = blueskyProps.parseCursor(propsValue.cursor);
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'get the timeline',
+ fn: async (agent) => {
+ const response = await agent.getTimeline({ limit, cursor });
+ return blueskyMappers.pageOf({ items: response.data.feed.map(blueskyMappers.feedItem), cursor: response.data.cursor });
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/like-post.ts b/packages/pieces/community/bluesky/src/lib/actions/like-post.ts
index 7370344ae8b..23a47167f76 100644
--- a/packages/pieces/community/bluesky/src/lib/actions/like-post.ts
+++ b/packages/pieces/community/bluesky/src/lib/actions/like-post.ts
@@ -1,9 +1,10 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { blueskyAuth, BlueSkyAuthType } from '../common/auth';
+import { blueskyAuth } from '../common/auth';
import { likePostOutputSchema } from '../output-schemas';
-import { createBlueskyAgent } from '../common/client';
-import { parseBlueskyUrl } from '../common/props';
-
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyRefs } from '../common/refs';
+import { blueskyMappers } from '../common/mappers';
export const likePost = createAction({
auth: blueskyAuth,
@@ -11,52 +12,16 @@ export const likePost = createAction({
classification: 'WRITE',
displayName: 'Like Post',
description: 'Like a post on Bluesky',
- audience: 'both',
+ audience: 'human',
outputSchema: likePostOutputSchema,
aiMetadata: {
- description: 'Adds a like from the authenticated account to a specific Bluesky post, identified either by an AT-URI / bsky.app post URL or by selecting from the recent timeline. Use to register approval of a post. Not idempotent — each call creates a separate like record.',
+ description:
+ 'Adds a like from the authenticated account to a specific Bluesky post, identified either by an AT-URI / bsky.app post URL or by selecting from the recent timeline. Use to register approval of a post. Not idempotent: each call creates a separate like record.',
idempotent: false,
},
props: {
- selectionMethod: Property.StaticDropdown({
- displayName: 'Select Method',
- description: 'How to choose the post',
- required: true,
- defaultValue: 'timeline',
- options: {
- options: [
- { label: 'From my timeline', value: 'timeline' },
- { label: 'Enter URL manually', value: 'manual' },
- ],
- },
- }),
-
- postSelection: Property.Dropdown({
- auth: blueskyAuth,
- displayName: 'Select Post',
- description: 'Choose from your recent timeline posts (only when "From my timeline" is selected above)',
- required: false,
- refreshers: ['auth'],
- options: async ({ auth }) => {
- try {
- if (!auth) return { options: [] };
- const agent = await createBlueskyAgent(auth.props);
- const timeline = await agent.getTimeline({ limit: 50 });
-
- return {
- options: timeline.data.feed.map(item => ({
- label: `@${item.post.author.handle}: ${item.post.record['text'] ? String(item.post.record['text']).substring(0, 80) : 'Media post'}${String(item.post.record['text'] || '').length > 80 ? '...' : ''} (${new Date(item.post.indexedAt).toLocaleDateString()})`,
- value: item.post.uri
- }))
- };
- } catch (error) {
- return {
- options: [{ label: 'Error loading posts', value: '' }]
- };
- }
- }
- }),
-
+ selectionMethod: blueskyProps.selectionMethodDropdown,
+ postSelection: blueskyProps.timelinePostDropdown(),
postUrl: Property.ShortText({
displayName: 'Post URL',
description: 'Paste the Bluesky post URL',
@@ -65,67 +30,35 @@ export const likePost = createAction({
},
async run({ auth, propsValue }) {
const { selectionMethod, postSelection, postUrl } = propsValue;
-
- let postUri: string;
-
- if (selectionMethod === 'timeline') {
- if (!postSelection) {
- throw new Error('Please select a post from your timeline dropdown');
- }
- postUri = postSelection as string;
- } else if (selectionMethod === 'manual') {
- if (!postUrl || !postUrl.trim()) {
- throw new Error('Post URL is required when using manual entry method');
- }
-
- try {
- const agent = await createBlueskyAgent(auth.props);
- postUri = await parseBlueskyUrl(postUrl.trim(), agent);
- } catch (error) {
- throw new Error(`Invalid post URL: ${error instanceof Error ? error.message : 'Unknown error'}`);
- }
- } else {
- throw new Error('Please select a post selection method');
+ const input = blueskyProps.selectedPostInput({ selectionMethod, postSelection, postUrl });
+ if (selectionMethod === 'manual') {
+ blueskyRefs.parsePostInput(input);
}
-
- try {
- const agent = await createBlueskyAgent(auth.props);
-
- const postsResponse = await agent.getPosts({ uris: [postUri] });
-
- if (!postsResponse.data.posts || postsResponse.data.posts.length === 0) {
- throw new Error('Post not found');
- }
-
- const post = postsResponse.data.posts[0];
-
- const response = await agent.like(postUri, post.cid);
-
- return {
- success: true,
- likeUri: response.uri,
- likeCid: response.cid,
- postUri: postUri,
- postCid: post.cid,
- postAuthor: post.author.handle,
- postText: post.record['text'] ? String(post.record['text']).substring(0, 100) + (String(post.record['text']).length > 100 ? '...' : '') : 'No text available',
- selectionMethod: selectionMethod,
- likedAt: new Date().toISOString(),
- };
- } catch (error) {
- if (error instanceof Error) {
- if (error.message.includes('Post not found')) {
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'like the post',
+ fn: async (agent) => {
+ const ref = await blueskyRefs.resolvePostRef({ agent, input });
+ const postsResponse = await agent.getPosts({ uris: [ref.uri] });
+ const post = postsResponse.data.posts[0];
+ if (!post) {
throw new Error('Post not found. Please check the URL and try again.');
}
- if (error.message.includes('Invalid post URL format')) {
- throw new Error('Invalid post URL format. Please use a valid Bluesky post URL or AT-URI.');
- }
- if (error.message.includes('Authentication')) {
- throw new Error('Authentication failed. Please check your credentials.');
- }
- throw new Error(`Failed to like post: ${error.message}`);
- }
- throw new Error('Failed to like post: Unknown error occurred');
- }
+ const response = await agent.like(ref.uri, post.cid);
+ const text = blueskyMappers.recordText(post.record);
+ return {
+ success: true,
+ likeUri: response.uri,
+ likeCid: response.cid,
+ postUri: ref.uri,
+ postCid: post.cid,
+ postUrl: blueskyRefs.postWebUrl({ uri: post.uri, handle: post.author.handle }),
+ postAuthor: post.author.handle,
+ postText: text ? text.substring(0, 100) + (text.length > 100 ? '...' : '') : 'No text available',
+ selectionMethod: selectionMethod,
+ likedAt: new Date().toISOString(),
+ };
+ },
+ });
},
});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/list-followers.ts b/packages/pieces/community/bluesky/src/lib/actions/list-followers.ts
new file mode 100644
index 00000000000..c2cccdf6411
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/list-followers.ts
@@ -0,0 +1,43 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { profileListOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyRefs } from '../common/refs';
+import { blueskyMappers } from '../common/mappers';
+
+export const listFollowers = createAction({
+ auth: blueskyAuth,
+ name: 'list_followers',
+ classification: 'SEARCH',
+ displayName: 'List Followers',
+ description: 'List the accounts that follow an account',
+ audience: 'both',
+ outputSchema: profileListOutputSchema,
+ aiMetadata: {
+ description:
+ 'Lists the accounts that follow a Bluesky account (the connected account when left empty), newest follow first, with cursor pagination. Use List Following for the accounts it follows. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ actor: blueskyProps.optionalActorProperty({ description: 'Handle (alice.bsky.social), DID or profile link. Leave empty for your own account.' }),
+ limit: blueskyProps.limitProperty(),
+ cursor: blueskyProps.cursorProperty(),
+ },
+ async run({ auth, propsValue }) {
+ if (propsValue.actor && propsValue.actor.trim() !== '') {
+ blueskyRefs.parseActorInput(propsValue.actor);
+ }
+ const limit = blueskyProps.parseLimit(propsValue.limit);
+ const cursor = blueskyProps.parseCursor(propsValue.cursor);
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'list the followers',
+ fn: async (agent) => {
+ const actor = propsValue.actor && propsValue.actor.trim() !== '' ? blueskyRefs.parseActorInput(propsValue.actor) : blueskyClient.sessionDid(agent);
+ const response = await agent.getFollowers({ actor, limit, cursor });
+ return blueskyMappers.pageOf({ items: response.data.followers.map(blueskyMappers.profileItem), cursor: response.data.cursor });
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/list-follows.ts b/packages/pieces/community/bluesky/src/lib/actions/list-follows.ts
new file mode 100644
index 00000000000..550a8b43b91
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/list-follows.ts
@@ -0,0 +1,43 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { profileListOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyRefs } from '../common/refs';
+import { blueskyMappers } from '../common/mappers';
+
+export const listFollows = createAction({
+ auth: blueskyAuth,
+ name: 'list_follows',
+ classification: 'SEARCH',
+ displayName: 'List Following',
+ description: 'List the accounts an account follows',
+ audience: 'both',
+ outputSchema: profileListOutputSchema,
+ aiMetadata: {
+ description:
+ 'Lists the accounts a Bluesky account follows (the connected account when left empty), newest follow first, with cursor pagination. Use List Followers for the accounts following it. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ actor: blueskyProps.optionalActorProperty({ description: 'Handle (alice.bsky.social), DID or profile link. Leave empty for your own account.' }),
+ limit: blueskyProps.limitProperty(),
+ cursor: blueskyProps.cursorProperty(),
+ },
+ async run({ auth, propsValue }) {
+ if (propsValue.actor && propsValue.actor.trim() !== '') {
+ blueskyRefs.parseActorInput(propsValue.actor);
+ }
+ const limit = blueskyProps.parseLimit(propsValue.limit);
+ const cursor = blueskyProps.parseCursor(propsValue.cursor);
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'list the follows',
+ fn: async (agent) => {
+ const actor = propsValue.actor && propsValue.actor.trim() !== '' ? blueskyRefs.parseActorInput(propsValue.actor) : blueskyClient.sessionDid(agent);
+ const response = await agent.getFollows({ actor, limit, cursor });
+ return blueskyMappers.pageOf({ items: response.data.follows.map(blueskyMappers.profileItem), cursor: response.data.cursor });
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/list-my-lists.ts b/packages/pieces/community/bluesky/src/lib/actions/list-my-lists.ts
new file mode 100644
index 00000000000..be8d87b32dd
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/list-my-lists.ts
@@ -0,0 +1,58 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { listListOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyRefs } from '../common/refs';
+import { blueskyMappers } from '../common/mappers';
+
+export const listMyLists = createAction({
+ auth: blueskyAuth,
+ name: 'list_my_lists',
+ classification: 'SEARCH',
+ displayName: 'List Lists',
+ description: 'List the user lists and moderation lists an account created',
+ audience: 'both',
+ outputSchema: listListOutputSchema,
+ aiMetadata: {
+ description:
+ 'Lists the curation and moderation lists created by a Bluesky account (the connected account when left empty), optionally only one kind, with cursor pagination. Use Get List Members to read who is on a list. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ actor: blueskyProps.optionalActorProperty({ description: 'Handle, DID or profile link of the list owner. Leave empty for your own lists.' }),
+ purpose: Property.StaticDropdown({
+ displayName: 'Kind',
+ required: false,
+ defaultValue: 'all',
+ options: {
+ options: [
+ { label: 'All lists', value: 'all' },
+ { label: 'User lists (curation)', value: 'app.bsky.graph.defs#curatelist' },
+ { label: 'Moderation lists', value: 'app.bsky.graph.defs#modlist' },
+ { label: 'Reference lists (starter packs)', value: 'app.bsky.graph.defs#referencelist' },
+ ],
+ },
+ }),
+ limit: blueskyProps.limitProperty(),
+ cursor: blueskyProps.cursorProperty(),
+ },
+ async run({ auth, propsValue }) {
+ if (propsValue.actor && propsValue.actor.trim() !== '') {
+ blueskyRefs.parseActorInput(propsValue.actor);
+ }
+ const limit = blueskyProps.parseLimit(propsValue.limit);
+ const cursor = blueskyProps.parseCursor(propsValue.cursor);
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'list the lists',
+ fn: async (agent) => {
+ const actor = propsValue.actor && propsValue.actor.trim() !== '' ? blueskyRefs.parseActorInput(propsValue.actor) : blueskyClient.sessionDid(agent);
+ const response = await agent.app.bsky.graph.getLists({ actor, limit, cursor });
+ const purpose = propsValue.purpose && propsValue.purpose !== 'all' ? propsValue.purpose : undefined;
+ const lists = purpose ? response.data.lists.filter((list) => list.purpose === purpose) : response.data.lists;
+ return blueskyMappers.pageOf({ items: lists.map(blueskyMappers.listItem), cursor: response.data.cursor });
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/list-notifications.ts b/packages/pieces/community/bluesky/src/lib/actions/list-notifications.ts
new file mode 100644
index 00000000000..54dca1534ea
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/list-notifications.ts
@@ -0,0 +1,50 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { notificationListOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyMappers } from '../common/mappers';
+import { blueskyCompose } from '../common/compose';
+
+export const listNotifications = createAction({
+ auth: blueskyAuth,
+ name: 'list_notifications',
+ classification: 'SEARCH',
+ displayName: 'List Notifications',
+ description: 'List your notifications (likes, reposts, follows, mentions, replies, quotes)',
+ audience: 'both',
+ outputSchema: notificationListOutputSchema,
+ aiMetadata: {
+ description:
+ 'Lists the connected account\'s notifications (likes, reposts, follows, mentions, replies, quotes and more), newest first, optionally filtered by type or to unread ones, with cursor pagination. Use Get Unread Count for only the number. Read-only and idempotent; it does not mark anything as seen.',
+ idempotent: true,
+ },
+ props: {
+ reasons: blueskyProps.notificationReasonsProperty({ description: 'Only these notification types. Leave empty for all.' }),
+ unreadOnly: Property.Checkbox({
+ displayName: 'Unread Only',
+ description: 'Only return notifications that are not yet marked as seen. A page can then hold fewer items than the limit.',
+ required: false,
+ defaultValue: false,
+ }),
+ limit: blueskyProps.limitProperty(),
+ cursor: blueskyProps.cursorProperty(),
+ },
+ async run({ auth, propsValue }) {
+ const limit = blueskyProps.parseLimit(propsValue.limit);
+ const cursor = blueskyProps.parseCursor(propsValue.cursor);
+ const reasons = blueskyCompose.stringList(propsValue.reasons);
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'list notifications',
+ fn: async (agent) => {
+ const response = await agent.listNotifications({ limit, cursor, ...(reasons.length > 0 ? { reasons } : {}) });
+ const notifications = propsValue.unreadOnly === true ? response.data.notifications.filter((n) => !n.isRead) : response.data.notifications;
+ return {
+ ...blueskyMappers.pageOf({ items: notifications.map(blueskyMappers.notificationItem), cursor: response.data.cursor }),
+ seenAt: response.data.seenAt ?? null,
+ };
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/mark-notifications-seen.ts b/packages/pieces/community/bluesky/src/lib/actions/mark-notifications-seen.ts
new file mode 100644
index 00000000000..71c51fd57d4
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/mark-notifications-seen.ts
@@ -0,0 +1,41 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { markSeenOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+
+export const markNotificationsSeen = createAction({
+ auth: blueskyAuth,
+ name: 'mark_notifications_seen',
+ classification: 'WRITE',
+ displayName: 'Mark Notifications as Seen',
+ description: 'Mark all notifications up to a time as seen',
+ audience: 'both',
+ outputSchema: markSeenOutputSchema,
+ aiMetadata: {
+ description:
+ 'Marks every notification of the connected Bluesky account up to a given time (default now) as seen, which resets the unread count in the Bluesky app. Use after processing List Notifications. Idempotent: repeating it with the same time changes nothing.',
+ idempotent: true,
+ },
+ props: {
+ seenAt: Property.DateTime({
+ displayName: 'Seen Up To',
+ description: 'Notifications up to this time are marked as seen. Leave empty for now.',
+ required: false,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const time = propsValue.seenAt ? Date.parse(propsValue.seenAt) : Date.now();
+ if (Number.isNaN(time)) {
+ throw new Error('Seen Up To is not a valid date.');
+ }
+ const seenAt = new Date(time).toISOString();
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'mark notifications as seen',
+ fn: async (agent) => {
+ await agent.updateSeenNotifications(seenAt);
+ return { seenAt };
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/mute-user.ts b/packages/pieces/community/bluesky/src/lib/actions/mute-user.ts
new file mode 100644
index 00000000000..5c75bb5e1d6
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/mute-user.ts
@@ -0,0 +1,36 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { muteOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyRefs } from '../common/refs';
+
+export const muteUser = createAction({
+ auth: blueskyAuth,
+ name: 'mute_user',
+ classification: 'WRITE',
+ displayName: 'Mute User',
+ description: 'Mute a Bluesky account (private)',
+ audience: 'both',
+ outputSchema: muteOutputSchema,
+ aiMetadata: {
+ description:
+ 'Mutes a Bluesky account given its handle, DID or profile link, hiding its posts from the connected account\'s feeds and notifications; mutes are private. Use Unmute User to undo, or Block User for a public block. Idempotent: muting an already-muted account changes nothing.',
+ idempotent: true,
+ },
+ props: {
+ actor: blueskyProps.actorProperty({ description: 'Handle (alice.bsky.social), DID or profile link of the account to mute.' }),
+ },
+ async run({ auth, propsValue }) {
+ blueskyRefs.parseActorInput(propsValue.actor);
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'mute the account',
+ fn: async (agent) => {
+ const profile = await blueskyRefs.fetchProfile({ agent, input: propsValue.actor });
+ await agent.mute(profile.did);
+ return { muted: true, wasMuted: Boolean(profile.viewer?.muted), did: profile.did, handle: profile.handle };
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/remove-user-from-list.ts b/packages/pieces/community/bluesky/src/lib/actions/remove-user-from-list.ts
new file mode 100644
index 00000000000..5ab9a4f4c53
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/remove-user-from-list.ts
@@ -0,0 +1,53 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { removeListMemberOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyRefs } from '../common/refs';
+
+export const removeUserFromList = createAction({
+ auth: blueskyAuth,
+ name: 'remove_user_from_list',
+ classification: 'WRITE',
+ displayName: 'Remove User from List',
+ description: 'Remove an account from one of your lists',
+ audience: 'both',
+ outputSchema: removeListMemberOutputSchema,
+ aiMetadata: {
+ description:
+ 'Removes every membership of a Bluesky account (handle, DID or profile link) from a list owned by the connected account, given the list\'s link or AT-URI. Use to undo Add User to List. Idempotent: when the account is not on the list it changes nothing and returns removed=0.',
+ idempotent: true,
+ },
+ props: {
+ list: blueskyProps.listInputProperty(),
+ actor: blueskyProps.actorProperty({ description: 'Handle (alice.bsky.social), DID or profile link of the account to remove.' }),
+ },
+ async run({ auth, propsValue }) {
+ blueskyRefs.parseListInput(propsValue.list);
+ blueskyRefs.parseActorInput(propsValue.actor);
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'remove the account from the list',
+ fn: async (agent) => {
+ const me = blueskyClient.sessionDid(agent);
+ const list = await blueskyRefs.resolveListRef({ agent, input: propsValue.list });
+ if (list.did !== me) {
+ throw new Error('This list belongs to another account. You can only remove members from lists owned by the connected account.');
+ }
+ const did = await blueskyRefs.resolveActorDid({ agent, input: propsValue.actor });
+ const members = await blueskyRefs.listMembers({ agent, listUri: list.uri });
+ if (!members.complete) {
+ throw new Error('The list is too large to search completely (more than 5,000 members); nothing was removed.');
+ }
+ const rkeys = members.items.flatMap((item) => {
+ const parsed = item.subject.did === did ? blueskyRefs.parseAtUri(item.uri) : null;
+ return parsed && parsed.repo === me ? [parsed.rkey] : [];
+ });
+ for (const rkey of rkeys) {
+ await agent.app.bsky.graph.listitem.delete({ repo: me, rkey });
+ }
+ return { removed: rkeys.length, listUri: list.uri, did };
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/repost.ts b/packages/pieces/community/bluesky/src/lib/actions/repost.ts
index b29c5c630e8..984e8f21ee8 100644
--- a/packages/pieces/community/bluesky/src/lib/actions/repost.ts
+++ b/packages/pieces/community/bluesky/src/lib/actions/repost.ts
@@ -1,10 +1,10 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { blueskyAuth, BlueSkyAuthType } from '../common/auth';
+import { blueskyAuth } from '../common/auth';
import { repostOutputSchema } from '../output-schemas';
-import { createBlueskyAgent } from '../common/client';
-import { parseBlueskyUrl } from '../common/props';
-
-
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyRefs } from '../common/refs';
+import { blueskyMappers } from '../common/mappers';
export const repostPost = createAction({
auth: blueskyAuth,
@@ -12,52 +12,16 @@ export const repostPost = createAction({
classification: 'WRITE',
displayName: 'Repost Post',
description: 'Share someone else\'s post to your timeline',
- audience: 'both',
+ audience: 'human',
outputSchema: repostOutputSchema,
aiMetadata: {
- description: 'Reposts an existing Bluesky post to the authenticated account\'s timeline, identified by an AT-URI / bsky.app post URL or selected from the recent timeline. Use to amplify another user\'s post. Not idempotent — each call creates a separate repost record.',
+ description:
+ 'Reposts an existing Bluesky post to the authenticated account\'s timeline, identified by an AT-URI / bsky.app post URL or selected from the recent timeline. Use to amplify another user\'s post. Not idempotent: each call creates a separate repost record.',
idempotent: false,
},
props: {
- selectionMethod: Property.StaticDropdown({
- displayName: 'Select Method',
- description: 'How to choose the post',
- required: true,
- defaultValue: 'timeline',
- options: {
- options: [
- { label: 'From my timeline', value: 'timeline' },
- { label: 'Enter URL manually', value: 'manual' },
- ],
- },
- }),
-
- postSelection: Property.Dropdown({
- auth: blueskyAuth,
- displayName: 'Select Post',
- description: 'Choose from your recent timeline posts (only when "From my timeline" is selected above)',
- required: false,
- refreshers: ['auth'],
- options: async ({ auth }) => {
- try {
- if (!auth) return { options: [] };
- const agent = await createBlueskyAgent(auth.props);
- const timeline = await agent.getTimeline({ limit: 50 });
-
- return {
- options: timeline.data.feed.map(item => ({
- label: `@${item.post.author.handle}: ${item.post.record['text'] ? String(item.post.record['text']).substring(0, 80) : 'Media post'}${String(item.post.record['text'] || '').length > 80 ? '...' : ''} (${new Date(item.post.indexedAt).toLocaleDateString()})`,
- value: item.post.uri
- }))
- };
- } catch (error) {
- return {
- options: [{ label: 'Error loading posts', value: '' }]
- };
- }
- }
- }),
-
+ selectionMethod: blueskyProps.selectionMethodDropdown,
+ postSelection: blueskyProps.timelinePostDropdown(),
postUrl: Property.ShortText({
displayName: 'Post URL',
description: 'Paste the Bluesky post URL',
@@ -66,70 +30,39 @@ export const repostPost = createAction({
},
async run({ auth, propsValue }) {
const { selectionMethod, postSelection, postUrl } = propsValue;
-
- let postUri: string;
-
- if (selectionMethod === 'timeline') {
- if (!postSelection) {
- throw new Error('Please select a post from your timeline dropdown');
- }
- postUri = postSelection as string;
- } else if (selectionMethod === 'manual') {
- if (!postUrl || !postUrl.trim()) {
- throw new Error('Post URL is required when using manual entry method');
- }
-
- try {
- const agent = await createBlueskyAgent(auth.props);
- postUri = await parseBlueskyUrl(postUrl.trim(), agent);
- } catch (error) {
- throw new Error(`Invalid post URL: ${error instanceof Error ? error.message : 'Unknown error'}`);
- }
- } else {
- throw new Error('Please select a post selection method');
+ const input = blueskyProps.selectedPostInput({ selectionMethod, postSelection, postUrl });
+ if (selectionMethod === 'manual') {
+ blueskyRefs.parsePostInput(input);
}
-
- try {
- const agent = await createBlueskyAgent(auth.props);
-
- const postsResponse = await agent.getPosts({ uris: [postUri] });
-
- if (!postsResponse.data.posts || postsResponse.data.posts.length === 0) {
- throw new Error('Post not found');
- }
-
- const post = postsResponse.data.posts[0];
-
- const response = await agent.repost(postUri, post.cid);
-
- return {
- success: true,
- repostUri: response.uri,
- repostCid: response.cid,
- originalPost: {
- uri: postUri,
- cid: post.cid,
- author: post.author.handle,
- text: post.record['text'] ? String(post.record['text']).substring(0, 100) + (String(post.record['text']).length > 100 ? '...' : '') : 'No text available',
- createdAt: post.record['createdAt'] || post.indexedAt,
- },
- selectionMethod: selectionMethod,
- repostedAt: new Date().toISOString(),
- };
- } catch (error) {
- if (error instanceof Error) {
- if (error.message.includes('Post not found')) {
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'repost the post',
+ fn: async (agent) => {
+ const ref = await blueskyRefs.resolvePostRef({ agent, input });
+ const postsResponse = await agent.getPosts({ uris: [ref.uri] });
+ const post = postsResponse.data.posts[0];
+ if (!post) {
throw new Error('Post not found. Please check the URL and try again.');
}
- if (error.message.includes('Invalid post URL format')) {
- throw new Error('Invalid post URL format. Please use a valid Bluesky post URL or AT-URI.');
- }
- if (error.message.includes('Authentication')) {
- throw new Error('Authentication failed. Please check your credentials.');
- }
- throw new Error(`Failed to repost: ${error.message}`);
- }
- throw new Error('Failed to repost: Unknown error occurred');
- }
+ const response = await agent.repost(ref.uri, post.cid);
+ const text = blueskyMappers.recordText(post.record);
+ const createdAt = post.record['createdAt'];
+ return {
+ success: true,
+ repostUri: response.uri,
+ repostCid: response.cid,
+ originalPost: {
+ uri: ref.uri,
+ cid: post.cid,
+ url: blueskyRefs.postWebUrl({ uri: post.uri, handle: post.author.handle }),
+ author: post.author.handle,
+ text: text ? text.substring(0, 100) + (text.length > 100 ? '...' : '') : 'No text available',
+ createdAt: typeof createdAt === 'string' ? createdAt : post.indexedAt,
+ },
+ selectionMethod: selectionMethod,
+ repostedAt: new Date().toISOString(),
+ };
+ },
+ });
},
-});
\ No newline at end of file
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/search-posts.ts b/packages/pieces/community/bluesky/src/lib/actions/search-posts.ts
new file mode 100644
index 00000000000..2d9277c8535
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/search-posts.ts
@@ -0,0 +1,94 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { postListOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyMappers } from '../common/mappers';
+import { blueskyRefs } from '../common/refs';
+import { blueskyCompose } from '../common/compose';
+
+export const searchPosts = createAction({
+ auth: blueskyAuth,
+ name: 'search_posts',
+ classification: 'SEARCH',
+ displayName: 'Search Posts',
+ description: 'Search public Bluesky posts',
+ audience: 'both',
+ outputSchema: postListOutputSchema,
+ aiMetadata: {
+ description:
+ 'Searches public Bluesky posts by query, with optional author, mention, language, domain, link, tag and date-range filters, sorted latest or top and paginated with a cursor. Use Get User\'s Posts to read one account\'s feed instead. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ query: Property.ShortText({
+ displayName: 'Search Query',
+ description: 'Words, "exact phrases", #hashtags or from:handle. Use * to match everything when you only filter.',
+ required: true,
+ }),
+ sort: Property.StaticDropdown({
+ displayName: 'Sort',
+ required: false,
+ defaultValue: 'latest',
+ options: { options: [{ label: 'Latest', value: 'latest' }, { label: 'Top', value: 'top' }] },
+ }),
+ author: Property.ShortText({ displayName: 'Author', description: 'Only posts by this handle or DID.', required: false }),
+ mentions: Property.ShortText({ displayName: 'Mentions', description: 'Only posts that mention this handle or DID.', required: false }),
+ lang: Property.ShortText({ displayName: 'Language', description: 'Only posts in this language, for example en or ja.', required: false }),
+ domain: Property.ShortText({ displayName: 'Link Domain', description: 'Only posts linking to this domain, for example activepieces.com.', required: false }),
+ url: Property.ShortText({ displayName: 'Link URL', description: 'Only posts linking to this exact URL.', required: false }),
+ tags: Property.Array({ displayName: 'Tags', description: 'Only posts with all of these hashtags (without #).', required: false }),
+ since: Property.DateTime({ displayName: 'Since', description: 'Only posts created at or after this time.', required: false }),
+ until: Property.DateTime({ displayName: 'Until', description: 'Only posts created before this time.', required: false }),
+ limit: blueskyProps.limitProperty(),
+ cursor: blueskyProps.cursorProperty(),
+ },
+ async run({ auth, propsValue }) {
+ const q = propsValue.query.trim();
+ if (q === '') {
+ throw new Error('Search Query is empty. Use * to match everything.');
+ }
+ const limit = blueskyProps.parseLimit(propsValue.limit);
+ const cursor = blueskyProps.parseCursor(propsValue.cursor);
+ const tag = blueskyCompose.stringList(propsValue.tags).map((value) => value.replace(/^#/, ''));
+ const since = isoOrUndefined({ value: propsValue.since, label: 'Since' });
+ const until = isoOrUndefined({ value: propsValue.until, label: 'Until' });
+ const author = propsValue.author?.trim() ? blueskyRefs.parseActorInput(propsValue.author) : undefined;
+ const mentions = propsValue.mentions?.trim() ? blueskyRefs.parseActorInput(propsValue.mentions) : undefined;
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'search posts',
+ fn: async (agent) => {
+ const response = await agent.app.bsky.feed.searchPosts({
+ q,
+ sort: propsValue.sort ?? 'latest',
+ limit,
+ cursor,
+ ...(author ? { author } : {}),
+ ...(mentions ? { mentions } : {}),
+ ...(propsValue.lang?.trim() ? { lang: propsValue.lang.trim() } : {}),
+ ...(propsValue.domain?.trim() ? { domain: propsValue.domain.trim() } : {}),
+ ...(propsValue.url?.trim() ? { url: propsValue.url.trim() } : {}),
+ ...(tag.length > 0 ? { tag } : {}),
+ ...(since ? { since } : {}),
+ ...(until ? { until } : {}),
+ });
+ return blueskyMappers.pageOf({
+ items: response.data.posts.map((post) => ({ ...blueskyMappers.postBase(post), text: blueskyMappers.recordText(post.record) })),
+ cursor: response.data.cursor,
+ });
+ },
+ });
+ },
+});
+
+function isoOrUndefined({ value, label }: { value: string | undefined; label: string }): string | undefined {
+ if (!value) {
+ return undefined;
+ }
+ const time = Date.parse(value);
+ if (Number.isNaN(time)) {
+ throw new Error(`${label} is not a valid date.`);
+ }
+ return new Date(time).toISOString();
+}
diff --git a/packages/pieces/community/bluesky/src/lib/actions/search-users.ts b/packages/pieces/community/bluesky/src/lib/actions/search-users.ts
new file mode 100644
index 00000000000..32c8edf42a7
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/search-users.ts
@@ -0,0 +1,42 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { profileListOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyMappers } from '../common/mappers';
+
+export const searchUsers = createAction({
+ auth: blueskyAuth,
+ name: 'search_users',
+ classification: 'SEARCH',
+ displayName: 'Search Users',
+ description: 'Search Bluesky accounts by name, handle or bio',
+ audience: 'both',
+ outputSchema: profileListOutputSchema,
+ aiMetadata: {
+ description:
+ 'Searches Bluesky accounts whose name, handle or bio match a query and returns one page of profiles with a cursor for the next page. Use to find an account when you do not know its exact handle; use Get Profile when you do. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ query: Property.ShortText({ displayName: 'Search Query', description: 'Words to search for, for example a name or company.', required: true }),
+ limit: blueskyProps.limitProperty(),
+ cursor: blueskyProps.cursorProperty(),
+ },
+ async run({ auth, propsValue }) {
+ const q = propsValue.query.trim();
+ if (q === '') {
+ throw new Error('Search Query is empty.');
+ }
+ const limit = blueskyProps.parseLimit(propsValue.limit);
+ const cursor = blueskyProps.parseCursor(propsValue.cursor);
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'search users',
+ fn: async (agent) => {
+ const response = await agent.searchActors({ q, limit, cursor });
+ return blueskyMappers.pageOf({ items: response.data.actors.map(blueskyMappers.profileItem), cursor: response.data.cursor });
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/unblock-user.ts b/packages/pieces/community/bluesky/src/lib/actions/unblock-user.ts
new file mode 100644
index 00000000000..c974e228cce
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/unblock-user.ts
@@ -0,0 +1,41 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { unblockOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyRefs } from '../common/refs';
+
+export const unblockUser = createAction({
+ auth: blueskyAuth,
+ name: 'unblock_user',
+ classification: 'WRITE',
+ displayName: 'Unblock User',
+ description: 'Unblock a Bluesky account',
+ audience: 'both',
+ outputSchema: unblockOutputSchema,
+ aiMetadata: {
+ description:
+ 'Removes the connected account\'s block on a Bluesky account given its handle, DID or profile link. Use to undo Block User. Idempotent: when the account is not blocked it changes nothing and returns removed=false.',
+ idempotent: true,
+ },
+ props: {
+ actor: blueskyProps.actorProperty({ description: 'Handle (alice.bsky.social), DID or profile link of the account to unblock.' }),
+ },
+ async run({ auth, propsValue }) {
+ blueskyRefs.parseActorInput(propsValue.actor);
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'unblock the account',
+ fn: async (agent) => {
+ const me = blueskyClient.sessionDid(agent);
+ const profile = await blueskyRefs.fetchProfile({ agent, input: propsValue.actor });
+ const blockUri = profile.viewer?.blocking;
+ const parsed = blockUri ? blueskyRefs.parseAtUri(blockUri) : null;
+ if (parsed) {
+ await agent.app.bsky.graph.block.delete({ repo: me, rkey: parsed.rkey });
+ }
+ return { removed: parsed !== null, did: profile.did, handle: profile.handle, blockUri: blockUri ?? null };
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/undo-repost.ts b/packages/pieces/community/bluesky/src/lib/actions/undo-repost.ts
new file mode 100644
index 00000000000..f739c03611a
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/undo-repost.ts
@@ -0,0 +1,40 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { undoRepostOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyRefs } from '../common/refs';
+import { blueskyCompose } from '../common/compose';
+
+export const undoRepost = createAction({
+ auth: blueskyAuth,
+ name: 'undo_repost',
+ classification: 'WRITE',
+ displayName: 'Undo Repost',
+ description: 'Remove your repost of a post',
+ audience: 'both',
+ outputSchema: undoRepostOutputSchema,
+ aiMetadata: {
+ description:
+ 'Removes the connected account\'s repost of a Bluesky post given the original post\'s bsky.app link or AT-URI. Use to undo Repost Post. Idempotent: when the post is not reposted it changes nothing and returns removed=false.',
+ idempotent: true,
+ },
+ props: {
+ post: blueskyProps.postInputProperty(),
+ },
+ async run({ auth, propsValue }) {
+ blueskyRefs.parsePostInput(propsValue.post);
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'undo the repost',
+ fn: async (agent) => {
+ const post = await blueskyCompose.fetchPostView({ agent, input: propsValue.post });
+ const repostUri = post.viewer?.repost;
+ if (repostUri) {
+ await agent.deleteRepost(repostUri);
+ }
+ return { removed: Boolean(repostUri), postUri: post.uri, repostUri: repostUri ?? null };
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/unfollow-user.ts b/packages/pieces/community/bluesky/src/lib/actions/unfollow-user.ts
new file mode 100644
index 00000000000..402b50490a7
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/unfollow-user.ts
@@ -0,0 +1,39 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { unfollowOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyRefs } from '../common/refs';
+
+export const unfollowUser = createAction({
+ auth: blueskyAuth,
+ name: 'unfollow_user',
+ classification: 'WRITE',
+ displayName: 'Unfollow User',
+ description: 'Stop following a Bluesky account',
+ audience: 'both',
+ outputSchema: unfollowOutputSchema,
+ aiMetadata: {
+ description:
+ 'Stops following a Bluesky account given its handle, DID or profile link. Use to undo Follow User. Idempotent: when the account is not followed it changes nothing and returns removed=false.',
+ idempotent: true,
+ },
+ props: {
+ actor: blueskyProps.actorProperty({ description: 'Handle (alice.bsky.social), DID or profile link of the account to unfollow.' }),
+ },
+ async run({ auth, propsValue }) {
+ blueskyRefs.parseActorInput(propsValue.actor);
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'unfollow the account',
+ fn: async (agent) => {
+ const profile = await blueskyRefs.fetchProfile({ agent, input: propsValue.actor });
+ const followUri = profile.viewer?.following;
+ if (followUri) {
+ await agent.deleteFollow(followUri);
+ }
+ return { removed: Boolean(followUri), did: profile.did, handle: profile.handle, followUri: followUri ?? null };
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/unlike-post.ts b/packages/pieces/community/bluesky/src/lib/actions/unlike-post.ts
new file mode 100644
index 00000000000..e4cc985d92c
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/unlike-post.ts
@@ -0,0 +1,40 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { unlikePostOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyRefs } from '../common/refs';
+import { blueskyCompose } from '../common/compose';
+
+export const unlikePost = createAction({
+ auth: blueskyAuth,
+ name: 'unlike_post',
+ classification: 'WRITE',
+ displayName: 'Unlike Post',
+ description: 'Remove your like from a post',
+ audience: 'both',
+ outputSchema: unlikePostOutputSchema,
+ aiMetadata: {
+ description:
+ 'Removes the connected account\'s like from a Bluesky post given its bsky.app link or AT-URI. Use to undo Like Post. Idempotent: when the post is not liked it changes nothing and returns removed=false.',
+ idempotent: true,
+ },
+ props: {
+ post: blueskyProps.postInputProperty(),
+ },
+ async run({ auth, propsValue }) {
+ blueskyRefs.parsePostInput(propsValue.post);
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'unlike the post',
+ fn: async (agent) => {
+ const post = await blueskyCompose.fetchPostView({ agent, input: propsValue.post });
+ const likeUri = post.viewer?.like;
+ if (likeUri) {
+ await agent.deleteLike(likeUri);
+ }
+ return { removed: Boolean(likeUri), postUri: post.uri, likeUri: likeUri ?? null };
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/unmute-user.ts b/packages/pieces/community/bluesky/src/lib/actions/unmute-user.ts
new file mode 100644
index 00000000000..7652fce684c
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/unmute-user.ts
@@ -0,0 +1,36 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { blueskyAuth } from '../common/auth';
+import { muteOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyRefs } from '../common/refs';
+
+export const unmuteUser = createAction({
+ auth: blueskyAuth,
+ name: 'unmute_user',
+ classification: 'WRITE',
+ displayName: 'Unmute User',
+ description: 'Unmute a Bluesky account',
+ audience: 'both',
+ outputSchema: muteOutputSchema,
+ aiMetadata: {
+ description:
+ 'Unmutes a Bluesky account given its handle, DID or profile link so its posts show again. Use to undo Mute User. Idempotent: unmuting an account that is not muted changes nothing.',
+ idempotent: true,
+ },
+ props: {
+ actor: blueskyProps.actorProperty({ description: 'Handle (alice.bsky.social), DID or profile link of the account to unmute.' }),
+ },
+ async run({ auth, propsValue }) {
+ blueskyRefs.parseActorInput(propsValue.actor);
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'unmute the account',
+ fn: async (agent) => {
+ const profile = await blueskyRefs.fetchProfile({ agent, input: propsValue.actor });
+ await agent.unmute(profile.did);
+ return { muted: false, wasMuted: Boolean(profile.viewer?.muted), did: profile.did, handle: profile.handle };
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/bluesky/src/lib/actions/update-profile.ts b/packages/pieces/community/bluesky/src/lib/actions/update-profile.ts
new file mode 100644
index 00000000000..1942074f3e9
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/actions/update-profile.ts
@@ -0,0 +1,118 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import type { AtpAgent, BlobRef } from '@atproto/api';
+import { blueskyAuth } from '../common/auth';
+import { updateProfileOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyCompose } from '../common/compose';
+
+const MAX_DISPLAY_NAME = 64;
+const MAX_DESCRIPTION = 256;
+const PROFILE_COLLECTION = 'app.bsky.actor.profile';
+
+export const updateProfile = createAction({
+ auth: blueskyAuth,
+ name: 'update_profile',
+ classification: 'WRITE',
+ displayName: 'Update Profile',
+ description: 'Change your display name, bio or avatar',
+ audience: 'both',
+ outputSchema: updateProfileOutputSchema,
+ aiMetadata: {
+ description:
+ 'Updates the connected Bluesky account\'s own profile: display name (max 64 characters), bio (max 256) and avatar image URL. Fields left empty keep their current value, every other profile field (banner, pinned post, existing avatar) is kept as it is, and the Clear options blank a field. Idempotent: the same input leaves the profile in the same state.',
+ idempotent: true,
+ },
+ props: {
+ displayName: Property.ShortText({ displayName: 'Display Name', description: 'New display name. Leave empty to keep the current one.', required: false }),
+ clearDisplayName: Property.Checkbox({ displayName: 'Clear Display Name', description: 'Remove the display name.', required: false, defaultValue: false }),
+ description: Property.LongText({ displayName: 'Bio', description: 'New bio. Leave empty to keep the current one.', required: false }),
+ clearDescription: Property.Checkbox({ displayName: 'Clear Bio', description: 'Remove the bio.', required: false, defaultValue: false }),
+ avatarUrl: Property.ShortText({ displayName: 'Avatar Image URL', description: 'PNG or JPEG, max 1 MB. Leave empty to keep the current avatar.', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const displayName = textChange({ value: propsValue.displayName, clear: propsValue.clearDisplayName, max: MAX_DISPLAY_NAME, label: 'Display Name' });
+ const description = textChange({ value: propsValue.description, clear: propsValue.clearDescription, max: MAX_DESCRIPTION, label: 'Bio' });
+ const avatarUrl = propsValue.avatarUrl?.trim() ? propsValue.avatarUrl.trim() : undefined;
+ if (displayName.kind === 'keep' && description.kind === 'keep' && avatarUrl === undefined) {
+ throw new Error('Nothing to update. Fill in at least one field or tick a Clear option.');
+ }
+ return blueskyClient.withBluesky({
+ auth: auth.props,
+ action: 'update the profile',
+ fn: async (agent) => {
+ const did = blueskyClient.sessionDid(agent);
+ const avatar = avatarUrl ? await uploadAvatar({ agent, url: avatarUrl }) : undefined;
+ const existing = await currentProfile({ agent, did });
+ const next = applyChanges({ existing: existing?.value ?? {}, displayName, description, avatar });
+ await agent.com.atproto.repo.putRecord({
+ repo: did,
+ collection: PROFILE_COLLECTION,
+ rkey: 'self',
+ record: next,
+ swapRecord: existing?.cid ?? null,
+ });
+ return {
+ did,
+ displayName: typeof next['displayName'] === 'string' ? next['displayName'] : '',
+ description: typeof next['description'] === 'string' ? next['description'] : '',
+ avatarUpdated: avatar !== undefined,
+ updatedAt: new Date().toISOString(),
+ };
+ },
+ });
+ },
+});
+
+async function currentProfile({ agent, did }: { agent: AtpAgent; did: string }): Promise<{ value: Record<string, unknown>; cid: string | null } | undefined> {
+ try {
+ const response = await agent.com.atproto.repo.getRecord({ repo: did, collection: PROFILE_COLLECTION, rkey: 'self' });
+ return { value: { ...response.data.value }, cid: response.data.cid ?? null };
+ } catch (error) {
+ if (blueskyClient.isXrpcError(error) && (error.error === 'RecordNotFound' || /could not locate record/i.test(error.message))) {
+ return undefined;
+ }
+ throw error;
+ }
+}
+
+function textChange({ value, clear, max, label }: { value: string | undefined; clear: boolean | undefined; max: number; label: string }): TextChange {
+ if (clear === true) {
+ return { kind: 'clear' };
+ }
+ if (value === undefined || value.trim() === '') {
+ return { kind: 'keep' };
+ }
+ const length = blueskyCompose.graphemeLength(value);
+ if (length > max) {
+ throw new Error(`${label} is ${length} characters long; Bluesky allows at most ${max}.`);
+ }
+ return { kind: 'set', value };
+}
+
+function applyChanges({
+ existing,
+ displayName,
+ description,
+ avatar,
+}: {
+ existing: Record<string, unknown>;
+ displayName: TextChange;
+ description: TextChange;
+ avatar: BlobRef | undefined;
+}): Record<string, unknown> {
+ const { displayName: currentName, description: currentDescription, ...rest } = existing;
+ return {
+ ...rest,
+ $type: PROFILE_COLLECTION,
+ ...(displayName.kind === 'set' ? { displayName: displayName.value } : displayName.kind === 'keep' && currentName !== undefined ? { displayName: currentName } : {}),
+ ...(description.kind === 'set' ? { description: description.value } : description.kind === 'keep' && currentDescription !== undefined ? { description: currentDescription } : {}),
+ ...(avatar ? { avatar } : {}),
+ };
+}
+
+async function uploadAvatar({ agent, url }: { agent: AtpAgent; url: string }): Promise<BlobRef | undefined> {
+ const embed = await blueskyCompose.uploadImages({ agent, images: [{ url, alt: '' }] });
+ return embed?.images[0]?.image;
+}
+
+type TextChange = { kind: 'keep' } | { kind: 'clear' } | { kind: 'set'; value: string };
diff --git a/packages/pieces/community/bluesky/src/lib/common/atproto.ts b/packages/pieces/community/bluesky/src/lib/common/atproto.ts
new file mode 100644
index 00000000000..281827928ce
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/common/atproto.ts
@@ -0,0 +1,91 @@
+import type * as Atproto from '@atproto/api';
+import type {
+ $Typed,
+ AppBskyEmbedExternal,
+ AppBskyEmbedImages,
+ AppBskyEmbedRecordWithMedia,
+ AppBskyEmbedVideo,
+ AppBskyFeedDefs,
+} from '@atproto/api';
+
+let atprotoModule: Promise<typeof Atproto> | undefined;
+
+function load(): Promise<typeof Atproto> {
+ if (atprotoModule === undefined) {
+ atprotoModule = import('@atproto/api').catch((error: unknown) => {
+ atprotoModule = undefined;
+ throw error;
+ });
+ }
+ return atprotoModule;
+}
+
+const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
+
+function graphemeLength(text: string): number {
+ let count = 0;
+ for (const segment of graphemeSegmenter.segment(text)) {
+ if (segment.segment !== '') {
+ count++;
+ }
+ }
+ return count;
+}
+
+function typeOf(value: unknown): string | undefined {
+ if (typeof value === 'object' && value !== null && '$type' in value && typeof value.$type === 'string') {
+ return value.$type;
+ }
+ return undefined;
+}
+
+function isReasonRepost(value: unknown): value is $Typed<AppBskyFeedDefs.ReasonRepost> {
+ return typeOf(value) === 'app.bsky.feed.defs#reasonRepost';
+}
+
+function isReasonPin(value: unknown): value is $Typed<AppBskyFeedDefs.ReasonPin> {
+ return typeOf(value) === 'app.bsky.feed.defs#reasonPin';
+}
+
+function isThreadViewPost(value: unknown): value is $Typed<AppBskyFeedDefs.ThreadViewPost> {
+ return typeOf(value) === 'app.bsky.feed.defs#threadViewPost';
+}
+
+function isNotFoundPost(value: unknown): value is $Typed<AppBskyFeedDefs.NotFoundPost> {
+ return typeOf(value) === 'app.bsky.feed.defs#notFoundPost';
+}
+
+function isBlockedPost(value: unknown): value is $Typed<AppBskyFeedDefs.BlockedPost> {
+ return typeOf(value) === 'app.bsky.feed.defs#blockedPost';
+}
+
+function isRecordWithMediaView(value: unknown): value is $Typed<AppBskyEmbedRecordWithMedia.View> {
+ return typeOf(value) === 'app.bsky.embed.recordWithMedia#view';
+}
+
+function isImagesView(value: unknown): value is $Typed<AppBskyEmbedImages.View> {
+ return typeOf(value) === 'app.bsky.embed.images#view';
+}
+
+function isVideoView(value: unknown): value is $Typed<AppBskyEmbedVideo.View> {
+ return typeOf(value) === 'app.bsky.embed.video#view';
+}
+
+function isExternalView(value: unknown): value is $Typed<AppBskyEmbedExternal.View> {
+ return typeOf(value) === 'app.bsky.embed.external#view';
+}
+
+export const blueskyAtproto = {
+ load,
+ graphemeLength,
+ typeOf,
+ isReasonRepost,
+ isReasonPin,
+ isThreadViewPost,
+ isNotFoundPost,
+ isBlockedPost,
+ isRecordWithMediaView,
+ isImagesView,
+ isVideoView,
+ isExternalView,
+};
diff --git a/packages/pieces/community/bluesky/src/lib/common/auth.ts b/packages/pieces/community/bluesky/src/lib/common/auth.ts
index 7124d44d369..c297de92a7d 100644
--- a/packages/pieces/community/bluesky/src/lib/common/auth.ts
+++ b/packages/pieces/community/bluesky/src/lib/common/auth.ts
@@ -1,20 +1,15 @@
import { PieceAuth, Property } from '@activepieces/pieces-framework';
-import { AtpAgent } from '@atproto/api';
-
-export interface BlueSkyAuthType {
- pdsHost?: string;
- identifier: string;
- password: string;
-}
+import { blueskyAtproto } from './atproto';
+import { blueskyClient } from './client';
const description = `
-To authenticate with Bluesky:
+To connect Bluesky:
-1. **PDS Host**: The Personal Data Server host. Leave empty to use the default Bluesky network (https://bsky.social).
-2. **Identifier**: Your Bluesky handle (e.g., yourhandle.bsky.social) or email address.
-3. **Password**: Your Bluesky account password or app password.
+1. **PDS Host**: Leave the default (https://bsky.social) unless your account lives on a self-hosted Personal Data Server.
+2. **Identifier**: Your Bluesky handle (for example yourname.bsky.social) or the email address of the account.
+3. **Password**: An **app password**. In Bluesky open **Settings → Privacy and security → App passwords**, click **Add App Password**, give it a name and paste the generated password here. Your main account password also works, but it grants full account access, so an app password is strongly recommended.
-For enhanced security, consider using an app password from your Bluesky account settings.
+Bluesky limits sign-ins to 30 per 5 minutes and 300 per day per account.
`;
export const blueskyAuth = PieceAuth.CustomAuth({
@@ -34,41 +29,42 @@ export const blueskyAuth = PieceAuth.CustomAuth({
}),
password: PieceAuth.SecretText({
displayName: 'Password',
- description: 'Your Bluesky account password or app password',
+ description: 'A Bluesky app password (recommended) or your account password',
required: true,
}),
},
validate: async ({ auth }) => {
+ let service: string;
try {
- const agent = new AtpAgent({
- service: auth.pdsHost || 'https://bsky.social',
- });
-
- await agent.login({
- identifier: auth.identifier,
- password: auth.password,
- });
-
+ service = blueskyClient.normalizePdsHost(auth.pdsHost);
+ } catch (error) {
+ return { valid: false, error: error instanceof Error ? error.message : 'Invalid PDS Host.' };
+ }
+ try {
+ const { AtpAgent } = await blueskyAtproto.load();
+ const agent = new AtpAgent({ service });
+ await agent.login({ identifier: auth.identifier.trim(), password: auth.password });
+ return { valid: true };
+ } catch (error) {
+ if (blueskyClient.isXrpcError(error) && (error.status === 401 || error.error === 'AuthenticationRequired')) {
+ return { valid: false, error: 'Invalid credentials. Please check your identifier and app password.' };
+ }
+ if (blueskyClient.isXrpcError(error) && error.status === 429) {
+ return { valid: false, error: 'Bluesky rate limit reached for sign-ins (30 per 5 minutes, 300 per day). Try again later.' };
+ }
+ if (blueskyClient.isXrpcError(error) && error.status === 400) {
+ return { valid: false, error: `Invalid request. Please check your identifier format. (${error.message})` };
+ }
return {
- valid: true,
+ valid: false,
+ error: `Authentication failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
};
- } catch (error: any) {
- if (error.message?.includes('Invalid identifier or password')) {
- return {
- valid: false,
- error: 'Invalid credentials. Please check your identifier and password.',
- };
- } else if (error.message?.includes('Invalid request')) {
- return {
- valid: false,
- error: 'Invalid request. Please check your identifier format.',
- };
- } else {
- return {
- valid: false,
- error: `Authentication failed: ${error.message || 'Unknown error'}`,
- };
- }
}
},
});
+
+export type BlueSkyAuthType = {
+ pdsHost?: string;
+ identifier: string;
+ password: string;
+};
diff --git a/packages/pieces/community/bluesky/src/lib/common/client.ts b/packages/pieces/community/bluesky/src/lib/common/client.ts
index 9dc61554fd7..f78a9e837d6 100644
--- a/packages/pieces/community/bluesky/src/lib/common/client.ts
+++ b/packages/pieces/community/bluesky/src/lib/common/client.ts
@@ -1,42 +1,217 @@
-import { AtpAgent } from '@atproto/api';
-import { BlueSkyAuthType } from './auth';
+import type { AtpAgent } from '@atproto/api';
+import { createHash } from 'crypto';
+import { blueskyAtproto } from './atproto';
+import type { BlueSkyAuthType } from './auth';
+
+const DEFAULT_PDS_HOST = 'https://bsky.social';
+const SESSION_TTL_MS = 50 * 60 * 1000;
+const TOKEN_REFRESH_MARGIN_SECONDS = 60;
const agentCache = new Map<string, { agent: AtpAgent; expires: number }>();
-export async function createBlueskyAgent(auth: BlueSkyAuthType): Promise<AtpAgent> {
- const cacheKey = `${auth.identifier}:${auth.pdsHost || 'https://bsky.social'}`;
+function normalizePdsHost(raw: string | undefined | null): string {
+ const trimmed = (raw ?? '').trim();
+ if (trimmed === '') {
+ return DEFAULT_PDS_HOST;
+ }
+ const withScheme = /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;
+ let parsed: URL;
+ try {
+ parsed = new URL(withScheme);
+ } catch {
+ throw new Error(`PDS Host "${trimmed}" is not a valid URL. Use something like https://bsky.social.`);
+ }
+ if (parsed.username !== '' || parsed.password !== '') {
+ throw new Error('PDS Host must not contain a username or password.');
+ }
+ return parsed.origin;
+}
+
+function cacheKeyFor(auth: BlueSkyAuthType): string {
+ const passwordHash = createHash('sha256').update(auth.password).digest('hex');
+ return `${normalizePdsHost(auth.pdsHost)}|${auth.identifier.trim().toLowerCase()}|${passwordHash}`;
+}
+
+async function createBlueskyAgent(auth: BlueSkyAuthType): Promise<AtpAgent> {
+ const cacheKey = cacheKeyFor(auth);
const cached = agentCache.get(cacheKey);
-
if (cached && Date.now() < cached.expires) {
return cached.agent;
}
-
+ const service = normalizePdsHost(auth.pdsHost);
+ const { AtpAgent } = await blueskyAtproto.load();
+ const agent = new AtpAgent({ service });
try {
- const agent = new AtpAgent({
- service: auth.pdsHost || 'https://bsky.social',
- });
-
- await agent.login({
- identifier: auth.identifier,
- password: auth.password,
- });
-
- agentCache.set(cacheKey, {
- agent,
- expires: Date.now() + 50 * 60 * 1000,
- });
-
- return agent;
- } catch (error: any) {
+ await agent.login({ identifier: auth.identifier.trim(), password: auth.password });
+ } catch (error) {
agentCache.delete(cacheKey);
- throw new Error(`Failed to create Bluesky agent: ${error.message || 'Unknown error'}`);
+ throw toBlueskyError({ error, action: 'sign in to Bluesky' });
+ }
+ agentCache.set(cacheKey, { agent, expires: Date.now() + SESSION_TTL_MS });
+ return agent;
+}
+
+function clearAgentCache(): void {
+ agentCache.clear();
+}
+
+function sessionDid(agent: AtpAgent): string {
+ const did = agent.session?.did;
+ if (!did) {
+ throw new Error('The Bluesky session has no account DID. Reconnect the Bluesky connection.');
+ }
+ return did;
+}
+
+async function withBluesky<T>({
+ auth,
+ action,
+ fn,
+}: {
+ auth: BlueSkyAuthType;
+ action: string;
+ fn: (agent: AtpAgent) => Promise<T>;
+}): Promise<T> {
+ const agent = await createBlueskyAgent(auth);
+ try {
+ return await fn(agent);
+ } catch (error) {
+ throw toBlueskyError({ error, action });
+ }
+}
+
+class BlueskyApiError extends Error {
+ readonly status: number;
+ readonly xrpcError: string;
+ constructor({ message, status, xrpcError }: { message: string; status: number; xrpcError: string }) {
+ super(message);
+ this.name = 'BlueskyApiError';
+ this.status = status;
+ this.xrpcError = xrpcError;
+ }
+}
+
+function isXrpcError(value: unknown): value is XrpcLikeError {
+ return (
+ value instanceof Error &&
+ 'status' in value &&
+ typeof value.status === 'number' &&
+ 'error' in value &&
+ typeof value.error === 'string'
+ );
+}
+
+function headerValue({ headers, name }: { headers: unknown; name: string }): string | undefined {
+ if (typeof headers !== 'object' || headers === null || !(name in headers)) {
+ return undefined;
+ }
+ const value: unknown = Reflect.get(headers, name);
+ return typeof value === 'string' ? value : undefined;
+}
+
+function toBlueskyError({ error, action }: { error: unknown; action: string }): Error {
+ if (error instanceof BlueskyApiError) {
+ return error;
+ }
+ if (!isXrpcError(error)) {
+ return error instanceof Error ? error : new Error(`Failed to ${action}: ${String(error)}`);
+ }
+ const vendorMessage = error.message && error.message !== error.error ? `${error.error}: ${error.message}` : error.error;
+ let message: string;
+ if (error.status === 429 || error.error === 'RateLimitExceeded') {
+ const reset = headerValue({ headers: error.headers, name: 'ratelimit-reset' });
+ const resetText = reset && /^\d+$/.test(reset) ? ` Limits reset at ${new Date(Number(reset) * 1000).toISOString()}.` : '';
+ message = `Bluesky rate limit reached while trying to ${action}. Sign-ins are limited to 30 per 5 minutes and 300 per day per account.${resetText} (${vendorMessage})`;
+ } else if (
+ error.status === 401 ||
+ error.error === 'AuthenticationRequired' ||
+ error.error === 'ExpiredToken' ||
+ error.error === 'InvalidToken'
+ ) {
+ message = `Bluesky rejected the credentials while trying to ${action}. Check the identifier and app password on the connection. (${vendorMessage})`;
+ } else if (error.error === 'AccountTakedown' || error.error === 'AccountDeactivated') {
+ message = `The Bluesky account cannot be used (${vendorMessage}).`;
+ } else if (error.status === 404 || error.error === 'RecordNotFound' || error.error === 'NotFound') {
+ message = `Bluesky could not find what was requested while trying to ${action}. (${vendorMessage})`;
+ } else if (error.status === 400) {
+ message = `Bluesky rejected the request to ${action}. (${vendorMessage})`;
+ } else {
+ message = `Failed to ${action}: Bluesky returned ${error.status}. (${vendorMessage})`;
+ }
+ return new BlueskyApiError({ message, status: error.status, xrpcError: error.error });
+}
+
+function jwtExpiry(token: string): number | undefined {
+ const parts = token.split('.');
+ if (parts.length !== 3) {
+ return undefined;
+ }
+ try {
+ const payload: unknown = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));
+ if (typeof payload === 'object' && payload !== null && 'exp' in payload && typeof payload.exp === 'number') {
+ return payload.exp;
+ }
+ } catch {
+ return undefined;
}
+ return undefined;
}
-export async function getCurrentSession(auth: BlueSkyAuthType) {
+async function freshAccessToken(auth: BlueSkyAuthType): Promise<string> {
const agent = await createBlueskyAgent(auth);
- return {
- did: agent.session?.did,
- handle: agent.session?.handle,
- };
+ const current = agent.session?.accessJwt;
+ const expiry = current ? jwtExpiry(current) : undefined;
+ const nowSeconds = Math.floor(Date.now() / 1000);
+ if (current && expiry !== undefined && expiry - TOKEN_REFRESH_MARGIN_SECONDS > nowSeconds) {
+ return current;
+ }
+ try {
+ await agent.sessionManager.refreshSession();
+ } catch (error) {
+ throw toBlueskyError({ error, action: 'refresh the Bluesky session' });
+ }
+ const refreshed = agent.session?.accessJwt;
+ if (!refreshed) {
+ throw new Error('Could not refresh the Bluesky session. Reconnect the Bluesky connection.');
+ }
+ return refreshed;
+}
+
+function assertSameOrigin({ url, pdsHost }: { url: unknown; pdsHost: string }): void {
+ if (typeof url !== 'string' || !/^[a-z][a-z0-9+.-]*:|^\/\//i.test(url.trim())) {
+ return;
+ }
+ let target: URL;
+ try {
+ target = new URL(url.trim());
+ } catch {
+ throw new Error('The custom API call URL is not valid.');
+ }
+ const base = new URL(pdsHost);
+ if (target.origin !== base.origin || target.username !== '' || target.password !== '') {
+ throw new Error(`Custom API calls can only go to the connection's PDS host (${base.origin}). Use a path such as /app.bsky.actor.getProfile instead of a full URL.`);
+ }
}
+
+async function getCurrentSession(auth: BlueSkyAuthType): Promise<{ did: string | undefined; handle: string | undefined }> {
+ const agent = await createBlueskyAgent(auth);
+ return { did: agent.session?.did, handle: agent.session?.handle };
+}
+
+export const blueskyClient = {
+ DEFAULT_PDS_HOST,
+ normalizePdsHost,
+ createAgent: createBlueskyAgent,
+ clearAgentCache,
+ sessionDid,
+ withBluesky,
+ isXrpcError,
+ toBlueskyError,
+ freshAccessToken,
+ assertSameOrigin,
+ getCurrentSession,
+};
+
+export { createBlueskyAgent, BlueskyApiError };
+
+type XrpcLikeError = { status: number; error: string; message: string; headers?: Record<string, string> };
diff --git a/packages/pieces/community/bluesky/src/lib/common/compose.ts b/packages/pieces/community/bluesky/src/lib/common/compose.ts
new file mode 100644
index 00000000000..7de530d50b8
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/common/compose.ts
@@ -0,0 +1,372 @@
+import type {
+ $Typed,
+ AppBskyEmbedExternal,
+ AppBskyEmbedImages,
+ AppBskyEmbedVideo,
+ AppBskyFeedPost,
+ AtpAgent,
+ BlobRef,
+ RichText,
+} from '@atproto/api';
+import { blueskyAtproto } from './atproto';
+import { blueskyDownload } from './download';
+import { blueskyRefs } from './refs';
+
+const MAX_POST_GRAPHEMES = 300;
+const MAX_TAGS = 8;
+const MAX_TAG_GRAPHEMES = 64;
+const MAX_IMAGES = 4;
+const MAX_LANGS = 3;
+const MAX_IMAGE_BYTES = 1_000_000;
+const MAX_VIDEO_BYTES = 52_428_800;
+const MAX_HTML_BYTES = 1_000_000;
+const FETCH_TIMEOUT_MS = 15_000;
+const HTML_ACCEPT = 'text/html,application/xhtml+xml;q=0.9,*/*;q=0.8';
+const VIDEO_FETCH_TIMEOUT_MS = 120_000;
+const MAX_META_TAG_LENGTH = 2_000;
+const LEGACY_WARNING_MAP: Record<string, string | null> = {
+ adult: 'porn',
+ violence: 'graphic-media',
+ sensitive: 'sexual',
+ spam: null,
+ 'graphic-media': 'graphic-media',
+ sexual: 'sexual',
+ nudity: 'nudity',
+ porn: 'porn',
+};
+const SELF_LABEL_VALUES = ['sexual', 'nudity', 'porn', 'graphic-media'];
+
+function graphemeLength(text: string): number {
+ return blueskyAtproto.graphemeLength(text);
+}
+
+async function buildRichText({ agent, text }: { agent: AtpAgent; text: string }): Promise<RichText> {
+ const { RichText } = await blueskyAtproto.load();
+ const richText = new RichText({ text });
+ await richText.detectFacets(agent);
+ return richText;
+}
+
+function assertPostLength({ text, label }: { text: string; label: string }): void {
+ const length = graphemeLength(text);
+ if (length > MAX_POST_GRAPHEMES) {
+ throw new Error(`${label} is ${length} characters long; Bluesky allows at most ${MAX_POST_GRAPHEMES}.`);
+ }
+}
+
+function normalizeTags(raw: unknown[]): string[] {
+ const tags = raw
+ .flatMap((value) => (typeof value === 'string' ? value.split(',') : []))
+ .map((tag) => tag.trim().replace(/^#/, ''))
+ .filter((tag) => tag !== '');
+ const unique = [...new Set(tags)];
+ if (unique.length > MAX_TAGS) {
+ throw new Error(`Bluesky allows at most ${MAX_TAGS} tags per post; got ${unique.length}.`);
+ }
+ const tooLong = unique.find((tag) => graphemeLength(tag) > MAX_TAG_GRAPHEMES);
+ if (tooLong !== undefined) {
+ throw new Error(`The tag "${tooLong}" is longer than ${MAX_TAG_GRAPHEMES} characters.`);
+ }
+ return unique;
+}
+
+function normalizeLangs(raw: unknown[]): string[] {
+ const langs = [...new Set(raw.flatMap((value) => (typeof value === 'string' && value.trim() !== '' ? [value.trim()] : [])))];
+ if (langs.length > MAX_LANGS) {
+ throw new Error(`Bluesky allows at most ${MAX_LANGS} languages per post; got ${langs.length}.`);
+ }
+ return langs;
+}
+
+function mapContentWarnings(raw: unknown[]): string[] {
+ const mapped = raw.flatMap((value) => {
+ if (typeof value !== 'string') {
+ return [];
+ }
+ const label = value in LEGACY_WARNING_MAP ? LEGACY_WARNING_MAP[value] : null;
+ return label === null ? [] : [label];
+ });
+ return [...new Set(mapped)];
+}
+
+function selfLabels(values: string[]): AppBskyFeedPost.Record['labels'] {
+ const valid = values.filter((value) => SELF_LABEL_VALUES.includes(value));
+ if (valid.length === 0) {
+ return undefined;
+ }
+ return {
+ $type: 'com.atproto.label.defs#selfLabels',
+ values: valid.map((val) => ({ val })),
+ };
+}
+
+function stringList(raw: unknown): string[] {
+ if (!Array.isArray(raw)) {
+ return [];
+ }
+ return raw.flatMap((value) => (typeof value === 'string' && value.trim() !== '' ? [value.trim()] : []));
+}
+
+function assertHttpUrl({ url, label }: { url: string; label: string }): URL {
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ throw new Error(`${label} "${url}" is not a valid URL.`);
+ }
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
+ throw new Error(`${label} "${url}" must start with http:// or https://.`);
+ }
+ return parsed;
+}
+
+async function fetchBinary({
+ url,
+ maxBytes,
+ timeoutMs = FETCH_TIMEOUT_MS,
+ accept = '*/*',
+ label,
+}: {
+ url: string;
+ maxBytes: number;
+ timeoutMs?: number;
+ accept?: string;
+ label: string;
+}): Promise<{ data: Uint8Array; contentType: string }> {
+ return blueskyDownload.download({ url, maxBytes, timeoutMs, accept, label });
+}
+
+function sniffImageType(data: Uint8Array): string | undefined {
+ if (data.length >= 8 && data[0] === 0x89 && data[1] === 0x50 && data[2] === 0x4e && data[3] === 0x47) {
+ return 'image/png';
+ }
+ if (data.length >= 3 && data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff) {
+ return 'image/jpeg';
+ }
+ if (data.length >= 6 && data[0] === 0x47 && data[1] === 0x49 && data[2] === 0x46 && data[3] === 0x38) {
+ return 'image/gif';
+ }
+ if (
+ data.length >= 12 &&
+ data[0] === 0x52 && data[1] === 0x49 && data[2] === 0x46 && data[3] === 0x46 &&
+ data[8] === 0x57 && data[9] === 0x45 && data[10] === 0x42 && data[11] === 0x50
+ ) {
+ return 'image/webp';
+ }
+ return undefined;
+}
+
+function imageEncoding({ data, contentType, url }: { data: Uint8Array; contentType: string; url: string }): string {
+ const sniffed = sniffImageType(data);
+ if (sniffed) {
+ return sniffed;
+ }
+ if (contentType.startsWith('image/')) {
+ return contentType;
+ }
+ throw new Error(`The file at ${url} is not a PNG, JPEG, GIF or WebP image.`);
+}
+
+async function uploadImages({
+ agent,
+ images,
+}: {
+ agent: AtpAgent;
+ images: { url: string; alt: string }[];
+}): Promise<$Typed<AppBskyEmbedImages.Main> | undefined> {
+ if (images.length === 0) {
+ return undefined;
+ }
+ if (images.length > MAX_IMAGES) {
+ throw new Error(`Bluesky allows at most ${MAX_IMAGES} images per post; got ${images.length}.`);
+ }
+ const uploaded: { alt: string; image: BlobRef }[] = [];
+ for (const [index, image] of images.entries()) {
+ const { data, contentType } = await fetchBinary({ url: image.url, maxBytes: MAX_IMAGE_BYTES, label: `Image ${index + 1}` });
+ const encoding = imageEncoding({ data, contentType, url: image.url });
+ const blob = await agent.uploadBlob(data, { encoding });
+ uploaded.push({ alt: image.alt, image: blob.data.blob });
+ }
+ return { $type: 'app.bsky.embed.images', images: uploaded };
+}
+
+async function uploadVideo({
+ agent,
+ url,
+ alt,
+ captions,
+}: {
+ agent: AtpAgent;
+ url: string;
+ alt?: string;
+ captions: { url: string; lang: string }[];
+}): Promise<$Typed<AppBskyEmbedVideo.Main>> {
+ const { data, contentType } = await fetchBinary({ url, maxBytes: MAX_VIDEO_BYTES, timeoutMs: VIDEO_FETCH_TIMEOUT_MS, label: 'Video' });
+ if (contentType !== '' && !contentType.startsWith('video/') && contentType !== 'application/octet-stream') {
+ throw new Error(`The file at ${url} is not a video (content type ${contentType}).`);
+ }
+ const video = await agent.uploadBlob(data, { encoding: contentType.startsWith('video/') ? contentType : 'video/mp4' });
+ const captionRefs: { lang: string; file: BlobRef }[] = [];
+ for (const caption of captions) {
+ const file = await fetchBinary({ url: caption.url, maxBytes: 20_000, label: 'Caption file' });
+ const blob = await agent.uploadBlob(file.data, { encoding: 'text/vtt' });
+ captionRefs.push({ lang: caption.lang, file: blob.data.blob });
+ }
+ return {
+ $type: 'app.bsky.embed.video',
+ video: video.data.blob,
+ ...(alt ? { alt } : {}),
+ ...(captionRefs.length > 0 ? { captions: captionRefs } : {}),
+ };
+}
+
+function metaTags(html: string): Record<string, string> {
+ const tags = html.match(new RegExp(`<meta\\b[^>]{0,${MAX_META_TAG_LENGTH}}>`, 'gi')) ?? [];
+ return tags.reduce<Record<string, string>>((found, tag) => {
+ const attributes = Object.fromEntries(
+ [...tag.matchAll(/([a-zA-Z:_-]{1,40})\s*=\s*("([^"]*)"|'([^']*)')/g)].map((match) => [
+ match[1].toLowerCase(),
+ match[3] ?? match[4] ?? '',
+ ]),
+ );
+ const name = (attributes['property'] ?? attributes['name'] ?? '').toLowerCase();
+ const content = attributes['content'];
+ if (name === '' || content === undefined || name in found) {
+ return found;
+ }
+ return { ...found, [name]: decodeEntities(content.trim()) };
+ }, {});
+}
+
+function decodeEntities(value: string): string {
+ return value
+ .replace(/&quot;/g, '"')
+ .replace(/&#39;|&apos;/g, "'")
+ .replace(/&lt;/g, '<')
+ .replace(/&gt;/g, '>')
+ .replace(/&amp;/g, '&');
+}
+
+function htmlTitle(html: string): string | undefined {
+ const match = html.match(/<title[^>]{0,200}>([^<]{0,500})<\/title>/i);
+ return match ? decodeEntities(match[1].trim()) : undefined;
+}
+
+async function buildLinkCard({ agent, url }: { agent: AtpAgent; url: string }): Promise<$Typed<AppBskyEmbedExternal.Main>> {
+ assertHttpUrl({ url, label: 'Link' });
+ const basic = { uri: url, title: url, description: 'Shared link' };
+ let html: string;
+ try {
+ const page = await fetchBinary({ url, maxBytes: MAX_HTML_BYTES, accept: HTML_ACCEPT, label: 'Link page' });
+ html = new TextDecoder().decode(page.data);
+ } catch {
+ return { $type: 'app.bsky.embed.external', external: basic };
+ }
+ const meta = metaTags(html);
+ const title = meta['og:title'] || meta['twitter:title'] || htmlTitle(html) || url;
+ const description = meta['og:description'] || meta['description'] || meta['twitter:description'] || 'Shared link';
+ const imageUrl = meta['og:image'] || meta['twitter:image'];
+ const thumb = imageUrl ? await uploadThumb({ agent, imageUrl, pageUrl: url }) : undefined;
+ return {
+ $type: 'app.bsky.embed.external',
+ external: { uri: url, title, description, ...(thumb ? { thumb } : {}) },
+ };
+}
+
+async function uploadThumb({ agent, imageUrl, pageUrl }: { agent: AtpAgent; imageUrl: string; pageUrl: string }): Promise<BlobRef | undefined> {
+ try {
+ const absolute = new URL(imageUrl, pageUrl).href;
+ const { data, contentType } = await fetchBinary({ url: absolute, maxBytes: MAX_IMAGE_BYTES, label: 'Link thumbnail' });
+ const encoding = sniffImageType(data) ?? (contentType.startsWith('image/') ? contentType : undefined);
+ if (!encoding) {
+ return undefined;
+ }
+ const blob = await agent.uploadBlob(data, { encoding });
+ return blob.data.blob;
+ } catch {
+ return undefined;
+ }
+}
+
+async function fetchPostView({ agent, input }: { agent: AtpAgent; input: string }) {
+ const ref = await blueskyRefs.resolvePostRef({ agent, input });
+ const response = await agent.getPosts({ uris: [ref.uri] });
+ const post = response.data.posts[0];
+ if (!post) {
+ throw new Error(`The post ${input} was not found or is not visible to this account.`);
+ }
+ return post;
+}
+
+async function replyRefs({ agent, input }: { agent: AtpAgent; input: string }) {
+ const parent = await fetchPostView({ agent, input });
+ const parentRef = { uri: parent.uri, cid: parent.cid };
+ return { root: replyRootOf(parent.record) ?? parentRef, parent: parentRef };
+}
+
+function replyRootOf(record: unknown): { uri: string; cid: string } | undefined {
+ if (typeof record !== 'object' || record === null || !('reply' in record)) {
+ return undefined;
+ }
+ const reply: unknown = record.reply;
+ if (typeof reply !== 'object' || reply === null || !('root' in reply)) {
+ return undefined;
+ }
+ const root: unknown = reply.root;
+ if (typeof root === 'object' && root !== null && 'uri' in root && 'cid' in root && typeof root.uri === 'string' && typeof root.cid === 'string') {
+ return { uri: root.uri, cid: root.cid };
+ }
+ return undefined;
+}
+
+async function quoteRef({ agent, input }: { agent: AtpAgent; input: string }) {
+ const quoted = await fetchPostView({ agent, input });
+ return { uri: quoted.uri, cid: quoted.cid };
+}
+
+function combineEmbed({
+ quote,
+ media,
+}: {
+ quote?: { uri: string; cid: string };
+ media?: MediaEmbed;
+}): AppBskyFeedPost.Record['embed'] {
+ if (quote && media) {
+ return {
+ $type: 'app.bsky.embed.recordWithMedia',
+ record: { $type: 'app.bsky.embed.record', record: quote },
+ media,
+ };
+ }
+ if (quote) {
+ return { $type: 'app.bsky.embed.record', record: quote };
+ }
+ return media;
+}
+
+export const blueskyCompose = {
+ MAX_POST_GRAPHEMES,
+ MAX_IMAGES,
+ MAX_VIDEO_BYTES,
+ SELF_LABEL_VALUES,
+ graphemeLength,
+ buildRichText,
+ assertPostLength,
+ normalizeTags,
+ normalizeLangs,
+ mapContentWarnings,
+ selfLabels,
+ stringList,
+ uploadImages,
+ uploadVideo,
+ buildLinkCard,
+ metaTags,
+ sniffImageType,
+ fetchBinary,
+ replyRefs,
+ quoteRef,
+ fetchPostView,
+ combineEmbed,
+};
+
+type MediaEmbed = $Typed<AppBskyEmbedImages.Main> | $Typed<AppBskyEmbedVideo.Main> | $Typed<AppBskyEmbedExternal.Main>;
diff --git a/packages/pieces/community/bluesky/src/lib/common/download.ts b/packages/pieces/community/bluesky/src/lib/common/download.ts
new file mode 100644
index 00000000000..678ae9a0a4a
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/common/download.ts
@@ -0,0 +1,324 @@
+import { lookup, LookupAddress, LookupOptions } from 'node:dns';
+import { IncomingMessage, request as httpRequest } from 'node:http';
+import { request as httpsRequest } from 'node:https';
+import { BlockList, isIP } from 'node:net';
+
+const MAX_REDIRECTS = 5;
+const REDIRECT_STATUSES = [301, 302, 303, 307, 308];
+const USER_AGENT = 'Mozilla/5.0 (compatible; Activepieces-Bot/1.0)';
+const BLOCKED_IPV4_SUBNETS: [string, number][] = [
+ ['0.0.0.0', 8],
+ ['10.0.0.0', 8],
+ ['100.64.0.0', 10],
+ ['127.0.0.0', 8],
+ ['169.254.0.0', 16],
+ ['172.16.0.0', 12],
+ ['192.0.0.0', 24],
+ ['192.0.2.0', 24],
+ ['192.88.99.0', 24],
+ ['192.168.0.0', 16],
+ ['198.18.0.0', 15],
+ ['198.51.100.0', 24],
+ ['203.0.113.0', 24],
+ ['224.0.0.0', 4],
+ ['240.0.0.0', 4],
+];
+const BLOCKED_IPV6_SUBNETS: [string, number][] = [
+ ['::', 128],
+ ['::1', 128],
+ ['64:ff9b::', 96],
+ ['64:ff9b:1::', 48],
+ ['100::', 64],
+ ['2001::', 32],
+ ['2001:db8::', 32],
+ ['2002::', 16],
+ ['fc00::', 7],
+ ['fe80::', 10],
+ ['fec0::', 10],
+ ['ff00::', 8],
+];
+
+const blockList = buildBlockList();
+
+function buildBlockList(): BlockList {
+ const list = new BlockList();
+ for (const [network, prefix] of BLOCKED_IPV4_SUBNETS) {
+ list.addSubnet(network, prefix, 'ipv4');
+ }
+ for (const [network, prefix] of BLOCKED_IPV6_SUBNETS) {
+ list.addSubnet(network, prefix, 'ipv6');
+ }
+ return list;
+}
+
+function isBlockedAddress(address: string): boolean {
+ const bare = address.replace(/^\[|\]$/g, '');
+ const version = isIP(bare);
+ if (version === 4) {
+ return blockList.check(bare, 'ipv4');
+ }
+ if (version === 6) {
+ const mapped = mappedIpv4(bare);
+ return mapped === undefined ? blockList.check(bare, 'ipv6') : blockList.check(mapped, 'ipv4');
+ }
+ return true;
+}
+
+function mappedIpv4(address: string): string | undefined {
+ const dotted = address.match(/^(?:0{0,4}:){0,5}:?ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i);
+ if (dotted) {
+ return dotted[1];
+ }
+ const hex = address.match(/^(?:0{0,4}:){0,5}:?ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);
+ if (!hex) {
+ return undefined;
+ }
+ const high = parseInt(hex[1], 16);
+ const low = parseInt(hex[2], 16);
+ return [high >> 8, high & 0xff, low >> 8, low & 0xff].join('.');
+}
+
+function guardedLookup({
+ hostname,
+ options,
+ callback,
+}: {
+ hostname: string;
+ options: LookupOptions;
+ callback: (error: NodeJS.ErrnoException | null, address: string | LookupAddress[], family?: number) => void;
+}): void {
+ lookup(hostname, { ...options, all: true }, (error, addresses) => {
+ if (error) {
+ callback(error, '', 0);
+ return;
+ }
+ const blocked = addresses.find((entry) => blueskyDownload.isBlockedAddress(entry.address));
+ if (blocked !== undefined || addresses.length === 0) {
+ callback(new PrivateAddressError({ host: hostname, address: blocked?.address }), '', 0);
+ return;
+ }
+ if (options.all) {
+ callback(null, addresses);
+ return;
+ }
+ callback(null, addresses[0].address, addresses[0].family);
+ });
+}
+
+function parseHttpUrl({ url, label }: { url: string; label: string }): URL {
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ throw new Error(`${label} "${url}" is not a valid URL.`);
+ }
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
+ throw new Error(`${label} "${url}" must start with http:// or https://.`);
+ }
+ if (parsed.username !== '' || parsed.password !== '') {
+ throw new Error(`${label} "${url}" must not contain a username or password.`);
+ }
+ const host = parsed.hostname.replace(/^\[|\]$/g, '');
+ if (isIP(host) !== 0 && blueskyDownload.isBlockedAddress(host)) {
+ throw new PrivateAddressError({ host, address: host });
+ }
+ return parsed;
+}
+
+async function download({
+ url,
+ maxBytes,
+ timeoutMs,
+ accept,
+ label,
+}: {
+ url: string;
+ maxBytes: number;
+ timeoutMs: number;
+ accept: string;
+ label: string;
+}): Promise<{ data: Uint8Array; contentType: string }> {
+ const deadline = Date.now() + timeoutMs;
+ let target = parseHttpUrl({ url, label });
+ for (let hop = 0; ; hop++) {
+ const response = await openOrFail({ target, accept, deadline, timeoutMs, url, label });
+ const status = response.statusCode ?? 0;
+ if (REDIRECT_STATUSES.includes(status)) {
+ response.destroy();
+ const location = headerValue(response.headers['location']);
+ if (location === undefined) {
+ throw new Error(`Could not download ${label} from ${url}: HTTP ${status} without a Location header.`);
+ }
+ if (hop >= MAX_REDIRECTS) {
+ throw new Error(`Could not download ${label} from ${url}: more than ${MAX_REDIRECTS} redirects.`);
+ }
+ target = redirectTarget({ location, base: target, url, label });
+ continue;
+ }
+ if (status < 200 || status >= 300) {
+ response.destroy();
+ throw new Error(`Could not download ${label} from ${url}: HTTP ${status}.`);
+ }
+ const declared = Number(headerValue(response.headers['content-length']) ?? '');
+ if (Number.isFinite(declared) && declared > maxBytes) {
+ response.destroy();
+ throw new Error(`${label} at ${url} is ${formatBytes(declared)}; the limit is ${formatBytes(maxBytes)}.`);
+ }
+ const data = await readCapped({ stream: response, maxBytes, url, label, deadline, timeoutMs });
+ const contentType = headerValue(response.headers['content-type']) ?? '';
+ return { data, contentType: contentType.split(';')[0].trim().toLowerCase() };
+ }
+}
+
+function redirectTarget({ location, base, url, label }: { location: string; base: URL; url: string; label: string }): URL {
+ let next: string;
+ try {
+ next = new URL(location, base).href;
+ } catch {
+ throw new Error(`Could not download ${label} from ${url}: the redirect location "${location}" is not a valid URL.`);
+ }
+ try {
+ return parseHttpUrl({ url: next, label: `${label} redirect` });
+ } catch (error) {
+ throw new Error(`Could not download ${label} from ${url}: ${error instanceof Error ? error.message : String(error)}`);
+ }
+}
+
+async function openOrFail({
+ target,
+ accept,
+ deadline,
+ timeoutMs,
+ url,
+ label,
+}: {
+ target: URL;
+ accept: string;
+ deadline: number;
+ timeoutMs: number;
+ url: string;
+ label: string;
+}): Promise<IncomingMessage> {
+ try {
+ return await open({ target, accept, deadline, timeoutMs });
+ } catch (error) {
+ throw new Error(`Could not download ${label} from ${url}: ${error instanceof Error ? error.message : String(error)}`);
+ }
+}
+
+function open({ target, accept, deadline, timeoutMs }: { target: URL; accept: string; deadline: number; timeoutMs: number }): Promise<IncomingMessage> {
+ return new Promise((resolve, reject) => {
+ const remaining = deadline - Date.now();
+ if (remaining <= 0) {
+ reject(timeoutError(timeoutMs));
+ return;
+ }
+ const headers = { 'User-Agent': USER_AGENT, Accept: accept };
+ const onResponse = (response: IncomingMessage): void => {
+ clearTimeout(timer);
+ resolve(response);
+ };
+ const request =
+ target.protocol === 'https:'
+ ? httpsRequest(
+ target,
+ {
+ method: 'GET',
+ headers,
+ agent: false,
+ rejectUnauthorized: true,
+ lookup: (hostname, options, callback) => guardedLookup({ hostname, options, callback }),
+ },
+ onResponse,
+ )
+ : httpRequest(
+ target,
+ { method: 'GET', headers, agent: false, lookup: (hostname, options, callback) => guardedLookup({ hostname, options, callback }) },
+ onResponse,
+ );
+ const timer = setTimeout(() => {
+ request.destroy(timeoutError(timeoutMs));
+ }, remaining);
+ request.on('error', (error) => {
+ clearTimeout(timer);
+ reject(error);
+ });
+ request.end();
+ });
+}
+
+async function readCapped({
+ stream,
+ maxBytes,
+ url,
+ label,
+ deadline,
+ timeoutMs,
+}: {
+ stream: IncomingMessage;
+ maxBytes: number;
+ url: string;
+ label: string;
+ deadline: number;
+ timeoutMs: number;
+}): Promise<Uint8Array> {
+ const chunks: Buffer[] = [];
+ let total = 0;
+ let tooLarge = false;
+ const timer = setTimeout(() => {
+ stream.destroy(timeoutError(timeoutMs));
+ }, Math.max(1, deadline - Date.now()));
+ try {
+ for await (const chunk of stream) {
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
+ total += buffer.byteLength;
+ if (total > maxBytes) {
+ tooLarge = true;
+ break;
+ }
+ chunks.push(buffer);
+ }
+ } catch (error) {
+ throw new Error(`Could not download ${label} from ${url}: ${error instanceof Error ? error.message : String(error)}`);
+ } finally {
+ clearTimeout(timer);
+ if (tooLarge) {
+ stream.destroy();
+ }
+ }
+ if (tooLarge) {
+ throw new Error(`${label} at ${url} is larger than the ${formatBytes(maxBytes)} limit.`);
+ }
+ return new Uint8Array(Buffer.concat(chunks, total));
+}
+
+function timeoutError(timeoutMs: number): Error {
+ return new Error(`timed out after ${Math.round(timeoutMs / 1000)} s`);
+}
+
+function headerValue(value: string | string[] | undefined): string | undefined {
+ return Array.isArray(value) ? value[0] : value;
+}
+
+function formatBytes(bytes: number): string {
+ return bytes >= 1_000_000 ? `${(bytes / 1_000_000).toFixed(1)} MB` : `${Math.round(bytes / 1000)} KB`;
+}
+
+class PrivateAddressError extends Error {
+ constructor({ host, address }: { host: string; address: string | undefined }) {
+ super(
+ address === undefined || address === host
+ ? `${host} is a private, loopback or internal address; only public internet addresses can be downloaded.`
+ : `${host} resolves to ${address}, a private, loopback or internal address; only public internet addresses can be downloaded.`,
+ );
+ this.name = 'PrivateAddressError';
+ }
+}
+
+export const blueskyDownload = {
+ MAX_REDIRECTS,
+ download,
+ isBlockedAddress,
+ guardedLookup,
+ parseHttpUrl,
+};
diff --git a/packages/pieces/community/bluesky/src/lib/common/mappers.ts b/packages/pieces/community/bluesky/src/lib/common/mappers.ts
new file mode 100644
index 00000000000..878805e9c1b
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/common/mappers.ts
@@ -0,0 +1,148 @@
+import type {
+ AppBskyActorDefs,
+ AppBskyFeedDefs,
+ AppBskyGraphDefs,
+ AppBskyNotificationListNotifications,
+} from '@atproto/api';
+import { blueskyAtproto } from './atproto';
+import { blueskyRefs } from './refs';
+
+function mediaFlags(embed: AppBskyFeedDefs.PostView['embed']): MediaFlags {
+ const media = embed && blueskyAtproto.isRecordWithMediaView(embed) ? embed.media : embed;
+ return {
+ hasImages: media !== undefined && blueskyAtproto.isImagesView(media),
+ hasVideo: media !== undefined && blueskyAtproto.isVideoView(media),
+ hasExternalLink: media !== undefined && blueskyAtproto.isExternalView(media),
+ };
+}
+
+function recordText(record: unknown): string {
+ if (typeof record === 'object' && record !== null && 'text' in record && typeof record.text === 'string') {
+ return record.text;
+ }
+ return '';
+}
+
+function recordReplyParentUri(record: unknown): string | null {
+ if (typeof record !== 'object' || record === null || !('reply' in record)) {
+ return null;
+ }
+ const reply: unknown = record.reply;
+ if (typeof reply !== 'object' || reply === null || !('parent' in reply)) {
+ return null;
+ }
+ const parent: unknown = reply.parent;
+ if (typeof parent === 'object' && parent !== null && 'uri' in parent && typeof parent.uri === 'string') {
+ return parent.uri;
+ }
+ return null;
+}
+
+function postBase(post: AppBskyFeedDefs.PostView) {
+ return {
+ uri: post.uri,
+ cid: post.cid,
+ url: blueskyRefs.postWebUrl({ uri: post.uri, handle: post.author.handle }),
+ author: post.author,
+ record: post.record,
+ indexedAt: post.indexedAt,
+ replyCount: post.replyCount ?? 0,
+ repostCount: post.repostCount ?? 0,
+ likeCount: post.likeCount ?? 0,
+ quoteCount: post.quoteCount ?? 0,
+ labels: post.labels ?? [],
+ viewer: post.viewer ?? {},
+ embed: post.embed ?? null,
+ };
+}
+
+function feedItem(entry: AppBskyFeedDefs.FeedViewPost) {
+ const repost = entry.reason && blueskyAtproto.isReasonRepost(entry.reason) ? entry.reason : undefined;
+ return {
+ ...postBase(entry.post),
+ text: recordText(entry.post.record),
+ isRepost: repost !== undefined,
+ repostedBy: repost ? repost.by : null,
+ repostedAt: repost ? repost.indexedAt : null,
+ isReply: recordReplyParentUri(entry.post.record) !== null,
+ replyToUri: recordReplyParentUri(entry.post.record),
+ isPinned: entry.reason !== undefined && blueskyAtproto.isReasonPin(entry.reason),
+ };
+}
+
+function profileItem(profile: AppBskyActorDefs.ProfileView | AppBskyActorDefs.ProfileViewDetailed) {
+ return {
+ did: profile.did,
+ handle: profile.handle,
+ displayName: profile.displayName ?? '',
+ description: profile.description ?? '',
+ avatar: profile.avatar ?? '',
+ url: blueskyRefs.profileWebUrl(profile.handle === 'handle.invalid' ? profile.did : profile.handle),
+ createdAt: profile.createdAt ?? null,
+ indexedAt: profile.indexedAt ?? null,
+ viewer: profile.viewer ?? {},
+ labels: profile.labels ?? [],
+ };
+}
+
+function detailedProfile(profile: AppBskyActorDefs.ProfileViewDetailed) {
+ return {
+ ...profileItem(profile),
+ banner: profile.banner ?? '',
+ followersCount: profile.followersCount ?? 0,
+ followsCount: profile.followsCount ?? 0,
+ postsCount: profile.postsCount ?? 0,
+ pinnedPost: profile.pinnedPost ?? null,
+ };
+}
+
+function notificationItem(notification: AppBskyNotificationListNotifications.Notification) {
+ return {
+ uri: notification.uri,
+ cid: notification.cid,
+ reason: notification.reason,
+ reasonSubject: notification.reasonSubject ?? null,
+ isRead: notification.isRead,
+ indexedAt: notification.indexedAt,
+ author: profileItem(notification.author),
+ text: recordText(notification.record),
+ record: notification.record,
+ url: blueskyRefs.parseAtUri(notification.uri)?.collection === blueskyRefs.POST_COLLECTION
+ ? blueskyRefs.postWebUrl({ uri: notification.uri, handle: notification.author.handle })
+ : '',
+ };
+}
+
+function listItem(list: AppBskyGraphDefs.ListView) {
+ return {
+ uri: list.uri,
+ cid: list.cid,
+ name: list.name,
+ purpose: list.purpose,
+ description: list.description ?? '',
+ avatar: list.avatar ?? '',
+ listItemCount: list.listItemCount ?? 0,
+ indexedAt: list.indexedAt,
+ creator: profileItem(list.creator),
+ url: blueskyRefs.postWebUrl({ uri: list.uri, handle: list.creator.handle }),
+ };
+}
+
+function pageOf<T>({ items, cursor }: { items: T[]; cursor: string | undefined }): { items: T[]; cursor: string | null; hasMore: boolean } {
+ return { items, cursor: cursor ?? null, hasMore: Boolean(cursor) };
+}
+
+export const blueskyMappers = {
+ pageOf,
+ mediaFlags,
+ recordText,
+ recordReplyParentUri,
+ postBase,
+ feedItem,
+ profileItem,
+ detailedProfile,
+ notificationItem,
+ listItem,
+};
+
+type MediaFlags = { hasImages: boolean; hasVideo: boolean; hasExternalLink: boolean };
diff --git a/packages/pieces/community/bluesky/src/lib/common/polling.ts b/packages/pieces/community/bluesky/src/lib/common/polling.ts
new file mode 100644
index 00000000000..fd41925976c
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/common/polling.ts
@@ -0,0 +1,240 @@
+const WINDOW_MS = 15 * 60 * 1000;
+const MAX_PAGES = 10;
+const SEEN_CAP = 500;
+const RESUME_STOP_KEYS = 100;
+const TEST_SAMPLE_SIZE = 5;
+
+function isPollState(value: unknown): value is PollState {
+ return (
+ typeof value === 'object' &&
+ value !== null &&
+ 'seen' in value &&
+ isStringArray(value.seen) &&
+ 'lastTime' in value &&
+ typeof value.lastTime === 'number'
+ );
+}
+
+function isStringArray(value: unknown): value is string[] {
+ return Array.isArray(value) && value.every((key: unknown) => typeof key === 'string');
+}
+
+function resumeOf(state: PollState): PollResume | undefined {
+ const resume: unknown = state.resume;
+ if (
+ typeof resume === 'object' &&
+ resume !== null &&
+ 'cursor' in resume &&
+ typeof resume.cursor === 'string' &&
+ 'stopBefore' in resume &&
+ typeof resume.stopBefore === 'number' &&
+ 'stopKeys' in resume &&
+ isStringArray(resume.stopKeys)
+ ) {
+ return { cursor: resume.cursor, stopBefore: resume.stopBefore, stopKeys: resume.stopKeys };
+ }
+ return undefined;
+}
+
+async function collect<T>({
+ fetchPage,
+ startCursor,
+ stopBefore,
+ maxPages,
+ seen,
+}: {
+ fetchPage: PageFetcher<T>;
+ startCursor?: string;
+ stopBefore: number;
+ maxPages: number;
+ seen: Set<string>;
+}): Promise<{ items: PollItem<T>[]; newestTime: number | undefined; unfinishedCursor: string | undefined }> {
+ const pages: PollPage<T>[] = [];
+ let cursor: string | undefined = startCursor;
+ let unfinishedCursor: string | undefined = undefined;
+ for (let page = 0; page < maxPages; page++) {
+ const result: PollPage<T> = await fetchPage({ cursor });
+ pages.push(result);
+ const reachedCheckpoint =
+ (result.oldestTime !== undefined && result.oldestTime < stopBefore) ||
+ result.items.some((item) => seen.has(item.key));
+ if (reachedCheckpoint || !result.cursor || result.cursor === cursor) {
+ unfinishedCursor = undefined;
+ break;
+ }
+ cursor = result.cursor;
+ unfinishedCursor = result.cursor;
+ }
+ const times = pages.flatMap((page) => (page.newestTime === undefined ? [] : [page.newestTime]));
+ return {
+ items: pages.flatMap((page) => page.items),
+ newestTime: times.length === 0 ? undefined : times.reduce((max, time) => (time > max ? time : max), times[0]),
+ unfinishedCursor,
+ };
+}
+
+function uniqueByKey<T>(items: PollItem<T>[]): PollItem<T>[] {
+ const byKey = new Map<string, PollItem<T>>();
+ for (const item of items) {
+ if (!byKey.has(item.key)) {
+ byKey.set(item.key, item);
+ }
+ }
+ return [...byKey.values()];
+}
+
+async function seed<T>({ store, storeKey, fetchPage, seenCap = SEEN_CAP, seedPages = 1 }: SeedParams<T>): Promise<PollState> {
+ const { items, newestTime } = await collect({ fetchPage, stopBefore: Number.NEGATIVE_INFINITY, maxPages: seedPages, seen: new Set() });
+ const keys = uniqueByKey(items).map((item) => item.key);
+ const state: PollState = {
+ seen: keys.slice(0, seenCap),
+ lastTime: newestTime ?? Date.now(),
+ };
+ await store.put(storeKey, state);
+ return state;
+}
+
+async function onEnable<T>({ store, storeKey, fetchPage, isRepublish, seenCap, seedPages }: SeedParams<T> & { isRepublish?: boolean }): Promise<void> {
+ if (isRepublish && isPollState(await store.get<unknown>(storeKey))) {
+ return;
+ }
+ await seed({ store, storeKey, fetchPage, seenCap, seedPages });
+}
+
+async function onDisable({ store, storeKey }: { store: PollStore; storeKey: string }): Promise<void> {
+ await store.delete(storeKey);
+}
+
+async function poll<T>({
+ store,
+ storeKey,
+ fetchPage,
+ maxPages = MAX_PAGES,
+ seenCap = SEEN_CAP,
+ windowMs = WINDOW_MS,
+ seedPages,
+ resumable = true,
+}: SeedParams<T> & { maxPages?: number; windowMs?: number; resumable?: boolean }): Promise<T[]> {
+ const stored = await store.get<unknown>(storeKey);
+ if (!isPollState(stored)) {
+ await seed({ store, storeKey, fetchPage, seenCap, seedPages });
+ return [];
+ }
+ const resume = resumable ? resumeOf(stored) : undefined;
+ if (resume !== undefined) {
+ return drain({ store, storeKey, fetchPage, maxPages, seenCap, stored, resume });
+ }
+ const cutoff = stored.lastTime - windowMs;
+ const seen = new Set(stored.seen);
+ const { items, newestTime, unfinishedCursor } = await collect({ fetchPage, stopBefore: cutoff, maxPages, seen });
+ const fresh = freshItems({ items, seen, stopBefore: cutoff });
+ const nextResume: PollResume | undefined =
+ resumable && unfinishedCursor !== undefined
+ ? { cursor: unfinishedCursor, stopBefore: cutoff, stopKeys: stored.seen.slice(0, RESUME_STOP_KEYS) }
+ : undefined;
+ const nextState: PollState = {
+ seen: keepSeen({ emitted: fresh.map((item) => item.key), previous: stored.seen, seenCap }),
+ lastTime: newestTime !== undefined && newestTime > stored.lastTime ? newestTime : stored.lastTime,
+ ...(nextResume ? { resume: nextResume } : {}),
+ };
+ await store.put(storeKey, nextState);
+ return fresh.map((item) => item.data);
+}
+
+async function drain<T>({
+ store,
+ storeKey,
+ fetchPage,
+ maxPages,
+ seenCap,
+ stored,
+ resume,
+}: {
+ store: PollStore;
+ storeKey: string;
+ fetchPage: PageFetcher<T>;
+ maxPages: number;
+ seenCap: number;
+ stored: PollState;
+ resume: PollResume;
+}): Promise<T[]> {
+ const stopKeys = new Set(resume.stopKeys);
+ const { items, unfinishedCursor } = await collect({
+ fetchPage,
+ startCursor: resume.cursor,
+ stopBefore: resume.stopBefore,
+ maxPages,
+ seen: stopKeys,
+ });
+ const fresh = freshItems({ items, seen: new Set([...stored.seen, ...resume.stopKeys]), stopBefore: resume.stopBefore });
+ const nextState: PollState = {
+ seen: [...stored.seen.slice(0, seenCap), ...fresh.map((item) => item.key)],
+ lastTime: stored.lastTime,
+ ...(unfinishedCursor !== undefined ? { resume: { ...resume, cursor: unfinishedCursor } } : {}),
+ };
+ await store.put(storeKey, nextState);
+ return fresh.map((item) => item.data);
+}
+
+function keepSeen({ emitted, previous, seenCap }: { emitted: string[]; previous: string[]; seenCap: number }): string[] {
+ return [...emitted, ...previous].slice(0, Math.max(seenCap, emitted.length));
+}
+
+function freshItems<T>({ items, seen, stopBefore }: { items: PollItem<T>[]; seen: Set<string>; stopBefore: number }): PollItem<T>[] {
+ return uniqueByKey(items)
+ .filter((item) => !seen.has(item.key) && item.time >= stopBefore)
+ .sort((a, b) => b.time - a.time);
+}
+
+async function sample<T>({ fetchPage, size = TEST_SAMPLE_SIZE }: { fetchPage: PageFetcher<T>; size?: number }): Promise<T[]> {
+ const first = await fetchPage({ cursor: undefined });
+ return uniqueByKey(first.items)
+ .sort((a, b) => b.time - a.time)
+ .slice(0, size)
+ .map((item) => item.data);
+}
+
+function timeOf(iso: string | undefined | null): number | undefined {
+ if (!iso) {
+ return undefined;
+ }
+ const time = Date.parse(iso);
+ return Number.isNaN(time) ? undefined : time;
+}
+
+function pageTimes(times: (number | undefined)[]): { oldestTime: number | undefined; newestTime: number | undefined } {
+ const known = times.flatMap((time) => (time === undefined ? [] : [time]));
+ if (known.length === 0) {
+ return { oldestTime: undefined, newestTime: undefined };
+ }
+ return {
+ oldestTime: known.reduce((min, time) => (time < min ? time : min), known[0]),
+ newestTime: known.reduce((max, time) => (time > max ? time : max), known[0]),
+ };
+}
+
+export const blueskyPolling = {
+ WINDOW_MS,
+ MAX_PAGES,
+ SEEN_CAP,
+ isPollState,
+ onEnable,
+ onDisable,
+ poll,
+ sample,
+ seed,
+ timeOf,
+ pageTimes,
+};
+
+export type PollItem<T> = { key: string; time: number; data: T };
+export type PollPage<T> = { items: PollItem<T>[]; cursor?: string; oldestTime: number | undefined; newestTime: number | undefined };
+export type PageFetcher<T> = (args: { cursor: string | undefined }) => Promise<PollPage<T>>;
+export type PollState = { seen: string[]; lastTime: number; resume?: PollResume };
+export type PollResume = { cursor: string; stopBefore: number; stopKeys: string[] };
+export type PollStore = {
+ get<V>(key: string): Promise<V | null>;
+ put<V>(key: string, value: V): Promise<V>;
+ delete(key: string): Promise<void>;
+};
+type SeedParams<T> = { store: PollStore; storeKey: string; fetchPage: PageFetcher<T>; seenCap?: number; seedPages?: number };
diff --git a/packages/pieces/community/bluesky/src/lib/common/props.ts b/packages/pieces/community/bluesky/src/lib/common/props.ts
index 716a6d83f5e..ff143edcb86 100644
--- a/packages/pieces/community/bluesky/src/lib/common/props.ts
+++ b/packages/pieces/community/bluesky/src/lib/common/props.ts
@@ -1,59 +1,12 @@
import { Property } from '@activepieces/pieces-framework';
import { blueskyAuth } from './auth';
+import { blueskyClient } from './client';
-export const languageOptions = [
- { label: 'English', value: 'en' },
- { label: 'Spanish', value: 'es' },
- { label: 'French', value: 'fr' },
- { label: 'German', value: 'de' },
- { label: 'Italian', value: 'it' },
- { label: 'Portuguese', value: 'pt' },
- { label: 'Russian', value: 'ru' },
- { label: 'Japanese', value: 'ja' },
- { label: 'Korean', value: 'ko' },
- { label: 'Chinese (Simplified)', value: 'zh' },
- { label: 'Chinese (Traditional)', value: 'zh-TW' },
- { label: 'Arabic', value: 'ar' },
- { label: 'Hindi', value: 'hi' },
- { label: 'Dutch', value: 'nl' },
- { label: 'Swedish', value: 'sv' },
- { label: 'Norwegian', value: 'no' },
- { label: 'Danish', value: 'da' },
- { label: 'Finnish', value: 'fi' },
- { label: 'Polish', value: 'pl' },
- { label: 'Czech', value: 'cs' },
- { label: 'Hungarian', value: 'hu' },
- { label: 'Romanian', value: 'ro' },
- { label: 'Greek', value: 'el' },
- { label: 'Turkish', value: 'tr' },
- { label: 'Hebrew', value: 'he' },
- { label: 'Thai', value: 'th' },
- { label: 'Vietnamese', value: 'vi' },
- { label: 'Indonesian', value: 'id' },
- { label: 'Malay', value: 'ms' },
- { label: 'Filipino', value: 'fil' },
-];
-
-
-export const languageDropdown = Property.StaticDropdown({
- displayName: 'Language',
- description: 'Select the language for the post',
- required: false,
- options: {
- options: languageOptions,
- },
-});
+const MAX_DROPDOWN_FOLLOWS = 1000;
+const MAX_LIMIT = 100;
+const DEFAULT_LIMIT = 25;
-export const multiLanguageDropdown = Property.StaticMultiSelectDropdown({
- displayName: 'Languages',
- description: 'Select one or more languages for the post',
- required: false,
- options: {
- options: languageOptions,
- },
-});
-
-export const threadDepthDropdown = Property.StaticDropdown({
+const threadDepthDropdown = Property.StaticDropdown({
displayName: 'Thread Depth',
description: 'How many levels deep to retrieve replies',
required: false,
@@ -72,7 +25,7 @@ export const threadDepthDropdown = Property.StaticDropdown({
},
});
-export const parentHeightDropdown = Property.StaticDropdown({
+const parentHeightDropdown = Property.StaticDropdown({
displayName: 'Parent Height',
description: 'How many parent posts to retrieve',
required: false,
@@ -91,126 +44,45 @@ export const parentHeightDropdown = Property.StaticDropdown({
},
});
-export const visibilityDropdown = Property.StaticDropdown({
- displayName: 'Visibility',
- description: 'Post visibility setting',
- required: false,
- defaultValue: 'public',
- options: {
- options: [
- { label: 'Public', value: 'public' },
- { label: 'Unlisted', value: 'unlisted' },
- ],
- },
-});
-
-export const moderationLabelDropdown = Property.StaticMultiSelectDropdown({
- displayName: 'Content Labels',
- description: 'Apply content moderation labels to the post',
- required: false,
- options: {
- options: [
- { label: 'Adult Content', value: 'adult' },
- { label: 'Graphic Media', value: 'graphic-media' },
- { label: 'Nudity', value: 'nudity' },
- { label: 'Sexual', value: 'sexual' },
- { label: 'Violence', value: 'violence' },
- { label: 'Self Harm', value: 'self-harm' },
- { label: 'Spam', value: 'spam' },
- { label: 'Impersonation', value: 'impersonation' },
- ],
- },
-});
-
-export const postUrlProperty = Property.ShortText({
+const postUrlProperty = Property.ShortText({
displayName: 'Post URL',
description: 'Paste the Bluesky post URL (e.g., https://bsky.app/profile/username.bsky.social/post/xxx)',
required: true,
});
-export const userHandleProperty = Property.ShortText({
- displayName: 'User Handle',
- description: 'Bluesky username (e.g., username.bsky.social)',
- required: true,
-});
-
-export const authorSelectionProperty = Property.Dropdown({
- displayName: 'Select Author',
- description: 'Choose from accounts you follow',
- required: false,
- auth: blueskyAuth,
- refreshers: ['auth'],
- options: async ({ auth }) => {
- try {
- const { createBlueskyAgent } = await import('./client');
- if (!auth) return { options: [] };
- const agent = await createBlueskyAgent(auth.props);
- const session = agent.session;
-
- if (!session?.did) {
- return { options: [{ label: 'Please authenticate first', value: '' }] };
- }
-
- const followingResponse = await agent.getFollows({
- actor: session.did,
- limit: 100
- });
-
- const options = followingResponse.data.follows.map((follow: any) => ({
- label: `${follow.displayName || follow.handle} (@${follow.handle})`,
- value: follow.handle
- }));
-
- options.unshift({ label: 'Enter handle manually', value: 'manual' });
-
- return { options };
- } catch (error) {
- return {
- options: [{ label: 'Error loading following list', value: '' }]
- };
- }
- }
-});
-
-export const postSearchProperty = Property.ShortText({
- displayName: 'Search Posts',
- description: 'Search for posts by keywords, hashtags, or content',
- required: false,
-});
-
-export const postTextProperty = Property.LongText({
+const postTextProperty = Property.LongText({
displayName: 'Post Text',
- description: 'What do you want to post? (Max 300 characters)',
+ description: 'What do you want to post? (Max 300 characters, counted as visible characters so emoji and non-Latin text count once each)',
required: true,
});
-export const imageUrlsProperty = Property.Array({
+const imageUrlsProperty = Property.Array({
displayName: 'Image URLs',
- description: 'Add up to 4 images by URL',
+ description: 'Add up to 4 images by URL (PNG, JPEG, GIF or WebP, max 1 MB each)',
required: false,
});
-export const imageDescriptionsProperty = Property.Array({
+const imageDescriptionsProperty = Property.Array({
displayName: 'Image Descriptions',
description: 'Describe each image for accessibility',
required: false,
});
-export const linkUrlProperty = Property.ShortText({
+const linkUrlProperty = Property.ShortText({
displayName: 'Link to Share',
description: 'URL to share with your post',
required: false,
});
-export const replyToPostProperty = Property.ShortText({
+const replyToPostProperty = Property.ShortText({
displayName: 'Reply to Post',
description: 'URL of post to reply to',
required: false,
});
-export const postTypeDropdown = Property.StaticDropdown({
+const postTypeDropdown = Property.StaticDropdown({
displayName: 'Post Type',
- description: 'Type of content you\'re sharing',
+ description: 'Informational only. To quote a post, fill in "Quote Post URL"; to reply, fill in "Reply to Post".',
required: false,
defaultValue: 'text',
options: {
@@ -224,7 +96,7 @@ export const postTypeDropdown = Property.StaticDropdown({
},
});
-export const simpleLanguageDropdown = Property.StaticDropdown({
+const simpleLanguageDropdown = Property.StaticDropdown({
displayName: 'Post Language',
description: 'Language of your post',
required: false,
@@ -250,39 +122,10 @@ export const simpleLanguageDropdown = Property.StaticDropdown({
},
});
-export const replyDepthDropdown = Property.StaticDropdown({
- displayName: 'How many replies to show?',
- description: 'Choose how deep to go into the conversation',
- required: false,
- defaultValue: '10',
- options: {
- options: [
- { label: 'Just direct replies (1 level)', value: '1' },
- { label: 'Short conversation (3 levels)', value: '3' },
- { label: 'Full conversation (10 levels)', value: '10' },
- { label: 'Entire thread (50+ levels)', value: '50' },
- ],
- },
-});
-
-export const parentPostsDropdown = Property.StaticDropdown({
- displayName: 'Show conversation context?',
- description: 'Include previous posts in the thread for context',
- required: false,
- defaultValue: '3',
- options: {
- options: [
- { label: 'No context - just this post', value: '0' },
- { label: 'Recent context (3 previous posts)', value: '3' },
- { label: 'Full context (10 previous posts)', value: '10' },
- { label: 'Complete thread history', value: '80' },
- ],
- },
-});
-
-export const contentWarningDropdown = Property.StaticMultiSelectDropdown({
+const contentWarningDropdown = Property.StaticMultiSelectDropdown({
displayName: 'Content Warnings',
- description: 'Add warnings for sensitive content',
+ description:
+ 'Self-labels Bluesky shows as content warnings. "Adult Content" is sent as Bluesky\'s Adult (porn) label, "Violence" as Graphic Media, "Sensitive Topic" as Suggestive (sexual); "Spam/Promotional" has no Bluesky label and is ignored.',
required: false,
options: {
options: [
@@ -291,13 +134,16 @@ export const contentWarningDropdown = Property.StaticMultiSelectDropdown({
{ label: 'Sensitive Topic', value: 'sensitive' },
{ label: 'Violence', value: 'violence' },
{ label: 'Spam/Promotional', value: 'spam' },
+ { label: 'Suggestive (sexual)', value: 'sexual' },
+ { label: 'Nudity', value: 'nudity' },
+ { label: 'Adult (porn)', value: 'porn' },
],
},
});
-export const audienceDropdown = Property.StaticDropdown({
+const audienceDropdown = Property.StaticDropdown({
displayName: 'Audience',
- description: 'Who can see this post',
+ description: 'Bluesky posts are always public; this setting has no effect and is kept only for older flows.',
required: false,
defaultValue: 'public',
options: {
@@ -309,84 +155,229 @@ export const audienceDropdown = Property.StaticDropdown({
},
});
-export function extractPostInfoFromUrl(url: string): { uri?: string; handle?: string; postId?: string } {
- if (url.startsWith('at://')) {
- return { uri: url };
- }
-
- const urlMatch = url.match(/https?:\/\/bsky\.app\/profile\/([^/]+)\/post\/([^/?]+)/);
- if (urlMatch) {
- const handle = urlMatch[1];
- const postId = urlMatch[2];
-
- return {
- handle: handle,
- postId: postId,
- };
- }
-
- return {};
+function limitProperty({ description }: { description?: string } = {}) {
+ return Property.Number({
+ displayName: 'Limit',
+ description: description ?? `How many results to return per page (1-${MAX_LIMIT}, default ${DEFAULT_LIMIT}).`,
+ required: false,
+ defaultValue: DEFAULT_LIMIT,
+ });
}
-export function normalizeHandle(handle: string): string {
- let cleanHandle = handle.replace(/^@/, '');
-
- if (!cleanHandle.includes('.')) {
- cleanHandle += '.bsky.social';
- }
-
- return cleanHandle;
+function cursorProperty() {
+ return Property.ShortText({
+ displayName: 'Cursor',
+ description: 'Leave empty for the first page. To get the next page, pass the "cursor" value returned by the previous run.',
+ required: false,
+ });
}
-export function createSimpleExternalLink(url: string): { uri: string; title: string; description?: string } {
- return {
- uri: url,
- title: url,
- description: 'Shared link'
- };
+function actorProperty({ description }: { description: string }) {
+ return Property.ShortText({ displayName: 'Account', description, required: true });
}
+function optionalActorProperty({ description }: { description: string }) {
+ return Property.ShortText({ displayName: 'Account', description, required: false });
+}
-export const postUriProperty = Property.ShortText({
- displayName: 'Post URI (Advanced)',
- description: 'Technical AT-URI format (at://did:plc:xxx/app.bsky.feed.post/xxx) - use Post URL field instead',
- required: false,
-});
+function postInputProperty() {
+ return Property.ShortText({
+ displayName: 'Post',
+ description: 'The post link (https://bsky.app/profile/alice.bsky.social/post/3k...) or its at:// URI.',
+ required: true,
+ });
+}
-export const externalLinkProperty = Property.Object({
- displayName: 'External Link (Advanced)',
- description: 'Manual link object - use "Link to Share" field instead',
- required: false,
-});
+function listInputProperty() {
+ return Property.ShortText({
+ displayName: 'List',
+ description: 'The list link (https://bsky.app/profile/alice.bsky.social/lists/3k...) or its at:// URI.',
+ required: true,
+ });
+}
-export const replyToProperty = Property.Object({
- displayName: 'Reply To (Advanced)',
- description: 'Manual reply object - use "Reply to Post" field instead',
- required: false,
-});
+const NOTIFICATION_REASONS = [
+ { label: 'Like', value: 'like' },
+ { label: 'Repost', value: 'repost' },
+ { label: 'Follow', value: 'follow' },
+ { label: 'Mention', value: 'mention' },
+ { label: 'Reply', value: 'reply' },
+ { label: 'Quote', value: 'quote' },
+ { label: 'Joined via your starter pack', value: 'starterpack-joined' },
+ { label: 'Like of your repost', value: 'like-via-repost' },
+ { label: 'Repost of your repost', value: 'repost-via-repost' },
+ { label: 'Post from an account you subscribed to', value: 'subscribed-post' },
+ { label: 'Verified', value: 'verified' },
+ { label: 'Verification removed', value: 'unverified' },
+];
+function notificationReasonsProperty({ defaultValue, description }: { defaultValue?: string[]; description: string }) {
+ return Property.StaticMultiSelectDropdown({
+ displayName: 'Notification Types',
+ description,
+ required: false,
+ defaultValue,
+ options: { options: NOTIFICATION_REASONS },
+ });
+}
+const selectionMethodDropdown = Property.StaticDropdown({
+ displayName: 'Select Method',
+ description: 'How to choose the post',
+ required: true,
+ defaultValue: 'timeline',
+ options: {
+ options: [
+ { label: 'From my timeline', value: 'timeline' },
+ { label: 'Enter URL manually', value: 'manual' },
+ ],
+ },
+});
-export async function parseBlueskyUrl(url: string, agent: any): Promise<string> {
- if (url.startsWith('at://')) {
- if (!url.match(/^at:\/\/did:plc:[a-z0-9]+\/app\.bsky\.feed\.post\/[a-z0-9]+$/)) {
- throw new Error('Invalid AT-URI format');
+function selectedPostInput({
+ selectionMethod,
+ postSelection,
+ postUrl,
+}: {
+ selectionMethod: unknown;
+ postSelection: unknown;
+ postUrl: unknown;
+}): string {
+ if (selectionMethod === 'timeline') {
+ if (typeof postSelection !== 'string' || postSelection.trim() === '') {
+ throw new Error('Please select a post from your timeline dropdown');
}
- return url;
+ return postSelection.trim();
}
-
- const urlMatch = url.match(/https?:\/\/bsky\.app\/profile\/([^/]+)\/post\/([^/?]+)/);
- if (urlMatch) {
- const handle = urlMatch[1];
- const postId = urlMatch[2];
-
- if (!handle.includes('.') && !handle.includes('@')) {
- throw new Error('Invalid handle format in URL');
+ if (selectionMethod === 'manual') {
+ if (typeof postUrl !== 'string' || postUrl.trim() === '') {
+ throw new Error('Post URL is required when using manual entry method');
}
-
- const didDoc = await agent.resolveHandle({ handle: handle.replace('@', '') });
- return `at://${didDoc.data.did}/app.bsky.feed.post/${postId}`;
+ return postUrl.trim();
}
-
- throw new Error('Invalid post URL format. Please use a valid Bluesky post URL or AT-URI.');
-}
\ No newline at end of file
+ throw new Error('Please select a post selection method');
+}
+
+function parseLimit(raw: unknown): number {
+ if (raw === undefined || raw === null || raw === '') {
+ return DEFAULT_LIMIT;
+ }
+ const value = typeof raw === 'number' ? raw : Number(raw);
+ if (!Number.isInteger(value) || value < 1 || value > MAX_LIMIT) {
+ throw new Error(`Limit must be a whole number between 1 and ${MAX_LIMIT}; got ${String(raw)}.`);
+ }
+ return value;
+}
+
+function parseCursor(raw: unknown): string | undefined {
+ return typeof raw === 'string' && raw.trim() !== '' ? raw.trim() : undefined;
+}
+
+function postLabel({ handle, text, indexedAt }: { handle: string; text: unknown; indexedAt: string }): string {
+ const body = typeof text === 'string' && text !== '' ? text : 'Media post';
+ const trimmed = body.length > 80 ? `${body.substring(0, 80)}...` : body;
+ return `@${handle}: ${trimmed} (${new Date(indexedAt).toLocaleDateString()})`;
+}
+
+function timelinePostDropdown() {
+ return Property.Dropdown({
+ auth: blueskyAuth,
+ displayName: 'Select Post',
+ description: 'Choose from your 50 most recent timeline posts (only when "From my timeline" is selected above)',
+ required: false,
+ refreshers: ['auth'],
+ options: async ({ auth }) => {
+ if (!auth) {
+ return { disabled: true, options: [], placeholder: 'Connect your Bluesky account first' };
+ }
+ try {
+ const agent = await blueskyClient.createAgent(auth.props);
+ const timeline = await agent.getTimeline({ limit: 50 });
+ return {
+ disabled: false,
+ options: timeline.data.feed.map((item) => ({
+ label: postLabel({ handle: item.post.author.handle, text: item.post.record['text'], indexedAt: item.post.indexedAt }),
+ value: item.post.uri,
+ })),
+ };
+ } catch (error) {
+ return {
+ disabled: true,
+ options: [],
+ placeholder: `Could not load your timeline: ${error instanceof Error ? error.message : 'unknown error'}`,
+ };
+ }
+ },
+ });
+}
+
+function followingDropdown() {
+ return Property.Dropdown({
+ auth: blueskyAuth,
+ displayName: 'Select Author',
+ description: 'Choose from accounts you follow',
+ required: false,
+ refreshers: ['auth'],
+ options: async ({ auth }) => {
+ if (!auth) {
+ return { disabled: true, options: [], placeholder: 'Connect your Bluesky account first' };
+ }
+ try {
+ const agent = await blueskyClient.createAgent(auth.props);
+ const did = blueskyClient.sessionDid(agent);
+ const options: { label: string; value: string }[] = [];
+ let cursor: string | undefined = undefined;
+ do {
+ const page: Awaited<ReturnType<typeof agent.getFollows>> = await agent.getFollows({ actor: did, limit: 100, cursor });
+ options.push(
+ ...page.data.follows.map((follow) => ({
+ label: `${follow.displayName || follow.handle} (@${follow.handle})`,
+ value: follow.handle,
+ })),
+ );
+ cursor = page.data.cursor && page.data.cursor !== cursor ? page.data.cursor : undefined;
+ } while (cursor && options.length < MAX_DROPDOWN_FOLLOWS);
+ if (options.length === 0) {
+ return { disabled: true, options: [], placeholder: 'You do not follow anyone yet. Use "Enter handle manually" instead.' };
+ }
+ return { disabled: false, options };
+ } catch (error) {
+ return {
+ disabled: true,
+ options: [],
+ placeholder: `Could not load the accounts you follow: ${error instanceof Error ? error.message : 'unknown error'}`,
+ };
+ }
+ },
+ });
+}
+
+export const blueskyProps = {
+ MAX_LIMIT,
+ DEFAULT_LIMIT,
+ threadDepthDropdown,
+ parentHeightDropdown,
+ postUrlProperty,
+ postTextProperty,
+ imageUrlsProperty,
+ imageDescriptionsProperty,
+ linkUrlProperty,
+ replyToPostProperty,
+ postTypeDropdown,
+ simpleLanguageDropdown,
+ contentWarningDropdown,
+ audienceDropdown,
+ limitProperty,
+ cursorProperty,
+ actorProperty,
+ optionalActorProperty,
+ postInputProperty,
+ listInputProperty,
+ timelinePostDropdown,
+ followingDropdown,
+ selectionMethodDropdown,
+ selectedPostInput,
+ notificationReasonsProperty,
+ parseLimit,
+ parseCursor,
+};
diff --git a/packages/pieces/community/bluesky/src/lib/common/refs.ts b/packages/pieces/community/bluesky/src/lib/common/refs.ts
new file mode 100644
index 00000000000..cefa294c0b4
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/common/refs.ts
@@ -0,0 +1,227 @@
+import type { AtpAgent } from '@atproto/api';
+import { blueskyClient } from './client';
+
+const DID_PATTERN = /^did:(plc:[a-z2-7]{24}|web:[a-zA-Z0-9.%:-]{1,253})$/;
+const HANDLE_PATTERN = /^(?=.{3,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]([a-z0-9-]{0,61}[a-z0-9])?$/;
+const RKEY_PATTERN = /^[a-zA-Z0-9._:~-]{1,512}$/;
+const WEB_HOSTS = new Set(['bsky.app', 'www.bsky.app', 'main.bsky.dev', 'staging.bsky.app']);
+const POST_COLLECTION = 'app.bsky.feed.post';
+const LIST_COLLECTION = 'app.bsky.graph.list';
+const WEB_BASE = 'https://bsky.app';
+const MAX_LIST_PAGES = 50;
+
+function isDid(value: string): boolean {
+ return DID_PATTERN.test(value);
+}
+
+function normalizeRepo(raw: string): string {
+ const decoded = safeDecode(raw.trim().replace(/^@/, ''));
+ if (decoded.startsWith('did:')) {
+ if (!isDid(decoded)) {
+ throw new Error(`"${raw}" is not a valid Bluesky DID.`);
+ }
+ return decoded;
+ }
+ const handle = decoded.toLowerCase();
+ if (!HANDLE_PATTERN.test(handle)) {
+ throw new Error(`"${raw}" is not a valid Bluesky handle. Use the full handle, for example alice.bsky.social.`);
+ }
+ return handle;
+}
+
+function safeDecode(value: string): string {
+ try {
+ return decodeURIComponent(value);
+ } catch {
+ return value;
+ }
+}
+
+function parseRecordInput({
+ input,
+ collection,
+ webSegment,
+ label,
+}: {
+ input: string;
+ collection: string;
+ webSegment: string;
+ label: string;
+}): { repo: string; rkey: string } {
+ const value = input.trim();
+ if (value === '') {
+ throw new Error(`The ${label} is empty. Paste a bsky.app link or an at:// URI.`);
+ }
+ if (value.toLowerCase().startsWith('at://')) {
+ const parts = value.slice(5).split(/[?#]/)[0].split('/');
+ if (parts.length !== 3 || parts[1] !== collection) {
+ throw new Error(`"${value}" is not a ${label} AT-URI. Expected at://<did or handle>/${collection}/<id>.`);
+ }
+ return { repo: normalizeRepo(parts[0]), rkey: validRkey({ rkey: parts[2], input: value }) };
+ }
+ let url: URL;
+ try {
+ url = new URL(/^https?:\/\//i.test(value) ? value : `https://${value}`);
+ } catch {
+ throw new Error(`"${value}" is not a valid ${label} link. Use a link like https://bsky.app/profile/alice.bsky.social/${webSegment}/abc123.`);
+ }
+ const segments = url.pathname.split('/').filter((segment) => segment !== '');
+ if (!WEB_HOSTS.has(url.hostname.toLowerCase()) || segments.length < 4 || segments[0] !== 'profile' || segments[2] !== webSegment) {
+ throw new Error(`"${value}" is not a ${label} link. Use a link like https://bsky.app/profile/alice.bsky.social/${webSegment}/abc123 or an at:// URI.`);
+ }
+ return { repo: normalizeRepo(segments[1]), rkey: validRkey({ rkey: segments[3], input: value }) };
+}
+
+function validRkey({ rkey, input }: { rkey: string; input: string }): string {
+ if (!RKEY_PATTERN.test(rkey) || rkey === '.' || rkey === '..') {
+ throw new Error(`"${input}" has an invalid record id.`);
+ }
+ return rkey;
+}
+
+function parsePostInput(input: string): { repo: string; rkey: string } {
+ return parseRecordInput({ input, collection: POST_COLLECTION, webSegment: 'post', label: 'post' });
+}
+
+function parseListInput(input: string): { repo: string; rkey: string } {
+ return parseRecordInput({ input, collection: LIST_COLLECTION, webSegment: 'lists', label: 'list' });
+}
+
+function parseActorInput(input: string): string {
+ const value = input.trim();
+ if (value === '') {
+ throw new Error('The account is empty. Enter a handle (alice.bsky.social), a DID or a profile link.');
+ }
+ if (/^https?:\/\//i.test(value) || /^(www\.)?bsky\.app\//i.test(value)) {
+ let url: URL;
+ try {
+ url = new URL(/^https?:\/\//i.test(value) ? value : `https://${value}`);
+ } catch {
+ throw new Error(`"${value}" is not a valid profile link.`);
+ }
+ const segments = url.pathname.split('/').filter((segment) => segment !== '');
+ if (!WEB_HOSTS.has(url.hostname.toLowerCase()) || segments.length < 2 || segments[0] !== 'profile') {
+ throw new Error(`"${value}" is not a Bluesky profile link. Use a link like https://bsky.app/profile/alice.bsky.social.`);
+ }
+ return normalizeRepo(segments[1]);
+ }
+ const bare = value.replace(/^@/, '');
+ if (!bare.startsWith('did:') && !bare.includes('.')) {
+ return normalizeRepo(`${bare}.bsky.social`);
+ }
+ return normalizeRepo(bare);
+}
+
+async function resolveRepoDid({ agent, repo }: { agent: AtpAgent; repo: string }): Promise<string> {
+ if (isDid(repo)) {
+ return repo;
+ }
+ try {
+ const response = await agent.resolveHandle({ handle: repo });
+ return response.data.did;
+ } catch (resolveError) {
+ try {
+ const profile = await agent.getProfile({ actor: repo });
+ return profile.data.did;
+ } catch {
+ throw resolveError;
+ }
+ }
+}
+
+async function resolvePostRef({ agent, input }: { agent: AtpAgent; input: string }): Promise<PostRef> {
+ const { repo, rkey } = parsePostInput(input);
+ const did = await resolveRepoDid({ agent, repo });
+ return { uri: `at://${did}/${POST_COLLECTION}/${rkey}`, did, rkey };
+}
+
+async function resolveListRef({ agent, input }: { agent: AtpAgent; input: string }): Promise<PostRef> {
+ const { repo, rkey } = parseListInput(input);
+ const did = await resolveRepoDid({ agent, repo });
+ return { uri: `at://${did}/${LIST_COLLECTION}/${rkey}`, did, rkey };
+}
+
+async function resolveActorDid({ agent, input }: { agent: AtpAgent; input: string }): Promise<string> {
+ return resolveRepoDid({ agent, repo: parseActorInput(input) });
+}
+
+async function fetchProfile({ agent, input }: { agent: AtpAgent; input?: string }) {
+ const actor = input && input.trim() !== '' ? parseActorInput(input) : agent.session?.did;
+ if (!actor) {
+ throw new Error('The Bluesky session has no account DID. Reconnect the Bluesky connection.');
+ }
+ const response = await agent.getProfile({ actor });
+ return response.data;
+}
+
+async function listMembers({ agent, listUri, maxPages = MAX_LIST_PAGES }: { agent: AtpAgent; listUri: string; maxPages?: number }) {
+ const pages: Awaited<ReturnType<typeof agent.app.bsky.graph.getList>>['data'][] = [];
+ let cursor: string | undefined = undefined;
+ for (let page = 0; page < maxPages; page++) {
+ const response: Awaited<ReturnType<typeof agent.app.bsky.graph.getList>> = await agent.app.bsky.graph.getList({ list: listUri, limit: 100, cursor });
+ pages.push(response.data);
+ if (!response.data.cursor || response.data.cursor === cursor) {
+ return { items: pages.flatMap((p) => p.items), complete: true };
+ }
+ cursor = response.data.cursor;
+ }
+ return { items: pages.flatMap((p) => p.items), complete: false };
+}
+
+async function recordExists({ agent, repo, collection, rkey }: { agent: AtpAgent; repo: string; collection: string; rkey: string }): Promise<boolean> {
+ try {
+ await agent.com.atproto.repo.getRecord({ repo, collection, rkey });
+ return true;
+ } catch (error) {
+ if (blueskyClient.isXrpcError(error) && (error.error === 'RecordNotFound' || error.status === 404 || /could not locate record/i.test(error.message))) {
+ return false;
+ }
+ throw error;
+ }
+}
+
+function parseAtUri(uri: string): { repo: string; collection: string; rkey: string } | null {
+ if (!uri.startsWith('at://')) {
+ return null;
+ }
+ const parts = uri.slice(5).split('/');
+ if (parts.length !== 3) {
+ return null;
+ }
+ return { repo: parts[0], collection: parts[1], rkey: parts[2] };
+}
+
+function profileWebUrl(actor: string): string {
+ return `${WEB_BASE}/profile/${actor}`;
+}
+
+function postWebUrl({ uri, handle }: { uri: string; handle?: string }): string {
+ const parsed = parseAtUri(uri);
+ if (parsed === null) {
+ return '';
+ }
+ const actor = handle && handle !== 'handle.invalid' ? handle : parsed.repo;
+ const segment = parsed.collection === LIST_COLLECTION ? 'lists' : 'post';
+ return `${profileWebUrl(actor)}/${segment}/${parsed.rkey}`;
+}
+
+export const blueskyRefs = {
+ isDid,
+ parsePostInput,
+ parseListInput,
+ parseActorInput,
+ parseAtUri,
+ resolvePostRef,
+ resolveListRef,
+ resolveActorDid,
+ resolveRepoDid,
+ fetchProfile,
+ listMembers,
+ recordExists,
+ postWebUrl,
+ profileWebUrl,
+ POST_COLLECTION,
+ LIST_COLLECTION,
+};
+
+export type PostRef = { uri: string; did: string; rkey: string };
diff --git a/packages/pieces/community/bluesky/src/lib/output-schemas.ts b/packages/pieces/community/bluesky/src/lib/output-schemas.ts
index 8cb9503710d..4a61ea49798 100644
--- a/packages/pieces/community/bluesky/src/lib/output-schemas.ts
+++ b/packages/pieces/community/bluesky/src/lib/output-schemas.ts
@@ -75,6 +75,72 @@ const postFields: OutputSchema['fields'] = [
...postEngagementFields,
];
+const linkedPostFields: OutputSchema['fields'] = [
+ { key: 'url', label: 'Post Link', format: 'url' },
+ ...postFields,
+];
+
+const profileFields: OutputSchema['fields'] = [
+ { key: 'did', label: 'DID' },
+ { key: 'handle', label: 'Handle' },
+ { key: 'displayName', label: 'Display Name' },
+ { key: 'description', label: 'Bio' },
+ { key: 'avatar', label: 'Avatar', format: 'image' },
+ { key: 'url', label: 'Profile Link', format: 'url' },
+ { key: 'createdAt', label: 'Account Created At', format: 'datetime' },
+ { key: 'indexedAt', label: 'Indexed At', format: 'datetime' },
+ {
+ key: 'viewer',
+ label: 'Viewer State',
+ description: 'The connected account\'s relationship to this account: following/followedBy/blocking hold record URIs when set, muted is true when muted.',
+ },
+];
+
+const listedPostFields: OutputSchema['fields'] = [
+ { key: 'text', label: 'Text' },
+ ...linkedPostFields,
+];
+
+const feedItemFields: OutputSchema['fields'] = [
+ ...listedPostFields,
+ { key: 'isRepost', label: 'Is Repost', format: 'boolean' },
+ { key: 'repostedBy', label: 'Reposted By', children: authorFields, description: 'Who reposted it into the feed; null when not a repost.' },
+ { key: 'repostedAt', label: 'Reposted At', format: 'datetime' },
+ { key: 'isReply', label: 'Is Reply', format: 'boolean' },
+ { key: 'replyToUri', label: 'Replied-To Post URI' },
+ { key: 'isPinned', label: 'Is Pinned', format: 'boolean' },
+];
+
+const notificationFields: OutputSchema['fields'] = [
+ { key: 'reason', label: 'Type', description: 'like, repost, follow, mention, reply, quote, starterpack-joined, like-via-repost, repost-via-repost, subscribed-post, verified or unverified.' },
+ { key: 'text', label: 'Text', description: 'The text of the post behind the notification; empty for likes, reposts and follows.' },
+ { key: 'author', label: 'From', children: profileFields },
+ { key: 'url', label: 'Post Link', format: 'url', description: 'Link to the mentioning, replying or quoting post; empty for likes, reposts and follows.' },
+ { key: 'reasonSubject', label: 'Subject URI', description: 'The post that was liked, reposted, replied to or quoted; null for follows and mentions.' },
+ { key: 'isRead', label: 'Is Read', format: 'boolean' },
+ { key: 'indexedAt', label: 'Indexed At', format: 'datetime' },
+ { key: 'uri', label: 'Record URI', description: 'URI of the like, repost, follow or post record that caused the notification.' },
+ { key: 'cid', label: 'Record CID' },
+];
+
+const listViewFields: OutputSchema['fields'] = [
+ { key: 'name', label: 'Name' },
+ { key: 'purpose', label: 'Kind', description: 'app.bsky.graph.defs#curatelist (user list), #modlist (moderation list) or #referencelist (starter pack).' },
+ { key: 'description', label: 'Description' },
+ { key: 'listItemCount', label: 'Members', format: 'number' },
+ { key: 'url', label: 'List Link', format: 'url' },
+ { key: 'uri', label: 'List URI' },
+ { key: 'avatar', label: 'Avatar', format: 'image' },
+ { key: 'indexedAt', label: 'Indexed At', format: 'datetime' },
+ { key: 'creator', label: 'Owner', children: profileFields },
+];
+
+const pageFields: OutputSchema['fields'] = [
+ { key: 'cursor', label: 'Next Page Cursor', description: 'Pass to Cursor to get the next page; null on the last page.' },
+ { key: 'hasMore', label: 'Has More', format: 'boolean' },
+];
+
+
export const createPostOutputSchema: OutputSchema = {
fields: [
{ key: 'success', label: 'Success', format: 'boolean' },
@@ -96,6 +162,17 @@ export const createPostOutputSchema: OutputSchema = {
{ key: 'cid', label: 'CID' },
],
},
+ {
+ key: 'failedThreadPosts',
+ label: 'Failed Thread Posts',
+ labelKey: 'index',
+ description: 'Thread posts Bluesky rejected, with their position (1 = first thread post) and the error; empty when every post went out.',
+ listItems: [
+ { key: 'index', label: 'Position', format: 'number' },
+ { key: 'error', label: 'Error' },
+ ],
+ },
+ { key: 'url', label: 'Post Link', format: 'url' },
{ key: 'totalPosts', label: 'Total Posts', format: 'number' },
{ key: 'record', label: 'Post', children: recordFields },
],
@@ -105,6 +182,7 @@ export const findPostOutputSchema: OutputSchema = {
fields: [
{ key: 'success', label: 'Success', format: 'boolean' },
{ key: 'uri', label: 'Post URI' },
+ { key: 'url', label: 'Post Link', format: 'url' },
{ key: 'cid', label: 'CID' },
{ key: 'record', label: 'Post', children: recordFields },
{ key: 'author', label: 'Author', children: authorFields },
@@ -130,6 +208,7 @@ export const likePostOutputSchema: OutputSchema = {
{ key: 'likeCid', label: 'Like CID' },
{ key: 'postUri', label: 'Post URI' },
{ key: 'postCid', label: 'Post CID' },
+ { key: 'postUrl', label: 'Post Link', format: 'url' },
{ key: 'postAuthor', label: 'Post Author' },
{ key: 'postText', label: 'Post Text' },
{
@@ -151,6 +230,7 @@ export const repostOutputSchema: OutputSchema = {
label: 'Original Post',
children: [
{ key: 'uri', label: 'Post URI' },
+ { key: 'url', label: 'Post Link', format: 'url' },
{ key: 'cid', label: 'CID' },
{ key: 'author', label: 'Author Handle' },
{ key: 'text', label: 'Text' },
@@ -212,7 +292,7 @@ export const findThreadOutputSchema: OutputSchema = {
export const newPostTriggerOutputSchema: OutputSchema = {
fields: [
- ...postFields,
+ ...linkedPostFields,
{
key: 'searchContext',
label: 'Search Context',
@@ -232,7 +312,7 @@ export const newPostTriggerOutputSchema: OutputSchema = {
export const newTimelinePostsTriggerOutputSchema: OutputSchema = {
fields: [
- ...postFields,
+ ...linkedPostFields,
{
key: 'reason',
label: 'Timeline Reason',
@@ -274,7 +354,7 @@ export const newTimelinePostsTriggerOutputSchema: OutputSchema = {
export const newPostsByAuthorTriggerOutputSchema: OutputSchema = {
fields: [
- ...postFields,
+ ...linkedPostFields,
{
key: 'postContext',
label: 'Post Context',
@@ -300,9 +380,7 @@ export const newFollowerTriggerOutputSchema: OutputSchema = {
{ key: 'displayName', label: 'Display Name' },
{ key: 'description', label: 'Bio' },
{ key: 'avatar', label: 'Avatar', format: 'image' },
- // followersCount/followsCount/postsCount are deliberately absent: the
- // trigger reads getFollowers(), whose ProfileView never carries the
- // counts, so the emitted values are a hardcoded 0
+ { key: 'url', label: 'Profile Link', format: 'url' },
{ key: 'indexedAt', label: 'Indexed At', format: 'datetime' },
{ key: 'createdAt', label: 'Account Created At', format: 'datetime' },
{
@@ -317,3 +395,271 @@ export const newFollowerTriggerOutputSchema: OutputSchema = {
},
],
};
+
+export const deletePostOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'deleted', label: 'Deleted', format: 'boolean' },
+ { key: 'existed', label: 'Existed Before', format: 'boolean', description: 'False when the post was already gone.' },
+ { key: 'uri', label: 'Post URI' },
+ { key: 'deletedAt', label: 'Deleted At', format: 'datetime' },
+ ],
+};
+
+export const unlikePostOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'removed', label: 'Removed', format: 'boolean', description: 'False when the post was not liked.' },
+ { key: 'postUri', label: 'Post URI' },
+ { key: 'likeUri', label: 'Removed Like URI' },
+ ],
+};
+
+export const undoRepostOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'removed', label: 'Removed', format: 'boolean', description: 'False when the post was not reposted.' },
+ { key: 'postUri', label: 'Post URI' },
+ { key: 'repostUri', label: 'Removed Repost URI' },
+ ],
+};
+
+export const profileOutputSchema: OutputSchema = {
+ fields: [
+ ...profileFields,
+ { key: 'banner', label: 'Banner', format: 'image' },
+ { key: 'followersCount', label: 'Followers', format: 'number' },
+ { key: 'followsCount', label: 'Following', format: 'number' },
+ { key: 'postsCount', label: 'Posts', format: 'number' },
+ { key: 'pinnedPost', label: 'Pinned Post', children: [{ key: 'uri', label: 'Post URI' }], description: 'Null when nothing is pinned.' },
+ ],
+};
+
+export const profileListOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'items', label: 'Accounts', labelKey: 'handle', listItems: profileFields },
+ ...pageFields,
+ ],
+};
+
+export const likeListOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'items',
+ label: 'Likes',
+ labelKey: 'handle',
+ listItems: [...profileFields, { key: 'likedAt', label: 'Liked At', format: 'datetime' }],
+ },
+ ...pageFields,
+ ],
+};
+
+export const postListOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'items', label: 'Posts', labelKey: 'text', listItems: listedPostFields },
+ ...pageFields,
+ ],
+};
+
+export const feedListOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'items', label: 'Posts', labelKey: 'text', listItems: feedItemFields },
+ ...pageFields,
+ ],
+};
+
+export const followOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'followUri', label: 'Follow URI' },
+ { key: 'did', label: 'DID' },
+ { key: 'handle', label: 'Handle' },
+ { key: 'alreadyFollowing', label: 'Already Following', format: 'boolean' },
+ ],
+};
+
+export const unfollowOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'removed', label: 'Removed', format: 'boolean', description: 'False when the account was not followed.' },
+ { key: 'did', label: 'DID' },
+ { key: 'handle', label: 'Handle' },
+ { key: 'followUri', label: 'Removed Follow URI' },
+ ],
+};
+
+export const blockOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'blockUri', label: 'Block URI' },
+ { key: 'did', label: 'DID' },
+ { key: 'handle', label: 'Handle' },
+ { key: 'alreadyBlocked', label: 'Already Blocked', format: 'boolean' },
+ ],
+};
+
+export const unblockOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'removed', label: 'Removed', format: 'boolean', description: 'False when the account was not blocked.' },
+ { key: 'did', label: 'DID' },
+ { key: 'handle', label: 'Handle' },
+ { key: 'blockUri', label: 'Removed Block URI' },
+ ],
+};
+
+export const muteOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'muted', label: 'Muted Now', format: 'boolean' },
+ { key: 'wasMuted', label: 'Was Muted Before', format: 'boolean' },
+ { key: 'did', label: 'DID' },
+ { key: 'handle', label: 'Handle' },
+ ],
+};
+
+export const notificationListOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'items', label: 'Notifications', labelKey: 'reason', listItems: notificationFields },
+ ...pageFields,
+ { key: 'seenAt', label: 'Last Seen At', format: 'datetime' },
+ ],
+};
+
+export const markSeenOutputSchema: OutputSchema = {
+ fields: [{ key: 'seenAt', label: 'Seen Up To', format: 'datetime' }],
+};
+
+export const updateProfileOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'did', label: 'DID' },
+ { key: 'displayName', label: 'Display Name' },
+ { key: 'description', label: 'Bio' },
+ { key: 'avatarUpdated', label: 'Avatar Updated', format: 'boolean' },
+ { key: 'updatedAt', label: 'Updated At', format: 'datetime' },
+ ],
+};
+
+export const listListOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'items', label: 'Lists', labelKey: 'name', listItems: listViewFields },
+ ...pageFields,
+ ],
+};
+
+export const listMembersOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'list', label: 'List', children: listViewFields },
+ {
+ key: 'items',
+ label: 'Members',
+ labelKey: 'handle',
+ listItems: [...profileFields, { key: 'listItemUri', label: 'Membership URI' }],
+ },
+ ...pageFields,
+ ],
+};
+
+export const createListOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'uri', label: 'List URI' },
+ { key: 'url', label: 'List Link', format: 'url' },
+ { key: 'cid', label: 'CID' },
+ { key: 'name', label: 'Name' },
+ { key: 'purpose', label: 'Kind' },
+ { key: 'description', label: 'Description' },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+ ],
+};
+
+export const deleteListOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'deleted', label: 'Deleted', format: 'boolean' },
+ { key: 'existed', label: 'Existed Before', format: 'boolean' },
+ { key: 'uri', label: 'List URI' },
+ { key: 'membersRemoved', label: 'Memberships Removed', format: 'number' },
+ { key: 'membersFailed', label: 'Memberships Not Removed', format: 'number' },
+ { key: 'membersComplete', label: 'All Memberships Found', format: 'boolean', description: 'True once every membership record of the list was removed before the list was deleted.' },
+ ],
+};
+
+export const addListMemberOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'listItemUri', label: 'Membership URI' },
+ { key: 'listItemCid', label: 'Membership CID' },
+ { key: 'listUri', label: 'List URI' },
+ { key: 'did', label: 'Member DID' },
+ ],
+};
+
+export const removeListMemberOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'removed', label: 'Memberships Removed', format: 'number' },
+ { key: 'listUri', label: 'List URI' },
+ { key: 'did', label: 'Member DID' },
+ ],
+};
+
+export const aiCreatePostOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'uri', label: 'Post URI' },
+ { key: 'cid', label: 'CID' },
+ { key: 'url', label: 'Post Link', format: 'url' },
+ { key: 'isReply', label: 'Is Reply', format: 'boolean' },
+ { key: 'quotedUri', label: 'Quoted Post URI' },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+ ],
+};
+
+export const aiLikeOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'likeUri', label: 'Like URI' },
+ { key: 'postUri', label: 'Post URI' },
+ { key: 'postCid', label: 'Post CID' },
+ { key: 'postUrl', label: 'Post Link', format: 'url' },
+ { key: 'alreadyLiked', label: 'Already Liked', format: 'boolean' },
+ ],
+};
+
+export const aiRepostOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'repostUri', label: 'Repost URI' },
+ { key: 'postUri', label: 'Post URI' },
+ { key: 'postCid', label: 'Post CID' },
+ { key: 'postUrl', label: 'Post Link', format: 'url' },
+ { key: 'alreadyReposted', label: 'Already Reposted', format: 'boolean' },
+ ],
+};
+
+export const getPostsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'posts', label: 'Posts', labelKey: 'text', listItems: listedPostFields },
+ { key: 'notFound', label: 'Not Found', description: 'Inputs whose post is deleted or not visible to this account.' },
+ ],
+};
+
+export const resolveHandleOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'handle', label: 'Handle' },
+ { key: 'did', label: 'DID' },
+ ],
+};
+
+export const unreadCountOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'count', label: 'Unread Notifications', format: 'number' },
+ { key: 'checkedAt', label: 'Checked At', format: 'datetime' },
+ ],
+};
+
+export const notificationTriggerOutputSchema: OutputSchema = {
+ fields: notificationFields,
+};
+
+export const mentionTriggerOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'notificationReason', label: 'Why', description: 'mention, reply or quote.' },
+ ...listedPostFields,
+ { key: 'replyToUri', label: 'Replied-To Post URI' },
+ { key: 'reasonSubject', label: 'Your Post URI', description: 'Your post that was replied to or quoted; null for mentions.' },
+ { key: 'isRead', label: 'Is Read', format: 'boolean' },
+ {
+ key: 'postAvailable',
+ label: 'Post Available',
+ format: 'boolean',
+ description: 'False when the post was deleted or hidden before the poll; the post fields then come from the notification and the counts are null.',
+ },
+ ],
+};
diff --git a/packages/pieces/community/bluesky/src/lib/triggers/new-follower-on-account.ts b/packages/pieces/community/bluesky/src/lib/triggers/new-follower-on-account.ts
index 11b48130584..4c3acabefe6 100644
--- a/packages/pieces/community/bluesky/src/lib/triggers/new-follower-on-account.ts
+++ b/packages/pieces/community/bluesky/src/lib/triggers/new-follower-on-account.ts
@@ -1,66 +1,14 @@
-import { createTrigger, TriggerStrategy, PiecePropValueSchema, AppConnectionValueForAuthProperty } from '@activepieces/pieces-framework';
-import { DedupeStrategy, Polling, pollingHelper } from '@activepieces/pieces-common';
+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
+import type { AppBskyActorDefs, AtpAgent } from '@atproto/api';
import { blueskyAuth } from '../common/auth';
import { newFollowerTriggerOutputSchema } from '../output-schemas';
-import { createBlueskyAgent } from '../common/client';
-import dayjs from 'dayjs';
+import { blueskyClient } from '../common/client';
+import { blueskyPolling, PageFetcher } from '../common/polling';
+import { blueskyRefs } from '../common/refs';
-const polling: Polling<AppConnectionValueForAuthProperty<typeof blueskyAuth>, Record<string, never>> = {
- strategy: DedupeStrategy.TIMEBASED,
- items: async ({ auth, lastFetchEpochMS }) => {
- try {
- const agent = await createBlueskyAgent(auth.props);
-
- const session = agent.session;
- if (!session?.did) {
- throw new Error('Could not get user DID from session');
- }
-
- const userDid = session.did;
-
- const response = await agent.getFollowers({
- actor: userDid,
- limit: 100
- });
-
- if (!response.data?.followers || !Array.isArray(response.data.followers)) {
- return [];
- }
-
- const currentTime = Date.now();
- const cutoffTime = lastFetchEpochMS || 0;
-
- return response.data.followers
- .filter((follower: any) => {
- const profileTime = follower.indexedAt ? dayjs(follower.indexedAt).valueOf() : currentTime;
- return profileTime > cutoffTime - (24 * 60 * 60 * 1000);
- })
- .map((follower: any) => ({
- epochMilliSeconds: follower.indexedAt ? dayjs(follower.indexedAt).valueOf() : currentTime,
- data: {
- did: follower.did,
- handle: follower.handle,
- displayName: follower.displayName || follower.handle,
- description: follower.description || '',
- avatar: follower.avatar || '',
- banner: follower.banner || '',
- followersCount: follower.followersCount || 0,
- followsCount: follower.followsCount || 0,
- postsCount: follower.postsCount || 0,
- indexedAt: follower.indexedAt || new Date().toISOString(),
- viewer: follower.viewer || {},
- labels: follower.labels || [],
- createdAt: follower.createdAt || null
- }
- }))
- .sort((a: any, b: any) => b.epochMilliSeconds - a.epochMilliSeconds);
-
- } catch (error) {
- console.error('Error fetching followers:', error);
- return [];
- }
- }
-};
+const STORE_KEY = 'bluesky_followers_poll';
+const FOLLOWER_SEEN_CAP = 1000;
+const FOLLOWER_SEED_PAGES = 10;
export const newFollowerOnAccount = createTrigger({
auth: blueskyAuth,
@@ -69,7 +17,8 @@ export const newFollowerOnAccount = createTrigger({
displayName: 'New Follower on Account',
description: 'Triggers when someone new follows your Bluesky account',
aiMetadata: {
- description: 'Fires when a new account follows the authenticated Bluesky account; each event represents one new follower and carries that follower\'s profile details.',
+ description:
+ 'Fires when a new account follows the authenticated Bluesky account; each event represents one new follower and carries that follower\'s profile details. An account that unfollows and follows again does not fire twice.',
},
props: {},
sampleData: {
@@ -79,6 +28,7 @@ export const newFollowerOnAccount = createTrigger({
description: 'A new user who just followed your account',
avatar: 'https://cdn.bsky.app/img/avatar/plain/did:plc:example123/example@jpeg',
banner: '',
+ url: 'https://bsky.app/profile/newfollower.bsky.social',
followersCount: 0,
followsCount: 0,
postsCount: 0,
@@ -87,29 +37,82 @@ export const newFollowerOnAccount = createTrigger({
muted: false,
blockedBy: false,
following: 'at://did:plc:example123/app.bsky.graph.follow/example456',
- followedBy: 'at://did:plc:example456/app.bsky.graph.follow/example789'
+ followedBy: 'at://did:plc:example456/app.bsky.graph.follow/example789',
},
labels: [],
- createdAt: '2023-06-01T12:00:00.000Z'
+ createdAt: '2023-06-01T12:00:00.000Z',
},
type: TriggerStrategy.POLLING,
outputSchema: newFollowerTriggerOutputSchema,
-
async test(context) {
- return await pollingHelper.test(polling, context);
+ return blueskyClient.withBluesky({
+ auth: context.auth.props,
+ action: 'read your followers',
+ fn: (agent) => blueskyPolling.sample({ fetchPage: followersPage({ agent }) }),
+ });
},
-
async onEnable(context) {
- const { store, auth, propsValue } = context;
- await pollingHelper.onEnable(polling, { store, auth, propsValue });
+ await blueskyClient.withBluesky({
+ auth: context.auth.props,
+ action: 'read your followers',
+ fn: (agent) =>
+ blueskyPolling.onEnable({
+ store: context.store,
+ storeKey: STORE_KEY,
+ fetchPage: followersPage({ agent }),
+ isRepublish: context.isRepublish,
+ seenCap: FOLLOWER_SEEN_CAP,
+ seedPages: FOLLOWER_SEED_PAGES,
+ }),
+ });
},
-
async onDisable(context) {
- const { store, auth, propsValue } = context;
- await pollingHelper.onDisable(polling, { store, auth, propsValue });
+ await blueskyPolling.onDisable({ store: context.store, storeKey: STORE_KEY });
},
-
async run(context) {
- return await pollingHelper.poll(polling, context);
+ return blueskyClient.withBluesky({
+ auth: context.auth.props,
+ action: 'read your followers',
+ fn: (agent) =>
+ blueskyPolling.poll({
+ store: context.store,
+ storeKey: STORE_KEY,
+ fetchPage: followersPage({ agent }),
+ seenCap: FOLLOWER_SEEN_CAP,
+ seedPages: FOLLOWER_SEED_PAGES,
+ }),
+ });
},
-});
\ No newline at end of file
+});
+
+function followersPage({ agent }: { agent: AtpAgent }): PageFetcher<ReturnType<typeof followerItem>> {
+ return async ({ cursor }) => {
+ const response = await agent.getFollowers({ actor: blueskyClient.sessionDid(agent), limit: 100, cursor });
+ const now = Date.now();
+ return {
+ items: response.data.followers.map((follower) => ({ key: follower.did, time: now, data: followerItem(follower) })),
+ cursor: response.data.cursor,
+ oldestTime: undefined,
+ newestTime: undefined,
+ };
+ };
+}
+
+function followerItem(follower: AppBskyActorDefs.ProfileView) {
+ return {
+ did: follower.did,
+ handle: follower.handle,
+ displayName: follower.displayName || follower.handle,
+ description: follower.description || '',
+ avatar: follower.avatar || '',
+ banner: '',
+ url: blueskyRefs.profileWebUrl(follower.handle === 'handle.invalid' ? follower.did : follower.handle),
+ followersCount: 0,
+ followsCount: 0,
+ postsCount: 0,
+ indexedAt: follower.indexedAt || new Date().toISOString(),
+ viewer: follower.viewer || {},
+ labels: follower.labels || [],
+ createdAt: follower.createdAt || null,
+ };
+}
diff --git a/packages/pieces/community/bluesky/src/lib/triggers/new-mention.ts b/packages/pieces/community/bluesky/src/lib/triggers/new-mention.ts
new file mode 100644
index 00000000000..02132de781d
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/triggers/new-mention.ts
@@ -0,0 +1,149 @@
+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
+import type { AppBskyFeedDefs, AppBskyNotificationListNotifications, AtpAgent } from '@atproto/api';
+import { blueskyAuth } from '../common/auth';
+import { mentionTriggerOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyMappers } from '../common/mappers';
+import { blueskyPolling, PageFetcher } from '../common/polling';
+import { blueskyRefs } from '../common/refs';
+
+const STORE_KEY = 'bluesky_mention_poll';
+const MENTION_REASONS = ['mention', 'reply', 'quote'];
+const GET_POSTS_BATCH = 25;
+
+export const newMention = createTrigger({
+ auth: blueskyAuth,
+ name: 'new_mention',
+ classification: 'READ',
+ displayName: 'New Mention or Reply',
+ description: 'Triggers when someone mentions you, replies to you or quotes your post',
+ aiMetadata: {
+ description:
+ 'Fires once per new post that mentions the authenticated Bluesky account, replies to it, or quotes one of its posts, carrying the full post plus why it notified. If the post was deleted or hidden before the poll, it still fires with the notification\'s copy of the post, postAvailable=false and null counts. It follows the account\'s notification settings, for example "only from people I follow", and never marks notifications as seen; use New Notification for likes, reposts or follows.',
+ },
+ props: {},
+ sampleData: {
+ uri: 'at://did:plc:example123/app.bsky.feed.post/3kexample',
+ cid: 'bafyreib2rxk3vcfbqij7y6kzgy4knknc7ff4t5jn2m5fbn6jdl7czfqyqe',
+ url: 'https://bsky.app/profile/friend.bsky.social/post/3kexample',
+ author: {
+ did: 'did:plc:example123',
+ handle: 'friend.bsky.social',
+ displayName: 'A Friend',
+ avatar: 'https://cdn.bsky.app/img/avatar/plain/did:plc:example123/example@jpeg',
+ },
+ record: { $type: 'app.bsky.feed.post', text: '@you.bsky.social what do you think?', createdAt: '2026-10-05T12:00:00.000Z' },
+ indexedAt: '2026-10-05T12:00:00.000Z',
+ replyCount: 0,
+ repostCount: 0,
+ likeCount: 0,
+ quoteCount: 0,
+ labels: [],
+ viewer: {},
+ embed: null,
+ text: '@you.bsky.social what do you think?',
+ notificationReason: 'mention',
+ reasonSubject: null,
+ isRead: false,
+ replyToUri: null,
+ postAvailable: true,
+ },
+ type: TriggerStrategy.POLLING,
+ outputSchema: mentionTriggerOutputSchema,
+ async test(context) {
+ return blueskyClient.withBluesky({
+ auth: context.auth.props,
+ action: 'read mentions',
+ fn: (agent) => blueskyPolling.sample({ fetchPage: mentionPage({ agent }) }),
+ });
+ },
+ async onEnable(context) {
+ await blueskyClient.withBluesky({
+ auth: context.auth.props,
+ action: 'read mentions',
+ fn: (agent) => blueskyPolling.onEnable({ store: context.store, storeKey: STORE_KEY, fetchPage: mentionPage({ agent }), isRepublish: context.isRepublish }),
+ });
+ },
+ async onDisable(context) {
+ await blueskyPolling.onDisable({ store: context.store, storeKey: STORE_KEY });
+ },
+ async run(context) {
+ return blueskyClient.withBluesky({
+ auth: context.auth.props,
+ action: 'read mentions',
+ fn: (agent) => blueskyPolling.poll({ store: context.store, storeKey: STORE_KEY, fetchPage: mentionPage({ agent }) }),
+ });
+ },
+});
+
+function mentionPage({ agent }: { agent: AtpAgent }): PageFetcher<ReturnType<typeof mentionItem>> {
+ return async ({ cursor }) => {
+ const response = await agent.listNotifications({ limit: 100, cursor, reasons: MENTION_REASONS });
+ const notifications = response.data.notifications.filter((notification) => MENTION_REASONS.includes(notification.reason));
+ const posts = await hydrate({ agent, uris: [...new Set(notifications.map((notification) => notification.uri))] });
+ const items = notifications.map((notification) => ({
+ key: `${notification.reason}:${notification.uri}`,
+ time: blueskyPolling.timeOf(notification.indexedAt) ?? 0,
+ data: mentionItem({ notification, post: posts.get(notification.uri) }),
+ }));
+ return {
+ items,
+ cursor: response.data.cursor,
+ ...blueskyPolling.pageTimes(response.data.notifications.map((notification) => blueskyPolling.timeOf(notification.indexedAt))),
+ };
+ };
+}
+
+async function hydrate({ agent, uris }: { agent: AtpAgent; uris: string[] }): Promise<Map<string, AppBskyFeedDefs.PostView>> {
+ const batches = Array.from({ length: Math.ceil(uris.length / GET_POSTS_BATCH) }, (_, index) =>
+ uris.slice(index * GET_POSTS_BATCH, (index + 1) * GET_POSTS_BATCH),
+ );
+ const results: AppBskyFeedDefs.PostView[] = [];
+ for (const batch of batches) {
+ const response = await agent.getPosts({ uris: batch });
+ results.push(...response.data.posts);
+ }
+ return new Map(results.map((post) => [post.uri, post]));
+}
+
+function mentionItem({
+ notification,
+ post,
+}: {
+ notification: AppBskyNotificationListNotifications.Notification;
+ post: AppBskyFeedDefs.PostView | undefined;
+}) {
+ const notificationFields = {
+ notificationReason: notification.reason,
+ reasonSubject: notification.reasonSubject ?? null,
+ isRead: notification.isRead,
+ };
+ if (post) {
+ return {
+ ...blueskyMappers.postBase(post),
+ text: blueskyMappers.recordText(post.record),
+ ...notificationFields,
+ replyToUri: blueskyMappers.recordReplyParentUri(post.record),
+ postAvailable: true,
+ };
+ }
+ return {
+ uri: notification.uri,
+ cid: notification.cid,
+ url: blueskyRefs.postWebUrl({ uri: notification.uri, handle: notification.author.handle }),
+ author: notification.author,
+ record: notification.record,
+ indexedAt: notification.indexedAt,
+ replyCount: null,
+ repostCount: null,
+ likeCount: null,
+ quoteCount: null,
+ labels: notification.labels ?? [],
+ viewer: {},
+ embed: null,
+ text: blueskyMappers.recordText(notification.record),
+ ...notificationFields,
+ replyToUri: blueskyMappers.recordReplyParentUri(notification.record),
+ postAvailable: false,
+ };
+}
diff --git a/packages/pieces/community/bluesky/src/lib/triggers/new-notification.ts b/packages/pieces/community/bluesky/src/lib/triggers/new-notification.ts
new file mode 100644
index 00000000000..d770cebd659
--- /dev/null
+++ b/packages/pieces/community/bluesky/src/lib/triggers/new-notification.ts
@@ -0,0 +1,99 @@
+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
+import type { AtpAgent } from '@atproto/api';
+import { blueskyAuth } from '../common/auth';
+import { notificationTriggerOutputSchema } from '../output-schemas';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyMappers } from '../common/mappers';
+import { blueskyCompose } from '../common/compose';
+import { blueskyPolling, PageFetcher } from '../common/polling';
+
+const STORE_KEY = 'bluesky_notification_poll';
+const DEFAULT_REASONS = ['mention', 'reply', 'quote'];
+
+export const newNotification = createTrigger({
+ auth: blueskyAuth,
+ name: 'new_notification',
+ classification: 'READ',
+ displayName: 'New Notification',
+ description: 'Triggers when you get a new notification (mention, reply, quote, like, repost, follow and more)',
+ aiMetadata: {
+ description:
+ 'Fires once per new notification of the authenticated Bluesky account whose type is in the chosen list (default: mentions, replies and quotes; likes, reposts, follows and others can be added). It never marks notifications as seen, and it follows the account\'s notification settings, for example "only from people I follow".',
+ },
+ props: {
+ reasons: blueskyProps.notificationReasonsProperty({
+ defaultValue: DEFAULT_REASONS,
+ description: 'Which notification types trigger the flow. Leave empty for all types.',
+ }),
+ },
+ sampleData: {
+ uri: 'at://did:plc:example123/app.bsky.feed.post/3kexample',
+ cid: 'bafyreib2rxk3vcfbqij7y6kzgy4knknc7ff4t5jn2m5fbn6jdl7czfqyqe',
+ reason: 'mention',
+ reasonSubject: null,
+ isRead: false,
+ indexedAt: '2026-10-05T12:00:00.000Z',
+ author: {
+ did: 'did:plc:example123',
+ handle: 'friend.bsky.social',
+ displayName: 'A Friend',
+ description: '',
+ avatar: 'https://cdn.bsky.app/img/avatar/plain/did:plc:example123/example@jpeg',
+ url: 'https://bsky.app/profile/friend.bsky.social',
+ createdAt: '2024-01-01T12:00:00.000Z',
+ indexedAt: '2024-01-01T12:00:00.000Z',
+ viewer: { muted: false, blockedBy: false },
+ labels: [],
+ },
+ text: 'Hey @you.bsky.social, have a look at this!',
+ record: { $type: 'app.bsky.feed.post', text: 'Hey @you.bsky.social, have a look at this!', createdAt: '2026-10-05T12:00:00.000Z' },
+ url: 'https://bsky.app/profile/friend.bsky.social/post/3kexample',
+ },
+ type: TriggerStrategy.POLLING,
+ outputSchema: notificationTriggerOutputSchema,
+ async test(context) {
+ const reasons = reasonsFrom(context.propsValue.reasons);
+ return blueskyClient.withBluesky({
+ auth: context.auth.props,
+ action: 'read notifications',
+ fn: (agent) => blueskyPolling.sample({ fetchPage: notificationPage({ agent, reasons }) }),
+ });
+ },
+ async onEnable(context) {
+ const reasons = reasonsFrom(context.propsValue.reasons);
+ await blueskyClient.withBluesky({
+ auth: context.auth.props,
+ action: 'read notifications',
+ fn: (agent) =>
+ blueskyPolling.onEnable({ store: context.store, storeKey: STORE_KEY, fetchPage: notificationPage({ agent, reasons }), isRepublish: context.isRepublish }),
+ });
+ },
+ async onDisable(context) {
+ await blueskyPolling.onDisable({ store: context.store, storeKey: STORE_KEY });
+ },
+ async run(context) {
+ const reasons = reasonsFrom(context.propsValue.reasons);
+ return blueskyClient.withBluesky({
+ auth: context.auth.props,
+ action: 'read notifications',
+ fn: (agent) => blueskyPolling.poll({ store: context.store, storeKey: STORE_KEY, fetchPage: notificationPage({ agent, reasons }) }),
+ });
+ },
+});
+
+function reasonsFrom(raw: unknown): string[] {
+ return blueskyCompose.stringList(raw);
+}
+
+function notificationPage({ agent, reasons }: { agent: AtpAgent; reasons: string[] }): PageFetcher<ReturnType<typeof blueskyMappers.notificationItem>> {
+ return async ({ cursor }) => {
+ const response = await agent.listNotifications({ limit: 100, cursor, ...(reasons.length > 0 ? { reasons } : {}) });
+ const items = response.data.notifications.map((notification) => ({
+ key: `${notification.reason}:${notification.uri}`,
+ time: blueskyPolling.timeOf(notification.indexedAt) ?? 0,
+ data: blueskyMappers.notificationItem(notification),
+ }));
+ return { items, cursor: response.data.cursor, ...blueskyPolling.pageTimes(items.map((item) => item.time)) };
+ };
+}
diff --git a/packages/pieces/community/bluesky/src/lib/triggers/new-post.ts b/packages/pieces/community/bluesky/src/lib/triggers/new-post.ts
index 3e56b3fa802..47980be48d9 100644
--- a/packages/pieces/community/bluesky/src/lib/triggers/new-post.ts
+++ b/packages/pieces/community/bluesky/src/lib/triggers/new-post.ts
@@ -1,121 +1,13 @@
-import { createTrigger, TriggerStrategy, PiecePropValueSchema, Property, AppConnectionValueForAuthProperty } from '@activepieces/pieces-framework';
-import { DedupeStrategy, Polling, pollingHelper } from '@activepieces/pieces-common';
+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';
+import type { AppBskyFeedDefs, AtpAgent } from '@atproto/api';
import { blueskyAuth } from '../common/auth';
import { newPostTriggerOutputSchema } from '../output-schemas';
-import { createBlueskyAgent } from '../common/client';
-import { simpleLanguageDropdown } from '../common/props';
-import dayjs from 'dayjs';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyMappers } from '../common/mappers';
+import { blueskyPolling, PageFetcher } from '../common/polling';
-const polling: Polling<AppConnectionValueForAuthProperty<typeof blueskyAuth>, {
- searchQuery: string;
- searchLanguage?: string;
- includeImages?: boolean;
- includeVideos?: boolean;
- sortBy?: string;
-}> = {
- strategy: DedupeStrategy.TIMEBASED,
- items: async ({ auth, propsValue, lastFetchEpochMS }) => {
- const { searchQuery, searchLanguage, includeImages, includeVideos, sortBy } = propsValue;
-
- try {
- if (!searchQuery || searchQuery.trim().length === 0) {
- return [];
- }
-
- const agent = await createBlueskyAgent(auth.props);
-
- const searchParams: any = {
- q: searchQuery.trim(),
- limit: 50,
- sort: sortBy || 'latest'
- };
-
- if (searchLanguage && searchLanguage !== 'other') {
- searchParams.lang = searchLanguage;
- }
-
- const response = await agent.api.app.bsky.feed.searchPosts(searchParams);
-
- if (!response.data?.posts || !Array.isArray(response.data.posts)) {
- return [];
- }
-
- const cutoffTime = lastFetchEpochMS || 0;
-
- return response.data.posts
- .filter((post: any) => {
- if (!post.indexedAt) return false;
-
- const postTime = dayjs(post.indexedAt).valueOf();
- if (postTime <= cutoffTime) return false;
-
- if (includeImages === false && post.embed?.images) return false;
- if (includeVideos === false && post.embed?.video) return false;
- if (includeImages === true && !post.embed?.images) return false;
- if (includeVideos === true && !post.embed?.video) return false;
-
- return true;
- })
- .map((post: any) => ({
- epochMilliSeconds: dayjs(post.indexedAt).valueOf(),
- data: {
- uri: post.uri,
- cid: post.cid,
- author: post.author,
- record: post.record,
- indexedAt: post.indexedAt,
-
- replyCount: post.replyCount || 0,
- repostCount: post.repostCount || 0,
- likeCount: post.likeCount || 0,
- quoteCount: post.quoteCount || 0,
-
- labels: post.labels || [],
- viewer: post.viewer || {},
- embed: post.embed || null,
-
- searchContext: {
- query: searchQuery,
- language: searchLanguage || null,
- matchedTerms: extractMatchedTerms(post.record?.text || '', searchQuery),
- hasImages: !!(post.embed?.images),
- hasVideo: !!(post.embed?.video),
- hasExternalLink: !!(post.embed?.external)
- }
- }
- }))
- .sort((a: any, b: any) => b.epochMilliSeconds - a.epochMilliSeconds);
-
- } catch (error) {
- console.warn('Failed to search posts:', error instanceof Error ? error.message : 'Unknown error');
- return [];
- }
- }
-};
-
-function extractMatchedTerms(text: string, query: string): string[] {
- if (!text || !query) return [];
-
- const cleanQuery = query.toLowerCase()
- .replace(/["']/g, '')
- .replace(/\s+(or|and)\s+/gi, ' ');
-
- const terms = cleanQuery.split(/\s+/).filter(term => term.length > 0 && !['or', 'and'].includes(term.toLowerCase()));
- const matchedTerms: string[] = [];
- const lowerText = text.toLowerCase();
-
- terms.forEach(term => {
- if (term.startsWith('#') || term.startsWith('@')) {
- if (lowerText.includes(term)) {
- matchedTerms.push(term);
- }
- } else if (lowerText.includes(term)) {
- matchedTerms.push(term);
- }
- });
-
- return [...new Set(matchedTerms)];
-}
+const STORE_KEY = 'bluesky_search_poll';
export const newPost = createTrigger({
auth: blueskyAuth,
@@ -124,31 +16,32 @@ export const newPost = createTrigger({
displayName: 'New Post (with Search Options)',
description: 'Triggers when posts match your search criteria',
aiMetadata: {
- description: 'Fires when a new public Bluesky post matches a configured search query (keywords, hashtags, or mentions), with optional language and media filters; each event represents one newly indexed matching post.',
+ description:
+ 'Fires when a new public Bluesky post matches a configured search query (keywords, hashtags, or mentions), with optional language filter and "only with images/videos" filters; each event represents one newly indexed matching post. With Most Popular sorting only the first page of top results is checked.',
},
props: {
searchQuery: Property.ShortText({
displayName: 'Search Query',
description: 'Keywords, hashtags (#example), or mentions (@handle) to find',
- required: true
+ required: true,
}),
searchLanguage: {
- ...simpleLanguageDropdown,
+ ...blueskyProps.simpleLanguageDropdown,
displayName: 'Language Filter',
description: 'Filter by language',
- required: false
+ required: false,
},
includeImages: Property.Checkbox({
displayName: 'Filter by Images',
- description: 'Only posts with/without images',
+ description: 'When ticked, only posts with images trigger the flow',
required: false,
- defaultValue: undefined
+ defaultValue: undefined,
}),
includeVideos: Property.Checkbox({
displayName: 'Filter by Videos',
- description: 'Only posts with/without videos',
+ description: 'When ticked, only posts with a video trigger the flow',
required: false,
- defaultValue: undefined
+ defaultValue: undefined,
}),
sortBy: Property.StaticDropdown({
displayName: 'Sort Order',
@@ -158,71 +51,164 @@ export const newPost = createTrigger({
options: {
options: [
{ label: 'Latest First', value: 'latest' },
- { label: 'Most Popular', value: 'top' }
- ]
- }
- })
+ { label: 'Most Popular', value: 'top' },
+ ],
+ },
+ }),
},
sampleData: {
uri: 'at://did:plc:example123/app.bsky.feed.post/example456',
cid: 'bafyreib2rxk3vcfbqij7y6kzgy4knknc7ff4t5jn2m5fbn6jdl7czfqyqe',
+ url: 'https://bsky.app/profile/searchauthor.bsky.social/post/example456',
author: {
did: 'did:plc:example123',
handle: 'searchauthor.bsky.social',
displayName: 'Search Result Author',
avatar: 'https://cdn.bsky.app/img/avatar/plain/did:plc:example123/example@jpeg',
- viewer: {
- muted: false,
- blockedBy: false
- }
+ viewer: { muted: false, blockedBy: false },
},
record: {
$type: 'app.bsky.feed.post',
createdAt: '2024-01-01T12:00:00.000Z',
text: 'This post matches your search criteria! #automation #activepieces',
- langs: ['en']
+ langs: ['en'],
},
indexedAt: '2024-01-01T12:00:00.000Z',
-
replyCount: 2,
repostCount: 5,
likeCount: 12,
quoteCount: 1,
-
labels: [],
- viewer: {
- repost: null,
- like: null
- },
+ viewer: { repost: null, like: null },
embed: null,
-
searchContext: {
query: 'automation',
language: 'en',
matchedTerms: ['automation'],
hasImages: false,
hasVideo: false,
- hasExternalLink: false
- }
+ hasExternalLink: false,
+ },
},
type: TriggerStrategy.POLLING,
outputSchema: newPostTriggerOutputSchema,
-
async test(context) {
- return await pollingHelper.test(polling, context);
+ const config = searchConfig(context.propsValue);
+ if (config === null) {
+ return [];
+ }
+ return blueskyClient.withBluesky({
+ auth: context.auth.props,
+ action: 'search posts',
+ fn: (agent) => blueskyPolling.sample({ fetchPage: searchPage({ agent, config }) }),
+ });
},
-
async onEnable(context) {
- const { store, auth, propsValue } = context;
- await pollingHelper.onEnable(polling, { store, auth, propsValue });
+ const config = searchConfig(context.propsValue);
+ if (config === null) {
+ return;
+ }
+ await blueskyClient.withBluesky({
+ auth: context.auth.props,
+ action: 'search posts',
+ fn: (agent) =>
+ blueskyPolling.onEnable({ store: context.store, storeKey: STORE_KEY, fetchPage: searchPage({ agent, config }), isRepublish: context.isRepublish }),
+ });
},
-
async onDisable(context) {
- const { store, auth, propsValue } = context;
- await pollingHelper.onDisable(polling, { store, auth, propsValue });
+ await blueskyPolling.onDisable({ store: context.store, storeKey: STORE_KEY });
},
-
async run(context) {
- return await pollingHelper.poll(polling, context);
+ const config = searchConfig(context.propsValue);
+ if (config === null) {
+ return [];
+ }
+ return blueskyClient.withBluesky({
+ auth: context.auth.props,
+ action: 'search posts',
+ fn: (agent) =>
+ blueskyPolling.poll({
+ store: context.store,
+ storeKey: STORE_KEY,
+ fetchPage: searchPage({ agent, config }),
+ maxPages: config.sort === 'top' ? 1 : blueskyPolling.MAX_PAGES,
+ resumable: config.sort !== 'top',
+ }),
+ });
},
-});
\ No newline at end of file
+});
+
+function searchConfig(props: {
+ searchQuery: string;
+ searchLanguage?: string;
+ includeImages?: boolean;
+ includeVideos?: boolean;
+ sortBy?: string;
+}): SearchConfig | null {
+ const query = (props.searchQuery ?? '').trim();
+ if (query === '') {
+ return null;
+ }
+ return {
+ query,
+ lang: props.searchLanguage && props.searchLanguage !== 'other' ? props.searchLanguage : undefined,
+ language: props.searchLanguage || null,
+ onlyImages: props.includeImages === true,
+ onlyVideos: props.includeVideos === true,
+ sort: props.sortBy === 'top' ? 'top' : 'latest',
+ };
+}
+
+function searchPage({ agent, config }: { agent: AtpAgent; config: SearchConfig }): PageFetcher<ReturnType<typeof searchItem>> {
+ return async ({ cursor }) => {
+ const response = await agent.app.bsky.feed.searchPosts({
+ q: config.query,
+ limit: 100,
+ sort: config.sort,
+ cursor,
+ ...(config.lang ? { lang: config.lang } : {}),
+ });
+ const times = response.data.posts.map((post) => blueskyPolling.timeOf(post.indexedAt));
+ const items = response.data.posts
+ .filter((post) => {
+ const flags = blueskyMappers.mediaFlags(post.embed);
+ return (!config.onlyImages || flags.hasImages) && (!config.onlyVideos || flags.hasVideo);
+ })
+ .map((post) => ({ key: post.uri, time: blueskyPolling.timeOf(post.indexedAt) ?? 0, data: searchItem({ post, config }) }));
+ return { items, cursor: response.data.cursor, ...blueskyPolling.pageTimes(times) };
+ };
+}
+
+function searchItem({ post, config }: { post: AppBskyFeedDefs.PostView; config: SearchConfig }) {
+ return {
+ ...blueskyMappers.postBase(post),
+ searchContext: {
+ query: config.query,
+ language: config.language,
+ matchedTerms: extractMatchedTerms({ text: blueskyMappers.recordText(post.record), query: config.query }),
+ ...blueskyMappers.mediaFlags(post.embed),
+ },
+ };
+}
+
+function extractMatchedTerms({ text, query }: { text: string; query: string }): string[] {
+ if (!text || !query) {
+ return [];
+ }
+ const terms = query
+ .toLowerCase()
+ .replace(/["']/g, '')
+ .split(/\s+/)
+ .filter((term) => term.length > 0 && term !== 'or' && term !== 'and');
+ const lowerText = text.toLowerCase();
+ return [...new Set(terms.filter((term) => lowerText.includes(term)))];
+}
+
+type SearchConfig = {
+ query: string;
+ lang: string | undefined;
+ language: string | null;
+ onlyImages: boolean;
+ onlyVideos: boolean;
+ sort: 'top' | 'latest';
+};
diff --git a/packages/pieces/community/bluesky/src/lib/triggers/new-posts-by-author.ts b/packages/pieces/community/bluesky/src/lib/triggers/new-posts-by-author.ts
index 1d9c12383ab..19aaca548f1 100644
--- a/packages/pieces/community/bluesky/src/lib/triggers/new-posts-by-author.ts
+++ b/packages/pieces/community/bluesky/src/lib/triggers/new-posts-by-author.ts
@@ -1,113 +1,15 @@
-import { createTrigger, TriggerStrategy, PiecePropValueSchema, Property, AppConnectionValueForAuthProperty } from '@activepieces/pieces-framework';
-import { DedupeStrategy, Polling, pollingHelper } from '@activepieces/pieces-common';
-import { blueskyAuth, BlueSkyAuthType } from '../common/auth';
+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';
+import type { AppBskyFeedDefs, AtpAgent } from '@atproto/api';
+import { blueskyAtproto } from '../common/atproto';
+import { blueskyAuth } from '../common/auth';
import { newPostsByAuthorTriggerOutputSchema } from '../output-schemas';
-import { createBlueskyAgent } from '../common/client';
-import dayjs from 'dayjs';
+import { blueskyClient } from '../common/client';
+import { blueskyProps } from '../common/props';
+import { blueskyRefs } from '../common/refs';
+import { blueskyMappers } from '../common/mappers';
+import { blueskyPolling, PageFetcher } from '../common/polling';
-const polling: Polling<AppConnectionValueForAuthProperty<typeof blueskyAuth>, {
- authorSelection: string;
- authorFromFollowing?: string;
- authorHandle?: string;
- includeReplies?: boolean;
- includeReposts?: boolean;
-}> = {
- strategy: DedupeStrategy.TIMEBASED,
- items: async ({ auth, propsValue, lastFetchEpochMS }) => {
- const { authorSelection, authorFromFollowing, authorHandle, includeReplies = false, includeReposts = false } = propsValue;
-
- let selectedAuthorHandle: string;
- if (authorSelection === 'following') {
- if (!authorFromFollowing) {
- return [];
- }
- selectedAuthorHandle = authorFromFollowing;
- } else if (authorSelection === 'manual') {
- if (!authorHandle) {
- return [];
- }
- selectedAuthorHandle = authorHandle;
- } else {
- return [];
- }
-
- try {
- if (!selectedAuthorHandle || selectedAuthorHandle.trim().length === 0) {
- return [];
- }
-
- const agent = await createBlueskyAgent(auth.props);
-
- const normalizedHandle = selectedAuthorHandle.replace('@', '').trim();
-
- const response = await agent.getAuthorFeed({
- actor: normalizedHandle,
- limit: 50,
- filter: 'posts_with_replies'
- });
-
- if (!response.data?.feed || !Array.isArray(response.data.feed)) {
- return [];
- }
-
- const cutoffTime = lastFetchEpochMS || 0;
-
- return response.data.feed
- .filter((feedItem: any) => {
- const post = feedItem.post;
- if (!post || !post.indexedAt) return false;
-
- const postTime = dayjs(post.indexedAt).valueOf();
- if (postTime <= cutoffTime) return false;
-
- const isReply = post.record?.reply !== undefined;
- const isRepost = feedItem.reason?.$type === 'app.bsky.feed.defs#reasonRepost';
-
- if (isReply && !includeReplies) return false;
- if (isRepost && !includeReposts) return false;
-
- return post.author.handle === normalizedHandle || post.author.did === normalizedHandle;
- })
- .map((feedItem: any) => {
- const post = feedItem.post;
- return {
- epochMilliSeconds: dayjs(post.indexedAt).valueOf(),
- data: {
- uri: post.uri,
- cid: post.cid,
- author: post.author,
- record: post.record,
- indexedAt: post.indexedAt,
-
- replyCount: post.replyCount || 0,
- repostCount: post.repostCount || 0,
- likeCount: post.likeCount || 0,
- quoteCount: post.quoteCount || 0,
-
- labels: post.labels || [],
- viewer: post.viewer || {},
- embed: post.embed || null,
-
- postContext: {
- authorHandle: normalizedHandle,
- isReply: post.record?.reply !== undefined,
- isRepost: feedItem.reason?.$type === 'app.bsky.feed.defs#reasonRepost',
- replyTo: post.record?.reply?.parent?.uri || null,
- hasImages: !!(post.embed?.images),
- hasVideo: !!(post.embed?.video),
- hasExternalLink: !!(post.embed?.external)
- }
- }
- };
- })
- .sort((a: any, b: any) => b.epochMilliSeconds - a.epochMilliSeconds);
-
- } catch (error) {
- console.warn('Failed to fetch author posts:', error instanceof Error ? error.message : 'Unknown error');
- return [];
- }
- }
-};
+const STORE_KEY = 'bluesky_author_poll';
export const newPostsByAuthor = createTrigger({
auth: blueskyAuth,
@@ -116,7 +18,8 @@ export const newPostsByAuthor = createTrigger({
displayName: 'New Posts by Author',
description: 'Triggers when a selected author creates a new post',
aiMetadata: {
- description: 'Fires when a chosen Bluesky author (picked from your following list or by handle) publishes a new post; each event represents one new post by that author, optionally including their replies and reposts.',
+ description:
+ 'Fires when a chosen Bluesky author (picked from your following list or by handle) publishes a new post; each event represents one new post by that author, optionally including their replies and the posts they repost.',
},
props: {
authorSelection: Property.StaticDropdown({
@@ -131,97 +34,50 @@ export const newPostsByAuthor = createTrigger({
],
},
}),
-
- authorFromFollowing: Property.Dropdown({
- auth: blueskyAuth,
- displayName: 'Select Author',
- description: 'Choose from accounts you follow',
- required: false,
- refreshers: ['auth'],
- options: async ({ auth }) => {
- try {
- if (!auth) return { options: [] };
- const agent = await createBlueskyAgent(auth.props);
- const session = agent.session;
-
- if (!session?.did) {
- return { options: [{ label: 'Please authenticate first', value: '' }] };
- }
-
- const followingResponse = await agent.getFollows({
- actor: session.did,
- limit: 100
- });
-
- return {
- options: followingResponse.data.follows.map(follow => ({
- label: `${follow.displayName || follow.handle} (@${follow.handle})`,
- value: follow.handle
- }))
- };
- } catch (error) {
- return {
- options: [{ label: 'Error loading following list', value: '' }]
- };
- }
- }
- }),
-
+ authorFromFollowing: blueskyProps.followingDropdown(),
authorHandle: Property.ShortText({
displayName: 'Author Handle',
- description: 'Enter the Bluesky username (e.g., username.bsky.social)',
- required: false
+ description: 'Enter the Bluesky username (e.g., username.bsky.social), a DID or a profile link',
+ required: false,
}),
includeReplies: Property.Checkbox({
displayName: 'Include Replies',
description: 'Include reply posts by this author',
required: false,
- defaultValue: false
+ defaultValue: false,
}),
includeReposts: Property.Checkbox({
displayName: 'Include Reposts',
description: 'Include posts that this author reposted',
required: false,
- defaultValue: false
- })
+ defaultValue: false,
+ }),
},
sampleData: {
uri: 'at://did:plc:example123/app.bsky.feed.post/example456',
cid: 'bafyreib2rxk3vcfbqij7y6kzgy4knknc7ff4t5jn2m5fbn6jdl7czfqyqe',
+ url: 'https://bsky.app/profile/author.bsky.social/post/example456',
author: {
did: 'did:plc:example123',
handle: 'author.bsky.social',
displayName: 'Example Author',
avatar: 'https://cdn.bsky.app/img/avatar/plain/did:plc:example123/example@jpeg',
- followersCount: 1500,
- followsCount: 300,
- postsCount: 250,
- viewer: {
- muted: false,
- blockedBy: false,
- following: 'at://following-record-uri'
- }
+ viewer: { muted: false, blockedBy: false, following: 'at://following-record-uri' },
},
record: {
$type: 'app.bsky.feed.post',
createdAt: '2024-01-01T12:00:00.000Z',
text: 'Just posted something new! Excited to share this with everyone.',
- langs: ['en']
+ langs: ['en'],
},
indexedAt: '2024-01-01T12:00:00.000Z',
-
replyCount: 3,
repostCount: 8,
likeCount: 25,
quoteCount: 2,
-
labels: [],
- viewer: {
- repost: null,
- like: null
- },
+ viewer: { repost: null, like: null },
embed: null,
-
postContext: {
authorHandle: 'author.bsky.social',
isReply: false,
@@ -229,27 +85,112 @@ export const newPostsByAuthor = createTrigger({
replyTo: null,
hasImages: false,
hasVideo: false,
- hasExternalLink: false
- }
+ hasExternalLink: false,
+ },
},
type: TriggerStrategy.POLLING,
outputSchema: newPostsByAuthorTriggerOutputSchema,
-
async test(context) {
- return await pollingHelper.test(polling, context);
+ const config = authorConfig(context.propsValue);
+ return blueskyClient.withBluesky({
+ auth: context.auth.props,
+ action: "read the author's posts",
+ fn: async (agent) => blueskyPolling.sample({ fetchPage: authorPage({ agent, config, did: await authorDid({ agent, config }) }) }),
+ });
},
-
async onEnable(context) {
- const { store, auth, propsValue } = context;
- await pollingHelper.onEnable(polling, { store, auth, propsValue });
+ const config = authorConfig(context.propsValue);
+ await blueskyClient.withBluesky({
+ auth: context.auth.props,
+ action: "read the author's posts",
+ fn: async (agent) =>
+ blueskyPolling.onEnable({
+ store: context.store,
+ storeKey: STORE_KEY,
+ fetchPage: authorPage({ agent, config, did: await authorDid({ agent, config }) }),
+ isRepublish: context.isRepublish,
+ }),
+ });
},
-
async onDisable(context) {
- const { store, auth, propsValue } = context;
- await pollingHelper.onDisable(polling, { store, auth, propsValue });
+ await blueskyPolling.onDisable({ store: context.store, storeKey: STORE_KEY });
},
-
async run(context) {
- return await pollingHelper.poll(polling, context);
+ const config = authorConfig(context.propsValue);
+ return blueskyClient.withBluesky({
+ auth: context.auth.props,
+ action: "read the author's posts",
+ fn: async (agent) =>
+ blueskyPolling.poll({ store: context.store, storeKey: STORE_KEY, fetchPage: authorPage({ agent, config, did: await authorDid({ agent, config }) }) }),
+ });
},
-});
\ No newline at end of file
+});
+
+function authorConfig(props: {
+ authorSelection: string;
+ authorFromFollowing?: unknown;
+ authorHandle?: string;
+ includeReplies?: boolean;
+ includeReposts?: boolean;
+}): AuthorConfig {
+ const raw = props.authorSelection === 'following' ? props.authorFromFollowing : props.authorHandle;
+ if (typeof raw !== 'string' || raw.trim() === '') {
+ throw new Error(
+ props.authorSelection === 'following'
+ ? 'Select an author from your following list, or switch to "Enter handle manually".'
+ : 'Enter the author handle.',
+ );
+ }
+ return {
+ actor: blueskyRefs.parseActorInput(raw),
+ displayHandle: raw.replace('@', '').trim(),
+ includeReplies: props.includeReplies === true,
+ includeReposts: props.includeReposts === true,
+ };
+}
+
+async function authorDid({ agent, config }: { agent: AtpAgent; config: AuthorConfig }): Promise<string> {
+ return blueskyRefs.resolveActorDid({ agent, input: config.actor });
+}
+
+function authorPage({ agent, config, did }: { agent: AtpAgent; config: AuthorConfig; did: string }): PageFetcher<ReturnType<typeof authorItem>> {
+ return async ({ cursor }) => {
+ const response = await agent.getAuthorFeed({ actor: did, limit: 100, cursor, filter: 'posts_with_replies' });
+ const times = response.data.feed.map((entry) =>
+ blueskyPolling.timeOf(entry.reason && blueskyAtproto.isReasonRepost(entry.reason) ? entry.reason.indexedAt : entry.post.indexedAt),
+ );
+ const items = response.data.feed.flatMap((entry) => {
+ const repost = entry.reason && blueskyAtproto.isReasonRepost(entry.reason) ? entry.reason : undefined;
+ const isReply = blueskyMappers.recordReplyParentUri(entry.post.record) !== null;
+ const ownPost = !entry.reason && entry.post.author.did === did;
+ const ownRepost = repost !== undefined && repost.by.did === did;
+ if ((!ownPost && !ownRepost) || (ownPost && isReply && !config.includeReplies) || (ownRepost && !config.includeReposts)) {
+ return [];
+ }
+ return [
+ {
+ key: repost ? `${did}:${entry.post.uri}` : entry.post.uri,
+ time: blueskyPolling.timeOf(repost ? repost.indexedAt : entry.post.indexedAt) ?? 0,
+ data: authorItem({ entry, config, isRepost: ownRepost }),
+ },
+ ];
+ });
+ return { items, cursor: response.data.cursor, ...blueskyPolling.pageTimes(times) };
+ };
+}
+
+function authorItem({ entry, config, isRepost }: { entry: AppBskyFeedDefs.FeedViewPost; config: AuthorConfig; isRepost: boolean }) {
+ const replyTo = blueskyMappers.recordReplyParentUri(entry.post.record);
+ return {
+ ...blueskyMappers.postBase(entry.post),
+ postContext: {
+ authorHandle: config.displayHandle,
+ isReply: replyTo !== null,
+ isRepost,
+ replyTo,
+ ...blueskyMappers.mediaFlags(entry.post.embed),
+ },
+ };
+}
+
+type AuthorConfig = { actor: string; displayHandle: string; includeReplies: boolean; includeReposts: boolean };
diff --git a/packages/pieces/community/bluesky/src/lib/triggers/new-timeline-posts.ts b/packages/pieces/community/bluesky/src/lib/triggers/new-timeline-posts.ts
index db855852ffa..9395cc6484f 100644
--- a/packages/pieces/community/bluesky/src/lib/triggers/new-timeline-posts.ts
+++ b/packages/pieces/community/bluesky/src/lib/triggers/new-timeline-posts.ts
@@ -1,71 +1,13 @@
-import { createTrigger, TriggerStrategy, PiecePropValueSchema, AppConnectionValueForAuthProperty } from '@activepieces/pieces-framework';
-import { DedupeStrategy, Polling, pollingHelper } from '@activepieces/pieces-common';
+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
+import type { AppBskyFeedDefs, AtpAgent } from '@atproto/api';
+import { blueskyAtproto } from '../common/atproto';
import { blueskyAuth } from '../common/auth';
import { newTimelinePostsTriggerOutputSchema } from '../output-schemas';
-import { createBlueskyAgent } from '../common/client';
-import dayjs from 'dayjs';
+import { blueskyClient } from '../common/client';
+import { blueskyMappers } from '../common/mappers';
+import { blueskyPolling, PageFetcher } from '../common/polling';
-const polling: Polling<AppConnectionValueForAuthProperty<typeof blueskyAuth>, Record<string, never>> = {
- strategy: DedupeStrategy.TIMEBASED,
- items: async ({ auth, lastFetchEpochMS }) => {
- try {
- const agent = await createBlueskyAgent(auth.props);
-
- const response = await agent.getTimeline({
- limit: 50
- });
-
- if (!response.data?.feed || !Array.isArray(response.data.feed)) {
- return [];
- }
-
- const cutoffTime = lastFetchEpochMS || 0;
-
- return response.data.feed
- .filter((item: any) => {
- if (!item.post || !item.post.indexedAt) return false;
-
- const postTime = dayjs(item.post.indexedAt).valueOf();
- return postTime > cutoffTime;
- })
- .map((item: any) => ({
- epochMilliSeconds: dayjs(item.post.indexedAt).valueOf(),
- data: {
- uri: item.post.uri,
- cid: item.post.cid,
- author: item.post.author,
- record: item.post.record,
- indexedAt: item.post.indexedAt,
-
- replyCount: item.post.replyCount || 0,
- repostCount: item.post.repostCount || 0,
- likeCount: item.post.likeCount || 0,
- quoteCount: item.post.quoteCount || 0,
-
- labels: item.post.labels || [],
- viewer: item.post.viewer || {},
- embed: item.post.embed || null,
-
- reason: item.reason || null,
- reply: item.reply || null,
-
- feedContext: {
- isRepost: !!item.reason,
- repostBy: item.reason?.by || null,
- isReply: !!item.reply,
- replyToPost: item.reply?.parent || null,
- replyToRoot: item.reply?.root || null
- }
- }
- }))
- .sort((a: any, b: any) => b.epochMilliSeconds - a.epochMilliSeconds);
-
- } catch (error) {
- console.warn('Failed to fetch timeline posts:', error instanceof Error ? error.message : 'Unknown error');
- return [];
- }
- }
-};
+const STORE_KEY = 'bluesky_timeline_poll';
export const newTimelinePosts = createTrigger({
auth: blueskyAuth,
@@ -74,71 +16,89 @@ export const newTimelinePosts = createTrigger({
displayName: 'New Timeline Posts',
description: 'Triggers when new posts appear in your timeline',
aiMetadata: {
- description: 'Fires when a new post appears in the authenticated account\'s home timeline (posts and reposts from accounts it follows); each event represents one such timeline item.',
+ description:
+ 'Fires when a new post or repost appears in the authenticated account\'s home timeline (from accounts it follows); each event is one timeline item, and a repost fires when it is reposted even if the original post is older.',
},
props: {},
sampleData: {
uri: 'at://did:plc:example123/app.bsky.feed.post/example456',
cid: 'bafyreib2rxk3vcfbqij7y6kzgy4knknc7ff4t5jn2m5fbn6jdl7czfqyqe',
+ url: 'https://bsky.app/profile/author.bsky.social/post/example456',
author: {
did: 'did:plc:example123',
handle: 'author.bsky.social',
displayName: 'Example Author',
avatar: 'https://cdn.bsky.app/img/avatar/plain/did:plc:example123/example@jpeg',
- viewer: {
- muted: false,
- blockedBy: false,
- following: 'at://did:plc:user456/app.bsky.graph.follow/example789'
- }
- },
- record: {
- $type: 'app.bsky.feed.post',
- createdAt: '2024-01-01T12:00:00.000Z',
- text: 'This is a new post in your timeline!',
- langs: ['en']
+ viewer: { muted: false, blockedBy: false, following: 'at://did:plc:user456/app.bsky.graph.follow/example789' },
},
+ record: { $type: 'app.bsky.feed.post', createdAt: '2024-01-01T12:00:00.000Z', text: 'This is a new post in your timeline!', langs: ['en'] },
indexedAt: '2024-01-01T12:00:00.000Z',
-
replyCount: 3,
repostCount: 8,
likeCount: 15,
quoteCount: 2,
-
labels: [],
- viewer: {
- repost: null,
- like: null
- },
+ viewer: { repost: null, like: null },
embed: null,
-
reason: null,
reply: null,
- feedContext: {
- isRepost: false,
- repostBy: null,
- isReply: false,
- replyToPost: null,
- replyToRoot: null
- }
+ feedContext: { isRepost: false, repostBy: null, isReply: false, replyToPost: null, replyToRoot: null },
},
type: TriggerStrategy.POLLING,
outputSchema: newTimelinePostsTriggerOutputSchema,
-
async test(context) {
- return await pollingHelper.test(polling, context);
+ return blueskyClient.withBluesky({
+ auth: context.auth.props,
+ action: 'read the timeline',
+ fn: (agent) => blueskyPolling.sample({ fetchPage: timelinePage({ agent }) }),
+ });
},
-
async onEnable(context) {
- const { store, auth, propsValue } = context;
- await pollingHelper.onEnable(polling, { store, auth, propsValue });
+ await blueskyClient.withBluesky({
+ auth: context.auth.props,
+ action: 'read the timeline',
+ fn: (agent) =>
+ blueskyPolling.onEnable({ store: context.store, storeKey: STORE_KEY, fetchPage: timelinePage({ agent }), isRepublish: context.isRepublish }),
+ });
},
-
async onDisable(context) {
- const { store, auth, propsValue } = context;
- await pollingHelper.onDisable(polling, { store, auth, propsValue });
+ await blueskyPolling.onDisable({ store: context.store, storeKey: STORE_KEY });
},
-
async run(context) {
- return await pollingHelper.poll(polling, context);
+ return blueskyClient.withBluesky({
+ auth: context.auth.props,
+ action: 'read the timeline',
+ fn: (agent) => blueskyPolling.poll({ store: context.store, storeKey: STORE_KEY, fetchPage: timelinePage({ agent }) }),
+ });
},
-});
\ No newline at end of file
+});
+
+function timelinePage({ agent }: { agent: AtpAgent }): PageFetcher<ReturnType<typeof timelineItem>> {
+ return async ({ cursor }) => {
+ const response = await agent.getTimeline({ limit: 100, cursor });
+ const items = response.data.feed.map((entry) => {
+ const repost = entry.reason && blueskyAtproto.isReasonRepost(entry.reason) ? entry.reason : undefined;
+ return {
+ key: repost ? `${repost.by.did}:${entry.post.uri}` : entry.post.uri,
+ time: blueskyPolling.timeOf(repost ? repost.indexedAt : entry.post.indexedAt) ?? 0,
+ data: timelineItem(entry),
+ };
+ });
+ return { items, cursor: response.data.cursor, ...blueskyPolling.pageTimes(items.map((item) => item.time)) };
+ };
+}
+
+function timelineItem(entry: AppBskyFeedDefs.FeedViewPost) {
+ return {
+ ...blueskyMappers.postBase(entry.post),
+ reason: entry.reason ?? null,
+ reply: entry.reply ?? null,
+ feedContext: {
+ isRepost: Boolean(entry.reason),
+ repostBy: entry.reason && blueskyAtproto.isReasonRepost(entry.reason) ? entry.reason.by : null,
+ isReply: Boolean(entry.reply),
+ replyToPost: entry.reply?.parent ?? null,
+ replyToRoot: entry.reply?.root ?? null,
+ },
+ };
+}
diff --git a/packages/pieces/community/bluesky/test/actions.test.ts b/packages/pieces/community/bluesky/test/actions.test.ts
new file mode 100644
index 00000000000..93537c67f2f
--- /dev/null
+++ b/packages/pieces/community/bluesky/test/actions.test.ts
@@ -0,0 +1,430 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createPost } from '../src/lib/actions/create-post';
+import { deletePost } from '../src/lib/actions/delete-post';
+import { blueskyLikePost } from '../src/lib/actions/bluesky-like-post';
+import { unlikePost } from '../src/lib/actions/unlike-post';
+import { followUser } from '../src/lib/actions/follow-user';
+import { searchPosts } from '../src/lib/actions/search-posts';
+import { getTimeline } from '../src/lib/actions/get-timeline';
+import { findThread } from '../src/lib/actions/find-thread';
+import { updateProfile } from '../src/lib/actions/update-profile';
+import { removeUserFromList } from '../src/lib/actions/remove-user-from-list';
+import { deleteList } from '../src/lib/actions/delete-list';
+import { blueskyCreatePost } from '../src/lib/actions/bluesky-create-post';
+import { bluesky } from '../src/index';
+import { blueskyClient } from '../src/lib/common/client';
+import {
+ CID,
+ ME_DID,
+ ME_HANDLE,
+ OTHER_DID,
+ OTHER_HANDLE,
+ installFakeBluesky,
+ json,
+ postView,
+ profileView,
+ runAction,
+ testAuth,
+ xrpcError,
+} from './helpers';
+
+const AVATAR_CID = 'bafkreicfupviocmcmzznacnwlma5ddzbsanhu2gfxa72r6cu3lysbry5cm';
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function createRecordRoute() {
+ let n = 0;
+ return () => {
+ n += 1;
+ return json({ uri: `at://${ME_DID}/app.bsky.feed.post/3new${n}`, cid: CID });
+ };
+}
+
+function recordOf(body: unknown): Record<string, unknown> {
+ if (typeof body === 'object' && body !== null && 'record' in body && typeof body.record === 'object' && body.record !== null) {
+ return Object.fromEntries(Object.entries(body.record));
+ }
+ return {};
+}
+
+describe('Create Post', () => {
+ it('posts 200 Japanese characters with real self-labels and hashtags as tags', async () => {
+ const fake = installFakeBluesky({ routes: { 'com.atproto.repo.createRecord': createRecordRoute() } });
+ const text = 'あ'.repeat(200);
+ const result = await runAction({
+ action: createPost,
+ propsValue: { text, language: 'ja', additionalHashtags: 'tech,#bluesky', contentWarnings: ['adult', 'spam'], audience: 'followers' },
+ });
+ const [call] = fake.callsTo('com.atproto.repo.createRecord');
+ const record = recordOf(call.body);
+ expect(record['text']).toBe(`${text} #tech #bluesky`);
+ expect(record['tags']).toEqual(['tech', 'bluesky']);
+ expect(record['langs']).toEqual(['ja']);
+ expect(record['labels']).toEqual({ $type: 'com.atproto.label.defs#selfLabels', values: [{ val: 'porn' }] });
+ expect(result).toMatchObject({ success: true, totalPosts: 1, failedThreadPosts: [], url: `https://bsky.app/profile/${ME_HANDLE}/post/3new1` });
+ });
+
+ it('checks every thread text before posting anything', async () => {
+ const fake = installFakeBluesky({ routes: { 'com.atproto.repo.createRecord': createRecordRoute() } });
+ await expect(
+ runAction({ action: createPost, propsValue: { text: 'AP-TEST', threadContent: ['ok', 'x'.repeat(301)] } }),
+ ).rejects.toThrow(/Thread post 2 is 301 characters/);
+ expect(fake.calls).toHaveLength(0);
+ });
+
+ it('reports a thread post Bluesky rejected instead of hiding it', async () => {
+ let n = 0;
+ const fake = installFakeBluesky({
+ routes: {
+ 'com.atproto.repo.createRecord': () => {
+ n += 1;
+ return n === 2
+ ? xrpcError({ status: 400, error: 'InvalidRequest', message: 'bad record' })
+ : json({ uri: `at://${ME_DID}/app.bsky.feed.post/3new${n}`, cid: CID });
+ },
+ },
+ });
+ const result = await runAction({ action: createPost, propsValue: { text: 'AP-TEST main', threadContent: ['one', 'two'] } });
+ expect(result).toMatchObject({ totalPosts: 2, failedThreadPosts: [{ index: 1 }] });
+ const third = recordOf(fake.callsTo('com.atproto.repo.createRecord')[2].body);
+ expect(third['reply']).toEqual({ root: { uri: `at://${ME_DID}/app.bsky.feed.post/3new1`, cid: CID }, parent: { uri: `at://${ME_DID}/app.bsky.feed.post/3new1`, cid: CID } });
+ });
+
+ it('embeds a quoted post when Quote Post URL is set', async () => {
+ const fake = installFakeBluesky({
+ routes: {
+ 'app.bsky.feed.getPosts': () => json({ posts: [postView({ rkey: '3quoted', did: OTHER_DID })] }),
+ 'com.atproto.repo.createRecord': createRecordRoute(),
+ },
+ });
+ await runAction({ action: createPost, propsValue: { text: 'AP-TEST quote', postType: 'quote', quotePostUrl: `at://${OTHER_DID}/app.bsky.feed.post/3quoted` } });
+ const record = recordOf(fake.callsTo('com.atproto.repo.createRecord')[0].body);
+ expect(record['embed']).toEqual({ $type: 'app.bsky.embed.record', record: { uri: `at://${OTHER_DID}/app.bsky.feed.post/3quoted`, cid: CID } });
+ });
+});
+
+describe('Create Post (AI)', () => {
+ it('rejects more than 8 tags before signing in', async () => {
+ const fake = installFakeBluesky({ routes: {} });
+ await expect(
+ runAction({ action: blueskyCreatePost, propsValue: { text: 'AP-TEST', tags: ['1', '2', '3', '4', '5', '6', '7', '8', '9'] } }),
+ ).rejects.toThrow(/at most 8 tags/);
+ expect(fake.calls).toHaveLength(0);
+ });
+
+ it('builds a reply with the parent thread root', async () => {
+ const parent = postView({
+ rkey: '3parent',
+ extra: { record: { $type: 'app.bsky.feed.post', text: 'p', createdAt: '2026-10-05T10:00:00.000Z', reply: { root: { uri: `at://${OTHER_DID}/app.bsky.feed.post/3root`, cid: CID }, parent: { uri: `at://${OTHER_DID}/app.bsky.feed.post/3root`, cid: CID } } } },
+ });
+ const fake = installFakeBluesky({
+ routes: { 'app.bsky.feed.getPosts': () => json({ posts: [parent] }), 'com.atproto.repo.createRecord': createRecordRoute() },
+ });
+ const result = await runAction({ action: blueskyCreatePost, propsValue: { text: 'AP-TEST reply', replyTo: `https://bsky.app/profile/${OTHER_DID}/post/3parent`, selfLabels: ['graphic-media'] } });
+ const record = recordOf(fake.callsTo('com.atproto.repo.createRecord')[0].body);
+ expect(record['reply']).toEqual({
+ root: { uri: `at://${OTHER_DID}/app.bsky.feed.post/3root`, cid: CID },
+ parent: { uri: `at://${OTHER_DID}/app.bsky.feed.post/3parent`, cid: CID },
+ });
+ expect(result).toMatchObject({ isReply: true, uri: `at://${ME_DID}/app.bsky.feed.post/3new1` });
+ });
+});
+
+describe('Delete Post', () => {
+ it('refuses a post of another account without deleting anything', async () => {
+ const fake = installFakeBluesky({ routes: {} });
+ await expect(runAction({ action: deletePost, propsValue: { post: `at://${OTHER_DID}/app.bsky.feed.post/3x` } })).rejects.toThrow(/another account/);
+ expect(fake.callsTo('com.atproto.repo.deleteRecord')).toHaveLength(0);
+ });
+
+ it('converges when the post is already gone', async () => {
+ const fake = installFakeBluesky({
+ routes: {
+ 'com.atproto.repo.getRecord': () => xrpcError({ status: 400, error: 'RecordNotFound', message: 'Could not locate record' }),
+ 'com.atproto.repo.deleteRecord': () => json({}),
+ },
+ });
+ const result = await runAction({ action: deletePost, propsValue: { post: `https://bsky.app/profile/${ME_DID}/post/3gone` } });
+ expect(result).toMatchObject({ deleted: true, existed: false, uri: `at://${ME_DID}/app.bsky.feed.post/3gone` });
+ expect(fake.callsTo('com.atproto.repo.deleteRecord')[0].body).toEqual({ repo: ME_DID, collection: 'app.bsky.feed.post', rkey: '3gone' });
+ });
+
+ it('falls back to the profile lookup when the PDS cannot resolve the handle', async () => {
+ const fake = installFakeBluesky({
+ routes: {
+ 'com.atproto.identity.resolveHandle': () => xrpcError({ status: 400, error: 'InvalidRequest', message: 'Unable to resolve handle' }),
+ 'app.bsky.actor.getProfile': () => json(profileView({ did: ME_DID, handle: ME_HANDLE })),
+ 'com.atproto.repo.getRecord': () => json({ uri: `at://${ME_DID}/app.bsky.feed.post/3mine`, cid: CID, value: {} }),
+ 'com.atproto.repo.deleteRecord': () => json({}),
+ },
+ });
+ const result = await runAction({ action: deletePost, propsValue: { post: `https://bsky.app/profile/${ME_HANDLE}/post/3mine` } });
+ expect(result).toMatchObject({ deleted: true, existed: true, uri: `at://${ME_DID}/app.bsky.feed.post/3mine` });
+ expect(fake.callsTo('app.bsky.actor.getProfile')[0].query.get('actor')).toBe(ME_HANDLE);
+ });
+
+ it('reports the resolve error when the profile lookup also fails', async () => {
+ installFakeBluesky({
+ routes: {
+ 'com.atproto.identity.resolveHandle': () => xrpcError({ status: 400, error: 'InvalidRequest', message: 'Unable to resolve handle' }),
+ 'app.bsky.actor.getProfile': () => xrpcError({ status: 400, error: 'InvalidRequest', message: 'Profile not found' }),
+ },
+ });
+ await expect(runAction({ action: deletePost, propsValue: { post: `https://bsky.app/profile/${ME_HANDLE}/post/3mine` } })).rejects.toThrow(
+ /Unable to resolve handle/,
+ );
+ });
+});
+
+describe('likes and follows are check-first', () => {
+ it('Like Post (AI) returns the existing like without creating another', async () => {
+ const likeUri = `at://${ME_DID}/app.bsky.feed.like/3like`;
+ const fake = installFakeBluesky({ routes: { 'app.bsky.feed.getPosts': () => json({ posts: [postView({ rkey: '3p', viewer: { like: likeUri } })] }) } });
+ const result = await runAction({ action: blueskyLikePost, propsValue: { post: `at://${OTHER_DID}/app.bsky.feed.post/3p` } });
+ expect(result).toMatchObject({ likeUri, alreadyLiked: true });
+ expect(fake.callsTo('com.atproto.repo.createRecord')).toHaveLength(0);
+ });
+
+ it('Unlike Post changes nothing when the post is not liked', async () => {
+ const fake = installFakeBluesky({ routes: { 'app.bsky.feed.getPosts': () => json({ posts: [postView({ rkey: '3p' })] }) } });
+ const result = await runAction({ action: unlikePost, propsValue: { post: `at://${OTHER_DID}/app.bsky.feed.post/3p` } });
+ expect(result).toEqual({ removed: false, postUri: `at://${OTHER_DID}/app.bsky.feed.post/3p`, likeUri: null });
+ expect(fake.callsTo('com.atproto.repo.deleteRecord')).toHaveLength(0);
+ });
+
+ it('Follow User follows once and reports an existing follow', async () => {
+ const followUri = `at://${ME_DID}/app.bsky.graph.follow/3f`;
+ const fake = installFakeBluesky({
+ routes: {
+ 'app.bsky.actor.getProfile': () => json(profileView()),
+ 'com.atproto.repo.createRecord': () => json({ uri: followUri, cid: CID }),
+ },
+ });
+ const result = await runAction({ action: followUser, propsValue: { actor: '@other.bsky.social' } });
+ expect(result).toEqual({ followUri, did: OTHER_DID, handle: OTHER_HANDLE, alreadyFollowing: false });
+ expect(fake.callsTo('app.bsky.actor.getProfile')[0].query.get('actor')).toBe(OTHER_HANDLE);
+ expect(fake.callsTo('com.atproto.repo.createRecord')[0].body).toMatchObject({ collection: 'app.bsky.graph.follow', record: { subject: OTHER_DID } });
+
+ const again = installFakeBluesky({ routes: { 'app.bsky.actor.getProfile': () => json(profileView({ viewer: { following: followUri } })) } });
+ expect(await runAction({ action: followUser, propsValue: { actor: OTHER_HANDLE } })).toMatchObject({ alreadyFollowing: true, followUri });
+ expect(again.callsTo('com.atproto.repo.createRecord')).toHaveLength(0);
+ });
+});
+
+describe('reads', () => {
+ it('Search Posts sends every filter and returns a cursor page', async () => {
+ const fake = installFakeBluesky({ routes: { 'app.bsky.feed.searchPosts': () => json({ posts: [postView({ rkey: '3s' })], cursor: 'next' }) } });
+ const result = await runAction({
+ action: searchPosts,
+ propsValue: { query: 'activepieces', sort: 'top', author: '@other.bsky.social', tags: ['#ai'], since: '2026-10-01T00:00:00Z', limit: 10 },
+ });
+ const query = fake.callsTo('app.bsky.feed.searchPosts')[0].query;
+ expect(query.get('q')).toBe('activepieces');
+ expect(query.get('sort')).toBe('top');
+ expect(query.get('author')).toBe(OTHER_HANDLE);
+ expect(query.getAll('tag')).toEqual(['ai']);
+ expect(query.get('since')).toBe('2026-10-01T00:00:00.000Z');
+ expect(query.get('limit')).toBe('10');
+ expect(result).toMatchObject({ cursor: 'next', hasMore: true, items: [{ text: 'hello', url: `https://bsky.app/profile/${OTHER_HANDLE}/post/3s` }] });
+ });
+
+ it('rejects an out-of-range limit before signing in', async () => {
+ const fake = installFakeBluesky({ routes: {} });
+ await expect(runAction({ action: getTimeline, propsValue: { limit: 500 } })).rejects.toThrow(/between 1 and 100/);
+ expect(fake.calls).toHaveLength(0);
+ });
+
+ it('turns a rate limit into a clear error without a body field', async () => {
+ installFakeBluesky({
+ routes: { 'app.bsky.feed.getTimeline': () => xrpcError({ status: 429, error: 'RateLimitExceeded', message: 'Rate Limit Exceeded', headers: { 'ratelimit-reset': '1790000000' } }) },
+ });
+ const error = await runAction({ action: getTimeline, propsValue: {} }).catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(Error);
+ expect(String(error)).toMatch(/rate limit reached while trying to get the timeline/);
+ expect(error).not.toHaveProperty('body');
+ expect(error).toHaveProperty('status', 429);
+ });
+
+ it('Find Thread counts every post in the thread', async () => {
+ const thread = {
+ $type: 'app.bsky.feed.defs#threadViewPost',
+ post: postView({ rkey: '3root' }),
+ parent: { $type: 'app.bsky.feed.defs#threadViewPost', post: postView({ rkey: '3up' }) },
+ replies: [
+ { $type: 'app.bsky.feed.defs#threadViewPost', post: postView({ rkey: '3r1' }), replies: [{ $type: 'app.bsky.feed.defs#threadViewPost', post: postView({ rkey: '3r2' }) }] },
+ { $type: 'app.bsky.feed.defs#notFoundPost', uri: `at://${OTHER_DID}/app.bsky.feed.post/3gone`, notFound: true },
+ ],
+ };
+ const fake = installFakeBluesky({ routes: { 'app.bsky.feed.getPostThread': () => json({ thread }) } });
+ const result = await runAction({ action: findThread, propsValue: { postUrl: `at://${OTHER_DID}/app.bsky.feed.post/3root` } });
+ expect(result).toMatchObject({ statistics: { totalPosts: 4, parentPosts: 1, replyPosts: 2, notFoundPosts: 1, blockedPosts: 0 }, parameters: { depth: 10, parentHeight: 3 } });
+ expect(fake.callsTo('app.bsky.feed.getPostThread')[0].query.get('depth')).toBe('10');
+ });
+});
+
+describe('writes with three states', () => {
+ it('Update Profile keeps every untouched field (even an avatar the lexicon would reject), sets given ones and clears on request', async () => {
+ const fake = installFakeBluesky({
+ routes: {
+ 'com.atproto.repo.getRecord': () =>
+ json({
+ uri: `at://${ME_DID}/app.bsky.actor.profile/self`,
+ cid: CID,
+ value: {
+ $type: 'app.bsky.actor.profile',
+ displayName: 'Old',
+ description: 'Old bio',
+ avatar: { $type: 'blob', ref: { $link: AVATAR_CID }, mimeType: 'image/webp', size: 2_000_000 },
+ pinnedPost: { uri: `at://${ME_DID}/app.bsky.feed.post/3pin`, cid: CID },
+ },
+ }),
+ 'com.atproto.repo.putRecord': () => json({ uri: `at://${ME_DID}/app.bsky.actor.profile/self`, cid: CID }),
+ },
+ });
+ const result = await runAction({ action: updateProfile, propsValue: { displayName: 'New', clearDescription: true } });
+ const record = recordOf(fake.callsTo('com.atproto.repo.putRecord')[0].body);
+ expect(record['displayName']).toBe('New');
+ expect(record).not.toHaveProperty('description');
+ expect(record['avatar']).toEqual({ $type: 'blob', ref: { $link: AVATAR_CID }, mimeType: 'image/webp', size: 2_000_000 });
+ expect(record['pinnedPost']).toEqual({ uri: `at://${ME_DID}/app.bsky.feed.post/3pin`, cid: CID });
+ expect(fake.callsTo('com.atproto.repo.putRecord')[0].body).toMatchObject({ swapRecord: CID, rkey: 'self' });
+ expect(result).toMatchObject({ displayName: 'New', description: '', avatarUpdated: false });
+ });
+
+ it('Update Profile refuses an empty request', async () => {
+ installFakeBluesky({ routes: {} });
+ await expect(runAction({ action: updateProfile, propsValue: {} })).rejects.toThrow(/Nothing to update/);
+ });
+
+ it('Remove User from List deletes every membership of that account only', async () => {
+ const listUri = `at://${ME_DID}/app.bsky.graph.list/3lst`;
+ const fake = installFakeBluesky({
+ routes: {
+ 'app.bsky.graph.getList': () =>
+ json({
+ list: { uri: listUri, cid: CID, name: 'AP-TEST', purpose: 'app.bsky.graph.defs#curatelist', creator: profileView({ did: ME_DID, handle: ME_HANDLE }), indexedAt: '2026-10-05T10:00:00.000Z' },
+ items: [
+ { uri: `at://${ME_DID}/app.bsky.graph.listitem/3i1`, subject: profileView() },
+ { uri: `at://${ME_DID}/app.bsky.graph.listitem/3i2`, subject: profileView({ did: 'did:plc:cccccccccccccccccccccccc', handle: 'third.bsky.social' }) },
+ { uri: `at://${ME_DID}/app.bsky.graph.listitem/3i3`, subject: profileView() },
+ ],
+ }),
+ 'com.atproto.repo.deleteRecord': () => json({}),
+ },
+ });
+ const result = await runAction({ action: removeUserFromList, propsValue: { list: listUri, actor: OTHER_DID } });
+ expect(result).toEqual({ removed: 2, listUri, did: OTHER_DID });
+ expect(fake.callsTo('com.atproto.repo.deleteRecord').map((c) => c.body)).toEqual([
+ { repo: ME_DID, collection: 'app.bsky.graph.listitem', rkey: '3i1' },
+ { repo: ME_DID, collection: 'app.bsky.graph.listitem', rkey: '3i3' },
+ ]);
+ });
+});
+
+describe('Delete List', () => {
+ const listUri = `at://${ME_DID}/app.bsky.graph.list/3lst`;
+ const otherListUri = `at://${ME_DID}/app.bsky.graph.list/3other`;
+ const listItems = [
+ ...Array.from({ length: 120 }, (_, index) => ({ rkey: `3m${index}`, list: listUri })),
+ ...Array.from({ length: 30 }, (_, index) => ({ rkey: `3o${index}`, list: otherListUri })),
+ ].map(({ rkey, list }) => ({
+ uri: `at://${ME_DID}/app.bsky.graph.listitem/${rkey}`,
+ cid: CID,
+ value: { $type: 'app.bsky.graph.listitem', subject: OTHER_DID, list, createdAt: '2026-10-05T10:00:00.000Z' },
+ }));
+ const listRecordsRoute = ({ records }: { records: typeof listItems }) => (call: { query: URLSearchParams }) => {
+ const offset = Number(call.query.get('cursor') ?? '0');
+ const page = records.slice(offset, offset + 100);
+ return json({ records: page, ...(offset + 100 < records.length ? { cursor: String(offset + 100) } : {}) });
+ };
+ const deletedRkeys = (body: unknown): string[] =>
+ typeof body === 'object' && body !== null && 'writes' in body && Array.isArray(body.writes)
+ ? body.writes.flatMap((write: unknown) => (typeof write === 'object' && write !== null && 'rkey' in write && typeof write.rkey === 'string' ? [write.rkey] : []))
+ : [];
+
+ it('removes every membership of the list from the repository, then deletes the list', async () => {
+ const fake = installFakeBluesky({
+ routes: {
+ 'com.atproto.repo.getRecord': () => json({ uri: listUri, cid: CID, value: {} }),
+ 'com.atproto.repo.listRecords': listRecordsRoute({ records: listItems }),
+ 'com.atproto.repo.applyWrites': () => json({}),
+ 'com.atproto.repo.deleteRecord': () => json({}),
+ },
+ });
+ const result = await runAction({ action: deleteList, propsValue: { list: listUri } });
+ expect(result).toEqual({ deleted: true, existed: true, uri: listUri, membersRemoved: 120, membersFailed: 0, membersComplete: true });
+ expect(fake.callsTo('com.atproto.repo.listRecords')).toHaveLength(2);
+ expect(fake.callsTo('com.atproto.repo.listRecords')[0].query.get('collection')).toBe('app.bsky.graph.listitem');
+ const removed = fake.callsTo('com.atproto.repo.applyWrites').flatMap((call) => deletedRkeys(call.body));
+ expect(removed).toHaveLength(120);
+ expect(removed.every((rkey) => rkey.startsWith('3m'))).toBe(true);
+ const order = fake.calls.map((call) => call.nsid).filter((nsid) => nsid === 'com.atproto.repo.applyWrites' || nsid === 'com.atproto.repo.deleteRecord');
+ expect(order).toEqual(['com.atproto.repo.applyWrites', 'com.atproto.repo.applyWrites', 'com.atproto.repo.deleteRecord']);
+ expect(fake.callsTo('com.atproto.repo.deleteRecord')[0].body).toEqual({ repo: ME_DID, collection: 'app.bsky.graph.list', rkey: '3lst' });
+ });
+
+ it('stops on a failed batch and keeps the list so a retry can finish', async () => {
+ let batch = 0;
+ const fake = installFakeBluesky({
+ routes: {
+ 'com.atproto.repo.getRecord': () => json({ uri: listUri, cid: CID, value: {} }),
+ 'com.atproto.repo.listRecords': listRecordsRoute({ records: listItems }),
+ 'com.atproto.repo.applyWrites': () => {
+ batch += 1;
+ return batch === 2 ? xrpcError({ status: 500, error: 'InternalServerError', message: 'boom' }) : json({});
+ },
+ 'com.atproto.repo.deleteRecord': () => json({}),
+ },
+ });
+ await expect(runAction({ action: deleteList, propsValue: { list: listUri } })).rejects.toThrow(
+ /Removed 100 of 120 list memberships, then Bluesky refused the next batch\. The list was not deleted; run the action again to finish\./,
+ );
+ expect(fake.callsTo('com.atproto.repo.deleteRecord')).toHaveLength(0);
+ });
+
+ it('cleans up leftover memberships when the list is already gone', async () => {
+ const leftovers = listItems.slice(100);
+ const fake = installFakeBluesky({
+ routes: {
+ 'com.atproto.repo.getRecord': () => xrpcError({ status: 400, error: 'RecordNotFound', message: 'Could not locate record' }),
+ 'com.atproto.repo.listRecords': listRecordsRoute({ records: leftovers }),
+ 'com.atproto.repo.applyWrites': () => json({}),
+ 'com.atproto.repo.deleteRecord': () => json({}),
+ },
+ });
+ const result = await runAction({ action: deleteList, propsValue: { list: listUri } });
+ expect(result).toEqual({ deleted: true, existed: false, uri: listUri, membersRemoved: 20, membersFailed: 0, membersComplete: true });
+ expect(fake.callsTo('com.atproto.repo.applyWrites').flatMap((call) => deletedRkeys(call.body))).toHaveLength(20);
+ expect(fake.callsTo('com.atproto.repo.deleteRecord')).toHaveLength(0);
+ });
+
+ it('refuses a list of another account before touching anything', async () => {
+ const fake = installFakeBluesky({ routes: {} });
+ await expect(runAction({ action: deleteList, propsValue: { list: `at://${OTHER_DID}/app.bsky.graph.list/3lst` } })).rejects.toThrow(/belongs to another account/);
+ expect(fake.callsTo('com.atproto.repo.listRecords')).toHaveLength(0);
+ });
+});
+
+describe('session handling', () => {
+ it('signs in once per process and again when the password changes', async () => {
+ const fake = installFakeBluesky({ routes: { 'app.bsky.feed.getTimeline': () => json({ feed: [] }) } });
+ await runAction({ action: getTimeline, propsValue: {} });
+ await runAction({ action: getTimeline, propsValue: {} });
+ expect(fake.callsTo('com.atproto.server.createSession')).toHaveLength(1);
+ await blueskyClient.createAgent(testAuth({ password: 'rotated-pass' }).props);
+ expect(fake.callsTo('com.atproto.server.createSession')).toHaveLength(2);
+ });
+
+ it('Custom API Call refuses a full URL on another host', async () => {
+ installFakeBluesky({ routes: {} });
+ const action = bluesky.getAction('custom_api_call');
+ if (!action) {
+ throw new Error('custom_api_call is missing');
+ }
+ await expect(
+ runAction({ action, propsValue: { url: { url: 'https://bsky.social.evil.io/xrpc/app.bsky.actor.getProfile' }, method: 'GET', headers: {}, queryParams: {} } }),
+ ).rejects.toThrow(/PDS host/);
+ });
+});
diff --git a/packages/pieces/community/bluesky/test/atproto.test.ts b/packages/pieces/community/bluesky/test/atproto.test.ts
new file mode 100644
index 00000000000..45aa0db17d5
--- /dev/null
+++ b/packages/pieces/community/bluesky/test/atproto.test.ts
@@ -0,0 +1,45 @@
+import { AppBskyEmbedImages, AppBskyFeedDefs, RichText } from '@atproto/api';
+import { describe, expect, it } from 'vitest';
+import { blueskyAtproto } from '../src/lib/common/atproto';
+
+describe('lazy atproto helpers', () => {
+ it('counts graphemes exactly like the SDK RichText', () => {
+ const samples = ['hello', '日本語のテキスト', '👍'.repeat(5), '👨‍👩‍👧‍👦 family', '🇯🇵🇺🇸 flags', 'é combining', '', 'mixed 😀 text with 🏳️‍🌈 and 각'];
+ for (const text of samples) {
+ expect(blueskyAtproto.graphemeLength(text), text).toBe(new RichText({ text }).graphemeLength);
+ }
+ });
+
+ it('matches the SDK type guards', () => {
+ const values: unknown[] = [
+ { $type: 'app.bsky.feed.defs#reasonRepost', by: {}, indexedAt: '' },
+ { $type: 'app.bsky.feed.defs#reasonPin' },
+ { $type: 'app.bsky.feed.defs#threadViewPost', post: {} },
+ { $type: 'app.bsky.feed.defs#notFoundPost', uri: '', notFound: true },
+ { $type: 'app.bsky.feed.defs#blockedPost', uri: '', blocked: true },
+ { $type: 'app.bsky.embed.images#view', images: [] },
+ { $type: 'app.bsky.embed.video#view' },
+ { $type: 'app.bsky.embed.external#view' },
+ { $type: 'app.bsky.embed.recordWithMedia#view' },
+ { $type: 'something.else' },
+ {},
+ null,
+ 'text',
+ ];
+ for (const value of values) {
+ expect(blueskyAtproto.isReasonRepost(value)).toBe(AppBskyFeedDefs.isReasonRepost(value));
+ expect(blueskyAtproto.isReasonPin(value)).toBe(AppBskyFeedDefs.isReasonPin(value));
+ expect(blueskyAtproto.isThreadViewPost(value)).toBe(AppBskyFeedDefs.isThreadViewPost(value));
+ expect(blueskyAtproto.isNotFoundPost(value)).toBe(AppBskyFeedDefs.isNotFoundPost(value));
+ expect(blueskyAtproto.isBlockedPost(value)).toBe(AppBskyFeedDefs.isBlockedPost(value));
+ expect(blueskyAtproto.isImagesView(value)).toBe(AppBskyEmbedImages.isView(value));
+ }
+ });
+
+ it('loads the SDK on first use and reuses it', async () => {
+ const first = await blueskyAtproto.load();
+ const second = await blueskyAtproto.load();
+ expect(first).toBe(second);
+ expect(typeof first.AtpAgent).toBe('function');
+ });
+});
diff --git a/packages/pieces/community/bluesky/test/compose-download.test.ts b/packages/pieces/community/bluesky/test/compose-download.test.ts
new file mode 100644
index 00000000000..94df01aba5c
--- /dev/null
+++ b/packages/pieces/community/bluesky/test/compose-download.test.ts
@@ -0,0 +1,188 @@
+import { createServer, IncomingMessage, Server, ServerResponse } from 'node:http';
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
+import { blueskyCompose } from '../src/lib/common/compose';
+import { blueskyDownload } from '../src/lib/common/download';
+
+const realIsBlocked = blueskyDownload.isBlockedAddress;
+const requests: { path: string; accept: string | undefined }[] = [];
+let routes: Record<string, (res: ServerResponse) => void> = {};
+let server: Server;
+let base = '';
+
+function allowLoopbackLiteral(): void {
+ vi.spyOn(blueskyDownload, 'isBlockedAddress').mockImplementation((address) => address !== '127.0.0.1' && realIsBlocked(address));
+}
+
+function endless({ res, status, headers = {} }: { res: ServerResponse; status: number; headers?: Record<string, string> }): void {
+ res.writeHead(status, headers);
+ const timer = setInterval(() => {
+ res.write(Buffer.alloc(64 * 1024));
+ }, 5);
+ res.on('close', () => clearInterval(timer));
+}
+
+beforeAll(async () => {
+ server = createServer((req: IncomingMessage, res: ServerResponse) => {
+ const path = req.url ?? '/';
+ requests.push({ path, accept: req.headers['accept'] });
+ const route = routes[path];
+ if (!route) {
+ res.writeHead(404).end('nope');
+ return;
+ }
+ route(res);
+ });
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const address = server.address();
+ base = typeof address === 'object' && address !== null ? `http://127.0.0.1:${address.port}` : '';
+});
+
+afterAll(async () => {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ routes = {};
+ requests.length = 0;
+});
+
+describe('fetchBinary', () => {
+ it('downloads the body and returns bytes and content type', async () => {
+ allowLoopbackLiteral();
+ routes = { '/a.png': (res) => res.writeHead(200, { 'content-type': 'image/png; charset=binary' }).end(Buffer.from([1, 2, 3])) };
+ const result = await blueskyCompose.fetchBinary({ url: `${base}/a.png`, maxBytes: 10, label: 'Image 1' });
+ expect(Array.from(result.data)).toEqual([1, 2, 3]);
+ expect(result.contentType).toBe('image/png');
+ });
+
+ it('asks for any content type by default and lets link pages ask for HTML', async () => {
+ allowLoopbackLiteral();
+ routes = { '/a.png': (res) => res.writeHead(200).end('x') };
+ await blueskyCompose.fetchBinary({ url: `${base}/a.png`, maxBytes: 10, label: 'Image 1' });
+ await blueskyCompose.fetchBinary({ url: `${base}/a.png`, maxBytes: 10, accept: 'text/html', label: 'Link page' });
+ expect(requests.map((request) => request.accept)).toEqual(['*/*', 'text/html']);
+ });
+
+ it('rejects a declared content-length above the limit before reading the body', async () => {
+ allowLoopbackLiteral();
+ routes = { '/big': (res) => res.writeHead(200, { 'content-length': '2000000' }).end(Buffer.alloc(2_000_000)) };
+ await expect(blueskyCompose.fetchBinary({ url: `${base}/big`, maxBytes: 1_000_000, label: 'Image 1' })).rejects.toThrow(
+ `Image 1 at ${base}/big is 2.0 MB; the limit is 1.0 MB.`,
+ );
+ });
+
+ it('stops reading once a streamed body passes the limit', async () => {
+ allowLoopbackLiteral();
+ routes = { '/stream': (res) => endless({ res, status: 200 }) };
+ await expect(blueskyCompose.fetchBinary({ url: `${base}/stream`, maxBytes: 1000, label: 'Image 1' })).rejects.toThrow(
+ `Image 1 at ${base}/stream is larger than the 1 KB limit.`,
+ );
+ });
+
+ it('times out while the body is still downloading', async () => {
+ allowLoopbackLiteral();
+ routes = {
+ '/slow': (res) => {
+ res.writeHead(200);
+ res.write('a');
+ },
+ };
+ await expect(blueskyCompose.fetchBinary({ url: `${base}/slow`, maxBytes: 1000, timeoutMs: 100, label: 'Video' })).rejects.toThrow(
+ `Could not download Video from ${base}/slow: timed out after 0 s`,
+ );
+ });
+
+ it('times out when the server never sends headers', async () => {
+ allowLoopbackLiteral();
+ routes = { '/hang': () => undefined };
+ await expect(blueskyCompose.fetchBinary({ url: `${base}/hang`, maxBytes: 1000, timeoutMs: 100, label: 'Video' })).rejects.toThrow(
+ `Could not download Video from ${base}/hang: timed out after 0 s`,
+ );
+ });
+
+ it('reports the HTTP status of an error without reading its endless body', async () => {
+ allowLoopbackLiteral();
+ routes = { '/error': (res) => endless({ res, status: 500, headers: { 'content-type': 'text/html' } }) };
+ const started = Date.now();
+ await expect(blueskyCompose.fetchBinary({ url: `${base}/error`, maxBytes: 1000, timeoutMs: 5000, label: 'Link page' })).rejects.toThrow(
+ `Could not download Link page from ${base}/error: HTTP 500.`,
+ );
+ expect(Date.now() - started).toBeLessThan(2000);
+ });
+
+ it('follows a redirect to a public address and checks each hop', async () => {
+ allowLoopbackLiteral();
+ routes = {
+ '/start': (res) => res.writeHead(302, { location: '/final' }).end(),
+ '/final': (res) => res.writeHead(200, { 'content-type': 'image/gif' }).end('GIF8'),
+ };
+ const result = await blueskyCompose.fetchBinary({ url: `${base}/start`, maxBytes: 100, label: 'Image 1' });
+ expect(result.contentType).toBe('image/gif');
+ expect(requests.map((request) => request.path)).toEqual(['/start', '/final']);
+ });
+
+ it('refuses a redirect to the cloud metadata address without contacting it', async () => {
+ allowLoopbackLiteral();
+ routes = { '/start': (res) => res.writeHead(302, { location: 'http://169.254.169.254/latest/meta-data/' }).end() };
+ await expect(blueskyCompose.fetchBinary({ url: `${base}/start`, maxBytes: 100, label: 'Image 1' })).rejects.toThrow(
+ /169\.254\.169\.254 is a private, loopback or internal address/,
+ );
+ });
+
+ it('refuses a redirect to a host name that resolves to a private address', async () => {
+ vi.spyOn(blueskyDownload, 'isBlockedAddress').mockImplementationOnce(() => false);
+ const port = new URL(base).port;
+ routes = { '/start': (res) => res.writeHead(307, { location: `http://localhost:${port}/final` }).end(), '/final': (res) => res.writeHead(200).end('x') };
+ await expect(blueskyCompose.fetchBinary({ url: `${base}/start`, maxBytes: 100, label: 'Image 1' })).rejects.toThrow(
+ /localhost resolves to .*private, loopback or internal address/,
+ );
+ expect(requests.map((request) => request.path)).toEqual(['/start']);
+ });
+
+ it('stops after five redirects', async () => {
+ allowLoopbackLiteral();
+ routes = { '/loop': (res) => res.writeHead(301, { location: '/loop' }).end() };
+ await expect(blueskyCompose.fetchBinary({ url: `${base}/loop`, maxBytes: 100, label: 'Image 1' })).rejects.toThrow(
+ `Could not download Image 1 from ${base}/loop: more than 5 redirects.`,
+ );
+ expect(requests).toHaveLength(6);
+ });
+
+ it('refuses loopback, private and metadata URLs without sending a request', async () => {
+ for (const url of ['http://127.0.0.1/a.png', 'http://10.1.2.3/a.png', 'http://169.254.169.254/', 'http://[::1]/a.png', 'http://[::ffff:127.0.0.1]/a.png', 'http://[fd00::1]/']) {
+ await expect(blueskyCompose.fetchBinary({ url, maxBytes: 100, label: 'Image 1' }), url).rejects.toThrow(/private, loopback or internal address/);
+ }
+ await expect(blueskyCompose.fetchBinary({ url: base.replace('127.0.0.1', 'localhost'), maxBytes: 100, label: 'Image 1' })).rejects.toThrow(
+ /localhost resolves to/,
+ );
+ expect(requests).toHaveLength(0);
+ });
+
+ it('refuses non-http URLs and embedded credentials without sending a request', async () => {
+ await expect(blueskyCompose.fetchBinary({ url: 'file:///etc/passwd', maxBytes: 1000, label: 'Image 1' })).rejects.toThrow(
+ 'Image 1 "file:///etc/passwd" must start with http:// or https://.',
+ );
+ await expect(blueskyCompose.fetchBinary({ url: 'https://user:[email protected]/a.png', maxBytes: 1000, label: 'Image 1' })).rejects.toThrow(
+ 'must not contain a username or password',
+ );
+ expect(requests).toHaveLength(0);
+ });
+});
+
+describe('address policy', () => {
+ it('blocks private, loopback, link-local, metadata and mapped addresses and allows public ones', () => {
+ const blocked = ['127.0.0.1', '10.0.0.1', '172.16.5.4', '192.168.1.1', '169.254.169.254', '100.64.0.1', '0.0.0.0', '224.0.0.1', '::1', '::', 'fe80::1', 'fd12:3456::1', '::ffff:10.0.0.1', '::ffff:7f00:1', 'not-an-ip'];
+ const allowed = ['8.8.8.8', '1.1.1.1', '151.101.1.140', '2606:4700:4700::1111', '2a00:1450:4001:80b::200e'];
+ expect(blocked.filter((address) => !blueskyDownload.isBlockedAddress(address))).toEqual([]);
+ expect(allowed.filter((address) => blueskyDownload.isBlockedAddress(address))).toEqual([]);
+ });
+
+ it('fails a DNS lookup that resolves to a loopback address', async () => {
+ const error = await new Promise<unknown>((resolve) => {
+ blueskyDownload.guardedLookup({ hostname: 'localhost', options: {}, callback: (lookupError) => resolve(lookupError) });
+ });
+ expect(error).toBeInstanceOf(Error);
+ expect(String(error)).toMatch(/localhost resolves to/);
+ });
+});
diff --git a/packages/pieces/community/bluesky/test/helpers.ts b/packages/pieces/community/bluesky/test/helpers.ts
new file mode 100644
index 00000000000..2d72917d762
--- /dev/null
+++ b/packages/pieces/community/bluesky/test/helpers.ts
@@ -0,0 +1,142 @@
+import {
+ ActionContext,
+ AppConnectionType,
+ InputPropertyMap,
+ StaticPropsValue,
+ TriggerHookContext,
+ TriggerStrategy,
+} from '@activepieces/pieces-framework';
+import { vi } from 'vitest';
+import { createMockActionContext, createMockPollingTriggerContext } from '../../../framework/src/lib/test';
+import { blueskyAuth } from '../src/lib/common/auth';
+import { blueskyClient } from '../src/lib/common/client';
+
+export const ME_DID = 'did:plc:aaaaaaaaaaaaaaaaaaaaaaaa';
+export const ME_HANDLE = 'me.bsky.social';
+export const OTHER_DID = 'did:plc:bbbbbbbbbbbbbbbbbbbbbbbb';
+export const OTHER_HANDLE = 'other.bsky.social';
+export const CID = 'bafyreib2rxk3vcfbqij7y6kzgy4knknc7ff4t5jn2m5fbn6jdl7czfqyqe';
+
+export function fakeJwt({ expSeconds }: { expSeconds: number }): string {
+ const encode = (value: object) => Buffer.from(JSON.stringify(value)).toString('base64url');
+ return `${encode({ alg: 'ES256K' })}.${encode({ exp: expSeconds, sub: ME_DID })}.sig`;
+}
+
+export function installFakeBluesky({ routes }: { routes: Record<string, RouteHandler> }) {
+ const calls: RecordedCall[] = [];
+ blueskyClient.clearAgentCache();
+ const allRoutes: Record<string, RouteHandler> = {
+ 'com.atproto.server.createSession': () =>
+ json({
+ did: ME_DID,
+ handle: ME_HANDLE,
+ accessJwt: fakeJwt({ expSeconds: Math.floor(Date.now() / 1000) + 3600 }),
+ refreshJwt: fakeJwt({ expSeconds: Math.floor(Date.now() / 1000) + 86400 }),
+ active: true,
+ }),
+ ...routes,
+ };
+ const fetchMock = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
+ const request = input instanceof Request ? input : new Request(String(input), init);
+ const url = new URL(request.url);
+ const nsid = url.pathname.replace('/xrpc/', '');
+ const bodyText = request.method === 'GET' ? '' : await request.text();
+ const body: unknown = bodyText && !bodyText.startsWith('\u0000') ? safeJson(bodyText) : undefined;
+ const call: RecordedCall = { nsid, method: request.method, query: url.searchParams, body, host: url.host };
+ calls.push(call);
+ const handler = allRoutes[nsid];
+ if (!handler) {
+ return xrpcError({ status: 501, error: 'MethodNotImplemented', message: `no fake for ${nsid}` });
+ }
+ return handler(call);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ return { calls, fetchMock, callsTo: (nsid: string) => calls.filter((call) => call.nsid === nsid) };
+}
+
+export function json(value: unknown): Response {
+ return new Response(JSON.stringify(value), { status: 200, headers: { 'content-type': 'application/json' } });
+}
+
+export function xrpcError({ status, error, message, headers = {} }: { status: number; error: string; message: string; headers?: Record<string, string> }): Response {
+ return new Response(JSON.stringify({ error, message }), { status, headers: { 'content-type': 'application/json', ...headers } });
+}
+
+export function postView({ rkey, did = OTHER_DID, handle = OTHER_HANDLE, text = 'hello', indexedAt = '2026-10-05T10:00:00.000Z', viewer = {}, extra = {} }: PostViewArgs) {
+ return {
+ uri: `at://${did}/app.bsky.feed.post/${rkey}`,
+ cid: CID,
+ author: { did, handle, displayName: 'Someone' },
+ record: { $type: 'app.bsky.feed.post', text, createdAt: indexedAt },
+ indexedAt,
+ likeCount: 1,
+ repostCount: 0,
+ replyCount: 0,
+ quoteCount: 0,
+ viewer,
+ labels: [],
+ ...extra,
+ };
+}
+
+export function profileView({ did = OTHER_DID, handle = OTHER_HANDLE, viewer = {} }: { did?: string; handle?: string; viewer?: Record<string, unknown> } = {}) {
+ return { did, handle, displayName: 'Other', viewer, labels: [], indexedAt: '2026-01-01T00:00:00.000Z', createdAt: '2024-01-01T00:00:00.000Z' };
+}
+
+export function testAuth({ password = 'app-pass-1234' }: { password?: string } = {}) {
+ return {
+ type: AppConnectionType.CUSTOM_AUTH as const,
+ props: { pdsHost: 'https://bsky.social', identifier: ME_HANDLE, password },
+ };
+}
+
+export function runAction<Props extends InputPropertyMap>({
+ action,
+ propsValue,
+}: {
+ action: { run: (context: ActionContext<typeof blueskyAuth, Props>) => Promise<unknown> };
+ propsValue: StaticPropsValue<Props>;
+}) {
+ return action.run({ ...createMockActionContext<Props>({ propsValue }), auth: testAuth() });
+}
+
+export function triggerContext<Props extends InputPropertyMap>({
+ propsValue,
+ store,
+ isRepublish,
+}: {
+ propsValue: StaticPropsValue<Props>;
+ store: Map<string, string>;
+ isRepublish?: boolean;
+}): TriggerHookContext<typeof blueskyAuth, Props, TriggerStrategy.POLLING> {
+ return {
+ ...createMockPollingTriggerContext<Props>({ propsValue }),
+ auth: testAuth(),
+ isRepublish,
+ store: {
+ put: async <T>(key: string, value: T) => {
+ store.set(key, JSON.stringify(value));
+ return value;
+ },
+ get: async <T>(key: string): Promise<T | null> => {
+ const raw = store.get(key);
+ return raw === undefined ? null : JSON.parse(raw);
+ },
+ delete: async (key: string) => {
+ store.delete(key);
+ },
+ },
+ };
+}
+
+function safeJson(text: string): unknown {
+ try {
+ return JSON.parse(text);
+ } catch {
+ return text;
+ }
+}
+
+export type RecordedCall = { nsid: string; method: string; query: URLSearchParams; body: unknown; host: string };
+export type RouteHandler = (call: RecordedCall) => Response | Promise<Response>;
+type PostViewArgs = { rkey: string; did?: string; handle?: string; text?: string; indexedAt?: string; viewer?: Record<string, unknown>; extra?: Record<string, unknown> };
diff --git a/packages/pieces/community/bluesky/test/polling.test.ts b/packages/pieces/community/bluesky/test/polling.test.ts
new file mode 100644
index 00000000000..b78fe30dd13
--- /dev/null
+++ b/packages/pieces/community/bluesky/test/polling.test.ts
@@ -0,0 +1,147 @@
+import { describe, expect, it } from 'vitest';
+import { blueskyPolling, PageFetcher, PollStore } from '../src/lib/common/polling';
+
+const PAGE_SIZE = 100;
+
+function memoryStore(): PollStore & { data: Map<string, unknown> } {
+ const data = new Map<string, unknown>();
+ return {
+ data,
+ get: async <V>(key: string): Promise<V | null> => {
+ const raw = data.get(key);
+ return raw === undefined ? null : JSON.parse(JSON.stringify(raw));
+ },
+ put: async <V>(key: string, value: V): Promise<V> => {
+ data.set(key, JSON.parse(JSON.stringify(value)));
+ return value;
+ },
+ delete: async (key: string) => {
+ data.delete(key);
+ },
+ };
+}
+
+function feedOf({ count, startTime, prefix }: { count: number; startTime: number; prefix: string }): FeedEntry[] {
+ return Array.from({ length: count }, (_, index) => ({ key: `${prefix}${index}`, time: startTime + index * 1000 })).reverse();
+}
+
+function pagedFeed({ entries, timed }: { entries: () => FeedEntry[]; timed: boolean }): { fetchPage: PageFetcher<string>; pagesRead: () => number } {
+ let pagesRead = 0;
+ const fetchPage: PageFetcher<string> = async ({ cursor }) => {
+ pagesRead++;
+ const all = entries();
+ const offset = cursor === undefined ? 0 : all.findIndex((entry) => entry.key === cursor) + 1;
+ const slice = all.slice(offset, offset + PAGE_SIZE);
+ const times = blueskyPolling.pageTimes(slice.map((entry) => (timed ? entry.time : undefined)));
+ return {
+ items: slice.map((entry) => ({ key: entry.key, time: timed ? entry.time : Date.now(), data: entry.key })),
+ cursor: offset + PAGE_SIZE < all.length ? slice[slice.length - 1].key : undefined,
+ ...times,
+ };
+ };
+ return { fetchPage, pagesRead: () => pagesRead };
+}
+
+describe('polling catch-up', () => {
+ it('emits every item when more pages than the per-poll budget arrive between polls', async () => {
+ const now = Date.now();
+ const old = feedOf({ count: 50, startTime: now - 3_600_000, prefix: 'old' });
+ let entries = old;
+ const store = memoryStore();
+ const feed = pagedFeed({ entries: () => entries, timed: true });
+ await blueskyPolling.onEnable({ store, storeKey: 'k', fetchPage: feed.fetchPage });
+ const burst = feedOf({ count: 1500, startTime: now - 1_800_000, prefix: 'new' });
+ entries = [...burst, ...old];
+
+ const first = await blueskyPolling.poll({ store, storeKey: 'k', fetchPage: feed.fetchPage });
+ expect(first).toHaveLength(blueskyPolling.MAX_PAGES * PAGE_SIZE);
+ const second = await blueskyPolling.poll({ store, storeKey: 'k', fetchPage: feed.fetchPage });
+ const third = await blueskyPolling.poll({ store, storeKey: 'k', fetchPage: feed.fetchPage });
+
+ const emitted = [...first, ...second, ...third];
+ expect(new Set(emitted).size).toBe(emitted.length);
+ expect(new Set(emitted)).toEqual(new Set(burst.map((entry) => entry.key)));
+ expect(third).toEqual([]);
+ });
+
+ it('keeps the key of every emitted event even when one poll emits more than the seen cap', async () => {
+ const now = Date.now();
+ const old = feedOf({ count: 20, startTime: now - 3_600_000, prefix: 'old' });
+ let entries = old;
+ const store = memoryStore();
+ const feed = pagedFeed({ entries: () => entries, timed: true });
+ await blueskyPolling.onEnable({ store, storeKey: 'k', fetchPage: feed.fetchPage });
+ const burst = feedOf({ count: 1800, startTime: now - 1_800_000, prefix: 'b' });
+ entries = [...burst, ...old];
+ const first = await blueskyPolling.poll({ store, storeKey: 'k', fetchPage: feed.fetchPage });
+ const afterHead = await store.get<{ seen: string[] }>('k');
+ expect(afterHead?.seen).toEqual(expect.arrayContaining(first));
+ const second = await blueskyPolling.poll({ store, storeKey: 'k', fetchPage: feed.fetchPage });
+ const afterDrain = await store.get<{ seen: string[] }>('k');
+ expect(second).toHaveLength(800);
+ expect(afterDrain?.seen).toEqual(expect.arrayContaining(second));
+ expect(afterDrain?.seen.slice(0, blueskyPolling.SEEN_CAP)).toEqual(afterHead?.seen.slice(0, blueskyPolling.SEEN_CAP));
+ });
+
+ it('keeps reading new items at the head after finishing the backlog', async () => {
+ const now = Date.now();
+ const old = feedOf({ count: 10, startTime: now - 3_600_000, prefix: 'old' });
+ let entries = old;
+ const store = memoryStore();
+ const feed = pagedFeed({ entries: () => entries, timed: true });
+ await blueskyPolling.onEnable({ store, storeKey: 'k', fetchPage: feed.fetchPage });
+ const burst = feedOf({ count: 450, startTime: now - 1_800_000, prefix: 'burst' });
+ entries = [...burst, ...old];
+ const first = await blueskyPolling.poll({ store, storeKey: 'k', fetchPage: feed.fetchPage, maxPages: 4 });
+ const later = feedOf({ count: 30, startTime: now - 60_000, prefix: 'later' });
+ entries = [...later, ...burst, ...old];
+ const second = await blueskyPolling.poll({ store, storeKey: 'k', fetchPage: feed.fetchPage, maxPages: 4 });
+ const third = await blueskyPolling.poll({ store, storeKey: 'k', fetchPage: feed.fetchPage, maxPages: 4 });
+ const fourth = await blueskyPolling.poll({ store, storeKey: 'k', fetchPage: feed.fetchPage, maxPages: 4 });
+
+ expect(first).toHaveLength(400);
+ expect(second).toHaveLength(50);
+ expect(third.sort()).toEqual(later.map((entry) => entry.key).sort());
+ expect(fourth).toEqual([]);
+ });
+
+ it('catches up an untimed list (followers) even when the seen list was trimmed', async () => {
+ const old = feedOf({ count: 20, startTime: 0, prefix: 'old' });
+ let entries = old;
+ const store = memoryStore();
+ const feed = pagedFeed({ entries: () => entries, timed: false });
+ await blueskyPolling.onEnable({ store, storeKey: 'k', fetchPage: feed.fetchPage, seenCap: 150 });
+ const burst = feedOf({ count: 650, startTime: 0, prefix: 'f' });
+ entries = [...burst, ...old];
+ const emitted: string[] = [];
+ for (let round = 0; round < 4; round++) {
+ emitted.push(...(await blueskyPolling.poll({ store, storeKey: 'k', fetchPage: feed.fetchPage, seenCap: 150, maxPages: 3 })));
+ }
+ expect(emitted.sort()).toEqual(burst.map((entry) => entry.key).sort());
+ });
+
+ it('does not keep a resume cursor when catching up is turned off', async () => {
+ const now = Date.now();
+ let entries = feedOf({ count: 5, startTime: now - 3_600_000, prefix: 'old' });
+ const store = memoryStore();
+ const feed = pagedFeed({ entries: () => entries, timed: true });
+ await blueskyPolling.onEnable({ store, storeKey: 'k', fetchPage: feed.fetchPage });
+ entries = [...feedOf({ count: 300, startTime: now - 600_000, prefix: 'top' }), ...entries];
+ await blueskyPolling.poll({ store, storeKey: 'k', fetchPage: feed.fetchPage, maxPages: 1, resumable: false });
+ const state = store.data.get('k');
+ expect(state).toBeDefined();
+ expect(typeof state === 'object' && state !== null && 'resume' in state).toBe(false);
+ });
+
+ it('ignores a malformed resume entry and polls from the head', async () => {
+ const now = Date.now();
+ const store = memoryStore();
+ const entries = feedOf({ count: 3, startTime: now - 60_000, prefix: 'n' });
+ await store.put('k', { seen: [], lastTime: now - 120_000, resume: { cursor: 5, stopBefore: 0 } });
+ const feed = pagedFeed({ entries: () => entries, timed: true });
+ const events = await blueskyPolling.poll({ store, storeKey: 'k', fetchPage: feed.fetchPage });
+ expect(events).toHaveLength(3);
+ });
+});
+
+type FeedEntry = { key: string; time: number };
diff --git a/packages/pieces/community/bluesky/test/refs.test.ts b/packages/pieces/community/bluesky/test/refs.test.ts
new file mode 100644
index 00000000000..acb1753cbd2
--- /dev/null
+++ b/packages/pieces/community/bluesky/test/refs.test.ts
@@ -0,0 +1,173 @@
+import { describe, expect, it } from 'vitest';
+import { blueskyRefs } from '../src/lib/common/refs';
+import { blueskyCompose } from '../src/lib/common/compose';
+import { blueskyClient } from '../src/lib/common/client';
+import { blueskyPolling, PollItem, PollStore } from '../src/lib/common/polling';
+import { blueskyProps } from '../src/lib/common/props';
+
+const PLC = 'did:plc:aaaaaaaaaaaaaaaaaaaaaaaa';
+
+describe('post and actor references', () => {
+ it('accepts bsky.app links with a handle or a DID and at:// URIs with did:plc, did:web or a handle', () => {
+ expect(blueskyRefs.parsePostInput('https://bsky.app/profile/Alice.BSKY.social/post/3kabc?x=1')).toEqual({ repo: 'alice.bsky.social', rkey: '3kabc' });
+ expect(blueskyRefs.parsePostInput(`https://bsky.app/profile/${PLC}/post/3kabc`)).toEqual({ repo: PLC, rkey: '3kabc' });
+ expect(blueskyRefs.parsePostInput('at://did:web:example.com/app.bsky.feed.post/3kabc')).toEqual({ repo: 'did:web:example.com', rkey: '3kabc' });
+ expect(blueskyRefs.parsePostInput('bsky.app/profile/alice.bsky.social/post/3kabc')).toEqual({ repo: 'alice.bsky.social', rkey: '3kabc' });
+ });
+
+ it('rejects other hosts, other collections and malformed ids', () => {
+ expect(() => blueskyRefs.parsePostInput('https://evil.example/profile/alice.bsky.social/post/3kabc')).toThrow(/not a post link/);
+ expect(() => blueskyRefs.parsePostInput(`at://${PLC}/app.bsky.feed.like/3kabc`)).toThrow(/AT-URI/);
+ expect(() => blueskyRefs.parsePostInput('https://bsky.app/profile/alice/post/3kabc')).toThrow(/handle/);
+ expect(() => blueskyRefs.parsePostInput('')).toThrow(/empty/);
+ });
+
+ it('normalises actor input: @handle, bare names, DIDs and profile links', () => {
+ expect(blueskyRefs.parseActorInput('@Alice.bsky.social')).toBe('alice.bsky.social');
+ expect(blueskyRefs.parseActorInput('alice')).toBe('alice.bsky.social');
+ expect(blueskyRefs.parseActorInput(PLC)).toBe(PLC);
+ expect(blueskyRefs.parseActorInput('https://bsky.app/profile/bsky.app')).toBe('bsky.app');
+ expect(() => blueskyRefs.parseActorInput('https://x.com/profile/bsky.app')).toThrow(/profile link/);
+ });
+
+ it('parses list links and builds web links', () => {
+ expect(blueskyRefs.parseListInput('https://bsky.app/profile/alice.bsky.social/lists/3lst')).toEqual({ repo: 'alice.bsky.social', rkey: '3lst' });
+ expect(blueskyRefs.postWebUrl({ uri: `at://${PLC}/app.bsky.feed.post/3kabc`, handle: 'alice.bsky.social' })).toBe('https://bsky.app/profile/alice.bsky.social/post/3kabc');
+ expect(blueskyRefs.postWebUrl({ uri: `at://${PLC}/app.bsky.feed.post/3kabc`, handle: 'handle.invalid' })).toBe(`https://bsky.app/profile/${PLC}/post/3kabc`);
+ expect(blueskyRefs.postWebUrl({ uri: `at://${PLC}/app.bsky.graph.list/3lst` })).toContain('/lists/3lst');
+ });
+});
+
+describe('post composition rules', () => {
+ it('counts graphemes, not UTF-8 bytes (200 Japanese characters fit in a post)', () => {
+ const japanese = 'あ'.repeat(200);
+ expect(blueskyCompose.graphemeLength(japanese)).toBe(200);
+ expect(() => blueskyCompose.assertPostLength({ text: japanese, label: 'Text' })).not.toThrow();
+ expect(() => blueskyCompose.assertPostLength({ text: '👍'.repeat(301), label: 'Text' })).toThrow(/301 characters/);
+ });
+
+ it('maps the old content-warning values to real Bluesky self-labels', () => {
+ expect(blueskyCompose.mapContentWarnings(['adult', 'violence', 'sensitive', 'spam', 'nudity', 'adult'])).toEqual(['porn', 'graphic-media', 'sexual', 'nudity']);
+ expect(blueskyCompose.selfLabels([])).toBeUndefined();
+ expect(blueskyCompose.selfLabels(['porn', 'bogus'])).toEqual({ $type: 'com.atproto.label.defs#selfLabels', values: [{ val: 'porn' }] });
+ });
+
+ it('limits tags to 8 and languages to 3', () => {
+ expect(blueskyCompose.normalizeTags(['#a, b', 'b', 'c'])).toEqual(['a', 'b', 'c']);
+ expect(() => blueskyCompose.normalizeTags(['1,2,3,4,5,6,7,8,9'])).toThrow(/at most 8/);
+ expect(() => blueskyCompose.normalizeLangs(['en', 'de', 'fr', 'ja'])).toThrow(/at most 3/);
+ });
+
+ it('reads Open Graph tags in any attribute order', () => {
+ const html = '<meta content="Card Title" property="og:title"><meta property=\'og:description\' content=\'Desc &amp; more\'><meta name="description" content="ignored">';
+ const tags = blueskyCompose.metaTags(html);
+ expect(tags['og:title']).toBe('Card Title');
+ expect(tags['og:description']).toBe('Desc & more');
+ });
+
+ it('stays fast on a hostile page', () => {
+ const started = Date.now();
+ blueskyCompose.metaTags('<meta ' + 'a="b" '.repeat(50000));
+ expect(Date.now() - started).toBeLessThan(1000);
+ });
+
+ it('sniffs image types from magic bytes', () => {
+ expect(blueskyCompose.sniffImageType(new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0, 0, 0, 0]))).toBe('image/png');
+ expect(blueskyCompose.sniffImageType(new Uint8Array([0xff, 0xd8, 0xff, 0xe0]))).toBe('image/jpeg');
+ expect(blueskyCompose.sniffImageType(new Uint8Array([1, 2, 3]))).toBeUndefined();
+ });
+});
+
+describe('connection host', () => {
+ it('normalises the PDS host once for validate and the client', () => {
+ expect(blueskyClient.normalizePdsHost(undefined)).toBe('https://bsky.social');
+ expect(blueskyClient.normalizePdsHost(' bsky.social/ ')).toBe('https://bsky.social');
+ expect(blueskyClient.normalizePdsHost('https://pds.example.com:8443/xrpc')).toBe('https://pds.example.com:8443');
+ expect(() => blueskyClient.normalizePdsHost('https://user:[email protected]')).toThrow(/username/);
+ });
+
+ it('keeps custom API calls on the PDS host', () => {
+ expect(() => blueskyClient.assertSameOrigin({ url: '/app.bsky.actor.getProfile', pdsHost: 'https://bsky.social' })).not.toThrow();
+ expect(() => blueskyClient.assertSameOrigin({ url: 'https://bsky.social/xrpc/x', pdsHost: 'https://bsky.social' })).not.toThrow();
+ expect(() => blueskyClient.assertSameOrigin({ url: 'https://bsky.social.evil.io/xrpc/x', pdsHost: 'https://bsky.social' })).toThrow(/PDS host/);
+ expect(() => blueskyClient.assertSameOrigin({ url: '//evil.io/xrpc/x', pdsHost: 'https://bsky.social' })).toThrow();
+ expect(() => blueskyClient.assertSameOrigin({ url: 'https://[email protected]/xrpc/x', pdsHost: 'https://bsky.social' })).toThrow(/PDS host/);
+ });
+});
+
+describe('paging inputs', () => {
+ it('validates limit and cursor', () => {
+ expect(blueskyProps.parseLimit(undefined)).toBe(25);
+ expect(blueskyProps.parseLimit('50')).toBe(50);
+ expect(() => blueskyProps.parseLimit(0)).toThrow(/between 1 and 100/);
+ expect(() => blueskyProps.parseLimit(101)).toThrow(/between 1 and 100/);
+ expect(blueskyProps.parseCursor(' ')).toBeUndefined();
+ });
+});
+
+describe('polling helper', () => {
+ function memoryStore(): PollStore & { data: Map<string, string> } {
+ const data = new Map<string, string>();
+ return {
+ data,
+ get: async <V>(key: string): Promise<V | null> => {
+ const raw = data.get(key);
+ return raw === undefined ? null : JSON.parse(raw);
+ },
+ put: async <V>(key: string, value: V) => {
+ data.set(key, JSON.stringify(value));
+ return value;
+ },
+ delete: async (key: string) => {
+ data.delete(key);
+ },
+ };
+ }
+ const item = ({ key, time }: { key: string; time: number }): PollItem<string> => ({ key, time, data: key });
+ const pageOf = ({ items, cursor }: { items: PollItem<string>[]; cursor?: string }) => ({ items, cursor, ...blueskyPolling.pageTimes(items.map((i) => i.time)) });
+
+ it('seeds on enable, then emits only unseen items newest first and never twice', async () => {
+ const store = memoryStore();
+ let feed = [item({ key: 'b', time: 2000 }), item({ key: 'a', time: 1000 })];
+ const fetchPage = async () => pageOf({ items: feed });
+ await blueskyPolling.onEnable({ store, storeKey: 'k', fetchPage });
+ expect(await blueskyPolling.poll({ store, storeKey: 'k', fetchPage })).toEqual([]);
+ feed = [item({ key: 'd', time: 4000 }), item({ key: 'c', time: 3000 }), ...feed];
+ expect(await blueskyPolling.poll({ store, storeKey: 'k', fetchPage })).toEqual(['d', 'c']);
+ expect(await blueskyPolling.poll({ store, storeKey: 'k', fetchPage })).toEqual([]);
+ });
+
+ it('pages back past one page when many items arrived, up to the page cap', async () => {
+ const store = memoryStore();
+ await store.put('k', { seen: ['old'], lastTime: 1000 });
+ const pages: Record<string, ReturnType<typeof pageOf>> = {
+ first: pageOf({ items: [item({ key: 'n4', time: 5000 }), item({ key: 'n3', time: 4000 })], cursor: 'p2' }),
+ p2: pageOf({ items: [item({ key: 'n2', time: 3000 }), item({ key: 'n1', time: 2000 })], cursor: 'p3' }),
+ p3: pageOf({ items: [item({ key: 'old', time: 1000 })], cursor: 'p4' }),
+ };
+ const fetched: string[] = [];
+ const fetchPage = async ({ cursor }: { cursor: string | undefined }) => {
+ fetched.push(cursor ?? 'first');
+ return pages[cursor ?? 'first'];
+ };
+ expect(await blueskyPolling.poll({ store, storeKey: 'k', fetchPage })).toEqual(['n4', 'n3', 'n2', 'n1']);
+ expect(fetched).toEqual(['first', 'p2', 'p3']);
+ });
+
+ it('keeps the seen set bounded and keeps state on republish', async () => {
+ const store = memoryStore();
+ const many = Array.from({ length: 700 }, (_, i) => item({ key: `k${i}`, time: 10_000 - i }));
+ await blueskyPolling.onEnable({ store, storeKey: 'k', fetchPage: async () => pageOf({ items: many }) });
+ const state = await store.get<{ seen: string[] }>('k');
+ expect(state?.seen.length).toBe(blueskyPolling.SEEN_CAP);
+ await blueskyPolling.onEnable({ store, storeKey: 'k', fetchPage: async () => pageOf({ items: [item({ key: 'new', time: 20_000 })] }), isRepublish: true });
+ expect((await store.get<{ seen: string[] }>('k'))?.seen.length).toBe(blueskyPolling.SEEN_CAP);
+ });
+
+ it('reseeds instead of flooding when the stored state is from the old pollingHelper', async () => {
+ const store = memoryStore();
+ await store.put('k', { lastPoll: 123 });
+ expect(await blueskyPolling.poll({ store, storeKey: 'k', fetchPage: async () => pageOf({ items: [item({ key: 'x', time: 5 })] }) })).toEqual([]);
+ expect(await blueskyPolling.poll({ store, storeKey: 'k', fetchPage: async () => pageOf({ items: [item({ key: 'y', time: 6 }), item({ key: 'x', time: 5 })] }) })).toEqual(['y']);
+ });
+});
diff --git a/packages/pieces/community/bluesky/test/triggers.test.ts b/packages/pieces/community/bluesky/test/triggers.test.ts
new file mode 100644
index 00000000000..b6ad6c5b083
--- /dev/null
+++ b/packages/pieces/community/bluesky/test/triggers.test.ts
@@ -0,0 +1,220 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { newTimelinePosts } from '../src/lib/triggers/new-timeline-posts';
+import { newFollowerOnAccount } from '../src/lib/triggers/new-follower-on-account';
+import { newPostsByAuthor } from '../src/lib/triggers/new-posts-by-author';
+import { newPost } from '../src/lib/triggers/new-post';
+import { newMention } from '../src/lib/triggers/new-mention';
+import { newNotification } from '../src/lib/triggers/new-notification';
+import { bluesky } from '../src/index';
+import { CID, ME_DID, OTHER_DID, OTHER_HANDLE, installFakeBluesky, json, postView, profileView, triggerContext, xrpcError } from './helpers';
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+const THIRD_DID = 'did:plc:cccccccccccccccccccccccc';
+const minutesAgo = (minutes: number) => new Date(Date.now() - minutes * 60_000).toISOString();
+
+function repostReason({ did, indexedAt }: { did: string; indexedAt: string }) {
+ return { $type: 'app.bsky.feed.defs#reasonRepost', by: { did, handle: 'reposter.bsky.social' }, indexedAt };
+}
+
+describe('New Timeline Posts', () => {
+ it('seeds on enable, then fires once per new item including a repost of an old post', async () => {
+ let feed: unknown[] = [{ post: postView({ rkey: '3a', indexedAt: minutesAgo(10) }) }];
+ installFakeBluesky({ routes: { 'app.bsky.feed.getTimeline': () => json({ feed }) } });
+ const store = new Map<string, string>();
+ const context = triggerContext({ propsValue: {}, store });
+ await newTimelinePosts.onEnable(context);
+ feed = [
+ { post: postView({ rkey: '3old', indexedAt: '2026-01-01T00:00:00.000Z' }), reason: repostReason({ did: THIRD_DID, indexedAt: minutesAgo(5) }) },
+ ...feed,
+ ];
+ const first = await newTimelinePosts.run(context);
+ expect(first).toHaveLength(1);
+ expect(first[0]).toMatchObject({ uri: `at://${OTHER_DID}/app.bsky.feed.post/3old`, feedContext: { isRepost: true } });
+ expect(await newTimelinePosts.run(context)).toEqual([]);
+ });
+
+ it('throws on bad credentials instead of returning no posts', async () => {
+ installFakeBluesky({
+ routes: { 'com.atproto.server.createSession': () => xrpcError({ status: 401, error: 'AuthenticationRequired', message: 'Invalid identifier or password' }) },
+ });
+ const context = triggerContext({ propsValue: {}, store: new Map() });
+ await expect(newTimelinePosts.run(context)).rejects.toThrow(/rejected the credentials/);
+ });
+
+ it('keeps its state on republish so nothing between polls is lost', async () => {
+ let feed: unknown[] = [{ post: postView({ rkey: '3a' }) }];
+ installFakeBluesky({ routes: { 'app.bsky.feed.getTimeline': () => json({ feed }) } });
+ const store = new Map<string, string>();
+ await newTimelinePosts.onEnable(triggerContext({ propsValue: {}, store }));
+ feed = [{ post: postView({ rkey: '3b', indexedAt: minutesAgo(9) }) }, ...feed];
+ await newTimelinePosts.onEnable(triggerContext({ propsValue: {}, store, isRepublish: true }));
+ expect(await newTimelinePosts.run(triggerContext({ propsValue: {}, store }))).toHaveLength(1);
+ });
+});
+
+describe('New Follower on Account', () => {
+ it('fires for a follower whose profile is old and never for the same follower twice', async () => {
+ let followers = [profileView({ did: THIRD_DID, handle: 'first.bsky.social' })];
+ installFakeBluesky({ routes: { 'app.bsky.graph.getFollowers': () => json({ subject: profileView({ did: ME_DID, handle: 'me.bsky.social' }), followers }) } });
+ const store = new Map<string, string>();
+ const context = triggerContext({ propsValue: {}, store });
+ await newFollowerOnAccount.onEnable(context);
+ followers = [profileView(), ...followers];
+ const events = await newFollowerOnAccount.run(context);
+ expect(events).toEqual([expect.objectContaining({ did: OTHER_DID, handle: OTHER_HANDLE, url: `https://bsky.app/profile/${OTHER_HANDLE}` })]);
+ expect(await newFollowerOnAccount.run(context)).toEqual([]);
+ });
+});
+
+describe('New Posts by Author', () => {
+ it('matches by DID and includes the author\'s reposts when asked', async () => {
+ let feed: unknown[] = [];
+ const fake = installFakeBluesky({
+ routes: {
+ 'com.atproto.identity.resolveHandle': () => json({ did: OTHER_DID }),
+ 'app.bsky.feed.getAuthorFeed': () => json({ feed }),
+ },
+ });
+ const store = new Map<string, string>();
+ const propsValue = { authorSelection: 'manual', authorHandle: '@Other.bsky.social', includeReposts: true, includeReplies: false };
+ const context = triggerContext({ propsValue, store });
+ await newPostsByAuthor.onEnable(context);
+ feed = [
+ { post: postView({ rkey: '3theirs', did: THIRD_DID, handle: 'third.bsky.social', indexedAt: '2026-01-01T00:00:00.000Z' }), reason: repostReason({ did: OTHER_DID, indexedAt: minutesAgo(5) }) },
+ { post: postView({ rkey: '3own', indexedAt: minutesAgo(6) }) },
+ {
+ post: postView({
+ rkey: '3reply',
+ indexedAt: minutesAgo(7),
+ extra: { record: { $type: 'app.bsky.feed.post', text: 'r', createdAt: minutesAgo(7), reply: { root: { uri: `at://${THIRD_DID}/app.bsky.feed.post/3x`, cid: CID }, parent: { uri: `at://${THIRD_DID}/app.bsky.feed.post/3x`, cid: CID } } } },
+ }),
+ },
+ ];
+ const events = await newPostsByAuthor.run(context);
+ expect(events.map((e) => (typeof e === 'object' && e !== null && 'uri' in e ? e.uri : null))).toEqual([
+ `at://${THIRD_DID}/app.bsky.feed.post/3theirs`,
+ `at://${OTHER_DID}/app.bsky.feed.post/3own`,
+ ]);
+ expect(events[0]).toMatchObject({ postContext: { isRepost: true, authorHandle: 'Other.bsky.social' } });
+ expect(fake.callsTo('app.bsky.feed.getAuthorFeed')[0].query.get('actor')).toBe(OTHER_DID);
+ });
+
+ it('refuses to enable without an author', async () => {
+ installFakeBluesky({ routes: {} });
+ const context = triggerContext({ propsValue: { authorSelection: 'following' }, store: new Map() });
+ await expect(newPostsByAuthor.onEnable(context)).rejects.toThrow(/Select an author/);
+ });
+});
+
+describe('New Post (search)', () => {
+ it('treats an unticked media filter as no filter', async () => {
+ const image = { $type: 'app.bsky.embed.images#view', images: [] };
+ let posts: unknown[] = [];
+ installFakeBluesky({ routes: { 'app.bsky.feed.searchPosts': () => json({ posts }) } });
+ const store = new Map<string, string>();
+ const context = triggerContext({ propsValue: { searchQuery: 'AP-TEST', includeImages: false, includeVideos: false }, store });
+ await newPost.onEnable(context);
+ posts = [postView({ rkey: '3img', indexedAt: minutesAgo(10), extra: { embed: image } }), postView({ rkey: '3txt', indexedAt: minutesAgo(11) })];
+ expect(await newPost.run(context)).toHaveLength(2);
+ });
+});
+
+describe('notification triggers', () => {
+ const notification = ({ rkey, reason, indexedAt }: { rkey: string; reason: string; indexedAt: string }) => ({
+ uri: `at://${OTHER_DID}/app.bsky.feed.post/${rkey}`,
+ cid: CID,
+ author: { did: OTHER_DID, handle: OTHER_HANDLE },
+ reason,
+ record: { $type: 'app.bsky.feed.post', text: `@me ${rkey}`, createdAt: indexedAt },
+ isRead: false,
+ indexedAt,
+ });
+
+ it('New Mention or Reply hydrates the post and never marks anything seen', async () => {
+ let notifications: unknown[] = [];
+ const fake = installFakeBluesky({
+ routes: {
+ 'app.bsky.notification.listNotifications': () => json({ notifications }),
+ 'app.bsky.feed.getPosts': () => json({ posts: [postView({ rkey: '3m', text: '@me 3m' })] }),
+ },
+ });
+ const store = new Map<string, string>();
+ const context = triggerContext({ propsValue: {}, store });
+ await newMention.onEnable(context);
+ notifications = [notification({ rkey: '3m', reason: 'mention', indexedAt: minutesAgo(10) })];
+ const events = await newMention.run(context);
+ expect(events).toEqual([expect.objectContaining({ notificationReason: 'mention', text: '@me 3m', url: `https://bsky.app/profile/${OTHER_HANDLE}/post/3m` })]);
+ expect(fake.callsTo('app.bsky.notification.listNotifications')[0].query.getAll('reasons')).toEqual(['mention', 'reply', 'quote']);
+ expect(fake.callsTo('app.bsky.notification.updateSeen')).toHaveLength(0);
+ });
+
+ it('New Mention or Reply still fires from the notification when the post was deleted', async () => {
+ let notifications: unknown[] = [];
+ installFakeBluesky({
+ routes: {
+ 'app.bsky.notification.listNotifications': () => json({ notifications }),
+ 'app.bsky.feed.getPosts': () => json({ posts: [postView({ rkey: '3kept', text: '@me 3kept' })] }),
+ },
+ });
+ const store = new Map<string, string>();
+ const context = triggerContext({ propsValue: {}, store });
+ await newMention.onEnable(context);
+ notifications = [
+ notification({ rkey: '3gone', reason: 'reply', indexedAt: minutesAgo(9) }),
+ notification({ rkey: '3kept', reason: 'mention', indexedAt: minutesAgo(10) }),
+ ];
+ const events = await newMention.run(context);
+ expect(events).toHaveLength(2);
+ expect(events[0]).toMatchObject({
+ uri: `at://${OTHER_DID}/app.bsky.feed.post/3gone`,
+ url: `https://bsky.app/profile/${OTHER_HANDLE}/post/3gone`,
+ text: '@me 3gone',
+ notificationReason: 'reply',
+ postAvailable: false,
+ likeCount: null,
+ replyCount: null,
+ });
+ expect(events[1]).toMatchObject({ text: '@me 3kept', postAvailable: true, likeCount: 1 });
+ expect(await newMention.run(context)).toEqual([]);
+ });
+
+ it('New Notification passes the chosen types', async () => {
+ const fake = installFakeBluesky({ routes: { 'app.bsky.notification.listNotifications': () => json({ notifications: [notification({ rkey: '3q', reason: 'quote', indexedAt: minutesAgo(10) })] }) } });
+ const events = await newNotification.test(triggerContext({ propsValue: { reasons: ['quote', 'like'] }, store: new Map() }));
+ expect(events).toHaveLength(1);
+ expect(fake.callsTo('app.bsky.notification.listNotifications')[0].query.getAll('reasons')).toEqual(['quote', 'like']);
+ });
+});
+
+describe('piece metadata', () => {
+ it('tags every action and trigger for agents', () => {
+ const metadata = bluesky.metadata();
+ const actions = Object.values(metadata.actions);
+ for (const action of actions) {
+ if (action.name === 'custom_api_call') {
+ continue;
+ }
+ expect(action.classification, action.name).toBeDefined();
+ expect(action.audience, action.name).toBeDefined();
+ expect(action.aiMetadata?.description, action.name).toBeTruthy();
+ expect(typeof action.aiMetadata?.idempotent, action.name).toBe('boolean');
+ expect(action.outputSchema, action.name).toBeDefined();
+ }
+ for (const trigger of Object.values(metadata.triggers)) {
+ expect(trigger.classification, trigger.name).toBe('READ');
+ expect(trigger.aiMetadata?.description, trigger.name).toBeTruthy();
+ expect(trigger.outputSchema, trigger.name).toBeDefined();
+ }
+ expect(actions.filter((a) => a.audience === 'ai').map((a) => a.name).sort()).toEqual([
+ 'bluesky_create_post',
+ 'bluesky_get_posts',
+ 'bluesky_get_unread_count',
+ 'bluesky_like_post',
+ 'bluesky_repost_post',
+ 'bluesky_resolve_handle',
+ ]);
+ });
+});
diff --git a/packages/pieces/community/bluesky/vitest.config.ts b/packages/pieces/community/bluesky/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/bluesky/vitest.config.ts
@@ -0,0 +1,19 @@
+import path from 'path'
+import { defineConfig } from 'vitest/config'
+
+const repoRoot = path.resolve(__dirname, '../../../..')
+
+export default defineConfig({
+ root: __dirname,
+ test: {
+ globals: true,
+ environment: 'node',
+ include: ['test/**/*.test.ts'],
+ },
+ resolve: {
+ alias: {
+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),
+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),
+ },
+ },
+})