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(bettermode): manage posts, replies, members, spaces and badges from flows and AI agents (#16461)
Odai Ahmad2685a0d1be46
diff --git a/bun.lock b/bun.lockindex 93930b63e55..48cd0f54c1b 100644--- a/bun.lock+++ b/bun.lock@@ -1157,16 +1157,14 @@},"packages/pieces/community/bettermode": {"name": "@activepieces/piece-bettermode",- "version": "0.2.1",+ "version": "0.3.0","dependencies": {- "@activepieces/core-piece-types": "workspace:*",- "@activepieces/core-utils": "workspace:*","@activepieces/pieces-common": "workspace:*","@activepieces/pieces-framework": "workspace:*",- "zod": "4.3.6",},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/bexio": {diff --git a/packages/pieces/community/bettermode/package.json b/packages/pieces/community/bettermode/package.jsonindex cfbd835025d..afbf68d0127 100644--- a/packages/pieces/community/bettermode/package.json+++ b/packages/pieces/community/bettermode/package.json@@ -1,21 +1,20 @@{"name": "@activepieces/piece-bettermode",- "version": "0.2.1",+ "version": "0.3.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:*",- "@activepieces/pieces-framework": "workspace:*",- "zod": "4.3.6",- "@activepieces/core-piece-types": "workspace:*",- "@activepieces/core-utils": "workspace:*"+ "@activepieces/pieces-framework": "workspace:*"},"devDependencies": {- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"}}diff --git a/packages/pieces/community/bettermode/src/i18n/translation.json b/packages/pieces/community/bettermode/src/i18n/translation.jsonindex bf47ff4d55b..6eb0fbe6ea0 100644--- a/packages/pieces/community/bettermode/src/i18n/translation.json+++ b/packages/pieces/community/bettermode/src/i18n/translation.json@@ -5,21 +5,99 @@"Email": "Email","Password": "Password","The region of your Bettermode account": "The region of your Bettermode account",- "The domain of your Bettermode account": "The domain of your Bettermode account",+ "The domain of your community, for example community.example.com": "The domain of your community, for example community.example.com","Email address for your Bettermode account": "Email address for your Bettermode account","Password for your Bettermode account": "Password for your Bettermode account","US Region": "US Region","EU Region": "EU Region",- "Your domain should be the base URL of your Bettermode community. Example: community.example.com": "Your domain should be the base URL of your Bettermode community. Example: community.example.com",+ "Connect with the email and password of a Bettermode member.\n\n1. Pick the region your community is hosted in (EU communities use api.bettermode.de).\n2. Enter the community domain, for example community.example.com (https:// is optional).\n3. Use the email and password of the member the flows should act as. Admin actions (badges, suspending or deleting members, moderation) need an admin account.": "Connect with the email and password of a Bettermode member.\n\n1. Pick the region your community is hosted in (EU communities use api.bettermode.de).\n2. Enter the community domain, for example community.example.com (https:// is optional).\n3. Use the email and password of the member the flows should act as. Admin actions (badges, suspending or deleting members, moderation) need an admin account.","Create Discussion Post": "Create Discussion Post","Create Question Post": "Create Question Post",+ "Assign Badge To Member": "Assign Badge To Member",+ "Revoke Badge From Member": "Revoke Badge From Member",+ "Get Current Member": "Get Current Member",+ "Get Community": "Get Community",+ "List Spaces": "List Spaces",+ "Get Space": "Get Space",+ "List Space Members": "List Space Members",+ "Add Members to Space": "Add Members to Space",+ "Remove Members from Space": "Remove Members from Space",+ "List Post Types": "List Post Types",+ "List Posts": "List Posts",+ "Search Posts": "Search Posts",+ "Get Post": "Get Post",+ "Create Post": "Create Post",+ "Update Post": "Update Post",+ "Delete Post": "Delete Post",+ "List Replies": "List Replies",+ "Create Reply": "Create Reply",+ "Add Reaction": "Add Reaction",+ "Remove Reaction": "Remove Reaction",+ "Pin Post": "Pin Post",+ "Unpin Post": "Unpin Post",+ "Hide Post": "Hide Post",+ "Unhide Post": "Unhide Post",+ "Move Post": "Move Post",+ "List Tags": "List Tags",+ "Find Member by Email": "Find Member by Email",+ "Get Member": "Get Member",+ "List Members": "List Members",+ "Update Member": "Update Member",+ "Invite Members": "Invite Members",+ "Suspend Member": "Suspend Member",+ "Unsuspend Member": "Unsuspend Member",+ "Delete Member": "Delete Member",+ "Send Direct Message": "Send Direct Message",+ "List Badges": "List Badges","Assign Badge to Member": "Assign Badge to Member","Revoke Badge from Member": "Revoke Badge from Member",+ "List Events": "List Events",+ "Register for Event": "Register for Event",+ "List Moderation Items": "List Moderation Items","Custom API Call": "Custom API Call","Create a new discussion post in a space": "Create a new discussion post in a space","Create a new question post in a space": "Create a new question post in a space","Assign an existing badge to a member by email": "Assign an existing badge to a member by email","Revoke a badge from a member by email": "Revoke a badge from a member by email",+ "Get the member the connection is logged in as.": "Get the member the connection is logged in as.",+ "Get the community (network) details.": "Get the community (network) details.",+ "List spaces in the community, optionally filtered by name.": "List spaces in the community, optionally filtered by name.",+ "Get a space by ID or slug.": "Get a space by ID or slug.",+ "List the members of a space.": "List the members of a space.",+ "Add one or more members to a space.": "Add one or more members to a space.",+ "Remove one or more members from a space.": "Remove one or more members from a space.",+ "List the post types (Discussion, Question, Article...) of the community.": "List the post types (Discussion, Question, Article...) of the community.",+ "List posts, optionally limited to spaces and post types.": "List posts, optionally limited to spaces and post types.",+ "Search posts by keyword.": "Search posts by keyword.",+ "Get a post or reply by ID.": "Get a post or reply by ID.",+ "Publish a post of any post type in a space.": "Publish a post of any post type in a space.",+ "Change the title, content, tags or lock state of a post.": "Change the title, content, tags or lock state of a post.",+ "Permanently delete a post or reply.": "Permanently delete a post or reply.",+ "List the replies of a post.": "List the replies of a post.",+ "Reply to a post.": "Reply to a post.",+ "React to a post as the connected member.": "React to a post as the connected member.",+ "Remove the connected member's reaction from a post.": "Remove the connected member's reaction from a post.",+ "Pin a post to the top of its space.": "Pin a post to the top of its space.",+ "Unpin a post from its space.": "Unpin a post from its space.",+ "Hide a post from members.": "Hide a post from members.",+ "Make a hidden post visible again.": "Make a hidden post visible again.",+ "Move a post to another space.": "Move a post to another space.",+ "List tags, optionally in one space or matching a name.": "List tags, optionally in one space or matching a name.",+ "Find the member with an exact email address.": "Find the member with an exact email address.",+ "Get a member by ID, username or external ID.": "Get a member by ID, username or external ID.",+ "List community members.": "List community members.",+ "Change the name, tagline or other profile fields of a member.": "Change the name, tagline or other profile fields of a member.",+ "Send community invitations by email.": "Send community invitations by email.",+ "Suspend a member so they can no longer log in.": "Suspend a member so they can no longer log in.",+ "Restore access for a suspended member.": "Restore access for a suspended member.",+ "Permanently delete a member from the community.": "Permanently delete a member from the community.",+ "Send a chat message to a member.": "Send a chat message to a member.",+ "List the badges defined in the community.": "List the badges defined in the community.",+ "Give a badge to a member by member ID.": "Give a badge to a member by member ID.",+ "Take a badge away from a member by member ID.": "Take a badge away from a member by member ID.",+ "List community events.": "List community events.",+ "Register the connected member for an event.": "Register the connected member for an event.",+ "List reported or flagged content waiting for moderation.": "List reported or flagged content waiting for moderation.","Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint","Space": "Space","Title": "Title",@@ -27,6 +105,41 @@"Tags": "Tags","Locked": "Locked","Badge": "Badge",+ "Search": "Search",+ "Member ID": "Member ID",+ "Limit": "Limit",+ "Cursor": "Cursor",+ "Space ID": "Space ID",+ "Space Slug": "Space Slug",+ "Member IDs": "Member IDs",+ "Space Role ID": "Space Role ID",+ "Context": "Context",+ "Space IDs": "Space IDs",+ "Post Type IDs": "Post Type IDs",+ "Order By": "Order By",+ "Reverse Order": "Reverse Order",+ "Search Text": "Search Text",+ "Post ID": "Post ID",+ "Post Type ID": "Post Type ID",+ "Clear Tags": "Clear Tags",+ "Lock State": "Lock State",+ "Reply Post Type ID": "Reply Post Type ID",+ "Reaction": "Reaction",+ "Target Space ID": "Target Space ID",+ "Username": "Username",+ "External ID": "External ID",+ "Status": "Status",+ "Name": "Name",+ "Tagline": "Tagline",+ "Clear Tagline": "Clear Tagline",+ "Role ID": "Role ID",+ "Emails": "Emails",+ "Invitation Message": "Invitation Message",+ "Default Space IDs": "Default Space IDs",+ "Recipient Member ID": "Recipient Member ID",+ "Message": "Message",+ "Badge ID": "Badge ID",+ "Event ID": "Event ID","Method": "Method","Headers": "Headers","Query Parameters": "Query Parameters",@@ -36,30 +149,123 @@"Return Error as Output": "Return Error as Output","Timeout": "Timeout","Follow redirects": "Follow redirects",- "The space to create the discussion in": "The space to create the discussion in",+ "The space to post in. Lists the spaces the connected member has joined.": "The space to post in. Lists the spaces the connected member has joined.","The title of the discussion": "The title of the discussion",- "The content of the discussion": "The content of the discussion",- "The tags to add to the discussion": "The tags to add to the discussion",+ "The content of the discussion. HTML is supported.": "The content of the discussion. HTML is supported.",+ "Comma-separated tag names to add, for example onboarding, feedback. Leave empty for no tags.": "Comma-separated tag names to add, for example onboarding, feedback. Leave empty for no tags.","If the discussion should be locked": "If the discussion should be locked",- "The space to create the question in": "The space to create the question in","The title of the question": "The title of the question",- "The content of the question": "The content of the question",- "The tags to add to the question": "The tags to add to the question",+ "The content of the question. HTML is supported.": "The content of the question. HTML is supported.","If the question should be locked": "If the question should be locked",- "The badge to assign": "The badge to assign",- "The email of the member to assign the badge to": "The email of the member to assign the badge to",- "The badge to revoke": "The badge to revoke",- "The email of the member to revoke the badge from": "The email of the member to revoke the badge from",+ "The badge to assign or revoke": "The badge to assign or revoke",+ "The exact email of the member. The connected account must be an admin to look members up by email.": "The exact email of the member. The connected account must be an admin to look members up by email.",+ "Only return spaces whose name matches this text.": "Only return spaces whose name matches this text.",+ "Only return spaces this member has joined.": "Only return spaces this member has joined.",+ "How many items to return (1-100). Defaults to 20.": "How many items to return (1-100). Defaults to 20.",+ "The next_cursor value from a previous call, to fetch the next page. Leave empty for the first page.": "The next_cursor value from a previous call, to fetch the next page. Leave empty for the first page.",+ "The space ID. Give this or the slug.": "The space ID. Give this or the slug.",+ "The slug from the space URL. Give this or the ID.": "The slug from the space URL. Give this or the ID.",+ "The space ID (from List Spaces).": "The space ID (from List Spaces).",+ "Member IDs to add (1-50).": "Member IDs to add (1-50).",+ "Optional space role ID. Leave empty for the default member role.": "Optional space role ID. Leave empty for the default member role.",+ "Member IDs to remove (1-50).": "Member IDs to remove (1-50).",+ "post for top-level post types, reply for reply types. Leave empty for both.": "post for top-level post types, reply for reply types. Leave empty for both.",+ "Filter post types by name.": "Filter post types by name.",+ "Only posts in these spaces.": "Only posts in these spaces.",+ "Only posts of these post types (from List Post Types).": "Only posts of these post types (from List Post Types).",+ "Sort field. Defaults to createdAt.": "Sort field. Defaults to createdAt.",+ "Reverse the sort direction.": "Reverse the sort direction.",+ "Words to search for.": "Words to search for.",+ "The post ID.": "The post ID.",+ "The space to post in.": "The space to post in.",+ "The post type ID (from List Post Types).": "The post type ID (from List Post Types).",+ "The post title.": "The post title.",+ "The post body. HTML is supported.": "The post body. HTML is supported.",+ "Tag names to add. New names create tags.": "Tag names to add. New names create tags.",+ "Lock the post so nobody can reply.": "Lock the post so nobody can reply.",+ "The post to update.": "The post to update.",+ "New title. Leave empty to keep it.": "New title. Leave empty to keep it.",+ "New HTML body. Leave empty to keep it.": "New HTML body. Leave empty to keep it.",+ "Replaces all tags with these names. Leave empty to keep the tags.": "Replaces all tags with these names. Leave empty to keep the tags.",+ "Remove all tags.": "Remove all tags.",+ "Lock or unlock replies. Leave empty to keep it.": "Lock or unlock replies. Leave empty to keep it.",+ "The post to delete.": "The post to delete.",+ "The post whose replies to list.": "The post whose replies to list.",+ "The post or reply to answer.": "The post or reply to answer.",+ "The reply body. HTML is supported.": "The reply body. HTML is supported.",+ "Optional reply type ID (List Post Types with Context reply). Defaults to the type the parent allows.": "Optional reply type ID (List Post Types with Context reply). Defaults to the type the parent allows.",+ "The post to react to.": "The post to react to.",+ "The reaction key, for example +1 or heart.": "The reaction key, for example +1 or heart.",+ "The post.": "The post.",+ "The reaction key to remove.": "The reaction key to remove.",+ "The post to move.": "The post to move.",+ "The space to move it to.": "The space to move it to.",+ "Only tags of this space.": "Only tags of this space.",+ "Filter tags by name.": "Filter tags by name.",+ "The exact email address.": "The exact email address.",+ "The member ID.": "The member ID.",+ "The member username.": "The member username.",+ "The external ID set by your SSO or integration.": "The external ID set by your SSO or integration.",+ "Fuzzy search on name, username or email.": "Fuzzy search on name, username or email.",+ "Only members with these statuses.": "Only members with these statuses.",+ "The member to update. Leave empty for the connected member.": "The member to update. Leave empty for the connected member.",+ "New display name.": "New display name.",+ "New username.": "New username.",+ "New tagline.": "New tagline.",+ "Remove the tagline.": "Remove the tagline.",+ "New external ID.": "New external ID.",+ "New community role ID (admin only).": "New community role ID (admin only).",+ "Email addresses to invite (1-20).": "Email addresses to invite (1-20).",+ "Optional personal message in the email.": "Optional personal message in the email.",+ "Optional community role ID for the invitees.": "Optional community role ID for the invitees.",+ "Optional spaces the invitees join.": "Optional spaces the invitees join.",+ "The member to delete.": "The member to delete.",+ "The member to message.": "The member to message.",+ "The message text.": "The message text.",+ "The badge ID (from List Badges).": "The badge ID (from List Badges).",+ "Only events in these spaces.": "Only events in these spaces.",+ "Only events with this status.": "Only events with this status.",+ "The event ID (from List Events).": "The event ID (from List Events).",+ "Only items with this status. REVIEW = waiting for a moderator.": "Only items with this status. REVIEW = waiting for a moderator.",+ "Only items in this space.": "Only items in this space.","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.",+ "Post": "Post",+ "Reply": "Reply",+ "Created At": "Created At",+ "Published At": "Published At",+ "Last Activity": "Last Activity",+ "Updated At": "Updated At",+ "Replies Count": "Replies Count",+ "Reactions Count": "Reactions Count",+ "Lock": "Lock",+ "Unlock": "Unlock",+ "VERIFIED": "VERIFIED",+ "UNVERIFIED": "UNVERIFIED",+ "Suspended": "Suspended",+ "published": "published",+ "draft": "draft",+ "deleted": "deleted",+ "REVIEW": "REVIEW",+ "ACCEPTED": "ACCEPTED",+ "REJECTED": "REJECTED",+ "PendingConfirmation": "PendingConfirmation","GET": "GET","POST": "POST","PATCH": "PATCH","PUT": "PUT","DELETE": "DELETE",- "HEAD": "HEAD"+ "HEAD": "HEAD",+ "New Post": "New Post",+ "New Member": "New Member",+ "New Reply": "New Reply",+ "Triggers when a new post is published, optionally only in some spaces.": "Triggers when a new post is published, optionally only in some spaces.",+ "Triggers when a new member joins the community.": "Triggers when a new member joins the community.",+ "Triggers when someone replies to a post (comments and answers).": "Triggers when someone replies to a post (comments and answers).",+ "Only watch these spaces. Leave empty for all spaces the connected member can see.": "Only watch these spaces. Leave empty for all spaces the connected member can see.",+ "Only watch replies in these spaces. Leave empty for all spaces.": "Only watch replies in these spaces. Leave empty for all spaces."}\ No newline at end of filediff --git a/packages/pieces/community/bettermode/src/index.ts b/packages/pieces/community/bettermode/src/index.tsindex 7a65b6dd4be..75f62bf4d24 100644--- a/packages/pieces/community/bettermode/src/index.ts+++ b/packages/pieces/community/bettermode/src/index.ts@@ -1,35 +1,144 @@import { createCustomApiCallAction } from '@activepieces/pieces-common';-import { createPiece } from '@activepieces/pieces-framework';-import { PieceCategory } from '@activepieces/pieces-framework';+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';+import { getCurrentMemberAction, getNetworkAction } from './lib/actions/ai/account';+import {+ assignBadgeToMemberAction,+ listBadgesAction,+ listEventsAction,+ listModerationItemsAction,+ registerForEventAction,+ revokeBadgeFromMemberAction,+} from './lib/actions/ai/community';+import {+ deleteMemberAction,+ findMemberByEmailAction,+ getMemberAction,+ inviteMembersAction,+ listMembersAction,+ sendDirectMessageAction,+ suspendMemberAction,+ unsuspendMemberAction,+ updateMemberAction,+} from './lib/actions/ai/members';+import {+ addReactionAction,+ createPostAction,+ createReplyAction,+ deletePostAction,+ getPostAction,+ hidePostAction,+ listPostsAction,+ listPostTypesAction,+ listRepliesAction,+ listTagsAction,+ movePostAction,+ pinPostAction,+ removeReactionAction,+ searchPostsAction,+ unhidePostAction,+ unpinPostAction,+ updatePostAction,+} from './lib/actions/ai/posts';+import {+ addMemberToSpaceAction,+ getSpaceAction,+ listSpaceMembersAction,+ listSpacesAction,+ removeMemberFromSpaceAction,+} from './lib/actions/ai/spaces';import { assignBadgeAction } from './lib/actions/assign-badge';import { createDiscussionAction } from './lib/actions/create-discussion';import { createQuestionAction } from './lib/actions/create-question';import { revokeBadgeAction } from './lib/actions/revoke-badge';import { bettermodeAuth } from './lib/auth';-import { getAuthToken } from './lib/api';+import {+ assertCustomCallUrl,+ assertRegion,+ BettermodeCredentials,+ BettermodeTokenStore,+ bindTokenStore,+ getSession,+ readPath,+} from './lib/common/client';+import { newMemberTrigger } from './lib/triggers/new-member';+import { newPostTrigger } from './lib/triggers/new-post';+import { newReplyTrigger } from './lib/triggers/new-reply';++function withTokenStore<T extends { run: unknown; test: unknown }>(action: T & { run: StoreRunner; test: StoreRunner }): T {+ return Object.assign(action, { run: bindingStore(action.run), test: bindingStore(action.test) });+}++function bindingStore<C extends StoreContext, R>(run: (context: C) => Promise<R>): (context: C) => Promise<R> {+ return async (context) => {+ bindTokenStore({ credentials: context.auth.props, store: context.store });+ return run(context);+ };+}export const bettermode = createPiece({displayName: 'Bettermode',- description: 'Feature-rich engagement platform. Browse beautifully designed templates, each flexible for precise customization to your needs.',+ description:+ 'Feature-rich engagement platform. Browse beautifully designed templates, each flexible for precise customization to your needs.',auth: bettermodeAuth,- minimumSupportedRelease: '0.30.0',+ minimumSupportedRelease: '0.88.2',logoUrl: 'https://cdn.activepieces.com/pieces/bettermode.png',categories: [PieceCategory.MARKETING],- authors: ["joeworkman","kishanprmr","MoShizzle","abuaboud"],+ authors: ['joeworkman', 'kishanprmr', 'MoShizzle', 'abuaboud'],actions: [createDiscussionAction,createQuestionAction,assignBadgeAction,revokeBadgeAction,- createCustomApiCallAction({- baseUrl: (auth) => auth ? auth.props.region : '', // replace with the actual base URL+ getCurrentMemberAction,+ getNetworkAction,+ listSpacesAction,+ getSpaceAction,+ listSpaceMembersAction,+ addMemberToSpaceAction,+ removeMemberFromSpaceAction,+ listPostTypesAction,+ listPostsAction,+ searchPostsAction,+ getPostAction,+ createPostAction,+ updatePostAction,+ deletePostAction,+ listRepliesAction,+ createReplyAction,+ addReactionAction,+ removeReactionAction,+ pinPostAction,+ unpinPostAction,+ hidePostAction,+ unhidePostAction,+ movePostAction,+ listTagsAction,+ findMemberByEmailAction,+ getMemberAction,+ listMembersAction,+ updateMemberAction,+ inviteMembersAction,+ suspendMemberAction,+ unsuspendMemberAction,+ deleteMemberAction,+ sendDirectMessageAction,+ listBadgesAction,+ assignBadgeToMemberAction,+ revokeBadgeFromMemberAction,+ listEventsAction,+ registerForEventAction,+ listModerationItemsAction,+ withTokenStore(createCustomApiCallAction({+ baseUrl: (auth) => (auth ? assertRegion(auth.props.region) : ''),auth: bettermodeAuth,- authMapping: async (auth) => ({- Authorization: `Bearer ${(await getAuthToken(auth.props)).token}`,- }),- }),+ authMapping: async (auth, propsValue) => {+ assertCustomCallUrl({ region: auth.props.region, url: readPath({ value: propsValue, path: ['url', 'url'] }) });+ return { Authorization: `Bearer ${(await getSession(auth.props)).token}` };+ },+ })),],- triggers: [],+ triggers: [newPostTrigger, newMemberTrigger, newReplyTrigger],});-// Bettermode API docs: https://developers.bettermode.com/+type StoreContext = { auth: { props: BettermodeCredentials }; store: BettermodeTokenStore };+type StoreRunner = (context: never) => Promise<unknown>;diff --git a/packages/pieces/community/bettermode/src/lib/actions/ai/account.ts b/packages/pieces/community/bettermode/src/lib/actions/ai/account.tsnew file mode 100644index 00000000000..b1730ea9750--- /dev/null+++ b/packages/pieces/community/bettermode/src/lib/actions/ai/account.ts@@ -0,0 +1,68 @@+import { createAction } from '@activepieces/pieces-framework';+import { bettermodeAuth } from '../../auth';+import { bindTokenStore, bettermodeQuery } from '../../common/client';+import { MEMBER_FIELDS } from '../../common/fields';+import { bettermodeMap } from '../../common/mappers';+import { bettermodeSchemas } from '../../common/schemas';++export const getCurrentMemberAction = createAction({+ auth: bettermodeAuth,+ name: 'get_current_member',+ classification: 'READ',+ displayName: 'Get Current Member',+ description: 'Get the member the connection is logged in as.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the Bettermode member this connection acts as (ID, name, email, role). Use first to learn your own member ID or check whether the connection has an admin role. Read-only, safe to retry.',+ idempotent: true,+ },+ props: {},+ outputSchema: bettermodeSchemas.member,+ async run({ auth, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const data = await bettermodeQuery({+ auth: auth.props,+ query: `query GetCurrentMember {+ authMember {+${MEMBER_FIELDS}+ }+}`,+ });+ return bettermodeMap.member(data['authMember']);+ },+});++export const getNetworkAction = createAction({+ auth: bettermodeAuth,+ name: 'get_network',+ classification: 'READ',+ displayName: 'Get Community',+ description: 'Get the community (network) details.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the connected Bettermode community: ID, name, domain, plan and member count. Use to confirm which community you are working in or check the plan before plan-gated actions (events, chat, badges). Read-only, safe to retry.',+ idempotent: true,+ },+ props: {},+ outputSchema: bettermodeSchemas.network,+ async run({ auth, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const data = await bettermodeQuery({+ auth: auth.props,+ query: `query GetNetwork {+ network {+ id+ name+ domain+ description+ planName+ membersCount+ createdAt+ }+}`,+ });+ return bettermodeMap.network(data['network']);+ },+});diff --git a/packages/pieces/community/bettermode/src/lib/actions/ai/community.ts b/packages/pieces/community/bettermode/src/lib/actions/ai/community.tsnew file mode 100644index 00000000000..e3c905f7424--- /dev/null+++ b/packages/pieces/community/bettermode/src/lib/actions/ai/community.ts@@ -0,0 +1,236 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { bettermodeAuth } from '../../auth';+import { bindTokenStore, bettermodeQuery } from '../../common/client';+import { bettermodeAiProps } from '../../common/ai-props';+import { EVENT_FIELDS, PAGE_INFO } from '../../common/fields';+import { bettermodeInput } from '../../common/input';+import { bettermodeMap } from '../../common/mappers';+import { bettermodeOps } from '../../common/operations';+import { bettermodeSchemas } from '../../common/schemas';++const EVENT_STATUSES = ['published', 'draft', 'deleted'];+const MODERATION_STATUSES = ['REVIEW', 'ACCEPTED', 'REJECTED', 'PendingConfirmation'];++export const listBadgesAction = createAction({+ auth: bettermodeAuth,+ name: 'list_badges',+ classification: 'SEARCH',+ displayName: 'List Badges',+ description: 'List the badges defined in the community.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists every badge of the community with its ID and name. Use to get the Badge ID for Assign Badge to Member or Revoke Badge from Member. Read-only, safe to retry.',+ idempotent: true,+ },+ props: {},+ outputSchema: bettermodeSchemas.badges,+ async run({ auth, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const items = await bettermodeOps.listBadges({ auth: auth.props });+ return { items, count: items.length };+ },+});++export const assignBadgeToMemberAction = createAction({+ auth: bettermodeAuth,+ name: 'assign_badge_to_member',+ classification: 'WRITE',+ displayName: 'Assign Badge to Member',+ description: 'Give a badge to a member by member ID.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Gives an existing badge to a member, both by ID (List Badges, Find Member by Email). Admin only. Safe to retry: assigning a badge the member already holds succeeds again with no change.',+ idempotent: true,+ },+ props: {+ badge_id: bettermodeAiProps.id({ displayName: 'Badge ID', description: 'The badge ID (from List Badges).' }),+ member_id: bettermodeAiProps.id({ displayName: 'Member ID', description: 'The member ID.' }),+ },+ outputSchema: bettermodeSchemas.badgeAction,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ return bettermodeOps.changeBadge({+ auth: auth.props,+ operation: 'assignBadge',+ badgeId: bettermodeInput.requireText({ value: propsValue.badge_id, label: 'Badge ID' }),+ memberId: bettermodeInput.requireText({ value: propsValue.member_id, label: 'Member ID' }),+ });+ },+});++export const revokeBadgeFromMemberAction = createAction({+ auth: bettermodeAuth,+ name: 'revoke_badge_from_member',+ classification: 'WRITE',+ displayName: 'Revoke Badge from Member',+ description: 'Take a badge away from a member by member ID.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Removes a badge from a member, both by ID; it can be assigned again later. Admin only. Safe to retry: revoking a badge the member does not hold succeeds with no change.',+ idempotent: true,+ },+ props: {+ badge_id: bettermodeAiProps.id({ displayName: 'Badge ID', description: 'The badge ID (from List Badges).' }),+ member_id: bettermodeAiProps.id({ displayName: 'Member ID', description: 'The member ID.' }),+ },+ outputSchema: bettermodeSchemas.badgeAction,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ return bettermodeOps.changeBadge({+ auth: auth.props,+ operation: 'revokeBadge',+ badgeId: bettermodeInput.requireText({ value: propsValue.badge_id, label: 'Badge ID' }),+ memberId: bettermodeInput.requireText({ value: propsValue.member_id, label: 'Member ID' }),+ });+ },+});++export const listEventsAction = createAction({+ auth: bettermodeAuth,+ name: 'list_events',+ classification: 'SEARCH',+ displayName: 'List Events',+ description: 'List community events.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists events one page at a time, optionally only in some spaces or with a status. Use to find an Event ID for Register for Event. Events need a plan that includes them. Read-only, safe to retry.',+ idempotent: true,+ },+ props: {+ space_ids: Property.Array({ displayName: 'Space IDs', description: 'Only events in these spaces.', required: false }),+ status: Property.StaticDropdown({+ displayName: 'Status',+ description: 'Only events with this status.',+ required: false,+ options: {+ options: EVENT_STATUSES.map((status) => ({ label: status, value: status })),+ },+ }),+ limit: bettermodeAiProps.limit(),+ cursor: bettermodeAiProps.cursor(),+ },+ outputSchema: bettermodeSchemas.events,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const status = bettermodeInput.optionalText(propsValue.status);+ if (status !== undefined && !EVENT_STATUSES.includes(status)) {+ throw new Error(`Status must be one of ${EVENT_STATUSES.join(', ')}.`);+ }+ const spaceIds = bettermodeInput.stringList({ value: propsValue.space_ids, label: 'Space IDs' });+ const data = await bettermodeQuery({+ auth: auth.props,+ query: `query ListEvents($limit: Int!, $after: String, $spaceIds: [ID!], $status: EventStatus) {+ events(limit: $limit, after: $after, spaceIds: $spaceIds, status: $status) {+ nodes {+${EVENT_FIELDS}+ }+ ${PAGE_INFO}+ }+}`,+ variables: {+ limit: bettermodeInput.limit({ value: propsValue.limit }),+ after: bettermodeInput.optionalText(propsValue.cursor) ?? null,+ spaceIds: spaceIds.length > 0 ? spaceIds : undefined,+ status,+ },+ });+ return bettermodeMap.page({ value: data['events'], map: bettermodeMap.event });+ },+});++export const registerForEventAction = createAction({+ auth: bettermodeAuth,+ name: 'register_member_for_event',+ classification: 'WRITE',+ displayName: 'Register for Event',+ description: 'Register the connected member for an event.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Registers the connected member (not another member) for an event by Event ID. Events need a plan that includes them. Not verified as retry-safe: registering twice may error.',+ idempotent: false,+ },+ props: {+ event_id: bettermodeAiProps.id({ displayName: 'Event ID', description: 'The event ID (from List Events).' }),+ },+ outputSchema: bettermodeSchemas.eventRegistration,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const eventId = bettermodeInput.requireText({ value: propsValue.event_id, label: 'Event ID' });+ const status = await bettermodeOps.runActionMutation({+ auth: auth.props,+ query: `mutation RegisterForEvent($eventId: ID!) {+ registerForEvent(eventId: $eventId) {+ status+ }+}`,+ variables: { eventId },+ field: 'registerForEvent',+ });+ return { success: true, status, event_id: eventId };+ },+});++export const listModerationItemsAction = createAction({+ auth: bettermodeAuth,+ name: 'list_moderation_items',+ classification: 'SEARCH',+ displayName: 'List Moderation Items',+ description: 'List reported or flagged content waiting for moderation.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists moderation queue items (reported or auto-flagged posts and members) one page at a time, optionally by status or space. Admin or moderator only. Read-only, safe to retry.',+ idempotent: true,+ },+ props: {+ status: Property.StaticDropdown({+ displayName: 'Status',+ description: 'Only items with this status. REVIEW = waiting for a moderator.',+ required: false,+ options: {+ options: MODERATION_STATUSES.map((status) => ({ label: status, value: status })),+ },+ }),+ space_id: bettermodeAiProps.optionalId({ displayName: 'Space ID', description: 'Only items in this space.' }),+ limit: bettermodeAiProps.limit(),+ cursor: bettermodeAiProps.cursor(),+ },+ outputSchema: bettermodeSchemas.moderationItems,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const status = bettermodeInput.optionalText(propsValue.status);+ if (status !== undefined && !MODERATION_STATUSES.includes(status)) {+ throw new Error(`Status must be one of ${MODERATION_STATUSES.join(', ')}.`);+ }+ const data = await bettermodeQuery({+ auth: auth.props,+ query: `query ListModerationItems($limit: Int!, $after: String, $status: ModerationStatus, $spaceId: String) {+ moderationItems(limit: $limit, after: $after, status: $status, spaceId: $spaceId) {+ nodes {+ id+ status+ flaggedBy+ description+ memberId+ spaceId+ createdAt+ updatedAt+ }+ ${PAGE_INFO}+ }+}`,+ variables: {+ limit: bettermodeInput.limit({ value: propsValue.limit }),+ after: bettermodeInput.optionalText(propsValue.cursor) ?? null,+ status,+ spaceId: bettermodeInput.optionalText(propsValue.space_id),+ },+ });+ return bettermodeMap.page({ value: data['moderationItems'], map: bettermodeMap.moderationItem });+ },+});diff --git a/packages/pieces/community/bettermode/src/lib/actions/ai/members.ts b/packages/pieces/community/bettermode/src/lib/actions/ai/members.tsnew file mode 100644index 00000000000..20ce839b74c--- /dev/null+++ b/packages/pieces/community/bettermode/src/lib/actions/ai/members.ts@@ -0,0 +1,420 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { bettermodeAuth } from '../../auth';+import { bindTokenStore, bettermodeQuery, readPath } from '../../common/client';+import { bettermodeAiProps } from '../../common/ai-props';+import { MEMBER_FIELDS, PAGE_INFO } from '../../common/fields';+import { bettermodeInput } from '../../common/input';+import { bettermodeMap } from '../../common/mappers';+import { bettermodeOps } from '../../common/operations';+import { bettermodeSchemas } from '../../common/schemas';++const MEMBER_STATUSES = ['VERIFIED', 'UNVERIFIED', 'Suspended'];++export const findMemberByEmailAction = createAction({+ auth: bettermodeAuth,+ name: 'find_member_by_email',+ classification: 'SEARCH',+ displayName: 'Find Member by Email',+ description: 'Find the member with an exact email address.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Looks up the one member whose email equals the given address (case-insensitive exact match, never a partial match). Returns found false when nobody matches. Use before badge, space or member actions that need a Member ID. Needs an admin connection to see emails. Read-only, safe to retry.',+ idempotent: true,+ },+ props: {+ email: Property.ShortText({ displayName: 'Email', description: 'The exact email address.', required: true }),+ },+ outputSchema: bettermodeSchemas.findMember,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const email = bettermodeInput.email({ value: propsValue.email, label: 'Email' });+ const member = await bettermodeOps.findMemberByEmail({ auth: auth.props, email });+ return { found: member !== null, member };+ },+});++export const getMemberAction = createAction({+ auth: bettermodeAuth,+ name: 'get_member',+ classification: 'READ',+ displayName: 'Get Member',+ description: 'Get a member by ID, username or external ID.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns one member by member ID, username or external ID (give exactly one). Use Find Member by Email when you only have an email. Read-only, safe to retry.',+ idempotent: true,+ },+ props: {+ member_id: bettermodeAiProps.optionalId({ displayName: 'Member ID', description: 'The member ID.' }),+ username: Property.ShortText({ displayName: 'Username', description: 'The member username.', required: false }),+ external_id: Property.ShortText({+ displayName: 'External ID',+ description: 'The external ID set by your SSO or integration.',+ required: false,+ }),+ },+ outputSchema: bettermodeSchemas.member,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const id = bettermodeInput.optionalText(propsValue.member_id);+ const username = bettermodeInput.optionalText(propsValue.username);+ const externalId = bettermodeInput.optionalText(propsValue.external_id);+ if ([id, username, externalId].filter((value) => value !== undefined).length !== 1) {+ throw new Error('Give exactly one of Member ID, Username or External ID.');+ }+ const data = await bettermodeQuery({+ auth: auth.props,+ query: `query GetMember($id: ID, $username: String, $externalId: String) {+ member(id: $id, username: $username, externalId: $externalId) {+${MEMBER_FIELDS}+ }+}`,+ variables: { id, username, externalId },+ });+ return bettermodeMap.member(data['member']);+ },+});++export const listMembersAction = createAction({+ auth: bettermodeAuth,+ name: 'list_members',+ classification: 'SEARCH',+ displayName: 'List Members',+ description: 'List community members.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists community members one page at a time, optionally by status or a name search (search is fuzzy; use Find Member by Email for an exact email). Read-only, safe to retry.',+ idempotent: true,+ },+ props: {+ query: Property.ShortText({ displayName: 'Search', description: 'Fuzzy search on name, username or email.', required: false }),+ status: Property.StaticMultiSelectDropdown({+ displayName: 'Status',+ description: 'Only members with these statuses.',+ required: false,+ options: {+ options: MEMBER_STATUSES.map((status) => ({ label: status, value: status })),+ },+ }),+ limit: bettermodeAiProps.limit(),+ cursor: bettermodeAiProps.cursor(),+ },+ outputSchema: bettermodeSchemas.members,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const statuses = bettermodeInput.stringList({ value: propsValue.status, label: 'Status' });+ const invalid = statuses.filter((status) => !MEMBER_STATUSES.includes(status));+ if (invalid.length > 0) {+ throw new Error(`Status must be one of ${MEMBER_STATUSES.join(', ')}.`);+ }+ const data = await bettermodeQuery({+ auth: auth.props,+ query: `query ListMembers($limit: Int!, $after: String, $query: String, $status: [MemberStatusInput!]) {+ members(limit: $limit, after: $after, query: $query, status: $status) {+ nodes {+${MEMBER_FIELDS}+ }+ ${PAGE_INFO}+ }+}`,+ variables: {+ limit: bettermodeInput.limit({ value: propsValue.limit }),+ after: bettermodeInput.optionalText(propsValue.cursor) ?? null,+ query: bettermodeInput.optionalText(propsValue.query),+ status: statuses.length > 0 ? statuses : undefined,+ },+ });+ return bettermodeMap.page({ value: data['members'], map: bettermodeMap.member });+ },+});++export const updateMemberAction = createAction({+ auth: bettermodeAuth,+ name: 'update_member',+ classification: 'WRITE',+ displayName: 'Update Member',+ description: 'Change the name, tagline or other profile fields of a member.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Updates only the profile fields you give (name, username, tagline, external ID, role ID); Clear Tagline blanks the tagline. Leave Member ID empty to update the connected member; other members need an admin connection. Setting the same values again changes nothing.',+ idempotent: true,+ },+ props: {+ member_id: bettermodeAiProps.optionalId({+ displayName: 'Member ID',+ description: 'The member to update. Leave empty for the connected member.',+ }),+ name: Property.ShortText({ displayName: 'Name', description: 'New display name.', required: false }),+ username: Property.ShortText({ displayName: 'Username', description: 'New username.', required: false }),+ tagline: Property.ShortText({ displayName: 'Tagline', description: 'New tagline.', required: false }),+ clear_tagline: Property.Checkbox({ displayName: 'Clear Tagline', description: 'Remove the tagline.', required: false }),+ external_id: Property.ShortText({ displayName: 'External ID', description: 'New external ID.', required: false }),+ role_id: bettermodeAiProps.optionalId({+ displayName: 'Role ID',+ description: 'New community role ID (admin only).',+ }),+ },+ outputSchema: bettermodeSchemas.member,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const tagline = bettermodeInput.optionalText(propsValue.tagline);+ const clearTagline = bettermodeInput.optionalBoolean({ value: propsValue.clear_tagline, label: 'Clear Tagline' }) === true;+ if (clearTagline && tagline !== undefined) {+ throw new Error('Give Tagline or Clear Tagline, not both.');+ }+ const input: Record<string, unknown> = {};+ const fields: [string, unknown][] = [+ ['name', propsValue.name],+ ['username', propsValue.username],+ ['externalId', propsValue.external_id],+ ['roleId', propsValue.role_id],+ ];+ for (const [key, value] of fields) {+ const text = bettermodeInput.optionalText(value);+ if (text !== undefined) {+ input[key] = text;+ }+ }+ if (clearTagline) {+ input['tagline'] = '';+ } else if (tagline !== undefined) {+ input['tagline'] = tagline;+ }+ if (Object.keys(input).length === 0) {+ throw new Error('Give at least one field to update.');+ }+ const data = await bettermodeQuery({+ auth: auth.props,+ query: `mutation UpdateMember($id: ID, $input: UpdateMemberInput!) {+ updateMember(id: $id, input: $input) {+${MEMBER_FIELDS}+ }+}`,+ variables: { id: bettermodeInput.optionalText(propsValue.member_id), input },+ });+ return bettermodeMap.member(data['updateMember']);+ },+});++export const inviteMembersAction = createAction({+ auth: bettermodeAuth,+ name: 'invite_members',+ classification: 'WRITE',+ displayName: 'Invite Members',+ description: 'Send community invitations by email.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Sends invitation emails to join the community (up to 20 addresses), with an optional message. Real emails go out: only call when the user asked to invite these people. Each call sends new invitations, so retries send duplicates.',+ idempotent: false,+ },+ props: {+ emails: Property.Array({ displayName: 'Emails', description: 'Email addresses to invite (1-20).', required: true }),+ invitation_message: Property.LongText({+ displayName: 'Invitation Message',+ description: 'Optional personal message in the email.',+ required: false,+ }),+ role_id: bettermodeAiProps.optionalId({+ displayName: 'Role ID',+ description: 'Optional community role ID for the invitees.',+ }),+ default_space_ids: Property.Array({+ displayName: 'Default Space IDs',+ description: 'Optional spaces the invitees join.',+ required: false,+ }),+ },+ outputSchema: bettermodeSchemas.invitations,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const emails = bettermodeInput.stringList({ value: propsValue.emails, label: 'Emails' });+ if (emails.length === 0 || emails.length > MAX_INVITES) {+ throw new Error(`Emails must contain between 1 and ${MAX_INVITES} addresses.`);+ }+ emails.forEach((email) => bettermodeInput.email({ value: email, label: 'Each email' }));+ const spaceIds = bettermodeInput.stringList({ value: propsValue.default_space_ids, label: 'Default Space IDs' });+ const input: Record<string, unknown> = {+ invitees: emails.map((email) => ({ email })),+ };+ const message = bettermodeInput.optionalText(propsValue.invitation_message);+ if (message !== undefined) {+ input['invitationMessage'] = message;+ }+ const roleId = bettermodeInput.optionalText(propsValue.role_id);+ if (roleId !== undefined) {+ input['roleId'] = roleId;+ }+ if (spaceIds.length > 0) {+ input['defaultSpacesIds'] = spaceIds;+ }+ const data = await bettermodeQuery({+ auth: auth.props,+ query: `mutation InviteMembers($input: InviteMembersInput!) {+ inviteMembers(input: $input) {+ id+ inviteeEmail+ inviteeName+ status+ expiresAt+ createdAt+ }+}`,+ variables: { input },+ });+ const items = bettermodeMap.records(data['inviteMembers']).map(bettermodeMap.invitation);+ return { items, count: items.length };+ },+});++export const suspendMemberAction = createAction({+ auth: bettermodeAuth,+ name: 'suspend_member',+ classification: 'DESTRUCTIVE',+ displayName: 'Suspend Member',+ description: 'Suspend a member so they can no longer log in.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Suspends a member: they are logged out and cannot sign in or post until unsuspended. Admin only. Only call when the user explicitly asked to suspend this exact member.',+ idempotent: false,+ },+ props: {+ member_id: bettermodeAiProps.id({ displayName: 'Member ID', description: 'The member ID.' }),+ },+ outputSchema: bettermodeSchemas.memberAction,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const memberId = bettermodeInput.requireText({ value: propsValue.member_id, label: 'Member ID' });+ const status = await bettermodeOps.runActionMutation({+ auth: auth.props,+ query: `mutation SuspendMember($memberId: String!) {+ suspendMember(memberId: $memberId) {+ status+ }+}`,+ variables: { memberId },+ field: 'suspendMember',+ });+ return { success: true, status, member_id: memberId };+ },+});++export const unsuspendMemberAction = createAction({+ auth: bettermodeAuth,+ name: 'unsuspend_member',+ classification: 'WRITE',+ displayName: 'Unsuspend Member',+ description: 'Restore access for a suspended member.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lifts a suspension so the member can sign in again. Admin only.',+ idempotent: false,+ },+ props: {+ member_id: bettermodeAiProps.id({ displayName: 'Member ID', description: 'The member ID.' }),+ },+ outputSchema: bettermodeSchemas.memberAction,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const memberId = bettermodeInput.requireText({ value: propsValue.member_id, label: 'Member ID' });+ const status = await bettermodeOps.runActionMutation({+ auth: auth.props,+ query: `mutation UnsuspendMember($memberId: String!) {+ unsuspendMember(memberId: $memberId) {+ status+ }+}`,+ variables: { memberId },+ field: 'unsuspendMember',+ });+ return { success: true, status, member_id: memberId };+ },+});++export const deleteMemberAction = createAction({+ auth: bettermodeAuth,+ name: 'delete_member',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Member',+ description: 'Permanently delete a member from the community.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Permanently deletes a member account from the community; this cannot be undone. Admin only. Only call when the user explicitly asked to delete this exact member; prefer Suspend Member when unsure.',+ idempotent: false,+ },+ props: {+ member_id: bettermodeAiProps.id({ displayName: 'Member ID', description: 'The member to delete.' }),+ },+ outputSchema: bettermodeSchemas.deleted,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const memberId = bettermodeInput.requireText({ value: propsValue.member_id, label: 'Member ID' });+ const status = await bettermodeOps.runActionMutation({+ auth: auth.props,+ query: `mutation DeleteMember($id: ID!) {+ deleteMember(id: $id) {+ status+ }+}`,+ variables: { id: memberId },+ field: 'deleteMember',+ });+ return { id: memberId, deleted: true, status };+ },+});++export const sendDirectMessageAction = createAction({+ auth: bettermodeAuth,+ name: 'send_direct_message',+ classification: 'WRITE',+ displayName: 'Send Direct Message',+ description: 'Send a chat message to a member.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Sends a private chat message from the connected member to another member. Needs chat enabled on the community plan. Each call sends a new message, so retries send duplicates.',+ idempotent: false,+ },+ props: {+ recipient_id: bettermodeAiProps.id({ displayName: 'Recipient Member ID', description: 'The member to message.' }),+ content: Property.LongText({ displayName: 'Message', description: 'The message text.', required: true }),+ },+ outputSchema: bettermodeSchemas.message,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const recipientId = bettermodeInput.requireText({ value: propsValue.recipient_id, label: 'Recipient Member ID' });+ const content = bettermodeInput.requireText({ value: propsValue.content, label: 'Message' });+ const data = await bettermodeQuery({+ auth: auth.props,+ query: `mutation SendMessage($input: SendMessageToMemberInput!) {+ sendMessageToMember(input: $input) {+ chatId+ message {+ _id+ content+ sentAt+ }+ }+}`,+ variables: { input: { recipientId, message: { content } } },+ });+ const sent = data['sendMessageToMember'];+ return {+ message_id: bettermodeMap.text(readPath({ value: sent, path: ['message', '_id'] })),+ chat_id: bettermodeMap.text(readPath({ value: sent, path: ['chatId'] })),+ recipient_id: recipientId,+ content: bettermodeMap.text(readPath({ value: sent, path: ['message', 'content'] })),+ sent_at: bettermodeMap.text(readPath({ value: sent, path: ['message', 'sentAt'] })),+ };+ },+});+++const MAX_INVITES = 20;diff --git a/packages/pieces/community/bettermode/src/lib/actions/ai/posts.ts b/packages/pieces/community/bettermode/src/lib/actions/ai/posts.tsnew file mode 100644index 00000000000..55165e95102--- /dev/null+++ b/packages/pieces/community/bettermode/src/lib/actions/ai/posts.ts@@ -0,0 +1,765 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { bettermodeAuth } from '../../auth';+import { bindTokenStore, bettermodeQuery, BettermodeCredentials, readPath } from '../../common/client';+import { bettermodeAiProps } from '../../common/ai-props';+import { PAGE_INFO, POST_FIELDS, POST_TYPE_FIELDS, TAG_FIELDS } from '../../common/fields';+import { bettermodeInput } from '../../common/input';+import { bettermodeMap } from '../../common/mappers';+import { bettermodeOps } from '../../common/operations';+import { bettermodeSchemas } from '../../common/schemas';++export const listPostTypesAction = createAction({+ auth: bettermodeAuth,+ name: 'list_post_types',+ classification: 'SEARCH',+ displayName: 'List Post Types',+ description: 'List the post types (Discussion, Question, Article...) of the community.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists post types with their IDs, one page at a time. Use to get the Post Type ID that Create Post needs; set Context to reply to get reply/comment types. Read-only, safe to retry.',+ idempotent: true,+ },+ props: {+ context: Property.StaticDropdown({+ displayName: 'Context',+ description: 'post for top-level post types, reply for reply types. Leave empty for both.',+ required: false,+ options: {+ options: [+ { label: 'Post', value: 'post' },+ { label: 'Reply', value: 'reply' },+ ],+ },+ }),+ query: Property.ShortText({ displayName: 'Search', description: 'Filter post types by name.', required: false }),+ limit: bettermodeAiProps.limit(),+ cursor: bettermodeAiProps.cursor(),+ },+ outputSchema: bettermodeSchemas.postTypes,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const context = bettermodeInput.optionalText(propsValue.context);+ if (context !== undefined && context !== 'post' && context !== 'reply') {+ throw new Error('Context must be post or reply.');+ }+ const data = await bettermodeQuery({+ auth: auth.props,+ query: `query ListPostTypes($limit: Int!, $after: String, $context: PostTypeContext, $query: String) {+ postTypes(limit: $limit, after: $after, context: $context, query: $query) {+ nodes {+${POST_TYPE_FIELDS}+ }+ ${PAGE_INFO}+ }+}`,+ variables: {+ limit: bettermodeInput.limit({ value: propsValue.limit }),+ after: bettermodeInput.optionalText(propsValue.cursor) ?? null,+ context,+ query: bettermodeInput.optionalText(propsValue.query),+ },+ });+ return bettermodeMap.page({ value: data['postTypes'], map: bettermodeMap.postType });+ },+});++export const listPostsAction = createAction({+ auth: bettermodeAuth,+ name: 'list_posts',+ classification: 'SEARCH',+ displayName: 'List Posts',+ description: 'List posts, optionally limited to spaces and post types.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists posts (newest activity order chosen by Order By) one page at a time, optionally only in given spaces or of given post types. Use to browse recent posts; use Search Posts for keyword search. Read-only, safe to retry.',+ idempotent: true,+ },+ props: {+ space_ids: Property.Array({ displayName: 'Space IDs', description: 'Only posts in these spaces.', required: false }),+ post_type_ids: Property.Array({+ displayName: 'Post Type IDs',+ description: 'Only posts of these post types (from List Post Types).',+ required: false,+ }),+ order_by: Property.StaticDropdown({+ displayName: 'Order By',+ description: 'Sort field. Defaults to createdAt.',+ required: false,+ options: {+ options: [+ { label: 'Created At', value: 'createdAt' },+ { label: 'Published At', value: 'publishedAt' },+ { label: 'Last Activity', value: 'lastActivityAt' },+ { label: 'Updated At', value: 'updatedAt' },+ { label: 'Replies Count', value: 'repliesCount' },+ { label: 'Reactions Count', value: 'reactionsCount' },+ ],+ },+ }),+ reverse: Property.Checkbox({+ displayName: 'Reverse Order',+ description: 'Reverse the sort direction.',+ required: false,+ }),+ limit: bettermodeAiProps.limit(),+ cursor: bettermodeAiProps.cursor(),+ },+ outputSchema: bettermodeSchemas.posts,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const spaceIds = bettermodeInput.stringList({ value: propsValue.space_ids, label: 'Space IDs' });+ const postTypeIds = bettermodeInput.stringList({ value: propsValue.post_type_ids, label: 'Post Type IDs' });+ const orderBy = bettermodeInput.optionalText(propsValue.order_by) ?? 'createdAt';+ if (!ORDER_BY_VALUES.includes(orderBy)) {+ throw new Error(`Order By must be one of ${ORDER_BY_VALUES.join(', ')}.`);+ }+ const data = await bettermodeQuery({+ auth: auth.props,+ query: `query ListPosts($limit: Int!, $after: String, $spaceIds: [ID!], $postTypeIds: [String!], $orderBy: PostListOrderByEnum, $reverse: Boolean) {+ posts(limit: $limit, after: $after, spaceIds: $spaceIds, postTypeIds: $postTypeIds, orderBy: $orderBy, reverse: $reverse) {+ nodes {+${POST_FIELDS}+ }+ ${PAGE_INFO}+ }+}`,+ variables: {+ limit: bettermodeInput.limit({ value: propsValue.limit }),+ after: bettermodeInput.optionalText(propsValue.cursor) ?? null,+ spaceIds: spaceIds.length > 0 ? spaceIds : undefined,+ postTypeIds: postTypeIds.length > 0 ? postTypeIds : undefined,+ orderBy,+ reverse: bettermodeInput.optionalBoolean({ value: propsValue.reverse, label: 'Reverse Order' }),+ },+ });+ return bettermodeMap.page({ value: data['posts'], map: bettermodeMap.post });+ },+});++export const searchPostsAction = createAction({+ auth: bettermodeAuth,+ name: 'search_posts',+ classification: 'SEARCH',+ displayName: 'Search Posts',+ description: 'Search posts by keyword.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Full-text search over posts the connected member can see, one page at a time. Use when you know words from the title or content; use List Posts to browse a space. Read-only, safe to retry.',+ idempotent: true,+ },+ props: {+ query: Property.ShortText({ displayName: 'Search Text', description: 'Words to search for.', required: true }),+ limit: bettermodeAiProps.limit(),+ cursor: bettermodeAiProps.cursor(),+ },+ outputSchema: bettermodeSchemas.posts,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const data = await bettermodeQuery({+ auth: auth.props,+ query: `query SearchPosts($query: String!, $limit: Int!, $after: String) {+ searchPosts(query: $query, limit: $limit, after: $after) {+ nodes {+${POST_FIELDS}+ }+ ${PAGE_INFO}+ }+}`,+ variables: {+ query: bettermodeInput.requireText({ value: propsValue.query, label: 'Search Text' }),+ limit: bettermodeInput.limit({ value: propsValue.limit }),+ after: bettermodeInput.optionalText(propsValue.cursor) ?? null,+ },+ });+ return bettermodeMap.page({ value: data['searchPosts'], map: bettermodeMap.post });+ },+});++export const getPostAction = createAction({+ auth: bettermodeAuth,+ name: 'get_post',+ classification: 'READ',+ displayName: 'Get Post',+ description: 'Get a post or reply by ID.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns one post or reply by ID with title, HTML content, tags, author and counts. Use to read a post before replying to or updating it. Read-only, safe to retry.',+ idempotent: true,+ },+ props: {+ post_id: bettermodeAiProps.id({ displayName: 'Post ID', description: 'The post ID.' }),+ },+ outputSchema: bettermodeSchemas.post,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const post = await fetchPost({+ auth: auth.props,+ postId: bettermodeInput.requireText({ value: propsValue.post_id, label: 'Post ID' }),+ });+ return bettermodeMap.post(post);+ },+});++export const createPostAction = createAction({+ auth: bettermodeAuth,+ name: 'create_post',+ classification: 'WRITE',+ displayName: 'Create Post',+ description: 'Publish a post of any post type in a space.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Publishes a new post in a space with a title, HTML content and optional tags. Needs the Space ID (List Spaces) and Post Type ID (List Post Types). Each call creates a separate post, so retries duplicate.',+ idempotent: false,+ },+ props: {+ space_id: bettermodeAiProps.id({ displayName: 'Space ID', description: 'The space to post in.' }),+ post_type_id: bettermodeAiProps.id({ displayName: 'Post Type ID', description: 'The post type ID (from List Post Types).' }),+ title: Property.ShortText({ displayName: 'Title', description: 'The post title.', required: true }),+ content: Property.LongText({ displayName: 'Content', description: 'The post body. HTML is supported.', required: true }),+ tag_names: Property.Array({ displayName: 'Tags', description: 'Tag names to add. New names create tags.', required: false }),+ locked: Property.Checkbox({ displayName: 'Locked', description: 'Lock the post so nobody can reply.', required: false }),+ },+ outputSchema: bettermodeSchemas.post,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ return bettermodeOps.createPost({+ auth: auth.props,+ spaceId: bettermodeInput.requireText({ value: propsValue.space_id, label: 'Space ID' }),+ postTypeId: bettermodeInput.requireText({ value: propsValue.post_type_id, label: 'Post Type ID' }),+ title: bettermodeInput.requireText({ value: propsValue.title, label: 'Title' }),+ content: bettermodeInput.requireText({ value: propsValue.content, label: 'Content' }),+ tagNames: bettermodeOps.tagNames(propsValue.tag_names),+ locked: bettermodeInput.optionalBoolean({ value: propsValue.locked, label: 'Locked' }),+ });+ },+});++export const updatePostAction = createAction({+ auth: bettermodeAuth,+ name: 'update_post',+ classification: 'WRITE',+ displayName: 'Update Post',+ description: 'Change the title, content, tags or lock state of a post.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Updates only the fields you give on an existing post or reply: title, HTML content, tags (replaces the tag list; Clear Tags removes all) and lock state. Use Get Post first if you need the current text. Setting the same values again changes nothing, so retries are safe.',+ idempotent: true,+ },+ props: {+ post_id: bettermodeAiProps.id({ displayName: 'Post ID', description: 'The post to update.' }),+ title: Property.ShortText({ displayName: 'Title', description: 'New title. Leave empty to keep it.', required: false }),+ content: Property.LongText({+ displayName: 'Content',+ description: 'New HTML body. Leave empty to keep it.',+ required: false,+ }),+ tag_names: Property.Array({+ displayName: 'Tags',+ description: 'Replaces all tags with these names. Leave empty to keep the tags.',+ required: false,+ }),+ clear_tags: Property.Checkbox({ displayName: 'Clear Tags', description: 'Remove all tags.', required: false }),+ lock: Property.StaticDropdown({+ displayName: 'Lock State',+ description: 'Lock or unlock replies. Leave empty to keep it.',+ required: false,+ options: {+ options: [+ { label: 'Lock', value: 'lock' },+ { label: 'Unlock', value: 'unlock' },+ ],+ },+ }),+ },+ outputSchema: bettermodeSchemas.post,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const postId = bettermodeInput.requireText({ value: propsValue.post_id, label: 'Post ID' });+ const title = bettermodeInput.optionalText(propsValue.title);+ const content = typeof propsValue.content === 'string' && propsValue.content.trim().length > 0 ? propsValue.content : undefined;+ const tags = bettermodeOps.tagNames(propsValue.tag_names);+ const clearTags = bettermodeInput.optionalBoolean({ value: propsValue.clear_tags, label: 'Clear Tags' }) === true;+ const lock = bettermodeInput.optionalText(propsValue.lock);+ if (clearTags && tags.length > 0) {+ throw new Error('Give Tags or Clear Tags, not both.');+ }+ if (lock !== undefined && lock !== 'lock' && lock !== 'unlock') {+ throw new Error('Lock State must be lock or unlock.');+ }+ const mappingFields = [+ ...(title === undefined ? [] : [{ key: 'title', type: 'text', value: JSON.stringify(title) }]),+ ...(content === undefined ? [] : [{ key: 'content', type: 'html', value: JSON.stringify(content) }]),+ ];+ const input: Record<string, unknown> = {};+ if (mappingFields.length > 0) {+ input['mappingFields'] = mappingFields;+ }+ if (clearTags) {+ input['tagNames'] = [];+ } else if (tags.length > 0) {+ input['tagNames'] = tags;+ }+ if (lock !== undefined) {+ input['locked'] = lock === 'lock';+ }+ if (Object.keys(input).length === 0) {+ throw new Error('Give at least one field to update.');+ }+ const data = await bettermodeQuery({+ auth: auth.props,+ query: `mutation UpdatePost($id: ID!, $input: UpdatePostInput!) {+ updatePost(id: $id, input: $input) {+${POST_FIELDS}+ }+}`,+ variables: { id: postId, input },+ });+ return bettermodeMap.post(data['updatePost']);+ },+});++export const deletePostAction = createAction({+ auth: bettermodeAuth,+ name: 'delete_post',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Post',+ description: 'Permanently delete a post or reply.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Permanently deletes a post or reply and its replies. Only call when the user asked to delete this exact post; use Hide Post to take it out of view reversibly. A second call fails because the post is gone.',+ idempotent: false,+ },+ props: {+ post_id: bettermodeAiProps.id({ displayName: 'Post ID', description: 'The post to delete.' }),+ },+ outputSchema: bettermodeSchemas.deleted,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const postId = bettermodeInput.requireText({ value: propsValue.post_id, label: 'Post ID' });+ const status = await bettermodeOps.runActionMutation({+ auth: auth.props,+ query: `mutation DeletePost($id: ID!) {+ deletePost(id: $id) {+ status+ }+}`,+ variables: { id: postId },+ field: 'deletePost',+ });+ return { id: postId, deleted: true, status };+ },+});++export const listRepliesAction = createAction({+ auth: bettermodeAuth,+ name: 'list_replies',+ classification: 'SEARCH',+ displayName: 'List Replies',+ description: 'List the replies of a post.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists replies to one post (or to one reply, for nested threads), one page at a time. Use to read a discussion before answering. Read-only, safe to retry.',+ idempotent: true,+ },+ props: {+ post_id: bettermodeAiProps.id({ displayName: 'Post ID', description: 'The post whose replies to list.' }),+ limit: bettermodeAiProps.limit(),+ cursor: bettermodeAiProps.cursor(),+ },+ outputSchema: bettermodeSchemas.posts,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const data = await bettermodeQuery({+ auth: auth.props,+ query: `query ListReplies($postId: ID!, $limit: Int!, $after: String) {+ replies(postId: $postId, limit: $limit, after: $after) {+ nodes {+${POST_FIELDS}+ }+ ${PAGE_INFO}+ }+}`,+ variables: {+ postId: bettermodeInput.requireText({ value: propsValue.post_id, label: 'Post ID' }),+ limit: bettermodeInput.limit({ value: propsValue.limit }),+ after: bettermodeInput.optionalText(propsValue.cursor) ?? null,+ },+ });+ return bettermodeMap.page({ value: data['replies'], map: bettermodeMap.post });+ },+});++export const createReplyAction = createAction({+ auth: bettermodeAuth,+ name: 'create_reply',+ classification: 'WRITE',+ displayName: 'Create Reply',+ description: 'Reply to a post.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Posts a reply (comment or answer) with HTML content under a post or reply. The reply type defaults to the first reply type the parent allows. Each call adds a new reply, so retries duplicate.',+ idempotent: false,+ },+ props: {+ post_id: bettermodeAiProps.id({ displayName: 'Post ID', description: 'The post or reply to answer.' }),+ content: Property.LongText({ displayName: 'Content', description: 'The reply body. HTML is supported.', required: true }),+ reply_post_type_id: bettermodeAiProps.optionalId({+ displayName: 'Reply Post Type ID',+ description: 'Optional reply type ID (List Post Types with Context reply). Defaults to the type the parent allows.',+ }),+ },+ outputSchema: bettermodeSchemas.post,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const postId = bettermodeInput.requireText({ value: propsValue.post_id, label: 'Post ID' });+ const content = bettermodeInput.requireText({ value: propsValue.content, label: 'Content' });+ const postTypeId =+ bettermodeInput.optionalText(propsValue.reply_post_type_id) ??+ (await defaultReplyTypeId({ auth: auth.props, postId }));+ const data = await bettermodeQuery({+ auth: auth.props,+ query: `mutation CreateReply($postId: ID!, $input: CreatePostInput!) {+ createReply(postId: $postId, input: $input) {+${POST_FIELDS}+ }+}`,+ variables: {+ postId,+ input: {+ postTypeId,+ mappingFields: [{ key: 'content', type: 'html', value: JSON.stringify(content) }],+ },+ },+ });+ return bettermodeOps.publishIfDraft({ auth: auth.props, post: bettermodeMap.post(data['createReply']) });+ },+});++export const addReactionAction = createAction({+ auth: bettermodeAuth,+ name: 'add_reaction',+ classification: 'WRITE',+ displayName: 'Add Reaction',+ description: 'React to a post as the connected member.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Adds a reaction (for example +1, heart, or an upvote key the post type allows) to a post as the connected member. Use Remove Reaction to undo. Not verified as retry-safe.',+ idempotent: false,+ },+ props: {+ post_id: bettermodeAiProps.id({ displayName: 'Post ID', description: 'The post to react to.' }),+ reaction: Property.ShortText({+ displayName: 'Reaction',+ description: 'The reaction key, for example +1 or heart.',+ required: true,+ }),+ },+ outputSchema: bettermodeSchemas.reaction,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const postId = bettermodeInput.requireText({ value: propsValue.post_id, label: 'Post ID' });+ const reaction = bettermodeInput.requireText({ value: propsValue.reaction, label: 'Reaction' });+ const status = await bettermodeOps.runActionMutation({+ auth: auth.props,+ query: `mutation AddReaction($postId: ID!, $input: AddReactionInput!) {+ addReaction(postId: $postId, input: $input) {+ status+ }+}`,+ variables: { postId, input: { reaction } },+ field: 'addReaction',+ });+ return { success: true, status, post_id: postId, reaction };+ },+});++export const removeReactionAction = createAction({+ auth: bettermodeAuth,+ name: 'remove_reaction',+ classification: 'WRITE',+ displayName: 'Remove Reaction',+ description: "Remove the connected member's reaction from a post.",+ audience: 'ai',+ aiMetadata: {+ description:+ 'Removes a reaction the connected member added to a post. Use to undo Add Reaction. Not verified as retry-safe: removing a reaction that is not there may error.',+ idempotent: false,+ },+ props: {+ post_id: bettermodeAiProps.id({ displayName: 'Post ID', description: 'The post.' }),+ reaction: Property.ShortText({ displayName: 'Reaction', description: 'The reaction key to remove.', required: true }),+ },+ outputSchema: bettermodeSchemas.reaction,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const postId = bettermodeInput.requireText({ value: propsValue.post_id, label: 'Post ID' });+ const reaction = bettermodeInput.requireText({ value: propsValue.reaction, label: 'Reaction' });+ const status = await bettermodeOps.runActionMutation({+ auth: auth.props,+ query: `mutation RemoveReaction($postId: ID!, $reaction: String!) {+ removeReaction(postId: $postId, reaction: $reaction) {+ status+ }+}`,+ variables: { postId, reaction },+ field: 'removeReaction',+ });+ return { success: true, status, post_id: postId, reaction };+ },+});++export const pinPostAction = createAction({+ auth: bettermodeAuth,+ name: 'pin_post',+ classification: 'WRITE',+ displayName: 'Pin Post',+ description: 'Pin a post to the top of its space.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Pins a post to the top of its space. Use Unpin Post to undo. Needs moderator or admin rights. Not verified as retry-safe.',+ idempotent: false,+ },+ props: {+ post_id: bettermodeAiProps.id({ displayName: 'Post ID', description: 'The post ID.' }),+ },+ outputSchema: bettermodeSchemas.postAction,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const postId = bettermodeInput.requireText({ value: propsValue.post_id, label: 'Post ID' });+ const status = await bettermodeOps.runActionMutation({+ auth: auth.props,+ query: `mutation PinPost($postId: ID!) {+ pinPostToSpace(postId: $postId) {+ status+ }+}`,+ variables: { postId: postId },+ field: 'pinPostToSpace',+ });+ return { success: true, status, post_id: postId };+ },+});++export const unpinPostAction = createAction({+ auth: bettermodeAuth,+ name: 'unpin_post',+ classification: 'WRITE',+ displayName: 'Unpin Post',+ description: 'Unpin a post from its space.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Removes a pinned post from the top of its space. Needs moderator or admin rights. Not verified as retry-safe.',+ idempotent: false,+ },+ props: {+ post_id: bettermodeAiProps.id({ displayName: 'Post ID', description: 'The post ID.' }),+ },+ outputSchema: bettermodeSchemas.postAction,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const postId = bettermodeInput.requireText({ value: propsValue.post_id, label: 'Post ID' });+ const status = await bettermodeOps.runActionMutation({+ auth: auth.props,+ query: `mutation UnpinPost($postId: ID!) {+ unpinPostFromSpace(postId: $postId) {+ status+ }+}`,+ variables: { postId: postId },+ field: 'unpinPostFromSpace',+ });+ return { success: true, status, post_id: postId };+ },+});++export const hidePostAction = createAction({+ auth: bettermodeAuth,+ name: 'hide_post',+ classification: 'WRITE',+ displayName: 'Hide Post',+ description: 'Hide a post from members.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Hides a post from regular members without deleting it; use Unhide Post to restore it. Prefer this over Delete Post when unsure. Needs moderator or admin rights.',+ idempotent: false,+ },+ props: {+ post_id: bettermodeAiProps.id({ displayName: 'Post ID', description: 'The post ID.' }),+ },+ outputSchema: bettermodeSchemas.postAction,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const postId = bettermodeInput.requireText({ value: propsValue.post_id, label: 'Post ID' });+ const status = await bettermodeOps.runActionMutation({+ auth: auth.props,+ query: `mutation HidePost($id: ID!) {+ hidePost(id: $id) {+ status+ }+}`,+ variables: { id: postId },+ field: 'hidePost',+ });+ return { success: true, status, post_id: postId };+ },+});++export const unhidePostAction = createAction({+ auth: bettermodeAuth,+ name: 'unhide_post',+ classification: 'WRITE',+ displayName: 'Unhide Post',+ description: 'Make a hidden post visible again.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Makes a hidden post visible to members again. Needs moderator or admin rights.',+ idempotent: false,+ },+ props: {+ post_id: bettermodeAiProps.id({ displayName: 'Post ID', description: 'The post ID.' }),+ },+ outputSchema: bettermodeSchemas.postAction,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const postId = bettermodeInput.requireText({ value: propsValue.post_id, label: 'Post ID' });+ const status = await bettermodeOps.runActionMutation({+ auth: auth.props,+ query: `mutation UnhidePost($id: ID!) {+ unhidePost(id: $id) {+ status+ }+}`,+ variables: { id: postId },+ field: 'unhidePost',+ });+ return { success: true, status, post_id: postId };+ },+});++export const movePostAction = createAction({+ auth: bettermodeAuth,+ name: 'move_post',+ classification: 'WRITE',+ displayName: 'Move Post',+ description: 'Move a post to another space.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Moves a post (with its replies) to another space. The target space must accept the post type. Not verified as retry-safe.',+ idempotent: false,+ },+ props: {+ post_id: bettermodeAiProps.id({ displayName: 'Post ID', description: 'The post to move.' }),+ space_id: bettermodeAiProps.id({ displayName: 'Target Space ID', description: 'The space to move it to.' }),+ },+ outputSchema: bettermodeSchemas.post,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const data = await bettermodeQuery({+ auth: auth.props,+ query: `mutation MovePost($id: ID!, $spaceId: ID!) {+ movePost(id: $id, spaceId: $spaceId) {+${POST_FIELDS}+ }+}`,+ variables: {+ id: bettermodeInput.requireText({ value: propsValue.post_id, label: 'Post ID' }),+ spaceId: bettermodeInput.requireText({ value: propsValue.space_id, label: 'Target Space ID' }),+ },+ });+ return bettermodeMap.post(data['movePost']);+ },+});++export const listTagsAction = createAction({+ auth: bettermodeAuth,+ name: 'list_tags',+ classification: 'SEARCH',+ displayName: 'List Tags',+ description: 'List tags, optionally in one space or matching a name.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists post tags one page at a time, optionally only those used in a space or matching a name. Use to reuse existing tag names when creating or updating posts. Read-only, safe to retry.',+ idempotent: true,+ },+ props: {+ space_id: bettermodeAiProps.optionalId({ displayName: 'Space ID', description: 'Only tags of this space.' }),+ query: Property.ShortText({ displayName: 'Search', description: 'Filter tags by name.', required: false }),+ limit: bettermodeAiProps.limit(),+ cursor: bettermodeAiProps.cursor(),+ },+ outputSchema: bettermodeSchemas.tags,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const data = await bettermodeQuery({+ auth: auth.props,+ query: `query ListTags($limit: Int!, $after: String, $spaceId: ID, $query: String) {+ tags(limit: $limit, after: $after, spaceId: $spaceId, query: $query) {+ nodes {+${TAG_FIELDS}+ }+ ${PAGE_INFO}+ }+}`,+ variables: {+ limit: bettermodeInput.limit({ value: propsValue.limit }),+ after: bettermodeInput.optionalText(propsValue.cursor) ?? null,+ spaceId: bettermodeInput.optionalText(propsValue.space_id),+ query: bettermodeInput.optionalText(propsValue.query),+ },+ });+ return bettermodeMap.page({ value: data['tags'], map: bettermodeMap.tag });+ },+});+++async function fetchPost({ auth, postId }: { auth: BettermodeCredentials; postId: string }) {+ const data = await bettermodeQuery({+ auth,+ query: `query GetPost($id: ID!) {+ post(id: $id) {+${POST_FIELDS}+ }+}`,+ variables: { id: postId },+ });+ return data['post'];+}++async function defaultReplyTypeId({ auth, postId }: { auth: BettermodeCredentials; postId: string }): Promise<string> {+ const data = await bettermodeQuery({+ auth,+ query: `query GetReplyTypes($id: ID!) {+ post(id: $id) {+ id+ postType {+ validReplyTypes { id name }+ }+ }+}`,+ variables: { id: postId },+ });+ const replyTypes = bettermodeMap.records(readPath({ value: data, path: ['post', 'postType', 'validReplyTypes'] }));+ const first = replyTypes.map((type) => bettermodeMap.text(type['id'])).find((id): id is string => id !== null);+ if (first === undefined) {+ throw new Error('This post does not accept replies. Check the post type, or pass a Reply Post Type ID.');+ }+ return first;+}++const ORDER_BY_VALUES = ['createdAt', 'publishedAt', 'lastActivityAt', 'updatedAt', 'repliesCount', 'reactionsCount'];diff --git a/packages/pieces/community/bettermode/src/lib/actions/ai/spaces.ts b/packages/pieces/community/bettermode/src/lib/actions/ai/spaces.tsnew file mode 100644index 00000000000..58415a52db1--- /dev/null+++ b/packages/pieces/community/bettermode/src/lib/actions/ai/spaces.ts@@ -0,0 +1,240 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { bettermodeAuth } from '../../auth';+import { bindTokenStore, bettermodeQuery } from '../../common/client';+import { bettermodeAiProps } from '../../common/ai-props';+import { MEMBER_FIELDS, PAGE_INFO, SPACE_FIELDS } from '../../common/fields';+import { bettermodeInput } from '../../common/input';+import { bettermodeMap } from '../../common/mappers';+import { bettermodeOps } from '../../common/operations';+import { bettermodeSchemas } from '../../common/schemas';++export const listSpacesAction = createAction({+ auth: bettermodeAuth,+ name: 'list_spaces',+ classification: 'SEARCH',+ displayName: 'List Spaces',+ description: 'List spaces in the community, optionally filtered by name.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists community spaces (ID, name, slug, privacy, counts), one page at a time; filter by name with Search. Use to find the Space ID needed by Create Post, List Posts or space membership actions. Read-only, safe to retry.',+ idempotent: true,+ },+ props: {+ query: Property.ShortText({+ displayName: 'Search',+ description: 'Only return spaces whose name matches this text.',+ required: false,+ }),+ member_id: bettermodeAiProps.optionalId({+ displayName: 'Member ID',+ description: 'Only return spaces this member has joined.',+ }),+ limit: bettermodeAiProps.limit(),+ cursor: bettermodeAiProps.cursor(),+ },+ outputSchema: bettermodeSchemas.spaces,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ return bettermodeOps.listSpacesPage({+ auth: auth.props,+ limit: bettermodeInput.limit({ value: propsValue.limit }),+ after: bettermodeInput.optionalText(propsValue.cursor) ?? null,+ query: bettermodeInput.optionalText(propsValue.query),+ memberId: bettermodeInput.optionalText(propsValue.member_id),+ });+ },+});++export const getSpaceAction = createAction({+ auth: bettermodeAuth,+ name: 'get_space',+ classification: 'READ',+ displayName: 'Get Space',+ description: 'Get a space by ID or slug.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns one space by its ID or by its URL slug (give exactly one). Use when you have a space link or ID and need its details. Read-only, safe to retry.',+ idempotent: true,+ },+ props: {+ space_id: bettermodeAiProps.optionalId({ displayName: 'Space ID', description: 'The space ID. Give this or the slug.' }),+ slug: Property.ShortText({+ displayName: 'Space Slug',+ description: 'The slug from the space URL. Give this or the ID.',+ required: false,+ }),+ },+ outputSchema: bettermodeSchemas.space,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const id = bettermodeInput.optionalText(propsValue.space_id);+ const slug = bettermodeInput.optionalText(propsValue.slug);+ if ((id === undefined) === (slug === undefined)) {+ throw new Error('Give exactly one of Space ID or Space Slug.');+ }+ const data = await bettermodeQuery({+ auth: auth.props,+ query: `query GetSpace($id: ID, $slug: ID) {+ space(id: $id, slug: $slug) {+${SPACE_FIELDS}+ }+}`,+ variables: { id, slug },+ });+ return bettermodeMap.space(data['space']);+ },+});++export const listSpaceMembersAction = createAction({+ auth: bettermodeAuth,+ name: 'list_space_members',+ classification: 'SEARCH',+ displayName: 'List Space Members',+ description: 'List the members of a space.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists members of one space with their space role, one page at a time. Use to check who belongs to a space before adding or removing members. Read-only, safe to retry.',+ idempotent: true,+ },+ props: {+ space_id: bettermodeAiProps.id({ displayName: 'Space ID', description: 'The space ID (from List Spaces).' }),+ limit: bettermodeAiProps.limit(),+ cursor: bettermodeAiProps.cursor(),+ },+ outputSchema: bettermodeSchemas.spaceMembers,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const data = await bettermodeQuery({+ auth: auth.props,+ query: `query ListSpaceMembers($spaceId: ID!, $limit: Int!, $after: String) {+ spaceMembers(spaceId: $spaceId, limit: $limit, after: $after) {+ nodes {+ member {+${MEMBER_FIELDS}+ }+ role { id name }+ }+ ${PAGE_INFO}+ }+}`,+ variables: {+ spaceId: bettermodeInput.requireText({ value: propsValue.space_id, label: 'Space ID' }),+ limit: bettermodeInput.limit({ value: propsValue.limit }),+ after: bettermodeInput.optionalText(propsValue.cursor) ?? null,+ },+ });+ return bettermodeMap.page({ value: data['spaceMembers'], map: bettermodeMap.spaceMember });+ },+});++export const addMemberToSpaceAction = createAction({+ auth: bettermodeAuth,+ name: 'add_member_to_space',+ classification: 'WRITE',+ displayName: 'Add Members to Space',+ description: 'Add one or more members to a space.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Adds members (by member ID) to a space, optionally with a space role ID. Use after Find Member by Email when you only have an email. Needs space or community admin rights. Safe to retry: re-adding a member already in the space succeeds and leaves them out of the returned items.',+ idempotent: true,+ },+ props: {+ space_id: bettermodeAiProps.id({ displayName: 'Space ID', description: 'The space ID (from List Spaces).' }),+ member_ids: Property.Array({+ displayName: 'Member IDs',+ description: 'Member IDs to add (1-50).',+ required: true,+ }),+ role_id: bettermodeAiProps.optionalId({+ displayName: 'Space Role ID',+ description: 'Optional space role ID. Leave empty for the default member role.',+ }),+ },+ outputSchema: bettermodeSchemas.spaceMembership,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const spaceId = bettermodeInput.requireText({ value: propsValue.space_id, label: 'Space ID' });+ const memberIds = requireMemberIds(propsValue.member_ids);+ const roleId = bettermodeInput.optionalText(propsValue.role_id);+ const data = await bettermodeQuery({+ auth: auth.props,+ query: `mutation AddSpaceMembers($spaceId: ID!, $input: [AddSpaceMemberInput!]!) {+ addSpaceMembers(spaceId: $spaceId, input: $input) {+ member { id name email username }+ role { id name }+ }+}`,+ variables: {+ spaceId,+ input: memberIds.map((memberId) => (roleId === undefined ? { memberId } : { memberId, roleId })),+ },+ });+ return {+ space_id: spaceId,+ member_ids: memberIds.join(', '),+ items: bettermodeMap.records(data['addSpaceMembers']).map(bettermodeMap.spaceMember),+ };+ },+});++export const removeMemberFromSpaceAction = createAction({+ auth: bettermodeAuth,+ name: 'remove_member_from_space',+ classification: 'DESTRUCTIVE',+ displayName: 'Remove Members from Space',+ description: 'Remove one or more members from a space.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Removes members (by member ID) from a space; they lose access to a private space until re-added. Only call when the user asked to remove these exact members. Needs space or community admin rights.',+ idempotent: false,+ },+ props: {+ space_id: bettermodeAiProps.id({ displayName: 'Space ID', description: 'The space ID (from List Spaces).' }),+ member_ids: Property.Array({+ displayName: 'Member IDs',+ description: 'Member IDs to remove (1-50).',+ required: true,+ }),+ },+ outputSchema: bettermodeSchemas.removeFromSpace,+ async run({ auth, propsValue, store }) {+ bindTokenStore({ credentials: auth.props, store });+ const spaceId = bettermodeInput.requireText({ value: propsValue.space_id, label: 'Space ID' });+ const memberIds = requireMemberIds(propsValue.member_ids);+ const data = await bettermodeQuery({+ auth: auth.props,+ query: `mutation RemoveSpaceMembers($spaceId: ID!, $memberIds: [ID!]!) {+ removeSpaceMembers(spaceId: $spaceId, memberIds: $memberIds) {+ status+ }+}`,+ variables: { spaceId, memberIds },+ });+ const statuses = bettermodeMap.records(data['removeSpaceMembers']).map((item) => bettermodeMap.actionStatus(item));+ const failed = statuses.length === 0 || statuses.some((status) => status !== 'succeeded');+ if (failed) {+ throw new Error(+ `Bettermode did not remove every member from the space (statuses: ${statuses.join(', ') || 'none'}). Removing a member who is not in the space fails.`+ );+ }+ return { success: true, status: 'succeeded', space_id: spaceId, member_ids: memberIds.join(', ') };+ },+});++function requireMemberIds(value: unknown): string[] {+ const memberIds = bettermodeInput.stringList({ value, label: 'Member IDs' });+ if (memberIds.length === 0) {+ throw new Error('Member IDs must contain at least one member ID.');+ }+ if (memberIds.length > MAX_MEMBER_IDS) {+ throw new Error(`Give at most ${MAX_MEMBER_IDS} member IDs per call.`);+ }+ return memberIds;+}++const MAX_MEMBER_IDS = 50;diff --git a/packages/pieces/community/bettermode/src/lib/actions/assign-badge.ts b/packages/pieces/community/bettermode/src/lib/actions/assign-badge.tsindex 70b04cab9d9..afbcbf57e69 100644--- a/packages/pieces/community/bettermode/src/lib/actions/assign-badge.ts+++ b/packages/pieces/community/bettermode/src/lib/actions/assign-badge.ts@@ -1,37 +1,38 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { assignBadgeToMember } from '../api';-import { buildBadgesDropdown } from '../props';+import { bindTokenStore } from '../common/client';import { bettermodeAuth } from '../auth';+import { bettermodeInput } from '../common/input';+import { bettermodeOps } from '../common/operations';+import { badgesDropdown } from '../common/props';+import { bettermodeSchemas } from '../common/schemas';export const assignBadgeAction = createAction({name: 'assign_badge',classification: 'WRITE',auth: bettermodeAuth,- displayName: 'Assign Badge to Member',+ displayName: 'Assign Badge To Member',description: 'Assign an existing badge to a member by email',- audience: 'both',- aiMetadata: { description: 'Grants an existing Bettermode badge (by badge ID) to the member resolved from the given email address. The badge must already exist and the email must match a network member, or the call fails. Idempotent: the member ends up holding the badge regardless of how many times it is called.', idempotent: true },+ audience: 'human',+ aiMetadata: {+ description: 'Grants an existing badge to the member whose email matches exactly. Agents should use Find Member by Email and Assign Badge to Member instead. Fails when no member has that exact email.',+ idempotent: false,+ },props: {- badgeId: Property.Dropdown({- auth: bettermodeAuth,- displayName: 'Badge',- description: 'The badge to assign',- required: true,- refreshers: [],- options: async ({ auth }) =>- await buildBadgesDropdown(auth?.props),- }),+ badgeId: badgesDropdown,email: Property.ShortText({displayName: 'Email',- description: 'The email of the member to assign the badge to',+ description: 'The exact email of the member. The connected account must be an admin to look members up by email.',required: true,}),},+ outputSchema: bettermodeSchemas.legacyBadgeAction,async run(context) {- return await assignBadgeToMember(- context.auth.props,- context.propsValue.badgeId,- context.propsValue.email- );+ bindTokenStore({ credentials: context.auth.props, store: context.store });+ const auth = context.auth.props;+ const badgeId = bettermodeInput.requireText({ value: context.propsValue.badgeId, label: 'Badge' });+ const email = bettermodeInput.email({ value: context.propsValue.email, label: 'Email' });+ const member = await bettermodeOps.requireMemberByEmail({ auth, email });+ const result = await bettermodeOps.changeBadge({ auth, operation: 'assignBadge', badgeId, memberId: member.id });+ return { ...result, member_name: member.name, member_email: member.email };},});diff --git a/packages/pieces/community/bettermode/src/lib/actions/create-discussion.ts b/packages/pieces/community/bettermode/src/lib/actions/create-discussion.tsindex 50040a1d46d..ad8143fca53 100644--- a/packages/pieces/community/bettermode/src/lib/actions/create-discussion.ts+++ b/packages/pieces/community/bettermode/src/lib/actions/create-discussion.ts@@ -1,7 +1,9 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { createDiscussion } from '../api';-import { buildMemberSpacesDropdown } from '../props';+import { bindTokenStore } from '../common/client';import { bettermodeAuth } from '../auth';+import { bettermodeSchemas } from '../common/schemas';+import { memberSpacesDropdown } from '../common/props';+import { createLegacyPost } from './create-post-of-type';export const createDiscussionAction = createAction({name: 'create_discussion',@@ -9,18 +11,14 @@ export const createDiscussionAction = createAction({auth: bettermodeAuth,displayName: 'Create Discussion Post',description: 'Create a new discussion post in a space',- audience: 'both',- aiMetadata: { description: 'Publishes a new discussion post (title, HTML content, optional comma-separated tags, optional locked flag) into a Bettermode community space identified by its space ID. Use to start a conversation thread programmatically. Not idempotent: each call publishes a separate post.', idempotent: false },+ audience: 'human',+ aiMetadata: {+ description:+ 'Publishes a new post of the community post type named exactly "Discussion" into a space the connected member has joined. Agents should use List Post Types and Create Post instead. Each call creates a separate post, so retries duplicate.',+ idempotent: false,+ },props: {- spaceId: Property.Dropdown({- auth: bettermodeAuth,- displayName: 'Space',- description: 'The space to create the discussion in',- required: true,- refreshers: [],- options: async ({ auth }) =>- await buildMemberSpacesDropdown(auth?.props),- }),+ spaceId: memberSpacesDropdown,title: Property.ShortText({displayName: 'Title',description: 'The title of the discussion',@@ -28,12 +26,12 @@ export const createDiscussionAction = createAction({}),content: Property.LongText({displayName: 'Content',- description: 'The content of the discussion',+ description: 'The content of the discussion. HTML is supported.',required: true,}),tagNames: Property.ShortText({displayName: 'Tags',- description: 'The tags to add to the discussion',+ description: 'Comma-separated tag names to add, for example onboarding, feedback. Leave empty for no tags.',required: false,}),locked: Property.Checkbox({@@ -43,14 +41,13 @@ export const createDiscussionAction = createAction({defaultValue: false,}),},+ outputSchema: bettermodeSchemas.legacyPost,async run(context) {- return await createDiscussion(- context.auth.props,- context.propsValue.spaceId,- context.propsValue.tagNames ?? '',- context.propsValue.title,- context.propsValue.content,- context.propsValue.locked- );+ bindTokenStore({ credentials: context.auth.props, store: context.store });+ return createLegacyPost({+ auth: context.auth.props,+ postTypeName: 'Discussion',+ propsValue: context.propsValue,+ });},});diff --git a/packages/pieces/community/bettermode/src/lib/actions/create-post-of-type.ts b/packages/pieces/community/bettermode/src/lib/actions/create-post-of-type.tsnew file mode 100644index 00000000000..87492b8c87a--- /dev/null+++ b/packages/pieces/community/bettermode/src/lib/actions/create-post-of-type.ts@@ -0,0 +1,30 @@+import { BettermodeCredentials } from '../common/client';+import { bettermodeInput } from '../common/input';+import { bettermodeOps } from '../common/operations';++export async function createLegacyPost({+ auth,+ postTypeName,+ propsValue,+}: {+ auth: BettermodeCredentials;+ postTypeName: string;+ propsValue: { spaceId: unknown; title: unknown; content: unknown; tagNames?: unknown; locked?: unknown };+}) {+ const spaceId = bettermodeInput.requireText({ value: propsValue.spaceId, label: 'Space' });+ const title = bettermodeInput.requireText({ value: propsValue.title, label: 'Title' });+ const content = bettermodeInput.requireText({ value: propsValue.content, label: 'Content' });+ const tagNames = bettermodeOps.tagNames(propsValue.tagNames);+ const locked = bettermodeInput.optionalBoolean({ value: propsValue.locked, label: 'Locked' }) ?? false;+ const postType = await bettermodeOps.findPostTypeByName({ auth, name: postTypeName, spaceId });+ const post = await bettermodeOps.createPost({+ auth,+ spaceId,+ postTypeId: postType.id,+ title,+ content,+ tagNames,+ locked,+ });+ return { createdAt: post.created_at, ...post };+}diff --git a/packages/pieces/community/bettermode/src/lib/actions/create-question.ts b/packages/pieces/community/bettermode/src/lib/actions/create-question.tsindex 2526784ba52..be26f74d20d 100644--- a/packages/pieces/community/bettermode/src/lib/actions/create-question.ts+++ b/packages/pieces/community/bettermode/src/lib/actions/create-question.ts@@ -1,7 +1,9 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { createQuestion } from '../api';-import { buildMemberSpacesDropdown } from '../props';+import { bindTokenStore } from '../common/client';import { bettermodeAuth } from '../auth';+import { bettermodeSchemas } from '../common/schemas';+import { memberSpacesDropdown } from '../common/props';+import { createLegacyPost } from './create-post-of-type';export const createQuestionAction = createAction({name: 'create_question',@@ -9,18 +11,14 @@ export const createQuestionAction = createAction({auth: bettermodeAuth,displayName: 'Create Question Post',description: 'Create a new question post in a space',- audience: 'both',- aiMetadata: { description: 'Publishes a new question post (title, HTML content, optional comma-separated tags, optional locked flag) into a Bettermode community space identified by its space ID. Use to post a question thread programmatically; the post type is "Question" rather than a discussion. Not idempotent: each call publishes a separate post.', idempotent: false },+ audience: 'human',+ aiMetadata: {+ description:+ 'Publishes a new post of the community post type named exactly "Question" into a space the connected member has joined. Agents should use List Post Types and Create Post instead. Each call creates a separate post, so retries duplicate.',+ idempotent: false,+ },props: {- spaceId: Property.Dropdown({- auth: bettermodeAuth,- displayName: 'Space',- description: 'The space to create the question in',- required: true,- refreshers: [],- options: async ({ auth }) =>- await buildMemberSpacesDropdown(auth?.props),- }),+ spaceId: memberSpacesDropdown,title: Property.ShortText({displayName: 'Title',description: 'The title of the question',@@ -28,12 +26,12 @@ export const createQuestionAction = createAction({}),content: Property.LongText({displayName: 'Content',- description: 'The content of the question',+ description: 'The content of the question. HTML is supported.',required: true,}),tagNames: Property.ShortText({displayName: 'Tags',- description: 'The tags to add to the question',+ description: 'Comma-separated tag names to add, for example onboarding, feedback. Leave empty for no tags.',required: false,}),locked: Property.Checkbox({@@ -43,14 +41,13 @@ export const createQuestionAction = createAction({defaultValue: false,}),},+ outputSchema: bettermodeSchemas.legacyPost,async run(context) {- return await createQuestion(- context.auth.props,- context.propsValue.spaceId,- context.propsValue.tagNames ?? '',- context.propsValue.title,- context.propsValue.content,- context.propsValue.locked- );+ bindTokenStore({ credentials: context.auth.props, store: context.store });+ return createLegacyPost({+ auth: context.auth.props,+ postTypeName: 'Question',+ propsValue: context.propsValue,+ });},});diff --git a/packages/pieces/community/bettermode/src/lib/actions/revoke-badge.ts b/packages/pieces/community/bettermode/src/lib/actions/revoke-badge.tsindex 0e930bc5555..47474347653 100644--- a/packages/pieces/community/bettermode/src/lib/actions/revoke-badge.ts+++ b/packages/pieces/community/bettermode/src/lib/actions/revoke-badge.ts@@ -1,37 +1,38 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { revokeBadgeFromMember } from '../api';-import { buildBadgesDropdown } from '../props';+import { bindTokenStore } from '../common/client';import { bettermodeAuth } from '../auth';+import { bettermodeInput } from '../common/input';+import { bettermodeOps } from '../common/operations';+import { badgesDropdown } from '../common/props';+import { bettermodeSchemas } from '../common/schemas';export const revokeBadgeAction = createAction({name: 'revoke_badge',classification: 'WRITE',auth: bettermodeAuth,- displayName: 'Revoke Badge from Member',+ displayName: 'Revoke Badge From Member',description: 'Revoke a badge from a member by email',- audience: 'both',- aiMetadata: { description: 'Removes a Bettermode badge (by badge ID) from the member resolved from the given email address. The email must match a network member, or the call fails. Idempotent: the member ends up without the badge regardless of how many times it is called.', idempotent: true },+ audience: 'human',+ aiMetadata: {+ description: 'Removes a badge from the member whose email matches exactly. Agents should use Find Member by Email and Revoke Badge from Member instead. Fails when no member has that exact email.',+ idempotent: false,+ },props: {- badgeId: Property.Dropdown({- auth: bettermodeAuth,- displayName: 'Badge',- description: 'The badge to revoke',- required: true,- refreshers: [],- options: async ({ auth }) =>- await buildBadgesDropdown(auth?.props),- }),+ badgeId: badgesDropdown,email: Property.ShortText({displayName: 'Email',- description: 'The email of the member to revoke the badge from',+ description: 'The exact email of the member. The connected account must be an admin to look members up by email.',required: true,}),- },+ },+ outputSchema: bettermodeSchemas.legacyBadgeAction,async run(context) {- return await revokeBadgeFromMember(- context.auth.props,- context.propsValue.badgeId,- context.propsValue.email- );+ bindTokenStore({ credentials: context.auth.props, store: context.store });+ const auth = context.auth.props;+ const badgeId = bettermodeInput.requireText({ value: context.propsValue.badgeId, label: 'Badge' });+ const email = bettermodeInput.email({ value: context.propsValue.email, label: 'Email' });+ const member = await bettermodeOps.requireMemberByEmail({ auth, email });+ const result = await bettermodeOps.changeBadge({ auth, operation: 'revokeBadge', badgeId, memberId: member.id });+ return { ...result, member_name: member.name, member_email: member.email };},});diff --git a/packages/pieces/community/bettermode/src/lib/api.ts b/packages/pieces/community/bettermode/src/lib/api.tsdeleted file mode 100644index 5fc57e0091d..00000000000--- a/packages/pieces/community/bettermode/src/lib/api.ts+++ /dev/null@@ -1,292 +0,0 @@-import {- httpClient,- HttpMethod,- HttpRequest,-} from '@activepieces/pieces-common';-import { BettermodeAuthType } from './auth';--type KeyValuePair = { [key: string]: string | boolean | object | undefined };--const bettermodeAPI = async (- auth: BettermodeAuthType,- query: string,- variables: KeyValuePair = {}-) => {- const request: HttpRequest = {- method: HttpMethod.POST,- url: auth.region,- headers: {- 'Content-Type': 'application/json',- Authorization: auth.token ? `Bearer ${auth.token}` : undefined,- },- body: JSON.stringify({- query: query,- variables: variables,- }),- };-- const response = await httpClient.sendRequest(request);-- if (response.body['errors']) {- throw new Error(response.body['errors'][0]['message']);- }-- return response.body['data'];-};--const getGuestToken = async (auth: BettermodeAuthType) => {- const query = `query GetGuestToken($domain: String!) {- tokens(networkDomain: $domain) {- accessToken- }- }`;-- const variables = { domain: auth.domain };- const response = await bettermodeAPI(auth, query, variables);-- auth.token = response.tokens.accessToken;-- return auth;-};--export const getAuthToken = async (auth: BettermodeAuthType) => {- const query = `mutation getAuthToken($email: String!, $password: String!) {- loginNetwork(input:{usernameOrEmail: $email, password: $password}) {- accessToken- member {- id- name- }- }- }`;-- const variables = {- email: auth.email,- password: auth.password,- };-- auth = await getGuestToken(auth);- const response = await bettermodeAPI(auth, query, variables);-- auth.token = response.loginNetwork.accessToken;- auth.memberId = response.loginNetwork.member.id;-- return auth;-};--const getPostType = async (auth: BettermodeAuthType, postTypeName: string) => {- const query = `query getPostType($postTypeName: String!) {- postTypes(limit: 1, query: $postTypeName) {- nodes {- id- name- }- }- }`;-- if (!auth.memberId) auth = await getAuthToken(auth);-- const variables = { postTypeName: postTypeName };- const response = await bettermodeAPI(auth, query, variables);-- return response.postTypes.nodes[0];-};--export const listBadges = async (auth: BettermodeAuthType) => {- const query = `query {- network {- badges {- id- name- }- }- }`;-- if (!auth.memberId) auth = await getAuthToken(auth);-- const response = await bettermodeAPI(auth, query);-- return response.network.badges;-};--export const listMemberSpaces = async (auth: BettermodeAuthType) => {- const query = `query listMemberSpaces($memberId: ID!) {- spaces(memberId: $memberId, limit: 100) {- nodes {- id- name- }- }- }`;-- if (!auth.memberId) auth = await getAuthToken(auth);-- const variables = { memberId: auth.memberId };- const response = await bettermodeAPI(auth, query, variables);-- return response.spaces.nodes;-};--const getMemberByEmail = async (auth: BettermodeAuthType, email: string) => {- const query = `query getMemberId($email: String!) {- members(limit: 1, query: $email) {- nodes {- id- name- }- }- }`;-- if (!auth.memberId) auth = await getAuthToken(auth);-- const variables = { email: email };- const response = await bettermodeAPI(auth, query, variables);-- if (response.members.nodes.length == 0) {- throw new Error(`Member with email ${email} not found`);- }-- return response.members.nodes[0];-};--export const assignBadgeToMember = async (- auth: BettermodeAuthType,- badgeId: string,- email: string-) => {- const query = `mutation assignBadgeToMember($badgeId: String!, $memberId: String!) {- assignBadge(- id: $badgeId,- input: {- memberId: $memberId,- }- ) {- status- }- }`;-- if (!auth.memberId) auth = await getAuthToken(auth);-- const member = await getMemberByEmail(auth, email);- const variables = { badgeId: badgeId, memberId: member.id };- const response = await bettermodeAPI(auth, query, variables);-- return response.assignBadge;-};--export const revokeBadgeFromMember = async (- auth: BettermodeAuthType,- badgeId: string,- email: string-) => {- const query = `mutation revokeBadgeFromMember($badgeId: String!, $memberId: String!) {- revokeBadge(- id: $badgeId,- input: {- memberId: $memberId,- }- ) {- status- }- }`;-- if (!auth.memberId) auth = await getAuthToken(auth);-- const member = await getMemberByEmail(auth, email);- const variables = { badgeId: badgeId, memberId: member.id };- const response = await bettermodeAPI(auth, query, variables);-- return response.revokeBadge;-};--export const createPostOfType = async (- auth: BettermodeAuthType,- postTypeName: string,- spaceId: string,- tagNames: string,- title: string,- content: string,- locked = false-) => {- const query = `mutation createPostOfType($spaceId: ID!, $postTypeId: String!, $locked: Boolean!, $tagNames: [String!], $title: String!, $content: String!) {- createPost(- spaceId : $spaceId,- input : {- postTypeId : $postTypeId,- locked : $locked,- publish : true,- tagNames : $tagNames,- mappingFields : [- {- key : "title",- type : text,- value : $title- },- {- key : "content",- type : html,- value : $content- }- ]- }- ) {- url- createdAt- }- }`;-- auth = await getAuthToken(auth);-- const postType = await getPostType(auth, postTypeName);-- const variables = {- spaceId: spaceId,- postTypeId: postType.id,- locked: locked,- tagNames: tagNames.split(',').map((tag: string) => tag.trim()),- title: JSON.stringify(title),- content: JSON.stringify(content),- };- const response = await bettermodeAPI(auth, query, variables);- return response.createPost;-};--export const createDiscussion = async (- auth: BettermodeAuthType,- spaceId: string,- tagNames: string,- title: string,- content: string,- locked = false-) => {- return await createPostOfType(- auth,- 'Discussion',- spaceId,- tagNames,- title,- content,- locked- );-};--export const createQuestion = async (- auth: BettermodeAuthType,- spaceId: string,- tagNames: string,- title: string,- content: string,- locked = false-) => {- return await createPostOfType(- auth,- 'Question',- spaceId,- tagNames,- title,- content,- locked- );-};--// TODO: assignBadge to memberdiff --git a/packages/pieces/community/bettermode/src/lib/auth.ts b/packages/pieces/community/bettermode/src/lib/auth.tsindex 679b1f39c5c..4426fddd824 100644--- a/packages/pieces/community/bettermode/src/lib/auth.ts+++ b/packages/pieces/community/bettermode/src/lib/auth.ts@@ -1,38 +1,32 @@+import { PieceAuth, Property } from '@activepieces/pieces-framework';import {- PieceAuth,- Property,-} from '@activepieces/pieces-framework';-import * as z from 'zod/mini'-import { propsValidation } from '@activepieces/pieces-common';-import { getAuthToken } from './api';--export type BettermodeAuthType = {- region: string;- domain: string;- email: string;- password: string;- token?: string;- memberId?: string;-};+ BETTERMODE_REGIONS,+ BettermodeApiError,+ BettermodeLoginError,+ isLoginLockout,+ loginWithPassword,+ normalizeDomain,+} from './common/client';export const bettermodeAuth = PieceAuth.CustomAuth({- description:- 'Your domain should be the base URL of your Bettermode community. Example: community.example.com',+ displayName: 'Bettermode',+ description: `Connect with the email and password of a Bettermode member.++1. Pick the region your community is hosted in (EU communities use api.bettermode.de).+2. Enter the community domain, for example community.example.com (https:// is optional).+3. Use the email and password of the member the flows should act as. Admin actions (badges, suspending or deleting members, moderation) need an admin account.`,props: {region: Property.StaticDropdown({displayName: 'Region',description: 'The region of your Bettermode account',required: true,options: {- options: [- { label: 'US Region', value: 'https://api.bettermode.com' },- { label: 'EU Region', value: 'https://api.bettermode.de' },- ],+ options: BETTERMODE_REGIONS,},}),domain: Property.ShortText({displayName: 'BetterMode Domain',- description: 'The domain of your Bettermode account',+ description: 'The domain of your community, for example community.example.com',required: true,}),email: Property.ShortText({@@ -48,30 +42,43 @@ export const bettermodeAuth = PieceAuth.CustomAuth({},validate: async ({ auth }) => {try {- await validateAuth(auth);- return {- valid: true,- };- } catch (e) {- return {- valid: false,- error: (e as Error)?.message,- };+ normalizeDomain(auth.domain);+ } catch (error) {+ return { valid: false, error: error instanceof Error ? error.message : 'Invalid community domain.' };+ }+ if (!EMAIL_PATTERN.test(auth.email.trim())) {+ return { valid: false, error: 'Enter a valid email address.' };+ }+ try {+ await loginWithPassword(auth);+ return { valid: true };+ } catch (error) {+ return { valid: false, error: describeValidationError(error) };}},required: true,});-const validateAuth = async (auth: BettermodeAuthType) => {- await propsValidation.validateZod(auth, {- domain: z.string().check(z.url()),- email: z.string().check(z.email()),- });-- const response = await getAuthToken(auth);- if (!response.memberId) {- throw new Error(- 'Authentication failed. Please check your credentials and try again.'- );+function describeValidationError(error: unknown): string {+ if (error instanceof BettermodeLoginError) {+ if (error.apiError.status === 401 || error.apiError.status === 403) {+ return 'Invalid credentials: Bettermode rejected the login. Check the email and password.';+ }+ if (error.stage === 'domain' && error.apiError.status === 200) {+ return `Community domain not found in the selected region. Check the domain and region. (${error.apiError.message})`;+ }+ if (error.stage === 'login' && isLoginLockout(error.apiError)) {+ return 'Bettermode has temporarily blocked logins for this account after too many attempts. Wait 5 minutes and try again.';+ }+ if (error.stage === 'login' && error.apiError.status === 200) {+ return `Invalid credentials: email or password incorrect. (${error.apiError.message})`;+ }+ return `Could not reach Bettermode: ${error.apiError.message}`;+ }+ if (error instanceof BettermodeApiError) {+ return `Could not reach Bettermode: ${error.message}`;}-};+ return `Could not reach Bettermode: ${error instanceof Error ? error.message : 'unknown error'}`;+}++const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;diff --git a/packages/pieces/community/bettermode/src/lib/common/ai-props.ts b/packages/pieces/community/bettermode/src/lib/common/ai-props.tsnew file mode 100644index 00000000000..54a6dada481--- /dev/null+++ b/packages/pieces/community/bettermode/src/lib/common/ai-props.ts@@ -0,0 +1,28 @@+import { Property } from '@activepieces/pieces-framework';++function id({ displayName, description }: { displayName: string; description: string }) {+ return Property.ShortText({ displayName, description, required: true });+}++function optionalId({ displayName, description }: { displayName: string; description: string }) {+ return Property.ShortText({ displayName, description, required: false });+}++function limit() {+ return Property.Number({+ displayName: 'Limit',+ description: 'How many items to return (1-100). Defaults to 20.',+ required: false,+ defaultValue: 20,+ });+}++function cursor() {+ return Property.ShortText({+ displayName: 'Cursor',+ description: 'The next_cursor value from a previous call, to fetch the next page. Leave empty for the first page.',+ required: false,+ });+}++export const bettermodeAiProps = { id, optionalId, limit, cursor };diff --git a/packages/pieces/community/bettermode/src/lib/common/client.ts b/packages/pieces/community/bettermode/src/lib/common/client.tsnew file mode 100644index 00000000000..9bef5db74b3--- /dev/null+++ b/packages/pieces/community/bettermode/src/lib/common/client.ts@@ -0,0 +1,547 @@+import { createHash } from 'node:crypto';+import { httpClient, HttpMethod } from '@activepieces/pieces-common';+import { Store, StoreScope } from '@activepieces/pieces-framework';++export class BettermodeApiError extends Error {+ readonly status: number;+ readonly code: string | null;+ readonly responseBody: unknown;++ constructor({+ message,+ status,+ code,+ responseBody,+ }: {+ message: string;+ status: number;+ code: string | null;+ responseBody: unknown;+ }) {+ super(message);+ this.name = 'BettermodeApiError';+ this.status = status;+ this.code = code;+ this.responseBody = responseBody;+ }+}++export class BettermodeLoginError extends Error {+ readonly stage: 'domain' | 'login';+ readonly apiError: BettermodeApiError;++ constructor({ stage, apiError }: { stage: 'domain' | 'login'; apiError: BettermodeApiError }) {+ super(+ stage === 'login' && isLoginLockout(apiError)+ ? 'Bettermode has temporarily blocked logins for this account after too many attempts. Wait 5 minutes and try again.'+ : `${stage === 'domain' ? 'Bettermode could not open the community domain' : 'Bettermode login failed'}. ${apiError.message}`+ );+ this.name = 'BettermodeLoginError';+ this.stage = stage;+ this.apiError = apiError;+ }+}++export function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}++export function assertRegion(region: unknown): string {+ const match = BETTERMODE_REGIONS.find((option) => option.value === region);+ if (match === undefined) {+ throw new Error('Select the US or EU region in the Bettermode connection.');+ }+ return match.value;+}++export function normalizeDomain(domain: unknown): string {+ if (typeof domain !== 'string' || domain.trim().length === 0) {+ throw new Error('Enter your community domain, for example community.example.com.');+ }+ let host = domain.trim().toLowerCase();+ host = host.replace(/^[a-z][a-z0-9+.-]*:\/\//, '');+ host = host.split(/[/?#]/)[0];+ if (host.includes('@')) {+ throw new Error('The community domain must not contain "@". Enter only the host, for example community.example.com.');+ }+ host = host.replace(/:\d+$/, '').replace(/\.$/, '');+ if (!HOSTNAME_PATTERN.test(host)) {+ throw new Error(`"${domain}" is not a valid community domain. Enter only the host, for example community.example.com.`);+ }+ return host;+}++export async function graphqlRequest({+ region,+ token,+ query,+ variables,+}: {+ region: string;+ token: string | null;+ query: string;+ variables?: GraphqlVariables;+}): Promise<Record<string, unknown>> {+ const url = assertRegion(region);+ for (let attempt = 0; ; attempt++) {+ const outcome = await sendOnce({ url, token, query, variables: variables ?? {} });+ if (outcome.kind === 'data') {+ return outcome.data;+ }+ if (outcome.error.status === 429 && attempt < MAX_RETRIES) {+ await sleep(RETRY_DELAYS_MS[attempt]);+ continue;+ }+ throw outcome.error;+ }+}++export async function loginWithPassword(+ credentials: BettermodeCredentials+): Promise<BettermodeSession> {+ const region = assertRegion(credentials.region);+ const domain = normalizeDomain(credentials.domain);+ const guest = await withStage({+ stage: 'domain',+ request: graphqlRequest({ region, token: null, query: GUEST_TOKEN_QUERY, variables: { domain } }),+ });+ const guestToken = readPath({ value: guest, path: ['tokens', 'accessToken'] });+ if (typeof guestToken !== 'string') {+ throw new Error('Bettermode did not return a guest token for this community domain.');+ }+ const login = await withStage({+ stage: 'login',+ request: graphqlRequest({+ region,+ token: guestToken,+ query: LOGIN_MUTATION,+ variables: {+ email: credentials.email.trim(),+ password: credentials.password,+ },+ }),+ });+ const token = readPath({ value: login, path: ['loginNetwork', 'accessToken'] });+ const memberId = readPath({ value: login, path: ['loginNetwork', 'member', 'id'] });+ const memberName = readPath({ value: login, path: ['loginNetwork', 'member', 'name'] });+ if (typeof token !== 'string' || typeof memberId !== 'string') {+ throw new Error('Bettermode login did not return an access token.');+ }+ return {+ region,+ token,+ memberId,+ memberName: typeof memberName === 'string' ? memberName : null,+ };+}++export function getSession(credentials: BettermodeCredentials): Promise<BettermodeSession> {+ const store = tokenStores.get(credentials);+ if (store === undefined) {+ return getProcessSession(credentials);+ }+ return getStoredSession({ credentials, store }).then((result) => result.session);+}++export function bindTokenStore({+ credentials,+ store,+}: {+ credentials: BettermodeCredentials;+ store: BettermodeTokenStore;+}): BettermodeCredentials {+ tokenStores.set(credentials, store);+ return credentials;+}++export function clearSessionCache(): void {+ sessionCache.clear();+}++export function isLoginLockout(error: BettermodeApiError): boolean {+ return error.code === '120' || /too many wrong attempts/i.test(error.message);+}++function getProcessSession(credentials: BettermodeCredentials): Promise<BettermodeSession> {+ const key = sessionKey(credentials);+ const cached = sessionCache.get(key);+ if (cached !== undefined && cached.expiresAt > Date.now()) {+ return cached.session;+ }+ for (const [staleKey, stale] of sessionCache) {+ if (stale.expiresAt <= Date.now()) {+ sessionCache.delete(staleKey);+ }+ }+ const session = loginWithPassword(credentials);+ const entry = { session, expiresAt: Date.now() + SESSION_TTL_MS };+ sessionCache.set(key, entry);+ session+ .then((value) => {+ entry.expiresAt = sessionExpiry({ token: value.token });+ })+ .catch(() => {+ if (sessionCache.get(key) === entry) {+ sessionCache.delete(key);+ }+ });+ return session;+}++async function getStoredSession({+ credentials,+ store,+}: {+ credentials: BettermodeCredentials;+ store: BettermodeTokenStore;+}): Promise<{ session: BettermodeSession; fromStore: boolean }> {+ const region = assertRegion(credentials.region);+ const key = storeKey(credentials);+ const stored = await readStoredToken({ store, key });+ if (stored !== null) {+ return {+ session: { region, token: stored.accessToken, memberId: stored.memberId, memberName: stored.memberName },+ fromStore: true,+ };+ }+ const session = await getProcessSession(credentials);+ const value: StoredToken = {+ accessToken: session.token,+ memberId: session.memberId,+ memberName: session.memberName,+ expiresAt: sessionExpiry({ token: session.token, ttlMs: STORE_TTL_MS }),+ };+ try {+ await store.put(key, value, StoreScope.PROJECT);+ } catch {+ return { session, fromStore: false };+ }+ return { session, fromStore: false };+}++async function readStoredToken({ store, key }: { store: BettermodeTokenStore; key: string }): Promise<StoredToken | null> {+ let value: unknown;+ try {+ value = await store.get(key, StoreScope.PROJECT);+ } catch {+ return null;+ }+ if (+ !isRecord(value) ||+ typeof value['accessToken'] !== 'string' ||+ typeof value['memberId'] !== 'string' ||+ typeof value['expiresAt'] !== 'number' ||+ value['expiresAt'] <= Date.now()+ ) {+ return null;+ }+ return {+ accessToken: value['accessToken'],+ memberId: value['memberId'],+ memberName: typeof value['memberName'] === 'string' ? value['memberName'] : null,+ expiresAt: value['expiresAt'],+ };+}++async function dropSession({ credentials }: { credentials: BettermodeCredentials }): Promise<void> {+ sessionCache.delete(sessionKey(credentials));+ const store = tokenStores.get(credentials);+ if (store === undefined) {+ return;+ }+ try {+ await store.delete(storeKey(credentials), StoreScope.PROJECT);+ } catch {+ return;+ }+}++function sessionKey(credentials: BettermodeCredentials): string {+ const passwordHash = createHash('sha256').update(String(credentials.password)).digest('hex');+ return JSON.stringify([credentials.region, credentials.domain, credentials.email, passwordHash]);+}++function storeKey(credentials: BettermodeCredentials): string {+ const digest = createHash('sha256')+ .update(+ JSON.stringify([+ credentials.region,+ String(credentials.domain).trim().toLowerCase(),+ String(credentials.email).trim().toLowerCase(),+ createHash('sha256').update(String(credentials.password)).digest('hex'),+ ])+ )+ .digest('hex');+ return `bettermode_token_${digest}`;+}++function sessionExpiry({ token, ttlMs = SESSION_TTL_MS }: { token: string; ttlMs?: number }): number {+ const fallback = Date.now() + SESSION_TTL_MS;+ const cap = Date.now() + ttlMs;+ const payload = token.split('.')[1];+ if (payload === undefined) {+ return fallback;+ }+ try {+ const exp: unknown = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'))['exp'];+ if (typeof exp !== 'number') {+ return fallback;+ }+ return Math.min(cap, exp * 1000 - SESSION_EXPIRY_MARGIN_MS);+ } catch {+ return fallback;+ }+}++function isTokenRejected(error: unknown): boolean {+ return (+ error instanceof BettermodeApiError &&+ (error.status === 401 || /jwt expired|token (?:has )?expired|invalid token|unauthenticated/i.test(error.message))+ );+}++export async function bettermodeQuery({+ auth,+ query,+ variables,+}: {+ auth: BettermodeCredentials;+ query: string;+ variables?: GraphqlVariables;+}): Promise<Record<string, unknown>> {+ const store = tokenStores.get(auth);+ const first =+ store === undefined+ ? { session: await getProcessSession(auth), fromStore: true }+ : await getStoredSession({ credentials: auth, store });+ try {+ return await graphqlRequest({ region: first.session.region, token: first.session.token, query, variables });+ } catch (error) {+ if (!isTokenRejected(error) || !first.fromStore) {+ throw error;+ }+ await dropSession({ credentials: auth });+ const fresh = await getSession(auth);+ return graphqlRequest({ region: fresh.region, token: fresh.token, query, variables });+ }+}++export function readPath({ value, path }: { value: unknown; path: string[] }): unknown {+ let current: unknown = value;+ for (const key of path) {+ if (!isRecord(current)) {+ return undefined;+ }+ current = current[key];+ }+ return current;+}++async function sendOnce({+ url,+ token,+ query,+ variables,+}: {+ url: string;+ token: string | null;+ query: string;+ variables: GraphqlVariables;+}): Promise<{ kind: 'data'; data: Record<string, unknown> } | { kind: 'error'; error: BettermodeApiError }> {+ const headers: Record<string, string> = {+ 'Content-Type': 'application/json',+ Accept: 'application/json',+ };+ if (token !== null) {+ headers['Authorization'] = `Bearer ${token}`;+ }+ let body: unknown;+ try {+ const response = await httpClient.sendRequest({+ method: HttpMethod.POST,+ url,+ headers,+ body: { query, variables },+ timeout: REQUEST_TIMEOUT_MS,+ followRedirects: false,+ redactBodyInErrors: true,+ });+ body = response.body;+ } catch (error) {+ const httpResponse = readHttpErrorResponse(error);+ if (httpResponse === undefined) {+ throw error;+ }+ return {+ kind: 'error',+ error: buildHttpError({ status: httpResponse.status, responseBody: httpResponse.body }),+ };+ }+ const errors = readPath({ value: body, path: ['errors'] });+ if (Array.isArray(errors) && errors.length > 0) {+ return { kind: 'error', error: buildGraphqlError({ errors, responseBody: body }) };+ }+ const data = readPath({ value: body, path: ['data'] });+ if (!isRecord(data)) {+ return {+ kind: 'error',+ error: new BettermodeApiError({+ message: 'Bettermode returned a response without data.',+ status: 200,+ code: null,+ responseBody: body,+ }),+ };+ }+ return { kind: 'data', data };+}++function readHttpErrorResponse(error: unknown): { status: number; body: unknown } | undefined {+ if (!(error instanceof Error) && !isRecord(error)) {+ return undefined;+ }+ const response: unknown = Reflect.get(error, 'response');+ if (!isRecord(response) || typeof response['status'] !== 'number') {+ return undefined;+ }+ return { status: response['status'], body: response['body'] };+}++function buildHttpError({ status, responseBody }: { status: number; responseBody: unknown }): BettermodeApiError {+ const graphqlErrors = readPath({ value: responseBody, path: ['errors'] });+ if (Array.isArray(graphqlErrors) && graphqlErrors.length > 0 && status !== 401 && status !== 403 && status !== 429) {+ const error = buildGraphqlError({ errors: graphqlErrors, responseBody });+ return new BettermodeApiError({ message: error.message, status, code: error.code, responseBody });+ }+ const base =+ STATUS_MESSAGES[status] ??+ (status >= 500+ ? 'Bettermode returned a server error. Retry later'+ : status >= 300 && status < 400+ ? 'Bettermode answered with an unexpected redirect, which was not followed'+ : 'Bettermode request failed');+ return new BettermodeApiError({ message: `${base} (HTTP ${status}).`, status, code: null, responseBody });+}++function buildGraphqlError({ errors, responseBody }: { errors: unknown[]; responseBody: unknown }): BettermodeApiError {+ const first = errors[0];+ const message = isRecord(first) && typeof first['message'] === 'string' ? first['message'] : 'Unknown error';+ const rawCode = isRecord(first) ? (first['code'] ?? readPath({ value: first, path: ['extensions', 'code'] })) : undefined;+ const code = typeof rawCode === 'string' || typeof rawCode === 'number' ? String(rawCode) : null;+ const path = isRecord(first) && Array.isArray(first['path']) ? first['path'].join('.') : null;+ const details = [code === null ? null : `code ${code}`, path === null ? null : `at ${path}`]+ .filter((part): part is string => part !== null)+ .join(', ');+ const rateLimited = /rate limit|too many requests/i.test(message);+ return new BettermodeApiError({+ message: `Bettermode error${details.length > 0 ? ` (${details})` : ''}: ${message.slice(0, 300)}`,+ status: rateLimited ? 429 : 200,+ code,+ responseBody,+ });+}++async function withStage({+ stage,+ request,+}: {+ stage: 'domain' | 'login';+ request: Promise<Record<string, unknown>>;+}): Promise<Record<string, unknown>> {+ try {+ return await request;+ } catch (error) {+ if (error instanceof BettermodeApiError) {+ throw new BettermodeLoginError({ stage, apiError: error });+ }+ throw error;+ }+}++function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++const sessionCache = new Map<string, { session: Promise<BettermodeSession>; expiresAt: number }>();+const SESSION_TTL_MS = 30 * 60 * 1000;+const SESSION_EXPIRY_MARGIN_MS = 30 * 1000;+const STORE_TTL_MS = 12 * 60 * 60 * 1000;+const tokenStores = new WeakMap<BettermodeCredentials, BettermodeTokenStore>();++type StoredToken = { accessToken: string; memberId: string; memberName: string | null; expiresAt: number };++const HOSTNAME_PATTERN = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;++const MAX_RETRIES = 2;+const RETRY_DELAYS_MS = [2000, 4000];+const REQUEST_TIMEOUT_MS = 30000;++const STATUS_MESSAGES: Record<number, string> = {+ 400: 'Bettermode rejected the request as invalid',+ 401: 'Bettermode rejected the login token. Re-connect the Bettermode connection',+ 403: 'Bettermode refused the request: the connected member lacks permission. Re-connect with an admin account or check the member role',+ 404: 'Bettermode endpoint not found. Check the region in the connection',+ 429: 'Bettermode rate limit reached. Retry later',+};++const GUEST_TOKEN_QUERY = `query GetGuestToken($domain: String!) {+ tokens(networkDomain: $domain) {+ accessToken+ }+}`;++const LOGIN_MUTATION = `mutation Login($email: String!, $password: String!) {+ loginNetwork(input: { usernameOrEmail: $email, password: $password }) {+ accessToken+ member {+ id+ name+ }+ }+}`;++export function assertCustomCallUrl({ region, url }: { region: string; url: unknown }): void {+ const base = new URL(assertRegion(region));+ if (typeof url !== 'string' || url.trim().length === 0) {+ return;+ }+ const value = url.trim();+ if (!/^[a-z][a-z0-9+.-]*:/i.test(value) && !value.startsWith('//')) {+ if (value.split(/[/?#]/).includes('..')) {+ throw new Error('The URL must not contain "..".');+ }+ return;+ }+ let target: URL;+ try {+ target = new URL(value);+ } catch {+ throw new Error('The URL is not valid.');+ }+ if (target.protocol !== 'https:' || target.origin !== base.origin || target.username !== '' || target.password !== '') {+ throw new Error(`Custom API calls can only go to ${base.origin}, the region of this connection.`);+ }+}++export type BettermodeCredentials = {+ region: string;+ domain: string;+ email: string;+ password: string;+};++export type BettermodeSession = {+ region: string;+ token: string;+ memberId: string;+ memberName: string | null;+};++type GraphqlVariables = Record<string, unknown>;++export type BettermodeTokenStore = Pick<Store, 'get' | 'put' | 'delete'>;++export const BETTERMODE_REGIONS = [+ { label: 'US Region', value: 'https://api.bettermode.com' },+ { label: 'EU Region', value: 'https://api.bettermode.de' },+];diff --git a/packages/pieces/community/bettermode/src/lib/common/fields.ts b/packages/pieces/community/bettermode/src/lib/common/fields.tsnew file mode 100644index 00000000000..36fff48f4a6--- /dev/null+++ b/packages/pieces/community/bettermode/src/lib/common/fields.ts@@ -0,0 +1,79 @@+export const MEMBER_FIELDS = `id+name+username+tagline+status+url+createdAt+role { id name }`;++export const SPACE_FIELDS = `id+name+slug+url+description+type+private+hidden+membersCount+postsCount+createdAt`;++export const POST_FIELDS = `id+title+slug+url+status+spaceId+space { name }+postTypeId+postType { name }+ownerId+owner { member { name } }+repliedToId+textContent+shortContent+fields { key value }+tags { id title }+repliesCount+reactionsCount+locked+isHidden+createdAt+updatedAt+publishedAt`;++export const POST_TYPE_FIELDS = `id+name+pluralName+slug+context+archived`;++export const TAG_FIELDS = `id+title+slug+description`;++export const BADGE_FIELDS = `id+name+shortDescription+type+active`;++export const EVENT_FIELDS = `id+title+slug+url+status+spaceId+startTime+endTime+timeZone+capacity+registrationsCount+createdAt`;++export const PAGE_INFO = `pageInfo { endCursor hasNextPage }+totalCount`;diff --git a/packages/pieces/community/bettermode/src/lib/common/input.ts b/packages/pieces/community/bettermode/src/lib/common/input.tsnew file mode 100644index 00000000000..24232c2377e--- /dev/null+++ b/packages/pieces/community/bettermode/src/lib/common/input.ts@@ -0,0 +1,85 @@+function requireText({ value, label }: { value: unknown; label: string }): string {+ const text = optionalText(value);+ if (text === undefined) {+ throw new Error(`${label} is required.`);+ }+ return text;+}++function optionalText(value: unknown): string | undefined {+ if (typeof value === 'number' && Number.isFinite(value)) {+ return String(value);+ }+ if (typeof value !== 'string') {+ return undefined;+ }+ const trimmed = value.trim();+ return trimmed.length === 0 ? undefined : trimmed;+}++function stringList({ value, label }: { value: unknown; label: string }): string[] {+ if (value === undefined || value === null || value === '') {+ return [];+ }+ const raw: unknown[] = Array.isArray(value)+ ? value.flatMap((item) => (typeof item === 'string' ? item.split(',') : [item]))+ : typeof value === 'string'+ ? value.split(',')+ : [value];+ const items = raw.map((item) => {+ if (typeof item !== 'string' && typeof item !== 'number') {+ throw new Error(`${label} must contain only text values.`);+ }+ return optionalText(item);+ });+ return [...new Set(items.filter((item): item is string => item !== undefined))];+}++function limit({ value, fallback = DEFAULT_LIMIT }: { value: unknown; fallback?: number }): number {+ if (value === undefined || value === null || value === '') {+ return fallback;+ }+ const parsed = typeof value === 'number' ? value : Number(value);+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > MAX_LIMIT) {+ throw new Error(`Limit must be a whole number between 1 and ${MAX_LIMIT}.`);+ }+ return parsed;+}++function optionalBoolean({ value, label }: { value: unknown; label: string }): boolean | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ if (typeof value === 'boolean') {+ return value;+ }+ if (value === 'true') {+ return true;+ }+ if (value === 'false') {+ return false;+ }+ throw new Error(`${label} must be true or false.`);+}++function email({ value, label }: { value: unknown; label: string }): string {+ const text = requireText({ value, label });+ if (!EMAIL_PATTERN.test(text)) {+ throw new Error(`${label} must be a valid email address.`);+ }+ return text;+}++const DEFAULT_LIMIT = 20;+const MAX_LIMIT = 100;+const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;++export const bettermodeInput = {+ requireText,+ optionalText,+ stringList,+ limit,+ optionalBoolean,+ email,+ MAX_LIMIT,+};diff --git a/packages/pieces/community/bettermode/src/lib/common/mappers.ts b/packages/pieces/community/bettermode/src/lib/common/mappers.tsnew file mode 100644index 00000000000..08dca8e0fde--- /dev/null+++ b/packages/pieces/community/bettermode/src/lib/common/mappers.ts@@ -0,0 +1,231 @@+import { isRecord, readPath } from './client';++function text(value: unknown): string | null {+ if (typeof value === 'string') {+ return value;+ }+ if (typeof value === 'number' && Number.isFinite(value)) {+ return String(value);+ }+ return null;+}++function num(value: unknown): number | null {+ return typeof value === 'number' && Number.isFinite(value) ? value : null;+}++function bool(value: unknown): boolean | null {+ return typeof value === 'boolean' ? value : null;+}++function records(value: unknown): Record<string, unknown>[] {+ return Array.isArray(value) ? value.filter(isRecord) : [];+}++function decodeFieldValue(value: unknown): string | null {+ if (typeof value !== 'string') {+ return null;+ }+ try {+ const parsed: unknown = JSON.parse(value);+ if (typeof parsed === 'string') {+ return parsed;+ }+ if (typeof parsed === 'number' || typeof parsed === 'boolean') {+ return String(parsed);+ }+ return value;+ } catch {+ return value;+ }+}++function post(value: unknown) {+ const tags = records(readPath({ value: value, path: ['tags'] }));+ const fields = records(readPath({ value: value, path: ['fields'] }));+ const contentField = fields.find((field) => field['key'] === 'content');+ return {+ id: text(readPath({ value: value, path: ['id'] })),+ title: text(readPath({ value: value, path: ['title'] })),+ slug: text(readPath({ value: value, path: ['slug'] })),+ url: text(readPath({ value: value, path: ['url'] })),+ status: text(readPath({ value: value, path: ['status'] })),+ space_id: text(readPath({ value: value, path: ['spaceId'] })),+ space_name: text(readPath({ value: value, path: ['space', 'name'] })),+ post_type_id: text(readPath({ value: value, path: ['postTypeId'] })),+ post_type_name: text(readPath({ value: value, path: ['postType', 'name'] })),+ owner_id: text(readPath({ value: value, path: ['ownerId'] })),+ owner_name: text(readPath({ value: value, path: ['owner', 'member', 'name'] })),+ replied_to_id: text(readPath({ value: value, path: ['repliedToId'] })),+ content_html: contentField === undefined ? null : decodeFieldValue(contentField['value']),+ text_content: text(readPath({ value: value, path: ['textContent'] })),+ short_content: text(readPath({ value: value, path: ['shortContent'] })),+ tags: tags.map((tag) => text(tag['title'])).filter((tag): tag is string => tag !== null).join(', '),+ tag_ids: tags.map((tag) => text(tag['id'])).filter((tag): tag is string => tag !== null).join(', '),+ replies_count: num(readPath({ value: value, path: ['repliesCount'] })),+ reactions_count: num(readPath({ value: value, path: ['reactionsCount'] })),+ locked: bool(readPath({ value: value, path: ['locked'] })),+ hidden: bool(readPath({ value: value, path: ['isHidden'] })),+ created_at: text(readPath({ value: value, path: ['createdAt'] })),+ updated_at: text(readPath({ value: value, path: ['updatedAt'] })),+ published_at: text(readPath({ value: value, path: ['publishedAt'] })),+ };+}++function member(value: unknown) {+ return {+ id: text(readPath({ value: value, path: ['id'] })),+ name: text(readPath({ value: value, path: ['name'] })),+ email: text(readPath({ value: value, path: ['email'] })),+ username: text(readPath({ value: value, path: ['username'] })),+ tagline: text(readPath({ value: value, path: ['tagline'] })),+ status: text(readPath({ value: value, path: ['status'] })),+ role_id: text(readPath({ value: value, path: ['role', 'id'] })),+ role_name: text(readPath({ value: value, path: ['role', 'name'] })),+ url: text(readPath({ value: value, path: ['url'] })),+ created_at: text(readPath({ value: value, path: ['createdAt'] })),+ };+}++function space(value: unknown) {+ return {+ id: text(readPath({ value: value, path: ['id'] })),+ name: text(readPath({ value: value, path: ['name'] })),+ slug: text(readPath({ value: value, path: ['slug'] })),+ url: text(readPath({ value: value, path: ['url'] })),+ description: text(readPath({ value: value, path: ['description'] })),+ type: text(readPath({ value: value, path: ['type'] })),+ private: bool(readPath({ value: value, path: ['private'] })),+ hidden: bool(readPath({ value: value, path: ['hidden'] })),+ members_count: num(readPath({ value: value, path: ['membersCount'] })),+ posts_count: num(readPath({ value: value, path: ['postsCount'] })),+ created_at: text(readPath({ value: value, path: ['createdAt'] })),+ };+}++function spaceMember(value: unknown) {+ return {+ member_id: text(readPath({ value: value, path: ['member', 'id'] })),+ member_name: text(readPath({ value: value, path: ['member', 'name'] })),+ member_email: text(readPath({ value: value, path: ['member', 'email'] })),+ member_username: text(readPath({ value: value, path: ['member', 'username'] })),+ role_id: text(readPath({ value: value, path: ['role', 'id'] })),+ role_name: text(readPath({ value: value, path: ['role', 'name'] })),+ };+}++function postType(value: unknown) {+ return {+ id: text(readPath({ value: value, path: ['id'] })),+ name: text(readPath({ value: value, path: ['name'] })),+ plural_name: text(readPath({ value: value, path: ['pluralName'] })),+ slug: text(readPath({ value: value, path: ['slug'] })),+ context: text(readPath({ value: value, path: ['context'] })),+ archived: bool(readPath({ value: value, path: ['archived'] })),+ };+}++function tag(value: unknown) {+ return {+ id: text(readPath({ value: value, path: ['id'] })),+ title: text(readPath({ value: value, path: ['title'] })),+ slug: text(readPath({ value: value, path: ['slug'] })),+ description: text(readPath({ value: value, path: ['description'] })),+ };+}++function badge(value: unknown) {+ return {+ id: text(readPath({ value: value, path: ['id'] })),+ name: text(readPath({ value: value, path: ['name'] })),+ short_description: text(readPath({ value: value, path: ['shortDescription'] })),+ type: text(readPath({ value: value, path: ['type'] })),+ active: bool(readPath({ value: value, path: ['active'] })),+ };+}++function event(value: unknown) {+ return {+ id: text(readPath({ value: value, path: ['id'] })),+ title: text(readPath({ value: value, path: ['title'] })),+ slug: text(readPath({ value: value, path: ['slug'] })),+ url: text(readPath({ value: value, path: ['url'] })),+ status: text(readPath({ value: value, path: ['status'] })),+ space_id: text(readPath({ value: value, path: ['spaceId'] })),+ start_time: text(readPath({ value: value, path: ['startTime'] })),+ end_time: text(readPath({ value: value, path: ['endTime'] })),+ time_zone: text(readPath({ value: value, path: ['timeZone'] })),+ capacity: num(readPath({ value: value, path: ['capacity'] })),+ registrations_count: num(readPath({ value: value, path: ['registrationsCount'] })),+ created_at: text(readPath({ value: value, path: ['createdAt'] })),+ };+}++function moderationItem(value: unknown) {+ return {+ id: text(readPath({ value: value, path: ['id'] })),+ status: text(readPath({ value: value, path: ['status'] })),+ flagged_by: text(readPath({ value: value, path: ['flaggedBy'] })),+ description: text(readPath({ value: value, path: ['description'] })),+ member_id: text(readPath({ value: value, path: ['memberId'] })),+ space_id: text(readPath({ value: value, path: ['spaceId'] })),+ created_at: text(readPath({ value: value, path: ['createdAt'] })),+ updated_at: text(readPath({ value: value, path: ['updatedAt'] })),+ };+}++function invitation(value: unknown) {+ return {+ id: text(readPath({ value: value, path: ['id'] })),+ invitee_email: text(readPath({ value: value, path: ['inviteeEmail'] })),+ invitee_name: text(readPath({ value: value, path: ['inviteeName'] })),+ status: text(readPath({ value: value, path: ['status'] })),+ expires_at: text(readPath({ value: value, path: ['expiresAt'] })),+ created_at: text(readPath({ value: value, path: ['createdAt'] })),+ };+}++function network(value: unknown) {+ return {+ id: text(readPath({ value: value, path: ['id'] })),+ name: text(readPath({ value: value, path: ['name'] })),+ domain: text(readPath({ value: value, path: ['domain'] })),+ description: text(readPath({ value: value, path: ['description'] })),+ plan_name: text(readPath({ value: value, path: ['planName'] })),+ members_count: num(readPath({ value: value, path: ['membersCount'] })),+ created_at: text(readPath({ value: value, path: ['createdAt'] })),+ };+}++function page<T>({ value, map }: { value: unknown; map: (item: unknown) => T }) {+ const hasMore = readPath({ value: value, path: ['pageInfo', 'hasNextPage'] }) === true;+ const cursor = text(readPath({ value: value, path: ['pageInfo', 'endCursor'] }));+ return {+ items: records(readPath({ value: value, path: ['nodes'] })).map(map),+ next_cursor: hasMore ? cursor : null,+ has_more: hasMore,+ total_count: num(readPath({ value: value, path: ['totalCount'] })),+ };+}++function actionStatus(value: unknown): string | null {+ return text(readPath({ value: value, path: ['status'] }));+}++export const bettermodeMap = {+ post,+ member,+ space,+ spaceMember,+ postType,+ tag,+ badge,+ event,+ moderationItem,+ invitation,+ network,+ page,+ actionStatus,+ records,+ text,+};diff --git a/packages/pieces/community/bettermode/src/lib/common/operations.ts b/packages/pieces/community/bettermode/src/lib/common/operations.tsnew file mode 100644index 00000000000..cc83dc4c3ef--- /dev/null+++ b/packages/pieces/community/bettermode/src/lib/common/operations.ts@@ -0,0 +1,314 @@+import { bettermodeQuery, BettermodeCredentials, readPath } from './client';+import { BADGE_FIELDS, MEMBER_FIELDS, PAGE_INFO, POST_FIELDS, POST_TYPE_FIELDS, SPACE_FIELDS } from './fields';+import { bettermodeInput } from './input';+import { bettermodeMap } from './mappers';++async function createPost({+ auth,+ spaceId,+ postTypeId,+ title,+ content,+ tagNames,+ locked,+}: {+ auth: BettermodeCredentials;+ spaceId: string;+ postTypeId: string;+ title: string;+ content: string;+ tagNames: string[];+ locked: boolean | undefined;+}) {+ const input: Record<string, unknown> = {+ postTypeId,+ mappingFields: [+ { key: 'title', type: 'text', value: JSON.stringify(title) },+ { key: 'content', type: 'html', value: JSON.stringify(content) },+ ],+ };+ if (tagNames.length > 0) {+ input['tagNames'] = tagNames;+ }+ if (locked !== undefined) {+ input['locked'] = locked;+ }+ const data = await bettermodeQuery({+ auth,+ query: `mutation CreatePost($spaceId: ID!, $input: CreatePostInput!) {+ createPost(spaceId: $spaceId, input: $input) {+${POST_FIELDS}+ }+}`,+ variables: { spaceId, input },+ });+ return publishIfDraft({ auth, post: bettermodeMap.post(data['createPost']) });+}++async function publishIfDraft({+ auth,+ post,+}: {+ auth: BettermodeCredentials;+ post: ReturnType<typeof bettermodeMap.post>;+}): Promise<ReturnType<typeof bettermodeMap.post>> {+ if (post.status !== 'DRAFT' || post.id === null) {+ return post;+ }+ const data = await bettermodeQuery({+ auth,+ query: `mutation PublishPost($postId: ID!) {+ publishPost(postId: $postId) {+${POST_FIELDS}+ }+}`,+ variables: { postId: post.id },+ });+ return bettermodeMap.post(data['publishPost']);+}++async function findPostTypeByName({+ auth,+ name,+ spaceId,+}: {+ auth: BettermodeCredentials;+ name: string;+ spaceId?: string;+}): Promise<{ id: string; name: string }> {+ const wanted = name.trim().toLowerCase();+ const spaceTypes = spaceId === undefined ? null : await listSpacePostTypes({ auth, spaceId });+ const types = spaceTypes ?? (await listAllPostTypes({ auth, context: 'post' }));+ const match = types.find((type) => type.name !== null && type.name.trim().toLowerCase() === wanted);+ if (match === undefined || match.id === null || match.name === null) {+ const available = types.map((type) => type.name).filter((typeName): typeName is string => typeName !== null);+ const scope = spaceTypes === null ? 'exists in this community' : 'is available in this space';+ throw new Error(+ `No post type named "${name}" ${scope}. Available post types: ${available.length > 0 ? available.join(', ') : 'none'}.`+ );+ }+ return { id: match.id, name: match.name };+}++async function listSpacePostTypes({+ auth,+ spaceId,+}: {+ auth: BettermodeCredentials;+ spaceId: string;+}): Promise<ReturnType<typeof bettermodeMap.postType>[] | null> {+ const data = await bettermodeQuery({+ auth,+ query: `query GetSpacePostTypes($id: ID!) {+ space(id: $id) {+ authMemberProps {+ availablePostTypes {+${POST_TYPE_FIELDS}+ }+ }+ }+}`,+ variables: { id: spaceId },+ });+ const available = readPath({ value: data, path: ['space', 'authMemberProps', 'availablePostTypes'] });+ if (!Array.isArray(available)) {+ return null;+ }+ return available+ .map((type) => bettermodeMap.postType(type))+ .filter((type) => type.context === null || type.context === 'post');+}++async function listAllPostTypes({+ auth,+ context,+}: {+ auth: BettermodeCredentials;+ context: 'post' | 'reply' | undefined;+}) {+ const results: ReturnType<typeof bettermodeMap.postType>[][] = [];+ let after: string | null = null;+ for (let pageIndex = 0; pageIndex < MAX_PAGES; pageIndex++) {+ const data = await bettermodeQuery({+ auth,+ query: `query ListPostTypes($limit: Int!, $after: String, $context: PostTypeContext) {+ postTypes(limit: $limit, after: $after, context: $context) {+ nodes {+${POST_TYPE_FIELDS}+ }+ ${PAGE_INFO}+ }+}`,+ variables: { limit: PAGE_SIZE, after, context },+ });+ const page = bettermodeMap.page({ value: data['postTypes'], map: bettermodeMap.postType });+ results.push(page.items);+ if (!page.has_more || page.next_cursor === null) {+ return results.flat();+ }+ after = page.next_cursor;+ }+ return results.flat();+}++async function findMemberByEmail({ auth, email }: { auth: BettermodeCredentials; email: string }) {+ const wanted = email.trim().toLowerCase();+ let after: string | null = null;+ for (let pageIndex = 0; pageIndex < MAX_EMAIL_PAGES; pageIndex++) {+ const data = await bettermodeQuery({+ auth,+ query: `query FindMembers($query: String!, $limit: Int!, $after: String) {+ members(query: $query, limit: $limit, after: $after) {+ nodes {+${MEMBER_FIELDS}+ }+ ${PAGE_INFO}+ }+}`,+ variables: { query: email.trim(), limit: PAGE_SIZE, after },+ });+ const page = bettermodeMap.page({ value: data['members'], map: bettermodeMap.member });+ const match = page.items.find((item) => item.email !== null && item.email.trim().toLowerCase() === wanted);+ if (match !== undefined) {+ return match;+ }+ if (!page.has_more || page.next_cursor === null) {+ return null;+ }+ after = page.next_cursor;+ }+ throw new Error(+ `Could not confirm a member with email ${email}: the search returned more than ${MAX_EMAIL_PAGES * PAGE_SIZE} partial matches. Use the member ID instead.`+ );+}++async function requireMemberByEmail({ auth, email }: { auth: BettermodeCredentials; email: string }) {+ const member = await findMemberByEmail({ auth, email });+ if (member === null || member.id === null) {+ throw new Error(+ `No member with email ${email} was found. The email must match exactly, and the connected account must be an admin to see member emails.`+ );+ }+ return { ...member, id: member.id };+}++async function changeBadge({+ auth,+ operation,+ badgeId,+ memberId,+}: {+ auth: BettermodeCredentials;+ operation: 'assignBadge' | 'revokeBadge';+ badgeId: string;+ memberId: string;+}) {+ const data = await bettermodeQuery({+ auth,+ query: BADGE_MUTATIONS[operation],+ variables: { badgeId, input: { memberId } },+ });+ const status = expectSucceeded({ value: data[operation], operation });+ return { success: true, status, badge_id: badgeId, member_id: memberId };+}++async function runActionMutation({+ auth,+ query,+ variables,+ field,+}: {+ auth: BettermodeCredentials;+ query: string;+ variables: Record<string, unknown>;+ field: string;+}): Promise<string> {+ const data = await bettermodeQuery({ auth, query, variables });+ return expectSucceeded({ value: data[field], operation: field });+}++function expectSucceeded({ value, operation }: { value: unknown; operation: string }): string {+ const status = bettermodeMap.actionStatus(value);+ if (status !== 'succeeded') {+ throw new Error(`Bettermode did not complete ${operation} (status: ${status ?? 'missing'}).`);+ }+ return status;+}++async function listBadges({ auth }: { auth: BettermodeCredentials }) {+ const data = await bettermodeQuery({+ auth,+ query: `query ListBadges {+ network {+ badges {+${BADGE_FIELDS}+ }+ }+}`,+ });+ return bettermodeMap.records(readPath({ value: data, path: ['network', 'badges'] })).map(bettermodeMap.badge);+}++async function listSpacesPage({+ auth,+ limit,+ after,+ query,+ memberId,+}: {+ auth: BettermodeCredentials;+ limit: number;+ after: string | null;+ query: string | undefined;+ memberId: string | undefined;+}) {+ const data = await bettermodeQuery({+ auth,+ query: `query ListSpaces($limit: Int!, $after: String, $query: String, $memberId: ID) {+ spaces(limit: $limit, after: $after, query: $query, memberId: $memberId) {+ nodes {+${SPACE_FIELDS}+ }+ ${PAGE_INFO}+ }+}`,+ variables: { limit, after, query, memberId },+ });+ return bettermodeMap.page({ value: data['spaces'], map: bettermodeMap.space });+}++function tagNames(value: unknown): string[] {+ return bettermodeInput.stringList({ value, label: 'Tags' });+}++const BADGE_MUTATIONS = {+ assignBadge: `mutation AssignBadge($badgeId: String!, $input: AssignOrRevokeBadgeInput!) {+ assignBadge(id: $badgeId, input: $input) {+ status+ }+}`,+ revokeBadge: `mutation RevokeBadge($badgeId: String!, $input: AssignOrRevokeBadgeInput!) {+ revokeBadge(id: $badgeId, input: $input) {+ status+ }+}`,+};++const PAGE_SIZE = 50;+const MAX_PAGES = 10;+const MAX_EMAIL_PAGES = 5;++export const bettermodeOps = {+ createPost,+ findPostTypeByName,+ publishIfDraft,+ listAllPostTypes,+ findMemberByEmail,+ requireMemberByEmail,+ changeBadge,+ runActionMutation,+ listBadges,+ listSpacesPage,+ tagNames,+ MAX_PAGES,+};diff --git a/packages/pieces/community/bettermode/src/lib/common/polling.ts b/packages/pieces/community/bettermode/src/lib/common/polling.tsnew file mode 100644index 00000000000..6184b7e8873--- /dev/null+++ b/packages/pieces/community/bettermode/src/lib/common/polling.ts@@ -0,0 +1,175 @@+function newestCheckpoint<T extends PolledItem>({+ items,+ fallback,+ timeField = 'created_at',+}: {+ items: T[];+ fallback: string;+ timeField?: TimeField;+}): Checkpoint {+ const timeOf = (item: PolledItem) => item[timeField] ?? null;+ const dated = items.filter((item) => parseTime(timeOf(item)) !== null);+ if (dated.length === 0) {+ return { lastCreatedAt: fallback, idsAtLast: [] };+ }+ const newest = dated.reduce((best, item) => (compareItems({ left: item, right: best, timeField }) > 0 ? item : best));+ const newestTime = parseTime(timeOf(newest));+ return {+ lastCreatedAt: timeOf(newest) ?? fallback,+ idsAtLast: dated+ .filter((item) => parseTime(timeOf(item)) === newestTime && item.id !== null)+ .map((item) => item.id)+ .filter((id): id is string => id !== null)+ .slice(0, MAX_IDS_AT_LAST),+ };+}++async function collectNewItems<T extends PolledItem>({+ checkpoint,+ fetchPage,+ timeField = 'created_at',+}: {+ checkpoint: Checkpoint;+ fetchPage: (cursor: string | null) => Promise<PolledPage<T>>;+ timeField?: TimeField;+}): Promise<{ items: T[]; checkpoint: Checkpoint }> {+ const timeOf = (item: PolledItem) => item[timeField] ?? null;+ const checkpointTime = parseTime(checkpoint.lastCreatedAt);+ if (checkpointTime === null) {+ throw new Error('The trigger checkpoint is invalid. Disable and re-enable the trigger.');+ }+ const seenAtLast = new Set(checkpoint.idsAtLast);+ const isFresh = (item: PolledItem) => {+ const time = parseTime(timeOf(item));+ if (time === null || item.id === null) {+ return false;+ }+ return time > checkpointTime || (time === checkpointTime && !seenAtLast.has(item.id));+ };+ const isOlderThanCheckpoint = (item: PolledItem) => {+ const time = parseTime(timeOf(item));+ return time !== null && time < checkpointTime;+ };+ const stack = checkpoint.resumeCursors ?? [];+ const drainedCursor = checkpoint.drainedCursor ?? null;+ const windowStart = stack.length > 0 ? stack[stack.length - 1] : null;+ const parents = stack.slice(0, -1);+ const pages: T[][] = [];+ let cursor: string | null = windowStart;+ let complete = false;+ for (let pageIndex = 0; pageIndex <= MAX_POLL_PAGES; pageIndex++) {+ if (pageIndex > 0 && cursor !== null && cursor === drainedCursor) {+ complete = true;+ break;+ }+ const page = await fetchPage(cursor);+ assertNewestFirst({ items: page.items, timeField });+ pages.push(page.items);+ if (page.items.some(isOlderThanCheckpoint) || !page.has_more || page.next_cursor === null) {+ complete = true;+ break;+ }+ if (pageIndex < MAX_POLL_PAGES) {+ cursor = page.next_cursor;+ }+ }+ const base: Checkpoint = { lastCreatedAt: checkpoint.lastCreatedAt, idsAtLast: checkpoint.idsAtLast };+ if (!complete && cursor !== null) {+ return { items: [], checkpoint: withCursors({ checkpoint: base, cursors: [...stack, cursor], drainedCursor }) };+ }+ const unique = new Map<string, T>();+ for (const item of pages.flat()) {+ if (item.id !== null && !unique.has(item.id)) {+ unique.set(item.id, item);+ }+ }+ const sorted = [...unique.values()].filter(isFresh).sort((left, right) => compareItems({ left, right, timeField }));+ const fresh = sorted.slice(0, MAX_EMIT_PER_POLL);+ const windowDrained = sorted.length <= MAX_EMIT_PER_POLL;+ const remaining = windowDrained ? parents : stack;+ const nextDrained = windowDrained ? windowStart : drainedCursor;+ if (fresh.length === 0) {+ return { items: [], checkpoint: withCursors({ checkpoint: base, cursors: parents, drainedCursor: windowStart }) };+ }+ const next = newestCheckpoint({ items: fresh, fallback: checkpoint.lastCreatedAt, timeField });+ const sameTime = parseTime(next.lastCreatedAt) === checkpointTime;+ const advanced: Checkpoint = sameTime+ ? { lastCreatedAt: next.lastCreatedAt, idsAtLast: [...checkpoint.idsAtLast, ...next.idsAtLast].slice(-MAX_IDS_AT_LAST) }+ : next;+ return { items: fresh, checkpoint: withCursors({ checkpoint: advanced, cursors: remaining, drainedCursor: nextDrained }) };+}++function withCursors({+ checkpoint,+ cursors,+ drainedCursor,+}: {+ checkpoint: Checkpoint;+ cursors: string[];+ drainedCursor: string | null;+}): Checkpoint {+ const withStack: Checkpoint = cursors.length > 0 ? { ...checkpoint, resumeCursors: cursors } : checkpoint;+ return drainedCursor !== null ? { ...withStack, drainedCursor } : withStack;+}++function checkpointChanged({ before, after }: { before: Checkpoint; after: Checkpoint }): boolean {+ return JSON.stringify(before) !== JSON.stringify(after);+}++function assertNewestFirst<T extends PolledItem>({ items, timeField }: { items: T[]; timeField: TimeField }): void {+ const times = items.map((item) => parseTime(item[timeField] ?? null)).filter((time): time is number => time !== null);+ const ascending = times.some((time, index) => index > 0 && time > times[index - 1]);+ if (ascending) {+ throw new Error('Bettermode returned items in an unexpected order (oldest first). The trigger cannot check for new items safely.');+ }+}++function compareItems({ left, right, timeField }: { left: PolledItem; right: PolledItem; timeField: TimeField }): number {+ const leftTime = parseTime(left[timeField] ?? null) ?? 0;+ const rightTime = parseTime(right[timeField] ?? null) ?? 0;+ if (leftTime !== rightTime) {+ return leftTime - rightTime;+ }+ return (left.id ?? '').localeCompare(right.id ?? '');+}++function parseTime(value: string | null): number | null {+ if (value === null) {+ return null;+ }+ const time = Date.parse(value);+ return Number.isNaN(time) ? null : time;+}++const MAX_POLL_PAGES = 10;+const MAX_EMIT_PER_POLL = 100;+const MAX_IDS_AT_LAST = 10000;++export const bettermodePolling = {+ newestCheckpoint,+ collectNewItems,+ checkpointChanged,+ CHECKPOINT_KEY: 'bettermode_checkpoint',+ POLL_PAGE_SIZE: 50,+};++export type Checkpoint = {+ lastCreatedAt: string;+ idsAtLast: string[];+ resumeCursors?: string[];+ drainedCursor?: string;+};++type TimeField = 'created_at' | 'published_at';++export type PolledItem = {+ id: string | null;+ created_at: string | null;+ published_at?: string | null;+};++export type PolledPage<T> = {+ items: T[];+ next_cursor: string | null;+ has_more: boolean;+};diff --git a/packages/pieces/community/bettermode/src/lib/common/props.ts b/packages/pieces/community/bettermode/src/lib/common/props.tsnew file mode 100644index 00000000000..f635aa98910--- /dev/null+++ b/packages/pieces/community/bettermode/src/lib/common/props.ts@@ -0,0 +1,75 @@+import { Property } from '@activepieces/pieces-framework';+import { bettermodeAuth } from '../auth';+import { getSession } from './client';+import { bettermodeOps } from './operations';++export const memberSpacesDropdown = Property.Dropdown({+ auth: bettermodeAuth,+ displayName: 'Space',+ description: 'The space to post in. Lists the spaces the connected member has joined.',+ required: true,+ refreshers: [],+ options: async ({ auth }) => {+ if (!auth) {+ return { options: [], disabled: true, placeholder: 'Please authenticate first' };+ }+ try {+ const session = await getSession(auth.props);+ const options: { label: string; value: string }[][] = [];+ let after: string | null = null;+ for (let pageIndex = 0; pageIndex < bettermodeOps.MAX_PAGES; pageIndex++) {+ const page = await bettermodeOps.listSpacesPage({+ auth: auth.props,+ limit: 100,+ after,+ query: undefined,+ memberId: session.memberId,+ });+ options.push(+ page.items.flatMap((space) =>+ space.id === null ? [] : [{ label: space.name ?? space.id, value: space.id }]+ )+ );+ if (!page.has_more || page.next_cursor === null) {+ break;+ }+ after = page.next_cursor;+ }+ return { options: options.flat(), disabled: false };+ } catch (error) {+ return {+ options: [],+ disabled: true,+ placeholder: `Could not load spaces: ${error instanceof Error ? error.message : 'unknown error'}`,+ };+ }+ },+});++export const badgesDropdown = Property.Dropdown({+ auth: bettermodeAuth,+ displayName: 'Badge',+ description: 'The badge to assign or revoke',+ required: true,+ refreshers: [],+ options: async ({ auth }) => {+ if (!auth) {+ return { options: [], disabled: true, placeholder: 'Please authenticate first' };+ }+ try {+ const badges = await bettermodeOps.listBadges({ auth: auth.props });+ return {+ options: badges.flatMap((badge) =>+ badge.id === null ? [] : [{ label: badge.name ?? badge.id, value: badge.id }]+ ),+ disabled: false,+ };+ } catch (error) {+ return {+ options: [],+ disabled: true,+ placeholder: `Could not load badges: ${error instanceof Error ? error.message : 'unknown error'}`,+ };+ }+ },+});diff --git a/packages/pieces/community/bettermode/src/lib/common/schemas.ts b/packages/pieces/community/bettermode/src/lib/common/schemas.tsnew file mode 100644index 00000000000..c8e166fbd78--- /dev/null+++ b/packages/pieces/community/bettermode/src/lib/common/schemas.ts@@ -0,0 +1,246 @@+import { OutputSchema, OutputSchemaField } from '@activepieces/pieces-framework';++function pageSchema({+ label,+ labelKey,+ itemFields,+}: {+ label: string;+ labelKey: string;+ itemFields: OutputSchemaField[];+}): OutputSchema {+ return {+ fields: [+ { key: 'items', label, labelKey, listItems: itemFields },+ {+ key: 'next_cursor',+ label: 'Next Cursor',+ description: 'Pass as Cursor to fetch the next page. Empty on the last page.',+ },+ { key: 'has_more', label: 'Has More', format: 'boolean' },+ { key: 'total_count', label: 'Total Count', format: 'number', description: 'Total reported by Bettermode, when available.' },+ ],+ };+}++const postFields: OutputSchemaField[] = [+ { key: 'id', label: 'Post ID' },+ { key: 'title', label: 'Title' },+ { key: 'slug', label: 'Slug' },+ { key: 'url', label: 'URL', format: 'url' },+ { key: 'status', label: 'Status' },+ { key: 'space_id', label: 'Space ID' },+ { key: 'space_name', label: 'Space Name' },+ { key: 'post_type_id', label: 'Post Type ID' },+ { key: 'post_type_name', label: 'Post Type Name' },+ { key: 'owner_id', label: 'Author Member ID' },+ { key: 'owner_name', label: 'Author Name' },+ { key: 'replied_to_id', label: 'Replied To Post ID', description: 'Set on replies only.' },+ { key: 'content_html', label: 'Content (HTML)', format: 'html' },+ { key: 'text_content', label: 'Text Content' },+ { key: 'short_content', label: 'Short Content' },+ { key: 'tags', label: 'Tags', description: 'Comma-separated tag titles.' },+ { key: 'tag_ids', label: 'Tag IDs', description: 'Comma-separated tag IDs.' },+ { key: 'replies_count', label: 'Replies Count', format: 'number' },+ { key: 'reactions_count', label: 'Reactions Count', format: 'number' },+ { key: 'locked', label: 'Locked', format: 'boolean' },+ { key: 'hidden', label: 'Hidden', format: 'boolean' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },+ { key: 'published_at', label: 'Published At', format: 'datetime' },+];++const memberFields: OutputSchemaField[] = [+ { key: 'id', label: 'Member ID' },+ { key: 'name', label: 'Name' },+ { key: 'email', label: 'Email', format: 'email', description: 'Only visible to admins and the member themselves.' },+ { key: 'username', label: 'Username' },+ { key: 'tagline', label: 'Tagline' },+ { key: 'status', label: 'Status' },+ { key: 'role_id', label: 'Role ID' },+ { key: 'role_name', label: 'Role Name' },+ { key: 'url', label: 'Profile URL', format: 'url' },+ { key: 'created_at', label: 'Joined At', format: 'datetime' },+];++const spaceFields: OutputSchemaField[] = [+ { key: 'id', label: 'Space ID' },+ { key: 'name', label: 'Name' },+ { key: 'slug', label: 'Slug' },+ { key: 'url', label: 'URL', format: 'url' },+ { key: 'description', label: 'Description' },+ { key: 'type', label: 'Type' },+ { key: 'private', label: 'Private', format: 'boolean' },+ { key: 'hidden', label: 'Hidden', format: 'boolean' },+ { key: 'members_count', label: 'Members Count', format: 'number' },+ { key: 'posts_count', label: 'Posts Count', format: 'number' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+];++const spaceMemberFields: OutputSchemaField[] = [+ { key: 'member_id', label: 'Member ID' },+ { key: 'member_name', label: 'Member Name' },+ { key: 'member_email', label: 'Member Email', format: 'email' },+ { key: 'member_username', label: 'Member Username' },+ { key: 'role_id', label: 'Space Role ID' },+ { key: 'role_name', label: 'Space Role Name' },+];++const postTypeFields: OutputSchemaField[] = [+ { key: 'id', label: 'Post Type ID' },+ { key: 'name', label: 'Name' },+ { key: 'plural_name', label: 'Plural Name' },+ { key: 'slug', label: 'Slug' },+ { key: 'context', label: 'Context', description: 'post for top-level posts, reply for reply types.' },+ { key: 'archived', label: 'Archived', format: 'boolean' },+];++const tagFields: OutputSchemaField[] = [+ { key: 'id', label: 'Tag ID' },+ { key: 'title', label: 'Title' },+ { key: 'slug', label: 'Slug' },+ { key: 'description', label: 'Description' },+];++const badgeFields: OutputSchemaField[] = [+ { key: 'id', label: 'Badge ID' },+ { key: 'name', label: 'Name' },+ { key: 'short_description', label: 'Short Description' },+ { key: 'type', label: 'Type' },+ { key: 'active', label: 'Active', format: 'boolean' },+];++const eventFields: OutputSchemaField[] = [+ { key: 'id', label: 'Event ID' },+ { key: 'title', label: 'Title' },+ { key: 'slug', label: 'Slug' },+ { key: 'url', label: 'URL', format: 'url' },+ { key: 'status', label: 'Status' },+ { key: 'space_id', label: 'Space ID' },+ { key: 'start_time', label: 'Start Time', format: 'datetime' },+ { key: 'end_time', label: 'End Time', format: 'datetime' },+ { key: 'time_zone', label: 'Time Zone' },+ { key: 'capacity', label: 'Capacity', format: 'number' },+ { key: 'registrations_count', label: 'Registrations Count', format: 'number' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+];++const moderationFields: OutputSchemaField[] = [+ { key: 'id', label: 'Moderation Item ID' },+ { key: 'status', label: 'Status' },+ { key: 'flagged_by', label: 'Flagged By' },+ { key: 'description', label: 'Description' },+ { key: 'member_id', label: 'Member ID' },+ { key: 'space_id', label: 'Space ID' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },+];++const invitationFields: OutputSchemaField[] = [+ { key: 'id', label: 'Invitation ID' },+ { key: 'invitee_email', label: 'Invitee Email', format: 'email' },+ { key: 'invitee_name', label: 'Invitee Name' },+ { key: 'status', label: 'Status' },+ { key: 'expires_at', label: 'Expires At', format: 'datetime' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+];++const networkFields: OutputSchemaField[] = [+ { key: 'id', label: 'Community ID' },+ { key: 'name', label: 'Name' },+ { key: 'domain', label: 'Domain' },+ { key: 'description', label: 'Description' },+ { key: 'plan_name', label: 'Plan' },+ { key: 'members_count', label: 'Members Count', format: 'number' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+];++function actionResult(extra: OutputSchemaField[]): OutputSchema {+ return {+ fields: [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'status', label: 'Bettermode Status', description: 'succeeded or failed, as reported by Bettermode.' },+ ...extra,+ ],+ };+}++export const bettermodeSchemas = {+ post: { fields: postFields },+ member: { fields: memberFields },+ space: { fields: spaceFields },+ network: { fields: networkFields },+ posts: pageSchema({ label: 'Posts', labelKey: 'title', itemFields: postFields }),+ members: pageSchema({ label: 'Members', labelKey: 'name', itemFields: memberFields }),+ spaces: pageSchema({ label: 'Spaces', labelKey: 'name', itemFields: spaceFields }),+ spaceMembers: pageSchema({ label: 'Space Members', labelKey: 'member_name', itemFields: spaceMemberFields }),+ postTypes: pageSchema({ label: 'Post Types', labelKey: 'name', itemFields: postTypeFields }),+ tags: pageSchema({ label: 'Tags', labelKey: 'title', itemFields: tagFields }),+ events: pageSchema({ label: 'Events', labelKey: 'title', itemFields: eventFields }),+ moderationItems: pageSchema({ label: 'Moderation Items', labelKey: 'id', itemFields: moderationFields }),+ badges: {+ fields: [+ { key: 'items', label: 'Badges', labelKey: 'name', listItems: badgeFields },+ { key: 'count', label: 'Badge Count', format: 'number' },+ ],+ },+ findMember: {+ fields: [+ { key: 'found', label: 'Found', format: 'boolean' },+ { key: 'member', label: 'Member', children: memberFields },+ ],+ },+ spaceMembership: {+ fields: [+ { key: 'space_id', label: 'Space ID' },+ { key: 'member_ids', label: 'Member IDs', description: 'Comma-separated member IDs.' },+ { key: 'items', label: 'Space Members', labelKey: 'member_name', listItems: spaceMemberFields },+ ],+ },+ removeFromSpace: actionResult([+ { key: 'space_id', label: 'Space ID' },+ { key: 'member_ids', label: 'Member IDs', description: 'Comma-separated member IDs.' },+ ]),+ postAction: actionResult([{ key: 'post_id', label: 'Post ID' }]),+ reaction: actionResult([+ { key: 'post_id', label: 'Post ID' },+ { key: 'reaction', label: 'Reaction' },+ ]),+ memberAction: actionResult([{ key: 'member_id', label: 'Member ID' }]),+ badgeAction: actionResult([+ { key: 'badge_id', label: 'Badge ID' },+ { key: 'member_id', label: 'Member ID' },+ ]),+ legacyBadgeAction: actionResult([+ { key: 'badge_id', label: 'Badge ID' },+ { key: 'member_id', label: 'Member ID' },+ { key: 'member_name', label: 'Member Name' },+ { key: 'member_email', label: 'Member Email', format: 'email' },+ ]),+ eventRegistration: actionResult([{ key: 'event_id', label: 'Event ID' }]),+ deleted: {+ fields: [+ { key: 'id', label: 'Deleted ID' },+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ { key: 'status', label: 'Bettermode Status' },+ ],+ },+ invitations: {+ fields: [+ { key: 'items', label: 'Invitations', labelKey: 'invitee_email', listItems: invitationFields },+ { key: 'count', label: 'Invitations Sent', format: 'number' },+ ],+ },+ message: {+ fields: [+ { key: 'message_id', label: 'Message ID' },+ { key: 'chat_id', label: 'Chat ID' },+ { key: 'recipient_id', label: 'Recipient Member ID' },+ { key: 'content', label: 'Content' },+ { key: 'sent_at', label: 'Sent At', format: 'datetime' },+ ],+ },+ legacyPost: {+ fields: [{ key: 'createdAt', label: 'Created At (legacy key)', format: 'datetime' }, ...postFields],+ },+} satisfies Record<string, OutputSchema>;diff --git a/packages/pieces/community/bettermode/src/lib/props.ts b/packages/pieces/community/bettermode/src/lib/props.tsdeleted file mode 100644index 319ebffc0a7..00000000000--- a/packages/pieces/community/bettermode/src/lib/props.ts+++ /dev/null@@ -1,36 +0,0 @@-import { BettermodeAuthType } from './auth';-import { listMemberSpaces, listBadges } from './api';--export async function buildMemberSpacesDropdown(auth?: BettermodeAuthType) {- if (!auth) {- return {- options: [],- disabled: true,- placeholder: 'Please authenticate first',- };- }- const spaces = await listMemberSpaces(auth as BettermodeAuthType);- const options = spaces.map((space: { name: string; id: string }) => {- return { label: space.name, value: space.id };- });- return {- options: options,- };-}--export async function buildBadgesDropdown(auth?: BettermodeAuthType) {- if (!auth) {- return {- options: [],- disabled: true,- placeholder: 'Please authenticate first',- };- }- const badges = await listBadges(auth as BettermodeAuthType);- const options = badges.map((badge: { name: string; id: string }) => {- return { label: badge.name, value: badge.id };- });- return {- options: options,- };-}diff --git a/packages/pieces/community/bettermode/src/lib/triggers/fetchers.ts b/packages/pieces/community/bettermode/src/lib/triggers/fetchers.tsnew file mode 100644index 00000000000..4e09723a990--- /dev/null+++ b/packages/pieces/community/bettermode/src/lib/triggers/fetchers.ts@@ -0,0 +1,137 @@+import { BettermodeCredentials, bettermodeQuery, readPath } from '../common/client';+import { MEMBER_FIELDS, PAGE_INFO, POST_FIELDS } from '../common/fields';+import { bettermodeInput } from '../common/input';+import { bettermodeMap } from '../common/mappers';+import { bettermodePolling } from '../common/polling';++async function fetchPostsPage({+ auth,+ spaceIds,+ postTypeIds,+ cursor,+ limit,+}: {+ auth: BettermodeCredentials;+ spaceIds: string[];+ postTypeIds: string[];+ cursor: string | null;+ limit: number;+}) {+ const data = await bettermodeQuery({+ auth,+ query: `query PollPosts($limit: Int!, $after: String, $spaceIds: [ID!], $postTypeIds: [String!], $orderBy: PostListOrderByEnum, $reverse: Boolean) {+ posts(limit: $limit, after: $after, spaceIds: $spaceIds, postTypeIds: $postTypeIds, orderBy: $orderBy, reverse: $reverse) {+ nodes {+${POST_FIELDS}+ }+ ${PAGE_INFO}+ }+}`,+ variables: {+ limit,+ after: cursor,+ spaceIds: spaceIds.length > 0 ? spaceIds : undefined,+ postTypeIds: postTypeIds.length > 0 ? postTypeIds : undefined,+ orderBy: 'publishedAt',+ reverse: true,+ },+ });+ const page = bettermodeMap.page({ value: data['posts'], map: bettermodeMap.post });+ return { ...page, items: page.items.filter((post) => post.published_at !== null && (post.status === null || post.status === 'PUBLISHED')) };+}++async function fetchMembersPage({+ auth,+ cursor,+ limit,+}: {+ auth: BettermodeCredentials;+ cursor: string | null;+ limit: number;+}) {+ const data = await bettermodeQuery({+ auth,+ query: `query PollMembers($limit: Int!, $after: String, $orderBy: String, $reverse: Boolean) {+ members(limit: $limit, after: $after, orderBy: $orderBy, reverse: $reverse) {+ nodes {+${MEMBER_FIELDS}+ }+ ${PAGE_INFO}+ }+}`,+ variables: { limit, after: cursor, orderBy: 'createdAt', reverse: true },+ });+ return bettermodeMap.page({ value: data['members'], map: bettermodeMap.member });+}++async function fetchRecentReplies({+ auth,+ spaceIds,+}: {+ auth: BettermodeCredentials;+ spaceIds: string[];+}) {+ const active = await bettermodeQuery({+ auth,+ query: `query PollActivePosts($limit: Int!, $spaceIds: [ID!], $orderBy: PostListOrderByEnum, $reverse: Boolean) {+ posts(limit: $limit, spaceIds: $spaceIds, orderBy: $orderBy, reverse: $reverse) {+ nodes {+ id+ repliesCount+ }+ }+}`,+ variables: {+ limit: ACTIVE_POSTS_PER_POLL,+ spaceIds: spaceIds.length > 0 ? spaceIds : undefined,+ orderBy: 'lastActivityAt',+ reverse: true,+ },+ });+ const postIds = bettermodeMap+ .records(readPath({ value: active, path: ['posts', 'nodes'] }))+ .filter((node) => typeof node['repliesCount'] !== 'number' || node['repliesCount'] > 0)+ .map((node) => node['id'])+ .filter((id): id is string => typeof id === 'string');+ if (postIds.length === 0) {+ return { items: [], next_cursor: null, has_more: false };+ }+ const declarations = postIds.map((_, index) => `$p${index}: ID!`).join(', ');+ const selections = postIds+ .map(+ (_, index) => ` r${index}: replies(postId: $p${index}, limit: ${REPLIES_PER_POST}, orderBy: createdAt, reverse: true) {+ nodes {+${POST_FIELDS}+ }+ }`+ )+ .join('\n');+ const variables = Object.fromEntries(postIds.map((id, index) => [`p${index}`, id]));+ const data = await bettermodeQuery({+ auth,+ query: `query PollReplies(${declarations}) {+${selections}+}`,+ variables,+ });+ const replies = postIds+ .flatMap((_, index) => bettermodeMap.records(readPath({ value: data, path: [`r${index}`, 'nodes'] })))+ .map((node) => bettermodeMap.post(node))+ .sort((left, right) => (Date.parse(right.created_at ?? '') || 0) - (Date.parse(left.created_at ?? '') || 0));+ return { items: replies, next_cursor: null, has_more: false };+}++function spaceFilter(value: unknown): string[] {+ return bettermodeInput.stringList({ value, label: 'Space IDs' });+}++const ACTIVE_POSTS_PER_POLL = 25;+const REPLIES_PER_POST = 20;++export const bettermodeFetchers = {+ fetchPostsPage,+ fetchMembersPage,+ fetchRecentReplies,+ spaceFilter,+ pageSize: bettermodePolling.POLL_PAGE_SIZE,+};diff --git a/packages/pieces/community/bettermode/src/lib/triggers/new-member.ts b/packages/pieces/community/bettermode/src/lib/triggers/new-member.tsnew file mode 100644index 00000000000..f9c9e8cb8dd--- /dev/null+++ b/packages/pieces/community/bettermode/src/lib/triggers/new-member.ts@@ -0,0 +1,68 @@+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';+import { bindTokenStore } from '../common/client';+import { bettermodeAuth } from '../auth';+import { bettermodePolling, Checkpoint } from '../common/polling';+import { bettermodeSchemas } from '../common/schemas';+import { bettermodeFetchers } from './fetchers';+import { SAMPLE_MEMBER } from './samples';++export const newMemberTrigger = createTrigger({+ auth: bettermodeAuth,+ name: 'new_member',+ classification: 'READ',+ displayName: 'New Member',+ description: 'Triggers when a new member joins the community.',+ aiMetadata: {+ description: 'Fires once per newly joined community member, checked on a schedule, oldest first. Emails are only included for admin connections.',+ },+ props: {},+ type: TriggerStrategy.POLLING,+ sampleData: SAMPLE_MEMBER,+ outputSchema: bettermodeSchemas.member,+ async onEnable(context) {+ if (context.isRepublish) {+ const existing = await context.store.get<Checkpoint>(bettermodePolling.CHECKPOINT_KEY);+ if (existing !== null && existing !== undefined) {+ return;+ }+ }+ bindTokenStore({ credentials: context.auth.props, store: context.store });+ const page = await bettermodeFetchers.fetchMembersPage({+ auth: context.auth.props,+ cursor: null,+ limit: bettermodeFetchers.pageSize,+ });+ await context.store.put<Checkpoint>(+ bettermodePolling.CHECKPOINT_KEY,+ bettermodePolling.newestCheckpoint({ items: page.items, fallback: new Date().toISOString() })+ );+ },+ async onDisable() {+ return;+ },+ async test(context) {+ bindTokenStore({ credentials: context.auth.props, store: context.store });+ const page = await bettermodeFetchers.fetchMembersPage({ auth: context.auth.props, cursor: null, limit: 5 });+ return page.items;+ },+ async run(context) {+ bindTokenStore({ credentials: context.auth.props, store: context.store });+ const checkpoint = await context.store.get<Checkpoint>(bettermodePolling.CHECKPOINT_KEY);+ if (checkpoint === null || checkpoint === undefined) {+ throw new Error('The trigger has no checkpoint yet. Disable and re-enable the trigger.');+ }+ const result = await bettermodePolling.collectNewItems({+ checkpoint,+ fetchPage: (cursor) =>+ bettermodeFetchers.fetchMembersPage({+ auth: context.auth.props,+ cursor,+ limit: bettermodeFetchers.pageSize,+ }),+ });+ if (bettermodePolling.checkpointChanged({ before: checkpoint, after: result.checkpoint })) {+ await context.store.put<Checkpoint>(bettermodePolling.CHECKPOINT_KEY, result.checkpoint);+ }+ return result.items;+ },+});diff --git a/packages/pieces/community/bettermode/src/lib/triggers/new-post.ts b/packages/pieces/community/bettermode/src/lib/triggers/new-post.tsnew file mode 100644index 00000000000..a3df90166af--- /dev/null+++ b/packages/pieces/community/bettermode/src/lib/triggers/new-post.ts@@ -0,0 +1,87 @@+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';+import { bindTokenStore } from '../common/client';+import { bettermodeAuth } from '../auth';+import { bettermodePolling, Checkpoint } from '../common/polling';+import { bettermodeSchemas } from '../common/schemas';+import { bettermodeFetchers } from './fetchers';+import { SAMPLE_POST } from './samples';++export const newPostTrigger = createTrigger({+ auth: bettermodeAuth,+ name: 'new_post',+ classification: 'READ',+ displayName: 'New Post',+ description: 'Triggers when a new post is published, optionally only in some spaces.',+ aiMetadata: {+ description:+ 'Fires once per new top-level post (checked on a schedule), oldest first, optionally only in the given spaces. Replies do not fire this trigger; use New Reply.',+ },+ props: {+ space_ids: Property.Array({+ displayName: 'Space IDs',+ description: 'Only watch these spaces. Leave empty for all spaces the connected member can see.',+ required: false,+ }),+ },+ type: TriggerStrategy.POLLING,+ sampleData: SAMPLE_POST,+ outputSchema: bettermodeSchemas.post,+ async onEnable(context) {+ if (context.isRepublish) {+ const existing = await context.store.get<Checkpoint>(bettermodePolling.CHECKPOINT_KEY);+ if (existing !== null && existing !== undefined) {+ return;+ }+ }+ bindTokenStore({ credentials: context.auth.props, store: context.store });+ const page = await bettermodeFetchers.fetchPostsPage({+ auth: context.auth.props,+ spaceIds: bettermodeFetchers.spaceFilter(context.propsValue.space_ids),+ postTypeIds: [],+ cursor: null,+ limit: bettermodeFetchers.pageSize,+ });+ await context.store.put<Checkpoint>(+ bettermodePolling.CHECKPOINT_KEY,+ bettermodePolling.newestCheckpoint({ items: page.items, fallback: new Date().toISOString(), timeField: 'published_at' })+ );+ },+ async onDisable() {+ return;+ },+ async test(context) {+ bindTokenStore({ credentials: context.auth.props, store: context.store });+ const page = await bettermodeFetchers.fetchPostsPage({+ auth: context.auth.props,+ spaceIds: bettermodeFetchers.spaceFilter(context.propsValue.space_ids),+ postTypeIds: [],+ cursor: null,+ limit: 5,+ });+ return page.items;+ },+ async run(context) {+ bindTokenStore({ credentials: context.auth.props, store: context.store });+ const checkpoint = await context.store.get<Checkpoint>(bettermodePolling.CHECKPOINT_KEY);+ if (checkpoint === null || checkpoint === undefined) {+ throw new Error('The trigger has no checkpoint yet. Disable and re-enable the trigger.');+ }+ const spaceIds = bettermodeFetchers.spaceFilter(context.propsValue.space_ids);+ const result = await bettermodePolling.collectNewItems({+ checkpoint,+ fetchPage: (cursor) =>+ bettermodeFetchers.fetchPostsPage({+ auth: context.auth.props,+ spaceIds,+ postTypeIds: [],+ cursor,+ limit: bettermodeFetchers.pageSize,+ }),+ timeField: 'published_at',+ });+ if (bettermodePolling.checkpointChanged({ before: checkpoint, after: result.checkpoint })) {+ await context.store.put<Checkpoint>(bettermodePolling.CHECKPOINT_KEY, result.checkpoint);+ }+ return result.items;+ },+});diff --git a/packages/pieces/community/bettermode/src/lib/triggers/new-reply.ts b/packages/pieces/community/bettermode/src/lib/triggers/new-reply.tsnew file mode 100644index 00000000000..ffab42acaba--- /dev/null+++ b/packages/pieces/community/bettermode/src/lib/triggers/new-reply.ts@@ -0,0 +1,73 @@+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';+import { bindTokenStore } from '../common/client';+import { bettermodeAuth } from '../auth';+import { bettermodePolling, Checkpoint } from '../common/polling';+import { bettermodeSchemas } from '../common/schemas';+import { bettermodeFetchers } from './fetchers';+import { SAMPLE_REPLY } from './samples';++export const newReplyTrigger = createTrigger({+ auth: bettermodeAuth,+ name: 'new_reply',+ classification: 'READ',+ displayName: 'New Reply',+ description: 'Triggers when someone replies to a post (comments and answers).',+ aiMetadata: {+ description:+ 'Fires once per new reply (comment or answer) on a post, checked on a schedule, oldest first, optionally only in the given spaces. Each check looks at the 25 most recently active posts and their 20 newest direct replies. Replied To Post ID holds the parent post.',+ },+ props: {+ space_ids: Property.Array({+ displayName: 'Space IDs',+ description: 'Only watch replies in these spaces. Leave empty for all spaces.',+ required: false,+ }),+ },+ type: TriggerStrategy.POLLING,+ sampleData: SAMPLE_REPLY,+ outputSchema: bettermodeSchemas.post,+ async onEnable(context) {+ if (context.isRepublish) {+ const existing = await context.store.get<Checkpoint>(bettermodePolling.CHECKPOINT_KEY);+ if (existing !== null && existing !== undefined) {+ return;+ }+ }+ bindTokenStore({ credentials: context.auth.props, store: context.store });+ const page = await bettermodeFetchers.fetchRecentReplies({+ auth: context.auth.props,+ spaceIds: bettermodeFetchers.spaceFilter(context.propsValue.space_ids),+ });+ await context.store.put<Checkpoint>(+ bettermodePolling.CHECKPOINT_KEY,+ bettermodePolling.newestCheckpoint({ items: page.items, fallback: new Date().toISOString() })+ );+ },+ async onDisable() {+ return;+ },+ async test(context) {+ bindTokenStore({ credentials: context.auth.props, store: context.store });+ const page = await bettermodeFetchers.fetchRecentReplies({+ auth: context.auth.props,+ spaceIds: bettermodeFetchers.spaceFilter(context.propsValue.space_ids),+ });+ return page.items.slice(0, 5);+ },+ async run(context) {+ bindTokenStore({ credentials: context.auth.props, store: context.store });+ const checkpoint = await context.store.get<Checkpoint>(bettermodePolling.CHECKPOINT_KEY);+ if (checkpoint === null || checkpoint === undefined) {+ throw new Error('The trigger has no checkpoint yet. Disable and re-enable the trigger.');+ }+ const spaceIds = bettermodeFetchers.spaceFilter(context.propsValue.space_ids);+ const result = await bettermodePolling.collectNewItems({+ checkpoint,+ fetchPage: () => bettermodeFetchers.fetchRecentReplies({ auth: context.auth.props, spaceIds }),+ });+ if (bettermodePolling.checkpointChanged({ before: checkpoint, after: result.checkpoint })) {+ await context.store.put<Checkpoint>(bettermodePolling.CHECKPOINT_KEY, result.checkpoint);+ }+ return result.items;+ },+});diff --git a/packages/pieces/community/bettermode/src/lib/triggers/samples.ts b/packages/pieces/community/bettermode/src/lib/triggers/samples.tsnew file mode 100644index 00000000000..50519ec89f2--- /dev/null+++ b/packages/pieces/community/bettermode/src/lib/triggers/samples.ts@@ -0,0 +1,57 @@+export const SAMPLE_POST = {+ id: 'Qx7PzLm0aB3c',+ title: 'Welcome to the community',+ slug: 'welcome-to-the-community-qx7pzlm0ab3c',+ url: 'https://community.example.com/discussions/post/welcome-to-the-community-qx7pzlm0ab3c',+ status: 'PUBLISHED',+ space_id: 'xG4nT2qWk9Lm',+ space_name: 'Discussions',+ post_type_id: 'dJk3Pq8vX1aZ',+ post_type_name: 'Discussion',+ owner_id: 'mB5tYv2nQ8rS',+ owner_name: 'Jane Doe',+ replied_to_id: null,+ content_html: '<p>Say hello!</p>',+ text_content: 'Say hello!',+ short_content: '<p>Say hello!</p>',+ tags: 'welcome, intro',+ tag_ids: 'tA1b2C3d4E5f, tG6h7I8j9K0l',+ replies_count: 3,+ reactions_count: 5,+ locked: false,+ hidden: false,+ created_at: '2026-10-13T09:15:00.000Z',+ updated_at: '2026-10-13T09:20:00.000Z',+ published_at: '2026-10-13T09:15:00.000Z',+};++export const SAMPLE_REPLY = {+ ...SAMPLE_POST,+ id: 'Rp2LmN8vQ4sT',+ title: null,+ slug: null,+ url: 'https://community.example.com/discussions/post/welcome-to-the-community-qx7pzlm0ab3c?highlight=Rp2LmN8vQ4sT',+ post_type_id: 'cMt5Rq1wE7yU',+ post_type_name: 'Comment',+ replied_to_id: 'Qx7PzLm0aB3c',+ content_html: '<p>Hi everyone!</p>',+ text_content: 'Hi everyone!',+ short_content: '<p>Hi everyone!</p>',+ tags: '',+ tag_ids: '',+ replies_count: 0,+ reactions_count: 1,+};++export const SAMPLE_MEMBER = {+ id: 'mB5tYv2nQ8rS',+ name: 'Jane Doe',+ email: '[email protected]',+ username: 'janedoe',+ tagline: 'Product designer',+ status: 'VERIFIED',+ role_id: 'rL3kP9mN2qW8',+ role_name: 'Member',+ url: 'https://community.example.com/member/mB5tYv2nQ8rS',+ created_at: '2026-10-13T08:00:00.000Z',+};diff --git a/packages/pieces/community/bettermode/test/actions.test.ts b/packages/pieces/community/bettermode/test/actions.test.tsnew file mode 100644index 00000000000..c44106d1d20--- /dev/null+++ b/packages/pieces/community/bettermode/test/actions.test.ts@@ -0,0 +1,697 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { bettermode } from '../src';+import { clearSessionCache } from '../src/lib/common/client';+import { getCurrentMemberAction, getNetworkAction } from '../src/lib/actions/ai/account';+import {+ assignBadgeToMemberAction,+ listBadgesAction,+ listEventsAction,+ listModerationItemsAction,+ registerForEventAction,+ revokeBadgeFromMemberAction,+} from '../src/lib/actions/ai/community';+import {+ deleteMemberAction,+ findMemberByEmailAction,+ getMemberAction,+ inviteMembersAction,+ listMembersAction,+ sendDirectMessageAction,+ suspendMemberAction,+ unsuspendMemberAction,+ updateMemberAction,+} from '../src/lib/actions/ai/members';+import {+ addReactionAction,+ createPostAction,+ createReplyAction,+ deletePostAction,+ getPostAction,+ hidePostAction,+ listPostsAction,+ listPostTypesAction,+ listRepliesAction,+ listTagsAction,+ movePostAction,+ pinPostAction,+ removeReactionAction,+ searchPostsAction,+ unhidePostAction,+ unpinPostAction,+ updatePostAction,+} from '../src/lib/actions/ai/posts';+import {+ addMemberToSpaceAction,+ getSpaceAction,+ listSpaceMembersAction,+ listSpacesAction,+ removeMemberFromSpaceAction,+} from '../src/lib/actions/ai/spaces';+import { assignBadgeAction } from '../src/lib/actions/assign-badge';+import { createDiscussionAction } from '../src/lib/actions/create-discussion';+import { createQuestionAction } from '../src/lib/actions/create-question';+import { revokeBadgeAction } from '../src/lib/actions/revoke-badge';+import { businessCalls, call, makeContext, MEMBER_TOKEN, pageOf, stubGraphql } from './helpers';++afterEach(() => {+ clearSessionCache();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++const POST_NODE = {+ id: 'post1',+ title: 'Hello',+ slug: 'hello-post1',+ url: 'https://community.example.com/p/hello-post1',+ status: 'PUBLISHED',+ spaceId: 'space1',+ space: { name: 'General' },+ postTypeId: 'type1',+ postType: { name: 'Discussion' },+ ownerId: 'm1',+ owner: { member: { name: 'Ann' } },+ repliedToId: null,+ textContent: 'Body',+ shortContent: '<p>Body</p>',+ fields: [+ { key: 'title', value: '"Hello"' },+ { key: 'content', value: '"<p>Body</p>"' },+ ],+ tags: [+ { id: 't1', title: 'news' },+ { id: 't2', title: 'intro' },+ ],+ repliesCount: 2,+ reactionsCount: 4,+ locked: false,+ isHidden: false,+ createdAt: '2026-10-13T10:00:00.000Z',+ updatedAt: '2026-10-13T10:05:00.000Z',+ publishedAt: '2026-10-13T10:00:00.000Z',+};++const POST_OUT = {+ id: 'post1',+ title: 'Hello',+ url: 'https://community.example.com/p/hello-post1',+ space_id: 'space1',+ space_name: 'General',+ post_type_name: 'Discussion',+ owner_name: 'Ann',+ content_html: '<p>Body</p>',+ tags: 'news, intro',+ tag_ids: 't1, t2',+ replies_count: 2,+ created_at: '2026-10-13T10:00:00.000Z',+};++const MEMBER_NODE = {+ id: 'm1',+ name: 'Ann',+ email: '[email protected]',+ username: 'ann',+ tagline: null,+ status: 'VERIFIED',+ url: 'https://community.example.com/member/m1',+ createdAt: '2026-10-01T00:00:00.000Z',+ role: { id: 'r1', name: 'Admin' },+};++const MEMBER_OUT = { id: 'm1', name: 'Ann', email: '[email protected]', role_name: 'Admin', tagline: null };++const SPACE_NODE = {+ id: 'space1',+ name: 'General',+ slug: 'general',+ url: 'https://community.example.com/general',+ description: null,+ type: 'Group',+ private: false,+ hidden: false,+ membersCount: 10,+ postsCount: 3,+ createdAt: '2026-01-01T00:00:00.000Z',+};++const OK = { status: 'succeeded' };++type Case = {+ name: string;+ action: unknown;+ props: Record<string, unknown>;+ operation: string;+ variables: Record<string, unknown>;+ data: Record<string, unknown>;+ output: Record<string, unknown>;+ extra?: Record<string, unknown>;+};++const CASES: Case[] = [+ {+ name: 'get_current_member',+ action: getCurrentMemberAction,+ props: {},+ operation: 'GetCurrentMember',+ variables: {},+ data: { authMember: MEMBER_NODE },+ output: MEMBER_OUT,+ },+ {+ name: 'get_network',+ action: getNetworkAction,+ props: {},+ operation: 'GetNetwork',+ variables: {},+ data: { network: { id: 'n1', name: 'Acme', domain: 'community.example.com', planName: 'Pro', membersCount: 50 } },+ output: { id: 'n1', name: 'Acme', plan_name: 'Pro', members_count: 50 },+ },+ {+ name: 'list_spaces',+ action: listSpacesAction,+ props: { query: 'gen', limit: 10, cursor: 'c1', member_id: 'm1' },+ operation: 'ListSpaces',+ variables: { limit: 10, after: 'c1', query: 'gen', memberId: 'm1' },+ data: { spaces: pageOf({ nodes: [SPACE_NODE], hasNextPage: true, endCursor: 'c2' }) },+ output: { items: [{ id: 'space1', name: 'General', members_count: 10 }], next_cursor: 'c2', has_more: true },+ },+ {+ name: 'get_space',+ action: getSpaceAction,+ props: { slug: 'general' },+ operation: 'GetSpace',+ variables: { slug: 'general' },+ data: { space: SPACE_NODE },+ output: { id: 'space1', slug: 'general' },+ },+ {+ name: 'list_space_members',+ action: listSpaceMembersAction,+ props: { space_id: 'space1' },+ operation: 'ListSpaceMembers',+ variables: { spaceId: 'space1', limit: 20, after: null },+ data: { spaceMembers: pageOf([{ member: MEMBER_NODE, role: { id: 'sr1', name: 'Member' } }]) },+ output: { items: [{ member_id: 'm1', member_name: 'Ann', role_name: 'Member' }], next_cursor: null, has_more: false },+ },+ {+ name: 'add_member_to_space',+ action: addMemberToSpaceAction,+ props: { space_id: 'space1', member_ids: ['m1', 'm2'], role_id: 'sr1' },+ operation: 'AddSpaceMembers',+ variables: {+ spaceId: 'space1',+ input: [+ { memberId: 'm1', roleId: 'sr1' },+ { memberId: 'm2', roleId: 'sr1' },+ ],+ },+ data: { addSpaceMembers: [{ member: MEMBER_NODE, role: { id: 'sr1', name: 'Member' } }] },+ output: { space_id: 'space1', member_ids: 'm1, m2', items: [{ member_id: 'm1' }] },+ },+ {+ name: 'remove_member_from_space',+ action: removeMemberFromSpaceAction,+ props: { space_id: 'space1', member_ids: ['m1'] },+ operation: 'RemoveSpaceMembers',+ variables: { spaceId: 'space1', memberIds: ['m1'] },+ data: { removeSpaceMembers: [OK] },+ output: { success: true, space_id: 'space1', member_ids: 'm1' },+ },+ {+ name: 'list_post_types',+ action: listPostTypesAction,+ props: { context: 'reply' },+ operation: 'ListPostTypes',+ variables: { limit: 20, after: null, context: 'reply' },+ data: { postTypes: pageOf([{ id: 'c1', name: 'Comment', pluralName: 'Comments', slug: 'comment', context: 'reply', archived: false }]) },+ output: { items: [{ id: 'c1', name: 'Comment', context: 'reply' }] },+ },+ {+ name: 'list_posts',+ action: listPostsAction,+ props: { space_ids: ['space1'], post_type_ids: [], order_by: 'lastActivityAt', reverse: true },+ operation: 'ListPosts',+ variables: { limit: 20, after: null, spaceIds: ['space1'], orderBy: 'lastActivityAt', reverse: true },+ data: { posts: pageOf([POST_NODE]) },+ output: { items: [POST_OUT] },+ },+ {+ name: 'search_posts',+ action: searchPostsAction,+ props: { query: 'hello' },+ operation: 'SearchPosts',+ variables: { query: 'hello', limit: 20, after: null },+ data: { searchPosts: pageOf([POST_NODE]) },+ output: { items: [POST_OUT] },+ },+ {+ name: 'get_post',+ action: getPostAction,+ props: { post_id: 'post1' },+ operation: 'GetPost',+ variables: { id: 'post1' },+ data: { post: POST_NODE },+ output: POST_OUT,+ },+ {+ name: 'create_post',+ action: createPostAction,+ props: { space_id: 'space1', post_type_id: 'type1', title: 'Hello "x"', content: '<p>Body</p>', tag_names: ['news', ' ', 'intro'], locked: true },+ operation: 'CreatePost',+ variables: {+ spaceId: 'space1',+ input: {+ postTypeId: 'type1',+ mappingFields: [+ { key: 'title', type: 'text', value: '"Hello \\"x\\""' },+ { key: 'content', type: 'html', value: '"<p>Body</p>"' },+ ],+ tagNames: ['news', 'intro'],+ locked: true,+ },+ },+ data: { createPost: POST_NODE },+ output: POST_OUT,+ },+ {+ name: 'update_post',+ action: updatePostAction,+ props: { post_id: 'post1', title: 'New', clear_tags: true, lock: 'unlock' },+ operation: 'UpdatePost',+ variables: {+ id: 'post1',+ input: { mappingFields: [{ key: 'title', type: 'text', value: '"New"' }], tagNames: [], locked: false },+ },+ data: { updatePost: POST_NODE },+ output: POST_OUT,+ },+ {+ name: 'delete_post',+ action: deletePostAction,+ props: { post_id: 'post1' },+ operation: 'DeletePost',+ variables: { id: 'post1' },+ data: { deletePost: OK },+ output: { id: 'post1', deleted: true, status: 'succeeded' },+ },+ {+ name: 'list_replies',+ action: listRepliesAction,+ props: { post_id: 'post1', limit: '5', cursor: 'c9' },+ operation: 'ListReplies',+ variables: { postId: 'post1', limit: 5, after: 'c9' },+ data: { replies: pageOf([{ ...POST_NODE, id: 'r1', repliedToId: 'post1' }]) },+ output: { items: [{ id: 'r1', replied_to_id: 'post1' }] },+ },+ {+ name: 'create_reply',+ action: createReplyAction,+ props: { post_id: 'post1', content: '<p>Hi</p>', reply_post_type_id: 'c1' },+ operation: 'CreateReply',+ variables: { postId: 'post1', input: { postTypeId: 'c1', mappingFields: [{ key: 'content', type: 'html', value: '"<p>Hi</p>"' }] } },+ data: { createReply: { ...POST_NODE, id: 'r1', repliedToId: 'post1' } },+ output: { id: 'r1', replied_to_id: 'post1' },+ },+ {+ name: 'add_reaction',+ action: addReactionAction,+ props: { post_id: 'post1', reaction: '+1' },+ operation: 'AddReaction',+ variables: { postId: 'post1', input: { reaction: '+1' } },+ data: { addReaction: OK },+ output: { success: true, post_id: 'post1', reaction: '+1' },+ },+ {+ name: 'remove_reaction',+ action: removeReactionAction,+ props: { post_id: 'post1', reaction: '+1' },+ operation: 'RemoveReaction',+ variables: { postId: 'post1', reaction: '+1' },+ data: { removeReaction: OK },+ output: { success: true, post_id: 'post1' },+ },+ {+ name: 'pin_post',+ action: pinPostAction,+ props: { post_id: 'post1' },+ operation: 'PinPost',+ variables: { postId: 'post1' },+ data: { pinPostToSpace: OK },+ output: { success: true, post_id: 'post1' },+ },+ {+ name: 'unpin_post',+ action: unpinPostAction,+ props: { post_id: 'post1' },+ operation: 'UnpinPost',+ variables: { postId: 'post1' },+ data: { unpinPostFromSpace: OK },+ output: { success: true },+ },+ {+ name: 'hide_post',+ action: hidePostAction,+ props: { post_id: 'post1' },+ operation: 'HidePost',+ variables: { id: 'post1' },+ data: { hidePost: OK },+ output: { success: true },+ },+ {+ name: 'unhide_post',+ action: unhidePostAction,+ props: { post_id: 'post1' },+ operation: 'UnhidePost',+ variables: { id: 'post1' },+ data: { unhidePost: OK },+ output: { success: true },+ },+ {+ name: 'move_post',+ action: movePostAction,+ props: { post_id: 'post1', space_id: 'space2' },+ operation: 'MovePost',+ variables: { id: 'post1', spaceId: 'space2' },+ data: { movePost: { ...POST_NODE, spaceId: 'space2' } },+ output: { id: 'post1', space_id: 'space2' },+ },+ {+ name: 'list_tags',+ action: listTagsAction,+ props: { space_id: 'space1', query: 'ne' },+ operation: 'ListTags',+ variables: { limit: 20, after: null, spaceId: 'space1', query: 'ne' },+ data: { tags: pageOf([{ id: 't1', title: 'news', slug: 'news', description: null }]) },+ output: { items: [{ id: 't1', title: 'news' }] },+ },+ {+ name: 'find_member_by_email',+ action: findMemberByEmailAction,+ props: { email: '[email protected]' },+ operation: 'FindMembers',+ variables: { query: '[email protected]', limit: 50, after: null },+ data: { members: pageOf([{ ...MEMBER_NODE, id: 'm9', email: '[email protected]' }, MEMBER_NODE]) },+ output: { found: true, member: MEMBER_OUT },+ },+ {+ name: 'get_member',+ action: getMemberAction,+ props: { username: 'ann' },+ operation: 'GetMember',+ variables: { username: 'ann' },+ data: { member: MEMBER_NODE },+ output: MEMBER_OUT,+ },+ {+ name: 'list_members',+ action: listMembersAction,+ props: { status: ['VERIFIED'], query: 'an' },+ operation: 'ListMembers',+ variables: { limit: 20, after: null, query: 'an', status: ['VERIFIED'] },+ data: { members: pageOf([MEMBER_NODE]) },+ output: { items: [MEMBER_OUT] },+ },+ {+ name: 'update_member',+ action: updateMemberAction,+ props: { member_id: 'm1', name: 'Ann B', clear_tagline: true },+ operation: 'UpdateMember',+ variables: { id: 'm1', input: { name: 'Ann B', tagline: '' } },+ data: { updateMember: MEMBER_NODE },+ output: MEMBER_OUT,+ },+ {+ name: 'invite_members',+ action: inviteMembersAction,+ props: { emails: ['[email protected]', '[email protected]'], invitation_message: 'Join us' },+ operation: 'InviteMembers',+ variables: { input: { invitees: [{ email: '[email protected]' }, { email: '[email protected]' }], invitationMessage: 'Join us' } },+ data: { inviteMembers: [{ id: 'i1', inviteeEmail: '[email protected]', status: 'PENDING' }] },+ output: { count: 1, items: [{ id: 'i1', invitee_email: '[email protected]' }] },+ },+ {+ name: 'suspend_member',+ action: suspendMemberAction,+ props: { member_id: 'm1' },+ operation: 'SuspendMember',+ variables: { memberId: 'm1' },+ data: { suspendMember: OK },+ output: { success: true, member_id: 'm1' },+ },+ {+ name: 'unsuspend_member',+ action: unsuspendMemberAction,+ props: { member_id: 'm1' },+ operation: 'UnsuspendMember',+ variables: { memberId: 'm1' },+ data: { unsuspendMember: OK },+ output: { success: true, member_id: 'm1' },+ },+ {+ name: 'delete_member',+ action: deleteMemberAction,+ props: { member_id: 'm1' },+ operation: 'DeleteMember',+ variables: { id: 'm1' },+ data: { deleteMember: OK },+ output: { id: 'm1', deleted: true },+ },+ {+ name: 'send_direct_message',+ action: sendDirectMessageAction,+ props: { recipient_id: 'm2', content: 'Hello' },+ operation: 'SendMessage',+ variables: { input: { recipientId: 'm2', message: { content: 'Hello' } } },+ data: { sendMessageToMember: { chatId: 'chat1', message: { _id: 'msg1', content: 'Hello', sentAt: '2026-10-13T00:00:00.000Z' } } },+ output: { message_id: 'msg1', chat_id: 'chat1', recipient_id: 'm2' },+ },+ {+ name: 'list_badges',+ action: listBadgesAction,+ props: {},+ operation: 'ListBadges',+ variables: {},+ data: { network: { badges: [{ id: 'b1', name: 'Helper', shortDescription: 'Helps', type: 'Custom', active: true }] } },+ output: { count: 1, items: [{ id: 'b1', name: 'Helper' }] },+ },+ {+ name: 'assign_badge_to_member',+ action: assignBadgeToMemberAction,+ props: { badge_id: 'b1', member_id: 'm1' },+ operation: 'AssignBadge',+ variables: { badgeId: 'b1', input: { memberId: 'm1' } },+ data: { assignBadge: OK },+ output: { success: true, badge_id: 'b1', member_id: 'm1' },+ },+ {+ name: 'revoke_badge_from_member',+ action: revokeBadgeFromMemberAction,+ props: { badge_id: 'b1', member_id: 'm1' },+ operation: 'RevokeBadge',+ variables: { badgeId: 'b1', input: { memberId: 'm1' } },+ data: { revokeBadge: OK },+ output: { success: true },+ },+ {+ name: 'list_events',+ action: listEventsAction,+ props: { space_ids: 'space1, space2', status: 'published' },+ operation: 'ListEvents',+ variables: { limit: 20, after: null, spaceIds: ['space1', 'space2'], status: 'published' },+ data: { events: pageOf([{ id: 'e1', title: 'Meetup', startTime: '2026-11-01T10:00:00.000Z', registrationsCount: 3 }]) },+ output: { items: [{ id: 'e1', title: 'Meetup', registrations_count: 3 }] },+ },+ {+ name: 'register_member_for_event',+ action: registerForEventAction,+ props: { event_id: 'e1' },+ operation: 'RegisterForEvent',+ variables: { eventId: 'e1' },+ data: { registerForEvent: OK },+ output: { success: true, event_id: 'e1' },+ },+ {+ name: 'list_moderation_items',+ action: listModerationItemsAction,+ props: { status: 'REVIEW' },+ operation: 'ListModerationItems',+ variables: { limit: 20, after: null, status: 'REVIEW' },+ data: { moderationItems: pageOf([{ id: 'mod1', status: 'REVIEW', flaggedBy: 'MEMBER' }]) },+ output: { items: [{ id: 'mod1', status: 'REVIEW', flagged_by: 'MEMBER' }] },+ },+];++describe('ai actions send the exact GraphQL request', () => {+ it.each(CASES)('$name', async ({ action, props, operation, variables, data, output }) => {+ const calls = stubGraphql({ [operation]: data });+ const result = await call({ fn: Reflect.get(Object(action), 'run'), ctx: makeContext({ props }) });+ const sent = businessCalls(calls);+ expect(sent).toHaveLength(1);+ expect(sent[0].operation).toBe(operation);+ expect(sent[0].variables).toEqual(variables);+ expect(sent[0].url).toBe('https://api.bettermode.com/');+ expect(sent[0].headers['authorization']).toBe(`Bearer ${MEMBER_TOKEN}`);+ expect(sent[0].redirect).toBe('manual');+ expect(result).toMatchObject(output);+ });++ it('covers every ai action of the piece', () => {+ const aiNames = Object.values(bettermode.actions())+ .filter((action) => action.audience === 'ai')+ .map((action) => action.name)+ .sort();+ expect(aiNames).toEqual(CASES.map((item) => item.name).sort());+ });++ it.each(CASES)('$name keeps input values out of the query text', async ({ action, props, operation, data }) => {+ const calls = stubGraphql({ [operation]: data });+ await call({ fn: Reflect.get(Object(action), 'run'), ctx: makeContext({ props }) });+ const query = businessCalls(calls)[0].query;+ const values = Object.values(props).flatMap((value) => (Array.isArray(value) ? value : [value]));+ for (const value of values) {+ if (typeof value === 'string' && value.trim().length >= 4) {+ expect(query).not.toContain(value.trim());+ }+ }+ });+});++describe('publishing', () => {+ it('publishes a post that Bettermode created as a draft', async () => {+ const calls = stubGraphql({+ CreatePost: { createPost: { ...POST_NODE, status: 'DRAFT' } },+ PublishPost: { publishPost: POST_NODE },+ });+ const result = await call({+ fn: createPostAction.run,+ ctx: makeContext({ props: { space_id: 's', post_type_id: 'pt', title: 'T', content: 'C' } }),+ });+ const publish = businessCalls(calls).find((item) => item.operation === 'PublishPost');+ expect(publish?.variables).toEqual({ postId: POST_NODE.id });+ expect(result).toMatchObject({ status: 'PUBLISHED' });+ });++ it('publishes a reply that Bettermode created as a draft', async () => {+ const calls = stubGraphql({+ CreateReply: { createReply: { ...POST_NODE, status: 'DRAFT' } },+ PublishPost: { publishPost: POST_NODE },+ });+ await call({+ fn: createReplyAction.run,+ ctx: makeContext({ props: { post_id: 'parent', content: 'C', reply_post_type_id: 'rt' } }),+ });+ expect(businessCalls(calls).some((item) => item.operation === 'PublishPost')).toBe(true);+ });++ it('does not publish again when the post is already published', async () => {+ const calls = stubGraphql({ CreatePost: { createPost: POST_NODE } });+ await call({+ fn: createPostAction.run,+ ctx: makeContext({ props: { space_id: 's', post_type_id: 'pt', title: 'T', content: 'C' } }),+ });+ expect(calls.some((item) => item.operation === 'PublishPost')).toBe(false);+ });+});++describe('human actions', () => {+ const postTypes = {+ postTypes: pageOf([+ { id: 'pt-board', name: 'Discussion Board' },+ { id: 'pt-disc', name: 'Discussion' },+ { id: 'pt-q', name: 'Question' },+ ]),+ };++ const noSpaceTypes = { space: { authMemberProps: { availablePostTypes: null } } };++ it('create_discussion matches the post type name exactly and omits empty tags', async () => {+ const calls = stubGraphql({ GetSpacePostTypes: noSpaceTypes, ListPostTypes: postTypes, CreatePost: { createPost: POST_NODE } });+ const result = await call({+ fn: createDiscussionAction.run,+ ctx: makeContext({ props: { spaceId: 'space1', title: 'T', content: 'C', tagNames: '', locked: false } }),+ });+ const create = businessCalls(calls).find((item) => item.operation === 'CreatePost');+ expect(create?.variables).toEqual({+ spaceId: 'space1',+ input: {+ postTypeId: 'pt-disc',+ mappingFields: [+ { key: 'title', type: 'text', value: '"T"' },+ { key: 'content', type: 'html', value: '"C"' },+ ],+ locked: false,+ },+ });+ expect(result).toMatchObject({ ...POST_OUT, createdAt: POST_NODE.createdAt });+ });++ it('create_question uses the Question type and splits comma tags', async () => {+ const calls = stubGraphql({ GetSpacePostTypes: noSpaceTypes, ListPostTypes: postTypes, CreatePost: { createPost: POST_NODE } });+ await call({+ fn: createQuestionAction.run,+ ctx: makeContext({ props: { spaceId: 'space1', title: 'T', content: 'C', tagNames: 'a, ,b,' } }),+ });+ const create = businessCalls(calls).find((item) => item.operation === 'CreatePost');+ expect(create?.variables['input']).toMatchObject({ postTypeId: 'pt-q', tagNames: ['a', 'b'] });+ });++ it('fails clearly when the post type does not exist instead of crashing', async () => {+ stubGraphql({ GetSpacePostTypes: noSpaceTypes, ListPostTypes: { postTypes: pageOf([{ id: 'x', name: 'Article' }]) } });+ await expect(+ call({ fn: createQuestionAction.run, ctx: makeContext({ props: { spaceId: 's', title: 'T', content: 'C' } }) })+ ).rejects.toThrow('No post type named "Question" exists in this community. Available post types: Article.');+ });++ it('create_discussion picks the Discussion type available in the space when names repeat', async () => {+ const calls = stubGraphql({+ GetSpacePostTypes: {+ space: { authMemberProps: { availablePostTypes: [{ id: 'pt-space-disc', name: 'Discussion', context: 'post' }] } },+ },+ CreatePost: { createPost: POST_NODE },+ });+ await call({ fn: createDiscussionAction.run, ctx: makeContext({ props: { spaceId: 'space1', title: 'T', content: 'C' } }) });+ expect(calls.some((item) => item.operation === 'ListPostTypes')).toBe(false);+ const create = businessCalls(calls).find((item) => item.operation === 'CreatePost');+ expect(create?.variables['input']).toMatchObject({ postTypeId: 'pt-space-disc' });+ });++ it('names the post types the space allows when the wanted type is not available there', async () => {+ stubGraphql({+ GetSpacePostTypes: { space: { authMemberProps: { availablePostTypes: [{ id: 'a', name: 'Article', context: 'post' }] } } },+ });+ await expect(+ call({ fn: createQuestionAction.run, ctx: makeContext({ props: { spaceId: 's', title: 'T', content: 'C' } }) })+ ).rejects.toThrow('No post type named "Question" is available in this space. Available post types: Article.');+ });++ it('assign_badge resolves the exact email, not the first fuzzy hit', async () => {+ const calls = stubGraphql({+ FindMembers: { members: pageOf([{ ...MEMBER_NODE, id: 'wrong', email: '[email protected]' }, MEMBER_NODE]) },+ AssignBadge: { assignBadge: OK },+ });+ const result = await call({+ fn: assignBadgeAction.run,+ ctx: makeContext({ props: { badgeId: 'b1', email: '[email protected]' } }),+ });+ expect(businessCalls(calls).find((item) => item.operation === 'AssignBadge')?.variables).toEqual({+ badgeId: 'b1',+ input: { memberId: 'm1' },+ });+ expect(result).toEqual({+ success: true,+ status: 'succeeded',+ badge_id: 'b1',+ member_id: 'm1',+ member_name: 'Ann',+ member_email: '[email protected]',+ });+ });++ it('revoke_badge fails when only partial email matches exist', async () => {+ const calls = stubGraphql({ FindMembers: { members: pageOf([{ ...MEMBER_NODE, email: '[email protected]' }]) } });+ await expect(+ call({ fn: revokeBadgeAction.run, ctx: makeContext({ props: { badgeId: 'b1', email: '[email protected]' } }) })+ ).rejects.toThrow('No member with email [email protected] was found');+ expect(businessCalls(calls).some((item) => item.operation === 'RevokeBadge')).toBe(false);+ });+});diff --git a/packages/pieces/community/bettermode/test/behaviour.test.ts b/packages/pieces/community/bettermode/test/behaviour.test.tsnew file mode 100644index 00000000000..11c056ae009--- /dev/null+++ b/packages/pieces/community/bettermode/test/behaviour.test.ts@@ -0,0 +1,783 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { bettermode } from '../src';+import { getPostAction, listPostsAction, updatePostAction, createReplyAction } from '../src/lib/actions/ai/posts';+import { getSpaceAction, removeMemberFromSpaceAction } from '../src/lib/actions/ai/spaces';+import { findMemberByEmailAction, getMemberAction, inviteMembersAction, updateMemberAction } from '../src/lib/actions/ai/members';+import { assignBadgeToMemberAction } from '../src/lib/actions/ai/community';+import { bettermodeAuth } from '../src/lib/auth';+import { assertCustomCallUrl, BettermodeApiError, bettermodeQuery, clearSessionCache, normalizeDomain } from '../src/lib/common/client';+import { badgesDropdown, memberSpacesDropdown } from '../src/lib/common/props';+import { bettermodePolling } from '../src/lib/common/polling';+import { newMemberTrigger } from '../src/lib/triggers/new-member';+import { newPostTrigger } from '../src/lib/triggers/new-post';+import { newReplyTrigger } from '../src/lib/triggers/new-reply';+import { StoreScope } from '@activepieces/pieces-framework';+import { businessCalls, call, makeAuth, makeContext, makeStore, MEMBER_TOKEN, pageOf, stubGraphql } from './helpers';++type TestStore = ReturnType<typeof makeStore>;++async function seedStoredToken({ store, token, expiresAt }: { store: TestStore; token: string; expiresAt?: number }) {+ const probe = makeStore();+ stubGraphql({ GetPost: { post: { id: 'seed' } } });+ await call({ fn: getPostAction.run, ctx: { ...makeContext({ props: { post_id: 'seed' } }), store: probe } });+ clearSessionCache();+ const [key] = probe.put.mock.calls[0];+ store.data.set(key, { accessToken: token, memberId: 'selfMember1', memberName: 'Self', expiresAt: expiresAt ?? Date.now() + 600000 });+}++function firstStored(store: TestStore): unknown {+ return [...store.data.values()][0];+}++afterEach(() => {+ clearSessionCache();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ vi.useRealTimers();+});++function validate(auth: Record<string, string>) {+ return call({ fn: bettermodeAuth.validate, ctx: { auth } });+}++describe('metadata', () => {+ const actions = Object.values(bettermode.actions());+ const triggers = Object.values(bettermode.triggers());++ it('has the expected audience split', () => {+ const count = (audience: string) => actions.filter((action) => action.audience === audience).length;+ expect(count('ai')).toBe(39);+ expect(count('human')).toBe(5);+ expect(count('both')).toBe(0);+ expect(triggers.map((trigger) => trigger.name).sort()).toEqual(['new_member', 'new_post', 'new_reply']);+ });++ it('tags every hand-written action and trigger', () => {+ for (const action of actions.filter((item) => item.name !== 'custom_api_call')) {+ expect(action.classification, action.name).toBeDefined();+ expect(action.aiMetadata?.description, action.name).toBeTruthy();+ expect(typeof action.aiMetadata?.idempotent, action.name).toBe('boolean');+ expect(action.outputSchema?.fields.length, action.name).toBeGreaterThan(0);+ }+ for (const trigger of triggers) {+ expect(trigger.classification).toBe('READ');+ expect(trigger.aiMetadata?.description).toBeTruthy();+ expect(trigger.outputSchema?.fields.length).toBeGreaterThan(0);+ }+ });++ it('marks deletes and suspensions as destructive and not idempotent', () => {+ const destructive = actions.filter((action) => action.classification === 'DESTRUCTIVE').map((action) => action.name).sort();+ expect(destructive).toEqual(['delete_member', 'delete_post', 'remove_member_from_space', 'suspend_member']);+ for (const action of actions.filter((item) => item.classification === 'DESTRUCTIVE')) {+ expect(action.aiMetadata?.idempotent).toBe(false);+ }+ });++ it('keeps legacy action names and demotes them to human', () => {+ for (const name of ['create_discussion', 'create_question', 'assign_badge', 'revoke_badge']) {+ expect(bettermode.getAction(name)?.audience).toBe('human');+ }+ });++ it('declares 0.88.2 as minimum release', () => {+ expect(bettermode.minimumSupportedRelease).toBe('0.88.2');+ });+});++describe('domain normalisation', () => {+ it.each([+ ['community.example.com', 'community.example.com'],+ ['https://Community.Example.com/', 'community.example.com'],+ ['http://community.example.com/spaces?x=1', 'community.example.com'],+ [' community.example.com:443 ', 'community.example.com'],+ ])('%s -> %s', (input, expected) => {+ expect(normalizeDomain(input)).toBe(expected);+ });++ it.each(['', 'not a host', '[email protected]', 'https://[email protected]', 'localhost'])('rejects %s', (input) => {+ expect(() => normalizeDomain(input)).toThrow();+ });+});++describe('custom API call host guard', () => {+ const region = 'https://api.bettermode.com';+ it.each(['/', '', 'graphql', 'https://api.bettermode.com', 'https://api.bettermode.com/x'])('allows %s', (url) => {+ expect(() => assertCustomCallUrl({ region, url })).not.toThrow();+ });+ it.each([+ 'https://api.bettermode.com.evil.io/',+ 'https://evil.io',+ '//evil.io/x',+ 'http://api.bettermode.com/',+ 'https://[email protected]/',+ 'https://api.bettermode.de/',+ '../x',+ ])('refuses %s', (url) => {+ expect(() => assertCustomCallUrl({ region, url })).toThrow();+ });++ it('runs inside the custom API call auth mapping before any login', async () => {+ const calls = stubGraphql({});+ const action = bettermode.getAction('custom_api_call');+ await expect(+ call({+ fn: action?.run,+ ctx: { ...makeContext({ props: { method: 'POST', url: { url: 'https://evil.io/steal' }, headers: {}, queryParams: {} } }) },+ })+ ).rejects.toThrow('Custom API calls can only go to https://api.bettermode.com');+ expect(calls).toHaveLength(0);+ });+});++describe('auth.validate', () => {+ it('accepts a domain with scheme and sends the bare host as networkDomain', async () => {+ const calls = stubGraphql({});+ const result = await validate(makeAuth({ domain: 'https://community.example.com/' }));+ expect(result).toEqual({ valid: true });+ expect(calls[0].operation).toBe('GetGuestToken');+ expect(calls[0].variables).toEqual({ domain: 'community.example.com' });+ expect(calls[0].headers['authorization']).toBeUndefined();+ expect(calls[1].operation).toBe('Login');+ expect(calls[1].headers['authorization']).toBe('Bearer guest-token');+ });++ it('reports an unknown community domain, not invalid credentials', async () => {+ stubGraphql({ GetGuestToken: { body: { errors: [{ message: 'Network not found', code: '110' }] } } });+ const result = await validate(makeAuth());+ expect(result).toMatchObject({ valid: false });+ expect(String(Reflect.get(Object(result), 'error'))).toContain('Community domain not found');+ });++ it('reports a failed login as invalid credentials', async () => {+ stubGraphql({ Login: { body: { errors: [{ message: 'Invalid email or password' }] } } });+ const result = await validate(makeAuth());+ expect(String(Reflect.get(Object(result), 'error'))).toContain('Invalid credentials');+ });++ it('reports the login lockout (code 120) as a wait, not invalid credentials', async () => {+ stubGraphql({+ Login: {+ body: { errors: [{ code: '120', message: "You've made too many wrong attempts to login into your account. Please wait 5 minutes and try again." }] },+ },+ });+ const result = await validate(makeAuth());+ const error = String(Reflect.get(Object(result), 'error'));+ expect(error).toContain('Wait 5 minutes');+ expect(error).not.toContain('Invalid credentials');+ });++ it('does not call a server error invalid credentials', async () => {+ stubGraphql({ Login: { status: 503, body: { message: 'down' } } });+ const result = await validate(makeAuth());+ const error = String(Reflect.get(Object(result), 'error'));+ expect(error).toContain('Could not reach Bettermode');+ expect(error).not.toContain('Invalid credentials');+ });++ it('maps HTTP 401 to invalid credentials', async () => {+ stubGraphql({ Login: { status: 401, body: {} } });+ const result = await validate(makeAuth());+ expect(String(Reflect.get(Object(result), 'error'))).toContain('Invalid credentials');+ });++ it('rejects an unknown region before any request', async () => {+ const calls = stubGraphql({});+ await expect(+ call({ fn: getPostAction.run, ctx: makeContext({ props: { post_id: 'p' }, auth: makeAuth({ region: 'https://api.bettermode.com.evil.io' }) }) })+ ).rejects.toThrow('Select the US or EU region');+ expect(calls).toHaveLength(0);+ });++ it('rejects an invalid email before any request', async () => {+ const calls = stubGraphql({});+ const result = await validate(makeAuth({ email: 'nope' }));+ expect(result).toEqual({ valid: false, error: 'Enter a valid email address.' });+ expect(calls).toHaveLength(0);+ });+});++describe('session and transport', () => {+ it('logs in once per run even with several requests', async () => {+ const calls = stubGraphql({+ GetSpacePostTypes: { space: { authMemberProps: { availablePostTypes: [{ id: 'pt', name: 'Discussion' }] } } },+ CreatePost: { createPost: { id: 'p1' } },+ });+ await call({+ fn: bettermode.getAction('create_discussion')?.run,+ ctx: makeContext({ props: { spaceId: 's', title: 'T', content: 'C' } }),+ });+ expect(calls.filter((item) => item.operation === 'GetGuestToken')).toHaveLength(1);+ expect(calls.filter((item) => item.operation === 'Login')).toHaveLength(1);+ });++ it('reuses the session across runs of the same connection (Bettermode locks out repeated logins)', async () => {+ const calls = stubGraphql({ GetPost: { post: { id: 'p1' } } });+ await call({ fn: getPostAction.run, ctx: makeContext({ props: { post_id: 'p1' } }) });+ await call({ fn: getPostAction.run, ctx: makeContext({ props: { post_id: 'p1' } }) });+ expect(calls.filter((item) => item.operation === 'Login')).toHaveLength(1);+ await call({ fn: getPostAction.run, ctx: makeContext({ props: { post_id: 'p1' }, auth: makeAuth({ password: 'other-secret' }) }) });+ expect(calls.filter((item) => item.operation === 'Login')).toHaveLength(2);+ });++ it('drops a stored token rejected with 401, logs in once and retries once', async () => {+ const ctx = makeContext({ props: { post_id: 'p1' } });+ await seedStoredToken({ store: ctx.store, token: 'stale-token' });+ const calls = stubGraphql({ GetPost: [{ status: 401, body: {} }, { body: { data: { post: { id: 'p1' } } } }] });+ const out = await call({ fn: getPostAction.run, ctx });+ expect(out).toMatchObject({ id: 'p1' });+ expect(calls.filter((item) => item.operation === 'Login')).toHaveLength(1);+ expect(calls.filter((item) => item.operation === 'GetPost').map((item) => item.headers['authorization'])).toEqual([+ 'Bearer stale-token',+ `Bearer ${MEMBER_TOKEN}`,+ ]);+ expect(ctx.store.delete).toHaveBeenCalledTimes(1);+ expect(firstStored(ctx.store)).toMatchObject({ accessToken: MEMBER_TOKEN });+ });++ it('does not log in a second time when a freshly issued token is rejected', async () => {+ const calls = stubGraphql({ GetPost: { status: 401, body: {} } });+ await expect(call({ fn: getPostAction.run, ctx: makeContext({ props: { post_id: 'p1' } }) })).rejects.toThrow('HTTP 401');+ expect(calls.filter((item) => item.operation === 'Login')).toHaveLength(1);+ });++ it('uses a valid stored token without logging in', async () => {+ const ctx = makeContext({ props: { post_id: 'p1' } });+ await seedStoredToken({ store: ctx.store, token: 'stored-token' });+ const calls = stubGraphql({ GetPost: { post: { id: 'p1' } } });+ await call({ fn: getPostAction.run, ctx });+ expect(calls.map((item) => item.operation)).toEqual(['GetPost']);+ expect(calls[0].headers['authorization']).toBe('Bearer stored-token');+ expect(ctx.store.put).not.toHaveBeenCalled();+ });++ it('logs in on a store miss and saves only the token, member and expiry in project scope', async () => {+ const calls = stubGraphql({ GetPost: { post: { id: 'p1' } } });+ const ctx = makeContext({ props: { post_id: 'p1' } });+ const out = await call({ fn: getPostAction.run, ctx });+ expect(calls.filter((item) => item.operation === 'Login')).toHaveLength(1);+ expect(ctx.store.put).toHaveBeenCalledTimes(1);+ const [key, value, scope] = ctx.store.put.mock.calls[0];+ expect(scope).toBe(StoreScope.PROJECT);+ expect(key).toMatch(/^bettermode_token_[0-9a-f]{64}$/);+ expect(Object.keys(Object(value)).sort()).toEqual(['accessToken', 'expiresAt', 'memberId', 'memberName']);+ expect(Reflect.get(Object(value), 'expiresAt')).toBeGreaterThan(Date.now());+ const serialized = JSON.stringify(ctx.store.put.mock.calls);+ expect(serialized).not.toContain('hunter2-secret');+ expect(serialized).not.toContain('[email protected]');+ expect(JSON.stringify(out)).not.toContain(MEMBER_TOKEN);+ });++ it('Custom API Call reuses the stored project token instead of logging in', async () => {+ const ctx = makeContext({+ props: { method: 'POST', url: { url: 'https://api.bettermode.com' }, headers: {}, queryParams: {}, body_type: 'json', body: { data: { query: 'query Ping { network { id } }' } } },+ });+ await seedStoredToken({ store: ctx.store, token: 'stored-token' });+ const calls = stubGraphql({ Ping: { network: { id: 'n1' } } });+ await call({ fn: bettermode.getAction('custom_api_call')?.run, ctx });+ expect(calls.filter((item) => item.operation === 'Login')).toHaveLength(0);+ expect(calls.at(-1)?.headers['authorization']).toBe('Bearer stored-token');+ });++ it('logs in again when the stored token has expired', async () => {+ const ctx = makeContext({ props: { post_id: 'p1' } });+ await seedStoredToken({ store: ctx.store, token: 'old-token', expiresAt: Date.now() - 1000 });+ const calls = stubGraphql({ GetPost: { post: { id: 'p1' } } });+ await call({ fn: getPostAction.run, ctx });+ expect(calls.filter((item) => item.operation === 'Login')).toHaveLength(1);+ expect(calls.find((item) => item.operation === 'GetPost')?.headers['authorization']).toBe(`Bearer ${MEMBER_TOKEN}`);+ expect(firstStored(ctx.store)).toMatchObject({ accessToken: MEMBER_TOKEN });+ });++ it('keeps a 5-minute Bettermode JWT usable (expiry from exp minus a short margin)', async () => {+ const payload = Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 300 })).toString('base64url');+ const jwt = `eyJhbGciOiJIUzI1NiJ9.${payload}.sig`;+ const calls = stubGraphql({+ Login: { body: { data: { loginNetwork: { accessToken: jwt, member: { id: 'selfMember1', name: 'Self' } } } } },+ GetPost: { post: { id: 'p1' } },+ });+ const ctx = makeContext({ props: { post_id: 'p1' } });+ await call({ fn: getPostAction.run, ctx });+ await call({ fn: getPostAction.run, ctx });+ expect(calls.filter((item) => item.operation === 'Login')).toHaveLength(1);+ const expiresAt = Number(Reflect.get(Object(firstStored(ctx.store)), 'expiresAt'));+ expect(expiresAt - Date.now()).toBeGreaterThan(240000);+ expect(expiresAt - Date.now()).toBeLessThanOrEqual(300000);+ });++ it('shares one login across separate runs through the store', async () => {+ const calls = stubGraphql({ GetPost: { post: { id: 'p1' } } });+ const store = makeStore();+ for (let run = 0; run < 3; run++) {+ clearSessionCache();+ const ctx = makeContext({ props: { post_id: 'p1' } });+ await call({ fn: getPostAction.run, ctx: { ...ctx, store } });+ }+ expect(calls.filter((item) => item.operation === 'Login')).toHaveLength(1);+ });++ it('reports the login lockout as a 5-minute wait without retrying', async () => {+ const calls = stubGraphql({+ Login: { body: { errors: [{ code: '120', message: "You've made too many wrong attempts to login into your account." }] } },+ });+ await expect(call({ fn: getPostAction.run, ctx: makeContext({ props: { post_id: 'p1' } }) })).rejects.toThrow('Wait 5 minutes');+ expect(calls.filter((item) => item.operation === 'Login')).toHaveLength(1);+ });++ it('never logs the password when the login request fails', async () => {+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);+ stubGraphql({ Login: { status: 500, body: { message: 'boom' } } });+ await expect(bettermodeQuery({ auth: makeAuth(), query: 'query X { a }' })).rejects.toThrow();+ const logged = JSON.stringify(errorSpy.mock.calls);+ expect(logged).not.toContain('hunter2-secret');+ });++ it('turns GraphQL errors into a message with code and path, keeping the body under responseBody', async () => {+ stubGraphql({ GetPost: { body: { errors: [{ message: 'Post not found', code: '404', path: ['post'] }] } } });+ const error = await call({ fn: getPostAction.run, ctx: makeContext({ props: { post_id: 'p' } }) }).catch((e: unknown) => e);+ expect(error).toBeInstanceOf(BettermodeApiError);+ expect(String(Reflect.get(Object(error), 'message'))).toBe('Bettermode error (code 404, at post): Post not found');+ expect(Reflect.has(Object(error), 'body')).toBe(false);+ expect(Reflect.get(Object(error), 'responseBody')).toBeDefined();+ });++ it('maps HTTP 403 to a permission message', async () => {+ stubGraphql({ GetPost: { status: 403, body: {} } });+ await expect(call({ fn: getPostAction.run, ctx: makeContext({ props: { post_id: 'p' } }) })).rejects.toThrow(+ 'connected member lacks permission'+ );+ });++ it('retries 429 twice then succeeds', async () => {+ vi.useFakeTimers();+ const calls = stubGraphql({+ GetPost: [{ status: 429, body: {} }, { status: 429, body: {} }, { body: { data: { post: { id: 'p' } } } }],+ });+ const pending = call({ fn: getPostAction.run, ctx: makeContext({ props: { post_id: 'p' } }) });+ await vi.runAllTimersAsync();+ await expect(pending).resolves.toMatchObject({ id: 'p' });+ expect(businessCalls(calls)).toHaveLength(3);+ });++ it('gives up after two 429 retries', async () => {+ vi.useFakeTimers();+ stubGraphql({ GetPost: [{ status: 429, body: {} }, { status: 429, body: {} }, { status: 429, body: {} }] });+ const pending = call({ fn: getPostAction.run, ctx: makeContext({ props: { post_id: 'p' } }) }).catch((e: unknown) => e);+ await vi.runAllTimersAsync();+ expect(String(Reflect.get(Object(await pending), 'message'))).toContain('rate limit');+ });++ it('fails when Bettermode reports a failed action status', async () => {+ stubGraphql({ AssignBadge: { assignBadge: { status: 'failed' } } });+ await expect(+ call({ fn: assignBadgeToMemberAction.run, ctx: makeContext({ props: { badge_id: 'b', member_id: 'm' } }) })+ ).rejects.toThrow('Bettermode did not complete assignBadge (status: failed)');+ });++ it('fails remove_member_from_space when any status failed', async () => {+ stubGraphql({ RemoveSpaceMembers: { removeSpaceMembers: [{ status: 'succeeded' }, { status: 'failed' }] } });+ await expect(+ call({ fn: removeMemberFromSpaceAction.run, ctx: makeContext({ props: { space_id: 's', member_ids: ['a', 'b'] } }) })+ ).rejects.toThrow('did not remove every member');+ });+});++describe('input validation', () => {+ it.each([+ [getSpaceAction, {}, 'Give exactly one of Space ID or Space Slug.'],+ [getSpaceAction, { space_id: 'a', slug: 'b' }, 'Give exactly one of Space ID or Space Slug.'],+ [getMemberAction, { member_id: 'a', username: 'b' }, 'Give exactly one of Member ID, Username or External ID.'],+ [updatePostAction, { post_id: 'p' }, 'Give at least one field to update.'],+ [updatePostAction, { post_id: 'p', tag_names: ['a'], clear_tags: true }, 'Give Tags or Clear Tags, not both.'],+ [updateMemberAction, { member_id: 'm' }, 'Give at least one field to update.'],+ [updateMemberAction, { tagline: 'x', clear_tagline: true }, 'Give Tagline or Clear Tagline, not both.'],+ [listPostsAction, { limit: 0 }, 'Limit must be a whole number between 1 and 100.'],+ [listPostsAction, { limit: 101 }, 'Limit must be a whole number between 1 and 100.'],+ [listPostsAction, { order_by: 'title; drop' }, 'Order By must be one of'],+ [findMemberByEmailAction, { email: 'not-an-email' }, 'Email must be a valid email address.'],+ [inviteMembersAction, { emails: [] }, 'Emails must contain between 1 and 20 addresses.'],+ [inviteMembersAction, { emails: ['[email protected]', 'bad'] }, 'Each email must be a valid email address.'],+ [removeMemberFromSpaceAction, { space_id: 's', member_ids: [] }, 'Member IDs must contain at least one member ID.'],+ ])('%#', async (action, props, message) => {+ const calls = stubGraphql({});+ await expect(call({ fn: action.run, ctx: makeContext({ props }) })).rejects.toThrow(message);+ expect(businessCalls(calls)).toHaveLength(0);+ });++ it('update_post omits fields that were not given', async () => {+ const calls = stubGraphql({ UpdatePost: { updatePost: { id: 'p' } } });+ await call({ fn: updatePostAction.run, ctx: makeContext({ props: { post_id: 'p', content: '<b>x</b>', tag_names: ['a'] } }) });+ expect(businessCalls(calls)[0].variables).toEqual({+ id: 'p',+ input: { mappingFields: [{ key: 'content', type: 'html', value: '"<b>x</b>"' }], tagNames: ['a'] },+ });+ });++ it('find_member_by_email returns found false when only partial matches exist', async () => {+ stubGraphql({ FindMembers: { members: pageOf([{ id: 'x', email: '[email protected]' }]) } });+ await expect(+ call({ fn: findMemberByEmailAction.run, ctx: makeContext({ props: { email: '[email protected]' } }) })+ ).resolves.toEqual({ found: false, member: null });+ });++ it('find_member_by_email pages until it finds the exact email', async () => {+ const calls = stubGraphql({+ FindMembers: [+ { body: { data: { members: pageOf({ nodes: [{ id: 'x', email: '[email protected]' }], hasNextPage: true, endCursor: 'c2' }) } } },+ { body: { data: { members: pageOf([{ id: 'm1', email: '[email protected]' }]) } } },+ ],+ });+ const result = await call({ fn: findMemberByEmailAction.run, ctx: makeContext({ props: { email: '[email protected]' } }) });+ expect(result).toMatchObject({ found: true, member: { id: 'm1' } });+ expect(businessCalls(calls)[1].variables).toMatchObject({ after: 'c2' });+ });++ it('create_reply defaults to the first reply type the parent allows', async () => {+ const calls = stubGraphql({+ GetReplyTypes: { post: { id: 'p', postType: { validReplyTypes: [{ id: 'comment', name: 'Comment' }] } } },+ CreateReply: { createReply: { id: 'r' } },+ });+ await call({ fn: createReplyAction.run, ctx: makeContext({ props: { post_id: 'p', content: 'hi' } }) });+ expect(businessCalls(calls)[1].variables).toMatchObject({ input: { postTypeId: 'comment' } });+ });++ it('create_reply explains when the parent accepts no replies', async () => {+ stubGraphql({ GetReplyTypes: { post: { id: 'p', postType: { validReplyTypes: [] } } } });+ await expect(+ call({ fn: createReplyAction.run, ctx: makeContext({ props: { post_id: 'p', content: 'hi' } }) })+ ).rejects.toThrow('does not accept replies');+ });+});++describe('dropdowns', () => {+ function options({ prop, auth }: { prop: unknown; auth: unknown }) {+ return call({ fn: Reflect.get(Object(prop), 'options'), ctx: { auth } });+ }++ it('spaces dropdown pages through every space the member joined', async () => {+ const calls = stubGraphql({+ ListSpaces: [+ { body: { data: { spaces: pageOf({ nodes: [{ id: 's1', name: 'One' }], hasNextPage: true, endCursor: 'c2' }) } } },+ { body: { data: { spaces: pageOf([{ id: 's2', name: 'Two' }]) } } },+ ],+ });+ const result = await options({ prop: memberSpacesDropdown, auth: { props: makeAuth() } });+ expect(result).toEqual({+ disabled: false,+ options: [+ { label: 'One', value: 's1' },+ { label: 'Two', value: 's2' },+ ],+ });+ expect(businessCalls(calls)[0].variables).toMatchObject({ memberId: 'selfMember1', limit: 100 });+ expect(businessCalls(calls)[1].variables).toMatchObject({ after: 'c2' });+ });++ it('dropdowns show a disabled state with a reason on error', async () => {+ stubGraphql({ ListBadges: { status: 403, body: {} } });+ const result = await options({ prop: badgesDropdown, auth: { props: makeAuth() } });+ expect(result).toMatchObject({ disabled: true, options: [] });+ expect(String(Reflect.get(Object(result), 'placeholder'))).toContain('Could not load badges');+ });++ it('dropdowns ask for a connection first', async () => {+ await expect(options({ prop: memberSpacesDropdown, auth: undefined })).resolves.toMatchObject({ disabled: true });+ });+});++function postNode({ id, createdAt, publishedAt, status }: { id: string; createdAt: string; publishedAt?: string | null; status?: string }) {+ return { id, title: id, createdAt, publishedAt: publishedAt === undefined ? createdAt : publishedAt, status: status ?? 'PUBLISHED' };+}++function triggerContext({ store = makeStore(), props = {} }: { store?: ReturnType<typeof makeStore>; props?: Record<string, unknown> }) {+ return { auth: { props: makeAuth() }, propsValue: props, store };+}++describe('polling triggers', () => {+ it('new_post stores the newest post as checkpoint on enable', async () => {+ const calls = stubGraphql({+ PollPosts: { posts: pageOf([postNode({ id: 'b', createdAt: '2026-10-13T10:00:00.000Z' }), postNode({ id: 'a', createdAt: '2026-10-13T09:00:00.000Z' })]) },+ });+ const store = makeStore();+ await call({ fn: newPostTrigger.onEnable, ctx: triggerContext({ store, props: { space_ids: ['s1'] } }) });+ expect(store.data.get(bettermodePolling.CHECKPOINT_KEY)).toEqual({+ lastCreatedAt: '2026-10-13T10:00:00.000Z',+ idsAtLast: ['b'],+ });+ expect(businessCalls(calls)[0].variables).toMatchObject({ spaceIds: ['s1'], orderBy: 'publishedAt', reverse: true });+ });++ it('new_post emits only new posts, oldest first, including same-time posts not seen yet', async () => {+ stubGraphql({+ PollPosts: {+ posts: pageOf([+ postNode({ id: 'd', createdAt: '2026-10-13T12:00:00.000Z' }),+ postNode({ id: 'c', createdAt: '2026-10-13T11:00:00.000Z' }),+ postNode({ id: 'b2', createdAt: '2026-10-13T10:00:00.000Z' }),+ postNode({ id: 'b', createdAt: '2026-10-13T10:00:00.000Z' }),+ postNode({ id: 'a', createdAt: '2026-10-13T09:00:00.000Z' }),+ ]),+ },+ });+ const store = makeStore();+ store.data.set(bettermodePolling.CHECKPOINT_KEY, { lastCreatedAt: '2026-10-13T10:00:00.000Z', idsAtLast: ['b'] });+ const items = await call({ fn: newPostTrigger.run, ctx: triggerContext({ store }) });+ expect(Array.isArray(items) ? items.map((item) => item.id) : items).toEqual(['b2', 'c', 'd']);+ expect(store.data.get(bettermodePolling.CHECKPOINT_KEY)).toEqual({ lastCreatedAt: '2026-10-13T12:00:00.000Z', idsAtLast: ['d'] });+ });++ it('new_post pages back until it reaches the checkpoint', async () => {+ const calls = stubGraphql({+ PollPosts: [+ { body: { data: { posts: pageOf({ nodes: [postNode({ id: 'c', createdAt: '2026-10-13T12:00:00.000Z' })], hasNextPage: true, endCursor: 'p2' }) } } },+ { body: { data: { posts: pageOf({ nodes: [postNode({ id: 'b', createdAt: '2026-10-13T11:00:00.000Z' }), postNode({ id: 'a', createdAt: '2026-10-13T09:00:00.000Z' })], hasNextPage: true, endCursor: 'p3' }) } } },+ ],+ });+ const store = makeStore();+ store.data.set(bettermodePolling.CHECKPOINT_KEY, { lastCreatedAt: '2026-10-13T10:00:00.000Z', idsAtLast: [] });+ const items = await call({ fn: newPostTrigger.run, ctx: triggerContext({ store }) });+ expect(Array.isArray(items) ? items.map((item) => item.id) : items).toEqual(['b', 'c']);+ expect(businessCalls(calls)).toHaveLength(2);+ });++ it('new_post returns nothing and keeps the checkpoint when nothing is new', async () => {+ stubGraphql({ PollPosts: { posts: pageOf([postNode({ id: 'a', createdAt: '2026-10-13T09:00:00.000Z' })]) } });+ const store = makeStore();+ store.data.set(bettermodePolling.CHECKPOINT_KEY, { lastCreatedAt: '2026-10-13T09:00:00.000Z', idsAtLast: ['a'] });+ await expect(call({ fn: newPostTrigger.run, ctx: triggerContext({ store }) })).resolves.toEqual([]);+ expect(store.put.mock.calls.filter(([key]) => key === bettermodePolling.CHECKPOINT_KEY)).toHaveLength(0);+ });++ it('fails loudly if Bettermode returns oldest first', async () => {+ stubGraphql({+ PollPosts: { posts: pageOf([postNode({ id: 'a', createdAt: '2026-10-13T09:00:00.000Z' }), postNode({ id: 'b', createdAt: '2026-10-13T11:00:00.000Z' })]) },+ });+ const store = makeStore();+ store.data.set(bettermodePolling.CHECKPOINT_KEY, { lastCreatedAt: '2026-10-13T10:00:00.000Z', idsAtLast: [] });+ await expect(call({ fn: newPostTrigger.run, ctx: triggerContext({ store }) })).rejects.toThrow('unexpected order');+ });++ it('caps one poll at 100 items and advances only to what it emitted', async () => {+ const nodes = Array.from({ length: 120 }, (_, index) =>+ postNode({ id: `p${String(index).padStart(3, '0')}`, createdAt: new Date(Date.UTC(2026, 9, 13, 12, 0, 0) - index * 1000).toISOString() })+ );+ stubGraphql({ PollPosts: { posts: pageOf(nodes) } });+ const store = makeStore();+ store.data.set(bettermodePolling.CHECKPOINT_KEY, { lastCreatedAt: '2026-10-01T00:00:00.000Z', idsAtLast: [] });+ const items = await call({ fn: newPostTrigger.run, ctx: triggerContext({ store }) });+ expect(Array.isArray(items) ? items.length : 0).toBe(100);+ expect(store.data.get(bettermodePolling.CHECKPOINT_KEY)).toEqual({+ lastCreatedAt: nodes[20].createdAt,+ idsAtLast: ['p020'],+ });+ });++ it('new_post fires for a draft created before the checkpoint and published after it', async () => {+ stubGraphql({+ PollPosts: {+ posts: pageOf([+ postNode({ id: 'old-draft', createdAt: '2026-10-13T08:00:00.000Z', publishedAt: '2026-10-13T11:00:00.000Z' }),+ postNode({ id: 'still-draft', createdAt: '2026-10-13T10:30:00.000Z', publishedAt: null, status: 'DRAFT' }),+ postNode({ id: 'a', createdAt: '2026-10-13T09:00:00.000Z' }),+ ]),+ },+ });+ const store = makeStore();+ store.data.set(bettermodePolling.CHECKPOINT_KEY, { lastCreatedAt: '2026-10-13T10:00:00.000Z', idsAtLast: [] });+ const items = await call({ fn: newPostTrigger.run, ctx: triggerContext({ store }) });+ expect(Array.isArray(items) ? items.map((item) => item.id) : items).toEqual(['old-draft']);+ expect(store.data.get(bettermodePolling.CHECKPOINT_KEY)).toEqual({ lastCreatedAt: '2026-10-13T11:00:00.000Z', idsAtLast: ['old-draft'] });+ });++ it('drains a 650-post backlog oldest first across polls and never loops', async () => {+ const feed = fakePostFeed({ count: 0 });+ const store = makeStore();+ const calls = stubGraphql({ PollPosts: feed.handler });+ feed.add(1);+ await call({ fn: newPostTrigger.onEnable, ctx: triggerContext({ store }) });+ feed.add(650);+ const id = (index: number) => `n${String(index).padStart(5, '0')}`;+ const first = await call({ fn: newPostTrigger.run, ctx: triggerContext({ store }) });+ expect(first).toEqual([]);+ expect(store.data.get(bettermodePolling.CHECKPOINT_KEY)).toMatchObject({ resumeCursors: [id(152)] });+ const second = await call({ fn: newPostTrigger.run, ctx: triggerContext({ store }) });+ expect(businessCalls(calls)[12].variables).toMatchObject({ after: id(152) });+ expect(Array.isArray(second) ? [second.length, second[0].id, second[99].id] : second).toEqual([100, id(2), id(101)]);+ expect(store.data.get(bettermodePolling.CHECKPOINT_KEY)).toEqual({ lastCreatedAt: '2026-10-13T12:01:41.000Z', idsAtLast: [id(101)], resumeCursors: [id(152)] });+ const rest = await pollUntilQuiet({ store, polls: 12 });+ expect(rest).toEqual(Array.from({ length: 550 }, (_, index) => id(102 + index)));+ expect(await pollUntilQuiet({ store, polls: 4 })).toEqual([]);+ });++ it('new_post on an empty community starts from now', async () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-10-13T00:00:00.000Z'));+ stubGraphql({ PollPosts: { posts: pageOf([]) } });+ const store = makeStore();+ await call({ fn: newPostTrigger.onEnable, ctx: triggerContext({ store }) });+ expect(store.data.get(bettermodePolling.CHECKPOINT_KEY)).toEqual({ lastCreatedAt: '2026-10-13T00:00:00.000Z', idsAtLast: [] });+ });++ it.each([+ ['new_post', newPostTrigger],+ ['new_member', newMemberTrigger],+ ['new_reply', newReplyTrigger],+ ])('%s keeps its checkpoint across a republish', async (_name, trigger) => {+ const calls = stubGraphql({});+ const store = makeStore();+ const saved = { lastCreatedAt: '2026-10-13T09:00:00.000Z', idsAtLast: ['x1'] };+ store.data.set(bettermodePolling.CHECKPOINT_KEY, saved);+ await call({ fn: trigger.onDisable, ctx: { ...triggerContext({ store }), isRepublish: true } });+ await call({ fn: trigger.onEnable, ctx: { ...triggerContext({ store }), isRepublish: true } });+ expect(store.data.get(bettermodePolling.CHECKPOINT_KEY)).toEqual(saved);+ expect(businessCalls(calls)).toEqual([]);+ });++ it('re-baselines on enable when a republish finds no checkpoint', async () => {+ stubGraphql({ PollMembers: { members: pageOf([{ id: 'm1', createdAt: '2026-10-13T09:00:00.000Z' }]) } });+ const store = makeStore();+ await call({ fn: newMemberTrigger.onEnable, ctx: { ...triggerContext({ store }), isRepublish: true } });+ expect(store.data.get(bettermodePolling.CHECKPOINT_KEY)).toEqual({ lastCreatedAt: '2026-10-13T09:00:00.000Z', idsAtLast: ['m1'] });+ });++ it('new_member polls members by createdAt and emits new ones', async () => {+ const calls = stubGraphql({+ PollMembers: { members: pageOf([{ id: 'm2', name: 'New', createdAt: '2026-10-13T11:00:00.000Z' }, { id: 'm1', createdAt: '2026-10-13T09:00:00.000Z' }]) },+ });+ const store = makeStore();+ store.data.set(bettermodePolling.CHECKPOINT_KEY, { lastCreatedAt: '2026-10-13T09:00:00.000Z', idsAtLast: ['m1'] });+ const items = await call({ fn: newMemberTrigger.run, ctx: triggerContext({ store }) });+ expect(items).toMatchObject([{ id: 'm2', name: 'New' }]);+ expect(businessCalls(calls)[0].variables).toMatchObject({ orderBy: 'createdAt', reverse: true });+ });++ it('new_reply reads the replies of the most recently active posts in one batched query', async () => {+ const calls = stubGraphql({+ PollActivePosts: { posts: { nodes: [{ id: 'p1', repliesCount: 2 }, { id: 'p2', repliesCount: 0 }, { id: 'p3', repliesCount: 1 }] } },+ PollReplies: {+ r0: { nodes: [{ id: 'r2', repliedToId: 'p1', createdAt: '2026-10-13T11:30:00.000Z' }, { id: 'r1', repliedToId: 'p1', createdAt: '2026-10-13T09:00:00.000Z' }] },+ r1: { nodes: [{ id: 'r3', repliedToId: 'p3', createdAt: '2026-10-13T11:00:00.000Z' }] },+ },+ });+ const store = makeStore();+ store.data.set(bettermodePolling.CHECKPOINT_KEY, { lastCreatedAt: '2026-10-13T10:00:00.000Z', idsAtLast: [] });+ const items = await call({ fn: newReplyTrigger.run, ctx: triggerContext({ store }) });+ expect(items).toMatchObject([+ { id: 'r3', replied_to_id: 'p3' },+ { id: 'r2', replied_to_id: 'p1' },+ ]);+ const sent = businessCalls(calls);+ expect(sent[0].variables).toMatchObject({ orderBy: 'lastActivityAt', reverse: true });+ expect(sent[1].variables).toEqual({ p0: 'p1', p1: 'p3' });+ expect(sent[1].query).not.toContain('p1"');+ expect(store.data.get(bettermodePolling.CHECKPOINT_KEY)).toEqual({ lastCreatedAt: '2026-10-13T11:30:00.000Z', idsAtLast: ['r2'] });+ });++ it('new_reply skips the replies query when no active post has replies', async () => {+ const calls = stubGraphql({ PollActivePosts: { posts: { nodes: [{ id: 'p1', repliesCount: 0 }] } } });+ const store = makeStore();+ store.data.set(bettermodePolling.CHECKPOINT_KEY, { lastCreatedAt: '2026-10-13T10:00:00.000Z', idsAtLast: [] });+ const items = await call({ fn: newReplyTrigger.run, ctx: triggerContext({ store }) });+ expect(items).toEqual([]);+ expect(calls.some((item) => item.operation === 'PollReplies')).toBe(false);+ });++ it('run without a checkpoint asks to re-enable', async () => {+ stubGraphql({});+ await expect(call({ fn: newPostTrigger.run, ctx: triggerContext({}) })).rejects.toThrow('re-enable');+ });+});++function fakePostFeed({ count, startIndex = 0 }: { count: number; startIndex?: number }) {+ const base = Date.UTC(2026, 9, 13, 12, 0, 0);+ const feed: ReturnType<typeof postNode>[] = [];+ let next = startIndex;+ const add = (amount: number) => {+ const added = Array.from({ length: amount }, () => {+ next += 1;+ return postNode({ id: `n${String(next).padStart(5, '0')}`, createdAt: new Date(base + next * 1000).toISOString() });+ });+ feed.unshift(...added.reverse());+ };+ const addSameTime = (amount: number) => {+ const createdAt = new Date(base + (next + 1) * 1000).toISOString();+ const added = Array.from({ length: amount }, () => {+ next += 1;+ return postNode({ id: `n${String(next).padStart(5, '0')}`, createdAt });+ });+ feed.unshift(...added);+ };+ add(count);+ const handler = (sent: { variables: Record<string, unknown> }) => {+ const after = sent.variables['after'];+ const limit = Number(sent.variables['limit']);+ const start = typeof after === 'string' ? feed.findIndex((item) => item.id === after) + 1 : 0;+ const nodes = feed.slice(start, start + limit);+ return {+ body: {+ data: { posts: pageOf({ nodes, hasNextPage: start + limit < feed.length, endCursor: nodes.length > 0 ? nodes[nodes.length - 1].id : null }) },+ },+ };+ };+ return { feed, add, addSameTime, handler };+}++async function pollUntilQuiet({ store, polls }: { store: ReturnType<typeof makeStore>; polls: number }) {+ const emitted: string[] = [];+ for (let index = 0; index < polls; index++) {+ const items = await call({ fn: newPostTrigger.run, ctx: triggerContext({ store }) });+ if (Array.isArray(items)) {+ emitted.push(...items.map((item) => String(item.id)));+ }+ }+ return emitted;+}++describe('polling bursts larger than the page budget', () => {+ it.each([650, 1000, 1234, 2600])('fires each of %i new posts exactly once and then stays quiet', async (burst) => {+ const feed = fakePostFeed({ count: 0 });+ const store = makeStore();+ stubGraphql({ PollPosts: feed.handler });+ feed.add(1);+ await call({ fn: newPostTrigger.onEnable, ctx: triggerContext({ store }) });+ feed.add(burst);+ const emitted = await pollUntilQuiet({ store, polls: Math.ceil(burst / 100) * 3 + 10 });+ const expected = feed.feed.slice(0, burst).map((item) => item.id).reverse();+ expect(new Set(emitted).size).toBe(emitted.length);+ expect([...emitted].sort()).toEqual([...expected].sort());+ expect(await pollUntilQuiet({ store, polls: 3 })).toEqual([]);+ });++ it.each([120, 250, 900, 2500])('fires each of %i posts sharing one timestamp exactly once when Bettermode lists them in ID order', async (burst) => {+ const feed = fakePostFeed({ count: 0 });+ const store = makeStore();+ stubGraphql({ PollPosts: feed.handler });+ feed.add(1);+ await call({ fn: newPostTrigger.onEnable, ctx: triggerContext({ store }) });+ feed.addSameTime(burst);+ const emitted = await pollUntilQuiet({ store, polls: Math.ceil(burst / 100) * 3 + 10 });+ const expected = feed.feed.slice(0, burst).map((item) => item.id);+ expect(new Set(emitted).size).toBe(emitted.length);+ expect([...emitted].sort()).toEqual([...expected].sort());+ expect(await pollUntilQuiet({ store, polls: 3 })).toEqual([]);+ });++ it('keeps up when new posts arrive while a large backlog drains', async () => {+ const feed = fakePostFeed({ count: 0 });+ const store = makeStore();+ stubGraphql({ PollPosts: feed.handler });+ feed.add(1);+ await call({ fn: newPostTrigger.onEnable, ctx: triggerContext({ store }) });+ feed.add(1200);+ const emitted: string[] = [];+ for (let round = 0; round < 40; round++) {+ emitted.push(...(await pollUntilQuiet({ store, polls: 1 })));+ if (round < 20) {+ feed.add(30);+ }+ }+ const expected = feed.feed.slice(0, feed.feed.length - 1).map((item) => item.id);+ expect(new Set(emitted).size).toBe(emitted.length);+ expect([...emitted].sort()).toEqual([...expected].sort());+ });+});diff --git a/packages/pieces/community/bettermode/test/helpers.ts b/packages/pieces/community/bettermode/test/helpers.tsnew file mode 100644index 00000000000..8478b29b88e--- /dev/null+++ b/packages/pieces/community/bettermode/test/helpers.ts@@ -0,0 +1,146 @@+import { vi } from 'vitest';++export type GraphqlCall = {+ url: string;+ headers: Record<string, string>;+ operation: string;+ query: string;+ variables: Record<string, unknown>;+ redirect: string | undefined;+};++export type FakeReply = { status?: number; body: unknown };++export type Handler = (call: GraphqlCall) => FakeReply | undefined;++export function operationName(query: string): string {+ const match = /^\s*(?:query|mutation)\s+(\w+)/.exec(query);+ return match ? match[1] : 'anonymous';+}++export function stubGraphql(handlers: Record<string, Handler | FakeReply | FakeReply[] | unknown>) {+ const calls: GraphqlCall[] = [];+ const queues = new Map<string, FakeReply[]>();+ const fetchMock = vi.fn(async (input: string | URL, init?: RequestInit) => {+ const headers: Record<string, string> = {};+ new Headers(init?.headers).forEach((value, key) => {+ headers[key] = value;+ });+ const parsed = JSON.parse(String(init?.body ?? '{}'));+ const call: GraphqlCall = {+ url: String(input),+ headers,+ operation: operationName(parsed.query),+ query: parsed.query,+ variables: parsed.variables,+ redirect: init?.redirect,+ };+ calls.push(call);+ const reply = resolve({ call, handlers, queues });+ return new Response(JSON.stringify(reply.body), {+ status: reply.status ?? 200,+ headers: { 'content-type': 'application/json' },+ });+ });+ vi.stubGlobal('fetch', fetchMock);+ return calls;+}++function resolve({+ call,+ handlers,+ queues,+}: {+ call: GraphqlCall;+ handlers: Record<string, unknown>;+ queues: Map<string, FakeReply[]>;+}): FakeReply {+ if (call.operation === 'GetGuestToken' && !(call.operation in handlers)) {+ return { body: { data: { tokens: { accessToken: GUEST_TOKEN } } } };+ }+ if (call.operation === 'Login' && !(call.operation in handlers)) {+ return { body: { data: { loginNetwork: { accessToken: MEMBER_TOKEN, member: { id: SELF_ID, name: 'Self' } } } } };+ }+ const handler = handlers[call.operation];+ if (handler === undefined) {+ throw new Error(`Unexpected operation ${call.operation}`);+ }+ if (typeof handler === 'function') {+ const reply = handler(call);+ if (reply === undefined) {+ throw new Error(`Handler for ${call.operation} returned nothing`);+ }+ return reply;+ }+ if (Array.isArray(handler)) {+ const queue = queues.get(call.operation) ?? [...handler];+ queues.set(call.operation, queue);+ const next = queue.shift();+ if (next === undefined) {+ throw new Error(`No more replies for ${call.operation}`);+ }+ return next;+ }+ if (isReply(handler)) {+ return handler;+ }+ return { body: { data: handler } };+}++function isReply(value: unknown): value is FakeReply {+ return typeof value === 'object' && value !== null && 'body' in value;+}++export function makeAuth(overrides: Record<string, string> = {}) {+ return {+ region: 'https://api.bettermode.com',+ domain: 'community.example.com',+ email: '[email protected]',+ password: 'hunter2-secret',+ ...overrides,+ };+}++export function makeStore() {+ const data = new Map<string, unknown>();+ return {+ data,+ get: vi.fn(async (key: string) => (data.has(key) ? data.get(key) : null)),+ put: vi.fn(async (key: string, value: unknown) => {+ data.set(key, value);+ return value;+ }),+ delete: vi.fn(async (key: string) => {+ data.delete(key);+ }),+ };+}++export function makeContext({ props = {}, auth = makeAuth() }: { props?: Record<string, unknown>; auth?: Record<string, string> }) {+ const connection = { type: 'CUSTOM_AUTH', props: auth };+ return {+ auth: connection,+ propsValue: { auth: connection, ...props },+ store: makeStore(),+ };+}++export function call({ fn, ctx }: { fn: unknown; ctx: unknown }): Promise<unknown> {+ if (typeof fn !== 'function') {+ throw new Error('not callable');+ }+ return fn(ctx);+}++export function businessCalls(calls: GraphqlCall[]): GraphqlCall[] {+ return calls.filter((item) => item.operation !== 'GetGuestToken' && item.operation !== 'Login');+}++export function pageOf(input: unknown[] | { nodes: unknown[]; hasNextPage?: boolean; endCursor?: string | null }) {+ const { nodes, hasNextPage = false, endCursor = null } = Array.isArray(input) ? { nodes: input } : input;+ return { nodes, pageInfo: { hasNextPage, endCursor }, totalCount: nodes.length };+}++export const GUEST_TOKEN = 'guest-token';+export const MEMBER_TOKEN = 'member-token';+export const SELF_ID = 'selfMember1';diff --git a/packages/pieces/community/bettermode/vitest.config.ts b/packages/pieces/community/bettermode/vitest.config.tsnew file mode 100644index 00000000000..ba8ade4a178--- /dev/null+++ b/packages/pieces/community/bettermode/vitest.config.ts@@ -0,0 +1,17 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ test: {+ globals: true,+ environment: 'node',+ },+ 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'),+ },+ },+})