Skip to content

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

feat(convertkit): let AI agents manage Kit subscribers, tags, forms, sequences and broadcasts (#15902)

Odai Ahmad4d73a9596b38
diff --git a/bun.lock b/bun.lock
index 4777376d4df..ab116368a67 100644
--- a/bun.lock
+++ b/bun.lock
@@ -2250,7 +2250,7 @@
},
"packages/pieces/community/convertkit": {
"name": "@activepieces/piece-convertkit",
- "version": "0.3.9",
+ "version": "0.4.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -2259,6 +2259,7 @@
},
"devDependencies": {
"tslib": "2.6.2",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/copper": {
diff --git a/packages/pieces/community/convertkit/package.json b/packages/pieces/community/convertkit/package.json
index 9e31c26960d..f45056c90f0 100644
--- a/packages/pieces/community/convertkit/package.json
+++ b/packages/pieces/community/convertkit/package.json
@@ -1,12 +1,13 @@
{
"name": "@activepieces/piece-convertkit",
- "version": "0.3.9",
+ "version": "0.4.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/convertkit/src/i18n/translation.json b/packages/pieces/community/convertkit/src/i18n/translation.json
index 6d9e6a2134c..c0c10b7dee0 100644
--- a/packages/pieces/community/convertkit/src/i18n/translation.json
+++ b/packages/pieces/community/convertkit/src/i18n/translation.json
@@ -1,6 +1,6 @@
{
"Email marketing for creators": "Email marketing for creators",
- "Enter your API Secret key": "Enter your API Secret key",
+ "Enter your API Secret key. In Kit, go to Settings > Developer, open the V3 Key section and copy the API Secret.": "Enter your API Secret key. In Kit, go to Settings > Developer, open the V3 Key section and copy the API Secret.",
"Get Subscriber By Id": "Get Subscriber By Id",
"Get Subscriber By Email": "Get Subscriber By Email",
"List Subscribers": "List Subscribers",
@@ -36,6 +36,20 @@
"Get Purchase By Id": "Get Purchase By Id",
"Create Purchase": "Create Purchase",
"Create Multiple Purchases": "Create Multiple Purchases",
+ "Get Account": "Get Account",
+ "Get Subscriber": "Get Subscriber",
+ "Remove Tag By Email": "Remove Tag By Email",
+ "Remove Tag From Subscriber": "Remove Tag From Subscriber",
+ "List Tag Subscriptions": "List Tag Subscriptions",
+ "Get Broadcast Stats": "Get Broadcast Stats",
+ "Update Custom Field": "Update Custom Field",
+ "Delete Custom Field": "Delete Custom Field",
+ "Create Webhook": "Create Webhook",
+ "List Webhooks": "List Webhooks",
+ "List Sequence Subscriptions": "List Sequence Subscriptions",
+ "List Subscriber Tags": "List Subscriber Tags",
+ "Get Purchase": "Get Purchase",
+ "Custom API Call": "Custom API Call",
"Returns data for a single subscriber": "Returns data for a single subscriber",
"Returns a list of all subscribers": "Returns a list of all subscribers",
"Update a subscriber": "Update a subscriber",
@@ -69,6 +83,40 @@
"Returns data for a single purchase": "Returns data for a single purchase",
"Creates a new purchase": "Creates a new purchase",
"Creates multiple purchases": "Creates multiple purchases",
+ "Get the name and primary email address of the connected Kit account.": "Get the name and primary email address of the connected Kit account.",
+ "List or search subscribers, 50 per page.": "List or search subscribers, 50 per page.",
+ "Get one subscriber by subscriber ID.": "Get one subscriber by subscriber ID.",
+ "Update the email, first name or custom fields of a subscriber.": "Update the email, first name or custom fields of a subscriber.",
+ "Unsubscribe an email address from all forms and sequences.": "Unsubscribe an email address from all forms and sequences.",
+ "List the tags on the account.": "List the tags on the account.",
+ "Create a tag, or return the existing tag with the same name.": "Create a tag, or return the existing tag with the same name.",
+ "Apply a tag to a subscriber by email, creating the subscriber if needed.": "Apply a tag to a subscriber by email, creating the subscriber if needed.",
+ "Remove a tag from a subscriber identified by email.": "Remove a tag from a subscriber identified by email.",
+ "Remove a tag from a subscriber identified by subscriber ID.": "Remove a tag from a subscriber identified by subscriber ID.",
+ "List the subscribers who have a tag, 50 per page.": "List the subscribers who have a tag, 50 per page.",
+ "List the forms and landing pages on the account.": "List the forms and landing pages on the account.",
+ "Subscribe an email address to a form, creating the subscriber if needed.": "Subscribe an email address to a form, creating the subscriber if needed.",
+ "List the subscribers who signed up through a form, 50 per page.": "List the subscribers who signed up through a form, 50 per page.",
+ "List the email sequences on the account.": "List the email sequences on the account.",
+ "List broadcasts (one-off emails), 50 per page.": "List broadcasts (one-off emails), 50 per page.",
+ "Get the content and settings of one broadcast.": "Get the content and settings of one broadcast.",
+ "Get delivery and engagement stats for one broadcast.": "Get delivery and engagement stats for one broadcast.",
+ "Create a broadcast email, as a draft or scheduled.": "Create a broadcast email, as a draft or scheduled.",
+ "Permanently delete a broadcast.": "Permanently delete a broadcast.",
+ "List the custom subscriber fields defined on the account.": "List the custom subscriber fields defined on the account.",
+ "Create a custom subscriber field.": "Create a custom subscriber field.",
+ "Rename a custom subscriber field.": "Rename a custom subscriber field.",
+ "Permanently delete a custom subscriber field and its values.": "Permanently delete a custom subscriber field and its values.",
+ "Register a webhook that Kit calls when an event happens.": "Register a webhook that Kit calls when an event happens.",
+ "Delete a webhook automation by its rule ID.": "Delete a webhook automation by its rule ID.",
+ "List the webhook automations registered on the Kit account.": "List the webhook automations registered on the Kit account.",
+ "Change fields on an existing broadcast. Fields left empty are not changed.": "Change fields on an existing broadcast. Fields left empty are not changed.",
+ "Enroll an email address in a sequence, creating the subscriber if needed.": "Enroll an email address in a sequence, creating the subscriber if needed.",
+ "List the subscribers enrolled in a sequence, 50 per page.": "List the subscribers enrolled in a sequence, 50 per page.",
+ "List the tags applied to one subscriber.": "List the tags applied to one subscriber.",
+ "List the purchases recorded in the account, 50 per page.": "List the purchases recorded in the account, 50 per page.",
+ "Get one purchase by purchase ID.": "Get one purchase by purchase ID.",
+ "Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",
"Subscriber ID": "Subscriber ID",
"Email": "Email",
"Page": "Page",
@@ -120,6 +168,34 @@
"Unit Price": "Unit Price",
"Quantity": "Quantity",
"Products": "Products",
+ "Created From": "Created From",
+ "Created To": "Created To",
+ "New Email Address": "New Email Address",
+ "Tag ID": "Tag ID",
+ "Additional Tag IDs": "Additional Tag IDs",
+ "Form ID": "Form ID",
+ "Tag IDs": "Tag IDs",
+ "Broadcast ID": "Broadcast ID",
+ "Internal Description": "Internal Description",
+ "From Email Address": "From Email Address",
+ "Email Template Name": "Email Template Name",
+ "Publish As Web Post": "Publish As Web Post",
+ "Thumbnail URL": "Thumbnail URL",
+ "Thumbnail Alt Text": "Thumbnail Alt Text",
+ "Label": "Label",
+ "Custom Field ID": "Custom Field ID",
+ "Sequence ID": "Sequence ID",
+ "Link URL": "Link URL",
+ "Rule ID": "Rule ID",
+ "Method": "Method",
+ "Headers": "Headers",
+ "Query Parameters": "Query Parameters",
+ "Body Type": "Body Type",
+ "Body": "Body",
+ "Response is Binary": "Response is Binary",
+ "Return Error as Output": "Return Error as Output",
+ "Timeout": "Timeout",
+ "Follow redirects": "Follow redirects",
"The subscriber ID": "The subscriber ID",
"The email of the subscriber": "The email of the subscriber",
"Page number. Each page of results will contain up to 50 subscribers.": "Page number. Each page of results will contain up to 50 subscribers.",
@@ -173,6 +249,78 @@
"The unit price of the product": "The unit price of the product",
"The quantity of the product": "The quantity of the product",
"The products": "The products",
+ "Only return the subscriber with this email address.": "Only return the subscriber with this email address.",
+ "Only subscribers added on or after this date. Format yyyy-mm-dd.": "Only subscribers added on or after this date. Format yyyy-mm-dd.",
+ "Only subscribers added on or before this date. Format yyyy-mm-dd.": "Only subscribers added on or before this date. Format yyyy-mm-dd.",
+ "Only subscribers updated after this date. Format yyyy-mm-dd.": "Only subscribers updated after this date. Format yyyy-mm-dd.",
+ "Only subscribers updated before this date. Format yyyy-mm-dd.": "Only subscribers updated before this date. Format yyyy-mm-dd.",
+ "Page number, 50 subscribers per page. Defaults to 1.": "Page number, 50 subscribers per page. Defaults to 1.",
+ "Sort direction. Kit defaults to ascending.": "Sort direction. Kit defaults to ascending.",
+ "Set to Cancelled At to list cancelled subscribers, sorted by cancellation date.": "Set to Cancelled At to list cancelled subscribers, sorted by cancellation date.",
+ "The subscriber ID, from List Subscribers.": "The subscriber ID, from List Subscribers.",
+ "Change the subscriber email address.": "Change the subscriber email address.",
+ "The first name to store on the subscriber.": "The first name to store on the subscriber.",
+ "A JSON object of custom field key to value, e.g. {\"last_name\": \"Snow\"}. Keys must already exist; get them from List Custom Fields.": "A JSON object of custom field key to value, e.g. {\"last_name\": \"Snow\"}. Keys must already exist; get them from List Custom Fields.",
+ "The email address to unsubscribe.": "The email address to unsubscribe.",
+ "The tag name.": "The tag name.",
+ "The tag to apply, from List Tags or Create Tag.": "The tag to apply, from List Tags or Create Tag.",
+ "The subscriber email address.": "The subscriber email address.",
+ "More tag IDs to apply in the same call.": "More tag IDs to apply in the same call.",
+ "The tag to remove, from List Tags.": "The tag to remove, from List Tags.",
+ "The subscriber ID, from List Subscribers or Get Subscriber.": "The subscriber ID, from List Subscribers or Get Subscriber.",
+ "The tag ID, from List Tags.": "The tag ID, from List Tags.",
+ "Page number, 50 subscriptions per page. Defaults to 1.": "Page number, 50 subscriptions per page. Defaults to 1.",
+ "Sort by tagging date. Kit defaults to ascending (oldest first).": "Sort by tagging date. Kit defaults to ascending (oldest first).",
+ "Return only active or only cancelled subscriptions. Leave empty for the Kit default.": "Return only active or only cancelled subscriptions. Leave empty for the Kit default.",
+ "The form ID, from List Forms.": "The form ID, from List Forms.",
+ "The email address to subscribe.": "The email address to subscribe.",
+ "Optional tag IDs to apply as well, from List Tags.": "Optional tag IDs to apply as well, from List Tags.",
+ "Sort by subscription date. Kit defaults to ascending (oldest first).": "Sort by subscription date. Kit defaults to ascending (oldest first).",
+ "Page number, 50 broadcasts per page. Defaults to 1.": "Page number, 50 broadcasts per page. Defaults to 1.",
+ "Sort by creation date. Kit defaults to ascending (oldest first).": "Sort by creation date. Kit defaults to ascending (oldest first).",
+ "The broadcast ID, from List Broadcasts.": "The broadcast ID, from List Broadcasts.",
+ "The email subject line.": "The email subject line.",
+ "The email body. Plain text or simple HTML (p, h1, img, a).": "The email body. Plain text or simple HTML (p, h1, img, a).",
+ "An internal note, not shown to subscribers.": "An internal note, not shown to subscribers.",
+ "Sending address. Leave empty to use the account default.": "Sending address. Leave empty to use the account default.",
+ "Name of the email template. Leave empty to use the account default.": "Name of the email template. Leave empty to use the account default.",
+ "When to send, as an ISO 8601 date-time in the future. Leave empty to keep a draft. Setting it schedules a real send.": "When to send, as an ISO 8601 date-time in the future. Leave empty to keep a draft. Setting it schedules a real send.",
+ "Also publish the broadcast on the Creator Profile web page.": "Also publish the broadcast on the Creator Profile web page.",
+ "Publication time shown on the web post. Only used when publishing as a web post.": "Publication time shown on the web post. Only used when publishing as a web post.",
+ "Image URL for the web post thumbnail.": "Image URL for the web post thumbnail.",
+ "Alt text for the web post thumbnail.": "Alt text for the web post thumbnail.",
+ "The field label, e.g. \"Company\". Must be unique on the account.": "The field label, e.g. \"Company\". Must be unique on the account.",
+ "The field ID, from List Custom Fields.": "The field ID, from List Custom Fields.",
+ "The new label. Must be unique on the account.": "The new label. Must be unique on the account.",
+ "The public https:// URL Kit will POST the event payload to.": "The public https:// URL Kit will POST the event payload to.",
+ "The event that fires the webhook.": "The event that fires the webhook.",
+ "Required for the Form subscribed event. Get it from List Forms.": "Required for the Form subscribed event. Get it from List Forms.",
+ "Required for the Sequence subscribed and Sequence completed events. Get it from List Sequences.": "Required for the Sequence subscribed and Sequence completed events. Get it from List Sequences.",
+ "Required for the Tag added and Tag removed events. Get it from List Tags.": "Required for the Tag added and Tag removed events. Get it from List Tags.",
+ "Required for the Product purchased event.": "Required for the Product purchased event.",
+ "Required for the Link clicked event: the link URL to watch.": "Required for the Link clicked event: the link URL to watch.",
+ "The webhook rule ID, from Create Webhook or List Webhooks.": "The webhook rule ID, from Create Webhook or List Webhooks.",
+ "New email subject line.": "New email subject line.",
+ "New email body. Plain text or simple HTML (p, h1, img, a).": "New email body. Plain text or simple HTML (p, h1, img, a).",
+ "New internal note, not shown to subscribers.": "New internal note, not shown to subscribers.",
+ "New sending address. It must be a confirmed sender in Kit.": "New sending address. It must be a confirmed sender in Kit.",
+ "New email template name.": "New email template name.",
+ "Schedule a real send at this ISO 8601 date-time, which must be in the future. Leave empty to keep the current schedule.": "Schedule a real send at this ISO 8601 date-time, which must be in the future. Leave empty to keep the current schedule.",
+ "Change web post visibility. Leave empty to keep it as it is.": "Change web post visibility. Leave empty to keep it as it is.",
+ "New publication time shown on the web post.": "New publication time shown on the web post.",
+ "New image URL for the web post thumbnail.": "New image URL for the web post thumbnail.",
+ "New alt text for the web post thumbnail.": "New alt text for the web post thumbnail.",
+ "The sequence ID, from List Sequences.": "The sequence ID, from List Sequences.",
+ "The email address to enroll.": "The email address to enroll.",
+ "Sort by enrollment date. Kit defaults to ascending (oldest first).": "Sort by enrollment date. Kit defaults to ascending (oldest first).",
+ "Page number, 50 purchases per page. Defaults to 1.": "Page number, 50 purchases per page. Defaults to 1.",
+ "The Kit purchase ID, from List Purchases.": "The Kit purchase ID, from List Purchases.",
+ "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.",
"Ascending": "Ascending",
"Descending": "Descending",
"Subscriber activated": "Subscriber activated",
@@ -188,7 +336,7 @@
"Tag removed from subscriber": "Tag removed from subscriber",
"Purchase created": "Purchase created",
"Active": "Active",
- "canceled": "canceled",
+ "Cancelled": "Cancelled",
"paid": "paid",
"pending": "pending",
"failed": "failed",
@@ -222,6 +370,17 @@
"AED": "AED",
"SAR": "SAR",
"ZAR": "ZAR",
+ "Ascending (oldest first)": "Ascending (oldest first)",
+ "Descending (newest first)": "Descending (newest first)",
+ "Cancelled At": "Cancelled At",
+ "Publish as web post": "Publish as web post",
+ "Do not publish as web post": "Do not publish as web post",
+ "GET": "GET",
+ "POST": "POST",
+ "PATCH": "PATCH",
+ "PUT": "PUT",
+ "DELETE": "DELETE",
+ "HEAD": "HEAD",
"Trigger when a tag is added to a subscriber": "Trigger when a tag is added to a subscriber",
"Trigger when a tag is removed from a subscriber": "Trigger when a tag is removed from a subscriber",
"Trigger when a subscriber is activated. This happens when a subscriber confirms their subscription.": "Trigger when a subscriber is activated. This happens when a subscriber confirms their subscription.",
diff --git a/packages/pieces/community/convertkit/src/index.ts b/packages/pieces/community/convertkit/src/index.ts
index c00772f92e9..854ceade8a8 100644
--- a/packages/pieces/community/convertkit/src/index.ts
+++ b/packages/pieces/community/convertkit/src/index.ts
@@ -1,4 +1,8 @@
-import { createPiece, PieceAuth } from '@activepieces/pieces-framework';
+import { createPiece } from '@activepieces/pieces-framework';
+import { createCustomApiCallAction } from '@activepieces/pieces-common';
+import { convertkitAuth } from './lib/auth';
+import { assertKitUrl } from './lib/common/custom-api-guard';
+import { CONVERTKIT_API_URL } from './lib/common/constants';
import {
createField,
deleteField,
@@ -54,6 +58,39 @@ import {
listPurchases,
} from './lib/actions/purchases';
+import { kitUpdateBroadcast } from './lib/actions/ai/update-broadcast';
+import { kitAddSubscriberToSequence } from './lib/actions/ai/add-subscriber-to-sequence';
+import { kitListSequenceSubscriptions } from './lib/actions/ai/list-sequence-subscriptions';
+import { kitListSubscriberTags } from './lib/actions/ai/list-subscriber-tags';
+import { kitListPurchases } from './lib/actions/ai/list-purchases';
+import { kitGetPurchase } from './lib/actions/ai/get-purchase';
+import { kitGetAccount } from './lib/actions/ai/get-account';
+import { kitListSubscribers } from './lib/actions/ai/list-subscribers';
+import { kitGetSubscriber } from './lib/actions/ai/get-subscriber';
+import { kitUpdateSubscriber } from './lib/actions/ai/update-subscriber';
+import { kitUnsubscribeSubscriber } from './lib/actions/ai/unsubscribe-subscriber';
+import { kitListTags } from './lib/actions/ai/list-tags';
+import { kitCreateTag } from './lib/actions/ai/create-tag';
+import { kitTagSubscriber } from './lib/actions/ai/tag-subscriber';
+import { kitRemoveTagByEmail } from './lib/actions/ai/remove-tag-by-email';
+import { kitRemoveTagFromSubscriber } from './lib/actions/ai/remove-tag-from-subscriber';
+import { kitListTagSubscriptions } from './lib/actions/ai/list-tag-subscriptions';
+import { kitListForms } from './lib/actions/ai/list-forms';
+import { kitAddSubscriberToForm } from './lib/actions/ai/add-subscriber-to-form';
+import { kitListFormSubscriptions } from './lib/actions/ai/list-form-subscriptions';
+import { kitListSequences } from './lib/actions/ai/list-sequences';
+import { kitListBroadcasts } from './lib/actions/ai/list-broadcasts';
+import { kitGetBroadcast } from './lib/actions/ai/get-broadcast';
+import { kitGetBroadcastStats } from './lib/actions/ai/get-broadcast-stats';
+import { kitCreateBroadcast } from './lib/actions/ai/create-broadcast';
+import { kitDeleteBroadcast } from './lib/actions/ai/delete-broadcast';
+import { kitListCustomFields } from './lib/actions/ai/list-custom-fields';
+import { kitCreateCustomField } from './lib/actions/ai/create-custom-field';
+import { kitUpdateCustomField } from './lib/actions/ai/update-custom-field';
+import { kitDeleteCustomField } from './lib/actions/ai/delete-custom-field';
+import { kitCreateWebhook } from './lib/actions/ai/create-webhook';
+import { kitDeleteWebhook } from './lib/actions/ai/delete-webhook';
+import { kitListWebhooks } from './lib/actions/ai/list-webhooks';
import { PieceCategory } from '@activepieces/pieces-framework';
import {
addTag,
@@ -70,18 +107,12 @@ import {
subscriberUnsubscribed,
} from './lib/triggers';
-export const convertkitAuth = PieceAuth.SecretText({
- displayName: 'API Secret',
- description: 'Enter your API Secret key',
- required: true,
-});
-
export const convertkit = createPiece({
displayName: 'ConvertKit',
description: 'Email marketing for creators',
auth: convertkitAuth,
- minimumSupportedRelease: '0.30.0',
+ minimumSupportedRelease: '0.88.2',
logoUrl: 'https://cdn.activepieces.com/pieces/convertkit.png',
categories: [PieceCategory.MARKETING],
authors: ["Gunther-Schulz","kishanprmr","abuaboud"],
@@ -121,6 +152,48 @@ export const convertkit = createPiece({
getPurchaseById,
createSinglePurchase,
createPurchases,
+ kitGetAccount,
+ kitListSubscribers,
+ kitGetSubscriber,
+ kitUpdateSubscriber,
+ kitUnsubscribeSubscriber,
+ kitListTags,
+ kitCreateTag,
+ kitTagSubscriber,
+ kitRemoveTagByEmail,
+ kitRemoveTagFromSubscriber,
+ kitListTagSubscriptions,
+ kitListForms,
+ kitAddSubscriberToForm,
+ kitListFormSubscriptions,
+ kitListSequences,
+ kitListBroadcasts,
+ kitGetBroadcast,
+ kitGetBroadcastStats,
+ kitCreateBroadcast,
+ kitDeleteBroadcast,
+ kitListCustomFields,
+ kitCreateCustomField,
+ kitUpdateCustomField,
+ kitDeleteCustomField,
+ kitCreateWebhook,
+ kitDeleteWebhook,
+ kitListWebhooks,
+ kitUpdateBroadcast,
+ kitAddSubscriberToSequence,
+ kitListSequenceSubscriptions,
+ kitListSubscriberTags,
+ kitListPurchases,
+ kitGetPurchase,
+ createCustomApiCallAction({
+ baseUrl: () => CONVERTKIT_API_URL,
+ auth: convertkitAuth,
+ authLocation: 'queryParams',
+ authMapping: async (auth, propsValue) => {
+ assertKitUrl(propsValue);
+ return { api_secret: auth.secret_text };
+ },
+ }),
],
triggers: [
addTag,
@@ -137,3 +210,5 @@ export const convertkit = createPiece({
purchaseCreated,
],
});
+
+export { convertkitAuth };
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/add-subscriber-to-form.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/add-subscriber-to-form.ts
new file mode 100644
index 00000000000..23a25cdc16a
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/add-subscriber-to-form.ts
@@ -0,0 +1,44 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient, kitCommon } from '../../common/client';
+import { kitProps } from '../../common/ai-props';
+import { Subscription } from '../../common/types';
+import { kitSubscriptionOutputSchema } from '../../output-schemas';
+
+export const kitAddSubscriberToForm = createAction({
+ auth: convertkitAuth,
+ name: 'kit_add_subscriber_to_form',
+ classification: 'WRITE',
+ outputSchema: kitSubscriptionOutputSchema,
+ displayName: 'Add Subscriber To Form',
+ description: 'Subscribe an email address to a form, creating the subscriber if needed.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Subscribes an email to a form, creating the subscriber if missing, and can set first name, custom fields and extra tags. This is the main way to add a subscriber. Each call can send the form double opt-in or incentive email and may reactivate an address that unsubscribed, so only use it with consent; retries can resend that email. To act on a subscriber ID, get the email with Get Subscriber first.',
+ idempotent: false,
+ },
+ props: {
+ form_id: kitProps.id('Form ID', 'The form ID, from List Forms.'),
+ email: kitProps.email('The email address to subscribe.'),
+ first_name: kitProps.firstName,
+ fields: kitProps.fields,
+ tag_ids: kitProps.tagIds('Tag IDs', 'Optional tag IDs to apply as well, from List Tags.'),
+ },
+ async run(context) {
+ const { form_id, email, first_name, fields, tag_ids } = context.propsValue;
+ const response = await kitClient.request<{ subscription: Subscription }>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.POST,
+ path: `/forms/${kitCommon.id({ value: form_id, label: 'Form ID' })}/subscribe`,
+ body: kitCommon.compact({
+ email: kitCommon.email({ value: email, label: 'Email' }),
+ first_name,
+ fields: kitCommon.toFields(fields),
+ tags: kitCommon.toIdList(tag_ids),
+ }),
+ });
+ return response.body.subscription;
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/add-subscriber-to-sequence.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/add-subscriber-to-sequence.ts
new file mode 100644
index 00000000000..6d9995c23c8
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/add-subscriber-to-sequence.ts
@@ -0,0 +1,44 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient, kitCommon } from '../../common/client';
+import { kitProps } from '../../common/ai-props';
+import { Subscription } from '../../common/types';
+import { kitSubscriptionOutputSchema } from '../../output-schemas';
+
+export const kitAddSubscriberToSequence = createAction({
+ auth: convertkitAuth,
+ name: 'kit_add_subscriber_to_sequence',
+ classification: 'WRITE',
+ outputSchema: kitSubscriptionOutputSchema,
+ displayName: 'Add Subscriber To Sequence',
+ description: 'Enroll an email address in a sequence, creating the subscriber if needed.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Enrolls an email in a sequence, creating the subscriber if missing, and can set first name, custom fields and extra tags. This starts the sequence emails for that person and may reactivate an address that unsubscribed, so only use it with consent. Enrolling the same email again does not create a second enrollment. Get the sequence ID from List Sequences.',
+ idempotent: true,
+ },
+ props: {
+ sequence_id: kitProps.id('Sequence ID', 'The sequence ID, from List Sequences.'),
+ email: kitProps.email('The email address to enroll.'),
+ first_name: kitProps.firstName,
+ fields: kitProps.fields,
+ tag_ids: kitProps.tagIds('Tag IDs', 'Optional tag IDs to apply as well, from List Tags.'),
+ },
+ async run(context) {
+ const { sequence_id, email, first_name, fields, tag_ids } = context.propsValue;
+ const response = await kitClient.request<{ subscription: Subscription }>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.POST,
+ path: `/sequences/${kitCommon.id({ value: sequence_id, label: 'Sequence ID' })}/subscribe`,
+ body: kitCommon.compact({
+ email: kitCommon.email({ value: email, label: 'Email' }),
+ first_name,
+ fields: kitCommon.toFields(fields),
+ tags: kitCommon.toIdList(tag_ids),
+ }),
+ });
+ return response.body.subscription;
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/create-broadcast.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/create-broadcast.ts
new file mode 100644
index 00000000000..cf697d85d06
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/create-broadcast.ts
@@ -0,0 +1,99 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient, kitCommon } from '../../common/client';
+import { Broadcast } from '../../common/types';
+import { kitBroadcastOutputSchema } from '../../output-schemas';
+
+export const kitCreateBroadcast = createAction({
+ auth: convertkitAuth,
+ name: 'kit_create_broadcast',
+ classification: 'WRITE',
+ outputSchema: kitBroadcastOutputSchema,
+ displayName: 'Create Broadcast',
+ description: 'Create a broadcast email, as a draft or scheduled.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates a broadcast email. Without Send At it is saved as an unsent draft; setting Send At schedules a real send to the account subscribers at that time, with no segment targeting on this endpoint. Public only publishes it as a web post. Each call creates another broadcast.',
+ idempotent: false,
+ },
+ props: {
+ subject: Property.ShortText({
+ displayName: 'Subject',
+ description: 'The email subject line.',
+ required: false,
+ }),
+ content: Property.LongText({
+ displayName: 'Content',
+ description: 'The email body. Plain text or simple HTML (p, h1, img, a).',
+ required: false,
+ }),
+ description: Property.ShortText({
+ displayName: 'Internal Description',
+ description: 'An internal note, not shown to subscribers.',
+ required: false,
+ }),
+ email_address: Property.ShortText({
+ displayName: 'From Email Address',
+ description: 'Sending address. Leave empty to use the account default.',
+ required: false,
+ }),
+ email_layout_template: Property.ShortText({
+ displayName: 'Email Template Name',
+ description: 'Name of the email template. Leave empty to use the account default.',
+ required: false,
+ }),
+ send_at: Property.DateTime({
+ displayName: 'Send At',
+ description:
+ 'When to send, as an ISO 8601 date-time in the future. Leave empty to keep a draft. Setting it schedules a real send.',
+ required: false,
+ }),
+ public: Property.Checkbox({
+ displayName: 'Publish As Web Post',
+ description: 'Also publish the broadcast on the Creator Profile web page.',
+ required: false,
+ }),
+ published_at: Property.DateTime({
+ displayName: 'Published At',
+ description: 'Publication time shown on the web post. Only used when publishing as a web post.',
+ required: false,
+ }),
+ thumbnail_url: Property.ShortText({
+ displayName: 'Thumbnail URL',
+ description: 'Image URL for the web post thumbnail.',
+ required: false,
+ }),
+ thumbnail_alt: Property.ShortText({
+ displayName: 'Thumbnail Alt Text',
+ description: 'Alt text for the web post thumbnail.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const props = context.propsValue;
+ const body = kitCommon.compact({
+ subject: props.subject,
+ content: props.content,
+ description: props.description,
+ email_address:
+ props.email_address === undefined || props.email_address === null || props.email_address.trim() === ''
+ ? undefined
+ : kitCommon.email({ value: props.email_address, label: 'From Email Address' }),
+ email_layout_template: props.email_layout_template,
+ send_at: kitCommon.toDateTime({ value: props.send_at, label: 'Send At', future: true }),
+ public: props.public === true ? true : undefined,
+ published_at: kitCommon.toDateTime({ value: props.published_at, label: 'Published At' }),
+ thumbnail_url: props.thumbnail_url,
+ thumbnail_alt: props.thumbnail_alt,
+ });
+ const response = await kitClient.request<{ broadcast: Broadcast }>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.POST,
+ path: '/broadcasts',
+ body,
+ });
+ return response.body.broadcast;
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/create-custom-field.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/create-custom-field.ts
new file mode 100644
index 00000000000..0e36cee7de9
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/create-custom-field.ts
@@ -0,0 +1,41 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient } from '../../common/client';
+import { CustomField } from '../../common/types';
+import { kitCustomFieldOutputSchema } from '../../output-schemas';
+
+export const kitCreateCustomField = createAction({
+ auth: convertkitAuth,
+ name: 'kit_create_custom_field',
+ classification: 'WRITE',
+ outputSchema: kitCustomFieldOutputSchema,
+ displayName: 'Create Custom Field',
+ description: 'Create a custom subscriber field.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates one custom subscriber field from a label; Kit derives its key (lowercase, underscored) and returns it. Labels must be unique and the account allows at most 140 fields. Check List Custom Fields first, because a retry with an existing label fails.',
+ idempotent: false,
+ },
+ props: {
+ label: Property.ShortText({
+ displayName: 'Label',
+ description: 'The field label, e.g. "Company". Must be unique on the account.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const label = context.propsValue.label.trim();
+ if (!label) {
+ throw new Error('Label cannot be empty.');
+ }
+ const response = await kitClient.request<CustomField>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.POST,
+ path: '/custom_fields',
+ body: { label },
+ });
+ return response.body;
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/create-tag.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/create-tag.ts
new file mode 100644
index 00000000000..b1c95611c77
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/create-tag.ts
@@ -0,0 +1,52 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient } from '../../common/client';
+import { Tag } from '../../common/types';
+import { kitCreateTagOutputSchema } from '../../output-schemas';
+
+export const kitCreateTag = createAction({
+ auth: convertkitAuth,
+ name: 'kit_create_tag',
+ classification: 'WRITE',
+ outputSchema: kitCreateTagOutputSchema,
+ displayName: 'Create Tag',
+ description: 'Create a tag, or return the existing tag with the same name.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Gets or creates a tag by name: if a tag with the same name exists (case-insensitive) it is returned with created false, otherwise a new tag is created with created true. Safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ name: Property.ShortText({
+ displayName: 'Name',
+ description: 'The tag name.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const name = context.propsValue.name.trim();
+ if (!name) {
+ throw new Error('Tag name cannot be empty.');
+ }
+ const existing = await kitClient.request<{ tags: Tag[] }>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: '/tags',
+ });
+ const match = (existing.body.tags ?? []).find(
+ (tag) => tag.name.trim().toLowerCase() === name.toLowerCase()
+ );
+ if (match) {
+ return { ...match, created: false };
+ }
+ const response = await kitClient.request<Tag>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.POST,
+ path: '/tags',
+ body: { tag: { name } },
+ });
+ return { ...response.body, created: true };
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/create-webhook.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/create-webhook.ts
new file mode 100644
index 00000000000..880981ebb3a
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/create-webhook.ts
@@ -0,0 +1,107 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient } from '../../common/client';
+import { createWebhookParameterOptions } from '../../common/webhooks';
+import { Webhook } from '../../common/types';
+import { kitWebhookOutputSchema } from '../../output-schemas';
+
+const numericParameters = ['form_id', 'sequence_id', 'tag_id', 'product_id'];
+
+export const kitCreateWebhook = createAction({
+ auth: convertkitAuth,
+ name: 'kit_create_webhook',
+ classification: 'WRITE',
+ outputSchema: kitWebhookOutputSchema,
+ displayName: 'Create Webhook',
+ description: 'Register a webhook that Kit calls when an event happens.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Registers a webhook rule that POSTs to a target URL when the chosen event fires. Form, sequence, tag, product and link-click events need their matching parameter (Form ID, Sequence ID, Tag ID, Product ID or Link URL). Each call registers another rule, so check List Webhooks first and keep the returned rule ID for Delete Webhook.',
+ idempotent: false,
+ },
+ props: {
+ target_url: Property.ShortText({
+ displayName: 'Target URL',
+ description: 'The public https:// URL Kit will POST the event payload to.',
+ required: true,
+ }),
+ event: Property.StaticDropdown({
+ displayName: 'Event',
+ description: 'The event that fires the webhook.',
+ required: true,
+ options: {
+ options: createWebhookParameterOptions.map((option) => ({
+ label: option.label,
+ value: option.value,
+ })),
+ },
+ }),
+ form_id: Property.Number({
+ displayName: 'Form ID',
+ description: 'Required for the Form subscribed event. Get it from List Forms.',
+ required: false,
+ }),
+ sequence_id: Property.Number({
+ displayName: 'Sequence ID',
+ description:
+ 'Required for the Sequence subscribed and Sequence completed events. Get it from List Sequences.',
+ required: false,
+ }),
+ tag_id: Property.Number({
+ displayName: 'Tag ID',
+ description:
+ 'Required for the Tag added and Tag removed events. Get it from List Tags.',
+ required: false,
+ }),
+ product_id: Property.Number({
+ displayName: 'Product ID',
+ description: 'Required for the Product purchased event.',
+ required: false,
+ }),
+ initiator_value: Property.ShortText({
+ displayName: 'Link URL',
+ description: 'Required for the Link clicked event: the link URL to watch.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const { event } = context.propsValue;
+ const target_url = context.propsValue.target_url.trim();
+ if (!/^https:\/\/[^\s/]+\.[^\s]+$/i.test(target_url)) {
+ throw new Error(`Target URL must be a public https:// URL, got "${context.propsValue.target_url}".`);
+ }
+ const option = createWebhookParameterOptions.find((item) => item.value === event);
+ if (!option) {
+ throw new Error(`Unknown event "${String(event)}".`);
+ }
+ const eventBody: Record<string, unknown> = { name: event };
+ const parameter = option.required_parameter;
+ if (parameter) {
+ const propValues: Record<string, unknown> = { ...context.propsValue };
+ const raw = propValues[parameter];
+ if (raw === undefined || raw === null || raw === '') {
+ throw new Error(
+ `The "${option.label}" event requires ${option.param_label ?? parameter}.`
+ );
+ }
+ if (numericParameters.includes(parameter)) {
+ const id = Number(raw);
+ if (!Number.isInteger(id)) {
+ throw new Error(`${option.param_label ?? parameter} must be a whole number.`);
+ }
+ eventBody[parameter] = id;
+ } else {
+ eventBody[parameter] = String(raw);
+ }
+ }
+ const response = await kitClient.request<{ rule: Webhook }>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.POST,
+ path: '/automations/hooks',
+ body: { target_url, event: eventBody },
+ });
+ return response.body.rule;
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/delete-broadcast.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/delete-broadcast.ts
new file mode 100644
index 00000000000..e9d36734be4
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/delete-broadcast.ts
@@ -0,0 +1,33 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient, kitCommon } from '../../common/client';
+import { kitProps } from '../../common/ai-props';
+import { kitDeleteBroadcastOutputSchema } from '../../output-schemas';
+
+export const kitDeleteBroadcast = createAction({
+ auth: convertkitAuth,
+ name: 'kit_delete_broadcast',
+ classification: 'DESTRUCTIVE',
+ outputSchema: kitDeleteBroadcastOutputSchema,
+ displayName: 'Delete Broadcast',
+ description: 'Permanently delete a broadcast.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Permanently deletes a draft or scheduled broadcast by ID; a scheduled one will not be sent. It cannot be undone, and a repeat call fails once the broadcast is gone. Confirm the ID with Get Broadcast first.',
+ idempotent: false,
+ },
+ props: {
+ broadcast_id: kitProps.id('Broadcast ID', 'The broadcast ID, from List Broadcasts.'),
+ },
+ async run(context) {
+ const broadcastId = kitCommon.id({ value: context.propsValue.broadcast_id, label: 'Broadcast ID' });
+ await kitClient.request<unknown>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.DELETE,
+ path: `/broadcasts/${broadcastId}`,
+ });
+ return { success: true, broadcast_id: broadcastId };
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/delete-custom-field.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/delete-custom-field.ts
new file mode 100644
index 00000000000..805c2773868
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/delete-custom-field.ts
@@ -0,0 +1,33 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient, kitCommon } from '../../common/client';
+import { kitProps } from '../../common/ai-props';
+import { kitDeleteCustomFieldOutputSchema } from '../../output-schemas';
+
+export const kitDeleteCustomField = createAction({
+ auth: convertkitAuth,
+ name: 'kit_delete_custom_field',
+ classification: 'DESTRUCTIVE',
+ outputSchema: kitDeleteCustomFieldOutputSchema,
+ displayName: 'Delete Custom Field',
+ description: 'Permanently delete a custom subscriber field and its values.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Permanently deletes a custom field by ID, erasing its stored value on every subscriber. It cannot be undone, and a repeat call fails once the field is gone.',
+ idempotent: false,
+ },
+ props: {
+ custom_field_id: kitProps.id('Custom Field ID', 'The field ID, from List Custom Fields.'),
+ },
+ async run(context) {
+ const fieldId = kitCommon.id({ value: context.propsValue.custom_field_id, label: 'Custom Field ID' });
+ await kitClient.request<unknown>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.DELETE,
+ path: `/custom_fields/${fieldId}`,
+ });
+ return { success: true, custom_field_id: fieldId };
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/delete-webhook.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/delete-webhook.ts
new file mode 100644
index 00000000000..f52eff66e99
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/delete-webhook.ts
@@ -0,0 +1,33 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient, kitCommon } from '../../common/client';
+import { kitProps } from '../../common/ai-props';
+import { kitDeleteWebhookOutputSchema } from '../../output-schemas';
+
+export const kitDeleteWebhook = createAction({
+ auth: convertkitAuth,
+ name: 'kit_delete_webhook',
+ classification: 'DESTRUCTIVE',
+ outputSchema: kitDeleteWebhookOutputSchema,
+ displayName: 'Delete Webhook',
+ description: 'Delete a webhook automation by its rule ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Deletes a webhook rule by its rule ID, from Create Webhook or List Webhooks. Kit stops calling the target URL immediately. A repeat call fails once the rule is gone.',
+ idempotent: false,
+ },
+ props: {
+ rule_id: kitProps.id('Rule ID', 'The webhook rule ID, from Create Webhook or List Webhooks.'),
+ },
+ async run(context) {
+ const ruleId = kitCommon.id({ value: context.propsValue.rule_id, label: 'Rule ID' });
+ const response = await kitClient.request<{ success?: boolean }>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.DELETE,
+ path: `/automations/hooks/${ruleId}`,
+ });
+ return { success: response.body?.success ?? true, rule_id: ruleId };
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/get-account.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/get-account.ts
new file mode 100644
index 00000000000..4f7fa606418
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/get-account.ts
@@ -0,0 +1,29 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient } from '../../common/client';
+import { kitGetAccountOutputSchema } from '../../output-schemas';
+
+export const kitGetAccount = createAction({
+ auth: convertkitAuth,
+ name: 'kit_get_account',
+ classification: 'READ',
+ outputSchema: kitGetAccountOutputSchema,
+ displayName: 'Get Account',
+ description: 'Get the name and primary email address of the connected Kit account.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns the connected Kit account name and primary email address. Use it to confirm which account the connection points at before making changes. Returns no account ID or timezone.',
+ idempotent: true,
+ },
+ props: {},
+ async run(context) {
+ const response = await kitClient.request<Record<string, unknown>>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: '/account',
+ });
+ return response.body;
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/get-broadcast-stats.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/get-broadcast-stats.ts
new file mode 100644
index 00000000000..a762a77f87d
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/get-broadcast-stats.ts
@@ -0,0 +1,45 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient, kitCommon } from '../../common/client';
+import { kitProps } from '../../common/ai-props';
+import { kitGetBroadcastStatsOutputSchema } from '../../output-schemas';
+
+type BroadcastStats = {
+ id?: number;
+ stats?: Record<string, unknown>;
+};
+
+export const kitGetBroadcastStats = createAction({
+ auth: convertkitAuth,
+ name: 'kit_get_broadcast_stats',
+ classification: 'READ',
+ outputSchema: kitGetBroadcastStatsOutputSchema,
+ displayName: 'Get Broadcast Stats',
+ description: 'Get delivery and engagement stats for one broadcast.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns the stats of one broadcast by ID: recipients, open rate, click rate, unsubscribes, total clicks, status and send progress. Use Get Broadcast for its content instead. A draft that was never sent reports zero counts.',
+ idempotent: true,
+ },
+ props: {
+ broadcast_id: kitProps.id('Broadcast ID', 'The broadcast ID, from List Broadcasts.'),
+ },
+ async run(context) {
+ const broadcastId = kitCommon.id({ value: context.propsValue.broadcast_id, label: 'Broadcast ID' });
+ const response = await kitClient.request<{
+ broadcast: BroadcastStats | BroadcastStats[];
+ }>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: `/broadcasts/${broadcastId}/stats`,
+ });
+ const raw = response.body.broadcast;
+ const broadcast = Array.isArray(raw) ? raw[0] : raw;
+ return {
+ broadcast_id: broadcast?.id ?? Number(broadcastId),
+ ...(broadcast?.stats ?? {}),
+ };
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/get-broadcast.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/get-broadcast.ts
new file mode 100644
index 00000000000..fd79f9c16e1
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/get-broadcast.ts
@@ -0,0 +1,33 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient, kitCommon } from '../../common/client';
+import { kitProps } from '../../common/ai-props';
+import { Broadcast } from '../../common/types';
+import { kitBroadcastOutputSchema } from '../../output-schemas';
+
+export const kitGetBroadcast = createAction({
+ auth: convertkitAuth,
+ name: 'kit_get_broadcast',
+ classification: 'READ',
+ outputSchema: kitBroadcastOutputSchema,
+ displayName: 'Get Broadcast',
+ description: 'Get the content and settings of one broadcast.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns one broadcast by ID: subject, content, sender, schedule and public-post settings. Use Get Broadcast Stats for opens and clicks instead. Get the ID from List Broadcasts.',
+ idempotent: true,
+ },
+ props: {
+ broadcast_id: kitProps.id('Broadcast ID', 'The broadcast ID, from List Broadcasts.'),
+ },
+ async run(context) {
+ const response = await kitClient.request<{ broadcast: Broadcast }>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: `/broadcasts/${kitCommon.id({ value: context.propsValue.broadcast_id, label: 'Broadcast ID' })}`,
+ });
+ return response.body.broadcast;
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/get-purchase.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/get-purchase.ts
new file mode 100644
index 00000000000..2ec90567b04
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/get-purchase.ts
@@ -0,0 +1,36 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient, kitCommon } from '../../common/client';
+import { kitProps } from '../../common/ai-props';
+import { Purchase } from '../../common/types';
+import { kitPurchaseOutputSchema } from '../../output-schemas';
+
+export const kitGetPurchase = createAction({
+ auth: convertkitAuth,
+ name: 'kit_get_purchase',
+ classification: 'READ',
+ outputSchema: kitPurchaseOutputSchema,
+ displayName: 'Get Purchase',
+ description: 'Get one purchase by purchase ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns one purchase record by its Kit purchase ID: transaction ID, buyer email, status, currency, totals and product line items. Find the purchase ID with List Purchases.',
+ idempotent: true,
+ },
+ props: {
+ purchase_id: kitProps.id(
+ 'Purchase ID',
+ 'The Kit purchase ID, from List Purchases.'
+ ),
+ },
+ async run(context) {
+ const response = await kitClient.request<Purchase>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: `/purchases/${kitCommon.id({ value: context.propsValue.purchase_id, label: 'Purchase ID' })}`,
+ });
+ return response.body;
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/get-subscriber.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/get-subscriber.ts
new file mode 100644
index 00000000000..8319ec462cd
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/get-subscriber.ts
@@ -0,0 +1,33 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient, kitCommon } from '../../common/client';
+import { kitProps } from '../../common/ai-props';
+import { Subscriber } from '../../common/types';
+import { kitSubscriberOutputSchema } from '../../output-schemas';
+
+export const kitGetSubscriber = createAction({
+ auth: convertkitAuth,
+ name: 'kit_get_subscriber',
+ classification: 'READ',
+ outputSchema: kitSubscriberOutputSchema,
+ displayName: 'Get Subscriber',
+ description: 'Get one subscriber by subscriber ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns one subscriber by ID: email, first name, state and custom field values. To look someone up by email, use List Subscribers with the Email Address filter instead.',
+ idempotent: true,
+ },
+ props: {
+ subscriber_id: kitProps.id('Subscriber ID', 'The subscriber ID, from List Subscribers.'),
+ },
+ async run(context) {
+ const response = await kitClient.request<{ subscriber: Subscriber }>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: `/subscribers/${kitCommon.id({ value: context.propsValue.subscriber_id, label: 'Subscriber ID' })}`,
+ });
+ return response.body.subscriber;
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/list-broadcasts.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/list-broadcasts.ts
new file mode 100644
index 00000000000..55bf716f82a
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/list-broadcasts.ts
@@ -0,0 +1,37 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient, kitCommon } from '../../common/client';
+import { kitProps } from '../../common/ai-props';
+import { Broadcast } from '../../common/types';
+import { kitListBroadcastsOutputSchema } from '../../output-schemas';
+
+export const kitListBroadcasts = createAction({
+ auth: convertkitAuth,
+ name: 'kit_list_broadcasts',
+ classification: 'SEARCH',
+ outputSchema: kitListBroadcastsOutputSchema,
+ displayName: 'List Broadcasts',
+ description: 'List broadcasts (one-off emails), 50 per page.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists broadcasts with their ID, subject and creation time, 50 per page. Use it to find a broadcast ID for Get Broadcast, Get Broadcast Stats or Delete Broadcast. Increase Page until fewer than 50 are returned to see older ones.',
+ idempotent: true,
+ },
+ props: {
+ page: kitProps.page('Page number, 50 broadcasts per page. Defaults to 1.'),
+ sort_order: kitProps.sortOrder('Sort by creation date. Kit defaults to ascending (oldest first).'),
+ },
+ async run(context) {
+ const page = kitCommon.page(context.propsValue.page);
+ const response = await kitClient.request<{ broadcasts: Broadcast[] }>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: '/broadcasts',
+ query: { page, sort_order: context.propsValue.sort_order },
+ });
+ const broadcasts = response.body.broadcasts ?? [];
+ return { broadcasts, count: broadcasts.length, page };
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/list-custom-fields.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/list-custom-fields.ts
new file mode 100644
index 00000000000..a42ffb75117
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/list-custom-fields.ts
@@ -0,0 +1,31 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient } from '../../common/client';
+import { CustomField } from '../../common/types';
+import { kitListCustomFieldsOutputSchema } from '../../output-schemas';
+
+export const kitListCustomFields = createAction({
+ auth: convertkitAuth,
+ name: 'kit_list_custom_fields',
+ classification: 'SEARCH',
+ outputSchema: kitListCustomFieldsOutputSchema,
+ displayName: 'List Custom Fields',
+ description: 'List the custom subscriber fields defined on the account.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists every custom field with its ID, label and key. Use the key when setting Custom Fields on subscribers, and the ID for Update or Delete Custom Field.',
+ idempotent: true,
+ },
+ props: {},
+ async run(context) {
+ const response = await kitClient.request<{ custom_fields: CustomField[] }>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: '/custom_fields',
+ });
+ const customFields = response.body.custom_fields ?? [];
+ return { custom_fields: customFields, count: customFields.length };
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/list-form-subscriptions.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/list-form-subscriptions.ts
new file mode 100644
index 00000000000..d3027dc2b12
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/list-form-subscriptions.ts
@@ -0,0 +1,48 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient, kitCommon } from '../../common/client';
+import { kitProps } from '../../common/ai-props';
+import { Subscription } from '../../common/types';
+import { kitListTagSubscriptionsOutputSchema } from '../../output-schemas';
+
+export const kitListFormSubscriptions = createAction({
+ auth: convertkitAuth,
+ name: 'kit_list_form_subscriptions',
+ classification: 'SEARCH',
+ outputSchema: kitListTagSubscriptionsOutputSchema,
+ displayName: 'List Form Subscriptions',
+ description: 'List the subscribers who signed up through a form, 50 per page.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists subscriptions to one form, each with the subscriber record, 50 per page, with total counts for paging. Filter by active or cancelled state. Get the form ID from List Forms.',
+ idempotent: true,
+ },
+ props: {
+ form_id: kitProps.id('Form ID', 'The form ID, from List Forms.'),
+ page: kitProps.page('Page number, 50 subscriptions per page. Defaults to 1.'),
+ sort_order: kitProps.sortOrder('Sort by subscription date. Kit defaults to ascending (oldest first).'),
+ subscriber_state: kitProps.subscriberState,
+ },
+ async run(context) {
+ const { form_id, page, sort_order, subscriber_state } = context.propsValue;
+ const response = await kitClient.request<{
+ subscriptions: Subscription[];
+ page: number;
+ total_pages: number;
+ total_subscriptions: number;
+ }>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: `/forms/${kitCommon.id({ value: form_id, label: 'Form ID' })}/subscriptions`,
+ query: { page: kitCommon.page(page), sort_order, subscriber_state },
+ });
+ return {
+ subscriptions: response.body.subscriptions ?? [],
+ page: response.body.page,
+ total_pages: response.body.total_pages,
+ total_subscriptions: response.body.total_subscriptions,
+ };
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/list-forms.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/list-forms.ts
new file mode 100644
index 00000000000..dee40f69f85
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/list-forms.ts
@@ -0,0 +1,31 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient } from '../../common/client';
+import { Form } from '../../common/types';
+import { kitListFormsOutputSchema } from '../../output-schemas';
+
+export const kitListForms = createAction({
+ auth: convertkitAuth,
+ name: 'kit_list_forms',
+ classification: 'SEARCH',
+ outputSchema: kitListFormsOutputSchema,
+ displayName: 'List Forms',
+ description: 'List the forms and landing pages on the account.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists all forms and landing pages with their ID, name, type and embed URL. Use it to find a form ID for Add Subscriber To Form or List Form Subscriptions.',
+ idempotent: true,
+ },
+ props: {},
+ async run(context) {
+ const response = await kitClient.request<{ forms: Form[] }>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: '/forms',
+ });
+ const forms = response.body.forms ?? [];
+ return { forms, count: forms.length };
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/list-purchases.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/list-purchases.ts
new file mode 100644
index 00000000000..31ee71c1f35
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/list-purchases.ts
@@ -0,0 +1,44 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient, kitCommon } from '../../common/client';
+import { kitProps } from '../../common/ai-props';
+import { Purchase } from '../../common/types';
+import { kitListPurchasesOutputSchema } from '../../output-schemas';
+
+export const kitListPurchases = createAction({
+ auth: convertkitAuth,
+ name: 'kit_list_purchases',
+ classification: 'SEARCH',
+ outputSchema: kitListPurchasesOutputSchema,
+ displayName: 'List Purchases',
+ description: 'List the purchases recorded in the account, 50 per page.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists purchase records in the account, newest pages last, 50 per page, with total counts for paging. Each purchase has its transaction ID, buyer email, currency, totals and products. There is no filter by buyer on this endpoint.',
+ idempotent: true,
+ },
+ props: {
+ page: kitProps.page('Page number, 50 purchases per page. Defaults to 1.'),
+ },
+ async run(context) {
+ const response = await kitClient.request<{
+ purchases: Purchase[];
+ page: number;
+ total_pages: number;
+ total_purchases: number;
+ }>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: '/purchases',
+ query: { page: kitCommon.page(context.propsValue.page) },
+ });
+ return {
+ purchases: response.body.purchases ?? [],
+ page: response.body.page,
+ total_pages: response.body.total_pages,
+ total_purchases: response.body.total_purchases,
+ };
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/list-sequence-subscriptions.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/list-sequence-subscriptions.ts
new file mode 100644
index 00000000000..2424a91a1ba
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/list-sequence-subscriptions.ts
@@ -0,0 +1,48 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient, kitCommon } from '../../common/client';
+import { kitProps } from '../../common/ai-props';
+import { Subscription } from '../../common/types';
+import { kitListTagSubscriptionsOutputSchema } from '../../output-schemas';
+
+export const kitListSequenceSubscriptions = createAction({
+ auth: convertkitAuth,
+ name: 'kit_list_sequence_subscriptions',
+ classification: 'SEARCH',
+ outputSchema: kitListTagSubscriptionsOutputSchema,
+ displayName: 'List Sequence Subscriptions',
+ description: 'List the subscribers enrolled in a sequence, 50 per page.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the subscribers enrolled in one sequence, each with the subscriber record, 50 per page, with total counts for paging. Filter by active or cancelled state. Get the sequence ID from List Sequences.',
+ idempotent: true,
+ },
+ props: {
+ sequence_id: kitProps.id('Sequence ID', 'The sequence ID, from List Sequences.'),
+ page: kitProps.page('Page number, 50 subscriptions per page. Defaults to 1.'),
+ sort_order: kitProps.sortOrder('Sort by enrollment date. Kit defaults to ascending (oldest first).'),
+ subscriber_state: kitProps.subscriberState,
+ },
+ async run(context) {
+ const { sequence_id, page, sort_order, subscriber_state } = context.propsValue;
+ const response = await kitClient.request<{
+ subscriptions: Subscription[];
+ page: number;
+ total_pages: number;
+ total_subscriptions: number;
+ }>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: `/sequences/${kitCommon.id({ value: sequence_id, label: 'Sequence ID' })}/subscriptions`,
+ query: { page: kitCommon.page(page), sort_order, subscriber_state },
+ });
+ return {
+ subscriptions: response.body.subscriptions ?? [],
+ page: response.body.page,
+ total_pages: response.body.total_pages,
+ total_subscriptions: response.body.total_subscriptions,
+ };
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/list-sequences.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/list-sequences.ts
new file mode 100644
index 00000000000..cc8efbadbe0
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/list-sequences.ts
@@ -0,0 +1,31 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient } from '../../common/client';
+import { Sequence } from '../../common/types';
+import { kitListSequencesOutputSchema } from '../../output-schemas';
+
+export const kitListSequences = createAction({
+ auth: convertkitAuth,
+ name: 'kit_list_sequences',
+ classification: 'SEARCH',
+ outputSchema: kitListSequencesOutputSchema,
+ displayName: 'List Sequences',
+ description: 'List the email sequences on the account.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists all sequences (automated email courses) with their ID and name. Use it to find a sequence ID for a sequence webhook or enrolment.',
+ idempotent: true,
+ },
+ props: {},
+ async run(context) {
+ const response = await kitClient.request<{ courses: Sequence[] }>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: '/sequences',
+ });
+ const sequences = response.body.courses ?? [];
+ return { sequences, count: sequences.length };
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/list-subscriber-tags.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/list-subscriber-tags.ts
new file mode 100644
index 00000000000..40542ef1980
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/list-subscriber-tags.ts
@@ -0,0 +1,34 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient, kitCommon } from '../../common/client';
+import { kitProps } from '../../common/ai-props';
+import { Tag } from '../../common/types';
+import { kitListTagsOutputSchema } from '../../output-schemas';
+
+export const kitListSubscriberTags = createAction({
+ auth: convertkitAuth,
+ name: 'kit_list_subscriber_tags',
+ classification: 'SEARCH',
+ outputSchema: kitListTagsOutputSchema,
+ displayName: 'List Subscriber Tags',
+ description: 'List the tags applied to one subscriber.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists every tag currently applied to one subscriber, by subscriber ID. When only an email is known, find the ID with List Subscribers and its Email Address filter first.',
+ idempotent: true,
+ },
+ props: {
+ subscriber_id: kitProps.id('Subscriber ID', 'The subscriber ID, from List Subscribers.'),
+ },
+ async run(context) {
+ const response = await kitClient.request<{ tags: Tag[] }>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: `/subscribers/${kitCommon.id({ value: context.propsValue.subscriber_id, label: 'Subscriber ID' })}/tags`,
+ });
+ const tags = response.body.tags ?? [];
+ return { tags, count: tags.length };
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/list-subscribers.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/list-subscribers.ts
new file mode 100644
index 00000000000..909b8843337
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/list-subscribers.ts
@@ -0,0 +1,101 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient, kitCommon } from '../../common/client';
+import { kitProps } from '../../common/ai-props';
+import { Subscriber } from '../../common/types';
+import { kitListSubscribersOutputSchema } from '../../output-schemas';
+
+const dateProp = ({
+ displayName,
+ description,
+}: {
+ displayName: string;
+ description: string;
+}) =>
+ Property.ShortText({
+ displayName,
+ description: `${description} Format yyyy-mm-dd.`,
+ required: false,
+ });
+
+export const kitListSubscribers = createAction({
+ auth: convertkitAuth,
+ name: 'kit_list_subscribers',
+ classification: 'SEARCH',
+ outputSchema: kitListSubscribersOutputSchema,
+ displayName: 'List Subscribers',
+ description: 'List or search subscribers, 50 per page.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists subscribers 50 per page with total counts, optionally filtered by exact email address or created/updated date range. This is also the way to find a subscriber ID from an email. Kit returns active subscribers by default; set Sort Field to cancelled_at to list cancelled ones.',
+ idempotent: true,
+ },
+ props: {
+ email_address: Property.ShortText({
+ displayName: 'Email Address',
+ description: 'Only return the subscriber with this email address.',
+ required: false,
+ }),
+ from: dateProp({
+ displayName: 'Created From',
+ description: 'Only subscribers added on or after this date.',
+ }),
+ to: dateProp({
+ displayName: 'Created To',
+ description: 'Only subscribers added on or before this date.',
+ }),
+ updated_from: dateProp({
+ displayName: 'Updated From',
+ description: 'Only subscribers updated after this date.',
+ }),
+ updated_to: dateProp({
+ displayName: 'Updated To',
+ description: 'Only subscribers updated before this date.',
+ }),
+ page: kitProps.page('Page number, 50 subscribers per page. Defaults to 1.'),
+ sort_order: kitProps.sortOrder('Sort direction. Kit defaults to ascending.'),
+ sort_field: Property.StaticDropdown({
+ displayName: 'Sort Field',
+ description: 'Set to Cancelled At to list cancelled subscribers, sorted by cancellation date.',
+ required: false,
+ options: {
+ options: [{ label: 'Cancelled At', value: 'cancelled_at' }],
+ },
+ }),
+ },
+ async run(context) {
+ const props = context.propsValue;
+ const page = kitCommon.page(props.page);
+ const response = await kitClient.request<{
+ subscribers: Subscriber[];
+ page: number;
+ total_pages: number;
+ total_subscribers: number;
+ }>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: '/subscribers',
+ query: {
+ page,
+ email_address:
+ props.email_address === undefined || props.email_address === null || props.email_address.trim() === ''
+ ? undefined
+ : kitCommon.email({ value: props.email_address, label: 'Email Address' }),
+ from: kitCommon.toDate(props.from),
+ to: kitCommon.toDate(props.to),
+ updated_from: kitCommon.toDate(props.updated_from),
+ updated_to: kitCommon.toDate(props.updated_to),
+ sort_order: props.sort_order,
+ sort_field: props.sort_field,
+ },
+ });
+ return {
+ subscribers: response.body.subscribers ?? [],
+ page: response.body.page ?? page,
+ total_pages: response.body.total_pages,
+ total_subscribers: response.body.total_subscribers,
+ };
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/list-tag-subscriptions.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/list-tag-subscriptions.ts
new file mode 100644
index 00000000000..ddc8f54829e
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/list-tag-subscriptions.ts
@@ -0,0 +1,48 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient, kitCommon } from '../../common/client';
+import { kitProps } from '../../common/ai-props';
+import { Subscription } from '../../common/types';
+import { kitListTagSubscriptionsOutputSchema } from '../../output-schemas';
+
+export const kitListTagSubscriptions = createAction({
+ auth: convertkitAuth,
+ name: 'kit_list_tag_subscriptions',
+ classification: 'SEARCH',
+ outputSchema: kitListTagSubscriptionsOutputSchema,
+ displayName: 'List Tag Subscriptions',
+ description: 'List the subscribers who have a tag, 50 per page.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the subscribers who have one tag, each with the subscriber record, 50 per page, with total counts for paging. Filter by active or cancelled state. Get the tag ID from List Tags.',
+ idempotent: true,
+ },
+ props: {
+ tag_id: kitProps.id('Tag ID', 'The tag ID, from List Tags.'),
+ page: kitProps.page('Page number, 50 subscriptions per page. Defaults to 1.'),
+ sort_order: kitProps.sortOrder('Sort by tagging date. Kit defaults to ascending (oldest first).'),
+ subscriber_state: kitProps.subscriberState,
+ },
+ async run(context) {
+ const { tag_id, page, sort_order, subscriber_state } = context.propsValue;
+ const response = await kitClient.request<{
+ subscriptions: Subscription[];
+ page: number;
+ total_pages: number;
+ total_subscriptions: number;
+ }>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: `/tags/${kitCommon.id({ value: tag_id, label: 'Tag ID' })}/subscriptions`,
+ query: { page: kitCommon.page(page), sort_order, subscriber_state },
+ });
+ return {
+ subscriptions: response.body.subscriptions ?? [],
+ page: response.body.page,
+ total_pages: response.body.total_pages,
+ total_subscriptions: response.body.total_subscriptions,
+ };
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/list-tags.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/list-tags.ts
new file mode 100644
index 00000000000..ad75a3b1c25
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/list-tags.ts
@@ -0,0 +1,31 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient } from '../../common/client';
+import { Tag } from '../../common/types';
+import { kitListTagsOutputSchema } from '../../output-schemas';
+
+export const kitListTags = createAction({
+ auth: convertkitAuth,
+ name: 'kit_list_tags',
+ classification: 'SEARCH',
+ outputSchema: kitListTagsOutputSchema,
+ displayName: 'List Tags',
+ description: 'List the tags on the account.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists every tag with its ID and name. Use it to resolve a tag name to the ID that Tag Subscriber, Remove Tag and List Tag Subscriptions need.',
+ idempotent: true,
+ },
+ props: {},
+ async run(context) {
+ const response = await kitClient.request<{ tags: Tag[] }>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: '/tags',
+ });
+ const tags = response.body.tags ?? [];
+ return { tags, count: tags.length };
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/list-webhooks.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/list-webhooks.ts
new file mode 100644
index 00000000000..81c714a6491
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/list-webhooks.ts
@@ -0,0 +1,49 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient } from '../../common/client';
+import { kitListWebhooksOutputSchema } from '../../output-schemas';
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+const rulesOf = (body: unknown): unknown[] => {
+ if (Array.isArray(body)) {
+ return body;
+ }
+ if (isRecord(body) && Array.isArray(body['rules'])) {
+ return body['rules'];
+ }
+ return [];
+};
+
+export const kitListWebhooks = createAction({
+ auth: convertkitAuth,
+ name: 'kit_list_webhooks',
+ classification: 'SEARCH',
+ outputSchema: kitListWebhooksOutputSchema,
+ displayName: 'List Webhooks',
+ description: 'List the webhook automations registered on the Kit account.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the webhook rules registered on the account, each with its rule ID, event and target URL. Use it to find a rule ID before Delete Webhook or to avoid registering a duplicate with Create Webhook.',
+ idempotent: true,
+ },
+ props: {},
+ async run(context) {
+ const response = await kitClient.request<unknown>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: '/automations/hooks',
+ });
+ const body = response.body;
+ const rules = rulesOf(body);
+ return {
+ rules: rules.map((item) =>
+ isRecord(item) && 'rule' in item ? item['rule'] : item
+ ),
+ count: rules.length,
+ };
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/remove-tag-by-email.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/remove-tag-by-email.ts
new file mode 100644
index 00000000000..384966cc123
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/remove-tag-by-email.ts
@@ -0,0 +1,41 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient, kitCommon } from '../../common/client';
+import { kitProps } from '../../common/ai-props';
+import { Tag } from '../../common/types';
+import { kitRemoveTagByEmailOutputSchema } from '../../output-schemas';
+
+export const kitRemoveTagByEmail = createAction({
+ auth: convertkitAuth,
+ name: 'kit_remove_tag_by_email',
+ classification: 'WRITE',
+ outputSchema: kitRemoveTagByEmailOutputSchema,
+ displayName: 'Remove Tag By Email',
+ description: 'Remove a tag from a subscriber identified by email.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Removes one tag from the subscriber with the given email; the subscriber stays subscribed. Use Remove Tag From Subscriber when you have the subscriber ID instead. Safe to retry: removing a tag the subscriber no longer has still succeeds.',
+ idempotent: true,
+ },
+ props: {
+ tag_id: kitProps.id('Tag ID', 'The tag to remove, from List Tags.'),
+ email: kitProps.email('The subscriber email address.'),
+ },
+ async run(context) {
+ const email = kitCommon.email({ value: context.propsValue.email, label: 'Email' });
+ const response = await kitClient.request<Tag>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.POST,
+ path: `/tags/${kitCommon.id({ value: context.propsValue.tag_id, label: 'Tag ID' })}/unsubscribe`,
+ body: { email },
+ });
+ return {
+ removed: true,
+ email,
+ tag_id: response.body?.id,
+ tag_name: response.body?.name,
+ };
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/remove-tag-from-subscriber.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/remove-tag-from-subscriber.ts
new file mode 100644
index 00000000000..e2469303b08
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/remove-tag-from-subscriber.ts
@@ -0,0 +1,41 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient, kitCommon } from '../../common/client';
+import { kitProps } from '../../common/ai-props';
+import { Tag } from '../../common/types';
+import { kitRemoveTagFromSubscriberOutputSchema } from '../../output-schemas';
+
+export const kitRemoveTagFromSubscriber = createAction({
+ auth: convertkitAuth,
+ name: 'kit_remove_tag_from_subscriber',
+ classification: 'WRITE',
+ outputSchema: kitRemoveTagFromSubscriberOutputSchema,
+ displayName: 'Remove Tag From Subscriber',
+ description: 'Remove a tag from a subscriber identified by subscriber ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Removes one tag from a subscriber by subscriber ID; the subscriber stays subscribed. Use Remove Tag By Email when you only have the address. Safe to retry: removing a tag the subscriber no longer has still succeeds.',
+ idempotent: true,
+ },
+ props: {
+ subscriber_id: kitProps.id('Subscriber ID', 'The subscriber ID, from List Subscribers or Get Subscriber.'),
+ tag_id: kitProps.id('Tag ID', 'The tag to remove, from List Tags.'),
+ },
+ async run(context) {
+ const subscriberId = kitCommon.id({ value: context.propsValue.subscriber_id, label: 'Subscriber ID' });
+ const tagId = kitCommon.id({ value: context.propsValue.tag_id, label: 'Tag ID' });
+ const response = await kitClient.request<Tag>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.DELETE,
+ path: `/subscribers/${subscriberId}/tags/${tagId}`,
+ });
+ return {
+ removed: true,
+ subscriber_id: subscriberId,
+ tag_id: response.body?.id ?? Number(tagId),
+ tag_name: response.body?.name,
+ };
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/tag-subscriber.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/tag-subscriber.ts
new file mode 100644
index 00000000000..608cbe977c7
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/tag-subscriber.ts
@@ -0,0 +1,44 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient, kitCommon } from '../../common/client';
+import { kitProps } from '../../common/ai-props';
+import { Subscription } from '../../common/types';
+import { kitSubscriptionOutputSchema } from '../../output-schemas';
+
+export const kitTagSubscriber = createAction({
+ auth: convertkitAuth,
+ name: 'kit_tag_subscriber',
+ classification: 'WRITE',
+ outputSchema: kitSubscriptionOutputSchema,
+ displayName: 'Tag Subscriber',
+ description: 'Apply a tag to a subscriber by email, creating the subscriber if needed.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Applies a tag (plus optional extra tags) to a subscriber by email, creating the subscriber if missing and optionally setting first name and custom fields. Re-applying the same tag is a no-op. Tagging can start automations tied to that tag and may reactivate an address that unsubscribed. To act on a subscriber ID, get the email with Get Subscriber first.',
+ idempotent: true,
+ },
+ props: {
+ tag_id: kitProps.id('Tag ID', 'The tag to apply, from List Tags or Create Tag.'),
+ email: kitProps.email('The subscriber email address.'),
+ additional_tag_ids: kitProps.tagIds('Additional Tag IDs', 'More tag IDs to apply in the same call.'),
+ first_name: kitProps.firstName,
+ fields: kitProps.fields,
+ },
+ async run(context) {
+ const { tag_id, email, additional_tag_ids, first_name, fields } = context.propsValue;
+ const response = await kitClient.request<{ subscription: Subscription }>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.POST,
+ path: `/tags/${kitCommon.id({ value: tag_id, label: 'Tag ID' })}/subscribe`,
+ body: kitCommon.compact({
+ email: kitCommon.email({ value: email, label: 'Email' }),
+ first_name,
+ fields: kitCommon.toFields(fields),
+ tags: kitCommon.toIdList(additional_tag_ids),
+ }),
+ });
+ return response.body.subscription;
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/unsubscribe-subscriber.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/unsubscribe-subscriber.ts
new file mode 100644
index 00000000000..e4b1b8768a3
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/unsubscribe-subscriber.ts
@@ -0,0 +1,34 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient, kitCommon } from '../../common/client';
+import { kitProps } from '../../common/ai-props';
+import { Subscriber } from '../../common/types';
+import { kitSubscriberOutputSchema } from '../../output-schemas';
+
+export const kitUnsubscribeSubscriber = createAction({
+ auth: convertkitAuth,
+ name: 'kit_unsubscribe_subscriber',
+ classification: 'DESTRUCTIVE',
+ outputSchema: kitSubscriberOutputSchema,
+ displayName: 'Unsubscribe Subscriber',
+ description: 'Unsubscribe an email address from all forms and sequences.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Unsubscribes an email address from every form, sequence and future email on the account; Kit has no delete-subscriber endpoint, so this is the removal action. Only the subscriber can reliably opt back in. To act on a subscriber ID, get the email with Get Subscriber first. Safe to retry: an already unsubscribed address returns the same cancelled record.',
+ idempotent: true,
+ },
+ props: {
+ email: kitProps.email('The email address to unsubscribe.'),
+ },
+ async run(context) {
+ const response = await kitClient.request<{ subscriber: Subscriber }>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.PUT,
+ path: '/unsubscribe',
+ body: { email: kitCommon.email({ value: context.propsValue.email, label: 'Email' }) },
+ });
+ return response.body.subscriber;
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/update-broadcast.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/update-broadcast.ts
new file mode 100644
index 00000000000..5671728912d
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/update-broadcast.ts
@@ -0,0 +1,110 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient, kitCommon } from '../../common/client';
+import { kitProps } from '../../common/ai-props';
+import { Broadcast } from '../../common/types';
+import { kitBroadcastOutputSchema } from '../../output-schemas';
+
+export const kitUpdateBroadcast = createAction({
+ auth: convertkitAuth,
+ name: 'kit_update_broadcast',
+ classification: 'WRITE',
+ outputSchema: kitBroadcastOutputSchema,
+ displayName: 'Update Broadcast',
+ description: 'Change fields on an existing broadcast. Fields left empty are not changed.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Updates only the fields you pass on an existing broadcast, such as subject or content; everything left empty keeps its current value. Setting Send At schedules a real send to subscribers, and Publish As Web Post changes its web visibility, so only set them when the user asked. Get the broadcast ID from List Broadcasts.',
+ idempotent: true,
+ },
+ props: {
+ broadcast_id: kitProps.id('Broadcast ID', 'The broadcast ID, from List Broadcasts.'),
+ subject: Property.ShortText({
+ displayName: 'Subject',
+ description: 'New email subject line.',
+ required: false,
+ }),
+ content: Property.LongText({
+ displayName: 'Content',
+ description: 'New email body. Plain text or simple HTML (p, h1, img, a).',
+ required: false,
+ }),
+ description: Property.ShortText({
+ displayName: 'Internal Description',
+ description: 'New internal note, not shown to subscribers.',
+ required: false,
+ }),
+ email_address: Property.ShortText({
+ displayName: 'From Email Address',
+ description: 'New sending address. It must be a confirmed sender in Kit.',
+ required: false,
+ }),
+ email_layout_template: Property.ShortText({
+ displayName: 'Email Template Name',
+ description: 'New email template name.',
+ required: false,
+ }),
+ send_at: Property.DateTime({
+ displayName: 'Send At',
+ description:
+ 'Schedule a real send at this ISO 8601 date-time, which must be in the future. Leave empty to keep the current schedule.',
+ required: false,
+ }),
+ public: Property.StaticDropdown({
+ displayName: 'Publish As Web Post',
+ description: 'Change web post visibility. Leave empty to keep it as it is.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Publish as web post', value: 'true' },
+ { label: 'Do not publish as web post', value: 'false' },
+ ],
+ },
+ }),
+ published_at: Property.DateTime({
+ displayName: 'Published At',
+ description: 'New publication time shown on the web post.',
+ required: false,
+ }),
+ thumbnail_url: Property.ShortText({
+ displayName: 'Thumbnail URL',
+ description: 'New image URL for the web post thumbnail.',
+ required: false,
+ }),
+ thumbnail_alt: Property.ShortText({
+ displayName: 'Thumbnail Alt Text',
+ description: 'New alt text for the web post thumbnail.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const props = context.propsValue;
+ const body = kitCommon.compact({
+ subject: props.subject,
+ content: props.content,
+ description: props.description,
+ email_address:
+ props.email_address === undefined || props.email_address === null || props.email_address.trim() === ''
+ ? undefined
+ : kitCommon.email({ value: props.email_address, label: 'From Email Address' }),
+ email_layout_template: props.email_layout_template,
+ send_at: kitCommon.toDateTime({ value: props.send_at, label: 'Send At', future: true }),
+ public: props.public === undefined || props.public === null ? undefined : props.public === 'true',
+ published_at: kitCommon.toDateTime({ value: props.published_at, label: 'Published At' }),
+ thumbnail_url: props.thumbnail_url,
+ thumbnail_alt: props.thumbnail_alt,
+ });
+ if (Object.keys(body).length === 0) {
+ throw new Error('Set at least one field to update.');
+ }
+ const response = await kitClient.request<{ broadcast: Broadcast }>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.PUT,
+ path: `/broadcasts/${kitCommon.id({ value: props.broadcast_id, label: 'Broadcast ID' })}`,
+ body,
+ });
+ return response.body.broadcast;
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/update-custom-field.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/update-custom-field.ts
new file mode 100644
index 00000000000..e10179c028c
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/update-custom-field.ts
@@ -0,0 +1,69 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient, kitCommon } from '../../common/client';
+import { kitProps } from '../../common/ai-props';
+import { CustomField } from '../../common/types';
+import { kitUpdateCustomFieldOutputSchema } from '../../output-schemas';
+
+export const kitUpdateCustomField = createAction({
+ auth: convertkitAuth,
+ name: 'kit_update_custom_field',
+ classification: 'WRITE',
+ outputSchema: kitUpdateCustomFieldOutputSchema,
+ displayName: 'Update Custom Field',
+ description: 'Rename a custom subscriber field.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Renames a custom field by ID and returns the updated field. Only the label changes: the field key used in subscriber fields and liquid tags stays the same, and stored subscriber values are kept. If reading the field back fails after the rename, it still succeeds and returns refreshed: false with the reason.',
+ idempotent: true,
+ },
+ props: {
+ custom_field_id: kitProps.id('Custom Field ID', 'The field ID, from List Custom Fields.'),
+ label: Property.ShortText({
+ displayName: 'New Label',
+ description: 'The new label. Must be unique on the account.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const fieldId = kitCommon.id({ value: context.propsValue.custom_field_id, label: 'Custom Field ID' });
+ const label = context.propsValue.label.trim();
+ if (!label) {
+ throw new Error('New Label cannot be empty.');
+ }
+ await kitClient.request<unknown>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.PUT,
+ path: `/custom_fields/${fieldId}`,
+ body: { label },
+ });
+ try {
+ const list = await kitClient.request<{ custom_fields: CustomField[] }>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: '/custom_fields',
+ });
+ const updated = (list.body.custom_fields ?? []).find((field) => String(field.id) === fieldId);
+ if (updated) {
+ return { ...updated, refreshed: true };
+ }
+ return {
+ id: Number(fieldId),
+ label,
+ refreshed: false,
+ refresh_error: 'The rename succeeded, but the field was not in the refreshed custom field list.',
+ };
+ } catch (error) {
+ return {
+ id: Number(fieldId),
+ label,
+ refreshed: false,
+ refresh_error: `The rename succeeded, but reading the field back failed: ${
+ error instanceof Error ? error.message : 'unknown error'
+ }`,
+ };
+ }
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/ai/update-subscriber.ts b/packages/pieces/community/convertkit/src/lib/actions/ai/update-subscriber.ts
new file mode 100644
index 00000000000..5984d5e6659
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/actions/ai/update-subscriber.ts
@@ -0,0 +1,56 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { convertkitAuth } from '../../auth';
+import { kitClient, kitCommon } from '../../common/client';
+import { kitProps } from '../../common/ai-props';
+import { Subscriber } from '../../common/types';
+import { kitSubscriberOutputSchema } from '../../output-schemas';
+
+export const kitUpdateSubscriber = createAction({
+ auth: convertkitAuth,
+ name: 'kit_update_subscriber',
+ classification: 'WRITE',
+ outputSchema: kitSubscriberOutputSchema,
+ displayName: 'Update Subscriber',
+ description: 'Update the email, first name or custom fields of a subscriber.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Updates a subscriber by ID. Only the inputs you supply are sent, so omitted ones keep their stored value; an empty string in Custom Fields clears that field. It cannot change subscription state; use Unsubscribe Subscriber for that.',
+ idempotent: true,
+ },
+ props: {
+ subscriber_id: kitProps.id('Subscriber ID', 'The subscriber ID, from List Subscribers.'),
+ email_address: Property.ShortText({
+ displayName: 'New Email Address',
+ description: 'Change the subscriber email address.',
+ required: false,
+ }),
+ first_name: kitProps.firstName,
+ fields: kitProps.fields,
+ },
+ async run(context) {
+ const { subscriber_id, email_address, first_name, fields } = context.propsValue;
+ const body: Record<string, unknown> = {};
+ if (email_address !== undefined && email_address !== null && email_address !== '') {
+ body['email_address'] = kitCommon.email({ value: email_address, label: 'New Email Address' });
+ }
+ if (first_name !== undefined && first_name !== null && first_name !== '') {
+ body['first_name'] = first_name;
+ }
+ const customFields = kitCommon.toFields(fields);
+ if (customFields) {
+ body['fields'] = customFields;
+ }
+ if (Object.keys(body).length === 0) {
+ throw new Error('Provide at least one of New Email Address, First Name or Custom Fields.');
+ }
+ const response = await kitClient.request<{ subscriber: Subscriber }>({
+ apiSecret: context.auth.secret_text,
+ method: HttpMethod.PUT,
+ path: `/subscribers/${kitCommon.id({ value: subscriber_id, label: 'Subscriber ID' })}`,
+ body,
+ });
+ return response.body.subscriber;
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/actions/broadcasts.ts b/packages/pieces/community/convertkit/src/lib/actions/broadcasts.ts
index f71d6b7b354..e08c2e14542 100644
--- a/packages/pieces/community/convertkit/src/lib/actions/broadcasts.ts
+++ b/packages/pieces/community/convertkit/src/lib/actions/broadcasts.ts
@@ -1,10 +1,7 @@
import { createAction } from '@activepieces/pieces-framework';
-import {
- httpClient,
- HttpMethod,
- HttpRequest,
-} from '@activepieces/pieces-common';
-import { convertkitAuth } from '../..';
+import { HttpMethod, HttpRequest } from '@activepieces/pieces-common';
+import { convertkitAuth } from '../auth';
+import { kitHttp } from '../common/http';
import {
broadcastId,
broadcastPageNumber,
@@ -22,14 +19,21 @@ import {
import { Broadcast } from '../common/types';
import { BROADCASTS_API_ENDPOINT } from '../common/constants';
import { buildQueryParams, fetchBroadcasts } from '../common/service';
+import {
+ kitBroadcastListOutputSchema,
+ kitBroadcastOutputSchema,
+ kitBroadcastStatsOutputSchema,
+ kitRequestStatusOutputSchema,
+} from '../output-schemas';
export const listBroadcasts = createAction({
auth: convertkitAuth,
name: 'broadcasts_list_broadcasts',
classification: 'SEARCH',
+ outputSchema: kitBroadcastListOutputSchema,
displayName: 'List Broadcasts',
description: 'List all broadcasts',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Retrieves a page of broadcasts (one-off emails) in the ConvertKit account, 50 per page. Use it to find a broadcast ID before getting, updating, or deleting one. Read-only and idempotent; pass a page number to fetch beyond the first 50.',
@@ -48,9 +52,10 @@ export const createBroadcast = createAction({
auth: convertkitAuth,
name: 'broadcasts_create_broadcast',
classification: 'WRITE',
+ outputSchema: kitBroadcastOutputSchema,
displayName: 'Create Broadcast',
description: 'Create a new broadcast',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Creates a new email broadcast (one-off email), optionally scheduled via the send-at field; without it the broadcast is saved unsent. Not idempotent — every call creates another broadcast, so do not retry blindly.',
@@ -105,7 +110,7 @@ export const createBroadcast = createAction({
'Content-Type': 'application/json',
},
};
- const response = await httpClient.sendRequest<{ broadcast: Broadcast }>(
+ const response = await kitHttp.sendRequest<{ broadcast: Broadcast }>(
request
);
if (response.status !== 201) {
@@ -119,9 +124,10 @@ export const getBroadcastById = createAction({
auth: convertkitAuth,
name: 'broadcasts_get_broadcast',
classification: 'READ',
+ outputSchema: kitBroadcastOutputSchema,
displayName: 'Get Broadcast',
description: 'Get a broadcast',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Fetches a single broadcast by its ID, returning its content and settings. Use when the broadcast ID is already known (e.g. from List Broadcasts); for delivery metrics use Broadcast Stats instead. Read-only and idempotent.',
@@ -139,7 +145,7 @@ export const getBroadcastById = createAction({
queryParams: buildQueryParams(context.auth.secret_text),
method: HttpMethod.GET,
};
- const response = await httpClient.sendRequest<{ broadcast: Broadcast }>(
+ const response = await kitHttp.sendRequest<{ broadcast: Broadcast }>(
request
);
if (response.status !== 200) {
@@ -153,9 +159,10 @@ export const updateBroadcast = createAction({
auth: convertkitAuth,
name: 'broadcasts_update_broadcast',
classification: 'WRITE',
+ outputSchema: kitBroadcastOutputSchema,
displayName: 'Update Broadcast',
description: 'Update a broadcast',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Updates the content, subject, scheduling, or other fields of an existing broadcast by broadcast ID. Idempotent — repeating the same update leaves the broadcast in the same state. Requires a valid broadcast ID from List Broadcasts.',
@@ -214,7 +221,7 @@ export const updateBroadcast = createAction({
'Content-Type': 'application/json',
},
};
- const response = await httpClient.sendRequest<{ broadcast: Broadcast }>(
+ const response = await kitHttp.sendRequest<{ broadcast: Broadcast }>(
request
);
if (response.status !== 200) {
@@ -228,9 +235,10 @@ export const broadcastStats = createAction({
auth: convertkitAuth,
name: 'broadcasts_broadcast_stats',
classification: 'READ',
+ outputSchema: kitBroadcastStatsOutputSchema,
displayName: 'Broadcast Stats',
description: 'Get broadcast stats',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Retrieves delivery and engagement statistics (recipients, opens, clicks, unsubscribes) for one broadcast by ID. Pick this over Get Broadcast when performance metrics are needed rather than content. Read-only and idempotent.',
@@ -248,7 +256,7 @@ export const broadcastStats = createAction({
queryParams: buildQueryParams(context.auth.secret_text),
method: HttpMethod.GET,
};
- const response = await httpClient.sendRequest<{ broadcast: Broadcast }>(
+ const response = await kitHttp.sendRequest<{ broadcast: Broadcast }>(
request
);
if (response.status !== 200) {
@@ -262,9 +270,10 @@ export const deleteBroadcast = createAction({
auth: convertkitAuth,
name: 'broadcasts_delete_broadcast',
classification: 'DESTRUCTIVE',
+ outputSchema: kitRequestStatusOutputSchema,
displayName: 'Delete Broadcast',
description: 'Delete a broadcast',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Permanently deletes a broadcast by ID. Destructive and not retry-safe — a repeat call fails once the broadcast is gone, so confirm the ID via List Broadcasts first.',
@@ -286,7 +295,7 @@ export const deleteBroadcast = createAction({
body,
method: HttpMethod.DELETE,
};
- const response = await httpClient.sendRequest<{ broadcast: Broadcast }>(
+ const response = await kitHttp.sendRequest<{ broadcast: Broadcast }>(
request
);
if (response.status !== 204) {
diff --git a/packages/pieces/community/convertkit/src/lib/actions/custom-fields.ts b/packages/pieces/community/convertkit/src/lib/actions/custom-fields.ts
index 05ce7aa53a8..3dcfd0996f6 100644
--- a/packages/pieces/community/convertkit/src/lib/actions/custom-fields.ts
+++ b/packages/pieces/community/convertkit/src/lib/actions/custom-fields.ts
@@ -1,22 +1,25 @@
import { createAction } from '@activepieces/pieces-framework';
-import {
- httpClient,
- HttpMethod,
- HttpRequest,
-} from '@activepieces/pieces-common';
-import { convertkitAuth } from '../..';
+import { HttpMethod, HttpRequest } from '@activepieces/pieces-common';
+import { convertkitAuth } from '../auth';
+import { kitHttp } from '../common/http';
import { fieldsArray, label, new_label } from '../common/custom-fields';
import { CustomField } from '../common/types';
import { CUSTOM_FIELDS_API_ENDPOINT } from '../common/constants';
import { fetchCustomFields } from '../common/service';
+import {
+ kitCustomFieldListOutputSchema,
+ kitCustomFieldOutputSchema,
+ kitRequestStatusOutputSchema,
+} from '../output-schemas';
export const listFields = createAction({
auth: convertkitAuth,
name: 'custom_fields_list_fields',
classification: 'SEARCH',
+ outputSchema: kitCustomFieldListOutputSchema,
displayName: 'List Custom Fields',
description: 'Returns a list of all custom fields',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Lists every custom field defined on the account, including each field id, key, and label. Use it to discover field keys before setting custom field values on subscribers. Takes no inputs; read-only and idempotent.',
@@ -32,9 +35,10 @@ export const createField = createAction({
auth: convertkitAuth,
name: 'custom_fields_create_field',
classification: 'WRITE',
+ outputSchema: kitCustomFieldOutputSchema,
displayName: 'Create Custom Field',
description: 'Create a new custom field',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Creates one or more new custom fields from an array of labels (ConvertKit derives each field key from its label). Not idempotent — repeating the call creates duplicate fields, so check List Custom Fields first.',
@@ -57,9 +61,7 @@ export const createField = createAction({
body,
};
- const response = await httpClient.sendRequest<{
- custom_field: CustomField;
- }>(request);
+ const response = await kitHttp.sendRequest<CustomField>(request);
if (response.status !== 201) {
throw new Error(`Error creating field: ${response.status}`);
@@ -72,9 +74,10 @@ export const updateField = createAction({
auth: convertkitAuth,
name: 'custom_fields_update_field',
classification: 'WRITE',
+ outputSchema: kitRequestStatusOutputSchema,
displayName: 'Custom Fields: Update Field',
description: 'Update a custom field',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Renames an existing custom field, selected by its current label, to a new label. Not idempotent — once the rename succeeds the old label no longer matches, so a retry with the same inputs fails.',
@@ -100,9 +103,7 @@ export const updateField = createAction({
body,
};
- const response = await httpClient.sendRequest<{
- custom_field: CustomField;
- }>(request);
+ const response = await kitHttp.sendRequest<unknown>(request);
if (response.status !== 204) {
throw new Error(`Error updating field: ${response.status}`);
@@ -115,9 +116,10 @@ export const deleteField = createAction({
auth: convertkitAuth,
name: 'custom_fields_delete_field',
classification: 'DESTRUCTIVE',
+ outputSchema: kitRequestStatusOutputSchema,
displayName: 'Custom Fields: Delete Field',
description: 'Delete a custom field',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Deletes a custom field by label, removing it and its stored values from all subscribers. Destructive and not retry-safe — a repeat call fails once the field is gone.',
@@ -141,9 +143,7 @@ export const deleteField = createAction({
body,
};
- const response = await httpClient.sendRequest<{
- custom_field: CustomField;
- }>(request);
+ const response = await kitHttp.sendRequest<unknown>(request);
if (response.status !== 204) {
throw new Error(`Error deleting field: ${response.status}`);
diff --git a/packages/pieces/community/convertkit/src/lib/actions/forms.ts b/packages/pieces/community/convertkit/src/lib/actions/forms.ts
index 14dda708251..ce9cf623325 100644
--- a/packages/pieces/community/convertkit/src/lib/actions/forms.ts
+++ b/packages/pieces/community/convertkit/src/lib/actions/forms.ts
@@ -1,32 +1,34 @@
import { createAction } from '@activepieces/pieces-framework';
-import {
- httpClient,
- HttpMethod,
- HttpRequest,
-} from '@activepieces/pieces-common';
+import { HttpMethod, HttpRequest } from '@activepieces/pieces-common';
import { Subscription } from '../common/types';
-import { convertkitAuth } from '../..';
+import { convertkitAuth } from '../auth';
+import { kitHttp } from '../common/http';
import { formId } from '../common/forms';
import { subscriberEmail, subscriberFirstName } from '../common/subscribers';
import { allFields } from '../common/custom-fields';
import { FORMS_API_ENDPOINT } from '../common/constants';
import { buildQueryParams, fetchForms } from '../common/service';
import { tags } from '../common/tags';
+import {
+ kitFormListOutputSchema,
+ kitSubscriptionOutputSchema,
+} from '../output-schemas';
export const listForms = createAction({
auth: convertkitAuth,
name: 'forms_list_forms',
classification: 'SEARCH',
+ outputSchema: kitFormListOutputSchema,
displayName: 'List Forms',
description: 'Returns a list of all forms',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Lists all forms and landing pages in the account with their IDs and names. Use it to find a form ID before adding subscribers to a form or listing form subscriptions. Takes no inputs; read-only and idempotent.',
idempotent: true,
},
props: {},
- run(context) {
+ run(context) {
return fetchForms(context.auth.secret_text);
},
});
@@ -42,9 +44,10 @@ export const addSubscriberToForm = createAction({
auth: convertkitAuth,
name: 'forms_add_subscriber_to_form',
classification: 'WRITE',
+ outputSchema: kitSubscriptionOutputSchema,
displayName: 'Add Subscriber To Form',
description: 'Add a subscriber to a form',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Subscribes an email address to a specific form, optionally setting first name, tags, and custom field values. This is the standard way to add a new subscriber in ConvertKit. Effectively idempotent — re-subscribing the same email to the same form upserts rather than creating a duplicate.',
@@ -76,7 +79,7 @@ export const addSubscriberToForm = createAction({
body,
};
- const response = await httpClient.sendRequest<{
+ const response = await kitHttp.sendRequest<{
subscription: Subscription;
}>(request);
@@ -93,7 +96,7 @@ export const listFormSubscriptions = createAction({
classification: 'SEARCH',
displayName: 'List Form Subscriptions',
description: 'List form subscriptions',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Lists the subscriptions for one form by form ID, one entry per subscriber who signed up through it. Use it to audit who joined via a given form. Read-only and idempotent.',
@@ -111,7 +114,7 @@ export const listFormSubscriptions = createAction({
method: HttpMethod.GET,
};
- const response = await httpClient.sendRequest<{
+ const response = await kitHttp.sendRequest<{
subscriptions: Subscription[];
}>(request);
diff --git a/packages/pieces/community/convertkit/src/lib/actions/purchases.ts b/packages/pieces/community/convertkit/src/lib/actions/purchases.ts
index 17b3385ed78..167b46fc5d0 100644
--- a/packages/pieces/community/convertkit/src/lib/actions/purchases.ts
+++ b/packages/pieces/community/convertkit/src/lib/actions/purchases.ts
@@ -1,10 +1,11 @@
import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod, HttpRequest } from '@activepieces/pieces-common';
+import { convertkitAuth } from '../auth';
+import { kitHttp } from '../common/http';
import {
- httpClient,
- HttpMethod,
- HttpRequest,
-} from '@activepieces/pieces-common';
-import { convertkitAuth } from '../..';
+ kitPurchaseListOutputSchema,
+ kitPurchaseOutputSchema,
+} from '../output-schemas';
import {
purchaseId,
purchasesPageNumber,
@@ -34,9 +35,10 @@ export const listPurchases = createAction({
auth: convertkitAuth,
name: 'purchases_list_purchases',
classification: 'SEARCH',
+ outputSchema: kitPurchaseListOutputSchema,
displayName: 'List Purchases',
description: 'Returns a list of all purchases',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Retrieves a paginated list of all purchase records in the account; pass a page number to go beyond the first page. For purchases scoped to one subscriber, product, form, or sequence, prefer the dedicated filtered list actions. Read-only and idempotent.',
@@ -55,9 +57,10 @@ export const getPurchaseById = createAction({
auth: convertkitAuth,
name: 'purchases_get_purchase_by_id',
classification: 'READ',
+ outputSchema: kitPurchaseOutputSchema,
displayName: 'Get Purchase By Id',
description: 'Returns data for a single purchase',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Fetches one purchase record by its ConvertKit purchase ID (not the external transaction ID). Use List Purchases first if only the transaction details are known. Read-only and idempotent.',
@@ -76,9 +79,7 @@ export const getPurchaseById = createAction({
queryParams: buildQueryParams(context.auth.secret_text),
};
- const response = await httpClient.sendRequest<{
- purchase: Purchase;
- }>(request);
+ const response = await kitHttp.sendRequest<Purchase>(request);
if (response.status !== 200) {
throw new Error(`Error fetching purchase: ${response.status}`);
@@ -99,6 +100,7 @@ export const createSinglePurchase = createAction({
auth: convertkitAuth,
name: 'purchases_create_purchase',
classification: 'WRITE',
+ outputSchema: kitPurchaseOutputSchema,
displayName: 'Create Purchase',
description: 'Creates a new purchase',
audience: 'both',
@@ -162,9 +164,7 @@ export const createSinglePurchase = createAction({
body,
};
- const response = await httpClient.sendRequest<{
- purchase: Purchase;
- }>(request);
+ const response = await kitHttp.sendRequest<Purchase>(request);
if (response.status !== 201) {
throw new Error(`Error creating purchase: ${response.status}`);
@@ -178,6 +178,7 @@ export const createPurchases = createAction({
auth: convertkitAuth,
name: 'purchases_create_multiple_purchases',
classification: 'WRITE',
+ outputSchema: kitPurchaseOutputSchema,
displayName: 'Create Multiple Purchases',
description: 'Creates multiple purchases',
audience: 'both',
@@ -241,9 +242,7 @@ export const createPurchases = createAction({
body,
};
- const response = await httpClient.sendRequest<{
- purchase: Purchase;
- }>(request);
+ const response = await kitHttp.sendRequest<Purchase>(request);
if (response.status !== 201) {
throw new Error(`Error creating purchase: ${response.status}`);
@@ -283,7 +282,7 @@ export const listPurchasesForSubscriber = createAction({
}),
};
- const response = await httpClient.sendRequest<{
+ const response = await kitHttp.sendRequest<{
purchases: Purchase[];
}>(request);
diff --git a/packages/pieces/community/convertkit/src/lib/actions/sequences.ts b/packages/pieces/community/convertkit/src/lib/actions/sequences.ts
index 5f20f66a0dc..5802c57c3a9 100644
--- a/packages/pieces/community/convertkit/src/lib/actions/sequences.ts
+++ b/packages/pieces/community/convertkit/src/lib/actions/sequences.ts
@@ -1,25 +1,28 @@
import { createAction } from '@activepieces/pieces-framework';
-import {
- httpClient,
- HttpMethod,
- HttpRequest,
-} from '@activepieces/pieces-common';
+import { HttpMethod, HttpRequest } from '@activepieces/pieces-common';
import { Sequence } from '../common/types';
-import { convertkitAuth } from '../..';
+import { convertkitAuth } from '../auth';
+import { kitHttp } from '../common/http';
import { sequenceIdDropdown } from '../common/sequences';
import { subscriberEmail, subscriberFirstName } from '../common/subscribers';
import { allFields } from '../common/custom-fields';
import { tags } from '../common/tags';
import { SEQUENCES_API_ENDPOINT } from '../common/constants';
import { buildQueryParams, fetchSequences } from '../common/service';
+import {
+ kitSequenceListOutputSchema,
+ kitSubscriptionListOutputSchema,
+ kitSubscriptionOutputSchema,
+} from '../output-schemas';
export const listSequences = createAction({
auth: convertkitAuth,
name: 'sequences_list_sequences',
classification: 'SEARCH',
+ outputSchema: kitSequenceListOutputSchema,
displayName: 'List Sequences',
description: 'Returns a list of all sequences',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Lists all sequences (automated email courses) in the account with their IDs and names. Use it to find a sequence ID before enrolling subscribers or listing enrollments. Takes no inputs; read-only and idempotent.',
@@ -35,9 +38,10 @@ export const addSubscriberToSequence = createAction({
auth: convertkitAuth,
name: 'sequences_add_subscriber_to_sequence',
classification: 'WRITE',
+ outputSchema: kitSubscriptionOutputSchema,
displayName: 'Add Subscriber To Sequence',
description: 'Add a subscriber to a sequence',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Enrolls an email address in a sequence so it starts receiving that automated email course, optionally setting first name, tags, and custom field values. Effectively idempotent — re-subscribing the same email to the same sequence upserts instead of duplicating the enrollment.',
@@ -68,7 +72,7 @@ export const addSubscriberToSequence = createAction({
body,
};
- const response = await httpClient.sendRequest<{
+ const response = await kitHttp.sendRequest<{
subscription: Sequence;
}>(request);
@@ -85,9 +89,10 @@ export const listSubscriptionsToSequence = createAction({
auth: convertkitAuth,
name: 'sequences_list_subscriptions_to_sequence',
classification: 'SEARCH',
+ outputSchema: kitSubscriptionListOutputSchema,
displayName: 'List Subscriptions To Sequence',
description: 'List all subscriptions to a sequence',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Lists all subscriber enrollments for one sequence by sequence ID. Use List Sequences first to find the ID. Read-only and idempotent.',
@@ -105,7 +110,7 @@ export const listSubscriptionsToSequence = createAction({
queryParams: buildQueryParams(context.auth.secret_text),
};
- const response = await httpClient.sendRequest<{
+ const response = await kitHttp.sendRequest<{
subscriptions: Sequence[];
}>(request);
diff --git a/packages/pieces/community/convertkit/src/lib/actions/subscribers.ts b/packages/pieces/community/convertkit/src/lib/actions/subscribers.ts
index 2a715aa5ff4..f4ed5fdb9d9 100644
--- a/packages/pieces/community/convertkit/src/lib/actions/subscribers.ts
+++ b/packages/pieces/community/convertkit/src/lib/actions/subscribers.ts
@@ -1,11 +1,8 @@
import { createAction } from '@activepieces/pieces-framework';
-import {
- httpClient,
- HttpMethod,
- HttpRequest,
-} from '@activepieces/pieces-common';
+import { HttpMethod, HttpRequest } from '@activepieces/pieces-common';
import { Subscriber } from '../common/types';
-import { convertkitAuth } from '../..';
+import { convertkitAuth } from '../auth';
+import { kitHttp } from '../common/http';
import {
subscriberId,
subscriberEmail,
@@ -30,14 +27,20 @@ import {
fetchSubscriberByEmail,
fetchSubscribedTags,
} from '../common/service';
+import {
+ kitSubscriberListOutputSchema,
+ kitSubscriberOutputSchema,
+ kitTagListOutputSchema,
+} from '../output-schemas';
export const getSubscriberById = createAction({
auth: convertkitAuth,
name: 'subscribers_get_subscriber_by_id',
classification: 'READ',
+ outputSchema: kitSubscriberOutputSchema,
displayName: 'Get Subscriber By Id',
description: 'Returns data for a single subscriber',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Fetches one subscriber record (email, name, state, custom fields) by numeric subscriber ID. Use Get Subscriber By Email when only an address is known. Read-only and idempotent.',
@@ -56,9 +59,10 @@ export const getSubscriberByEmail = createAction({
auth: convertkitAuth,
name: 'subscribers_get_subscriber_by_email',
classification: 'READ',
+ outputSchema: kitSubscriberOutputSchema,
displayName: 'Get Subscriber By Email',
description: 'Returns data for a single subscriber',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Looks up a single subscriber by email address and returns the full record including the numeric subscriber ID. Prefer this over Get Subscriber By Id when the ID is unknown. Read-only and idempotent.',
@@ -77,9 +81,10 @@ export const listSubscribers = createAction({
auth: convertkitAuth,
name: 'subscribers_list_subscribers',
classification: 'SEARCH',
+ outputSchema: kitSubscriberListOutputSchema,
displayName: 'List Subscribers',
description: 'Returns a list of all subscribers',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Lists subscribers with optional filters (created/updated date ranges, email address), paging, and sorting. Use it for bulk audits or fuzzy searches; for one known subscriber prefer the Get Subscriber actions. Read-only and idempotent.',
@@ -124,7 +129,7 @@ export const listSubscribers = createAction({
}),
};
- const response = await httpClient.sendRequest<{
+ const response = await kitHttp.sendRequest<{
subscribers: Subscriber[];
}>(request);
@@ -140,9 +145,10 @@ export const updateSubscriber = createAction({
auth: convertkitAuth,
name: 'subscribers_update_subscriber',
classification: 'WRITE',
+ outputSchema: kitSubscriberOutputSchema,
displayName: 'Update Subscriber',
description: 'Update a subscriber',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Updates a subscriber email address, first name, or custom field values by numeric subscriber ID. Idempotent — repeating the same update leaves the subscriber in the same state. It cannot change subscription status; use Unsubscribe Subscriber for that.',
@@ -172,7 +178,7 @@ export const updateSubscriber = createAction({
body,
};
- const response = await httpClient.sendRequest<{ subscriber: Subscriber }>(
+ const response = await kitHttp.sendRequest<{ subscriber: Subscriber }>(
request
);
@@ -188,9 +194,10 @@ export const unsubscribeSubscriber = createAction({
auth: convertkitAuth,
name: 'subscribers_unsubscribe_subscriber',
classification: 'DESTRUCTIVE',
+ outputSchema: kitSubscriberOutputSchema,
displayName: 'Unsubscribe Subscriber',
description: 'Unsubscribe a subscriber',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Unsubscribes the given email address from all emails in the account; this is the only removal mechanism, as there is no delete-subscriber action. Treated as non-idempotent — a retry may error once the address is already unsubscribed, though the end state is the same.',
@@ -211,7 +218,7 @@ export const unsubscribeSubscriber = createAction({
body,
};
- const response = await httpClient.sendRequest<{
+ const response = await kitHttp.sendRequest<{
subscriber: Subscriber;
}>(request);
@@ -227,9 +234,10 @@ export const listTagsBySubscriberId = createAction({
auth: convertkitAuth,
name: 'subscribers_list_tags_by_subscriber_id',
classification: 'SEARCH',
+ outputSchema: kitTagListOutputSchema,
displayName: 'List Tags By Subscriber Id',
description: 'Returns a list of all subscribed tags',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Lists all tags currently applied to a subscriber, looked up by numeric subscriber ID. Use List Tags By Email when only an address is known. Read-only and idempotent.',
@@ -248,9 +256,10 @@ export const listSubscriberTagsByEmail = createAction({
auth: convertkitAuth,
name: 'subscribers_list_tags_by_email',
classification: 'SEARCH',
+ outputSchema: kitTagListOutputSchema,
displayName: 'List Tags By Email',
description: 'Returns a list of all subscribed tags',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Lists all tags applied to a subscriber, looked up by email address (the email is resolved to a subscriber ID internally). Read-only and idempotent.',
diff --git a/packages/pieces/community/convertkit/src/lib/actions/tags.ts b/packages/pieces/community/convertkit/src/lib/actions/tags.ts
index 7964be6e93b..4c2e86f8a69 100644
--- a/packages/pieces/community/convertkit/src/lib/actions/tags.ts
+++ b/packages/pieces/community/convertkit/src/lib/actions/tags.ts
@@ -1,10 +1,7 @@
import { createAction } from '@activepieces/pieces-framework';
-import {
- httpClient,
- HttpMethod,
- HttpRequest,
-} from '@activepieces/pieces-common';
-import { convertkitAuth } from '../..';
+import { HttpMethod, HttpRequest } from '@activepieces/pieces-common';
+import { convertkitAuth } from '../auth';
+import { kitHttp } from '../common/http';
import {
tag,
tagsRequired,
@@ -22,19 +19,29 @@ import {
} from '../common/subscribers';
import { Tag } from '../common/types';
import { allFields } from '../common/custom-fields';
-import { TAGS_API_ENDPOINT } from '../common/constants';
+import {
+ SUBSCRIBERS_API_ENDPOINT,
+ TAGS_API_ENDPOINT,
+} from '../common/constants';
import { buildQueryParams, fetchTags } from '../common/service';
+import {
+ kitSubscriptionListOutputSchema,
+ kitSubscriptionOutputSchema,
+ kitTagListOutputSchema,
+ kitTagOutputSchema,
+} from '../output-schemas';
export const listTags = createAction({
auth: convertkitAuth,
name: 'tags_list_tags',
classification: 'SEARCH',
+ outputSchema: kitTagListOutputSchema,
displayName: 'List Tags',
description: 'Returns a list of all tags',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
- 'Lists every tag in the account with its ID and name. Use it to find a tag ID before tagging or untagging subscribers, or before listing a tag\'s subscriptions. Takes no inputs; read-only and idempotent.',
+ "Lists every tag in the account with its ID and name. Use it to find a tag ID before tagging or untagging subscribers, or before listing a tag's subscriptions. Takes no inputs; read-only and idempotent.",
idempotent: true,
},
props: {},
@@ -47,9 +54,10 @@ export const createTag = createAction({
auth: convertkitAuth,
name: 'tags_create_tag',
classification: 'WRITE',
+ outputSchema: kitTagOutputSchema,
displayName: 'Create Tag',
description: 'Create a tag',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Creates a new tag with the given name. Not idempotent — calling it again can create a duplicate, so check List Tags for an existing tag first.',
@@ -72,7 +80,7 @@ export const createTag = createAction({
body,
};
- const response = await httpClient.sendRequest<{ tag: Tag }>(request);
+ const response = await kitHttp.sendRequest<Tag>(request);
if (response.status !== 201) {
throw new Error(`Error creating tag: ${response.status}`);
@@ -89,9 +97,10 @@ export const tagSubscriber = createAction({
auth: convertkitAuth,
name: 'tags_tag_subscriber',
classification: 'WRITE',
+ outputSchema: kitSubscriptionOutputSchema,
displayName: 'Tag Subscriber',
description: 'Tag a subscriber',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Applies one or more existing tags to a subscriber by email address (subscribing the email to the first tag and attaching the rest), optionally setting first name and custom fields; at least one tag is required. Effectively idempotent — re-applying the same tags converges to the same state.',
@@ -127,7 +136,7 @@ export const tagSubscriber = createAction({
body,
};
- const response = await httpClient.sendRequest<{
+ const response = await kitHttp.sendRequest<{
subscription: Tag;
}>(request);
@@ -143,9 +152,10 @@ export const removeTagFromSubscriberByEmail = createAction({
auth: convertkitAuth,
name: 'tags_remove_tag_from_subscriber_by_email',
classification: 'WRITE',
+ outputSchema: kitTagOutputSchema,
displayName: 'Remove Tag From Subscriber By Email',
description: 'Remove a tag from a subscriber by email',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Removes a single tag from a subscriber identified by email address. Use the By Id variant when the numeric subscriber ID is already known. Treated as non-idempotent — a retry may error once the tag is already removed, though the end state is the same.',
@@ -170,7 +180,7 @@ export const removeTagFromSubscriberByEmail = createAction({
body,
};
- const response = await httpClient.sendRequest<{ subscriber: Tag }>(request);
+ const response = await kitHttp.sendRequest<{ subscriber: Tag }>(request);
if (response.status !== 200) {
throw new Error(`Error removing tag from subscriber: ${response.status}`);
@@ -184,9 +194,10 @@ export const removeTagFromSubscriberById = createAction({
auth: convertkitAuth,
name: 'tags_remove_tag_from_subscriber_by_id',
classification: 'WRITE',
+ outputSchema: kitTagOutputSchema,
displayName: 'Remove Tag From Subscriber By Id',
description: 'Remove a tag from a subscriber by id',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Removes a single tag from a subscriber identified by numeric subscriber ID. Use the By Email variant when only an address is known. Treated as non-idempotent — a retry may error once the tag is already removed.',
@@ -198,20 +209,15 @@ export const removeTagFromSubscriberById = createAction({
},
async run(context) {
const { subscriberId, tagId } = context.propsValue;
- const url = `${TAGS_API_ENDPOINT}/${tagId}/unsubscribe`;
-
- const body = {
- id: subscriberId,
- api_secret: context.auth.secret_text,
- };
+ const url = `${SUBSCRIBERS_API_ENDPOINT}/${subscriberId}/tags/${tagId}`;
const request: HttpRequest = {
url,
- method: HttpMethod.POST,
- body,
+ method: HttpMethod.DELETE,
+ queryParams: buildQueryParams(context.auth.secret_text),
};
- const response = await httpClient.sendRequest<{ subscriber: Tag }>(request);
+ const response = await kitHttp.sendRequest<{ subscriber: Tag }>(request);
if (response.status !== 200) {
throw new Error(`Error removing tag from subscriber: ${response.status}`);
@@ -225,9 +231,10 @@ export const listSubscriptionsToATag = createAction({
auth: convertkitAuth,
name: 'tags_list_subscriptions_to_tag',
classification: 'SEARCH',
+ outputSchema: kitSubscriptionListOutputSchema,
displayName: 'List Subscriptions To Tag',
description: 'List all subscriptions to a tag',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Lists the subscribers subscribed to a specific tag, with paging, sort order, and subscriber-state filtering. Use List Tags first to find the tag ID. Read-only and idempotent.',
@@ -253,7 +260,7 @@ export const listSubscriptionsToATag = createAction({
}),
};
- const response = await httpClient.sendRequest<{
+ const response = await kitHttp.sendRequest<{
subscriptions: Tag[];
}>(request);
diff --git a/packages/pieces/community/convertkit/src/lib/actions/webhooks.ts b/packages/pieces/community/convertkit/src/lib/actions/webhooks.ts
index 26cf37b5e58..a1efc8b63cd 100644
--- a/packages/pieces/community/convertkit/src/lib/actions/webhooks.ts
+++ b/packages/pieces/community/convertkit/src/lib/actions/webhooks.ts
@@ -1,5 +1,5 @@
import { createAction } from '@activepieces/pieces-framework';
-import { convertkitAuth } from '../..';
+import { convertkitAuth } from '../auth';
import {
targetUrl,
event,
@@ -10,14 +10,16 @@ import {
createWebhook as createWebhookAction,
removeWebhook as removeWebhookAction,
} from '../common/service';
+import { kitWebhookOutputSchema } from '../output-schemas';
export const createWebhook = createAction({
auth: convertkitAuth,
name: 'create_webhook',
classification: 'WRITE',
+ outputSchema: kitWebhookOutputSchema,
displayName: 'Add Webhook',
description: 'Create a webhook automation',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Registers a webhook automation that POSTs to a target URL whenever the chosen ConvertKit event fires (e.g. subscriber activated, tag added); some events also need an event parameter such as a tag or form ID. Not idempotent — each call registers another webhook, so keep the returned rule ID for later deletion.',
@@ -49,7 +51,7 @@ export const deleteWebhook = createAction({
classification: 'DESTRUCTIVE',
displayName: 'Delete Webhook',
description: 'Delete a webhook automation',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Deletes a previously registered webhook automation by its webhook rule ID (returned when the webhook was created). Not retry-safe — a repeat call fails once the webhook is gone.',
diff --git a/packages/pieces/community/convertkit/src/lib/auth.ts b/packages/pieces/community/convertkit/src/lib/auth.ts
new file mode 100644
index 00000000000..99b83d9d52d
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/auth.ts
@@ -0,0 +1,33 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { PieceAuth } from '@activepieces/pieces-framework';
+import { CONVERTKIT_API_URL } from './common/constants';
+import { kitErrorStatus, kitHttp } from './common/http';
+
+export const convertkitAuth = PieceAuth.SecretText({
+ displayName: 'API Secret',
+ description:
+ 'Enter your API Secret key. In Kit, go to Settings > Developer, open the V3 Key section and copy the API Secret.',
+ required: true,
+ validate: async ({ auth }) => {
+ try {
+ await kitHttp.sendRequest({
+ method: HttpMethod.GET,
+ url: `${CONVERTKIT_API_URL}/account`,
+ queryParams: { api_secret: auth },
+ });
+ return { valid: true };
+ } catch (error) {
+ const status = kitErrorStatus(error);
+ if (status === 401 || status === 403) {
+ return {
+ valid: false,
+ error: 'Kit rejected this API Secret. Use the V3 API Secret from Kit Settings > Developer, not the API Key or a V4 key.',
+ };
+ }
+ return {
+ valid: false,
+ error: `Could not check the API Secret with Kit: ${error instanceof Error ? error.message : 'unknown error'}`,
+ };
+ }
+ },
+});
diff --git a/packages/pieces/community/convertkit/src/lib/common/ai-props.ts b/packages/pieces/community/convertkit/src/lib/common/ai-props.ts
new file mode 100644
index 00000000000..72875914863
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/common/ai-props.ts
@@ -0,0 +1,64 @@
+import { Property } from '@activepieces/pieces-framework';
+
+export const kitProps = {
+ page: (description: string) =>
+ Property.Number({
+ displayName: 'Page',
+ description,
+ required: false,
+ defaultValue: 1,
+ }),
+ sortOrder: (description: string) =>
+ Property.StaticDropdown({
+ displayName: 'Sort Order',
+ description,
+ required: false,
+ options: {
+ options: [
+ { label: 'Ascending (oldest first)', value: 'asc' },
+ { label: 'Descending (newest first)', value: 'desc' },
+ ],
+ },
+ }),
+ subscriberState: Property.StaticDropdown({
+ displayName: 'Subscriber State',
+ description:
+ 'Return only active or only cancelled subscriptions. Leave empty for the Kit default.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Active', value: 'active' },
+ { label: 'Cancelled', value: 'cancelled' },
+ ],
+ },
+ }),
+ email: (description: string) =>
+ Property.ShortText({
+ displayName: 'Email',
+ description,
+ required: true,
+ }),
+ firstName: Property.ShortText({
+ displayName: 'First Name',
+ description: 'The first name to store on the subscriber.',
+ required: false,
+ }),
+ fields: Property.Json({
+ displayName: 'Custom Fields',
+ description:
+ 'A JSON object of custom field key to value, e.g. {"last_name": "Snow"}. Keys must already exist; get them from List Custom Fields.',
+ required: false,
+ }),
+ tagIds: (displayName: string, description: string) =>
+ Property.Array({
+ displayName,
+ description,
+ required: false,
+ }),
+ id: (displayName: string, description: string) =>
+ Property.ShortText({
+ displayName,
+ description,
+ required: true,
+ }),
+};
diff --git a/packages/pieces/community/convertkit/src/lib/common/client.ts b/packages/pieces/community/convertkit/src/lib/common/client.ts
new file mode 100644
index 00000000000..f1d34b19ee5
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/common/client.ts
@@ -0,0 +1,158 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { CONVERTKIT_API_URL } from './constants';
+import { buildQueryParams } from './service';
+import { kitHttp } from './http';
+
+type QueryValue = string | number | undefined | null;
+
+export const kitClient = {
+ async request<T>({
+ apiSecret,
+ method,
+ path,
+ query,
+ body,
+ }: {
+ apiSecret: string;
+ method: HttpMethod;
+ path: string;
+ query?: Record<string, QueryValue>;
+ body?: Record<string, unknown>;
+ }): Promise<{ status: number; body: T }> {
+ const hasBody = method === HttpMethod.POST || method === HttpMethod.PUT;
+ const response = await kitHttp.sendRequest<T>({
+ method,
+ url: `${CONVERTKIT_API_URL}${path}`,
+ queryParams: buildQueryParams(apiSecret, query ?? {}),
+ body: hasBody ? body ?? {} : undefined,
+ });
+ return { status: response.status, body: response.body };
+ },
+};
+
+const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
+const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+
+export const kitCommon = {
+ id({ value, label }: { value: unknown; label: string }): string {
+ const text = typeof value === 'number' ? String(value) : typeof value === 'string' ? value.trim() : '';
+ if (!/^\d+$/.test(text)) {
+ throw new Error(`${label} must be a numeric Kit ID, got "${String(value ?? '')}".`);
+ }
+ return text;
+ },
+ page(value: unknown): number {
+ if (value === undefined || value === null || value === '') {
+ return 1;
+ }
+ const page = Number(value);
+ if (!Number.isInteger(page) || page < 1) {
+ throw new Error(`Page must be a whole number of 1 or more, got "${String(value)}".`);
+ }
+ return page;
+ },
+ email({ value, label }: { value: unknown; label: string }): string {
+ const text = typeof value === 'string' ? value.trim() : '';
+ if (!EMAIL.test(text)) {
+ throw new Error(`${label} must be a valid email address, got "${String(value ?? '')}".`);
+ }
+ return text;
+ },
+ toDate(value: unknown): string | undefined {
+ if (value === undefined || value === null || value === '') {
+ return undefined;
+ }
+ const text = String(value).trim().slice(0, 10);
+ if (!ISO_DATE.test(text) || Number.isNaN(Date.parse(`${text}T00:00:00Z`))) {
+ throw new Error(`"${String(value)}" is not a valid date. Use YYYY-MM-DD.`);
+ }
+ return text;
+ },
+ toDateTime({
+ value,
+ label,
+ future = false,
+ }: {
+ value: unknown;
+ label: string;
+ future?: boolean;
+ }): string | undefined {
+ if (value === undefined || value === null || value === '') {
+ return undefined;
+ }
+ const text = String(value).trim();
+ const time = Date.parse(text);
+ if (Number.isNaN(time)) {
+ throw new Error(`${label} must be an ISO 8601 date-time, got "${text}".`);
+ }
+ if (future && time <= Date.now()) {
+ throw new Error(`${label} must be in the future, got "${text}".`);
+ }
+ return text;
+ },
+ toIdList(value: unknown): number[] | undefined {
+ if (value === undefined || value === null || value === '') {
+ return undefined;
+ }
+ if (typeof value === 'number') {
+ return kitCommon.toIdList([value]);
+ }
+ if (typeof value === 'string') {
+ const text = value.trim();
+ if (text.startsWith('[')) {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(text);
+ } catch {
+ throw new Error(`"${text}" is not a valid list of IDs. Use a JSON array like [123, 456] or comma-separated IDs.`);
+ }
+ return kitCommon.toIdList(parsed);
+ }
+ return kitCommon.toIdList(
+ text
+ .split(',')
+ .map((part) => part.trim())
+ .filter((part) => part.length > 0),
+ );
+ }
+ if (!Array.isArray(value)) {
+ throw new Error('IDs must be a list of numeric IDs.');
+ }
+ if (value.length === 0) {
+ return undefined;
+ }
+ return value.map((item) => {
+ const id = Number(item);
+ if (!Number.isInteger(id)) {
+ throw new Error(`"${String(item)}" is not a valid numeric ID.`);
+ }
+ return id;
+ });
+ },
+ toFields(value: unknown): Record<string, unknown> | undefined {
+ if (value === undefined || value === null || value === '') {
+ return undefined;
+ }
+ if (typeof value === 'string') {
+ try {
+ return kitCommon.toFields(JSON.parse(value));
+ } catch {
+ throw new Error('Custom Fields must be a JSON object of field key to value.');
+ }
+ }
+ if (typeof value !== 'object' || Array.isArray(value)) {
+ throw new Error('Custom Fields must be a JSON object of field key to value.');
+ }
+ const fields: Record<string, unknown> = Object.fromEntries(Object.entries(value));
+ return Object.keys(fields).length > 0 ? fields : undefined;
+ },
+ compact(values: Record<string, unknown>): Record<string, unknown> {
+ const result: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(values)) {
+ if (value !== undefined && value !== null && value !== '') {
+ result[key] = value;
+ }
+ }
+ return result;
+ },
+};
diff --git a/packages/pieces/community/convertkit/src/lib/common/custom-api-guard.ts b/packages/pieces/community/convertkit/src/lib/common/custom-api-guard.ts
new file mode 100644
index 00000000000..a0d46c77e68
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/common/custom-api-guard.ts
@@ -0,0 +1,54 @@
+import { CONVERTKIT_API_URL } from './constants';
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+const KIT_ORIGIN = new URL(CONVERTKIT_API_URL).origin;
+const KIT_PATH = new URL(CONVERTKIT_API_URL).pathname;
+
+const resolveTarget = (url: string): string => {
+ if (url.startsWith('http://') || url.startsWith('https://')) {
+ return url;
+ }
+ const relative = url.startsWith('/') ? url.slice(1) : url;
+ return `${CONVERTKIT_API_URL}/${relative}`;
+};
+
+const hasDotSegment = (url: string): boolean => {
+ const path = url.split(/[?#]/)[0] ?? '';
+ return path
+ .split('/')
+ .some((segment) => {
+ const decoded = segment.replace(/%2e/gi, '.');
+ return decoded === '.' || decoded === '..';
+ });
+};
+
+const isKitTarget = (url: string): boolean => {
+ if (url.startsWith('//') || url.includes('\\') || hasDotSegment(url)) {
+ return false;
+ }
+ let target: URL;
+ try {
+ target = new URL(resolveTarget(url));
+ } catch {
+ return false;
+ }
+ if (target.origin !== KIT_ORIGIN || target.username !== '' || target.password !== '') {
+ return false;
+ }
+ return target.pathname === KIT_PATH || target.pathname.startsWith(`${KIT_PATH}/`);
+};
+
+export const assertKitUrl = (propsValue: unknown): void => {
+ const urlProp = isRecord(propsValue) ? propsValue['url'] : undefined;
+ const url = isRecord(urlProp) ? urlProp['url'] : undefined;
+ if (typeof url !== 'string') {
+ return;
+ }
+ if (!isKitTarget(url.trim())) {
+ throw new Error(
+ `Custom API Call only sends your Kit API Secret to ${CONVERTKIT_API_URL}. Use a path relative to it, e.g. /subscribers.`
+ );
+ }
+};
diff --git a/packages/pieces/community/convertkit/src/lib/common/custom-fields/index.ts b/packages/pieces/community/convertkit/src/lib/common/custom-fields/index.ts
index 7b6e30b1248..d8836e90776 100644
--- a/packages/pieces/community/convertkit/src/lib/common/custom-fields/index.ts
+++ b/packages/pieces/community/convertkit/src/lib/common/custom-fields/index.ts
@@ -1,7 +1,7 @@
import { Property, DynamicPropsValue } from '@activepieces/pieces-framework';
import { CustomField } from '../types';
import { fetchCustomFields } from '../service';
-import { convertkitAuth } from '../../..';
+import { convertkitAuth } from '../../auth';
export const fieldsArray = Property.Array({
displayName: 'Fields',
diff --git a/packages/pieces/community/convertkit/src/lib/common/forms/index.ts b/packages/pieces/community/convertkit/src/lib/common/forms/index.ts
index 0068b23a14e..6d338370c97 100644
--- a/packages/pieces/community/convertkit/src/lib/common/forms/index.ts
+++ b/packages/pieces/community/convertkit/src/lib/common/forms/index.ts
@@ -1,6 +1,6 @@
import { Property } from '@activepieces/pieces-framework';
import { fetchForms } from '../../common/service';
-import { convertkitAuth } from '../../..';
+import { convertkitAuth } from '../../auth';
export const formId = Property.Dropdown({
displayName: 'Form',
diff --git a/packages/pieces/community/convertkit/src/lib/common/http.ts b/packages/pieces/community/convertkit/src/lib/common/http.ts
new file mode 100644
index 00000000000..07c12789813
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/common/http.ts
@@ -0,0 +1,123 @@
+import {
+ httpClient,
+ HttpRequest,
+ HttpResponse,
+} from '@activepieces/pieces-common';
+
+export const describeKitError = ({
+ status,
+ body,
+}: {
+ status: number;
+ body: unknown;
+}): string => {
+ const detail = typeof body === 'string' ? body : JSON.stringify(body);
+ if (status === 401) {
+ return `Kit rejected the API Secret (401). Reconnect with the V3 API Secret from Kit Settings > Developer. ${detail}`;
+ }
+ if (status === 404) {
+ return `Kit could not find the requested resource (404). Check the ID. ${detail}`;
+ }
+ if (status === 422) {
+ return `Kit rejected the request (422). ${detail}`;
+ }
+ if (status === 429) {
+ return `Kit rate limit reached (429). Wait a moment and retry. ${detail}`;
+ }
+ return `Kit API request failed (${status}). ${detail}`;
+};
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+const secretsOf = (request: HttpRequest): string[] => {
+ const values: unknown[] = [
+ isRecord(request.body) ? request.body['api_secret'] : undefined,
+ request.queryParams?.['api_secret'],
+ ];
+ return values.filter(
+ (value): value is string => typeof value === 'string' && value.length > 0
+ );
+};
+
+export const redactKitSecret = ({
+ text,
+ secrets = [],
+}: {
+ text: string;
+ secrets?: string[];
+}): string => {
+ let result = text;
+ for (const secret of secrets) {
+ result = result.split(secret).join('[redacted]');
+ }
+ return result
+ .replace(/("api_secret"\s*:\s*")[^"]*(")/g, '$1[redacted]$2')
+ .replace(/(\\"api_secret\\"\s*:\s*\\")[^\\"]*(\\")/g, '$1[redacted]$2')
+ .replace(/(api_secret=)[^&\s"]*/g, '$1[redacted]');
+};
+
+const responseOf = (
+ error: unknown
+): { status: number; body: unknown } | undefined => {
+ if (!isRecord(error) || !isRecord(error['response'])) {
+ return undefined;
+ }
+ const status = error['response']['status'];
+ if (typeof status !== 'number' || status === 0) {
+ return undefined;
+ }
+ return { status, body: error['response']['body'] };
+};
+
+const withSecretInQuery = (request: HttpRequest): HttpRequest => {
+ if (!isRecord(request.body)) {
+ return request;
+ }
+ const secret = request.body['api_secret'];
+ if (typeof secret !== 'string') {
+ return request;
+ }
+ const body = Object.fromEntries(
+ Object.entries(request.body).filter(([key]) => key !== 'api_secret')
+ );
+ return {
+ ...request,
+ body,
+ queryParams: { ...(request.queryParams ?? {}), api_secret: secret },
+ };
+};
+
+export const kitErrorStatus = (error: unknown): number | undefined => {
+ if (!isRecord(error)) {
+ return undefined;
+ }
+ const status = error['status'];
+ return typeof status === 'number' ? status : undefined;
+};
+
+export const kitHttp = {
+ async sendRequest<T>(
+ request: HttpRequest
+ ): Promise<HttpResponse<T>> {
+ try {
+ return await httpClient.sendRequest<T>(withSecretInQuery(request));
+ } catch (error) {
+ const secrets = secretsOf(request);
+ const response = responseOf(error);
+ if (response) {
+ throw Object.assign(
+ new Error(redactKitSecret({ text: describeKitError(response), secrets })),
+ { status: response.status }
+ );
+ }
+ throw new Error(
+ `Kit API request failed: ${
+ error instanceof Error
+ ? redactKitSecret({ text: error.message, secrets })
+ : 'unknown error'
+ }`
+ );
+ }
+ },
+};
diff --git a/packages/pieces/community/convertkit/src/lib/common/sequences/index.ts b/packages/pieces/community/convertkit/src/lib/common/sequences/index.ts
index 6e6219545d4..2352cc6b51c 100644
--- a/packages/pieces/community/convertkit/src/lib/common/sequences/index.ts
+++ b/packages/pieces/community/convertkit/src/lib/common/sequences/index.ts
@@ -1,6 +1,6 @@
import { Property } from '@activepieces/pieces-framework';
import { fetchSequences } from '../../common/service';
-import { convertkitAuth } from '../../..';
+import { convertkitAuth } from '../../auth';
export const sequenceId = Property.ShortText({
displayName: 'Sequence ID',
diff --git a/packages/pieces/community/convertkit/src/lib/common/service.ts b/packages/pieces/community/convertkit/src/lib/common/service.ts
index cad1b729213..aad39a1912a 100644
--- a/packages/pieces/community/convertkit/src/lib/common/service.ts
+++ b/packages/pieces/community/convertkit/src/lib/common/service.ts
@@ -19,11 +19,12 @@ import {
WEBHOOKS_API_ENDPOINT,
} from './constants';
import {
- httpClient,
HttpMethod,
HttpRequest,
QueryParams,
} from '@activepieces/pieces-common';
+import { Store } from '@activepieces/pieces-framework';
+import { kitErrorStatus, kitHttp } from './http';
export const buildQueryParams = (
auth: string,
@@ -45,7 +46,7 @@ export const fetchBroadcasts = async (auth: string, page: number) => {
method: HttpMethod.GET,
queryParams: buildQueryParams(auth, { page, sort_order: 'desc' }),
};
- const response = await httpClient.sendRequest<{ broadcasts: Broadcast[] }>(
+ const response = await kitHttp.sendRequest<{ broadcasts: Broadcast[] }>(
request
);
@@ -74,7 +75,7 @@ export const fetchCustomFields = async (
queryParams: buildQueryParams(auth),
method: HttpMethod.GET,
};
- const response = await httpClient.sendRequest<{
+ const response = await kitHttp.sendRequest<{
custom_fields: CustomField[];
}>(request);
@@ -101,7 +102,7 @@ export const fetchForms = async (auth: string) => {
queryParams: buildQueryParams(auth),
method: HttpMethod.GET,
};
- const response = await httpClient.sendRequest<{ forms: Form[] }>(request);
+ const response = await kitHttp.sendRequest<{ forms: Form[] }>(request);
const errorMessage = `Failed to fetch forms. Response code: ${
response.status
@@ -126,7 +127,7 @@ export const fetchPurchases = async (auth: string, page: number) => {
queryParams: buildQueryParams(auth, { page }),
method: HttpMethod.GET,
};
- const response = await httpClient.sendRequest<{ purchases: Purchase[] }>(
+ const response = await kitHttp.sendRequest<{ purchases: Purchase[] }>(
request
);
@@ -152,7 +153,7 @@ export const fetchSequences = async (auth: string) => {
queryParams: buildQueryParams(auth),
method: HttpMethod.GET,
};
- const response = await httpClient.sendRequest<{ courses: Sequence[] }>(
+ const response = await kitHttp.sendRequest<{ courses: Sequence[] }>(
request
);
@@ -182,7 +183,7 @@ export const fetchSubscriperById = async (
method: HttpMethod.GET,
};
- const response = await httpClient.sendRequest<{ subscriber: Subscriber }>(
+ const response = await kitHttp.sendRequest<{ subscriber: Subscriber }>(
request
);
@@ -212,7 +213,7 @@ export const fetchSubscriberByEmail = async (
method: HttpMethod.GET,
};
- const response = await httpClient.sendRequest<{ subscribers: Subscriber[] }>(
+ const response = await kitHttp.sendRequest<{ subscribers: Subscriber[] }>(
request
);
@@ -244,7 +245,7 @@ export const fetchSubscribedTags = async (
method: HttpMethod.GET,
};
- const response = await httpClient.sendRequest<{ tags: Tag[] }>(request);
+ const response = await kitHttp.sendRequest<{ tags: Tag[] }>(request);
const errorMessage = `Failed to fetch tags. Response code: ${
response.status
@@ -268,7 +269,7 @@ export const fetchTags = async (auth: string) => {
method: HttpMethod.GET,
};
- const response = await httpClient.sendRequest<{ tags: Tag[] }>(request);
+ const response = await kitHttp.sendRequest<{ tags: Tag[] }>(request);
const errorMessage = `Failed to fetch tags. Response code: ${
response.status
@@ -295,7 +296,7 @@ export const createWebhook = async (auth: string, payload: object) => {
method: HttpMethod.POST,
};
- const response = await httpClient.sendRequest<{ rule: Webhook }>(request);
+ const response = await kitHttp.sendRequest<{ rule: Webhook }>(request);
const errorMessage = `Failed to create webhook. Response code: ${
response.status
@@ -322,7 +323,7 @@ export const removeWebhook = async (auth: string, ruleId: number) => {
method: HttpMethod.DELETE,
};
- const response = await httpClient.sendRequest<{ success: boolean }>(request);
+ const response = await kitHttp.sendRequest<{ success: boolean }>(request);
const errorMessage = `Failed to remove webhook. Response code: ${
response.status
@@ -337,3 +338,60 @@ export const removeWebhook = async (auth: string, ruleId: number) => {
throw new Error(errorMessage);
};
+
+type WebhookInformation = {
+ ruleId: number;
+};
+
+export const kitWebhookLifecycle = {
+ async enable({
+ apiSecret,
+ store,
+ storeKey,
+ payload,
+ }: {
+ apiSecret: string;
+ store: Store;
+ storeKey: string;
+ payload: object;
+ }): Promise<void> {
+ const rule = await createWebhook(apiSecret, payload);
+ try {
+ await store.put<WebhookInformation>(storeKey, { ruleId: rule.id });
+ } catch (error) {
+ const reason = error instanceof Error ? error.message : 'unknown error';
+ try {
+ await removeWebhook(apiSecret, rule.id);
+ } catch (cleanupError) {
+ throw new Error(
+ `Saving the Kit webhook rule ${rule.id} failed (${reason}) and removing it also failed (${
+ cleanupError instanceof Error ? cleanupError.message : 'unknown error'
+ }). Delete it in Kit to stop duplicate deliveries.`
+ );
+ }
+ throw new Error(`Saving the Kit webhook rule failed, so it was removed again: ${reason}`);
+ }
+ },
+ async disable({
+ apiSecret,
+ store,
+ storeKey,
+ }: {
+ apiSecret: string;
+ store: Store;
+ storeKey: string;
+ }): Promise<void> {
+ const saved = await store.get<WebhookInformation>(storeKey);
+ if (saved === null || saved === undefined) {
+ return;
+ }
+ try {
+ await removeWebhook(apiSecret, saved.ruleId);
+ } catch (error) {
+ if (kitErrorStatus(error) !== 404) {
+ throw error;
+ }
+ }
+ await store.delete(storeKey);
+ },
+};
diff --git a/packages/pieces/community/convertkit/src/lib/common/tags/index.ts b/packages/pieces/community/convertkit/src/lib/common/tags/index.ts
index 574e9a7d65b..fbb68c3f142 100644
--- a/packages/pieces/community/convertkit/src/lib/common/tags/index.ts
+++ b/packages/pieces/community/convertkit/src/lib/common/tags/index.ts
@@ -6,8 +6,8 @@ import {
fetchSubscribedTags,
fetchTags,
} from '../service';
-import { Tag, AuthEmail } from '../types';
-import { convertkitAuth } from '../../..';
+import { Tag } from '../types';
+import { convertkitAuth } from '../../auth';
export const tagId = Property.ShortText({
displayName: 'Tag Id',
@@ -106,7 +106,7 @@ export const subscriberState = Property.StaticDropdown({
options: {
options: [
{ label: 'Active', value: 'active' },
- { label: 'canceled', value: 'canceled' },
+ { label: 'Cancelled', value: 'cancelled' },
],
},
});
diff --git a/packages/pieces/community/convertkit/src/lib/common/webhooks/index.ts b/packages/pieces/community/convertkit/src/lib/common/webhooks/index.ts
index c5767b9fa85..738a54efd34 100644
--- a/packages/pieces/community/convertkit/src/lib/common/webhooks/index.ts
+++ b/packages/pieces/community/convertkit/src/lib/common/webhooks/index.ts
@@ -1,7 +1,7 @@
import { Property, DynamicPropsValue } from '@activepieces/pieces-framework';
import { EventType, EventOption } from '../types';
import { fetchTags, fetchForms, fetchSequences } from '../service';
-import { convertkitAuth } from '../../..';
+import { convertkitAuth } from '../../auth';
export const initiatorValue = Property.ShortText({
displayName: 'Initiator Value URL',
diff --git a/packages/pieces/community/convertkit/src/lib/output-schemas.ts b/packages/pieces/community/convertkit/src/lib/output-schemas.ts
new file mode 100644
index 00000000000..33783872545
--- /dev/null
+++ b/packages/pieces/community/convertkit/src/lib/output-schemas.ts
@@ -0,0 +1,447 @@
+import { OutputSchema } from '@activepieces/pieces-framework';
+
+const subscriberFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Subscriber ID', format: 'number' },
+ { key: 'first_name', label: 'First Name' },
+ { key: 'email_address', label: 'Email Address', format: 'email' },
+ { key: 'state', label: 'State' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'fields', label: 'Custom Fields', dynamicKey: true },
+];
+
+const tagFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Tag ID', format: 'number' },
+ { key: 'name', label: 'Name' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+];
+
+const customFieldFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Custom Field ID', format: 'number' },
+ { key: 'key', label: 'Key' },
+ { key: 'label', label: 'Label' },
+ { key: 'name', label: 'Internal Name' },
+];
+
+const subscriptionFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Subscription ID', format: 'number' },
+ { key: 'state', label: 'State' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'source', label: 'Source' },
+ { key: 'referrer', label: 'Referrer', format: 'url' },
+ { key: 'subscribable_id', label: 'Subscribed To ID', format: 'number' },
+ { key: 'subscribable_type', label: 'Subscribed To Type' },
+ { key: 'subscriber', label: 'Subscriber', children: subscriberFields },
+];
+
+const broadcastSummaryFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Broadcast ID', format: 'number' },
+ { key: 'subject', label: 'Subject' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+];
+
+const broadcastFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Broadcast ID', format: 'number' },
+ { key: 'subject', label: 'Subject' },
+ { key: 'description', label: 'Description' },
+ { key: 'content', label: 'Content', format: 'html' },
+ { key: 'public', label: 'Public', format: 'boolean' },
+ { key: 'published_at', label: 'Published At', format: 'datetime' },
+ { key: 'send_at', label: 'Send At', format: 'datetime' },
+ { key: 'email_address', label: 'From Email', format: 'email' },
+ { key: 'email_layout_template', label: 'Email Template' },
+ { key: 'thumbnail_url', label: 'Thumbnail URL', format: 'image' },
+ { key: 'thumbnail_alt', label: 'Thumbnail Alt Text' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+];
+
+const broadcastStatsFields: OutputSchema['fields'] = [
+ { key: 'status', label: 'Status' },
+ { key: 'recipients', label: 'Recipients', format: 'number' },
+ { key: 'emails_opened', label: 'Emails Opened', format: 'number' },
+ { key: 'open_rate', label: 'Open Rate', format: 'number' },
+ { key: 'emails_clicked', label: 'Emails Clicked', format: 'number' },
+ { key: 'total_clicks', label: 'Total Clicks', format: 'number' },
+ { key: 'click_rate', label: 'Click Rate', format: 'number' },
+ { key: 'unsubscribes', label: 'Unsubscribes', format: 'number' },
+ { key: 'unsubscribe_rate', label: 'Unsubscribe Rate', format: 'number' },
+ { key: 'progress', label: 'Progress', format: 'number' },
+ { key: 'show_total_clicks', label: 'Show Total Clicks', format: 'boolean' },
+ {
+ key: 'open_tracking_disabled',
+ label: 'Open Tracking Disabled',
+ format: 'boolean',
+ },
+ {
+ key: 'click_tracking_disabled',
+ label: 'Click Tracking Disabled',
+ format: 'boolean',
+ },
+];
+
+const webhookRuleFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Webhook ID', format: 'number' },
+ { key: 'target_url', label: 'Target URL', format: 'url' },
+ {
+ key: 'event',
+ label: 'Event',
+ children: [
+ { key: 'name', label: 'Event Name' },
+ { key: 'tag_id', label: 'Tag ID', format: 'number' },
+ { key: 'initiator_value', label: 'Link URL', format: 'url' },
+ ],
+ },
+ { key: 'account_id', label: 'Account ID', format: 'number' },
+];
+
+export const kitGetAccountOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'name', label: 'Account Name' },
+ { key: 'primary_email_address', label: 'Primary Email', format: 'email' },
+ { key: 'plan_type', label: 'Plan Type' },
+ ],
+};
+
+export const kitSubscriberOutputSchema: OutputSchema = {
+ fields: subscriberFields,
+};
+
+export const kitListSubscribersOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'subscribers',
+ label: 'Subscribers',
+ labelKey: 'email_address',
+ listItems: subscriberFields,
+ },
+ { key: 'page', label: 'Page', format: 'number' },
+ { key: 'total_pages', label: 'Total Pages', format: 'number' },
+ { key: 'total_subscribers', label: 'Total Subscribers', format: 'number' },
+ ],
+};
+
+export const kitSubscriberListOutputSchema: OutputSchema = {
+ itemLabel: '{email_address}',
+ fields: [
+ {
+ key: 'subscribers',
+ label: 'Subscribers',
+ value: '',
+ listItems: subscriberFields,
+ },
+ ],
+};
+
+export const kitTagOutputSchema: OutputSchema = {
+ fields: tagFields,
+};
+
+export const kitCreateTagOutputSchema: OutputSchema = {
+ fields: [
+ ...tagFields,
+ { key: 'created', label: 'Newly Created', format: 'boolean' },
+ ],
+};
+
+export const kitListTagsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'tags', label: 'Tags', labelKey: 'name', listItems: tagFields },
+ { key: 'count', label: 'Count', format: 'number' },
+ ],
+};
+
+export const kitTagListOutputSchema: OutputSchema = {
+ itemLabel: '{name}',
+ fields: [{ key: 'tags', label: 'Tags', value: '', listItems: tagFields }],
+};
+
+export const kitSubscriptionOutputSchema: OutputSchema = {
+ fields: subscriptionFields,
+};
+
+export const kitListTagSubscriptionsOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'subscriptions',
+ label: 'Subscriptions',
+ labelKey: 'id',
+ listItems: subscriptionFields,
+ },
+ { key: 'page', label: 'Page', format: 'number' },
+ { key: 'total_pages', label: 'Total Pages', format: 'number' },
+ {
+ key: 'total_subscriptions',
+ label: 'Total Subscriptions',
+ format: 'number',
+ },
+ ],
+};
+
+export const kitSubscriptionListOutputSchema: OutputSchema = {
+ itemLabel: 'Subscription {id}',
+ fields: [
+ {
+ key: 'subscriptions',
+ label: 'Subscriptions',
+ value: '',
+ listItems: subscriptionFields,
+ },
+ ],
+};
+
+export const kitRemoveTagByEmailOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'removed', label: 'Removed', format: 'boolean' },
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'tag_id', label: 'Tag ID', format: 'number' },
+ { key: 'tag_name', label: 'Tag Name' },
+ ],
+};
+
+export const kitRemoveTagFromSubscriberOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'removed', label: 'Removed', format: 'boolean' },
+ { key: 'subscriber_id', label: 'Subscriber ID' },
+ { key: 'tag_id', label: 'Tag ID', format: 'number' },
+ { key: 'tag_name', label: 'Tag Name' },
+ ],
+};
+
+export const kitCustomFieldOutputSchema: OutputSchema = {
+ fields: customFieldFields,
+};
+
+export const kitUpdateCustomFieldOutputSchema: OutputSchema = {
+ fields: [
+ ...customFieldFields,
+ { key: 'refreshed', label: 'Read Back After Rename', format: 'boolean' },
+ { key: 'refresh_error', label: 'Read Back Error' },
+ ],
+};
+
+export const kitListCustomFieldsOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'custom_fields',
+ label: 'Custom Fields',
+ labelKey: 'label',
+ listItems: customFieldFields,
+ },
+ { key: 'count', label: 'Count', format: 'number' },
+ ],
+};
+
+export const kitCustomFieldListOutputSchema: OutputSchema = {
+ itemLabel: '{label}',
+ fields: [
+ {
+ key: 'custom_fields',
+ label: 'Custom Fields',
+ value: '',
+ listItems: customFieldFields,
+ },
+ ],
+};
+
+export const kitDeleteCustomFieldOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'custom_field_id', label: 'Custom Field ID' },
+ ],
+};
+
+export const kitRequestStatusOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'status', label: 'Status Code', format: 'number' },
+ { key: 'message', label: 'Message' },
+ ],
+};
+
+export const kitListBroadcastsOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'broadcasts',
+ label: 'Broadcasts',
+ labelKey: 'subject',
+ listItems: broadcastSummaryFields,
+ },
+ { key: 'count', label: 'Count', format: 'number' },
+ { key: 'page', label: 'Page', format: 'number' },
+ ],
+};
+
+export const kitBroadcastListOutputSchema: OutputSchema = {
+ itemLabel: '{subject}',
+ fields: [
+ {
+ key: 'broadcasts',
+ label: 'Broadcasts',
+ value: '',
+ listItems: broadcastSummaryFields,
+ },
+ ],
+};
+
+export const kitBroadcastOutputSchema: OutputSchema = {
+ fields: broadcastFields,
+};
+
+export const kitGetBroadcastStatsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'broadcast_id', label: 'Broadcast ID', format: 'number' },
+ ...broadcastStatsFields,
+ ],
+};
+
+export const kitBroadcastStatsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'id', label: 'Broadcast ID', format: 'number' },
+ { key: 'stats', label: 'Stats', children: broadcastStatsFields },
+ ],
+};
+
+export const kitDeleteBroadcastOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'broadcast_id', label: 'Broadcast ID' },
+ ],
+};
+
+export const kitWebhookOutputSchema: OutputSchema = {
+ fields: webhookRuleFields,
+};
+
+export const kitListWebhooksOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'rules',
+ label: 'Webhooks',
+ labelKey: 'target_url',
+ listItems: [...webhookRuleFields, { key: 'status', label: 'Status' }],
+ },
+ { key: 'count', label: 'Count', format: 'number' },
+ ],
+};
+
+export const kitDeleteWebhookOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'rule_id', label: 'Webhook ID' },
+ ],
+};
+
+const formFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Form ID', format: 'number' },
+ { key: 'name', label: 'Name' },
+ { key: 'type', label: 'Type' },
+ { key: 'format', label: 'Format' },
+ { key: 'embed_url', label: 'Embed URL', format: 'url' },
+ { key: 'embed_js', label: 'Embed Script URL', format: 'url' },
+ { key: 'archived', label: 'Archived', format: 'boolean' },
+ { key: 'uid', label: 'UID' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+];
+
+const sequenceFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Sequence ID', format: 'number' },
+ { key: 'name', label: 'Name' },
+ { key: 'active', label: 'Active', format: 'boolean' },
+ { key: 'available', label: 'Available', format: 'boolean' },
+ { key: 'hold', label: 'On Hold', format: 'boolean' },
+ { key: 'repeat', label: 'Repeat', format: 'boolean' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+];
+
+export const kitListFormsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'forms', label: 'Forms', labelKey: 'name', listItems: formFields },
+ { key: 'count', label: 'Count', format: 'number' },
+ ],
+};
+
+export const kitListSequencesOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'sequences',
+ label: 'Sequences',
+ labelKey: 'name',
+ listItems: sequenceFields,
+ },
+ { key: 'count', label: 'Count', format: 'number' },
+ ],
+};
+
+export const kitFormListOutputSchema: OutputSchema = {
+ itemLabel: '{name}',
+ fields: [{ key: 'forms', label: 'Forms', value: '', listItems: formFields }],
+};
+
+export const kitSequenceListOutputSchema: OutputSchema = {
+ itemLabel: '{name}',
+ fields: [
+ {
+ key: 'sequences',
+ label: 'Sequences',
+ value: '',
+ listItems: sequenceFields,
+ },
+ ],
+};
+
+const purchaseProductFields: OutputSchema['fields'] = [
+ { key: 'pid', label: 'Product ID' },
+ { key: 'lid', label: 'Line Item ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'sku', label: 'SKU' },
+ { key: 'unit_price', label: 'Unit Price', format: 'number' },
+ { key: 'quantity', label: 'Quantity', format: 'number' },
+];
+
+const purchaseFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Purchase ID', format: 'number' },
+ { key: 'transaction_id', label: 'Transaction ID' },
+ { key: 'status', label: 'Status' },
+ { key: 'email_address', label: 'Email Address', format: 'email' },
+ { key: 'currency', label: 'Currency' },
+ { key: 'transaction_time', label: 'Transaction Time', format: 'datetime' },
+ { key: 'subtotal', label: 'Subtotal', format: 'number' },
+ { key: 'discount', label: 'Discount', format: 'number' },
+ { key: 'tax', label: 'Tax', format: 'number' },
+ { key: 'total', label: 'Total', format: 'number' },
+ {
+ key: 'products',
+ label: 'Products',
+ labelKey: 'name',
+ listItems: purchaseProductFields,
+ },
+];
+
+export const kitPurchaseOutputSchema: OutputSchema = {
+ fields: purchaseFields,
+};
+
+export const kitListPurchasesOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'purchases',
+ label: 'Purchases',
+ labelKey: 'transaction_id',
+ listItems: purchaseFields,
+ },
+ { key: 'page', label: 'Page', format: 'number' },
+ { key: 'total_pages', label: 'Total Pages', format: 'number' },
+ { key: 'total_purchases', label: 'Total Purchases', format: 'number' },
+ ],
+};
+
+export const kitPurchaseListOutputSchema: OutputSchema = {
+ itemLabel: 'Purchase {transaction_id}',
+ fields: [
+ {
+ key: 'purchases',
+ label: 'Purchases',
+ value: '',
+ listItems: purchaseFields,
+ },
+ ],
+};
diff --git a/packages/pieces/community/convertkit/src/lib/triggers/index.ts b/packages/pieces/community/convertkit/src/lib/triggers/index.ts
index 8dbf74f75a1..badf96e2198 100644
--- a/packages/pieces/community/convertkit/src/lib/triggers/index.ts
+++ b/packages/pieces/community/convertkit/src/lib/triggers/index.ts
@@ -1,15 +1,11 @@
import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
-import { convertkitAuth } from '../..';
+import { convertkitAuth } from '../auth';
import { tag } from '../common/tags';
import { formId } from '../common/forms';
import { sequenceIdDropdown } from '../common/sequences';
import { productId } from '../common/purchases';
import { initiatorValue } from '../common/webhooks';
-import { createWebhook, removeWebhook } from '../common/service';
-
-interface WebhookInformation {
- ruleId: number;
-}
+import { kitWebhookLifecycle } from '../common/service';
const sampleData = {
rule: {
@@ -49,23 +45,19 @@ export const addTag = createTrigger({
target_url: context.webhookUrl,
};
- const response = await createWebhook(context.auth.secret_text, payload);
- const ruleId = response.id;
-
- await context.store?.put<WebhookInformation>(
- `_webhook_subscriber_tag_add`,
- {
- ruleId,
- }
- );
+ await kitWebhookLifecycle.enable({
+ apiSecret: context.auth.secret_text,
+ store: context.store,
+ storeKey: '_webhook_subscriber_tag_add',
+ payload,
+ });
},
async onDisable(context) {
- const response = await context.store?.get<WebhookInformation>(
- '_webhook_subscriber_tag_add'
- );
- if (response !== null && response !== undefined) {
- await removeWebhook(context.auth.secret_text, response.ruleId);
- }
+ await kitWebhookLifecycle.disable({
+ apiSecret: context.auth.secret_text,
+ store: context.store,
+ storeKey: '_webhook_subscriber_tag_add',
+ });
},
async run(context) {
const body = context.payload.body as { subscriber: unknown };
@@ -100,23 +92,19 @@ export const removeTag = createTrigger({
target_url: context.webhookUrl,
};
- const response = await createWebhook(context.auth.secret_text, payload);
- const ruleId = response.id;
-
- await context.store?.put<WebhookInformation>(
- `_webhook_subscriber_tag_remove`,
- {
- ruleId,
- }
- );
+ await kitWebhookLifecycle.enable({
+ apiSecret: context.auth.secret_text,
+ store: context.store,
+ storeKey: '_webhook_subscriber_tag_remove',
+ payload,
+ });
},
async onDisable(context) {
- const response = await context.store?.get<WebhookInformation>(
- '_webhook_subscriber_tag_remove'
- );
- if (response !== null && response !== undefined) {
- await removeWebhook(context.auth.secret_text, response.ruleId);
- }
+ await kitWebhookLifecycle.disable({
+ apiSecret: context.auth.secret_text,
+ store: context.store,
+ storeKey: '_webhook_subscriber_tag_remove',
+ });
},
async run(context) {
const body = context.payload.body as { subscriber: unknown };
@@ -147,23 +135,19 @@ export const subscriberActivated = createTrigger({
target_url: context.webhookUrl,
};
- const response = await createWebhook(context.auth.secret_text, payload);
- const ruleId = response.id;
-
- await context.store?.put<WebhookInformation>(
- `_webhook_subscriber_activated`,
- {
- ruleId,
- }
- );
+ await kitWebhookLifecycle.enable({
+ apiSecret: context.auth.secret_text,
+ store: context.store,
+ storeKey: '_webhook_subscriber_activated',
+ payload,
+ });
},
async onDisable(context) {
- const response = await context.store?.get<WebhookInformation>(
- '_webhook_subscriber_activated'
- );
- if (response !== null && response !== undefined) {
- await removeWebhook(context.auth.secret_text, response.ruleId);
- }
+ await kitWebhookLifecycle.disable({
+ apiSecret: context.auth.secret_text,
+ store: context.store,
+ storeKey: '_webhook_subscriber_activated',
+ });
},
async run(context) {
const body = context.payload.body as { subscriber: unknown };
@@ -193,23 +177,19 @@ export const subscriberUnsubscribed = createTrigger({
target_url: context.webhookUrl,
};
- const response = await createWebhook(context.auth.secret_text, payload);
- const ruleId = response.id;
-
- await context.store?.put<WebhookInformation>(
- `_webhook_subscriber_unsubscribed`,
- {
- ruleId,
- }
- );
+ await kitWebhookLifecycle.enable({
+ apiSecret: context.auth.secret_text,
+ store: context.store,
+ storeKey: '_webhook_subscriber_unsubscribed',
+ payload,
+ });
},
async onDisable(context) {
- const response = await context.store?.get<WebhookInformation>(
- '_webhook_subscriber_unsubscribed'
- );
- if (response !== null && response !== undefined) {
- await removeWebhook(context.auth.secret_text, response.ruleId);
- }
+ await kitWebhookLifecycle.disable({
+ apiSecret: context.auth.secret_text,
+ store: context.store,
+ storeKey: '_webhook_subscriber_unsubscribed',
+ });
},
async run(context) {
const body = context.payload.body as { subscriber: unknown };
@@ -240,23 +220,19 @@ export const subscriberBounced = createTrigger({
target_url: context.webhookUrl,
};
- const response = await createWebhook(context.auth.secret_text, payload);
- const ruleId = response.id;
-
- await context.store?.put<WebhookInformation>(
- `_webhook_subscriber_bounced`,
- {
- ruleId,
- }
- );
+ await kitWebhookLifecycle.enable({
+ apiSecret: context.auth.secret_text,
+ store: context.store,
+ storeKey: '_webhook_subscriber_bounced',
+ payload,
+ });
},
async onDisable(context) {
- const response = await context.store?.get<WebhookInformation>(
- '_webhook_subscriber_bounced'
- );
- if (response !== null && response !== undefined) {
- await removeWebhook(context.auth.secret_text, response.ruleId);
- }
+ await kitWebhookLifecycle.disable({
+ apiSecret: context.auth.secret_text,
+ store: context.store,
+ storeKey: '_webhook_subscriber_bounced',
+ });
},
async run(context) {
const body = context.payload.body as { subscriber: unknown };
@@ -290,23 +266,19 @@ export const subscriberComplained = createTrigger({
target_url: context.webhookUrl,
};
- const response = await createWebhook(context.auth.secret_text, payload);
- const ruleId = response.id;
-
- await context.store?.put<WebhookInformation>(
- `_webhook_subscriber_complained`,
- {
- ruleId,
- }
- );
+ await kitWebhookLifecycle.enable({
+ apiSecret: context.auth.secret_text,
+ store: context.store,
+ storeKey: '_webhook_subscriber_complained',
+ payload,
+ });
},
async onDisable(context) {
- const response = await context.store?.get<WebhookInformation>(
- '_webhook_subscriber_complained'
- );
- if (response !== null && response !== undefined) {
- await removeWebhook(context.auth.secret_text, response.ruleId);
- }
+ await kitWebhookLifecycle.disable({
+ apiSecret: context.auth.secret_text,
+ store: context.store,
+ storeKey: '_webhook_subscriber_complained',
+ });
},
async run(context) {
const body = context.payload.body as { subscriber: unknown };
@@ -341,20 +313,19 @@ export const formSubscribed = createTrigger({
target_url: context.webhookUrl,
};
- const response = await createWebhook(context.auth.secret_text, payload);
- const ruleId = response.id;
-
- await context.store?.put<WebhookInformation>(`_webhook_form_subscribed`, {
- ruleId,
+ await kitWebhookLifecycle.enable({
+ apiSecret: context.auth.secret_text,
+ store: context.store,
+ storeKey: '_webhook_form_subscribed',
+ payload,
});
},
async onDisable(context) {
- const response = await context.store?.get<WebhookInformation>(
- '_webhook_form_subscribed'
- );
- if (response !== null && response !== undefined) {
- await removeWebhook(context.auth.secret_text, response.ruleId);
- }
+ await kitWebhookLifecycle.disable({
+ apiSecret: context.auth.secret_text,
+ store: context.store,
+ storeKey: '_webhook_form_subscribed',
+ });
},
async run(context) {
const body = context.payload.body as { subscriber: unknown };
@@ -389,23 +360,19 @@ export const sequenceSubscribed = createTrigger({
target_url: context.webhookUrl,
};
- const response = await createWebhook(context.auth.secret_text, payload);
- const ruleId = response.id;
-
- await context.store?.put<WebhookInformation>(
- `_webhook_sequence_subscribed`,
- {
- ruleId,
- }
- );
+ await kitWebhookLifecycle.enable({
+ apiSecret: context.auth.secret_text,
+ store: context.store,
+ storeKey: '_webhook_sequence_subscribed',
+ payload,
+ });
},
async onDisable(context) {
- const response = await context.store?.get<WebhookInformation>(
- '_webhook_sequence_subscribed'
- );
- if (response !== null && response !== undefined) {
- await removeWebhook(context.auth.secret_text, response.ruleId);
- }
+ await kitWebhookLifecycle.disable({
+ apiSecret: context.auth.secret_text,
+ store: context.store,
+ storeKey: '_webhook_sequence_subscribed',
+ });
},
async run(context) {
const body = context.payload.body as { subscriber: unknown };
@@ -440,23 +407,19 @@ export const sequenceCompleted = createTrigger({
target_url: context.webhookUrl,
};
- const response = await createWebhook(context.auth.secret_text, payload);
- const ruleId = response.id;
-
- await context.store?.put<WebhookInformation>(
- `_webhook_sequence_completed`,
- {
- ruleId,
- }
- );
+ await kitWebhookLifecycle.enable({
+ apiSecret: context.auth.secret_text,
+ store: context.store,
+ storeKey: '_webhook_sequence_completed',
+ payload,
+ });
},
async onDisable(context) {
- const response = await context.store?.get<WebhookInformation>(
- '_webhook_sequence_completed'
- );
- if (response !== null && response !== undefined) {
- await removeWebhook(context.auth.secret_text, response.ruleId);
- }
+ await kitWebhookLifecycle.disable({
+ apiSecret: context.auth.secret_text,
+ store: context.store,
+ storeKey: '_webhook_sequence_completed',
+ });
},
async run(context) {
const body = context.payload.body as { subscriber: unknown };
@@ -491,20 +454,19 @@ export const linkClicked = createTrigger({
target_url: context.webhookUrl,
};
- const response = await createWebhook(context.auth.secret_text, payload);
- const ruleId = response.id;
-
- await context.store?.put<WebhookInformation>(`_webhook_link_clicked`, {
- ruleId,
+ await kitWebhookLifecycle.enable({
+ apiSecret: context.auth.secret_text,
+ store: context.store,
+ storeKey: '_webhook_link_clicked',
+ payload,
});
},
async onDisable(context) {
- const response = await context.store?.get<WebhookInformation>(
- '_webhook_link_clicked'
- );
- if (response !== null && response !== undefined) {
- await removeWebhook(context.auth.secret_text, response.ruleId);
- }
+ await kitWebhookLifecycle.disable({
+ apiSecret: context.auth.secret_text,
+ store: context.store,
+ storeKey: '_webhook_link_clicked',
+ });
},
async run(context) {
const { initiatorValue } = context.propsValue;
@@ -540,20 +502,19 @@ export const productPurchased = createTrigger({
},
target_url: context.webhookUrl,
};
- const response = await createWebhook(context.auth.secret_text, payload);
- const ruleId = response.id;
-
- await context.store?.put<WebhookInformation>(`_webhook_product_purchased`, {
- ruleId,
+ await kitWebhookLifecycle.enable({
+ apiSecret: context.auth.secret_text,
+ store: context.store,
+ storeKey: '_webhook_product_purchased',
+ payload,
});
},
async onDisable(context) {
- const response = await context.store?.get<WebhookInformation>(
- '_webhook_product_purchased'
- );
- if (response !== null && response !== undefined) {
- await removeWebhook(context.auth.secret_text, response.ruleId);
- }
+ await kitWebhookLifecycle.disable({
+ apiSecret: context.auth.secret_text,
+ store: context.store,
+ storeKey: '_webhook_product_purchased',
+ });
},
async run(context) {
const { productId } = context.propsValue;
@@ -584,20 +545,19 @@ export const purchaseCreated = createTrigger({
target_url: context.webhookUrl,
};
- const response = await createWebhook(context.auth.secret_text, payload);
- const ruleId = response.id;
-
- await context.store?.put<WebhookInformation>(`_webhook_purchase_created`, {
- ruleId,
+ await kitWebhookLifecycle.enable({
+ apiSecret: context.auth.secret_text,
+ store: context.store,
+ storeKey: '_webhook_purchase_created',
+ payload,
});
},
async onDisable(context) {
- const response = await context.store?.get<WebhookInformation>(
- '_webhook_purchase_created'
- );
- if (response !== null && response !== undefined) {
- await removeWebhook(context.auth.secret_text, response.ruleId);
- }
+ await kitWebhookLifecycle.disable({
+ apiSecret: context.auth.secret_text,
+ store: context.store,
+ storeKey: '_webhook_purchase_created',
+ });
},
async run(context) {
const body = context.payload.body as {
diff --git a/packages/pieces/community/convertkit/test/actions.test.ts b/packages/pieces/community/convertkit/test/actions.test.ts
new file mode 100644
index 00000000000..4e0a17e1f54
--- /dev/null
+++ b/packages/pieces/community/convertkit/test/actions.test.ts
@@ -0,0 +1,163 @@
+/// <reference types="vitest/globals" />
+
+import { kitCreateTag } from '../src/lib/actions/ai/create-tag';
+import { kitTagSubscriber } from '../src/lib/actions/ai/tag-subscriber';
+import { kitRemoveTagFromSubscriber } from '../src/lib/actions/ai/remove-tag-from-subscriber';
+import { kitUpdateSubscriber } from '../src/lib/actions/ai/update-subscriber';
+import { kitUpdateBroadcast } from '../src/lib/actions/ai/update-broadcast';
+import { kitCreateBroadcast } from '../src/lib/actions/ai/create-broadcast';
+import { kitUpdateCustomField } from '../src/lib/actions/ai/update-custom-field';
+import { kitListSubscribers } from '../src/lib/actions/ai/list-subscribers';
+import { kitCreateWebhook } from '../src/lib/actions/ai/create-webhook';
+import { SECRET, call, mockKit, run } from './helpers';
+
+afterEach(() => vi.restoreAllMocks());
+
+describe('Create Tag (get-or-create)', () => {
+ test('returns the existing tag with created:false on a case-insensitive name match, without creating', async () => {
+ const { requests } = mockKit([{ body: { tags: [{ id: 9, name: 'VIP Customers', created_at: '2026-01-01' }] } }]);
+ const result = await run({ action: kitCreateTag, propsValue: { name: ' vip customers ' } });
+ expect(result).toEqual({ id: 9, name: 'VIP Customers', created_at: '2026-01-01', created: false });
+ expect(requests).toHaveLength(1);
+ expect(requests[0].method).toBe('GET');
+ });
+
+ test('creates the tag when none matches, with the secret in the query and not the body', async () => {
+ const { requests } = mockKit([{ body: { tags: [] } }, { status: 201, body: { id: 10, name: 'New', created_at: '2026-01-02' } }]);
+ const result = await run({ action: kitCreateTag, propsValue: { name: 'New' } });
+ expect(result).toEqual({ id: 10, name: 'New', created_at: '2026-01-02', created: true });
+ expect(requests[1]).toMatchObject({ method: 'POST', url: 'https://api.convertkit.com/v3/tags', body: { tag: { name: 'New' } } });
+ expect(requests[1].queryParams).toEqual({ api_secret: SECRET });
+ });
+});
+
+describe('Tag Subscriber', () => {
+ test('sends the exact subscribe request', async () => {
+ const { requests } = mockKit([{ body: { subscription: { id: 1 } } }]);
+ await run({ action: kitTagSubscriber, propsValue: { tag_id: '123', email: ' [email protected] ', additional_tag_ids: ['4', 5], first_name: '' } });
+ expect(requests[0]).toMatchObject({
+ method: 'POST',
+ url: 'https://api.convertkit.com/v3/tags/123/subscribe',
+ body: { email: '[email protected]', tags: [4, 5] },
+ });
+ expect(requests[0].body).not.toHaveProperty('first_name');
+ });
+
+ test('refuses a non-numeric tag ID before any request', async () => {
+ const { requests } = mockKit([]);
+ await expect(run({ action: kitTagSubscriber, propsValue: { tag_id: '12/../34', email: '[email protected]' } })).rejects.toThrow('Tag ID must be a numeric Kit ID');
+ expect(requests).toHaveLength(0);
+ });
+});
+
+describe('Remove Tag From Subscriber', () => {
+ test('uses DELETE /subscribers/:id/tags/:tag_id', async () => {
+ const { requests } = mockKit([{ body: { id: 2, name: 'VIP' } }]);
+ const result = await run({ action: kitRemoveTagFromSubscriber, propsValue: { subscriber_id: '1', tag_id: '2' } });
+ expect(requests[0]).toMatchObject({ method: 'DELETE', url: 'https://api.convertkit.com/v3/subscribers/1/tags/2' });
+ expect(result).toEqual({ removed: true, subscriber_id: '1', tag_id: 2, tag_name: 'VIP' });
+ });
+});
+
+describe('Update Subscriber (partial update)', () => {
+ test('an empty first name is left out so the stored name is kept', async () => {
+ const { requests } = mockKit([{ body: { subscriber: { id: 1 } } }]);
+ await run({ action: kitUpdateSubscriber, propsValue: { subscriber_id: '1', first_name: '', fields: { plan: 'pro' } } });
+ expect(requests[0].body).toEqual({ fields: { plan: 'pro' } });
+ });
+
+ test('an update with nothing set is refused before any request', async () => {
+ const { requests } = mockKit([]);
+ await expect(run({ action: kitUpdateSubscriber, propsValue: { subscriber_id: '1', first_name: '', email_address: '' } })).rejects.toThrow('Provide at least one');
+ expect(requests).toHaveLength(0);
+ });
+});
+
+describe('Update Broadcast (partial update)', () => {
+ test('sends only the fields that were set and never send_at implicitly', async () => {
+ const { requests } = mockKit([{ body: { broadcast: { id: 5 } } }]);
+ await run({ action: kitUpdateBroadcast, propsValue: { broadcast_id: '5', subject: 'New subject', public: 'false' } });
+ expect(requests[0]).toMatchObject({ method: 'PUT', url: 'https://api.convertkit.com/v3/broadcasts/5' });
+ expect(requests[0].body).toEqual({ subject: 'New subject', public: false });
+ });
+
+ test('a past send time is refused before any request', async () => {
+ const { requests } = mockKit([]);
+ await expect(run({ action: kitUpdateBroadcast, propsValue: { broadcast_id: '5', send_at: '2000-01-01T00:00:00Z' } })).rejects.toThrow('Send At must be in the future');
+ expect(requests).toHaveLength(0);
+ });
+
+ test('Create Broadcast stays a draft when send_at is empty', async () => {
+ const { requests } = mockKit([{ status: 201, body: { broadcast: { id: 6 } } }]);
+ await run({ action: kitCreateBroadcast, propsValue: { subject: 'Draft', content: '<p>x</p>' } });
+ expect(requests[0].body).toEqual({ subject: 'Draft', content: '<p>x</p>' });
+ });
+});
+
+describe('Update Custom Field', () => {
+ test('a failed read-back after a successful rename is reported, not thrown', async () => {
+ const { requests } = mockKit([{ status: 204 }, { error: { status: 500, body: { error: 'boom' } } }]);
+ const result = await run({ action: kitUpdateCustomField, propsValue: { custom_field_id: '77', label: 'Plan' } });
+ expect(requests[0]).toMatchObject({ method: 'PUT', url: 'https://api.convertkit.com/v3/custom_fields/77', body: { label: 'Plan' } });
+ expect(result).toMatchObject({ id: 77, label: 'Plan', refreshed: false });
+ expect(JSON.stringify(result)).not.toContain(SECRET);
+ });
+
+ test('returns the refreshed field when the read-back works', async () => {
+ mockKit([{ status: 204 }, { body: { custom_fields: [{ id: 77, key: 'plan', label: 'Plan', name: 'ck_field_77_plan' }] } }]);
+ const result = await run({ action: kitUpdateCustomField, propsValue: { custom_field_id: '77', label: 'Plan' } });
+ expect(result).toEqual({ id: 77, key: 'plan', label: 'Plan', name: 'ck_field_77_plan', refreshed: true });
+ });
+});
+
+describe('List Subscribers', () => {
+ test('passes date filters as YYYY-MM-DD and a validated page', async () => {
+ const { requests } = mockKit([{ body: { subscribers: [], page: 2, total_pages: 2, total_subscribers: 51 } }]);
+ const result = await run({ action: kitListSubscribers, propsValue: { from: '2026-09-01T12:00:00Z', page: 2 } });
+ expect(requests[0].queryParams).toEqual({ api_secret: SECRET, page: '2', from: '2026-09-01' });
+ expect(result).toEqual({ subscribers: [], page: 2, total_pages: 2, total_subscribers: 51 });
+ });
+
+ test('an invalid date is refused before any request', async () => {
+ const { requests } = mockKit([]);
+ await expect(run({ action: kitListSubscribers, propsValue: { from: 'last week' } })).rejects.toThrow('is not a valid date');
+ expect(requests).toHaveLength(0);
+ });
+});
+
+describe('Create Webhook', () => {
+ test('refuses a non-https target before any request', async () => {
+ const { requests } = mockKit([]);
+ await expect(run({ action: kitCreateWebhook, propsValue: { target_url: 'http://example.com/hook', event: 'subscriber.subscriber_activate' } })).rejects.toThrow('Target URL must be a public https:// URL');
+ expect(requests).toHaveLength(0);
+ });
+
+ test('refuses an event whose required parameter is missing', async () => {
+ const { requests } = mockKit([]);
+ await expect(run({ action: kitCreateWebhook, propsValue: { target_url: 'https://example.com/hook', event: 'subscriber.tag_add' } })).rejects.toThrow('requires');
+ expect(requests).toHaveLength(0);
+ });
+});
+
+describe('connection validation', () => {
+ test('a 401 from Kit is reported as a rejected API Secret', async () => {
+ const { convertkitAuth } = await import('../src/lib/auth');
+ const { requests } = mockKit([{ error: { status: 401, body: { error: 'Authorization Failed' } } }]);
+ const result = await call({ target: convertkitAuth, method: 'validate', context: { auth: SECRET } });
+ expect(requests[0]).toMatchObject({ method: 'GET', url: 'https://api.convertkit.com/v3/account', queryParams: { api_secret: SECRET } });
+ expect(result).toEqual({ valid: false, error: expect.stringContaining('Kit rejected this API Secret') });
+ });
+
+ test('validates the secret exactly as actions will send it', async () => {
+ const { convertkitAuth } = await import('../src/lib/auth');
+ const { requests } = mockKit([{ body: { name: 'Odai', primary_email_address: '[email protected]' } }]);
+ await call({ target: convertkitAuth, method: 'validate', context: { auth: ` ${SECRET} ` } });
+ expect(requests[0]).toMatchObject({ queryParams: { api_secret: ` ${SECRET} ` } });
+ });
+
+ test('a working secret is valid', async () => {
+ const { convertkitAuth } = await import('../src/lib/auth');
+ mockKit([{ body: { name: 'Odai', primary_email_address: '[email protected]' } }]);
+ expect(await call({ target: convertkitAuth, method: 'validate', context: { auth: SECRET } })).toEqual({ valid: true });
+ });
+});
diff --git a/packages/pieces/community/convertkit/test/client.test.ts b/packages/pieces/community/convertkit/test/client.test.ts
new file mode 100644
index 00000000000..2aeb198e49b
--- /dev/null
+++ b/packages/pieces/community/convertkit/test/client.test.ts
@@ -0,0 +1,57 @@
+/// <reference types="vitest/globals" />
+
+import { kitCommon } from '../src/lib/common/client';
+
+describe('kitCommon.toIdList', () => {
+ test.each([
+ [['1', 2], [1, 2]],
+ ['[3, 4]', [3, 4]],
+ ['5, 6', [5, 6]],
+ [7, [7]],
+ ])('parses %j', (input, expected) => {
+ expect(kitCommon.toIdList(input)).toEqual(expected);
+ });
+
+ test('treats empty input as unset', () => {
+ expect(kitCommon.toIdList(undefined)).toBeUndefined();
+ expect(kitCommon.toIdList('')).toBeUndefined();
+ expect(kitCommon.toIdList([])).toBeUndefined();
+ });
+
+ test('refuses a non-numeric ID instead of dropping it', () => {
+ expect(() => kitCommon.toIdList(['abc'])).toThrow('not a valid numeric ID');
+ expect(() => kitCommon.toIdList('[1,')).toThrow('not a valid list of IDs');
+ });
+});
+
+describe('input validation', () => {
+ test('id accepts numeric strings and numbers only', () => {
+ expect(kitCommon.id({ value: ' 42 ', label: 'Tag ID' })).toBe('42');
+ expect(kitCommon.id({ value: 42, label: 'Tag ID' })).toBe('42');
+ expect(() => kitCommon.id({ value: '42/../x', label: 'Tag ID' })).toThrow('Tag ID must be a numeric Kit ID');
+ expect(() => kitCommon.id({ value: '', label: 'Tag ID' })).toThrow('Tag ID must be a numeric Kit ID');
+ });
+
+ test('page defaults to 1 and refuses 0 or fractions', () => {
+ expect(kitCommon.page(undefined)).toBe(1);
+ expect(kitCommon.page('3')).toBe(3);
+ expect(() => kitCommon.page(0)).toThrow('Page must be a whole number');
+ expect(() => kitCommon.page(1.5)).toThrow('Page must be a whole number');
+ });
+
+ test('email refuses a malformed address', () => {
+ expect(kitCommon.email({ value: ' [email protected] ', label: 'Email' })).toBe('[email protected]');
+ expect(() => kitCommon.email({ value: 'not-an-email', label: 'Email' })).toThrow('Email must be a valid email address');
+ });
+
+ test('toDate keeps YYYY-MM-DD and refuses anything else', () => {
+ expect(kitCommon.toDate('2026-09-01T10:00:00Z')).toBe('2026-09-01');
+ expect(() => kitCommon.toDate('yesterday')).toThrow('is not a valid date');
+ });
+
+ test('toDateTime refuses a past time when a future one is required', () => {
+ expect(() => kitCommon.toDateTime({ value: '2000-01-01T00:00:00Z', label: 'Send At', future: true })).toThrow('Send At must be in the future');
+ expect(() => kitCommon.toDateTime({ value: 'soon', label: 'Send At' })).toThrow('Send At must be an ISO 8601 date-time');
+ expect(kitCommon.toDateTime({ value: '2999-01-01T00:00:00Z', label: 'Send At', future: true })).toBe('2999-01-01T00:00:00Z');
+ });
+});
diff --git a/packages/pieces/community/convertkit/test/custom-api-guard.test.ts b/packages/pieces/community/convertkit/test/custom-api-guard.test.ts
new file mode 100644
index 00000000000..7b5d4481a9f
--- /dev/null
+++ b/packages/pieces/community/convertkit/test/custom-api-guard.test.ts
@@ -0,0 +1,33 @@
+/// <reference types="vitest/globals" />
+
+import { assertKitUrl } from '../src/lib/common/custom-api-guard';
+
+const check = (url: string) => () => assertKitUrl({ url: { url } });
+
+describe('Custom API Call host guard', () => {
+ test.each([
+ '/account',
+ 'account',
+ '/subscribers?page=2',
+ 'https://api.convertkit.com/v3/account',
+ 'https://api.convertkit.com/v3',
+ ])('allows %s', (url) => {
+ expect(check(url)).not.toThrow();
+ });
+
+ test.each([
+ 'https://example.com/steal',
+ 'https://api.convertkit.com.evil.io/v3/account',
+ 'https://[email protected]/v3/account',
+ 'https://user:[email protected]/v3/account',
+ 'http://api.convertkit.com/v3/account',
+ 'https://api.convertkit.com/v4/account',
+ 'https://api.convertkit.com/v3/../v4/account',
+ '/../account',
+ '%2e%2e/account',
+ '//evil.io/account',
+ '\\\\evil.io\\account',
+ ])('refuses %s', (url) => {
+ expect(check(url)).toThrow('only sends your Kit API Secret');
+ });
+});
diff --git a/packages/pieces/community/convertkit/test/helpers.ts b/packages/pieces/community/convertkit/test/helpers.ts
new file mode 100644
index 00000000000..f217006fb2d
--- /dev/null
+++ b/packages/pieces/community/convertkit/test/helpers.ts
@@ -0,0 +1,40 @@
+import { HttpRequest, HttpResponse, httpClient } from '@activepieces/pieces-common';
+
+export const SECRET = 'sk_test_fixture_secret_000000000000';
+export const AUTH = { secret_text: SECRET };
+
+export type Reply = { status?: number; body?: unknown } | { error: { status: number; body: unknown } };
+
+export function mockKit(replies: Reply[]) {
+ const requests: HttpRequest[] = [];
+ const spy = vi.spyOn(httpClient, 'sendRequest').mockImplementation(async (request: HttpRequest): Promise<HttpResponse> => {
+ requests.push(request);
+ const reply = replies.shift() ?? { status: 200, body: {} };
+ if ('error' in reply) {
+ throw Object.assign(new Error(`Request failed with status ${reply.error.status}: ${JSON.stringify(request)}`), {
+ response: { status: reply.error.status, body: reply.error.body },
+ });
+ }
+ return { status: reply.status ?? 200, headers: {}, body: reply.body ?? {} };
+ });
+ return { requests, spy };
+}
+
+export function call({ target, method, context }: { target: object; method: string; context: unknown }): Promise<unknown> {
+ const fn: unknown = Reflect.get(target, method);
+ if (typeof fn !== 'function') {
+ throw new Error(`${method} is not a function`);
+ }
+ return Promise.resolve(Reflect.apply(fn, target, [context]));
+}
+
+export function run({ action, propsValue }: { action: object; propsValue: Record<string, unknown> }) {
+ return call({ target: action, method: 'run', context: { auth: AUTH, propsValue } });
+}
+
+export function messageOf(error: unknown): string {
+ if (!(error instanceof Error)) {
+ throw new Error('expected an Error');
+ }
+ return error.message;
+}
diff --git a/packages/pieces/community/convertkit/test/http.test.ts b/packages/pieces/community/convertkit/test/http.test.ts
new file mode 100644
index 00000000000..0560aa67c86
--- /dev/null
+++ b/packages/pieces/community/convertkit/test/http.test.ts
@@ -0,0 +1,72 @@
+/// <reference types="vitest/globals" />
+
+import { HttpMethod } from '@activepieces/pieces-common';
+import { kitHttp, kitErrorStatus, redactKitSecret, describeKitError } from '../src/lib/common/http';
+import { SECRET, messageOf, mockKit } from './helpers';
+
+afterEach(() => vi.restoreAllMocks());
+
+describe('kitHttp', () => {
+ test('moves api_secret from the body to the query so the logged request body never carries it', async () => {
+ const { requests } = mockKit([{ status: 201, body: { id: 1 } }]);
+ await kitHttp.sendRequest({
+ method: HttpMethod.POST,
+ url: 'https://api.convertkit.com/v3/tags',
+ body: { api_secret: SECRET, tag: { name: 'x' } },
+ });
+ expect(requests[0].body).toEqual({ tag: { name: 'x' } });
+ expect(requests[0].queryParams).toEqual({ api_secret: SECRET });
+ expect(JSON.stringify(requests[0].body)).not.toContain(SECRET);
+ });
+
+ test('keeps a GET request unchanged', async () => {
+ const { requests } = mockKit([{ status: 200, body: { tags: [] } }]);
+ await kitHttp.sendRequest({
+ method: HttpMethod.GET,
+ url: 'https://api.convertkit.com/v3/tags',
+ queryParams: { api_secret: SECRET },
+ });
+ expect(requests[0].queryParams).toEqual({ api_secret: SECRET });
+ expect(requests[0].body).toBeUndefined();
+ });
+
+ test('a Kit HTTP error rethrows with the status and never the secret', async () => {
+ mockKit([{ error: { status: 404, body: { error: 'Not Found', echo: `api_secret=${SECRET}` } } }]);
+ const error = await kitHttp
+ .sendRequest({ method: HttpMethod.PUT, url: 'https://api.convertkit.com/v3/custom_fields/1', body: { api_secret: SECRET, label: 'x' } })
+ .catch((e: unknown) => e);
+ expect(messageOf(error)).toContain('Kit could not find the requested resource (404)');
+ expect(messageOf(error)).not.toContain(SECRET);
+ expect(kitErrorStatus(error)).toBe(404);
+ });
+
+ test('a network error message is redacted', async () => {
+ vi.spyOn((await import('@activepieces/pieces-common')).httpClient, 'sendRequest').mockRejectedValue(
+ new Error(`socket hang up ${JSON.stringify({ api_secret: SECRET })}`)
+ );
+ const error = await kitHttp
+ .sendRequest({ method: HttpMethod.POST, url: 'https://api.convertkit.com/v3/tags', body: { api_secret: SECRET } })
+ .catch((e: unknown) => e);
+ expect(messageOf(error)).toContain('Kit API request failed');
+ expect(messageOf(error)).not.toContain(SECRET);
+ expect(kitErrorStatus(error)).toBeUndefined();
+ });
+});
+
+describe('redactKitSecret', () => {
+ test.each([
+ [`{"api_secret":"${SECRET}"}`],
+ [`{\\"api_secret\\":\\"${SECRET}\\"}`],
+ [`https://api.convertkit.com/v3/tags?api_secret=${SECRET}&page=1`],
+ ])('hides the secret in %s', (text) => {
+ expect(redactKitSecret({ text })).not.toContain(SECRET);
+ });
+
+ test('hides a known secret value wherever it appears', () => {
+ expect(redactKitSecret({ text: `raw ${SECRET} here`, secrets: [SECRET] })).toBe('raw [redacted] here');
+ });
+
+ test('describes a 401 as a credential problem', () => {
+ expect(describeKitError({ status: 401, body: {} })).toContain('Kit rejected the API Secret (401)');
+ });
+});
diff --git a/packages/pieces/community/convertkit/test/triggers.test.ts b/packages/pieces/community/convertkit/test/triggers.test.ts
new file mode 100644
index 00000000000..2917296c8c0
--- /dev/null
+++ b/packages/pieces/community/convertkit/test/triggers.test.ts
@@ -0,0 +1,78 @@
+/// <reference types="vitest/globals" />
+
+import { subscriberActivated } from '../src/lib/triggers';
+import { AUTH, call, mockKit } from './helpers';
+
+afterEach(() => vi.restoreAllMocks());
+
+function memoryStore({ failPut = false }: { failPut?: boolean } = {}) {
+ const data = new Map<string, unknown>();
+ return {
+ data,
+ put: vi.fn(async (key: string, value: unknown) => {
+ if (failPut) {
+ throw new Error('store unavailable');
+ }
+ data.set(key, value);
+ return value;
+ }),
+ get: vi.fn(async (key: string) => data.get(key) ?? null),
+ delete: vi.fn(async (key: string) => {
+ data.delete(key);
+ }),
+ };
+}
+
+const KEY = '_webhook_subscriber_activated';
+const lifecycle = ({ method, store }: { method: 'onEnable' | 'onDisable'; store: ReturnType<typeof memoryStore> }) =>
+ call({
+ target: subscriberActivated,
+ method,
+ context: { auth: AUTH, propsValue: {}, webhookUrl: 'https://cloud.example/webhooks/1', store },
+ });
+
+describe('webhook trigger lifecycle', () => {
+ test('onEnable creates the Kit rule and stores its ID', async () => {
+ const { requests } = mockKit([{ body: { rule: { id: 55 } } }]);
+ const store = memoryStore();
+ await lifecycle({ method: 'onEnable', store });
+ expect(requests[0]).toMatchObject({
+ method: 'POST',
+ url: 'https://api.convertkit.com/v3/automations/hooks',
+ body: { event: { name: 'subscriber.subscriber_activate' }, target_url: 'https://cloud.example/webhooks/1' },
+ });
+ expect(store.data.get(KEY)).toEqual({ ruleId: 55 });
+ });
+
+ test('onEnable deletes the rule it created when saving its ID fails', async () => {
+ const { requests } = mockKit([{ body: { rule: { id: 56 } } }, { body: { success: true } }]);
+ const store = memoryStore({ failPut: true });
+ await expect(lifecycle({ method: 'onEnable', store })).rejects.toThrow('so it was removed again');
+ expect(requests[1]).toMatchObject({ method: 'DELETE', url: 'https://api.convertkit.com/v3/automations/hooks/56' });
+ });
+
+ test('onDisable deletes the rule and then forgets its ID', async () => {
+ const { requests } = mockKit([{ body: { success: true } }]);
+ const store = memoryStore();
+ store.data.set(KEY, { ruleId: 57 });
+ await lifecycle({ method: 'onDisable', store });
+ expect(requests[0]).toMatchObject({ method: 'DELETE', url: 'https://api.convertkit.com/v3/automations/hooks/57' });
+ expect(store.data.has(KEY)).toBe(false);
+ });
+
+ test('onDisable treats a 404 as already deleted', async () => {
+ mockKit([{ error: { status: 404, body: { error: 'Not Found' } } }]);
+ const store = memoryStore();
+ store.data.set(KEY, { ruleId: 58 });
+ await lifecycle({ method: 'onDisable', store });
+ expect(store.data.has(KEY)).toBe(false);
+ });
+
+ test('onDisable keeps the ID when Kit fails, so a retry can still delete the rule', async () => {
+ mockKit([{ error: { status: 500, body: { error: 'boom' } } }]);
+ const store = memoryStore();
+ store.data.set(KEY, { ruleId: 59 });
+ await expect(lifecycle({ method: 'onDisable', store })).rejects.toThrow('Kit API request failed (500)');
+ expect(store.data.get(KEY)).toEqual({ ruleId: 59 });
+ });
+});
diff --git a/packages/pieces/community/convertkit/vitest.config.ts b/packages/pieces/community/convertkit/vitest.config.ts
new file mode 100644
index 00000000000..ba8ade4a178
--- /dev/null
+++ b/packages/pieces/community/convertkit/vitest.config.ts
@@ -0,0 +1,17 @@
+import path from 'path'
+import { defineConfig } from 'vitest/config'
+
+const repoRoot = path.resolve(__dirname, '../../../..')
+
+export default defineConfig({
+ test: {
+ globals: true,
+ environment: 'node',
+ },
+ resolve: {
+ alias: {
+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),
+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),
+ },
+ },
+})