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
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(mastodon): add triggers and richer Post Status for flow builders (#16073)
Odai Ahmadf7e7e9e3fc91
diff --git a/bun.lock b/bun.lockindex afb7d33cfc3..c7d459d4712 100644--- a/bun.lock+++ b/bun.lock@@ -5556,7 +5556,7 @@},"packages/pieces/community/mastodon": {"name": "@activepieces/piece-mastodon",- "version": "0.7.0",+ "version": "0.8.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -5566,6 +5566,7 @@},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/matomo": {diff --git a/packages/pieces/community/mastodon/package.json b/packages/pieces/community/mastodon/package.jsonindex 80adc540dc9..3ef9ed4fa9e 100644--- a/packages/pieces/community/mastodon/package.json+++ b/packages/pieces/community/mastodon/package.json@@ -1,12 +1,13 @@{"name": "@activepieces/piece-mastodon",- "version": "0.7.0",+ "version": "0.8.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","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"},"dependencies": {"@activepieces/pieces-common": "workspace:*",@@ -16,6 +17,7 @@"@activepieces/core-utils": "workspace:*"},"devDependencies": {- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"}}diff --git a/packages/pieces/community/mastodon/src/i18n/translation.json b/packages/pieces/community/mastodon/src/i18n/translation.jsonindex 632a419f437..4fbdc16d463 100644--- a/packages/pieces/community/mastodon/src/i18n/translation.json+++ b/packages/pieces/community/mastodon/src/i18n/translation.json@@ -6,7 +6,6 @@"The access token for your Mastodon account, check the documentation for how to get this": "The access token for your Mastodon account, check the documentation for how to get this","Post Status": "Post Status","Custom API Call": "Custom API Call",- "Post a status to Mastodon": "Post a status to Mastodon","Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint","Status": "Status","Media URL or File": "Media URL or File",@@ -140,14 +139,12 @@"Get a scheduled status by its ID.": "Get a scheduled status by its ID.","Change the publication time of a scheduled status.": "Change the publication time of a scheduled status.","Cancel a scheduled status so it is never published.": "Cancel a scheduled status so it is never published.",- "Upload an image, video or audio file to attach to a status.": "Upload an image, video or audio file to attach to a status.","Check an uploaded media file, including whether it has finished processing.": "Check an uploaded media file, including whether it has finished processing.","Change the alt text or focal point of an uploaded media file.": "Change the alt text or focal point of an uploaded media file.","Delete an uploaded media file that is not attached to a status.": "Delete an uploaded media file that is not attached to a status.","Get the profile of the connected account.": "Get the profile of the connected account.","Update the display name, bio and settings of the connected account.": "Update the display name, bio and settings of the connected account.","Get a Mastodon account profile by its ID.": "Get a Mastodon account profile by its ID.",- "Find an account by its handle (username or user@domain).": "Find an account by its handle (username or user@domain).","Search for accounts by name or handle.": "Search for accounts by name or handle.","List the statuses posted by an account.": "List the statuses posted by an account.","List the followers of an account.": "List the followers of an account.",@@ -291,19 +288,13 @@"How long the poll stays open, in seconds. Mastodon accepts 300 (5 minutes) to 2629746 (1 month). Required with Poll Options.": "How long the poll stays open, in seconds. Mastodon accepts 300 (5 minutes) to 2629746 (1 month). Required with Poll Options.","Whether voters may pick more than one option. Leave empty for single choice.": "Whether voters may pick more than one option. Leave empty for single choice.","Optional unique string (for example a UUID). Mastodon keeps it for up to 1 hour and returns the original post instead of creating a duplicate when the same key is sent again.": "Optional unique string (for example a UUID). Mastodon keeps it for up to 1 hour and returns the original post instead of creating a duplicate when the same key is sent again.",- "When to publish, as an ISO 8601 date-time such as 2026-10-01T09:30:00Z. Must be at least 6 minutes in the future.": "When to publish, as an ISO 8601 date-time such as 2026-10-01T09:30:00Z. Must be at least 6 minutes in the future.","Optional unique string (for example a UUID). Mastodon keeps it for up to 1 hour and ignores a duplicate submission with the same key.": "Optional unique string (for example a UUID). Mastodon keeps it for up to 1 hour and ignores a duplicate submission with the same key.",- "Local ID of the status on this server, for example 109372843234737004. Obtain it from a timeline, Create Status or Search.": "Local ID of the status on this server, for example 109372843234737004. Obtain it from a timeline, Create Status or Search.",- "Local ID of your own status to edit. Obtain it from Create Status, Get Status or List Account Statuses.": "Local ID of your own status to edit. Obtain it from Create Status, Get Status or List Account Statuses.","New text of the post. Leave empty to keep the current text.": "New text of the post. Leave empty to keep the current text.",- "New content warning. Leave empty to keep the current one.": "New content warning. Leave empty to keep the current one.","Leave empty to keep the current setting.": "Leave empty to keep the current setting.","New ISO 639-1 language code, for example en. Leave empty to keep the current language.": "New ISO 639-1 language code, for example en. Leave empty to keep the current language.",- "Replaces the attached media with these IDs (from Upload Media or the current media_attachments). Leave empty to keep the current media.": "Replaces the attached media with these IDs (from Upload Media or the current media_attachments). Leave empty to keep the current media.","New poll choices, one per item. Changing them resets all votes. Leave empty to keep the current poll.": "New poll choices, one per item. Changing them resets all votes. Leave empty to keep the current poll.","New poll duration from now, in seconds (300 to 2629746). Leave empty to keep the current closing time.": "New poll duration from now, in seconds (300 to 2629746). Leave empty to keep the current closing time.","Changing this resets all votes. Leave empty to keep the current setting.": "Changing this resets all votes. Leave empty to keep the current setting.",- "Local ID of your own status to delete. Obtain it from Create Status, Get Status or List Account Statuses.": "Local ID of your own status to delete. Obtain it from Create Status, Get Status or List Account Statuses.","Delete the attached media right away instead of keeping it for about 24 hours for reuse. Requires Mastodon 4.4 or later; older servers ignore it.": "Delete the attached media right away instead of keeping it for about 24 hours for reuse. Requires Mastodon 4.4 or later; older servers ignore it.","Local ID of the status whose thread to read. Obtain it from a timeline, Get Status or Search.": "Local ID of the status whose thread to read. Obtain it from a timeline, Get Status or Search.","Local ID of the status. Obtain it from a timeline, Get Status or Search.": "Local ID of the status. Obtain it from a timeline, Get Status or Search.",@@ -311,22 +302,17 @@"Cursor for the next (older) page. Pass the `next_max_id` value from the previous page of this same action. Leave empty for the newest page.": "Cursor for the next (older) page. Pass the `next_max_id` value from the previous page of this same action. Leave empty for the newest page.","Cursor for newer results. Pass the `prev_since_id` value from a previous page of this same action to page back towards newer items.": "Cursor for newer results. Pass the `prev_since_id` value from a previous page of this same action to page back towards newer items.","Local ID of the status on this server, for example 109372843234737004. Obtain it from a timeline, Get Status or Search (use resolve for a status URL from another server).": "Local ID of the status on this server, for example 109372843234737004. Obtain it from a timeline, Get Status or Search (use resolve for a status URL from another server).",- "Local ID of the status to boost. Obtain it from a timeline, Get Status or Search (use resolve for a status URL from another server).": "Local ID of the status to boost. Obtain it from a timeline, Get Status or Search (use resolve for a status URL from another server).","Who sees the boost. Leave empty to use the account default posting privacy.": "Who sees the boost. Leave empty to use the account default posting privacy.","Local ID of your own status. Obtain it from Create Status, Get Status or List Account Statuses.": "Local ID of your own status. Obtain it from Create Status, Get Status or List Account Statuses.","Maximum number of scheduled statuses to return in this page. Defaults to 20, maximum 40.": "Maximum number of scheduled statuses to return in this page. Defaults to 20, maximum 40.","Cursor for the page immediately newer than a previous page. Pass the `prev_min_id` value from a previous page of this same action.": "Cursor for the page immediately newer than a previous page. Pass the `prev_min_id` value from a previous page of this same action.","ID of the scheduled status. Obtain it from Schedule Status or List Scheduled Statuses.": "ID of the scheduled status. Obtain it from Schedule Status or List Scheduled Statuses.",- "New publication time as an ISO 8601 date-time such as 2026-10-01T09:30:00Z. Must be at least 6 minutes in the future.": "New publication time as an ISO 8601 date-time such as 2026-10-01T09:30:00Z. Must be at least 6 minutes in the future.","The image, video or audio file to upload.": "The image, video or audio file to upload.",- "Plain-text description of the media for accessibility (alt text).": "Plain-text description of the media for accessibility (alt text).","Focal point for thumbnail cropping as two comma-separated numbers from -1.0 to 1.0, for example 0.0,0.5.": "Focal point for thumbnail cropping as two comma-separated numbers from -1.0 to 1.0, for example 0.0,0.5.","ID of the unattached media. Obtain it from Upload Media.": "ID of the unattached media. Obtain it from Upload Media.","New plain-text description of the media for accessibility.": "New plain-text description of the media for accessibility.","New focal point as two comma-separated numbers from -1.0 to 1.0, for example 0.0,0.5.": "New focal point as two comma-separated numbers from -1.0 to 1.0, for example 0.0,0.5.","ID of the media attachment. Obtain it from Upload Media.": "ID of the media attachment. Obtain it from Upload Media.",- "New display name shown on the profile.": "New display name shown on the profile.",- "New profile bio text.": "New profile bio text.","Whether new followers must be approved manually. Leave empty to keep the current setting.": "Whether new followers must be approved manually. Leave empty to keep the current setting.","Whether the profile is flagged as an automated (bot) account. Leave empty to keep the current setting.": "Whether the profile is flagged as an automated (bot) account. Leave empty to keep the current setting.","Whether the account is featured in the profile directory. Leave empty to keep the current setting.": "Whether the account is featured in the profile directory. Leave empty to keep the current setting.",@@ -342,7 +328,6 @@"Only statuses using this hashtag, without the # sign, for example mastodon.": "Only statuses using this hashtag, without the # sign, for example mastodon.","Maximum number of statuses to return in this page. Defaults to 20, maximum 40.": "Maximum number of statuses to return in this page. Defaults to 20, maximum 40.","Local account IDs to check, one per item. Obtain them from Lookup Account, Search Accounts or Get Account.": "Local account IDs to check, one per item. Obtain them from Lookup Account, Search Accounts or Get Account.",- "Local ID of the account to follow. Obtain it from Lookup Account, Search Accounts or Search (use resolve for a remote user@domain).": "Local ID of the account to follow. Obtain it from Lookup Account, Search Accounts or Search (use resolve for a remote user@domain).","Whether their boosts appear in your home timeline. Leave empty for the default (yes).": "Whether their boosts appear in your home timeline. Leave empty for the default (yes).","Whether to get a notification for each of their posts. Leave empty for the default (no).": "Whether to get a notification for each of their posts. Leave empty for the default (no).","Only show their posts in these ISO 639-1 languages, one code per item (for example en). Leave empty for all languages.": "Only show their posts in these ISO 639-1 languages, one code per item (for example en). Leave empty for all languages.",@@ -370,7 +355,6 @@"Only return one kind of result. Leave empty for all three.": "Only return one kind of result. Leave empty for all three.","Fetch unknown remote accounts or URLs from their server. Leave empty to resolve automatically when the query is a URL or user@domain handle.": "Fetch unknown remote accounts or URLs from their server. Leave empty to resolve automatically when the query is a URL or user@domain handle.","Only include accounts the connected account follows. Leave empty for no restriction.": "Only include accounts the connected account follows. Leave empty for no restriction.",- "Only return statuses authored by this account (local account ID).": "Only return statuses authored by this account (local account ID).","Leave out hashtags not yet reviewed by moderators. Leave empty for the default (no).": "Leave out hashtags not yet reviewed by moderators. Leave empty for the default (no).","Maximum number of results per type to return in this page. Defaults to 20, maximum 40.": "Maximum number of results per type to return in this page. Defaults to 20, maximum 40.","Number of results to skip, for paging. Only applies when Result Type is set.": "Number of results to skip, for paging. Only applies when Result Type is set.",@@ -442,5 +426,45 @@"New content warning. Leave empty to keep the current one; an existing content warning cannot be removed here.": "New content warning. Leave empty to keep the current one; an existing content warning cannot be removed here.","Replaces the attached media with these IDs (from Upload Media or the current media_attachments). Leave empty to keep the current media; all media cannot be detached here.": "Replaces the attached media with these IDs (from Upload Media or the current media_attachments). Leave empty to keep the current media; all media cannot be detached here.","New display name shown on the profile. Leave empty to keep the current display name.": "New display name shown on the profile. Leave empty to keep the current display name.",- "New profile bio text. Leave empty to keep the current bio.": "New profile bio text. Leave empty to keep the current bio."-}\ No newline at end of file+ "New profile bio text. Leave empty to keep the current bio.": "New profile bio text. Leave empty to keep the current bio.",+ "Post a status to Mastodon, optionally as a reply, with a content warning or with limited visibility.": "Post a status to Mastodon, optionally as a reply, with a content warning or with limited visibility.",+ "Upload an image, video or audio file, then map its Media ID into Media IDs of Post Status, Schedule Status or Edit Status to attach it.": "Upload an image, video or audio file, then map its Media ID into Media IDs of Post Status, Schedule Status or Edit Status to attach it.",+ "Find an account by its handle (username or user@domain) to get its Account ID for Follow Account and other steps.": "Find an account by its handle (username or user@domain) to get its Account ID for Follow Account and other steps.",+ "Reply To (Status ID)": "Reply To (Status ID)",+ "Who can see the post. Leave empty to use the default posting privacy from your Mastodon preferences.": "Who can see the post. Leave empty to use the default posting privacy from your Mastodon preferences.",+ "Optional warning shown in place of the post text until the reader chooses to reveal it, for example \"Spoilers for episode 3\".": "Optional warning shown in place of the post text until the reader chooses to reveal it, for example \"Spoilers for episode 3\".",+ "To post a reply, the ID of the status you are answering: map the Status ID from the New Mention trigger (Related Status > Status ID), from Get Status, or from a previous Post Status step (Status > Status ID). Leave empty for a new post.": "To post a reply, the ID of the status you are answering: map the Status ID from the New Mention trigger (Related Status > Status ID), from Get Status, or from a previous Post Status step (Status > Status ID). Leave empty for a new post.",+ "IDs of media you already uploaded with the Upload Media action, one per item. Most servers allow 4 attachments in total, including the file above. Leave empty if you have none.": "IDs of media you already uploaded with the Upload Media action, one per item. Most servers allow 4 attachments in total, including the file above. Leave empty if you have none.",+ "Hide attached media behind a sensitive-content warning. Leave empty to use your account default.": "Hide attached media behind a sensitive-content warning. Leave empty to use your account default.",+ "When to publish, as a date-time such as 2026-10-01T09:30:00Z. Must be at least 6 minutes in the future (Mastodon requires 5, plus a minute for clock drift).": "When to publish, as a date-time such as 2026-10-01T09:30:00Z. Must be at least 6 minutes in the future (Mastodon requires 5, plus a minute for clock drift).",+ "ID of the status on your server, for example 109372843234737004. Map it from a trigger such as New Mention (Related Status > Status ID), from Post Status, a timeline or Search.": "ID of the status on your server, for example 109372843234737004. Map it from a trigger such as New Mention (Related Status > Status ID), from Post Status, a timeline or Search.",+ "ID of your own status to edit. Map it from a previous Post Status step (Status > Status ID), Create Status, Get Status or List Account Statuses.": "ID of your own status to edit. Map it from a previous Post Status step (Status > Status ID), Create Status, Get Status or List Account Statuses.",+ "ID of your own status to delete. Map it from a previous Post Status step (Status > Status ID), Create Status, Get Status or List Account Statuses.": "ID of your own status to delete. Map it from a previous Post Status step (Status > Status ID), Create Status, Get Status or List Account Statuses.",+ "ID of the status to favourite, for example 109372843234737004. Map it from a trigger such as New Mention (Related Status > Status ID), a timeline, Get Status or Search (Search turns a status URL from another server into an ID).": "ID of the status to favourite, for example 109372843234737004. Map it from a trigger such as New Mention (Related Status > Status ID), a timeline, Get Status or Search (Search turns a status URL from another server into an ID).",+ "ID of the status to boost, for example 109372843234737004. Map it from a trigger such as New Status with Hashtag (Status ID), a timeline, Get Status or Search (Search turns a status URL from another server into an ID).": "ID of the status to boost, for example 109372843234737004. Map it from a trigger such as New Status with Hashtag (Status ID), a timeline, Get Status or Search (Search turns a status URL from another server into an ID).",+ "Describe the media for people using screen readers (alt text), for example \"A cat asleep on a keyboard\".": "Describe the media for people using screen readers (alt text), for example \"A cat asleep on a keyboard\".",+ "ID of the account to follow, for example 109302436954721982 (not the @handle). Map it from Lookup Account (Account ID), from the New Follower trigger (From Account > Account ID) to follow back, or from Search for a user@domain on another server.": "ID of the account to follow, for example 109302436954721982 (not the @handle). Map it from Lookup Account (Account ID), from the New Follower trigger (From Account > Account ID) to follow back, or from Search for a user@domain on another server.",+ "ID of the account to unfollow, for example 109302436954721982 (not the @handle). Map it from Lookup Account (Account ID), Search Accounts, Get Account or Search for a user@domain on another server.": "ID of the account to unfollow, for example 109302436954721982 (not the @handle). Map it from Lookup Account (Account ID), Search Accounts, Get Account or Search for a user@domain on another server.",+ "Only include statuses posted by accounts on your own server.": "Only include statuses posted by accounts on your own server.",+ "Only include statuses posted by accounts on other servers.": "Only include statuses posted by accounts on other servers.",+ "Only include statuses that have images, video or audio attached.": "Only include statuses that have images, video or audio attached.",+ "Only return statuses written by this account. Use the Account ID from Lookup Account, not the @handle.": "Only return statuses written by this account. Use the Account ID from Lookup Account, not the @handle.",+ "New Mention": "New Mention",+ "New Follower": "New Follower",+ "New Status from Account": "New Status from Account",+ "New Status with Hashtag": "New Status with Hashtag",+ "Triggers when someone mentions your account in a post, including replies and direct messages. On mastodon.social and other servers running Mastodon 4.3 or later, direct messages and mentions from accounts you do not follow may be held back by your notification filters (Preferences > Notifications) and will not trigger the flow until you accept them.": "Triggers when someone mentions your account in a post, including replies and direct messages. On mastodon.social and other servers running Mastodon 4.3 or later, direct messages and mentions from accounts you do not follow may be held back by your notification filters (Preferences > Notifications) and will not trigger the flow until you accept them.",+ "Triggers when someone starts following your account. If your account requires follow approval, people appear here only after you accept their request.": "Triggers when someone starts following your account. If your account requires follow approval, people appear here only after you accept their request.",+ "Triggers when a specific account publishes a new post. For accounts on other servers, only posts that reach your server are seen, so following the account makes this reliable.": "Triggers when a specific account publishes a new post. For accounts on other servers, only posts that reach your server are seen, so following the account makes this reliable.",+ "Triggers when a new public post uses a hashtag. Posts from other servers are included once they reach your server.": "Triggers when a new public post uses a hashtag. Posts from other servers are included once they reach your server.",+ "Account": "Account",+ "Skip Replies": "Skip Replies",+ "Skip Boosts": "Skip Boosts",+ "The handle of the account to watch, for example [email protected] (or just Gargron for an account on your own server). An Account ID from Lookup Account also works.": "The handle of the account to watch, for example [email protected] (or just Gargron for an account on your own server). An Account ID from Lookup Account also works.",+ "Do not trigger for replies the account posts to other people.": "Do not trigger for replies the account posts to other people.",+ "Do not trigger when the account boosts someone else's post.": "Do not trigger when the account boosts someone else's post.",+ "The hashtag to watch, without the # sign, for example opensource.": "The hashtag to watch, without the # sign, for example opensource.",+ "Only trigger for posts by accounts on your own server.": "Only trigger for posts by accounts on your own server.",+ "Only trigger for posts that have images, video or audio attached.": "Only trigger for posts that have images, video or audio attached.",+ "New publication time as an ISO 8601 date-time such as 2026-10-01T09:30:00Z. Must be at least 6 minutes in the future.": "New publication time as an ISO 8601 date-time such as 2026-10-01T09:30:00Z. Must be at least 6 minutes in the future."+}diff --git a/packages/pieces/community/mastodon/src/index.ts b/packages/pieces/community/mastodon/src/index.tsindex 4e26d846d5e..3ce77a53219 100644--- a/packages/pieces/community/mastodon/src/index.ts+++ b/packages/pieces/community/mastodon/src/index.ts@@ -90,6 +90,10 @@ import { getTrendingTags } from './lib/actions/get-trending-tags';import { getTrendingStatuses } from './lib/actions/get-trending-statuses';import { getTrendingLinks } from './lib/actions/get-trending-links';import { getInstanceInfo } from './lib/actions/get-instance-info';+import { newMention } from './lib/triggers/new-mention';+import { newFollower } from './lib/triggers/new-follower';+import { newStatusFromAccount } from './lib/triggers/new-status-from-account';+import { newStatusWithHashtag } from './lib/triggers/new-status-with-hashtag';const markdownDescription = `**Base Url**: The base url of your Mastodon instance (e.g \`https://mastodon.social\`)@@ -230,5 +234,5 @@ export const mastodon = createPiece({}),}),],- triggers: [],+ triggers: [newMention, newFollower, newStatusFromAccount, newStatusWithHashtag],});diff --git a/packages/pieces/community/mastodon/src/lib/actions/boost-status.ts b/packages/pieces/community/mastodon/src/lib/actions/boost-status.tsindex 3f05eea728e..136b661eacf 100644--- a/packages/pieces/community/mastodon/src/lib/actions/boost-status.ts+++ b/packages/pieces/community/mastodon/src/lib/actions/boost-status.ts@@ -10,7 +10,7 @@ export const boostStatus = createAction({classification: 'WRITE',displayName: 'Boost Status',description: 'Boost (reblog) a status to your followers.',- audience: 'ai',+ audience: 'both',aiMetadata: {description:'Boosts (reblogs) a status so it appears to the connected account\'s followers and the author is notified. Visibility defaults to the account\'s default posting privacy, not public; set it explicitly to control reach. Boosting an already-boosted status returns the existing boost, so it is safe to retry. Use Unboost Status to undo.',@@ -21,7 +21,7 @@ export const boostStatus = createAction({status_id: Property.ShortText({displayName: 'Status ID',description:- 'Local ID of the status to boost. Obtain it from a timeline, Get Status or Search (use resolve for a status URL from another server).',+ 'ID of the status to boost, for example 109372843234737004. Map it from a trigger such as New Status with Hashtag (Status ID), a timeline, Get Status or Search (Search turns a status URL from another server into an ID).',required: true,}),visibility: Property.StaticDropdown({diff --git a/packages/pieces/community/mastodon/src/lib/actions/delete-status.ts b/packages/pieces/community/mastodon/src/lib/actions/delete-status.tsindex 278e126d71a..242e06787c2 100644--- a/packages/pieces/community/mastodon/src/lib/actions/delete-status.ts+++ b/packages/pieces/community/mastodon/src/lib/actions/delete-status.ts@@ -10,7 +10,7 @@ export const deleteStatus = createAction({classification: 'DESTRUCTIVE',displayName: 'Delete Status',description: 'Permanently delete one of your own statuses.',- audience: 'ai',+ audience: 'both',aiMetadata: {description:'Permanently deletes a status posted by the connected account and returns the deleted status including its source text (useful to redraft). Followers and remote servers may already have received it, so deletion cannot recall copies. Only works on your own posts; repeating the call fails with not found.',@@ -21,7 +21,7 @@ export const deleteStatus = createAction({status_id: Property.ShortText({displayName: 'Status ID',description:- 'Local ID of your own status to delete. Obtain it from Create Status, Get Status or List Account Statuses.',+ 'ID of your own status to delete. Map it from a previous Post Status step (Status > Status ID), Create Status, Get Status or List Account Statuses.',required: true,}),delete_media: Property.Checkbox({diff --git a/packages/pieces/community/mastodon/src/lib/actions/edit-status.ts b/packages/pieces/community/mastodon/src/lib/actions/edit-status.tsindex a58a04f3646..292cf135153 100644--- a/packages/pieces/community/mastodon/src/lib/actions/edit-status.ts+++ b/packages/pieces/community/mastodon/src/lib/actions/edit-status.ts@@ -18,7 +18,7 @@ export const editStatus = createAction({classification: 'WRITE',displayName: 'Edit Status',description: 'Edit the text, content warning, media or poll of one of your statuses.',- audience: 'ai',+ audience: 'both',aiMetadata: {description:'Edits a status posted by the connected account; only the fields you set change, everything else (text, content warning, sensitivity, media, poll) is carried over from the current post. An existing poll keeps its votes when you leave the poll fields empty, but its hidden-totals setting is reset to visible, and the edit is refused if the poll has ended or closes in under 5 minutes. Setting Poll Options or Allow Multiple Choices to different values resets all votes. Media IDs replace the attached media set. It cannot remove an existing content warning or detach all media; to do that, delete the status and create it again.',@@ -29,7 +29,7 @@ export const editStatus = createAction({status_id: Property.ShortText({displayName: 'Status ID',description:- 'Local ID of your own status to edit. Obtain it from Create Status, Get Status or List Account Statuses.',+ 'ID of your own status to edit. Map it from a previous Post Status step (Status > Status ID), Create Status, Get Status or List Account Statuses.',required: true,}),status: Property.LongText({diff --git a/packages/pieces/community/mastodon/src/lib/actions/favourite-status.ts b/packages/pieces/community/mastodon/src/lib/actions/favourite-status.tsindex 69dc278c455..93469bfd3b3 100644--- a/packages/pieces/community/mastodon/src/lib/actions/favourite-status.ts+++ b/packages/pieces/community/mastodon/src/lib/actions/favourite-status.ts@@ -10,7 +10,7 @@ export const favouriteStatus = createAction({classification: 'WRITE',displayName: 'Favourite Status',description: 'Add a status to your favourites.',- audience: 'ai',+ audience: 'both',aiMetadata: {description:'Favourites (likes) a status as the connected account; the author is notified. Use Bookmark Status to save privately instead. Favouriting an already-favourited status changes nothing, so it is safe to retry. Returns the updated status.',@@ -21,7 +21,7 @@ export const favouriteStatus = createAction({status_id: Property.ShortText({displayName: 'Status ID',description:- 'Local ID of the status on this server, for example 109372843234737004. Obtain it from a timeline, Get Status or Search (use resolve for a status URL from another server).',+ 'ID of the status to favourite, for example 109372843234737004. Map it from a trigger such as New Mention (Related Status > Status ID), a timeline, Get Status or Search (Search turns a status URL from another server into an ID).',required: true,}),},diff --git a/packages/pieces/community/mastodon/src/lib/actions/follow-account.ts b/packages/pieces/community/mastodon/src/lib/actions/follow-account.tsindex f9abeb091e3..cde4b00b463 100644--- a/packages/pieces/community/mastodon/src/lib/actions/follow-account.ts+++ b/packages/pieces/community/mastodon/src/lib/actions/follow-account.ts@@ -15,7 +15,7 @@ export const followAccount = createAction({classification: 'WRITE',displayName: 'Follow Account',description: 'Follow an account, or send a follow request to a locked account.',- audience: 'ai',+ audience: 'both',aiMetadata: {description:'Follows an account as the connected account (for a locked account this sends a follow request); the target is notified. Calling it again on an account you already follow does not error and just updates the boost, notification and language options. Returns the relationship.',@@ -26,7 +26,7 @@ export const followAccount = createAction({account_id: Property.ShortText({displayName: 'Account ID',description:- 'Local ID of the account to follow. Obtain it from Lookup Account, Search Accounts or Search (use resolve for a remote user@domain).',+ 'ID of the account to follow, for example 109302436954721982 (not the @handle). Map it from Lookup Account (Account ID), from the New Follower trigger (From Account > Account ID) to follow back, or from Search for a user@domain on another server.',required: true,}),reblogs: mastodonProps.optionalBoolean({diff --git a/packages/pieces/community/mastodon/src/lib/actions/get-hashtag-timeline.ts b/packages/pieces/community/mastodon/src/lib/actions/get-hashtag-timeline.tsindex b2a80a34909..e9bc8facaa3 100644--- a/packages/pieces/community/mastodon/src/lib/actions/get-hashtag-timeline.ts+++ b/packages/pieces/community/mastodon/src/lib/actions/get-hashtag-timeline.ts@@ -15,7 +15,7 @@ export const getHashtagTimeline = createAction({classification: 'SEARCH',displayName: 'Get Hashtag Timeline',description: 'Get recent public statuses that use a hashtag.',- audience: 'ai',+ audience: 'both',aiMetadata: {description:'Returns one page of recent public statuses using a hashtag, newest first, with cursors for further pages; combine extra tags with any, all or none. Use Search for free-text queries. Read-only and safe to retry.',@@ -45,16 +45,19 @@ export const getHashtagTimeline = createAction({}),local: Property.Checkbox({displayName: 'Only Local Statuses',+ description: 'Only include statuses posted by accounts on your own server.',required: false,defaultValue: false,}),remote: Property.Checkbox({displayName: 'Only Remote Statuses',+ description: 'Only include statuses posted by accounts on other servers.',required: false,defaultValue: false,}),only_media: Property.Checkbox({displayName: 'Only Statuses With Media',+ description: 'Only include statuses that have images, video or audio attached.',required: false,defaultValue: false,}),diff --git a/packages/pieces/community/mastodon/src/lib/actions/get-status.ts b/packages/pieces/community/mastodon/src/lib/actions/get-status.tsindex 3527030add2..0e090e390d1 100644--- a/packages/pieces/community/mastodon/src/lib/actions/get-status.ts+++ b/packages/pieces/community/mastodon/src/lib/actions/get-status.ts@@ -10,7 +10,7 @@ export const getStatus = createAction({classification: 'READ',displayName: 'Get Status',description: 'Get a single status by its ID.',- audience: 'ai',+ audience: 'both',aiMetadata: {description:'Fetches one status by its local ID, including text, author, counts, media attachments and poll. Use it to read a post before replying, editing or engaging with it; for a status URL from another server, first import it with Search (resolve) to get a local ID. Read-only and safe to retry.',@@ -21,7 +21,7 @@ export const getStatus = createAction({status_id: Property.ShortText({displayName: 'Status ID',description:- 'Local ID of the status on this server, for example 109372843234737004. Obtain it from a timeline, Create Status or Search.',+ 'ID of the status on your server, for example 109372843234737004. Map it from a trigger such as New Mention (Related Status > Status ID), from Post Status, a timeline or Search.',required: true,}),},diff --git a/packages/pieces/community/mastodon/src/lib/actions/lookup-account.ts b/packages/pieces/community/mastodon/src/lib/actions/lookup-account.tsindex 77db8b091e4..1e184508b57 100644--- a/packages/pieces/community/mastodon/src/lib/actions/lookup-account.ts+++ b/packages/pieces/community/mastodon/src/lib/actions/lookup-account.ts@@ -9,8 +9,9 @@ export const lookupAccount = createAction({name: 'lookup_account',classification: 'READ',displayName: 'Lookup Account',- description: 'Find an account by its handle (username or user@domain).',- audience: 'ai',+ description:+ 'Find an account by its handle (username or user@domain) to get its Account ID for Follow Account and other steps.',+ audience: 'both',aiMetadata: {description:'Resolves a handle such as Gargron or [email protected] to the account profile and local ID, without a fuzzy search. Only finds accounts already known to this server; for a remote user@domain that 404s, use Search with resolve=true (type accounts). Read-only and safe to retry.',diff --git a/packages/pieces/community/mastodon/src/lib/actions/post-status.ts b/packages/pieces/community/mastodon/src/lib/actions/post-status.tsindex 4325528a350..ab2d9b639dc 100644--- a/packages/pieces/community/mastodon/src/lib/actions/post-status.ts+++ b/packages/pieces/community/mastodon/src/lib/actions/post-status.ts@@ -6,6 +6,7 @@ import {HttpMethod,} from '@activepieces/pieces-common';import { mastodonAuth } from '../..';+import { mastodonProps, mastodonUtils } from '../common/client';import { postStatusOutputSchema } from '../output-schemas';const uploadMedia = async (media: ApFile, baseUrl: string, token: string) => {@@ -33,9 +34,10 @@ export const postStatus = createAction({name: 'post_status',classification: 'WRITE',displayName: 'Post Status',- description: 'Post a status to Mastodon',+ description:+ 'Post a status to Mastodon, optionally as a reply, with a content warning or with limited visibility.',audience: 'human',- aiMetadata: { description: 'Publishes a new status (toot) to a Mastodon instance from the authenticated account, optionally attaching a single media file uploaded alongside the post. Use to broadcast a message or share content on Mastodon. Requires status text; not idempotent — each call creates a separate post.', idempotent: false },+ aiMetadata: { description: 'Publishes a new status (toot) to a Mastodon instance from the authenticated account, optionally attaching a media file uploaded alongside the post and media already uploaded with Upload Media, with optional visibility, content warning, reply target and sensitive flag. Use to broadcast a message or share content on Mastodon. Requires status text; not idempotent — each call creates a separate post.', idempotent: false },outputSchema: postStatusOutputSchema,props: {status: Property.LongText({@@ -48,18 +50,56 @@ export const postStatus = createAction({description: 'The media attachment for your status',required: false,}),+ visibility: Property.StaticDropdown({+ displayName: 'Visibility',+ description:+ 'Who can see the post. Leave empty to use the default posting privacy from your Mastodon preferences.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Public', value: 'public' },+ { label: 'Unlisted (public, hidden from public timelines)', value: 'unlisted' },+ { label: 'Followers only', value: 'private' },+ { label: 'Direct (mentioned accounts only)', value: 'direct' },+ ],+ },+ }),+ spoiler_text: Property.ShortText({+ displayName: 'Content Warning',+ description:+ 'Optional warning shown in place of the post text until the reader chooses to reveal it, for example "Spoilers for episode 3".',+ required: false,+ }),+ in_reply_to_id: Property.ShortText({+ displayName: 'Reply To (Status ID)',+ description:+ 'To post a reply, the ID of the status you are answering: map the Status ID from the New Mention trigger (Related Status > Status ID), from Get Status, or from a previous Post Status step (Status > Status ID). Leave empty for a new post.',+ required: false,+ }),+ media_ids: Property.Array({+ displayName: 'Media IDs',+ description:+ 'IDs of media you already uploaded with the Upload Media action, one per item. Most servers allow 4 attachments in total, including the file above. Leave empty if you have none.',+ required: false,+ }),+ sensitive: mastodonProps.optionalBoolean({+ displayName: 'Mark Media as Sensitive',+ description:+ 'Hide attached media behind a sensitive-content warning. Leave empty to use your account default.',+ }),},async run(context) {const token = context.auth.props.access_token;- const status = context.propsValue.status;- const media = context.propsValue.media;- // Remove trailing slash from base_url+ const { status, media, visibility, spoiler_text, in_reply_to_id, media_ids, sensitive } =+ context.propsValue;const baseUrl = context.auth.props.base_url.replace(/\/$/, '');- let mediaId: string | undefined = undefined;- if (media) {- mediaId = await uploadMedia(media, baseUrl, token);- }+ const mediaId = media ? await uploadMedia(media, baseUrl, token) : undefined;+ const mediaIds = [+ ...(mastodonUtils.toStringArray(media_ids) ?? []),+ ...(mediaId ? [mediaId] : []),+ ];return await httpClient.sendRequest({url: `${baseUrl}/api/v1/statuses`,@@ -70,7 +110,11 @@ export const postStatus = createAction({},body: {status,- ...(mediaId ? { media_ids: [mediaId] } : {}),+ ...(mastodonUtils.hasValue(visibility) ? { visibility } : {}),+ ...(mastodonUtils.hasValue(spoiler_text) ? { spoiler_text } : {}),+ ...(mastodonUtils.hasValue(in_reply_to_id) ? { in_reply_to_id } : {}),+ ...(typeof sensitive === 'boolean' ? { sensitive } : {}),+ ...(mediaIds.length > 0 ? { media_ids: mediaIds } : {}),},});},diff --git a/packages/pieces/community/mastodon/src/lib/actions/schedule-status.ts b/packages/pieces/community/mastodon/src/lib/actions/schedule-status.tsindex f65b65feb4d..6fbeaf51459 100644--- a/packages/pieces/community/mastodon/src/lib/actions/schedule-status.ts+++ b/packages/pieces/community/mastodon/src/lib/actions/schedule-status.ts@@ -15,10 +15,10 @@ export const scheduleStatus = createAction({classification: 'WRITE',displayName: 'Schedule Status',description: 'Schedule a status to be published automatically at a future time.',- audience: 'ai',+ audience: 'both',aiMetadata: {description:- 'Schedules a status to be published by Mastodon at a future date-time (at least 6 minutes ahead) and returns the scheduled status, not a published post. Use Create Status to post immediately; manage the result with List Scheduled Statuses, Reschedule Status or Cancel Scheduled Status. Each call schedules another post.',+ 'Schedules a status to be published by Mastodon at a future date-time (at least 5 minutes ahead) and returns the scheduled status, not a published post. Use Create Status to post immediately; manage the result with List Scheduled Statuses, Reschedule Status or Cancel Scheduled Status. Each call schedules another post.',idempotent: false,},outputSchema: scheduledStatusOutputSchema,@@ -26,7 +26,7 @@ export const scheduleStatus = createAction({scheduled_at: Property.DateTime({displayName: 'Scheduled At',description:- 'When to publish, as an ISO 8601 date-time such as 2026-10-01T09:30:00Z. Must be at least 6 minutes in the future.',+ 'When to publish, as a date-time such as 2026-10-01T09:30:00Z. Must be at least 6 minutes in the future (Mastodon requires 5, plus a minute for clock drift).',required: true,}),...mastodonProps.compose(),diff --git a/packages/pieces/community/mastodon/src/lib/actions/search.ts b/packages/pieces/community/mastodon/src/lib/actions/search.tsindex dfa3256e7bb..2959c4d582b 100644--- a/packages/pieces/community/mastodon/src/lib/actions/search.ts+++ b/packages/pieces/community/mastodon/src/lib/actions/search.ts@@ -13,7 +13,7 @@ export const search = createAction({classification: 'SEARCH',displayName: 'Search',description: 'Search for accounts, statuses and hashtags.',- audience: 'ai',+ audience: 'both',aiMetadata: {description:'Searches accounts, statuses and hashtags on the connected server. It is also how to import remote content: a status URL or a user@domain handle with resolve=true fetches it from the other server and returns its local ID for other actions; resolve is turned on automatically for such queries unless you set it. Full-text status search depends on the server and may only match your own posts. Read-only and safe to retry.',@@ -51,7 +51,8 @@ export const search = createAction({}),account_id: Property.ShortText({displayName: 'Statuses By Account ID',- description: 'Only return statuses authored by this account (local account ID).',+ description:+ 'Only return statuses written by this account. Use the Account ID from Lookup Account, not the @handle.',required: false,}),exclude_unreviewed: mastodonProps.optionalBoolean({diff --git a/packages/pieces/community/mastodon/src/lib/actions/unfollow-account.ts b/packages/pieces/community/mastodon/src/lib/actions/unfollow-account.tsindex 071809a6a1d..792a37700e9 100644--- a/packages/pieces/community/mastodon/src/lib/actions/unfollow-account.ts+++ b/packages/pieces/community/mastodon/src/lib/actions/unfollow-account.ts@@ -10,7 +10,7 @@ export const unfollowAccount = createAction({classification: 'WRITE',displayName: 'Unfollow Account',description: 'Stop following an account.',- audience: 'ai',+ audience: 'both',aiMetadata: {description:'Unfollows an account (or withdraws a pending follow request) as the connected account. Safe to retry. Returns the updated relationship.',@@ -21,7 +21,7 @@ export const unfollowAccount = createAction({account_id: Property.ShortText({displayName: 'Account ID',description:- 'Local ID of the account on this server, for example 109302436954721982. Obtain it from Lookup Account, Search Accounts, Get Account or Search (use resolve for a remote user@domain).',+ 'ID of the account to unfollow, for example 109302436954721982 (not the @handle). Map it from Lookup Account (Account ID), Search Accounts, Get Account or Search for a user@domain on another server.',required: true,}),},diff --git a/packages/pieces/community/mastodon/src/lib/actions/upload-media.ts b/packages/pieces/community/mastodon/src/lib/actions/upload-media.tsindex ad6ff2b08e4..26fc6f53f34 100644--- a/packages/pieces/community/mastodon/src/lib/actions/upload-media.ts+++ b/packages/pieces/community/mastodon/src/lib/actions/upload-media.ts@@ -10,8 +10,9 @@ export const uploadMedia = createAction({name: 'upload_media',classification: 'WRITE',displayName: 'Upload Media',- description: 'Upload an image, video or audio file to attach to a status.',- audience: 'ai',+ description:+ 'Upload an image, video or audio file, then map its Media ID into Media IDs of Post Status, Schedule Status or Edit Status to attach it.',+ audience: 'both',aiMetadata: {description:'Uploads a media file and returns its ID to pass as Media IDs to Create Status, Schedule Status or Edit Status. Large video and audio are processed asynchronously: when processing is true the url is still null, so call Get Media until url is non-null before attaching it. Unattached uploads expire after a while. Each call uploads a new file.',@@ -26,7 +27,7 @@ export const uploadMedia = createAction({}),description: Property.LongText({displayName: 'Alt Text',- description: 'Plain-text description of the media for accessibility (alt text).',+ description: 'Describe the media for people using screen readers (alt text), for example "A cat asleep on a keyboard".',required: false,}),focus: Property.ShortText({diff --git a/packages/pieces/community/mastodon/src/lib/common/client.ts b/packages/pieces/community/mastodon/src/lib/common/client.tsindex 4caf24d984a..01c1c3a79ae 100644--- a/packages/pieces/community/mastodon/src/lib/common/client.ts+++ b/packages/pieces/community/mastodon/src/lib/common/client.ts@@ -227,17 +227,43 @@ async function requestPage<T>(params: MastodonRequestParams): Promise<MastodonPa};}-function toStringArray(value: unknown[] | undefined): string[] | undefined {- if (value === undefined) {+function toStringArray(value: unknown): string[] | undefined {+ const list = toList(value);+ if (list === undefined) {return undefined;}- const items = value+ const items = list.filter((item) => typeof item === 'string' || typeof item === 'number').map((item) => String(item).trim()).filter((item) => item !== '');return items.length === 0 ? undefined : items;}+function toList(value: unknown): unknown[] | undefined {+ if (Array.isArray(value)) {+ return value;+ }+ if (typeof value !== 'string' || value.trim() === '') {+ return undefined;+ }+ const trimmed = value.trim();+ if (trimmed.startsWith('[')) {+ const parsed = safeParseJson(trimmed);+ if (Array.isArray(parsed)) {+ return parsed;+ }+ }+ return [trimmed];+}++function safeParseJson(value: string): unknown {+ try {+ return JSON.parse(value);+ } catch {+ return undefined;+ }+}+function hasValue(value: unknown): boolean {return value !== undefined && value !== null && value !== '';}diff --git a/packages/pieces/community/mastodon/src/lib/common/polling.ts b/packages/pieces/community/mastodon/src/lib/common/polling.tsnew file mode 100644index 00000000000..5bf81af66af--- /dev/null+++ b/packages/pieces/community/mastodon/src/lib/common/polling.ts@@ -0,0 +1,219 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { tryCatch } from '@activepieces/pieces-framework';+import {+ MastodonApiError,+ MastodonConnection,+ MastodonEntity,+ MastodonQuery,+ mastodonClient,+} from './client';++const POLL_PAGE_LIMIT = 40;+const NUMERIC_ID_PATTERN = /^\d+$/;++async function fetchNewItems({+ auth,+ path,+ query,+ lastItemId,+ operation,+ scope,+}: {+ auth: MastodonConnection;+ path: string;+ query?: MastodonQuery;+ lastItemId: unknown;+ operation: string;+ scope: string;+}): Promise<PolledItem[]> {+ const page = await mastodonClient.requestPage<MastodonEntity>({+ auth,+ method: HttpMethod.GET,+ path,+ operation,+ scope,+ query: {+ ...query,+ limit: POLL_PAGE_LIMIT,+ min_id: typeof lastItemId === 'string' && lastItemId !== '' ? lastItemId : undefined,+ },+ });+ return page.items+ .filter(hasStringId)+ .sort((left, right) => compareIdsDescending({ left: left.id, right: right.id }))+ .map((item) => ({ id: item.id, data: item }));+}++async function resolveAccountId({+ auth,+ account,+ operation,+}: {+ auth: MastodonConnection;+ account: string;+ operation: string;+}): Promise<string> {+ const handle = account.trim().replace(/^@/, '');+ if (handle === '') {+ throw new Error('Enter the account handle (for example [email protected]) or its Account ID.');+ }+ if (NUMERIC_ID_PATTERN.test(handle)) {+ return handle;+ }+ const lookup = await tryCatch(() =>+ mastodonClient.request<MastodonEntity>({+ auth,+ method: HttpMethod.GET,+ path: '/api/v1/accounts/lookup',+ operation,+ scope: 'read:accounts',+ query: { acct: handle },+ })+ );+ if (lookup.error === null) {+ return readAccountId({ account: lookup.data, handle });+ }+ if (!(lookup.error instanceof MastodonApiError) || lookup.error.status !== 404) {+ throw lookup.error;+ }+ const searchResult = await mastodonClient.request<{ accounts?: MastodonEntity[] }>({+ auth,+ method: HttpMethod.GET,+ path: '/api/v2/search',+ operation,+ scope: 'read:search',+ query: { q: handle, type: 'accounts', resolve: true, limit: 5 },+ });+ const match = (searchResult.accounts ?? []).find((candidate) =>+ matchesHandle({ candidate, handle, baseUrl: auth.base_url })+ );+ if (match === undefined) {+ throw new Error(+ `Mastodon found no account for "${handle}". Check the spelling; for an account on another server use the full handle, for example [email protected].`+ );+ }+ return readAccountId({ account: match, handle });+}++function encodeAccountCursor({+ auth,+ account,+ accountId,+ statusId,+}: {+ auth: MastodonConnection;+ account: string;+ accountId: string;+ statusId: string;+}): string {+ return JSON.stringify({ server: normalizeServer(auth), handle: normalizeHandle(account), account_id: accountId, status_id: statusId });+}++function decodeAccountCursor({+ auth,+ account,+ cursor,+}: {+ auth: MastodonConnection;+ account: string;+ cursor: unknown;+}): AccountCursor {+ if (cursor === null || cursor === undefined) {+ return { kind: 'none' };+ }+ const parsed = typeof cursor === 'string' ? tryParseJson(cursor) : null;+ if (+ !isRecord(parsed) ||+ parsed['server'] !== normalizeServer(auth) ||+ parsed['handle'] !== normalizeHandle(account) ||+ typeof parsed['account_id'] !== 'string' ||+ typeof parsed['status_id'] !== 'string'+ ) {+ return { kind: 'other_account' };+ }+ return { kind: 'same_account', accountId: parsed['account_id'], statusId: parsed['status_id'] };+}++function tryParseJson(value: string): unknown {+ try {+ return JSON.parse(value);+ } catch {+ return null;+ }+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function normalizeServer(auth: MastodonConnection): string {+ return auth.base_url.trim().replace(/\/+$/, '').toLowerCase();+}++function normalizeHandle(account: string): string {+ return account.trim().replace(/^@/, '').toLowerCase();+}++function hasStringId(item: MastodonEntity): item is MastodonEntity & { id: string } {+ return typeof item['id'] === 'string' && item['id'] !== '';+}++function compareIdsDescending({ left, right }: { left: string; right: string }): number {+ if (left.length !== right.length) {+ return right.length - left.length;+ }+ if (left === right) {+ return 0;+ }+ return left < right ? 1 : -1;+}++function readAccountId({ account, handle }: { account: MastodonEntity; handle: string }): string {+ const id = account['id'];+ if (typeof id !== 'string' || id === '') {+ throw new Error(`Mastodon returned no Account ID for "${handle}".`);+ }+ return id;+}++function matchesHandle({+ candidate,+ handle,+ baseUrl,+}: {+ candidate: MastodonEntity;+ handle: string;+ baseUrl: string;+}): boolean {+ const acct = candidate['acct'];+ if (typeof acct !== 'string') {+ return false;+ }+ const wanted = handle.toLowerCase();+ const found = acct.toLowerCase();+ if (found === wanted) {+ return true;+ }+ const host = readHost({ baseUrl });+ return host !== null && `${found}@${host}` === wanted;+}++function readHost({ baseUrl }: { baseUrl: string }): string | null {+ try {+ return new URL(baseUrl).host.toLowerCase();+ } catch {+ return null;+ }+}++export const mastodonPolling = { fetchNewItems, resolveAccountId, encodeAccountCursor, decodeAccountCursor };++export type PolledItem = {+ id: string;+ data: MastodonEntity;+};++type AccountCursor =+ | { kind: 'none' }+ | { kind: 'other_account' }+ | { kind: 'same_account'; accountId: string; statusId: string };diff --git a/packages/pieces/community/mastodon/src/lib/common/sample-data.ts b/packages/pieces/community/mastodon/src/lib/common/sample-data.tsnew file mode 100644index 00000000000..13c3aecc395--- /dev/null+++ b/packages/pieces/community/mastodon/src/lib/common/sample-data.ts@@ -0,0 +1,83 @@+const sampleAccount = {+ id: '109302436954721982',+ username: 'alice',+ acct: '[email protected]',+ display_name: 'Alice Martin',+ locked: false,+ bot: false,+ discoverable: true,+ indexable: true,+ group: false,+ created_at: '2022-11-08T00:00:00.000Z',+ note: '<p>Open-source maintainer. Coffee, bikes and automation.</p>',+ url: 'https://fosstodon.org/@alice',+ uri: 'https://fosstodon.org/users/alice',+ avatar: 'https://files.mastodon.social/cache/accounts/avatars/109/302/436/954/721/982/original/avatar.png',+ avatar_static: 'https://files.mastodon.social/cache/accounts/avatars/109/302/436/954/721/982/original/avatar.png',+ header: 'https://mastodon.social/headers/original/missing.png',+ header_static: 'https://mastodon.social/headers/original/missing.png',+ followers_count: 312,+ following_count: 180,+ statuses_count: 1024,+ last_status_at: '2026-09-23',+ emojis: [],+ fields: [],+};++const sampleStatus = {+ id: '117322188854695939',+ created_at: '2026-09-23T20:15:32.088Z',+ in_reply_to_id: null,+ in_reply_to_account_id: null,+ sensitive: false,+ spoiler_text: '',+ visibility: 'public',+ language: 'en',+ uri: 'https://fosstodon.org/users/alice/statuses/113208846513722012',+ url: 'https://fosstodon.org/@alice/113208846513722012',+ replies_count: 2,+ reblogs_count: 5,+ favourites_count: 14,+ edited_at: null,+ favourited: false,+ reblogged: false,+ muted: false,+ bookmarked: false,+ content:+ '<p>Just shipped a new release of our automation toolkit <a href="https://mastodon.social/tags/opensource" class="mention hashtag" rel="tag">#<span>opensource</span></a> <span class="h-card"><a href="https://mastodon.social/@example" class="u-url mention">@<span>example</span></a></span></p>',+ filtered: [],+ reblog: null,+ account: sampleAccount,+ media_attachments: [],+ mentions: [+ {+ id: '117320753014121404',+ username: 'example',+ url: 'https://mastodon.social/@example',+ acct: 'example',+ },+ ],+ tags: [{ name: 'opensource', url: 'https://mastodon.social/tags/opensource' }],+ emojis: [],+ card: null,+ poll: null,+};++export const mastodonSampleData = {+ status: sampleStatus,+ mentionNotification: {+ id: '622629923',+ type: 'mention',+ created_at: '2026-09-23T20:15:32.409Z',+ group_key: 'ungrouped-622629923',+ account: sampleAccount,+ status: sampleStatus,+ },+ followNotification: {+ id: '622629915',+ type: 'follow',+ created_at: '2026-09-23T20:15:30.346Z',+ group_key: 'follow-497276',+ account: sampleAccount,+ },+};diff --git a/packages/pieces/community/mastodon/src/lib/output-schemas.ts b/packages/pieces/community/mastodon/src/lib/output-schemas.tsindex a74afbe7b1b..e563521ca16 100644--- a/packages/pieces/community/mastodon/src/lib/output-schemas.ts+++ b/packages/pieces/community/mastodon/src/lib/output-schemas.ts@@ -623,6 +623,10 @@ export const mutedAccountPageOutputSchema: OutputSchema = pageSchema({export const notificationOutputSchema: OutputSchema = { fields: notificationFields };+export const followNotificationOutputSchema: OutputSchema = {+ fields: notificationFields.filter((field) => field.key !== 'status'),+};+export const notificationPageOutputSchema: OutputSchema = pageSchema({itemsKey: 'notifications',label: 'Notifications',diff --git a/packages/pieces/community/mastodon/src/lib/triggers/new-follower.ts b/packages/pieces/community/mastodon/src/lib/triggers/new-follower.tsnew file mode 100644index 00000000000..473181e7c15--- /dev/null+++ b/packages/pieces/community/mastodon/src/lib/triggers/new-follower.ts@@ -0,0 +1,52 @@+import {+ AppConnectionValueForAuthProperty,+ createTrigger,+ TriggerStrategy,+} from '@activepieces/pieces-framework';+import { DedupeStrategy, Polling, pollingHelper } from '@activepieces/pieces-common';+import { mastodonAuth } from '../..';+import { mastodonPolling } from '../common/polling';+import { mastodonSampleData } from '../common/sample-data';+import { followNotificationOutputSchema } from '../output-schemas';++const polling: Polling<AppConnectionValueForAuthProperty<typeof mastodonAuth>, Record<string, never>> = {+ strategy: DedupeStrategy.LAST_ITEM,+ items: async ({ auth, lastItemId }) =>+ mastodonPolling.fetchNewItems({+ auth: auth.props,+ path: '/api/v1/notifications',+ query: { types: ['follow'] },+ lastItemId,+ operation: 'New Follower',+ scope: 'read:notifications',+ }),+};++export const newFollower = createTrigger({+ auth: mastodonAuth,+ name: 'new_follower',+ classification: 'READ',+ displayName: 'New Follower',+ description:+ 'Triggers when someone starts following your account. If your account requires follow approval, people appear here only after you accept their request.',+ aiMetadata: {+ description:+ 'Fires once per new follow notification of the connected account; the payload is the notification, and its account field is the new follower (use its id with Follow Account to follow back). Pending follow requests on a locked account do not fire until accepted.',+ },+ props: {},+ sampleData: mastodonSampleData.followNotification,+ outputSchema: followNotificationOutputSchema,+ type: TriggerStrategy.POLLING,+ async test(context) {+ return pollingHelper.test(polling, context);+ },+ async onEnable(context) {+ await pollingHelper.onEnable(polling, context);+ },+ async onDisable(context) {+ await pollingHelper.onDisable(polling, context);+ },+ async run(context) {+ return pollingHelper.poll(polling, context);+ },+});diff --git a/packages/pieces/community/mastodon/src/lib/triggers/new-mention.ts b/packages/pieces/community/mastodon/src/lib/triggers/new-mention.tsnew file mode 100644index 00000000000..aee6bb0677d--- /dev/null+++ b/packages/pieces/community/mastodon/src/lib/triggers/new-mention.ts@@ -0,0 +1,52 @@+import {+ AppConnectionValueForAuthProperty,+ createTrigger,+ TriggerStrategy,+} from '@activepieces/pieces-framework';+import { DedupeStrategy, Polling, pollingHelper } from '@activepieces/pieces-common';+import { mastodonAuth } from '../..';+import { mastodonPolling } from '../common/polling';+import { mastodonSampleData } from '../common/sample-data';+import { notificationOutputSchema } from '../output-schemas';++const polling: Polling<AppConnectionValueForAuthProperty<typeof mastodonAuth>, Record<string, never>> = {+ strategy: DedupeStrategy.LAST_ITEM,+ items: async ({ auth, lastItemId }) =>+ mastodonPolling.fetchNewItems({+ auth: auth.props,+ path: '/api/v1/notifications',+ query: { types: ['mention'] },+ lastItemId,+ operation: 'New Mention',+ scope: 'read:notifications',+ }),+};++export const newMention = createTrigger({+ auth: mastodonAuth,+ name: 'new_mention',+ classification: 'READ',+ displayName: 'New Mention',+ description:+ 'Triggers when someone mentions your account in a post, including replies and direct messages. On mastodon.social and other servers running Mastodon 4.3 or later, direct messages and mentions from accounts you do not follow may be held back by your notification filters (Preferences > Notifications) and will not trigger the flow until you accept them.',+ aiMetadata: {+ description:+ 'Fires once per new mention notification of the connected account (a post, reply or direct message that @mentions it); the payload is the notification with the mentioning account and the full status. Mentions filtered by the account\'s notification policy (by default, private mentions from accounts it does not follow on Mastodon 4.3+) do not fire until accepted.',+ },+ props: {},+ sampleData: mastodonSampleData.mentionNotification,+ outputSchema: notificationOutputSchema,+ type: TriggerStrategy.POLLING,+ async test(context) {+ return pollingHelper.test(polling, context);+ },+ async onEnable(context) {+ await pollingHelper.onEnable(polling, context);+ },+ async onDisable(context) {+ await pollingHelper.onDisable(polling, context);+ },+ async run(context) {+ return pollingHelper.poll(polling, context);+ },+});diff --git a/packages/pieces/community/mastodon/src/lib/triggers/new-status-from-account.ts b/packages/pieces/community/mastodon/src/lib/triggers/new-status-from-account.tsnew file mode 100644index 00000000000..50a6673c28b--- /dev/null+++ b/packages/pieces/community/mastodon/src/lib/triggers/new-status-from-account.ts@@ -0,0 +1,119 @@+import {+ AppConnectionValueForAuthProperty,+ createTrigger,+ Property,+ StaticPropsValue,+ TriggerStrategy,+ tryCatch,+} from '@activepieces/pieces-framework';+import { DedupeStrategy, Polling, pollingHelper } from '@activepieces/pieces-common';+import { mastodonAuth } from '../..';+import { MastodonApiError } from '../common/client';+import { mastodonPolling } from '../common/polling';+import { mastodonSampleData } from '../common/sample-data';+import { statusOutputSchema } from '../output-schemas';++const props = {+ account: Property.ShortText({+ displayName: 'Account',+ description:+ 'The handle of the account to watch, for example [email protected] (or just Gargron for an account on your own server). An Account ID from Lookup Account also works.',+ required: true,+ }),+ exclude_replies: Property.Checkbox({+ displayName: 'Skip Replies',+ description: 'Do not trigger for replies the account posts to other people.',+ required: false,+ defaultValue: false,+ }),+ exclude_reblogs: Property.Checkbox({+ displayName: 'Skip Boosts',+ description: 'Do not trigger when the account boosts someone else\'s post.',+ required: false,+ defaultValue: false,+ }),+};++const polling: Polling<+ AppConnectionValueForAuthProperty<typeof mastodonAuth>,+ StaticPropsValue<typeof props>+> = {+ strategy: DedupeStrategy.LAST_ITEM,+ items: async ({ auth, store, propsValue, lastItemId }) => {+ const fetchStatuses = async ({ accountId, minId }: { accountId: string; minId: string | null }) => {+ const items = await mastodonPolling.fetchNewItems({+ auth: auth.props,+ path: `/api/v1/accounts/${encodeURIComponent(accountId)}/statuses`,+ query: {+ exclude_replies: propsValue.exclude_replies === true ? true : undefined,+ exclude_reblogs: propsValue.exclude_reblogs === true ? true : undefined,+ },+ lastItemId: minId,+ operation: 'New Status from Account',+ scope: 'read:statuses',+ });+ return items.map((item) => ({+ id: mastodonPolling.encodeAccountCursor({ auth: auth.props, account: propsValue.account, accountId, statusId: item.id }),+ data: item.data,+ }));+ };+ const resolveAccount = () =>+ mastodonPolling.resolveAccountId({+ auth: auth.props,+ account: propsValue.account,+ operation: 'New Status from Account',+ });+ const cursor = mastodonPolling.decodeAccountCursor({ auth: auth.props, account: propsValue.account, cursor: lastItemId });+ if (cursor.kind === 'same_account') {+ const cached = await tryCatch(() => fetchStatuses({ accountId: cursor.accountId, minId: cursor.statusId }));+ if (cached.error === null) {+ return cached.data;+ }+ if (!(cached.error instanceof MastodonApiError) || cached.error.status !== 404) {+ throw cached.error;+ }+ return fetchStatuses({ accountId: await resolveAccount(), minId: cursor.statusId });+ }+ const latest = await fetchStatuses({ accountId: await resolveAccount(), minId: null });+ if (cursor.kind === 'none') {+ return latest;+ }+ if (latest.length > 0) {+ await store.put(LAST_ITEM_KEY, latest[0].id);+ } else {+ await store.delete(LAST_ITEM_KEY);+ }+ return [];+ },+};++const LAST_ITEM_KEY = 'lastItem';++export const newStatusFromAccount = createTrigger({+ auth: mastodonAuth,+ name: 'new_status_from_account',+ classification: 'READ',+ displayName: 'New Status from Account',+ description:+ 'Triggers when a specific account publishes a new post. For accounts on other servers, only posts that reach your server are seen, so following the account makes this reliable.',+ aiMetadata: {+ description:+ 'Fires once per new status published by one watched account (by handle or Account ID), optionally skipping its replies and boosts; the payload is the full status. For remote accounts only statuses federated to the connected server are visible.',+ },+ props,+ sampleData: mastodonSampleData.status,+ outputSchema: statusOutputSchema,+ type: TriggerStrategy.POLLING,+ async test(context) {+ return pollingHelper.test(polling, context);+ },+ async onEnable(context) {+ await pollingHelper.onEnable(polling, context);+ },+ async onDisable(context) {+ await pollingHelper.onDisable(polling, context);+ },+ async run(context) {+ return pollingHelper.poll(polling, context);+ },+});diff --git a/packages/pieces/community/mastodon/src/lib/triggers/new-status-with-hashtag.ts b/packages/pieces/community/mastodon/src/lib/triggers/new-status-with-hashtag.tsnew file mode 100644index 00000000000..58e865a4c03--- /dev/null+++ b/packages/pieces/community/mastodon/src/lib/triggers/new-status-with-hashtag.ts@@ -0,0 +1,85 @@+import {+ AppConnectionValueForAuthProperty,+ createTrigger,+ Property,+ StaticPropsValue,+ TriggerStrategy,+} from '@activepieces/pieces-framework';+import { DedupeStrategy, Polling, pollingHelper } from '@activepieces/pieces-common';+import { mastodonAuth } from '../..';+import { mastodonPolling } from '../common/polling';+import { mastodonSampleData } from '../common/sample-data';+import { statusOutputSchema } from '../output-schemas';++const props = {+ hashtag: Property.ShortText({+ displayName: 'Hashtag',+ description: 'The hashtag to watch, without the # sign, for example opensource.',+ required: true,+ }),+ local: Property.Checkbox({+ displayName: 'Only Local Statuses',+ description: 'Only trigger for posts by accounts on your own server.',+ required: false,+ defaultValue: false,+ }),+ only_media: Property.Checkbox({+ displayName: 'Only Statuses With Media',+ description: 'Only trigger for posts that have images, video or audio attached.',+ required: false,+ defaultValue: false,+ }),+};++const polling: Polling<+ AppConnectionValueForAuthProperty<typeof mastodonAuth>,+ StaticPropsValue<typeof props>+> = {+ strategy: DedupeStrategy.LAST_ITEM,+ items: async ({ auth, propsValue, lastItemId }) => {+ const hashtag = propsValue.hashtag.trim().replace(/^#/, '');+ if (hashtag === '') {+ throw new Error('Enter a hashtag to watch, for example opensource.');+ }+ return mastodonPolling.fetchNewItems({+ auth: auth.props,+ path: `/api/v1/timelines/tag/${encodeURIComponent(hashtag)}`,+ query: {+ local: propsValue.local === true ? true : undefined,+ only_media: propsValue.only_media === true ? true : undefined,+ },+ lastItemId,+ operation: 'New Status with Hashtag',+ scope: 'read:statuses',+ });+ },+};++export const newStatusWithHashtag = createTrigger({+ auth: mastodonAuth,+ name: 'new_status_with_hashtag',+ classification: 'READ',+ displayName: 'New Status with Hashtag',+ description:+ 'Triggers when a new public post uses a hashtag. Posts from other servers are included once they reach your server.',+ aiMetadata: {+ description:+ 'Fires once per new public status using the watched hashtag, as seen by the connected server, optionally limited to local posts or posts with media; the payload is the full status.',+ },+ props,+ sampleData: mastodonSampleData.status,+ outputSchema: statusOutputSchema,+ type: TriggerStrategy.POLLING,+ async test(context) {+ return pollingHelper.test(polling, context);+ },+ async onEnable(context) {+ await pollingHelper.onEnable(polling, context);+ },+ async onDisable(context) {+ await pollingHelper.onDisable(polling, context);+ },+ async run(context) {+ return pollingHelper.poll(polling, context);+ },+});diff --git a/packages/pieces/community/mastodon/test/polling.test.ts b/packages/pieces/community/mastodon/test/polling.test.tsnew file mode 100644index 00000000000..8868aea19a2--- /dev/null+++ b/packages/pieces/community/mastodon/test/polling.test.ts@@ -0,0 +1,311 @@+import { HttpError } from '@activepieces/pieces-common';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import '../src';+import { mastodonPolling } from '../src/lib/common/polling';+import { newFollower } from '../src/lib/triggers/new-follower';+import { newMention } from '../src/lib/triggers/new-mention';+import { newStatusFromAccount } from '../src/lib/triggers/new-status-from-account';+import { newStatusWithHashtag } from '../src/lib/triggers/new-status-with-hashtag';++const sendRequest = vi.fn();++vi.mock('@activepieces/pieces-common', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();+ return {+ ...actual,+ httpClient: {+ sendRequest: (...args: unknown[]) => sendRequest(...args),+ },+ };+});++const AUTH = { base_url: 'https://social.example/', access_token: 'token' };++type Route = (url: URL) => unknown;++let routes: Record<string, Route> = {};++function route({ path, handler }: { path: string; handler: Route }): void {+ routes[path] = handler;+}++function notFound(): never {+ throw new HttpError(undefined, { status: 404, responseBody: { error: 'Record not found' } });+}++function callsTo(path: string): URL[] {+ return sendRequest.mock.calls.map((call) => new URL(call[0].url)).filter((url) => url.pathname === path);+}++function memoryStore() {+ const values = new Map<string, unknown>();+ return {+ values,+ get: async <T>(key: string) => (values.has(key) ? (values.get(key) as T) : null),+ put: async <T>(key: string, value: T) => {+ values.set(key, value);+ return value;+ },+ delete: async (key: string) => {+ values.delete(key);+ },+ };+}++function triggerContext({+ propsValue,+ store,+ auth = AUTH,+}: {+ propsValue: Record<string, unknown>;+ store: ReturnType<typeof memoryStore>;+ auth?: typeof AUTH;+}) {+ return { auth: { props: auth }, propsValue, store, files: {} } as never;+}++beforeEach(() => {+ routes = {};+ sendRequest.mockReset();+ sendRequest.mockImplementation(async ({ url }: { url: string }) => {+ const parsed = new URL(url);+ const handler = routes[parsed.pathname];+ if (handler === undefined) {+ throw new Error(`Unexpected request to ${parsed.pathname}`);+ }+ return { status: 200, headers: {}, body: handler(parsed) };+ });+});++describe('fetchNewItems', () => {+ it('sends min_id and the page limit, drops items without an ID and sorts IDs newest first by number', async () => {+ route({+ path: '/api/v1/notifications',+ handler: () => [{ id: '99' }, { id: '1000' }, { id: '' }, { other: true }, { id: '101' }],+ });++ const items = await mastodonPolling.fetchNewItems({+ auth: AUTH,+ path: '/api/v1/notifications',+ query: { types: ['mention'] },+ lastItemId: '98',+ operation: 'New Mention',+ scope: 'read:notifications',+ });++ expect(items.map((item) => item.id)).toEqual(['1000', '101', '99']);+ const [url] = callsTo('/api/v1/notifications');+ expect(url.searchParams.get('min_id')).toBe('98');+ expect(url.searchParams.get('limit')).toBe('40');+ });++ it('leaves min_id out on the first poll', async () => {+ route({ path: '/api/v1/notifications', handler: () => [] });++ await mastodonPolling.fetchNewItems({+ auth: AUTH,+ path: '/api/v1/notifications',+ lastItemId: null,+ operation: 'New Follower',+ scope: 'read:notifications',+ });++ expect(callsTo('/api/v1/notifications')[0].searchParams.has('min_id')).toBe(false);+ });+});++describe('resolveAccountId', () => {+ it('uses a numeric Account ID as is, without a request', async () => {+ await expect(mastodonPolling.resolveAccountId({ auth: AUTH, account: ' 12345 ', operation: 'test' })).resolves.toBe('12345');+ expect(sendRequest).not.toHaveBeenCalled();+ });++ it('looks up a handle and strips a leading @', async () => {+ route({ path: '/api/v1/accounts/lookup', handler: () => ({ id: '77', acct: '[email protected]' }) });++ await expect(+ mastodonPolling.resolveAccountId({ auth: AUTH, account: '@[email protected]', operation: 'test' })+ ).resolves.toBe('77');+ expect(callsTo('/api/v1/accounts/lookup')[0].searchParams.get('acct')).toBe('[email protected]');+ });++ it('falls back to a resolving search when the lookup returns 404, matching a local account by host', async () => {+ route({ path: '/api/v1/accounts/lookup', handler: notFound });+ route({+ path: '/api/v2/search',+ handler: () => ({ accounts: [{ id: '5', acct: '[email protected]' }, { id: '6', acct: 'alice' }] }),+ });++ await expect(+ mastodonPolling.resolveAccountId({ auth: AUTH, account: '[email protected]', operation: 'test' })+ ).resolves.toBe('6');+ expect(callsTo('/api/v2/search')[0].searchParams.get('resolve')).toBe('true');+ });++ it('explains when no account matches', async () => {+ route({ path: '/api/v1/accounts/lookup', handler: notFound });+ route({ path: '/api/v2/search', handler: () => ({ accounts: [] }) });++ await expect(mastodonPolling.resolveAccountId({ auth: AUTH, account: 'ghost', operation: 'test' })).rejects.toThrow(+ 'Mastodon found no account for "ghost"'+ );+ });+});++describe('New Status from Account', () => {+ const propsValue = { account: '[email protected]', exclude_replies: true, exclude_reblogs: false };++ function cursor({ server = 'https://social.example', handle = '[email protected]', accountId, statusId }: CursorParts) {+ return JSON.stringify({ server, handle, account_id: accountId, status_id: statusId });+ }++ it('fires only for statuses newer than the cursor, and looks the account up once', async () => {+ const store = memoryStore();+ let statuses = [{ id: '10' }, { id: '9' }];+ route({ path: '/api/v1/accounts/lookup', handler: () => ({ id: '77' }) });+ route({ path: '/api/v1/accounts/77/statuses', handler: () => statuses });++ await newStatusFromAccount.onEnable(triggerContext({ propsValue, store }));+ statuses = [{ id: '12' }, { id: '11' }];+ const fired = await newStatusFromAccount.run(triggerContext({ propsValue, store }));++ expect(fired).toEqual([{ id: '12' }, { id: '11' }]);+ expect(store.values.get('lastItem')).toBe(cursor({ accountId: '77', statusId: '12' }));+ expect(callsTo('/api/v1/accounts/lookup')).toHaveLength(1);+ const lastCall = callsTo('/api/v1/accounts/77/statuses').at(-1);+ expect(lastCall?.searchParams.get('min_id')).toBe('10');+ expect(lastCall?.searchParams.get('exclude_replies')).toBe('true');+ expect(lastCall?.searchParams.has('exclude_reblogs')).toBe(false);+ });++ it('restarts from the newest post of the new account, without firing, when the handle changes', async () => {+ const store = memoryStore();+ let otherStatuses = [{ id: '2' }];+ route({ path: '/api/v1/accounts/lookup', handler: (url) => ({ id: url.searchParams.get('acct') === 'other' ? '88' : '77' }) });+ route({ path: '/api/v1/accounts/77/statuses', handler: () => [{ id: '900' }] });+ route({ path: '/api/v1/accounts/88/statuses', handler: () => otherStatuses });+ const otherProps = { ...propsValue, account: 'other' };++ await newStatusFromAccount.onEnable(triggerContext({ propsValue, store }));+ const afterSwitch = await newStatusFromAccount.run(triggerContext({ propsValue: otherProps, store }));+ otherStatuses = [{ id: '3' }];+ const nextPoll = await newStatusFromAccount.run(triggerContext({ propsValue: otherProps, store }));++ expect(afterSwitch).toEqual([]);+ expect(nextPoll).toEqual([{ id: '3' }]);+ expect(callsTo('/api/v1/accounts/88/statuses')[0].searchParams.has('min_id')).toBe(false);+ expect(callsTo('/api/v1/accounts/88/statuses')[1].searchParams.get('min_id')).toBe('2');+ expect(store.values.get('lastItem')).toBe(cursor({ handle: 'other', accountId: '88', statusId: '3' }));+ });++ it('restarts from the newest post when the connection points to another server', async () => {+ const store = memoryStore();+ route({ path: '/api/v1/accounts/lookup', handler: (url) => ({ id: url.hostname === 'social.example' ? '77' : '55' }) });+ route({ path: '/api/v1/accounts/77/statuses', handler: () => [{ id: '900' }] });+ route({ path: '/api/v1/accounts/55/statuses', handler: () => [{ id: '5' }] });++ await newStatusFromAccount.onEnable(triggerContext({ propsValue, store }));+ const fired = await newStatusFromAccount.run(+ triggerContext({ propsValue, store, auth: { ...AUTH, base_url: 'https://other.example' } })+ );++ expect(fired).toEqual([]);+ expect(callsTo('/api/v1/accounts/55/statuses')[0].searchParams.has('min_id')).toBe(false);+ expect(store.values.get('lastItem')).toBe(cursor({ server: 'https://other.example', accountId: '55', statusId: '5' }));+ });++ it('clears the cursor when the new account has no posts yet, so its first post fires', async () => {+ const store = memoryStore();+ let otherStatuses: { id: string }[] = [];+ route({ path: '/api/v1/accounts/lookup', handler: (url) => ({ id: url.searchParams.get('acct') === 'other' ? '88' : '77' }) });+ route({ path: '/api/v1/accounts/77/statuses', handler: () => [{ id: '900' }] });+ route({ path: '/api/v1/accounts/88/statuses', handler: () => otherStatuses });+ const otherProps = { ...propsValue, account: 'other' };++ await newStatusFromAccount.onEnable(triggerContext({ propsValue, store }));+ const afterSwitch = await newStatusFromAccount.run(triggerContext({ propsValue: otherProps, store }));+ expect(store.values.has('lastItem')).toBe(false);+ otherStatuses = [{ id: '3' }];+ const nextPoll = await newStatusFromAccount.run(triggerContext({ propsValue: otherProps, store }));++ expect(afterSwitch).toEqual([]);+ expect(nextPoll).toEqual([{ id: '3' }]);+ expect(callsTo('/api/v1/accounts/88/statuses')[1].searchParams.has('min_id')).toBe(false);+ });++ it('keeps the old cursor when reading the new account fails, and retries the switch on the next poll', async () => {+ const store = memoryStore();+ let failOther = true;+ route({ path: '/api/v1/accounts/lookup', handler: (url) => ({ id: url.searchParams.get('acct') === 'other' ? '88' : '77' }) });+ route({ path: '/api/v1/accounts/77/statuses', handler: () => [{ id: '900' }] });+ route({+ path: '/api/v1/accounts/88/statuses',+ handler: () => {+ if (failOther) {+ throw new HttpError(undefined, { status: 503, responseBody: {} });+ }+ return [{ id: '4' }];+ },+ });+ const otherProps = { ...propsValue, account: 'other' };++ await newStatusFromAccount.onEnable(triggerContext({ propsValue, store }));+ await expect(newStatusFromAccount.run(triggerContext({ propsValue: otherProps, store }))).rejects.toThrow();+ expect(store.values.get('lastItem')).toBe(cursor({ accountId: '77', statusId: '900' }));+ failOther = false;+ const retried = await newStatusFromAccount.run(triggerContext({ propsValue: otherProps, store }));++ expect(retried).toEqual([]);+ expect(store.values.get('lastItem')).toBe(cursor({ handle: 'other', accountId: '88', statusId: '4' }));+ expect(callsTo('/api/v1/accounts/88/statuses').every((url) => !url.searchParams.has('min_id'))).toBe(true);+ });++ it('looks the account up again, keeping the cursor, when the cached Account ID returns 404', async () => {+ const store = memoryStore();+ let currentId = '77';+ route({ path: '/api/v1/accounts/lookup', handler: () => ({ id: currentId }) });+ route({ path: '/api/v1/accounts/77/statuses', handler: () => (currentId === '77' ? [{ id: '1' }] : notFound()) });+ route({ path: '/api/v1/accounts/90/statuses', handler: () => [{ id: '3' }] });++ await newStatusFromAccount.onEnable(triggerContext({ propsValue, store }));+ currentId = '90';+ const fired = await newStatusFromAccount.run(triggerContext({ propsValue, store }));++ expect(fired).toEqual([{ id: '3' }]);+ expect(callsTo('/api/v1/accounts/90/statuses')[0].searchParams.get('min_id')).toBe('1');+ expect(store.values.get('lastItem')).toBe(cursor({ accountId: '90', statusId: '3' }));+ });+});++describe('notification and hashtag triggers', () => {+ it('New Mention and New Follower poll notifications of their own type', async () => {+ route({ path: '/api/v1/notifications', handler: () => [{ id: '5' }] });++ await newMention.run(triggerContext({ propsValue: {}, store: memoryStore() }));+ await newFollower.run(triggerContext({ propsValue: {}, store: memoryStore() }));++ const types = callsTo('/api/v1/notifications').map((url) => url.searchParams.getAll('types[]').concat(url.searchParams.getAll('types')));+ expect(types).toEqual([['mention'], ['follow']]);+ });++ it('New Status with Hashtag strips the # and refuses an empty hashtag', async () => {+ route({ path: '/api/v1/timelines/tag/opensource', handler: () => [{ id: '8' }] });++ const fired = await newStatusWithHashtag.run(+ triggerContext({ propsValue: { hashtag: '#opensource', local: true, only_media: false }, store: memoryStore() })+ );++ expect(fired).toEqual([{ id: '8' }]);+ expect(callsTo('/api/v1/timelines/tag/opensource')[0].searchParams.get('local')).toBe('true');+ await expect(+ newStatusWithHashtag.run(triggerContext({ propsValue: { hashtag: ' # ', local: false, only_media: false }, store: memoryStore() }))+ ).rejects.toThrow('Enter a hashtag to watch');+ });+});++type CursorParts = {+ server?: string;+ handle?: string;+ accountId: string;+ statusId: string;+};diff --git a/packages/pieces/community/mastodon/vitest.config.ts b/packages/pieces/community/mastodon/vitest.config.tsnew file mode 100644index 00000000000..79c97261904--- /dev/null+++ b/packages/pieces/community/mastodon/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'),+ },+ },+})