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(emailit): let AI agents send, track and manage emails, audiences and suppressions (#16429)
Odai Ahmade66572409394
diff --git a/bun.lock b/bun.lockindex 4a2e5bf8308..0c62e2d1108 100644--- a/bun.lock+++ b/bun.lock@@ -2955,15 +2955,17 @@},"packages/pieces/community/emailit": {"name": "@activepieces/piece-emailit",- "version": "0.1.3",+ "version": "0.2.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*","@activepieces/pieces-common": "workspace:*","@activepieces/pieces-framework": "workspace:*",+ "undici": "7.29.1",},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/emailoctopus": {diff --git a/packages/pieces/community/emailit/package.json b/packages/pieces/community/emailit/package.jsonindex 92f79db4725..31bf34c2cc0 100644--- a/packages/pieces/community/emailit/package.json+++ b/packages/pieces/community/emailit/package.json@@ -1,20 +1,23 @@{"name": "@activepieces/piece-emailit",- "version": "0.1.3",+ "version": "0.2.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","dependencies": {"@activepieces/pieces-common": "workspace:*","@activepieces/pieces-framework": "workspace:*","@activepieces/core-piece-types": "workspace:*",- "@activepieces/core-utils": "workspace:*"+ "@activepieces/core-utils": "workspace:*",+ "undici": "7.29.1"},"devDependencies": {- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"},"scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"}}diff --git a/packages/pieces/community/emailit/src/i18n/translation.json b/packages/pieces/community/emailit/src/i18n/translation.jsonindex c0bc91d3db8..558e689951c 100644--- a/packages/pieces/community/emailit/src/i18n/translation.json+++ b/packages/pieces/community/emailit/src/i18n/translation.json@@ -1,9 +1,61 @@{"Send transactional emails with Emailit": "Send transactional emails with Emailit",- "Get your API key from your [Emailit Workspace Settings](https://app.emailit.com/settings/api-keys).": "Get your API key from your [Emailit Workspace Settings](https://app.emailit.com/settings/api-keys).",+ "Get your API key from your [Emailit Workspace Settings](https://app.emailit.com/settings/api-keys). A **Full Access** key works with every action. A **Sending Only** key can send, reschedule, cancel, retry and forward emails, but not read emails or manage domains, audiences, contacts or suppressions.": "Get your API key from your [Emailit Workspace Settings](https://app.emailit.com/settings/api-keys). A **Full Access** key works with every action. A **Sending Only** key can send, reschedule, cancel, retry and forward emails, but not read emails or manage domains, audiences, contacts or suppressions.","Send Email": "Send Email",+ "Send Email (AI)": "Send Email (AI)",+ "Get Email": "Get Email",+ "Find Emails": "Find Emails",+ "Reschedule Email": "Reschedule Email",+ "Cancel Scheduled Email": "Cancel Scheduled Email",+ "Retry Email": "Retry Email",+ "Forward Email": "Forward Email",+ "List Sending Domains": "List Sending Domains",+ "Get Sending Domain": "Get Sending Domain",+ "Get Sending Domain (by ID)": "Get Sending Domain (by ID)",+ "Check Domain Verification": "Check Domain Verification",+ "Check Domain Verification (by ID)": "Check Domain Verification (by ID)",+ "List Audiences": "List Audiences",+ "Add Subscriber to Audience": "Add Subscriber to Audience",+ "Add Subscriber to Audience (by ID)": "Add Subscriber to Audience (by ID)",+ "Update Subscriber": "Update Subscriber",+ "Update Subscriber (by ID)": "Update Subscriber (by ID)",+ "Remove Subscriber": "Remove Subscriber",+ "Remove Subscriber (by ID)": "Remove Subscriber (by ID)",+ "Find Contact": "Find Contact",+ "Create or Update Contact": "Create or Update Contact",+ "Create or Update Contact (by Audience ID)": "Create or Update Contact (by Audience ID)",+ "Suppress Email Address": "Suppress Email Address",+ "Remove Suppression": "Remove Suppression",+ "Verify Email Address": "Verify Email Address",+ "List Templates": "List Templates","Custom API Call": "Custom API Call","Send an email to one or more recipients via Emailit.": "Send an email to one or more recipients via Emailit.",+ "Send an email through Emailit and return the created email.": "Send an email through Emailit and return the created email.",+ "Get one sent or received email with its status, headers, body and attachment list.": "Get one sent or received email with its status, headers, body and attachment list.",+ "Search sent or received emails, newest first (last 14 days unless you set dates).": "Search sent or received emails, newest first (last 14 days unless you set dates).",+ "Change the send time of a scheduled email.": "Change the send time of a scheduled email.",+ "Cancel an email that is scheduled, queued or waiting to retry.": "Cancel an email that is scheduled, queued or waiting to retry.",+ "Send a bounced, failed, suppressed or held email again as a new email.": "Send a bounced, failed, suppressed or held email again as a new email.",+ "Send a copy of a sent email to new recipients.": "Send a copy of a sent email to new recipients.",+ "List the sending domains of the workspace with their verification status.": "List the sending domains of the workspace with their verification status.",+ "Get a sending domain with its verification status and the DNS records to publish.": "Get a sending domain with its verification status and the DNS records to publish.",+ "Get a sending domain by ID or name.": "Get a sending domain by ID or name.",+ "Re-check a sending domain's DNS records now and update its verification status.": "Re-check a sending domain's DNS records now and update its verification status.",+ "Re-check a sending domain given by ID or name.": "Re-check a sending domain given by ID or name.",+ "List the audiences (subscriber lists) of the workspace.": "List the audiences (subscriber lists) of the workspace.",+ "Add an email address to an audience, creating the contact if needed.": "Add an email address to an audience, creating the contact if needed.",+ "Add an email address to an audience given by ID or name.": "Add an email address to an audience given by ID or name.",+ "Subscribe or unsubscribe someone from an audience, or change their name.": "Subscribe or unsubscribe someone from an audience, or change their name.",+ "Update a subscriber of an audience given by ID or name.": "Update a subscriber of an audience given by ID or name.",+ "Delete someone's membership in an audience. The contact is kept.": "Delete someone's membership in an audience. The contact is kept.",+ "Remove a subscriber from an audience given by ID or name.": "Remove a subscriber from an audience given by ID or name.",+ "Look up a contact by email address or contact ID.": "Look up a contact by email address or contact ID.",+ "Create a contact, or update the existing contact with the same email.": "Create a contact, or update the existing contact with the same email.",+ "Create or update a contact, adding it to audiences given by ID.": "Create or update a contact, adding it to audiences given by ID.",+ "Stop Emailit from sending to an address, permanently or until a date.": "Stop Emailit from sending to an address, permanently or until a date.",+ "Remove a suppression so Emailit can send to the address again.": "Remove a suppression so Emailit can send to the address again.",+ "Check whether an address is valid and safe to send to. Costs 5 credits per check.": "Check whether an address is valid and safe to send to. Costs 5 credits per check.",+ "List the published email templates of the workspace.": "List the published email templates of the workspace.","Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint","To": "To","Sender Name": "Sender Name",@@ -14,7 +66,48 @@"Subject": "Subject","Content Type": "Content Type","Email Body": "Email Body",+ "Plain-Text Version": "Plain-Text Version","Custom Headers": "Custom Headers",+ "Send At": "Send At",+ "Template": "Template",+ "Template Variables": "Template Variables",+ "Metadata": "Metadata",+ "Open & Click Tracking": "Open & Click Tracking",+ "Attachments (by URL)": "Attachments (by URL)",+ "Attachment (file)": "Attachment (file)",+ "Idempotency Key": "Idempotency Key",+ "HTML Body": "HTML Body",+ "Plain-Text Body": "Plain-Text Body",+ "Email ID": "Email ID",+ "Direction": "Direction",+ "Recipient": "Recipient",+ "Status": "Status",+ "Search": "Search",+ "From Date": "From Date",+ "To Date": "To Date",+ "Limit": "Limit",+ "Page": "Page",+ "New Send Time": "New Send Time",+ "Add Forwarded-Message Header": "Add Forwarded-Message Header",+ "Note": "Note",+ "Sender": "Sender",+ "Domain": "Domain",+ "Audience": "Audience",+ "Email": "Email",+ "First Name": "First Name",+ "Last Name": "Last Name",+ "Custom Fields": "Custom Fields",+ "Subscriber": "Subscriber",+ "Subscribed": "Subscribed",+ "Email or Contact ID": "Email or Contact ID",+ "Add to Audiences": "Add to Audiences",+ "Unsubscribed from Campaigns": "Unsubscribed from Campaigns",+ "Type": "Type",+ "Reason": "Reason",+ "Keep Until": "Keep Until",+ "Suppression ID or Email": "Suppression ID or Email",+ "Mode": "Mode",+ "Name Contains": "Name Contains","Method": "Method","Headers": "Headers","Query Parameters": "Query Parameters",@@ -24,15 +117,65 @@"Return Error as Output": "Return Error as Output","Timeout": "Timeout","Follow redirects": "Follow redirects",- "Recipient email addresses. Up to 50 total across To, CC, and BCC.": "Recipient email addresses. Up to 50 total across To, CC, and BCC.",+ "Recipient email addresses, e.g. [email protected] or Ada Lovelace <[email protected]>. Up to 50 here, and up to 50 each in CC and BCC.": "Recipient email addresses, e.g. [email protected] or Ada Lovelace <[email protected]>. Up to 50 here, and up to 50 each in CC and BCC.","Name recipients will see in their inbox, e.g. \"Acme Support\". If left blank, only the email address is shown.": "Name recipients will see in their inbox, e.g. \"Acme Support\". If left blank, only the email address is shown.",- "Email address to send from. Must be verified in your Emailit account.": "Email address to send from. Must be verified in your Emailit account.",- "Send a visible copy to these addresses.": "Send a visible copy to these addresses.",- "Send a hidden copy to these addresses. Other recipients won't see them.": "Send a hidden copy to these addresses. Other recipients won't see them.",- "Where replies go. Defaults to the sender email if left blank.": "Where replies go. Defaults to the sender email if left blank.",- "The subject line shown in the recipient's inbox.": "The subject line shown in the recipient's inbox.",- "The message body. Use Plain Text for simple messages or HTML for rich formatting.": "The message body. Use Plain Text for simple messages or HTML for rich formatting.",- "Add custom email headers as key-value pairs, e.g. X-Campaign-ID: welcome.": "Add custom email headers as key-value pairs, e.g. X-Campaign-ID: welcome.",+ "Email address to send from. It must be on a verified sending domain of your Emailit workspace.": "Email address to send from. It must be on a verified sending domain of your Emailit workspace.",+ "Send a visible copy to these addresses. Up to 50.": "Send a visible copy to these addresses. Up to 50.",+ "Send a hidden copy to these addresses. Other recipients won't see them. Up to 50.": "Send a hidden copy to these addresses. Other recipients won't see them. Up to 50.",+ "Where replies go. Defaults to the sender email if left blank. Separate several addresses with commas.": "Where replies go. Defaults to the sender email if left blank. Separate several addresses with commas.",+ "The subject line shown in the recipient's inbox. Required unless you send a template.": "The subject line shown in the recipient's inbox. Required unless you send a template.",+ "The message body. Use Plain Text for simple messages or HTML for rich formatting. Required unless you send a template.": "The message body. Use Plain Text for simple messages or HTML for rich formatting. Required unless you send a template.",+ "Optional, for HTML emails: a plain-text version sent alongside the HTML. Recommended for deliverability.": "Optional, for HTML emails: a plain-text version sent alongside the HTML. Recommended for deliverability.",+ "Add custom email headers as key-value pairs, e.g. X-Campaign-ID: welcome. Line breaks are not allowed.": "Add custom email headers as key-value pairs, e.g. X-Campaign-ID: welcome. Line breaks are not allowed.",+ "Optional. Schedule the email for later (ISO 8601 with time zone). Leave empty to send now.": "Optional. Schedule the email for later (ISO 8601 with time zone). Leave empty to send now.",+ "Optional. A template ID (tem_…) or alias. Subject and body in this step override the template's.": "Optional. A template ID (tem_…) or alias. Subject and body in this step override the template's.",+ "Optional. Values for {{placeholders}} in the subject and body, e.g. {\"first_name\": \"Ada\"}.": "Optional. Values for {{placeholders}} in the subject and body, e.g. {\"first_name\": \"Ada\"}.",+ "Optional. Your own key-value data stored with the email and sent back in webhooks, e.g. order_id: 1042.": "Optional. Your own key-value data stored with the email and sent back in webhooks, e.g. order_id: 1042.",+ "Uses the sending domain's setting by default. Tracking only works when the domain's tracking CNAME is verified.": "Uses the sending domain's setting by default. Tracking only works when the domain's tracking CNAME is verified.",+ "Optional. Files Emailit downloads when sending (public http/https URL, max 25 MB, no redirects).": "Optional. Files Emailit downloads when sending (public http/https URL, max 25 MB, no redirects).",+ "Optional. A file from a previous step to attach.": "Optional. A file from a previous step to attach.",+ "Optional. A unique value (letters, digits, - and _; up to 256) such as an order ID. If this step runs again with the same key within 24 hours, Emailit returns the first result instead of sending again.": "Optional. A unique value (letters, digits, - and _; up to 256) such as an order ID. If this step runs again with the same key within 24 hours, Emailit returns the first result instead of sending again.",+ "Recipient addresses, up to 50.": "Recipient addresses, up to 50.",+ "Address on a verified sending domain of the workspace.": "Address on a verified sending domain of the workspace.",+ "Required unless template is set.": "Required unless template is set.",+ "Up to 50.": "Up to 50.",+ "Addresses for replies.": "Addresses for replies.",+ "Template ID (tem_…) or alias.": "Template ID (tem_…) or alias.",+ "JSON object of placeholder values.": "JSON object of placeholder values.",+ "ISO 8601 date-time with time zone, e.g. 2026-10-02T09:00:00Z. Empty sends now.": "ISO 8601 date-time with time zone, e.g. 2026-10-02T09:00:00Z. Empty sends now.",+ "The Emailit email ID, e.g. em_4KYof1ZzXndZE2VPi0DgULiekG8 (from a Send Email step or Find Emails).": "The Emailit email ID, e.g. em_4KYof1ZzXndZE2VPi0DgULiekG8 (from a Send Email step or Find Emails).",+ "Exact recipient address.": "Exact recipient address.",+ "Matches recipient, sender or subject.": "Matches recipient, sender or subject.",+ "YYYY-MM-DD (UTC). Defaults to 14 days ago.": "YYYY-MM-DD (UTC). Defaults to 14 days ago.",+ "YYYY-MM-DD (UTC).": "YYYY-MM-DD (UTC).",+ "Results per page, 1-100. Defaults to 25.": "Results per page, 1-100. Defaults to 25.",+ "Page to return, starting at 1. Use it when the previous result had Has More Pages = true.": "Page to return, starting at 1. Use it when the previous result had Has More Pages = true.",+ "ID of the scheduled email. For a send to several recipients, each recipient has its own ID.": "ID of the scheduled email. For a send to several recipients, each recipient has its own ID.",+ "ISO 8601 with time zone; at least 3 minutes from now.": "ISO 8601 with time zone; at least 3 minutes from now.",+ "ID of the bounced, failed, suppressed or held email.": "ID of the bounced, failed, suppressed or held email.",+ "ID of the outgoing email to forward.": "ID of the outgoing email to forward.",+ "New recipients, up to 50.": "New recipients, up to 50.",+ "Adds the original sender, date and subject above the content, with your note.": "Adds the original sender, date and subject above the content, with your note.",+ "Plain-text note above the forwarded message (only with the header option).": "Plain-text note above the forwarded message (only with the header option).",+ "Optional. Defaults to the original sender.": "Optional. Defaults to the original sender.",+ "Optional. Defaults to the original subject.": "Optional. Defaults to the original subject.",+ "Part of the domain name.": "Part of the domain name.",+ "The sending domain.": "The sending domain.",+ "Domain ID (dom_…) or domain name, e.g. acme.com.": "Domain ID (dom_…) or domain name, e.g. acme.com.",+ "Domain ID (dom_…) or domain name.": "Domain ID (dom_…) or domain name.",+ "Part of the audience name.": "Part of the audience name.",+ "The audience (subscriber list).": "The audience (subscriber list).",+ "Replaces all of the contact's custom fields, e.g. company: Acme.": "Replaces all of the contact's custom fields, e.g. company: Acme.",+ "The audience ID (aud_…) or its exact name. Use List Audiences to find it.": "The audience ID (aud_…) or its exact name. Use List Audiences to find it.",+ "Subscriber ID (sub_…) or email address.": "Subscriber ID (sub_…) or email address.",+ "Leave empty to keep.": "Leave empty to keep.",+ "Replaces all custom fields of an existing contact. Leave empty to keep.": "Replaces all custom fields of an existing contact. Leave empty to keep.",+ "Audiences to subscribe the contact to. Existing memberships are kept.": "Audiences to subscribe the contact to. Existing memberships are kept.",+ "Audience IDs (aud_…) to subscribe the contact to.": "Audience IDs (aud_…) to subscribe the contact to.",+ "Only \"recipient\" blocks API and SMTP sends; campaigns skip every type.": "Only \"recipient\" blocks API and SMTP sends; campaigns skip every type.",+ "Free-text note, e.g. \"Asked to stop receiving invoices\".": "Free-text note, e.g. \"Asked to stop receiving invoices\".",+ "Optional expiry. Leave empty for a permanent suppression.": "Optional expiry. Leave empty for a permanent suppression.",+ "Part of the template name or alias.": "Part of the template name or alias.","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.",@@ -41,6 +184,34 @@"Follow 3xx redirects instead of returning them as the response.": "Follow 3xx redirects instead of returning them as the response.","Plain Text": "Plain Text","HTML": "HTML",+ "Domain default": "Domain default",+ "On": "On",+ "Off": "Off",+ "Sent (outbound)": "Sent (outbound)",+ "Received (inbound)": "Received (inbound)",+ "accepted": "accepted",+ "scheduled": "scheduled",+ "delivered": "delivered",+ "loaded": "loaded",+ "clicked": "clicked",+ "attempted": "attempted",+ "bounced": "bounced",+ "failed": "failed",+ "rejected": "rejected",+ "suppressed": "suppressed",+ "received": "received",+ "complained": "complained",+ "canceled": "canceled",+ "held": "held",+ "Keep as is": "Keep as is",+ "Unsubscribed": "Unsubscribed",+ "Keep as is (new contacts: subscribed)": "Keep as is (new contacts: subscribed)",+ "recipient": "recipient",+ "bounce": "bounce",+ "complaint": "complaint",+ "unsubscribe": "unsubscribe",+ "Fast (syntax, domain, MX)": "Fast (syntax, domain, MX)",+ "Full (also checks the mailbox)": "Full (also checks the mailbox)","GET": "GET","POST": "POST","PATCH": "PATCH",diff --git a/packages/pieces/community/emailit/src/index.ts b/packages/pieces/community/emailit/src/index.tsindex f3d9e25758f..9063d31a25a 100644--- a/packages/pieces/community/emailit/src/index.ts+++ b/packages/pieces/community/emailit/src/index.ts@@ -1,25 +1,72 @@-import { createPiece } from '@activepieces/pieces-framework'-import { sendEmailAction } from './lib/actions/send-email'-import { PieceCategory } from '@activepieces/pieces-framework';-import { createCustomApiCallAction } from '@activepieces/pieces-common'-import { emailitAuth } from './lib/auth'+import { createCustomApiCallAction } from '@activepieces/pieces-common';+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';+import { addSubscriberAction, addSubscriberByIdAction } from './lib/actions/add-subscriber';+import { addSuppressionAction } from './lib/actions/add-suppression';+import { cancelEmailAction } from './lib/actions/cancel-email';+import { findContactAction } from './lib/actions/find-contact';+import { forwardEmailAction } from './lib/actions/forward-email';+import { getDomainAction, getDomainByIdAction } from './lib/actions/get-domain';+import { getEmailAction } from './lib/actions/get-email';+import { listAudiencesAction } from './lib/actions/list-audiences';+import { listDomainsAction } from './lib/actions/list-domains';+import { listEmailsAction } from './lib/actions/list-emails';+import { listTemplatesAction } from './lib/actions/list-templates';+import { removeSubscriberAction, removeSubscriberByIdAction } from './lib/actions/remove-subscriber';+import { removeSuppressionAction } from './lib/actions/remove-suppression';+import { rescheduleEmailAction } from './lib/actions/reschedule-email';+import { retryEmailAction } from './lib/actions/retry-email';+import { sendEmailAction } from './lib/actions/send-email';+import { sendEmailAiAction } from './lib/actions/send-email-ai';+import { updateSubscriberAction, updateSubscriberByIdAction } from './lib/actions/update-subscriber';+import { upsertContactAction, upsertContactByIdAction } from './lib/actions/upsert-contact';+import { verifyDomainAction, verifyDomainByIdAction } from './lib/actions/verify-domain';+import { verifyEmailAddressAction } from './lib/actions/verify-email-address';+import { emailitAuth } from './lib/auth';+import { EMAILIT_API_BASE, emailitClient } from './lib/common/client';export const emailit = createPiece({- displayName: 'Emailit',- description: 'Send transactional emails with Emailit',- logoUrl: 'https://cdn.activepieces.com/pieces/emailit.svg',- categories: [PieceCategory.COMMUNICATION, PieceCategory.PRODUCTIVITY],- authors: ['dennisklappe', 'onyedikachi-david'],- auth: emailitAuth,- actions: [- sendEmailAction,- createCustomApiCallAction({- baseUrl: () => 'https://api.emailit.com/v2',- auth: emailitAuth,- authMapping: async (auth) => ({- Authorization: `Bearer ${auth.secret_text}`,- }),- }),- ],- triggers: [],-})+ displayName: 'Emailit',+ description: 'Send transactional emails with Emailit',+ logoUrl: 'https://cdn.activepieces.com/pieces/emailit.svg',+ categories: [PieceCategory.COMMUNICATION, PieceCategory.PRODUCTIVITY],+ minimumSupportedRelease: '0.88.2',+ authors: ['dennisklappe', 'onyedikachi-david'],+ auth: emailitAuth,+ actions: [+ sendEmailAction,+ sendEmailAiAction,+ getEmailAction,+ listEmailsAction,+ rescheduleEmailAction,+ cancelEmailAction,+ retryEmailAction,+ forwardEmailAction,+ listDomainsAction,+ getDomainAction,+ getDomainByIdAction,+ verifyDomainAction,+ verifyDomainByIdAction,+ listAudiencesAction,+ addSubscriberAction,+ addSubscriberByIdAction,+ updateSubscriberAction,+ updateSubscriberByIdAction,+ removeSubscriberAction,+ removeSubscriberByIdAction,+ findContactAction,+ upsertContactAction,+ upsertContactByIdAction,+ addSuppressionAction,+ removeSuppressionAction,+ verifyEmailAddressAction,+ listTemplatesAction,+ createCustomApiCallAction({+ baseUrl: () => EMAILIT_API_BASE,+ auth: emailitAuth,+ authMapping: async (auth) => ({+ Authorization: `Bearer ${emailitClient.apiKeyOf(auth)}`,+ }),+ }),+ ],+ triggers: [],+});diff --git a/packages/pieces/community/emailit/src/lib/actions/add-subscriber.ts b/packages/pieces/community/emailit/src/lib/actions/add-subscriber.tsnew file mode 100644index 00000000000..6a7e4d0c3d8--- /dev/null+++ b/packages/pieces/community/emailit/src/lib/actions/add-subscriber.ts@@ -0,0 +1,53 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { emailitAuth } from '../auth';+import { emailitDropdowns } from '../common/dropdowns';+import { emailitOperations } from '../common/operations';+import { emailitSchemas } from '../common/output-schemas';+import { emailitProps } from '../common/props';++export const addSubscriberAction = createAction({+ auth: emailitAuth,+ name: 'add_subscriber',+ displayName: 'Add Subscriber to Audience',+ description: 'Add an email address to an audience, creating the contact if needed.',+ audience: 'human',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Adds an email address to an Emailit audience (creating the contact if it does not exist) with optional first/last name and custom fields, which overwrite the contact\'s values. If the address is already subscribed nothing changes and alreadySubscribed=true is returned; if it had unsubscribed, this resubscribes it, so only use it when the person opted in again. Returns the subscriber (id = sub_…); pass that id or the email to Update Subscriber or Remove Subscriber. Needs a Full Access key.',+ idempotent: true,+ },+ outputSchema: emailitSchemas.subscriber,+ props: { audience: emailitDropdowns.audience(), ...fields() },+ async run({ auth, propsValue }) {+ return emailitOperations.addSubscriber({ auth, input: { audience: propsValue.audience, email: propsValue.email, firstName: propsValue.first_name, lastName: propsValue.last_name, customFields: propsValue.custom_fields } });+ },+});++export const addSubscriberByIdAction = createAction({+ auth: emailitAuth,+ name: 'add_subscriber_by_id',+ displayName: 'Add Subscriber to Audience (by ID)',+ description: 'Add an email address to an audience given by ID or name.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Adds an email address to an Emailit audience (creating the contact if it does not exist) with optional first/last name and custom fields, which overwrite the contact\'s values. If the address is already subscribed nothing changes and alreadySubscribed=true is returned; if it had unsubscribed, this resubscribes it, so only use it when the person opted in again. Returns the subscriber (id = sub_…); pass that id or the email to Update Subscriber or Remove Subscriber. Needs a Full Access key. Get the audience ID from List Audiences first.',+ idempotent: true,+ },+ outputSchema: emailitSchemas.subscriber,+ props: { audience: emailitProps.audienceId(), ...fields() },+ async run({ auth, propsValue }) {+ return emailitOperations.addSubscriber({ auth, input: { audience: propsValue.audience, email: propsValue.email, firstName: propsValue.first_name, lastName: propsValue.last_name, customFields: propsValue.custom_fields } });+ },+});++function fields() {+ return {+ email: Property.ShortText({ displayName: 'Email', required: true }),+ first_name: Property.ShortText({ displayName: 'First Name', required: false }),+ last_name: Property.ShortText({ displayName: 'Last Name', required: false }),+ custom_fields: Property.Object({ displayName: 'Custom Fields', description: 'Replaces all of the contact\'s custom fields, e.g. company: Acme.', required: false }),+ };+}diff --git a/packages/pieces/community/emailit/src/lib/actions/add-suppression.ts b/packages/pieces/community/emailit/src/lib/actions/add-suppression.tsnew file mode 100644index 00000000000..5882de57329--- /dev/null+++ b/packages/pieces/community/emailit/src/lib/actions/add-suppression.ts@@ -0,0 +1,56 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { emailitAuth } from '../auth';+import { EmailitApiError, emailitClient } from '../common/client';+import { emailitSchemas } from '../common/output-schemas';+import { emailitValues } from '../common/values';++export const addSuppressionAction = createAction({+ auth: emailitAuth,+ name: 'add_suppression',+ displayName: 'Suppress Email Address',+ description: 'Stop Emailit from sending to an address, permanently or until a date.',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Adds an address to the Emailit suppression list so API/SMTP sends to it get status suppressed instead of being delivered (type recipient) and campaigns skip it, permanently or until keep_until. If the address already has a suppression of this type, returns it with alreadySuppressed=true. Needs a Full Access key.',+ idempotent: true,+ },+ outputSchema: emailitSchemas.suppression,+ props: {+ email: Property.ShortText({ displayName: 'Email', required: true }),+ type: Property.StaticDropdown<'recipient' | 'bounce' | 'complaint' | 'unsubscribe'>({+ displayName: 'Type',+ description: 'Only "recipient" blocks API and SMTP sends; campaigns skip every type.',+ required: false,+ defaultValue: 'recipient',+ options: { disabled: false, options: [{ label: 'recipient', value: 'recipient' }, { label: 'bounce', value: 'bounce' }, { label: 'complaint', value: 'complaint' }, { label: 'unsubscribe', value: 'unsubscribe' }] },+ }),+ reason: Property.ShortText({ displayName: 'Reason', description: 'Free-text note, e.g. "Asked to stop receiving invoices".', required: false }),+ keep_until: Property.DateTime({ displayName: 'Keep Until', description: 'Optional expiry. Leave empty for a permanent suppression.', required: false }),+ },+ async run({ auth, propsValue }) {+ const body = emailitValues.compact({+ email: emailitValues.requiredText({ value: propsValue.email, label: 'Email' }),+ type: propsValue.type ?? 'recipient',+ reason: emailitValues.optionalText(propsValue.reason),+ keep_until: emailitValues.dateTime(propsValue.keep_until),+ });+ try {+ const created = await emailitClient.request({ auth, method: HttpMethod.POST, path: '/suppressions', body, redactBody: true, safeToRetry: true });+ return { ...unwrap(created), alreadySuppressed: false };+ } catch (error) {+ if (error instanceof EmailitApiError && error.status === 409 && emailitClient.isRecord(error.responseBody)) {+ return { ...unwrap(error.responseBody['existing']), alreadySuppressed: true };+ }+ throw error;+ }+ },+});++function unwrap(value: unknown): Record<string, unknown> {+ if (!emailitClient.isRecord(value)) return {};+ const data = value['data'];+ return emailitClient.isRecord(data) ? data : value;+}diff --git a/packages/pieces/community/emailit/src/lib/actions/cancel-email.ts b/packages/pieces/community/emailit/src/lib/actions/cancel-email.tsnew file mode 100644index 00000000000..1ee71e9c5dc--- /dev/null+++ b/packages/pieces/community/emailit/src/lib/actions/cancel-email.ts@@ -0,0 +1,26 @@+import { createAction } from '@activepieces/pieces-framework';+import { emailitAuth } from '../auth';+import { emailitOperations } from '../common/operations';+import { emailitSchemas } from '../common/output-schemas';+import { emailitProps } from '../common/props';++export const cancelEmailAction = createAction({+ auth: emailitAuth,+ name: 'cancel_email',+ displayName: 'Cancel Scheduled Email',+ description: 'Cancel an email that is scheduled, queued or waiting to retry.',+ audience: 'both',+ classification: 'DESTRUCTIVE',+ aiMetadata: {+ description:+ 'Cancels an Emailit email that is still scheduled, accepted (queued) or attempted (retrying); sent emails cannot be recalled and the credit is not refunded. Best effort: in_flight=true means a delivery attempt may still complete. A repeat call on an already canceled email returns alreadyCanceled=true instead of failing.',+ idempotent: true,+ },+ outputSchema: emailitSchemas.canceled,+ props: {+ email_id: emailitProps.emailId(),+ },+ async run({ auth, propsValue }) {+ return emailitOperations.cancelEmail({ auth, emailId: propsValue.email_id });+ },+});diff --git a/packages/pieces/community/emailit/src/lib/actions/find-contact.ts b/packages/pieces/community/emailit/src/lib/actions/find-contact.tsnew file mode 100644index 00000000000..07d6bcc13da--- /dev/null+++ b/packages/pieces/community/emailit/src/lib/actions/find-contact.ts@@ -0,0 +1,36 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { emailitAuth } from '../auth';+import { emailitClient } from '../common/client';+import { emailitSchemas } from '../common/output-schemas';+import { emailitValues } from '../common/values';++export const findContactAction = createAction({+ auth: emailitAuth,+ name: 'find_contact',+ displayName: 'Find Contact',+ description: 'Look up a contact by email address or contact ID.',+ audience: 'both',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Looks up one Emailit contact by email address or contact ID (con_…) and returns {found, contact} with names, custom fields, unsubscribed flag and audience memberships. found=false when no contact matches. Read-only; needs a Full Access key.',+ idempotent: true,+ },+ outputSchema: emailitSchemas.contactLookup,+ props: {+ contact: Property.ShortText({ displayName: 'Email or Contact ID', required: true }),+ },+ async run({ auth, propsValue }) {+ const key = emailitValues.requiredText({ value: propsValue.contact, label: 'Email or Contact ID' });+ try {+ const contact = await emailitClient.request({ auth, method: HttpMethod.GET, path: `/contacts/${emailitClient.seg({ value: key, label: 'Email or Contact ID' })}` });+ return { found: true, contact };+ } catch (error) {+ if (emailitClient.statusOf(error) === 404) {+ return { found: false, contact: null };+ }+ throw error;+ }+ },+});diff --git a/packages/pieces/community/emailit/src/lib/actions/forward-email.ts b/packages/pieces/community/emailit/src/lib/actions/forward-email.tsnew file mode 100644index 00000000000..6a84aa1c684--- /dev/null+++ b/packages/pieces/community/emailit/src/lib/actions/forward-email.ts@@ -0,0 +1,55 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { emailitAuth } from '../auth';+import { emailitClient } from '../common/client';+import { emailitSchemas } from '../common/output-schemas';+import { emailitProps } from '../common/props';+import { emailitValues } from '../common/values';++export const forwardEmailAction = createAction({+ auth: emailitAuth,+ name: 'forward_email',+ displayName: 'Forward Email',+ description: 'Send a copy of a sent email to new recipients.',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Forwards an outgoing Emailit email to up to 50 new recipients as a new send, either as a plain resend or with a "Forwarded message" block and an optional note. Each recipient costs a credit; the workspace can forward at most 3 emails per hour. Not idempotent unless the same idempotency_key is given within 24 hours.',+ idempotent: false,+ },+ outputSchema: emailitSchemas.forwarded,+ props: {+ email_id: emailitProps.emailId({ description: 'ID of the outgoing email to forward.' }),+ to: emailitProps.recipientList({ displayName: 'To', description: 'New recipients, up to 50.', required: true }),+ include_headers: Property.Checkbox({ displayName: 'Add Forwarded-Message Header', description: 'Adds the original sender, date and subject above the content, with your note.', required: false, defaultValue: false }),+ comment: Property.LongText({ displayName: 'Note', description: 'Plain-text note above the forwarded message (only with the header option).', required: false }),+ from: Property.ShortText({ displayName: 'Sender', description: 'Optional. Defaults to the original sender.', required: false }),+ subject: Property.ShortText({ displayName: 'Subject', description: 'Optional. Defaults to the original subject.', required: false }),+ idempotency_key: emailitProps.idempotencyKey(),+ },+ async run({ auth, propsValue }) {+ const body = emailitValues.compact({+ to: emailitValues.recipients({ value: propsValue.to, label: 'To', required: true }),+ include_headers: propsValue.include_headers === true ? true : undefined,+ comment: propsValue.include_headers === true ? emailitValues.optionalText(propsValue.comment) : undefined,+ from: emailitValues.singleLine({ value: propsValue.from, label: 'Sender' }),+ subject: emailitValues.singleLine({ value: propsValue.subject, label: 'Subject' }),+ });+ try {+ return await emailitClient.request({+ auth,+ method: HttpMethod.POST,+ path: `/emails/${emailitClient.seg({ value: propsValue.email_id, label: 'Email ID' })}/forward`,+ body,+ idempotencyKey: emailitValues.idempotencyKey(propsValue.idempotency_key),+ redactBody: true,+ });+ } catch (error) {+ return emailitClient.rethrowWithHint({+ error,+ hints: { 404: 'Email not found.', 422: 'Only outgoing emails whose content is still kept can be forwarded.', 429: 'Forward limit reached (3 per hour per workspace).' },+ });+ }+ },+});diff --git a/packages/pieces/community/emailit/src/lib/actions/get-domain.ts b/packages/pieces/community/emailit/src/lib/actions/get-domain.tsnew file mode 100644index 00000000000..08e0896fc0a--- /dev/null+++ b/packages/pieces/community/emailit/src/lib/actions/get-domain.ts@@ -0,0 +1,43 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { emailitAuth } from '../auth';+import { emailitDropdowns } from '../common/dropdowns';+import { emailitOperations } from '../common/operations';+import { emailitSchemas } from '../common/output-schemas';++export const getDomainAction = createAction({+ auth: emailitAuth,+ name: 'get_domain',+ displayName: 'Get Sending Domain',+ description: 'Get a sending domain with its verification status and the DNS records to publish.',+ audience: 'human',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Returns one Emailit sending domain: verification_status, each record\'s status and error, and the DNS records to publish. Statuses reflect the last DNS check; call Check Domain Verification to re-check now. Read-only; needs a Full Access key.',+ idempotent: true,+ },+ outputSchema: emailitSchemas.domain,+ props: { domain: emailitDropdowns.domain() },+ async run({ auth, propsValue }) {+ return emailitOperations.getDomain({ auth, domain: propsValue.domain });+ },+});++export const getDomainByIdAction = createAction({+ auth: emailitAuth,+ name: 'get_domain_by_id',+ displayName: 'Get Sending Domain (by ID)',+ description: 'Get a sending domain by ID or name.',+ audience: 'ai',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Returns one Emailit sending domain: verification_status, each record\'s status and error, and the DNS records to publish. Statuses reflect the last DNS check; call Check Domain Verification to re-check now. Read-only; needs a Full Access key. Takes the domain ID (dom_…) or name (acme.com); List Sending Domains finds them.',+ idempotent: true,+ },+ outputSchema: emailitSchemas.domain,+ props: { domain: Property.ShortText({ displayName: 'Domain', description: 'Domain ID (dom_…) or domain name, e.g. acme.com.', required: true }) },+ async run({ auth, propsValue }) {+ return emailitOperations.getDomain({ auth, domain: propsValue.domain });+ },+});diff --git a/packages/pieces/community/emailit/src/lib/actions/get-email.ts b/packages/pieces/community/emailit/src/lib/actions/get-email.tsnew file mode 100644index 00000000000..9f7268f7103--- /dev/null+++ b/packages/pieces/community/emailit/src/lib/actions/get-email.ts@@ -0,0 +1,44 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { emailitAuth } from '../auth';+import { emailitClient } from '../common/client';+import { emailitSchemas } from '../common/output-schemas';+import { emailitProps } from '../common/props';++export const getEmailAction = createAction({+ auth: emailitAuth,+ name: 'get_email',+ displayName: 'Get Email',+ description: 'Get one sent or received email with its status, headers, body and attachment list.',+ audience: 'both',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Returns one Emailit email by ID: status (accepted, delivered, bounced, …), from, to, subject, metadata, headers, HTML/text body and attachment names and sizes. Attachment contents are not returned. Read-only; needs a Full Access key.',+ idempotent: true,+ },+ outputSchema: emailitSchemas.email,+ props: {+ email_id: emailitProps.emailId(),+ },+ async run({ auth, propsValue }) {+ try {+ const email = await emailitClient.request({ auth, method: HttpMethod.GET, path: `/emails/${emailitClient.seg({ value: propsValue.email_id, label: 'Email ID' })}` });+ return withoutAttachmentContent(email);+ } catch (error) {+ return emailitClient.rethrowWithHint({ error, hints: { 404: 'Email not found.' } });+ }+ },+});++function withoutAttachmentContent(email: unknown): unknown {+ if (!emailitClient.isRecord(email)) return email;+ const attachments = email['attachments'];+ if (!Array.isArray(attachments)) return email;+ return {+ ...email,+ attachments: attachments.map((item) =>+ emailitClient.isRecord(item) ? Object.fromEntries(Object.entries(item).filter(([key]) => key !== 'content')) : item,+ ),+ };+}diff --git a/packages/pieces/community/emailit/src/lib/actions/list-audiences.ts b/packages/pieces/community/emailit/src/lib/actions/list-audiences.tsnew file mode 100644index 00000000000..154bd688999--- /dev/null+++ b/packages/pieces/community/emailit/src/lib/actions/list-audiences.ts@@ -0,0 +1,38 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { emailitAuth } from '../auth';+import { emailitClient } from '../common/client';+import { emailitSchemas } from '../common/output-schemas';+import { emailitProps } from '../common/props';+import { emailitValues } from '../common/values';++export const listAudiencesAction = createAction({+ auth: emailitAuth,+ name: 'list_audiences',+ displayName: 'List Audiences',+ description: 'List the audiences (subscriber lists) of the workspace.',+ audience: 'both',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Lists Emailit audiences (subscriber lists) newest first with id, name, subscriber count and plan usage, one page at a time {items, count, page, hasMore, totalRecords}. Use the id with the subscriber actions. Read-only; needs a Full Access key.',+ idempotent: true,+ },+ outputSchema: emailitSchemas.audienceList,+ props: {+ search: Property.ShortText({ displayName: 'Search', description: 'Part of the audience name.', required: false }),+ limit: emailitProps.limit(),+ page: emailitProps.page(),+ },+ async run({ auth, propsValue }) {+ const page = emailitClient.page(propsValue.page);+ const body = await emailitClient.request({+ auth,+ method: HttpMethod.GET,+ path: '/audiences',+ query: { search: emailitValues.optionalText(propsValue.search), limit: emailitClient.clampLimit(propsValue.limit), page },+ });+ const { items, hasMore, totalRecords } = emailitClient.listPage(body);+ return { items, count: items.length, page, hasMore, totalRecords };+ },+});diff --git a/packages/pieces/community/emailit/src/lib/actions/list-domains.ts b/packages/pieces/community/emailit/src/lib/actions/list-domains.tsnew file mode 100644index 00000000000..3ec65b6d39d--- /dev/null+++ b/packages/pieces/community/emailit/src/lib/actions/list-domains.ts@@ -0,0 +1,38 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { emailitAuth } from '../auth';+import { emailitClient } from '../common/client';+import { emailitSchemas } from '../common/output-schemas';+import { emailitProps } from '../common/props';+import { emailitValues } from '../common/values';++export const listDomainsAction = createAction({+ auth: emailitAuth,+ name: 'list_domains',+ displayName: 'List Sending Domains',+ description: 'List the sending domains of the workspace with their verification status.',+ audience: 'both',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Lists the Emailit workspace\'s sending domains (id, name, verification_status and per-record SPF/DKIM/return-path status), one page at a time {items, count, page, hasMore}. Use it to find a verified domain to send from. Read-only; needs a Full Access key.',+ idempotent: true,+ },+ outputSchema: emailitSchemas.domainList,+ props: {+ search: Property.ShortText({ displayName: 'Search', description: 'Part of the domain name.', required: false }),+ limit: emailitProps.limit(),+ page: emailitProps.page(),+ },+ async run({ auth, propsValue }) {+ const page = emailitClient.page(propsValue.page);+ const body = await emailitClient.request({+ auth,+ method: HttpMethod.GET,+ path: '/domains',+ query: { search: emailitValues.optionalText(propsValue.search), limit: emailitClient.clampLimit(propsValue.limit), page },+ });+ const { items, hasMore, totalRecords } = emailitClient.listPage(body);+ return { items, count: items.length, page, hasMore, totalRecords };+ },+});diff --git a/packages/pieces/community/emailit/src/lib/actions/list-emails.ts b/packages/pieces/community/emailit/src/lib/actions/list-emails.tsnew file mode 100644index 00000000000..7cff1fd1c27--- /dev/null+++ b/packages/pieces/community/emailit/src/lib/actions/list-emails.ts@@ -0,0 +1,73 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { emailitAuth } from '../auth';+import { emailitClient } from '../common/client';+import { emailitSchemas } from '../common/output-schemas';+import { emailitProps } from '../common/props';+import { emailitValues } from '../common/values';++export const listEmailsAction = createAction({+ auth: emailitAuth,+ name: 'list_emails',+ displayName: 'Find Emails',+ description: 'Search sent or received emails, newest first (last 14 days unless you set dates).',+ audience: 'both',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Searches Emailit emails newest first and returns one page {items, count, page, hasMore}. Filter by recipient, status, free-text search (recipient, sender or subject), direction and a date range (defaults to the last 14 days). Each recipient of a send is a separate item. Read-only; needs a Full Access key.',+ idempotent: true,+ },+ outputSchema: emailitSchemas.emailList,+ props: {+ type: Property.StaticDropdown<'outbound' | 'inbound'>({+ displayName: 'Direction',+ required: false,+ defaultValue: 'outbound',+ options: { disabled: false, options: [{ label: 'Sent (outbound)', value: 'outbound' }, { label: 'Received (inbound)', value: 'inbound' }] },+ }),+ to: Property.ShortText({ displayName: 'Recipient', description: 'Exact recipient address.', required: false }),+ status: Property.StaticDropdown({+ displayName: 'Status',+ required: false,+ options: {+ disabled: false,+ options: ['accepted', 'scheduled', 'delivered', 'loaded', 'clicked', 'attempted', 'bounced', 'failed', 'rejected', 'suppressed', 'received', 'complained', 'canceled', 'held'].map((value) => ({ label: value, value })),+ },+ }),+ search: Property.ShortText({ displayName: 'Search', description: 'Matches recipient, sender or subject.', required: false }),+ date_from: Property.ShortText({ displayName: 'From Date', description: 'YYYY-MM-DD (UTC). Defaults to 14 days ago.', required: false }),+ date_to: Property.ShortText({ displayName: 'To Date', description: 'YYYY-MM-DD (UTC).', required: false }),+ limit: emailitProps.limit(),+ page: emailitProps.page(),+ },+ async run({ auth, propsValue }) {+ const page = emailitClient.page(propsValue.page);+ const body = await emailitClient.request({+ auth,+ method: HttpMethod.GET,+ path: '/emails',+ query: {+ type: propsValue.type,+ 'to.exact': emailitValues.optionalText(propsValue.to),+ 'status.exact': propsValue.status,+ search: emailitValues.optionalText(propsValue.search),+ date_from: day({ value: propsValue.date_from, label: 'From Date' }),+ date_to: day({ value: propsValue.date_to, label: 'To Date' }),+ limit: emailitClient.clampLimit(propsValue.limit),+ page,+ },+ });+ const { items, hasMore, totalRecords } = emailitClient.listPage(body);+ return { items, count: items.length, page, hasMore, totalRecords };+ },+});++function day({ value, label }: { value: unknown; label: string }): string | undefined {+ const text = emailitValues.optionalText(value);+ if (text === undefined) return undefined;+ if (!/^\d{4}-\d{2}-\d{2}/.test(text) || Number.isNaN(Date.parse(text))) {+ throw new Error(`${label} must be a date like 2026-08-01.`);+ }+ return text.slice(0, 10);+}diff --git a/packages/pieces/community/emailit/src/lib/actions/list-templates.ts b/packages/pieces/community/emailit/src/lib/actions/list-templates.tsnew file mode 100644index 00000000000..b40d6cf70c0--- /dev/null+++ b/packages/pieces/community/emailit/src/lib/actions/list-templates.ts@@ -0,0 +1,38 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { emailitAuth } from '../auth';+import { emailitClient } from '../common/client';+import { emailitSchemas } from '../common/output-schemas';+import { emailitProps } from '../common/props';+import { emailitValues } from '../common/values';++export const listTemplatesAction = createAction({+ auth: emailitAuth,+ name: 'list_templates',+ displayName: 'List Templates',+ description: 'List the published email templates of the workspace.',+ audience: 'both',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Lists the published version of each Emailit template (id, name, alias, subject, editor), newest first, one page at a time {items, count, page, hasMore, totalRecords}. Pass a template\'s alias or id as Template when sending. Content is not included. Read-only; needs a Full Access key.',+ idempotent: true,+ },+ outputSchema: emailitSchemas.templateList,+ props: {+ name: Property.ShortText({ displayName: 'Name Contains', description: 'Part of the template name or alias.', required: false }),+ limit: emailitProps.limit(),+ page: emailitProps.page(),+ },+ async run({ auth, propsValue }) {+ const page = emailitClient.page(propsValue.page);+ const body = await emailitClient.request({+ auth,+ method: HttpMethod.GET,+ path: '/templates',+ query: { 'filter[name]': emailitValues.optionalText(propsValue.name), per_page: emailitClient.clampLimit(propsValue.limit), page },+ });+ const { items, hasMore, totalRecords } = emailitClient.listPage(body);+ return { items, count: items.length, page, hasMore, totalRecords };+ },+});diff --git a/packages/pieces/community/emailit/src/lib/actions/remove-subscriber.ts b/packages/pieces/community/emailit/src/lib/actions/remove-subscriber.tsnew file mode 100644index 00000000000..c91755e6811--- /dev/null+++ b/packages/pieces/community/emailit/src/lib/actions/remove-subscriber.ts@@ -0,0 +1,48 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { emailitAuth } from '../auth';+import { emailitDropdowns } from '../common/dropdowns';+import { emailitOperations } from '../common/operations';+import { emailitSchemas } from '../common/output-schemas';+import { emailitProps } from '../common/props';++export const removeSubscriberAction = createAction({+ auth: emailitAuth,+ name: 'remove_subscriber',+ displayName: 'Remove Subscriber',+ description: 'Delete someone\'s membership in an audience. The contact is kept.',+ audience: 'human',+ classification: 'DESTRUCTIVE',+ aiMetadata: {+ description:+ 'Removes one subscriber (by sub_… ID or email) from an Emailit audience; the contact and its other audiences are kept, and no opt-out is recorded (for opt-outs use Update Subscriber with Subscribed off instead). If nothing matches, returns alreadyRemoved=true instead of failing. Needs a Full Access key.',+ idempotent: true,+ },+ outputSchema: emailitSchemas.removed,+ props: { audience: emailitDropdowns.audience(), subscriber: subscriberProp() },+ async run({ auth, propsValue }) {+ return emailitOperations.removeSubscriber({ auth, input: { audience: propsValue.audience, subscriber: propsValue.subscriber } });+ },+});++export const removeSubscriberByIdAction = createAction({+ auth: emailitAuth,+ name: 'remove_subscriber_by_id',+ displayName: 'Remove Subscriber (by ID)',+ description: 'Remove a subscriber from an audience given by ID or name.',+ audience: 'ai',+ classification: 'DESTRUCTIVE',+ aiMetadata: {+ description:+ 'Removes one subscriber (by sub_… ID or email) from an Emailit audience; the contact and its other audiences are kept, and no opt-out is recorded (for opt-outs use Update Subscriber with Subscribed off instead). If nothing matches, returns alreadyRemoved=true instead of failing. Needs a Full Access key. Get the audience ID from List Audiences first.',+ idempotent: true,+ },+ outputSchema: emailitSchemas.removed,+ props: { audience: emailitProps.audienceId(), subscriber: subscriberProp() },+ async run({ auth, propsValue }) {+ return emailitOperations.removeSubscriber({ auth, input: { audience: propsValue.audience, subscriber: propsValue.subscriber } });+ },+});++function subscriberProp() {+ return Property.ShortText({ displayName: 'Subscriber', description: 'Subscriber ID (sub_…) or email address.', required: true });+}diff --git a/packages/pieces/community/emailit/src/lib/actions/remove-suppression.ts b/packages/pieces/community/emailit/src/lib/actions/remove-suppression.tsnew file mode 100644index 00000000000..8d98a1dfa04--- /dev/null+++ b/packages/pieces/community/emailit/src/lib/actions/remove-suppression.ts@@ -0,0 +1,39 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { emailitAuth } from '../auth';+import { emailitClient } from '../common/client';+import { emailitSchemas } from '../common/output-schemas';++export const removeSuppressionAction = createAction({+ auth: emailitAuth,+ name: 'remove_suppression',+ displayName: 'Remove Suppression',+ description: 'Remove a suppression so Emailit can send to the address again.',+ audience: 'both',+ classification: 'DESTRUCTIVE',+ aiMetadata: {+ description:+ 'Deletes one Emailit suppression by suppression ID (sup_…) or email address so the address can receive email again. An address with several suppression types needs one call per type (use the ID to target one). If nothing matches, returns alreadyRemoved=true instead of failing. Needs a Full Access key.',+ idempotent: true,+ },+ outputSchema: emailitSchemas.removed,+ props: {+ suppression: Property.ShortText({ displayName: 'Suppression ID or Email', required: true }),+ },+ async run({ auth, propsValue }) {+ try {+ const body = await emailitClient.request({+ auth,+ method: HttpMethod.DELETE,+ path: `/suppressions/${emailitClient.seg({ value: propsValue.suppression, label: 'Suppression ID or Email' })}`,+ safeToRetry: true,+ });+ return { ...(emailitClient.isRecord(body) ? body : {}), deleted: true, alreadyRemoved: false };+ } catch (error) {+ if (emailitClient.statusOf(error) === 404) {+ return { id: propsValue.suppression.trim(), deleted: false, alreadyRemoved: true };+ }+ throw error;+ }+ },+});diff --git a/packages/pieces/community/emailit/src/lib/actions/reschedule-email.ts b/packages/pieces/community/emailit/src/lib/actions/reschedule-email.tsnew file mode 100644index 00000000000..430e11d758a--- /dev/null+++ b/packages/pieces/community/emailit/src/lib/actions/reschedule-email.ts@@ -0,0 +1,46 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { emailitAuth } from '../auth';+import { emailitClient } from '../common/client';+import { emailitSchemas } from '../common/output-schemas';+import { emailitProps } from '../common/props';+import { emailitValues } from '../common/values';++export const rescheduleEmailAction = createAction({+ auth: emailitAuth,+ name: 'update_scheduled_email',+ displayName: 'Reschedule Email',+ description: 'Change the send time of a scheduled email.',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Moves a scheduled Emailit email to a new send time. Works only while the email is still scheduled and more than 3 minutes from its current send time, and the new time must be over 3 minutes ahead. Content cannot change. Repeating with the same time leaves the same result.',+ idempotent: true,+ },+ outputSchema: emailitSchemas.rescheduled,+ props: {+ email_id: emailitProps.emailId({ description: 'ID of the scheduled email. For a send to several recipients, each recipient has its own ID.' }),+ scheduled_at: Property.DateTime({ displayName: 'New Send Time', description: 'ISO 8601 with time zone; at least 3 minutes from now.', required: true }),+ },+ async run({ auth, propsValue }) {+ const scheduledAt = emailitValues.dateTime(propsValue.scheduled_at);+ if (scheduledAt === undefined) {+ throw new Error('New Send Time is required.');+ }+ try {+ return await emailitClient.request({+ auth,+ method: HttpMethod.POST,+ path: `/emails/${emailitClient.seg({ value: propsValue.email_id, label: 'Email ID' })}`,+ body: { scheduled_at: scheduledAt },+ safeToRetry: true,+ });+ } catch (error) {+ return emailitClient.rethrowWithHint({+ error,+ hints: { 404: 'Email not found.', 422: 'The email can no longer be rescheduled (not scheduled, or due within 3 minutes), or the new time is too soon.' },+ });+ }+ },+});diff --git a/packages/pieces/community/emailit/src/lib/actions/retry-email.ts b/packages/pieces/community/emailit/src/lib/actions/retry-email.tsnew file mode 100644index 00000000000..41eb752579c--- /dev/null+++ b/packages/pieces/community/emailit/src/lib/actions/retry-email.ts@@ -0,0 +1,38 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { emailitAuth } from '../auth';+import { emailitClient } from '../common/client';+import { emailitSchemas } from '../common/output-schemas';+import { emailitProps } from '../common/props';++export const retryEmailAction = createAction({+ auth: emailitAuth,+ name: 'retry_email',+ displayName: 'Retry Email',+ description: 'Send a bounced, failed, suppressed or held email again as a new email.',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Queues a new copy (new ID, same content and recipient) of an Emailit email whose status is bounced, failed, suppressed or held, created in the last 30 days. Costs a credit like a new send. Not idempotent: each call sends another copy. Fix the cause first, e.g. remove the suppression.',+ idempotent: false,+ },+ outputSchema: emailitSchemas.retried,+ props: {+ email_id: emailitProps.emailId({ description: 'ID of the bounced, failed, suppressed or held email.' }),+ },+ async run({ auth, propsValue }) {+ try {+ return await emailitClient.request({+ auth,+ method: HttpMethod.POST,+ path: `/emails/${emailitClient.seg({ value: propsValue.email_id, label: 'Email ID' })}/retry`,+ });+ } catch (error) {+ return emailitClient.rethrowWithHint({+ error,+ hints: { 404: 'Email not found.', 422: 'This email cannot be retried (status not bounced/failed/suppressed/held, older than 30 days, or content purged).' },+ });+ }+ },+});diff --git a/packages/pieces/community/emailit/src/lib/actions/send-email-ai.ts b/packages/pieces/community/emailit/src/lib/actions/send-email-ai.tsnew file mode 100644index 00000000000..c29b6ad0481--- /dev/null+++ b/packages/pieces/community/emailit/src/lib/actions/send-email-ai.ts@@ -0,0 +1,56 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { emailitAuth } from '../auth';+import { emailitSchemas } from '../common/output-schemas';+import { emailitProps } from '../common/props';+import { emailitSend } from '../common/send';++export const sendEmailAiAction = createAction({+ auth: emailitAuth,+ name: 'send_email_ai',+ displayName: 'Send Email (AI)',+ description: 'Send an email through Emailit and return the created email.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Sends one email through Emailit from an address on a verified sending domain to up to 50 To recipients (CC and BCC take up to 50 each), with an HTML body, a plain-text body, both, or a stored template with variables, optionally scheduled for later. Returns the email (id, ids per recipient, status). Not idempotent: a repeat call sends again unless the same idempotency_key is given within 24 hours.',+ idempotent: false,+ },+ outputSchema: emailitSchemas.sentEmail,+ props: {+ to: emailitProps.recipientList({ displayName: 'To', description: 'Recipient addresses, up to 50.', required: true }),+ from_email: Property.ShortText({ displayName: 'Sender Email', description: 'Address on a verified sending domain of the workspace.', required: true }),+ from_name: Property.ShortText({ displayName: 'Sender Name', required: false }),+ subject: Property.ShortText({ displayName: 'Subject', description: 'Required unless template is set.', required: false }),+ html: Property.LongText({ displayName: 'HTML Body', required: false }),+ text: Property.LongText({ displayName: 'Plain-Text Body', required: false }),+ cc: emailitProps.recipientList({ displayName: 'CC', description: 'Up to 50.', required: false }),+ bcc: emailitProps.recipientList({ displayName: 'BCC', description: 'Up to 50.', required: false }),+ reply_to: emailitProps.recipientList({ displayName: 'Reply-To', description: 'Addresses for replies.', required: false }),+ template: Property.ShortText({ displayName: 'Template', description: 'Template ID (tem_…) or alias.', required: false }),+ variables: Property.Json({ displayName: 'Template Variables', description: 'JSON object of placeholder values.', required: false }),+ scheduled_at: Property.ShortText({ displayName: 'Send At', description: 'ISO 8601 date-time with time zone, e.g. 2026-10-02T09:00:00Z. Empty sends now.', required: false }),+ idempotency_key: emailitProps.idempotencyKey(),+ },+ async run({ auth, propsValue }) {+ const response = await emailitSend.send({+ auth,+ input: {+ to: propsValue.to,+ cc: propsValue.cc,+ bcc: propsValue.bcc,+ replyTo: propsValue.reply_to,+ fromName: propsValue.from_name,+ fromEmail: propsValue.from_email,+ subject: propsValue.subject,+ html: propsValue.html,+ text: propsValue.text,+ template: propsValue.template,+ variables: propsValue.variables,+ scheduledAt: propsValue.scheduled_at,+ idempotencyKey: propsValue.idempotency_key,+ },+ });+ return response.body;+ },+});diff --git a/packages/pieces/community/emailit/src/lib/actions/send-email.ts b/packages/pieces/community/emailit/src/lib/actions/send-email.tsindex c290fb9228d..2c05318fb54 100644--- a/packages/pieces/community/emailit/src/lib/actions/send-email.ts+++ b/packages/pieces/community/emailit/src/lib/actions/send-email.ts@@ -1,125 +1,103 @@-import { createAction, Property } from '@activepieces/pieces-framework'-import { HttpMethod, AuthenticationType, httpClient } from '@activepieces/pieces-common'-import { emailitAuth } from '../auth'+import { createAction, Property } from '@activepieces/pieces-framework';+import { emailitAuth } from '../auth';+import { emailitSchemas } from '../common/output-schemas';+import { emailitProps } from '../common/props';+import { emailitSend } from '../common/send';export const sendEmailAction = createAction({- auth: emailitAuth,- name: 'send_email',- classification: 'WRITE',- displayName: 'Send Email',- description: 'Send an email to one or more recipients via Emailit.',- audience: 'both',- aiMetadata: { description: 'Sends a transactional email through Emailit to one or more To recipients (with optional CC/BCC, reply-to, and custom headers). Choose this to deliver a message via Emailit; the body is sent as either plain text or HTML depending on the content type. The sender email must be verified in the Emailit account, and the combined To/CC/BCC list is capped at 50 addresses. Not idempotent: each call dispatches a new email.', idempotent: false },- props: {- to: Property.Array({- displayName: 'To',- description: 'Recipient email addresses. Up to 50 total across To, CC, and BCC.',- required: true,- }),- from_name: Property.ShortText({- displayName: 'Sender Name',- description: 'Name recipients will see in their inbox, e.g. "Acme Support". If left blank, only the email address is shown.',- required: false,- }),- from_email: Property.ShortText({- displayName: 'Sender Email',- description: 'Email address to send from. Must be verified in your Emailit account.',- required: true,- }),- cc: Property.Array({- displayName: 'CC',- description: 'Send a visible copy to these addresses.',- required: false,- }),- bcc: Property.Array({- displayName: 'BCC',- description: "Send a hidden copy to these addresses. Other recipients won't see them.",- required: false,- }),- reply_to: Property.ShortText({- displayName: 'Reply-To',- description: 'Where replies go. Defaults to the sender email if left blank.',- required: false,- }),- subject: Property.ShortText({- displayName: 'Subject',- description: "The subject line shown in the recipient's inbox.",- required: true,- }),- content_type: Property.StaticDropdown<'text' | 'html'>({- displayName: 'Content Type',- required: true,- defaultValue: 'html',- options: {- disabled: false,- options: [- { label: 'Plain Text', value: 'text' },- { label: 'HTML', value: 'html' },- ],- },- }),- content: Property.LongText({- displayName: 'Email Body',- description:- 'The message body. Use Plain Text for simple messages or HTML for rich formatting.',- required: true,- }),- headers: Property.Object({- displayName: 'Custom Headers',- description: 'Add custom email headers as key-value pairs, e.g. X-Campaign-ID: welcome.',- required: false,- }),- },- async run(context) {- const {- to,- from_name,- from_email,- cc,- bcc,- reply_to,- subject,- content_type,- content,- headers,- } = context.propsValue-- const requestBody: Record<string, unknown> = {- from: from_name ? `${from_name} <${from_email}>` : from_email,- to: to,- subject: subject,- }-- if (content_type === 'text') {- requestBody['text'] = content- } else {- requestBody['html'] = content- }-- if (cc && cc.length > 0) {- requestBody['cc'] = cc- }-- if (bcc && bcc.length > 0) {- requestBody['bcc'] = bcc- }-- if (reply_to) {- requestBody['reply_to'] = reply_to- }-- if (headers && Object.keys(headers).length > 0) {- requestBody['headers'] = headers- }-- return await httpClient.sendRequest({- method: HttpMethod.POST,- url: 'https://api.emailit.com/v2/emails',- body: requestBody,- authentication: {- type: AuthenticationType.BEARER_TOKEN,- token: context.auth.secret_text,- },- })- },-})+ auth: emailitAuth,+ name: 'send_email',+ classification: 'WRITE',+ displayName: 'Send Email',+ description: 'Send an email to one or more recipients via Emailit.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Sends a transactional email through Emailit from an address on a verified sending domain to up to 50 To recipients (each of CC and BCC also takes up to 50), as HTML or plain text or from a stored template, optionally scheduled. Returns the HTTP status, response headers and the email in body (body.id is the email ID). Not idempotent: a repeat call sends again unless the same Idempotency Key is given within 24 hours.',+ idempotent: false,+ },+ outputSchema: emailitSchemas.sendEmailLegacy,+ props: {+ to: emailitProps.recipientList({+ displayName: 'To',+ description: 'Recipient email addresses, e.g. [email protected] or Ada Lovelace <[email protected]>. Up to 50 here, and up to 50 each in CC and BCC.',+ required: true,+ }),+ from_name: Property.ShortText({+ displayName: 'Sender Name',+ description: 'Name recipients will see in their inbox, e.g. "Acme Support". If left blank, only the email address is shown.',+ required: false,+ }),+ from_email: Property.ShortText({+ displayName: 'Sender Email',+ description: 'Email address to send from. It must be on a verified sending domain of your Emailit workspace.',+ required: true,+ }),+ cc: emailitProps.recipientList({ displayName: 'CC', description: 'Send a visible copy to these addresses. Up to 50.', required: false }),+ bcc: emailitProps.recipientList({ displayName: 'BCC', description: "Send a hidden copy to these addresses. Other recipients won't see them. Up to 50.", required: false }),+ reply_to: Property.ShortText({+ displayName: 'Reply-To',+ description: 'Where replies go. Defaults to the sender email if left blank. Separate several addresses with commas.',+ required: false,+ }),+ subject: Property.ShortText({+ displayName: 'Subject',+ description: "The subject line shown in the recipient's inbox. Required unless you send a template.",+ required: false,+ }),+ content_type: Property.StaticDropdown<'text' | 'html'>({+ displayName: 'Content Type',+ required: true,+ defaultValue: 'html',+ options: {+ disabled: false,+ options: [+ { label: 'Plain Text', value: 'text' },+ { label: 'HTML', value: 'html' },+ ],+ },+ }),+ content: Property.LongText({+ displayName: 'Email Body',+ description: 'The message body. Use Plain Text for simple messages or HTML for rich formatting. Required unless you send a template.',+ required: false,+ }),+ plain_text: Property.LongText({+ displayName: 'Plain-Text Version',+ description: 'Optional, for HTML emails: a plain-text version sent alongside the HTML. Recommended for deliverability.',+ required: false,+ }),+ headers: Property.Object({+ displayName: 'Custom Headers',+ description: 'Add custom email headers as key-value pairs, e.g. X-Campaign-ID: welcome. Line breaks are not allowed.',+ required: false,+ }),+ ...emailitProps.sendingProps(),+ },+ async run({ auth, propsValue }) {+ const isText = propsValue.content_type === 'text';+ return emailitSend.send({+ auth,+ input: {+ to: propsValue.to,+ cc: propsValue.cc,+ bcc: propsValue.bcc,+ replyTo: propsValue.reply_to,+ fromName: propsValue.from_name,+ fromEmail: propsValue.from_email,+ subject: propsValue.subject,+ html: isText ? undefined : propsValue.content,+ text: isText ? propsValue.content : propsValue.plain_text,+ template: propsValue.template,+ variables: propsValue.variables,+ headers: propsValue.headers,+ meta: propsValue.meta,+ scheduledAt: propsValue.scheduled_at,+ tracking: propsValue.tracking,+ attachmentUrls: propsValue.attachments,+ attachmentFile: propsValue.attachment_file,+ idempotencyKey: propsValue.idempotency_key,+ },+ });+ },+});diff --git a/packages/pieces/community/emailit/src/lib/actions/update-subscriber.ts b/packages/pieces/community/emailit/src/lib/actions/update-subscriber.tsnew file mode 100644index 00000000000..ffac3872bda--- /dev/null+++ b/packages/pieces/community/emailit/src/lib/actions/update-subscriber.ts@@ -0,0 +1,58 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { emailitAuth } from '../auth';+import { emailitDropdowns } from '../common/dropdowns';+import { emailitOperations } from '../common/operations';+import { emailitSchemas } from '../common/output-schemas';+import { emailitProps } from '../common/props';++export const updateSubscriberAction = createAction({+ auth: emailitAuth,+ name: 'update_subscriber',+ displayName: 'Update Subscriber',+ description: 'Subscribe or unsubscribe someone from an audience, or change their name.',+ audience: 'human',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Updates one subscriber of an Emailit audience, found by subscriber ID (sub_…) or email address: turn Subscribed on or off for this audience (use this for opt-outs), or change first/last name (names belong to the contact, so they change everywhere). Only the fields given are sent. Repeating with the same values changes nothing. Needs a Full Access key.',+ idempotent: true,+ },+ outputSchema: emailitSchemas.subscriberUpdated,+ props: { audience: emailitDropdowns.audience(), ...fields() },+ async run({ auth, propsValue }) {+ return emailitOperations.updateSubscriber({ auth, input: { audience: propsValue.audience, subscriber: propsValue.subscriber, subscribed: propsValue.subscribed, firstName: propsValue.first_name, lastName: propsValue.last_name } });+ },+});++export const updateSubscriberByIdAction = createAction({+ auth: emailitAuth,+ name: 'update_subscriber_by_id',+ displayName: 'Update Subscriber (by ID)',+ description: 'Update a subscriber of an audience given by ID or name.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Updates one subscriber of an Emailit audience, found by subscriber ID (sub_…) or email address: turn Subscribed on or off for this audience (use this for opt-outs), or change first/last name (names belong to the contact, so they change everywhere). Only the fields given are sent. Repeating with the same values changes nothing. Needs a Full Access key. Get the audience ID from List Audiences first.',+ idempotent: true,+ },+ outputSchema: emailitSchemas.subscriberUpdated,+ props: { audience: emailitProps.audienceId(), ...fields() },+ async run({ auth, propsValue }) {+ return emailitOperations.updateSubscriber({ auth, input: { audience: propsValue.audience, subscriber: propsValue.subscriber, subscribed: propsValue.subscribed, firstName: propsValue.first_name, lastName: propsValue.last_name } });+ },+});++function fields() {+ return {+ subscriber: Property.ShortText({ displayName: 'Subscriber', description: 'Subscriber ID (sub_…) or email address.', required: true }),+ subscribed: Property.StaticDropdown<'keep' | 'yes' | 'no'>({+ displayName: 'Subscribed',+ required: false,+ defaultValue: 'keep',+ options: { disabled: false, options: [{ label: 'Keep as is', value: 'keep' }, { label: 'Subscribed', value: 'yes' }, { label: 'Unsubscribed', value: 'no' }] },+ }),+ first_name: Property.ShortText({ displayName: 'First Name', description: 'Leave empty to keep.', required: false }),+ last_name: Property.ShortText({ displayName: 'Last Name', description: 'Leave empty to keep.', required: false }),+ };+}diff --git a/packages/pieces/community/emailit/src/lib/actions/upsert-contact.ts b/packages/pieces/community/emailit/src/lib/actions/upsert-contact.tsnew file mode 100644index 00000000000..92d73faf7a3--- /dev/null+++ b/packages/pieces/community/emailit/src/lib/actions/upsert-contact.ts@@ -0,0 +1,65 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { emailitAuth } from '../auth';+import { emailitDropdowns } from '../common/dropdowns';+import { emailitOperations } from '../common/operations';+import { emailitSchemas } from '../common/output-schemas';++export const upsertContactAction = createAction({+ auth: emailitAuth,+ name: 'create_or_update_contact',+ displayName: 'Create or Update Contact',+ description: 'Create a contact, or update the existing contact with the same email.',+ audience: 'human',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Upserts an Emailit contact by email address: creates it (optionally subscribed to audiences) or updates names, custom fields (which replace all existing custom fields when given) and the campaign unsubscribed flag. On update, audiences given are added; existing memberships are kept. Returns the contact (id = con_…) with created=true/false. Running it again with the same input leaves the same contact. Use Find Contact to read it later. Needs a Full Access key.',+ idempotent: true,+ },+ outputSchema: emailitSchemas.contactUpsert,+ props: { ...fields(), audiences: emailitDropdowns.audiences(), unsubscribed: unsubscribedProp() },+ async run({ auth, propsValue }) {+ return emailitOperations.upsertContact({ auth, input: { email: propsValue.email, firstName: propsValue.first_name, lastName: propsValue.last_name, customFields: propsValue.custom_fields, audiences: propsValue.audiences, unsubscribed: propsValue.unsubscribed } });+ },+});++export const upsertContactByIdAction = createAction({+ auth: emailitAuth,+ name: 'create_or_update_contact_by_id',+ displayName: 'Create or Update Contact (by Audience ID)',+ description: 'Create or update a contact, adding it to audiences given by ID.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Upserts an Emailit contact by email address: creates it (optionally subscribed to audiences) or updates names, custom fields (which replace all existing custom fields when given) and the campaign unsubscribed flag. On update, audiences given are added; existing memberships are kept. Returns the contact (id = con_…) with created=true/false. Running it again with the same input leaves the same contact. Use Find Contact to read it later. Needs a Full Access key. Audience IDs (aud_…) come from List Audiences.',+ idempotent: true,+ },+ outputSchema: emailitSchemas.contactUpsert,+ props: {+ ...fields(),+ audiences: Property.Array({ displayName: 'Add to Audiences', description: 'Audience IDs (aud_…) to subscribe the contact to.', required: false }),+ unsubscribed: unsubscribedProp(),+ },+ async run({ auth, propsValue }) {+ return emailitOperations.upsertContact({ auth, input: { email: propsValue.email, firstName: propsValue.first_name, lastName: propsValue.last_name, customFields: propsValue.custom_fields, audiences: propsValue.audiences, unsubscribed: propsValue.unsubscribed } });+ },+});++function fields() {+ return {+ email: Property.ShortText({ displayName: 'Email', required: true }),+ first_name: Property.ShortText({ displayName: 'First Name', description: 'Leave empty to keep.', required: false }),+ last_name: Property.ShortText({ displayName: 'Last Name', description: 'Leave empty to keep.', required: false }),+ custom_fields: Property.Object({ displayName: 'Custom Fields', description: 'Replaces all custom fields of an existing contact. Leave empty to keep.', required: false }),+ };+}++function unsubscribedProp() {+ return Property.StaticDropdown<'keep' | 'yes' | 'no'>({+ displayName: 'Unsubscribed from Campaigns',+ required: false,+ defaultValue: 'keep',+ options: { disabled: false, options: [{ label: 'Keep as is (new contacts: subscribed)', value: 'keep' }, { label: 'Unsubscribed', value: 'yes' }, { label: 'Subscribed', value: 'no' }] },+ });+}diff --git a/packages/pieces/community/emailit/src/lib/actions/verify-domain.ts b/packages/pieces/community/emailit/src/lib/actions/verify-domain.tsnew file mode 100644index 00000000000..c85fc4f5ef5--- /dev/null+++ b/packages/pieces/community/emailit/src/lib/actions/verify-domain.ts@@ -0,0 +1,43 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { emailitAuth } from '../auth';+import { emailitDropdowns } from '../common/dropdowns';+import { emailitOperations } from '../common/operations';+import { emailitSchemas } from '../common/output-schemas';++export const verifyDomainAction = createAction({+ auth: emailitAuth,+ name: 'verify_domain',+ displayName: 'Check Domain Verification',+ description: 'Re-check a sending domain\'s DNS records now and update its verification status.',+ audience: 'human',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Makes Emailit look up a sending domain\'s DNS records now and save the result, then returns the domain with fresh statuses. The domain becomes verified when SPF, DKIM and return-path are ok; any failing record shows in dns_records with its error. It changes no DNS; repeating it only re-checks. Needs a Full Access key.',+ idempotent: true,+ },+ outputSchema: emailitSchemas.domain,+ props: { domain: emailitDropdowns.domain() },+ async run({ auth, propsValue }) {+ return emailitOperations.verifyDomain({ auth, domain: propsValue.domain });+ },+});++export const verifyDomainByIdAction = createAction({+ auth: emailitAuth,+ name: 'verify_domain_by_id',+ displayName: 'Check Domain Verification (by ID)',+ description: 'Re-check a sending domain given by ID or name.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Makes Emailit look up a sending domain\'s DNS records now and save the result, then returns the domain with fresh statuses. The domain becomes verified when SPF, DKIM and return-path are ok; any failing record shows in dns_records with its error. It changes no DNS; repeating it only re-checks. Needs a Full Access key. Takes the domain ID (dom_…) or name; List Sending Domains finds them.',+ idempotent: true,+ },+ outputSchema: emailitSchemas.domain,+ props: { domain: Property.ShortText({ displayName: 'Domain', description: 'Domain ID (dom_…) or domain name.', required: true }) },+ async run({ auth, propsValue }) {+ return emailitOperations.verifyDomain({ auth, domain: propsValue.domain });+ },+});diff --git a/packages/pieces/community/emailit/src/lib/actions/verify-email-address.ts b/packages/pieces/community/emailit/src/lib/actions/verify-email-address.tsnew file mode 100644index 00000000000..b8860e36142--- /dev/null+++ b/packages/pieces/community/emailit/src/lib/actions/verify-email-address.ts@@ -0,0 +1,41 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { emailitAuth } from '../auth';+import { emailitClient } from '../common/client';+import { emailitSchemas } from '../common/output-schemas';+import { emailitValues } from '../common/values';++export const verifyEmailAddressAction = createAction({+ auth: emailitAuth,+ name: 'verify_email_address',+ displayName: 'Verify Email Address',+ description: 'Check whether an address is valid and safe to send to. Costs 5 credits per check.',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Checks one email address with Emailit and returns result (safe, invalid, disposable, disabled, inbox_full, role, unknown), risk, a 0-100 score, individual checks and a did_you_mean typo suggestion. Fast mode checks syntax, domain and MX; full mode also asks the mailbox server. Each call is charged 5 credits, even for invalid input. Needs a Full Access key.',+ idempotent: false,+ },+ outputSchema: emailitSchemas.verification,+ props: {+ email: Property.ShortText({ displayName: 'Email', required: true }),+ mode: Property.StaticDropdown<'fast' | 'full'>({+ displayName: 'Mode',+ required: false,+ defaultValue: 'fast',+ options: { disabled: false, options: [{ label: 'Fast (syntax, domain, MX)', value: 'fast' }, { label: 'Full (also checks the mailbox)', value: 'full' }] },+ }),+ },+ async run({ auth, propsValue }) {+ const body = await emailitClient.request({+ auth,+ method: HttpMethod.POST,+ path: '/email-verifications',+ body: { email: emailitValues.requiredText({ value: propsValue.email, label: 'Email' }), mode: propsValue.mode ?? 'fast' },+ redactBody: true,+ });+ if (emailitClient.isRecord(body) && emailitClient.isRecord(body['data'])) return body['data'];+ return body;+ },+});diff --git a/packages/pieces/community/emailit/src/lib/auth.ts b/packages/pieces/community/emailit/src/lib/auth.tsindex 7436f9f3419..bca817af053 100644--- a/packages/pieces/community/emailit/src/lib/auth.ts+++ b/packages/pieces/community/emailit/src/lib/auth.ts@@ -1,27 +1,33 @@-import { PieceAuth } from '@activepieces/pieces-framework'-import { httpClient, HttpMethod, AuthenticationType } from '@activepieces/pieces-common'+import { HttpMethod } from '@activepieces/pieces-common';+import { PieceAuth } from '@activepieces/pieces-framework';+import { EmailitApiError, emailitClient } from './common/client';export const emailitAuth = PieceAuth.SecretText({- displayName: 'API Key',- description:- `Get your API key from your [Emailit Workspace Settings](https://app.emailit.com/settings/api-keys).`,- required: true,- validate: async ({ auth }) => {- try {- await httpClient.sendRequest({- method: HttpMethod.GET,- url: 'https://api.emailit.com/v2/domains',- authentication: {- type: AuthenticationType.BEARER_TOKEN,- token: auth,- },- })- return { valid: true }- } catch {- return {- valid: false,- error: 'Invalid API key. Please check your Emailit Workspace Settings.',- }- }- },-})+ displayName: 'API Key',+ description:+ 'Get your API key from your [Emailit Workspace Settings](https://app.emailit.com/settings/api-keys). A **Full Access** key works with every action. A **Sending Only** key can send, reschedule, cancel, retry and forward emails, but not read emails or manage domains, audiences, contacts or suppressions.',+ required: true,+ validate: async ({ auth }) => {+ try {+ await emailitClient.request({ auth, method: HttpMethod.GET, path: '/domains', query: { limit: 1 } });+ return { valid: true };+ } catch (error) {+ if (error instanceof EmailitApiError && error.status === 401) {+ return { valid: false, error: 'Invalid API key. Please check your Emailit Workspace Settings.' };+ }+ if (error instanceof EmailitApiError && error.status === 403 && isScopeDenied(error.responseBody)) {+ return { valid: true };+ }+ return {+ valid: false,+ error: error instanceof Error ? `Could not reach Emailit to check the key: ${error.message}` : 'Could not reach Emailit to check the key.',+ };+ }+ },+});++function isScopeDenied(body: unknown): boolean {+ if (body === null || typeof body !== 'object') return false;+ const message = Reflect.get(body, 'message');+ return typeof message === 'string' && message.toLowerCase().includes('permission denied');+}diff --git a/packages/pieces/community/emailit/src/lib/common/client.ts b/packages/pieces/community/emailit/src/lib/common/client.tsnew file mode 100644index 00000000000..40abcc432bb--- /dev/null+++ b/packages/pieces/community/emailit/src/lib/common/client.ts@@ -0,0 +1,272 @@+import { httpClient, HttpMethod, HttpResponse, QueryParams } from '@activepieces/pieces-common';++export const EMAILIT_API_BASE = 'https://api.emailit.com/v2';+const REQUEST_TIMEOUT_MS = 30_000;+const MAX_RETRIES_ON_429 = 2;+const MAX_RETRY_WAIT_MS = 10_000;+let verifiedTlsAgent: Promise<unknown> | undefined;++export class EmailitApiError extends Error {+ constructor(+ message: string,+ public readonly status: number,+ public readonly responseBody: unknown,+ ) {+ super(message);+ this.name = 'EmailitApiError';+ }+}++function apiKeyOf(auth: EmailitAuthInput): string {+ const raw = typeof auth === 'string' ? auth : auth?.secret_text;+ const key = typeof raw === 'string' ? raw.trim() : '';+ if (!key) {+ throw new Error('The Emailit connection has no API key.');+ }+ return key;+}++function toText(value: unknown): string {+ if (typeof value === 'number' && Number.isFinite(value)) {+ return String(value);+ }+ return typeof value === 'string' ? value.trim() : '';+}++function seg({ value, label }: { value: unknown; label: string }): string {+ const text = toText(value);+ if (text === '' || text === '.' || text === '..') {+ throw new Error(`${label} is required.`);+ }+ return encodeURIComponent(text);+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}++function stringField({ record, key }: { record: Record<string, unknown>; key: string }): string {+ const value = record[key];+ return typeof value === 'string' ? value.trim() : '';+}++function validationDetails(body: Record<string, unknown>): string {+ const list = body['validation_errors'] ?? body['details'] ?? body['errors'];+ if (Array.isArray(list)) {+ return list+ .slice(0, 10)+ .map((item) => {+ if (typeof item === 'string') return item;+ if (isRecord(item)) {+ const where = stringField({ record: item, key: 'instancePath' }) || stringField({ record: item, key: 'field' });+ const what = stringField({ record: item, key: 'message' });+ return where ? `${where}: ${what}` : what;+ }+ return '';+ })+ .filter((text) => text !== '')+ .join('; ');+ }+ if (isRecord(list)) {+ return Object.entries(list)+ .slice(0, 10)+ .map(([field, value]) => `${field}: ${Array.isArray(value) ? value.join(', ') : String(value)}`)+ .join('; ');+ }+ return '';+}++function vendorMessage(responseBody: unknown): string {+ if (isRecord(responseBody)) {+ const error = responseBody['error'];+ const nested = isRecord(error) ? stringField({ record: error, key: 'message' }) : '';+ const message = stringField({ record: responseBody, key: 'message' }) || nested;+ const errorText = typeof error === 'string' ? error.trim() : '';+ const head = message && errorText && !message.includes(errorText) ? `${errorText}: ${message}` : message || errorText;+ const details = validationDetails(responseBody);+ const text = details ? `${head || 'Validation failed'} (${details})` : head;+ if (text) {+ return text;+ }+ }+ if (typeof responseBody === 'string' && responseBody.trim()) {+ return responseBody.trim().slice(0, 300);+ }+ return 'request failed';+}++function hintFor({ status, responseBody }: { status: number; responseBody: unknown }): string {+ const code = isRecord(responseBody) ? stringField({ record: responseBody, key: 'code' }) || stringField({ record: responseBody, key: 'error' }) : '';+ const message = vendorMessage(responseBody).toLowerCase();+ if (status === 401) return ' Check the API key in the Emailit connection.';+ if (status === 402) return ' The Emailit workspace is out of credits.';+ if (status === 403 && (code === 'unverified_workspace_recipient' || message.includes('workspace not verified'))) {+ return ' The workspace is in sandbox mode: it can only send to its members\' account emails until Emailit grants production access.';+ }+ if (status === 403 && code === 'plan_required') return ' This feature needs a higher Emailit plan.';+ if (status === 403 && message.includes('permission denied')) {+ return ' This API key is Sending Only. Use a Full Access key for this action.';+ }+ if (status === 429) return ' Emailit rate limit reached; try again later.';+ return '';+}++function toApiError({ status, responseBody }: { status: number; responseBody: unknown }): EmailitApiError {+ const base = status >= 300 && status < 400 ? 'unexpected redirect' : vendorMessage(responseBody);+ return new EmailitApiError(`Emailit API error (${status}): ${base}.${hintFor({ status, responseBody })}`.replace('..', '.'), status, responseBody);+}++function buildQuery(query?: Record<string, QueryValue>): QueryParams {+ return Object.fromEntries(+ Object.entries(query ?? {})+ .filter(([, value]) => value !== undefined && value !== null && value !== '')+ .map(([key, value]) => [key, String(value)]),+ );+}++function headerValue({ headers, name }: { headers: unknown; name: string }): string | null {+ if (!isRecord(headers)) return null;+ const value = headers[name];+ if (Array.isArray(value)) return typeof value[0] === 'string' ? value[0] : null;+ return typeof value === 'string' ? value : null;+}++function retryDelayMs({ response, attempt }: { response: RawResponse; attempt: number }): number | null {+ const header = headerValue({ headers: response.headers, name: 'retry-after' });+ const bodyValue = isRecord(response.body) ? response.body['retry_after'] : undefined;+ const raw = header ?? (typeof bodyValue === 'number' || typeof bodyValue === 'string' ? String(bodyValue) : '');+ const seconds = /^\d+(\.\d+)?$/.test(raw.trim()) ? Number(raw.trim()) : NaN;+ const wait = Number.isFinite(seconds) ? seconds * 1000 : 1000 * 2 ** attempt;+ return wait > MAX_RETRY_WAIT_MS ? null : wait;+}++function verifiedTls(): Promise<unknown> {+ verifiedTlsAgent ??= import('undici').then(({ Agent }) => new Agent({ connect: { rejectUnauthorized: true } }));+ return verifiedTlsAgent;+}++function failureOf(error: unknown): RawResponse | null {+ if (error === null || typeof error !== 'object') return null;+ const response = Reflect.get(error, 'response');+ if (!isRecord(response)) return null;+ const status = response['status'];+ return typeof status === 'number' ? { status, body: response['body'], headers: isRecord(response['headers']) ? response['headers'] : {} } : null;+}++async function sendOnce(request: EmailitRequest): Promise<RawResponse> {+ const dispatcher = await verifiedTls();+ const hasBody = request.body !== undefined && request.method !== HttpMethod.GET && request.method !== HttpMethod.DELETE;+ const headers: Record<string, string> = {+ authorization: `Bearer ${apiKeyOf(request.auth)}`,+ accept: 'application/json',+ };+ if (hasBody) headers['content-type'] = 'application/json';+ if (request.idempotencyKey) headers['idempotency-key'] = request.idempotencyKey;+ try {+ const response: HttpResponse = await httpClient.sendRequest(+ {+ method: request.method,+ url: `${EMAILIT_API_BASE}${request.path}`,+ headers,+ queryParams: buildQuery(request.query),+ body: hasBody ? request.body : undefined,+ timeout: REQUEST_TIMEOUT_MS,+ followRedirects: false,+ redactBodyInErrors: request.redactBody === true,+ },+ { dispatcher },+ );+ return { status: response.status, body: response.body, headers: isRecord(response.headers) ? response.headers : {} };+ } catch (error) {+ const failure = failureOf(error);+ if (failure) return failure;+ throw error;+ }+}++async function send(request: EmailitRequest): Promise<RawResponse> {+ const retryable = request.method === HttpMethod.GET || request.idempotencyKey !== undefined || request.safeToRetry === true;+ for (let attempt = 0; ; attempt++) {+ const response = await sendOnce(request);+ const delay = response.status === 429 && retryable && attempt < MAX_RETRIES_ON_429+ ? retryDelayMs({ response, attempt })+ : null;+ if (delay !== null) {+ await new Promise((resolve) => setTimeout(resolve, delay));+ continue;+ }+ if (response.status < 200 || response.status >= 300) {+ throw toApiError({ status: response.status, responseBody: response.body });+ }+ return response;+ }+}++async function request(req: EmailitRequest): Promise<unknown> {+ const response = await send(req);+ return response.body;+}++function statusOf(error: unknown): number | undefined {+ return error instanceof EmailitApiError ? error.status : undefined;+}++function rethrowWithHint({ error, hints }: { error: unknown; hints: Partial<Record<number, string>> }): never {+ const status = statusOf(error);+ const hint = status !== undefined ? hints[status] : undefined;+ if (hint && error instanceof EmailitApiError && !error.message.toLowerCase().includes(hint.replace(/\.$/, '').toLowerCase())) {+ throw new EmailitApiError(`${hint} ${error.message}`, error.status, error.responseBody);+ }+ throw error;+}++function clampLimit(value: unknown): number {+ const fallback = 25;+ const parsed = typeof value === 'string' ? Number(value) : value;+ if (parsed === undefined || parsed === null || parsed === '') return fallback;+ if (typeof parsed !== 'number' || !Number.isInteger(parsed) || parsed < 1 || parsed > 100) {+ throw new Error('Limit must be a whole number from 1 to 100.');+ }+ return parsed;+}++function page(value: unknown): number {+ const parsed = typeof value === 'string' ? Number(value) : value;+ if (parsed === undefined || parsed === null || parsed === '') return 1;+ if (typeof parsed !== 'number' || !Number.isInteger(parsed) || parsed < 1) {+ throw new Error('Page must be a whole number of 1 or more.');+ }+ return parsed;+}++function listPage(body: unknown): { items: unknown[]; hasMore: boolean; totalRecords: number | null } {+ const record = isRecord(body) ? body : {};+ const items = Array.isArray(record['data']) ? record['data'] : [];+ const next = record['next_page_url'];+ const currentPage = record['current_page'];+ const totalPages = record['total_pages'];+ const hasMore =+ typeof next === 'string' && next !== ''+ ? true+ : typeof currentPage === 'number' && typeof totalPages === 'number'+ ? currentPage < totalPages+ : false;+ const total = record['total_records'];+ return { items, hasMore, totalRecords: typeof total === 'number' ? total : null };+}++export const emailitClient = { request, send, seg, isRecord, rethrowWithHint, statusOf, clampLimit, page, listPage, apiKeyOf, toApiError };++type QueryValue = string | number | boolean | undefined | null;+export type EmailitAuthInput = string | { secret_text: string } | undefined;+type RawResponse = { status: number; body: unknown; headers: Record<string, unknown> };+export type EmailitRequest = {+ auth: EmailitAuthInput;+ method: HttpMethod;+ path: string;+ query?: Record<string, QueryValue>;+ body?: unknown;+ idempotencyKey?: string;+ redactBody?: boolean;+ safeToRetry?: boolean;+};diff --git a/packages/pieces/community/emailit/src/lib/common/dropdowns.ts b/packages/pieces/community/emailit/src/lib/common/dropdowns.tsnew file mode 100644index 00000000000..2e4eedbda30--- /dev/null+++ b/packages/pieces/community/emailit/src/lib/common/dropdowns.ts@@ -0,0 +1,88 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property } from '@activepieces/pieces-framework';+import { emailitAuth } from '../auth';+import { EmailitAuthInput, emailitClient } from './client';++const PAGE_SIZE = 100;+const MAX_PAGES = 20;++async function listAll({ auth, path }: { auth: EmailitAuthInput; path: string }): Promise<{ items: Record<string, unknown>[]; truncated: boolean }> {+ const items: Record<string, unknown>[] = [];+ for (let page = 1; page <= MAX_PAGES; page++) {+ const body = await emailitClient.request({ auth, method: HttpMethod.GET, path, query: { limit: PAGE_SIZE, page } });+ const result = emailitClient.listPage(body);+ items.push(...result.items.filter(emailitClient.isRecord));+ if (!result.hasMore || result.items.length === 0) {+ return { items, truncated: false };+ }+ }+ return { items, truncated: true };+}++async function options({ auth, path, label }: { auth: EmailitAuthInput | undefined; path: string; label: (item: Record<string, unknown>) => string }): Promise<DropdownState> {+ if (!auth) {+ return { disabled: true, options: [], placeholder: 'Connect your Emailit account first' };+ }+ try {+ const { items, truncated } = await listAll({ auth, path });+ const choices = items+ .filter((item) => typeof item['id'] === 'string')+ .map((item) => ({ label: label(item), value: String(item['id']) }));+ return {+ disabled: false,+ options: choices,+ placeholder: choices.length === 0 ? 'Nothing found in this workspace' : truncated ? `Showing the first ${choices.length}` : 'Select one',+ };+ } catch (error) {+ return { disabled: true, options: [], placeholder: `Could not load the list: ${error instanceof Error ? error.message : 'unknown error'}` };+ }+}++function audienceLabel(item: Record<string, unknown>): string {+ const name = typeof item['name'] === 'string' && item['name'].trim() !== '' ? item['name'] : '(unnamed audience)';+ const count = typeof item['subscribers_count'] === 'number' ? ` (${item['subscribers_count']} subscribers)` : '';+ return `${name}${count}`;+}++function domainLabel(item: Record<string, unknown>): string {+ const name = typeof item['name'] === 'string' ? item['name'] : String(item['id']);+ const status = typeof item['verification_status'] === 'string' ? ` (${item['verification_status']})` : '';+ return `${name}${status}`;+}++function audience() {+ return Property.Dropdown({+ auth: emailitAuth,+ displayName: 'Audience',+ description: 'The audience (subscriber list).',+ required: true,+ refreshers: ['auth'],+ options: async ({ auth }) => options({ auth, path: '/audiences', label: audienceLabel }),+ });+}++function audiences() {+ return Property.MultiSelectDropdown({+ auth: emailitAuth,+ displayName: 'Add to Audiences',+ description: 'Audiences to subscribe the contact to. Existing memberships are kept.',+ required: false,+ refreshers: ['auth'],+ options: async ({ auth }) => options({ auth, path: '/audiences', label: audienceLabel }),+ });+}++function domain() {+ return Property.Dropdown({+ auth: emailitAuth,+ displayName: 'Domain',+ description: 'The sending domain.',+ required: true,+ refreshers: ['auth'],+ options: async ({ auth }) => options({ auth, path: '/domains', label: domainLabel }),+ });+}++export const emailitDropdowns = { audience, audiences, domain, listAll };++type DropdownState = { disabled: boolean; options: { label: string; value: string }[]; placeholder: string };diff --git a/packages/pieces/community/emailit/src/lib/common/operations.ts b/packages/pieces/community/emailit/src/lib/common/operations.tsnew file mode 100644index 00000000000..25e1556ef32--- /dev/null+++ b/packages/pieces/community/emailit/src/lib/common/operations.ts@@ -0,0 +1,193 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { EmailitApiError, EmailitAuthInput, emailitClient } from './client';+import { emailitValues } from './values';++async function addSubscriber({ auth, input }: { auth: EmailitAuthInput; input: SubscriberInput }): Promise<Record<string, unknown>> {+ const body = emailitValues.compact({+ email: emailitValues.requiredText({ value: input.email, label: 'Email' }),+ first_name: emailitValues.optionalText(input.firstName),+ last_name: emailitValues.optionalText(input.lastName),+ custom_fields: emailitValues.objectInput({ value: input.customFields, label: 'Custom Fields' }),+ });+ const audience = emailitClient.seg({ value: input.audience, label: 'Audience' });+ try {+ const created = await emailitClient.request({ auth, method: HttpMethod.POST, path: `/audiences/${audience}/subscribers`, body, redactBody: true, safeToRetry: true });+ return { ...record(created), alreadySubscribed: false };+ } catch (error) {+ if (error instanceof EmailitApiError && error.status === 409) {+ const existing = emailitClient.isRecord(error.responseBody) ? error.responseBody['existing'] : undefined;+ if (emailitClient.isRecord(existing) && typeof existing['id'] === 'string') {+ return { ...existing, alreadySubscribed: true };+ }+ const current = await emailitClient.request({+ auth,+ method: HttpMethod.GET,+ path: `/audiences/${audience}/subscribers/${emailitClient.seg({ value: body['email'], label: 'Email' })}`,+ });+ return { ...record(current), alreadySubscribed: true };+ }+ return emailitClient.rethrowWithHint({ error, hints: { 404: 'Audience not found.', 422: 'The audience is at your plan\'s subscriber limit.' } });+ }+}++async function updateSubscriber({ auth, input }: { auth: EmailitAuthInput; input: SubscriberUpdateInput }): Promise<unknown> {+ const body = emailitValues.compact({+ subscribed: input.subscribed === 'yes' ? true : input.subscribed === 'no' ? false : undefined,+ first_name: emailitValues.optionalText(input.firstName),+ last_name: emailitValues.optionalText(input.lastName),+ });+ if (Object.keys(body).length === 0) {+ throw new Error('Choose at least one change: Subscribed, First Name or Last Name.');+ }+ try {+ return await emailitClient.request({+ auth,+ method: HttpMethod.POST,+ path: `/audiences/${emailitClient.seg({ value: input.audience, label: 'Audience' })}/subscribers/${emailitClient.seg({ value: input.subscriber, label: 'Subscriber' })}`,+ body,+ redactBody: true,+ safeToRetry: true,+ });+ } catch (error) {+ return emailitClient.rethrowWithHint({ error, hints: { 404: 'Audience or subscriber not found.' } });+ }+}++async function removeSubscriber({ auth, input }: { auth: EmailitAuthInput; input: { audience: unknown; subscriber: unknown } }): Promise<Record<string, unknown>> {+ const audience = emailitClient.seg({ value: input.audience, label: 'Audience' });+ const subscriber = emailitClient.seg({ value: input.subscriber, label: 'Subscriber' });+ try {+ const body = await emailitClient.request({ auth, method: HttpMethod.DELETE, path: `/audiences/${audience}/subscribers/${subscriber}`, safeToRetry: true });+ return { ...record(body), deleted: true, alreadyRemoved: false };+ } catch (error) {+ if (emailitClient.statusOf(error) === 404 && (await audienceExists({ auth, audience }))) {+ return { id: decodeURIComponent(subscriber), deleted: false, alreadyRemoved: true };+ }+ return emailitClient.rethrowWithHint({ error, hints: { 404: 'Audience not found.' } });+ }+}++async function upsertContact({ auth, input }: { auth: EmailitAuthInput; input: ContactInput }): Promise<Record<string, unknown>> {+ const email = emailitValues.requiredText({ value: input.email, label: 'Email' });+ const audiences = (Array.isArray(input.audiences) ? input.audiences : [])+ .map((item) => (typeof item === 'string' ? item.trim() : ''))+ .filter((item) => item !== '');+ const fields = emailitValues.compact({+ first_name: emailitValues.optionalText(input.firstName),+ last_name: emailitValues.optionalText(input.lastName),+ custom_fields: emailitValues.objectInput({ value: input.customFields, label: 'Custom Fields' }),+ unsubscribed: input.unsubscribed === 'yes' ? true : input.unsubscribed === 'no' ? false : undefined,+ });+ const existing = await lookupContact({ auth, email });+ if (existing === null) {+ try {+ const created = await emailitClient.request({+ auth,+ method: HttpMethod.POST,+ path: '/contacts',+ body: { email, ...fields, ...(audiences.length > 0 ? { audiences } : {}) },+ redactBody: true,+ });+ return { ...record(created), created: true };+ } catch (error) {+ if (!(error instanceof EmailitApiError && error.status === 409)) throw error;+ }+ }+ const current = existing ?? (await lookupContact({ auth, email }));+ const id = current && typeof current['id'] === 'string' ? current['id'] : email;+ const currentAudiences = Array.isArray(current?.['audiences'])+ ? current['audiences'].flatMap((item) => (emailitClient.isRecord(item) && typeof item['id'] === 'string' ? [item['id']] : []))+ : [];+ const merged = [...new Set([...currentAudiences, ...audiences])];+ const update = { ...fields, ...(merged.length > currentAudiences.length ? { audiences: merged } : {}) };+ if (Object.keys(update).length === 0) {+ return { ...(current ?? {}), created: false };+ }+ const updated = await emailitClient.request({+ auth,+ method: HttpMethod.POST,+ path: `/contacts/${emailitClient.seg({ value: id, label: 'Contact' })}`,+ body: update,+ redactBody: true,+ safeToRetry: true,+ });+ return { ...record(updated), created: false };+}++async function getDomain({ auth, domain }: { auth: EmailitAuthInput; domain: unknown }): Promise<unknown> {+ try {+ return await emailitClient.request({ auth, method: HttpMethod.GET, path: `/domains/${emailitClient.seg({ value: domain, label: 'Domain' })}` });+ } catch (error) {+ return emailitClient.rethrowWithHint({ error, hints: { 404: 'Domain not found in this workspace.' } });+ }+}++async function verifyDomain({ auth, domain }: { auth: EmailitAuthInput; domain: unknown }): Promise<unknown> {+ try {+ return await emailitClient.request({+ auth,+ method: HttpMethod.POST,+ path: `/domains/${emailitClient.seg({ value: domain, label: 'Domain' })}/verify`,+ safeToRetry: true,+ });+ } catch (error) {+ return emailitClient.rethrowWithHint({ error, hints: { 404: 'Domain not found in this workspace.' } });+ }+}++async function cancelEmail({ auth, emailId }: { auth: EmailitAuthInput; emailId: unknown }): Promise<Record<string, unknown>> {+ const id = emailitClient.seg({ value: emailId, label: 'Email ID' });+ try {+ const body = await emailitClient.request({ auth, method: HttpMethod.POST, path: `/emails/${id}/cancel`, safeToRetry: true });+ return { ...record(body), alreadyCanceled: false };+ } catch (error) {+ if (emailitClient.statusOf(error) === 422 && (await emailStatus({ auth, id })) === 'canceled') {+ return { id: decodeURIComponent(id), status: 'canceled', in_flight: false, alreadyCanceled: true, message: 'The email was already canceled.' };+ }+ return emailitClient.rethrowWithHint({+ error,+ hints: { 404: 'Email not found.', 422: 'The email can no longer be canceled (already sent, failed, or due within 3 minutes).' },+ });+ }+}++async function emailStatus({ auth, id }: { auth: EmailitAuthInput; id: string }): Promise<string | undefined> {+ try {+ const body = await emailitClient.request({ auth, method: HttpMethod.GET, path: `/email/${id}` });+ const status = emailitClient.isRecord(body) ? body['status'] : undefined;+ return typeof status === 'string' ? status : undefined;+ } catch (error) {+ if (emailitClient.statusOf(error) === 403 || emailitClient.statusOf(error) === 404) return undefined;+ throw error;+ }+}++async function audienceExists({ auth, audience }: { auth: EmailitAuthInput; audience: string }): Promise<boolean> {+ try {+ await emailitClient.request({ auth, method: HttpMethod.GET, path: `/audiences/${audience}` });+ return true;+ } catch (error) {+ if (emailitClient.statusOf(error) === 404) return false;+ throw error;+ }+}++async function lookupContact({ auth, email }: { auth: EmailitAuthInput; email: string }): Promise<Record<string, unknown> | null> {+ try {+ const body = await emailitClient.request({ auth, method: HttpMethod.GET, path: `/contacts/${emailitClient.seg({ value: email, label: 'Email' })}` });+ return emailitClient.isRecord(body) ? body : null;+ } catch (error) {+ if (emailitClient.statusOf(error) === 404) return null;+ throw error;+ }+}++function record(value: unknown): Record<string, unknown> {+ return emailitClient.isRecord(value) ? value : {};+}++export const emailitOperations = { cancelEmail, addSubscriber, updateSubscriber, removeSubscriber, upsertContact, getDomain, verifyDomain };++type SubscriberInput = { audience: unknown; email: unknown; firstName?: unknown; lastName?: unknown; customFields?: unknown };+type SubscriberUpdateInput = { audience: unknown; subscriber: unknown; subscribed?: unknown; firstName?: unknown; lastName?: unknown };+type ContactInput = { email: unknown; firstName?: unknown; lastName?: unknown; customFields?: unknown; audiences?: unknown; unsubscribed?: unknown };diff --git a/packages/pieces/community/emailit/src/lib/common/output-schemas.ts b/packages/pieces/community/emailit/src/lib/common/output-schemas.tsnew file mode 100644index 00000000000..0c02d0d2c60--- /dev/null+++ b/packages/pieces/community/emailit/src/lib/common/output-schemas.ts@@ -0,0 +1,312 @@+import { OutputSchema } from '@activepieces/pieces-framework';++type Fields = OutputSchema['fields'];++const trackingFields: Fields = [+ { key: 'loads', label: 'Open Tracking', format: 'boolean' },+ { key: 'clicks', label: 'Click Tracking', format: 'boolean' },+];++const sentEmailFields: Fields = [+ { key: 'id', label: 'Email ID', description: 'ID of the first recipient\'s copy. Pass it as Email ID to other Emailit steps.' },+ { key: 'ids', label: 'Email IDs by Recipient', description: 'Recipient address to email ID. Only present with more than one recipient.', dynamicKey: true },+ { key: 'object', label: 'Object' },+ { key: 'message_id', label: 'Message-ID Header' },+ { key: 'from', label: 'From' },+ { key: 'to', label: 'To' },+ { key: 'cc', label: 'CC' },+ { key: 'bcc', label: 'BCC' },+ { key: 'subject', label: 'Subject' },+ { key: 'status', label: 'Status', description: 'accepted, or scheduled for a future send time.' },+ { key: 'scheduled_at', label: 'Scheduled At', format: 'datetime' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'tracking', label: 'Tracking', children: trackingFields },+];++const emailSummaryFields: Fields = [+ { key: 'id', label: 'Email ID' },+ { key: 'type', label: 'Type', description: 'outbound or inbound.' },+ { key: 'from', label: 'From' },+ { key: 'to', label: 'To' },+ { key: 'subject', label: 'Subject' },+ { key: 'status', label: 'Status' },+ { key: 'size', label: 'Size', format: 'filesize' },+ { key: 'scheduled_at', label: 'Scheduled At', format: 'datetime' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },+ { key: 'meta', label: 'Metadata', dynamicKey: true },+];++const domainSummaryFields: Fields = [+ { key: 'id', label: 'Domain ID' },+ { key: 'name', label: 'Domain Name' },+ { key: 'verification_status', label: 'Verification Status', description: 'verified, pending or pending_review.' },+ { key: 'verified_at', label: 'Verified At', format: 'datetime' },+ { key: 'spf_status', label: 'SPF Status' },+ { key: 'dkim_status', label: 'DKIM Status' },+ { key: 'return_path_status', label: 'Return Path Status' },+ { key: 'dmarc_status', label: 'DMARC Status' },+ { key: 'tracking_status', label: 'Tracking Status' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+];++const domainFields: Fields = [+ ...domainSummaryFields,+ { key: 'dns_checked_at', label: 'DNS Checked At', format: 'datetime' },+ { key: 'manual_review_required', label: 'Manual Review Required', format: 'boolean' },+ { key: 'spf_error', label: 'SPF Error' },+ { key: 'dkim_error', label: 'DKIM Error' },+ { key: 'return_path_error', label: 'Return Path Error' },+ { key: 'dmarc_error', label: 'DMARC Error' },+ { key: 'track_loads', label: 'Open Tracking Default', format: 'number' },+ { key: 'track_clicks', label: 'Click Tracking Default', format: 'number' },+ {+ key: 'dns_records',+ label: 'DNS Records',+ labelKey: 'name',+ listItems: [+ { key: 'type', label: 'Type' },+ { key: 'name', label: 'Name' },+ { key: 'value', label: 'Value' },+ { key: 'priority', label: 'Priority', format: 'number' },+ { key: 'required', label: 'Required', format: 'boolean' },+ { key: 'status', label: 'Status' },+ { key: 'error', label: 'Error' },+ ],+ },+];++const usageFields: Fields = [+ { key: 'used', label: 'Used', format: 'number' },+ { key: 'limit', label: 'Limit', format: 'number' },+ { key: 'plan', label: 'Plan' },+];++const audienceFields: Fields = [+ { key: 'id', label: 'Audience ID' },+ { key: 'name', label: 'Name' },+ { key: 'subscribers_count', label: 'Subscribers', format: 'number' },+ { key: 'usage', label: 'Usage', children: usageFields },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },+];++const subscriberFields: Fields = [+ { key: 'id', label: 'Subscriber ID', description: 'sub_… ID. Pass it as Subscriber to update or remove.' },+ { key: 'audience_id', label: 'Audience ID' },+ { key: 'contact_id', label: 'Contact ID' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'first_name', label: 'First Name' },+ { key: 'last_name', label: 'Last Name' },+ { key: 'custom_fields', label: 'Custom Fields', dynamicKey: true },+ { key: 'subscribed', label: 'Subscribed', format: 'boolean' },+ { key: 'subscribed_at', label: 'Subscribed At', format: 'datetime' },+ { key: 'unsubscribed_at', label: 'Unsubscribed At', format: 'datetime' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },+];++const contactFields: Fields = [+ { key: 'id', label: 'Contact ID' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'first_name', label: 'First Name' },+ { key: 'last_name', label: 'Last Name' },+ { key: 'custom_fields', label: 'Custom Fields', dynamicKey: true },+ { key: 'unsubscribed', label: 'Unsubscribed', format: 'boolean' },+ {+ key: 'audiences',+ label: 'Audiences',+ labelKey: 'name',+ listItems: [+ { key: 'id', label: 'Audience ID' },+ { key: 'name', label: 'Audience Name' },+ { key: 'subscribed', label: 'Subscribed (list view)', format: 'boolean' },+ { key: 'subscriber', label: 'Membership', children: [+ { key: 'id', label: 'Subscriber ID' },+ { key: 'subscribed', label: 'Subscribed', format: 'boolean' },+ { key: 'subscribed_at', label: 'Subscribed At', format: 'datetime' },+ { key: 'unsubscribed_at', label: 'Unsubscribed At', format: 'datetime' },+ ] },+ ],+ },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },+];++const suppressionFields: Fields = [+ { key: 'id', label: 'Suppression ID' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'type', label: 'Type', description: 'recipient, bounce, complaint or unsubscribe.' },+ { key: 'reason', label: 'Reason' },+ { key: 'keep_until', label: 'Keep Until', format: 'datetime' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },+];++const templateFields: Fields = [+ { key: 'id', label: 'Template ID' },+ { key: 'name', label: 'Name' },+ { key: 'alias', label: 'Alias', description: 'Pass the alias as Template when sending to always use the published version.' },+ { key: 'subject', label: 'Subject' },+ { key: 'from', label: 'From' },+ { key: 'reply_to', label: 'Reply-To' },+ { key: 'editor', label: 'Editor' },+ { key: 'total_versions', label: 'Versions', format: 'number' },+ { key: 'published_at', label: 'Published At', format: 'datetime' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },+];++function listOf({ items, extra = [] }: { items: Fields; extra?: Fields }): OutputSchema {+ return {+ fields: [+ { key: 'items', label: 'Items', listItems: items },+ { key: 'count', label: 'Count on This Page', format: 'number' },+ { key: 'page', label: 'Page', format: 'number' },+ { key: 'hasMore', label: 'Has More Pages', format: 'boolean', description: 'True when another page exists. Request it with Page + 1.' },+ { key: 'totalRecords', label: 'Total Records', format: 'number', description: 'Total matches across all pages, when Emailit reports it.' },+ ...extra,+ ],+ };+}++export const emailitSchemas = {+ sendEmailLegacy: {+ fields: [+ { key: 'status', label: 'HTTP Status', format: 'number' },+ { key: 'headers', label: 'Response Headers', dynamicKey: true },+ { key: 'body', label: 'Email', children: sentEmailFields },+ ],+ } satisfies OutputSchema,+ sentEmail: { fields: sentEmailFields } satisfies OutputSchema,+ email: {+ fields: [+ ...emailSummaryFields,+ { key: 'message_id', label: 'Message-ID Header' },+ { key: 'tracking', label: 'Tracking', children: trackingFields },+ { key: 'headers', label: 'Headers', dynamicKey: true },+ { key: 'body', label: 'Body', children: [+ { key: 'text', label: 'Text' },+ { key: 'html', label: 'HTML', format: 'html' },+ ] },+ {+ key: 'attachments',+ label: 'Attachments',+ labelKey: 'filename',+ listItems: [+ { key: 'filename', label: 'File Name' },+ { key: 'content_type', label: 'Content Type' },+ { key: 'size', label: 'Size', format: 'filesize' },+ ],+ },+ ],+ } satisfies OutputSchema,+ emailList: listOf({ items: emailSummaryFields }),+ rescheduled: {+ fields: [+ { key: 'id', label: 'Email ID' },+ { key: 'status', label: 'Status' },+ { key: 'scheduled_at', label: 'Scheduled At', format: 'datetime' },+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },+ { key: 'message', label: 'Message' },+ ],+ } satisfies OutputSchema,+ canceled: {+ fields: [+ { key: 'id', label: 'Email ID' },+ { key: 'status', label: 'Status' },+ { key: 'in_flight', label: 'Delivery May Still Complete', format: 'boolean' },+ { key: 'alreadyCanceled', label: 'Already Canceled', format: 'boolean', description: 'True when the email was canceled before this step ran.' },+ { key: 'message', label: 'Message' },+ ],+ } satisfies OutputSchema,+ retried: {+ fields: [+ { key: 'id', label: 'New Email ID' },+ { key: 'original_id', label: 'Original Email ID' },+ { key: 'from', label: 'From' },+ { key: 'to', label: 'To' },+ { key: 'subject', label: 'Subject' },+ { key: 'status', label: 'Status' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'message', label: 'Message' },+ ],+ } satisfies OutputSchema,+ forwarded: {+ fields: [+ ...sentEmailFields,+ { key: 'original_id', label: 'Original Email ID' },+ { key: 'message', label: 'Message' },+ ],+ } satisfies OutputSchema,+ domainList: listOf({ items: domainSummaryFields }),+ domain: { fields: domainFields } satisfies OutputSchema,+ audienceList: listOf({ items: audienceFields }),+ subscriber: {+ fields: [...subscriberFields, { key: 'alreadySubscribed', label: 'Already Subscribed', format: 'boolean', description: 'True when the address was already an active subscriber; nothing changed.' }],+ } satisfies OutputSchema,+ subscriberUpdated: { fields: subscriberFields } satisfies OutputSchema,+ removed: {+ fields: [+ { key: 'id', label: 'ID' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'audience_id', label: 'Audience ID' },+ { key: 'contact_id', label: 'Contact ID' },+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ { key: 'alreadyRemoved', label: 'Already Removed', format: 'boolean', description: 'True when nothing matched, so there was nothing to remove.' },+ ],+ } satisfies OutputSchema,+ contactLookup: {+ fields: [+ { key: 'found', label: 'Found', format: 'boolean' },+ { key: 'contact', label: 'Contact', children: contactFields },+ ],+ } satisfies OutputSchema,+ contactUpsert: {+ fields: [+ ...contactFields,+ { key: 'created', label: 'Created', format: 'boolean', description: 'True when a new contact was created, false when an existing one was updated.' },+ ],+ } satisfies OutputSchema,+ suppression: {+ fields: [...suppressionFields, { key: 'alreadySuppressed', label: 'Already Suppressed', format: 'boolean', description: 'True when the address already had a suppression of this type.' }],+ } satisfies OutputSchema,+ verification: {+ fields: [+ { key: 'id', label: 'Verification ID' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'status', label: 'Status' },+ { key: 'result', label: 'Result', description: 'safe, invalid, disposable, disabled, inbox_full, role or unknown.' },+ { key: 'risk', label: 'Risk', description: 'low, medium or high.' },+ { key: 'score', label: 'Score', format: 'number' },+ { key: 'mode', label: 'Mode' },+ { key: 'did_you_mean', label: 'Did You Mean' },+ { key: 'address', label: 'Address Parts', children: [+ { key: 'mailbox', label: 'Mailbox' },+ { key: 'domain', label: 'Domain' },+ { key: 'suffix', label: 'Plus Suffix' },+ { key: 'root', label: 'Root Address', format: 'email' },+ ] },+ { key: 'mx_records', label: 'MX Records', labelKey: 'exchange', listItems: [+ { key: 'priority', label: 'Priority', format: 'number' },+ { key: 'exchange', label: 'Mail Server' },+ ] },+ { key: 'created_at', label: 'Checked At', format: 'datetime' },+ { key: 'checks', label: 'Checks', children: [+ { key: 'valid_syntax', label: 'Valid Syntax', format: 'boolean' },+ { key: 'disposable', label: 'Disposable', format: 'boolean' },+ { key: 'role_account', label: 'Role Account', format: 'boolean' },+ { key: 'free_email', label: 'Free Email', format: 'boolean' },+ { key: 'gibberish', label: 'Gibberish', format: 'boolean' },+ { key: 'has_mx_records', label: 'Has MX Records', format: 'boolean' },+ { key: 'domain_age', label: 'Domain Age (days)', format: 'number' },+ { key: 'smtp_connect', label: 'SMTP Connect', format: 'boolean' },+ { key: 'deliverable', label: 'Deliverable', format: 'boolean' },+ { key: 'disabled', label: 'Disabled', format: 'boolean' },+ { key: 'inbox_full', label: 'Inbox Full', format: 'boolean' },+ { key: 'catch_all', label: 'Catch-All', format: 'boolean' },+ ] },+ ],+ } satisfies OutputSchema,+ templateList: listOf({ items: templateFields }),+};diff --git a/packages/pieces/community/emailit/src/lib/common/props.ts b/packages/pieces/community/emailit/src/lib/common/props.tsnew file mode 100644index 00000000000..bc9a56835e6--- /dev/null+++ b/packages/pieces/community/emailit/src/lib/common/props.ts@@ -0,0 +1,102 @@+import { Property } from '@activepieces/pieces-framework';++function emailId({ description }: { description?: string } = {}) {+ return Property.ShortText({+ displayName: 'Email ID',+ description: description ?? 'The Emailit email ID, e.g. em_4KYof1ZzXndZE2VPi0DgULiekG8 (from a Send Email step or Find Emails).',+ required: true,+ });+}++function audienceId() {+ return Property.ShortText({+ displayName: 'Audience',+ description: 'The audience ID (aud_…) or its exact name. Use List Audiences to find it.',+ required: true,+ });+}++function limit() {+ return Property.Number({+ displayName: 'Limit',+ description: 'Results per page, 1-100. Defaults to 25.',+ required: false,+ });+}++function page() {+ return Property.Number({+ displayName: 'Page',+ description: 'Page to return, starting at 1. Use it when the previous result had Has More Pages = true.',+ required: false,+ });+}++function idempotencyKey() {+ return Property.ShortText({+ displayName: 'Idempotency Key',+ description:+ 'Optional. A unique value (letters, digits, - and _; up to 256) such as an order ID. If this step runs again with the same key within 24 hours, Emailit returns the first result instead of sending again.',+ required: false,+ });+}++function recipientList({ displayName, description, required }: { displayName: string; description: string; required: boolean }) {+ return Property.Array({ displayName, description, required });+}++function sendingProps() {+ return {+ scheduled_at: Property.DateTime({+ displayName: 'Send At',+ description: 'Optional. Schedule the email for later (ISO 8601 with time zone). Leave empty to send now.',+ required: false,+ }),+ template: Property.ShortText({+ displayName: 'Template',+ description: 'Optional. A template ID (tem_…) or alias. Subject and body in this step override the template\'s.',+ required: false,+ }),+ variables: Property.Json({+ displayName: 'Template Variables',+ description: 'Optional. Values for {{placeholders}} in the subject and body, e.g. {"first_name": "Ada"}.',+ required: false,+ }),+ meta: Property.Object({+ displayName: 'Metadata',+ description: 'Optional. Your own key-value data stored with the email and sent back in webhooks, e.g. order_id: 1042.',+ required: false,+ }),+ tracking: Property.StaticDropdown<'default' | 'on' | 'off'>({+ displayName: 'Open & Click Tracking',+ description: 'Uses the sending domain\'s setting by default. Tracking only works when the domain\'s tracking CNAME is verified.',+ required: false,+ defaultValue: 'default',+ options: {+ disabled: false,+ options: [+ { label: 'Domain default', value: 'default' },+ { label: 'On', value: 'on' },+ { label: 'Off', value: 'off' },+ ],+ },+ }),+ attachments: Property.Array({+ displayName: 'Attachments (by URL)',+ description: 'Optional. Files Emailit downloads when sending (public http/https URL, max 25 MB, no redirects).',+ required: false,+ properties: {+ filename: Property.ShortText({ displayName: 'File Name', description: 'Including the extension, e.g. invoice.pdf.', required: true }),+ url: Property.ShortText({ displayName: 'File URL', required: true }),+ },+ }),+ attachment_file: Property.File({+ displayName: 'Attachment (file)',+ description: 'Optional. A file from a previous step to attach.',+ required: false,+ }),+ idempotency_key: idempotencyKey(),+ };+}++export const emailitProps = { emailId, audienceId, limit, page, idempotencyKey, recipientList, sendingProps };diff --git a/packages/pieces/community/emailit/src/lib/common/send.ts b/packages/pieces/community/emailit/src/lib/common/send.tsnew file mode 100644index 00000000000..d601ef10ada--- /dev/null+++ b/packages/pieces/community/emailit/src/lib/common/send.ts@@ -0,0 +1,69 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { EmailitAuthInput, emailitClient } from './client';+import { emailitValues } from './values';++function buildBody(input: SendInput): Record<string, unknown> {+ const template = emailitValues.optionalText(input.template);+ const subject = emailitValues.singleLine({ value: input.subject, label: 'Subject' });+ const html = nonBlank(input.html);+ const text = nonBlank(input.text);+ if (subject === undefined && template === undefined) {+ throw new Error('Subject is required unless you send a template.');+ }+ if (html === undefined && text === undefined && template === undefined) {+ throw new Error('Add an email body (HTML or plain text) or a template.');+ }+ const urlAttachments = emailitValues.attachmentsFromUrls(input.attachmentUrls);+ const fileAttachment = emailitValues.attachmentFromFile(input.attachmentFile);+ const attachments = [...urlAttachments, ...(fileAttachment ? [fileAttachment] : [])];+ return emailitValues.compact({+ from: emailitValues.sender({ name: input.fromName, email: input.fromEmail }),+ to: emailitValues.recipients({ value: input.to, label: 'To', required: true }),+ cc: emailitValues.recipients({ value: input.cc, label: 'CC', required: false }),+ bcc: emailitValues.recipients({ value: input.bcc, label: 'BCC', required: false }),+ reply_to: emailitValues.recipients({ value: input.replyTo, label: 'Reply-To', required: false }),+ subject,+ html,+ text,+ template,+ variables: emailitValues.objectInput({ value: input.variables, label: 'Template Variables' }),+ headers: emailitValues.headers(input.headers),+ meta: emailitValues.stringMap({ value: input.meta, label: 'Metadata' }),+ scheduled_at: emailitValues.dateTime(input.scheduledAt),+ tracking: emailitValues.tracking(input.tracking),+ attachments: attachments.length > 0 ? attachments : undefined,+ });+}++async function send({ auth, input }: { auth: EmailitAuthInput; input: SendInput }): Promise<{ status: number; headers: Record<string, unknown>; body: unknown }> {+ const body = buildBody(input);+ const idempotencyKey = emailitValues.idempotencyKey(input.idempotencyKey);+ return emailitClient.send({ auth, method: HttpMethod.POST, path: '/emails', body, idempotencyKey, redactBody: true });+}++function nonBlank(value: unknown): string | undefined {+ return typeof value === 'string' && value.trim() !== '' ? value : undefined;+}++export const emailitSend = { buildBody, send };++export type SendInput = {+ to: unknown;+ cc?: unknown;+ bcc?: unknown;+ replyTo?: unknown;+ fromName?: unknown;+ fromEmail: unknown;+ subject?: unknown;+ html?: unknown;+ text?: unknown;+ template?: unknown;+ variables?: unknown;+ headers?: unknown;+ meta?: unknown;+ scheduledAt?: unknown;+ tracking?: unknown;+ attachmentUrls?: unknown;+ attachmentFile?: unknown;+ idempotencyKey?: unknown;+};diff --git a/packages/pieces/community/emailit/src/lib/common/values.ts b/packages/pieces/community/emailit/src/lib/common/values.tsnew file mode 100644index 00000000000..ea4e0ea191b--- /dev/null+++ b/packages/pieces/community/emailit/src/lib/common/values.ts@@ -0,0 +1,233 @@+const MAX_RECIPIENTS_PER_FIELD = 50;+const HEADER_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;+const IDEMPOTENCY_KEY = /^[A-Za-z0-9_-]{1,256}$/;++function recipients({ value, label, required }: { value: unknown; label: string; required: boolean }): string[] | undefined {+ const raw = Array.isArray(value) ? value : typeof value === 'string' ? [value] : value === undefined || value === null ? [] : [value];+ const list = raw+ .flatMap((item) => (typeof item === 'string' ? splitAddresses(item) : typeof item === 'number' ? [String(item)] : []))+ .map((item) => item.trim())+ .filter((item) => item !== '');+ if (list.some((item) => /"[^"]*,[^"]*"/.test(item))) {+ throw new Error(`${label}: Emailit does not accept a comma inside a display name such as "Doe, Jane" <[email protected]>. Remove the comma or use the bare address.`);+ }+ if (list.some((item) => /[\r\n]/.test(item))) {+ throw new Error(`${label} must not contain line breaks.`);+ }+ if (list.length > MAX_RECIPIENTS_PER_FIELD) {+ throw new Error(`${label} accepts at most ${MAX_RECIPIENTS_PER_FIELD} addresses (got ${list.length}).`);+ }+ if (list.length === 0) {+ if (required) {+ throw new Error(`${label} needs at least one email address.`);+ }+ return undefined;+ }+ return list;+}++function headers(value: unknown): Record<string, string> | undefined {+ const record = objectInput({ value, label: 'Custom Headers' });+ if (record === undefined) return undefined;+ const entries = Object.entries(record).map(([key, item]): [string, string] => {+ const name = key.trim();+ const text = typeof item === 'string' ? item : typeof item === 'number' || typeof item === 'boolean' ? String(item) : '';+ if (!HEADER_NAME.test(name)) {+ throw new Error(`Custom header name "${name}" is not a valid header name.`);+ }+ if (/[\r\n\0]/.test(text)) {+ throw new Error(`Custom header "${name}" must not contain line breaks.`);+ }+ return [name, text];+ });+ return entries.length > 0 ? Object.fromEntries(entries) : undefined;+}++function objectInput({ value, label }: { value: unknown; label: string }): Record<string, unknown> | undefined {+ if (value === undefined || value === null || value === '') return undefined;+ const parsed = typeof value === 'string' ? parseJson({ text: value, label }) : value;+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {+ throw new Error(`${label} must be a JSON object.`);+ }+ const record = Object.fromEntries(Object.entries(parsed));+ return Object.keys(record).length > 0 ? record : undefined;+}++function stringMap({ value, label }: { value: unknown; label: string }): Record<string, string> | undefined {+ const record = objectInput({ value, label });+ if (record === undefined) return undefined;+ return Object.fromEntries(+ Object.entries(record).map(([key, item]) => [key, typeof item === 'string' ? item : JSON.stringify(item)]),+ );+}++function parseJson({ text, label }: { text: string; label: string }): unknown {+ try {+ return JSON.parse(text);+ } catch {+ throw new Error(`${label} is not valid JSON.`);+ }+}++function idempotencyKey(value: unknown): string | undefined {+ if (value === undefined || value === null) return undefined;+ const text = String(value).trim();+ if (text === '') return undefined;+ if (!IDEMPOTENCY_KEY.test(text)) {+ throw new Error('Idempotency Key must be 1-256 letters, digits, "-" or "_".');+ }+ 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 text = value.trim();+ return text === '' ? undefined : text;+}++function requiredText({ value, label }: { value: unknown; label: string }): string {+ const text = optionalText(value);+ if (text === undefined) {+ throw new Error(`${label} is required.`);+ }+ return text;+}++function singleLine({ value, label }: { value: unknown; label: string }): string | undefined {+ const text = optionalText(value);+ if (text !== undefined && /[\r\n]/.test(text)) {+ throw new Error(`${label} must not contain line breaks.`);+ }+ return text;+}++function dateTime(value: unknown): string | undefined {+ const text = optionalText(value);+ if (text === undefined) return undefined;+ const parsed = Date.parse(text);+ if (Number.isNaN(parsed)) {+ throw new Error(`"${text}" is not a valid date-time. Use ISO 8601, e.g. 2026-10-02T09:00:00Z.`);+ }+ return new Date(parsed).toISOString();+}++function sender({ name, email }: { name: unknown; email: unknown }): string {+ const address = singleLine({ value: email, label: 'Sender Email' });+ if (address === undefined) {+ throw new Error('Sender Email is required.');+ }+ const display = singleLine({ value: name, label: 'Sender Name' });+ if (display === undefined) return address;+ if (/["\\<>]/.test(display)) {+ throw new Error('Sender Name cannot contain quotes, backslashes or angle brackets: Emailit rejects them.');+ }+ return `"${display}" <${address}>`;+}++function splitAddresses(text: string): string[] {+ const list: string[] = [];+ let start = 0;+ let quoted = false;+ let angle = false;+ for (let index = 0; index < text.length; index++) {+ const char = text[index];+ if (quoted && char === '\\') {+ index++;+ } else if (char === '"') {+ quoted = !quoted;+ } else if (!quoted && char === '<') {+ angle = true;+ } else if (!quoted && char === '>') {+ angle = false;+ } else if (!quoted && !angle && char === ',') {+ list.push(text.slice(start, index));+ start = index + 1;+ }+ }+ list.push(text.slice(start));+ return list;+}++function tracking(value: unknown): boolean | undefined {+ if (value === 'on') return true;+ if (value === 'off') return false;+ return undefined;+}++function attachmentsFromUrls(value: unknown): Array<{ filename: string; url: string }> {+ if (!Array.isArray(value)) return [];+ return value.flatMap((item): Array<{ filename: string; url: string }> => {+ if (item === null || typeof item !== 'object') return [];+ const filename = optionalText(Reflect.get(item, 'filename'));+ const url = optionalText(Reflect.get(item, 'url'));+ if (filename === undefined && url === undefined) return [];+ if (filename === undefined || url === undefined) {+ throw new Error('Each attachment needs both a file name and a URL.');+ }+ if (!/^https?:\/\//i.test(url)) {+ throw new Error(`Attachment URL for "${filename}" must start with http:// or https://.`);+ }+ return [{ filename, url }];+ });+}++function attachmentFromFile(value: unknown): { filename: string; content: string; content_type: string } | undefined {+ if (value === undefined || value === null || typeof value !== 'object') return undefined;+ const filename = optionalText(Reflect.get(value, 'filename'));+ const base64 = Reflect.get(value, 'base64');+ const data = Reflect.get(value, 'data');+ const content = typeof base64 === 'string' && base64 !== '' ? base64 : Buffer.isBuffer(data) ? data.toString('base64') : undefined;+ if (filename === undefined || content === undefined) {+ throw new Error('The attached file could not be read.');+ }+ return { filename, content, content_type: mimeType(filename) };+}++function mimeType(filename: string): string {+ const extension = filename.split('.').pop()?.toLowerCase() ?? '';+ return MIME_TYPES[extension] ?? 'application/octet-stream';+}++function compact(record: Record<string, unknown>): Record<string, unknown> {+ return Object.fromEntries(Object.entries(record).filter(([, value]) => value !== undefined));+}++const MIME_TYPES: Record<string, string> = {+ pdf: 'application/pdf',+ png: 'image/png',+ jpg: 'image/jpeg',+ jpeg: 'image/jpeg',+ gif: 'image/gif',+ svg: 'image/svg+xml',+ txt: 'text/plain',+ csv: 'text/csv',+ ics: 'text/calendar',+ xml: 'application/xml',+ zip: 'application/zip',+ doc: 'application/msword',+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',+ xls: 'application/vnd.ms-excel',+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',+ ppt: 'application/vnd.ms-powerpoint',+ pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',+ eml: 'message/rfc822',+};++export const emailitValues = {+ recipients,+ headers,+ objectInput,+ stringMap,+ idempotencyKey,+ optionalText,+ requiredText,+ singleLine,+ dateTime,+ sender,+ tracking,+ attachmentsFromUrls,+ attachmentFromFile,+ compact,+ MAX_RECIPIENTS_PER_FIELD,+};diff --git a/packages/pieces/community/emailit/test/actions.test.ts b/packages/pieces/community/emailit/test/actions.test.tsnew file mode 100644index 00000000000..07baa8e8f89--- /dev/null+++ b/packages/pieces/community/emailit/test/actions.test.ts@@ -0,0 +1,132 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { addSubscriberAction, addSubscriberByIdAction } from '../src/lib/actions/add-subscriber';+import { addSuppressionAction } from '../src/lib/actions/add-suppression';+import { cancelEmailAction } from '../src/lib/actions/cancel-email';+import { findContactAction } from '../src/lib/actions/find-contact';+import { forwardEmailAction } from '../src/lib/actions/forward-email';+import { getEmailAction } from '../src/lib/actions/get-email';+import { listEmailsAction } from '../src/lib/actions/list-emails';+import { listTemplatesAction } from '../src/lib/actions/list-templates';+import { removeSubscriberAction } from '../src/lib/actions/remove-subscriber';+import { removeSuppressionAction } from '../src/lib/actions/remove-suppression';+import { rescheduleEmailAction } from '../src/lib/actions/reschedule-email';+import { updateSubscriberAction } from '../src/lib/actions/update-subscriber';+import { upsertContactAction } from '../src/lib/actions/upsert-contact';+import { replies, run, stubFetch } from './helpers';++afterEach(() => vi.unstubAllGlobals());++describe('email actions', () => {+ test('get_email encodes the ID and drops attachment contents', async () => {+ const seen = stubFetch(replies([{ body: { id: 'em_1', attachments: [{ filename: 'a.pdf', size: 3, content: 'AAAA' }] } }]));+ const result = await run({ action: getEmailAction, props: { email_id: ' em_1/../x ' } });+ expect(seen[0].url.pathname).toBe('/v2/emails/em_1%2F..%2Fx');+ expect(result).toEqual({ id: 'em_1', attachments: [{ filename: 'a.pdf', size: 3 }] });+ });+ test('list_emails sends filters and reports hasMore', async () => {+ const seen = stubFetch(replies([{ body: { data: [{ id: 'em_1' }], next_page_url: '/v2/emails?page=3' } }]));+ const result = await run({ action: listEmailsAction, props: { status: 'bounced', to: '[email protected]', date_from: '2026-10-01', limit: 10, page: 2 } });+ expect(Object.fromEntries(seen[0].url.searchParams)).toEqual({ 'status.exact': 'bounced', 'to.exact': '[email protected]', date_from: '2026-10-01', limit: '10', page: '2' });+ expect(result).toEqual({ items: [{ id: 'em_1' }], count: 1, page: 2, hasMore: true, totalRecords: null });+ await expect(run({ action: listEmailsAction, props: { date_from: '01/10/2026' } })).rejects.toThrow('date like');+ });+ test('reschedule posts the ISO time', async () => {+ const seen = stubFetch(replies([{ body: { id: 'em_1', status: 'scheduled' } }]));+ await run({ action: rescheduleEmailAction, props: { email_id: 'em_1', scheduled_at: '2026-11-01T10:00:00Z' } });+ expect(seen[0]).toMatchObject({ method: 'POST', body: { scheduled_at: '2026-11-01T10:00:00.000Z' } });+ expect(seen[0].url.pathname).toBe('/v2/emails/em_1');+ });+ test('cancel returns alreadyCanceled when the email is already canceled', async () => {+ const seen = stubFetch(replies([{ status: 422, body: { error: 'Cannot cancel email' } }, { body: { status: 'canceled' } }]));+ expect(await run({ action: cancelEmailAction, props: { email_id: 'em_1' } })).toMatchObject({ alreadyCanceled: true, status: 'canceled' });+ expect(seen[1].url.pathname).toBe('/v2/email/em_1');+ });+ test('cancel still fails when the email was delivered', async () => {+ stubFetch(replies([{ status: 422, body: { error: 'Cannot cancel email' } }, { body: { status: 'delivered' } }]));+ await expect(run({ action: cancelEmailAction, props: { email_id: 'em_1' } })).rejects.toThrow('can no longer be canceled');+ });+ test('forward only sends the note with the header option and passes the idempotency key', async () => {+ const seen = stubFetch(replies([{ body: { id: 'em_9', original_id: 'em_1' } }]));+ await run({ action: forwardEmailAction, props: { email_id: 'em_1', to: ['[email protected]'], comment: 'fyi', idempotency_key: 'fw-1' } });+ expect(seen[0].body).toEqual({ to: ['[email protected]'] });+ expect(seen[0].headers.get('idempotency-key')).toBe('fw-1');+ });+});++describe('audience, contact and suppression actions', () => {+ test('add_subscriber returns the existing subscriber on 409', async () => {+ stubFetch(replies([{ status: 409, body: { error: 'Contact is already subscribed', existing: { id: 'sub_1', email: '[email protected]', subscribed: true } } }]));+ expect(await run({ action: addSubscriberAction, props: { audience: 'aud_1', email: '[email protected]' } })).toEqual({ id: 'sub_1', email: '[email protected]', subscribed: true, alreadySubscribed: true });+ });+ test('add_subscriber reads the subscriber back when the 409 has no existing record (live behavior)', async () => {+ const seen = stubFetch(replies([{ status: 409, body: { error: 'Contact is already subscribed to this audience' } }, { body: { id: 'sub_2', subscribed: true } }]));+ expect(await run({ action: addSubscriberAction, props: { audience: 'aud_1', email: '[email protected]' } })).toEqual({ id: 'sub_2', subscribed: true, alreadySubscribed: true });+ expect(seen[1]).toMatchObject({ method: 'GET' });+ expect(seen[1].url.pathname).toBe('/v2/audiences/aud_1/subscribers/a%40b.co');+ });+ test('update_subscriber sends only chosen fields and refuses an empty update', async () => {+ const seen = stubFetch(replies([{ body: { id: 'sub_1', subscribed: false } }]));+ await run({ action: updateSubscriberAction, props: { audience: 'News letter', subscriber: '[email protected]', subscribed: 'no' } });+ expect(seen[0].url.pathname).toBe('/v2/audiences/News%20letter/subscribers/a%40b.co');+ expect(seen[0].body).toEqual({ subscribed: false });+ await expect(run({ action: updateSubscriberAction, props: { audience: 'aud_1', subscriber: '[email protected]', subscribed: 'keep' } })).rejects.toThrow('at least one change');+ expect(seen).toHaveLength(1);+ });+ test('remove_subscriber: 404 on the subscriber with an existing audience is alreadyRemoved', async () => {+ stubFetch(replies([{ status: 404, body: { error: 'Subscriber not found' } }, { body: { id: 'aud_1' } }]));+ expect(await run({ action: removeSubscriberAction, props: { audience: 'aud_1', subscriber: '[email protected]' } })).toMatchObject({ alreadyRemoved: true, deleted: false });+ stubFetch(replies([{ status: 404, body: { error: 'Subscriber not found' } }, { status: 404, body: { error: 'Audience not found' } }]));+ await expect(run({ action: removeSubscriberAction, props: { audience: 'aud_x', subscriber: '[email protected]' } })).rejects.toThrow('Audience not found');+ });+ test('find_contact returns found=false on 404 and fails on other errors', async () => {+ stubFetch(replies([{ status: 404, body: { error: 'Contact not found' } }]));+ expect(await run({ action: findContactAction, props: { contact: '[email protected]' } })).toEqual({ found: false, contact: null });+ stubFetch(replies([{ status: 500, body: { error: 'boom' } }]));+ await expect(run({ action: findContactAction, props: { contact: '[email protected]' } })).rejects.toThrow('boom');+ });+ test('create_or_update_contact creates when missing', async () => {+ const seen = stubFetch(replies([{ status: 404, body: { error: 'Contact not found' } }, { status: 201, body: { id: 'con_1', email: '[email protected]' } }]));+ expect(await run({ action: upsertContactAction, props: { email: '[email protected]', first_name: 'Ada', audiences: ['aud_1', ''] } })).toEqual({ id: 'con_1', email: '[email protected]', created: true });+ expect(seen[1]).toMatchObject({ method: 'POST', body: { email: '[email protected]', first_name: 'Ada', audiences: ['aud_1'] } });+ });+ test('create_or_update_contact updates and keeps existing audiences', async () => {+ const seen = stubFetch(replies([{ body: { id: 'con_1', email: '[email protected]', audiences: [{ id: 'aud_0' }] } }, { body: { id: 'con_1' } }]));+ expect(await run({ action: upsertContactAction, props: { email: '[email protected]', last_name: 'L', audiences: ['aud_1'], unsubscribed: 'keep' } })).toMatchObject({ created: false });+ expect(seen[1].url.pathname).toBe('/v2/contacts/con_1');+ expect(seen[1].body).toEqual({ last_name: 'L', audiences: ['aud_0', 'aud_1'] });+ });+ test('create_or_update_contact with nothing to change makes no write', async () => {+ const seen = stubFetch(replies([{ body: { id: 'con_1', email: '[email protected]', audiences: [{ id: 'aud_1' }] } }]));+ expect(await run({ action: upsertContactAction, props: { email: '[email protected]', audiences: ['aud_1'] } })).toMatchObject({ id: 'con_1', created: false });+ expect(seen).toHaveLength(1);+ });+ test('add_suppression defaults to recipient and returns existing on 409', async () => {+ const seen = stubFetch(replies([{ status: 409, body: { error: 'exists', existing: { id: 'sup_1', email: '[email protected]', type: 'recipient' } } }]));+ expect(await run({ action: addSuppressionAction, props: { email: '[email protected]' } })).toMatchObject({ id: 'sup_1', alreadySuppressed: true });+ expect(seen[0].body).toEqual({ email: '[email protected]', type: 'recipient' });+ });+ test('remove_suppression: 404 is alreadyRemoved', async () => {+ const seen = stubFetch(replies([{ status: 404, body: { error: 'Suppression not found' } }]));+ expect(await run({ action: removeSuppressionAction, props: { suppression: '[email protected]' } })).toMatchObject({ alreadyRemoved: true });+ expect(seen[0]).toMatchObject({ method: 'DELETE' });+ expect(seen[0].url.pathname).toBe('/v2/suppressions/a%40b.co');+ });+});++describe('other actions', () => {+ test('list_templates uses per_page and filter[name]', async () => {+ const seen = stubFetch(replies([{ body: { data: [], total_records: 0, per_page: 5, current_page: 1, total_pages: 0 } }]));+ expect(await run({ action: listTemplatesAction, props: { name: 'welc', limit: 5 } })).toEqual({ items: [], count: 0, page: 1, hasMore: false, totalRecords: 0 });+ expect(Object.fromEntries(seen[0].url.searchParams)).toEqual({ 'filter[name]': 'welc', per_page: '5', page: '1' });+ });+});++describe('human and AI twins share the same request', () => {+ test('add_subscriber_by_id sends the same request as the dropdown action', async () => {+ const seen = stubFetch(replies([{ status: 201, body: { id: 'sub_1' } }]));+ await run({ action: addSubscriberAction, props: { audience: 'aud_1', email: '[email protected]' } });+ await run({ action: addSubscriberByIdAction, props: { audience: ' aud_1 ', email: '[email protected]' } });+ expect(seen[0].url.toString()).toBe(seen[1].url.toString());+ expect(seen[0].body).toEqual(seen[1].body);+ });+});diff --git a/packages/pieces/community/emailit/test/client.test.ts b/packages/pieces/community/emailit/test/client.test.tsnew file mode 100644index 00000000000..e765e32c1ea--- /dev/null+++ b/packages/pieces/community/emailit/test/client.test.ts@@ -0,0 +1,125 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { afterEach, describe, expect, test, vi } from 'vitest';+import { emailitAuth } from '../src/lib/auth';+import { EmailitApiError, emailitClient } from '../src/lib/common/client';+import { API_KEY, failure, replies, stubFetch } from './helpers';++const auth = { secret_text: ` ${API_KEY} ` };+const server = { apiUrl: '', publicUrl: '', mintOidcToken: async () => '' };++afterEach(() => {+ vi.unstubAllGlobals();+ vi.useRealTimers();+ vi.restoreAllMocks();+});++describe('client', () => {+ test('seg encodes and rejects empty and dot segments', () => {+ expect(emailitClient.seg({ value: '../domains', label: 'Email ID' })).toBe('..%2Fdomains');+ expect(emailitClient.seg({ value: '[email protected]', label: 'x' })).toBe('ada%40example.com');+ expect(() => emailitClient.seg({ value: '..', label: 'Email ID' })).toThrow('Email ID is required');+ expect(() => emailitClient.seg({ value: ' ', label: 'Email ID' })).toThrow('Email ID is required');+ });+ test('sends a trimmed Bearer key to api.emailit.com/v2 and maps errors into responseBody', async () => {+ const seen = stubFetch(replies([{ status: 404, body: { error: 'Not Found', message: 'Email not found' } }]));+ const error = await failure(emailitClient.request({ auth, method: HttpMethod.GET, path: '/emails/x' }));+ expect(seen[0].headers.get('authorization')).toBe(`Bearer ${API_KEY}`);+ expect(seen[0].url.toString()).toBe('https://api.emailit.com/v2/emails/x');+ expect(error).toBeInstanceOf(EmailitApiError);+ expect(error).toMatchObject({ status: 404, responseBody: { message: 'Email not found' } });+ expect(error).not.toHaveProperty('body');+ expect(String(error)).toContain('Email not found');+ });+ test('sandbox, plan, credits and Sending Only errors get a specific hint', async () => {+ stubFetch(replies([{ status: 403, body: { error: 'Workspace not verified', code: 'unverified_workspace_recipient' } }]));+ expect(String(await failure(emailitClient.request({ auth, method: HttpMethod.GET, path: '/x' })))).toContain('sandbox mode');+ stubFetch(replies([{ status: 403, body: { error: 'plan_required', required_plan: 'pro' } }]));+ expect(String(await failure(emailitClient.request({ auth, method: HttpMethod.GET, path: '/x' })))).toContain('higher Emailit plan');+ stubFetch(replies([{ status: 402, body: { error: 'Insufficient credits' } }]));+ expect(String(await failure(emailitClient.request({ auth, method: HttpMethod.GET, path: '/x' })))).toContain('out of credits');+ stubFetch(replies([{ status: 403, body: { statusCode: 403, error: 'Forbidden', message: 'Permission denied: read' } }]));+ expect(String(await failure(emailitClient.request({ auth, method: HttpMethod.GET, path: '/x' })))).toContain('Sending Only');+ });+ test('send validation errors list each problem', async () => {+ stubFetch(replies([{ status: 400, body: { error: 'Validation failed', validation_errors: [{ field: 'to', message: 'is invalid' }] } }]));+ expect(String(await failure(emailitClient.request({ auth, method: HttpMethod.POST, path: '/emails', body: {} })))).toContain('to: is invalid');+ });+ test('GET retries 429 at most twice, honoring retry-after', async () => {+ vi.useFakeTimers();+ const seen = stubFetch(replies([{ status: 429, body: { retry_after: 1 } }, { status: 429 }, { status: 429, body: { error: 'Rate limit exceeded' } }]));+ const promise = failure(emailitClient.request({ auth, method: HttpMethod.GET, path: '/x' }));+ await vi.runAllTimersAsync();+ expect(await promise).toMatchObject({ status: 429 });+ expect(seen).toHaveLength(3);+ });+ test('a retry-after longer than 10 s fails at once instead of retrying early', async () => {+ const seen = stubFetch(replies([{ status: 429, headers: { 'retry-after': '60' }, body: { error: 'Daily limit exceeded', retry_after: 41760 } }]));+ expect(await failure(emailitClient.request({ auth, method: HttpMethod.GET, path: '/x' }))).toMatchObject({ status: 429 });+ expect(seen).toHaveLength(1);+ });+ test('the documented retry_after body field is honoured', async () => {+ vi.useFakeTimers();+ const seen = stubFetch(replies([{ status: 429, body: { error: 'Rate limit exceeded', retry_after: 5 } }, { body: { ok: true } }]));+ const promise = emailitClient.request({ auth, method: HttpMethod.GET, path: '/x' });+ await vi.advanceTimersByTimeAsync(4_000);+ expect(seen).toHaveLength(1);+ await vi.advanceTimersByTimeAsync(1_500);+ expect(await promise).toEqual({ ok: true });+ expect(seen).toHaveLength(2);+ });+ test('a POST without an idempotency key is never auto-retried; with a key it is', async () => {+ vi.useFakeTimers();+ const seen = stubFetch(replies([{ status: 429 }]));+ const first = failure(emailitClient.request({ auth, method: HttpMethod.POST, path: '/emails', body: {} }));+ await vi.runAllTimersAsync();+ expect(await first).toMatchObject({ status: 429 });+ expect(seen).toHaveLength(1);+ const keyed = stubFetch(replies([{ status: 429 }, { body: { id: 'em_1' } }]));+ const second = emailitClient.request({ auth, method: HttpMethod.POST, path: '/emails', body: {}, idempotencyKey: 'k1' });+ await vi.runAllTimersAsync();+ expect(await second).toEqual({ id: 'em_1' });+ expect(keyed).toHaveLength(2);+ expect(keyed[0].headers.get('idempotency-key')).toBe('k1');+ });+ test('redirects are not followed', async () => {+ stubFetch(replies([{ status: 302 }]));+ expect(await failure(emailitClient.request({ auth, method: HttpMethod.GET, path: '/x' }))).toMatchObject({ status: 302 });+ });+ test('a failed request carrying email content is not logged with its body', async () => {+ const logged = vi.spyOn(console, 'error').mockImplementation(() => undefined);+ stubFetch(replies([{ status: 400, body: { error: 'bad' } }]));+ await failure(emailitClient.request({ auth, method: HttpMethod.POST, path: '/emails', body: { to: ['[email protected]'], html: 'private text' }, redactBody: true }));+ expect(JSON.stringify(logged.mock.calls)).not.toContain('secret-person');+ expect(JSON.stringify(logged.mock.calls)).not.toContain('private text');+ });+ test('listPage reads both next_page_url and current/total page formats', () => {+ expect(emailitClient.listPage({ data: [1], next_page_url: '/v2/x?page=2' })).toEqual({ items: [1], hasMore: true, totalRecords: null });+ expect(emailitClient.listPage({ data: [], total_records: 0, current_page: 1, total_pages: 0 })).toEqual({ items: [], hasMore: false, totalRecords: 0 });+ expect(emailitClient.listPage({ data: [1], current_page: 1, total_pages: 3 })).toMatchObject({ hasMore: true });+ });+ test('limit and page are validated', () => {+ expect(emailitClient.clampLimit(undefined)).toBe(25);+ expect(emailitClient.clampLimit('50')).toBe(50);+ expect(() => emailitClient.clampLimit(101)).toThrow('1 to 100');+ expect(() => emailitClient.page(0)).toThrow('Page');+ });+});++describe('auth.validate', () => {+ test('401 is an invalid key', async () => {+ stubFetch(replies([{ status: 401, body: { error: 'Unauthorized' } }]));+ expect(await emailitAuth.validate?.({ auth: 'bad', server })).toMatchObject({ valid: false, error: expect.stringContaining('Invalid API key') });+ });+ test('a Sending Only key (403 Permission denied) is accepted', async () => {+ const seen = stubFetch(replies([{ status: 403, body: { statusCode: 403, error: 'Forbidden', message: 'Permission denied: read' } }]));+ expect(await emailitAuth.validate?.({ auth: 'sending-key', server })).toEqual({ valid: true });+ expect(seen[0].method).toBe('GET');+ });+ test('a suspended workspace 403 and a 500 are not reported as an invalid key', async () => {+ stubFetch(replies([{ status: 500, body: { error: 'Upstream failed' } }]));+ const result = await emailitAuth.validate?.({ auth: 'k', server });+ expect(result).toMatchObject({ valid: false });+ expect(JSON.stringify(result)).toContain('Upstream failed');+ expect(JSON.stringify(result)).not.toContain('Invalid API key');+ });+});diff --git a/packages/pieces/community/emailit/test/helpers.ts b/packages/pieces/community/emailit/test/helpers.tsnew file mode 100644index 00000000000..4474ba67fdc--- /dev/null+++ b/packages/pieces/community/emailit/test/helpers.ts@@ -0,0 +1,62 @@+import { vi } from 'vitest';++export type SeenRequest = { url: URL; method: string; headers: Headers; body: unknown };+export type FakeReply = { status?: number; body?: unknown; headers?: Record<string, string> };++export function stubFetch(respond: (request: SeenRequest, index: number) => FakeReply): SeenRequest[] {+ const seen: SeenRequest[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: string | URL, init?: RequestInit) => {+ const request: SeenRequest = {+ url: new URL(String(input)),+ method: (init?.method ?? 'GET').toUpperCase(),+ headers: new Headers(init?.headers),+ body: typeof init?.body === 'string' ? JSON.parse(init.body) : null,+ };+ seen.push(request);+ const reply = respond(request, seen.length - 1);+ const status = reply.status ?? 200;+ const payload = status === 204 ? null : JSON.stringify(reply.body ?? {});+ return new Response(payload, { status, headers: { 'content-type': 'application/json', ...(reply.headers ?? {}) } });+ }),+ );+ return seen;+}++export function replies(list: FakeReply[]): (request: SeenRequest, index: number) => FakeReply {+ return (_request, index) => list[Math.min(index, list.length - 1)];+}++export function run({ action, props }: { action: Runnable; props: Record<string, unknown> }): Promise<unknown> {+ return action.run({+ auth: { secret_text: ` ${API_KEY} ` },+ propsValue: props,+ server: { apiUrl: 'http://localhost:3000/api/', publicUrl: 'http://localhost:4200/', token: 'x' },+ });+}++export async function failure(promise: Promise<unknown>): Promise<unknown> {+ return promise.then(+ () => {+ throw new Error('expected a failure');+ },+ (error: unknown) => error,+ );+}++export const API_KEY = 'em_test_key';+export const SEND_REPLY = {+ object: 'email',+ id: 'em_1',+ ids: { '[email protected]': 'em_1', '[email protected]': 'em_2' },+ from: 'Acme <[email protected]>',+ to: ['[email protected]', '[email protected]'],+ subject: 'Hi',+ status: 'accepted',+ scheduled_at: null,+ created_at: '2026-10-12T10:00:00Z',+ tracking: { loads: false, clicks: false },+};++type Runnable = { run(context: never): Promise<unknown> };diff --git a/packages/pieces/community/emailit/test/metadata.test.ts b/packages/pieces/community/emailit/test/metadata.test.tsnew file mode 100644index 00000000000..b2612ab285e--- /dev/null+++ b/packages/pieces/community/emailit/test/metadata.test.ts@@ -0,0 +1,75 @@+import { describe, expect, test } from 'vitest';+import { emailit } from '../src';+import { emailitDropdowns } from '../src/lib/common/dropdowns';+import { replies, stubFetch } from './helpers';++const actions = Object.values(emailit.actions());+const nonCustom = actions.filter((action) => action.name !== 'custom_api_call');+const HUMAN = ['send_email', 'add_subscriber', 'update_subscriber', 'remove_subscriber', 'create_or_update_contact', 'get_domain', 'verify_domain'];+const AI = ['send_email_ai', 'add_subscriber_by_id', 'update_subscriber_by_id', 'remove_subscriber_by_id', 'create_or_update_contact_by_id', 'get_domain_by_id', 'verify_domain_by_id'];++function propTypes(action: { props: Record<string, unknown> }): unknown[] {+ return Object.values(action.props).map((prop) => (prop !== null && typeof prop === 'object' ? Reflect.get(prop, 'type') : undefined));+}++async function loadOptions({ prop, auth }: { prop: unknown; auth: unknown }): Promise<unknown> {+ const options = prop !== null && typeof prop === 'object' ? Reflect.get(prop, 'options') : undefined;+ if (typeof options !== 'function') throw new Error('not a dropdown');+ return Reflect.apply(options, prop, [{ auth }, {}]);+}++describe('piece metadata', () => {+ test('27 actions plus Custom API Call, no triggers, 0.88.2', () => {+ expect(nonCustom).toHaveLength(27);+ expect(actions.map((action) => action.name)).toContain('custom_api_call');+ expect(actions.map((action) => action.name)).not.toContain('trigger_automation');+ expect(Object.keys(emailit.triggers())).toEqual([]);+ expect(emailit.minimumSupportedRelease).toBe('0.88.2');+ });+ test.each(nonCustom.map((action) => [action.name, action]))('%s has audience, classification, aiMetadata and outputSchema', (_name, action) => {+ expect(['both', 'ai', 'human']).toContain(action.audience);+ expect(['READ', 'SEARCH', 'WRITE', 'DESTRUCTIVE']).toContain(action.classification);+ expect(action.aiMetadata?.description?.length ?? 0).toBeGreaterThan(80);+ expect(typeof action.aiMetadata?.idempotent).toBe('boolean');+ expect(action.outputSchema?.fields.length).toBeGreaterThan(0);+ });+ test('7 human, 7 AI twins, 13 both', () => {+ expect(nonCustom.filter((action) => action.audience === 'human').map((action) => action.name).sort()).toEqual([...HUMAN].sort());+ expect(nonCustom.filter((action) => action.audience === 'ai').map((action) => action.name).sort()).toEqual([...AI].sort());+ expect(nonCustom.filter((action) => action.audience === 'both')).toHaveLength(13);+ });+ test('AI-visible actions have no dynamic dropdowns; human selector actions do', () => {+ for (const action of nonCustom.filter((item) => item.audience !== 'human')) {+ expect(propTypes(action)).not.toContain('DROPDOWN');+ expect(propTypes(action)).not.toContain('MULTI_SELECT_DROPDOWN');+ }+ for (const action of nonCustom.filter((item) => item.audience === 'human' && item.name !== 'send_email')) {+ expect(propTypes(action).some((type) => type === 'DROPDOWN' || type === 'MULTI_SELECT_DROPDOWN')).toBe(true);+ }+ });+ test('send_email keeps its prop names and required set', () => {+ const send = emailit.actions()['send_email'];+ for (const name of ['to', 'from_name', 'from_email', 'cc', 'bcc', 'reply_to', 'subject', 'content_type', 'content', 'headers']) {+ expect(send.props).toHaveProperty(name);+ }+ const required = Object.entries(send.props).filter(([, prop]) => Reflect.get(prop, 'required') === true).map(([name]) => name).sort();+ expect(required).toEqual(['content_type', 'from_email', 'to']);+ });+});++describe('dropdowns', () => {+ test('audience dropdown pages to the end and labels unnamed audiences', async () => {+ const seen = stubFetch(replies([+ { body: { data: [{ id: 'aud_1', name: '', subscribers_count: 2 }], next_page_url: '/v2/audiences?page=2' } },+ { body: { data: [{ id: 'aud_2', name: 'News' }], next_page_url: null } },+ ]));+ const state = await loadOptions({ prop: emailitDropdowns.audience(), auth: { secret_text: 'k' } });+ expect(state).toMatchObject({ disabled: false, options: [{ label: '(unnamed audience) (2 subscribers)', value: 'aud_1' }, { label: 'News', value: 'aud_2' }] });+ expect(seen.map((request) => request.url.searchParams.get('page'))).toEqual(['1', '2']);+ });+ test('domain dropdown is disabled with the reason on error and without auth', async () => {+ stubFetch(replies([{ status: 403, body: { message: 'Permission denied: read' } }]));+ expect(await loadOptions({ prop: emailitDropdowns.domain(), auth: { secret_text: 'k' } })).toMatchObject({ disabled: true, placeholder: expect.stringContaining('Sending Only') });+ expect(await loadOptions({ prop: emailitDropdowns.domain(), auth: undefined })).toMatchObject({ disabled: true });+ });+});diff --git a/packages/pieces/community/emailit/test/send.test.ts b/packages/pieces/community/emailit/test/send.test.tsnew file mode 100644index 00000000000..0808e63e46d--- /dev/null+++ b/packages/pieces/community/emailit/test/send.test.ts@@ -0,0 +1,121 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { sendEmailAction } from '../src/lib/actions/send-email';+import { sendEmailAiAction } from '../src/lib/actions/send-email-ai';+import { failure, replies, run, SEND_REPLY, stubFetch } from './helpers';++afterEach(() => vi.unstubAllGlobals());++const base = { from_email: '[email protected]', subject: 'Hi', content_type: 'html', content: '<p>Hi</p>' };++describe('send_email (existing action)', () => {+ test('keeps the old request for the old props and returns {status, headers, body}', async () => {+ const seen = stubFetch(replies([{ body: SEND_REPLY, headers: { 'ratelimit-remaining': '9' } }]));+ const result = await run({ action: sendEmailAction, props: { ...base, from_name: 'Acme', to: ['[email protected]'], headers: { 'X-Campaign-ID': 'welcome' } } });+ expect(seen[0].method).toBe('POST');+ expect(seen[0].url.toString()).toBe('https://api.emailit.com/v2/emails');+ expect(seen[0].body).toEqual({ from: '"Acme" <[email protected]>', to: ['[email protected]'], subject: 'Hi', html: '<p>Hi</p>', headers: { 'X-Campaign-ID': 'welcome' } });+ expect(seen[0].headers.get('idempotency-key')).toBeNull();+ expect(result).toMatchObject({ status: 200, body: { id: 'em_1' }, headers: { 'ratelimit-remaining': '9' } });+ });+ test('plain-text content goes in text; the plain-text version goes with HTML', async () => {+ const seen = stubFetch(replies([{ body: SEND_REPLY }]));+ await run({ action: sendEmailAction, props: { ...base, to: ['[email protected]'], content_type: 'text', content: 'hello' } });+ expect(seen[0].body).toMatchObject({ text: 'hello' });+ expect(seen[0].body).not.toHaveProperty('html');+ await run({ action: sendEmailAction, props: { ...base, to: ['[email protected]'], plain_text: 'Hi (text)' } });+ expect(seen[1].body).toMatchObject({ html: '<p>Hi</p>', text: 'Hi (text)' });+ });+ test('recipients are trimmed, split on commas, and empty entries dropped', async () => {+ const seen = stubFetch(replies([{ body: SEND_REPLY }]));+ await run({ action: sendEmailAction, props: { ...base, to: [' [email protected] ', '', '[email protected], [email protected]'], cc: [''], reply_to: '[email protected], [email protected]' } });+ expect(seen[0].body).toMatchObject({ to: ['[email protected]', '[email protected]', '[email protected]'], reply_to: ['[email protected]', '[email protected]'] });+ expect(seen[0].body).not.toHaveProperty('cc');+ });+ test('a comma inside a quoted display name is not split; Emailit rejects it, so the step explains why', async () => {+ const seen = stubFetch(replies([{ body: SEND_REPLY }]));+ await expect(run({ action: sendEmailAction, props: { ...base, to: ['"Doe, Jane" <[email protected]>'] } })).rejects.toThrow('comma inside a display name');+ await run({ action: sendEmailAction, props: { ...base, to: ['"Jane Doe" <[email protected]>, [email protected]'], reply_to: '"Support" <[email protected]>, [email protected]' } });+ expect(seen).toHaveLength(1);+ expect(seen[0].body).toMatchObject({ to: ['"Jane Doe" <[email protected]>', '[email protected]'], reply_to: ['"Support" <[email protected]>', '[email protected]'] });+ });+ test('a sender name Emailit would reject fails clearly instead of being changed', async () => {+ const seen = stubFetch(replies([{ body: SEND_REPLY }]));+ await expect(run({ action: sendEmailAction, props: { ...base, to: ['[email protected]'], from_name: 'Acme "Support"' } })).rejects.toThrow('Sender Name cannot contain quotes');+ await run({ action: sendEmailAction, props: { ...base, to: ['[email protected]'], from_name: 'Acme Support, EU' } });+ expect(seen).toHaveLength(1);+ expect(seen[0].body).toMatchObject({ from: '"Acme Support, EU" <[email protected]>' });+ });+ test('the 50-address limit applies per field, not combined', async () => {+ const seen = stubFetch(replies([{ body: SEND_REPLY }]));+ const fifty = Array.from({ length: 50 }, (_, index) => `u${index}@x.io`);+ await run({ action: sendEmailAction, props: { ...base, to: fifty, cc: fifty, bcc: fifty } });+ expect(seen).toHaveLength(1);+ await expect(run({ action: sendEmailAction, props: { ...base, to: [...fifty, '[email protected]'] } })).rejects.toThrow('at most 50');+ expect(seen).toHaveLength(1);+ });+ test('header injection is refused before any request', async () => {+ const seen = stubFetch(replies([{ body: SEND_REPLY }]));+ await expect(run({ action: sendEmailAction, props: { ...base, to: ['[email protected]'], headers: { 'X-A': 'ok\r\nBcc: [email protected]' } } })).rejects.toThrow('line breaks');+ await expect(run({ action: sendEmailAction, props: { ...base, to: ['[email protected]'], headers: { 'X A\n': 'v' } } })).rejects.toThrow('not a valid header name');+ await expect(run({ action: sendEmailAction, props: { ...base, to: ['[email protected]'], from_name: 'Evil\r\nBcc: x' } })).rejects.toThrow('line breaks');+ await expect(run({ action: sendEmailAction, props: { ...base, to: ['[email protected]\nBcc: [email protected]'] } })).rejects.toThrow('line breaks');+ expect(seen).toHaveLength(0);+ });+ test('idempotency key, schedule, template, variables, meta, tracking and attachments are sent', async () => {+ const seen = stubFetch(replies([{ body: SEND_REPLY }]));+ await run({+ action: sendEmailAction,+ props: {+ from_email: '[email protected]',+ content_type: 'html',+ to: ['[email protected]'],+ template: 'welcome',+ variables: { first_name: 'Ada' },+ meta: { order_id: 1042 },+ scheduled_at: '2026-10-20T09:00:00+02:00',+ tracking: 'off',+ attachments: [{ filename: 'invoice.pdf', url: 'https://files.acme.com/i.pdf' }],+ attachment_file: { filename: 'note.txt', extension: 'txt', data: Buffer.from('hi'), base64: Buffer.from('hi').toString('base64') },+ idempotency_key: 'order-1042',+ },+ });+ expect(seen[0].headers.get('idempotency-key')).toBe('order-1042');+ expect(seen[0].body).toEqual({+ from: '[email protected]',+ to: ['[email protected]'],+ template: 'welcome',+ variables: { first_name: 'Ada' },+ meta: { order_id: '1042' },+ scheduled_at: '2026-10-20T07:00:00.000Z',+ tracking: false,+ attachments: [+ { filename: 'invoice.pdf', url: 'https://files.acme.com/i.pdf' },+ { filename: 'note.txt', content: 'aGk=', content_type: 'text/plain' },+ ],+ });+ });+ test('bad input fails before any request', async () => {+ const seen = stubFetch(replies([{ body: SEND_REPLY }]));+ await expect(run({ action: sendEmailAction, props: { ...base, to: ['[email protected]'], scheduled_at: 'next tuesday-ish' } })).rejects.toThrow('not a valid date-time');+ await expect(run({ action: sendEmailAction, props: { ...base, to: ['[email protected]'], idempotency_key: 'has space' } })).rejects.toThrow('Idempotency Key');+ await expect(run({ action: sendEmailAction, props: { ...base, to: ['[email protected]'], subject: undefined } })).rejects.toThrow('Subject is required');+ await expect(run({ action: sendEmailAction, props: { ...base, to: ['[email protected]'], content: ' ' } })).rejects.toThrow('email body');+ await expect(run({ action: sendEmailAction, props: { ...base, to: [] } })).rejects.toThrow('at least one');+ await expect(run({ action: sendEmailAction, props: { ...base, to: ['[email protected]'], attachments: [{ filename: 'a.pdf', url: 'file:///etc/passwd' }] } })).rejects.toThrow('http');+ expect(seen).toHaveLength(0);+ });+ test('a sandbox rejection explains what to do', async () => {+ stubFetch(replies([{ status: 403, body: { error: 'Workspace not verified', code: 'unverified_workspace_recipient' } }]));+ expect(String(await failure(run({ action: sendEmailAction, props: { ...base, to: ['[email protected]'] } })))).toContain('sandbox mode');+ });+});++describe('send_email_ai', () => {+ test('returns only the email body and sends html + text together', async () => {+ const seen = stubFetch(replies([{ body: SEND_REPLY }]));+ const result = await run({ action: sendEmailAiAction, props: { from_email: '[email protected]', to: ['[email protected]'], subject: 'Hi', html: '<b>x</b>', text: 'x', idempotency_key: 'k-1' } });+ expect(result).toEqual(SEND_REPLY);+ expect(seen[0].body).toMatchObject({ html: '<b>x</b>', text: 'x' });+ expect(seen[0].headers.get('idempotency-key')).toBe('k-1');+ });+});diff --git a/packages/pieces/community/emailit/vitest.config.ts b/packages/pieces/community/emailit/vitest.config.tsnew file mode 100644index 00000000000..79c97261904--- /dev/null+++ b/packages/pieces/community/emailit/vitest.config.ts@@ -0,0 +1,19 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ root: __dirname,+ test: {+ globals: true,+ environment: 'node',+ include: ['test/**/*.test.ts'],+ },+ resolve: {+ alias: {+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),+ },+ },+})