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(totalcms): connect Total CMS 3 sites and manage collections and objects from flows and AI agents (#16212)

Odai Ahmad9bb5bc1f595b
diff --git a/bun.lock b/bun.lock
index 156dd47689a..7ff5eb9c2d3 100644
--- a/bun.lock
+++ b/bun.lock
@@ -9252,7 +9252,7 @@
},
"packages/pieces/community/totalcms": {
"name": "@activepieces/piece-totalcms",
- "version": "0.2.0",
+ "version": "1.0.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -9263,6 +9263,7 @@
},
"devDependencies": {
"tslib": "2.6.2",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/trello": {
diff --git a/docs/install/reference/breaking-changes.mdx b/docs/install/reference/breaking-changes.mdx
index bd81f75e547..aad1f313243 100644
--- a/docs/install/reference/breaking-changes.mdx
+++ b/docs/install/reference/breaking-changes.mdx
@@ -8,6 +8,15 @@ icon: "hammer"
### What has changed?
+#### Total CMS 1.0.0 supports Total CMS 3 only
+
+Total CMS 0.2.0 called the Total CMS 1 and 2 API (`rw_common/plugins/stacks/total-cms/totalapi.php` with a license key), which Total CMS 3 no longer has. From 1.0.0 the piece uses the Total CMS 3 REST API. The connection now takes a **Site URL** and an **API Key** (Utilities → API Keys in the Total CMS admin, Pro edition) instead of a domain and license key.
+
+Actions now take a Collection ID and an Object ID instead of a "CMS ID", and a blog post's permalink is now its Post ID. The thumbnail, scale, crop and extension options on image actions are removed, because Total CMS 3 resizes images on request through ImageWorks. The RSS title and description, genre, labels, extra2 and archived fields on blog posts are removed, because the Total CMS 3 blog schema does not have them. Get Content takes a collection instead of a data type, Save Date takes a date and time instead of a Unix timestamp, and New Blog Post takes a blog collection, fires on the post's created time and skips drafts by default.
+
+#### What you need to do
+
+Upgrade the site to Total CMS 3, create an API key and reconnect with the Site URL and API Key. Then upgrade each Total CMS step to 1.0.0 and map its inputs again. Steps keep running on the version they were built with until you upgrade them, and those steps stop working once the site runs Total CMS 3.
#### AI steps and agents stop running a model their key no longer allows
An AI provider key can limit which models it offers. Until now, a flow AI step or a flow-step agent that already named a model kept running it after an admin removed that model from the key's list. From this release the step fails with "The model … isn't allowed for this AI provider key anymore". This is checked when the step is queued and again when it runs.
diff --git a/packages/pieces/community/totalcms/package.json b/packages/pieces/community/totalcms/package.json
index 55dae652c98..24b585fcdb7 100644
--- a/packages/pieces/community/totalcms/package.json
+++ b/packages/pieces/community/totalcms/package.json
@@ -1,12 +1,13 @@
{
"name": "@activepieces/piece-totalcms",
- "version": "0.2.0",
+ "version": "1.0.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:*",
@@ -17,6 +18,7 @@
"@activepieces/core-utils": "workspace:*"
},
"devDependencies": {
- "tslib": "2.6.2"
+ "tslib": "2.6.2",
+ "vitest": "3.2.6"
}
}
diff --git a/packages/pieces/community/totalcms/src/i18n/translation.json b/packages/pieces/community/totalcms/src/i18n/translation.json
index 6ee4eb507e5..e76be8e0c12 100644
--- a/packages/pieces/community/totalcms/src/i18n/translation.json
+++ b/packages/pieces/community/totalcms/src/i18n/translation.json
@@ -1,157 +1,206 @@
{
- "Content management system for modern websites": "Content management system for modern websites",
- "Total CMS Domain": "Total CMS Domain",
- "License Key": "License Key",
- "The domain of your Total CMS website": "The domain of your Total CMS website",
- "The License key for your Total CMS domain": "The License key for your Total CMS domain",
- "Setup your Total CMS connection": "Setup your Total CMS connection",
- "Get Content": "Get Content",
+ "Flat-file content management system for websites, with collections, blogs, images and files.": "Flat-file content management system for websites, with collections, blogs, images and files.",
+ "Site URL": "Site URL",
+ "API Key": "API Key",
+ "The address of your Total CMS site, e.g. https://www.example.com": "The address of your Total CMS site, e.g. https://www.example.com",
+ "A Total CMS API key, starting with tcms_": "A Total CMS API key, starting with tcms_",
+ "Connect a Total CMS 3 site.\n\n1. Sign in to your Total CMS admin.\n2. Go to **Utilities → API Keys** (or open `/admin/utils/api-keys`).\n3. Click **Create New API Key**, give it a name, choose the HTTP methods and endpoints Activepieces may use (all endpoints is simplest), and copy the key. It is shown only once.\n4. Paste your site address and the key below.\n\nAPI keys need the Pro edition of Total CMS (local development domains such as localhost include it).": "Connect a Total CMS 3 site.\n\n1. Sign in to your Total CMS admin.\n2. Go to **Utilities → API Keys** (or open `/admin/utils/api-keys`).\n3. Click **Create New API Key**, give it a name, choose the HTTP methods and endpoints Activepieces may use (all endpoints is simplest), and copy the key. It is shown only once.\n4. Paste your site address and the key below.\n\nAPI keys need the Pro edition of Total CMS (local development domains such as localhost include it).",
+ "List Collections": "List Collections",
+ "Get Collection Fields": "Get Collection Fields",
+ "Find Objects": "Find Objects",
+ "Get Object": "Get Object",
+ "Get Object (by ID)": "Get Object (by ID)",
+ "Create Object": "Create Object",
+ "Update Object": "Update Object",
+ "Update Object (by ID)": "Update Object (by ID)",
+ "Duplicate Object": "Duplicate Object",
+ "Delete Object": "Delete Object",
+ "Upload File to Field": "Upload File to Field",
+ "Increase or Decrease Number": "Increase or Decrease Number",
"Get Blog Post": "Get Blog Post",
- "Save Blog Post": "Save Blog Post",
- "Save Blog Post Gallery Image": "Save Blog Post Gallery Image",
- "Save Blog Post Image": "Save Blog Post Image",
- "Save Date Content": "Save Date Content",
- "Save Depot": "Save Depot",
- "Save File": "Save File",
- "Save Gallery Image": "Save Gallery Image",
- "Save Image": "Save Image",
- "Save Text Content": "Save Text Content",
+ "Create or Update Blog Post": "Create or Update Blog Post",
+ "Set Blog Post Image": "Set Blog Post Image",
+ "Add Image to Blog Post Gallery": "Add Image to Blog Post Gallery",
+ "Save Text": "Save Text",
"Save Toggle": "Save Toggle",
- "Save Video Content": "Save Video Content",
+ "Save Date": "Save Date",
+ "Save Image": "Save Image",
+ "Add Image to Gallery": "Add Image to Gallery",
+ "Save File": "Save File",
+ "Add File to Depot": "Add File to Depot",
+ "Save Video": "Save Video",
+ "Get Collection Fields (by ID)": "Get Collection Fields (by ID)",
+ "Find Objects (by Collection ID)": "Find Objects (by Collection ID)",
+ "Create Object (by Collection ID)": "Create Object (by Collection ID)",
+ "Upload File to Field (by ID)": "Upload File to Field (by ID)",
+ "Increase or Decrease Number (by ID)": "Increase or Decrease Number (by ID)",
+ "Duplicate Object (by ID)": "Duplicate Object (by ID)",
"Custom API Call": "Custom API Call",
- "Get content from your Total CMS website": "Get content from your Total CMS website",
- "Get a blog post from Total CMS": "Get a blog post from Total CMS",
- "Save blog content to Total CMS": "Save blog content to Total CMS",
- "Save image to Total CMS blog post gallery": "Save image to Total CMS blog post gallery",
- "Save image to Total CMS blog post": "Save image to Total CMS blog post",
- "Save date content to Total CMS": "Save date content to Total CMS",
- "Save file to Total CMS depot": "Save file to Total CMS depot",
- "Save file to Total CMS": "Save file to Total CMS",
- "Save image to Total CMS gallery": "Save image to Total CMS gallery",
- "Save image to Total CMS": "Save image to Total CMS",
- "Save text content to Total CMS": "Save text content to Total CMS",
- "Save toggle content to Total CMS": "Save toggle content to Total CMS",
- "Save video content to Total CMS": "Save video content to Total CMS",
+ "Lists all collections on the site.": "Lists all collections on the site.",
+ "Lists the fields of a collection, with their types.": "Lists the fields of a collection, with their types.",
+ "Searches, filters and sorts the objects of a collection.": "Searches, filters and sorts the objects of a collection.",
+ "Gets one object (all its fields) from a collection.": "Gets one object (all its fields) from a collection.",
+ "Gets one object by collection ID and object ID.": "Gets one object by collection ID and object ID.",
+ "Creates a new object in any collection.": "Creates a new object in any collection.",
+ "Changes some fields of an object and keeps the others.": "Changes some fields of an object and keeps the others.",
+ "Changes some fields of an object, given the collection ID and object ID.": "Changes some fields of an object, given the collection ID and object ID.",
+ "Copies an object under a new ID.": "Copies an object under a new ID.",
+ "Permanently deletes an object and its files.": "Permanently deletes an object and its files.",
+ "Uploads a file or image to an image, gallery, file or depot field of an object.": "Uploads a file or image to an image, gallery, file or depot field of an object.",
+ "Adds to or subtracts from a number field, such as a counter or stock level.": "Adds to or subtracts from a number field, such as a counter or stock level.",
+ "Gets a blog post with its full content.": "Gets a blog post with its full content.",
+ "Creates a blog post, or updates the post with the given ID.": "Creates a blog post, or updates the post with the given ID.",
+ "Uploads the main image of a blog post, replacing the current one.": "Uploads the main image of a blog post, replacing the current one.",
+ "Adds an image to the gallery of a blog post.": "Adds an image to the gallery of a blog post.",
+ "Creates or replaces a text object.": "Creates or replaces a text object.",
+ "Turns a toggle object on or off.": "Turns a toggle object on or off.",
+ "Creates or replaces a date object.": "Creates or replaces a date object.",
+ "Uploads an image to an image object, replacing the current image.": "Uploads an image to an image object, replacing the current image.",
+ "Adds an image to a gallery object.": "Adds an image to a gallery object.",
+ "Uploads a file to a file object, replacing the current file.": "Uploads a file to a file object, replacing the current file.",
+ "Adds a file to a depot (file library) object.": "Adds a file to a depot (file library) object.",
+ "Creates or replaces a video object from a video link.": "Creates or replaces a video object from a video link.",
"Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",
- "Data Type": "Data Type",
- "CMS ID": "CMS ID",
- "Permalink": "Permalink",
+ "Collection": "Collection",
+ "Search": "Search",
+ "Only Include": "Only Include",
+ "Exclude": "Exclude",
+ "Sort By": "Sort By",
+ "Limit": "Limit",
+ "Offset": "Offset",
+ "Object": "Object",
+ "Collection ID": "Collection ID",
+ "Object ID": "Object ID",
+ "Fields": "Fields",
+ "Fields to Change": "Fields to Change",
+ "New Object ID": "New Object ID",
+ "Field": "Field",
+ "File": "File",
+ "File URL": "File URL",
+ "Folder": "Folder",
+ "Number Field": "Number Field",
+ "Change": "Change",
+ "Amount": "Amount",
+ "Blog": "Blog",
+ "Post": "Post",
+ "Post ID": "Post ID",
"Title": "Title",
- "Date (Unix Timestamp)": "Date (Unix Timestamp)",
+ "Date": "Date",
+ "Author": "Author",
"Summary": "Summary",
"Content": "Content",
"Extra Content": "Extra Content",
- "Extra Content 2": "Extra Content 2",
- "Media": "Media",
- "RSS Title": "RSS Title",
- "RSS Description": "RSS Description",
- "Author": "Author",
- "Genre": "Genre",
+ "Media URL": "Media URL",
"Categories": "Categories",
"Tags": "Tags",
- "Labels": "Labels",
- "Draft": "Draft",
+ "Status": "Status",
"Featured": "Featured",
- "Archived": "Archived",
"Image": "Image",
+ "Image URL": "Image URL",
"Alt Text": "Alt Text",
- "Thumbnail Quality": "Thumbnail Quality",
- "Thumbnail Scale": "Thumbnail Scale",
- "Thumbnail Square Scale": "Thumbnail Square Scale",
- "Thumbnail Resize Method": "Thumbnail Resize Method",
- "Thumbnail Landscape Crop": "Thumbnail Landscape Crop",
- "Pull Alt Text from Meta Data": "Pull Alt Text from Meta Data",
- "Unix Timestamp": "Unix Timestamp",
- "File": "File",
- "File Extension": "File Extension",
- "Extension": "Extension",
- "Text Content": "Text Content",
- "Status": "Status",
+ "Text": "Text",
+ "On": "On",
"Video URL": "Video URL",
+ "Field Name": "Field Name",
"Method": "Method",
"Headers": "Headers",
"Query Parameters": "Query Parameters",
"Body Type": "Body Type",
"Body": "Body",
- "Response is Binary ?": "Response is Binary ?",
- "No Error on Failure": "No Error on Failure",
- "Timeout (in seconds)": "Timeout (in seconds)",
+ "Response is Binary": "Response is Binary",
+ "Return Error as Output": "Return Error as Output",
+ "Timeout": "Timeout",
"Follow redirects": "Follow redirects",
- "The type of data to return": "The type of data to return",
- "The CMS ID of the content to retrieve": "The CMS ID of the content to retrieve",
- "The permalink of the post to retrieve": "The permalink of the post to retrieve",
- "The CMS ID of the content to save": "The CMS ID of the content to save",
- "The permalink of the blog post. Ensure this is unique or it will overwrite the existing post.": "The permalink of the blog post. Ensure this is unique or it will overwrite the existing post.",
- "The title of the blog post": "The title of the blog post",
- "The date in unix timestamp format": "The date in unix timestamp format",
- "The summary of the blog post": "The summary of the blog post",
- "The content of the blog post": "The content of the blog post",
- "The extra content of the blog post": "The extra content of the blog post",
- "The extra content 2 of the blog post": "The extra content 2 of the blog post",
- "The media of the blog post": "The media of the blog post",
- "The RSS title of the blog post": "The RSS title of the blog post",
- "The RSS description of the blog post": "The RSS description of the blog post",
- "The author of the blog post": "The author of the blog post",
- "The genre of the blog post": "The genre of the blog post",
- "A comma separated list of categories for the blog post": "A comma separated list of categories for the blog post",
- "A comma separated list of tags for the blog post": "A comma separated list of tags for the blog post",
- "A comma separated list of labels for the blog post": "A comma separated list of labels for the blog post",
- "Set to true to save as a draft": "Set to true to save as a draft",
- "Set to true to save as a featured post": "Set to true to save as a featured post",
- "Set to true to save as an archived post": "Set to true to save as an archived post",
- "The CMS ID of the blog to save": "The CMS ID of the blog to save",
- "The permalink of the blog post to save": "The permalink of the blog post to save",
- "The image to save": "The image to save",
- "The alt text for the image": "The alt text for the image",
- "The quality of the thumbnail": "The quality of the thumbnail",
- "The scale of the thumbnail": "The scale of the thumbnail",
- "The scale of the square thumbnail": "The scale of the square thumbnail",
- "The method to use when resizing the thumbnail": "The method to use when resizing the thumbnail",
- "The method to use when cropping the landscape thumbnail for the square thumbnail": "The method to use when cropping the landscape thumbnail for the square thumbnail",
- "Pull the alt text from the meta data of the image. If set, place placeholder text in the alt text field above.": "Pull the alt text from the meta data of the image. If set, place placeholder text in the alt text field above.",
- "The unix timestamp to save": "The unix timestamp to save",
- "The CMS ID of the depot to save": "The CMS ID of the depot to save",
- "The file to save": "The file to save",
- "The CMS ID of the file to save": "The CMS ID of the file to save",
- "The file extension of the file": "The file extension of the file",
- "The CMS ID of the gallery to save": "The CMS ID of the gallery to save",
- "The extension of the image": "The extension of the image",
- "The text content to save": "The text content to save",
- "The status of the toggle. \"true\" is on, \"false\" is off.": "The status of the toggle. \"true\" is on, \"false\" is off.",
- "The URL of the video to save": "The URL of the video to save",
+ "The Total CMS collection to use.": "The Total CMS collection to use.",
+ "Words to search for in any field. Use \"quotes\" for an exact phrase and \"or\" between words to match any.": "Words to search for in any field. Use \"quotes\" for an exact phrase and \"or\" between words to match any.",
+ "Keep only objects matching ALL of these filters, separated by commas. Examples: draft:false, featured, category:in:news|events, price:lte:100.": "Keep only objects matching ALL of these filters, separated by commas. Examples: draft:false, featured, category:in:news|events, price:lte:100.",
+ "Drop objects matching ANY of these filters, separated by commas. Example: draft:true.": "Drop objects matching ANY of these filters, separated by commas. Example: draft:true.",
+ "A field name to sort by. Put - in front for newest or largest first, for example -created or -date.": "A field name to sort by. Put - in front for newest or largest first, for example -created or -date.",
+ "How many objects to return (1-100).": "How many objects to return (1-100).",
+ "How many matching objects to skip. Use Next Offset from a previous run to get the next page.": "How many matching objects to skip. Use Next Offset from a previous run to get the next page.",
+ "The object to use. The list shows each object by title and ID.": "The object to use. The list shows each object by title and ID.",
+ "The collection ID, for example blog. Get it from List Collections.": "The collection ID, for example blog. Get it from List Collections.",
+ "The object ID (its URL slug). Get it from Find Objects (by Collection ID).": "The object ID (its URL slug). Get it from Find Objects (by Collection ID).",
+ "The ID (URL slug) for the new object. Leave empty to let Total CMS generate it, when the collection supports that.": "The ID (URL slug) for the new object. Leave empty to let Total CMS generate it, when the collection supports that.",
+ "The field values as JSON, for example {\"title\": \"Hello\", \"draft\": false}. Use Get Collection Fields to see the field names.": "The field values as JSON, for example {\"title\": \"Hello\", \"draft\": false}. Use Get Collection Fields to see the field names.",
+ "Only the fields to change, as JSON, for example {\"title\": \"New title\"}. Use Get Collection Fields to see the field names.": "Only the fields to change, as JSON, for example {\"title\": \"New title\"}. Use Get Collection Fields to see the field names.",
+ "The object to copy.": "The object to copy.",
+ "The ID (URL slug) for the copy, for example my-post-copy. Must not exist yet.": "The ID (URL slug) for the copy, for example my-post-copy. Must not exist yet.",
+ "The object to delete. This cannot be undone.": "The object to delete. This cannot be undone.",
+ "The image, gallery, file or depot field to upload to.": "The image, gallery, file or depot field to upload to.",
+ "The file to upload. Leave empty to use File URL instead.": "The file to upload. Leave empty to use File URL instead.",
+ "A public link to the file, ending in its file name with extension (for example https://example.com/photo.jpg). Your Total CMS site downloads it. Use either this or File.": "A public link to the file, ending in its file name with extension (for example https://example.com/photo.jpg). Your Total CMS site downloads it. Use either this or File.",
+ "Depot fields only: an optional folder path, such as 2026/reports.": "Depot fields only: an optional folder path, such as 2026/reports.",
+ "The number field to change.": "The number field to change.",
+ "How much to add or subtract. Must be more than 0.": "How much to add or subtract. Must be more than 0.",
+ "The blog collection.": "The blog collection.",
+ "The blog post to get.": "The blog post to get.",
+ "The ID of a collection that uses the Blog schema. The built-in Blog collection is called blog. Find other IDs with List Collections.": "The ID of a collection that uses the Blog schema. The built-in Blog collection is called blog. Find other IDs with List Collections.",
+ "The post ID (URL slug), for example my-first-post. If a post with this ID exists it is updated, otherwise a new post is created. Leave empty to create a new post with an ID made from the title.": "The post ID (URL slug), for example my-first-post. If a post with this ID exists it is updated, otherwise a new post is created. Leave empty to create a new post with an ID made from the title.",
+ "Required when creating a post.": "Required when creating a post.",
+ "The publication date. Defaults to now for new posts.": "The publication date. Defaults to now for new posts.",
+ "HTML is allowed.": "HTML is allowed.",
+ "The post body. HTML is allowed.": "The post body. HTML is allowed.",
+ "A link to related media, such as a video or podcast episode.": "A link to related media, such as a video or podcast episode.",
+ "Replaces the post categories. Separate them with commas, or map a list. Use a JSON list such as [\"News, Events\"] when a name contains a comma. Leave empty to keep the current ones.": "Replaces the post categories. Separate them with commas, or map a list. Use a JSON list such as [\"News, Events\"] when a name contains a comma. Leave empty to keep the current ones.",
+ "Replaces the post tags. Separate them with commas, or map a list. Use a JSON list such as [\"News, Events\"] when a name contains a comma. Leave empty to keep the current ones.": "Replaces the post tags. Separate them with commas, or map a list. Use a JSON list such as [\"News, Events\"] when a name contains a comma. Leave empty to keep the current ones.",
+ "Leave empty to keep the current status (new posts are published).": "Leave empty to keep the current status (new posts are published).",
+ "Leave empty to keep the current value.": "Leave empty to keep the current value.",
+ "The blog post to update.": "The blog post to update.",
+ "The image to upload. Leave empty to use Image URL instead.": "The image to upload. Leave empty to use Image URL instead.",
+ "A public link to the image, ending in its file name with extension (for example https://example.com/photo.jpg). Your Total CMS site downloads it. Use either this or Image.": "A public link to the image, ending in its file name with extension (for example https://example.com/photo.jpg). Your Total CMS site downloads it. Use either this or Image.",
+ "Describes the image for screen readers and search engines.": "Describes the image for screen readers and search engines.",
+ "The ID of a collection that uses the Text schema. The built-in Text collection is called text. Find other IDs with List Collections.": "The ID of a collection that uses the Text schema. The built-in Text collection is called text. Find other IDs with List Collections.",
+ "The ID of the text object, for example headline. A new ID creates the object.": "The ID of the text object, for example headline. A new ID creates the object.",
+ "The ID of a collection that uses the Toggle schema. The built-in Toggle collection is called toggle. Find other IDs with List Collections.": "The ID of a collection that uses the Toggle schema. The built-in Toggle collection is called toggle. Find other IDs with List Collections.",
+ "The ID of the toggle object. A new ID creates the object.": "The ID of the toggle object. A new ID creates the object.",
+ "Checked turns the toggle on, unchecked turns it off.": "Checked turns the toggle on, unchecked turns it off.",
+ "The ID of a collection that uses the Date schema. The built-in Date collection is called date. Find other IDs with List Collections.": "The ID of a collection that uses the Date schema. The built-in Date collection is called date. Find other IDs with List Collections.",
+ "The ID of the date object. A new ID creates the object.": "The ID of the date object. A new ID creates the object.",
+ "The date and time to store, for example 2026-12-31T18:00:00Z.": "The date and time to store, for example 2026-12-31T18:00:00Z.",
+ "The ID of a collection that uses the Image schema. The built-in Image collection is called image. Find other IDs with List Collections.": "The ID of a collection that uses the Image schema. The built-in Image collection is called image. Find other IDs with List Collections.",
+ "The ID of the image object. A new ID creates the object.": "The ID of the image object. A new ID creates the object.",
+ "The ID of a collection that uses the Gallery schema. The built-in Gallery collection is called gallery. Find other IDs with List Collections.": "The ID of a collection that uses the Gallery schema. The built-in Gallery collection is called gallery. Find other IDs with List Collections.",
+ "The ID of the gallery object. A new ID creates the object.": "The ID of the gallery object. A new ID creates the object.",
+ "The ID of a collection that uses the File schema. The built-in File collection is called file. Find other IDs with List Collections.": "The ID of a collection that uses the File schema. The built-in File collection is called file. Find other IDs with List Collections.",
+ "The ID of the file object. A new ID creates the object.": "The ID of the file object. A new ID creates the object.",
+ "The ID of a collection that uses the Depot schema. The built-in Depot collection is called depot. Find other IDs with List Collections.": "The ID of a collection that uses the Depot schema. The built-in Depot collection is called depot. Find other IDs with List Collections.",
+ "The ID of the depot object. A new ID creates the object.": "The ID of the depot object. A new ID creates the object.",
+ "Optional folder path inside the depot, such as 2026/reports.": "Optional folder path inside the depot, such as 2026/reports.",
+ "The ID of a collection that uses the Video schema. The built-in Video collection is called video. Find other IDs with List Collections.": "The ID of a collection that uses the Video schema. The built-in Video collection is called video. Find other IDs with List Collections.",
+ "The ID of the video object. A new ID creates the object.": "The ID of the video object. A new ID creates the object.",
+ "The video page link from YouTube, Vimeo, Loom or similar.": "The video page link from YouTube, Vimeo, Loom or similar.",
+ "The image, gallery, file or depot field name, such as image.": "The image, gallery, file or depot field name, such as image.",
+ "The name of the number field, for example views.": "The name of the number field, for example views.",
"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.",
- "Blog": "Blog",
- "Datastore": "Datastore",
- "Date": "Date",
- "Depot": "Depot",
- "Feed": "Feed",
- "Gallery": "Gallery",
- "Ratings": "Ratings",
- "Text": "Text",
- "Toggle": "Toggle",
- "Video": "Video",
- "Auto": "Auto",
- "Landscape": "Landscape",
- "Portrait": "Portrait",
- "Left": "Left",
- "Center": "Center",
- "Right": "Right",
- "Top": "Top",
- "Middle": "Middle",
- "Bottom": "Bottom",
- "jpg": "jpg",
- "png": "png",
+ "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.",
+ "Increase": "Increase",
+ "Decrease": "Decrease",
+ "Published": "Published",
+ "Draft": "Draft",
+ "Yes": "Yes",
+ "No": "No",
"GET": "GET",
"POST": "POST",
"PATCH": "PATCH",
"PUT": "PUT",
"DELETE": "DELETE",
"HEAD": "HEAD",
- "None": "None",
- "JSON": "JSON",
- "Form Data": "Form Data",
- "Raw": "Raw",
"New Blog Post": "New Blog Post",
- "Triggers when a new blog post is published": "Triggers when a new blog post is published"
+ "New Object": "New Object",
+ "Updated Object": "Updated Object",
+ "Triggers when a new post is added to a blog.": "Triggers when a new post is added to a blog.",
+ "Triggers when an object is added to a collection.": "Triggers when an object is added to a collection.",
+ "Triggers when an object in a collection is changed.": "Triggers when an object in a collection is changed.",
+ "Include Drafts": "Include Drafts",
+ "Include New Objects": "Include New Objects",
+ "The blog collection to watch.": "The blog collection to watch.",
+ "Also trigger for posts saved as drafts.": "Also trigger for posts saved as drafts.",
+ "The collection to watch. Its schema must have a \"created\" date field.": "The collection to watch. Its schema must have a \"created\" date field.",
+ "The collection to watch. Its schema must have an \"updated\" date field.": "The collection to watch. Its schema must have an \"updated\" date field.",
+ "Also trigger when an object is created.": "Also trigger when an object is created."
}
\ No newline at end of file
diff --git a/packages/pieces/community/totalcms/src/index.ts b/packages/pieces/community/totalcms/src/index.ts
index 76e79f3e2d1..be4cb80fc67 100644
--- a/packages/pieces/community/totalcms/src/index.ts
+++ b/packages/pieces/community/totalcms/src/index.ts
@@ -1,8 +1,22 @@
-import { createPiece } from '@activepieces/pieces-framework';
-import { cmsAuth } from './lib/auth';
-
+import { createCustomApiCallAction } from '@activepieces/pieces-common';
+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';
+import { adjustNumberAction } from './lib/actions/adjust-number';
+import { adjustNumberByIdAction } from './lib/actions/ai/adjust-number-by-id';
+import { cloneObjectByIdAction } from './lib/actions/ai/clone-object-by-id';
+import { createObjectByIdAction } from './lib/actions/ai/create-object-by-id';
+import { findObjectsByIdAction } from './lib/actions/ai/find-objects-by-id';
+import { getCollectionFieldsByIdAction } from './lib/actions/ai/get-collection-fields-by-id';
+import { getObjectByIdAction } from './lib/actions/ai/get-object-by-id';
+import { updateObjectByIdAction } from './lib/actions/ai/update-object-by-id';
+import { uploadFileByIdAction } from './lib/actions/ai/upload-file-by-id';
+import { cloneObjectAction } from './lib/actions/clone-object';
+import { createObjectAction } from './lib/actions/create-object';
+import { deleteObjectAction } from './lib/actions/delete-object';
+import { findObjectsAction } from './lib/actions/find-objects';
import { getBlogPostAction } from './lib/actions/get-blog-post';
+import { getCollectionSchemaAction } from './lib/actions/get-collection-schema';
import { getContentAction } from './lib/actions/get-content';
+import { listCollectionsAction } from './lib/actions/list-collections';
import { saveBlogGalleryAction } from './lib/actions/save-blog-gallery';
import { saveBlogImageAction } from './lib/actions/save-blog-image';
import { saveBlogPostAction } from './lib/actions/save-blog-post';
@@ -14,45 +28,64 @@ import { saveImageAction } from './lib/actions/save-image';
import { saveTextAction } from './lib/actions/save-text';
import { saveToggleAction } from './lib/actions/save-toggle';
import { saveVideoAction } from './lib/actions/save-video';
-
-import { createCustomApiCallAction } from '@activepieces/pieces-common';
-import { PieceCategory } from '@activepieces/pieces-framework';
+import { updateObjectAction } from './lib/actions/update-object';
+import { uploadFileAction } from './lib/actions/upload-file';
+import { cmsAuth, totalcmsBaseUrl } from './lib/auth';
import { newBlogPost } from './lib/triggers/new-blog-post';
+import { newObjectTrigger } from './lib/triggers/new-object';
+import { updatedObjectTrigger } from './lib/triggers/updated-object';
export const totalcms = createPiece({
displayName: 'Total CMS',
- description: 'Content management system for modern websites',
+ description: 'Flat-file content management system for websites, with collections, blogs, images and files.',
auth: cmsAuth,
- minimumSupportedRelease: '0.30.0',
+ minimumSupportedRelease: '0.88.2',
logoUrl: 'https://cdn.activepieces.com/pieces/totalcms.png',
categories: [PieceCategory.MARKETING],
- authors: ["joeworkman","kishanprmr","MoShizzle","abuaboud"],
+ authors: ['joeworkman', 'kishanprmr', 'MoShizzle', 'abuaboud'],
actions: [
+ listCollectionsAction,
+ getCollectionSchemaAction,
+ findObjectsAction,
getContentAction,
+ getObjectByIdAction,
+ createObjectAction,
+ updateObjectAction,
+ updateObjectByIdAction,
+ cloneObjectAction,
+ deleteObjectAction,
+ uploadFileAction,
+ adjustNumberAction,
getBlogPostAction,
saveBlogPostAction,
- saveBlogGalleryAction,
saveBlogImageAction,
- saveDateAction,
- saveDepotAction,
- saveFileAction,
- saveGalleryAction,
- saveImageAction,
+ saveBlogGalleryAction,
saveTextAction,
saveToggleAction,
+ saveDateAction,
+ saveImageAction,
+ saveGalleryAction,
+ saveFileAction,
+ saveDepotAction,
saveVideoAction,
+ getCollectionFieldsByIdAction,
+ findObjectsByIdAction,
+ createObjectByIdAction,
+ uploadFileByIdAction,
+ adjustNumberByIdAction,
+ cloneObjectByIdAction,
createCustomApiCallAction({
- baseUrl: (auth) => {
- if (!auth) {
- return '';
- }
- return (auth.props).domain;
- },
+ baseUrl: (auth) => {
+ if (!auth) {
+ return '';
+ }
+ return `${totalcmsBaseUrl(auth.props.domain)}/api`;
+ },
auth: cmsAuth,
authMapping: async (auth) => ({
- 'total-key': (auth.props ).license,
+ 'X-API-Key': auth.props.apiKey.trim(),
}),
}),
],
- triggers: [newBlogPost],
+ triggers: [newBlogPost, newObjectTrigger, updatedObjectTrigger],
});
diff --git a/packages/pieces/community/totalcms/src/lib/actions/adjust-number.ts b/packages/pieces/community/totalcms/src/lib/actions/adjust-number.ts
new file mode 100644
index 00000000000..75c0035021b
--- /dev/null
+++ b/packages/pieces/community/totalcms/src/lib/actions/adjust-number.ts
@@ -0,0 +1,33 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { cmsAuth } from '../auth';
+import { totalcmsOperations } from '../common/operations';
+import { totalcmsProps } from '../common/props';
+import { totalcmsOutputSchemas } from '../output-schemas';
+
+export const adjustNumberAction = createAction({
+ name: 'adjust_number',
+ classification: 'WRITE',
+ auth: cmsAuth,
+ displayName: 'Increase or Decrease Number',
+ description: 'Adds to or subtracts from a number field, such as a counter or stock level.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Adds to or subtracts from a number field of a Total CMS object in one step, for counters such as views, votes or stock. Use Update Object to set an exact value instead. Every call changes the number again, so retries double count.',
+ idempotent: false,
+ },
+ props: {
+ collection: totalcmsProps.collection(),
+ object_id: totalcmsProps.object(),
+ field: totalcmsProps.schemaField({
+ displayName: 'Number Field',
+ description: 'The number field to change.',
+ numeric: true,
+ }),
+ ...totalcmsOperations.adjustProps(),
+ },
+ outputSchema: totalcmsOutputSchemas.number,
+ async run(context) {
+ return totalcmsOperations.adjustNumber({ auth: context.auth, input: context.propsValue });
+ },
+});
diff --git a/packages/pieces/community/totalcms/src/lib/actions/ai/adjust-number-by-id.ts b/packages/pieces/community/totalcms/src/lib/actions/ai/adjust-number-by-id.ts
new file mode 100644
index 00000000000..d462e13e1d4
--- /dev/null
+++ b/packages/pieces/community/totalcms/src/lib/actions/ai/adjust-number-by-id.ts
@@ -0,0 +1,33 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { cmsAuth } from '../../auth';
+import { totalcmsOperations } from '../../common/operations';
+import { totalcmsProps } from '../../common/props';
+import { totalcmsOutputSchemas } from '../../output-schemas';
+
+export const adjustNumberByIdAction = createAction({
+ name: 'adjust_number_by_id',
+ classification: 'WRITE',
+ auth: cmsAuth,
+ displayName: 'Increase or Decrease Number (by ID)',
+ description: 'Adds to or subtracts from a number field, such as a counter or stock level.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Adds to or subtracts from a number field of a Total CMS object, given the collection ID, object ID and field name, for counters such as views, votes or stock. Use Update Object (by ID) to set an exact value. Every call changes the number again, so retries double count.',
+ idempotent: false,
+ },
+ props: {
+ collection: totalcmsProps.collectionIdText(),
+ object_id: totalcmsProps.objectIdText(),
+ field: Property.ShortText({
+ displayName: 'Field Name',
+ description: 'The name of the number field, for example views.',
+ required: true,
+ }),
+ ...totalcmsOperations.adjustProps(),
+ },
+ outputSchema: totalcmsOutputSchemas.number,
+ async run(context) {
+ return totalcmsOperations.adjustNumber({ auth: context.auth, input: context.propsValue });
+ },
+});
diff --git a/packages/pieces/community/totalcms/src/lib/actions/ai/clone-object-by-id.ts b/packages/pieces/community/totalcms/src/lib/actions/ai/clone-object-by-id.ts
new file mode 100644
index 00000000000..159166488db
--- /dev/null
+++ b/packages/pieces/community/totalcms/src/lib/actions/ai/clone-object-by-id.ts
@@ -0,0 +1,33 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { cmsAuth } from '../../auth';
+import { totalcmsOperations } from '../../common/operations';
+import { totalcmsProps } from '../../common/props';
+import { totalcmsOutputSchemas } from '../../output-schemas';
+
+export const cloneObjectByIdAction = createAction({
+ name: 'clone_object_by_id',
+ classification: 'WRITE',
+ auth: cmsAuth,
+ displayName: 'Duplicate Object (by ID)',
+ description: 'Copies an object under a new ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Copies a Total CMS object, given the collection ID and object ID, with its fields and files, to a new ID in the same collection. Use it to start new content from a template. Fails if the new ID already exists, so a retry does not create a second copy.',
+ idempotent: false,
+ },
+ props: {
+ collection: totalcmsProps.collectionIdText(),
+ object_id: totalcmsProps.objectIdText(),
+ new_id: totalcmsOperations.newIdProp(),
+ },
+ outputSchema: totalcmsOutputSchemas.object,
+ async run(context) {
+ return totalcmsOperations.cloneObject({
+ auth: context.auth,
+ collection: context.propsValue.collection,
+ objectId: context.propsValue.object_id,
+ newId: context.propsValue.new_id,
+ });
+ },
+});
diff --git a/packages/pieces/community/totalcms/src/lib/actions/ai/create-object-by-id.ts b/packages/pieces/community/totalcms/src/lib/actions/ai/create-object-by-id.ts
new file mode 100644
index 00000000000..ecc8e1f9b05
--- /dev/null
+++ b/packages/pieces/community/totalcms/src/lib/actions/ai/create-object-by-id.ts
@@ -0,0 +1,36 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { cmsAuth } from '../../auth';
+import { totalcmsOperations } from '../../common/operations';
+import { totalcmsProps } from '../../common/props';
+import { totalcmsOutputSchemas } from '../../output-schemas';
+
+export const createObjectByIdAction = createAction({
+ name: 'create_object_by_id',
+ classification: 'WRITE',
+ auth: cmsAuth,
+ displayName: 'Create Object (by Collection ID)',
+ description: 'Creates a new object in any collection.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates a new object in a Total CMS collection, given its ID (from List Collections), from a JSON object of field values (names from Get Collection Fields (by ID)). Fails if the object ID already exists; leave it empty to let Total CMS make one from the title when the schema allows it. Each call creates a new object.',
+ idempotent: false,
+ },
+ props: {
+ collection: totalcmsProps.collectionIdText(),
+ object_id: totalcmsProps.objectIdText({
+ description: 'The ID (URL slug) for the new object. Leave empty to let Total CMS generate it, when the collection supports that.',
+ required: false,
+ }),
+ fields: totalcmsOperations.createFieldsProp(),
+ },
+ outputSchema: totalcmsOutputSchemas.object,
+ async run(context) {
+ return totalcmsOperations.createObject({
+ auth: context.auth,
+ collection: context.propsValue.collection,
+ objectId: context.propsValue.object_id,
+ fields: context.propsValue.fields,
+ });
+ },
+});
diff --git a/packages/pieces/community/totalcms/src/lib/actions/ai/find-objects-by-id.ts b/packages/pieces/community/totalcms/src/lib/actions/ai/find-objects-by-id.ts
new file mode 100644
index 00000000000..85ce3a57218
--- /dev/null
+++ b/packages/pieces/community/totalcms/src/lib/actions/ai/find-objects-by-id.ts
@@ -0,0 +1,27 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { cmsAuth } from '../../auth';
+import { totalcmsOperations } from '../../common/operations';
+import { totalcmsProps } from '../../common/props';
+import { totalcmsOutputSchemas } from '../../output-schemas';
+
+export const findObjectsByIdAction = createAction({
+ name: 'find_objects_by_id',
+ classification: 'SEARCH',
+ auth: cmsAuth,
+ displayName: 'Find Objects (by Collection ID)',
+ description: 'Searches, filters and sorts the objects of a collection.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Searches a Total CMS collection, given its ID (from List Collections), by full-text search, include/exclude filters (e.g. draft:false, price:lte:100) and sort (e.g. -created), returning up to 100 objects with total, has_more and next_offset for paging. Returns index fields only; use Get Object (by ID) for long fields such as blog content. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ collection: totalcmsProps.collectionIdText(),
+ ...totalcmsOperations.findProps(),
+ },
+ outputSchema: totalcmsOutputSchemas.find,
+ async run(context) {
+ return totalcmsOperations.findObjects({ auth: context.auth, input: context.propsValue });
+ },
+});
diff --git a/packages/pieces/community/totalcms/src/lib/actions/ai/get-collection-fields-by-id.ts b/packages/pieces/community/totalcms/src/lib/actions/ai/get-collection-fields-by-id.ts
new file mode 100644
index 00000000000..86a31957ea3
--- /dev/null
+++ b/packages/pieces/community/totalcms/src/lib/actions/ai/get-collection-fields-by-id.ts
@@ -0,0 +1,26 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { cmsAuth } from '../../auth';
+import { totalcmsOperations } from '../../common/operations';
+import { totalcmsProps } from '../../common/props';
+import { totalcmsOutputSchemas } from '../../output-schemas';
+
+export const getCollectionFieldsByIdAction = createAction({
+ name: 'get_collection_fields_by_id',
+ classification: 'READ',
+ auth: cmsAuth,
+ displayName: 'Get Collection Fields (by ID)',
+ description: 'Lists the fields of a collection, with their types.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns the field list of a Total CMS collection, given its ID (from List Collections): name, label, field type, data type, required, and whether Find Objects returns it. Call it before Create Object (by ID) or Update Object (by ID) to learn the field names. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ collection: totalcmsProps.collectionIdText(),
+ },
+ outputSchema: totalcmsOutputSchemas.schema,
+ async run(context) {
+ return totalcmsOperations.collectionFields({ auth: context.auth, collection: context.propsValue.collection });
+ },
+});
diff --git a/packages/pieces/community/totalcms/src/lib/actions/ai/get-object-by-id.ts b/packages/pieces/community/totalcms/src/lib/actions/ai/get-object-by-id.ts
new file mode 100644
index 00000000000..d1d99baa3c8
--- /dev/null
+++ b/packages/pieces/community/totalcms/src/lib/actions/ai/get-object-by-id.ts
@@ -0,0 +1,31 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { cmsAuth } from '../../auth';
+import { totalcmsApi } from '../../common/client';
+import { totalcmsProps } from '../../common/props';
+import { totalcmsShape } from '../../common/shape';
+import { totalcmsOutputSchemas } from '../../output-schemas';
+
+export const getObjectByIdAction = createAction({
+ name: 'get_object_by_id',
+ classification: 'READ',
+ auth: cmsAuth,
+ displayName: 'Get Object (by ID)',
+ description: 'Gets one object by collection ID and object ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Reads one Total CMS object with all its fields, given the collection ID (from List Collections) and object ID (from Find Objects (by Collection ID)). Use it to fetch long fields such as blog content, which Find Objects leaves out. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ collection: totalcmsProps.collectionIdText(),
+ object_id: totalcmsProps.objectIdText(),
+ },
+ outputSchema: totalcmsOutputSchemas.object,
+ async run(context) {
+ const collection = totalcmsShape.requireId({ value: context.propsValue.collection, label: 'Collection ID' });
+ const id = totalcmsShape.requireId({ value: context.propsValue.object_id, label: 'Object ID' });
+ const object = await totalcmsApi.getObject({ auth: context.auth, collection, id });
+ return totalcmsShape.generic({ collection, object });
+ },
+});
diff --git a/packages/pieces/community/totalcms/src/lib/actions/ai/update-object-by-id.ts b/packages/pieces/community/totalcms/src/lib/actions/ai/update-object-by-id.ts
new file mode 100644
index 00000000000..47cc349c76a
--- /dev/null
+++ b/packages/pieces/community/totalcms/src/lib/actions/ai/update-object-by-id.ts
@@ -0,0 +1,33 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { cmsAuth } from '../../auth';
+import { totalcmsOperations } from '../../common/operations';
+import { totalcmsProps } from '../../common/props';
+import { totalcmsOutputSchemas } from '../../output-schemas';
+
+export const updateObjectByIdAction = createAction({
+ name: 'update_object_by_id',
+ classification: 'WRITE',
+ auth: cmsAuth,
+ displayName: 'Update Object (by ID)',
+ description: 'Changes some fields of an object, given the collection ID and object ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Updates only the given fields of an existing Total CMS object, given the collection ID (from List Collections) and object ID (from Find Objects (by Collection ID)); other fields stay as stored. Get field names from Get Collection Fields (by ID). Fails if the object does not exist. Sending the same values again changes nothing.',
+ idempotent: true,
+ },
+ props: {
+ collection: totalcmsProps.collectionIdText(),
+ object_id: totalcmsProps.objectIdText(),
+ fields: totalcmsOperations.updateFieldsProp(),
+ },
+ outputSchema: totalcmsOutputSchemas.object,
+ async run(context) {
+ return totalcmsOperations.updateObject({
+ auth: context.auth,
+ collection: context.propsValue.collection,
+ objectId: context.propsValue.object_id,
+ fields: context.propsValue.fields,
+ });
+ },
+});
diff --git a/packages/pieces/community/totalcms/src/lib/actions/ai/upload-file-by-id.ts b/packages/pieces/community/totalcms/src/lib/actions/ai/upload-file-by-id.ts
new file mode 100644
index 00000000000..cfd80f6da46
--- /dev/null
+++ b/packages/pieces/community/totalcms/src/lib/actions/ai/upload-file-by-id.ts
@@ -0,0 +1,33 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { cmsAuth } from '../../auth';
+import { totalcmsOperations } from '../../common/operations';
+import { totalcmsProps } from '../../common/props';
+import { totalcmsOutputSchemas } from '../../output-schemas';
+
+export const uploadFileByIdAction = createAction({
+ name: 'upload_file_by_id',
+ classification: 'WRITE',
+ auth: cmsAuth,
+ displayName: 'Upload File to Field (by ID)',
+ description: 'Uploads a file or image to an image, gallery, file or depot field of an object.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Uploads a file (public URL or file) into an image, gallery, file or depot field of a Total CMS object, given the collection ID, object ID and field name (from Get Collection Fields (by ID)). Image and file fields are replaced; gallery and depot fields get one more entry per call, so retries can add duplicates.',
+ idempotent: false,
+ },
+ props: {
+ collection: totalcmsProps.collectionIdText(),
+ object_id: totalcmsProps.objectIdText(),
+ field: Property.ShortText({
+ displayName: 'Field Name',
+ description: 'The image, gallery, file or depot field name, such as image.',
+ required: true,
+ }),
+ ...totalcmsOperations.uploadExtraProps(),
+ },
+ outputSchema: totalcmsOutputSchemas.upload,
+ async run(context) {
+ return totalcmsOperations.uploadFile({ auth: context.auth, input: context.propsValue });
+ },
+});
diff --git a/packages/pieces/community/totalcms/src/lib/actions/clone-object.ts b/packages/pieces/community/totalcms/src/lib/actions/clone-object.ts
new file mode 100644
index 00000000000..9a025ccc0ef
--- /dev/null
+++ b/packages/pieces/community/totalcms/src/lib/actions/clone-object.ts
@@ -0,0 +1,33 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { cmsAuth } from '../auth';
+import { totalcmsOperations } from '../common/operations';
+import { totalcmsProps } from '../common/props';
+import { totalcmsOutputSchemas } from '../output-schemas';
+
+export const cloneObjectAction = createAction({
+ name: 'clone_object',
+ classification: 'WRITE',
+ auth: cmsAuth,
+ displayName: 'Duplicate Object',
+ description: 'Copies an object under a new ID.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Copies an existing Total CMS object, with its fields and files, to a new ID in the same collection. Use it to start a new post or page from a template. Fails if the new ID already exists, so a retry does not create a second copy.',
+ idempotent: false,
+ },
+ props: {
+ collection: totalcmsProps.collection(),
+ object_id: totalcmsProps.object({ description: 'The object to copy.' }),
+ new_id: totalcmsOperations.newIdProp(),
+ },
+ outputSchema: totalcmsOutputSchemas.object,
+ async run(context) {
+ return totalcmsOperations.cloneObject({
+ auth: context.auth,
+ collection: context.propsValue.collection,
+ objectId: context.propsValue.object_id,
+ newId: context.propsValue.new_id,
+ });
+ },
+});
diff --git a/packages/pieces/community/totalcms/src/lib/actions/create-object.ts b/packages/pieces/community/totalcms/src/lib/actions/create-object.ts
new file mode 100644
index 00000000000..0343993bd3d
--- /dev/null
+++ b/packages/pieces/community/totalcms/src/lib/actions/create-object.ts
@@ -0,0 +1,36 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { cmsAuth } from '../auth';
+import { totalcmsOperations } from '../common/operations';
+import { totalcmsProps } from '../common/props';
+import { totalcmsOutputSchemas } from '../output-schemas';
+
+export const createObjectAction = createAction({
+ name: 'create_object',
+ classification: 'WRITE',
+ auth: cmsAuth,
+ displayName: 'Create Object',
+ description: 'Creates a new object in any collection.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Creates a new object in a Total CMS collection from a JSON object of field values (get the field names from Get Collection Fields). Fails if the ID already exists; leave the ID empty to let Total CMS make one from the title when the schema allows it. Each call creates a new object.',
+ idempotent: false,
+ },
+ props: {
+ collection: totalcmsProps.collection(),
+ object_id: totalcmsProps.objectIdText({
+ description: 'The ID (URL slug) for the new object. Leave empty to let Total CMS generate it, when the collection supports that.',
+ required: false,
+ }),
+ fields: totalcmsOperations.createFieldsProp(),
+ },
+ outputSchema: totalcmsOutputSchemas.object,
+ async run(context) {
+ return totalcmsOperations.createObject({
+ auth: context.auth,
+ collection: context.propsValue.collection,
+ objectId: context.propsValue.object_id,
+ fields: context.propsValue.fields,
+ });
+ },
+});
diff --git a/packages/pieces/community/totalcms/src/lib/actions/delete-object.ts b/packages/pieces/community/totalcms/src/lib/actions/delete-object.ts
new file mode 100644
index 00000000000..36675fd3578
--- /dev/null
+++ b/packages/pieces/community/totalcms/src/lib/actions/delete-object.ts
@@ -0,0 +1,35 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { cmsAuth } from '../auth';
+import { totalcmsApi } from '../common/client';
+import { totalcmsProps } from '../common/props';
+import { totalcmsShape } from '../common/shape';
+import { totalcmsOutputSchemas } from '../output-schemas';
+
+export const deleteObjectAction = createAction({
+ name: 'delete_object',
+ classification: 'DESTRUCTIVE',
+ auth: cmsAuth,
+ displayName: 'Delete Object',
+ description: 'Permanently deletes an object and its files.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Permanently deletes one Total CMS object, including its uploaded files. This cannot be undone; a second call fails because the object is gone.',
+ idempotent: false,
+ },
+ props: {
+ collection: totalcmsProps.collection(),
+ object_id: totalcmsProps.object({ description: 'The object to delete. This cannot be undone.' }),
+ },
+ outputSchema: totalcmsOutputSchemas.deleted,
+ async run(context) {
+ const collection = totalcmsShape.requireId({ value: context.propsValue.collection, label: 'Collection' });
+ const id = totalcmsShape.requireId({ value: context.propsValue.object_id, label: 'Object' });
+ const existing = await totalcmsApi.findObject({ auth: context.auth, collection, id });
+ if (!existing) {
+ throw new Error(`Object "${id}" was not found in collection "${collection}". It may already be deleted.`);
+ }
+ await totalcmsApi.deleteObject({ auth: context.auth, collection, id });
+ return { deleted: true, collection, id };
+ },
+});
diff --git a/packages/pieces/community/totalcms/src/lib/actions/find-objects.ts b/packages/pieces/community/totalcms/src/lib/actions/find-objects.ts
new file mode 100644
index 00000000000..60b8d4d48fd
--- /dev/null
+++ b/packages/pieces/community/totalcms/src/lib/actions/find-objects.ts
@@ -0,0 +1,27 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { cmsAuth } from '../auth';
+import { totalcmsOperations } from '../common/operations';
+import { totalcmsProps } from '../common/props';
+import { totalcmsOutputSchemas } from '../output-schemas';
+
+export const findObjectsAction = createAction({
+ name: 'find_objects',
+ classification: 'SEARCH',
+ auth: cmsAuth,
+ displayName: 'Find Objects',
+ description: 'Searches, filters and sorts the objects of a collection.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Searches a Total CMS collection by full-text search, include/exclude filters (e.g. draft:false, price:lte:100) and sort (e.g. -created), returning up to 100 objects per call with total, has_more and next_offset for paging. Returns index fields only; use Get Object for long fields such as blog content. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ collection: totalcmsProps.collection(),
+ ...totalcmsOperations.findProps(),
+ },
+ outputSchema: totalcmsOutputSchemas.find,
+ async run(context) {
+ return totalcmsOperations.findObjects({ auth: context.auth, input: context.propsValue });
+ },
+});
diff --git a/packages/pieces/community/totalcms/src/lib/actions/get-blog-post.ts b/packages/pieces/community/totalcms/src/lib/actions/get-blog-post.ts
index eadeeba440d..2565d9707d6 100644
--- a/packages/pieces/community/totalcms/src/lib/actions/get-blog-post.ts
+++ b/packages/pieces/community/totalcms/src/lib/actions/get-blog-post.ts
@@ -1,30 +1,31 @@
-import { createAction, Property } from '@activepieces/pieces-framework';
-import { getBlogPost } from '../api';
+import { createAction } from '@activepieces/pieces-framework';
import { cmsAuth } from '../auth';
+import { totalcmsApi } from '../common/client';
+import { totalcmsProps } from '../common/props';
+import { totalcmsShape } from '../common/shape';
+import { totalcmsOutputSchemas } from '../output-schemas';
export const getBlogPostAction = createAction({
name: 'get_blog_post',
classification: 'READ',
auth: cmsAuth,
displayName: 'Get Blog Post',
- description: 'Get a blog post from Total CMS',
- audience: 'both',
- aiMetadata: { description: 'Reads a single blog post from a Total CMS blog, identified by the blog CMS ID (slug) plus the post permalink. Use to retrieve an existing post when you already know its permalink. Read-only and idempotent.', idempotent: true },
+ description: 'Gets a blog post with its full content.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Reads one blog post (title, content, summary, author, categories, tags, image, gallery, draft and featured flags) from a Total CMS blog collection, given the post ID. Use Find Objects to search posts first. Read-only and safe to retry.',
+ idempotent: true,
+ },
props: {
- slug: Property.ShortText({
- displayName: 'CMS ID',
- description: 'The CMS ID of the content to retrieve',
- required: true,
- }),
- permalink: Property.ShortText({
- displayName: 'Permalink',
- description: 'The permalink of the post to retrieve',
- required: true,
- }),
+ collection: totalcmsProps.collection({ displayName: 'Blog', description: 'The blog collection.', schemas: ['blog'] }),
+ object_id: totalcmsProps.object({ displayName: 'Post', description: 'The blog post to get.' }),
},
+ outputSchema: totalcmsOutputSchemas.blogPost,
async run(context) {
- const slug = context.propsValue.slug;
- const permalink = context.propsValue.permalink;
- return await getBlogPost(context.auth, slug, permalink);
+ const collection = totalcmsShape.requireId({ value: context.propsValue.collection, label: 'Blog' });
+ const id = totalcmsShape.requireId({ value: context.propsValue.object_id, label: 'Post' });
+ const object = await totalcmsApi.getObject({ auth: context.auth, collection, id });
+ return totalcmsShape.typed({ collection, object });
},
});
diff --git a/packages/pieces/community/totalcms/src/lib/actions/get-collection-schema.ts b/packages/pieces/community/totalcms/src/lib/actions/get-collection-schema.ts
new file mode 100644
index 00000000000..33c25633941
--- /dev/null
+++ b/packages/pieces/community/totalcms/src/lib/actions/get-collection-schema.ts
@@ -0,0 +1,26 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { cmsAuth } from '../auth';
+import { totalcmsOperations } from '../common/operations';
+import { totalcmsProps } from '../common/props';
+import { totalcmsOutputSchemas } from '../output-schemas';
+
+export const getCollectionSchemaAction = createAction({
+ name: 'get_collection_schema',
+ classification: 'READ',
+ auth: cmsAuth,
+ displayName: 'Get Collection Fields',
+ description: 'Lists the fields of a collection, with their types.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Returns the field list of a Total CMS collection (name, label, field type, data type, required, and whether Find Objects returns it). Call it before Create Object or Update Object to learn which field names to send. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ collection: totalcmsProps.collection(),
+ },
+ outputSchema: totalcmsOutputSchemas.schema,
+ async run(context) {
+ return totalcmsOperations.collectionFields({ auth: context.auth, collection: context.propsValue.collection });
+ },
+});
diff --git a/packages/pieces/community/totalcms/src/lib/actions/get-content.ts b/packages/pieces/community/totalcms/src/lib/actions/get-content.ts
index 7269e7559c1..9107660d636 100644
--- a/packages/pieces/community/totalcms/src/lib/actions/get-content.ts
+++ b/packages/pieces/community/totalcms/src/lib/actions/get-content.ts
@@ -1,46 +1,31 @@
-import { createAction, Property } from '@activepieces/pieces-framework';
-import { getContent } from '../api';
+import { createAction } from '@activepieces/pieces-framework';
import { cmsAuth } from '../auth';
+import { totalcmsApi } from '../common/client';
+import { totalcmsProps } from '../common/props';
+import { totalcmsShape } from '../common/shape';
+import { totalcmsOutputSchemas } from '../output-schemas';
export const getContentAction = createAction({
name: 'get_content',
classification: 'READ',
auth: cmsAuth,
- displayName: 'Get Content',
- description: 'Get content from your Total CMS website',
- audience: 'both',
- aiMetadata: { description: 'Reads a single Total CMS content item by its CMS ID, where the content type is one of blog, datastore, date, depot, feed, file, gallery, image, ratings, text, toggle, or video. Use to fetch the current value of a known CMS field before displaying or updating it. Requires both the content type and the exact CMS ID (slug); read-only and idempotent.', idempotent: true },
+ displayName: 'Get Object',
+ description: 'Gets one object (all its fields) from a collection.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Reads one Total CMS object with all its fields, given the collection and the object ID. Use it to fetch full content (Find Objects only returns index fields). Read-only and safe to retry.',
+ idempotent: true,
+ },
props: {
- type: Property.StaticDropdown({
- displayName: 'Data Type',
- description: 'The type of data to return',
- required: true,
- options: {
- options: [
- { label: 'Blog', value: 'blog' },
- { label: 'Datastore', value: 'datastore' },
- { label: 'Date', value: 'date' },
- { label: 'Depot', value: 'depot' },
- { label: 'Feed', value: 'feed' },
- { label: 'File', value: 'file' },
- { label: 'Gallery', value: 'gallery' },
- { label: 'Image', value: 'image' },
- { label: 'Ratings', value: 'ratings' },
- { label: 'Text', value: 'text' },
- { label: 'Toggle', value: 'toggle' },
- { label: 'Video', value: 'video' },
- ],
- },
- }),
- slug: Property.ShortText({
- displayName: 'CMS ID',
- description: 'The CMS ID of the content to retrieve',
- required: true,
- }),
+ collection: totalcmsProps.collection(),
+ object_id: totalcmsProps.object(),
},
+ outputSchema: totalcmsOutputSchemas.object,
async run(context) {
- const type = context.propsValue.type;
- const slug = context.propsValue.slug;
- return await getContent(context.auth, type, slug);
+ const collection = totalcmsShape.requireId({ value: context.propsValue.collection, label: 'Collection' });
+ const id = totalcmsShape.requireId({ value: context.propsValue.object_id, label: 'Object' });
+ const object = await totalcmsApi.getObject({ auth: context.auth, collection, id });
+ return totalcmsShape.generic({ collection, object });
},
});
diff --git a/packages/pieces/community/totalcms/src/lib/actions/list-collections.ts b/packages/pieces/community/totalcms/src/lib/actions/list-collections.ts
new file mode 100644
index 00000000000..db39bc157a1
--- /dev/null
+++ b/packages/pieces/community/totalcms/src/lib/actions/list-collections.ts
@@ -0,0 +1,24 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { cmsAuth } from '../auth';
+import { totalcmsApi } from '../common/client';
+import { totalcmsOutputSchemas } from '../output-schemas';
+
+export const listCollectionsAction = createAction({
+ name: 'list_collections',
+ classification: 'SEARCH',
+ auth: cmsAuth,
+ displayName: 'List Collections',
+ description: 'Lists all collections on the site.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Lists every Total CMS collection on the site with its ID, schema (blog, text, image and so on) and object count. Call it first to find the collection ID other actions need. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ props: {},
+ outputSchema: totalcmsOutputSchemas.collections,
+ async run(context) {
+ const collections = await totalcmsApi.listCollections({ auth: context.auth });
+ return { collections, count: collections.length };
+ },
+});
diff --git a/packages/pieces/community/totalcms/src/lib/actions/save-blog-gallery.ts b/packages/pieces/community/totalcms/src/lib/actions/save-blog-gallery.ts
index 043988d9230..4faf9489e07 100644
--- a/packages/pieces/community/totalcms/src/lib/actions/save-blog-gallery.ts
+++ b/packages/pieces/community/totalcms/src/lib/actions/save-blog-gallery.ts
@@ -1,130 +1,42 @@
-import {
- createAction,
- Property,
-} from '@activepieces/pieces-framework';
-import { saveBlogGallery } from '../api';
+import { createAction } from '@activepieces/pieces-framework';
import { cmsAuth } from '../auth';
-import * as z from 'zod/mini'
-import { propsValidation } from '@activepieces/pieces-common';
+import { totalcmsProps } from '../common/props';
+import { totalcmsShape } from '../common/shape';
+import { totalcmsUpload } from '../common/upload';
+import { totalcmsOutputSchemas } from '../output-schemas';
export const saveBlogGalleryAction = createAction({
name: 'save_blog_gallery',
classification: 'WRITE',
auth: cmsAuth,
- displayName: 'Save Blog Post Gallery Image',
- description: 'Save image to Total CMS blog post gallery',
- audience: 'both',
- aiMetadata: { description: 'Uploads an image into the gallery of a specific blog post in Total CMS, identified by the blog CMS ID (slug) and post permalink, with alt text and thumbnail sizing/crop options. Use to add a photo to a post gallery. Not idempotent: each call appends another image to the gallery.', idempotent: false },
+ displayName: 'Add Image to Blog Post Gallery',
+ description: 'Adds an image to the gallery of a blog post.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Adds one image (file or public URL) to the gallery of an existing Total CMS blog post. Optional alt text is saved on the new image. Each call adds another image, so retries add duplicates.',
+ idempotent: false,
+ },
props: {
- slug: Property.ShortText({
- displayName: 'CMS ID',
- description: 'The CMS ID of the blog to save',
- required: true,
- }),
- permalink: Property.ShortText({
- displayName: 'Permalink',
- description: 'The permalink of the blog post to save',
- required: true,
- }),
- image: Property.File({
- displayName: 'Image',
- description: 'The image to save',
- required: true,
- }),
- alt: Property.ShortText({
- displayName: 'Alt Text',
- description: 'The alt text for the image',
- required: true,
- }),
- quality: Property.Number({
- displayName: 'Thumbnail Quality',
- description: 'The quality of the thumbnail',
- required: true,
- defaultValue: 85,
- }),
- scaleTh: Property.Number({
- displayName: 'Thumbnail Scale',
- description: 'The scale of the thumbnail',
- required: true,
- defaultValue: 400,
- }),
- scaleSq: Property.Number({
- displayName: 'Thumbnail Square Scale',
- description: 'The scale of the square thumbnail',
- required: true,
- defaultValue: 400,
- }),
- resize: Property.StaticDropdown({
- displayName: 'Thumbnail Resize Method',
- description: 'The method to use when resizing the thumbnail',
- required: true,
- defaultValue: 'auto',
- options: {
- options: [
- { label: 'Auto', value: 'auto' },
- { label: 'Landscape', value: 'landscape' },
- { label: 'Portrait', value: 'portrait' },
- ],
- },
- }),
- lcrop: Property.StaticDropdown({
- displayName: 'Thumbnail Landscape Crop',
- description:
- 'The method to use when cropping the landscape thumbnail for the square thumbnail',
- required: true,
- defaultValue: 'center',
- options: {
- options: [
- { label: 'Left', value: 'left' },
- { label: 'Center', value: 'center' },
- { label: 'Right', value: 'right' },
- ],
- },
- }),
- pcrop: Property.StaticDropdown({
- displayName: 'Thumbnail Landscape Crop',
- description:
- 'The method to use when cropping the landscape thumbnail for the square thumbnail',
- required: true,
- defaultValue: 'middle',
- options: {
- options: [
- { label: 'Top', value: 'top' },
- { label: 'Middle', value: 'middle' },
- { label: 'Bottom', value: 'bottom' },
- ],
- },
- }),
- altMeta: Property.Checkbox({
- displayName: 'Pull Alt Text from Meta Data',
- description:
- 'Pull the alt text from the meta data of the image. If set, place placeholder text in the alt text field above.',
- required: true,
- }),
+ collection: totalcmsProps.collection({ displayName: 'Blog', description: 'The blog collection.', schemas: ['blog'] }),
+ object_id: totalcmsProps.object({ displayName: 'Post', description: 'The blog post to update.' }),
+ ...totalcmsUpload.fileProps({ fileLabel: 'Image' }),
+ alt: totalcmsUpload.altProp(),
},
+ outputSchema: totalcmsOutputSchemas.blogPostUpload,
async run(context) {
- await propsValidation.validateZod(context.propsValue, {
- quality: z.number().check(z.minimum(1), z.maximum(100)),
- scaleTh: z.number().check(z.minimum(1)),
- scaleSq: z.number().check(z.minimum(1)),
- });
- const slug = context.propsValue.slug;
- const image = {
- filename: context.propsValue.image.filename,
- base64: context.propsValue.image.base64,
- };
- return await saveBlogGallery(context.auth, slug, image, {
- permalink: context.propsValue.permalink,
- thumbs: 1,
- optimize: 1,
- alttype: context.propsValue.altMeta ? 'meta' : 'user',
- alt: context.propsValue.alt,
- quality: context.propsValue.quality,
- scale_th: context.propsValue.scaleTh,
- scale_sq: context.propsValue.scaleSq,
- resize: context.propsValue.resize,
- lcrop: context.propsValue.lcrop,
- pcrop: context.propsValue.pcrop,
+ const collection = totalcmsShape.requireId({ value: context.propsValue.collection, label: 'Collection' });
+ const id = totalcmsShape.requireId({ value: context.propsValue.object_id, label: 'Post' });
+ const result = await totalcmsUpload.save({
+ auth: context.auth,
+ collection,
+ id,
+ property: 'gallery',
+ file: context.propsValue.file,
+ fileUrl: context.propsValue.file_url,
+ alt: context.propsValue.alt ?? undefined,
+ multiple: true,
});
+ return { ...totalcmsShape.typed({ collection, object: result.object }), preview_url: result.preview_url, warning: result.warning };
},
});
diff --git a/packages/pieces/community/totalcms/src/lib/actions/save-blog-image.ts b/packages/pieces/community/totalcms/src/lib/actions/save-blog-image.ts
index 07db9cc6bb5..0b99f5217da 100644
--- a/packages/pieces/community/totalcms/src/lib/actions/save-blog-image.ts
+++ b/packages/pieces/community/totalcms/src/lib/actions/save-blog-image.ts
@@ -1,134 +1,42 @@
-import {
- createAction,
- Property,
-} from '@activepieces/pieces-framework';
-import * as z from 'zod/mini'
-import { propsValidation } from '@activepieces/pieces-common';
-import { saveBlogImage } from '../api';
+import { createAction } from '@activepieces/pieces-framework';
import { cmsAuth } from '../auth';
+import { totalcmsProps } from '../common/props';
+import { totalcmsShape } from '../common/shape';
+import { totalcmsUpload } from '../common/upload';
+import { totalcmsOutputSchemas } from '../output-schemas';
export const saveBlogImageAction = createAction({
name: 'save_blog_image',
classification: 'WRITE',
auth: cmsAuth,
- displayName: 'Save Blog Post Image',
- description: 'Save image to Total CMS blog post',
- audience: 'both',
- aiMetadata: { description: "Sets the featured/main image of a specific blog post in Total CMS, identified by the blog CMS ID (slug) and post permalink, with alt text and thumbnail sizing/crop options. Use to attach or replace a post's primary image. Idempotent: the post holds one such image, so repeating with the same input replaces it rather than accumulating.", idempotent: true },
+ displayName: 'Set Blog Post Image',
+ description: 'Uploads the main image of a blog post, replacing the current one.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Uploads the main image (file or public URL) of an existing Total CMS blog post, replacing the current image. Optional alt text is saved with it. Running it again with the same image leaves the same result.',
+ idempotent: true,
+ },
props: {
- slug: Property.ShortText({
- displayName: 'CMS ID',
- description: 'The CMS ID of the content to save',
- required: true,
- }),
- permalink: Property.ShortText({
- displayName: 'Permalink',
- description: 'The permalink of the blog post to save',
- required: true,
- }),
- image: Property.File({
- displayName: 'Image',
- description: 'The image to save',
- required: true,
- }),
- alt: Property.ShortText({
- displayName: 'Alt Text',
- description: 'The alt text for the image',
- required: true,
- }),
- quality: Property.Number({
- displayName: 'Thumbnail Quality',
- description: 'The quality of the thumbnail',
- required: true,
- defaultValue: 85,
- }),
- scaleTh: Property.Number({
- displayName: 'Thumbnail Scale',
- description: 'The scale of the thumbnail',
- required: true,
- defaultValue: 400,
- }),
- scaleSq: Property.Number({
- displayName: 'Thumbnail Square Scale',
- description: 'The scale of the square thumbnail',
- required: true,
- defaultValue: 400,
- }),
- resize: Property.StaticDropdown({
- displayName: 'Thumbnail Resize Method',
- description: 'The method to use when resizing the thumbnail',
- required: true,
- defaultValue: 'auto',
- options: {
- options: [
- { label: 'Auto', value: 'auto' },
- { label: 'Landscape', value: 'landscape' },
- { label: 'Portrait', value: 'portrait' },
- ],
- },
- }),
- lcrop: Property.StaticDropdown({
- displayName: 'Thumbnail Landscape Crop',
- description:
- 'The method to use when cropping the landscape thumbnail for the square thumbnail',
- required: true,
- defaultValue: 'center',
- options: {
- options: [
- { label: 'Left', value: 'left' },
- { label: 'Center', value: 'center' },
- { label: 'Right', value: 'right' },
- ],
- },
- }),
- pcrop: Property.StaticDropdown({
- displayName: 'Thumbnail Landscape Crop',
- description:
- 'The method to use when cropping the landscape thumbnail for the square thumbnail',
- required: true,
- defaultValue: 'middle',
- options: {
- options: [
- { label: 'Top', value: 'top' },
- { label: 'Middle', value: 'middle' },
- { label: 'Bottom', value: 'bottom' },
- ],
- },
- }),
- altMeta: Property.Checkbox({
- displayName: 'Pull Alt Text from Meta Data',
- description:
- 'Pull the alt text from the meta data of the image. If set, place placeholder text in the alt text field above.',
- required: true,
- }),
+ collection: totalcmsProps.collection({ displayName: 'Blog', description: 'The blog collection.', schemas: ['blog'] }),
+ object_id: totalcmsProps.object({ displayName: 'Post', description: 'The blog post to update.' }),
+ ...totalcmsUpload.fileProps({ fileLabel: 'Image' }),
+ alt: totalcmsUpload.altProp(),
},
+ outputSchema: totalcmsOutputSchemas.blogPostUpload,
async run(context) {
- await propsValidation.validateZod(context.propsValue, {
- quality: z.number().check(z.minimum(1), z.maximum(100)),
- scaleTh: z.number().check(z.minimum(1)),
- scaleSq: z.number().check(z.minimum(1)),
- });
-
- const slug = context.propsValue.slug;
- const image = {
- filename: context.propsValue.image.filename,
- base64: context.propsValue.image.base64,
- };
- return await saveBlogImage(context.auth, slug, image, {
- permalink: context.propsValue.permalink,
- thumbs: 1,
- optimize: 1,
- alttype: context.propsValue.altMeta ? 'meta' : 'user',
- alt: context.propsValue.alt,
- quality: context.propsValue.quality,
- scale_th: context.propsValue.scaleTh,
- scale_sq: context.propsValue.scaleSq,
- resize: context.propsValue.resize,
- lcrop: context.propsValue.lcrop,
- pcrop: context.propsValue.pcrop,
- // Cannot add support for ext option with how this API is built.
- // it would break the saving of the blog post since it would try
- // to save the blog post JSON file with the extension of the ext option
+ const collection = totalcmsShape.requireId({ value: context.propsValue.collection, label: 'Collection' });
+ const id = totalcmsShape.requireId({ value: context.propsValue.object_id, label: 'Post' });
+ const result = await totalcmsUpload.save({
+ auth: context.auth,
+ collection,
+ id,
+ property: 'image',
+ file: context.propsValue.file,
+ fileUrl: context.propsValue.file_url,
+ alt: context.propsValue.alt ?? undefined,
+ multiple: false,
});
+ return { ...totalcmsShape.typed({ collection, object: result.object }), preview_url: result.preview_url, warning: result.warning };
},
});
diff --git a/packages/pieces/community/totalcms/src/lib/actions/save-blog-post.ts b/packages/pieces/community/totalcms/src/lib/actions/save-blog-post.ts
index c0b3bc8f533..f3b532eb3b7 100644
--- a/packages/pieces/community/totalcms/src/lib/actions/save-blog-post.ts
+++ b/packages/pieces/community/totalcms/src/lib/actions/save-blog-post.ts
@@ -1,135 +1,182 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { saveContent } from '../api';
import { cmsAuth } from '../auth';
+import { totalcmsApi } from '../common/client';
+import { totalcmsProps } from '../common/props';
+import { totalcmsShape } from '../common/shape';
+import { totalcmsOutputSchemas } from '../output-schemas';
export const saveBlogPostAction = createAction({
name: 'save_blog_post',
classification: 'WRITE',
auth: cmsAuth,
- displayName: 'Save Blog Post',
- description: 'Save blog content to Total CMS',
+ displayName: 'Create or Update Blog Post',
+ description: 'Creates a blog post, or updates the post with the given ID.',
audience: 'both',
- aiMetadata: { description: 'Creates or overwrites a blog post in a Total CMS blog, identified by the blog CMS ID (slug) plus a permalink, writing fields such as title, summary, content, author, categories, tags, and draft/featured/archived flags. Use to publish or edit a post. The permalink is the post key: reusing an existing permalink overwrites that post rather than creating a new one, so repeating the call with the same permalink and values is idempotent.', idempotent: true },
+ aiMetadata: {
+ description:
+ 'Creates a Total CMS blog post, or updates only the fields you pass on an existing post when Post ID matches one. Leave Post ID empty to create a post whose ID is made from the title. Creating twice with an empty Post ID fails on the duplicate ID; updates are safe to repeat.',
+ idempotent: false,
+ },
props: {
- slug: Property.ShortText({
- displayName: 'CMS ID',
- description: 'The CMS ID of the content to save',
- required: true,
- }),
- permalink: Property.ShortText({
- displayName: 'Permalink',
+ collection: totalcmsProps.collectionForSchema({ schema: 'blog', label: 'Blog' }),
+ post_id: totalcmsProps.objectIdText({
+ displayName: 'Post ID',
description:
- 'The permalink of the blog post. Ensure this is unique or it will overwrite the existing post.',
- required: true,
+ 'The post ID (URL slug), for example my-first-post. If a post with this ID exists it is updated, otherwise a new post is created. Leave empty to create a new post with an ID made from the title.',
+ required: false,
}),
title: Property.ShortText({
displayName: 'Title',
- description: 'The title of the blog post',
- required: false,
- }),
- timestamp: Property.Number({
- displayName: 'Date (Unix Timestamp)',
- description: 'The date in unix timestamp format',
- required: false,
- }),
- summary: Property.LongText({
- displayName: 'Summary',
- description: 'The summary of the blog post',
- required: false,
- }),
- content: Property.LongText({
- displayName: 'Content',
- description: 'The content of the blog post',
+ description: 'Required when creating a post.',
required: false,
}),
- extra: Property.LongText({
- displayName: 'Extra Content',
- description: 'The extra content of the blog post',
- required: false,
- }),
- extra2: Property.LongText({
- displayName: 'Extra Content 2',
- description: 'The extra content 2 of the blog post',
+ date: Property.DateTime({
+ displayName: 'Date',
+ description: 'The publication date. Defaults to now for new posts.',
required: false,
}),
+ author: Property.ShortText({ displayName: 'Author', required: false }),
+ summary: Property.LongText({ displayName: 'Summary', description: 'HTML is allowed.', required: false }),
+ content: Property.LongText({ displayName: 'Content', description: 'The post body. HTML is allowed.', required: false }),
+ extra: Property.LongText({ displayName: 'Extra Content', description: 'HTML is allowed.', required: false }),
media: Property.ShortText({
- displayName: 'Media',
- description: 'The media of the blog post',
- required: false,
- }),
- rssTitle: Property.ShortText({
- displayName: 'RSS Title',
- description: 'The RSS title of the blog post',
- required: false,
- }),
- rssDescription: Property.ShortText({
- displayName: 'RSS Description',
- description: 'The RSS description of the blog post',
- required: false,
- }),
- author: Property.ShortText({
- displayName: 'Author',
- description: 'The author of the blog post',
- required: false,
- }),
- genre: Property.ShortText({
- displayName: 'Genre',
- description: 'The genre of the blog post',
+ displayName: 'Media URL',
+ description: 'A link to related media, such as a video or podcast episode.',
required: false,
}),
categories: Property.ShortText({
displayName: 'Categories',
- description: 'A comma separated list of categories for the blog post',
+ description:
+ 'Replaces the post categories. Separate them with commas, or map a list. Use a JSON list such as ["News, Events"] when a name contains a comma. Leave empty to keep the current ones.',
required: false,
}),
tags: Property.ShortText({
displayName: 'Tags',
- description: 'A comma separated list of tags for the blog post',
- required: false,
- }),
- labels: Property.ShortText({
- displayName: 'Labels',
- description: 'A comma separated list of labels for the blog post',
+ description:
+ 'Replaces the post tags. Separate them with commas, or map a list. Use a JSON list such as ["News, Events"] when a name contains a comma. Leave empty to keep the current ones.',
required: false,
}),
- draft: Property.Checkbox({
- displayName: 'Draft',
- description: 'Set to true to save as a draft',
+ draft: Property.StaticDropdown({
+ displayName: 'Status',
+ description: 'Leave empty to keep the current status (new posts are published).',
required: false,
+ options: {
+ options: [
+ { label: 'Published', value: 'published' },
+ { label: 'Draft', value: 'draft' },
+ ],
+ },
}),
- featured: Property.Checkbox({
+ featured: Property.StaticDropdown({
displayName: 'Featured',
- description: 'Set to true to save as a featured post',
- required: false,
- }),
- archived: Property.Checkbox({
- displayName: 'Archived',
- description: 'Set to true to save as an archived post',
+ description: 'Leave empty to keep the current value.',
required: false,
+ options: {
+ options: [
+ { label: 'Yes', value: 'yes' },
+ { label: 'No', value: 'no' },
+ ],
+ },
}),
},
+ outputSchema: totalcmsOutputSchemas.savedBlogPost,
async run(context) {
- const slug = context.propsValue.slug;
- return await saveContent(context.auth, 'blog', slug, {
- nodecode: true,
- permalink: context.propsValue.permalink,
- title: context.propsValue.title,
- timestamp: context.propsValue.timestamp?.toString(),
- summary: context.propsValue.summary,
- content: context.propsValue.content,
- extra: context.propsValue.extra,
- extra2: context.propsValue.extra2,
- media: context.propsValue.media,
- rss_title: context.propsValue.rssTitle,
- rss_description: context.propsValue.rssDescription,
- author: context.propsValue.author,
- genre: context.propsValue.genre,
- categories: context.propsValue.categories,
- tags: context.propsValue.tags,
- labels: context.propsValue.labels,
- draft: context.propsValue.draft ? 'true' : 'false',
- featured: context.propsValue.featured ? 'true' : 'false',
- archived: context.propsValue.archived ? 'true' : 'false',
+ const { propsValue, auth } = context;
+ const collection = totalcmsShape.requireId({ value: propsValue.collection, label: 'Collection ID' });
+ const fields = buildFields({ propsValue });
+ const postId = typeof propsValue.post_id === 'string' ? propsValue.post_id.trim() : '';
+ const existing = postId ? await totalcmsApi.findObject({ auth, collection, id: postId }) : null;
+ if (existing) {
+ if (Object.keys(fields).length === 0) {
+ throw new Error('Nothing to update. Fill in at least one field to change.');
+ }
+ const object = await totalcmsApi.patchObject({ auth, collection, id: postId, fields });
+ return { result: 'updated', ...totalcmsShape.typed({ collection, object }) };
+ }
+ if (typeof fields['title'] !== 'string') {
+ throw new Error('Title is required to create a new blog post.');
+ }
+ const object = await totalcmsApi.createObject({
+ auth,
+ collection,
+ fields: postId ? { id: postId, draft: false, ...fields } : { draft: false, ...fields },
});
+ return { result: 'created', ...totalcmsShape.typed({ collection, object }) };
},
});
+
+const TEXT_KEYS: TextKey[] = ['title', 'author', 'summary', 'content', 'extra', 'media'];
+const LIST_KEYS: ListKey[] = ['categories', 'tags'];
+
+function buildFields({ propsValue }: { propsValue: BlogPostProps }): Record<string, unknown> {
+ const textEntries = TEXT_KEYS.flatMap((key) => {
+ const value = propsValue[key];
+ return typeof value === 'string' && value.trim().length > 0 ? [[key, value]] : [];
+ });
+ const listEntries = LIST_KEYS.flatMap((key) => {
+ const list = toStringList({ value: propsValue[key] });
+ return list.length > 0 ? [[key, list]] : [];
+ });
+ const fields: Record<string, unknown> = Object.fromEntries([...textEntries, ...listEntries]);
+ if (propsValue.date !== undefined && propsValue.date !== null && String(propsValue.date).length > 0) {
+ const date = new Date(String(propsValue.date));
+ if (Number.isNaN(date.getTime())) {
+ throw new Error('Date is not a valid date. Use a format such as 2026-12-31T18:00:00Z.');
+ }
+ fields['date'] = date.toISOString();
+ }
+ if (propsValue.media && !/^https?:\/\//i.test(propsValue.media.trim())) {
+ throw new Error('Media URL must start with http:// or https://.');
+ }
+ if (propsValue.draft === 'draft' || propsValue.draft === 'published') {
+ fields['draft'] = propsValue.draft === 'draft';
+ }
+ if (propsValue.featured === 'yes' || propsValue.featured === 'no') {
+ fields['featured'] = propsValue.featured === 'yes';
+ }
+ return fields;
+}
+
+function toStringList({ value }: { value: unknown }): string[] {
+ const list = typeof value === 'string' ? listFromString({ text: value }) : value;
+ if (!Array.isArray(list)) {
+ return [];
+ }
+ return list
+ .flatMap((item) => (typeof item === 'string' ? [item] : typeof item === 'number' ? [String(item)] : []))
+ .map((item) => item.trim())
+ .filter((item) => item.length > 0);
+}
+
+function listFromString({ text }: { text: string }): unknown[] {
+ const trimmed = text.trim();
+ const parsed = trimmed.startsWith('[') ? parseJsonArray({ text: trimmed }) : null;
+ return parsed ?? trimmed.split(',');
+}
+
+function parseJsonArray({ text }: { text: string }): unknown[] | null {
+ try {
+ const parsed: unknown = JSON.parse(text);
+ return Array.isArray(parsed) ? parsed : null;
+ } catch {
+ return null;
+ }
+}
+
+type BlogPostProps = {
+ title?: string;
+ author?: string;
+ summary?: string;
+ content?: string;
+ extra?: string;
+ media?: string;
+ categories?: string;
+ tags?: string;
+ date?: string;
+ draft?: string;
+ featured?: string;
+};
+
+type TextKey = 'title' | 'author' | 'summary' | 'content' | 'extra' | 'media';
+
+type ListKey = 'categories' | 'tags';
diff --git a/packages/pieces/community/totalcms/src/lib/actions/save-date.ts b/packages/pieces/community/totalcms/src/lib/actions/save-date.ts
index 2e7cb0f67c4..a32eb19f03a 100644
--- a/packages/pieces/community/totalcms/src/lib/actions/save-date.ts
+++ b/packages/pieces/community/totalcms/src/lib/actions/save-date.ts
@@ -1,33 +1,47 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { saveContent } from '../api';
import { cmsAuth } from '../auth';
+import { totalcmsApi } from '../common/client';
+import { totalcmsProps } from '../common/props';
+import { totalcmsShape } from '../common/shape';
+import { totalcmsOutputSchemas } from '../output-schemas';
export const saveDateAction = createAction({
name: 'save_date',
classification: 'WRITE',
auth: cmsAuth,
- displayName: 'Save Date Content',
- description: 'Save date content to Total CMS',
+ displayName: 'Save Date',
+ description: 'Creates or replaces a date object.',
audience: 'both',
- aiMetadata: { description: 'Sets a date-type CMS field in Total CMS, identified by its CMS ID (slug), to a given Unix timestamp. Use to write or update a stored date value. Idempotent: the value is keyed on the slug, so repeating with the same timestamp leaves the same result.', idempotent: true },
+ aiMetadata: {
+ description:
+ 'Sets the date and time stored in a Total CMS date object, creating the object if the ID is new. Use for countdowns or event dates shown on the site. Takes an ISO 8601 date; repeating the call is safe.',
+ idempotent: true,
+ },
props: {
- slug: Property.ShortText({
- displayName: 'CMS ID',
- description: 'The CMS ID of the content to save',
- required: true,
+ collection: totalcmsProps.collectionForSchema({ schema: 'date', label: 'Date' }),
+ object_id: totalcmsProps.objectIdText({
+ description: 'The ID of the date object. A new ID creates the object.',
}),
- timestamp: Property.Number({
- displayName: 'Unix Timestamp',
- description: 'The unix timestamp to save',
+ date: Property.DateTime({
+ displayName: 'Date',
+ description: 'The date and time to store, for example 2026-12-31T18:00:00Z.',
required: true,
}),
},
+ outputSchema: totalcmsOutputSchemas.date,
async run(context) {
- const slug = context.propsValue.slug;
- const timestamp = context.propsValue.timestamp;
- return await saveContent(context.auth, 'date', slug, {
- nodecode: true,
- timestamp: timestamp.toString(),
+ const collection = totalcmsShape.requireId({ value: context.propsValue.collection, label: 'Collection ID' });
+ const id = totalcmsShape.requireId({ value: context.propsValue.object_id, label: 'Object ID' });
+ const date = new Date(String(context.propsValue.date));
+ if (Number.isNaN(date.getTime())) {
+ throw new Error('Date is not a valid date. Use a format such as 2026-12-31T18:00:00Z.');
+ }
+ const object = await totalcmsApi.replaceObject({
+ auth: context.auth,
+ collection,
+ id,
+ fields: { date: date.toISOString() },
});
+ return totalcmsShape.typed({ collection, object });
},
});
diff --git a/packages/pieces/community/totalcms/src/lib/actions/save-depot.ts b/packages/pieces/community/totalcms/src/lib/actions/save-depot.ts
index df1b9ebe7b6..71743645904 100644
--- a/packages/pieces/community/totalcms/src/lib/actions/save-depot.ts
+++ b/packages/pieces/community/totalcms/src/lib/actions/save-depot.ts
@@ -1,33 +1,46 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { saveDepot } from '../api';
import { cmsAuth } from '../auth';
+import { totalcmsProps } from '../common/props';
+import { totalcmsShape } from '../common/shape';
+import { totalcmsUpload } from '../common/upload';
+import { totalcmsOutputSchemas } from '../output-schemas';
export const saveDepotAction = createAction({
name: 'save_depot',
classification: 'WRITE',
auth: cmsAuth,
- displayName: 'Save Depot',
- description: 'Save file to Total CMS depot',
+ displayName: 'Add File to Depot',
+ description: 'Adds a file to a depot (file library) object.',
audience: 'both',
- aiMetadata: { description: 'Uploads a file into a Total CMS depot (a multi-file collection), identified by the depot CMS ID (slug). Use to add a document or asset to a depot. Not idempotent: each call appends another file to the depot.', idempotent: false },
+ aiMetadata: {
+ description:
+ 'Adds one file (file or public URL) to a Total CMS depot object, optionally inside a folder, creating the object if the ID is new. Each call adds another file, so retries add duplicates.',
+ idempotent: false,
+ },
props: {
- slug: Property.ShortText({
- displayName: 'CMS ID',
- description: 'The CMS ID of the depot to save',
- required: true,
- }),
- file: Property.File({
- displayName: 'File',
- description: 'The file to save',
- required: true,
+ collection: totalcmsProps.collectionForSchema({ schema: 'depot', label: 'Depot' }),
+ object_id: totalcmsProps.objectIdText({ description: 'The ID of the depot object. A new ID creates the object.' }),
+ ...totalcmsUpload.fileProps({ fileLabel: 'File' }),
+ folder: Property.ShortText({
+ displayName: 'Folder',
+ description: 'Optional folder path inside the depot, such as 2026/reports.',
+ required: false,
}),
},
+ outputSchema: totalcmsOutputSchemas.depot,
async run(context) {
- const slug = context.propsValue.slug;
- const file = {
- filename: context.propsValue.file.filename,
- base64: context.propsValue.file.base64,
- };
- return await saveDepot(context.auth, slug, file);
+ const collection = totalcmsShape.requireId({ value: context.propsValue.collection, label: 'Collection ID' });
+ const id = totalcmsShape.requireId({ value: context.propsValue.object_id, label: 'Object ID' });
+ const result = await totalcmsUpload.save({
+ auth: context.auth,
+ collection,
+ id,
+ property: 'depot',
+ file: context.propsValue.file,
+ fileUrl: context.propsValue.file_url,
+ folder: context.propsValue.folder ?? undefined,
+ multiple: false,
+ });
+ return totalcmsShape.typed({ collection, object: result.object });
},
});
diff --git a/packages/pieces/community/totalcms/src/lib/actions/save-file.ts b/packages/pieces/community/totalcms/src/lib/actions/save-file.ts
index e093e9c71a5..b430a1925c0 100644
--- a/packages/pieces/community/totalcms/src/lib/actions/save-file.ts
+++ b/packages/pieces/community/totalcms/src/lib/actions/save-file.ts
@@ -1,40 +1,40 @@
-import { createAction, Property } from '@activepieces/pieces-framework';
-import { saveFile } from '../api';
+import { createAction } from '@activepieces/pieces-framework';
import { cmsAuth } from '../auth';
+import { totalcmsProps } from '../common/props';
+import { totalcmsShape } from '../common/shape';
+import { totalcmsUpload } from '../common/upload';
+import { totalcmsOutputSchemas } from '../output-schemas';
export const saveFileAction = createAction({
name: 'save_file',
classification: 'WRITE',
auth: cmsAuth,
displayName: 'Save File',
- description: 'Save file to Total CMS',
+ description: 'Uploads a file to a file object, replacing the current file.',
audience: 'both',
- aiMetadata: { description: 'Uploads a single file to a file-type CMS field in Total CMS, identified by its CMS ID (slug), with an explicit file extension. Use to set or replace the file stored at a given CMS ID. Idempotent: the field holds one file keyed on the slug, so repeating with the same input replaces it.', idempotent: true },
+ aiMetadata: {
+ description:
+ 'Uploads a file (file or public URL) to a Total CMS file object, replacing its current file and creating the object if the ID is new. Use for downloadable documents. Running it again with the same file leaves the same result.',
+ idempotent: true,
+ },
props: {
- slug: Property.ShortText({
- displayName: 'CMS ID',
- description: 'The CMS ID of the file to save',
- required: true,
- }),
- ext: Property.ShortText({
- displayName: 'File Extension',
- description: 'The file extension of the file',
- required: true,
- }),
- file: Property.File({
- displayName: 'File',
- description: 'The file to save',
- required: true,
- }),
+ collection: totalcmsProps.collectionForSchema({ schema: 'file', label: 'File' }),
+ object_id: totalcmsProps.objectIdText({ description: 'The ID of the file object. A new ID creates the object.' }),
+ ...totalcmsUpload.fileProps({ fileLabel: 'File' }),
},
+ outputSchema: totalcmsOutputSchemas.file,
async run(context) {
- const slug = context.propsValue.slug;
- const file = {
- filename: context.propsValue.file.filename,
- base64: context.propsValue.file.base64,
- };
- return await saveFile(context.auth, slug, file, {
- ext: context.propsValue.ext,
+ const collection = totalcmsShape.requireId({ value: context.propsValue.collection, label: 'Collection ID' });
+ const id = totalcmsShape.requireId({ value: context.propsValue.object_id, label: 'Object ID' });
+ const result = await totalcmsUpload.save({
+ auth: context.auth,
+ collection,
+ id,
+ property: 'file',
+ file: context.propsValue.file,
+ fileUrl: context.propsValue.file_url,
+ multiple: false,
});
+ return totalcmsShape.typed({ collection, object: result.object });
},
});
diff --git a/packages/pieces/community/totalcms/src/lib/actions/save-gallery.ts b/packages/pieces/community/totalcms/src/lib/actions/save-gallery.ts
index 23753b50c02..7d4c5d8cb08 100644
--- a/packages/pieces/community/totalcms/src/lib/actions/save-gallery.ts
+++ b/packages/pieces/community/totalcms/src/lib/actions/save-gallery.ts
@@ -1,125 +1,42 @@
-import {
- createAction,
- Property,
-} from '@activepieces/pieces-framework';
-import { saveGallery } from '../api';
+import { createAction } from '@activepieces/pieces-framework';
import { cmsAuth } from '../auth';
-import * as z from 'zod/mini'
-import { propsValidation } from '@activepieces/pieces-common';
+import { totalcmsProps } from '../common/props';
+import { totalcmsShape } from '../common/shape';
+import { totalcmsUpload } from '../common/upload';
+import { totalcmsOutputSchemas } from '../output-schemas';
export const saveGalleryAction = createAction({
name: 'save_gallery',
classification: 'WRITE',
auth: cmsAuth,
- displayName: 'Save Gallery Image',
- description: 'Save image to Total CMS gallery',
+ displayName: 'Add Image to Gallery',
+ description: 'Adds an image to a gallery object.',
audience: 'both',
- aiMetadata: { description: 'Uploads an image into a gallery-type CMS field in Total CMS, identified by the gallery CMS ID (slug), with alt text and thumbnail sizing/crop options. Use to add a photo to a standalone gallery. Not idempotent: each call appends another image to the gallery.', idempotent: false },
+ aiMetadata: {
+ description:
+ 'Adds one image (file or public URL) to the end of a Total CMS gallery object, creating the object if the ID is new. Optional alt text is saved on the new image. Each call adds another image, so retries add duplicates.',
+ idempotent: false,
+ },
props: {
- slug: Property.ShortText({
- displayName: 'CMS ID',
- description: 'The CMS ID of the gallery to save',
- required: true,
- }),
- image: Property.File({
- displayName: 'Image',
- description: 'The image to save',
- required: true,
- }),
- alt: Property.ShortText({
- displayName: 'Alt Text',
- description: 'The alt text for the image',
- required: true,
- }),
- quality: Property.Number({
- displayName: 'Thumbnail Quality',
- description: 'The quality of the thumbnail',
- required: true,
- defaultValue: 85,
- }),
- scaleTh: Property.Number({
- displayName: 'Thumbnail Scale',
- description: 'The scale of the thumbnail',
- required: true,
- defaultValue: 400,
- }),
- scaleSq: Property.Number({
- displayName: 'Thumbnail Square Scale',
- description: 'The scale of the square thumbnail',
- required: true,
- defaultValue: 400,
- }),
- resize: Property.StaticDropdown({
- displayName: 'Thumbnail Resize Method',
- description: 'The method to use when resizing the thumbnail',
- required: true,
- defaultValue: 'auto',
- options: {
- options: [
- { label: 'Auto', value: 'auto' },
- { label: 'Landscape', value: 'landscape' },
- { label: 'Portrait', value: 'portrait' },
- ],
- },
- }),
- lcrop: Property.StaticDropdown({
- displayName: 'Thumbnail Landscape Crop',
- description:
- 'The method to use when cropping the landscape thumbnail for the square thumbnail',
- required: true,
- defaultValue: 'center',
- options: {
- options: [
- { label: 'Left', value: 'left' },
- { label: 'Center', value: 'center' },
- { label: 'Right', value: 'right' },
- ],
- },
- }),
- pcrop: Property.StaticDropdown({
- displayName: 'Thumbnail Landscape Crop',
- description:
- 'The method to use when cropping the landscape thumbnail for the square thumbnail',
- required: true,
- defaultValue: 'middle',
- options: {
- options: [
- { label: 'Top', value: 'top' },
- { label: 'Middle', value: 'middle' },
- { label: 'Bottom', value: 'bottom' },
- ],
- },
- }),
- altMeta: Property.Checkbox({
- displayName: 'Pull Alt Text from Meta Data',
- description:
- 'Pull the alt text from the meta data of the image. If set, place placeholder text in the alt text field above.',
- required: true,
- }),
+ collection: totalcmsProps.collectionForSchema({ schema: 'gallery', label: 'Gallery' }),
+ object_id: totalcmsProps.objectIdText({ description: 'The ID of the gallery object. A new ID creates the object.' }),
+ ...totalcmsUpload.fileProps({ fileLabel: 'Image' }),
+ alt: totalcmsUpload.altProp(),
},
+ outputSchema: totalcmsOutputSchemas.gallery,
async run(context) {
- await propsValidation.validateZod(context.propsValue, {
- quality: z.number().check(z.minimum(1), z.maximum(100)),
- scaleTh: z.number().check(z.minimum(1)),
- scaleSq: z.number().check(z.minimum(1)),
- });
-
- const slug = context.propsValue.slug;
- const image = {
- filename: context.propsValue.image.filename,
- base64: context.propsValue.image.base64,
- };
- return await saveGallery(context.auth, slug, image, {
- thumbs: 1,
- optimize: 1,
- alttype: context.propsValue.altMeta ? 'meta' : 'user',
- alt: context.propsValue.alt,
- quality: context.propsValue.quality,
- scale_th: context.propsValue.scaleTh,
- scale_sq: context.propsValue.scaleSq,
- resize: context.propsValue.resize,
- lcrop: context.propsValue.lcrop,
- pcrop: context.propsValue.pcrop,
+ const collection = totalcmsShape.requireId({ value: context.propsValue.collection, label: 'Collection ID' });
+ const id = totalcmsShape.requireId({ value: context.propsValue.object_id, label: 'Object ID' });
+ const result = await totalcmsUpload.save({
+ auth: context.auth,
+ collection,
+ id,
+ property: 'gallery',
+ file: context.propsValue.file,
+ fileUrl: context.propsValue.file_url,
+ alt: context.propsValue.alt ?? undefined,
+ multiple: true,
});
+ return { ...totalcmsShape.typed({ collection, object: result.object }), preview_url: result.preview_url, warning: result.warning };
},
});
diff --git a/packages/pieces/community/totalcms/src/lib/actions/save-image.ts b/packages/pieces/community/totalcms/src/lib/actions/save-image.ts
index 3ea6c9d25ac..d02bfa50918 100644
--- a/packages/pieces/community/totalcms/src/lib/actions/save-image.ts
+++ b/packages/pieces/community/totalcms/src/lib/actions/save-image.ts
@@ -1,137 +1,42 @@
-import {
- createAction,
- Property,
-} from '@activepieces/pieces-framework';
-import { saveImage } from '../api';
+import { createAction } from '@activepieces/pieces-framework';
import { cmsAuth } from '../auth';
-import * as z from 'zod/mini'
-import { propsValidation } from '@activepieces/pieces-common';
+import { totalcmsProps } from '../common/props';
+import { totalcmsShape } from '../common/shape';
+import { totalcmsUpload } from '../common/upload';
+import { totalcmsOutputSchemas } from '../output-schemas';
export const saveImageAction = createAction({
name: 'save_image',
classification: 'WRITE',
auth: cmsAuth,
displayName: 'Save Image',
- description: 'Save image to Total CMS',
+ description: 'Uploads an image to an image object, replacing the current image.',
audience: 'both',
- aiMetadata: { description: 'Sets a single image-type CMS field in Total CMS, identified by its CMS ID (slug), with alt text, output extension (jpg/png), and thumbnail sizing/crop options. Use to set or replace the image stored at a given CMS ID. Idempotent: the field holds one image keyed on the slug, so repeating with the same input replaces it.', idempotent: true },
+ aiMetadata: {
+ description:
+ 'Uploads an image (file or public URL) to a Total CMS image object, replacing its current image and creating the object if the ID is new. Optional alt text is saved with it. Running it again with the same image leaves the same result.',
+ idempotent: true,
+ },
props: {
- slug: Property.ShortText({
- displayName: 'CMS ID',
- description: 'The CMS ID of the content to save',
- required: true,
- }),
- image: Property.File({
- displayName: 'Image',
- description: 'The image to save',
- required: true,
- }),
- alt: Property.ShortText({
- displayName: 'Alt Text',
- description: 'The alt text for the image',
- required: true,
- }),
- ext: Property.StaticDropdown({
- displayName: 'Extension',
- description: 'The extension of the image',
- required: true,
- defaultValue: 'jpg',
- options: {
- options: [
- { label: 'jpg', value: 'jpg' },
- { label: 'png', value: 'png' },
- ],
- },
- }),
- quality: Property.Number({
- displayName: 'Thumbnail Quality',
- description: 'The quality of the thumbnail',
- required: true,
- defaultValue: 85,
- }),
- scaleTh: Property.Number({
- displayName: 'Thumbnail Scale',
- description: 'The scale of the thumbnail',
- required: true,
- defaultValue: 400,
- }),
- scaleSq: Property.Number({
- displayName: 'Thumbnail Square Scale',
- description: 'The scale of the square thumbnail',
- required: true,
- defaultValue: 400,
- }),
- resize: Property.StaticDropdown({
- displayName: 'Thumbnail Resize Method',
- description: 'The method to use when resizing the thumbnail',
- required: true,
- defaultValue: 'auto',
- options: {
- options: [
- { label: 'Auto', value: 'auto' },
- { label: 'Landscape', value: 'landscape' },
- { label: 'Portrait', value: 'portrait' },
- ],
- },
- }),
- lcrop: Property.StaticDropdown({
- displayName: 'Thumbnail Landscape Crop',
- description:
- 'The method to use when cropping the landscape thumbnail for the square thumbnail',
- required: true,
- defaultValue: 'center',
- options: {
- options: [
- { label: 'Left', value: 'left' },
- { label: 'Center', value: 'center' },
- { label: 'Right', value: 'right' },
- ],
- },
- }),
- pcrop: Property.StaticDropdown({
- displayName: 'Thumbnail Landscape Crop',
- description:
- 'The method to use when cropping the landscape thumbnail for the square thumbnail',
- required: true,
- defaultValue: 'middle',
- options: {
- options: [
- { label: 'Top', value: 'top' },
- { label: 'Middle', value: 'middle' },
- { label: 'Bottom', value: 'bottom' },
- ],
- },
- }),
- altMeta: Property.Checkbox({
- displayName: 'Pull Alt Text from Meta Data',
- description:
- 'Pull the alt text from the meta data of the image. If set, place placeholder text in the alt text field above.',
- required: true,
- }),
+ collection: totalcmsProps.collectionForSchema({ schema: 'image', label: 'Image' }),
+ object_id: totalcmsProps.objectIdText({ description: 'The ID of the image object. A new ID creates the object.' }),
+ ...totalcmsUpload.fileProps({ fileLabel: 'Image' }),
+ alt: totalcmsUpload.altProp(),
},
+ outputSchema: totalcmsOutputSchemas.image,
async run(context) {
- await propsValidation.validateZod(context.propsValue, {
- quality: z.number().check(z.minimum(1), z.maximum(100)),
- scaleTh: z.number().check(z.minimum(1)),
- scaleSq: z.number().check(z.minimum(1)),
- });
- const slug = context.propsValue.slug;
- const image = {
- filename: context.propsValue.image.filename,
- base64: context.propsValue.image.base64,
- };
- return await saveImage(context.auth, slug, image, {
- thumbs: 1,
- optimize: 1,
- alttype: context.propsValue.altMeta ? 'meta' : 'user',
- alt: context.propsValue.alt,
- ext: context.propsValue.ext,
- quality: context.propsValue.quality,
- scale_th: context.propsValue.scaleTh,
- scale_sq: context.propsValue.scaleSq,
- resize: context.propsValue.resize,
- lcrop: context.propsValue.lcrop,
- pcrop: context.propsValue.pcrop,
+ const collection = totalcmsShape.requireId({ value: context.propsValue.collection, label: 'Collection ID' });
+ const id = totalcmsShape.requireId({ value: context.propsValue.object_id, label: 'Object ID' });
+ const result = await totalcmsUpload.save({
+ auth: context.auth,
+ collection,
+ id,
+ property: 'image',
+ file: context.propsValue.file,
+ fileUrl: context.propsValue.file_url,
+ alt: context.propsValue.alt ?? undefined,
+ multiple: false,
});
+ return { ...totalcmsShape.typed({ collection, object: result.object }), preview_url: result.preview_url, warning: result.warning };
},
});
diff --git a/packages/pieces/community/totalcms/src/lib/actions/save-text.ts b/packages/pieces/community/totalcms/src/lib/actions/save-text.ts
index b7f5e7d42ca..f61a8744b73 100644
--- a/packages/pieces/community/totalcms/src/lib/actions/save-text.ts
+++ b/packages/pieces/community/totalcms/src/lib/actions/save-text.ts
@@ -1,33 +1,42 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { saveContent } from '../api';
import { cmsAuth } from '../auth';
+import { totalcmsApi } from '../common/client';
+import { totalcmsProps } from '../common/props';
+import { totalcmsShape } from '../common/shape';
+import { totalcmsOutputSchemas } from '../output-schemas';
export const saveTextAction = createAction({
name: 'save_text',
classification: 'WRITE',
auth: cmsAuth,
- displayName: 'Save Text Content',
- description: 'Save text content to Total CMS',
+ displayName: 'Save Text',
+ description: 'Creates or replaces a text object.',
audience: 'both',
- aiMetadata: { description: 'Sets a text-type CMS field in Total CMS, identified by its CMS ID (slug), to the supplied text content. Use to write or update a stored text/HTML value. Idempotent: the value is keyed on the slug, so repeating with the same text leaves the same result.', idempotent: true },
+ aiMetadata: {
+ description:
+ 'Sets the text of a Total CMS text object, creating the object if the ID is new and replacing its text otherwise. Use for site snippets such as headlines. Repeating the call with the same values leaves the same result, so it is safe to retry.',
+ idempotent: true,
+ },
props: {
- slug: Property.ShortText({
- displayName: 'CMS ID',
- description: 'The CMS ID of the content to save',
- required: true,
+ collection: totalcmsProps.collectionForSchema({ schema: 'text', label: 'Text' }),
+ object_id: totalcmsProps.objectIdText({
+ description: 'The ID of the text object, for example headline. A new ID creates the object.',
}),
text: Property.LongText({
- displayName: 'Text Content',
- description: 'The text content to save',
+ displayName: 'Text',
required: true,
}),
},
+ outputSchema: totalcmsOutputSchemas.text,
async run(context) {
- const slug = context.propsValue.slug;
- const text = context.propsValue.text;
- return await saveContent(context.auth, 'text', slug, {
- nodecode: true,
- text: text,
+ const collection = totalcmsShape.requireId({ value: context.propsValue.collection, label: 'Collection ID' });
+ const id = totalcmsShape.requireId({ value: context.propsValue.object_id, label: 'Object ID' });
+ const object = await totalcmsApi.replaceObject({
+ auth: context.auth,
+ collection,
+ id,
+ fields: { text: context.propsValue.text },
});
+ return totalcmsShape.typed({ collection, object });
},
});
diff --git a/packages/pieces/community/totalcms/src/lib/actions/save-toggle.ts b/packages/pieces/community/totalcms/src/lib/actions/save-toggle.ts
index 34b5ee32f0d..0953d471f3d 100644
--- a/packages/pieces/community/totalcms/src/lib/actions/save-toggle.ts
+++ b/packages/pieces/community/totalcms/src/lib/actions/save-toggle.ts
@@ -1,33 +1,44 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { saveContent } from '../api';
import { cmsAuth } from '../auth';
+import { totalcmsApi } from '../common/client';
+import { totalcmsProps } from '../common/props';
+import { totalcmsShape } from '../common/shape';
+import { totalcmsOutputSchemas } from '../output-schemas';
export const saveToggleAction = createAction({
name: 'save_toggle',
classification: 'WRITE',
auth: cmsAuth,
displayName: 'Save Toggle',
- description: 'Save toggle content to Total CMS',
+ description: 'Turns a toggle object on or off.',
audience: 'both',
- aiMetadata: { description: 'Sets a toggle-type (boolean on/off) CMS field in Total CMS, identified by its CMS ID (slug), to the supplied true/false state. Use to flip a stored toggle. Idempotent: the state is keyed on the slug, so repeating with the same value leaves the same result.', idempotent: true },
+ aiMetadata: {
+ description:
+ 'Sets a Total CMS toggle object on or off, creating the object if the ID is new. Use to switch site features such as a banner. Setting the same state again changes nothing, so it is safe to retry.',
+ idempotent: true,
+ },
props: {
- slug: Property.ShortText({
- displayName: 'CMS ID',
- description: 'The CMS ID of the content to save',
- required: true,
+ collection: totalcmsProps.collectionForSchema({ schema: 'toggle', label: 'Toggle' }),
+ object_id: totalcmsProps.objectIdText({
+ description: 'The ID of the toggle object. A new ID creates the object.',
}),
status: Property.Checkbox({
- displayName: 'Status',
- description: 'The status of the toggle. "true" is on, "false" is off.',
+ displayName: 'On',
+ description: 'Checked turns the toggle on, unchecked turns it off.',
required: true,
+ defaultValue: true,
}),
},
+ outputSchema: totalcmsOutputSchemas.toggle,
async run(context) {
- const slug = context.propsValue.slug;
- const status = context.propsValue.status ? 'true' : 'false';
- return await saveContent(context.auth, 'toggle', slug, {
- nodecode: true,
- state: status,
+ const collection = totalcmsShape.requireId({ value: context.propsValue.collection, label: 'Collection ID' });
+ const id = totalcmsShape.requireId({ value: context.propsValue.object_id, label: 'Object ID' });
+ const object = await totalcmsApi.replaceObject({
+ auth: context.auth,
+ collection,
+ id,
+ fields: { status: context.propsValue.status === true },
});
+ return totalcmsShape.typed({ collection, object });
},
});
diff --git a/packages/pieces/community/totalcms/src/lib/actions/save-video.ts b/packages/pieces/community/totalcms/src/lib/actions/save-video.ts
index 8e552b31f7a..7ad07831398 100644
--- a/packages/pieces/community/totalcms/src/lib/actions/save-video.ts
+++ b/packages/pieces/community/totalcms/src/lib/actions/save-video.ts
@@ -1,42 +1,47 @@
-import {
- createAction,
- Property,
-} from '@activepieces/pieces-framework';
-import { saveContent } from '../api';
+import { createAction, Property } from '@activepieces/pieces-framework';
import { cmsAuth } from '../auth';
-import * as z from 'zod/mini'
-import { propsValidation } from '@activepieces/pieces-common';
+import { totalcmsApi } from '../common/client';
+import { totalcmsProps } from '../common/props';
+import { totalcmsShape } from '../common/shape';
+import { totalcmsOutputSchemas } from '../output-schemas';
export const saveVideoAction = createAction({
name: 'save_video',
classification: 'WRITE',
auth: cmsAuth,
- displayName: 'Save Video Content',
- description: 'Save video content to Total CMS',
+ displayName: 'Save Video',
+ description: 'Creates or replaces a video object from a video link.',
audience: 'both',
- aiMetadata: { description: 'Sets a video-type CMS field in Total CMS, identified by its CMS ID (slug), to a given video URL (must be a valid URL). Use to write or update the stored video reference. Idempotent: the value is keyed on the slug, so repeating with the same URL leaves the same result.', idempotent: true },
+ aiMetadata: {
+ description:
+ 'Sets the video link (YouTube, Vimeo, Loom, Wistia, a direct MP4 and others) of a Total CMS video object, creating the object if the ID is new. Total CMS detects the provider and thumbnail. Repeating the call with the same link is safe.',
+ idempotent: true,
+ },
props: {
- slug: Property.ShortText({
- displayName: 'CMS ID',
- description: 'The CMS ID of the content to save',
- required: true,
+ collection: totalcmsProps.collectionForSchema({ schema: 'video', label: 'Video' }),
+ object_id: totalcmsProps.objectIdText({
+ description: 'The ID of the video object. A new ID creates the object.',
}),
video: Property.ShortText({
displayName: 'Video URL',
- description: 'The URL of the video to save',
+ description: 'The video page link from YouTube, Vimeo, Loom or similar.',
required: true,
}),
},
+ outputSchema: totalcmsOutputSchemas.video,
async run(context) {
- await propsValidation.validateZod(context.propsValue, {
- video: z.string().check(z.url()),
- });
-
- const slug = context.propsValue.slug;
- const video = context.propsValue.video;
- return await saveContent(context.auth, 'video', slug, {
- nodecode: true,
- video: video,
+ const collection = totalcmsShape.requireId({ value: context.propsValue.collection, label: 'Collection ID' });
+ const id = totalcmsShape.requireId({ value: context.propsValue.object_id, label: 'Object ID' });
+ const url = totalcmsShape.requireId({ value: context.propsValue.video, label: 'Video URL' });
+ if (!/^https?:\/\//i.test(url)) {
+ throw new Error('Video URL must start with http:// or https://.');
+ }
+ const object = await totalcmsApi.replaceObject({
+ auth: context.auth,
+ collection,
+ id,
+ fields: { video: url },
});
+ return totalcmsShape.typed({ collection, object });
},
});
diff --git a/packages/pieces/community/totalcms/src/lib/actions/update-object.ts b/packages/pieces/community/totalcms/src/lib/actions/update-object.ts
new file mode 100644
index 00000000000..de7c05b319c
--- /dev/null
+++ b/packages/pieces/community/totalcms/src/lib/actions/update-object.ts
@@ -0,0 +1,33 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { cmsAuth } from '../auth';
+import { totalcmsOperations } from '../common/operations';
+import { totalcmsProps } from '../common/props';
+import { totalcmsOutputSchemas } from '../output-schemas';
+
+export const updateObjectAction = createAction({
+ name: 'update_object',
+ classification: 'WRITE',
+ auth: cmsAuth,
+ displayName: 'Update Object',
+ description: 'Changes some fields of an object and keeps the others.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Updates only the given fields of an existing Total CMS object and keeps all other fields as stored. Use Create Object for new objects and Duplicate Object to copy one under a new ID. Sending the same values again changes nothing, so it is safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ collection: totalcmsProps.collection(),
+ object_id: totalcmsProps.object(),
+ fields: totalcmsOperations.updateFieldsProp(),
+ },
+ outputSchema: totalcmsOutputSchemas.object,
+ async run(context) {
+ return totalcmsOperations.updateObject({
+ auth: context.auth,
+ collection: context.propsValue.collection,
+ objectId: context.propsValue.object_id,
+ fields: context.propsValue.fields,
+ });
+ },
+});
diff --git a/packages/pieces/community/totalcms/src/lib/actions/upload-file.ts b/packages/pieces/community/totalcms/src/lib/actions/upload-file.ts
new file mode 100644
index 00000000000..fe795e8e894
--- /dev/null
+++ b/packages/pieces/community/totalcms/src/lib/actions/upload-file.ts
@@ -0,0 +1,33 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { cmsAuth } from '../auth';
+import { totalcmsOperations } from '../common/operations';
+import { totalcmsProps } from '../common/props';
+import { totalcmsOutputSchemas } from '../output-schemas';
+
+export const uploadFileAction = createAction({
+ name: 'upload_file',
+ classification: 'WRITE',
+ auth: cmsAuth,
+ displayName: 'Upload File to Field',
+ description: 'Uploads a file or image to an image, gallery, file or depot field of an object.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Uploads a file (file or public URL) into an image, gallery, file or depot field of an existing Total CMS object. Image and file fields are replaced; gallery and depot fields get one more entry per call, so retries can add duplicates.',
+ idempotent: false,
+ },
+ props: {
+ collection: totalcmsProps.collection(),
+ object_id: totalcmsProps.object(),
+ field: totalcmsProps.schemaField({
+ displayName: 'Field',
+ description: 'The image, gallery, file or depot field to upload to.',
+ fieldTypes: ['image', 'gallery', 'file', 'depot'],
+ }),
+ ...totalcmsOperations.uploadExtraProps(),
+ },
+ outputSchema: totalcmsOutputSchemas.upload,
+ async run(context) {
+ return totalcmsOperations.uploadFile({ auth: context.auth, input: context.propsValue });
+ },
+});
diff --git a/packages/pieces/community/totalcms/src/lib/api.ts b/packages/pieces/community/totalcms/src/lib/api.ts
deleted file mode 100644
index 33b8ee01875..00000000000
--- a/packages/pieces/community/totalcms/src/lib/api.ts
+++ /dev/null
@@ -1,173 +0,0 @@
-import {
- httpClient,
- HttpMethod,
- HttpRequest,
- QueryParams,
-} from '@activepieces/pieces-common';
-import { TotalCMSAuthType } from './auth';
-import FormData from 'form-data';
-
-export type KeyValuePair = {
- [key: string]: string | boolean | number | object | undefined;
-};
-export type FileUpload = { filename: string; base64: string };
-
-const totalcmsAPI = async (
- auth: TotalCMSAuthType,
- type: string,
- slug: string,
- query: QueryParams = {},
- data: KeyValuePair = {},
- method: HttpMethod = HttpMethod.GET
-) => {
- if (method === HttpMethod.GET) {
- query['slug'] = slug;
- query['type'] = type;
- } else {
- data['slug'] = slug;
- data['type'] = type;
- }
-
- const request: HttpRequest = {
- body: data,
- queryParams: query,
- method: method,
- url: `${auth.props.domain}/rw_common/plugins/stacks/total-cms/totalapi.php`,
- headers: {
- 'Content-Type': 'application/x-www-form-urlencoded',
- 'total-key': auth.props.license,
- },
- };
- const response = await httpClient.sendRequest(request);
-
- if (response.status !== 200) {
- throw new Error(`Total CMS API error: ${response.status} ${response.body}`);
- }
-
- return {
- success: true,
- data: response.body['data'],
- };
-};
-
-const totalcmsUploadAPI = async (
- auth: TotalCMSAuthType,
- type: string,
- slug: string,
- file: FileUpload,
- data: KeyValuePair = {},
- fileName = 'file'
-) => {
- const formData = new FormData();
- formData.append('type', type);
- formData.append('slug', slug);
-
- formData.append(fileName, Buffer.from(file.base64, 'base64'), file.filename);
-
- for (const key in data) {
- if (fileName !== 'file') {
- // blog post images use the format image[alt] or gallery[alt]
- formData.append(`${fileName}[${key}]`, data[key]);
- }
- formData.append(key, data[key]);
- }
-
- const request: HttpRequest = {
- body: formData,
- method: HttpMethod.POST,
- url: `${auth.props.domain}/rw_common/plugins/stacks/total-cms/totalapi.php`,
- headers: {
- 'Content-Type': 'multipart/form-data',
- 'total-key': auth.props.license,
- },
- };
- const response = await httpClient.sendRequest(request);
-
- if (response.status !== 200) {
- throw new Error(`Total CMS API error: ${response.status} ${response.body}`);
- }
-
- return {
- success: true,
- data: response.body['data'],
- };
-};
-
-export async function saveFile(
- auth: TotalCMSAuthType,
- slug: string,
- file: FileUpload,
- data: KeyValuePair
-) {
- return totalcmsUploadAPI(auth, 'file', slug, file, data);
-}
-
-export async function saveDepot(
- auth: TotalCMSAuthType,
- slug: string,
- file: FileUpload
-) {
- return totalcmsUploadAPI(auth, 'depot', slug, file);
-}
-
-export async function saveImage(
- auth: TotalCMSAuthType,
- slug: string,
- file: FileUpload,
- data: KeyValuePair
-) {
- return totalcmsUploadAPI(auth, 'image', slug, file, data);
-}
-
-export async function saveGallery(
- auth: TotalCMSAuthType,
- slug: string,
- file: FileUpload,
- data: KeyValuePair
-) {
- return totalcmsUploadAPI(auth, 'gallery', slug, file, data);
-}
-
-export async function saveBlogImage(
- auth: TotalCMSAuthType,
- slug: string,
- file: FileUpload,
- data: KeyValuePair
-) {
- return totalcmsUploadAPI(auth, 'blog', slug, file, data, 'image');
-}
-
-export async function saveBlogGallery(
- auth: TotalCMSAuthType,
- slug: string,
- file: FileUpload,
- data: KeyValuePair
-) {
- return totalcmsUploadAPI(auth, 'blog', slug, file, data, 'gallery');
-}
-
-export async function saveContent(
- auth: TotalCMSAuthType,
- type: string,
- slug: string,
- data: KeyValuePair
-) {
- return totalcmsAPI(auth, type, slug, {}, data, HttpMethod.POST);
-}
-
-export async function getContent(
- auth: TotalCMSAuthType,
- type: string,
- slug: string,
- query: QueryParams = {}
-) {
- return totalcmsAPI(auth, type, slug, query);
-}
-
-export async function getBlogPost(
- auth: TotalCMSAuthType,
- slug: string,
- permalink: string
-) {
- return totalcmsAPI(auth, 'blog', slug, { permalink: permalink });
-}
diff --git a/packages/pieces/community/totalcms/src/lib/auth.ts b/packages/pieces/community/totalcms/src/lib/auth.ts
index 3ba9641eaa2..e1333a05f2b 100644
--- a/packages/pieces/community/totalcms/src/lib/auth.ts
+++ b/packages/pieces/community/totalcms/src/lib/auth.ts
@@ -1,45 +1,104 @@
import { AppConnectionValueForAuthProperty, PieceAuth, Property } from '@activepieces/pieces-framework';
-import * as z from 'zod/mini'
-import { propsValidation } from '@activepieces/pieces-common';
-import { saveContent } from './api';
-import { AppConnectionType } from '@activepieces/pieces-framework';
+import { httpClient, HttpMethod } from '@activepieces/pieces-common';
-export type TotalCMSAuthType = AppConnectionValueForAuthProperty<typeof cmsAuth>;
+
+export function totalcmsBaseUrl(domain: string): string {
+ return domain.trim().replace(/\/+$/, '');
+}
export const cmsAuth = PieceAuth.CustomAuth({
- description: 'Setup your Total CMS connection',
+ displayName: 'Total CMS Connection',
+ description: `Connect a Total CMS 3 site.
+
+1. Sign in to your Total CMS admin.
+2. Go to **Utilities → API Keys** (or open \`/admin/utils/api-keys\`).
+3. Click **Create New API Key**, give it a name, choose the HTTP methods and endpoints Activepieces may use (all endpoints is simplest), and copy the key. It is shown only once.
+4. Paste your site address and the key below.
+
+API keys need the Pro edition of Total CMS (local development domains such as localhost include it).`,
props: {
domain: Property.ShortText({
- displayName: 'Total CMS Domain',
- description: 'The domain of your Total CMS website',
+ displayName: 'Site URL',
+ description: 'The address of your Total CMS site, e.g. https://www.example.com',
required: true,
}),
- license: PieceAuth.SecretText({
- displayName: 'License Key',
- description: 'The License key for your Total CMS domain',
+ apiKey: PieceAuth.SecretText({
+ displayName: 'API Key',
+ description: 'A Total CMS API key, starting with tcms_',
required: true,
}),
},
required: true,
async validate({ auth }) {
- await propsValidation.validateZod(auth, {
- domain: z.string().check(z.url()),
- license: z.string(),
- });
-
- const response = await saveContent({
- type: AppConnectionType.CUSTOM_AUTH,
- props: auth,
- }, 'text', 'activepieces', {
- text: 'verified',
- });
- if (response.success !== true) {
- throw new Error(
- 'Authentication failed. Please check your domain and license key and try again.'
- );
+ let base: string;
+ try {
+ const url = new URL(totalcmsBaseUrl(auth.domain));
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
+ return { valid: false, error: 'The Site URL must start with http:// or https://.' };
+ }
+ base = totalcmsBaseUrl(auth.domain);
+ } catch {
+ return { valid: false, error: 'The Site URL is not a valid web address.' };
+ }
+ try {
+ const response = await httpClient.sendRequest<unknown>({
+ method: HttpMethod.GET,
+ url: `${base}/api/collections`,
+ headers: { 'X-API-Key': auth.apiKey.trim(), Accept: 'application/json' },
+ followRedirects: false,
+ });
+ if (response.status >= 300) {
+ return {
+ valid: false,
+ error: 'The Site URL redirects to another address. Enter the final address of your site (check https:// and www).',
+ };
+ }
+ if (!hasDataList(response.body)) {
+ return {
+ valid: false,
+ error: 'This Site URL did not answer like a Total CMS 3 API. Check the address (Total CMS 1 and 2 are not supported).',
+ };
+ }
+ return { valid: true };
+ } catch (e) {
+ const status = errorStatus(e);
+ if (status === 401 || status === 403) {
+ return {
+ valid: false,
+ error: 'Total CMS rejected the API key. Check the key and that it allows GET requests.',
+ };
+ }
+ if (status === 404) {
+ return {
+ valid: false,
+ error: 'No Total CMS 3 API was found at this Site URL. Check the address (Total CMS 1 and 2 are not supported).',
+ };
+ }
+ return {
+ valid: false,
+ error: 'Could not reach the Total CMS site. Check the Site URL and that the site is online.',
+ };
}
- return {
- valid: true,
- };
},
});
+
+function errorStatus(error: unknown): number | undefined {
+ if (error === null || typeof error !== 'object') {
+ return undefined;
+ }
+ const response: unknown = Reflect.get(error, 'response');
+ if (response === null || typeof response !== 'object') {
+ return undefined;
+ }
+ const status: unknown = Reflect.get(response, 'status');
+ return typeof status === 'number' ? status : undefined;
+}
+
+function hasDataList(body: unknown): boolean {
+ if (body === null || typeof body !== 'object') {
+ return false;
+ }
+ return Array.isArray(Reflect.get(body, 'data'));
+}
+
+export type TotalCMSAuthType = AppConnectionValueForAuthProperty<typeof cmsAuth>;
diff --git a/packages/pieces/community/totalcms/src/lib/common/client.ts b/packages/pieces/community/totalcms/src/lib/common/client.ts
new file mode 100644
index 00000000000..3450619db7e
--- /dev/null
+++ b/packages/pieces/community/totalcms/src/lib/common/client.ts
@@ -0,0 +1,544 @@
+import { httpClient, HttpMethod, QueryParams } from '@activepieces/pieces-common';
+import FormData from 'form-data';
+import { totalcmsBaseUrl } from '../auth';
+
+const REQUEST_TIMEOUT_MS = 60_000;
+const MAX_ERROR_TEXT = 500;
+
+export class TotalCmsApiError extends Error {
+ readonly status: number;
+ readonly responseBody: unknown;
+
+ constructor({ operation, status, responseBody }: { operation: string; status: number; responseBody: unknown }) {
+ super(`Total CMS could not ${operation} (HTTP ${status}): ${describeStatus({ status, responseBody })}`);
+ this.name = 'TotalCmsApiError';
+ this.status = status;
+ this.responseBody = responseBody;
+ }
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+function vendorMessage(responseBody: unknown): string {
+ if (typeof responseBody === 'string' && responseBody.trim().length > 0) {
+ return responseBody.trim().slice(0, MAX_ERROR_TEXT);
+ }
+ if (isRecord(responseBody)) {
+ const error = responseBody['error'];
+ if (typeof error === 'string' && error.length > 0) {
+ return error.slice(0, MAX_ERROR_TEXT);
+ }
+ if (isRecord(error) && typeof error['message'] === 'string') {
+ return error['message'].replace(/^\d{3} [A-Za-z ]+ - /, '').slice(0, MAX_ERROR_TEXT);
+ }
+ if (typeof responseBody['message'] === 'string') {
+ return responseBody['message'].slice(0, MAX_ERROR_TEXT);
+ }
+ return JSON.stringify(responseBody).slice(0, MAX_ERROR_TEXT);
+ }
+ return 'no details returned';
+}
+
+function describeStatus({ status, responseBody }: { status: number; responseBody: unknown }): string {
+ const detail = vendorMessage(responseBody);
+ switch (status) {
+ case 401:
+ return `the API key is invalid or was revoked. ${detail}`;
+ case 403:
+ return `the API key is not allowed to do this. Check the key's allowed methods and endpoints in Total CMS (Utilities > API Keys). ${detail}`;
+ case 404:
+ return `not found. Check the collection and object ID. ${detail}`;
+ case 429:
+ return `Total CMS rate limit reached; try again in a minute. ${detail}`;
+ default:
+ return detail;
+ }
+}
+
+function statusOf(error: unknown): number | undefined {
+ if (error instanceof TotalCmsApiError) {
+ return error.status;
+ }
+ if (!isRecord(error) && !(error instanceof Error)) {
+ return undefined;
+ }
+ const response: unknown = Reflect.get(error, 'response');
+ if (isRecord(response) && typeof response['status'] === 'number') {
+ return response['status'];
+ }
+ return undefined;
+}
+
+function responseBodyOf(error: unknown): unknown {
+ if (!isRecord(error) && !(error instanceof Error)) {
+ return undefined;
+ }
+ const response: unknown = Reflect.get(error, 'response');
+ return isRecord(response) ? response['body'] : undefined;
+}
+
+function seg({ value, label }: { value: unknown; label: string }): string {
+ if (value === undefined || value === null) {
+ throw new Error(`${label} is required.`);
+ }
+ const text = String(value).trim();
+ if (text.length === 0) {
+ throw new Error(`${label} is required.`);
+ }
+ if (text === '.' || text === '..' || text.includes('/') || text.includes('\\')) {
+ throw new Error(`${label} "${text.slice(0, 100)}" is not valid. Use the ID only, without slashes.`);
+ }
+ return encodeURIComponent(text);
+}
+
+function apiBase(auth: TotalCmsConnection): string {
+ const base = totalcmsBaseUrl(auth.props.domain);
+ let url: URL;
+ try {
+ url = new URL(base);
+ } catch {
+ throw new Error('The connection Site URL is not a valid web address. Reconnect Total CMS with a full URL such as https://www.example.com.');
+ }
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
+ throw new Error('The connection Site URL must start with http:// or https://.');
+ }
+ return `${base}/api`;
+}
+
+function siteBase(auth: TotalCmsConnection): string {
+ return totalcmsBaseUrl(auth.props.domain);
+}
+
+async function request<T>({
+ auth,
+ method,
+ path,
+ queryParams,
+ body,
+ operation,
+}: {
+ auth: TotalCmsConnection;
+ method: HttpMethod;
+ path: string[];
+ queryParams?: QueryParams;
+ body?: unknown;
+ operation: string;
+}): Promise<T> {
+ const url = `${apiBase(auth)}/${path.join('/')}`;
+ const isForm = body instanceof FormData;
+ try {
+ const response = await httpClient.sendRequest<T>({
+ method,
+ url,
+ headers: {
+ 'X-API-Key': auth.props.apiKey.trim(),
+ Accept: 'application/json',
+ ...(isForm ? body.getHeaders() : {}),
+ },
+ queryParams,
+ body,
+ timeout: REQUEST_TIMEOUT_MS,
+ followRedirects: false,
+ });
+ if (response.status >= 300) {
+ throw new TotalCmsApiError({
+ operation,
+ status: response.status,
+ responseBody: 'The site answered with a redirect. Use the final site address (for example https:// and the www prefix if your site uses it) as the Site URL.',
+ });
+ }
+ return response.body;
+ } catch (error) {
+ if (error instanceof TotalCmsApiError) {
+ throw error;
+ }
+ const status = statusOf(error);
+ if (status === undefined) {
+ throw error;
+ }
+ throw new TotalCmsApiError({ operation, status, responseBody: responseBodyOf(error) });
+ }
+}
+
+function unwrap(body: unknown): Record<string, unknown> {
+ if (isRecord(body) && isRecord(body['data'])) {
+ return body['data'];
+ }
+ if (isRecord(body)) {
+ return body;
+ }
+ throw new Error('Total CMS returned an unexpected response.');
+}
+
+async function listCollections({ auth }: { auth: TotalCmsConnection }): Promise<TotalCmsCollection[]> {
+ const body = await request<unknown>({ auth, method: HttpMethod.GET, path: ['collections'], operation: 'list collections' });
+ const data = isRecord(body) ? body['data'] : undefined;
+ if (!Array.isArray(data)) {
+ throw new Error('Total CMS returned an unexpected collection list.');
+ }
+ return data.filter(isRecord).map((item) => ({
+ id: String(item['id'] ?? ''),
+ name: typeof item['name'] === 'string' ? item['name'] : String(item['id'] ?? ''),
+ schema: typeof item['schema'] === 'string' ? item['schema'] : '',
+ description: typeof item['description'] === 'string' ? item['description'] : '',
+ object_count: typeof item['totalObjects'] === 'number' ? item['totalObjects'] : null,
+ label_singular: typeof item['labelSingular'] === 'string' ? item['labelSingular'] : '',
+ label_plural: typeof item['labelPlural'] === 'string' ? item['labelPlural'] : '',
+ singleton: item['singleton'] === true,
+ last_updated: typeof item['lastUpdated'] === 'string' ? item['lastUpdated'] : null,
+ }));
+}
+
+async function getSchema({ auth, collection }: { auth: TotalCmsConnection; collection: string }): Promise<Record<string, unknown>> {
+ const body = await request<unknown>({
+ auth,
+ method: HttpMethod.GET,
+ path: ['collections', seg({ value: collection, label: 'Collection' }), 'schema'],
+ operation: `read the schema of collection "${collection}"`,
+ });
+ return unwrap(body);
+}
+
+async function queryObjects({
+ auth,
+ collection,
+ limit,
+ offset,
+ sort,
+ search,
+ include,
+ exclude,
+}: {
+ auth: TotalCmsConnection;
+ collection: string;
+ limit: number;
+ offset: number;
+ sort?: string;
+ search?: string;
+ include?: string;
+ exclude?: string;
+}): Promise<QueryPage> {
+ const queryParams: QueryParams = { limit: String(limit), offset: String(offset) };
+ if (sort) {
+ queryParams['sort'] = sort;
+ }
+ if (search) {
+ queryParams['search'] = search;
+ }
+ if (include) {
+ queryParams['include'] = include;
+ }
+ if (exclude) {
+ queryParams['exclude'] = exclude;
+ }
+ const body = await request<unknown>({
+ auth,
+ method: HttpMethod.GET,
+ path: ['collections', seg({ value: collection, label: 'Collection' }), 'query'],
+ queryParams,
+ operation: `query collection "${collection}"`,
+ });
+ if (!isRecord(body) || !Array.isArray(body['data'])) {
+ throw new Error('Total CMS returned an unexpected query response.');
+ }
+ const meta = isRecord(body['meta']) ? body['meta'] : {};
+ const pagination = isRecord(meta['pagination']) ? meta['pagination'] : {};
+ const objects = body['data'].filter(isRecord);
+ const total = typeof pagination['total'] === 'number' ? pagination['total'] : objects.length;
+ return { objects, total };
+}
+
+async function getObject({ auth, collection, id }: { auth: TotalCmsConnection; collection: string; id: string }): Promise<Record<string, unknown>> {
+ const body = await request<unknown>({
+ auth,
+ method: HttpMethod.GET,
+ path: ['collections', seg({ value: collection, label: 'Collection' }), seg({ value: id, label: 'Object ID' })],
+ operation: `read object "${id}" in collection "${collection}"`,
+ });
+ return unwrap(body);
+}
+
+async function findObject({ auth, collection, id }: { auth: TotalCmsConnection; collection: string; id: string }): Promise<Record<string, unknown> | null> {
+ try {
+ return await getObject({ auth, collection, id });
+ } catch (error) {
+ if (statusOf(error) === 404) {
+ return null;
+ }
+ throw error;
+ }
+}
+
+async function createObject({ auth, collection, fields }: { auth: TotalCmsConnection; collection: string; fields: Record<string, unknown> }): Promise<Record<string, unknown>> {
+ const body = await request<unknown>({
+ auth,
+ method: HttpMethod.POST,
+ path: ['collections', seg({ value: collection, label: 'Collection' })],
+ body: fields,
+ operation: `create an object in collection "${collection}"`,
+ });
+ return unwrap(body);
+}
+
+async function replaceObject({ auth, collection, id, fields }: { auth: TotalCmsConnection; collection: string; id: string; fields: Record<string, unknown> }): Promise<Record<string, unknown>> {
+ const body = await request<unknown>({
+ auth,
+ method: HttpMethod.PUT,
+ path: ['collections', seg({ value: collection, label: 'Collection' }), seg({ value: id, label: 'Object ID' })],
+ body: { ...fields, id: id.trim() },
+ operation: `save object "${id}" in collection "${collection}"`,
+ });
+ return unwrap(body);
+}
+
+async function patchObject({ auth, collection, id, fields }: { auth: TotalCmsConnection; collection: string; id: string; fields: Record<string, unknown> }): Promise<Record<string, unknown>> {
+ const body = await request<unknown>({
+ auth,
+ method: HttpMethod.PATCH,
+ path: ['collections', seg({ value: collection, label: 'Collection' }), seg({ value: id, label: 'Object ID' })],
+ body: fields,
+ operation: `update object "${id}" in collection "${collection}"`,
+ });
+ return unwrap(body);
+}
+
+async function deleteObject({ auth, collection, id }: { auth: TotalCmsConnection; collection: string; id: string }): Promise<void> {
+ await request<unknown>({
+ auth,
+ method: HttpMethod.DELETE,
+ path: ['collections', seg({ value: collection, label: 'Collection' }), seg({ value: id, label: 'Object ID' })],
+ operation: `delete object "${id}" in collection "${collection}"`,
+ });
+}
+
+async function cloneObject({
+ auth,
+ collection,
+ id,
+ newId,
+ targetCollection,
+}: {
+ auth: TotalCmsConnection;
+ collection: string;
+ id: string;
+ newId: string;
+ targetCollection?: string;
+}): Promise<Record<string, unknown>> {
+ const payload: Record<string, unknown> = { id: newId };
+ if (targetCollection) {
+ payload['collection'] = targetCollection;
+ }
+ const body = await request<unknown>({
+ auth,
+ method: HttpMethod.POST,
+ path: ['collections', seg({ value: collection, label: 'Collection' }), seg({ value: id, label: 'Object ID' }), 'clone'],
+ body: payload,
+ operation: `duplicate object "${id}" in collection "${collection}"`,
+ });
+ return unwrap(body);
+}
+
+async function adjustNumber({
+ auth,
+ collection,
+ id,
+ property,
+ direction,
+ amount,
+}: {
+ auth: TotalCmsConnection;
+ collection: string;
+ id: string;
+ property: string;
+ direction: 'increment' | 'decrement';
+ amount: number;
+}): Promise<Record<string, unknown>> {
+ const body = await request<unknown>({
+ auth,
+ method: HttpMethod.POST,
+ path: [
+ 'collections',
+ seg({ value: collection, label: 'Collection' }),
+ seg({ value: id, label: 'Object ID' }),
+ seg({ value: property, label: 'Field' }),
+ direction,
+ encodeURIComponent(String(amount)),
+ ],
+ operation: `${direction} field "${property}" of object "${id}"`,
+ });
+ return unwrap(body);
+}
+
+async function uploadFile({
+ auth,
+ collection,
+ id,
+ property,
+ source,
+ folder,
+}: {
+ auth: TotalCmsConnection;
+ collection: string;
+ id: string;
+ property: string;
+ source: UploadSource;
+ folder?: string;
+}): Promise<UploadResult> {
+ const path = [
+ 'collections',
+ seg({ value: collection, label: 'Collection' }),
+ seg({ value: id, label: 'Object ID' }),
+ seg({ value: property, label: 'Field' }),
+ ];
+ const folderSegments = folder ? splitFolder(folder) : [];
+ path.push(...folderSegments.map((part) => encodeURIComponent(part)));
+ const fieldName = folderSegments.length > 0 ? folderSegments[folderSegments.length - 1] : property.trim();
+ let body: unknown;
+ if (source.kind === 'file') {
+ const form = new FormData();
+ form.append(fieldName, source.data, { filename: source.filename });
+ body = form;
+ } else {
+ body = { [fieldName]: source.url };
+ }
+ const response = await request<unknown>({
+ auth,
+ method: HttpMethod.POST,
+ path,
+ body,
+ operation: `upload a file to field "${property}" of object "${id}"`,
+ });
+ const meta = isRecord(response) && isRecord(response['meta']) ? response['meta'] : {};
+ const preview = typeof meta['preview'] === 'string' ? meta['preview'] : null;
+ return {
+ object: unwrap(response),
+ preview_url: preview ? `${siteBase(auth)}${preview.startsWith('/') ? '' : '/'}${preview}` : null,
+ };
+}
+
+async function patchFileMeta({
+ auth,
+ collection,
+ id,
+ property,
+ fileName,
+ fields,
+}: {
+ auth: TotalCmsConnection;
+ collection: string;
+ id: string;
+ property: string;
+ fileName?: string;
+ fields: Record<string, unknown>;
+}): Promise<Record<string, unknown>> {
+ const path = [
+ 'collections',
+ seg({ value: collection, label: 'Collection' }),
+ seg({ value: id, label: 'Object ID' }),
+ seg({ value: property, label: 'Field' }),
+ ];
+ if (fileName) {
+ path.push(seg({ value: fileName, label: 'File name' }));
+ }
+ const body = await request<unknown>({
+ auth,
+ method: HttpMethod.PATCH,
+ path,
+ body: fields,
+ operation: `update the details of field "${property}" of object "${id}"`,
+ });
+ return unwrap(body);
+}
+
+function splitFolder(folder: string): string[] {
+ const parts = folder
+ .split('/')
+ .map((part) => part.trim())
+ .filter((part) => part.length > 0);
+ for (const part of parts) {
+ if (part === '.' || part === '..' || part.includes('\\')) {
+ throw new Error(`Folder "${folder.slice(0, 100)}" is not valid. Use folder names separated by /, for example 2026/reports.`);
+ }
+ }
+ return parts;
+}
+
+function parseFileSource({ file, url }: { file: unknown; url: unknown }): UploadSource {
+ const hasUrl = typeof url === 'string' && url.trim().length > 0;
+ const hasFile = isFileLike(file);
+ if (hasFile && hasUrl) {
+ throw new Error('Provide either a file or a file URL, not both.');
+ }
+ if (hasFile) {
+ return { kind: 'file', data: file.data, filename: file.filename };
+ }
+ if (hasUrl) {
+ const text = url.trim();
+ let parsed: URL;
+ try {
+ parsed = new URL(text);
+ } catch {
+ throw new Error(`"${text.slice(0, 200)}" is not a valid URL.`);
+ }
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
+ throw new Error('The file URL must start with http:// or https://.');
+ }
+ return { kind: 'url', url: text };
+ }
+ throw new Error('Provide a file or a file URL.');
+}
+
+function isFileLike(value: unknown): value is { data: Buffer; filename: string } {
+ if (!isRecord(value) && !(typeof value === 'object' && value !== null)) {
+ return false;
+ }
+ const data: unknown = Reflect.get(value, 'data');
+ const filename: unknown = Reflect.get(value, 'filename');
+ return Buffer.isBuffer(data) && typeof filename === 'string' && filename.length > 0;
+}
+
+export const totalcmsApi = {
+ listCollections,
+ getSchema,
+ queryObjects,
+ getObject,
+ findObject,
+ createObject,
+ replaceObject,
+ patchObject,
+ deleteObject,
+ cloneObject,
+ adjustNumber,
+ uploadFile,
+ patchFileMeta,
+};
+
+export const totalcmsHelpers = {
+ isRecord,
+ statusOf,
+ parseFileSource,
+ apiBase,
+ siteBase,
+};
+
+export type TotalCmsConnection = { props: { domain: string; apiKey: string } };
+
+export type TotalCmsCollection = {
+ id: string;
+ name: string;
+ schema: string;
+ description: string;
+ object_count: number | null;
+ label_singular: string;
+ label_plural: string;
+ singleton: boolean;
+ last_updated: string | null;
+};
+
+export type QueryPage = { objects: Record<string, unknown>[]; total: number };
+
+export type UploadSource = { kind: 'file'; data: Buffer; filename: string } | { kind: 'url'; url: string };
+
+export type UploadResult = { object: Record<string, unknown>; preview_url: string | null };
diff --git a/packages/pieces/community/totalcms/src/lib/common/operations.ts b/packages/pieces/community/totalcms/src/lib/common/operations.ts
new file mode 100644
index 00000000000..adaf9eaba68
--- /dev/null
+++ b/packages/pieces/community/totalcms/src/lib/common/operations.ts
@@ -0,0 +1,270 @@
+import { Property } from '@activepieces/pieces-framework';
+import { totalcmsApi, totalcmsHelpers, TotalCmsConnection } from './client';
+import { totalcmsShape } from './shape';
+import { totalcmsUpdate } from './update';
+import { totalcmsUpload } from './upload';
+
+const MAX_LIMIT = 100;
+
+export const totalcmsOperations = {
+ findProps,
+ findObjects,
+ collectionFields,
+ createFieldsProp,
+ createObject,
+ updateFieldsProp,
+ updateObject,
+ uploadExtraProps,
+ uploadFile,
+ adjustProps,
+ adjustNumber,
+ newIdProp,
+ cloneObject,
+};
+
+function findProps() {
+ return {
+ search: Property.ShortText({
+ displayName: 'Search',
+ description: 'Words to search for in any field. Use "quotes" for an exact phrase and "or" between words to match any.',
+ required: false,
+ }),
+ include: Property.ShortText({
+ displayName: 'Only Include',
+ description:
+ 'Keep only objects matching ALL of these filters, separated by commas. Examples: draft:false, featured, category:in:news|events, price:lte:100.',
+ required: false,
+ }),
+ exclude: Property.ShortText({
+ displayName: 'Exclude',
+ description: 'Drop objects matching ANY of these filters, separated by commas. Example: draft:true.',
+ required: false,
+ }),
+ sort: Property.ShortText({
+ displayName: 'Sort By',
+ description: 'A field name to sort by. Put - in front for newest or largest first, for example -created or -date.',
+ required: false,
+ }),
+ limit: Property.Number({
+ displayName: 'Limit',
+ description: `How many objects to return (1-${MAX_LIMIT}).`,
+ required: false,
+ defaultValue: 20,
+ }),
+ offset: Property.Number({
+ displayName: 'Offset',
+ description: 'How many matching objects to skip. Use Next Offset from a previous run to get the next page.',
+ required: false,
+ defaultValue: 0,
+ }),
+ };
+}
+
+async function findObjects({ auth, input }: { auth: TotalCmsConnection; input: FindInput }) {
+ const collection = totalcmsShape.requireId({ value: input.collection, label: 'Collection' });
+ const limit = wholeNumber({ value: input.limit, fallback: 20, label: 'Limit', min: 1, max: MAX_LIMIT });
+ const offset = wholeNumber({ value: input.offset, fallback: 0, label: 'Offset', min: 0, max: Number.MAX_SAFE_INTEGER });
+ const page = await totalcmsApi.queryObjects({
+ auth,
+ collection,
+ limit,
+ offset,
+ sort: trimmed({ value: input.sort }),
+ search: trimmed({ value: input.search }),
+ include: trimmed({ value: input.include }),
+ exclude: trimmed({ value: input.exclude }),
+ });
+ const hasMore = offset + page.objects.length < page.total;
+ return {
+ objects: page.objects,
+ count: page.objects.length,
+ total: page.total,
+ offset,
+ has_more: hasMore,
+ next_offset: hasMore ? offset + page.objects.length : null,
+ };
+}
+
+async function collectionFields({ auth, collection }: { auth: TotalCmsConnection; collection: unknown }) {
+ const collectionId = totalcmsShape.requireId({ value: collection, label: 'Collection' });
+ const schema = await totalcmsApi.getSchema({ auth, collection: collectionId });
+ const required = stringList({ value: schema['required'] });
+ const index = stringList({ value: schema['index'] });
+ const properties = totalcmsHelpers.isRecord(schema['properties']) ? schema['properties'] : {};
+ const fields = Object.entries(properties).map(([key, value]) => {
+ const property = totalcmsHelpers.isRecord(value) ? value : {};
+ return {
+ key,
+ label: typeof property['label'] === 'string' ? property['label'] : key,
+ field_type: typeof property['field'] === 'string' ? property['field'] : null,
+ data_type: typeof property['type'] === 'string' ? property['type'] : refName({ value: property['$ref'] }),
+ required: required.includes(key),
+ in_index: index.includes(key),
+ help: typeof property['help'] === 'string' ? property['help'] : null,
+ };
+ });
+ return {
+ collection: collectionId,
+ schema: typeof schema['id'] === 'string' ? schema['id'] : null,
+ description: typeof schema['description'] === 'string' ? schema['description'] : null,
+ fields,
+ };
+}
+
+function createFieldsProp() {
+ return Property.Json({
+ displayName: 'Fields',
+ description: 'The field values as JSON, for example {"title": "Hello", "draft": false}. Use Get Collection Fields to see the field names.',
+ required: true,
+ defaultValue: {},
+ });
+}
+
+async function createObject({ auth, collection, objectId, fields }: { auth: TotalCmsConnection; collection: unknown; objectId: unknown; fields: unknown }) {
+ const collectionId = totalcmsShape.requireId({ value: collection, label: 'Collection' });
+ const parsed = totalcmsShape.parseFields({ value: fields, label: 'Fields' });
+ const id = typeof objectId === 'string' ? objectId.trim() : '';
+ const object = await totalcmsApi.createObject({ auth, collection: collectionId, fields: id ? { ...parsed, id } : parsed });
+ return totalcmsShape.generic({ collection: collectionId, object });
+}
+
+function updateFieldsProp() {
+ return Property.Json({
+ displayName: 'Fields to Change',
+ description: 'Only the fields to change, as JSON, for example {"title": "New title"}. Use Get Collection Fields to see the field names.',
+ required: true,
+ defaultValue: {},
+ });
+}
+
+async function updateObject({ auth, collection, objectId, fields }: { auth: TotalCmsConnection; collection: unknown; objectId: unknown; fields: unknown }) {
+ const collectionId = totalcmsShape.requireId({ value: collection, label: 'Collection' });
+ const id = totalcmsShape.requireId({ value: objectId, label: 'Object ID' });
+ return totalcmsUpdate.run({ auth, collection: collectionId, id, fields });
+}
+
+function uploadExtraProps() {
+ return {
+ ...totalcmsUpload.fileProps(),
+ folder: Property.ShortText({
+ displayName: 'Folder',
+ description: 'Depot fields only: an optional folder path, such as 2026/reports.',
+ required: false,
+ }),
+ };
+}
+
+async function uploadFile({ auth, input }: { auth: TotalCmsConnection; input: UploadInput }) {
+ const collection = totalcmsShape.requireId({ value: input.collection, label: 'Collection' });
+ const id = totalcmsShape.requireId({ value: input.object_id, label: 'Object ID' });
+ const field = totalcmsShape.requireId({ value: input.field, label: 'Field' });
+ const result = await totalcmsUpload.save({
+ auth,
+ collection,
+ id,
+ property: field,
+ file: input.file,
+ fileUrl: input.file_url,
+ folder: typeof input.folder === 'string' ? input.folder : undefined,
+ multiple: false,
+ });
+ return { ...totalcmsShape.generic({ collection, object: result.object }), field, preview_url: result.preview_url };
+}
+
+function adjustProps() {
+ return {
+ direction: Property.StaticDropdown({
+ displayName: 'Change',
+ required: true,
+ defaultValue: 'increment',
+ options: {
+ options: [
+ { label: 'Increase', value: 'increment' },
+ { label: 'Decrease', value: 'decrement' },
+ ],
+ },
+ }),
+ amount: Property.Number({
+ displayName: 'Amount',
+ description: 'How much to add or subtract. Must be more than 0.',
+ required: true,
+ defaultValue: 1,
+ }),
+ };
+}
+
+async function adjustNumber({ auth, input }: { auth: TotalCmsConnection; input: AdjustInput }) {
+ const collection = totalcmsShape.requireId({ value: input.collection, label: 'Collection' });
+ const id = totalcmsShape.requireId({ value: input.object_id, label: 'Object ID' });
+ const field = totalcmsShape.requireId({ value: input.field, label: 'Number Field' });
+ const direction = input.direction === 'decrement' ? 'decrement' : input.direction === 'increment' ? 'increment' : null;
+ if (!direction) {
+ throw new Error('Change must be Increase or Decrease.');
+ }
+ const amount = Number(input.amount);
+ if (!Number.isFinite(amount) || amount <= 0) {
+ throw new Error('Amount must be a number greater than 0.');
+ }
+ const result = await totalcmsApi.adjustNumber({ auth, collection, id, property: field, direction, amount });
+ return { collection, id, field, value: typeof result['value'] === 'number' ? result['value'] : null };
+}
+
+function newIdProp() {
+ return Property.ShortText({
+ displayName: 'New Object ID',
+ description: 'The ID (URL slug) for the copy, for example my-post-copy. Must not exist yet.',
+ required: true,
+ });
+}
+
+async function cloneObject({ auth, collection, objectId, newId }: { auth: TotalCmsConnection; collection: unknown; objectId: unknown; newId: unknown }) {
+ const collectionId = totalcmsShape.requireId({ value: collection, label: 'Collection' });
+ const id = totalcmsShape.requireId({ value: objectId, label: 'Object ID' });
+ const target = totalcmsShape.requireId({ value: newId, label: 'New Object ID' });
+ if (target === id) {
+ throw new Error('New Object ID must be different from the object being copied.');
+ }
+ const object = await totalcmsApi.cloneObject({ auth, collection: collectionId, id, newId: target });
+ return totalcmsShape.generic({ collection: collectionId, object });
+}
+
+function wholeNumber({ value, fallback, label, min, max }: { value: unknown; fallback: number; label: string; min: number; max: number }): number {
+ if (value === undefined || value === null || value === '') {
+ return fallback;
+ }
+ const number = Number(value);
+ if (!Number.isInteger(number) || number < min || number > max) {
+ throw new Error(max === Number.MAX_SAFE_INTEGER ? `${label} must be a whole number of ${min} or more.` : `${label} must be a whole number from ${min} to ${max}.`);
+ }
+ return number;
+}
+
+function trimmed({ value }: { value: unknown }): string | undefined {
+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;
+}
+
+function stringList({ value }: { value: unknown }): string[] {
+ return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];
+}
+
+function refName({ value }: { value: unknown }): string | null {
+ if (typeof value !== 'string') {
+ return null;
+ }
+ const last = value.split('/').pop() ?? '';
+ return last.replace(/\.json$/, '') || null;
+}
+
+type FindInput = {
+ collection: unknown;
+ search?: unknown;
+ include?: unknown;
+ exclude?: unknown;
+ sort?: unknown;
+ limit?: unknown;
+ offset?: unknown;
+};
+
+type UploadInput = { collection: unknown; object_id: unknown; field: unknown; file?: unknown; file_url?: unknown; folder?: unknown };
+
+type AdjustInput = { collection: unknown; object_id: unknown; field: unknown; direction: unknown; amount: unknown };
diff --git a/packages/pieces/community/totalcms/src/lib/common/polling.ts b/packages/pieces/community/totalcms/src/lib/common/polling.ts
new file mode 100644
index 00000000000..adf67fdbcf4
--- /dev/null
+++ b/packages/pieces/community/totalcms/src/lib/common/polling.ts
@@ -0,0 +1,184 @@
+import { Store } from '@activepieces/pieces-framework';
+import { totalcmsApi, totalcmsHelpers, TotalCmsConnection } from './client';
+
+const PAGE_SIZE = 100;
+const MAX_PAGES = 50;
+const MAX_EVENTS = 200;
+const LOAD_CONCURRENCY = 10;
+const TEST_ITEMS = 5;
+const STORE_KEY = 'totalcms_checkpoint';
+
+export const totalcmsPolling = {
+ enable,
+ disable,
+ poll,
+ sample,
+};
+
+async function enable({ auth, store, collection, field, isRepublish }: PollParams & { isRepublish?: boolean }): Promise<void> {
+ await assertTimestampField({ auth, collection, field });
+ if (isRepublish && (await readCheckpoint({ store })) !== null) {
+ return;
+ }
+ const newest = await collectNewestGroup({ auth, collection, field });
+ await store.put(STORE_KEY, checkpointFrom({ objects: newest, field, previous: { ts: 0, ids: [] } }));
+}
+
+async function disable({ store }: { store: Store }): Promise<void> {
+ await store.delete(STORE_KEY);
+}
+
+async function poll({ auth, store, collection, field }: PollParams): Promise<Record<string, unknown>[]> {
+ const checkpoint = await readCheckpoint({ store });
+ if (checkpoint === null) {
+ await enable({ auth, store, collection, field });
+ return [];
+ }
+ const fresh = await collectSince({ auth, collection, field, checkpoint });
+ const batch = [...fresh].reverse().slice(0, MAX_EVENTS);
+ const objects = await loadFull({ auth, collection, items: batch });
+ await store.put(STORE_KEY, checkpointFrom({ objects: batch, field, previous: checkpoint }));
+ return objects;
+}
+
+async function sample({ auth, collection, field, keep }: Omit<PollParams, 'store'> & { keep: (object: Record<string, unknown>) => boolean }): Promise<Record<string, unknown>[]> {
+ await assertTimestampField({ auth, collection, field });
+ const page = await totalcmsApi.queryObjects({ auth, collection, limit: PAGE_SIZE, offset: 0, sort: `-${field}` });
+ const objects = await loadFull({ auth, collection, items: page.objects.slice(0, TEST_ITEMS * 4) });
+ return objects.filter(keep).slice(0, TEST_ITEMS);
+}
+
+async function collectSince({
+ auth,
+ collection,
+ field,
+ checkpoint,
+}: {
+ auth: TotalCmsConnection;
+ collection: string;
+ field: string;
+ checkpoint: Checkpoint;
+}): Promise<Record<string, unknown>[]> {
+ const fresh: Record<string, unknown>[] = [];
+ for (let pageIndex = 0; pageIndex < MAX_PAGES; pageIndex++) {
+ const page = await totalcmsApi.queryObjects({
+ auth,
+ collection,
+ limit: PAGE_SIZE,
+ offset: pageIndex * PAGE_SIZE,
+ sort: `-${field}`,
+ });
+ fresh.push(...page.objects.filter((item) => isNewer({ item, field, checkpoint })));
+ const reachedCheckpoint = page.objects.some((item) => timestampOf({ item, field }) < checkpoint.ts);
+ if (reachedCheckpoint || page.objects.length < PAGE_SIZE) {
+ break;
+ }
+ }
+ return fresh;
+}
+
+async function collectNewestGroup({
+ auth,
+ collection,
+ field,
+}: {
+ auth: TotalCmsConnection;
+ collection: string;
+ field: string;
+}): Promise<Record<string, unknown>[]> {
+ const collected: Record<string, unknown>[] = [];
+ for (let pageIndex = 0; pageIndex < MAX_PAGES; pageIndex++) {
+ const page = await totalcmsApi.queryObjects({
+ auth,
+ collection,
+ limit: PAGE_SIZE,
+ offset: pageIndex * PAGE_SIZE,
+ sort: `-${field}`,
+ });
+ collected.push(...page.objects);
+ const newest = collected.map((item) => timestampOf({ item, field })).find((ts) => !Number.isNaN(ts));
+ const reachedOlder = newest !== undefined && page.objects.some((item) => timestampOf({ item, field }) < newest);
+ if (reachedOlder || page.objects.length < PAGE_SIZE) {
+ return collected;
+ }
+ }
+ const next = await totalcmsApi.queryObjects({
+ auth,
+ collection,
+ limit: 1,
+ offset: MAX_PAGES * PAGE_SIZE,
+ sort: `-${field}`,
+ });
+ const newestTs = collected.map((item) => timestampOf({ item, field })).find((ts) => !Number.isNaN(ts));
+ const groupContinues = next.objects.some((item) => timestampOf({ item, field }) === newestTs);
+ if (!groupContinues) {
+ return collected;
+ }
+ throw new Error(
+ `More than ${MAX_PAGES * PAGE_SIZE} objects in collection "${collection}" share the newest "${field}" date, so Activepieces cannot tell which ones already exist. Try again after newer objects are added.`,
+ );
+}
+
+function isNewer({ item, field, checkpoint }: { item: Record<string, unknown>; field: string; checkpoint: Checkpoint }): boolean {
+ const ts = timestampOf({ item, field });
+ if (Number.isNaN(ts) || ts < checkpoint.ts) {
+ return false;
+ }
+ if (ts === checkpoint.ts) {
+ return !checkpoint.ids.includes(String(item['id']));
+ }
+ return true;
+}
+
+function checkpointFrom({ objects, field, previous }: { objects: Record<string, unknown>[]; field: string; previous: Checkpoint }): Checkpoint {
+ const stamps = objects.map((item) => timestampOf({ item, field })).filter((ts) => !Number.isNaN(ts));
+ if (stamps.length === 0) {
+ return previous;
+ }
+ const newest = stamps.reduce((max, ts) => (ts > max ? ts : max), previous.ts);
+ const idsAtNewest = objects.filter((item) => timestampOf({ item, field }) === newest).map((item) => String(item['id']));
+ const ids = newest === previous.ts ? [...new Set([...previous.ids, ...idsAtNewest])] : idsAtNewest;
+ return { ts: newest, ids };
+}
+
+function timestampOf({ item, field }: { item: Record<string, unknown>; field: string }): number {
+ const value = item[field];
+ return typeof value === 'string' ? Date.parse(value) : NaN;
+}
+
+async function loadFull({ auth, collection, items }: { auth: TotalCmsConnection; collection: string; items: Record<string, unknown>[] }): Promise<Record<string, unknown>[]> {
+ const ids = items.map((item) => String(item['id'] ?? '')).filter((id) => id.length > 0);
+ const loaded: Record<string, unknown>[] = [];
+ for (let start = 0; start < ids.length; start += LOAD_CONCURRENCY) {
+ const chunk = await Promise.all(ids.slice(start, start + LOAD_CONCURRENCY).map((id) => totalcmsApi.findObject({ auth, collection, id })));
+ for (const full of chunk) {
+ if (full) {
+ loaded.push({ collection, ...full });
+ }
+ }
+ }
+ return loaded;
+}
+
+async function assertTimestampField({ auth, collection, field }: { auth: TotalCmsConnection; collection: string; field: string }): Promise<void> {
+ const schema = await totalcmsApi.getSchema({ auth, collection });
+ const index = Array.isArray(schema['index']) ? schema['index'] : [];
+ const properties = totalcmsHelpers.isRecord(schema['properties']) ? schema['properties'] : {};
+ if (!(field in properties) || !index.includes(field)) {
+ throw new Error(
+ `Collection "${collection}" does not record a "${field}" date for its objects, so Activepieces cannot tell when objects are ${field === 'created' ? 'added' : 'changed'}. Add a "${field}" datetime field to its schema (and to the schema index), or pick another collection.`,
+ );
+ }
+}
+
+async function readCheckpoint({ store }: { store: Store }): Promise<Checkpoint | null> {
+ const value = await store.get<unknown>(STORE_KEY);
+ if (!totalcmsHelpers.isRecord(value) || typeof value['ts'] !== 'number' || !Array.isArray(value['ids'])) {
+ return null;
+ }
+ return { ts: value['ts'], ids: value['ids'].map(String) };
+}
+
+type Checkpoint = { ts: number; ids: string[] };
+
+type PollParams = { auth: TotalCmsConnection; store: Store; collection: string; field: 'created' | 'updated' };
diff --git a/packages/pieces/community/totalcms/src/lib/common/props.ts b/packages/pieces/community/totalcms/src/lib/common/props.ts
new file mode 100644
index 00000000000..bd9f696de86
--- /dev/null
+++ b/packages/pieces/community/totalcms/src/lib/common/props.ts
@@ -0,0 +1,224 @@
+import { DropdownOption, Property } from '@activepieces/pieces-framework';
+import { cmsAuth } from '../auth';
+import { totalcmsApi, totalcmsHelpers, TotalCmsConnection } from './client';
+
+const OBJECT_PAGE_SIZE = 100;
+const OBJECT_DROPDOWN_MAX = 2000;
+const LABEL_KEYS = ['title', 'name', 'label', 'email'];
+
+export const totalcmsProps = {
+ collection,
+ object,
+ objectIdText,
+ collectionIdText,
+ collectionForSchema,
+ schemaField,
+};
+
+function collection({
+ displayName = 'Collection',
+ description = 'The Total CMS collection to use.',
+ schemas,
+}: {
+ displayName?: string;
+ description?: string;
+ schemas?: string[];
+} = {}) {
+ return Property.Dropdown({
+ auth: cmsAuth,
+ displayName,
+ description,
+ required: true,
+ refreshers: [],
+ options: async ({ auth }) => {
+ if (!auth) {
+ return { disabled: true, placeholder: 'Connect your Total CMS site first.', options: [] };
+ }
+ try {
+ const collections = await totalcmsApi.listCollections({ auth });
+ const matching = schemas ? collections.filter((item) => schemas.includes(item.schema)) : collections;
+ if (matching.length === 0) {
+ return {
+ disabled: true,
+ placeholder: schemas
+ ? `No collection uses the ${schemas.join(' or ')} schema. Create one in Total CMS first.`
+ : 'This site has no collections yet.',
+ options: [],
+ };
+ }
+ return {
+ disabled: false,
+ options: matching.map((item) => ({
+ label: item.name && item.name !== item.id ? `${item.name} (${item.id})` : item.id,
+ value: item.id,
+ })),
+ };
+ } catch (error) {
+ return { disabled: true, placeholder: errorPlaceholder({ error, what: 'collections' }), options: [] };
+ }
+ },
+ });
+}
+
+function object({
+ displayName = 'Object',
+ description = 'The object to use. The list shows each object by title and ID.',
+}: {
+ displayName?: string;
+ description?: string;
+} = {}) {
+ return Property.Dropdown({
+ auth: cmsAuth,
+ displayName,
+ description,
+ required: true,
+ refreshers: ['collection'],
+ options: async ({ auth, collection }) => {
+ if (!auth) {
+ return { disabled: true, placeholder: 'Connect your Total CMS site first.', options: [] };
+ }
+ if (typeof collection !== 'string' || collection.length === 0) {
+ return { disabled: true, placeholder: 'Select a collection first.', options: [] };
+ }
+ try {
+ const { options, truncated } = await objectOptions({ auth, collection });
+ if (options.length === 0) {
+ return { disabled: true, placeholder: 'This collection has no objects yet.', options: [] };
+ }
+ return {
+ disabled: false,
+ placeholder: truncated ? `Showing the first ${OBJECT_DROPDOWN_MAX} objects. Use an expression with the ID for others.` : undefined,
+ options,
+ };
+ } catch (error) {
+ return { disabled: true, placeholder: errorPlaceholder({ error, what: 'objects' }), options: [] };
+ }
+ },
+ });
+}
+
+function schemaField({
+ displayName,
+ description,
+ fieldTypes,
+ numeric,
+}: {
+ displayName: string;
+ description: string;
+ fieldTypes?: string[];
+ numeric?: boolean;
+}) {
+ return Property.Dropdown({
+ auth: cmsAuth,
+ displayName,
+ description,
+ required: true,
+ refreshers: ['collection'],
+ options: async ({ auth, collection }) => {
+ if (!auth) {
+ return { disabled: true, placeholder: 'Connect your Total CMS site first.', options: [] };
+ }
+ if (typeof collection !== 'string' || collection.length === 0) {
+ return { disabled: true, placeholder: 'Select a collection first.', options: [] };
+ }
+ try {
+ const schema = await totalcmsApi.getSchema({ auth, collection });
+ const properties = totalcmsHelpers.isRecord(schema['properties']) ? schema['properties'] : {};
+ const options = Object.entries(properties).flatMap(([key, value]): DropdownOption<string>[] => {
+ if (!totalcmsHelpers.isRecord(value)) {
+ return [];
+ }
+ const field = typeof value['field'] === 'string' ? value['field'] : '';
+ const type = typeof value['type'] === 'string' ? value['type'] : '';
+ const matches = numeric
+ ? type === 'number' || type === 'integer'
+ : fieldTypes !== undefined && fieldTypes.includes(field);
+ if (!matches) {
+ return [];
+ }
+ const label = typeof value['label'] === 'string' && value['label'].length > 0 ? value['label'] : key;
+ return [{ label: `${label} (${key})`, value: key }];
+ });
+ if (options.length === 0) {
+ return {
+ disabled: true,
+ placeholder: numeric ? 'This collection has no number fields.' : 'This collection has no file or image fields.',
+ options: [],
+ };
+ }
+ return { disabled: false, options };
+ } catch (error) {
+ return { disabled: true, placeholder: errorPlaceholder({ error, what: 'fields' }), options: [] };
+ }
+ },
+ });
+}
+
+function collectionIdText() {
+ return Property.ShortText({
+ displayName: 'Collection ID',
+ description: 'The collection ID, for example blog. Get it from List Collections.',
+ required: true,
+ });
+}
+
+function collectionForSchema({ schema, label }: { schema: string; label: string }) {
+ return Property.ShortText({
+ displayName: 'Collection ID',
+ description: `The ID of a collection that uses the ${label} schema. The built-in ${label} collection is called ${schema}. Find other IDs with List Collections.`,
+ required: true,
+ defaultValue: schema,
+ });
+}
+
+function objectIdText({
+ displayName = 'Object ID',
+ description = 'The object ID (its URL slug). Get it from Find Objects (by Collection ID).',
+ required = true,
+}: {
+ displayName?: string;
+ description?: string;
+ required?: boolean;
+} = {}) {
+ return Property.ShortText({ displayName, description, required });
+}
+
+async function objectOptions({
+ auth,
+ collection,
+}: {
+ auth: TotalCmsConnection;
+ collection: string;
+}): Promise<{ options: DropdownOption<string>[]; truncated: boolean }> {
+ const pages: DropdownOption<string>[][] = [];
+ let offset = 0;
+ let total = Infinity;
+ while (offset < total && offset < OBJECT_DROPDOWN_MAX) {
+ const page = await totalcmsApi.queryObjects({ auth, collection, limit: OBJECT_PAGE_SIZE, offset });
+ total = page.total;
+ pages.push(page.objects.map((item) => ({ label: objectLabel(item), value: String(item['id'] ?? '') })));
+ if (page.objects.length < OBJECT_PAGE_SIZE) {
+ break;
+ }
+ offset += OBJECT_PAGE_SIZE;
+ }
+ const options = pages.flat().filter((option) => option.value.length > 0);
+ return { options, truncated: total > options.length };
+}
+
+function objectLabel(item: Record<string, unknown>): string {
+ const id = String(item['id'] ?? '');
+ const labelKey = LABEL_KEYS.find((key) => typeof item[key] === 'string' && String(item[key]).trim().length > 0);
+ return labelKey ? `${String(item[labelKey]).trim()} (${id})` : id;
+}
+
+function errorPlaceholder({ error, what }: { error: unknown; what: string }): string {
+ const status = totalcmsHelpers.statusOf(error);
+ if (status === 401 || status === 403) {
+ return `Total CMS refused to list ${what}. Check the API key and its allowed endpoints.`;
+ }
+ if (status === 404) {
+ return `Could not find ${what}. Check the collection still exists.`;
+ }
+ return `Could not load ${what}. Check the connection and that the site is online.`;
+}
diff --git a/packages/pieces/community/totalcms/src/lib/common/shape.ts b/packages/pieces/community/totalcms/src/lib/common/shape.ts
new file mode 100644
index 00000000000..d0c51ba0759
--- /dev/null
+++ b/packages/pieces/community/totalcms/src/lib/common/shape.ts
@@ -0,0 +1,46 @@
+import { totalcmsHelpers } from './client';
+
+export const totalcmsShape = {
+ typed,
+ generic,
+ parseFields,
+ requireId,
+};
+
+function typed({ collection, object }: { collection: string; object: Record<string, unknown> }): Record<string, unknown> {
+ return { collection, ...object };
+}
+
+function generic({ collection, object }: { collection: string; object: Record<string, unknown> }) {
+ return { collection, id: String(object['id'] ?? ''), object };
+}
+
+function parseFields({ value, label }: { value: unknown; label: string }): Record<string, unknown> {
+ const parsed = typeof value === 'string' ? parseJson({ text: value, label }) : value;
+ if (!totalcmsHelpers.isRecord(parsed)) {
+ throw new Error(`${label} must be a JSON object, for example {"title": "Hello"}.`);
+ }
+ if (Object.keys(parsed).length === 0) {
+ throw new Error(`${label} is empty. Add at least one field.`);
+ }
+ return parsed;
+}
+
+function requireId({ value, label }: { value: unknown; label: string }): string {
+ if (typeof value !== 'string' && typeof value !== 'number') {
+ throw new Error(`${label} is required.`);
+ }
+ const text = String(value).trim();
+ if (text.length === 0) {
+ throw new Error(`${label} is required.`);
+ }
+ return text;
+}
+
+function parseJson({ text, label }: { text: string; label: string }): unknown {
+ try {
+ return JSON.parse(text);
+ } catch {
+ throw new Error(`${label} is not valid JSON.`);
+ }
+}
diff --git a/packages/pieces/community/totalcms/src/lib/common/update.ts b/packages/pieces/community/totalcms/src/lib/common/update.ts
new file mode 100644
index 00000000000..d908a732a1f
--- /dev/null
+++ b/packages/pieces/community/totalcms/src/lib/common/update.ts
@@ -0,0 +1,33 @@
+import { totalcmsApi, TotalCmsConnection } from './client';
+import { totalcmsShape } from './shape';
+
+export const totalcmsUpdate = {
+ run,
+};
+
+async function run({
+ auth,
+ collection,
+ id,
+ fields,
+}: {
+ auth: TotalCmsConnection;
+ collection: string;
+ id: string;
+ fields: unknown;
+}) {
+ const parsed = totalcmsShape.parseFields({ value: fields, label: 'Fields to Change' });
+ if ('id' in parsed && String(parsed['id']).trim() !== id) {
+ throw new Error('The object ID cannot be changed here. Use Duplicate Object to copy it under a new ID, then delete the old one.');
+ }
+ const rest = Object.fromEntries(Object.entries(parsed).filter(([key]) => key !== 'id'));
+ if (Object.keys(rest).length === 0) {
+ throw new Error('Fields to Change is empty. Add at least one field other than id.');
+ }
+ const existing = await totalcmsApi.findObject({ auth, collection, id });
+ if (!existing) {
+ throw new Error(`Object "${id}" was not found in collection "${collection}". Use Create Object to add it.`);
+ }
+ const object = await totalcmsApi.patchObject({ auth, collection, id, fields: rest });
+ return totalcmsShape.generic({ collection, object });
+}
diff --git a/packages/pieces/community/totalcms/src/lib/common/upload.ts b/packages/pieces/community/totalcms/src/lib/common/upload.ts
new file mode 100644
index 00000000000..1131095dc42
--- /dev/null
+++ b/packages/pieces/community/totalcms/src/lib/common/upload.ts
@@ -0,0 +1,92 @@
+import { Property } from '@activepieces/pieces-framework';
+import { totalcmsApi, totalcmsHelpers, TotalCmsConnection } from './client';
+
+export const totalcmsUpload = {
+ fileProps,
+ altProp,
+ save,
+};
+
+function fileProps({ fileLabel = 'File' }: { fileLabel?: string } = {}) {
+ return {
+ file: Property.File({
+ displayName: fileLabel,
+ description: `The ${fileLabel.toLowerCase()} to upload. Leave empty to use ${fileLabel} URL instead.`,
+ required: false,
+ }),
+ file_url: Property.ShortText({
+ displayName: `${fileLabel} URL`,
+ description: `A public link to the ${fileLabel.toLowerCase()}, ending in its file name with extension (for example https://example.com/photo.jpg). Your Total CMS site downloads it. Use either this or ${fileLabel}.`,
+ required: false,
+ }),
+ };
+}
+
+function altProp() {
+ return Property.ShortText({
+ displayName: 'Alt Text',
+ description: 'Describes the image for screen readers and search engines.',
+ required: false,
+ });
+}
+
+async function save({
+ auth,
+ collection,
+ id,
+ property,
+ file,
+ fileUrl,
+ alt,
+ folder,
+ multiple,
+}: {
+ auth: TotalCmsConnection;
+ collection: string;
+ id: string;
+ property: string;
+ file: unknown;
+ fileUrl: unknown;
+ alt?: string;
+ folder?: string;
+ multiple: boolean;
+}): Promise<SaveResult> {
+ const source = totalcmsHelpers.parseFileSource({ file, url: fileUrl });
+ const uploaded = await totalcmsApi.uploadFile({ auth, collection, id, property, source, folder });
+ const altText = alt?.trim();
+ if (!altText) {
+ return { object: uploaded.object, preview_url: uploaded.preview_url, warning: null };
+ }
+ const fileName = multiple ? lastItemName({ value: uploaded.object[property] }) : undefined;
+ if (multiple && !fileName) {
+ return {
+ object: uploaded.object,
+ preview_url: uploaded.preview_url,
+ warning: 'The image was uploaded, but its alt text was not saved because the new image could not be identified.',
+ };
+ }
+ try {
+ const object = await totalcmsApi.patchFileMeta({ auth, collection, id, property, fileName, fields: { alt: altText } });
+ return { object, preview_url: uploaded.preview_url, warning: null };
+ } catch (error) {
+ const reason = error instanceof Error ? error.message : String(error);
+ return {
+ object: uploaded.object,
+ preview_url: uploaded.preview_url,
+ warning: `The image was uploaded, but its alt text was not saved: ${reason}`,
+ };
+ }
+}
+
+function lastItemName({ value }: { value: unknown }): string | undefined {
+ if (!Array.isArray(value) || value.length === 0) {
+ return undefined;
+ }
+ const last: unknown = value[value.length - 1];
+ if (!totalcmsHelpers.isRecord(last) || typeof last['name'] !== 'string' || last['name'].length === 0) {
+ return undefined;
+ }
+ return last['name'];
+}
+
+type SaveResult = { object: Record<string, unknown>; preview_url: string | null; warning: string | null };
diff --git a/packages/pieces/community/totalcms/src/lib/output-schemas.ts b/packages/pieces/community/totalcms/src/lib/output-schemas.ts
new file mode 100644
index 00000000000..46885d570e3
--- /dev/null
+++ b/packages/pieces/community/totalcms/src/lib/output-schemas.ts
@@ -0,0 +1,222 @@
+import { OutputSchema } from '@activepieces/pieces-framework';
+
+const imageFields: OutputSchema['fields'] = [
+ { key: 'name', label: 'File Name' },
+ { key: 'alt', label: 'Alt Text' },
+ { key: 'mime', label: 'MIME Type' },
+ { key: 'size', label: 'Size', format: 'filesize' },
+ { key: 'width', label: 'Width', format: 'number' },
+ { key: 'height', label: 'Height', format: 'number' },
+ { key: 'uploadDate', label: 'Uploaded At', format: 'datetime' },
+];
+
+const fileFields: OutputSchema['fields'] = [
+ { key: 'name', label: 'File Name' },
+ { key: 'mime', label: 'MIME Type' },
+ { key: 'ext', label: 'Extension' },
+ { key: 'size', label: 'Size', format: 'filesize' },
+ { key: 'uploadDate', label: 'Uploaded At', format: 'datetime' },
+];
+
+const warningField: OutputSchema['fields'][number] = {
+ key: 'warning',
+ label: 'Warning',
+ description: 'Set when the file was uploaded but a follow-up change (such as alt text) failed.',
+};
+
+const collectionField: OutputSchema['fields'][number] = {
+ key: 'collection',
+ label: 'Collection',
+ description: 'The collection ID the object belongs to.',
+};
+
+const objectIdField: OutputSchema['fields'][number] = {
+ key: 'id',
+ label: 'Object ID',
+ description: 'The object ID (URL slug). Use it to read or change this object in a later step.',
+};
+
+const blogPostFields: OutputSchema['fields'] = [
+ collectionField,
+ { key: 'id', label: 'Post ID', description: 'The post ID (URL slug).' },
+ { key: 'title', label: 'Title' },
+ { key: 'date', label: 'Date', format: 'datetime' },
+ { key: 'author', label: 'Author' },
+ { key: 'draft', label: 'Draft', format: 'boolean' },
+ { key: 'featured', label: 'Featured', format: 'boolean' },
+ { key: 'summary', label: 'Summary', format: 'html' },
+ { key: 'content', label: 'Content', format: 'html' },
+ { key: 'extra', label: 'Extra Content', format: 'html' },
+ { key: 'media', label: 'Media URL', format: 'url' },
+ { key: 'categories', label: 'Categories' },
+ { key: 'tags', label: 'Tags' },
+ { key: 'image', label: 'Image', children: imageFields },
+ { key: 'gallery', label: 'Gallery', labelKey: 'name', listItems: imageFields },
+ { key: 'created', label: 'Created At', format: 'datetime' },
+ { key: 'updated', label: 'Updated At', format: 'datetime' },
+];
+
+const genericObjectFields: OutputSchema['fields'] = [
+ collectionField,
+ objectIdField,
+ {
+ key: 'object',
+ label: 'Fields',
+ dynamicKey: true,
+ description: 'All fields of the object, keyed by field name. The names depend on the collection schema.',
+ },
+];
+
+const previewField: OutputSchema['fields'][number] = {
+ key: 'preview_url',
+ label: 'Preview URL',
+ format: 'url',
+ description: 'A resized preview of the uploaded image, when Total CMS returns one.',
+};
+
+export const totalcmsOutputSchemas = {
+ blogPost: { fields: blogPostFields },
+ savedBlogPost: {
+ fields: [
+ { key: 'result', label: 'Result', description: 'created when a new post was made, updated when an existing post was changed.' },
+ ...blogPostFields,
+ ],
+ },
+ blogPostUpload: { fields: [...blogPostFields, previewField, warningField] },
+ object: { fields: genericObjectFields },
+ text: { fields: [collectionField, objectIdField, { key: 'text', label: 'Text' }] },
+ toggle: { fields: [collectionField, objectIdField, { key: 'status', label: 'On', format: 'boolean' }] },
+ date: { fields: [collectionField, objectIdField, { key: 'date', label: 'Date', format: 'datetime' }] },
+ image: {
+ fields: [collectionField, objectIdField, { key: 'image', label: 'Image', children: imageFields }, previewField, warningField],
+ },
+ gallery: {
+ fields: [
+ collectionField,
+ objectIdField,
+ { key: 'gallery', label: 'Gallery Images', labelKey: 'name', listItems: imageFields },
+ previewField,
+ warningField,
+ ],
+ },
+ file: {
+ fields: [collectionField, objectIdField, { key: 'file', label: 'File', children: fileFields }],
+ },
+ depot: {
+ fields: [
+ collectionField,
+ objectIdField,
+ {
+ key: 'depot',
+ label: 'Depot',
+ children: [
+ {
+ key: 'files',
+ label: 'Files and Folders',
+ labelKey: 'name',
+ listItems: [
+ ...fileFields,
+ { key: 'files', label: 'Folder Contents', description: 'Files inside this entry when it is a folder.' },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ video: {
+ fields: [
+ collectionField,
+ objectIdField,
+ {
+ key: 'video',
+ label: 'Video',
+ children: [
+ { key: 'url', label: 'Video URL', format: 'url' },
+ { key: 'provider', label: 'Provider' },
+ { key: 'videoId', label: 'Provider Video ID' },
+ { key: 'thumbnail', label: 'Thumbnail', format: 'image' },
+ { key: 'title', label: 'Title' },
+ { key: 'aspectRatio', label: 'Aspect Ratio' },
+ ],
+ },
+ ],
+ },
+ upload: {
+ fields: [
+ ...genericObjectFields,
+ { key: 'field', label: 'Field', description: 'The field the file was saved to.' },
+ previewField,
+ ],
+ },
+ collections: {
+ fields: [
+ {
+ key: 'collections',
+ label: 'Collections',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Collection ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'schema', label: 'Schema' },
+ { key: 'description', label: 'Description' },
+ { key: 'object_count', label: 'Objects', format: 'number' },
+ { key: 'label_singular', label: 'Singular Label' },
+ { key: 'label_plural', label: 'Plural Label' },
+ { key: 'singleton', label: 'Single Object', format: 'boolean' },
+ { key: 'last_updated', label: 'Last Updated', format: 'datetime' },
+ ],
+ },
+ { key: 'count', label: 'Count', format: 'number' },
+ ],
+ },
+ schema: {
+ fields: [
+ collectionField,
+ { key: 'schema', label: 'Schema ID' },
+ { key: 'description', label: 'Description' },
+ {
+ key: 'fields',
+ label: 'Fields',
+ labelKey: 'key',
+ listItems: [
+ { key: 'key', label: 'Field Name' },
+ { key: 'label', label: 'Label' },
+ { key: 'field_type', label: 'Field Type' },
+ { key: 'data_type', label: 'Data Type' },
+ { key: 'required', label: 'Required', format: 'boolean' },
+ { key: 'in_index', label: 'Returned by Find Objects', format: 'boolean' },
+ { key: 'help', label: 'Help Text' },
+ ],
+ },
+ ],
+ },
+ find: {
+ fields: [
+ {
+ key: 'objects',
+ label: 'Objects',
+ description: 'Matching objects with their index fields. Long fields such as blog content are not included; use Get Object for those.',
+ },
+ { key: 'count', label: 'Returned', format: 'number' },
+ { key: 'total', label: 'Total Matches', format: 'number' },
+ { key: 'offset', label: 'Offset', format: 'number' },
+ { key: 'has_more', label: 'Has More', format: 'boolean' },
+ { key: 'next_offset', label: 'Next Offset', format: 'number', description: 'Pass this as Offset to get the next page. Empty when there are no more.' },
+ ],
+ },
+ number: {
+ fields: [
+ collectionField,
+ objectIdField,
+ { key: 'field', label: 'Field' },
+ { key: 'value', label: 'New Value', format: 'number' },
+ ],
+ },
+ deleted: {
+ fields: [
+ { key: 'deleted', label: 'Deleted', format: 'boolean' },
+ collectionField,
+ objectIdField,
+ ],
+ },
+} satisfies Record<string, OutputSchema>;
diff --git a/packages/pieces/community/totalcms/src/lib/triggers/new-blog-post.ts b/packages/pieces/community/totalcms/src/lib/triggers/new-blog-post.ts
index 307094ad8e5..816cf746acb 100644
--- a/packages/pieces/community/totalcms/src/lib/triggers/new-blog-post.ts
+++ b/packages/pieces/community/totalcms/src/lib/triggers/new-blog-post.ts
@@ -1,79 +1,63 @@
-import {
- TriggerStrategy,
- createTrigger,
- Property,
- PiecePropValueSchema,
- AppConnectionValueForAuthProperty,
-} from '@activepieces/pieces-framework';
-import {
- DedupeStrategy,
- Polling,
- pollingHelper,
-} from '@activepieces/pieces-common';
-import { TotalCMSAuthType, cmsAuth } from '../auth';
-import { getContent } from '../api';
-
-const polling: Polling<
- AppConnectionValueForAuthProperty<typeof cmsAuth>,
- { slug: string }
-> = {
- strategy: DedupeStrategy.LAST_ITEM,
- items: async ({ auth, propsValue }) => {
- const slug = propsValue.slug;
- const posts = await getContent(auth, 'blog', slug);
-
- return posts.data.map((post: { permalink: string }) => ({
- id: post.permalink,
- data: post,
- }));
- },
-};
+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';
+import { cmsAuth } from '../auth';
+import { totalcmsPolling } from '../common/polling';
+import { totalcmsProps } from '../common/props';
+import { totalcmsOutputSchemas } from '../output-schemas';
+import { totalcmsSamples } from './samples';
export const newBlogPost = createTrigger({
+ auth: cmsAuth,
name: 'new_blog_post',
classification: 'READ',
displayName: 'New Blog Post',
- description: 'Triggers when a new blog post is published',
+ description: 'Triggers when a new post is added to a blog.',
aiMetadata: {
- description: 'Fires when a new blog post appears in the specified Total CMS blog (identified by its CMS ID). Polls the blog and emits one event per newly published post, deduplicated by permalink.',
+ description:
+ 'Fires once for each new post added to a Total CMS blog collection, with the full post (content included). Drafts are skipped unless Include Drafts is on; a post created as a draft and published later is not reported again.',
},
type: TriggerStrategy.POLLING,
props: {
- slug: Property.ShortText({
- displayName: 'CMS ID',
- description: 'The CMS ID of the content to retrieve',
- required: true,
+ collection: totalcmsProps.collection({ displayName: 'Blog', description: 'The blog collection to watch.', schemas: ['blog'] }),
+ include_drafts: Property.Checkbox({
+ displayName: 'Include Drafts',
+ description: 'Also trigger for posts saved as drafts.',
+ required: false,
+ defaultValue: false,
}),
},
- sampleData: {},
- onEnable: async (context) => {
- await pollingHelper.onEnable(polling, {
- auth: context.auth as TotalCMSAuthType,
+ sampleData: totalcmsSamples.blogPost,
+ outputSchema: totalcmsOutputSchemas.blogPost,
+ async onEnable(context) {
+ await totalcmsPolling.enable({
+ auth: context.auth,
store: context.store,
- propsValue: context.propsValue,
+ collection: context.propsValue.collection,
+ field: 'created',
+ isRepublish: context.isRepublish,
});
},
- onDisable: async (context) => {
- await pollingHelper.onDisable(polling, {
- auth: context.auth as TotalCMSAuthType,
- store: context.store,
- propsValue: context.propsValue,
- });
+ async onDisable(context) {
+ await totalcmsPolling.disable({ store: context.store });
},
- run: async (context) => {
- return await pollingHelper.poll(polling, {
- auth: context.auth as TotalCMSAuthType,
+ async run(context) {
+ const posts = await totalcmsPolling.poll({
+ auth: context.auth,
store: context.store,
- propsValue: context.propsValue,
- files: context.files,
+ collection: context.propsValue.collection,
+ field: 'created',
});
+ return posts.filter((post) => keepPost({ post, includeDrafts: context.propsValue.include_drafts === true }));
},
- test: async (context) => {
- return await pollingHelper.test(polling, {
- auth: context.auth as TotalCMSAuthType,
- store: context.store,
- propsValue: context.propsValue,
- files: context.files,
+ async test(context) {
+ return totalcmsPolling.sample({
+ auth: context.auth,
+ collection: context.propsValue.collection,
+ field: 'created',
+ keep: (post) => keepPost({ post, includeDrafts: context.propsValue.include_drafts === true }),
});
},
});
+
+function keepPost({ post, includeDrafts }: { post: Record<string, unknown>; includeDrafts: boolean }): boolean {
+ return includeDrafts || post['draft'] !== true;
+}
diff --git a/packages/pieces/community/totalcms/src/lib/triggers/new-object.ts b/packages/pieces/community/totalcms/src/lib/triggers/new-object.ts
new file mode 100644
index 00000000000..3a6d349ebe2
--- /dev/null
+++ b/packages/pieces/community/totalcms/src/lib/triggers/new-object.ts
@@ -0,0 +1,52 @@
+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
+import { cmsAuth } from '../auth';
+import { totalcmsPolling } from '../common/polling';
+import { totalcmsProps } from '../common/props';
+import { totalcmsSamples } from './samples';
+
+export const newObjectTrigger = createTrigger({
+ auth: cmsAuth,
+ name: 'new_object',
+ classification: 'READ',
+ displayName: 'New Object',
+ description: 'Triggers when an object is added to a collection.',
+ aiMetadata: {
+ description:
+ 'Fires once for each new object added to a Total CMS collection, with all its fields. Works only for collections whose schema records a created date (blog, feed and most custom schemas).',
+ },
+ type: TriggerStrategy.POLLING,
+ props: {
+ collection: totalcmsProps.collection({
+ description: 'The collection to watch. Its schema must have a "created" date field.',
+ }),
+ },
+ sampleData: totalcmsSamples.object,
+ async onEnable(context) {
+ await totalcmsPolling.enable({
+ auth: context.auth,
+ store: context.store,
+ collection: context.propsValue.collection,
+ field: 'created',
+ isRepublish: context.isRepublish,
+ });
+ },
+ async onDisable(context) {
+ await totalcmsPolling.disable({ store: context.store });
+ },
+ async run(context) {
+ return totalcmsPolling.poll({
+ auth: context.auth,
+ store: context.store,
+ collection: context.propsValue.collection,
+ field: 'created',
+ });
+ },
+ async test(context) {
+ return totalcmsPolling.sample({
+ auth: context.auth,
+ collection: context.propsValue.collection,
+ field: 'created',
+ keep: () => true,
+ });
+ },
+});
diff --git a/packages/pieces/community/totalcms/src/lib/triggers/samples.ts b/packages/pieces/community/totalcms/src/lib/triggers/samples.ts
new file mode 100644
index 00000000000..e2a90c7c382
--- /dev/null
+++ b/packages/pieces/community/totalcms/src/lib/triggers/samples.ts
@@ -0,0 +1,46 @@
+const image = {
+ alt: '',
+ exif: { nodata: '' },
+ featured: false,
+ focalpoint: { x: 50, y: 50 },
+ hash: '0b9e9d46',
+ height: 630,
+ link: '',
+ mime: 'image/jpeg',
+ name: 'cover.jpg',
+ palette: [],
+ size: 84512,
+ tags: [],
+ uploadDate: '2026-10-07T11:40:26+00:00',
+ width: 1200,
+};
+
+export const totalcmsSamples = {
+ blogPost: {
+ collection: 'blog',
+ id: 'hello-from-activepieces',
+ draft: false,
+ featured: false,
+ title: 'Hello from Activepieces',
+ date: '2026-10-07T11:40:26+00:00',
+ author: 'Jane Doe',
+ summary: '<p>A short summary.</p>',
+ media: '',
+ content: '<p>The full post content.</p>',
+ extra: '',
+ categories: ['News'],
+ tags: ['automation'],
+ image,
+ gallery: [],
+ updated: '2026-10-07T11:40:26+00:00',
+ created: '2026-10-07T11:40:26+00:00',
+ },
+ object: {
+ collection: 'blog',
+ id: 'hello-from-activepieces',
+ title: 'Hello from Activepieces',
+ draft: false,
+ updated: '2026-10-07T12:10:00+00:00',
+ created: '2026-10-07T11:40:26+00:00',
+ },
+};
diff --git a/packages/pieces/community/totalcms/src/lib/triggers/updated-object.ts b/packages/pieces/community/totalcms/src/lib/triggers/updated-object.ts
new file mode 100644
index 00000000000..21826e2c775
--- /dev/null
+++ b/packages/pieces/community/totalcms/src/lib/triggers/updated-object.ts
@@ -0,0 +1,63 @@
+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';
+import { cmsAuth } from '../auth';
+import { totalcmsPolling } from '../common/polling';
+import { totalcmsProps } from '../common/props';
+import { totalcmsSamples } from './samples';
+
+export const updatedObjectTrigger = createTrigger({
+ auth: cmsAuth,
+ name: 'updated_object',
+ classification: 'READ',
+ displayName: 'Updated Object',
+ description: 'Triggers when an object in a collection is changed.',
+ aiMetadata: {
+ description:
+ 'Fires when an object in a Total CMS collection is saved with changes, once per object per check, with its current fields. Several saves between checks give one event. New objects are skipped unless Include New Objects is on. Needs a schema with an updated date field.',
+ },
+ type: TriggerStrategy.POLLING,
+ props: {
+ collection: totalcmsProps.collection({
+ description: 'The collection to watch. Its schema must have an "updated" date field.',
+ }),
+ include_new: Property.Checkbox({
+ displayName: 'Include New Objects',
+ description: 'Also trigger when an object is created.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ sampleData: totalcmsSamples.object,
+ async onEnable(context) {
+ await totalcmsPolling.enable({
+ auth: context.auth,
+ store: context.store,
+ collection: context.propsValue.collection,
+ field: 'updated',
+ isRepublish: context.isRepublish,
+ });
+ },
+ async onDisable(context) {
+ await totalcmsPolling.disable({ store: context.store });
+ },
+ async run(context) {
+ const objects = await totalcmsPolling.poll({
+ auth: context.auth,
+ store: context.store,
+ collection: context.propsValue.collection,
+ field: 'updated',
+ });
+ return objects.filter((object) => keepObject({ object, includeNew: context.propsValue.include_new === true }));
+ },
+ async test(context) {
+ return totalcmsPolling.sample({
+ auth: context.auth,
+ collection: context.propsValue.collection,
+ field: 'updated',
+ keep: (object) => keepObject({ object, includeNew: context.propsValue.include_new === true }),
+ });
+ },
+});
+
+function keepObject({ object, includeNew }: { object: Record<string, unknown>; includeNew: boolean }): boolean {
+ return includeNew || object['created'] === undefined || object['created'] !== object['updated'];
+}
diff --git a/packages/pieces/community/totalcms/test/actions.test.ts b/packages/pieces/community/totalcms/test/actions.test.ts
new file mode 100644
index 00000000000..33541d8ad76
--- /dev/null
+++ b/packages/pieces/community/totalcms/test/actions.test.ts
@@ -0,0 +1,192 @@
+import { PropertyType } from '@activepieces/pieces-framework';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { adjustNumberByIdAction } from '../src/lib/actions/ai/adjust-number-by-id';
+import { findObjectsByIdAction } from '../src/lib/actions/ai/find-objects-by-id';
+import { updateObjectByIdAction } from '../src/lib/actions/ai/update-object-by-id';
+import { uploadFileByIdAction } from '../src/lib/actions/ai/upload-file-by-id';
+import { deleteObjectAction } from '../src/lib/actions/delete-object';
+import { saveBlogPostAction } from '../src/lib/actions/save-blog-post';
+import { saveDateAction } from '../src/lib/actions/save-date';
+import { saveGalleryAction } from '../src/lib/actions/save-gallery';
+import { saveImageAction } from '../src/lib/actions/save-image';
+import { saveTextAction } from '../src/lib/actions/save-text';
+import { saveToggleAction } from '../src/lib/actions/save-toggle';
+import { context, stubFetch } from './helpers';
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+const file = { filename: 'photo.png', extension: 'png', data: Buffer.from('png-bytes'), base64: Buffer.from('png-bytes').toString('base64') };
+
+describe('typed save actions', () => {
+ test('save_text upserts with PUT', async () => {
+ const seen = stubFetch(() => ({ body: { data: { id: 'headline', text: 'Hello' } } }));
+ const result = await saveTextAction.run(context({ collection: 'text', object_id: 'headline', text: 'Hello' }));
+ expect(seen[0].method).toBe('PUT');
+ expect(seen[0].json).toEqual({ text: 'Hello', id: 'headline' });
+ expect(result).toEqual({ collection: 'text', id: 'headline', text: 'Hello' });
+ });
+
+ test('save_toggle sends a boolean status', async () => {
+ const seen = stubFetch(() => ({ body: { data: { id: 'banner', status: false } } }));
+ await saveToggleAction.run(context({ collection: 'toggle', object_id: 'banner', status: false }));
+ expect(seen[0].json).toEqual({ status: false, id: 'banner' });
+ });
+
+ test('save_date validates and normalises the date', async () => {
+ const seen = stubFetch(() => ({ body: { data: { id: 'launch', date: '2026-12-31T18:00:00+00:00' } } }));
+ await saveDateAction.run(context({ collection: 'date', object_id: 'launch', date: '2026-12-31T18:00:00Z' }));
+ expect(seen[0].json).toEqual({ date: '2026-12-31T18:00:00.000Z', id: 'launch' });
+ await expect(saveDateAction.run(context({ collection: 'date', object_id: 'launch', date: 'soon' }))).rejects.toThrow('not a valid date');
+ expect(seen).toHaveLength(1);
+ });
+});
+
+describe('save_blog_post', () => {
+ test('updates only the given fields of an existing post', async () => {
+ const seen = stubFetch((request) =>
+ request.method === 'GET' ? { body: { data: { id: 'hello', title: 'Hello' } } } : { body: { data: { id: 'hello', title: 'Hello', summary: 'New' } } },
+ );
+ const result = await saveBlogPostAction.run(context({ collection: 'blog', post_id: 'hello', summary: 'New', categories: '', tags: undefined }));
+ expect(seen.map((request) => request.method)).toEqual(['GET', 'PATCH']);
+ expect(seen[1].json).toEqual({ summary: 'New' });
+ expect(result).toMatchObject({ result: 'updated', collection: 'blog', id: 'hello' });
+ });
+
+ test('creates a new post with the given id, published by default', async () => {
+ const seen = stubFetch((request) =>
+ request.method === 'GET' ? { status: 404, body: { error: { message: 'Not Found' } } } : { body: { data: { id: 'new-post', title: 'New' } } },
+ );
+ const result = await saveBlogPostAction.run(
+ context({ collection: 'blog', post_id: 'new-post', title: 'New', categories: 'News, Tech', featured: 'yes', draft: 'draft' }),
+ );
+ expect(seen[1].method).toBe('POST');
+ expect(seen[1].path).toBe('/api/collections/blog');
+ expect(seen[1].json).toEqual({ id: 'new-post', draft: true, title: 'New', categories: ['News', 'Tech'], featured: true });
+ expect(result).toMatchObject({ result: 'created' });
+ });
+
+ test('requires a title to create', async () => {
+ const seen = stubFetch(() => ({ status: 404, body: {} }));
+ await expect(saveBlogPostAction.run(context({ collection: 'blog', post_id: 'x', summary: 's' }))).rejects.toThrow('Title is required');
+ expect(seen.filter((request) => request.method !== 'GET')).toHaveLength(0);
+ });
+
+ test('without a post id it creates and lets Total CMS make the slug', async () => {
+ const seen = stubFetch(() => ({ body: { data: { id: 'my-title', title: 'My Title' } } }));
+ await saveBlogPostAction.run(context({ collection: 'blog', title: 'My Title' }));
+ expect(seen).toHaveLength(1);
+ expect(seen[0].json).toEqual({ draft: false, title: 'My Title' });
+ });
+
+ test('accepts categories and tags passed as a string expression', async () => {
+ const seen = stubFetch(() => ({ body: { data: { id: 'my-title', title: 'My Title' } } }));
+ await saveBlogPostAction.run(context({ collection: 'blog', title: 'My Title', categories: '["News","Tech"]', tags: 'a, b' }));
+ expect(seen[0].json).toEqual({ draft: false, title: 'My Title', categories: ['News', 'Tech'], tags: ['a', 'b'] });
+ });
+
+ test('categories and tags are text inputs, so the engine accepts typed and mapped values', () => {
+ expect(saveBlogPostAction.props.categories.type).toBe(PropertyType.SHORT_TEXT);
+ expect(saveBlogPostAction.props.tags.type).toBe(PropertyType.SHORT_TEXT);
+ });
+
+ test('keeps commas inside list entries and splits only plain text', async () => {
+ const seen = stubFetch(() => ({ body: { data: { id: 'my-title', title: 'My Title' } } }));
+ await saveBlogPostAction.run(context({ collection: 'blog', title: 'My Title', categories: '["News, Events","Tech"]', tags: 'one, two ,' }));
+ await saveBlogPostAction.run(context({ collection: 'blog', title: 'My Title', categories: ['News, Events'] }));
+ expect(seen[0].json).toEqual({ draft: false, title: 'My Title', categories: ['News, Events', 'Tech'], tags: ['one', 'two'] });
+ expect(seen[1].json).toEqual({ draft: false, title: 'My Title', categories: ['News, Events'] });
+ });
+});
+
+describe('uploads', () => {
+ test('save_image sends multipart under the field name and saves alt text', async () => {
+ const seen = stubFetch((request) =>
+ request.method === 'POST'
+ ? { body: { data: { id: 'hero', image: { name: 'photo.png', alt: '' } }, meta: { preview: '/imageworks/image/hero/image.png?w=600' } } }
+ : { body: { data: { id: 'hero', image: { name: 'photo.png', alt: 'Sunset' } } } },
+ );
+ const result = await saveImageAction.run(context({ collection: 'image', object_id: 'hero', file, alt: 'Sunset' }));
+ expect(seen[0].path).toBe('/api/collections/image/hero/image');
+ expect(seen[0].headers.get('content-type')).toContain('multipart/form-data');
+ expect(seen[0].text).toContain('name="image"; filename="photo.png"');
+ expect(seen[1].method).toBe('PATCH');
+ expect(seen[1].path).toBe('/api/collections/image/hero/image');
+ expect(seen[1].json).toEqual({ alt: 'Sunset' });
+ expect(result).toMatchObject({ preview_url: 'https://cms.example.com/imageworks/image/hero/image.png?w=600', warning: null });
+ });
+
+ test('save_gallery sets alt on the newly added image and reports alt failures as a warning', async () => {
+ const seen = stubFetch((request) =>
+ request.method === 'POST'
+ ? { body: { data: { id: 'g', gallery: [{ name: 'old.png' }, { name: 'photo-2.png' }] } } }
+ : { status: 500, body: { error: { message: 'disk full' } } },
+ );
+ const result = await saveGalleryAction.run(context({ collection: 'gallery', object_id: 'g', file, alt: 'Alt' }));
+ expect(seen[1].path).toBe('/api/collections/gallery/g/gallery/photo-2.png');
+ expect(result).toMatchObject({ id: 'g', warning: expect.stringContaining('disk full') });
+ });
+
+ test('upload by URL sends JSON and a depot folder targets the last folder segment', async () => {
+ const seen = stubFetch(() => ({ body: { data: { id: 'docs', depot: { files: [] } } } }));
+ await uploadFileByIdAction.run(
+ context({ collection: 'depot', object_id: 'docs', field: 'depot', file_url: 'https://files.example.com/a.pdf', folder: '2026/reports' }),
+ );
+ expect(seen[0].path).toBe('/api/collections/depot/docs/depot/2026/reports');
+ expect(seen[0].json).toEqual({ reports: 'https://files.example.com/a.pdf' });
+ });
+
+ test('refuses both a file and a URL, or neither, and folder traversal', async () => {
+ const seen = stubFetch(() => ({ body: {} }));
+ await expect(uploadFileByIdAction.run(context({ collection: 'c', object_id: 'o', field: 'f', file, file_url: 'https://x.io/a' }))).rejects.toThrow('not both');
+ await expect(uploadFileByIdAction.run(context({ collection: 'c', object_id: 'o', field: 'f' }))).rejects.toThrow('Provide a file');
+ await expect(uploadFileByIdAction.run(context({ collection: 'c', object_id: 'o', field: 'f', file_url: 'file:///etc/passwd' }))).rejects.toThrow('http');
+ await expect(uploadFileByIdAction.run(context({ collection: 'c', object_id: 'o', field: 'f', file, folder: '../x' }))).rejects.toThrow('not valid');
+ expect(seen).toHaveLength(0);
+ });
+});
+
+describe('generic object actions', () => {
+ test('find_objects_by_id validates limit and reports paging', async () => {
+ const seen = stubFetch(() => ({ body: { data: [{ id: 'a' }, { id: 'b' }], meta: { pagination: { total: 5 } } } }));
+ const result = await findObjectsByIdAction.run(context({ collection: 'blog', limit: 2, offset: 2, sort: '-created' }));
+ expect(result).toMatchObject({ count: 2, total: 5, has_more: true, next_offset: 4 });
+ await expect(findObjectsByIdAction.run(context({ collection: 'blog', limit: 500 }))).rejects.toThrow('from 1 to 100');
+ expect(seen).toHaveLength(1);
+ });
+
+ test('update_object_by_id patches existing objects and refuses id changes', async () => {
+ const seen = stubFetch((request) => (request.method === 'GET' ? { body: { data: { id: 'a' } } } : { body: { data: { id: 'a', title: 'T' } } }));
+ const result = await updateObjectByIdAction.run(context({ collection: 'blog', object_id: 'a', fields: '{"title":"T","id":"a"}' }));
+ expect(seen[1].method).toBe('PATCH');
+ expect(seen[1].json).toEqual({ title: 'T' });
+ expect(result).toEqual({ collection: 'blog', id: 'a', object: { id: 'a', title: 'T' } });
+ await expect(updateObjectByIdAction.run(context({ collection: 'blog', object_id: 'a', fields: { id: 'b' } }))).rejects.toThrow('cannot be changed');
+ await expect(updateObjectByIdAction.run(context({ collection: 'blog', object_id: 'a', fields: {} }))).rejects.toThrow('empty');
+ });
+
+ test('update_object_by_id fails clearly when the object is missing', async () => {
+ const seen = stubFetch(() => ({ status: 404, body: { error: { message: 'Not Found' } } }));
+ await expect(updateObjectByIdAction.run(context({ collection: 'blog', object_id: 'gone', fields: { title: 'x' } }))).rejects.toThrow('was not found');
+ expect(seen.filter((request) => request.method === 'PATCH')).toHaveLength(0);
+ });
+
+ test('adjust_number_by_id calls increment with the amount and rejects non-positive amounts', async () => {
+ const seen = stubFetch(() => ({ body: { property: 'views', value: 12 } }));
+ const result = await adjustNumberByIdAction.run(context({ collection: 'stats', object_id: 'home', field: 'views', direction: 'increment', amount: 2 }));
+ expect(seen[0].method).toBe('POST');
+ expect(seen[0].path).toBe('/api/collections/stats/home/views/increment/2');
+ expect(result).toEqual({ collection: 'stats', id: 'home', field: 'views', value: 12 });
+ await expect(adjustNumberByIdAction.run(context({ collection: 'stats', object_id: 'home', field: 'views', direction: 'increment', amount: 0 }))).rejects.toThrow('greater than 0');
+ });
+
+ test('delete_object refuses a missing object and deletes an existing one', async () => {
+ const seen = stubFetch((request) => (request.method === 'GET' ? { body: { data: { id: 'a' } } } : { body: { deleted: true } }));
+ const result = await deleteObjectAction.run(context({ collection: 'blog', object_id: 'a' }));
+ expect(seen.map((request) => request.method)).toEqual(['GET', 'DELETE']);
+ expect(result).toEqual({ deleted: true, collection: 'blog', id: 'a' });
+ stubFetch(() => ({ status: 404, body: {} }));
+ await expect(deleteObjectAction.run(context({ collection: 'blog', object_id: 'a' }))).rejects.toThrow('not found');
+ });
+});
diff --git a/packages/pieces/community/totalcms/test/auth.test.ts b/packages/pieces/community/totalcms/test/auth.test.ts
new file mode 100644
index 00000000000..570f2c7bc9b
--- /dev/null
+++ b/packages/pieces/community/totalcms/test/auth.test.ts
@@ -0,0 +1,28 @@
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { cmsAuth } from '../src/lib/auth';
+import { stubFetch } from './helpers';
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+const validate = (auth: { domain: string; apiKey: string }) => cmsAuth.validate!({ auth, server: { apiUrl: '', publicUrl: '', token: '' } });
+
+describe('auth validate', () => {
+ test('accepts a Total CMS 3 site', async () => {
+ const seen = stubFetch(() => ({ body: { data: [] } }));
+ expect(await validate({ domain: 'https://cms.example.com/', apiKey: ' tcms_x ' })).toEqual({ valid: true });
+ expect(seen[0].url).toBe('https://cms.example.com/api/collections');
+ expect(seen[0].headers.get('x-api-key')).toBe('tcms_x');
+ });
+
+ test('rejects a bad key, a redirect, a non-CMS page and a bad URL', async () => {
+ stubFetch(() => ({ status: 401, body: { error: { message: 'Unauthorized' } } }));
+ expect(await validate({ domain: 'https://cms.example.com', apiKey: 'bad' })).toMatchObject({ valid: false, error: expect.stringContaining('API key') });
+ stubFetch(() => ({ status: 301, body: {}, headers: { location: 'https://www.cms.example.com/api/collections' } }));
+ expect(await validate({ domain: 'https://cms.example.com', apiKey: 'k' })).toMatchObject({ valid: false, error: expect.stringContaining('redirects') });
+ stubFetch(() => ({ text: '<html>hello</html>' }));
+ expect(await validate({ domain: 'https://cms.example.com', apiKey: 'k' })).toMatchObject({ valid: false, error: expect.stringContaining('Total CMS 3') });
+ expect(await validate({ domain: 'ftp://cms.example.com', apiKey: 'k' })).toMatchObject({ valid: false });
+ });
+});
diff --git a/packages/pieces/community/totalcms/test/client.test.ts b/packages/pieces/community/totalcms/test/client.test.ts
new file mode 100644
index 00000000000..dd567a1cf26
--- /dev/null
+++ b/packages/pieces/community/totalcms/test/client.test.ts
@@ -0,0 +1,82 @@
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { totalcmsApi, totalcmsHelpers } from '../src/lib/common/client';
+import { API_KEY, connection, SITE, stubFetch } from './helpers';
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('client', () => {
+ test('sends X-API-Key, trims the site URL and encodes path segments', async () => {
+ const seen = stubFetch(() => ({ body: { data: { id: 'a b', text: 'x' } } }));
+ await totalcmsApi.getObject({ auth: connection(), collection: 'text', id: 'a b' });
+ expect(seen[0].url).toBe(`${SITE}/api/collections/text/a%20b`);
+ expect(seen[0].headers.get('x-api-key')).toBe(API_KEY);
+ expect(seen[0].headers.get('accept')).toBe('application/json');
+ expect(seen[0].redirect).toBe('manual');
+ });
+
+ test('refuses path traversal in IDs before any request', async () => {
+ const seen = stubFetch(() => ({ body: {} }));
+ await expect(totalcmsApi.getObject({ auth: connection(), collection: 'text', id: '..' })).rejects.toThrow('not valid');
+ await expect(totalcmsApi.getObject({ auth: connection(), collection: 'blog/../auth', id: 'x' })).rejects.toThrow('not valid');
+ expect(seen).toHaveLength(0);
+ });
+
+ test('surfaces the nested error.message from Total CMS', async () => {
+ stubFetch(() => ({ status: 400, body: { error: { message: '400 Bad Request - Object with id x already exists in text' } } }));
+ await expect(totalcmsApi.createObject({ auth: connection(), collection: 'text', fields: { id: 'x' } })).rejects.toThrow(
+ 'Total CMS could not create an object in collection "text" (HTTP 400): Object with id x already exists in text',
+ );
+ });
+
+ test('surfaces a plain string error', async () => {
+ stubFetch(() => ({ status: 400, body: { error: "Property 'text' is not numeric" } }));
+ await expect(
+ totalcmsApi.adjustNumber({ auth: connection(), collection: 'text', id: 'a', property: 'text', direction: 'increment', amount: 1 }),
+ ).rejects.toThrow("Property 'text' is not numeric");
+ });
+
+ test('error keeps status but no body field', async () => {
+ stubFetch(() => ({ status: 401, body: { error: { message: 'Unauthorized' } } }));
+ const error = await totalcmsApi.listCollections({ auth: connection() }).catch((e: unknown) => e);
+ expect(totalcmsHelpers.statusOf(error)).toBe(401);
+ expect(error instanceof Error && error.message).toContain('API key is invalid');
+ expect(error !== null && typeof error === 'object' && 'body' in error).toBe(false);
+ });
+
+ test('findObject returns null only on 404', async () => {
+ stubFetch(() => ({ status: 404, body: { error: { message: '404 Not Found - Unable to fetch object text/x' } } }));
+ expect(await totalcmsApi.findObject({ auth: connection(), collection: 'text', id: 'x' })).toBeNull();
+ stubFetch(() => ({ status: 500, body: { error: { message: 'boom' } } }));
+ await expect(totalcmsApi.findObject({ auth: connection(), collection: 'text', id: 'x' })).rejects.toThrow('boom');
+ });
+
+ test('a redirect is reported, not followed', async () => {
+ stubFetch(() => ({ status: 301, body: {}, headers: { location: 'https://evil.example.com/api' } }));
+ await expect(totalcmsApi.listCollections({ auth: connection() })).rejects.toThrow('redirect');
+ });
+
+ test('rejects a non-http site URL', async () => {
+ const seen = stubFetch(() => ({ body: {} }));
+ const auth = { props: { domain: 'ftp://cms.example.com', apiKey: API_KEY } };
+ await expect(totalcmsApi.listCollections({ auth })).rejects.toThrow('http');
+ expect(seen).toHaveLength(0);
+ });
+
+ test('replaceObject PUTs the whole object with the id in the body', async () => {
+ const seen = stubFetch(() => ({ body: { data: { id: 'headline', text: 'Hi' } } }));
+ await totalcmsApi.replaceObject({ auth: connection(), collection: 'text', id: ' headline ', fields: { text: 'Hi' } });
+ expect(seen[0].method).toBe('PUT');
+ expect(seen[0].path).toBe('/api/collections/text/headline');
+ expect(seen[0].json).toEqual({ text: 'Hi', id: 'headline' });
+ });
+
+ test('queryObjects passes paging, sort and filters and reads the total', async () => {
+ const seen = stubFetch(() => ({ body: { data: [{ id: 'a' }], meta: { pagination: { total: 7 } } } }));
+ const page = await totalcmsApi.queryObjects({ auth: connection(), collection: 'blog', limit: 10, offset: 20, sort: '-created', include: 'draft:false' });
+ expect(seen[0].path).toBe('/api/collections/blog/query');
+ expect(Object.fromEntries(seen[0].query)).toEqual({ limit: '10', offset: '20', sort: '-created', include: 'draft:false' });
+ expect(page.total).toBe(7);
+ });
+});
diff --git a/packages/pieces/community/totalcms/test/helpers.ts b/packages/pieces/community/totalcms/test/helpers.ts
new file mode 100644
index 00000000000..477fe42dac1
--- /dev/null
+++ b/packages/pieces/community/totalcms/test/helpers.ts
@@ -0,0 +1,80 @@
+import { vi } from 'vitest';
+
+export const API_KEY = 'tcms_test_key';
+export const SITE = 'https://cms.example.com';
+
+export function connection() {
+ return { type: 'CUSTOM_AUTH', props: { domain: `${SITE}/`, apiKey: ` ${API_KEY} ` } };
+}
+
+export function stubFetch(respond: (request: SeenRequest, index: number) => FakeReply): SeenRequest[] {
+ const seen: SeenRequest[] = [];
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
+ const url = input instanceof Request ? input.url : String(input);
+ const headers = new Headers(init?.headers);
+ const parsed = new URL(url);
+ const raw = init?.body;
+ const text = typeof raw === 'string' ? raw : Buffer.isBuffer(raw) ? raw.toString('latin1') : '';
+ const request: SeenRequest = {
+ url,
+ method: (init?.method ?? 'GET').toUpperCase(),
+ path: decodeURIComponent(parsed.pathname),
+ rawPath: parsed.pathname,
+ query: parsed.searchParams,
+ headers,
+ text,
+ json: headers.get('content-type')?.includes('application/json') && text ? JSON.parse(text) : null,
+ redirect: init?.redirect,
+ };
+ seen.push(request);
+ const reply = respond(request, seen.length - 1);
+ const payload = reply.text ?? (reply.body === undefined ? '' : JSON.stringify(reply.body));
+ return new Response(payload, {
+ status: reply.status ?? 200,
+ headers: { 'content-type': reply.text !== undefined ? 'text/plain' : 'application/json', ...(reply.headers ?? {}) },
+ });
+ }),
+ );
+ return seen;
+}
+
+export function memoryStore() {
+ const data = new Map<string, string>();
+ return {
+ put: async <T>(key: string, value: T): Promise<T> => {
+ data.set(key, JSON.stringify(value));
+ return value;
+ },
+ get: async <T>(key: string): Promise<T | null> => {
+ const raw = data.get(key);
+ return raw === undefined ? null : JSON.parse(raw);
+ },
+ delete: async (key: string): Promise<void> => {
+ data.delete(key);
+ },
+ };
+}
+
+export function context(propsValue: Record<string, unknown>) {
+ return contextWithStore({ propsValue, store: memoryStore() });
+}
+
+export function contextWithStore({ propsValue, store }: { propsValue: Record<string, unknown>; store: ReturnType<typeof memoryStore> }) {
+ return { auth: connection(), propsValue, store, files: {}, server: { apiUrl: '', publicUrl: '', token: '' }, isRepublish: false };
+}
+
+export type SeenRequest = {
+ url: string;
+ method: string;
+ path: string;
+ rawPath: string;
+ query: URLSearchParams;
+ headers: Headers;
+ text: string;
+ json: unknown;
+ redirect: RequestRedirect | undefined;
+};
+
+export type FakeReply = { status?: number; body?: unknown; text?: string; headers?: Record<string, string> };
diff --git a/packages/pieces/community/totalcms/test/metadata.test.ts b/packages/pieces/community/totalcms/test/metadata.test.ts
new file mode 100644
index 00000000000..c0b5dcca18c
--- /dev/null
+++ b/packages/pieces/community/totalcms/test/metadata.test.ts
@@ -0,0 +1,56 @@
+import { describe, expect, test } from 'vitest';
+import { totalcms } from '../src';
+
+const actions = Object.values(totalcms.actions());
+const nonCustom = actions.filter((action) => action.name !== 'custom_api_call');
+const triggers = Object.values(totalcms.triggers());
+
+describe('piece metadata', () => {
+ test('30 actions plus custom API call, 3 triggers', () => {
+ expect(nonCustom).toHaveLength(30);
+ expect(actions).toHaveLength(31);
+ expect(triggers.map((trigger) => trigger.name).sort()).toEqual(['new_blog_post', 'new_object', 'updated_object']);
+ });
+
+ test('legacy action names are kept', () => {
+ const names = nonCustom.map((action) => action.name);
+ for (const name of [
+ 'get_content', 'get_blog_post', 'save_blog_post', 'save_blog_image', 'save_blog_gallery', 'save_text', 'save_toggle',
+ 'save_date', 'save_image', 'save_gallery', 'save_file', 'save_depot', 'save_video',
+ ]) {
+ expect(names).toContain(name);
+ }
+ });
+
+ test.each(nonCustom.map((action) => [action.name, action]))('%s declares audience, classification, aiMetadata and outputSchema', (_name, action) => {
+ expect(['both', 'ai', 'human']).toContain(action.audience);
+ expect(['READ', 'SEARCH', 'WRITE', 'DESTRUCTIVE']).toContain(action.classification);
+ expect(action.aiMetadata?.description?.length ?? 0).toBeGreaterThan(60);
+ expect(typeof action.aiMetadata?.idempotent).toBe('boolean');
+ expect(action.outputSchema?.fields.length).toBeGreaterThan(0);
+ });
+
+ test('actions visible to agents have no dynamic dropdowns', () => {
+ for (const action of nonCustom.filter((item) => item.audience !== 'human')) {
+ const types = Object.values(action.props).map((prop: unknown) => (prop !== null && typeof prop === 'object' ? Reflect.get(prop, 'type') : undefined));
+ expect(types, action.name).not.toContain('DROPDOWN');
+ }
+ });
+
+ test('only delete is destructive and it is human-only', () => {
+ const destructive = nonCustom.filter((action) => action.classification === 'DESTRUCTIVE');
+ expect(destructive.map((action) => action.name)).toEqual(['delete_object']);
+ expect(destructive[0].audience).toBe('human');
+ });
+
+ test('triggers are READ with aiMetadata', () => {
+ for (const trigger of triggers) {
+ expect(trigger.classification).toBe('READ');
+ expect(trigger.aiMetadata?.description?.length ?? 0).toBeGreaterThan(40);
+ }
+ });
+
+ test('minimum release supports ai audience', () => {
+ expect(totalcms.minimumSupportedRelease).toBe('0.88.2');
+ });
+});
diff --git a/packages/pieces/community/totalcms/test/triggers.test.ts b/packages/pieces/community/totalcms/test/triggers.test.ts
new file mode 100644
index 00000000000..55484f0a6f3
--- /dev/null
+++ b/packages/pieces/community/totalcms/test/triggers.test.ts
@@ -0,0 +1,130 @@
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { newBlogPost } from '../src/lib/triggers/new-blog-post';
+import { updatedObjectTrigger } from '../src/lib/triggers/updated-object';
+import { context, contextWithStore, memoryStore, stubFetch } from './helpers';
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+const schema = { data: { id: 'blog', properties: { created: {}, updated: {} }, index: ['id', 'created', 'updated'] } };
+
+function site(objects: () => Record<string, unknown>[]) {
+ return stubFetch((request) => {
+ if (request.path.endsWith('/schema')) {
+ return { body: schema };
+ }
+ if (request.path.endsWith('/query')) {
+ const sortField = (request.query.get('sort') ?? '-created').replace('-', '');
+ const sorted = [...objects()].sort((a, b) => String(b[sortField]).localeCompare(String(a[sortField])));
+ const offset = Number(request.query.get('offset'));
+ const limit = Number(request.query.get('limit'));
+ return { body: { data: sorted.slice(offset, offset + limit), meta: { pagination: { total: sorted.length } } } };
+ }
+ const id = request.path.split('/').pop();
+ const found = objects().find((object) => object['id'] === id);
+ return found ? { body: { data: { ...found, content: 'full' } } } : { status: 404, body: {} };
+ });
+}
+
+describe('new_blog_post', () => {
+ test('emits each new post once, including one created in the same second as the checkpoint', async () => {
+ let objects: Record<string, unknown>[] = [{ id: 'old', created: '2026-10-07T10:00:00+00:00', draft: false }];
+ site(() => objects);
+ const store = memoryStore();
+ const ctx = contextWithStore({ propsValue: { collection: 'blog', include_drafts: false }, store });
+ await newBlogPost.onEnable(ctx);
+ expect(await newBlogPost.run(ctx)).toEqual([]);
+ objects = [...objects, { id: 'a', created: '2026-10-07T10:05:00+00:00', draft: false }, { id: 'draft', created: '2026-10-07T10:05:00+00:00', draft: true }];
+ const first = await newBlogPost.run(ctx);
+ expect(first.map((post) => Reflect.get(Object(post), 'id'))).toEqual(['a']);
+ expect(first[0]).toMatchObject({ collection: 'blog', content: 'full' });
+ objects = [...objects, { id: 'b', created: '2026-10-07T10:05:00+00:00', draft: false }];
+ expect((await newBlogPost.run(ctx)).map((post) => Reflect.get(Object(post), 'id'))).toEqual(['b']);
+ expect(await newBlogPost.run(ctx)).toEqual([]);
+ });
+
+ test('pages back past 100 new items to the checkpoint', async () => {
+ let objects: Record<string, unknown>[] = [{ id: 'old', created: '2026-01-01T00:00:00+00:00' }];
+ const seen = site(() => objects);
+ const ctx = context({ collection: 'blog', include_drafts: true });
+ await newBlogPost.onEnable(ctx);
+ objects = [...objects, ...Array.from({ length: 150 }, (_, i) => ({ id: `p${i}`, created: `2026-02-01T00:00:${String(i % 60).padStart(2, '0')}+00:00`, minute: i }))];
+ objects = objects.map((object, i) => (i === 0 ? object : { ...object, created: new Date(Date.UTC(2026, 1, 1, 0, 0, i)).toISOString() }));
+ const emitted = await newBlogPost.run(ctx);
+ expect(emitted).toHaveLength(150);
+ expect(seen.filter((request) => request.path.endsWith('/query')).length).toBeGreaterThanOrEqual(3);
+ });
+
+ test('enable records every existing post that shares the newest timestamp', async () => {
+ let objects: Record<string, unknown>[] = [
+ { id: 'older', created: '2026-10-07T09:00:00+00:00' },
+ ...Array.from({ length: 250 }, (_, i) => ({ id: `same${i}`, created: '2026-10-07T10:00:00+00:00' })),
+ ];
+ const seen = site(() => objects);
+ const ctx = context({ collection: 'blog', include_drafts: true });
+ await newBlogPost.onEnable(ctx);
+ expect(seen.filter((request) => request.path.endsWith('/query')).map((request) => request.query.get('offset'))).toEqual(['0', '100', '200']);
+ expect(await newBlogPost.run(ctx)).toEqual([]);
+ objects = [...objects, { id: 'fresh', created: '2026-10-07T10:00:00+00:00' }];
+ expect((await newBlogPost.run(ctx)).map((post) => Reflect.get(Object(post), 'id'))).toEqual(['fresh']);
+ });
+
+ test('enable accepts exactly 5,000 posts at the newest timestamp and refuses more', async () => {
+ const tied = (count: number) => Array.from({ length: count }, (_, i) => ({ id: `same${i}`, created: '2026-10-07T10:00:00+00:00' }));
+ let objects: Record<string, unknown>[] = [...tied(5000), { id: 'older', created: '2026-10-07T09:00:00+00:00' }];
+ site(() => objects);
+ const ctx = context({ collection: 'blog', include_drafts: true });
+ await newBlogPost.onEnable(ctx);
+ expect(await newBlogPost.run(ctx)).toEqual([]);
+ objects = tied(5000);
+ await expect(newBlogPost.onEnable(context({ collection: 'blog', include_drafts: true }))).resolves.toBeUndefined();
+ objects = tied(5001);
+ await expect(newBlogPost.onEnable(context({ collection: 'blog', include_drafts: true }))).rejects.toThrow('More than 5000 objects');
+ });
+
+ test('finds a new post that sorts behind 500 already-seen posts with the same timestamp', async () => {
+ const tied = Array.from({ length: 500 }, (_, i) => ({ id: `same${i}`, created: '2026-10-07T10:00:00+00:00' }));
+ let objects: Record<string, unknown>[] = [...tied, { id: 'older', created: '2026-10-07T09:00:00+00:00' }];
+ site(() => objects);
+ const ctx = context({ collection: 'blog', include_drafts: true });
+ await newBlogPost.onEnable(ctx);
+ objects = [...tied, { id: 'late', created: '2026-10-07T10:00:00+00:00' }, { id: 'older', created: '2026-10-07T09:00:00+00:00' }];
+ expect((await newBlogPost.run(ctx)).map((post) => Reflect.get(Object(post), 'id'))).toEqual(['late']);
+ expect(await newBlogPost.run(ctx)).toEqual([]);
+ });
+
+ test('emits at most 200 posts per poll, oldest first, and the rest on the next poll', async () => {
+ let objects: Record<string, unknown>[] = [{ id: 'old', created: '2026-01-01T00:00:00.000Z' }];
+ site(() => objects);
+ const ctx = context({ collection: 'blog', include_drafts: true });
+ await newBlogPost.onEnable(ctx);
+ objects = [...objects, ...Array.from({ length: 250 }, (_, i) => ({ id: `p${i}`, created: new Date(Date.UTC(2026, 1, 1, 0, 0, i)).toISOString() }))];
+ const ids = async () => (await newBlogPost.run(ctx)).map((post) => Reflect.get(Object(post), 'id'));
+ const first = await ids();
+ expect(first).toHaveLength(200);
+ expect(first[0]).toBe('p0');
+ expect(first[199]).toBe('p199');
+ expect(await ids()).toEqual(Array.from({ length: 50 }, (_, i) => `p${200 + i}`));
+ expect(await ids()).toEqual([]);
+ });
+
+ test('a collection without a created field fails clearly', async () => {
+ stubFetch((request) => (request.path.endsWith('/schema') ? { body: { data: { properties: { text: {} }, index: ['id', 'text'] } } } : { body: { data: [] } }));
+ await expect(newBlogPost.onEnable(context({ collection: 'text' }))).rejects.toThrow('does not record a "created" date');
+ });
+});
+
+describe('updated_object', () => {
+ test('skips new objects by default and reports later changes', async () => {
+ let objects: Record<string, unknown>[] = [{ id: 'a', created: '2026-10-07T10:00:00+00:00', updated: '2026-10-07T10:00:00+00:00' }];
+ site(() => objects);
+ const ctx = context({ collection: 'blog', include_new: false });
+ await updatedObjectTrigger.onEnable(ctx);
+ objects = [...objects, { id: 'b', created: '2026-10-07T11:00:00+00:00', updated: '2026-10-07T11:00:00+00:00' }];
+ expect(await updatedObjectTrigger.run(ctx)).toEqual([]);
+ objects = objects.map((object) => (object['id'] === 'a' ? { ...object, updated: '2026-10-07T12:00:00+00:00' } : object));
+ expect((await updatedObjectTrigger.run(ctx)).map((object) => Reflect.get(Object(object), 'id'))).toEqual(['a']);
+ expect(await updatedObjectTrigger.run(ctx)).toEqual([]);
+ });
+});
diff --git a/packages/pieces/community/totalcms/vitest.config.ts b/packages/pieces/community/totalcms/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/totalcms/vitest.config.ts
@@ -0,0 +1,19 @@
+import path from 'path'
+import { defineConfig } from 'vitest/config'
+
+const repoRoot = path.resolve(__dirname, '../../../..')
+
+export default defineConfig({
+ root: __dirname,
+ test: {
+ globals: true,
+ environment: 'node',
+ include: ['test/**/*.test.ts'],
+ },
+ resolve: {
+ alias: {
+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),
+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),
+ },
+ },
+})