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(drip): let AI agents manage subscribers, tags, orders and email series, and trigger on subscriber events (#16180)
Odai Ahmad46d28539aa03
diff --git a/bun.lock b/bun.lockindex 8ad0c6417de..4bbf8299159 100644--- a/bun.lock+++ b/bun.lock@@ -2768,7 +2768,7 @@},"packages/pieces/community/drip": {"name": "@activepieces/piece-drip",- "version": "0.5.1",+ "version": "0.6.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -2777,6 +2777,7 @@},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/dropbox": {diff --git a/packages/pieces/community/drip/package.json b/packages/pieces/community/drip/package.jsonindex 2215c55c1da..df2ef7d5d15 100644--- a/packages/pieces/community/drip/package.json+++ b/packages/pieces/community/drip/package.json@@ -1,12 +1,13 @@{"name": "@activepieces/piece-drip",- "version": "0.5.1",+ "version": "0.6.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"},"dependencies": {"@activepieces/pieces-common": "workspace:*",@@ -15,6 +16,7 @@"@activepieces/core-utils": "workspace:*"},"devDependencies": {- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"}}diff --git a/packages/pieces/community/drip/src/i18n/translation.json b/packages/pieces/community/drip/src/i18n/translation.jsonindex 51463e643e9..5bf29db68fd 100644--- a/packages/pieces/community/drip/src/i18n/translation.json+++ b/packages/pieces/community/drip/src/i18n/translation.json@@ -1,18 +1,82 @@{- "E-commerce CRM for B2B marketers": "E-commerce CRM for B2B marketers",- "Get it from https://www.getdrip.com/user/edit": "Get it from https://www.getdrip.com/user/edit",+ "Email and SMS marketing automation for e-commerce": "Email and SMS marketing automation for e-commerce",+ "Your Drip API token. In Drip go to Settings → User Settings → API Token (https://www.getdrip.com/user/edit) and copy the token.": "Your Drip API token. In Drip go to Settings → User Settings → API Token (https://www.getdrip.com/user/edit) and copy the token.","Apply a tag to subscriber": "Apply a tag to subscriber","Add a subscriber to a campaign": "Add a subscriber to a campaign","Create or Update Subscriber": "Create or Update Subscriber",+ "Create or Update Subscribers (Batch)": "Create or Update Subscribers (Batch)",+ "Delete Subscriber": "Delete Subscriber",+ "Find Subscriber": "Find Subscriber",+ "Get Broadcast": "Get Broadcast",+ "Get Email Series": "Get Email Series",+ "Get Conversion": "Get Conversion",+ "Get Current User": "Get Current User",+ "Get Form": "Get Form",+ "Get Workflow": "Get Workflow",+ "List Accounts": "List Accounts",+ "List Broadcasts": "List Broadcasts",+ "List Email Series Subscribers": "List Email Series Subscribers",+ "List Email Series": "List Email Series",+ "List Conversions": "List Conversions",+ "List Custom Fields": "List Custom Fields",+ "List Custom Event Names": "List Custom Event Names",+ "List Forms": "List Forms",+ "List Subscriber's Email Series": "List Subscriber's Email Series",+ "List Subscribers": "List Subscribers",+ "List Tags": "List Tags",+ "List Workflows": "List Workflows",+ "Record Cart Activity": "Record Cart Activity",+ "Record Custom Event": "Record Custom Event",+ "Record Order Activity": "Record Order Activity",+ "Remove Subscriber From Email Series": "Remove Subscriber From Email Series",+ "Remove Subscriber From Workflow": "Remove Subscriber From Workflow",+ "Remove Tag From Subscriber": "Remove Tag From Subscriber",+ "Start Workflow for Subscriber": "Start Workflow for Subscriber",+ "Unsubscribe From All Emails": "Unsubscribe From All Emails",+ "Apply Tag (by Account ID)": "Apply Tag (by Account ID)",+ "Create or Update Subscriber (by Account ID)": "Create or Update Subscriber (by Account ID)",+ "Subscribe to Email Series (by Campaign ID)": "Subscribe to Email Series (by Campaign ID)","Custom API Call": "Custom API Call","Apply a tag to a subscriber": "Apply a tag to a subscriber","Add a subscriber to a campaign (Email series)": "Add a subscriber to a campaign (Email series)",+ "Creates or updates up to 1,000 subscribers in one request. Drip processes the batch in the background.": "Creates or updates up to 1,000 subscribers in one request. Drip processes the batch in the background.",+ "Permanently deletes a subscriber and their history. This cannot be undone.": "Permanently deletes a subscriber and their history. This cannot be undone.",+ "Finds one subscriber by email address or Drip subscriber ID.": "Finds one subscriber by email address or Drip subscriber ID.",+ "Gets one Single-Email Campaign (broadcast) by ID.": "Gets one Single-Email Campaign (broadcast) by ID.",+ "Gets one Email Series Campaign by ID.": "Gets one Email Series Campaign by ID.",+ "Gets one conversion goal by ID.": "Gets one conversion goal by ID.",+ "Gets the Drip user who owns the API token.": "Gets the Drip user who owns the API token.",+ "Gets one opt-in form by ID.": "Gets one opt-in form by ID.",+ "Gets one workflow by ID.": "Gets one workflow by ID.",+ "Lists the Drip accounts this API token can access.": "Lists the Drip accounts this API token can access.",+ "Lists Single-Email Campaigns (broadcasts) one page at a time.": "Lists Single-Email Campaigns (broadcasts) one page at a time.",+ "Lists the subscribers of one Email Series Campaign one page at a time.": "Lists the subscribers of one Email Series Campaign one page at a time.",+ "Lists Email Series Campaigns one page at a time.": "Lists Email Series Campaigns one page at a time.",+ "Lists conversion goals one page at a time.": "Lists conversion goals one page at a time.",+ "Lists the custom field identifiers used in the Drip account.": "Lists the custom field identifiers used in the Drip account.",+ "Lists the custom event action names recorded in the Drip account.": "Lists the custom event action names recorded in the Drip account.",+ "Lists the opt-in forms in the Drip account.": "Lists the opt-in forms in the Drip account.",+ "Lists the Email Series Campaign subscriptions of one subscriber.": "Lists the Email Series Campaign subscriptions of one subscriber.",+ "Lists subscribers one page at a time, optionally filtered by status, tags or sign-up date.": "Lists subscribers one page at a time, optionally filtered by status, tags or sign-up date.",+ "Lists every tag used in the Drip account.": "Lists every tag used in the Drip account.",+ "Lists workflows one page at a time.": "Lists workflows one page at a time.",+ "Sends a cart created or updated event to Drip Shopper Activity, e.g. for abandoned-cart workflows.": "Sends a cart created or updated event to Drip Shopper Activity, e.g. for abandoned-cart workflows.",+ "Records a custom event (such as \"Logged in\") for a subscriber. Workflows and rules listening for it may run.": "Records a custom event (such as \"Logged in\") for a subscriber. Workflows and rules listening for it may run.",+ "Sends an order event (placed, updated, paid, fulfilled, refunded or canceled) to Drip Shopper Activity.": "Sends an order event (placed, updated, paid, fulfilled, refunded or canceled) to Drip Shopper Activity.",+ "Removes a subscriber from one Email Series Campaign, or from all of them when no campaign ID is given.": "Removes a subscriber from one Email Series Campaign, or from all of them when no campaign ID is given.",+ "Removes a subscriber from a workflow. Nothing happens if they are not on it.": "Removes a subscriber from a workflow. Nothing happens if they are not on it.",+ "Removes a tag from a subscriber.": "Removes a tag from a subscriber.",+ "Starts a subscriber on an active workflow. The workflow may send emails.": "Starts a subscriber on an active workflow. The workflow may send emails.",+ "Unsubscribes a subscriber from all Drip mailings.": "Unsubscribes a subscriber from all Drip mailings.",+ "Applies a tag to a subscriber by email, without picking the account from a list.": "Applies a tag to a subscriber by email, without picking the account from a list.",+ "Creates a subscriber or updates the one with this email or ID, without picking the account from a list.": "Creates a subscriber or updates the one with this email or ID, without picking the account from a list.",+ "Subscribes a contact to an Email Series Campaign by campaign ID, which starts sending that sequence to them.": "Subscribes a contact to an Email Series Campaign by campaign ID, which starts sending that sequence to them.","Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint","Account": "Account","Subscriber Email": "Subscriber Email","Tag": "Tag","Email Series Campaign": "Email Series Campaign",- "tags": "tags",+ "Tags": "Tags","Custom Fields": "Custom Fields","First Name": "First Name","Last Name": "Last Name",@@ -22,14 +86,66 @@"City": "City","Phone": "Phone","Address": "Address",+ "Account ID": "Account ID",+ "Subscribers": "Subscribers",+ "Subscriber Email or ID": "Subscriber Email or ID",+ "Broadcast ID": "Broadcast ID",+ "Campaign ID": "Campaign ID",+ "Conversion ID": "Conversion ID",+ "Form ID": "Form ID",+ "Workflow ID": "Workflow ID",+ "Status": "Status",+ "Page": "Page",+ "Results per Page": "Results per Page",+ "Subscription Status": "Subscription Status",+ "Has Any of These Tags": "Has Any of These Tags",+ "Created After": "Created After",+ "Created Before": "Created Before",+ "Cart Action": "Cart Action",+ "Cart ID": "Cart ID",+ "Cart URL": "Cart URL",+ "Customer Email": "Customer Email",+ "Drip Person ID": "Drip Person ID",+ "Provider": "Provider",+ "New Person Status": "New Person Status",+ "Occurred At": "Occurred At",+ "Public Cart Number": "Public Cart Number",+ "Grand Total": "Grand Total",+ "Total Discounts": "Total Discounts",+ "Currency": "Currency",+ "Items": "Items",+ "Event Action": "Event Action",+ "Properties": "Properties",+ "Order Action": "Order Action",+ "Order ID": "Order ID",+ "Public Order Number": "Public Order Number",+ "Total Taxes": "Total Taxes",+ "Total Shipping": "Total Shipping",+ "Refund Amount": "Refund Amount",+ "Order URL": "Order URL",+ "Address Line 1": "Address Line 1",+ "Address Line 2": "Address Line 2",+ "State / Region": "State / Region",+ "Postal Code": "Postal Code",+ "Your User ID": "Your User ID",+ "Time Zone": "Time Zone",+ "Email": "Email",+ "New Email": "New Email",+ "SMS Number": "SMS Number",+ "Lifetime Value (cents)": "Lifetime Value (cents)",+ "Add Tags": "Add Tags",+ "Remove Tags": "Remove Tags",+ "Double Opt-In": "Double Opt-In",+ "Starting Email Index": "Starting Email Index",+ "Reactivate if Removed": "Reactivate if Removed","Method": "Method","Headers": "Headers","Query Parameters": "Query Parameters","Body Type": "Body Type","Body": "Body",- "Response is Binary ?": "Response is Binary ?",- "No Error on Failure": "No Error on Failure",- "Timeout (in seconds)": "Timeout (in seconds)",+ "Response is Binary": "Response is Binary",+ "Return Error as Output": "Return Error as Output",+ "Timeout": "Timeout","Follow redirects": "Follow redirects","Email of the subscriber": "Email of the subscriber","Tag to apply": "Tag to apply",@@ -40,21 +156,118 @@"The region in which the subscriber resides": "The region in which the subscriber resides","The city in which the subscriber resides": "The city in which the subscriber resides","The subscriber's primary phone number": "The subscriber's primary phone number",- "The subscriber's mailing address": "The subscriber's mailing address",+ "Address line 1 of the subscriber's mailing address": "Address line 1 of the subscriber's mailing address",+ "Drip account ID (digits, from List Accounts or the Drip URL). Leave empty when the API token has only one account.": "Drip account ID (digits, from List Accounts or the Drip URL). Leave empty when the API token has only one account.",+ "A JSON array of 1 to 1,000 subscriber objects. Each needs \"email\" or \"id\"; other keys use Drip names, e.g. [{\"email\": \"[email protected]\", \"first_name\": \"Jane\", \"tags\": [\"Customer\"]}].": "A JSON array of 1 to 1,000 subscriber objects. Each needs \"email\" or \"id\"; other keys use Drip names, e.g. [{\"email\": \"[email protected]\", \"first_name\": \"Jane\", \"tags\": [\"Customer\"]}].",+ "The subscriber email address or Drip subscriber ID.": "The subscriber email address or Drip subscriber ID.",+ "Single-Email Campaign ID (digits, from List Broadcasts).": "Single-Email Campaign ID (digits, from List Broadcasts).",+ "Email Series Campaign ID (digits, from List Email Series).": "Email Series Campaign ID (digits, from List Email Series).",+ "Conversion ID (digits, from List Conversions).": "Conversion ID (digits, from List Conversions).",+ "Form ID (digits, from List Forms).": "Form ID (digits, from List Forms).",+ "Workflow ID (digits, from List Workflows).": "Workflow ID (digits, from List Workflows).",+ "Only broadcasts with this status. Defaults to all except deleted.": "Only broadcasts with this status. Defaults to all except deleted.",+ "Page number, starting at 1. Pass the next page while Has More is true.": "Page number, starting at 1. Pass the next page while Has More is true.",+ "How many results per page (1-100).": "How many results per page (1-100).",+ "Defaults to active.": "Defaults to active.",+ "How many results per page (1-1000).": "How many results per page (1-1000).",+ "Only campaigns with this status. Defaults to all.": "Only campaigns with this status. Defaults to all.",+ "Only conversions with this status.": "Only conversions with this status.",+ "Which subscribers to return. Drip defaults to Active.": "Which subscribers to return. Drip defaults to Active.",+ "Only return subscribers with at least one of these tags.": "Only return subscribers with at least one of these tags.",+ "Only subscribers created after this date-time (ISO-8601).": "Only subscribers created after this date-time (ISO-8601).",+ "Only subscribers created before this date-time (ISO-8601).": "Only subscribers created before this date-time (ISO-8601).",+ "Only workflows with this status. Defaults to all.": "Only workflows with this status. Defaults to all.",+ "Your unique internal cart ID.": "Your unique internal cart ID.",+ "Link back to the shopper cart in your store.": "Link back to the shopper cart in your store.",+ "Email of the customer. Either this or Drip Person ID is required.": "Email of the customer. Either this or Drip Person ID is required.",+ "Drip subscriber ID of the customer. Used instead of the email when both are given.": "Drip subscriber ID of the customer. Used instead of the email when both are given.",+ "Lower snake_case name of the store platform, e.g. shopify or my_store. Drip treats provider + ID as the unique key.": "Lower snake_case name of the store platform, e.g. shopify or my_store. Drip treats provider + ID as the unique key.",+ "Status for a person Drip creates from this activity. Drip subscribes them (active) when left empty; choose Unsubscribed if they have not consented to marketing.": "Status for a person Drip creates from this activity. Drip subscribes them (active) when left empty; choose Unsubscribed if they have not consented to marketing.",+ "When it happened (ISO-8601). Defaults to now.": "When it happened (ISO-8601). Defaults to now.",+ "Cart total after discounts, e.g. 16.99.": "Cart total after discounts, e.g. 16.99.",+ "ISO 4217 code, e.g. USD.": "ISO 4217 code, e.g. USD.",+ "Optional JSON array of cart items. Each needs \"product_id\", \"product_variant_id\", \"name\" and \"price\"; e.g. [{\"product_id\": \"B01\", \"product_variant_id\": \"B01\", \"name\": \"Water Bottle\", \"price\": 11.16, \"quantity\": 2}].": "Optional JSON array of cart items. Each needs \"product_id\", \"product_variant_id\", \"name\" and \"price\"; e.g. [{\"product_id\": \"B01\", \"product_variant_id\": \"B01\", \"name\": \"Water Bottle\", \"price\": 11.16, \"quantity\": 2}].",+ "The event name, e.g. Logged in. Reuse names from List Custom Event Names.": "The event name, e.g. Logged in. Reuse names from List Custom Event Names.",+ "Optional event properties. For a conversion, add \"value\" in cents.": "Optional event properties. For a conversion, add \"value\" in cents.",+ "When the event happened (ISO-8601). Defaults to now.": "When the event happened (ISO-8601). Defaults to now.",+ "Your unique internal order ID. Provider + Order ID identify the order.": "Your unique internal order ID. Provider + Order ID identify the order.",+ "Customer-facing order number, e.g. #1001.": "Customer-facing order number, e.g. #1001.",+ "Order total after discounts, e.g. 49.99.": "Order total after discounts, e.g. 49.99.",+ "For refunded or canceled orders: the amount refunded. Leave Grand Total unchanged.": "For refunded or canceled orders: the amount refunded. Leave Grand Total unchanged.",+ "Optional JSON array of line items. Each needs \"name\"; e.g. [{\"product_id\": \"B01\", \"name\": \"Water Bottle\", \"price\": 11.16, \"quantity\": 2}].": "Optional JSON array of line items. Each needs \"name\"; e.g. [{\"product_id\": \"B01\", \"name\": \"Water Bottle\", \"price\": 11.16, \"quantity\": 2}].",+ "Email Series Campaign ID (from List Email Series). Leave empty to remove the subscriber from all email series.": "Email Series Campaign ID (from List Email Series). Leave empty to remove the subscriber from all email series.",+ "The tag to remove.": "The tag to remove.",+ "Workflow ID (digits, from List Workflows). The workflow must be active.": "Workflow ID (digits, from List Workflows). The workflow must be active.",+ "Email address of the person to start, or the Drip subscriber ID of an existing one.": "Email address of the person to start, or the Drip subscriber ID of an existing one.",+ "Your own ID for this person, e.g. the primary key in your database.": "Your own ID for this person, e.g. the primary key in your database.",+ "Olson time zone, e.g. America/Los_Angeles.": "Olson time zone, e.g. America/Los_Angeles.",+ "Custom field values keyed by field identifier, e.g. {\"shirt_size\": \"Medium\"}. A new identifier creates the custom field in Drip.": "Custom field values keyed by field identifier, e.g. {\"shirt_size\": \"Medium\"}. A new identifier creates the custom field in Drip.",+ "Tags to apply to the subscriber.": "Tags to apply to the subscriber.",+ "The subscriber email address.": "The subscriber email address.",+ "The tag to apply, e.g. Customer.": "The tag to apply, e.g. Customer.",+ "Email address of the subscriber to create or update, or the Drip subscriber ID of an existing one.": "Email address of the subscriber to create or update, or the Drip subscriber ID of an existing one.",+ "Change the subscriber email address to this one.": "Change the subscriber email address to this one.",+ "Mobile number in E.164 format, e.g. +16125551212 (US numbers only).": "Mobile number in E.164 format, e.g. +16125551212 (US numbers only).",+ "Total the customer has spent, in cents (e.g. 2500 = $25.00).": "Total the customer has spent, in cents (e.g. 2500 = $25.00).",+ "Tags to remove from the subscriber.": "Tags to remove from the subscriber.",+ "Send the double opt-in confirmation email first. Off by default.": "Send the double opt-in confirmation email first. Off by default.",+ "Zero-based index of the first email to send. Defaults to 0 (the first email).": "Zero-based index of the first email to send. Defaults to 0 (the first email).",+ "Re-subscribe the contact if they were removed from this series before. When off, Drip rejects such contacts. Drip defaults to on.": "Re-subscribe the contact if they were removed from this series before. When off, Drip rejects such contacts. Drip defaults to on.",+ "The subscriber time zone in Olson format, e.g. America/Los_Angeles.": "The subscriber time zone in Olson format, e.g. America/Los_Angeles.","Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.",+ "Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.","Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.",+ "On a failed request, output the error instead of failing the step.": "On a failed request, output the error instead of failing the step.",+ "Seconds to wait for a response. Empty: up to the flow limit (10 min).": "Seconds to wait for a response. Empty: up to the flow limit (10 min).",+ "Follow 3xx redirects instead of returning them as the response.": "Follow 3xx redirects instead of returning them as the response.",+ "All except deleted": "All except deleted",+ "Draft": "Draft",+ "Scheduled": "Scheduled",+ "Sending": "Sending",+ "Sent": "Sent",+ "Canceled": "Canceled",+ "Active": "Active",+ "Unsubscribed": "Unsubscribed",+ "Removed": "Removed",+ "All": "All",+ "Paused": "Paused",+ "Disabled": "Disabled",+ "Active or unsubscribed": "Active or unsubscribed",+ "Undeliverable": "Undeliverable",+ "Created": "Created",+ "Updated": "Updated",+ "Active (subscribed)": "Active (subscribed)",+ "Placed": "Placed",+ "Paid": "Paid",+ "Fulfilled": "Fulfilled",+ "Refunded": "Refunded","GET": "GET","POST": "POST","PATCH": "PATCH","PUT": "PUT","DELETE": "DELETE","HEAD": "HEAD",- "None": "None",- "JSON": "JSON",- "Form Data": "Form Data",- "Raw": "Raw","New Subscriber": "New Subscriber","Tag Applied": "Tag Applied",+ "Completed Email Series": "Completed Email Series",+ "Custom Event Performed": "Custom Event Performed",+ "Email Link Clicked": "Email Link Clicked",+ "Removed From Email Series": "Removed From Email Series",+ "Subscribed to Email Series": "Subscribed to Email Series",+ "Subscriber Deleted": "Subscriber Deleted",+ "Subscriber Unsubscribed From All": "Subscriber Unsubscribed From All",+ "Tag Removed": "Tag Removed","Triggers when a subscriber is created in your Drip account.": "Triggers when a subscriber is created in your Drip account.",- "Triggers when a tag is applied.": "Triggers when a tag is applied."+ "Triggers when a tag is applied.": "Triggers when a tag is applied.",+ "Triggers when a subscriber completes an Email Series Campaign.": "Triggers when a subscriber completes an Email Series Campaign.",+ "Triggers when a custom event is recorded for a subscriber.": "Triggers when a custom event is recorded for a subscriber.",+ "Triggers when a subscriber clicks a link in a Drip email. Can be high volume.": "Triggers when a subscriber clicks a link in a Drip email. Can be high volume.",+ "Triggers when a subscriber is removed from an Email Series Campaign.": "Triggers when a subscriber is removed from an Email Series Campaign.",+ "Triggers when a subscriber subscribes to an Email Series Campaign.": "Triggers when a subscriber subscribes to an Email Series Campaign.",+ "Triggers when a subscriber is deleted from your Drip account.": "Triggers when a subscriber is deleted from your Drip account.",+ "Triggers when a subscriber unsubscribes from all mailings.": "Triggers when a subscriber unsubscribes from all mailings.",+ "Triggers when a tag is removed from a subscriber.": "Triggers when a tag is removed from a subscriber.",+ "Only trigger for this tag (not case-sensitive). Leave empty for every tag.": "Only trigger for this tag (not case-sensitive). Leave empty for every tag.",+ "Only trigger for this email series. Leave empty for all.": "Only trigger for this email series. Leave empty for all.",+ "Only trigger for this event name (not case-sensitive). Leave empty for every custom event.": "Only trigger for this event name (not case-sensitive). Leave empty for every custom event."}\ No newline at end of filediff --git a/packages/pieces/community/drip/src/index.ts b/packages/pieces/community/drip/src/index.tsindex 8b770269147..5b7e238fb50 100644--- a/packages/pieces/community/drip/src/index.ts+++ b/packages/pieces/community/drip/src/index.ts@@ -1,34 +1,115 @@import { createCustomApiCallAction } from '@activepieces/pieces-common';-import { PieceAuth, createPiece } from '@activepieces/pieces-framework';-import { PieceCategory } from '@activepieces/pieces-framework';+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';import { dripAddSubscriberToCampaign } from './lib/actions/add-subscriber-to-campaign.action';import { dripApplyTagToSubscriber } from './lib/actions/apply-tag-to-subscriber.action';+import { batchUpsertSubscribersAction } from './lib/actions/batch-upsert-subscribers.action';+import { deleteSubscriberAction } from './lib/actions/delete-subscriber.action';+import { findSubscriberAction } from './lib/actions/find-subscriber.action';+import { getBroadcastAction } from './lib/actions/get-broadcast.action';+import { getCampaignAction } from './lib/actions/get-campaign.action';+import { getConversionAction } from './lib/actions/get-conversion.action';+import { getCurrentUserAction } from './lib/actions/get-current-user.action';+import { getFormAction } from './lib/actions/get-form.action';+import { getWorkflowAction } from './lib/actions/get-workflow.action';+import { listAccountsAction } from './lib/actions/list-accounts.action';+import { listBroadcastsAction } from './lib/actions/list-broadcasts.action';+import { listCampaignSubscribersAction } from './lib/actions/list-campaign-subscribers.action';+import { listCampaignsAction } from './lib/actions/list-campaigns.action';+import { listConversionsAction } from './lib/actions/list-conversions.action';+import { listCustomFieldsAction } from './lib/actions/list-custom-fields.action';+import { listEventActionsAction } from './lib/actions/list-event-actions.action';+import { listFormsAction } from './lib/actions/list-forms.action';+import { listSubscriberCampaignsAction } from './lib/actions/list-subscriber-campaigns.action';+import { listSubscribersAction } from './lib/actions/list-subscribers.action';+import { listTagsAction } from './lib/actions/list-tags.action';+import { listWorkflowsAction } from './lib/actions/list-workflows.action';+import { recordCartAction } from './lib/actions/record-cart.action';+import { recordEventAction } from './lib/actions/record-event.action';+import { recordOrderAction } from './lib/actions/record-order.action';+import { removeFromCampaignAction } from './lib/actions/remove-from-campaign.action';+import { removeFromWorkflowAction } from './lib/actions/remove-from-workflow.action';+import { removeTagAction } from './lib/actions/remove-tag.action';+import { startWorkflowAction } from './lib/actions/start-workflow.action';+import { unsubscribeSubscriberAction } from './lib/actions/unsubscribe-subscriber.action';import { dripUpsertSubscriberAction } from './lib/actions/upsert-subscriber.action';+import { applyTagAction } from './lib/actions/ai/apply-tag.action';+import { createOrUpdateSubscriberAction } from './lib/actions/ai/create-or-update-subscriber.action';+import { subscribeToCampaignAction } from './lib/actions/ai/subscribe-to-campaign.action';+import { dripCompletedCampaignEvent } from './lib/trigger/completed-campaign.trigger';+import { dripCustomEventPerformedEvent } from './lib/trigger/custom-event-performed.trigger';+import { dripEmailClickedEvent } from './lib/trigger/email-clicked.trigger';import { dripNewSubscriberEvent } from './lib/trigger/new-subscriber.trigger';import { dripTagAppliedEvent } from './lib/trigger/new-tag.trigger';+import { dripRemovedFromCampaignEvent } from './lib/trigger/removed-from-campaign.trigger';+import { dripSubscribedToCampaignEvent } from './lib/trigger/subscribed-to-campaign.trigger';+import { dripSubscriberDeletedEvent } from './lib/trigger/subscriber-deleted.trigger';+import { dripSubscriberUnsubscribedEvent } from './lib/trigger/subscriber-unsubscribed.trigger';+import { dripTagRemovedEvent } from './lib/trigger/tag-removed.trigger';import { dripAuth } from './lib/auth';+import { dripApi } from './lib/common/client';export const drip = createPiece({displayName: 'Drip',- description: 'E-commerce CRM for B2B marketers',- minimumSupportedRelease: '0.30.0',+ description: 'Email and SMS marketing automation for e-commerce',+ minimumSupportedRelease: '0.88.2',logoUrl: 'https://cdn.activepieces.com/pieces/drip.png',- authors: ["kishanprmr","MoShizzle","AbdulTheActivePiecer","khaledmashaly","abuaboud"],+ authors: ['kishanprmr', 'MoShizzle', 'AbdulTheActivePiecer', 'khaledmashaly', 'abuaboud'],categories: [PieceCategory.MARKETING],auth: dripAuth,actions: [dripApplyTagToSubscriber,dripAddSubscriberToCampaign,dripUpsertSubscriberAction,+ batchUpsertSubscribersAction,+ deleteSubscriberAction,+ findSubscriberAction,+ getBroadcastAction,+ getCampaignAction,+ getConversionAction,+ getCurrentUserAction,+ getFormAction,+ getWorkflowAction,+ listAccountsAction,+ listBroadcastsAction,+ listCampaignSubscribersAction,+ listCampaignsAction,+ listConversionsAction,+ listCustomFieldsAction,+ listEventActionsAction,+ listFormsAction,+ listSubscriberCampaignsAction,+ listSubscribersAction,+ listTagsAction,+ listWorkflowsAction,+ recordCartAction,+ recordEventAction,+ recordOrderAction,+ removeFromCampaignAction,+ removeFromWorkflowAction,+ removeTagAction,+ startWorkflowAction,+ unsubscribeSubscriberAction,+ applyTagAction,+ createOrUpdateSubscriberAction,+ subscribeToCampaignAction,createCustomApiCallAction({- baseUrl: () => `https://api.getdrip.com/v2/`,+ baseUrl: () => `${dripApi.DRIP_ORIGIN}/v2/`,auth: dripAuth,authMapping: async (auth) => ({- Authorization: `Basic ${Buffer.from(auth.secret_text).toString(- 'base64'- )}`,+ Authorization: dripApi.authHeader(auth.secret_text),}),}),],- triggers: [dripNewSubscriberEvent, dripTagAppliedEvent],+ triggers: [+ dripNewSubscriberEvent,+ dripTagAppliedEvent,+ dripCompletedCampaignEvent,+ dripCustomEventPerformedEvent,+ dripEmailClickedEvent,+ dripRemovedFromCampaignEvent,+ dripSubscribedToCampaignEvent,+ dripSubscriberDeletedEvent,+ dripSubscriberUnsubscribedEvent,+ dripTagRemovedEvent,+ ],});diff --git a/packages/pieces/community/drip/src/lib/actions/add-subscriber-to-campaign.action.ts b/packages/pieces/community/drip/src/lib/actions/add-subscriber-to-campaign.action.tsindex 7c5814211a4..5f89447226c 100644--- a/packages/pieces/community/drip/src/lib/actions/add-subscriber-to-campaign.action.ts+++ b/packages/pieces/community/drip/src/lib/actions/add-subscriber-to-campaign.action.ts@@ -1,80 +1,37 @@-import { createAction, Property } from '@activepieces/pieces-framework';-import {- HttpRequest,- HttpMethod,- httpClient,-} from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';import { dripCommon } from '../common';+import { dripApi } from '../common/client';import { dripAuth } from '../auth';+import { dripOutputSchemas } from '../output-schemas';export const dripAddSubscriberToCampaign = createAction({auth: dripAuth,name: 'add_subscriber_to_campaign',classification: 'WRITE',description: 'Add a subscriber to a campaign (Email series)',- audience: 'both',- aiMetadata: { description: 'Subscribes a contact (by email) to a Drip email-series campaign in the given account, optionally attaching tags and custom fields. Use to enroll someone into an automated email sequence. Requires an existing campaign id (selectable from the account). Not idempotent: each call re-subscribes and can re-trigger the series.', idempotent: false },+ audience: 'human',+ aiMetadata: {+ description:+ "Subscribes a contact (by email) to a Drip Email Series Campaign picked from the account, optionally attaching tags and custom fields; this starts the sequence, and if the series has double opt-in on, Drip first emails a confirmation. Not idempotent: each call re-subscribes and can restart the series.",+ idempotent: false,+ },displayName: 'Add a subscriber to a campaign',props: {account_id: dripCommon.account_id,- campaign_id: Property.Dropdown({- displayName: 'Email Series Campaign',- auth: dripAuth,- refreshers: ['account_id'],- required: true,- options: async ({ auth, account_id }) => {- if (!auth) {- return {- disabled: true,- options: [],- placeholder: 'Please fill in API key first',- };- }- if (!account_id) {- return {- disabled: true,- options: [],- placeholder: 'Please select an account first',- };- }- const request: HttpRequest = {- method: HttpMethod.GET,- url: `${dripCommon.baseUrl(account_id as string)}/campaigns`,- headers: {- Authorization: `Basic ${Buffer.from(auth .secret_text).toString(- 'base64'- )}`,- },- };- const response = await httpClient.sendRequest<{- campaigns: { name: string; id: string }[];- }>(request);- const opts = response.body.campaigns.map((campaign) => {- return { value: campaign.id, label: campaign.name };- });- if (opts.length === 0) {- return {- disabled: false,- options: [],- placeholder: 'Please create an email series campaign',- };- }- return {- disabled: false,- options: opts,- };- },- }),+ campaign_id: dripCommon.campaign_id({ required: true }),subscriber: dripCommon.subscriber,tags: dripCommon.tags,custom_fields: dripCommon.custom_fields,},+ outputSchema: dripOutputSchemas.legacySubscribersResponse,async run({ auth, propsValue }) {- const request: HttpRequest = {+ const campaignId = dripApi.seg({ value: propsValue.campaign_id, label: 'Email Series Campaign' });+ return await dripApi.send<Record<string, unknown>>({+ token: auth.secret_text,method: HttpMethod.POST,- url: `${dripCommon.baseUrl(propsValue.account_id)}/campaigns/${- propsValue.campaign_id- }/subscribers`,+ path: `${dripApi.accountPath(propsValue.account_id)}/campaigns/${campaignId}/subscribers`,+ operation: 'add subscriber to email series',body: {subscribers: [{@@ -84,11 +41,6 @@ export const dripAddSubscriberToCampaign = createAction({},],},- headers: {- Authorization: dripCommon.authorizationHeader(auth),- },- queryParams: {},- };- return await httpClient.sendRequest<Record<string, never>>(request);+ });},});diff --git a/packages/pieces/community/drip/src/lib/actions/ai/apply-tag.action.ts b/packages/pieces/community/drip/src/lib/actions/ai/apply-tag.action.tsnew file mode 100644index 00000000000..e68b61793a0--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/ai/apply-tag.action.ts@@ -0,0 +1,40 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { dripAuth } from '../../auth';+import { dripApi } from '../../common/client';+import { dripProps } from '../../common/props';+import { dripOutputSchemas } from '../../output-schemas';++export const applyTagAction = createAction({+ auth: dripAuth,+ name: 'apply_tag',+ displayName: 'Apply Tag (by Account ID)',+ description: 'Applies a tag to a subscriber by email, without picking the account from a list.',+ classification: 'WRITE',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Applies a tag to a Drip subscriber identified by email address. If no subscriber has that email, Drip creates one (active) with the tag. Workflows or rules that start on this tag may run. Applying a tag the subscriber already has changes nothing, so it is idempotent.',+ idempotent: true,+ },+ props: {+ accountId: dripProps.accountId(),+ email: dripProps.email(),+ tag: Property.ShortText({ displayName: 'Tag', description: 'The tag to apply, e.g. Customer.', required: true }),+ },+ outputSchema: dripOutputSchemas.applyTag,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const email = dripApi.requireText({ value: propsValue.email, label: 'Email' });+ const tag = dripApi.requireText({ value: propsValue.tag, label: 'Tag' });+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ await dripApi.request<unknown>({+ token,+ method: HttpMethod.POST,+ path: `${dripApi.accountPath(accountId)}/tags`,+ operation: 'apply tag',+ body: { tags: [{ email, tag }] },+ });+ return { email, tag, applied: true };+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/ai/create-or-update-subscriber.action.ts b/packages/pieces/community/drip/src/lib/actions/ai/create-or-update-subscriber.action.tsnew file mode 100644index 00000000000..152e10fd55a--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/ai/create-or-update-subscriber.action.ts@@ -0,0 +1,57 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { dripAuth } from '../../auth';+import { dripApi } from '../../common/client';+import { dripProps } from '../../common/props';+import { subscriberFieldProps, subscriberInput } from '../../common/subscriber-input';+import { dripOutputSchemas } from '../../output-schemas';++export const createOrUpdateSubscriberAction = createAction({+ auth: dripAuth,+ name: 'create_or_update_subscriber',+ displayName: 'Create or Update Subscriber (by Account ID)',+ description: 'Creates a subscriber or updates the one with this email or ID, without picking the account from a list.',+ classification: 'WRITE',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates a Drip subscriber or updates the one with this email (or Drip subscriber ID), setting name, address, phone, time zone, lifetime value and custom fields, adding tags and removing tags; New Email changes their address. Fields you leave out stay unchanged. Matched on email or ID, so repeating the same input is idempotent.',+ idempotent: true,+ },+ props: {+ accountId: dripProps.accountId(),+ subscriber: dripProps.subscriber({ description: 'Email address of the subscriber to create or update, or the Drip subscriber ID of an existing one.' }),+ newEmail: Property.ShortText({ displayName: 'New Email', description: 'Change the subscriber email address to this one.', required: false }),+ ...subscriberFieldProps,+ smsNumber: Property.ShortText({ displayName: 'SMS Number', description: 'Mobile number in E.164 format, e.g. +16125551212 (US numbers only).', required: false }),+ lifetimeValue: Property.Number({ displayName: 'Lifetime Value (cents)', description: 'Total the customer has spent, in cents (e.g. 2500 = $25.00).', required: false }),+ customFields: dripProps.customFields(),+ tags: dripProps.tags({ displayName: 'Add Tags' }),+ removeTags: dripProps.tags({ displayName: 'Remove Tags', description: 'Tags to remove from the subscriber.' }),+ },+ outputSchema: dripOutputSchemas.subscriber,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const identity = dripApi.identify({ value: propsValue.subscriber, label: 'Subscriber Email or ID' });+ const removeTags = dripApi.textList(propsValue.removeTags);+ const record = {+ ...subscriberInput.fields(propsValue),+ ...identity,+ ...dripApi.compact({+ new_email: dripApi.optionalText(propsValue.newEmail),+ sms_number: dripApi.optionalText(propsValue.smsNumber),+ lifetime_value: dripApi.validateInteger({ value: propsValue.lifetimeValue, label: 'Lifetime Value (cents)', min: 0, max: 2_147_483_647 }),+ remove_tags: removeTags && removeTags.length > 0 ? removeTags : undefined,+ }),+ };+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ const body = await dripApi.request<unknown>({+ token,+ method: HttpMethod.POST,+ path: `${dripApi.accountPath(accountId)}/subscribers`,+ operation: 'create or update subscriber',+ body: { subscribers: [record] },+ });+ return dripApi.firstRecord({ body, key: 'subscribers', operation: 'create or update subscriber' });+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/ai/subscribe-to-campaign.action.ts b/packages/pieces/community/drip/src/lib/actions/ai/subscribe-to-campaign.action.tsnew file mode 100644index 00000000000..17f3368c73e--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/ai/subscribe-to-campaign.action.ts@@ -0,0 +1,66 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { dripAuth } from '../../auth';+import { dripApi } from '../../common/client';+import { dripProps } from '../../common/props';+import { dripOutputSchemas } from '../../output-schemas';++export const subscribeToCampaignAction = createAction({+ auth: dripAuth,+ name: 'subscribe_to_campaign',+ displayName: 'Subscribe to Email Series (by Campaign ID)',+ description: 'Subscribes a contact to an Email Series Campaign by campaign ID, which starts sending that sequence to them.',+ classification: 'WRITE',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Subscribes a contact by email to a Drip Email Series Campaign by Campaign ID (from List Email Series), creating the subscriber if needed; this starts sending that email sequence to them. The double opt-in confirmation email is skipped unless Double Opt-In is true. Not idempotent: a repeat call can restart the series for a subscriber who was removed from it.',+ idempotent: false,+ },+ props: {+ accountId: dripProps.accountId(),+ campaignId: Property.ShortText({ displayName: 'Campaign ID', description: 'Email Series Campaign ID (digits, from List Email Series).', required: true }),+ email: dripProps.email(),+ doubleOptin: Property.Checkbox({+ displayName: 'Double Opt-In',+ description: 'Send the double opt-in confirmation email first. Off by default.',+ required: false,+ defaultValue: false,+ }),+ startingEmailIndex: Property.Number({ displayName: 'Starting Email Index', description: 'Zero-based index of the first email to send. Defaults to 0 (the first email).', required: false }),+ reactivateIfRemoved: Property.Checkbox({+ displayName: 'Reactivate if Removed',+ description: 'Re-subscribe the contact if they were removed from this series before. When off, Drip rejects such contacts. Drip defaults to on.',+ required: false,+ defaultValue: true,+ }),+ timeZone: dripProps.timeZone(),+ tags: dripProps.tags(),+ customFields: dripProps.customFields(),+ },+ outputSchema: dripOutputSchemas.campaignSubscribe,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const campaignId = dripApi.parseNumericId({ value: propsValue.campaignId, label: 'Campaign ID' });+ const email = dripApi.requireText({ value: propsValue.email, label: 'Email' });+ const tags = dripApi.textList(propsValue.tags);+ const record = dripApi.compact({+ email,+ double_optin: propsValue.doubleOptin === true,+ starting_email_index: dripApi.validateInteger({ value: propsValue.startingEmailIndex, label: 'Starting Email Index', min: 0, max: 10_000 }),+ reactivate_if_removed: typeof propsValue.reactivateIfRemoved === 'boolean' ? propsValue.reactivateIfRemoved : undefined,+ time_zone: dripApi.optionalText(propsValue.timeZone),+ tags: tags && tags.length > 0 ? tags : undefined,+ custom_fields: dripApi.parseObject({ value: propsValue.customFields, label: 'Custom Fields' }),+ });+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ const body = await dripApi.request<unknown>({+ token,+ method: HttpMethod.POST,+ path: `${dripApi.accountPath(accountId)}/campaigns/${campaignId}/subscribers`,+ operation: 'subscribe to email series',+ body: { subscribers: [record] },+ });+ return { campaignId, subscriber: dripApi.firstRecord({ body, key: 'subscribers', operation: 'subscribe to email series' }) };+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/apply-tag-to-subscriber.action.ts b/packages/pieces/community/drip/src/lib/actions/apply-tag-to-subscriber.action.tsindex c6ecce41845..ba7314e4e4b 100644--- a/packages/pieces/community/drip/src/lib/actions/apply-tag-to-subscriber.action.ts+++ b/packages/pieces/community/drip/src/lib/actions/apply-tag-to-subscriber.action.ts@@ -1,19 +1,21 @@import { createAction, Property } from '@activepieces/pieces-framework';-import {- HttpRequest,- HttpMethod,- httpClient,-} from '@activepieces/pieces-common';+import { HttpMethod } from '@activepieces/pieces-common';import { dripCommon } from '../common';+import { dripApi } from '../common/client';import { dripAuth } from '../auth';+import { dripOutputSchemas } from '../output-schemas';export const dripApplyTagToSubscriber = createAction({auth: dripAuth,name: 'apply_tag_to_subscriber',classification: 'WRITE',description: 'Apply a tag to a subscriber',- audience: 'both',- aiMetadata: { description: 'Applies a tag to a subscriber in a Drip account, identifying the subscriber by email address. Use to label or segment a contact. Repeating with the same email and tag has no additional effect, so it is idempotent.', idempotent: true },+ audience: 'human',+ aiMetadata: {+ description:+ 'Applies a tag to a subscriber in a Drip account, identifying the subscriber by email address; if no subscriber has that email, Drip creates one with the tag. Repeating with the same email and tag has no additional effect, so it is idempotent.',+ idempotent: true,+ },displayName: 'Apply a tag to subscriber',props: {account_id: dripCommon.account_id,@@ -24,10 +26,13 @@ export const dripApplyTagToSubscriber = createAction({description: 'Tag to apply',}),},+ outputSchema: dripOutputSchemas.legacyEmptyResponse,async run({ auth, propsValue }) {- const request: HttpRequest = {+ return await dripApi.send<Record<string, never>>({+ token: auth.secret_text,method: HttpMethod.POST,- url: `${dripCommon.baseUrl(propsValue.account_id)}/tags`,+ path: `${dripApi.accountPath(propsValue.account_id)}/tags`,+ operation: 'apply tag',body: {tags: [{@@ -36,11 +41,6 @@ export const dripApplyTagToSubscriber = createAction({},],},- headers: {- Authorization: dripCommon.authorizationHeader(auth),- },- queryParams: {},- };- return await httpClient.sendRequest<Record<string, never>>(request);+ });},});diff --git a/packages/pieces/community/drip/src/lib/actions/batch-upsert-subscribers.action.ts b/packages/pieces/community/drip/src/lib/actions/batch-upsert-subscribers.action.tsnew file mode 100644index 00000000000..5ecb5787b86--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/batch-upsert-subscribers.action.ts@@ -0,0 +1,53 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripApi } from '../common/client';+import { dripProps } from '../common/props';+import { dripOutputSchemas } from '../output-schemas';++const MAX_BATCH = 1000;++export const batchUpsertSubscribersAction = createAction({+ auth: dripAuth,+ name: 'batch_upsert_subscribers',+ displayName: 'Create or Update Subscribers (Batch)',+ description: 'Creates or updates up to 1,000 subscribers in one request. Drip processes the batch in the background.',+ classification: 'WRITE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Creates or updates up to 1,000 Drip subscribers in one call; each item is a subscriber object with an email or id plus optional fields such as first_name, tags or custom_fields. Drip processes the batch in the background (changes appear after a delay) and allows only 50 batch calls per hour. Matched on email or id, so repeating the same batch is idempotent.',+ idempotent: true,+ },+ props: {+ accountId: dripProps.accountId(),+ subscribers: Property.Json({+ displayName: 'Subscribers',+ description:+ 'A JSON array of 1 to 1,000 subscriber objects. Each needs "email" or "id"; other keys use Drip names, e.g. [{"email": "[email protected]", "first_name": "Jane", "tags": ["Customer"]}].',+ required: true,+ defaultValue: [{ email: '[email protected]', first_name: 'Jane', tags: ['Customer'] }],+ }),+ },+ outputSchema: dripOutputSchemas.batchUpsert,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const subscribers = dripApi.parseArray({ value: propsValue.subscribers, label: 'Subscribers' }) ?? [];+ if (subscribers.length < 1 || subscribers.length > MAX_BATCH) {+ throw new Error(`Subscribers must contain between 1 and ${MAX_BATCH} items (got ${subscribers.length}).`);+ }+ const invalid = subscribers.findIndex((item) => !dripApi.isRecord(item) || (dripApi.optionalText(item['email']) === undefined && dripApi.optionalText(item['id']) === undefined));+ if (invalid !== -1) {+ throw new Error(`Subscriber #${invalid + 1} must be an object with an "email" or "id".`);+ }+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ await dripApi.request<unknown>({+ token,+ method: HttpMethod.POST,+ path: `${dripApi.accountPath(accountId)}/subscribers/batches`,+ operation: 'batch create or update subscribers',+ body: { batches: [{ subscribers }] },+ });+ return { submitted: subscribers.length, accepted: true };+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/delete-subscriber.action.ts b/packages/pieces/community/drip/src/lib/actions/delete-subscriber.action.tsnew file mode 100644index 00000000000..9dd1322b3ba--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/delete-subscriber.action.ts@@ -0,0 +1,45 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripApi } from '../common/client';+import { dripProps } from '../common/props';+import { dripOutputSchemas } from '../output-schemas';++export const deleteSubscriberAction = createAction({+ auth: dripAuth,+ name: 'delete_subscriber',+ displayName: 'Delete Subscriber',+ description: 'Permanently deletes a subscriber and their history. This cannot be undone.',+ classification: 'DESTRUCTIVE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Permanently deletes a subscriber and all their history from Drip, by email or subscriber ID; this cannot be undone. Use only when the user asks to erase a contact; to stop emails use Unsubscribe From All Emails instead. A repeat call finds them gone and reports alreadyDeleted=true, so it is idempotent.',+ idempotent: true,+ },+ props: {+ accountId: dripProps.accountId(),+ subscriber: dripProps.subscriber(),+ },+ outputSchema: dripOutputSchemas.deleteSubscriber,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const subscriber = dripApi.requireText({ value: propsValue.subscriber, label: 'Subscriber Email or ID' });+ const segment = dripApi.seg({ value: subscriber, label: 'Subscriber Email or ID' });+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ try {+ await dripApi.request<unknown>({+ token,+ method: HttpMethod.DELETE,+ path: `${dripApi.accountPath(accountId)}/subscribers/${segment}`,+ operation: 'delete subscriber',+ });+ return { subscriber, deleted: true, alreadyDeleted: false };+ } catch (error) {+ if (dripApi.isNotFound(error)) {+ return { subscriber, deleted: false, alreadyDeleted: true };+ }+ throw error;+ }+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/find-subscriber.action.ts b/packages/pieces/community/drip/src/lib/actions/find-subscriber.action.tsnew file mode 100644index 00000000000..7a0f13f4786--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/find-subscriber.action.ts@@ -0,0 +1,44 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripApi } from '../common/client';+import { dripProps } from '../common/props';+import { dripOutputSchemas } from '../output-schemas';++export const findSubscriberAction = createAction({+ auth: dripAuth,+ name: 'find_subscriber',+ displayName: 'Find Subscriber',+ description: 'Finds one subscriber by email address or Drip subscriber ID.',+ classification: 'READ',+ audience: 'both',+ aiMetadata: {+ description:+ 'Looks up one Drip subscriber by email address or subscriber ID and returns their profile, status, tags and custom fields, or found=false when there is no such subscriber. Use before updating, tagging or deleting a contact. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ accountId: dripProps.accountId(),+ subscriber: dripProps.subscriber(),+ },+ outputSchema: dripOutputSchemas.findSubscriber,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const subscriber = dripApi.seg({ value: propsValue.subscriber, label: 'Subscriber Email or ID' });+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ try {+ const body = await dripApi.request<unknown>({+ token,+ method: HttpMethod.GET,+ path: `${dripApi.accountPath(accountId)}/subscribers/${subscriber}`,+ operation: 'find subscriber',+ });+ return { found: true, subscriber: dripApi.firstRecord({ body, key: 'subscribers', operation: 'find subscriber' }) };+ } catch (error) {+ if (dripApi.isNotFound(error)) {+ return { found: false, subscriber: null };+ }+ throw error;+ }+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/get-broadcast.action.ts b/packages/pieces/community/drip/src/lib/actions/get-broadcast.action.tsnew file mode 100644index 00000000000..28414f14ae6--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/get-broadcast.action.ts@@ -0,0 +1,37 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripApi } from '../common/client';+import { dripProps } from '../common/props';+import { dripOutputSchemas } from '../output-schemas';++export const getBroadcastAction = createAction({+ auth: dripAuth,+ name: 'get_broadcast',+ displayName: 'Get Broadcast',+ description: 'Gets one Single-Email Campaign (broadcast) by ID.',+ classification: 'READ',+ audience: 'both',+ aiMetadata: {+ description:+ 'Returns one Drip Single-Email Campaign (broadcast) by ID with name, status, subject, sender, send time and preview URL. Use after List Broadcasts to inspect one; this cannot send it. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ accountId: dripProps.accountId(),+ id: Property.ShortText({ displayName: 'Broadcast ID', description: 'Single-Email Campaign ID (digits, from List Broadcasts).', required: true }),+ },+ outputSchema: dripOutputSchemas.broadcast,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const id = dripApi.parseNumericId({ value: propsValue.id, label: 'Broadcast ID' });+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ const body = await dripApi.request<unknown>({+ token,+ method: HttpMethod.GET,+ path: `${dripApi.accountPath(accountId)}/broadcasts/${id}`,+ operation: 'get broadcast',+ });+ return dripApi.firstRecord({ body, key: 'broadcasts', operation: 'get broadcast' });+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/get-campaign.action.ts b/packages/pieces/community/drip/src/lib/actions/get-campaign.action.tsnew file mode 100644index 00000000000..c63227d25d5--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/get-campaign.action.ts@@ -0,0 +1,37 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripApi } from '../common/client';+import { dripProps } from '../common/props';+import { dripOutputSchemas } from '../output-schemas';++export const getCampaignAction = createAction({+ auth: dripAuth,+ name: 'get_campaign',+ displayName: 'Get Email Series',+ description: 'Gets one Email Series Campaign by ID.',+ classification: 'READ',+ audience: 'both',+ aiMetadata: {+ description:+ 'Returns one Drip Email Series Campaign by Campaign ID: name, status, sender, sending schedule, double opt-in setting, email count and subscriber counts. Use after List Email Series to inspect a sequence. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ accountId: dripProps.accountId(),+ id: Property.ShortText({ displayName: 'Campaign ID', description: 'Email Series Campaign ID (digits, from List Email Series).', required: true }),+ },+ outputSchema: dripOutputSchemas.campaign,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const id = dripApi.parseNumericId({ value: propsValue.id, label: 'Campaign ID' });+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ const body = await dripApi.request<unknown>({+ token,+ method: HttpMethod.GET,+ path: `${dripApi.accountPath(accountId)}/campaigns/${id}`,+ operation: 'get email series',+ });+ return dripApi.firstRecord({ body, key: 'campaigns', operation: 'get email series' });+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/get-conversion.action.ts b/packages/pieces/community/drip/src/lib/actions/get-conversion.action.tsnew file mode 100644index 00000000000..6af1dc328aa--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/get-conversion.action.ts@@ -0,0 +1,37 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripApi } from '../common/client';+import { dripProps } from '../common/props';+import { dripOutputSchemas } from '../output-schemas';++export const getConversionAction = createAction({+ auth: dripAuth,+ name: 'get_conversion',+ displayName: 'Get Conversion',+ description: 'Gets one conversion goal by ID.',+ classification: 'READ',+ audience: 'both',+ aiMetadata: {+ description:+ 'Returns one Drip conversion (goal) by ID with name, status, URL, default value in cents and counting method. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ accountId: dripProps.accountId(),+ id: Property.ShortText({ displayName: 'Conversion ID', description: 'Conversion ID (digits, from List Conversions).', required: true }),+ },+ outputSchema: dripOutputSchemas.conversion,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const id = dripApi.parseNumericId({ value: propsValue.id, label: 'Conversion ID' });+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ const body = await dripApi.request<unknown>({+ token,+ method: HttpMethod.GET,+ path: `${dripApi.accountPath(accountId)}/goals/${id}`,+ operation: 'get conversion',+ });+ return dripApi.firstRecord({ body, key: 'goals', operation: 'get conversion' });+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/get-current-user.action.ts b/packages/pieces/community/drip/src/lib/actions/get-current-user.action.tsnew file mode 100644index 00000000000..9f83cdf62e8--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/get-current-user.action.ts@@ -0,0 +1,24 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripApi } from '../common/client';+import { dripOutputSchemas } from '../output-schemas';++export const getCurrentUserAction = createAction({+ auth: dripAuth,+ name: 'get_current_user',+ displayName: 'Get Current User',+ description: 'Gets the Drip user who owns the API token.',+ classification: 'READ',+ audience: 'both',+ aiMetadata: {+ description: 'Returns the email, name and time zone of the Drip user who owns the connected API token. Use to confirm which Drip login the connection belongs to. Read-only and idempotent.',+ idempotent: true,+ },+ props: {},+ outputSchema: dripOutputSchemas.user,+ async run({ auth }) {+ const body = await dripApi.request<unknown>({ token: auth.secret_text, method: HttpMethod.GET, path: '/user', operation: 'get current user' });+ return dripApi.firstRecord({ body, key: 'users', operation: 'get current user' });+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/get-form.action.ts b/packages/pieces/community/drip/src/lib/actions/get-form.action.tsnew file mode 100644index 00000000000..2d16dd0e583--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/get-form.action.ts@@ -0,0 +1,37 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripApi } from '../common/client';+import { dripProps } from '../common/props';+import { dripOutputSchemas } from '../output-schemas';++export const getFormAction = createAction({+ auth: dripAuth,+ name: 'get_form',+ displayName: 'Get Form',+ description: 'Gets one opt-in form by ID.',+ classification: 'READ',+ audience: 'both',+ aiMetadata: {+ description:+ 'Returns one Drip opt-in form by Form ID with its headline, description, button text and display settings. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ accountId: dripProps.accountId(),+ id: Property.ShortText({ displayName: 'Form ID', description: 'Form ID (digits, from List Forms).', required: true }),+ },+ outputSchema: dripOutputSchemas.form,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const id = dripApi.parseNumericId({ value: propsValue.id, label: 'Form ID' });+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ const body = await dripApi.request<unknown>({+ token,+ method: HttpMethod.GET,+ path: `${dripApi.accountPath(accountId)}/forms/${id}`,+ operation: 'get form',+ });+ return dripApi.firstRecord({ body, key: 'forms', operation: 'get form' });+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/get-workflow.action.ts b/packages/pieces/community/drip/src/lib/actions/get-workflow.action.tsnew file mode 100644index 00000000000..90d3edcce93--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/get-workflow.action.ts@@ -0,0 +1,37 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripApi } from '../common/client';+import { dripProps } from '../common/props';+import { dripOutputSchemas } from '../output-schemas';++export const getWorkflowAction = createAction({+ auth: dripAuth,+ name: 'get_workflow',+ displayName: 'Get Workflow',+ description: 'Gets one workflow by ID.',+ classification: 'READ',+ audience: 'both',+ aiMetadata: {+ description:+ 'Returns one Drip workflow by Workflow ID with its name, status (draft, active, paused) and creation date. Use to check a workflow is active before starting someone on it. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ accountId: dripProps.accountId(),+ id: Property.ShortText({ displayName: 'Workflow ID', description: 'Workflow ID (digits, from List Workflows).', required: true }),+ },+ outputSchema: dripOutputSchemas.workflow,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const id = dripApi.parseNumericId({ value: propsValue.id, label: 'Workflow ID' });+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ const body = await dripApi.request<unknown>({+ token,+ method: HttpMethod.GET,+ path: `${dripApi.accountPath(accountId)}/workflows/${id}`,+ operation: 'get workflow',+ });+ return dripApi.firstRecord({ body, key: 'workflows', operation: 'get workflow' });+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/list-accounts.action.ts b/packages/pieces/community/drip/src/lib/actions/list-accounts.action.tsnew file mode 100644index 00000000000..f5c7dd9683f--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/list-accounts.action.ts@@ -0,0 +1,24 @@+import { createAction } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripApi } from '../common/client';+import { dripOutputSchemas } from '../output-schemas';++export const listAccountsAction = createAction({+ auth: dripAuth,+ name: 'list_accounts',+ displayName: 'List Accounts',+ description: 'Lists the Drip accounts this API token can access.',+ classification: 'SEARCH',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists every Drip account the connected API token can access, with account ID, name, website and sender details. Use first when another Drip step needs an Account ID and the token may have more than one account. Read-only and idempotent.',+ idempotent: true,+ },+ props: {},+ outputSchema: dripOutputSchemas.listAccounts,+ async run({ auth }) {+ const accounts = await dripApi.listAccounts(auth.secret_text);+ return { items: accounts };+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/list-broadcasts.action.ts b/packages/pieces/community/drip/src/lib/actions/list-broadcasts.action.tsnew file mode 100644index 00000000000..6ab3a9602c0--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/list-broadcasts.action.ts@@ -0,0 +1,49 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripApi } from '../common/client';+import { dripProps } from '../common/props';+import { dripOutputSchemas } from '../output-schemas';++export const listBroadcastsAction = createAction({+ auth: dripAuth,+ name: 'list_broadcasts',+ displayName: 'List Broadcasts',+ description: 'Lists Single-Email Campaigns (broadcasts) one page at a time.',+ classification: 'SEARCH',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists Drip Single-Email Campaigns (broadcasts) one page at a time with ID, name, status (draft, scheduled, sending, sent, canceled), subject and send time. Use to report on or look up a broadcast; this cannot create or send one. Pass the next page while hasMore is true. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ accountId: dripProps.accountId(),+ status: Property.StaticDropdown({+ displayName: 'Status',+ description: 'Only broadcasts with this status. Defaults to all except deleted.',+ required: false,+ options: {+ disabled: false,+ options: [{ label: 'All except deleted', value: 'all' }, { label: 'Draft', value: 'draft' }, { label: 'Scheduled', value: 'scheduled' }, { label: 'Sending', value: 'sending' }, { label: 'Sent', value: 'sent' }, { label: 'Canceled', value: 'canceled' }],+ },+ }),+ page: dripProps.page(),+ perPage: dripProps.perPage({ max: 100 }),+ },+ outputSchema: dripOutputSchemas.broadcastPage,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const { page, perPage } = dripApi.paging({ page: propsValue.page, perPage: propsValue.perPage, max: 100 });+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ return dripApi.listPage({+ token,+ accountId,+ resource: '/broadcasts',+ key: 'broadcasts',+ operation: 'list broadcasts',+ page,+ perPage,+ query: { status: propsValue.status },+ });+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/list-campaign-subscribers.action.ts b/packages/pieces/community/drip/src/lib/actions/list-campaign-subscribers.action.tsnew file mode 100644index 00000000000..0e77912a128--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/list-campaign-subscribers.action.ts@@ -0,0 +1,55 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripApi } from '../common/client';+import { dripProps } from '../common/props';+import { dripOutputSchemas } from '../output-schemas';++export const listCampaignSubscribersAction = createAction({+ auth: dripAuth,+ name: 'list_campaign_subscribers',+ displayName: 'List Email Series Subscribers',+ description: 'Lists the subscribers of one Email Series Campaign one page at a time.',+ classification: 'SEARCH',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists the subscribers of one Drip Email Series Campaign by Campaign ID, one page at a time, filtered by subscription status (active by default, unsubscribed or removed). Pass the next page while hasMore is true. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ accountId: dripProps.accountId(),+ campaignId: Property.ShortText({ displayName: 'Campaign ID', description: 'Email Series Campaign ID (digits, from List Email Series).', required: true }),+ status: Property.StaticDropdown({+ displayName: 'Subscription Status',+ description: 'Defaults to active.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Active', value: 'active' },+ { label: 'Unsubscribed', value: 'unsubscribed' },+ { label: 'Removed', value: 'removed' },+ ],+ },+ }),+ page: dripProps.page(),+ perPage: dripProps.perPage({ max: 1000 }),+ },+ outputSchema: dripOutputSchemas.subscriberPage,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const campaignId = dripApi.parseNumericId({ value: propsValue.campaignId, label: 'Campaign ID' });+ const { page, perPage } = dripApi.paging({ page: propsValue.page, perPage: propsValue.perPage, max: 1000 });+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ return dripApi.listPage({+ token,+ accountId,+ resource: `/campaigns/${campaignId}/subscribers`,+ key: 'subscribers',+ operation: 'list email series subscribers',+ page,+ perPage,+ query: { status: propsValue.status },+ });+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/list-campaigns.action.ts b/packages/pieces/community/drip/src/lib/actions/list-campaigns.action.tsnew file mode 100644index 00000000000..9749624ccac--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/list-campaigns.action.ts@@ -0,0 +1,49 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripApi } from '../common/client';+import { dripProps } from '../common/props';+import { dripOutputSchemas } from '../output-schemas';++export const listCampaignsAction = createAction({+ auth: dripAuth,+ name: 'list_campaigns',+ displayName: 'List Email Series',+ description: 'Lists Email Series Campaigns one page at a time.',+ classification: 'SEARCH',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists Drip Email Series Campaigns (automated email sequences) one page at a time with ID, name, status (draft, active, paused), sender, email count and subscriber counts. Use to find a Campaign ID for Subscribe to Email Series or Remove Subscriber From Email Series; pass the next page while hasMore is true. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ accountId: dripProps.accountId(),+ status: Property.StaticDropdown({+ displayName: 'Status',+ description: 'Only campaigns with this status. Defaults to all.',+ required: false,+ options: {+ disabled: false,+ options: [{ label: 'All', value: 'all' }, { label: 'Active', value: 'active' }, { label: 'Draft', value: 'draft' }, { label: 'Paused', value: 'paused' }],+ },+ }),+ page: dripProps.page(),+ perPage: dripProps.perPage({ max: 1000 }),+ },+ outputSchema: dripOutputSchemas.campaignPage,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const { page, perPage } = dripApi.paging({ page: propsValue.page, perPage: propsValue.perPage, max: 1000 });+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ return dripApi.listPage({+ token,+ accountId,+ resource: '/campaigns',+ key: 'campaigns',+ operation: 'list email series',+ page,+ perPage,+ query: { status: propsValue.status },+ });+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/list-conversions.action.ts b/packages/pieces/community/drip/src/lib/actions/list-conversions.action.tsnew file mode 100644index 00000000000..7434f0e4e45--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/list-conversions.action.ts@@ -0,0 +1,49 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripApi } from '../common/client';+import { dripProps } from '../common/props';+import { dripOutputSchemas } from '../output-schemas';++export const listConversionsAction = createAction({+ auth: dripAuth,+ name: 'list_conversions',+ displayName: 'List Conversions',+ description: 'Lists conversion goals one page at a time.',+ classification: 'SEARCH',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists Drip conversions (goals) one page at a time with ID, name, status, URL, default value in cents and counting method. Use to find a conversion before recording a conversion event. Pass the next page while hasMore is true. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ accountId: dripProps.accountId(),+ status: Property.StaticDropdown({+ displayName: 'Status',+ description: 'Only conversions with this status.',+ required: false,+ options: {+ disabled: false,+ options: [{ label: 'All', value: 'all' }, { label: 'Active', value: 'active' }, { label: 'Disabled', value: 'disabled' }],+ },+ }),+ page: dripProps.page(),+ perPage: dripProps.perPage({ max: 1000 }),+ },+ outputSchema: dripOutputSchemas.conversionPage,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const { page, perPage } = dripApi.paging({ page: propsValue.page, perPage: propsValue.perPage, max: 1000 });+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ return dripApi.listPage({+ token,+ accountId,+ resource: '/goals',+ key: 'goals',+ operation: 'list conversions',+ page,+ perPage,+ query: { status: propsValue.status },+ });+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/list-custom-fields.action.ts b/packages/pieces/community/drip/src/lib/actions/list-custom-fields.action.tsnew file mode 100644index 00000000000..b68244873a1--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/list-custom-fields.action.ts@@ -0,0 +1,35 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripApi } from '../common/client';+import { dripProps } from '../common/props';+import { dripOutputSchemas } from '../output-schemas';++export const listCustomFieldsAction = createAction({+ auth: dripAuth,+ name: 'list_custom_fields',+ displayName: 'List Custom Fields',+ description: 'Lists the custom field identifiers used in the Drip account.',+ classification: 'SEARCH',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists the custom field identifiers (keys such as shirt_size) used in a Drip account. Use to find the exact key before setting custom fields on a subscriber. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ accountId: dripProps.accountId(),+ },+ outputSchema: dripOutputSchemas.stringList,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ const body = await dripApi.request<{ custom_field_identifiers?: unknown }>({+ token,+ method: HttpMethod.GET,+ path: `${dripApi.accountPath(accountId)}/custom_field_identifiers`,+ operation: 'list custom fields',+ });+ return { items: Array.isArray(body.custom_field_identifiers) ? body.custom_field_identifiers.map(String) : [] };+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/list-event-actions.action.ts b/packages/pieces/community/drip/src/lib/actions/list-event-actions.action.tsnew file mode 100644index 00000000000..36f0862f460--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/list-event-actions.action.ts@@ -0,0 +1,40 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripApi } from '../common/client';+import { dripProps } from '../common/props';+import { dripOutputSchemas } from '../output-schemas';++export const listEventActionsAction = createAction({+ auth: dripAuth,+ name: 'list_event_actions',+ displayName: 'List Custom Event Names',+ description: 'Lists the custom event action names recorded in the Drip account.',+ classification: 'SEARCH',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists the custom event action names (e.g. "Logged in") recorded in a Drip account, one page at a time. Use to reuse an existing event name exactly before Record Custom Event; pass the next page while hasMore is true. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ accountId: dripProps.accountId(),+ page: dripProps.page(),+ perPage: dripProps.perPage({ max: 1000 }),+ },+ outputSchema: dripOutputSchemas.stringPage,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const { page, perPage } = dripApi.paging({ page: propsValue.page, perPage: propsValue.perPage, max: 1000 });+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ const body = await dripApi.request<Record<string, unknown>>({+ token,+ method: HttpMethod.GET,+ path: `${dripApi.accountPath(accountId)}/event_actions`,+ operation: 'list custom event names',+ query: { page, per_page: perPage },+ });+ const items = Array.isArray(body['event_actions']) ? body['event_actions'].map(String) : [];+ return { items, ...dripApi.pageInfo({ meta: body['meta'], page, perPage, count: items.length }) };+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/list-forms.action.ts b/packages/pieces/community/drip/src/lib/actions/list-forms.action.tsnew file mode 100644index 00000000000..d70af67b5b8--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/list-forms.action.ts@@ -0,0 +1,29 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripApi } from '../common/client';+import { dripProps } from '../common/props';+import { dripOutputSchemas } from '../output-schemas';++export const listFormsAction = createAction({+ auth: dripAuth,+ name: 'list_forms',+ displayName: 'List Forms',+ description: 'Lists the opt-in forms in the Drip account.',+ classification: 'SEARCH',+ audience: 'both',+ aiMetadata: {+ description: 'Lists every Drip opt-in form in an account with ID, headline, description and whether it shows as a widget or can be embedded. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ accountId: dripProps.accountId(),+ },+ outputSchema: dripOutputSchemas.formList,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ const body = await dripApi.request<unknown>({ token, method: HttpMethod.GET, path: `${dripApi.accountPath(accountId)}/forms`, operation: 'list forms' });+ return { items: dripApi.recordList({ body, key: 'forms' }) };+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/list-subscriber-campaigns.action.ts b/packages/pieces/community/drip/src/lib/actions/list-subscriber-campaigns.action.tsnew file mode 100644index 00000000000..88c9a9e08ed--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/list-subscriber-campaigns.action.ts@@ -0,0 +1,41 @@+import { createAction } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripApi } from '../common/client';+import { dripProps } from '../common/props';+import { dripOutputSchemas } from '../output-schemas';++export const listSubscriberCampaignsAction = createAction({+ auth: dripAuth,+ name: 'list_subscriber_campaigns',+ displayName: "List Subscriber's Email Series",+ description: 'Lists the Email Series Campaign subscriptions of one subscriber.',+ classification: 'SEARCH',+ audience: 'both',+ aiMetadata: {+ description:+ "Lists one subscriber's Drip Email Series Campaign subscriptions (by email or subscriber ID): campaign ID, status, whether the series is complete and the last email sent. Use to check which sequences a contact is in before adding or removing them. Read-only and idempotent.",+ idempotent: true,+ },+ props: {+ accountId: dripProps.accountId(),+ subscriber: dripProps.subscriber(),+ page: dripProps.page(),+ perPage: dripProps.perPage({ max: 1000 }),+ },+ outputSchema: dripOutputSchemas.campaignSubscriptionPage,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const segment = dripApi.seg({ value: propsValue.subscriber, label: 'Subscriber Email or ID' });+ const { page, perPage } = dripApi.paging({ page: propsValue.page, perPage: propsValue.perPage, max: 1000 });+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ return dripApi.listPage({+ token,+ accountId,+ resource: `/subscribers/${segment}/campaign_subscriptions`,+ key: 'campaign_subscriptions',+ operation: 'list subscriber email series',+ page,+ perPage,+ });+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/list-subscribers.action.ts b/packages/pieces/community/drip/src/lib/actions/list-subscribers.action.tsnew file mode 100644index 00000000000..499ae479263--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/list-subscribers.action.ts@@ -0,0 +1,69 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripApi } from '../common/client';+import { dripProps } from '../common/props';+import { dripOutputSchemas } from '../output-schemas';++export const listSubscribersAction = createAction({+ auth: dripAuth,+ name: 'list_subscribers',+ displayName: 'List Subscribers',+ description: 'Lists subscribers one page at a time, optionally filtered by status, tags or sign-up date.',+ classification: 'SEARCH',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists subscribers of a Drip account one page at a time, optionally only those with at least one of the given tags, a status (active by default, unsubscribed, undeliverable or all) or created within a date range. Use to find contacts in a segment; pass the next page number while hasMore is true. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ accountId: dripProps.accountId(),+ status: Property.StaticDropdown({+ displayName: 'Status',+ description: 'Which subscribers to return. Drip defaults to Active.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Active', value: 'active' },+ { label: 'Unsubscribed', value: 'unsubscribed' },+ { label: 'Active or unsubscribed', value: 'active_or_unsubscribed' },+ { label: 'Undeliverable', value: 'undeliverable' },+ { label: 'All', value: 'all' },+ ],+ },+ }),+ tags: dripProps.tags({ displayName: 'Has Any of These Tags', description: 'Only return subscribers with at least one of these tags.' }),+ subscribedAfter: Property.DateTime({ displayName: 'Created After', description: 'Only subscribers created after this date-time (ISO-8601).', required: false }),+ subscribedBefore: Property.DateTime({ displayName: 'Created Before', description: 'Only subscribers created before this date-time (ISO-8601).', required: false }),+ page: dripProps.page(),+ perPage: dripProps.perPage({ max: 1000 }),+ },+ outputSchema: dripOutputSchemas.subscriberPage,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const { page, perPage } = dripApi.paging({ page: propsValue.page, perPage: propsValue.perPage, max: 1000 });+ const subscribedAfter = dripApi.parseIsoDate({ value: propsValue.subscribedAfter, label: 'Created After' });+ const subscribedBefore = dripApi.parseIsoDate({ value: propsValue.subscribedBefore, label: 'Created Before' });+ const tags = dripApi.textList(propsValue.tags);+ if (tags?.some((tag) => tag.includes(','))) {+ throw new Error('Tag filters cannot contain commas: Drip reads this filter as a comma-separated list.');+ }+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ return dripApi.listPage({+ token,+ accountId,+ resource: '/subscribers',+ key: 'subscribers',+ operation: 'list subscribers',+ page,+ perPage,+ query: {+ status: propsValue.status,+ tags: tags && tags.length > 0 ? tags.join(',') : undefined,+ subscribed_after: subscribedAfter,+ subscribed_before: subscribedBefore,+ },+ });+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/list-tags.action.ts b/packages/pieces/community/drip/src/lib/actions/list-tags.action.tsnew file mode 100644index 00000000000..a03fcc0dde9--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/list-tags.action.ts@@ -0,0 +1,29 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripApi } from '../common/client';+import { dripProps } from '../common/props';+import { dripOutputSchemas } from '../output-schemas';++export const listTagsAction = createAction({+ auth: dripAuth,+ name: 'list_tags',+ displayName: 'List Tags',+ description: 'Lists every tag used in the Drip account.',+ classification: 'SEARCH',+ audience: 'both',+ aiMetadata: {+ description: 'Lists every tag name used in a Drip account. Use to check the exact spelling of a tag before tagging, filtering or removing it. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ accountId: dripProps.accountId(),+ },+ outputSchema: dripOutputSchemas.stringList,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ const body = await dripApi.request<{ tags?: unknown }>({ token, method: HttpMethod.GET, path: `${dripApi.accountPath(accountId)}/tags`, operation: 'list tags' });+ return { items: Array.isArray(body.tags) ? body.tags.map(String) : [] };+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/list-workflows.action.ts b/packages/pieces/community/drip/src/lib/actions/list-workflows.action.tsnew file mode 100644index 00000000000..3aa73001c96--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/list-workflows.action.ts@@ -0,0 +1,49 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripApi } from '../common/client';+import { dripProps } from '../common/props';+import { dripOutputSchemas } from '../output-schemas';++export const listWorkflowsAction = createAction({+ auth: dripAuth,+ name: 'list_workflows',+ displayName: 'List Workflows',+ description: 'Lists workflows one page at a time.',+ classification: 'SEARCH',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists Drip workflows (visual automations) one page at a time with ID, name and status (draft, active, paused). Use to find a Workflow ID for Start Workflow for Subscriber; pass the next page while hasMore is true. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ accountId: dripProps.accountId(),+ status: Property.StaticDropdown({+ displayName: 'Status',+ description: 'Only workflows with this status. Defaults to all.',+ required: false,+ options: {+ disabled: false,+ options: [{ label: 'All', value: 'all' }, { label: 'Active', value: 'active' }, { label: 'Draft', value: 'draft' }, { label: 'Paused', value: 'paused' }],+ },+ }),+ page: dripProps.page(),+ perPage: dripProps.perPage({ max: 1000 }),+ },+ outputSchema: dripOutputSchemas.workflowPage,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const { page, perPage } = dripApi.paging({ page: propsValue.page, perPage: propsValue.perPage, max: 1000 });+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ return dripApi.listPage({+ token,+ accountId,+ resource: '/workflows',+ key: 'workflows',+ operation: 'list workflows',+ page,+ perPage,+ query: { status: propsValue.status },+ });+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/record-cart.action.ts b/packages/pieces/community/drip/src/lib/actions/record-cart.action.tsnew file mode 100644index 00000000000..d55e95907cf--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/record-cart.action.ts@@ -0,0 +1,84 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripApi } from '../common/client';+import { dripProps } from '../common/props';+import { shopperInput, shopperProps } from '../common/shopper';+import { dripOutputSchemas } from '../output-schemas';++export const recordCartAction = createAction({+ auth: dripAuth,+ name: 'record_cart',+ displayName: 'Record Cart Activity',+ description: 'Sends a cart created or updated event to Drip Shopper Activity, e.g. for abandoned-cart workflows.',+ classification: 'WRITE',+ audience: 'both',+ aiMetadata: {+ description:+ "Sends a shopping cart created or updated event for a customer to Drip Shopper Activity, with the cart link and line items, which powers abandoned-cart workflows; Drip creates the person if needed (subscribed unless New Person Status says otherwise) and workflows listening for cart events may send emails. Drip queues it and returns a request ID. Not idempotent: each call adds a cart event to the person's timeline.",+ idempotent: false,+ },+ props: {+ accountId: dripProps.accountId(),+ action: Property.StaticDropdown({+ displayName: 'Cart Action',+ required: true,+ options: {+ disabled: false,+ options: [+ { label: 'Created', value: 'created' },+ { label: 'Updated', value: 'updated' },+ ],+ },+ }),+ cartId: Property.ShortText({ displayName: 'Cart ID', description: 'Your unique internal cart ID.', required: true }),+ cartUrl: Property.ShortText({ displayName: 'Cart URL', description: 'Link back to the shopper cart in your store.', required: true }),+ email: shopperProps.email,+ personId: shopperProps.personId,+ provider: shopperProps.provider,+ initialStatus: shopperProps.initialStatus,+ occurredAt: shopperProps.occurredAt,+ cartPublicId: Property.ShortText({ displayName: 'Public Cart Number', required: false }),+ grandTotal: Property.Number({ displayName: 'Grand Total', description: 'Cart total after discounts, e.g. 16.99.', required: false }),+ totalDiscounts: Property.Number({ displayName: 'Total Discounts', required: false }),+ currency: shopperProps.currency,+ items: Property.Json({+ displayName: 'Items',+ description:+ 'Optional JSON array of cart items. Each needs "product_id", "product_variant_id", "name" and "price"; e.g. [{"product_id": "B01", "product_variant_id": "B01", "name": "Water Bottle", "price": 11.16, "quantity": 2}].',+ required: false,+ }),+ },+ outputSchema: dripOutputSchemas.recordCart,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const action = dripApi.requireText({ value: propsValue.action, label: 'Cart Action' });+ const cartId = dripApi.requireText({ value: propsValue.cartId, label: 'Cart ID' });+ const payload = {+ ...shopperInput.person({ email: propsValue.email, personId: propsValue.personId }),+ ...dripApi.compact({+ provider: shopperInput.provider(propsValue.provider),+ action,+ cart_id: cartId,+ cart_url: dripApi.requireText({ value: propsValue.cartUrl, label: 'Cart URL' }),+ initial_status: dripApi.optionalText(propsValue.initialStatus),+ occurred_at: dripApi.parseIsoDate({ value: propsValue.occurredAt, label: 'Occurred At' }),+ cart_public_id: dripApi.optionalText(propsValue.cartPublicId),+ grand_total: shopperInput.amount({ value: propsValue.grandTotal, label: 'Grand Total' }),+ total_discounts: shopperInput.amount({ value: propsValue.totalDiscounts, label: 'Total Discounts' }),+ currency: shopperInput.currency(propsValue.currency),+ items: shopperInput.items({ value: propsValue.items, required: ['product_id', 'product_variant_id', 'name', 'price'] }),+ }),+ };+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ const body = await dripApi.request<unknown>({+ token,+ method: HttpMethod.POST,+ version: 'v3',+ path: `${dripApi.accountPath(accountId)}/shopper_activity/cart`,+ operation: 'record cart activity',+ body: payload,+ });+ return { requestId: shopperInput.requestId(body), cartId, action, accepted: true };+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/record-event.action.ts b/packages/pieces/community/drip/src/lib/actions/record-event.action.tsnew file mode 100644index 00000000000..4781bff8199--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/record-event.action.ts@@ -0,0 +1,53 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripApi } from '../common/client';+import { dripProps } from '../common/props';+import { dripOutputSchemas } from '../output-schemas';++const MAX_ACTION_LENGTH = 255;++export const recordEventAction = createAction({+ auth: dripAuth,+ name: 'record_event',+ displayName: 'Record Custom Event',+ description: 'Records a custom event (such as "Logged in") for a subscriber. Workflows and rules listening for it may run.',+ classification: 'WRITE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Records a custom event (an action name such as "Viewed pricing" plus optional properties) for a Drip subscriber by email or subscriber ID; an unknown email creates the subscriber. Drip workflows and rules listening for that action may run and send emails. Not idempotent: each call records another event.',+ idempotent: false,+ },+ props: {+ accountId: dripProps.accountId(),+ subscriber: dripProps.subscriber(),+ action: Property.ShortText({ displayName: 'Event Action', description: 'The event name, e.g. Logged in. Reuse names from List Custom Event Names.', required: true }),+ properties: Property.Object({+ displayName: 'Properties',+ description: 'Optional event properties. For a conversion, add "value" in cents.',+ required: false,+ }),+ occurredAt: Property.DateTime({ displayName: 'Occurred At', description: 'When the event happened (ISO-8601). Defaults to now.', required: false }),+ },+ outputSchema: dripOutputSchemas.recordEvent,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const identity = dripApi.identify({ value: propsValue.subscriber, label: 'Subscriber Email or ID' });+ const action = dripApi.requireText({ value: propsValue.action, label: 'Event Action' });+ if (action.length > MAX_ACTION_LENGTH) {+ throw new Error(`Event Action must be at most ${MAX_ACTION_LENGTH} characters.`);+ }+ const occurredAt = dripApi.parseIsoDate({ value: propsValue.occurredAt, label: 'Occurred At' });+ const properties = dripApi.parseObject({ value: propsValue.properties, label: 'Properties' });+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ await dripApi.request<unknown>({+ token,+ method: HttpMethod.POST,+ path: `${dripApi.accountPath(accountId)}/events`,+ operation: 'record event',+ body: { events: [{ ...identity, ...dripApi.compact({ action, properties, occurred_at: occurredAt }) }] },+ });+ return { subscriber: dripApi.requireText({ value: propsValue.subscriber, label: 'Subscriber' }), action, occurredAt: occurredAt ?? null, recorded: true };+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/record-order.action.ts b/packages/pieces/community/drip/src/lib/actions/record-order.action.tsnew file mode 100644index 00000000000..cd345e60666--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/record-order.action.ts@@ -0,0 +1,93 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripApi } from '../common/client';+import { dripProps } from '../common/props';+import { shopperInput, shopperProps } from '../common/shopper';+import { dripOutputSchemas } from '../output-schemas';++export const recordOrderAction = createAction({+ auth: dripAuth,+ name: 'record_order',+ displayName: 'Record Order Activity',+ description: 'Sends an order event (placed, updated, paid, fulfilled, refunded or canceled) to Drip Shopper Activity.',+ classification: 'WRITE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Sends an e-commerce order event (placed, updated, paid, fulfilled, refunded or canceled) for a customer to Drip Shopper Activity, updating their order history and lifetime value; Drip creates the person if needed (subscribed unless New Person Status says otherwise) and workflows listening for order events may run. Drip queues it and returns a request ID. Not idempotent: each call adds an event to the timeline.',+ idempotent: false,+ },+ props: {+ accountId: dripProps.accountId(),+ action: Property.StaticDropdown({+ displayName: 'Order Action',+ required: true,+ options: {+ disabled: false,+ options: [+ { label: 'Placed', value: 'placed' },+ { label: 'Updated', value: 'updated' },+ { label: 'Paid', value: 'paid' },+ { label: 'Fulfilled', value: 'fulfilled' },+ { label: 'Refunded', value: 'refunded' },+ { label: 'Canceled', value: 'canceled' },+ ],+ },+ }),+ orderId: Property.ShortText({ displayName: 'Order ID', description: 'Your unique internal order ID. Provider + Order ID identify the order.', required: true }),+ email: shopperProps.email,+ personId: shopperProps.personId,+ provider: shopperProps.provider,+ initialStatus: shopperProps.initialStatus,+ occurredAt: shopperProps.occurredAt,+ orderPublicId: Property.ShortText({ displayName: 'Public Order Number', description: 'Customer-facing order number, e.g. #1001.', required: false }),+ grandTotal: Property.Number({ displayName: 'Grand Total', description: 'Order total after discounts, e.g. 49.99.', required: false }),+ totalDiscounts: Property.Number({ displayName: 'Total Discounts', required: false }),+ totalTaxes: Property.Number({ displayName: 'Total Taxes', required: false }),+ totalShipping: Property.Number({ displayName: 'Total Shipping', required: false }),+ refundAmount: Property.Number({ displayName: 'Refund Amount', description: 'For refunded or canceled orders: the amount refunded. Leave Grand Total unchanged.', required: false }),+ currency: shopperProps.currency,+ orderUrl: Property.ShortText({ displayName: 'Order URL', required: false }),+ items: Property.Json({+ displayName: 'Items',+ description: 'Optional JSON array of line items. Each needs "name"; e.g. [{"product_id": "B01", "name": "Water Bottle", "price": 11.16, "quantity": 2}].',+ required: false,+ }),+ },+ outputSchema: dripOutputSchemas.recordOrder,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const action = dripApi.requireText({ value: propsValue.action, label: 'Order Action' });+ const orderId = dripApi.requireText({ value: propsValue.orderId, label: 'Order ID' });+ const payload = {+ ...shopperInput.person({ email: propsValue.email, personId: propsValue.personId }),+ ...dripApi.compact({+ provider: shopperInput.provider(propsValue.provider),+ action,+ order_id: orderId,+ initial_status: dripApi.optionalText(propsValue.initialStatus),+ occurred_at: dripApi.parseIsoDate({ value: propsValue.occurredAt, label: 'Occurred At' }),+ order_public_id: dripApi.optionalText(propsValue.orderPublicId),+ grand_total: shopperInput.amount({ value: propsValue.grandTotal, label: 'Grand Total' }),+ total_discounts: shopperInput.amount({ value: propsValue.totalDiscounts, label: 'Total Discounts' }),+ total_taxes: shopperInput.amount({ value: propsValue.totalTaxes, label: 'Total Taxes' }),+ total_shipping: shopperInput.amount({ value: propsValue.totalShipping, label: 'Total Shipping' }),+ refund_amount: shopperInput.amount({ value: propsValue.refundAmount, label: 'Refund Amount' }),+ currency: shopperInput.currency(propsValue.currency),+ order_url: dripApi.optionalText(propsValue.orderUrl),+ items: shopperInput.items({ value: propsValue.items, required: ['name'] }),+ }),+ };+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ const body = await dripApi.request<unknown>({+ token,+ method: HttpMethod.POST,+ version: 'v3',+ path: `${dripApi.accountPath(accountId)}/shopper_activity/order`,+ operation: 'record order activity',+ body: payload,+ });+ return { requestId: shopperInput.requestId(body), orderId, action, accepted: true };+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/remove-from-campaign.action.ts b/packages/pieces/community/drip/src/lib/actions/remove-from-campaign.action.tsnew file mode 100644index 00000000000..673ea08ed10--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/remove-from-campaign.action.ts@@ -0,0 +1,45 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripApi } from '../common/client';+import { dripProps } from '../common/props';+import { dripOutputSchemas } from '../output-schemas';++export const removeFromCampaignAction = createAction({+ auth: dripAuth,+ name: 'remove_from_campaign',+ displayName: 'Remove Subscriber From Email Series',+ description: 'Removes a subscriber from one Email Series Campaign, or from all of them when no campaign ID is given.',+ classification: 'WRITE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Removes a subscriber (by email or ID) from one Drip Email Series Campaign, or from every email series when Campaign ID is empty, so they stop receiving those sequences; they stay subscribed to other mailings. Returns the subscriber. Repeating it changes nothing more, so it is idempotent.',+ idempotent: true,+ },+ props: {+ accountId: dripProps.accountId(),+ subscriber: dripProps.subscriber(),+ campaignId: Property.ShortText({+ displayName: 'Campaign ID',+ description: 'Email Series Campaign ID (from List Email Series). Leave empty to remove the subscriber from all email series.',+ required: false,+ }),+ },+ outputSchema: dripOutputSchemas.subscriber,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const segment = dripApi.seg({ value: propsValue.subscriber, label: 'Subscriber Email or ID' });+ const campaignText = dripApi.optionalText(propsValue.campaignId);+ const campaignId = campaignText === undefined ? undefined : dripApi.parseNumericId({ value: campaignText, label: 'Campaign ID' });+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ const body = await dripApi.request<unknown>({+ token,+ method: HttpMethod.POST,+ path: `${dripApi.accountPath(accountId)}/subscribers/${segment}/remove`,+ operation: 'remove subscriber from email series',+ query: { campaign_id: campaignId },+ });+ return dripApi.firstRecord({ body, key: 'subscribers', operation: 'remove subscriber from email series' });+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/remove-from-workflow.action.ts b/packages/pieces/community/drip/src/lib/actions/remove-from-workflow.action.tsnew file mode 100644index 00000000000..3f6de4c5478--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/remove-from-workflow.action.ts@@ -0,0 +1,40 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripApi } from '../common/client';+import { dripProps } from '../common/props';+import { dripOutputSchemas } from '../output-schemas';++export const removeFromWorkflowAction = createAction({+ auth: dripAuth,+ name: 'remove_from_workflow',+ displayName: 'Remove Subscriber From Workflow',+ description: 'Removes a subscriber from a workflow. Nothing happens if they are not on it.',+ classification: 'WRITE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Removes a subscriber (by email or subscriber ID) from a Drip workflow by Workflow ID so it stops acting on them; nothing happens if they are not on it. Repeating it changes nothing more, so it is idempotent.',+ idempotent: true,+ },+ props: {+ accountId: dripProps.accountId(),+ workflowId: Property.ShortText({ displayName: 'Workflow ID', description: 'Workflow ID (digits, from List Workflows).', required: true }),+ subscriber: dripProps.subscriber(),+ },+ outputSchema: dripOutputSchemas.workflowRemove,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const workflowId = dripApi.parseNumericId({ value: propsValue.workflowId, label: 'Workflow ID' });+ const subscriber = dripApi.requireText({ value: propsValue.subscriber, label: 'Subscriber Email or ID' });+ const segment = dripApi.seg({ value: subscriber, label: 'Subscriber Email or ID' });+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ await dripApi.request<unknown>({+ token,+ method: HttpMethod.DELETE,+ path: `${dripApi.accountPath(accountId)}/workflows/${workflowId}/subscribers/${segment}`,+ operation: 'remove subscriber from workflow',+ });+ return { workflowId, subscriber, removed: true };+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/remove-tag.action.ts b/packages/pieces/community/drip/src/lib/actions/remove-tag.action.tsnew file mode 100644index 00000000000..a27102a789e--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/remove-tag.action.ts@@ -0,0 +1,54 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripApi } from '../common/client';+import { dripProps } from '../common/props';+import { dripOutputSchemas } from '../output-schemas';++export const removeTagAction = createAction({+ auth: dripAuth,+ name: 'remove_tag',+ displayName: 'Remove Tag From Subscriber',+ description: 'Removes a tag from a subscriber.',+ classification: 'WRITE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Removes a tag from a Drip subscriber identified by email or subscriber ID and reports whether the tag had been applied; fails if there is no such subscriber. Removing a tag the subscriber does not have changes nothing, so it is idempotent.',+ idempotent: true,+ },+ props: {+ accountId: dripProps.accountId(),+ subscriber: dripProps.subscriber(),+ tag: Property.ShortText({ displayName: 'Tag', description: 'The tag to remove.', required: true }),+ },+ outputSchema: dripOutputSchemas.removeTag,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const segment = dripApi.seg({ value: propsValue.subscriber, label: 'Subscriber Email or ID' });+ const tag = dripApi.requireText({ value: propsValue.tag, label: 'Tag' });+ const tagSegment = dripApi.seg({ value: tag, label: 'Tag' });+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ const body = await dripApi.request<unknown>({+ token,+ method: HttpMethod.GET,+ path: `${dripApi.accountPath(accountId)}/subscribers/${segment}`,+ operation: 'find subscriber',+ });+ const subscriber = dripApi.firstRecord({ body, key: 'subscribers', operation: 'find subscriber' });+ const tags = Array.isArray(subscriber['tags']) ? subscriber['tags'].map((item) => String(item).toLowerCase()) : [];+ await dripApi.request<unknown>({+ token,+ method: HttpMethod.DELETE,+ path: `${dripApi.accountPath(accountId)}/subscribers/${segment}/tags/${tagSegment}`,+ operation: 'remove tag',+ });+ return {+ subscriberId: subscriber['id'] ?? null,+ email: subscriber['email'] ?? null,+ tag,+ wasApplied: tags.includes(tag.toLowerCase()),+ removed: true,+ };+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/start-workflow.action.ts b/packages/pieces/community/drip/src/lib/actions/start-workflow.action.tsnew file mode 100644index 00000000000..a256577047d--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/start-workflow.action.ts@@ -0,0 +1,45 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripApi } from '../common/client';+import { dripProps } from '../common/props';+import { subscriberFieldProps, subscriberInput } from '../common/subscriber-input';+import { dripOutputSchemas } from '../output-schemas';++export const startWorkflowAction = createAction({+ auth: dripAuth,+ name: 'start_workflow',+ displayName: 'Start Workflow for Subscriber',+ description: 'Starts a subscriber on an active workflow. The workflow may send emails.',+ classification: 'WRITE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Starts a contact (by email or subscriber ID) on an active Drip workflow by Workflow ID (from List Workflows), creating or updating the subscriber with any fields given; the workflow may then send emails or apply tags. Drip ignores the request when the workflow is not active. Not idempotent: each call can start the subscriber on the workflow again.',+ idempotent: false,+ },+ props: {+ accountId: dripProps.accountId(),+ workflowId: Property.ShortText({ displayName: 'Workflow ID', description: 'Workflow ID (digits, from List Workflows). The workflow must be active.', required: true }),+ subscriber: dripProps.subscriber({ description: 'Email address of the person to start, or the Drip subscriber ID of an existing one.' }),+ ...subscriberFieldProps,+ customFields: dripProps.customFields(),+ tags: dripProps.tags(),+ },+ outputSchema: dripOutputSchemas.workflowStart,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const workflowId = dripApi.parseNumericId({ value: propsValue.workflowId, label: 'Workflow ID' });+ const record = { ...subscriberInput.fields(propsValue), ...dripApi.identify({ value: propsValue.subscriber, label: 'Subscriber Email or ID' }) };+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ const body = await dripApi.request<unknown>({+ token,+ method: HttpMethod.POST,+ path: `${dripApi.accountPath(accountId)}/workflows/${workflowId}/subscribers`,+ operation: 'start workflow',+ body: { subscribers: [record] },+ });+ const subscribers = dripApi.recordList({ body, key: 'subscribers' });+ return { workflowId, subscriber: subscribers[0] ?? null };+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/unsubscribe-subscriber.action.ts b/packages/pieces/community/drip/src/lib/actions/unsubscribe-subscriber.action.tsnew file mode 100644index 00000000000..ca9e6a2ada5--- /dev/null+++ b/packages/pieces/community/drip/src/lib/actions/unsubscribe-subscriber.action.ts@@ -0,0 +1,37 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripApi } from '../common/client';+import { dripProps } from '../common/props';+import { dripOutputSchemas } from '../output-schemas';++export const unsubscribeSubscriberAction = createAction({+ auth: dripAuth,+ name: 'unsubscribe_subscriber',+ displayName: 'Unsubscribe From All Emails',+ description: 'Unsubscribes a subscriber from all Drip mailings.',+ classification: 'DESTRUCTIVE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Unsubscribes a contact (by email or subscriber ID) from all Drip mailings and returns the updated subscriber with status unsubscribed. Use only when the user asks to opt someone out; re-subscribing them later needs their consent. Repeating it leaves them unsubscribed, so it is idempotent.',+ idempotent: true,+ },+ props: {+ accountId: dripProps.accountId(),+ subscriber: dripProps.subscriber(),+ },+ outputSchema: dripOutputSchemas.subscriber,+ async run({ auth, propsValue }) {+ const token = auth.secret_text;+ const segment = dripApi.seg({ value: propsValue.subscriber, label: 'Subscriber Email or ID' });+ const accountId = await dripApi.resolveAccountId({ token, accountId: propsValue.accountId });+ const body = await dripApi.request<unknown>({+ token,+ method: HttpMethod.POST,+ path: `${dripApi.accountPath(accountId)}/subscribers/${segment}/unsubscribe_all`,+ operation: 'unsubscribe subscriber',+ });+ return dripApi.firstRecord({ body, key: 'subscribers', operation: 'unsubscribe subscriber' });+ },+});diff --git a/packages/pieces/community/drip/src/lib/actions/upsert-subscriber.action.ts b/packages/pieces/community/drip/src/lib/actions/upsert-subscriber.action.tsindex 512b3ae6044..c9d491ee924 100644--- a/packages/pieces/community/drip/src/lib/actions/upsert-subscriber.action.ts+++ b/packages/pieces/community/drip/src/lib/actions/upsert-subscriber.action.ts@@ -1,18 +1,16 @@import { createAction, Property } from '@activepieces/pieces-framework';-import {- HttpRequest,- HttpMethod,- httpClient,-} from '@activepieces/pieces-common';+import { HttpMethod } from '@activepieces/pieces-common';import { dripCommon } from '../common';+import { dripApi } from '../common/client';import { dripAuth } from '../auth';+import { dripOutputSchemas } from '../output-schemas';export const dripUpsertSubscriberAction = createAction({auth: dripAuth,name: 'upsert_subscriber',classification: 'WRITE',description: 'Create or Update Subscriber',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Creates a subscriber in a Drip account, or updates the existing one matched by email address, setting tags, custom fields, and contact details (name, address, phone, location). Use to add a new contact or keep an existing contact in sync. Idempotent: matched on the stable email, so repeating with the same input converges to the same record.', idempotent: true },displayName: 'Create or Update Subscriber',props: {@@ -55,14 +53,17 @@ export const dripUpsertSubscriberAction = createAction({}),address: Property.ShortText({displayName: 'Address',- description: "The subscriber's mailing address",+ description: "Address line 1 of the subscriber's mailing address",required: false,}),},+ outputSchema: dripOutputSchemas.legacySubscribersResponse,async run({ auth, propsValue }) {- const request: HttpRequest = {+ return await dripApi.send<Record<string, unknown>>({+ token: auth.secret_text,method: HttpMethod.POST,- url: `${dripCommon.baseUrl(propsValue.account_id)}/subscribers`,+ path: `${dripApi.accountPath(propsValue.account_id)}/subscribers`,+ operation: 'create or update subscriber',body: {subscribers: [{@@ -80,11 +81,6 @@ export const dripUpsertSubscriberAction = createAction({},],},- headers: {- Authorization: dripCommon.authorizationHeader(auth),- },- queryParams: {},- };- return await httpClient.sendRequest<Record<string, never>>(request);+ });},});diff --git a/packages/pieces/community/drip/src/lib/auth.ts b/packages/pieces/community/drip/src/lib/auth.tsindex 5c1ebb30555..cdddf11a660 100644--- a/packages/pieces/community/drip/src/lib/auth.ts+++ b/packages/pieces/community/drip/src/lib/auth.ts@@ -1,7 +1,24 @@import { PieceAuth } from '@activepieces/pieces-framework';+import { dripApi } from './common/client';export const dripAuth = PieceAuth.SecretText({displayName: 'API Key',required: true,- description: 'Get it from https://www.getdrip.com/user/edit',+ description: 'Your Drip API token. In Drip go to Settings → User Settings → API Token (https://www.getdrip.com/user/edit) and copy the token.',+ validate: async ({ auth }) => {+ try {+ const accounts = await dripApi.listAccounts(auth);+ if (accounts.length === 0) {+ return { valid: false, error: 'This Drip API token has no accounts.' };+ }+ return { valid: true };+ } catch (error) {+ const status = dripApi.statusOf(error);+ if (status === 401 || status === 403) {+ return { valid: false, error: 'Invalid Drip API token. Copy it again from Settings → User Settings → API Token.' };+ }+ const message = error instanceof Error ? error.message : String(error);+ return { valid: false, error: `Could not check the token with Drip: ${message.slice(0, 300)}` };+ }+ },});diff --git a/packages/pieces/community/drip/src/lib/common/client.ts b/packages/pieces/community/drip/src/lib/common/client.tsnew file mode 100644index 00000000000..bf66be910a4--- /dev/null+++ b/packages/pieces/community/drip/src/lib/common/client.ts@@ -0,0 +1,463 @@+import { HttpMethod, HttpRequest, HttpResponse, httpClient } from '@activepieces/pieces-common';++const DRIP_ORIGIN = 'https://api.getdrip.com';+const USER_AGENT = 'Activepieces (www.activepieces.com)';+const REQUEST_TIMEOUT_MS = 30_000;+const RATE_LIMIT_RETRY_DELAYS_MS = [10_000, 15_000];+const MAX_ERROR_TEXT = 500;+const ACCOUNT_ID_PATTERN = /^\d+$/;+const ISO_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;++export class DripApiError extends Error {+ readonly status: number;+ readonly code: string | undefined;+ readonly responseBody: unknown;++ constructor({ operation, status, responseBody }: { operation: string; status: number; responseBody: unknown }) {+ const code = firstErrorCode(responseBody);+ super(`Drip ${operation} failed (${status}${code ? ` ${code}` : ''}): ${describeStatus({ status, responseBody })}`);+ this.name = 'DripApiError';+ this.status = status;+ this.code = code;+ this.responseBody = responseBody;+ }+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}++function firstError(responseBody: unknown): Record<string, unknown> | undefined {+ if (!isRecord(responseBody) || !Array.isArray(responseBody['errors'])) {+ return undefined;+ }+ const first: unknown = responseBody['errors'][0];+ return isRecord(first) ? first : undefined;+}++function firstErrorCode(responseBody: unknown): string | undefined {+ const code = firstError(responseBody)?.['code'];+ return typeof code === 'string' ? code : undefined;+}++function vendorMessage(responseBody: unknown): string {+ if (typeof responseBody === 'string' && responseBody.length > 0) {+ return responseBody.slice(0, MAX_ERROR_TEXT);+ }+ if (isRecord(responseBody) && Array.isArray(responseBody['errors'])) {+ const parts = responseBody['errors']+ .filter(isRecord)+ .map((error) => {+ const message = typeof error['message'] === 'string' ? error['message'] : String(error['code'] ?? 'error');+ return typeof error['attribute'] === 'string' ? `${error['attribute']}: ${message}` : message;+ });+ if (parts.length > 0) {+ return parts.join('; ').slice(0, MAX_ERROR_TEXT);+ }+ }+ if (isRecord(responseBody)) {+ if (typeof responseBody['message'] === 'string') {+ return responseBody['message'].slice(0, MAX_ERROR_TEXT);+ }+ return JSON.stringify(responseBody).slice(0, MAX_ERROR_TEXT);+ }+ return 'no details returned';+}++function describeStatus({ status, responseBody }: { status: number; responseBody: unknown }): string {+ const detail = vendorMessage(responseBody);+ if (status === 401) {+ return `the API token is invalid or was revoked. ${detail}`;+ }+ if (status === 403 && /disabled/i.test(detail)) {+ return `the Drip account is disabled (usually billing or an ended trial); reactivate it in Drip. ${detail}`;+ }+ if (status === 403) {+ return `Drip refused the request (no access, or the change is not allowed in this state). ${detail}`;+ }+ if (status === 404) {+ return `not found. Check the account ID and the IDs or email you passed. ${detail}`;+ }+ if (status === 422) {+ return `Drip rejected the input. ${detail}`;+ }+ if (status === 429) {+ return `Drip rate limit reached (3,600 requests per hour, 50 per hour for batch endpoints, or too many concurrent updates to one subscriber); try again later. ${detail}`;+ }+ return detail;+}++function statusOf(error: unknown): number | undefined {+ if (error instanceof DripApiError) {+ return error.status;+ }+ if (!(error instanceof Error) && !isRecord(error)) {+ return undefined;+ }+ const response: unknown = Reflect.get(error, 'response');+ if (isRecord(response) && typeof response['status'] === 'number') {+ return response['status'];+ }+ return undefined;+}++function responseBodyOf(error: unknown): unknown {+ if (!(error instanceof Error) && !isRecord(error)) {+ return undefined;+ }+ const response: unknown = Reflect.get(error, 'response');+ return isRecord(response) ? response['body'] : undefined;+}++function isNotFound(error: unknown): boolean {+ return statusOf(error) === 404;+}++function authHeader(token: string): string {+ return `Basic ${Buffer.from(token.trim()).toString('base64')}`;+}++function seg({ value, label }: { value: unknown; label: string }): string {+ const text = requireText({ value, label });+ if (text === '.' || text === '..') {+ throw new Error(`${label} "${text}" is not valid.`);+ }+ return encodeURIComponent(text);+}++function requireText({ value, label }: { value: unknown; label: string }): string {+ if (value === undefined || value === null || String(value).trim() === '') {+ throw new Error(`${label} is required.`);+ }+ return String(value).trim();+}++function identify({ value, label }: { value: unknown; label: string }): { email: string } | { id: string } {+ const text = requireText({ value, label });+ return text.includes('@') ? { email: text } : { id: text };+}++function optionalText(value: unknown): string | undefined {+ if (value === undefined || value === null) {+ return undefined;+ }+ const text = String(value).trim();+ return text === '' ? undefined : text;+}++function parseAccountId(value: unknown): string {+ const text = requireText({ value, label: 'Account ID' });+ if (!ACCOUNT_ID_PATTERN.test(text)) {+ throw new Error(`"${text.slice(0, 100)}" is not a valid Drip account ID (digits only, e.g. 1234567). Use List Accounts to find it.`);+ }+ return text;+}++function parseNumericId({ value, label }: { value: unknown; label: string }): string {+ const text = requireText({ value, label });+ if (!ACCOUNT_ID_PATTERN.test(text)) {+ throw new Error(`"${text.slice(0, 100)}" is not a valid ${label} (digits only).`);+ }+ return text;+}++function validateInteger({ value, label, min, max }: { value: unknown; label: string; min: number; max: number }): number | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ const number = Number(value);+ if (!Number.isInteger(number) || number < min || number > max) {+ throw new Error(`${label} must be a whole number between ${min} and ${max}.`);+ }+ return number;+}++function validateNumber({ value, label, min }: { value: unknown; label: string; min?: number }): number | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ const number = typeof value === 'number' ? value : Number(String(value).trim());+ if (!Number.isFinite(number) || (min !== undefined && number < min)) {+ throw new Error(`${label} must be a number${min !== undefined ? ` of at least ${min}` : ''}.`);+ }+ return number;+}++function parseIsoDate({ value, label }: { value: unknown; label: string }): string | undefined {+ const text = optionalText(value);+ if (text === undefined) {+ return undefined;+ }+ if (!ISO_DATE_PATTERN.test(text) || Number.isNaN(Date.parse(text))) {+ throw new Error(`${label} must be an ISO-8601 date or date-time, e.g. 2026-01-31T09:00:00Z.`);+ }+ return new Date(text).toISOString().replace(/\.\d{3}Z$/, 'Z');+}++function parseObject({ value, label }: { value: unknown; label: string }): Record<string, unknown> | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ let parsed: unknown = value;+ if (typeof value === 'string') {+ try {+ parsed = JSON.parse(value);+ } catch {+ throw new Error(`${label} must be a JSON object, e.g. {"key": "value"}.`);+ }+ }+ if (!isRecord(parsed)) {+ throw new Error(`${label} must be an object of key/value pairs.`);+ }+ return parsed;+}++function parseArray({ value, label }: { value: unknown; label: string }): unknown[] | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ let parsed: unknown = value;+ if (typeof value === 'string') {+ try {+ parsed = JSON.parse(value);+ } catch {+ throw new Error(`${label} must be a JSON array.`);+ }+ }+ if (!Array.isArray(parsed)) {+ throw new Error(`${label} must be a list (JSON array).`);+ }+ return parsed;+}++function textList(value: unknown): string[] | undefined {+ if (value === undefined || value === null) {+ return undefined;+ }+ const raw = Array.isArray(value) ? value : String(value).split(',');+ const seen = new Set<string>();+ for (const item of raw.flat()) {+ const text = optionalText(item);+ if (text !== undefined) {+ seen.add(text);+ }+ }+ return [...seen];+}++function compact(record: Record<string, unknown>): Record<string, unknown> {+ return Object.fromEntries(Object.entries(record).filter(([, value]) => value !== undefined));+}++function paging({ page, perPage, max }: { page: unknown; perPage: unknown; max: number }): { page: number; perPage: number } {+ return {+ page: validateInteger({ value: page, label: 'Page', min: 1, max: 1_000_000 }) ?? 1,+ perPage: validateInteger({ value: perPage, label: 'Results per Page', min: 1, max }) ?? Math.min(100, max),+ };+}++function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++function toQueryParams(query: Record<string, DripQueryValue> | undefined): Record<string, string> {+ if (!query) {+ return {};+ }+ const result: Record<string, string> = {};+ for (const [key, value] of Object.entries(query)) {+ if (value !== undefined && value !== null && value !== '') {+ result[key] = String(value);+ }+ }+ return result;+}++async function send<T>({ token, method, path, version = 'v2', operation, query, body, wait = sleep }: DripRequest): Promise<HttpResponse<T>> {+ if (!path.startsWith('/')) {+ throw new Error(`Internal error: Drip path must start with "/" (${operation}).`);+ }+ const httpRequest: HttpRequest = {+ method,+ url: `${DRIP_ORIGIN}/${version}${path}`,+ headers: { Authorization: authHeader(token), 'User-Agent': USER_AGENT },+ queryParams: toQueryParams(query),+ timeout: REQUEST_TIMEOUT_MS,+ followRedirects: false,+ };+ if (body !== undefined) {+ httpRequest.body = body;+ httpRequest.headers = { ...httpRequest.headers, 'Content-Type': 'application/json' };+ }+ for (let attempt = 0; ; attempt++) {+ try {+ const response = await httpClient.sendRequest<T>(httpRequest);+ if (response.status >= 300) {+ throw new DripApiError({ operation, status: response.status, responseBody: response.body });+ }+ return response;+ } catch (error) {+ if (error instanceof DripApiError) {+ throw error;+ }+ const status = statusOf(error);+ if (status === undefined) {+ throw error;+ }+ if (status === 429 && attempt < RATE_LIMIT_RETRY_DELAYS_MS.length) {+ await wait(RATE_LIMIT_RETRY_DELAYS_MS[attempt]);+ continue;+ }+ throw new DripApiError({ operation, status, responseBody: responseBodyOf(error) });+ }+ }+}++async function request<T>(params: DripRequest): Promise<T> {+ const response = await send<T>(params);+ return response.body;+}++async function listAccounts(token: string): Promise<DripAccount[]> {+ const body = await request<{ accounts?: DripAccount[] }>({ token, method: HttpMethod.GET, path: '/accounts', operation: 'list accounts' });+ return Array.isArray(body.accounts) ? body.accounts : [];+}++async function resolveAccountId({ token, accountId }: { token: string; accountId: unknown }): Promise<string> {+ const given = optionalText(accountId);+ if (given !== undefined) {+ return parseAccountId(given);+ }+ const accounts = await listAccounts(token);+ if (accounts.length === 0) {+ throw new Error('This Drip API token has no accounts.');+ }+ if (accounts.length > 1) {+ const choices = accounts.map((account) => `${account.id}: ${account.name}`).join(', ');+ throw new Error(`This Drip API token has ${accounts.length} accounts; pass the Account ID of one of them (${choices.slice(0, MAX_ERROR_TEXT)}).`);+ }+ return parseAccountId(accounts[0].id);+}++function accountPath(accountId: string): string {+ return `/${parseAccountId(accountId)}`;+}++function pageInfo({ meta, page, perPage, count }: { meta: unknown; page: number; perPage: number; count: number }): PageInfo {+ const totalPages = isRecord(meta) && typeof meta['total_pages'] === 'number' ? meta['total_pages'] : undefined;+ const totalCount = isRecord(meta) && typeof meta['total_count'] === 'number' ? meta['total_count'] : undefined;+ const hasMore = totalPages !== undefined ? page < totalPages : count >= perPage;+ return { page, totalPages: totalPages ?? null, totalCount: totalCount ?? null, hasMore };+}++async function listPage({+ token,+ accountId,+ resource,+ key,+ operation,+ page,+ perPage,+ query,+}: {+ token: string;+ accountId: string;+ resource: string;+ key: string;+ operation: string;+ page: number;+ perPage: number;+ query?: Record<string, DripQueryValue>;+}): Promise<{ items: DripRecord[] } & PageInfo> {+ const body = await request<Record<string, unknown>>({+ token,+ method: HttpMethod.GET,+ path: `${accountPath(accountId)}${resource}`,+ operation,+ query: { ...query, page, per_page: perPage },+ });+ const raw = body[key];+ const items = Array.isArray(raw) ? raw.filter(isRecord) : [];+ return { items, ...pageInfo({ meta: body['meta'], page, perPage, count: items.length }) };+}++function firstRecord({ body, key, operation }: { body: unknown; key: string; operation: string }): DripRecord {+ const list = isRecord(body) ? body[key] : undefined;+ const first: unknown = Array.isArray(list) ? list[0] : undefined;+ if (!isRecord(first)) {+ throw new Error(`Drip ${operation} returned no ${key} record.`);+ }+ return first;+}++function recordList({ body, key }: { body: unknown; key: string }): DripRecord[] {+ const list = isRecord(body) ? body[key] : undefined;+ return Array.isArray(list) ? list.filter(isRecord) : [];+}++export const dripApi = {+ send,+ request,+ listAccounts,+ resolveAccountId,+ accountPath,+ listPage,+ pageInfo,+ firstRecord,+ recordList,+ authHeader,+ seg,+ requireText,+ optionalText,+ identify,+ parseAccountId,+ parseNumericId,+ validateInteger,+ validateNumber,+ parseIsoDate,+ parseObject,+ parseArray,+ textList,+ compact,+ paging,+ isNotFound,+ statusOf,+ isRecord,+ vendorMessage,+ sleep,+ DRIP_ORIGIN,+ USER_AGENT,+ RATE_LIMIT_RETRY_DELAYS_MS,+};++export type DripQueryValue = string | number | boolean | undefined | null;++export type DripRequest = {+ token: string;+ method: HttpMethod;+ path: string;+ version?: 'v2' | 'v3';+ operation: string;+ query?: Record<string, DripQueryValue>;+ body?: unknown;+ wait?: (ms: number) => Promise<void>;+};++export type DripRecord = Record<string, unknown>;++export type PageInfo = {+ page: number;+ totalPages: number | null;+ totalCount: number | null;+ hasMore: boolean;+};++export type DripAccount = {+ id: string;+ name: string;+ url?: string | null;+ primary_email?: string | null;+ default_from_name?: string | null;+ default_from_email?: string | null;+ created_at?: string | null;+};diff --git a/packages/pieces/community/drip/src/lib/common/index.ts b/packages/pieces/community/drip/src/lib/common/index.tsindex 27e04ca69d6..c246540a433 100644--- a/packages/pieces/community/drip/src/lib/common/index.ts+++ b/packages/pieces/community/drip/src/lib/common/index.ts@@ -1,14 +1,13 @@import { AppConnectionValueForAuthProperty, Property } from '@activepieces/pieces-framework';-import {- HttpRequest,- HttpMethod,- httpClient,-} from '@activepieces/pieces-common';import { dripAuth } from '../auth';+import { dripApi } from './client';++const MAX_DROPDOWN_PAGES = 10;+const DROPDOWN_PAGE_SIZE = 1000;export const dripCommon = {baseUrl: (accountId: string) => {- return `https://api.getdrip.com/v2/${accountId}`;+ return `${dripApi.DRIP_ORIGIN}/v2${dripApi.accountPath(accountId)}`;},account_id: Property.Dropdown({auth: dripAuth,@@ -23,35 +22,71 @@ export const dripCommon = {placeholder: 'Please fill in API key first',};}-- const request: HttpRequest = {- method: HttpMethod.GET,- url: 'https://api.getdrip.com/v2/accounts',- headers: {- Authorization: `Basic ${Buffer.from(auth.secret_text ).toString(- 'base64'- )}`,- },- };- const response = await httpClient.sendRequest<{- accounts: { id: string; name: string }[];- }>(request);- const opts = response.body.accounts.map((acc) => {- return { value: acc.id, label: acc.name };- });- return {- disabled: false,- options: opts,- };+ try {+ const accounts = await dripApi.listAccounts(auth.secret_text);+ if (accounts.length === 0) {+ return { disabled: true, options: [], placeholder: 'This API token has no Drip accounts' };+ }+ return {+ disabled: false,+ options: accounts.map((account) => ({ value: account.id, label: account.name })),+ };+ } catch (error) {+ return dropdownError(error);+ }},}),+ campaign_id: ({ required, description }: { required: boolean; description?: string }) =>+ Property.Dropdown({+ displayName: 'Email Series Campaign',+ description,+ auth: dripAuth,+ refreshers: ['account_id'],+ required,+ options: async ({ auth, account_id }) => {+ if (!auth) {+ return {+ disabled: true,+ options: [],+ placeholder: 'Please fill in API key first',+ };+ }+ if (!account_id) {+ return {+ disabled: true,+ options: [],+ placeholder: 'Please select an account first',+ };+ }+ try {+ const { campaigns, truncated } = await listAllCampaigns({ token: auth.secret_text, accountId: String(account_id) });+ if (campaigns.length === 0) {+ return {+ disabled: false,+ options: [],+ placeholder: 'Please create an email series campaign',+ };+ }+ return {+ disabled: false,+ ...(truncated ? { placeholder: `Showing the first ${campaigns.length} email series campaigns by name. Drip has more, so some campaigns are not listed here.` } : {}),+ options: campaigns.map((campaign) => ({+ value: String(campaign['id']),+ label: `${String(campaign['name'] ?? campaign['id'])} (${String(campaign['status'] ?? 'unknown')})`,+ })),+ };+ } catch (error) {+ return dropdownError(error);+ }+ },+ }),subscriber: Property.ShortText({required: true,displayName: 'Subscriber Email',description: 'Email of the subscriber',}),tags: Property.Array({- displayName: 'tags',+ displayName: 'Tags',required: false,description: 'Tags to apply to subscriber',}),@@ -60,6 +95,35 @@ export const dripCommon = {required: false,description: 'Custom field data about the subscriber',}),- authorizationHeader: (apiKey: AppConnectionValueForAuthProperty<typeof dripAuth>) =>- `Basic ${Buffer.from(apiKey.secret_text).toString('base64')}`,+ authorizationHeader: (apiKey: AppConnectionValueForAuthProperty<typeof dripAuth>) => dripApi.authHeader(apiKey.secret_text),+ dropdownError,+ listAllCampaigns,};++function dropdownError(error: unknown): { disabled: true; options: []; placeholder: string } {+ const message = error instanceof Error ? error.message : String(error);+ return { disabled: true, options: [], placeholder: message.slice(0, 300) };+}++async function listAllCampaigns({ token, accountId }: { token: string; accountId: string }): Promise<{ campaigns: Record<string, unknown>[]; truncated: boolean }> {+ const pages: Record<string, unknown>[][] = [];+ let truncated = false;+ for (let page = 1; page <= MAX_DROPDOWN_PAGES; page++) {+ const result = await dripApi.listPage({+ token,+ accountId,+ resource: '/campaigns',+ key: 'campaigns',+ operation: 'list email series campaigns',+ page,+ perPage: DROPDOWN_PAGE_SIZE,+ query: { status: 'all', sort: 'name', direction: 'asc' },+ });+ pages.push(result.items);+ if (!result.hasMore) {+ break;+ }+ truncated = page === MAX_DROPDOWN_PAGES;+ }+ return { campaigns: pages.flat(), truncated };+}diff --git a/packages/pieces/community/drip/src/lib/common/props.ts b/packages/pieces/community/drip/src/lib/common/props.tsnew file mode 100644index 00000000000..afe958bf995--- /dev/null+++ b/packages/pieces/community/drip/src/lib/common/props.ts@@ -0,0 +1,60 @@+import { Property } from '@activepieces/pieces-framework';++export const dripProps = {+ accountId: () =>+ Property.ShortText({+ displayName: 'Account ID',+ description: 'Drip account ID (digits, from List Accounts or the Drip URL). Leave empty when the API token has only one account.',+ required: false,+ }),+ subscriber: ({ description }: { description?: string } = {}) =>+ Property.ShortText({+ displayName: 'Subscriber Email or ID',+ description: description ?? 'The subscriber email address or Drip subscriber ID.',+ required: true,+ }),+ email: ({ required = true, description }: { required?: boolean; description?: string } = {}) =>+ Property.ShortText({+ displayName: 'Email',+ description: description ?? 'The subscriber email address.',+ required,+ }),+ page: () =>+ Property.Number({+ displayName: 'Page',+ description: 'Page number, starting at 1. Pass the next page while Has More is true.',+ required: false,+ defaultValue: 1,+ }),+ perPage: ({ max }: { max: number }) =>+ Property.Number({+ displayName: 'Results per Page',+ description: `How many results per page (1-${max}).`,+ required: false,+ defaultValue: 100,+ }),+ tags: ({ displayName = 'Tags', description }: { displayName?: string; description?: string } = {}) =>+ Property.Array({+ displayName,+ description: description ?? 'Tags to apply to the subscriber.',+ required: false,+ }),+ customFields: () =>+ Property.Object({+ displayName: 'Custom Fields',+ description: 'Custom field values keyed by field identifier, e.g. {"shirt_size": "Medium"}. A new identifier creates the custom field in Drip.',+ required: false,+ }),+ timeZone: () =>+ Property.ShortText({+ displayName: 'Time Zone',+ description: 'The subscriber time zone in Olson format, e.g. America/Los_Angeles.',+ required: false,+ }),+};++export const pagingDefaults = {+ perPage: 100,+ maxPerPage: 1000,+ maxPerPageSmall: 100,+};diff --git a/packages/pieces/community/drip/src/lib/common/samples.ts b/packages/pieces/community/drip/src/lib/common/samples.tsnew file mode 100644index 00000000000..76c509fec64--- /dev/null+++ b/packages/pieces/community/drip/src/lib/common/samples.ts@@ -0,0 +1,37 @@+const subscriber = {+ id: 'o0csqd1jqiez381idl4o',+ status: 'active',+ deliverable: true,+ email: '[email protected]',+ custom_fields: { first_name: 'John' },+ tags: ['Customer'],+ time_zone: null,+ utc_offset: 0,+ created_at: '2026-10-06T15:52:58Z',+ ip_address: null,+ user_agent: null,+ lifetime_value: null,+ original_referrer: null,+ landing_url: null,+ prospect: false,+ base_lead_score: null,+ lead_score: null,+ user_id: null,+};++function event({ name, properties = {} }: { name: string; properties?: Record<string, unknown> }): Record<string, unknown> {+ return {+ event: name,+ data: {+ subscriber,+ properties: { ...properties, source: 'drip' },+ account_id: '9999999',+ },+ occurred_at: '2026-10-06T15:52:58Z',+ };+}++export const dripSamples = {+ subscriber,+ event,+};diff --git a/packages/pieces/community/drip/src/lib/common/shopper.ts b/packages/pieces/community/drip/src/lib/common/shopper.tsnew file mode 100644index 00000000000..ab67fb037ee--- /dev/null+++ b/packages/pieces/community/drip/src/lib/common/shopper.ts@@ -0,0 +1,114 @@+import { Property } from '@activepieces/pieces-framework';+import { dripApi } from './client';++const PROVIDER_PATTERN = /^[a-z0-9_]+$/;+const CURRENCY_PATTERN = /^[A-Za-z]{3}$/;+const MAX_ITEMS = 1000;++export const shopperProps = {+ email: Property.ShortText({ displayName: 'Customer Email', description: 'Email of the customer. Either this or Drip Person ID is required.', required: false }),+ personId: Property.ShortText({ displayName: 'Drip Person ID', description: 'Drip subscriber ID of the customer. Used instead of the email when both are given.', required: false }),+ provider: Property.ShortText({+ displayName: 'Provider',+ description: 'Lower snake_case name of the store platform, e.g. shopify or my_store. Drip treats provider + ID as the unique key.',+ required: true,+ defaultValue: 'activepieces',+ }),+ initialStatus: Property.StaticDropdown({+ displayName: 'New Person Status',+ description: 'Status for a person Drip creates from this activity. Drip subscribes them (active) when left empty; choose Unsubscribed if they have not consented to marketing.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Active (subscribed)', value: 'active' },+ { label: 'Unsubscribed', value: 'unsubscribed' },+ ],+ },+ }),+ occurredAt: Property.DateTime({ displayName: 'Occurred At', description: 'When it happened (ISO-8601). Defaults to now.', required: false }),+ currency: Property.ShortText({ displayName: 'Currency', description: 'ISO 4217 code, e.g. USD.', required: false }),+};++export const shopperInput = {+ person,+ provider,+ currency,+ amount,+ items,+ requestId,+};++function requestId(body: unknown): string | null {+ if (!dripApi.isRecord(body)) {+ return null;+ }+ if (typeof body['request_id'] === 'string') {+ return body['request_id'];+ }+ const ids = body['request_ids'];+ return Array.isArray(ids) && typeof ids[0] === 'string' ? ids[0] : null;+}++function person({ email, personId }: { email: unknown; personId: unknown }): Record<string, string> {+ const id = dripApi.optionalText(personId);+ if (id !== undefined) {+ return { person_id: id };+ }+ const address = dripApi.optionalText(email);+ if (address === undefined) {+ throw new Error('Customer Email or Drip Person ID is required.');+ }+ return { email: address };+}++function provider(value: unknown): string {+ const text = dripApi.requireText({ value, label: 'Provider' });+ if (!PROVIDER_PATTERN.test(text)) {+ throw new Error('Provider must be lower snake_case letters, digits and underscores, e.g. my_store.');+ }+ return text;+}++function currency(value: unknown): string | undefined {+ const text = dripApi.optionalText(value);+ if (text === undefined) {+ return undefined;+ }+ if (!CURRENCY_PATTERN.test(text)) {+ throw new Error('Currency must be a 3-letter ISO 4217 code, e.g. USD.');+ }+ return text.toUpperCase();+}++function amount({ value, label }: { value: unknown; label: string }): number | undefined {+ return dripApi.validateNumber({ value, label, min: 0 });+}++function items({ value, required }: { value: unknown; required: string[] }): Record<string, unknown>[] | undefined {+ const list = dripApi.parseArray({ value, label: 'Items' });+ if (list === undefined) {+ return undefined;+ }+ if (list.length > MAX_ITEMS) {+ throw new Error(`Items can contain at most ${MAX_ITEMS} entries.`);+ }+ return list.map((item, index) => {+ if (!dripApi.isRecord(item)) {+ throw new Error(`Item #${index + 1} must be an object.`);+ }+ const missing = required.filter((key) => item[key] === undefined || item[key] === null || String(item[key]).trim() === '');+ if (missing.length > 0) {+ throw new Error(`Item #${index + 1} is missing ${missing.join(', ')}.`);+ }+ for (const key of ['price', 'quantity', 'discounts', 'taxes', 'fees', 'shipping', 'total']) {+ if (item[key] !== undefined && item[key] !== null) {+ const number = Number(item[key]);+ if (!Number.isFinite(number)) {+ throw new Error(`Item #${index + 1} ${key} must be a number.`);+ }+ }+ }+ return item;+ });+}diff --git a/packages/pieces/community/drip/src/lib/common/subscriber-input.ts b/packages/pieces/community/drip/src/lib/common/subscriber-input.tsnew file mode 100644index 00000000000..5561bd6d013--- /dev/null+++ b/packages/pieces/community/drip/src/lib/common/subscriber-input.ts@@ -0,0 +1,58 @@+import { Property } from '@activepieces/pieces-framework';+import { dripApi } from './client';++export const subscriberFieldProps = {+ firstName: Property.ShortText({ displayName: 'First Name', required: false }),+ lastName: Property.ShortText({ displayName: 'Last Name', required: false }),+ address1: Property.ShortText({ displayName: 'Address Line 1', required: false }),+ address2: Property.ShortText({ displayName: 'Address Line 2', required: false }),+ city: Property.ShortText({ displayName: 'City', required: false }),+ state: Property.ShortText({ displayName: 'State / Region', required: false }),+ zip: Property.ShortText({ displayName: 'Postal Code', required: false }),+ country: Property.ShortText({ displayName: 'Country', required: false }),+ phone: Property.ShortText({ displayName: 'Phone', required: false }),+ userId: Property.ShortText({ displayName: 'Your User ID', description: 'Your own ID for this person, e.g. the primary key in your database.', required: false }),+ timeZone: Property.ShortText({ displayName: 'Time Zone', description: 'Olson time zone, e.g. America/Los_Angeles.', required: false }),+};++export const subscriberInput = {+ fields: buildFields,+};++function buildFields(values: SubscriberFieldValues): Record<string, unknown> {+ return dripApi.compact({+ first_name: dripApi.optionalText(values.firstName),+ last_name: dripApi.optionalText(values.lastName),+ address1: dripApi.optionalText(values.address1),+ address2: dripApi.optionalText(values.address2),+ city: dripApi.optionalText(values.city),+ state: dripApi.optionalText(values.state),+ zip: dripApi.optionalText(values.zip),+ country: dripApi.optionalText(values.country),+ phone: dripApi.optionalText(values.phone),+ user_id: dripApi.optionalText(values.userId),+ time_zone: dripApi.optionalText(values.timeZone),+ custom_fields: dripApi.parseObject({ value: values.customFields, label: 'Custom Fields' }),+ tags: nonEmpty(dripApi.textList(values.tags)),+ });+}++function nonEmpty(list: string[] | undefined): string[] | undefined {+ return list && list.length > 0 ? list : undefined;+}++type SubscriberFieldValues = {+ firstName?: unknown;+ lastName?: unknown;+ address1?: unknown;+ address2?: unknown;+ city?: unknown;+ state?: unknown;+ zip?: unknown;+ country?: unknown;+ phone?: unknown;+ userId?: unknown;+ timeZone?: unknown;+ customFields?: unknown;+ tags?: unknown;+};diff --git a/packages/pieces/community/drip/src/lib/common/webhook.ts b/packages/pieces/community/drip/src/lib/common/webhook.tsnew file mode 100644index 00000000000..b653cd7bd20--- /dev/null+++ b/packages/pieces/community/drip/src/lib/common/webhook.ts@@ -0,0 +1,334 @@+import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';+import { HttpMethod } from '@activepieces/pieces-common';+import { DEDUPE_KEY_PROPERTY, Store } from '@activepieces/pieces-framework';+import { dripApi, DripRecord } from './client';++const TOKEN_PARAM = 'ap_token';+const CLAIM_CELLS = 256;+const CLAIM_PROBES = 4;+const CLAIM_SETTLE_MS = 500;+const ABANDONED_CLAIM_MS = 60_000;+const CELL_DELETE_BATCH = 32;++async function enable({ token, accountId, webhookUrl, store, storeKey, event }: EnableParams): Promise<void> {+ const account = dripApi.parseAccountId(accountId);+ const secret = randomBytes(32).toString('hex');+ const body = await dripApi.request<unknown>({+ token,+ method: HttpMethod.POST,+ path: `${dripApi.accountPath(account)}/webhooks`,+ operation: 'create webhook',+ body: { webhooks: [{ post_url: withToken({ url: webhookUrl, secret }), events: [event] }] },+ });+ const created = dripApi.firstRecord({ body, key: 'webhooks', operation: 'create webhook' });+ const webhookId = dripApi.optionalText(created['id']);+ if (webhookId === undefined) {+ throw new Error('Drip created the webhook but returned no webhook ID.');+ }+ try {+ await store.put<DripWebhookInformation>(storeKey, { webhookId, userId: account, secret });+ } catch (error) {+ await deleteWebhook({ token, accountId: account, webhookId }).catch(() => undefined);+ throw error;+ }+}++async function disable({ token, store, storeKey }: DisableParams): Promise<void> {+ const stored = await store.get<DripWebhookInformation>(storeKey);+ if (stored === null || stored === undefined) {+ return;+ }+ await deleteWebhook({ token, accountId: stored.userId, webhookId: stored.webhookId });+ await store.delete(storeKey);+ const keys = Array.from({ length: CLAIM_CELLS }, (_, cell) => cellKeyOf({ storeKey, cell })).flatMap((cellKey) => [cellKey, doneKeyOf(cellKey)]);+ for (let start = 0; start < keys.length; start += CELL_DELETE_BATCH) {+ await Promise.all(keys.slice(start, start + CELL_DELETE_BATCH).map((key) => store.delete(key)));+ }+}++async function handle({ token, store, storeKey, event, payload, matches }: HandleParams): Promise<unknown[]> {+ const stored = await store.get<DripWebhookInformation>(storeKey);+ if (stored === null || stored === undefined) {+ return [];+ }+ const body = payload.body;+ if (!dripApi.isRecord(body) || body['event'] !== event) {+ return [];+ }+ const data = body['data'];+ if (!dripApi.isRecord(data) || String(data['account_id'] ?? '') !== String(stored.userId)) {+ return [];+ }+ const delivered = readToken(payload.queryParams);+ let verifiedBody: DripRecord = body;+ if (stored.secret) {+ if (delivered === undefined || !sameSecret({ expected: stored.secret, given: delivered })) {+ return [];+ }+ } else {+ const refetched = await confirmWithDrip({ token, accountId: stored.userId, event, body, data });+ if (refetched === undefined) {+ return [];+ }+ verifiedBody = refetched;+ }+ if (matches && !matches(verifiedBody)) {+ return [];+ }+ const key = dedupeKey({ event, data, occurredAt: body['occurred_at'] });+ if (!(await claimDelivery({ store, storeKey, key }))) {+ return [];+ }+ return [{ ...verifiedBody, [DEDUPE_KEY_PROPERTY]: `drip:${storeKey}:${key}` }];+}++async function claimDelivery({ store, storeKey, key }: { store: Store; storeKey: string; key: string }): Promise<boolean> {+ const cells = probeCells({ storeKey, key });+ const states = await readCells({ store, cells });+ if (states.some((state) => holds({ state, key, now: Date.now() }))) {+ return false;+ }+ const claim: DeliveryClaim = { key, token: randomUUID(), at: Date.now() };+ const order = preferredCells({ cells, states, key });+ for (const cellKey of order) {+ const outcome = await tryCell({ store, cellKey, claim });+ if (outcome === 'lost') {+ return false;+ }+ if (outcome === 'won') {+ return recordDone({ store, cells, cellKey, claim });+ }+ }+ return recordDone({ store, cells, cellKey: order[0], claim });+}++async function recordDone({ store, cells, cellKey, claim }: { store: Store; cells: string[]; cellKey: string; claim: DeliveryClaim }): Promise<boolean> {+ try {+ if ((await readCells({ store, cells })).some((state) => state.done?.key === claim.key)) {+ return false;+ }+ await store.put<DeliveryClaim>(doneKeyOf(cellKey), claim);+ } catch (error) {+ await releaseClaim({ store, cellKey, claimToken: claim.token });+ throw error;+ }+ return true;+}++async function tryCell({ store, cellKey, claim }: { store: Store; cellKey: string; claim: DeliveryClaim }): Promise<'won' | 'lost' | 'taken'> {+ try {+ await store.put<DeliveryClaim>(cellKey, claim);+ await dripApi.sleep(CLAIM_SETTLE_MS);+ const current = await store.get<DeliveryClaim>(cellKey);+ if (current === null || current === undefined) {+ return 'won';+ }+ if (current.key !== claim.key) {+ return 'taken';+ }+ return current.token === claim.token ? 'won' : 'lost';+ } catch (error) {+ await releaseClaim({ store, cellKey, claimToken: claim.token });+ throw error;+ }+}++async function readCells({ store, cells }: { store: Store; cells: string[] }): Promise<CellState[]> {+ return Promise.all(+ cells.map(async (cellKey) => {+ const [claim, done] = await Promise.all([store.get<DeliveryClaim>(cellKey), store.get<DeliveryClaim>(doneKeyOf(cellKey))]);+ return { claim: claim ?? undefined, done: done ?? undefined };+ }),+ );+}++function holds({ state, key, now }: { state: CellState; key: string; now: number }): boolean {+ if (state.done?.key === key) {+ return true;+ }+ return state.claim?.key === key && !isAbandoned({ claim: state.claim, now });+}++function preferredCells({ cells, states, key }: { cells: string[]; states: CellState[]; key: string }): string[] {+ const rank = (state: CellState): number => {+ if (state.claim?.key === key) {+ return -2;+ }+ if (state.claim === undefined && state.done === undefined) {+ return -1;+ }+ return Math.max(state.claim?.at ?? 0, state.done?.at ?? 0);+ };+ return cells.map((cellKey, index) => ({ cellKey, rank: rank(states[index]) })).sort((a, b) => a.rank - b.rank).map((entry) => entry.cellKey);+}++function isAbandoned({ claim, now }: { claim: DeliveryClaim; now: number }): boolean {+ return typeof claim.at === 'number' && now - claim.at > ABANDONED_CLAIM_MS;+}++async function releaseClaim({ store, cellKey, claimToken }: { store: Store; cellKey: string; claimToken: string }): Promise<void> {+ try {+ const current = await store.get<DeliveryClaim>(cellKey);+ if (current?.token === claimToken) {+ await store.delete(cellKey);+ }+ } catch {+ return;+ }+}++function probeCells({ storeKey, key }: { storeKey: string; key: string }): string[] {+ const cells = Array.from({ length: CLAIM_PROBES }, (_, probe) => parseInt(key.slice(probe * 6, probe * 6 + 6), 16) % CLAIM_CELLS);+ return [...new Set(cells)].map((cell) => cellKeyOf({ storeKey, cell }));+}++function cellKeyOf({ storeKey, cell }: { storeKey: string; cell: number }): string {+ return `${storeKey}_c_${cell}`;+}++function doneKeyOf(cellKey: string): string {+ return `${cellKey}_ok`;+}++function withToken({ url, secret }: { url: string; secret: string }): string {+ const parsed = new URL(url);+ parsed.searchParams.set(TOKEN_PARAM, secret);+ return parsed.toString();+}++function readToken(queryParams: Record<string, unknown> | undefined): string | undefined {+ const value = queryParams?.[TOKEN_PARAM];+ const first: unknown = Array.isArray(value) ? value[0] : value;+ return typeof first === 'string' && first.length > 0 ? first : undefined;+}++function sameSecret({ expected, given }: { expected: string; given: string }): boolean {+ const a = Buffer.from(expected);+ const b = Buffer.from(given);+ return a.length === b.length && timingSafeEqual(a, b);+}++async function confirmWithDrip({ token, accountId, event, body, data }: { token: string; accountId: string; event: string; body: DripRecord; data: DripRecord }): Promise<DripRecord | undefined> {+ const subscriber = data['subscriber'];+ if (event === 'subscriber.deleted' || !dripApi.isRecord(subscriber)) {+ return undefined;+ }+ const id = dripApi.optionalText(subscriber['id']);+ const email = dripApi.optionalText(subscriber['email']);+ if (id === undefined) {+ return undefined;+ }+ let fetched: DripRecord;+ try {+ const response = await dripApi.request<unknown>({+ token,+ method: HttpMethod.GET,+ path: `${dripApi.accountPath(accountId)}/subscribers/${dripApi.seg({ value: id, label: 'Subscriber ID' })}`,+ operation: 'confirm webhook subscriber',+ });+ fetched = dripApi.firstRecord({ body: response, key: 'subscribers', operation: 'confirm webhook subscriber' });+ } catch (error) {+ if (dripApi.isNotFound(error)) {+ return undefined;+ }+ throw error;+ }+ if (email !== undefined && String(fetched['email'] ?? '').toLowerCase() !== email.toLowerCase()) {+ return undefined;+ }+ const properties = dripApi.isRecord(data['properties']) ? data['properties'] : {};+ const tag = dripApi.optionalText(properties['tag'])?.toLowerCase();+ const tags = Array.isArray(fetched['tags']) ? fetched['tags'].map((item) => String(item).toLowerCase()) : [];+ if (event === 'subscriber.applied_tag' && (tag === undefined || !tags.includes(tag))) {+ return undefined;+ }+ if (event === 'subscriber.removed_tag' && (tag === undefined || tags.includes(tag))) {+ return undefined;+ }+ return { ...body, data: { ...data, subscriber: fetched } };+}++function dedupeKey({ event, data, occurredAt }: { event: string; data: DripRecord; occurredAt: unknown }): string {+ const subscriber = dripApi.isRecord(data['subscriber']) ? data['subscriber'] : {};+ const parts = [event, String(subscriber['id'] ?? subscriber['email'] ?? ''), String(occurredAt ?? ''), JSON.stringify(data['properties'] ?? null)];+ return createHash('sha256').update(parts.join('|')).digest('hex');+}++async function deleteWebhook({ token, accountId, webhookId }: { token: string; accountId: string; webhookId: string }): Promise<void> {+ try {+ await dripApi.request<unknown>({+ token,+ method: HttpMethod.DELETE,+ path: `${dripApi.accountPath(accountId)}/webhooks/${dripApi.seg({ value: webhookId, label: 'Webhook ID' })}`,+ operation: 'delete webhook',+ });+ } catch (error) {+ if (!dripApi.isNotFound(error)) {+ throw error;+ }+ }+}++function propertiesOf(body: DripRecord): DripRecord {+ const data = body['data'];+ if (!dripApi.isRecord(data) || !dripApi.isRecord(data['properties'])) {+ return {};+ }+ return data['properties'];+}++function textMatches({ expected, actual }: { expected: unknown; actual: unknown }): boolean {+ const wanted = dripApi.optionalText(expected);+ if (wanted === undefined) {+ return true;+ }+ return String(actual ?? '').trim().toLowerCase() === wanted.toLowerCase();+}++export const dripWebhook = {+ enable,+ disable,+ handle,+ withToken,+ propertiesOf,+ textMatches,+ TOKEN_PARAM,+ CLAIM_CELLS,+ ABANDONED_CLAIM_MS,+ probeCells,+ doneKeyOf,+};++type DeliveryClaim = { key?: string; token: string; at?: number };++type CellState = { claim?: DeliveryClaim; done?: DeliveryClaim };++export type DripWebhookInformation = {+ webhookId: string;+ userId: string;+ secret?: string;+};++type EnableParams = {+ token: string;+ accountId: string;+ webhookUrl: string;+ store: Store;+ storeKey: string;+ event: string;+};++type DisableParams = {+ token: string;+ store: Store;+ storeKey: string;+};++type HandleParams = {+ token: string;+ store: Store;+ storeKey: string;+ event: string;+ payload: { body: unknown; queryParams?: Record<string, unknown> };+ matches?: (body: DripRecord) => boolean;+};diff --git a/packages/pieces/community/drip/src/lib/output-schemas.ts b/packages/pieces/community/drip/src/lib/output-schemas.tsnew file mode 100644index 00000000000..304de6e5781--- /dev/null+++ b/packages/pieces/community/drip/src/lib/output-schemas.ts@@ -0,0 +1,276 @@+import { OutputSchema } from '@activepieces/pieces-framework';++type Fields = OutputSchema['fields'];++const pageFields: Fields = [+ { key: 'page', label: 'Page', format: 'number' },+ { key: 'totalPages', label: 'Total Pages', format: 'number' },+ { key: 'totalCount', label: 'Total Count', format: 'number' },+ { key: 'hasMore', label: 'Has More', format: 'boolean', description: 'True when another page exists; pass Page + 1 to get it.' },+];++const subscriberFields: Fields = [+ { key: 'id', label: 'Subscriber ID' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'status', label: 'Status' },+ { key: 'first_name', label: 'First Name' },+ { key: 'last_name', label: 'Last Name' },+ { key: 'tags', label: 'Tags' },+ { key: 'custom_fields', label: 'Custom Fields', dynamicKey: true },+ { key: 'deliverable', label: 'Deliverable', format: 'boolean' },+ { key: 'address1', label: 'Address Line 1' },+ { key: 'address2', label: 'Address Line 2' },+ { key: 'city', label: 'City' },+ { key: 'state', label: 'State' },+ { key: 'zip', label: 'Postal Code' },+ { key: 'country', label: 'Country' },+ { key: 'phone', label: 'Phone' },+ { key: 'sms_number', label: 'SMS Number' },+ { key: 'time_zone', label: 'Time Zone' },+ { key: 'user_id', label: 'Your User ID' },+ { key: 'lifetime_value', label: 'Lifetime Value (cents)', format: 'number' },+ { key: 'lead_score', label: 'Lead Score', format: 'number' },+ { key: 'prospect', label: 'Prospect', format: 'boolean' },+ { key: 'eu_consent', label: 'EU Consent' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+];++const webhookSubscriberFields: Fields = [+ { key: 'id', label: 'Subscriber ID' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'status', label: 'Status' },+ { key: 'tags', label: 'Tags' },+ { key: 'custom_fields', label: 'Custom Fields', dynamicKey: true, description: 'Includes first_name and last_name when set.' },+ { key: 'deliverable', label: 'Deliverable', format: 'boolean' },+ { key: 'time_zone', label: 'Time Zone' },+ { key: 'user_id', label: 'Your User ID' },+ { key: 'lifetime_value', label: 'Lifetime Value (cents)', format: 'number' },+ { key: 'lead_score', label: 'Lead Score', format: 'number' },+ { key: 'prospect', label: 'Prospect', format: 'boolean' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+];++const webhookCauseFields: Fields = [+ { key: 'source', label: 'Source' },+];++const accountFields: Fields = [+ { key: 'id', label: 'Account ID', description: 'Pass this as Account ID in other Drip steps.' },+ { key: 'name', label: 'Name' },+ { key: 'url', label: 'Website' },+ { key: 'primary_email', label: 'Primary Email', format: 'email' },+ { key: 'default_from_name', label: 'Default From Name' },+ { key: 'default_from_email', label: 'Default From Email', format: 'email' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+];++const campaignFields: Fields = [+ { key: 'id', label: 'Campaign ID' },+ { key: 'name', label: 'Name' },+ { key: 'status', label: 'Status' },+ { key: 'from_name', label: 'From Name' },+ { key: 'from_email', label: 'From Email', format: 'email' },+ { key: 'email_count', label: 'Email Count', format: 'number' },+ { key: 'active_subscriber_count', label: 'Active Subscribers', format: 'number' },+ { key: 'unsubscribed_subscriber_count', label: 'Unsubscribed Subscribers', format: 'number' },+ { key: 'double_optin', label: 'Double Opt-In', format: 'boolean' },+ { key: 'start_immediately', label: 'Starts Immediately', format: 'boolean' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+];++const workflowFields: Fields = [+ { key: 'id', label: 'Workflow ID' },+ { key: 'name', label: 'Name' },+ { key: 'status', label: 'Status' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+];++const broadcastFields: Fields = [+ { key: 'id', label: 'Broadcast ID' },+ { key: 'name', label: 'Name' },+ { key: 'status', label: 'Status' },+ { key: 'subject', label: 'Subject' },+ { key: 'from_name', label: 'From Name' },+ { key: 'from_email', label: 'From Email', format: 'email' },+ { key: 'send_at', label: 'Send At', format: 'datetime' },+ { key: 'preview_url', label: 'Preview URL', format: 'url' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+];++const conversionFields: Fields = [+ { key: 'id', label: 'Conversion ID' },+ { key: 'name', label: 'Name' },+ { key: 'status', label: 'Status' },+ { key: 'url', label: 'URL' },+ { key: 'default_value', label: 'Default Value (cents)', format: 'number' },+ { key: 'counting_method', label: 'Counting Method' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+];++const formFields: Fields = [+ { key: 'id', label: 'Form ID' },+ { key: 'headline', label: 'Headline' },+ { key: 'description', label: 'Description' },+ { key: 'button_text', label: 'Button Text' },+ { key: 'is_widget_enabled', label: 'Widget Enabled', format: 'boolean' },+ { key: 'is_embeddable', label: 'Embeddable', format: 'boolean' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+];++const campaignSubscriptionFields: Fields = [+ { key: 'id', label: 'Subscription ID' },+ { key: 'campaign_id', label: 'Campaign ID' },+ { key: 'status', label: 'Status' },+ { key: 'is_complete', label: 'Completed', format: 'boolean' },+ { key: 'lap', label: 'Lap', format: 'number' },+ { key: 'last_sent_email_index', label: 'Last Sent Email Index', format: 'number' },+ { key: 'last_sent_email_at', label: 'Last Sent Email At', format: 'datetime' },+];++export const dripOutputSchemas = {+ listAccounts: { fields: [list({ fields: accountFields, labelKey: 'name', label: 'Accounts' })] },+ user: {+ fields: [+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'name', label: 'Name' },+ { key: 'time_zone', label: 'Time Zone' },+ ],+ },+ subscriber: { fields: subscriberFields },+ findSubscriber: {+ fields: [+ { key: 'found', label: 'Found', format: 'boolean' },+ { key: 'subscriber', label: 'Subscriber', children: subscriberFields },+ ],+ },+ subscriberPage: { fields: [list({ fields: subscriberFields, labelKey: 'email', label: 'Subscribers' }), ...pageFields] },+ deleteSubscriber: {+ fields: [+ { key: 'subscriber', label: 'Subscriber' },+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ { key: 'alreadyDeleted', label: 'Already Deleted', format: 'boolean', description: 'True when Drip had no such subscriber.' },+ ],+ },+ campaignSubscriptionPage: { fields: [list({ fields: campaignSubscriptionFields, labelKey: 'campaign_id', label: 'Subscriptions' }), ...pageFields] },+ batchUpsert: {+ fields: [+ { key: 'submitted', label: 'Subscribers Submitted', format: 'number' },+ { key: 'accepted', label: 'Accepted for Processing', format: 'boolean' },+ ],+ },+ stringList: { fields: [{ key: 'items', label: 'Items' }] },+ stringPage: { fields: [{ key: 'items', label: 'Items' }, ...pageFields] },+ applyTag: {+ fields: [+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'tag', label: 'Tag' },+ { key: 'applied', label: 'Applied', format: 'boolean' },+ ],+ },+ removeTag: {+ fields: [+ { key: 'subscriberId', label: 'Subscriber ID' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'tag', label: 'Tag' },+ { key: 'wasApplied', label: 'Tag Was Applied', format: 'boolean' },+ { key: 'removed', label: 'Removed', format: 'boolean' },+ ],+ },+ campaign: { fields: campaignFields },+ campaignPage: { fields: [list({ fields: campaignFields, labelKey: 'name', label: 'Email Series' }), ...pageFields] },+ workflow: { fields: workflowFields },+ workflowPage: { fields: [list({ fields: workflowFields, labelKey: 'name', label: 'Workflows' }), ...pageFields] },+ broadcast: { fields: broadcastFields },+ broadcastPage: { fields: [list({ fields: broadcastFields, labelKey: 'name', label: 'Broadcasts' }), ...pageFields] },+ conversion: { fields: conversionFields },+ conversionPage: { fields: [list({ fields: conversionFields, labelKey: 'name', label: 'Conversions' }), ...pageFields] },+ form: { fields: formFields },+ formList: { fields: [list({ fields: formFields, labelKey: 'headline', label: 'Forms' })] },+ campaignSubscribe: {+ fields: [+ { key: 'campaignId', label: 'Campaign ID' },+ { key: 'subscriber', label: 'Subscriber', children: subscriberFields },+ ],+ },+ workflowStart: {+ fields: [+ { key: 'workflowId', label: 'Workflow ID' },+ { key: 'subscriber', label: 'Subscriber', children: subscriberFields },+ ],+ },+ workflowRemove: {+ fields: [+ { key: 'workflowId', label: 'Workflow ID' },+ { key: 'subscriber', label: 'Subscriber' },+ { key: 'removed', label: 'Removed', format: 'boolean' },+ ],+ },+ recordEvent: {+ fields: [+ { key: 'subscriber', label: 'Subscriber' },+ { key: 'action', label: 'Event Action' },+ { key: 'occurredAt', label: 'Occurred At', format: 'datetime' },+ { key: 'recorded', label: 'Recorded', format: 'boolean' },+ ],+ },+ recordOrder: {+ fields: [+ { key: 'requestId', label: 'Drip Request ID' },+ { key: 'orderId', label: 'Order ID' },+ { key: 'action', label: 'Order Action' },+ { key: 'accepted', label: 'Accepted', format: 'boolean' },+ ],+ },+ recordCart: {+ fields: [+ { key: 'requestId', label: 'Drip Request ID' },+ { key: 'cartId', label: 'Cart ID' },+ { key: 'action', label: 'Cart Action' },+ { key: 'accepted', label: 'Accepted', format: 'boolean' },+ ],+ },+ legacySubscribersResponse: {+ fields: [+ { key: 'status', label: 'HTTP Status', format: 'number' },+ { key: 'subscribers', label: 'Subscribers', value: 'body.subscribers', labelKey: 'email', listItems: subscriberFields },+ ],+ },+ legacyEmptyResponse: {+ fields: [{ key: 'status', label: 'HTTP Status', format: 'number', description: '201 when Drip accepted the tag.' }],+ },+ subscriberEvent: webhookEvent([]),+ tagEvent: webhookEvent([{ key: 'tag', label: 'Tag' }]),+ campaignEvent: webhookEvent([+ { key: 'campaign_id', label: 'Campaign ID' },+ { key: 'campaign_name', label: 'Campaign Name' },+ ]),+ customEvent: {+ fields: [+ ...webhookEvent([]).fields.filter((field) => field.key !== 'properties'),+ { key: 'action', label: 'Event Action', value: 'data.properties.action' },+ { key: 'properties', label: 'Event Properties', value: 'data.properties', dynamicKey: true },+ ],+ },+ clickEvent: webhookEvent([+ { key: 'url', label: 'Clicked URL', format: 'url' },+ { key: 'email_subject', label: 'Email Subject' },+ { key: 'email_id', label: 'Email ID' },+ { key: 'delivery_id', label: 'Delivery ID' },+ ]),+} satisfies Record<string, OutputSchema>;++function list({ fields, labelKey, label = 'Items' }: { fields: Fields; labelKey: string; label?: string }): Fields[number] {+ return { key: 'items', label, labelKey, listItems: fields };+}++function webhookEvent(properties: Fields): OutputSchema {+ return {+ fields: [+ { key: 'event', label: 'Event' },+ { key: 'occurred_at', label: 'Occurred At', format: 'datetime' },+ { key: 'account_id', label: 'Account ID', value: 'data.account_id' },+ { key: 'subscriber', label: 'Subscriber', value: 'data.subscriber', children: webhookSubscriberFields },+ { key: 'properties', label: 'Details', value: 'data.properties', children: [...properties, ...webhookCauseFields] },+ ],+ };+}diff --git a/packages/pieces/community/drip/src/lib/trigger/completed-campaign.trigger.ts b/packages/pieces/community/drip/src/lib/trigger/completed-campaign.trigger.tsnew file mode 100644index 00000000000..dd4fe9bd150--- /dev/null+++ b/packages/pieces/community/drip/src/lib/trigger/completed-campaign.trigger.ts@@ -0,0 +1,57 @@+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripCommon } from '../common';+import { dripSamples } from '../common/samples';+import { dripWebhook } from '../common/webhook';+import { dripOutputSchemas } from '../output-schemas';++const STORE_KEY = 'drip_completed_campaign_trigger';+const EVENT = 'subscriber.completed_campaign';++export const dripCompletedCampaignEvent = createTrigger({+ auth: dripAuth,+ name: 'completed_campaign',+ classification: 'READ',+ displayName: 'Completed Email Series',+ description: 'Triggers when a subscriber completes an Email Series Campaign.',+ aiMetadata: {+ description: 'Fires when a subscriber receives the last email of an Email Series Campaign in the selected Drip account (Drip event subscriber.completed_campaign), optionally only for one campaign; data.properties has campaign_id and campaign_name.',+ },+ props: {+ account_id: dripCommon.account_id,+ campaign_id: dripCommon.campaign_id({ required: false, description: 'Only trigger for this email series. Leave empty for all.' }),+ },+ sampleData: dripSamples.event({ name: EVENT, properties: { campaign_id: '123456', campaign_name: 'Welcome series' } }),+ outputSchema: dripOutputSchemas.campaignEvent,+ type: TriggerStrategy.WEBHOOK,+ async onEnable(context) {+ await dripWebhook.enable({+ token: context.auth.secret_text,+ accountId: context.propsValue.account_id,+ webhookUrl: context.webhookUrl,+ store: context.store,+ storeKey: STORE_KEY,+ event: EVENT,+ });+ },+ async onDisable(context) {+ await dripWebhook.disable({ token: context.auth.secret_text, store: context.store, storeKey: STORE_KEY });+ },+ async run(context) {+ return dripWebhook.handle({+ token: context.auth.secret_text,+ store: context.store,+ storeKey: STORE_KEY,+ event: EVENT,+ payload: context.payload,+ matches: (body) => campaignMatches({ expected: context.propsValue.campaign_id, body }),+ });+ },+});++function campaignMatches({ expected, body }: { expected: unknown; body: Record<string, unknown> }): boolean {+ if (expected === undefined || expected === null || String(expected).trim() === '') {+ return true;+ }+ return String(dripWebhook.propertiesOf(body)['campaign_id'] ?? '') === String(expected).trim();+}diff --git a/packages/pieces/community/drip/src/lib/trigger/custom-event-performed.trigger.ts b/packages/pieces/community/drip/src/lib/trigger/custom-event-performed.trigger.tsnew file mode 100644index 00000000000..b019dbfdfeb--- /dev/null+++ b/packages/pieces/community/drip/src/lib/trigger/custom-event-performed.trigger.ts@@ -0,0 +1,50 @@+import { Property, createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripCommon } from '../common';+import { dripSamples } from '../common/samples';+import { dripWebhook } from '../common/webhook';+import { dripOutputSchemas } from '../output-schemas';++const STORE_KEY = 'drip_custom_event_performed_trigger';+const EVENT = 'subscriber.performed_custom_event';++export const dripCustomEventPerformedEvent = createTrigger({+ auth: dripAuth,+ name: 'custom_event_performed',+ classification: 'READ',+ displayName: 'Custom Event Performed',+ description: 'Triggers when a custom event is recorded for a subscriber.',+ aiMetadata: {+ description: 'Fires when a custom event (such as "Logged in") is recorded for a subscriber in the selected Drip account (Drip event subscriber.performed_custom_event), optionally only for one event name; data.properties has the action and its properties.',+ },+ props: {+ account_id: dripCommon.account_id,+ action: Property.ShortText({ displayName: 'Event Action', description: 'Only trigger for this event name (not case-sensitive). Leave empty for every custom event.', required: false }),+ },+ sampleData: dripSamples.event({ name: EVENT, properties: { action: 'Logged in', plan: 'pro' } }),+ outputSchema: dripOutputSchemas.customEvent,+ type: TriggerStrategy.WEBHOOK,+ async onEnable(context) {+ await dripWebhook.enable({+ token: context.auth.secret_text,+ accountId: context.propsValue.account_id,+ webhookUrl: context.webhookUrl,+ store: context.store,+ storeKey: STORE_KEY,+ event: EVENT,+ });+ },+ async onDisable(context) {+ await dripWebhook.disable({ token: context.auth.secret_text, store: context.store, storeKey: STORE_KEY });+ },+ async run(context) {+ return dripWebhook.handle({+ token: context.auth.secret_text,+ store: context.store,+ storeKey: STORE_KEY,+ event: EVENT,+ payload: context.payload,+ matches: (body) => dripWebhook.textMatches({ expected: context.propsValue.action, actual: dripWebhook.propertiesOf(body)['action'] }),+ });+ },+});diff --git a/packages/pieces/community/drip/src/lib/trigger/email-clicked.trigger.ts b/packages/pieces/community/drip/src/lib/trigger/email-clicked.trigger.tsnew file mode 100644index 00000000000..7b41be94d2f--- /dev/null+++ b/packages/pieces/community/drip/src/lib/trigger/email-clicked.trigger.ts@@ -0,0 +1,42 @@+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripCommon } from '../common';+import { dripSamples } from '../common/samples';+import { dripWebhook } from '../common/webhook';+import { dripOutputSchemas } from '../output-schemas';++const STORE_KEY = 'drip_email_clicked_trigger';+const EVENT = 'subscriber.clicked_email';++export const dripEmailClickedEvent = createTrigger({+ auth: dripAuth,+ name: 'email_clicked',+ classification: 'READ',+ displayName: 'Email Link Clicked',+ description: 'Triggers when a subscriber clicks a link in a Drip email. Can be high volume.',+ aiMetadata: {+ description: 'Fires when a subscriber clicks a link in a Drip email in the selected account (Drip event subscriber.clicked_email); data.properties has the URL, email subject and email ID. Can fire often on large lists.',+ },+ props: {+ account_id: dripCommon.account_id,+ },+ sampleData: dripSamples.event({ name: EVENT, properties: { delivery_id: '99999', email_id: '88888', url: 'https://www.example.com', email_subject: 'Welcome to the course' } }),+ outputSchema: dripOutputSchemas.clickEvent,+ type: TriggerStrategy.WEBHOOK,+ async onEnable(context) {+ await dripWebhook.enable({+ token: context.auth.secret_text,+ accountId: context.propsValue.account_id,+ webhookUrl: context.webhookUrl,+ store: context.store,+ storeKey: STORE_KEY,+ event: EVENT,+ });+ },+ async onDisable(context) {+ await dripWebhook.disable({ token: context.auth.secret_text, store: context.store, storeKey: STORE_KEY });+ },+ async run(context) {+ return dripWebhook.handle({ token: context.auth.secret_text, store: context.store, storeKey: STORE_KEY, event: EVENT, payload: context.payload });+ },+});diff --git a/packages/pieces/community/drip/src/lib/trigger/new-subscriber.trigger.ts b/packages/pieces/community/drip/src/lib/trigger/new-subscriber.trigger.tsindex ab04c977dd9..5e2a3eb6ade 100644--- a/packages/pieces/community/drip/src/lib/trigger/new-subscriber.trigger.ts+++ b/packages/pieces/community/drip/src/lib/trigger/new-subscriber.trigger.ts@@ -1,13 +1,13 @@-import {- HttpRequest,- HttpMethod,- httpClient,-} from '@activepieces/pieces-common';-import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';-import { dripCommon } from '../common';+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';import { dripAuth } from '../auth';+import { dripCommon } from '../common';+import { dripSamples } from '../common/samples';+import { dripWebhook } from '../common/webhook';+import { dripOutputSchemas } from '../output-schemas';++const STORE_KEY = 'drip_new_subscriber_trigger';+const EVENT = 'subscriber.created';-const triggerNameInStore = 'drip_new_subscriber_trigger';export const dripNewSubscriberEvent = createTrigger({auth: dripAuth,name: 'new_subscriber',@@ -15,63 +15,28 @@ export const dripNewSubscriberEvent = createTrigger({displayName: 'New Subscriber',description: 'Triggers when a subscriber is created in your Drip account.',aiMetadata: {- description: 'Fires when a new subscriber is created in the selected Drip account, emitting the subscriber.created event. Represents a contact being added to the list.',+ description: 'Fires when a new subscriber is created in the selected Drip account (Drip event subscriber.created), with the subscriber profile. Represents a contact being added to the list.',},props: {account_id: dripCommon.account_id,},- sampleData: {- event: 'subscriber.created',- data: {- account_id: '9999999',- subscriber: {},- },- occurred_at: '2013-06-21T10:31:58Z',- },+ sampleData: dripSamples.event({ name: EVENT }),+ outputSchema: dripOutputSchemas.subscriberEvent,type: TriggerStrategy.WEBHOOK,- async onEnable({ auth, propsValue, webhookUrl, store }) {- const request: HttpRequest = {- method: HttpMethod.POST,- url: `${dripCommon.baseUrl(propsValue.account_id)}/webhooks`,- body: {- webhooks: [{ post_url: webhookUrl, events: ['subscriber.created'] }],- },- headers: {- Authorization: dripCommon.authorizationHeader(auth),- },- queryParams: {},- };- const { body } = await httpClient.sendRequest<{- webhooks: { id: string }[];- }>(request);- await store.put<DripWebhookInformation>(triggerNameInStore, {- webhookId: body.webhooks[0].id,- userId: propsValue.account_id,+ async onEnable(context) {+ await dripWebhook.enable({+ token: context.auth.secret_text,+ accountId: context.propsValue.account_id,+ webhookUrl: context.webhookUrl,+ store: context.store,+ storeKey: STORE_KEY,+ event: EVENT,});},async onDisable(context) {- const response = await context.store?.get<DripWebhookInformation>(- triggerNameInStore- );- if (response !== null && response !== undefined) {- const request: HttpRequest = {- method: HttpMethod.DELETE,- url: `${dripCommon.baseUrl(response.userId)}/webhooks/${- response.webhookId- }`,- headers: {- Authorization: dripCommon.authorizationHeader(context.auth),- },- };- await httpClient.sendRequest(request);- }+ await dripWebhook.disable({ token: context.auth.secret_text, store: context.store, storeKey: STORE_KEY });},async run(context) {- return [context.payload.body];+ return dripWebhook.handle({ token: context.auth.secret_text, store: context.store, storeKey: STORE_KEY, event: EVENT, payload: context.payload });},});--interface DripWebhookInformation {- webhookId: string;- userId: string;-}diff --git a/packages/pieces/community/drip/src/lib/trigger/new-tag.trigger.ts b/packages/pieces/community/drip/src/lib/trigger/new-tag.trigger.tsindex f0400c19779..e3c053331fd 100644--- a/packages/pieces/community/drip/src/lib/trigger/new-tag.trigger.ts+++ b/packages/pieces/community/drip/src/lib/trigger/new-tag.trigger.ts@@ -1,13 +1,13 @@-import {- HttpRequest,- HttpMethod,- httpClient,-} from '@activepieces/pieces-common';-import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';-import { dripCommon } from '../common';+import { Property, createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';import { dripAuth } from '../auth';+import { dripCommon } from '../common';+import { dripSamples } from '../common/samples';+import { dripWebhook } from '../common/webhook';+import { dripOutputSchemas } from '../output-schemas';++const STORE_KEY = 'drip_tag_applied_to_subscriber_trigger';+const EVENT = 'subscriber.applied_tag';-const triggerNameInStore = 'drip_tag_applied_to_subscriber_trigger';export const dripTagAppliedEvent = createTrigger({auth: dripAuth,name: 'tag_applied_to_subscribers',@@ -15,68 +15,36 @@ export const dripTagAppliedEvent = createTrigger({displayName: 'Tag Applied',description: 'Triggers when a tag is applied.',aiMetadata: {- description: 'Fires when a tag is applied to a subscriber in the selected Drip account, emitting the subscriber.applied_tag event. Represents a contact being labeled or segmented; the payload includes the applied tag.',+ description: 'Fires when a tag is applied to a subscriber in the selected Drip account (Drip event subscriber.applied_tag), optionally only for one tag; the payload has the subscriber and the tag in data.properties.tag.',},props: {account_id: dripCommon.account_id,+ tag: Property.ShortText({ displayName: 'Tag', description: 'Only trigger for this tag (not case-sensitive). Leave empty for every tag.', required: false }),},- sampleData: {- event: 'subscriber.applied_tag',- data: {- account_id: '9999999',- subscriber: {},- properties: {- tag: 'Customer',- },- },- occurred_at: '2013-06-21T10:31:58Z',- },+ sampleData: dripSamples.event({ name: EVENT, properties: { tag: 'Customer' } }),+ outputSchema: dripOutputSchemas.tagEvent,type: TriggerStrategy.WEBHOOK,async onEnable(context) {- const request: HttpRequest = {- method: HttpMethod.POST,- url: `${dripCommon.baseUrl(context.propsValue.account_id)}/webhooks`,- body: {- webhooks: [- { post_url: context.webhookUrl, events: ['subscriber.applied_tag'] },- ],- },- headers: {- Authorization: dripCommon.authorizationHeader(context.auth),- },- queryParams: {},- };- const { body } = await httpClient.sendRequest<{- webhooks: { id: string }[];- }>(request);- await context.store?.put<DripWebhookInformation>(triggerNameInStore, {- webhookId: body.webhooks[0].id,- userId: context.propsValue['account_id']!,+ await dripWebhook.enable({+ token: context.auth.secret_text,+ accountId: context.propsValue.account_id,+ webhookUrl: context.webhookUrl,+ store: context.store,+ storeKey: STORE_KEY,+ event: EVENT,});},async onDisable(context) {- const response = await context.store?.get<DripWebhookInformation>(- triggerNameInStore- );- if (response !== null && response !== undefined) {- const request: HttpRequest<never> = {- method: HttpMethod.DELETE,- url: `${dripCommon.baseUrl(response.userId)}/webhooks/${- response.webhookId- }`,- headers: {- Authorization: dripCommon.authorizationHeader(context.auth),- },- };- await httpClient.sendRequest(request);- }+ await dripWebhook.disable({ token: context.auth.secret_text, store: context.store, storeKey: STORE_KEY });},async run(context) {- return [context.payload.body];+ return dripWebhook.handle({+ token: context.auth.secret_text,+ store: context.store,+ storeKey: STORE_KEY,+ event: EVENT,+ payload: context.payload,+ matches: (body) => dripWebhook.textMatches({ expected: context.propsValue.tag, actual: dripWebhook.propertiesOf(body)['tag'] }),+ });},});--interface DripWebhookInformation {- webhookId: string;- userId: string;-}diff --git a/packages/pieces/community/drip/src/lib/trigger/removed-from-campaign.trigger.ts b/packages/pieces/community/drip/src/lib/trigger/removed-from-campaign.trigger.tsnew file mode 100644index 00000000000..012122003f2--- /dev/null+++ b/packages/pieces/community/drip/src/lib/trigger/removed-from-campaign.trigger.ts@@ -0,0 +1,57 @@+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripCommon } from '../common';+import { dripSamples } from '../common/samples';+import { dripWebhook } from '../common/webhook';+import { dripOutputSchemas } from '../output-schemas';++const STORE_KEY = 'drip_removed_from_campaign_trigger';+const EVENT = 'subscriber.removed_from_campaign';++export const dripRemovedFromCampaignEvent = createTrigger({+ auth: dripAuth,+ name: 'removed_from_campaign',+ classification: 'READ',+ displayName: 'Removed From Email Series',+ description: 'Triggers when a subscriber is removed from an Email Series Campaign.',+ aiMetadata: {+ description: 'Fires when a subscriber is removed from an Email Series Campaign in the selected Drip account (Drip event subscriber.removed_from_campaign), optionally only for one campaign; data.properties has campaign_id and campaign_name.',+ },+ props: {+ account_id: dripCommon.account_id,+ campaign_id: dripCommon.campaign_id({ required: false, description: 'Only trigger for this email series. Leave empty for all.' }),+ },+ sampleData: dripSamples.event({ name: EVENT, properties: { campaign_id: '123456', campaign_name: 'Welcome series' } }),+ outputSchema: dripOutputSchemas.campaignEvent,+ type: TriggerStrategy.WEBHOOK,+ async onEnable(context) {+ await dripWebhook.enable({+ token: context.auth.secret_text,+ accountId: context.propsValue.account_id,+ webhookUrl: context.webhookUrl,+ store: context.store,+ storeKey: STORE_KEY,+ event: EVENT,+ });+ },+ async onDisable(context) {+ await dripWebhook.disable({ token: context.auth.secret_text, store: context.store, storeKey: STORE_KEY });+ },+ async run(context) {+ return dripWebhook.handle({+ token: context.auth.secret_text,+ store: context.store,+ storeKey: STORE_KEY,+ event: EVENT,+ payload: context.payload,+ matches: (body) => campaignMatches({ expected: context.propsValue.campaign_id, body }),+ });+ },+});++function campaignMatches({ expected, body }: { expected: unknown; body: Record<string, unknown> }): boolean {+ if (expected === undefined || expected === null || String(expected).trim() === '') {+ return true;+ }+ return String(dripWebhook.propertiesOf(body)['campaign_id'] ?? '') === String(expected).trim();+}diff --git a/packages/pieces/community/drip/src/lib/trigger/subscribed-to-campaign.trigger.ts b/packages/pieces/community/drip/src/lib/trigger/subscribed-to-campaign.trigger.tsnew file mode 100644index 00000000000..3c9548ffcc8--- /dev/null+++ b/packages/pieces/community/drip/src/lib/trigger/subscribed-to-campaign.trigger.ts@@ -0,0 +1,57 @@+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripCommon } from '../common';+import { dripSamples } from '../common/samples';+import { dripWebhook } from '../common/webhook';+import { dripOutputSchemas } from '../output-schemas';++const STORE_KEY = 'drip_subscribed_to_campaign_trigger';+const EVENT = 'subscriber.subscribed_to_campaign';++export const dripSubscribedToCampaignEvent = createTrigger({+ auth: dripAuth,+ name: 'subscribed_to_campaign',+ classification: 'READ',+ displayName: 'Subscribed to Email Series',+ description: 'Triggers when a subscriber subscribes to an Email Series Campaign.',+ aiMetadata: {+ description: 'Fires when a subscriber is subscribed to an Email Series Campaign in the selected Drip account (Drip event subscriber.subscribed_to_campaign), optionally only for one campaign; data.properties has campaign_id and campaign_name.',+ },+ props: {+ account_id: dripCommon.account_id,+ campaign_id: dripCommon.campaign_id({ required: false, description: 'Only trigger for this email series. Leave empty for all.' }),+ },+ sampleData: dripSamples.event({ name: EVENT, properties: { campaign_id: '123456', campaign_name: 'Welcome series' } }),+ outputSchema: dripOutputSchemas.campaignEvent,+ type: TriggerStrategy.WEBHOOK,+ async onEnable(context) {+ await dripWebhook.enable({+ token: context.auth.secret_text,+ accountId: context.propsValue.account_id,+ webhookUrl: context.webhookUrl,+ store: context.store,+ storeKey: STORE_KEY,+ event: EVENT,+ });+ },+ async onDisable(context) {+ await dripWebhook.disable({ token: context.auth.secret_text, store: context.store, storeKey: STORE_KEY });+ },+ async run(context) {+ return dripWebhook.handle({+ token: context.auth.secret_text,+ store: context.store,+ storeKey: STORE_KEY,+ event: EVENT,+ payload: context.payload,+ matches: (body) => campaignMatches({ expected: context.propsValue.campaign_id, body }),+ });+ },+});++function campaignMatches({ expected, body }: { expected: unknown; body: Record<string, unknown> }): boolean {+ if (expected === undefined || expected === null || String(expected).trim() === '') {+ return true;+ }+ return String(dripWebhook.propertiesOf(body)['campaign_id'] ?? '') === String(expected).trim();+}diff --git a/packages/pieces/community/drip/src/lib/trigger/subscriber-deleted.trigger.ts b/packages/pieces/community/drip/src/lib/trigger/subscriber-deleted.trigger.tsnew file mode 100644index 00000000000..9e21b47fe21--- /dev/null+++ b/packages/pieces/community/drip/src/lib/trigger/subscriber-deleted.trigger.ts@@ -0,0 +1,42 @@+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripCommon } from '../common';+import { dripSamples } from '../common/samples';+import { dripWebhook } from '../common/webhook';+import { dripOutputSchemas } from '../output-schemas';++const STORE_KEY = 'drip_subscriber_deleted_trigger';+const EVENT = 'subscriber.deleted';++export const dripSubscriberDeletedEvent = createTrigger({+ auth: dripAuth,+ name: 'subscriber_deleted',+ classification: 'READ',+ displayName: 'Subscriber Deleted',+ description: 'Triggers when a subscriber is deleted from your Drip account.',+ aiMetadata: {+ description: 'Fires when a subscriber is deleted from the selected Drip account (Drip event subscriber.deleted), with the last known subscriber profile.',+ },+ props: {+ account_id: dripCommon.account_id,+ },+ sampleData: dripSamples.event({ name: EVENT }),+ outputSchema: dripOutputSchemas.subscriberEvent,+ type: TriggerStrategy.WEBHOOK,+ async onEnable(context) {+ await dripWebhook.enable({+ token: context.auth.secret_text,+ accountId: context.propsValue.account_id,+ webhookUrl: context.webhookUrl,+ store: context.store,+ storeKey: STORE_KEY,+ event: EVENT,+ });+ },+ async onDisable(context) {+ await dripWebhook.disable({ token: context.auth.secret_text, store: context.store, storeKey: STORE_KEY });+ },+ async run(context) {+ return dripWebhook.handle({ token: context.auth.secret_text, store: context.store, storeKey: STORE_KEY, event: EVENT, payload: context.payload });+ },+});diff --git a/packages/pieces/community/drip/src/lib/trigger/subscriber-unsubscribed.trigger.ts b/packages/pieces/community/drip/src/lib/trigger/subscriber-unsubscribed.trigger.tsnew file mode 100644index 00000000000..270fdc6e690--- /dev/null+++ b/packages/pieces/community/drip/src/lib/trigger/subscriber-unsubscribed.trigger.ts@@ -0,0 +1,42 @@+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripCommon } from '../common';+import { dripSamples } from '../common/samples';+import { dripWebhook } from '../common/webhook';+import { dripOutputSchemas } from '../output-schemas';++const STORE_KEY = 'drip_subscriber_unsubscribed_trigger';+const EVENT = 'subscriber.unsubscribed_all';++export const dripSubscriberUnsubscribedEvent = createTrigger({+ auth: dripAuth,+ name: 'subscriber_unsubscribed',+ classification: 'READ',+ displayName: 'Subscriber Unsubscribed From All',+ description: 'Triggers when a subscriber unsubscribes from all mailings.',+ aiMetadata: {+ description: 'Fires when a subscriber in the selected Drip account is unsubscribed from all mailings (Drip event subscriber.unsubscribed_all), with the subscriber profile. Represents a contact opting out.',+ },+ props: {+ account_id: dripCommon.account_id,+ },+ sampleData: dripSamples.event({ name: EVENT, properties: {} }),+ outputSchema: dripOutputSchemas.subscriberEvent,+ type: TriggerStrategy.WEBHOOK,+ async onEnable(context) {+ await dripWebhook.enable({+ token: context.auth.secret_text,+ accountId: context.propsValue.account_id,+ webhookUrl: context.webhookUrl,+ store: context.store,+ storeKey: STORE_KEY,+ event: EVENT,+ });+ },+ async onDisable(context) {+ await dripWebhook.disable({ token: context.auth.secret_text, store: context.store, storeKey: STORE_KEY });+ },+ async run(context) {+ return dripWebhook.handle({ token: context.auth.secret_text, store: context.store, storeKey: STORE_KEY, event: EVENT, payload: context.payload });+ },+});diff --git a/packages/pieces/community/drip/src/lib/trigger/tag-removed.trigger.ts b/packages/pieces/community/drip/src/lib/trigger/tag-removed.trigger.tsnew file mode 100644index 00000000000..8112d8778ee--- /dev/null+++ b/packages/pieces/community/drip/src/lib/trigger/tag-removed.trigger.ts@@ -0,0 +1,50 @@+import { Property, createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';+import { dripAuth } from '../auth';+import { dripCommon } from '../common';+import { dripSamples } from '../common/samples';+import { dripWebhook } from '../common/webhook';+import { dripOutputSchemas } from '../output-schemas';++const STORE_KEY = 'drip_tag_removed_trigger';+const EVENT = 'subscriber.removed_tag';++export const dripTagRemovedEvent = createTrigger({+ auth: dripAuth,+ name: 'tag_removed',+ classification: 'READ',+ displayName: 'Tag Removed',+ description: 'Triggers when a tag is removed from a subscriber.',+ aiMetadata: {+ description: 'Fires when a tag is removed from a subscriber in the selected Drip account (Drip event subscriber.removed_tag), optionally only for one tag; the payload has the subscriber and the tag in data.properties.tag.',+ },+ props: {+ account_id: dripCommon.account_id,+ tag: Property.ShortText({ displayName: 'Tag', description: 'Only trigger for this tag (not case-sensitive). Leave empty for every tag.', required: false }),+ },+ sampleData: dripSamples.event({ name: EVENT, properties: { tag: 'Customer' } }),+ outputSchema: dripOutputSchemas.tagEvent,+ type: TriggerStrategy.WEBHOOK,+ async onEnable(context) {+ await dripWebhook.enable({+ token: context.auth.secret_text,+ accountId: context.propsValue.account_id,+ webhookUrl: context.webhookUrl,+ store: context.store,+ storeKey: STORE_KEY,+ event: EVENT,+ });+ },+ async onDisable(context) {+ await dripWebhook.disable({ token: context.auth.secret_text, store: context.store, storeKey: STORE_KEY });+ },+ async run(context) {+ return dripWebhook.handle({+ token: context.auth.secret_text,+ store: context.store,+ storeKey: STORE_KEY,+ event: EVENT,+ payload: context.payload,+ matches: (body) => dripWebhook.textMatches({ expected: context.propsValue.tag, actual: dripWebhook.propertiesOf(body)['tag'] }),+ });+ },+});diff --git a/packages/pieces/community/drip/test/activity.test.ts b/packages/pieces/community/drip/test/activity.test.tsnew file mode 100644index 00000000000..4119dceffd4--- /dev/null+++ b/packages/pieces/community/drip/test/activity.test.ts@@ -0,0 +1,93 @@+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { recordCartAction } from '../src/lib/actions/record-cart.action';+import { recordEventAction } from '../src/lib/actions/record-event.action';+import { recordOrderAction } from '../src/lib/actions/record-order.action';+import { run, stubFetch } from './helpers';++const A = '4617837';+const EMAIL = '[email protected]';++beforeEach(() => {+ vi.useFakeTimers();+});++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++describe('record_event', () => {+ test('posts one event with normalised time', async () => {+ const seen = stubFetch(() => ({ status: 204 }));+ const result = await run(recordEventAction)({ accountId: A, subscriber: EMAIL, action: 'Logged in', properties: { plan: 'pro' }, occurredAt: '2026-10-06T10:00:00.000Z' });+ expect(seen[0].path).toBe(`/${A}/events`);+ expect(seen[0].body).toEqual({ events: [{ email: EMAIL, action: 'Logged in', properties: { plan: 'pro' }, occurred_at: '2026-10-06T10:00:00Z' }] });+ expect(result).toEqual({ subscriber: EMAIL, action: 'Logged in', occurredAt: '2026-10-06T10:00:00Z', recorded: true });+ });+ test('uses id for non-email subscribers and validates the action length', async () => {+ const seen = stubFetch(() => ({ status: 204 }));+ await run(recordEventAction)({ accountId: A, subscriber: 'z1tog', action: 'x' });+ expect(seen[0].body).toEqual({ events: [{ id: 'z1tog', action: 'x' }] });+ await expect(run(recordEventAction)({ accountId: A, subscriber: 'z1tog', action: 'x'.repeat(256) })).rejects.toThrow('255');+ });+});++describe('shopper activity', () => {+ test('record_order posts to v3 with only the given fields', async () => {+ const seen = stubFetch(() => ({ status: 202, body: { request_id: 'req-1' } }));+ const result = await run(recordOrderAction)({+ accountId: A,+ action: 'placed',+ orderId: 'aptest-1',+ email: EMAIL,+ provider: 'activepieces_test',+ initialStatus: 'unsubscribed',+ grandTotal: '10.5',+ currency: 'usd',+ items: [{ name: 'Bottle', price: 5.25, quantity: 2 }],+ });+ expect(seen[0].url).toBe(`https://api.getdrip.com/v3/${A}/shopper_activity/order`);+ expect(seen[0].body).toEqual({+ email: EMAIL,+ provider: 'activepieces_test',+ action: 'placed',+ order_id: 'aptest-1',+ initial_status: 'unsubscribed',+ grand_total: 10.5,+ currency: 'USD',+ items: [{ name: 'Bottle', price: 5.25, quantity: 2 }],+ });+ expect(result).toEqual({ requestId: 'req-1', orderId: 'aptest-1', action: 'placed', accepted: true });+ });+ test('record_order validates person, provider, currency, amounts and items before the request', async () => {+ const seen = stubFetch(() => ({ status: 202, body: {} }));+ const base = { accountId: A, action: 'placed', orderId: 'o', email: EMAIL, provider: 'p' };+ await expect(run(recordOrderAction)({ ...base, email: undefined })).rejects.toThrow('Customer Email or Drip Person ID');+ await expect(run(recordOrderAction)({ ...base, provider: 'My Store' })).rejects.toThrow('snake_case');+ await expect(run(recordOrderAction)({ ...base, currency: 'dollars' })).rejects.toThrow('ISO 4217');+ await expect(run(recordOrderAction)({ ...base, grandTotal: -1 })).rejects.toThrow('Grand Total');+ await expect(run(recordOrderAction)({ ...base, items: [{ price: 1 }] })).rejects.toThrow('missing name');+ await expect(run(recordOrderAction)({ ...base, items: [{ name: 'x', price: 'abc' }] })).rejects.toThrow('price must be a number');+ expect(seen).toHaveLength(0);+ });+ test('person ID wins over email', async () => {+ const seen = stubFetch(() => ({ status: 202, body: { request_id: 'r' } }));+ await run(recordOrderAction)({ accountId: A, action: 'paid', orderId: 'o', email: EMAIL, personId: 'p1', provider: 'p' });+ expect(seen[0].body).toMatchObject({ person_id: 'p1' });+ expect(seen[0].body).not.toHaveProperty('email');+ });+ test('record_cart requires the cart url and full item fields', async () => {+ const seen = stubFetch(() => ({ status: 202, body: { request_ids: ['r2'] } }));+ const item = { product_id: 'B1', product_variant_id: 'B1', name: 'Bottle', price: 1 };+ await expect(run(recordCartAction)({ accountId: A, action: 'created', cartId: 'c1', cartUrl: 'https://s.example/cart/c1', email: EMAIL, provider: 'p', items: [item] })).resolves.toEqual({+ requestId: 'r2',+ cartId: 'c1',+ action: 'created',+ accepted: true,+ });+ expect(seen[0].url).toBe(`https://api.getdrip.com/v3/${A}/shopper_activity/cart`);+ expect(seen[0].body).toEqual({ email: EMAIL, provider: 'p', action: 'created', cart_id: 'c1', cart_url: 'https://s.example/cart/c1', items: [item] });+ await expect(run(recordCartAction)({ accountId: A, action: 'created', cartId: 'c1', email: EMAIL, provider: 'p' })).rejects.toThrow('Cart URL');+ await expect(run(recordCartAction)({ accountId: A, action: 'created', cartId: 'c1', cartUrl: 'u', email: EMAIL, provider: 'p', items: [{ name: 'x' }] })).rejects.toThrow('product_id');+ });+});diff --git a/packages/pieces/community/drip/test/catalog.test.ts b/packages/pieces/community/drip/test/catalog.test.tsnew file mode 100644index 00000000000..54c1e3959dc--- /dev/null+++ b/packages/pieces/community/drip/test/catalog.test.ts@@ -0,0 +1,138 @@+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { applyTagAction } from '../src/lib/actions/ai/apply-tag.action';+import { subscribeToCampaignAction } from '../src/lib/actions/ai/subscribe-to-campaign.action';+import { getBroadcastAction } from '../src/lib/actions/get-broadcast.action';+import { getCampaignAction } from '../src/lib/actions/get-campaign.action';+import { getConversionAction } from '../src/lib/actions/get-conversion.action';+import { getCurrentUserAction } from '../src/lib/actions/get-current-user.action';+import { getFormAction } from '../src/lib/actions/get-form.action';+import { getWorkflowAction } from '../src/lib/actions/get-workflow.action';+import { listAccountsAction } from '../src/lib/actions/list-accounts.action';+import { listBroadcastsAction } from '../src/lib/actions/list-broadcasts.action';+import { listCampaignSubscribersAction } from '../src/lib/actions/list-campaign-subscribers.action';+import { listCampaignsAction } from '../src/lib/actions/list-campaigns.action';+import { listConversionsAction } from '../src/lib/actions/list-conversions.action';+import { listCustomFieldsAction } from '../src/lib/actions/list-custom-fields.action';+import { listEventActionsAction } from '../src/lib/actions/list-event-actions.action';+import { listFormsAction } from '../src/lib/actions/list-forms.action';+import { listTagsAction } from '../src/lib/actions/list-tags.action';+import { listWorkflowsAction } from '../src/lib/actions/list-workflows.action';+import { removeFromWorkflowAction } from '../src/lib/actions/remove-from-workflow.action';+import { removeTagAction } from '../src/lib/actions/remove-tag.action';+import { startWorkflowAction } from '../src/lib/actions/start-workflow.action';+import { run, stubFetch } from './helpers';++const A = '4617837';+const SUB = { id: 'z1tog', email: '[email protected]', tags: ['Customer'] };++beforeEach(() => {+ vi.useFakeTimers();+});++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++describe('account-level reads', () => {+ test('list accounts and current user', async () => {+ stubFetch((request) => (request.path === '/accounts' ? { body: { accounts: [{ id: A, name: 'a' }] } } : { body: { users: [{ email: '[email protected]', name: 'O', time_zone: 'Etc/UTC' }] } }));+ await expect(run(listAccountsAction)({})).resolves.toEqual({ items: [{ id: A, name: 'a' }] });+ await expect(run(getCurrentUserAction)({})).resolves.toEqual({ email: '[email protected]', name: 'O', time_zone: 'Etc/UTC' });+ });+ test('tags, custom fields, forms and event names', async () => {+ stubFetch((request) => {+ if (request.path.endsWith('/tags')) return { body: { tags: ['a', 'b'] } };+ if (request.path.endsWith('/custom_field_identifiers')) return { body: { custom_field_identifiers: ['shirt_size'] } };+ if (request.path.endsWith('/forms')) return { body: { forms: [{ id: '7', headline: 'H' }] } };+ return { body: { event_actions: ['Logged in'], meta: { total_pages: 2, total_count: 2 } } };+ });+ await expect(run(listTagsAction)({ accountId: A })).resolves.toEqual({ items: ['a', 'b'] });+ await expect(run(listCustomFieldsAction)({ accountId: A })).resolves.toEqual({ items: ['shirt_size'] });+ await expect(run(listFormsAction)({ accountId: A })).resolves.toEqual({ items: [{ id: '7', headline: 'H' }] });+ await expect(run(listEventActionsAction)({ accountId: A, perPage: 1 })).resolves.toEqual({ items: ['Logged in'], page: 1, totalPages: 2, totalCount: 2, hasMore: true });+ });+ test.each([+ [listCampaignsAction, 'campaigns', 'campaigns'],+ [listWorkflowsAction, 'workflows', 'workflows'],+ [listBroadcastsAction, 'broadcasts', 'broadcasts'],+ [listConversionsAction, 'goals', 'goals'],+ ])('%#: list pages pass status, page and per_page', async (action, resource, key) => {+ const seen = stubFetch(() => ({ body: { [key]: [{ id: '1', name: 'n' }], meta: { page: 1 } } }));+ const result = await run(action)({ accountId: A, status: 'all', perPage: 1 });+ expect(seen[0].path).toBe(`/${A}/${resource}`);+ expect(Object.fromEntries(seen[0].query)).toEqual({ status: 'all', page: '1', per_page: '1' });+ expect(result).toEqual({ items: [{ id: '1', name: 'n' }], page: 1, totalPages: null, totalCount: null, hasMore: true });+ });+ test('broadcasts allow at most 100 per page', async () => {+ stubFetch(() => ({ body: {} }));+ await expect(run(listBroadcastsAction)({ accountId: A, perPage: 101 })).rejects.toThrow('between 1 and 100');+ });+ test.each([+ [getCampaignAction, 'campaigns'],+ [getWorkflowAction, 'workflows'],+ [getBroadcastAction, 'broadcasts'],+ [getConversionAction, 'goals'],+ [getFormAction, 'forms'],+ ])('%#: get by numeric ID unwraps the single record', async (action, key) => {+ const seen = stubFetch(() => ({ body: { [key]: [{ id: '55', name: 'x' }] } }));+ await expect(run(action)({ accountId: A, id: ' 55 ' })).resolves.toEqual({ id: '55', name: 'x' });+ expect(seen[0].path).toBe(`/${A}/${key}/55`);+ await expect(run(action)({ accountId: A, id: '../55' })).rejects.toThrow('digits only');+ });+ test('campaign subscribers filter by subscription status', async () => {+ const seen = stubFetch(() => ({ body: { subscribers: [SUB], meta: { total_pages: 1, total_count: 1 } } }));+ await run(listCampaignSubscribersAction)({ accountId: A, campaignId: '9', status: 'removed' });+ expect(seen[0].path).toBe(`/${A}/campaigns/9/subscribers`);+ expect(seen[0].query.get('status')).toBe('removed');+ });+});++describe('tags', () => {+ test('apply_tag posts one email/tag pair', async () => {+ const seen = stubFetch(() => ({ status: 201, body: {} }));+ await expect(run(applyTagAction)({ accountId: A, email: SUB.email, tag: ' VIP ' })).resolves.toEqual({ email: SUB.email, tag: 'VIP', applied: true });+ expect(seen[0].body).toEqual({ tags: [{ email: SUB.email, tag: 'VIP' }] });+ });+ test('remove_tag looks the subscriber up, deletes the encoded tag and reports wasApplied', async () => {+ const seen = stubFetch((request) => (request.method === 'GET' ? { body: { subscribers: [SUB] } } : { status: 204 }));+ await expect(run(removeTagAction)({ accountId: A, subscriber: SUB.email, tag: 'customer' })).resolves.toEqual({ subscriberId: 'z1tog', email: SUB.email, tag: 'customer', wasApplied: true, removed: true });+ expect(seen[1].method).toBe('DELETE');+ expect(seen[1].path).toBe(`/${A}/subscribers/odai%2Baptest-1%40activepieces.com/tags/customer`);+ await run(removeTagAction)({ accountId: A, subscriber: SUB.email, tag: 'Big / Spender' });+ expect(seen[3].url).toContain('/tags/Big%20%2F%20Spender');+ });+ test('remove_tag fails when there is no such subscriber (Drip would silently 204)', async () => {+ const seen = stubFetch(() => ({ status: 404, body: { errors: [{ code: 'not_found_error', message: 'not found' }] } }));+ await expect(run(removeTagAction)({ accountId: A, subscriber: '[email protected]', tag: 'a' })).rejects.toThrow('404');+ expect(seen).toHaveLength(1);+ });+});++describe('email series and workflows', () => {+ test('subscribe_to_campaign skips double opt-in by default', async () => {+ const seen = stubFetch(() => ({ body: { subscribers: [SUB] } }));+ await expect(run(subscribeToCampaignAction)({ accountId: A, campaignId: '9', email: SUB.email, reactivateIfRemoved: true })).resolves.toEqual({ campaignId: '9', subscriber: SUB });+ expect(seen[0].path).toBe(`/${A}/campaigns/9/subscribers`);+ expect(seen[0].body).toEqual({ subscribers: [{ email: SUB.email, double_optin: false, reactivate_if_removed: true }] });+ });+ test('subscribe_to_campaign passes options and validates the index', async () => {+ const seen = stubFetch(() => ({ body: { subscribers: [SUB] } }));+ await run(subscribeToCampaignAction)({ accountId: A, campaignId: '9', email: SUB.email, doubleOptin: true, startingEmailIndex: 2, tags: ['t'], customFields: { a: 1 }, timeZone: 'Asia/Amman' });+ expect(seen[0].body).toEqual({ subscribers: [{ email: SUB.email, double_optin: true, starting_email_index: 2, tags: ['t'], custom_fields: { a: 1 }, time_zone: 'Asia/Amman' }] });+ await expect(run(subscribeToCampaignAction)({ accountId: A, campaignId: '9', email: SUB.email, startingEmailIndex: -1 })).rejects.toThrow('Starting Email Index');+ });+ test('start_workflow sends the subscriber record; remove_from_workflow DELETEs', async () => {+ const seen = stubFetch((request) => (request.method === 'POST' ? { body: { subscribers: [SUB] } } : { status: 204 }));+ await expect(run(startWorkflowAction)({ accountId: A, workflowId: '77', subscriber: SUB.email, firstName: 'O', tags: ['x'] })).resolves.toEqual({ workflowId: '77', subscriber: SUB });+ expect(seen[0].path).toBe(`/${A}/workflows/77/subscribers`);+ expect(seen[0].body).toEqual({ subscribers: [{ email: SUB.email, first_name: 'O', tags: ['x'] }] });+ await expect(run(removeFromWorkflowAction)({ accountId: A, workflowId: '77', subscriber: SUB.email })).resolves.toEqual({ workflowId: '77', subscriber: SUB.email, removed: true });+ expect(seen[1].method).toBe('DELETE');+ expect(seen[1].path).toBe(`/${A}/workflows/77/subscribers/odai%2Baptest-1%40activepieces.com`);+ });+ test('start_workflow returns subscriber null when Drip returns none', async () => {+ stubFetch(() => ({ body: { subscribers: [] } }));+ await expect(run(startWorkflowAction)({ accountId: A, workflowId: '77', subscriber: SUB.email })).resolves.toEqual({ workflowId: '77', subscriber: null });+ });+});diff --git a/packages/pieces/community/drip/test/client.test.ts b/packages/pieces/community/drip/test/client.test.tsnew file mode 100644index 00000000000..bdefe4252a8--- /dev/null+++ b/packages/pieces/community/drip/test/client.test.ts@@ -0,0 +1,120 @@+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { HttpMethod } from '@activepieces/pieces-common';+import { DripApiError, dripApi } from '../src/lib/common/client';+import { replies, runStep, stubFetch, TOKEN } from './helpers';++const ACCOUNT = '4617837';++beforeEach(() => {+ vi.useFakeTimers();+});++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++describe('request', () => {+ test('sends Basic auth with the trimmed token, a User-Agent, JSON body and a fixed Drip origin', async () => {+ const seen = stubFetch(() => ({ body: { ok: 1 } }));+ await runStep(dripApi.request({ token: ` ${TOKEN} `, method: HttpMethod.POST, path: '/1/tags', operation: 'x', body: { a: 1 } }));+ expect(seen[0].url).toBe('https://api.getdrip.com/v2/1/tags');+ expect(seen[0].auth).toBe(`Basic ${Buffer.from(TOKEN).toString('base64')}`);+ expect(seen[0].userAgent).toBe('Activepieces (www.activepieces.com)');+ expect(seen[0].headers.get('content-type')).toContain('application/json');+ expect(seen[0].body).toEqual({ a: 1 });+ });+ test('v3 requests use the same host', async () => {+ const seen = stubFetch(() => ({ status: 202, body: { request_id: 'r' } }));+ await runStep(dripApi.request({ token: TOKEN, method: HttpMethod.POST, version: 'v3', path: '/1/shopper_activity/order', operation: 'x', body: {} }));+ expect(seen[0].url).toBe('https://api.getdrip.com/v3/1/shopper_activity/order');+ });+ test('refuses paths that do not start with a slash, so a lookalike host can never be built', async () => {+ const seen = stubFetch(() => ({ body: {} }));+ await expect(runStep(dripApi.request({ token: TOKEN, method: HttpMethod.GET, path: '.evil.io/x', operation: 'x' }))).rejects.toThrow('must start with');+ expect(seen).toHaveLength(0);+ });+ test('wraps errors in DripApiError with responseBody (never body) and the Drip message', async () => {+ stubFetch(() => ({ status: 422, body: { errors: [{ code: 'presence_error', attribute: 'email', message: 'Email is required' }] } }));+ const error = await runStep(dripApi.request({ token: TOKEN, method: HttpMethod.POST, path: '/1/subscribers', operation: 'create subscriber' })).catch((e: unknown) => e);+ expect(error).toBeInstanceOf(DripApiError);+ expect(String(Reflect.get(Object(error), 'message'))).toContain('Drip create subscriber failed (422 presence_error)');+ expect(String(Reflect.get(Object(error), 'message'))).toContain('email: Email is required');+ expect(Reflect.get(Object(error), 'responseBody')).toEqual({ errors: [{ code: 'presence_error', attribute: 'email', message: 'Email is required' }] });+ expect(Object.keys(Object(error))).not.toContain('body');+ });+ test('explains the disabled-account 403', async () => {+ stubFetch(() => ({ status: 403, body: { errors: [{ code: 'authorization_error', message: 'Your account is disabled.' }] } }));+ await expect(runStep(dripApi.request({ token: TOKEN, method: HttpMethod.GET, path: '/1/tags', operation: 'list tags' }))).rejects.toThrow('account is disabled');+ });+ test('retries 429 twice with bounded waits, then fails', async () => {+ const waits: number[] = [];+ const seen = stubFetch(() => ({ status: 429, body: { message: 'API rate limit exceeded.' } }));+ const wait = async (ms: number) => {+ waits.push(ms);+ };+ await expect(runStep(dripApi.request({ token: TOKEN, method: HttpMethod.GET, path: '/1/tags', operation: 'list tags', wait }))).rejects.toThrow('rate limit');+ expect(seen).toHaveLength(3);+ expect(waits).toEqual([10_000, 15_000]);+ });+ test('a 429 followed by success returns the body', async () => {+ const seen = stubFetch(replies([{ status: 429, body: {} }, { body: { tags: ['a'] } }]));+ await expect(runStep(dripApi.request({ token: TOKEN, method: HttpMethod.GET, path: '/1/tags', operation: 'x' }))).resolves.toEqual({ tags: ['a'] });+ expect(seen).toHaveLength(2);+ });+});++describe('inputs', () => {+ test('seg encodes emails and rejects empty and dot segments', () => {+ expect(dripApi.seg({ value: ' [email protected] ', label: 'S' })).toBe('a%2Bb%40x.com');+ expect(dripApi.seg({ value: 'a/b', label: 'S' })).toBe('a%2Fb');+ expect(() => dripApi.seg({ value: '', label: 'S' })).toThrow('S is required');+ expect(() => dripApi.seg({ value: '..', label: 'S' })).toThrow('not valid');+ });+ test('account IDs must be digits', () => {+ expect(dripApi.accountPath(ACCOUNT)).toBe(`/${ACCOUNT}`);+ expect(() => dripApi.accountPath('12/../x')).toThrow('not a valid Drip account ID');+ expect(() => dripApi.parseNumericId({ value: '12a', label: 'Campaign ID' })).toThrow('Campaign ID');+ });+ test('identify picks email or id', () => {+ expect(dripApi.identify({ value: '[email protected]', label: 'S' })).toEqual({ email: '[email protected]' });+ expect(dripApi.identify({ value: 'z1tog', label: 'S' })).toEqual({ id: 'z1tog' });+ });+ test('dates, numbers, objects and paging are validated', () => {+ expect(dripApi.parseIsoDate({ value: '2026-01-31T09:00:00.000Z', label: 'D' })).toBe('2026-01-31T09:00:00Z');+ expect(dripApi.parseIsoDate({ value: '', label: 'D' })).toBeUndefined();+ expect(() => dripApi.parseIsoDate({ value: 'yesterday', label: 'D' })).toThrow('ISO-8601');+ expect(dripApi.validateInteger({ value: '5', label: 'N', min: 0, max: 10 })).toBe(5);+ expect(() => dripApi.validateInteger({ value: 1.5, label: 'N', min: 0, max: 10 })).toThrow('whole number');+ expect(dripApi.parseObject({ value: '{"a":1}', label: 'O' })).toEqual({ a: 1 });+ expect(() => dripApi.parseObject({ value: '[1]', label: 'O' })).toThrow('object');+ expect(dripApi.paging({ page: undefined, perPage: undefined, max: 100 })).toEqual({ page: 1, perPage: 100 });+ expect(() => dripApi.paging({ page: 0, perPage: 5, max: 100 })).toThrow('Page');+ expect(() => dripApi.paging({ page: 1, perPage: 101, max: 100 })).toThrow('between 1 and 100');+ expect(dripApi.textList(['a', ' a ', '', 'b'])).toEqual(['a', 'b']);+ });+ test('pageInfo uses total_pages, else a full page means there may be more', () => {+ expect(dripApi.pageInfo({ meta: { total_pages: 3, total_count: 250 }, page: 1, perPage: 100, count: 100 })).toEqual({ page: 1, totalPages: 3, totalCount: 250, hasMore: true });+ expect(dripApi.pageInfo({ meta: { total_pages: 1, total_count: 3 }, page: 1, perPage: 100, count: 3 })).toEqual({ page: 1, totalPages: 1, totalCount: 3, hasMore: false });+ expect(dripApi.pageInfo({ meta: { page: 2 }, page: 2, perPage: 5, count: 5 })).toEqual({ page: 2, totalPages: null, totalCount: null, hasMore: true });+ });+});++describe('resolveAccountId', () => {+ test('uses the given ID without a request', async () => {+ const seen = stubFetch(() => ({ body: {} }));+ await expect(runStep(dripApi.resolveAccountId({ token: TOKEN, accountId: ` ${ACCOUNT} ` }))).resolves.toBe(ACCOUNT);+ expect(seen).toHaveLength(0);+ });+ test('falls back to the only account', async () => {+ stubFetch(() => ({ body: { accounts: [{ id: ACCOUNT, name: 'a' }] } }));+ await expect(runStep(dripApi.resolveAccountId({ token: TOKEN, accountId: undefined }))).resolves.toBe(ACCOUNT);+ });+ test('fails with the choices when there are several accounts, and when there are none', async () => {+ stubFetch(() => ({ body: { accounts: [{ id: '1', name: 'One' }, { id: '2', name: 'Two' }] } }));+ await expect(runStep(dripApi.resolveAccountId({ token: TOKEN, accountId: '' }))).rejects.toThrow('1: One, 2: Two');+ vi.unstubAllGlobals();+ stubFetch(() => ({ body: { accounts: [] } }));+ await expect(runStep(dripApi.resolveAccountId({ token: TOKEN, accountId: '' }))).rejects.toThrow('no accounts');+ });+});diff --git a/packages/pieces/community/drip/test/helpers.ts b/packages/pieces/community/drip/test/helpers.tsnew file mode 100644index 00000000000..be01608581c--- /dev/null+++ b/packages/pieces/community/drip/test/helpers.ts@@ -0,0 +1,126 @@+import { AppConnectionType, Store } from '@activepieces/pieces-framework';+import { vi } from 'vitest';++export type SeenRequest = {+ url: string;+ method: string;+ path: string;+ version: string;+ headers: Headers;+ query: URLSearchParams;+ auth: string | null;+ accept: string | null;+ body: unknown;+ userAgent: string | null;+};++export type FakeReply = {+ status?: number;+ body?: unknown;+ text?: string;+ 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 | Request, init?: RequestInit) => {+ const url = input instanceof Request ? input.url : String(input);+ const headers = new Headers(init?.headers);+ const parsed = new URL(url);+ const rawBody = typeof init?.body === 'string' ? init.body : null;+ const request: SeenRequest = {+ url,+ method: (init?.method ?? 'GET').toUpperCase(),+ path: parsed.pathname.replace(/^\/v[23]/, ''),+ version: parsed.pathname.startsWith('/v3') ? 'v3' : parsed.pathname.startsWith('/v2') ? 'v2' : 'other',+ headers,+ query: parsed.searchParams,+ auth: headers.get('authorization'),+ accept: headers.get('accept'),+ body: rawBody ? JSON.parse(rawBody) : null,+ userAgent: headers.get('user-agent'),+ };+ seen.push(request);+ const reply = respond(request, seen.length - 1);+ const status = reply.status ?? 200;+ const payload = status === 204 ? null : reply.text ?? JSON.stringify(reply.body ?? {});+ return new Response(payload, {+ status,+ headers: { 'content-type': reply.text !== undefined ? 'text/plain' : '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 const TOKEN = 'test-token';++export const SERVER = { apiUrl: 'http://localhost:3000/api/', publicUrl: 'http://localhost:4200/', token: 'x' };++export function dripConnection() {+ return { type: AppConnectionType.SECRET_TEXT as const, secret_text: TOKEN };+}++export function actionContext(propsValue: Record<string, unknown>): TestActionContext {+ return { auth: dripConnection(), propsValue, store: memoryStore(), server: SERVER };+}++export function memoryStore(initial: Record<string, unknown> = {}): MemoryStore {+ const data = new Map<string, string>(Object.entries(initial).map(([key, value]) => [key, JSON.stringify(value)]));+ return {+ keys: (): string[] => [...data.keys()],+ read: (key: string): unknown => {+ const raw = data.get(key);+ return raw === undefined ? undefined : JSON.parse(raw);+ },+ put: async <T>(key: string, value: T): Promise<T> => {+ data.set(key, JSON.stringify(value));+ return value;+ },+ get: async <T>(key: string): Promise<T | null> => {+ const raw = data.get(key);+ return raw === undefined ? null : JSON.parse(raw);+ },+ delete: async (key: string): Promise<void> => {+ data.delete(key);+ },+ };+}++export async function runStep<T>(promise: Promise<T>): Promise<T> {+ const settled = promise.then(+ (value) => ({ ok: true as const, value }),+ (error: unknown) => ({ ok: false as const, error }),+ );+ await vi.runAllTimersAsync();+ const result = await settled;+ if (!result.ok) {+ throw result.error;+ }+ return result.value;+}++export function run(action: Runnable) {+ return (propsValue: Record<string, unknown>): Promise<unknown> => runStep(action.run(actionContext(propsValue)));+}++export function idsOf(items: unknown): unknown[] {+ return Array.isArray(items) ? items.map((item: unknown) => (item !== null && typeof item === 'object' ? Reflect.get(item, 'id') : undefined)) : [];+}++export type MemoryStore = Store & { read: (key: string) => unknown; keys: () => string[] };++type TestActionContext = {+ auth: { type: AppConnectionType.SECRET_TEXT; secret_text: string };+ propsValue: Record<string, unknown>;+ store: Store;+ server: typeof SERVER;+};++type Runnable = { run(context: TestActionContext): Promise<unknown> };diff --git a/packages/pieces/community/drip/test/legacy.test.ts b/packages/pieces/community/drip/test/legacy.test.tsnew file mode 100644index 00000000000..72e595f53e8--- /dev/null+++ b/packages/pieces/community/drip/test/legacy.test.ts@@ -0,0 +1,107 @@+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { dripAddSubscriberToCampaign } from '../src/lib/actions/add-subscriber-to-campaign.action';+import { dripApplyTagToSubscriber } from '../src/lib/actions/apply-tag-to-subscriber.action';+import { dripUpsertSubscriberAction } from '../src/lib/actions/upsert-subscriber.action';+import { dripAuth } from '../src/lib/auth';+import { dripCommon } from '../src/lib/common';+import { dripConnection, run, runStep, SERVER, stubFetch, TOKEN } from './helpers';++const A = '4617837';+const EMAIL = '[email protected]';+const ctx = { server: SERVER, project: { id: 'p', externalId: () => undefined }, flows: {}, step: { name: 's' } };++function options({ prop, propsValue = {} }: { prop: { options: (propsValue: never, context: never) => Promise<unknown> }; propsValue?: Record<string, unknown> }) {+ return runStep(Reflect.apply(prop.options, prop, [{ auth: dripConnection(), ...propsValue }, ctx]));+}++beforeEach(() => {+ vi.useFakeTimers();+});++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++describe('existing actions keep their request and raw response shape', () => {+ test('upsert_subscriber posts the same body and returns {status, headers, body}', async () => {+ const seen = stubFetch(() => ({ body: { subscribers: [{ id: 'z', email: EMAIL }] } }));+ const result = await run(dripUpsertSubscriberAction)({ account_id: A, subscriber: EMAIL, first_name: 'O', address: 'Line 1', tags: ['t'] });+ expect(seen[0].url).toBe(`https://api.getdrip.com/v2/${A}/subscribers`);+ expect(seen[0].auth).toBe(`Basic ${Buffer.from(TOKEN).toString('base64')}`);+ expect(seen[0].body).toEqual({ subscribers: [{ email: EMAIL, tags: ['t'], address1: 'Line 1', first_name: 'O' }] });+ expect(result).toMatchObject({ status: 200, body: { subscribers: [{ id: 'z', email: EMAIL }] } });+ expect(result).toHaveProperty('headers');+ });+ test('apply_tag_to_subscriber posts tags and returns the 201 response', async () => {+ const seen = stubFetch(() => ({ status: 201, body: {} }));+ await expect(run(dripApplyTagToSubscriber)({ account_id: A, subscriber: EMAIL, tag: 'x' })).resolves.toMatchObject({ status: 201, body: {} });+ expect(seen[0].body).toEqual({ tags: [{ email: EMAIL, tag: 'x' }] });+ });+ test('add_subscriber_to_campaign posts to the campaign and does not send double_optin', async () => {+ const seen = stubFetch(() => ({ body: { subscribers: [{ id: 'z' }] } }));+ await run(dripAddSubscriberToCampaign)({ account_id: A, campaign_id: '9', subscriber: EMAIL, custom_fields: { a: 1 } });+ expect(seen[0].path).toBe(`/${A}/campaigns/9/subscribers`);+ expect(seen[0].body).toEqual({ subscribers: [{ email: EMAIL, custom_fields: { a: 1 } }] });+ });+ test('errors carry the Drip message', async () => {+ stubFetch(() => ({ status: 422, body: { errors: [{ code: 'email_error', attribute: 'email', message: 'Email is invalid' }] } }));+ await expect(run(dripUpsertSubscriberAction)({ account_id: A, subscriber: 'bad' })).rejects.toThrow('email: Email is invalid');+ });+});++describe('dropdowns', () => {+ test('account dropdown lists accounts', async () => {+ stubFetch(() => ({ body: { accounts: [{ id: A, name: 'activepieces' }] } }));+ await expect(options({ prop: dripCommon.account_id })).resolves.toEqual({ disabled: false, options: [{ value: A, label: 'activepieces' }] });+ });+ test('account dropdown shows the Drip error instead of throwing', async () => {+ stubFetch(() => ({ status: 401, body: { errors: [{ code: 'authentication_error', message: 'bad token' }] } }));+ await expect(options({ prop: dripCommon.account_id })).resolves.toMatchObject({ disabled: true, options: [], placeholder: expect.stringContaining('invalid or was revoked') });+ });+ test('campaign dropdown follows total_pages and labels the status', async () => {+ const seen = stubFetch((_request, index) => ({ body: { campaigns: [{ id: String(index), name: `C${index}`, status: index === 0 ? 'draft' : 'active' }], meta: { total_pages: 2 } } }));+ const result = await options({ prop: dripCommon.campaign_id({ required: true }), propsValue: { account_id: A } });+ expect(seen).toHaveLength(2);+ expect(seen[0].query.get('per_page')).toBe('1000');+ expect(seen[1].query.get('page')).toBe('2');+ expect(result).toEqual({ disabled: false, options: [{ value: '0', label: 'C0 (draft)' }, { value: '1', label: 'C1 (active)' }] });+ });+ test('campaign dropdown stops after 10 pages', async () => {+ const seen = stubFetch(() => ({ body: { campaigns: [{ id: '1', name: 'C', status: 'active' }], meta: { total_pages: 50 } } }));+ const result = await options({ prop: dripCommon.campaign_id({ required: true }), propsValue: { account_id: A } });+ expect(seen).toHaveLength(10);+ expect(result).toMatchObject({ disabled: false, placeholder: expect.stringContaining('Drip has more') });+ });+ test('campaign dropdown shows no truncation note when the last page is the 10th', async () => {+ stubFetch((_request, index) => ({ body: { campaigns: [{ id: String(index), name: 'C', status: 'active' }], meta: { total_pages: 10 } } }));+ const result = await options({ prop: dripCommon.campaign_id({ required: true }), propsValue: { account_id: A } });+ expect(result).not.toHaveProperty('placeholder');+ });+ test('campaign dropdown needs an account and reports a disabled Drip account', async () => {+ await expect(options({ prop: dripCommon.campaign_id({ required: true }) })).resolves.toMatchObject({ disabled: true, placeholder: 'Please select an account first' });+ stubFetch(() => ({ status: 403, body: { errors: [{ code: 'authorization_error', message: 'Your account is disabled.' }] } }));+ await expect(options({ prop: dripCommon.campaign_id({ required: true }), propsValue: { account_id: A } })).resolves.toMatchObject({ disabled: true, placeholder: expect.stringContaining('account is disabled') });+ });+});++describe('auth.validate', () => {+ function validate() {+ return runStep(Reflect.apply(dripAuth.validate ?? (async () => undefined), dripAuth, [{ auth: TOKEN, server: SERVER }]));+ }+ test('valid with accounts', async () => {+ const seen = stubFetch(() => ({ body: { accounts: [{ id: A, name: 'a' }] } }));+ await expect(validate()).resolves.toEqual({ valid: true });+ expect(seen[0].url).toBe('https://api.getdrip.com/v2/accounts');+ });+ test('401 is an invalid token; other errors explain themselves; no accounts is invalid', async () => {+ stubFetch(() => ({ status: 401, body: { errors: [{ code: 'authentication_error', message: 'x' }] } }));+ await expect(validate()).resolves.toMatchObject({ valid: false, error: expect.stringContaining('Invalid Drip API token') });+ vi.unstubAllGlobals();+ stubFetch(() => ({ status: 500, body: { errors: [{ code: 'x', message: 'down' }] } }));+ await expect(validate()).resolves.toMatchObject({ valid: false, error: expect.stringContaining('down') });+ vi.unstubAllGlobals();+ stubFetch(() => ({ body: { accounts: [] } }));+ await expect(validate()).resolves.toMatchObject({ valid: false, error: expect.stringContaining('no accounts') });+ });+});diff --git a/packages/pieces/community/drip/test/metadata.test.ts b/packages/pieces/community/drip/test/metadata.test.tsnew file mode 100644index 00000000000..76fed8d393b--- /dev/null+++ b/packages/pieces/community/drip/test/metadata.test.ts@@ -0,0 +1,53 @@+import { describe, expect, test } from 'vitest';+import { drip } from '../src';++const actions = Object.values(drip.actions());+const nonCustom = actions.filter((action) => action.name !== 'custom_api_call');+const byName = Object.fromEntries(actions.map((action) => [action.name, action]));++describe('piece metadata', () => {+ test('36 actions and 10 triggers', () => {+ expect(actions).toHaveLength(36);+ expect(Object.keys(drip.triggers())).toHaveLength(10);+ });+ test.each(nonCustom.map((action) => [action.name, action]))('%s declares 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(60);+ expect(typeof action.aiMetadata?.idempotent).toBe('boolean');+ expect(action.outputSchema?.fields.length).toBeGreaterThan(0);+ });+ test('dropdown actions are human-only and AI-visible actions have no dropdowns', () => {+ for (const name of ['add_subscriber_to_campaign', 'apply_tag_to_subscriber', 'upsert_subscriber']) {+ expect(byName[name].audience).toBe('human');+ }+ for (const name of ['subscribe_to_campaign', 'apply_tag', 'create_or_update_subscriber']) {+ expect(byName[name].audience).toBe('ai');+ }+ const aiVisible = actions.filter((action) => action.audience !== 'human' && action.name !== 'custom_api_call');+ for (const action of aiVisible) {+ const types = Object.values(action.props).map((prop: unknown) => (prop !== null && typeof prop === 'object' ? Reflect.get(prop, 'type') : undefined));+ expect(types).not.toContain('DROPDOWN');+ }+ });+ test('delete_subscriber and unsubscribe_subscriber (dedicated unsubscribe, rubric wave-15) are destructive; non-idempotent writes are the ones that start or record things', () => {+ expect(nonCustom.filter((action) => action.classification === 'DESTRUCTIVE').map((action) => action.name).sort()).toEqual(['delete_subscriber', 'unsubscribe_subscriber']);+ expect(+ nonCustom+ .filter((action) => action.aiMetadata?.idempotent === false)+ .map((action) => action.name)+ .sort(),+ ).toEqual(['add_subscriber_to_campaign', 'record_cart', 'record_event', 'record_order', 'start_workflow', 'subscribe_to_campaign']);+ });+ test('triggers are READ with aiMetadata, sample data and an output schema', () => {+ for (const trigger of Object.values(drip.triggers())) {+ expect(trigger.classification).toBe('READ');+ expect(trigger.aiMetadata?.description?.length ?? 0).toBeGreaterThan(40);+ expect(trigger.sampleData).toBeTruthy();+ expect(trigger.outputSchema?.fields.length).toBeGreaterThan(0);+ }+ });+ test('minimum release supports ai audience', () => {+ expect(drip.minimumSupportedRelease).toBe('0.88.2');+ });+});diff --git a/packages/pieces/community/drip/test/subscribers.test.ts b/packages/pieces/community/drip/test/subscribers.test.tsnew file mode 100644index 00000000000..f1c8cf13b8e--- /dev/null+++ b/packages/pieces/community/drip/test/subscribers.test.ts@@ -0,0 +1,162 @@+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { createOrUpdateSubscriberAction } from '../src/lib/actions/ai/create-or-update-subscriber.action';+import { batchUpsertSubscribersAction } from '../src/lib/actions/batch-upsert-subscribers.action';+import { deleteSubscriberAction } from '../src/lib/actions/delete-subscriber.action';+import { findSubscriberAction } from '../src/lib/actions/find-subscriber.action';+import { listSubscriberCampaignsAction } from '../src/lib/actions/list-subscriber-campaigns.action';+import { listSubscribersAction } from '../src/lib/actions/list-subscribers.action';+import { removeFromCampaignAction } from '../src/lib/actions/remove-from-campaign.action';+import { unsubscribeSubscriberAction } from '../src/lib/actions/unsubscribe-subscriber.action';+import { run, stubFetch } from './helpers';++const A = '4617837';+const SUB = { id: 'z1tog', email: '[email protected]', status: 'active', tags: ['Customer'] };+const NOT_FOUND = { status: 404, body: { errors: [{ code: 'not_found_error', message: 'The resource you requested was not found' }] } };++beforeEach(() => {+ vi.useFakeTimers();+});++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++describe('find_subscriber', () => {+ test('GETs the encoded email and returns found + subscriber', async () => {+ const seen = stubFetch(() => ({ body: { subscribers: [SUB] } }));+ await expect(run(findSubscriberAction)({ accountId: A, subscriber: SUB.email })).resolves.toEqual({ found: true, subscriber: SUB });+ expect(seen[0].method).toBe('GET');+ expect(seen[0].url).toBe(`https://api.getdrip.com/v2/${A}/subscribers/odai%2Baptest-1%40activepieces.com`);+ });+ test('404 is found=false; other errors fail', async () => {+ stubFetch(() => NOT_FOUND);+ await expect(run(findSubscriberAction)({ accountId: A, subscriber: '[email protected]' })).resolves.toEqual({ found: false, subscriber: null });+ vi.unstubAllGlobals();+ stubFetch(() => ({ status: 500, body: { errors: [{ code: 'x', message: 'boom' }] } }));+ await expect(run(findSubscriberAction)({ accountId: A, subscriber: '[email protected]' })).rejects.toThrow('boom');+ });+ test('resolves the single account when Account ID is empty', async () => {+ const seen = stubFetch((request) => (request.path === '/accounts' ? { body: { accounts: [{ id: A, name: 'a' }] } } : { body: { subscribers: [SUB] } }));+ await run(findSubscriberAction)({ subscriber: SUB.id });+ expect(seen.map((r) => r.path)).toEqual(['/accounts', `/${A}/subscribers/z1tog`]);+ });+});++describe('list_subscribers', () => {+ test('sends filters and paging and reports hasMore from total_pages', async () => {+ const seen = stubFetch(() => ({ body: { subscribers: [SUB], meta: { page: 2, total_pages: 3, total_count: 5 } } }));+ const result = await run(listSubscribersAction)({+ accountId: A,+ status: 'all',+ tags: ['VIP', 'Customer'],+ subscribedAfter: '2026-01-01T00:00:00.000Z',+ page: 2,+ perPage: 2,+ });+ expect(Object.fromEntries(seen[0].query)).toEqual({ status: 'all', tags: 'VIP,Customer', subscribed_after: '2026-01-01T00:00:00Z', page: '2', per_page: '2' });+ expect(result).toEqual({ items: [SUB], page: 2, totalPages: 3, totalCount: 5, hasMore: true });+ });+ test('rejects tags with commas, bad dates and perPage over 1000 before any request', async () => {+ const seen = stubFetch(() => ({ body: {} }));+ await expect(run(listSubscribersAction)({ accountId: A, tags: ['a,b'] })).rejects.toThrow('commas');+ await expect(run(listSubscribersAction)({ accountId: A, subscribedBefore: 'soon' })).rejects.toThrow('ISO-8601');+ await expect(run(listSubscribersAction)({ accountId: A, perPage: 5000 })).rejects.toThrow('between 1 and 1000');+ expect(seen).toHaveLength(0);+ });+});++describe('create_or_update_subscriber', () => {+ test('sends only the fields given and returns the subscriber', async () => {+ const seen = stubFetch(() => ({ body: { subscribers: [SUB] } }));+ const result = await run(createOrUpdateSubscriberAction)({+ accountId: A,+ subscriber: SUB.email,+ firstName: 'Odai',+ lastName: '',+ newEmail: '[email protected]',+ lifetimeValue: 2500,+ customFields: { plan: 'pro' },+ tags: ['a'],+ removeTags: ['b'],+ });+ expect(seen[0].method).toBe('POST');+ expect(seen[0].path).toBe(`/${A}/subscribers`);+ expect(seen[0].body).toEqual({+ subscribers: [+ {+ email: SUB.email,+ first_name: 'Odai',+ new_email: '[email protected]',+ lifetime_value: 2500,+ custom_fields: { plan: 'pro' },+ tags: ['a'],+ remove_tags: ['b'],+ },+ ],+ });+ expect(result).toEqual(SUB);+ });+ test('an ID updates by id; a non-integer lifetime value is refused', async () => {+ const seen = stubFetch(() => ({ body: { subscribers: [SUB] } }));+ await run(createOrUpdateSubscriberAction)({ accountId: A, subscriber: 'z1tog', city: 'Amman' });+ expect(seen[0].body).toEqual({ subscribers: [{ id: 'z1tog', city: 'Amman' }] });+ await expect(run(createOrUpdateSubscriberAction)({ accountId: A, subscriber: 'z1tog', lifetimeValue: 1.5 })).rejects.toThrow('whole number');+ });+});++describe('delete_subscriber', () => {+ test('DELETE 204 → deleted; 404 → alreadyDeleted', async () => {+ const seen = stubFetch(() => ({ status: 204 }));+ await expect(run(deleteSubscriberAction)({ accountId: A, subscriber: SUB.email })).resolves.toEqual({ subscriber: SUB.email, deleted: true, alreadyDeleted: false });+ expect(seen[0].method).toBe('DELETE');+ vi.unstubAllGlobals();+ stubFetch(() => NOT_FOUND);+ await expect(run(deleteSubscriberAction)({ accountId: A, subscriber: SUB.email })).resolves.toEqual({ subscriber: SUB.email, deleted: false, alreadyDeleted: true });+ });+ test('refuses an empty subscriber', async () => {+ const seen = stubFetch(() => ({ status: 204 }));+ await expect(run(deleteSubscriberAction)({ accountId: A, subscriber: ' ' })).rejects.toThrow('required');+ expect(seen).toHaveLength(0);+ });+});++describe('unsubscribe / remove from email series / subscriptions', () => {+ test('unsubscribe POSTs unsubscribe_all', async () => {+ const seen = stubFetch(() => ({ body: { subscribers: [{ ...SUB, status: 'unsubscribed' }] } }));+ await expect(run(unsubscribeSubscriberAction)({ accountId: A, subscriber: SUB.id })).resolves.toMatchObject({ status: 'unsubscribed' });+ expect(seen[0].method).toBe('POST');+ expect(seen[0].path).toBe(`/${A}/subscribers/z1tog/unsubscribe_all`);+ });+ test('remove passes campaign_id only when given', async () => {+ const seen = stubFetch(() => ({ body: { subscribers: [SUB] } }));+ await run(removeFromCampaignAction)({ accountId: A, subscriber: SUB.id, campaignId: '123' });+ await run(removeFromCampaignAction)({ accountId: A, subscriber: SUB.id });+ expect(seen[0].query.get('campaign_id')).toBe('123');+ expect(seen[1].query.has('campaign_id')).toBe(false);+ await expect(run(removeFromCampaignAction)({ accountId: A, subscriber: SUB.id, campaignId: 'abc' })).rejects.toThrow('Campaign ID');+ });+ test('list subscriber campaigns pages', async () => {+ const seen = stubFetch(() => ({ body: { campaign_subscriptions: [{ id: '1', campaign_id: '9' }], meta: { total_pages: 1, total_count: 1 } } }));+ await expect(run(listSubscriberCampaignsAction)({ accountId: A, subscriber: SUB.email })).resolves.toEqual({ items: [{ id: '1', campaign_id: '9' }], page: 1, totalPages: 1, totalCount: 1, hasMore: false });+ expect(seen[0].path).toBe(`/${A}/subscribers/odai%2Baptest-1%40activepieces.com/campaign_subscriptions`);+ });+});++describe('batch_upsert_subscribers', () => {+ test('wraps the array in one batch', async () => {+ const seen = stubFetch(() => ({ status: 201, body: {} }));+ const subscribers = [{ email: '[email protected]' }, { id: 'z1tog', tags: ['x'] }];+ await expect(run(batchUpsertSubscribersAction)({ accountId: A, subscribers })).resolves.toEqual({ submitted: 2, accepted: true });+ expect(seen[0].path).toBe(`/${A}/subscribers/batches`);+ expect(seen[0].body).toEqual({ batches: [{ subscribers }] });+ });+ test('validates size and identity before the request', async () => {+ const seen = stubFetch(() => ({ status: 201, body: {} }));+ await expect(run(batchUpsertSubscribersAction)({ accountId: A, subscribers: [] })).rejects.toThrow('between 1 and 1000');+ await expect(run(batchUpsertSubscribersAction)({ accountId: A, subscribers: Array.from({ length: 1001 }, (_, i) => ({ email: `${i}@x.co` })) })).rejects.toThrow('between 1 and 1000');+ await expect(run(batchUpsertSubscribersAction)({ accountId: A, subscribers: [{ email: '[email protected]' }, { first_name: 'x' }] })).rejects.toThrow('#2');+ await expect(run(batchUpsertSubscribersAction)({ accountId: A, subscribers: '{"a":1}' })).rejects.toThrow('list');+ expect(seen).toHaveLength(0);+ });+});diff --git a/packages/pieces/community/drip/test/webhook.test.ts b/packages/pieces/community/drip/test/webhook.test.tsnew file mode 100644index 00000000000..558f72eb574--- /dev/null+++ b/packages/pieces/community/drip/test/webhook.test.ts@@ -0,0 +1,354 @@+import { createHash } from 'node:crypto';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { dripWebhook } from '../src/lib/common/webhook';+import { dripCustomEventPerformedEvent } from '../src/lib/trigger/custom-event-performed.trigger';+import { dripNewSubscriberEvent } from '../src/lib/trigger/new-subscriber.trigger';+import { dripTagAppliedEvent } from '../src/lib/trigger/new-tag.trigger';+import { dripSubscribedToCampaignEvent } from '../src/lib/trigger/subscribed-to-campaign.trigger';+import { dripSubscriberDeletedEvent } from '../src/lib/trigger/subscriber-deleted.trigger';+import { dripTagRemovedEvent } from '../src/lib/trigger/tag-removed.trigger';+import { dripConnection, memoryStore, MemoryStore, runStep, stubFetch } from './helpers';++const A = '4617837';+const HOOK = 'https://cloud.example.com/api/v1/webhooks/flow1';+const SECRET = 'a'.repeat(64);+const NEW_SUB_KEY = 'drip_new_subscriber_trigger';+const TAG_KEY = 'drip_tag_applied_to_subscriber_trigger';+const SUB = { id: 'z1tog', email: '[email protected]', tags: ['vip'] };++type Hook = { onEnable: (ctx: never) => Promise<unknown>; onDisable: (ctx: never) => Promise<unknown>; run: (ctx: never) => Promise<unknown> };++function ctx({ store, propsValue = { account_id: A }, payload }: { store: MemoryStore; propsValue?: Record<string, unknown>; payload?: unknown }) {+ return { auth: dripConnection(), propsValue, store, webhookUrl: HOOK, payload };+}++function call<T>({ trigger, fn, context }: { trigger: Hook; fn: keyof Hook; context: unknown }): Promise<T> {+ return runStep(Reflect.apply(trigger[fn], trigger, [context]));+}++function delivery({ event = 'subscriber.created', token = SECRET, properties, account = A, occurredAt = '2026-10-06T15:31:58Z' }: { event?: string; token?: string | null; properties?: Record<string, unknown>; account?: string; occurredAt?: string } = {}) {+ return {+ body: { event, data: { account_id: account, subscriber: SUB, ...(properties ? { properties } : {}) }, occurred_at: occurredAt },+ headers: {},+ queryParams: token === null ? {} : { ap_token: token },+ };+}++function dedupeKeyOf(d: ReturnType<typeof delivery>): string {+ const parts = [d.body.event, d.body.data.subscriber.id, d.body.occurred_at, JSON.stringify(Reflect.get(d.body.data, 'properties') ?? null)];+ return createHash('sha256').update(parts.join('|')).digest('hex');+}++function emitted({ body, storeKey = NEW_SUB_KEY }: { body: unknown; storeKey?: string }) {+ return { ...Object(body), _dedupe_key: expect.stringMatching(new RegExp(`^drip:${storeKey}:[0-9a-f]{64}$`)) };+}++function cellsOf(d: ReturnType<typeof delivery>): string[] {+ return dripWebhook.probeCells({ storeKey: NEW_SUB_KEY, key: dedupeKeyOf(d) });+}++function stored({ key, extra = { secret: SECRET } }: { key: string; extra?: Record<string, unknown> }) {+ return memoryStore({ [key]: { webhookId: '77', userId: A, ...extra } });+}++beforeEach(() => {+ vi.useFakeTimers();+});++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++describe('onEnable / onDisable', () => {+ test('registers the event with a random ap_token on the URL and stores id, account and secret', async () => {+ const seen = stubFetch(() => ({ status: 201, body: { webhooks: [{ id: '77', post_url: 'x' }] } }));+ const store = memoryStore();+ await call({ trigger: dripNewSubscriberEvent, fn: 'onEnable', context: ctx({ store }) });+ expect(seen[0].url).toBe(`https://api.getdrip.com/v2/${A}/webhooks`);+ const webhooks: unknown = Reflect.get(Object(seen[0].body), 'webhooks');+ const first: object = Array.isArray(webhooks) ? Object(webhooks[0]) : {};+ expect(Reflect.get(first, 'events')).toEqual(['subscriber.created']);+ const registered = new URL(String(Reflect.get(first, 'post_url')));+ expect(`${registered.origin}${registered.pathname}`).toBe(HOOK);+ const token = registered.searchParams.get('ap_token') ?? '';+ expect(token).toMatch(/^[0-9a-f]{64}$/);+ expect(store.read(NEW_SUB_KEY)).toEqual({ webhookId: '77', userId: A, secret: token });+ });+ test('two enables get different secrets', async () => {+ stubFetch(() => ({ status: 201, body: { webhooks: [{ id: '77' }] } }));+ const one = memoryStore();+ const two = memoryStore();+ await call({ trigger: dripNewSubscriberEvent, fn: 'onEnable', context: ctx({ store: one }) });+ await call({ trigger: dripNewSubscriberEvent, fn: 'onEnable', context: ctx({ store: two }) });+ expect(Reflect.get(Object(one.read(NEW_SUB_KEY)), 'secret')).not.toBe(Reflect.get(Object(two.read(NEW_SUB_KEY)), 'secret'));+ });+ test('deletes the webhook it created when store.put fails', async () => {+ const seen = stubFetch((request) => (request.method === 'POST' ? { status: 201, body: { webhooks: [{ id: '77' }] } } : { status: 204 }));+ const store = memoryStore();+ store.put = async () => {+ throw new Error('store down');+ };+ await expect(call({ trigger: dripNewSubscriberEvent, fn: 'onEnable', context: ctx({ store }) })).rejects.toThrow('store down');+ expect(seen.map((r) => `${r.method} ${r.path}`)).toEqual([`POST /${A}/webhooks`, `DELETE /${A}/webhooks/77`]);+ });+ test('fails when Drip returns no webhook id', async () => {+ stubFetch(() => ({ status: 201, body: { webhooks: [] } }));+ await expect(call({ trigger: dripNewSubscriberEvent, fn: 'onEnable', context: ctx({ store: memoryStore() }) })).rejects.toThrow('no webhooks record');+ });+ test('onDisable deletes and forgets; 404 counts as deleted', async () => {+ const seen = stubFetch(() => ({ status: 404, body: { errors: [{ code: 'not_found_error', message: 'nf' }] } }));+ const store = stored({ key: NEW_SUB_KEY });+ await call({ trigger: dripNewSubscriberEvent, fn: 'onDisable', context: ctx({ store }) });+ expect(seen[0].method).toBe('DELETE');+ expect(seen[0].path).toBe(`/${A}/webhooks/77`);+ expect(store.read(NEW_SUB_KEY)).toBeUndefined();+ });+ test('onDisable keeps the stored id when the delete fails', async () => {+ stubFetch(() => ({ status: 500, body: { errors: [{ code: 'x', message: 'boom' }] } }));+ const store = stored({ key: NEW_SUB_KEY });+ await expect(call({ trigger: dripNewSubscriberEvent, fn: 'onDisable', context: ctx({ store }) })).rejects.toThrow('boom');+ expect(store.read(NEW_SUB_KEY)).toEqual({ webhookId: '77', userId: A, secret: SECRET });+ });+ test('onDisable works for a legacy (0.5.x) store entry', async () => {+ const seen = stubFetch(() => ({ status: 204 }));+ const store = memoryStore({ [TAG_KEY]: { webhookId: '12', userId: A } });+ await call({ trigger: dripTagAppliedEvent, fn: 'onDisable', context: ctx({ store }) });+ expect(seen[0].path).toBe(`/${A}/webhooks/12`);+ expect(store.read(TAG_KEY)).toBeUndefined();+ });+});++describe('run', () => {+ test('emits a delivery with the right token, event and account', async () => {+ const store = stored({ key: NEW_SUB_KEY });+ const d = delivery();+ await expect(call({ trigger: dripNewSubscriberEvent, fn: 'run', context: ctx({ store, payload: d }) })).resolves.toEqual([emitted({ body: d.body })]);+ });+ test('drops a wrong token, another event, another account, and anything without a registration', async () => {+ const seen = stubFetch(() => ({ body: {} }));+ const store = stored({ key: NEW_SUB_KEY });+ await expect(call({ trigger: dripNewSubscriberEvent, fn: 'run', context: ctx({ store, payload: delivery({ token: 'b'.repeat(64) }) }) })).resolves.toEqual([]);+ await expect(call({ trigger: dripNewSubscriberEvent, fn: 'run', context: ctx({ store, payload: delivery({ token: 'short' }) }) })).resolves.toEqual([]);+ await expect(call({ trigger: dripNewSubscriberEvent, fn: 'run', context: ctx({ store, payload: delivery({ event: 'subscriber.deleted' }) }) })).resolves.toEqual([]);+ await expect(call({ trigger: dripNewSubscriberEvent, fn: 'run', context: ctx({ store, payload: delivery({ account: '1' }) }) })).resolves.toEqual([]);+ await expect(call({ trigger: dripNewSubscriberEvent, fn: 'run', context: ctx({ store: memoryStore(), payload: delivery() }) })).resolves.toEqual([]);+ expect(seen).toHaveLength(0);+ });+ test('legacy store entries without a secret are verified by re-fetching the subscriber from Drip', async () => {+ const store = stored({ key: NEW_SUB_KEY, extra: {} });+ const seen = stubFetch(() => ({ body: { subscribers: [SUB] } }));+ const d = delivery({ token: null });+ await expect(call({ trigger: dripNewSubscriberEvent, fn: 'run', context: ctx({ store, payload: d }) })).resolves.toEqual([emitted({ body: d.body })]);+ expect(seen[0].path).toBe(`/${A}/subscribers/z1tog`);+ vi.unstubAllGlobals();+ stubFetch(() => ({ status: 404, body: { errors: [{ code: 'not_found_error', message: 'nf' }] } }));+ const forged = delivery({ token: 'anything', occurredAt: '2026-10-06T16:00:00Z' });+ await expect(call({ trigger: dripNewSubscriberEvent, fn: 'run', context: ctx({ store, payload: forged }) })).resolves.toEqual([]);+ });+ test('a registration with a secret drops deliveries without ap_token and never calls Drip', async () => {+ const seen = stubFetch(() => ({ status: 404, body: { errors: [{ code: 'not_found_error', message: 'nf' }] } }));+ const store = stored({ key: NEW_SUB_KEY });+ await expect(call({ trigger: dripNewSubscriberEvent, fn: 'run', context: ctx({ store, payload: delivery({ token: null }) }) })).resolves.toEqual([]);+ const deletedStore = memoryStore({ drip_subscriber_deleted_trigger: { webhookId: '1', userId: A, secret: SECRET } });+ const forged = delivery({ event: 'subscriber.deleted', token: null, occurredAt: '2026-10-06T17:00:00Z' });+ await expect(call({ trigger: dripSubscriberDeletedEvent, fn: 'run', context: ctx({ store: deletedStore, payload: forged }) })).resolves.toEqual([]);+ expect(seen).toHaveLength(0);+ });+ test('legacy store entries (no secret): unknown subscriber, other email, or tag state not matching → dropped', async () => {+ const store = stored({ key: TAG_KEY, extra: {} });+ stubFetch(() => ({ status: 404, body: { errors: [{ code: 'not_found_error', message: 'nf' }] } }));+ await expect(call({ trigger: dripTagAppliedEvent, fn: 'run', context: ctx({ store, payload: delivery({ event: 'subscriber.applied_tag', token: null, properties: { tag: 'vip' } }) }) })).resolves.toEqual([]);+ vi.unstubAllGlobals();+ stubFetch(() => ({ body: { subscribers: [{ ...SUB, email: '[email protected]' }] } }));+ await expect(call({ trigger: dripTagAppliedEvent, fn: 'run', context: ctx({ store, payload: delivery({ event: 'subscriber.applied_tag', token: null, properties: { tag: 'vip' } }) }) })).resolves.toEqual([]);+ vi.unstubAllGlobals();+ const fresh = { ...SUB, first_name: 'From Drip' };+ stubFetch(() => ({ body: { subscribers: [fresh] } }));+ await expect(call({ trigger: dripTagAppliedEvent, fn: 'run', context: ctx({ store, payload: delivery({ event: 'subscriber.applied_tag', token: null, properties: { tag: 'other' } }) }) })).resolves.toEqual([]);+ const applied = delivery({ event: 'subscriber.applied_tag', token: null, properties: { tag: 'VIP' } });+ await expect(call<unknown[]>({ trigger: dripTagAppliedEvent, fn: 'run', context: ctx({ store, payload: applied }) })).resolves.toEqual([+ emitted({ body: { ...applied.body, data: { ...applied.body.data, subscriber: fresh } }, storeKey: TAG_KEY }),+ ]);+ const removedStore = memoryStore({ drip_tag_removed_trigger: { webhookId: '1', userId: A } });+ await expect(call({ trigger: dripTagRemovedEvent, fn: 'run', context: ctx({ store: removedStore, payload: delivery({ event: 'subscriber.removed_tag', token: null, properties: { tag: 'vip' } }) }) })).resolves.toEqual([]);+ });+ test('subscriber.deleted is emitted only with the right ap_token; a legacy entry without a secret never emits it', async () => {+ const seen = stubFetch(() => ({ status: 404, body: { errors: [{ code: 'not_found_error', message: 'nf' }] } }));+ const store = memoryStore({ drip_subscriber_deleted_trigger: { webhookId: '1', userId: A, secret: SECRET } });+ await expect(call<unknown[]>({ trigger: dripSubscriberDeletedEvent, fn: 'run', context: ctx({ store, payload: delivery({ event: 'subscriber.deleted' }) }) })).resolves.toHaveLength(1);+ const legacy = memoryStore({ drip_subscriber_deleted_trigger: { webhookId: '1', userId: A } });+ await expect(call({ trigger: dripSubscriberDeletedEvent, fn: 'run', context: ctx({ store: legacy, payload: delivery({ event: 'subscriber.deleted', token: null }) }) })).resolves.toEqual([]);+ expect(seen).toHaveLength(0);+ });+ test('duplicate deliveries are emitted once and the claim cells are a fixed, bounded set', async () => {+ const store = stored({ key: NEW_SUB_KEY });+ await expect(call<unknown[]>({ trigger: dripNewSubscriberEvent, fn: 'run', context: ctx({ store, payload: delivery() }) })).resolves.toHaveLength(1);+ await expect(call<unknown[]>({ trigger: dripNewSubscriberEvent, fn: 'run', context: ctx({ store, payload: delivery() }) })).resolves.toHaveLength(0);+ for (let i = 0; i < 600; i++) {+ await call({ trigger: dripNewSubscriberEvent, fn: 'run', context: ctx({ store, payload: delivery({ occurredAt: `2026-10-06T${String(10 + Math.floor(i / 60)).padStart(2, '0')}:${String(i % 60).padStart(2, '0')}:00Z` }) }) });+ }+ const claimKeys = store.keys().filter((key) => key !== NEW_SUB_KEY);+ expect(claimKeys.every((key) => /_c_\d+(_ok)?$/.test(key))).toBe(true);+ expect(claimKeys.length).toBeLessThanOrEqual(dripWebhook.CLAIM_CELLS * 2);+ });+ test('two concurrent runs of the same delivery emit it once (claim token + read-back)', async () => {+ const store = stored({ key: NEW_SUB_KEY });+ const runs: Promise<unknown>[] = [1, 2].map(() => Reflect.apply(dripNewSubscriberEvent.run, dripNewSubscriberEvent, [ctx({ store, payload: delivery() })]));+ await vi.runAllTimersAsync();+ const results = await Promise.all(runs);+ expect(results.map((r) => (Array.isArray(r) ? r.length : -1)).sort()).toEqual([0, 1]);+ });+ test('a repeat of an emitted delivery within the claim window is dropped and carries the same platform dedupe key', async () => {+ const store = stored({ key: NEW_SUB_KEY });+ const first = await call<Record<string, unknown>[]>({ trigger: dripNewSubscriberEvent, fn: 'run', context: ctx({ store, payload: delivery() }) });+ expect(first).toHaveLength(1);+ await expect(call<unknown[]>({ trigger: dripNewSubscriberEvent, fn: 'run', context: ctx({ store, payload: delivery() }) })).resolves.toHaveLength(0);+ const other = await call<Record<string, unknown>[]>({ trigger: dripNewSubscriberEvent, fn: 'run', context: ctx({ store, payload: delivery({ occurredAt: '2026-10-06T18:00:00Z' }) }) });+ expect(other[0]['_dedupe_key']).not.toBe(first[0]['_dedupe_key']);+ });+ test('a completed claim keeps blocking repeats after the claim window', async () => {+ const store = stored({ key: NEW_SUB_KEY });+ const d = delivery();+ await expect(call<unknown[]>({ trigger: dripNewSubscriberEvent, fn: 'run', context: ctx({ store, payload: d }) })).resolves.toHaveLength(1);+ const [cell] = cellsOf(d);+ const claim = Object(store.read(cell));+ expect(claim).toMatchObject({ key: dedupeKeyOf(d) });+ expect(store.read(dripWebhook.doneKeyOf(cell))).toEqual(claim);+ await store.put(cell, { ...claim, at: Date.now() - 24 * 60 * 60 * 1000 });+ await expect(call<unknown[]>({ trigger: dripNewSubscriberEvent, fn: 'run', context: ctx({ store, payload: d }) })).resolves.toHaveLength(0);+ });+ test('another delivery\'s completed claim in a shared cell is kept while a free probe cell exists', async () => {+ const store = stored({ key: NEW_SUB_KEY });+ const d = delivery();+ const [first, second] = cellsOf(d);+ const other = { key: 'f'.repeat(64), token: 'other', at: Date.now() };+ await store.put(first, other);+ await store.put(dripWebhook.doneKeyOf(first), other);+ await expect(call<unknown[]>({ trigger: dripNewSubscriberEvent, fn: 'run', context: ctx({ store, payload: d }) })).resolves.toHaveLength(1);+ expect(store.read(dripWebhook.doneKeyOf(first))).toEqual(other);+ expect(store.read(dripWebhook.doneKeyOf(second))).toMatchObject({ key: dedupeKeyOf(d) });+ await expect(call<unknown[]>({ trigger: dripNewSubscriberEvent, fn: 'run', context: ctx({ store, payload: d }) })).resolves.toHaveLength(0);+ });+ test('when every probe cell is taken, only the oldest one is reused', async () => {+ const store = stored({ key: NEW_SUB_KEY });+ const d = delivery();+ const cells = cellsOf(d);+ const now = Date.now();+ for (const [index, cell] of cells.entries()) {+ const record = { key: `other-${index}`, token: `t${index}`, at: now - 1000 * (10 - index) };+ await store.put(cell, record);+ await store.put(dripWebhook.doneKeyOf(cell), record);+ }+ await expect(call<unknown[]>({ trigger: dripNewSubscriberEvent, fn: 'run', context: ctx({ store, payload: d }) })).resolves.toHaveLength(1);+ expect(store.read(dripWebhook.doneKeyOf(cells[0]))).toMatchObject({ key: dedupeKeyOf(d) });+ for (const [index, cell] of cells.entries()) {+ if (index > 0) {+ expect(store.read(dripWebhook.doneKeyOf(cell))).toMatchObject({ key: `other-${index}` });+ }+ }+ });+ test('a run whose claim write landed late does not emit a delivery another run already finished', async () => {+ const store = stored({ key: NEW_SUB_KEY });+ const d = delivery();+ const [first, second] = cellsOf(d);+ const put = store.put;+ store.put = async <T>(key: string, value: T): Promise<T> => {+ const result = await put(key, value);+ if (key === first) {+ await put(dripWebhook.doneKeyOf(second), { key: dedupeKeyOf(d), token: 'first-run', at: Date.now() });+ }+ return result;+ };+ await expect(call<unknown[]>({ trigger: dripNewSubscriberEvent, fn: 'run', context: ctx({ store, payload: d }) })).resolves.toHaveLength(0);+ expect(store.read(dripWebhook.doneKeyOf(first))).toBeUndefined();+ });+ test('a different delivery taking the same cell during the settle wait moves this claim to the next cell', async () => {+ const store = stored({ key: NEW_SUB_KEY });+ const d = delivery();+ const [first, second] = cellsOf(d);+ const put = store.put;+ let takeovers = 1;+ store.put = async <T>(key: string, value: T): Promise<T> => {+ const result = await put(key, value);+ if (key === first && takeovers-- > 0) {+ await put(first, { key: 'e'.repeat(64), token: 'other', at: Date.now() });+ }+ return result;+ };+ await expect(call<unknown[]>({ trigger: dripNewSubscriberEvent, fn: 'run', context: ctx({ store, payload: d }) })).resolves.toHaveLength(1);+ expect(store.read(first)).toMatchObject({ key: 'e'.repeat(64) });+ expect(store.read(dripWebhook.doneKeyOf(second))).toMatchObject({ key: dedupeKeyOf(d) });+ });+ test('a delivery whose claim cells are all taken during the settle wait is still recorded before it is emitted', async () => {+ const store = stored({ key: NEW_SUB_KEY });+ const d = delivery();+ const key = dedupeKeyOf(d);+ const cells = cellsOf(d);+ const put = store.put;+ let contended = true;+ store.put = async <T>(cellKey: string, value: T): Promise<T> => {+ const result = await put(cellKey, value);+ if (contended && cells.includes(cellKey) && Reflect.get(Object(value), 'key') === key) {+ await put(cellKey, { key: `other-${cellKey}`, token: 'other', at: Date.now() });+ }+ return result;+ };+ await expect(call<unknown[]>({ trigger: dripNewSubscriberEvent, fn: 'run', context: ctx({ store, payload: d }) })).resolves.toHaveLength(1);+ contended = false;+ expect(cells.some((cell) => Reflect.get(Object(store.read(dripWebhook.doneKeyOf(cell))), 'key') === key)).toBe(true);+ await expect(call<unknown[]>({ trigger: dripNewSubscriberEvent, fn: 'run', context: ctx({ store, payload: d }) })).resolves.toHaveLength(0);+ });+ test('an unfinished claim blocks a retry until it is abandoned, then the retry emits', async () => {+ const store = stored({ key: NEW_SUB_KEY });+ const d = delivery();+ const [cell] = cellsOf(d);+ await store.put(cell, { key: dedupeKeyOf(d), token: 'other', at: Date.now() });+ await expect(call<unknown[]>({ trigger: dripNewSubscriberEvent, fn: 'run', context: ctx({ store, payload: d }) })).resolves.toHaveLength(0);+ await store.put(cell, { key: dedupeKeyOf(d), token: 'other', at: Date.now() - dripWebhook.ABANDONED_CLAIM_MS - 1 });+ await expect(call<unknown[]>({ trigger: dripNewSubscriberEvent, fn: 'run', context: ctx({ store, payload: d }) })).resolves.toHaveLength(1);+ });+ test('a store failure while claiming fails the run and releases the claim so a retry can emit', async () => {+ const store = stored({ key: NEW_SUB_KEY });+ const put = store.put;+ let failures = 1;+ store.put = async <T>(key: string, value: T): Promise<T> => {+ if (key.endsWith('_ok') && failures-- > 0) {+ throw new Error('store down');+ }+ return put(key, value);+ };+ await expect(call({ trigger: dripNewSubscriberEvent, fn: 'run', context: ctx({ store, payload: delivery() }) })).rejects.toThrow('store down');+ await expect(call<unknown[]>({ trigger: dripNewSubscriberEvent, fn: 'run', context: ctx({ store, payload: delivery() }) })).resolves.toHaveLength(1);+ });+ test('onDisable also clears the delivery claims', async () => {+ stubFetch(() => ({ status: 204 }));+ const store = stored({ key: NEW_SUB_KEY });+ await call({ trigger: dripNewSubscriberEvent, fn: 'run', context: ctx({ store, payload: delivery() }) });+ expect(store.keys().some((key) => key.startsWith(`${NEW_SUB_KEY}_c_`))).toBe(true);+ await call({ trigger: dripNewSubscriberEvent, fn: 'onDisable', context: ctx({ store }) });+ expect(store.keys()).toEqual([]);+ });+ test('tag, campaign and event-name filters', async () => {+ const tagStore = stored({ key: TAG_KEY });+ const tagCtx = ({ tag, filter }: { tag: string; filter?: string }) => ctx({ store: tagStore, propsValue: { account_id: A, tag: filter }, payload: delivery({ event: 'subscriber.applied_tag', properties: { tag }, occurredAt: `2026-01-01T00:00:0${tag.length % 10}Z` }) });+ await expect(call<unknown[]>({ trigger: dripTagAppliedEvent, fn: 'run', context: tagCtx({ tag: 'Customer', filter: ' customer ' }) })).resolves.toHaveLength(1);+ await expect(call<unknown[]>({ trigger: dripTagAppliedEvent, fn: 'run', context: tagCtx({ tag: 'Lead', filter: 'customer' }) })).resolves.toHaveLength(0);+ await expect(call<unknown[]>({ trigger: dripTagAppliedEvent, fn: 'run', context: tagCtx({ tag: 'Anything' }) })).resolves.toHaveLength(1);+ const campaignStore = memoryStore({ drip_subscribed_to_campaign_trigger: { webhookId: '1', userId: A, secret: SECRET } });+ const campaignCtx = ({ campaign, filter }: { campaign: string; filter?: string }) =>+ ctx({ store: campaignStore, propsValue: { account_id: A, campaign_id: filter }, payload: delivery({ event: 'subscriber.subscribed_to_campaign', properties: { campaign_id: campaign, campaign_name: 'S' }, occurredAt: `2026-01-01T00:00:${campaign}Z` }) });+ await expect(call<unknown[]>({ trigger: dripSubscribedToCampaignEvent, fn: 'run', context: campaignCtx({ campaign: '11', filter: '11' }) })).resolves.toHaveLength(1);+ await expect(call<unknown[]>({ trigger: dripSubscribedToCampaignEvent, fn: 'run', context: campaignCtx({ campaign: '12', filter: '11' }) })).resolves.toHaveLength(0);+ await expect(call<unknown[]>({ trigger: dripSubscribedToCampaignEvent, fn: 'run', context: campaignCtx({ campaign: '13' }) })).resolves.toHaveLength(1);+ const eventStore = memoryStore({ drip_custom_event_performed_trigger: { webhookId: '1', userId: A, secret: SECRET } });+ const eventCtx = ({ action, filter }: { action: string; filter?: string }) => ctx({ store: eventStore, propsValue: { account_id: A, action: filter }, payload: delivery({ event: 'subscriber.performed_custom_event', properties: { action } }) });+ await expect(call<unknown[]>({ trigger: dripCustomEventPerformedEvent, fn: 'run', context: eventCtx({ action: 'Logged in', filter: 'logged in' }) })).resolves.toHaveLength(1);+ await expect(call<unknown[]>({ trigger: dripCustomEventPerformedEvent, fn: 'run', context: eventCtx({ action: 'Signed up', filter: 'logged in' }) })).resolves.toHaveLength(0);+ });+ test('withToken keeps existing query parameters', () => {+ const url = new URL(dripWebhook.withToken({ url: 'https://x.example/hook?a=1', secret: 's' }));+ expect(url.searchParams.get('a')).toBe('1');+ expect(url.searchParams.get('ap_token')).toBe('s');+ });+});diff --git a/packages/pieces/community/drip/vitest.config.ts b/packages/pieces/community/drip/vitest.config.tsnew file mode 100644index 00000000000..79c97261904--- /dev/null+++ b/packages/pieces/community/drip/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'),+ },+ },+})