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(nuelink): manage posts, collections and automations from flows and AI agents (#16386)

Odai Ahmad7aa9123522bd
diff --git a/bun.lock b/bun.lock
index f034f652b5b..03be0fa37fc 100644
--- a/bun.lock
+++ b/bun.lock
@@ -6480,15 +6480,17 @@
},
"packages/pieces/community/nuelink": {
"name": "@activepieces/piece-nuelink",
- "version": "0.1.7",
+ "version": "0.2.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
+ "undici": "7.29.1",
},
"devDependencies": {
"tslib": "2.6.2",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/octopush-sms": {
diff --git a/packages/pieces/community/nuelink/package.json b/packages/pieces/community/nuelink/package.json
index 925514a3898..4636601b06b 100644
--- a/packages/pieces/community/nuelink/package.json
+++ b/packages/pieces/community/nuelink/package.json
@@ -1,20 +1,23 @@
{
"name": "@activepieces/piece-nuelink",
- "version": "0.1.7",
+ "version": "0.2.0",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
"scripts": {
"build": "tsc -p tsconfig.lib.json && cp package.json dist/",
"bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",
- "lint": "eslint 'src/**/*.ts'"
+ "lint": "eslint 'src/**/*.ts'",
+ "test": "vitest run"
},
"dependencies": {
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
"@activepieces/core-piece-types": "workspace:*",
- "@activepieces/core-utils": "workspace:*"
+ "@activepieces/core-utils": "workspace:*",
+ "undici": "7.29.1"
},
"devDependencies": {
- "tslib": "2.6.2"
+ "tslib": "2.6.2",
+ "vitest": "3.2.6"
}
}
diff --git a/packages/pieces/community/nuelink/src/i18n/translation.json b/packages/pieces/community/nuelink/src/i18n/translation.json
index 68678e3a345..ee60b6be3ed 100644
--- a/packages/pieces/community/nuelink/src/i18n/translation.json
+++ b/packages/pieces/community/nuelink/src/i18n/translation.json
@@ -1,17 +1,354 @@
{
- "Please use **Nuelink API Key**.": "Please use **Nuelink API Key**.",
+ "Social media scheduling: create, schedule, edit and track posts across your Nuelink brands and collections.": "Social media scheduling: create, schedule, edit and track posts across your Nuelink brands and collections.",
+ "Create Post in Collection": "Create Post in Collection",
+ "Update Post": "Update Post",
+ "Delete Post": "Delete Post",
+ "List Posts": "List Posts",
+ "List Published Posts": "List Published Posts",
+ "Upload Media": "Upload Media",
"Create Post": "Create Post",
- "Creates a post on nuelink.": "Creates a post on nuelink.",
+ "List Brands": "List Brands",
+ "List Collections": "List Collections",
+ "Get Profile": "Get Profile",
+ "Get Weekly Queue Schedule": "Get Weekly Queue Schedule",
+ "List Channels": "List Channels",
+ "Create Collection": "Create Collection",
+ "Update Collection": "Update Collection",
+ "Add Channel to Collection": "Add Channel to Collection",
+ "Remove Channel from Collection": "Remove Channel from Collection",
+ "Add Queue Time Slot": "Add Queue Time Slot",
+ "Delete Queue Time Slot": "Delete Queue Time Slot",
+ "List Feed Automations": "List Feed Automations",
+ "Create Feed Automation": "Create Feed Automation",
+ "Pause or Activate Feed Automation": "Pause or Activate Feed Automation",
+ "List Media": "List Media",
+ "Upload Media File": "Upload Media File",
+ "Move Posts to Collection": "Move Posts to Collection",
+ "Creates a post in a Nuelink collection as a draft, in the queue, at a scheduled time or right away. It goes to every channel in the collection.": "Creates a post in a Nuelink collection as a draft, in the queue, at a scheduled time or right away. It goes to every channel in the collection.",
+ "Changes the caption of a post that is not published yet, turns it back into a draft, reschedules it or moves it in the queue.": "Changes the caption of a post that is not published yet, turns it back into a draft, reschedules it or moves it in the queue.",
+ "Permanently deletes a post from Nuelink. Anything already published on a social network stays there. Needs \"Allow AI to perform sensitive actions\" turned on in Nuelink Settings → API.": "Permanently deletes a post from Nuelink. Anything already published on a social network stays there. Needs \"Allow AI to perform sensitive actions\" turned on in Nuelink Settings → API.",
+ "Lists a brand's drafts, queued, scheduled and published posts, one page at a time.": "Lists a brand's drafts, queued, scheduled and published posts, one page at a time.",
+ "Lists what Nuelink sent to each channel, with the delivery status, the link to the post and its engagement counts.": "Lists what Nuelink sent to each channel, with the delivery status, the link to the post and its engagement counts.",
+ "Uploads an image, video or PDF to the brand's Nuelink media library and returns its media ID for Create Post in Collection.": "Uploads an image, video or PDF to the brand's Nuelink media library and returns its media ID for Create Post in Collection.",
+ "Adds a post to the collection linked to your Nuelink automation token. Needs an Automation Token connection; with an API key, use Create Post in Collection.": "Adds a post to the collection linked to your Nuelink automation token. Needs an Automation Token connection; with an API key, use Create Post in Collection.",
+ "Lists the Nuelink brands the API key can access, with their IDs and timezones.": "Lists the Nuelink brands the API key can access, with their IDs and timezones.",
+ "Lists a brand's collections with their channels, queue slots and post counts.": "Lists a brand's collections with their channels, queue slots and post counts.",
+ "Returns the Nuelink user the API key belongs to.": "Returns the Nuelink user the API key belongs to.",
+ "Returns every weekly queue time slot of a brand, grouped by weekday, in the brand timezone.": "Returns every weekly queue time slot of a brand, grouped by weekday, in the brand timezone.",
+ "Lists the social channels connected to a brand.": "Lists the social channels connected to a brand.",
+ "Creates a collection in a brand, optionally with channels and weekly queue time slots.": "Creates a collection in a brand, optionally with channels and weekly queue time slots.",
+ "Renames a collection, changes its description or evergreen interval, or pauses or resumes it.": "Renames a collection, changes its description or evergreen interval, or pauses or resumes it.",
+ "Connects one of the brand's channels to a collection, so the collection's posts publish there too.": "Connects one of the brand's channels to a collection, so the collection's posts publish there too.",
+ "Disconnects a channel from a collection. The channel stays connected to the brand.": "Disconnects a channel from a collection. The channel stays connected to the brand.",
+ "Adds a weekly time slot (weekday and time, brand timezone) to a collection's queue.": "Adds a weekly time slot (weekday and time, brand timezone) to a collection's queue.",
+ "Deletes one weekly time slot from a collection's queue.": "Deletes one weekly time slot from a collection's queue.",
+ "Lists a brand's RSS and feed automations.": "Lists a brand's RSS and feed automations.",
+ "Creates an RSS or feed automation that turns new feed items into posts in a collection.": "Creates an RSS or feed automation that turns new feed items into posts in a collection.",
+ "Pauses a feed automation, or activates it again.": "Pauses a feed automation, or activates it again.",
+ "Lists the files in a brand's Nuelink media library, newest first.": "Lists the files in a brand's Nuelink media library, newest first.",
+ "Uploads one image, video or PDF to the brand's Nuelink media library and returns its media ID.": "Uploads one image, video or PDF to the brand's Nuelink media library and returns its media ID.",
+ "Creates a post (caption, poll or both) in a Nuelink collection as a draft, in the queue, scheduled or published now.": "Creates a post (caption, poll or both) in a Nuelink collection as a draft, in the queue, scheduled or published now.",
+ "Changes the caption, publish mode, schedule or queue position of a post that is not published yet.": "Changes the caption, publish mode, schedule or queue position of a post that is not published yet.",
+ "Moves up to 100 posts from one collection to another in the same brand.": "Moves up to 100 posts from one collection to another in the same brand.",
+ "Permanently deletes a post from Nuelink, in any status. Content already on a social network stays there.": "Permanently deletes a post from Nuelink, in any status. Content already on a social network stays there.",
+ "Lists a brand's posts (drafts, queued, scheduled, published), optionally for one collection, one page at a time.": "Lists a brand's posts (drafts, queued, scheduled, published), optionally for one collection, one page at a time.",
+ "Lists what Nuelink sent to each channel, with delivery status, post URL and engagement counts.": "Lists what Nuelink sent to each channel, with delivery status, post URL and engagement counts.",
+ "Brand": "Brand",
+ "Collection": "Collection",
+ "Publish Mode": "Publish Mode",
+ "Scheduled Time": "Scheduled Time",
"Caption": "Caption",
- "Media": "Media",
"Title": "Title",
+ "Media": "Media",
"Alt Text": "Alt Text",
+ "Link": "Link",
+ "Post as Story": "Post as Story",
+ "Split Long Text into a Thread": "Split Long Text into a Thread",
+ "First Comment": "First Comment",
+ "First Comment Delay (seconds)": "First Comment Delay (seconds)",
+ "Instagram: Share Reel to Feed": "Instagram: Share Reel to Feed",
+ "Instagram: Collaborator": "Instagram: Collaborator",
+ "TikTok: Add Music Automatically": "TikTok: Add Music Automatically",
+ "YouTube: Tags": "YouTube: Tags",
+ "Post ID": "Post ID",
+ "New Caption": "New Caption",
+ "New Publish Mode": "New Publish Mode",
+ "Queue Position": "Queue Position",
+ "Show": "Show",
+ "Post Type": "Post Type",
+ "Created From": "Created From",
+ "Created To": "Created To",
+ "Sort By": "Sort By",
+ "Sort Order": "Sort Order",
+ "Page": "Page",
+ "Results per Page": "Results per Page",
+ "Delivery Status": "Delivery Status",
+ "Channel": "Channel",
+ "Search Text": "Search Text",
+ "Published From": "Published From",
+ "Published To": "Published To",
+ "File": "File",
"Share Instagram Reel to Feed": "Share Instagram Reel to Feed",
"Treat videos as short-form vertical videos": "Treat videos as short-form vertical videos",
- "The your post caption here": "The your post caption here",
- "Enter the media URL here": "Enter the media URL here",
+ "Brand ID": "Brand ID",
+ "Description": "Description",
+ "Evergreen Republish Interval (weeks)": "Evergreen Republish Interval (weeks)",
+ "Channel IDs": "Channel IDs",
+ "Queue Slots": "Queue Slots",
+ "Collection ID": "Collection ID",
+ "New Title": "New Title",
+ "New Description": "New Description",
+ "Clear Description": "Clear Description",
+ "Status": "Status",
+ "Channel ID": "Channel ID",
+ "Slot": "Slot",
+ "Slot ID": "Slot ID",
+ "Name": "Name",
+ "Feed Type": "Feed Type",
+ "Feed URL": "Feed URL",
+ "Import As": "Import As",
+ "Title Template": "Title Template",
+ "Caption Template": "Caption Template",
+ "Add Posts as Drafts": "Add Posts as Drafts",
+ "Import Existing Feed Items": "Import Existing Feed Items",
+ "Refresh Every (hours)": "Refresh Every (hours)",
+ "Automation ID": "Automation ID",
+ "Type": "Type",
+ "Poll Question": "Poll Question",
+ "Poll Options": "Poll Options",
+ "Poll Duration": "Poll Duration",
+ "Poll Correct Option Index": "Poll Correct Option Index",
+ "Poll Explanation": "Poll Explanation",
+ "Source Collection ID": "Source Collection ID",
+ "Destination Collection ID": "Destination Collection ID",
+ "Post IDs": "Post IDs",
+ "View": "View",
+ "Posting Type": "Posting Type",
+ "The Nuelink brand (workspace) to use.": "The Nuelink brand (workspace) to use.",
+ "The collection to add the post to. The post is published to every channel connected to it.": "The collection to add the post to. The post is published to every channel connected to it.",
+ "Draft saves the post without publishing it. Queue gives it the collection's next free time slot. Schedule publishes it at Scheduled Time. Publish Now sends it to every channel immediately.": "Draft saves the post without publishing it. Queue gives it the collection's next free time slot. Schedule publishes it at Scheduled Time. Publish Now sends it to every channel immediately.",
+ "Only for Publish Mode = Schedule, at least 10 minutes ahead. Include a timezone offset; it is converted to the brand's timezone for Nuelink.": "Only for Publish Mode = Schedule, at least 10 minutes ahead. Include a timezone offset; it is converted to the brand's timezone for Nuelink.",
+ "The text of the post, up to 3,000 characters. Separating parts with two empty lines turns it into a thread (up to 10 parts).": "The text of the post, up to 3,000 characters. Separating parts with two empty lines turns it into a thread (up to 10 parts).",
+ "Title used for videos, Reels and Pinterest pins (up to 255 characters).": "Title used for videos, Reels and Pinterest pins (up to 255 characters).",
+ "Up to 10 images or videos. Each entry is a public http(s) URL that Nuelink downloads (it must open without a login), or a media ID from Upload Media.": "Up to 10 images or videos. Each entry is a public http(s) URL that Nuelink downloads (it must open without a login), or a media ID from Upload Media.",
+ "Describes the image or video for screen readers (up to 255 characters).": "Describes the image or video for screen readers (up to 255 characters).",
+ "Destination link for Pinterest pins and the Google Business \"Learn more\" button.": "Destination link for Pinterest pins and the Google Business \"Learn more\" button.",
+ "Publish as a story on channels that support stories.": "Publish as a story on channels that support stories.",
+ "Let Nuelink split text that is too long for a channel into a thread.": "Let Nuelink split text that is too long for a channel into a thread.",
+ "A comment Nuelink adds under the post after it is published (up to 1,000 characters). Set First Comment Delay too.": "A comment Nuelink adds under the post after it is published (up to 1,000 characters). Set First Comment Delay too.",
+ "How many seconds after publishing to post the first comment. Required when First Comment is set.": "How many seconds after publishing to post the first comment. Required when First Comment is set.",
+ "When on, Instagram Reels also appear in the feed. When off, Nuelink's default applies.": "When on, Instagram Reels also appear in the feed. When off, Nuelink's default applies.",
+ "Instagram username to invite as a collaborator.": "Instagram username to invite as a collaborator.",
+ "When on, TikTok adds music to photo posts. When off, Nuelink's default applies.": "When on, TikTok adds music to photo posts. When off, Nuelink's default applies.",
+ "Tags for YouTube videos.": "Tags for YouTube videos.",
+ "The numeric ID of the post, from Create Post in Collection or List Posts.": "The numeric ID of the post, from Create Post in Collection or List Posts.",
+ "Replaces the post text (up to 3,000 characters). Leave empty to keep the current caption. Media is not changed.": "Replaces the post text (up to 3,000 characters). Leave empty to keep the current caption. Media is not changed.",
+ "Leave empty to keep the current mode.": "Leave empty to keep the current mode.",
+ "Required when New Publish Mode is Schedule, at least 10 minutes ahead; not allowed otherwise. Include a timezone offset.": "Required when New Publish Mode is Schedule, at least 10 minutes ahead; not allowed otherwise. Include a timezone offset.",
+ "Move a queued post to the front or back of its collection queue. Works on its own or with New Publish Mode = Add to Queue.": "Move a queued post to the front or back of its collection queue. Works on its own or with New Publish Mode = Add to Queue.",
+ "The numeric ID of the post to delete, from Create Post in Collection or List Posts.": "The numeric ID of the post to delete, from Create Post in Collection or List Posts.",
+ "Only list posts of this collection. Leave empty for all collections.": "Only list posts of this collection. Leave empty for all collections.",
+ "Which kind of posts to list. Leave empty for all.": "Which kind of posts to list. Leave empty for all.",
+ "Only posts created at or after this time. A time without a timezone is read as UTC.": "Only posts created at or after this time. A time without a timezone is read as UTC.",
+ "Only posts created at or before this time. A time without a timezone is read as UTC.": "Only posts created at or before this time. A time without a timezone is read as UTC.",
+ "Which page of results to return, starting at 1. When the output says hasMore is true, run again with the next page number.": "Which page of results to return, starting at 1. When the output says hasMore is true, run again with the next page number.",
+ "How many results to return per page (1 to 100).": "How many results to return per page (1 to 100).",
+ "Only results from this collection. Leave empty for all collections.": "Only results from this collection. Leave empty for all collections.",
+ "Only return results for this social channel.": "Only return results for this social channel.",
+ "Only results of this Nuelink post (the ID from Create Post in Collection or List Posts).": "Only results of this Nuelink post (the ID from Create Post in Collection or List Posts).",
+ "Only results whose published text contains this (not case-sensitive, up to 255 characters).": "Only results whose published text contains this (not case-sensitive, up to 255 characters).",
+ "Only results published at or after this time. A time without a timezone is read as UTC.": "Only results published at or after this time. A time without a timezone is read as UTC.",
+ "Only results published at or before this time. A time without a timezone is read as UTC.": "Only results published at or before this time. A time without a timezone is read as UTC.",
+ "A JPG, PNG, BMP, MP4, MOV or PDF file, up to 100 MB.": "A JPG, PNG, BMP, MP4, MOV or PDF file, up to 100 MB.",
+ "The text of the post.": "The text of the post.",
+ "Public URL of one image or video. Nuelink downloads it, so it must open without a login.": "Public URL of one image or video. Nuelink downloads it, so it must open without a login.",
"Enter a title to use for your Reels, videos and/or Pinterest posts.": "Enter a title to use for your Reels, videos and/or Pinterest posts.",
"Enter an alt text for your image or video.": "Enter an alt text for your image or video.",
"Share your Instagram Reel to your feed as well.": "Share your Instagram Reel to your feed as well.",
- "We will treat the videos imported as short-form vertical videos (Reels, Shorts, Tiktoks etc...).": "We will treat the videos imported as short-form vertical videos (Reels, Shorts, Tiktoks etc...)."
+ "We will treat the videos imported as short-form vertical videos (Reels, Shorts, Tiktoks etc...).": "We will treat the videos imported as short-form vertical videos (Reels, Shorts, Tiktoks etc...).",
+ "The numeric brand ID from List Brands.": "The numeric brand ID from List Brands.",
+ "The numeric brand ID from nuelink_list_brands.": "The numeric brand ID from nuelink_list_brands.",
+ "Collection name, 1 to 255 characters.": "Collection name, 1 to 255 characters.",
+ "Up to 1,000 characters.": "Up to 1,000 characters.",
+ "Republish posts every N weeks; 0 or empty turns it off.": "Republish posts every N weeks; 0 or empty turns it off.",
+ "Numeric channel IDs from nuelink_list_channels. Posts in the collection publish to these.": "Numeric channel IDs from nuelink_list_channels. Posts in the collection publish to these.",
+ "Weekly brand-local slots like \"Mon 09:30\". Duplicates are removed.": "Weekly brand-local slots like \"Mon 09:30\". Duplicates are removed.",
+ "The numeric collection ID from nuelink_list_collections.": "The numeric collection ID from nuelink_list_collections.",
+ "1 to 255 characters. Empty keeps the current title.": "1 to 255 characters. Empty keeps the current title.",
+ "Up to 1,000 characters. Empty keeps the current one.": "Up to 1,000 characters. Empty keeps the current one.",
+ "Remove the description. Do not combine with New Description.": "Remove the description. Do not combine with New Description.",
+ "PAUSED stops publishing from this collection; ACTIVE resumes it. Empty keeps it.": "PAUSED stops publishing from this collection; ACTIVE resumes it. Empty keeps it.",
+ "0 turns evergreen off. Empty keeps it.": "0 turns evergreen off. Empty keeps it.",
+ "The numeric channel ID from nuelink_list_channels.": "The numeric channel ID from nuelink_list_channels.",
+ "The numeric channel ID, from the collection's channels in nuelink_list_collections.": "The numeric channel ID, from the collection's channels in nuelink_list_collections.",
+ "Weekday and brand-local 24-hour time, e.g. \"Tue 09:00\".": "Weekday and brand-local 24-hour time, e.g. \"Tue 09:00\".",
+ "The numeric collection ID the slot belongs to.": "The numeric collection ID the slot belongs to.",
+ "The numeric queue slot ID from nuelink_get_schedule or nuelink_list_collections.": "The numeric queue slot ID from nuelink_get_schedule or nuelink_list_collections.",
+ "The numeric collection ID (nuelink_list_collections) that receives the posts.": "The numeric collection ID (nuelink_list_collections) that receives the posts.",
+ "Automation name, up to 255 characters.": "Automation name, up to 255 characters.",
+ "Public http(s) URL of the feed.": "Public http(s) URL of the feed.",
+ "Up to 255 characters; placeholders {{title}}, {{description}}, {{link}}. Default {{title}}.": "Up to 255 characters; placeholders {{title}}, {{description}}, {{link}}. Default {{title}}.",
+ "Up to 255 characters; placeholders {{title}}, {{description}}, {{link}}.": "Up to 255 characters; placeholders {{title}}, {{description}}, {{link}}.",
+ "Defaults to true. False lets imported posts publish through the queue.": "Defaults to true. False lets imported posts publish through the queue.",
+ "Defaults to false. True back-fills the whole feed; only allowed with drafts.": "Defaults to false. True back-fills the whole feed; only allowed with drafts.",
+ "The numeric automation ID from nuelink_list_automations.": "The numeric automation ID from nuelink_list_automations.",
+ "Only this media category. APPLICATION covers every document record; DOCUMENT only office/document MIME types.": "Only this media category. APPLICATION covers every document record; DOCUMENT only office/document MIME types.",
+ "A JPG, PNG, BMP, MP4, MOV or PDF file (URL or file reference), up to 100 MB.": "A JPG, PNG, BMP, MP4, MOV or PDF file (URL or file reference), up to 100 MB.",
+ "The numeric collection ID from nuelink_list_collections. The post goes to every channel in it.": "The numeric collection ID from nuelink_list_collections. The post goes to every channel in it.",
+ "DRAFT (default) saves without publishing, QUEUE takes the next free slot, SCHEDULE publishes at Scheduled Time, IMMEDIATE publishes now.": "DRAFT (default) saves without publishing, QUEUE takes the next free slot, SCHEDULE publishes at Scheduled Time, IMMEDIATE publishes now.",
+ "Only with Publish Mode SCHEDULE. ISO-8601 with an offset or Z, e.g. 2026-10-12T09:00:00+03:00.": "Only with Publish Mode SCHEDULE. ISO-8601 with an offset or Z, e.g. 2026-10-12T09:00:00+03:00.",
+ "Post text, up to 3,000 characters. Optional when a poll is set.": "Post text, up to 3,000 characters. Optional when a poll is set.",
+ "Title for videos, Reels and Pinterest pins (up to 255 characters).": "Title for videos, Reels and Pinterest pins (up to 255 characters).",
+ "Up to 10 entries: public http(s) URLs, or media IDs from nuelink_upload_file or nuelink_list_media.": "Up to 10 entries: public http(s) URLs, or media IDs from nuelink_upload_file or nuelink_list_media.",
+ "Alt text for the media (up to 255 characters).": "Alt text for the media (up to 255 characters).",
+ "Destination link for Pinterest pins and the Google Business button.": "Destination link for Pinterest pins and the Google Business button.",
+ "Publish as a story where supported.": "Publish as a story where supported.",
+ "Let Nuelink split long text into a thread.": "Let Nuelink split long text into a thread.",
+ "Comment added after publishing (up to 1,000 characters). Needs First Comment Delay.": "Comment added after publishing (up to 1,000 characters). Needs First Comment Delay.",
+ "Seconds after publishing to add the first comment.": "Seconds after publishing to add the first comment.",
+ "Up to 280 characters. Setting any poll field requires Question, Options and Duration.": "Up to 280 characters. Setting any poll field requires Question, Options and Duration.",
+ "2 to 4 answers, each up to 30 characters.": "2 to 4 answers, each up to 30 characters.",
+ "Zero-based index of the correct answer, for quiz polls.": "Zero-based index of the correct answer, for quiz polls.",
+ "Shown with the correct answer (up to 512 characters).": "Shown with the correct answer (up to 512 characters).",
+ "Instagram username to invite as collaborator.": "Instagram username to invite as collaborator.",
+ "The numeric post ID from nuelink_create_post or nuelink_list_brand_posts.": "The numeric post ID from nuelink_create_post or nuelink_list_brand_posts.",
+ "Replaces the post text (up to 3,000 characters). Leave empty to keep it.": "Replaces the post text (up to 3,000 characters). Leave empty to keep it.",
+ "Required with New Publish Mode SCHEDULE, not allowed otherwise. ISO-8601 with an offset, e.g. 2026-10-12T09:00:00+03:00.": "Required with New Publish Mode SCHEDULE, not allowed otherwise. ISO-8601 with an offset, e.g. 2026-10-12T09:00:00+03:00.",
+ "Move a queued post to the front or back of its queue.": "Move a queued post to the front or back of its queue.",
+ "The collection that currently holds every listed post.": "The collection that currently holds every listed post.",
+ "A different collection of the same brand.": "A different collection of the same brand.",
+ "1 to 100 numeric post IDs.": "1 to 100 numeric post IDs.",
+ "The numeric post ID from nuelink_list_brand_posts.": "The numeric post ID from nuelink_list_brand_posts.",
+ "Only posts of this collection (numeric ID from nuelink_list_collections). Empty for all.": "Only posts of this collection (numeric ID from nuelink_list_collections). Empty for all.",
+ "QUEUE, SCHEDULED, DRAFT or PUBLISHED.": "QUEUE, SCHEDULED, DRAFT or PUBLISHED.",
+ "Lifecycle status.": "Lifecycle status.",
+ "Content type.": "Content type.",
+ "How the post is published.": "How the post is published.",
+ "ISO-8601 time; a value without offset is read as UTC.": "ISO-8601 time; a value without offset is read as UTC.",
+ "Sort field.": "Sort field.",
+ "Defaults to PUBLISHED.": "Defaults to PUBLISHED.",
+ "Only results from this collection.": "Only results from this collection.",
+ "Only results for this channel (from nuelink_list_channels).": "Only results for this channel (from nuelink_list_channels).",
+ "Only results of this post.": "Only results of this post.",
+ "Only results of this post type, e.g. IMAGE.": "Only results of this post type, e.g. IMAGE.",
+ "Text contained in the published body (up to 255 characters).": "Text contained in the published body (up to 255 characters).",
+ "ISO-8601 time; without offset it is read as UTC.": "ISO-8601 time; without offset it is read as UTC.",
+ "Draft (do not publish)": "Draft (do not publish)",
+ "Add to Queue": "Add to Queue",
+ "Schedule": "Schedule",
+ "Publish Now": "Publish Now",
+ "Draft (stop it from publishing)": "Draft (stop it from publishing)",
+ "Front (publish next)": "Front (publish next)",
+ "Back": "Back",
+ "Queued": "Queued",
+ "Scheduled": "Scheduled",
+ "Drafts": "Drafts",
+ "Published": "Published",
+ "Text": "Text",
+ "Image": "Image",
+ "Video": "Video",
+ "Multimedia": "Multimedia",
+ "Short": "Short",
+ "Document": "Document",
+ "Thread": "Thread",
+ "Slides": "Slides",
+ "Reel": "Reel",
+ "Tiktok": "Tiktok",
+ "Story": "Story",
+ "Poll": "Poll",
+ "Engage Comment": "Engage Comment",
+ "Scheduled date": "Scheduled date",
+ "Created date": "Created date",
+ "Updated date": "Updated date",
+ "Newest / highest first": "Newest / highest first",
+ "Oldest / lowest first": "Oldest / lowest first",
+ "Failed": "Failed",
+ "Retrying": "Retrying",
+ "Skipped": "Skipped",
+ "Sent": "Sent",
+ "Newest (ID)": "Newest (ID)",
+ "Likes": "Likes",
+ "Comments": "Comments",
+ "Shares": "Shares",
+ "Active": "Active",
+ "Paused": "Paused",
+ "RSS": "RSS",
+ "ATOM": "ATOM",
+ "YOUTUBE": "YOUTUBE",
+ "MEDIUM": "MEDIUM",
+ "SHOPIFY": "SHOPIFY",
+ "WORDPRESS": "WORDPRESS",
+ "WOOCOMMERCE": "WOOCOMMERCE",
+ "ETSY": "ETSY",
+ "GHOST": "GHOST",
+ "SUBSTACK": "SUBSTACK",
+ "ANCHOR": "ANCHOR",
+ "TRANSISTOR": "TRANSISTOR",
+ "CAPTIVATE": "CAPTIVATE",
+ "SOUNDCLOUD": "SOUNDCLOUD",
+ "BLOGGER": "BLOGGER",
+ "WIX": "WIX",
+ "SQUARESPACEBLOG": "SQUARESPACEBLOG",
+ "SQUARESPACESHOP": "SQUARESPACESHOP",
+ "WEEBLY": "WEEBLY",
+ "TUMBLR": "TUMBLR",
+ "SHOPIFY2": "SHOPIFY2",
+ "WOOCOMMERCE2": "WOOCOMMERCE2",
+ "PRESTASHOP": "PRESTASHOP",
+ "BUZZSPROUT": "BUZZSPROUT",
+ "RSSCOM": "RSSCOM",
+ "CASTOS": "CASTOS",
+ "PODCASTCO": "PODCASTCO",
+ "LINK": "LINK",
+ "IMAGE": "IMAGE",
+ "VIDEO": "VIDEO",
+ "CAROUSEL": "CAROUSEL",
+ "1 h": "1 h",
+ "6 h": "6 h",
+ "12 h": "12 h",
+ "24 h": "24 h",
+ "GIF": "GIF",
+ "APPLICATION": "APPLICATION",
+ "DOCUMENT": "DOCUMENT",
+ "CSV": "CSV",
+ "Draft": "Draft",
+ "Queue": "Queue",
+ "1 day": "1 day",
+ "3 days": "3 days",
+ "7 days": "7 days",
+ "Front": "Front",
+ "QUEUE": "QUEUE",
+ "SCHEDULED": "SCHEDULED",
+ "DRAFT": "DRAFT",
+ "PUBLISHED": "PUBLISHED",
+ "PENDING": "PENDING",
+ "TEXT": "TEXT",
+ "MULTIMEDIA": "MULTIMEDIA",
+ "SHORT": "SHORT",
+ "THREAD": "THREAD",
+ "SLIDES": "SLIDES",
+ "REEL": "REEL",
+ "TIKTOK": "TIKTOK",
+ "STORY": "STORY",
+ "POLL": "POLL",
+ "ENGAGE_COMMENT": "ENGAGE_COMMENT",
+ "NOW": "NOW",
+ "SCHEDULE": "SCHEDULE",
+ "id": "id",
+ "title": "title",
+ "post_date": "post_date",
+ "created_at": "created_at",
+ "updated_at": "updated_at",
+ "FAILED": "FAILED",
+ "RETRYING": "RETRYING",
+ "SKIPPED": "SKIPPED",
+ "SENT": "SENT",
+ "likes": "likes",
+ "comments": "comments",
+ "shares": "shares",
+ "New Published Post": "New Published Post",
+ "Fires when Nuelink publishes a post to a channel (or fails to, if you choose Failed). Runs once per channel.": "Fires when Nuelink publishes a post to a channel (or fails to, if you choose Failed). Runs once per channel.",
+ "Trigger On": "Trigger On",
+ "Only fire for posts from this collection. Leave empty for all collections.": "Only fire for posts from this collection. Leave empty for all collections.",
+ "Failed to publish": "Failed to publish"
}
\ No newline at end of file
diff --git a/packages/pieces/community/nuelink/src/index.ts b/packages/pieces/community/nuelink/src/index.ts
index d366f875e73..3ee93d90d48 100644
--- a/packages/pieces/community/nuelink/src/index.ts
+++ b/packages/pieces/community/nuelink/src/index.ts
@@ -1,21 +1,74 @@
-
-import { createPiece, PieceAuth } from "@activepieces/pieces-framework";
-import { createPost } from "./lib/actions/create-post";
-import { PieceCategory } from '@activepieces/pieces-framework';
-
-export const nuelinkAuth = PieceAuth.SecretText({
- displayName: 'API Key',
- required: true,
- description: 'Please use **Nuelink API Key**.',
-});
+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';
+import { nuelinkAuths } from './lib/auth';
+import { createPost } from './lib/actions/create-post';
+import { createCollectionPost } from './lib/actions/create-collection-post';
+import { updatePost } from './lib/actions/update-post';
+import { deletePost } from './lib/actions/delete-post';
+import { listPosts } from './lib/actions/list-posts';
+import { listPublishedPosts } from './lib/actions/list-published-posts';
+import { uploadMedia } from './lib/actions/upload-media';
+import { aiListBrands } from './lib/actions/ai/list-brands';
+import { aiListCollections } from './lib/actions/ai/list-collections';
+import { aiGetMe } from './lib/actions/ai/get-me';
+import { aiGetSchedule } from './lib/actions/ai/get-schedule';
+import { aiListChannels } from './lib/actions/ai/list-channels';
+import { aiCreateCollection } from './lib/actions/ai/create-collection';
+import { aiUpdateCollection } from './lib/actions/ai/update-collection';
+import { aiAddCollectionChannel } from './lib/actions/ai/add-collection-channel';
+import { aiRemoveCollectionChannel } from './lib/actions/ai/remove-collection-channel';
+import { aiAddCollectionQueueSlot } from './lib/actions/ai/add-collection-queue-slot';
+import { aiDeleteCollectionQueueSlot } from './lib/actions/ai/delete-collection-queue-slot';
+import { aiListAutomations } from './lib/actions/ai/list-automations';
+import { aiCreateAutomation } from './lib/actions/ai/create-automation';
+import { aiUpdateAutomationStatus } from './lib/actions/ai/update-automation-status';
+import { aiListMedia } from './lib/actions/ai/list-media';
+import { aiUploadFile } from './lib/actions/ai/upload-file';
+import { aiCreatePost } from './lib/actions/ai/create-post';
+import { aiUpdatePost } from './lib/actions/ai/update-post';
+import { aiMovePosts } from './lib/actions/ai/move-posts';
+import { aiDeletePost } from './lib/actions/ai/delete-post';
+import { aiListBrandPosts } from './lib/actions/ai/list-brand-posts';
+import { aiListPublishedPosts } from './lib/actions/ai/list-published-posts';
+import { newPublishedPost } from './lib/triggers/new-published-post';
export const nuelink = createPiece({
- displayName: "Nuelink",
- auth: nuelinkAuth,
- minimumSupportedRelease: '0.36.1',
- logoUrl: "https://cdn.activepieces.com/pieces/nuelink.png",
- categories:[PieceCategory.CONTENT_AND_FILES,PieceCategory.MARKETING],
+ displayName: 'Nuelink',
+ description: 'Social media scheduling: create, schedule, edit and track posts across your Nuelink brands and collections.',
+ auth: nuelinkAuths,
+ minimumSupportedRelease: '0.88.2',
+ logoUrl: 'https://cdn.activepieces.com/pieces/nuelink.png',
+ categories: [PieceCategory.CONTENT_AND_FILES, PieceCategory.MARKETING],
authors: ['AouladLahceneOussama'],
- actions: [createPost],
- triggers: [],
+ actions: [
+ createCollectionPost,
+ updatePost,
+ deletePost,
+ listPosts,
+ listPublishedPosts,
+ uploadMedia,
+ createPost,
+ aiListBrands,
+ aiListCollections,
+ aiGetMe,
+ aiGetSchedule,
+ aiListChannels,
+ aiCreateCollection,
+ aiUpdateCollection,
+ aiAddCollectionChannel,
+ aiRemoveCollectionChannel,
+ aiAddCollectionQueueSlot,
+ aiDeleteCollectionQueueSlot,
+ aiListAutomations,
+ aiCreateAutomation,
+ aiUpdateAutomationStatus,
+ aiListMedia,
+ aiUploadFile,
+ aiCreatePost,
+ aiUpdatePost,
+ aiMovePosts,
+ aiDeletePost,
+ aiListBrandPosts,
+ aiListPublishedPosts,
+ ],
+ triggers: [newPublishedPost],
});
diff --git a/packages/pieces/community/nuelink/src/lib/actions/ai/add-collection-channel.ts b/packages/pieces/community/nuelink/src/lib/actions/ai/add-collection-channel.ts
new file mode 100644
index 00000000000..a7153516180
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/actions/ai/add-collection-channel.ts
@@ -0,0 +1,33 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { nuelinkAuths } from '../../auth';
+import { nuelinkAiProps } from '../../common/ai-props';
+import { nuelinkClient } from '../../common/client';
+import { nuelinkOutputSchemas } from '../../output-schemas';
+import { nuelinkCollectionChannels } from '../../common/operations';
+
+export const aiAddCollectionChannel = createAction({
+ name: 'nuelink_add_collection_channel',
+ classification: 'WRITE',
+ auth: nuelinkAuths,
+ displayName: 'Add Channel to Collection',
+ description: 'Connects one of the brand\'s channels to a collection, so the collection\'s posts publish there too.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Adds a brand channel (from nuelink_list_channels) to a collection. The channel then receives ALL of the collection\'s posts, including ones already queued and scheduled, not only future ones: call nuelink_list_collections first and confirm its postsCount.queued and scheduled with the user. To stage a channel without publishing, pause the collection first with nuelink_update_collection status PAUSED. Adding a channel that is already assigned changes nothing.',
+ idempotent: true,
+ },
+ props: {
+ brandId: nuelinkAiProps.brandId(),
+ collectionId: nuelinkAiProps.collectionId({ required: true, description: 'The numeric collection ID from nuelink_list_collections.' }),
+ channelId: nuelinkAiProps.idText({ displayName: 'Channel ID', description: 'The numeric channel ID from nuelink_list_channels.', required: true }),
+ },
+ outputSchema: nuelinkOutputSchemas.collectionChannel,
+ async run(context) {
+ const apiKey = nuelinkClient.apiKeyOf({ auth: context.auth });
+ const brandId = nuelinkClient.numericId({ value: context.propsValue.brandId, label: 'Brand ID' });
+ const collectionId = nuelinkClient.numericId({ value: context.propsValue.collectionId, label: 'Collection ID' });
+ const channelId = nuelinkClient.bodyId({ value: context.propsValue.channelId, label: 'Channel ID' });
+ return nuelinkCollectionChannels.add({ apiKey, brandId, collectionId, channelId });
+ },
+});
diff --git a/packages/pieces/community/nuelink/src/lib/actions/ai/add-collection-queue-slot.ts b/packages/pieces/community/nuelink/src/lib/actions/ai/add-collection-queue-slot.ts
new file mode 100644
index 00000000000..8d406a1a0a7
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/actions/ai/add-collection-queue-slot.ts
@@ -0,0 +1,41 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { nuelinkAuths } from '../../auth';
+import { nuelinkAiProps } from '../../common/ai-props';
+import { NUELINK_LIMITS, nuelinkClient } from '../../common/client';
+import { nuelinkOutputSchemas } from '../../output-schemas';
+import { nuelinkInputs } from '../../common/inputs';
+
+export const aiAddCollectionQueueSlot = createAction({
+ name: 'nuelink_add_collection_queue_slot',
+ classification: 'WRITE',
+ auth: nuelinkAuths,
+ displayName: 'Add Queue Time Slot',
+ description: 'Adds a weekly time slot (weekday and time, brand timezone) to a collection\'s queue.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Adds one weekly queue slot to a collection, given as weekday plus 24-hour time in the BRAND timezone (from nuelink_list_brands), e.g. "Tue 09:00"; do not convert time zones. Queued posts publish at these slots. Nuelink does not reject duplicates, so check nuelink_get_schedule or nuelink_list_collections first, and after a timeout check again before retrying.',
+ idempotent: false,
+ },
+ props: {
+ brandId: nuelinkAiProps.brandId(),
+ collectionId: nuelinkAiProps.collectionId({ required: true, description: 'The numeric collection ID from nuelink_list_collections.' }),
+ slot: Property.ShortText({ displayName: 'Slot', description: 'Weekday and brand-local 24-hour time, e.g. "Tue 09:00".', required: true }),
+ },
+ outputSchema: nuelinkOutputSchemas.queueSlot,
+ async run(context) {
+ const apiKey = nuelinkClient.apiKeyOf({ auth: context.auth });
+ const brandId = nuelinkClient.numericId({ value: context.propsValue.brandId, label: 'Brand ID' });
+ const collectionId = nuelinkClient.numericId({ value: context.propsValue.collectionId, label: 'Collection ID' });
+ const date = nuelinkInputs.queueSlot({ value: context.propsValue.slot, label: 'Slot' });
+ return nuelinkClient.request({
+ apiKey,
+ method: HttpMethod.POST,
+ path: ['brands', brandId, 'collections', collectionId, 'queues'],
+ body: { date },
+ timeoutMs: NUELINK_LIMITS.createTimeoutMs,
+ timeoutHint: 'The slot may still have been added. Check nuelink_get_schedule before trying again.',
+ });
+ },
+});
diff --git a/packages/pieces/community/nuelink/src/lib/actions/ai/create-automation.ts b/packages/pieces/community/nuelink/src/lib/actions/ai/create-automation.ts
new file mode 100644
index 00000000000..0c34502c4fb
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/actions/ai/create-automation.ts
@@ -0,0 +1,91 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { nuelinkAuths } from '../../auth';
+import { nuelinkAiProps } from '../../common/ai-props';
+import { NUELINK_LIMITS, nuelinkClient } from '../../common/client';
+import { nuelinkOutputSchemas } from '../../output-schemas';
+import { nuelinkInputs } from '../../common/inputs';
+import { FEED_TYPES, IMPORT_TYPES, REFRESH_RATES } from '../../common/operations';
+
+export const aiCreateAutomation = createAction({
+ name: 'nuelink_create_automation',
+ classification: 'WRITE',
+ auth: nuelinkAuths,
+ displayName: 'Create Feed Automation',
+ description: 'Creates an RSS or feed automation that turns new feed items into posts in a collection.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates a feed importer (RSS, YouTube, WordPress, Shopify, …) that adds each new feed item as a post in a collection; those posts go to that collection\'s channels. By default posts are added as drafts and old items are not back-filled; addPostsAsDraft false makes new items publish through the queue, and loadOldPosts true with addPostsAsDraft false is refused. Automations cannot be deleted through the API: to stop one use nuelink_update_automation_status PAUSED. Nuelink fetches the feed first (400 if it cannot). Each call creates a new automation: after a timeout check nuelink_list_automations before retrying.',
+ idempotent: false,
+ },
+ props: {
+ brandId: nuelinkAiProps.brandId(),
+ collectionId: nuelinkAiProps.collectionId({ required: true, description: 'The numeric collection ID (nuelink_list_collections) that receives the posts.' }),
+ name: Property.ShortText({ displayName: 'Name', description: 'Automation name, up to 255 characters.', required: true }),
+ type: Property.StaticDropdown({
+ displayName: 'Feed Type',
+ required: true,
+ options: { options: FEED_TYPES.map((value) => ({ label: value, value })) },
+ }),
+ feedUrl: Property.ShortText({ displayName: 'Feed URL', description: 'Public http(s) URL of the feed.', required: true }),
+ importAsType: Property.StaticDropdown({
+ displayName: 'Import As',
+ required: true,
+ options: { options: IMPORT_TYPES.map((value) => ({ label: value, value })) },
+ }),
+ title: Property.ShortText({ displayName: 'Title Template', description: 'Up to 255 characters; placeholders {{title}}, {{description}}, {{link}}. Default {{title}}.', required: false }),
+ caption: Property.ShortText({ displayName: 'Caption Template', description: 'Up to 255 characters; placeholders {{title}}, {{description}}, {{link}}.', required: false }),
+ addPostsAsDraft: Property.Checkbox({ displayName: 'Add Posts as Drafts', description: 'Defaults to true. False lets imported posts publish through the queue.', required: false }),
+ loadOldPosts: Property.Checkbox({ displayName: 'Import Existing Feed Items', description: 'Defaults to false. True back-fills the whole feed; only allowed with drafts.', required: false }),
+ refreshRate: Property.StaticDropdown({
+ displayName: 'Refresh Every (hours)',
+ required: false,
+ options: { options: REFRESH_RATES.map((value) => ({ label: `${value} h`, value })) },
+ }),
+ },
+ outputSchema: nuelinkOutputSchemas.automation,
+ async run(context) {
+ const apiKey = nuelinkClient.apiKeyOf({ auth: context.auth });
+ const props = context.propsValue;
+ const brandId = nuelinkClient.numericId({ value: props.brandId, label: 'Brand ID' });
+ const collectionId = nuelinkClient.bodyId({ value: props.collectionId, label: 'Collection ID' });
+ const name = nuelinkInputs.requiredText({ value: props.name, label: 'Name', max: 255 }).trim();
+ const type = nuelinkInputs.oneOf({ value: props.type, label: 'Feed Type', allowed: FEED_TYPES });
+ const importAsType = nuelinkInputs.oneOf({ value: props.importAsType, label: 'Import As', allowed: IMPORT_TYPES });
+ if (type === undefined || importAsType === undefined) {
+ throw new Error('Feed Type and Import As are required.');
+ }
+ const feedUrl = nuelinkInputs.httpUrl({ value: nuelinkInputs.requiredText({ value: props.feedUrl, label: 'Feed URL', max: 1000 }), label: 'Feed URL' });
+ const title = nuelinkInputs.optionalText({ value: props.title, label: 'Title Template', max: 255 });
+ const caption = nuelinkInputs.optionalText({ value: props.caption, label: 'Caption Template', max: 255 });
+ const refreshRate = nuelinkInputs.optionalInteger({ value: props.refreshRate, label: 'Refresh Every (hours)', min: 1, max: 24 });
+ if (refreshRate !== undefined && !REFRESH_RATES.includes(refreshRate)) {
+ throw new Error('Refresh Every (hours) must be 1, 6, 12 or 24.');
+ }
+ const addPostsAsDraft = props.addPostsAsDraft === undefined || props.addPostsAsDraft === null ? true : nuelinkInputs.isChecked({ value: props.addPostsAsDraft });
+ const loadOldPosts = props.loadOldPosts === undefined || props.loadOldPosts === null ? false : nuelinkInputs.isChecked({ value: props.loadOldPosts });
+ if (loadOldPosts && !addPostsAsDraft) {
+ throw new Error('Importing existing feed items is only allowed with Add Posts as Drafts on, so the whole feed is not pushed into the publishing queue.');
+ }
+ return nuelinkClient.request({
+ apiKey,
+ method: HttpMethod.POST,
+ path: ['brands', brandId, 'automations'],
+ body: {
+ name,
+ collectionId,
+ type,
+ feedUrl,
+ importAsType,
+ ...(title === undefined ? {} : { title }),
+ ...(caption === undefined ? {} : { caption }),
+ addPostsAsDraft,
+ loadOldPosts,
+ ...(refreshRate === undefined ? {} : { refreshRate }),
+ },
+ timeoutMs: NUELINK_LIMITS.createTimeoutMs,
+ timeoutHint: 'The automation may still have been created. Check nuelink_list_automations before trying again.',
+ });
+ },
+});
diff --git a/packages/pieces/community/nuelink/src/lib/actions/ai/create-collection.ts b/packages/pieces/community/nuelink/src/lib/actions/ai/create-collection.ts
new file mode 100644
index 00000000000..08eb765da32
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/actions/ai/create-collection.ts
@@ -0,0 +1,54 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { nuelinkAuths } from '../../auth';
+import { nuelinkAiProps } from '../../common/ai-props';
+import { NUELINK_LIMITS, nuelinkClient } from '../../common/client';
+import { nuelinkOutputSchemas } from '../../output-schemas';
+import { nuelinkInputs } from '../../common/inputs';
+
+export const aiCreateCollection = createAction({
+ name: 'nuelink_create_collection',
+ classification: 'WRITE',
+ auth: nuelinkAuths,
+ displayName: 'Create Collection',
+ description: 'Creates a collection in a brand, optionally with channels and weekly queue time slots.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates a new collection (a queue of posts with its own channels and weekly time slots). Collections cannot be deleted through the API, so call nuelink_list_collections first and reuse an existing one when it fits. channels are channel IDs from nuelink_list_channels; queues are brand-local weekday slots like "Tue 09:00" (brand timezone from nuelink_list_brands; at most 10 per day, 5 if the account is unverified). maxRepublish is the evergreen republish interval in weeks (0 = off). Each call creates a new collection: after a timeout check nuelink_list_collections before retrying.',
+ idempotent: false,
+ },
+ props: {
+ brandId: nuelinkAiProps.brandId(),
+ title: Property.ShortText({ displayName: 'Title', description: 'Collection name, 1 to 255 characters.', required: true }),
+ description: Property.LongText({ displayName: 'Description', description: 'Up to 1,000 characters.', required: false }),
+ maxRepublish: Property.Number({ displayName: 'Evergreen Republish Interval (weeks)', description: 'Republish posts every N weeks; 0 or empty turns it off.', required: false }),
+ channels: Property.Array({ displayName: 'Channel IDs', description: 'Numeric channel IDs from nuelink_list_channels. Posts in the collection publish to these.', required: false }),
+ queues: Property.Array({ displayName: 'Queue Slots', description: 'Weekly brand-local slots like "Mon 09:30". Duplicates are removed.', required: false }),
+ },
+ outputSchema: nuelinkOutputSchemas.collection,
+ async run(context) {
+ const apiKey = nuelinkClient.apiKeyOf({ auth: context.auth });
+ const props = context.propsValue;
+ const brandId = nuelinkClient.numericId({ value: props.brandId, label: 'Brand ID' });
+ const title = nuelinkInputs.requiredText({ value: props.title, label: 'Title', max: 255 }).trim();
+ const description = nuelinkInputs.optionalText({ value: props.description, label: 'Description', max: 1000 });
+ const maxRepublish = nuelinkInputs.optionalInteger({ value: props.maxRepublish, label: 'Evergreen Republish Interval (weeks)', min: 0, max: 10000 });
+ const channels = nuelinkInputs.bodyIds({ value: props.channels, label: 'Channel IDs', maxItems: 500 });
+ const queues = nuelinkInputs.queueSlots({ value: props.queues, label: 'Queue Slots' });
+ return nuelinkClient.request({
+ apiKey,
+ method: HttpMethod.POST,
+ path: ['brands', brandId, 'collections'],
+ body: {
+ title,
+ ...(description === undefined ? {} : { description }),
+ ...(maxRepublish === undefined ? {} : { maxRepublish }),
+ ...(channels.length === 0 ? {} : { channels }),
+ ...(queues.length === 0 ? {} : { queues }),
+ },
+ timeoutMs: NUELINK_LIMITS.createTimeoutMs,
+ timeoutHint: 'The collection may still have been created. Check nuelink_list_collections before trying again.',
+ });
+ },
+});
diff --git a/packages/pieces/community/nuelink/src/lib/actions/ai/create-post.ts b/packages/pieces/community/nuelink/src/lib/actions/ai/create-post.ts
new file mode 100644
index 00000000000..06d71f0ebb2
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/actions/ai/create-post.ts
@@ -0,0 +1,85 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { nuelinkAuths } from '../../auth';
+import { nuelinkAiProps } from '../../common/ai-props';
+import { nuelinkClient } from '../../common/client';
+import { nuelinkPosts } from '../../common/operations';
+import { nuelinkOutputSchemas } from '../../output-schemas';
+
+export const aiCreatePost = createAction({
+ name: 'nuelink_create_post',
+ classification: 'WRITE',
+ auth: nuelinkAuths,
+ displayName: 'Create Post',
+ description: 'Creates a post (caption, poll or both) in a Nuelink collection as a draft, in the queue, scheduled or published now.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates a post in a collection; it goes to every channel of that collection (check them with nuelink_list_collections). publishMode defaults to DRAFT; use IMMEDIATE only when the user explicitly asks to post now, and QUEUE or SCHEDULE only on explicit intent to publish. scheduledAt must be ISO-8601 with an offset (e.g. 2026-10-12T09:00:00+03:00), at least 10 minutes ahead; it is converted to the brand timezone from nuelink_list_brands. Needs a caption, a poll, or both; polls cannot be edited later and only reach LinkedIn, X, Telegram, Threads, Mastodon and Bluesky. Each call creates a new post: after a timeout, check nuelink_list_brand_posts before retrying.',
+ idempotent: false,
+ },
+ props: {
+ brandId: nuelinkAiProps.brandId(),
+ collectionId: nuelinkAiProps.collectionId({ required: true, description: 'The numeric collection ID from nuelink_list_collections. The post goes to every channel in it.' }),
+ publishMode: Property.StaticDropdown({
+ displayName: 'Publish Mode',
+ description: 'DRAFT (default) saves without publishing, QUEUE takes the next free slot, SCHEDULE publishes at Scheduled Time, IMMEDIATE publishes now.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Draft', value: 'DRAFT' },
+ { label: 'Queue', value: 'QUEUE' },
+ { label: 'Schedule', value: 'SCHEDULE' },
+ { label: 'Publish Now', value: 'IMMEDIATE' },
+ ],
+ },
+ }),
+ scheduledAt: Property.ShortText({
+ displayName: 'Scheduled Time',
+ description: 'Only with Publish Mode SCHEDULE. ISO-8601 with an offset or Z, e.g. 2026-10-12T09:00:00+03:00.',
+ required: false,
+ }),
+ caption: Property.LongText({
+ displayName: 'Caption',
+ description: 'Post text, up to 3,000 characters. Optional when a poll is set.',
+ required: false,
+ }),
+ title: Property.ShortText({ displayName: 'Title', description: 'Title for videos, Reels and Pinterest pins (up to 255 characters).', required: false }),
+ media: Property.Array({
+ displayName: 'Media',
+ description: 'Up to 10 entries: public http(s) URLs, or media IDs from nuelink_upload_file or nuelink_list_media.',
+ required: false,
+ }),
+ alt: Property.ShortText({ displayName: 'Alt Text', description: 'Alt text for the media (up to 255 characters).', required: false }),
+ link: Property.ShortText({ displayName: 'Link', description: 'Destination link for Pinterest pins and the Google Business button.', required: false }),
+ postAsStory: Property.Checkbox({ displayName: 'Post as Story', description: 'Publish as a story where supported.', required: false }),
+ autoThreadText: Property.Checkbox({ displayName: 'Split Long Text into a Thread', description: 'Let Nuelink split long text into a thread.', required: false }),
+ firstComment: Property.LongText({ displayName: 'First Comment', description: 'Comment added after publishing (up to 1,000 characters). Needs First Comment Delay.', required: false }),
+ firstCommentDelaySeconds: Property.Number({ displayName: 'First Comment Delay (seconds)', description: 'Seconds after publishing to add the first comment.', required: false }),
+ pollQuestion: Property.ShortText({ displayName: 'Poll Question', description: 'Up to 280 characters. Setting any poll field requires Question, Options and Duration.', required: false }),
+ pollOptions: Property.Array({ displayName: 'Poll Options', description: '2 to 4 answers, each up to 30 characters.', required: false }),
+ pollPeriod: Property.StaticDropdown({
+ displayName: 'Poll Duration',
+ required: false,
+ options: {
+ options: [
+ { label: '1 day', value: '1d' },
+ { label: '3 days', value: '3d' },
+ { label: '7 days', value: '7d' },
+ ],
+ },
+ }),
+ pollCorrectOptionIndex: Property.Number({ displayName: 'Poll Correct Option Index', description: 'Zero-based index of the correct answer, for quiz polls.', required: false }),
+ pollExplanation: Property.LongText({ displayName: 'Poll Explanation', description: 'Shown with the correct answer (up to 512 characters).', required: false }),
+ instagramShareToFeed: Property.Checkbox({ displayName: 'Instagram: Share Reel to Feed', required: false }),
+ instagramCollab: Property.ShortText({ displayName: 'Instagram: Collaborator', description: 'Instagram username to invite as collaborator.', required: false }),
+ tiktokAutoAddMusic: Property.Checkbox({ displayName: 'TikTok: Add Music Automatically', required: false }),
+ youtubeTags: Property.Array({ displayName: 'YouTube: Tags', required: false }),
+ },
+ outputSchema: nuelinkOutputSchemas.createCollectionPost,
+ async run(context) {
+ const apiKey = nuelinkClient.apiKeyOf({ auth: context.auth });
+ const brandId = nuelinkClient.numericId({ value: context.propsValue.brandId, label: 'Brand ID' });
+ const collectionId = nuelinkClient.numericId({ value: context.propsValue.collectionId, label: 'Collection ID' });
+ return nuelinkPosts.create({ apiKey, brandId, collectionId, props: context.propsValue, pollAllowed: true });
+ },
+});
diff --git a/packages/pieces/community/nuelink/src/lib/actions/ai/delete-collection-queue-slot.ts b/packages/pieces/community/nuelink/src/lib/actions/ai/delete-collection-queue-slot.ts
new file mode 100644
index 00000000000..4ad6fb2625a
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/actions/ai/delete-collection-queue-slot.ts
@@ -0,0 +1,33 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { nuelinkAuths } from '../../auth';
+import { nuelinkAiProps } from '../../common/ai-props';
+import { nuelinkOutputSchemas } from '../../output-schemas';
+import { nuelinkClient } from '../../common/client';
+
+export const aiDeleteCollectionQueueSlot = createAction({
+ name: 'nuelink_delete_collection_queue_slot',
+ classification: 'DESTRUCTIVE',
+ auth: nuelinkAuths,
+ displayName: 'Delete Queue Time Slot',
+ description: 'Deletes one weekly time slot from a collection\'s queue.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Deletes one weekly queue slot of a collection; queueId comes from nuelink_get_schedule (queueId) or nuelink_list_collections (queues[].id). Queued posts then wait for the remaining slots. Confirm with the user first. A repeat call returns 404.',
+ idempotent: false,
+ },
+ props: {
+ brandId: nuelinkAiProps.brandId(),
+ collectionId: nuelinkAiProps.collectionId({ required: true, description: 'The numeric collection ID the slot belongs to.' }),
+ queueId: nuelinkAiProps.idText({ displayName: 'Slot ID', description: 'The numeric queue slot ID from nuelink_get_schedule or nuelink_list_collections.', required: true }),
+ },
+ outputSchema: nuelinkOutputSchemas.deletedQueueSlot,
+ async run(context) {
+ const apiKey = nuelinkClient.apiKeyOf({ auth: context.auth });
+ const brandId = nuelinkClient.numericId({ value: context.propsValue.brandId, label: 'Brand ID' });
+ const collectionId = nuelinkClient.numericId({ value: context.propsValue.collectionId, label: 'Collection ID' });
+ const queueId = nuelinkClient.numericId({ value: context.propsValue.queueId, label: 'Slot ID' });
+ return nuelinkClient.request({ apiKey, method: HttpMethod.DELETE, path: ['brands', brandId, 'collections', collectionId, 'queues', queueId] });
+ },
+});
diff --git a/packages/pieces/community/nuelink/src/lib/actions/ai/delete-post.ts b/packages/pieces/community/nuelink/src/lib/actions/ai/delete-post.ts
new file mode 100644
index 00000000000..d46c2f9eb98
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/actions/ai/delete-post.ts
@@ -0,0 +1,31 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { nuelinkAuths } from '../../auth';
+import { nuelinkAiProps } from '../../common/ai-props';
+import { nuelinkClient } from '../../common/client';
+import { nuelinkPosts } from '../../common/operations';
+import { nuelinkOutputSchemas } from '../../output-schemas';
+
+export const aiDeletePost = createAction({
+ name: 'nuelink_delete_post',
+ classification: 'DESTRUCTIVE',
+ auth: nuelinkAuths,
+ displayName: 'Delete Post',
+ description: 'Permanently deletes a post from Nuelink, in any status. Content already on a social network stays there.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Permanently deletes one post from Nuelink (any status, published included); what is already on a social network stays there. To only stop a post from going out, use nuelink_update_post with publishMode DRAFT instead. Nuelink refuses this (403) unless the account owner enabled "Allow AI to perform sensitive actions" in Settings → API. Cannot be undone; a repeat call returns 404.',
+ idempotent: false,
+ },
+ props: {
+ brandId: nuelinkAiProps.brandId(),
+ postId: nuelinkAiProps.idText({ displayName: 'Post ID', description: 'The numeric post ID from nuelink_list_brand_posts.', required: true }),
+ },
+ outputSchema: nuelinkOutputSchemas.deletePost,
+ async run(context) {
+ const apiKey = nuelinkClient.apiKeyOf({ auth: context.auth });
+ const brandId = nuelinkClient.numericId({ value: context.propsValue.brandId, label: 'Brand ID' });
+ const postId = nuelinkClient.numericId({ value: context.propsValue.postId, label: 'Post ID' });
+ return nuelinkPosts.remove({ apiKey, brandId, postId });
+ },
+});
diff --git a/packages/pieces/community/nuelink/src/lib/actions/ai/get-me.ts b/packages/pieces/community/nuelink/src/lib/actions/ai/get-me.ts
new file mode 100644
index 00000000000..02b935fc50e
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/actions/ai/get-me.ts
@@ -0,0 +1,25 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { nuelinkAuths } from '../../auth';
+import { nuelinkOutputSchemas } from '../../output-schemas';
+import { nuelinkClient } from '../../common/client';
+
+export const aiGetMe = createAction({
+ name: 'nuelink_get_me',
+ classification: 'READ',
+ auth: nuelinkAuths,
+ displayName: 'Get Profile',
+ description: 'Returns the Nuelink user the API key belongs to.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns the user the API key acts as (opaque id, name, joinedAt, timezone), to confirm whose account is in use. The user timezone may be null or an internal UUID: never use it for scheduling; scheduled times use the brand timezone from nuelink_list_brands. Read-only.',
+ idempotent: true,
+ },
+ props: {},
+ outputSchema: nuelinkOutputSchemas.profile,
+ async run(context) {
+ const apiKey = nuelinkClient.apiKeyOf({ auth: context.auth });
+ return nuelinkClient.request({ apiKey, method: HttpMethod.GET, path: ['me'] });
+ },
+});
diff --git a/packages/pieces/community/nuelink/src/lib/actions/ai/get-schedule.ts b/packages/pieces/community/nuelink/src/lib/actions/ai/get-schedule.ts
new file mode 100644
index 00000000000..d5fe6fb0d43
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/actions/ai/get-schedule.ts
@@ -0,0 +1,29 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { nuelinkAuths } from '../../auth';
+import { nuelinkAiProps } from '../../common/ai-props';
+import { nuelinkOutputSchemas } from '../../output-schemas';
+import { nuelinkClient } from '../../common/client';
+
+export const aiGetSchedule = createAction({
+ name: 'nuelink_get_schedule',
+ classification: 'READ',
+ auth: nuelinkAuths,
+ displayName: 'Get Weekly Queue Schedule',
+ description: 'Returns every weekly queue time slot of a brand, grouped by weekday, in the brand timezone.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns the brand\'s whole weekly queue (MON..SUN, each slot with time, queueId, collectionId, collectionTitle, collectionStatus) in the brand timezone. Use it to answer when queued posts will go out, or to find a queueId for nuelink_delete_collection_queue_slot. When queueStatus is PAUSED nothing publishes from the queues. Slots of paused collections are not listed, and timezone may be an offset like +03:00. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ brandId: nuelinkAiProps.brandId(),
+ },
+ outputSchema: nuelinkOutputSchemas.schedule,
+ async run(context) {
+ const apiKey = nuelinkClient.apiKeyOf({ auth: context.auth });
+ const brandId = nuelinkClient.numericId({ value: context.propsValue.brandId, label: 'Brand ID' });
+ return nuelinkClient.request({ apiKey, method: HttpMethod.GET, path: ['brands', brandId, 'schedule'] });
+ },
+});
diff --git a/packages/pieces/community/nuelink/src/lib/actions/ai/list-automations.ts b/packages/pieces/community/nuelink/src/lib/actions/ai/list-automations.ts
new file mode 100644
index 00000000000..daaf677cf9c
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/actions/ai/list-automations.ts
@@ -0,0 +1,33 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { nuelinkAuths } from '../../auth';
+import { nuelinkAiProps } from '../../common/ai-props';
+import { nuelinkOutputSchemas } from '../../output-schemas';
+import { nuelinkClient } from '../../common/client';
+import { nuelinkInputs } from '../../common/inputs';
+import { nuelinkProps } from '../../common/props';
+
+export const aiListAutomations = createAction({
+ name: 'nuelink_list_automations',
+ classification: 'SEARCH',
+ auth: nuelinkAuths,
+ displayName: 'List Feed Automations',
+ description: 'Lists a brand\'s RSS and feed automations.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the brand\'s feed automations (id, name, collectionId, status, feed type, feedUrl, runCount, lastRun as a Unix timestamp, title/caption templates). Use it to find an automationId for nuelink_update_automation_status. status may read INACTIVE for a paused automation. One page per call with hasMore. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ brandId: nuelinkAiProps.brandId(),
+ page: nuelinkProps.page(),
+ perPage: nuelinkProps.perPage(),
+ },
+ outputSchema: nuelinkOutputSchemas.listAutomations,
+ async run(context) {
+ const apiKey = nuelinkClient.apiKeyOf({ auth: context.auth });
+ const brandId = nuelinkClient.numericId({ value: context.propsValue.brandId, label: 'Brand ID' });
+ const { page, perPage } = nuelinkInputs.paging({ page: context.propsValue.page, perPage: context.propsValue.perPage });
+ return nuelinkClient.getPage({ apiKey, path: ['brands', brandId, 'automations'], page, perPage });
+ },
+});
diff --git a/packages/pieces/community/nuelink/src/lib/actions/ai/list-brand-posts.ts b/packages/pieces/community/nuelink/src/lib/actions/ai/list-brand-posts.ts
new file mode 100644
index 00000000000..23adbfb80cc
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/actions/ai/list-brand-posts.ts
@@ -0,0 +1,52 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { nuelinkAuths } from '../../auth';
+import { nuelinkAiProps } from '../../common/ai-props';
+import { nuelinkClient } from '../../common/client';
+import { nuelinkInputs } from '../../common/inputs';
+import { POSTING_TYPES, POST_SORT_FIELDS, POST_STATUSES, POST_TYPES, VIEWS, nuelinkPosts } from '../../common/operations';
+import { nuelinkProps } from '../../common/props';
+import { nuelinkOutputSchemas } from '../../output-schemas';
+
+export const aiListBrandPosts = createAction({
+ name: 'nuelink_list_brand_posts',
+ classification: 'SEARCH',
+ auth: nuelinkAuths,
+ displayName: 'List Posts',
+ description: 'Lists a brand\'s posts (drafts, queued, scheduled, published), optionally for one collection, one page at a time.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists a brand\'s posts across collections, or one collection with collectionId, filtered by view, status, post type, posting type and creation time (createdFrom/createdTo are UTC). Use it to find a post ID or to check whether a create already happened. An unknown collectionId returns 404; get IDs from nuelink_list_collections. For per-channel delivery results use nuelink_list_published_posts. One page per call with hasMore. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ brandId: nuelinkAiProps.brandId(),
+ collectionId: nuelinkAiProps.collectionId({ required: false, description: 'Only posts of this collection (numeric ID from nuelink_list_collections). Empty for all.' }),
+ view: staticOptions({ displayName: 'View', values: VIEWS, description: 'QUEUE, SCHEDULED, DRAFT or PUBLISHED.' }),
+ status: staticOptions({ displayName: 'Status', values: POST_STATUSES, description: 'Lifecycle status.' }),
+ postType: staticOptions({ displayName: 'Post Type', values: POST_TYPES, description: 'Content type.' }),
+ postingType: staticOptions({ displayName: 'Posting Type', values: POSTING_TYPES, description: 'How the post is published.' }),
+ createdFrom: Property.ShortText({ displayName: 'Created From', description: 'ISO-8601 time; a value without offset is read as UTC.', required: false }),
+ createdTo: Property.ShortText({ displayName: 'Created To', description: 'ISO-8601 time; a value without offset is read as UTC.', required: false }),
+ sortBy: staticOptions({ displayName: 'Sort By', values: POST_SORT_FIELDS, description: 'Sort field.' }),
+ sortOrder: nuelinkProps.sortOrder(),
+ page: nuelinkProps.page(),
+ perPage: nuelinkProps.perPage(),
+ },
+ outputSchema: nuelinkOutputSchemas.listPosts,
+ async run(context) {
+ const apiKey = nuelinkClient.apiKeyOf({ auth: context.auth });
+ const brandId = nuelinkClient.numericId({ value: context.propsValue.brandId, label: 'Brand ID' });
+ const collectionId = nuelinkInputs.optionalId({ value: context.propsValue.collectionId, label: 'Collection ID' });
+ return nuelinkPosts.list({ apiKey, brandId, collectionId, props: context.propsValue });
+ },
+});
+
+function staticOptions({ displayName, values, description }: { displayName: string; values: readonly string[]; description: string }) {
+ return Property.StaticDropdown({
+ displayName,
+ description,
+ required: false,
+ options: { options: values.map((value) => ({ label: value, value })) },
+ });
+}
diff --git a/packages/pieces/community/nuelink/src/lib/actions/ai/list-brands.ts b/packages/pieces/community/nuelink/src/lib/actions/ai/list-brands.ts
new file mode 100644
index 00000000000..e6bad9491c3
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/actions/ai/list-brands.ts
@@ -0,0 +1,30 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { nuelinkAuths } from '../../auth';
+import { nuelinkClient } from '../../common/client';
+import { nuelinkInputs } from '../../common/inputs';
+import { nuelinkProps } from '../../common/props';
+import { nuelinkOutputSchemas } from '../../output-schemas';
+
+export const aiListBrands = createAction({
+ name: 'nuelink_list_brands',
+ classification: 'SEARCH',
+ auth: nuelinkAuths,
+ displayName: 'List Brands',
+ description: 'Lists the Nuelink brands the API key can access, with their IDs and timezones.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the Nuelink brands (workspaces) the API key can access, with each brand\'s timezone, which scheduled times are interpreted in. Call this first to get a brandId; on multi-brand accounts, match the brand by title instead of taking the first one. One page per call with hasMore. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ page: nuelinkProps.page(),
+ perPage: nuelinkProps.perPage(),
+ },
+ outputSchema: nuelinkOutputSchemas.listBrands,
+ async run(context) {
+ const apiKey = nuelinkClient.apiKeyOf({ auth: context.auth });
+ const { page, perPage } = nuelinkInputs.paging({ page: context.propsValue.page, perPage: context.propsValue.perPage });
+ return nuelinkClient.getPage({ apiKey, path: ['brands'], page, perPage });
+ },
+});
diff --git a/packages/pieces/community/nuelink/src/lib/actions/ai/list-channels.ts b/packages/pieces/community/nuelink/src/lib/actions/ai/list-channels.ts
new file mode 100644
index 00000000000..113cc2f5d38
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/actions/ai/list-channels.ts
@@ -0,0 +1,33 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { nuelinkAuths } from '../../auth';
+import { nuelinkAiProps } from '../../common/ai-props';
+import { nuelinkClient } from '../../common/client';
+import { nuelinkOutputSchemas } from '../../output-schemas';
+import { nuelinkInputs } from '../../common/inputs';
+import { nuelinkProps } from '../../common/props';
+
+export const aiListChannels = createAction({
+ name: 'nuelink_list_channels',
+ classification: 'SEARCH',
+ auth: nuelinkAuths,
+ displayName: 'List Channels',
+ description: 'Lists the social channels connected to a brand.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the social channels connected to the brand (id, name, platform type, status), including ones not in any collection yet. Use it to find a channelId for nuelink_add_collection_channel, nuelink_remove_collection_channel or nuelink_list_published_posts. Pages can be short or empty while total is above 0 (Nuelink counts before filtering), so follow hasMore, not the item count. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ brandId: nuelinkAiProps.brandId(),
+ page: nuelinkProps.page(),
+ perPage: nuelinkProps.perPage(),
+ },
+ outputSchema: nuelinkOutputSchemas.listChannels,
+ async run(context) {
+ const apiKey = nuelinkClient.apiKeyOf({ auth: context.auth });
+ const brandId = nuelinkClient.numericId({ value: context.propsValue.brandId, label: 'Brand ID' });
+ const { page, perPage } = nuelinkInputs.paging({ page: context.propsValue.page, perPage: context.propsValue.perPage });
+ return nuelinkClient.getPage({ apiKey, path: ['brands', brandId, 'channels'], page, perPage });
+ },
+});
diff --git a/packages/pieces/community/nuelink/src/lib/actions/ai/list-collections.ts b/packages/pieces/community/nuelink/src/lib/actions/ai/list-collections.ts
new file mode 100644
index 00000000000..b05dcccf2bd
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/actions/ai/list-collections.ts
@@ -0,0 +1,36 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { nuelinkAuths } from '../../auth';
+import { nuelinkClient } from '../../common/client';
+import { nuelinkInputs } from '../../common/inputs';
+import { nuelinkProps } from '../../common/props';
+import { nuelinkOutputSchemas } from '../../output-schemas';
+
+export const aiListCollections = createAction({
+ name: 'nuelink_list_collections',
+ classification: 'SEARCH',
+ auth: nuelinkAuths,
+ displayName: 'List Collections',
+ description: 'Lists a brand\'s collections with their channels, queue slots and post counts.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists a brand\'s collections with their connected channels, weekly queue slots (brand timezone) and post counts. Use it to choose the collectionId for nuelink_create_post, nuelink_move_posts or nuelink_add_collection_channel, and to read queues[].id for nuelink_delete_collection_queue_slot; the collection\'s channels are where the post will go, and a collection with no channels publishes nowhere. The collection timezone may be an offset such as +03:00; queue slots are in the brand timezone. One page per call with hasMore. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ brandId: Property.ShortText({
+ displayName: 'Brand ID',
+ description: 'The numeric brand ID from List Brands.',
+ required: true,
+ }),
+ page: nuelinkProps.page(),
+ perPage: nuelinkProps.perPage(),
+ },
+ outputSchema: nuelinkOutputSchemas.listCollections,
+ async run(context) {
+ const apiKey = nuelinkClient.apiKeyOf({ auth: context.auth });
+ const brandId = nuelinkClient.numericId({ value: context.propsValue.brandId, label: 'Brand ID' });
+ const { page, perPage } = nuelinkInputs.paging({ page: context.propsValue.page, perPage: context.propsValue.perPage });
+ return nuelinkClient.getPage({ apiKey, path: ['brands', brandId, 'collections'], page, perPage });
+ },
+});
diff --git a/packages/pieces/community/nuelink/src/lib/actions/ai/list-media.ts b/packages/pieces/community/nuelink/src/lib/actions/ai/list-media.ts
new file mode 100644
index 00000000000..04826ef044d
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/actions/ai/list-media.ts
@@ -0,0 +1,41 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { nuelinkAuths } from '../../auth';
+import { nuelinkAiProps } from '../../common/ai-props';
+import { nuelinkOutputSchemas } from '../../output-schemas';
+import { nuelinkClient } from '../../common/client';
+import { nuelinkInputs } from '../../common/inputs';
+import { MEDIA_TYPES } from '../../common/operations';
+import { nuelinkProps } from '../../common/props';
+
+export const aiListMedia = createAction({
+ name: 'nuelink_list_media',
+ classification: 'SEARCH',
+ auth: nuelinkAuths,
+ displayName: 'List Media',
+ description: 'Lists the files in a brand\'s Nuelink media library, newest first.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the brand media library (id, name, MIME type, size, dates), newest first, optionally filtered by type. Reuse an item\'s id in the media list of nuelink_create_post instead of uploading the file again with nuelink_upload_file. One page per call with hasMore. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ brandId: nuelinkAiProps.brandId(),
+ type: Property.StaticDropdown({
+ displayName: 'Type',
+ description: 'Only this media category. APPLICATION covers every document record; DOCUMENT only office/document MIME types.',
+ required: false,
+ options: { options: MEDIA_TYPES.map((value) => ({ label: value, value })) },
+ }),
+ page: nuelinkProps.page(),
+ perPage: nuelinkProps.perPage(),
+ },
+ outputSchema: nuelinkOutputSchemas.listMedia,
+ async run(context) {
+ const apiKey = nuelinkClient.apiKeyOf({ auth: context.auth });
+ const brandId = nuelinkClient.numericId({ value: context.propsValue.brandId, label: 'Brand ID' });
+ const type = nuelinkInputs.oneOf({ value: context.propsValue.type, label: 'Type', allowed: MEDIA_TYPES });
+ const { page, perPage } = nuelinkInputs.paging({ page: context.propsValue.page, perPage: context.propsValue.perPage });
+ return nuelinkClient.getPage({ apiKey, path: ['brands', brandId, 'media'], query: { type }, page, perPage });
+ },
+});
diff --git a/packages/pieces/community/nuelink/src/lib/actions/ai/list-published-posts.ts b/packages/pieces/community/nuelink/src/lib/actions/ai/list-published-posts.ts
new file mode 100644
index 00000000000..60f4713d8b1
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/actions/ai/list-published-posts.ts
@@ -0,0 +1,52 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { nuelinkAuths } from '../../auth';
+import { nuelinkAiProps } from '../../common/ai-props';
+import { nuelinkClient } from '../../common/client';
+import { DELIVERY_STATUSES, PUBLISHED_SORT_FIELDS, nuelinkPosts } from '../../common/operations';
+import { nuelinkProps } from '../../common/props';
+import { nuelinkOutputSchemas } from '../../output-schemas';
+
+export const aiListPublishedPosts = createAction({
+ name: 'nuelink_list_published_posts',
+ classification: 'SEARCH',
+ auth: nuelinkAuths,
+ displayName: 'List Published Posts',
+ description: 'Lists what Nuelink sent to each channel, with delivery status, post URL and engagement counts.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists per-channel delivery results: status, platform URL, error message and engagement (likes, comments, shares, views, saves, clicks, impressions, reach). status defaults to PUBLISHED, so checking a postId with the defaults only shows the channels where it succeeded; query FAILED, RETRYING or SKIPPED to see failures. Filter by collectionId, channelId (nuelink_list_channels), postId (nuelink_list_brand_posts), postType, text search or publish time (UTC). One page per call with hasMore. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ brandId: nuelinkAiProps.brandId(),
+ status: Property.StaticDropdown({
+ displayName: 'Delivery Status',
+ description: 'Defaults to PUBLISHED.',
+ required: false,
+ options: { options: DELIVERY_STATUSES.map((value) => ({ label: value, value })) },
+ }),
+ collectionId: nuelinkAiProps.collectionId({ required: false, description: 'Only results from this collection.' }),
+ channelId: nuelinkAiProps.idText({ displayName: 'Channel ID', description: 'Only results for this channel (from nuelink_list_channels).', required: false }),
+ postId: nuelinkAiProps.idText({ displayName: 'Post ID', description: 'Only results of this post.', required: false }),
+ postType: Property.ShortText({ displayName: 'Post Type', description: 'Only results of this post type, e.g. IMAGE.', required: false }),
+ search: Property.ShortText({ displayName: 'Search Text', description: 'Text contained in the published body (up to 255 characters).', required: false }),
+ publishedFrom: Property.ShortText({ displayName: 'Published From', description: 'ISO-8601 time; without offset it is read as UTC.', required: false }),
+ publishedTo: Property.ShortText({ displayName: 'Published To', description: 'ISO-8601 time; without offset it is read as UTC.', required: false }),
+ sortBy: Property.StaticDropdown({
+ displayName: 'Sort By',
+ required: false,
+ options: { options: PUBLISHED_SORT_FIELDS.map((value) => ({ label: value, value })) },
+ }),
+ sortOrder: nuelinkProps.sortOrder(),
+ page: nuelinkProps.page(),
+ perPage: nuelinkProps.perPage(),
+ },
+ outputSchema: nuelinkOutputSchemas.listPublishedPosts,
+ async run(context) {
+ const apiKey = nuelinkClient.apiKeyOf({ auth: context.auth });
+ const props = context.propsValue;
+ const brandId = nuelinkClient.numericId({ value: props.brandId, label: 'Brand ID' });
+ return nuelinkPosts.listPublished({ apiKey, brandId, props, ids: { collection: props.collectionId, channel: props.channelId, post: props.postId } });
+ },
+});
diff --git a/packages/pieces/community/nuelink/src/lib/actions/ai/move-posts.ts b/packages/pieces/community/nuelink/src/lib/actions/ai/move-posts.ts
new file mode 100644
index 00000000000..da568d9ff2b
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/actions/ai/move-posts.ts
@@ -0,0 +1,48 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { nuelinkAuths } from '../../auth';
+import { nuelinkAiProps } from '../../common/ai-props';
+import { nuelinkClient } from '../../common/client';
+import { nuelinkOutputSchemas } from '../../output-schemas';
+import { nuelinkInputs } from '../../common/inputs';
+
+export const aiMovePosts = createAction({
+ name: 'nuelink_move_posts',
+ classification: 'WRITE',
+ auth: nuelinkAuths,
+ displayName: 'Move Posts to Collection',
+ description: 'Moves up to 100 posts from one collection to another in the same brand.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Moves 1 to 100 posts (IDs from nuelink_list_brand_posts) from a source collection to a different destination collection. All or nothing: if any post is not in the source, nothing moves. Moved posts go to the destination\'s channels unless a post has its own channels set in the dashboard, so read the destination\'s channels with nuelink_list_collections and show them to the user first. A queued post takes the destination\'s next free slot and can publish sooner; a scheduled post keeps its date. The destination must be active and have capacity (403). A repeat call fails.',
+ idempotent: false,
+ },
+ props: {
+ brandId: nuelinkAiProps.brandId(),
+ sourceCollectionId: nuelinkAiProps.idText({ displayName: 'Source Collection ID', description: 'The collection that currently holds every listed post.', required: true }),
+ destinationCollectionId: nuelinkAiProps.idText({ displayName: 'Destination Collection ID', description: 'A different collection of the same brand.', required: true }),
+ postIds: Property.Array({ displayName: 'Post IDs', description: '1 to 100 numeric post IDs.', required: true }),
+ },
+ outputSchema: nuelinkOutputSchemas.movePosts,
+ async run(context) {
+ const apiKey = nuelinkClient.apiKeyOf({ auth: context.auth });
+ const props = context.propsValue;
+ const brandId = nuelinkClient.numericId({ value: props.brandId, label: 'Brand ID' });
+ const sourceCollectionId = nuelinkClient.bodyId({ value: props.sourceCollectionId, label: 'Source Collection ID' });
+ const destinationCollectionId = nuelinkClient.bodyId({ value: props.destinationCollectionId, label: 'Destination Collection ID' });
+ if (sourceCollectionId === destinationCollectionId) {
+ throw new Error('Source and destination collection must be different.');
+ }
+ const postIds = nuelinkInputs.bodyIds({ value: props.postIds, label: 'Post IDs', maxItems: 100 });
+ if (postIds.length === 0) {
+ throw new Error('Post IDs needs at least one post ID.');
+ }
+ return nuelinkClient.request({
+ apiKey,
+ method: HttpMethod.PATCH,
+ path: ['brands', brandId, 'posts', 'move'],
+ body: { sourceCollectionId, destinationCollectionId, postIds },
+ });
+ },
+});
diff --git a/packages/pieces/community/nuelink/src/lib/actions/ai/remove-collection-channel.ts b/packages/pieces/community/nuelink/src/lib/actions/ai/remove-collection-channel.ts
new file mode 100644
index 00000000000..fbac4a46585
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/actions/ai/remove-collection-channel.ts
@@ -0,0 +1,33 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { nuelinkAuths } from '../../auth';
+import { nuelinkAiProps } from '../../common/ai-props';
+import { nuelinkClient } from '../../common/client';
+import { nuelinkOutputSchemas } from '../../output-schemas';
+import { nuelinkCollectionChannels } from '../../common/operations';
+
+export const aiRemoveCollectionChannel = createAction({
+ name: 'nuelink_remove_collection_channel',
+ classification: 'WRITE',
+ auth: nuelinkAuths,
+ displayName: 'Remove Channel from Collection',
+ description: 'Disconnects a channel from a collection. The channel stays connected to the brand.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Removes a channel from a collection so the collection\'s posts stop going to it; the channel stays connected to the brand and nuelink_add_collection_channel restores it. Ask the user before removing, since queued posts will no longer reach that channel. A repeat call returns 404.',
+ idempotent: false,
+ },
+ props: {
+ brandId: nuelinkAiProps.brandId(),
+ collectionId: nuelinkAiProps.collectionId({ required: true, description: 'The numeric collection ID from nuelink_list_collections.' }),
+ channelId: nuelinkAiProps.idText({ displayName: 'Channel ID', description: 'The numeric channel ID, from the collection\'s channels in nuelink_list_collections.', required: true }),
+ },
+ outputSchema: nuelinkOutputSchemas.collectionChannel,
+ async run(context) {
+ const apiKey = nuelinkClient.apiKeyOf({ auth: context.auth });
+ const brandId = nuelinkClient.numericId({ value: context.propsValue.brandId, label: 'Brand ID' });
+ const collectionId = nuelinkClient.numericId({ value: context.propsValue.collectionId, label: 'Collection ID' });
+ const channelId = nuelinkClient.numericId({ value: context.propsValue.channelId, label: 'Channel ID' });
+ return nuelinkCollectionChannels.remove({ apiKey, brandId, collectionId, channelId });
+ },
+});
diff --git a/packages/pieces/community/nuelink/src/lib/actions/ai/update-automation-status.ts b/packages/pieces/community/nuelink/src/lib/actions/ai/update-automation-status.ts
new file mode 100644
index 00000000000..49806121dc2
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/actions/ai/update-automation-status.ts
@@ -0,0 +1,41 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { nuelinkAuths } from '../../auth';
+import { nuelinkAiProps } from '../../common/ai-props';
+import { nuelinkOutputSchemas } from '../../output-schemas';
+import { nuelinkClient } from '../../common/client';
+import { nuelinkInputs } from '../../common/inputs';
+
+export const aiUpdateAutomationStatus = createAction({
+ name: 'nuelink_update_automation_status',
+ classification: 'WRITE',
+ auth: nuelinkAuths,
+ displayName: 'Pause or Activate Feed Automation',
+ description: 'Pauses a feed automation, or activates it again.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Sets a feed automation (id from nuelink_list_automations) to PAUSED, which stops importing, or ACTIVE, which resumes importing new feed items into its collection. Pausing is the only way to stop an automation through the API. The response may read INACTIVE for a paused automation. Setting the same status again changes nothing.',
+ idempotent: true,
+ },
+ props: {
+ brandId: nuelinkAiProps.brandId(),
+ automationId: nuelinkAiProps.idText({ displayName: 'Automation ID', description: 'The numeric automation ID from nuelink_list_automations.', required: true }),
+ status: Property.StaticDropdown({
+ displayName: 'Status',
+ required: true,
+ options: { options: [{ label: 'Paused', value: 'PAUSED' }, { label: 'Active', value: 'ACTIVE' }] },
+ }),
+ },
+ outputSchema: nuelinkOutputSchemas.automationStatus,
+ async run(context) {
+ const apiKey = nuelinkClient.apiKeyOf({ auth: context.auth });
+ const brandId = nuelinkClient.numericId({ value: context.propsValue.brandId, label: 'Brand ID' });
+ const automationId = nuelinkClient.numericId({ value: context.propsValue.automationId, label: 'Automation ID' });
+ const status = nuelinkInputs.oneOf({ value: context.propsValue.status, label: 'Status', allowed: ['PAUSED', 'ACTIVE'] as const });
+ if (status === undefined) {
+ throw new Error('Status is required: PAUSED or ACTIVE.');
+ }
+ return nuelinkClient.request({ apiKey, method: HttpMethod.PATCH, path: ['brands', brandId, 'automations', automationId], body: { status } });
+ },
+});
diff --git a/packages/pieces/community/nuelink/src/lib/actions/ai/update-collection.ts b/packages/pieces/community/nuelink/src/lib/actions/ai/update-collection.ts
new file mode 100644
index 00000000000..eeee2dcdbdd
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/actions/ai/update-collection.ts
@@ -0,0 +1,61 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { nuelinkAuths } from '../../auth';
+import { nuelinkAiProps } from '../../common/ai-props';
+import { nuelinkOutputSchemas } from '../../output-schemas';
+import { nuelinkClient } from '../../common/client';
+import { nuelinkInputs } from '../../common/inputs';
+
+export const aiUpdateCollection = createAction({
+ name: 'nuelink_update_collection',
+ classification: 'WRITE',
+ auth: nuelinkAuths,
+ displayName: 'Update Collection',
+ description: 'Renames a collection, changes its description or evergreen interval, or pauses or resumes it.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Changes only the fields you set on a collection: title, description (or clearDescription to empty it), status ACTIVE/PAUSED, maxRepublish (evergreen interval in weeks, 0 = off). Setting status PAUSED is the safe way to stop a collection from publishing, since collections cannot be deleted through the API. Do not copy a maxRepublish of -1 read from nuelink_list_collections back; it is read-only. The response lists no queue slots while paused, but the slots are kept. Re-sending the same values changes nothing.',
+ idempotent: true,
+ },
+ props: {
+ brandId: nuelinkAiProps.brandId(),
+ collectionId: nuelinkAiProps.collectionId({ required: true, description: 'The numeric collection ID from nuelink_list_collections.' }),
+ title: Property.ShortText({ displayName: 'New Title', description: '1 to 255 characters. Empty keeps the current title.', required: false }),
+ description: Property.LongText({ displayName: 'New Description', description: 'Up to 1,000 characters. Empty keeps the current one.', required: false }),
+ clearDescription: Property.Checkbox({ displayName: 'Clear Description', description: 'Remove the description. Do not combine with New Description.', required: false }),
+ status: Property.StaticDropdown({
+ displayName: 'Status',
+ description: 'PAUSED stops publishing from this collection; ACTIVE resumes it. Empty keeps it.',
+ required: false,
+ options: { options: [{ label: 'Active', value: 'ACTIVE' }, { label: 'Paused', value: 'PAUSED' }] },
+ }),
+ maxRepublish: Property.Number({ displayName: 'Evergreen Republish Interval (weeks)', description: '0 turns evergreen off. Empty keeps it.', required: false }),
+ },
+ outputSchema: nuelinkOutputSchemas.collection,
+ async run(context) {
+ const apiKey = nuelinkClient.apiKeyOf({ auth: context.auth });
+ const props = context.propsValue;
+ const brandId = nuelinkClient.numericId({ value: props.brandId, label: 'Brand ID' });
+ const collectionId = nuelinkClient.numericId({ value: props.collectionId, label: 'Collection ID' });
+ const title = nuelinkInputs.optionalText({ value: props.title, label: 'New Title', max: 255 })?.trim();
+ const description = nuelinkInputs.optionalText({ value: props.description, label: 'New Description', max: 1000 });
+ const clearDescription = nuelinkInputs.isChecked({ value: props.clearDescription });
+ const status = nuelinkInputs.oneOf({ value: props.status, label: 'Status', allowed: ['ACTIVE', 'PAUSED'] as const });
+ const maxRepublish = nuelinkInputs.optionalInteger({ value: props.maxRepublish, label: 'Evergreen Republish Interval (weeks)', min: 0, max: 10000 });
+ if (clearDescription && description !== undefined) {
+ throw new Error('Set either New Description or Clear Description, not both.');
+ }
+ const body = {
+ ...(title === undefined ? {} : { title }),
+ ...(description === undefined ? {} : { description }),
+ ...(clearDescription ? { description: null } : {}),
+ ...(status === undefined ? {} : { status }),
+ ...(maxRepublish === undefined ? {} : { maxRepublish }),
+ };
+ if (Object.keys(body).length === 0) {
+ throw new Error('Nothing to update. Set New Title, New Description, Clear Description, Status or Evergreen Republish Interval.');
+ }
+ return nuelinkClient.request({ apiKey, method: HttpMethod.PATCH, path: ['brands', brandId, 'collections', collectionId], body });
+ },
+});
diff --git a/packages/pieces/community/nuelink/src/lib/actions/ai/update-post.ts b/packages/pieces/community/nuelink/src/lib/actions/ai/update-post.ts
new file mode 100644
index 00000000000..db7b41598cd
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/actions/ai/update-post.ts
@@ -0,0 +1,60 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { nuelinkAuths } from '../../auth';
+import { nuelinkAiProps } from '../../common/ai-props';
+import { nuelinkClient } from '../../common/client';
+import { nuelinkPosts } from '../../common/operations';
+import { nuelinkOutputSchemas } from '../../output-schemas';
+
+export const aiUpdatePost = createAction({
+ name: 'nuelink_update_post',
+ classification: 'WRITE',
+ auth: nuelinkAuths,
+ displayName: 'Update Post',
+ description: 'Changes the caption, publish mode, schedule or queue position of a post that is not published yet.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Edits an unpublished post from nuelink_create_post or nuelink_list_brand_posts: new caption (replaces the old one), publishMode DRAFT/QUEUE/SCHEDULE, or queuePosition FRONT/BACK. Setting DRAFT is the safe way to stop a post; prefer it over nuelink_delete_post. Moving a draft to QUEUE or SCHEDULE puts it on track to publish, so only do that on explicit user intent. scheduledAt must be ISO-8601 with an offset, at least 10 minutes ahead. Published posts (409) and polls (400) cannot be edited. Re-sending the same values changes nothing.',
+ idempotent: true,
+ },
+ props: {
+ brandId: nuelinkAiProps.brandId(),
+ postId: nuelinkAiProps.idText({ displayName: 'Post ID', description: 'The numeric post ID from nuelink_create_post or nuelink_list_brand_posts.', required: true }),
+ caption: Property.LongText({ displayName: 'New Caption', description: 'Replaces the post text (up to 3,000 characters). Leave empty to keep it.', required: false }),
+ publishMode: Property.StaticDropdown({
+ displayName: 'New Publish Mode',
+ description: 'Leave empty to keep the current mode.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Draft', value: 'DRAFT' },
+ { label: 'Queue', value: 'QUEUE' },
+ { label: 'Schedule', value: 'SCHEDULE' },
+ ],
+ },
+ }),
+ scheduledAt: Property.ShortText({
+ displayName: 'Scheduled Time',
+ description: 'Required with New Publish Mode SCHEDULE, not allowed otherwise. ISO-8601 with an offset, e.g. 2026-10-12T09:00:00+03:00.',
+ required: false,
+ }),
+ queuePosition: Property.StaticDropdown({
+ displayName: 'Queue Position',
+ description: 'Move a queued post to the front or back of its queue.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Front', value: 'FRONT' },
+ { label: 'Back', value: 'BACK' },
+ ],
+ },
+ }),
+ },
+ outputSchema: nuelinkOutputSchemas.updatePost,
+ async run(context) {
+ const apiKey = nuelinkClient.apiKeyOf({ auth: context.auth });
+ const brandId = nuelinkClient.numericId({ value: context.propsValue.brandId, label: 'Brand ID' });
+ const postId = nuelinkClient.numericId({ value: context.propsValue.postId, label: 'Post ID' });
+ return nuelinkPosts.update({ apiKey, brandId, postId, props: context.propsValue });
+ },
+});
diff --git a/packages/pieces/community/nuelink/src/lib/actions/ai/upload-file.ts b/packages/pieces/community/nuelink/src/lib/actions/ai/upload-file.ts
new file mode 100644
index 00000000000..0c7419a9715
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/actions/ai/upload-file.ts
@@ -0,0 +1,30 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { nuelinkAuths } from '../../auth';
+import { nuelinkAiProps } from '../../common/ai-props';
+import { nuelinkClient } from '../../common/client';
+import { nuelinkPosts } from '../../common/operations';
+import { nuelinkOutputSchemas } from '../../output-schemas';
+
+export const aiUploadFile = createAction({
+ name: 'nuelink_upload_file',
+ classification: 'WRITE',
+ auth: nuelinkAuths,
+ displayName: 'Upload Media File',
+ description: 'Uploads one image, video or PDF to the brand\'s Nuelink media library and returns its media ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Uploads one JPG, PNG, BMP, MP4, MOV or PDF file (up to 100 MB) to the brand media library and returns a media ID for nuelink_create_post. Not needed when the file has a public URL (nuelink_create_post takes URLs) or is already in the library (nuelink_list_media). Each call stores a new copy that cannot be deleted through the API; after a timeout check nuelink_list_media before retrying.',
+ idempotent: false,
+ },
+ props: {
+ brandId: nuelinkAiProps.brandId(),
+ file: Property.File({ displayName: 'File', description: 'A JPG, PNG, BMP, MP4, MOV or PDF file (URL or file reference), up to 100 MB.', required: true }),
+ },
+ outputSchema: nuelinkOutputSchemas.uploadMedia,
+ async run(context) {
+ const apiKey = nuelinkClient.apiKeyOf({ auth: context.auth });
+ const brandId = nuelinkClient.numericId({ value: context.propsValue.brandId, label: 'Brand ID' });
+ return nuelinkPosts.upload({ apiKey, brandId, file: context.propsValue.file });
+ },
+});
diff --git a/packages/pieces/community/nuelink/src/lib/actions/create-collection-post.ts b/packages/pieces/community/nuelink/src/lib/actions/create-collection-post.ts
new file mode 100644
index 00000000000..f19fe234d4a
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/actions/create-collection-post.ts
@@ -0,0 +1,119 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { nuelinkAuths } from '../auth';
+import { nuelinkClient } from '../common/client';
+import { nuelinkPosts } from '../common/operations';
+import { nuelinkProps } from '../common/props';
+import { nuelinkOutputSchemas } from '../output-schemas';
+
+export const createCollectionPost = createAction({
+ name: 'create_collection_post',
+ classification: 'WRITE',
+ auth: nuelinkAuths,
+ displayName: 'Create Post in Collection',
+ description: 'Creates a post in a Nuelink collection as a draft, in the queue, at a scheduled time or right away. It goes to every channel in the collection.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Creates a post in a Nuelink collection; it goes to every channel connected to that collection. DRAFT (the default) saves without publishing, QUEUE takes the collection\'s next time slot, SCHEDULE needs scheduledAt at least 10 minutes ahead, and IMMEDIATE publishes now. Use IMMEDIATE only when the user explicitly asks to post now. Each call creates a new post, so do not retry after a timeout without checking List Posts first.',
+ idempotent: false,
+ },
+ props: {
+ brand: nuelinkProps.brand(),
+ collection: nuelinkProps.collection({ required: true, description: 'The collection to add the post to. The post is published to every channel connected to it.' }),
+ publishMode: Property.StaticDropdown({
+ displayName: 'Publish Mode',
+ description: 'Draft saves the post without publishing it. Queue gives it the collection\'s next free time slot. Schedule publishes it at Scheduled Time. Publish Now sends it to every channel immediately.',
+ required: true,
+ defaultValue: 'DRAFT',
+ options: {
+ options: [
+ { label: 'Draft (do not publish)', value: 'DRAFT' },
+ { label: 'Add to Queue', value: 'QUEUE' },
+ { label: 'Schedule', value: 'SCHEDULE' },
+ { label: 'Publish Now', value: 'IMMEDIATE' },
+ ],
+ },
+ }),
+ scheduledAt: Property.DateTime({
+ displayName: 'Scheduled Time',
+ description: 'Only for Publish Mode = Schedule, at least 10 minutes ahead. Include a timezone offset; it is converted to the brand\'s timezone for Nuelink.',
+ required: false,
+ }),
+ caption: Property.LongText({
+ displayName: 'Caption',
+ description: 'The text of the post, up to 3,000 characters. Separating parts with two empty lines turns it into a thread (up to 10 parts).',
+ required: true,
+ }),
+ title: Property.ShortText({
+ displayName: 'Title',
+ description: 'Title used for videos, Reels and Pinterest pins (up to 255 characters).',
+ required: false,
+ }),
+ media: Property.Array({
+ displayName: 'Media',
+ description: 'Up to 10 images or videos. Each entry is a public http(s) URL that Nuelink downloads (it must open without a login), or a media ID from Upload Media.',
+ required: false,
+ }),
+ alt: Property.ShortText({
+ displayName: 'Alt Text',
+ description: 'Describes the image or video for screen readers (up to 255 characters).',
+ required: false,
+ }),
+ link: Property.ShortText({
+ displayName: 'Link',
+ description: 'Destination link for Pinterest pins and the Google Business "Learn more" button.',
+ required: false,
+ }),
+ postAsStory: Property.Checkbox({
+ displayName: 'Post as Story',
+ description: 'Publish as a story on channels that support stories.',
+ required: false,
+ defaultValue: false,
+ }),
+ autoThreadText: Property.Checkbox({
+ displayName: 'Split Long Text into a Thread',
+ description: 'Let Nuelink split text that is too long for a channel into a thread.',
+ required: false,
+ defaultValue: false,
+ }),
+ firstComment: Property.LongText({
+ displayName: 'First Comment',
+ description: 'A comment Nuelink adds under the post after it is published (up to 1,000 characters). Set First Comment Delay too.',
+ required: false,
+ }),
+ firstCommentDelaySeconds: Property.Number({
+ displayName: 'First Comment Delay (seconds)',
+ description: 'How many seconds after publishing to post the first comment. Required when First Comment is set.',
+ required: false,
+ }),
+ instagramShareToFeed: Property.Checkbox({
+ displayName: 'Instagram: Share Reel to Feed',
+ description: 'When on, Instagram Reels also appear in the feed. When off, Nuelink\'s default applies.',
+ required: false,
+ defaultValue: false,
+ }),
+ instagramCollab: Property.ShortText({
+ displayName: 'Instagram: Collaborator',
+ description: 'Instagram username to invite as a collaborator.',
+ required: false,
+ }),
+ tiktokAutoAddMusic: Property.Checkbox({
+ displayName: 'TikTok: Add Music Automatically',
+ description: 'When on, TikTok adds music to photo posts. When off, Nuelink\'s default applies.',
+ required: false,
+ defaultValue: false,
+ }),
+ youtubeTags: Property.Array({
+ displayName: 'YouTube: Tags',
+ description: 'Tags for YouTube videos.',
+ required: false,
+ }),
+ },
+ outputSchema: nuelinkOutputSchemas.createCollectionPost,
+ async run(context) {
+ const apiKey = nuelinkClient.apiKeyOf({ auth: context.auth });
+ const brandId = nuelinkClient.numericId({ value: context.propsValue.brand, label: 'Brand' });
+ const collectionId = nuelinkClient.numericId({ value: context.propsValue.collection, label: 'Collection' });
+ return nuelinkPosts.create({ apiKey, brandId, collectionId, props: context.propsValue, pollAllowed: false });
+ },
+});
diff --git a/packages/pieces/community/nuelink/src/lib/actions/create-post.ts b/packages/pieces/community/nuelink/src/lib/actions/create-post.ts
index df9d95a4deb..ebcf3b5aafc 100644
--- a/packages/pieces/community/nuelink/src/lib/actions/create-post.ts
+++ b/packages/pieces/community/nuelink/src/lib/actions/create-post.ts
@@ -1,26 +1,29 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { httpClient, HttpMethod } from '@activepieces/pieces-common';
-import { nuelinkAuth } from '../..';
+import { nuelinkAuths } from '../auth';
+import { nuelinkClient } from '../common/client';
export const createPost = createAction({
- // auth: check https://www.activepieces.com/docs/developers/piece-reference/authentication,
name: 'createPost',
classification: 'WRITE',
- auth: nuelinkAuth,
+ auth: nuelinkAuths,
displayName: 'Create Post',
- description: 'Creates a post on nuelink.',
- audience: 'both',
- aiMetadata: { description: 'Publishes a social media post through Nuelink to the connected social channels, with a required caption and optional media URL, title (for Reels/videos/Pinterest), alt text, and flags to share Instagram Reels to the feed or treat videos as short-form vertical content. Choose this to publish or schedule content via Nuelink. Not idempotent: each call creates a new post.', idempotent: false },
+ description: 'Adds a post to the collection linked to your Nuelink automation token. Needs an Automation Token connection; with an API key, use Create Post in Collection.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Adds a post to the single Nuelink collection tied to this connection\'s automation token; the post then follows that collection\'s channels and schedule. It cannot choose the collection, publish mode or time, and needs an Automation Token connection; prefer Create Post in Collection. Each call creates a new post, so retries duplicate it.',
+ idempotent: false,
+ },
props: {
body: Property.LongText({
displayName: 'Caption',
required: true,
- description: 'The your post caption here',
+ description: 'The text of the post.',
}),
media: Property.LongText({
displayName: 'Media',
required: false,
- description: 'Enter the media URL here',
+ description: 'Public URL of one image or video. Nuelink downloads it, so it must open without a login.',
}),
title: Property.LongText({
displayName: 'Title',
@@ -45,24 +48,13 @@ export const createPost = createAction({
defaultValue: false,
}),
},
-
async run(context) {
- const res = await httpClient.sendRequest<string[]>({
- method: HttpMethod.POST,
- url: 'https://nuelink.com/api/v1/pabbly',
- headers: {
- Authorization: `Bearer ${context.auth.secret_text}`,
- },
- body: {
- body: context.propsValue.body,
- media: context.propsValue.media,
- title: context.propsValue.title,
- altText: context.propsValue.altText,
- shareToFeed: context.propsValue.shareToFeed,
- postAsShort: context.propsValue.postAsShort
- },
+ const token = nuelinkClient.legacyTokenOf({ auth: context.auth });
+ const { body, media, title, altText, shareToFeed, postAsShort } = context.propsValue;
+ const mediaUrl = typeof media === 'string' && media.trim().length > 0 ? media.trim() : undefined;
+ return nuelinkClient.legacyCreatePost({
+ token,
+ body: { body, media: mediaUrl, title, altText, shareToFeed, postAsShort },
});
- return res.body;
},
-
});
diff --git a/packages/pieces/community/nuelink/src/lib/actions/delete-post.ts b/packages/pieces/community/nuelink/src/lib/actions/delete-post.ts
new file mode 100644
index 00000000000..1b691917836
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/actions/delete-post.ts
@@ -0,0 +1,35 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { nuelinkAuths } from '../auth';
+import { nuelinkClient } from '../common/client';
+import { nuelinkPosts } from '../common/operations';
+import { nuelinkProps } from '../common/props';
+import { nuelinkOutputSchemas } from '../output-schemas';
+
+export const deletePost = createAction({
+ name: 'delete_post',
+ classification: 'DESTRUCTIVE',
+ auth: nuelinkAuths,
+ displayName: 'Delete Post',
+ description: 'Permanently deletes a post from Nuelink. Anything already published on a social network stays there. Needs "Allow AI to perform sensitive actions" turned on in Nuelink Settings → API.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Permanently deletes a post from Nuelink; anything already published on a social network stays there. Nuelink refuses this (403) unless the account owner enabled "Allow AI to perform sensitive actions" in Settings → API. Prefer Update Post with publishMode DRAFT to stop a post. Cannot be undone, and a repeat call fails with 404.',
+ idempotent: false,
+ },
+ props: {
+ brand: nuelinkProps.brand(),
+ postId: Property.ShortText({
+ displayName: 'Post ID',
+ description: 'The numeric ID of the post to delete, from Create Post in Collection or List Posts.',
+ required: true,
+ }),
+ },
+ outputSchema: nuelinkOutputSchemas.deletePost,
+ async run(context) {
+ const apiKey = nuelinkClient.apiKeyOf({ auth: context.auth });
+ const brandId = nuelinkClient.numericId({ value: context.propsValue.brand, label: 'Brand' });
+ const postId = nuelinkClient.numericId({ value: context.propsValue.postId, label: 'Post ID' });
+ return nuelinkPosts.remove({ apiKey, brandId, postId });
+ },
+});
diff --git a/packages/pieces/community/nuelink/src/lib/actions/list-posts.ts b/packages/pieces/community/nuelink/src/lib/actions/list-posts.ts
new file mode 100644
index 00000000000..cd93c905c57
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/actions/list-posts.ts
@@ -0,0 +1,85 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { nuelinkAuths } from '../auth';
+import { nuelinkClient } from '../common/client';
+import { nuelinkInputs } from '../common/inputs';
+import { POST_TYPES, nuelinkPosts } from '../common/operations';
+import { nuelinkProps } from '../common/props';
+import { nuelinkOutputSchemas } from '../output-schemas';
+
+export const listPosts = createAction({
+ name: 'list_posts',
+ classification: 'SEARCH',
+ auth: nuelinkAuths,
+ displayName: 'List Posts',
+ description: 'Lists a brand\'s drafts, queued, scheduled and published posts, one page at a time.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Lists a brand\'s posts (drafts, queued, scheduled, published), optionally for one collection, with type and creation-date filters, one page at a time (hasMore says whether to ask for the next page). Use it to find a post ID or to check what is queued. Use List Published Posts for delivery status and engagement. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ brand: nuelinkProps.brand(),
+ collection: nuelinkProps.collection({ required: false, description: 'Only list posts of this collection. Leave empty for all collections.' }),
+ view: Property.StaticDropdown({
+ displayName: 'Show',
+ description: 'Which kind of posts to list. Leave empty for all.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Queued', value: 'QUEUE' },
+ { label: 'Scheduled', value: 'SCHEDULED' },
+ { label: 'Drafts', value: 'DRAFT' },
+ { label: 'Published', value: 'PUBLISHED' },
+ ],
+ },
+ }),
+ postType: Property.StaticDropdown({
+ displayName: 'Post Type',
+ required: false,
+ options: { options: POST_TYPES.map((type) => ({ label: titleCase({ text: type }), value: type })) },
+ }),
+ createdFrom: Property.DateTime({
+ displayName: 'Created From',
+ description: 'Only posts created at or after this time. A time without a timezone is read as UTC.',
+ required: false,
+ }),
+ createdTo: Property.DateTime({
+ displayName: 'Created To',
+ description: 'Only posts created at or before this time. A time without a timezone is read as UTC.',
+ required: false,
+ }),
+ sortBy: Property.StaticDropdown({
+ displayName: 'Sort By',
+ required: false,
+ defaultValue: 'id',
+ options: {
+ options: [
+ { label: 'Post ID', value: 'id' },
+ { label: 'Title', value: 'title' },
+ { label: 'Scheduled date', value: 'post_date' },
+ { label: 'Created date', value: 'created_at' },
+ { label: 'Updated date', value: 'updated_at' },
+ ],
+ },
+ }),
+ sortOrder: nuelinkProps.sortOrder(),
+ page: nuelinkProps.page(),
+ perPage: nuelinkProps.perPage(),
+ },
+ outputSchema: nuelinkOutputSchemas.listPosts,
+ async run(context) {
+ const apiKey = nuelinkClient.apiKeyOf({ auth: context.auth });
+ const brandId = nuelinkClient.numericId({ value: context.propsValue.brand, label: 'Brand' });
+ const collectionId = nuelinkInputs.optionalId({ value: context.propsValue.collection, label: 'Collection' });
+ return nuelinkPosts.list({ apiKey, brandId, collectionId, props: context.propsValue });
+ },
+});
+
+function titleCase({ text }: { text: string }): string {
+ return text
+ .toLowerCase()
+ .split('_')
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
+ .join(' ');
+}
diff --git a/packages/pieces/community/nuelink/src/lib/actions/list-published-posts.ts b/packages/pieces/community/nuelink/src/lib/actions/list-published-posts.ts
new file mode 100644
index 00000000000..b8545481847
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/actions/list-published-posts.ts
@@ -0,0 +1,83 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { nuelinkAuths } from '../auth';
+import { nuelinkClient } from '../common/client';
+import { nuelinkPosts } from '../common/operations';
+import { nuelinkProps } from '../common/props';
+import { nuelinkOutputSchemas } from '../output-schemas';
+
+export const listPublishedPosts = createAction({
+ name: 'list_published_posts',
+ classification: 'SEARCH',
+ auth: nuelinkAuths,
+ displayName: 'List Published Posts',
+ description: 'Lists what Nuelink sent to each channel, with the delivery status, the link to the post and its engagement counts.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Lists what Nuelink actually sent to each channel, one entry per channel: delivery status (published, failed, retrying, skipped), the platform post URL, and engagement counts (likes, comments, shares, views, saves, clicks, impressions, reach). Filter by collection, channel, source post, text search or publish date; one page per call with hasMore. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ brand: nuelinkProps.brand(),
+ status: Property.StaticDropdown({
+ displayName: 'Delivery Status',
+ required: false,
+ defaultValue: 'PUBLISHED',
+ options: {
+ options: [
+ { label: 'Published', value: 'PUBLISHED' },
+ { label: 'Failed', value: 'FAILED' },
+ { label: 'Retrying', value: 'RETRYING' },
+ { label: 'Skipped', value: 'SKIPPED' },
+ { label: 'Sent', value: 'SENT' },
+ ],
+ },
+ }),
+ collection: nuelinkProps.collection({ required: false, description: 'Only results from this collection. Leave empty for all collections.' }),
+ channel: nuelinkProps.channel(),
+ postId: Property.ShortText({
+ displayName: 'Post ID',
+ description: 'Only results of this Nuelink post (the ID from Create Post in Collection or List Posts).',
+ required: false,
+ }),
+ search: Property.ShortText({
+ displayName: 'Search Text',
+ description: 'Only results whose published text contains this (not case-sensitive, up to 255 characters).',
+ required: false,
+ }),
+ publishedFrom: Property.DateTime({
+ displayName: 'Published From',
+ description: 'Only results published at or after this time. A time without a timezone is read as UTC.',
+ required: false,
+ }),
+ publishedTo: Property.DateTime({
+ displayName: 'Published To',
+ description: 'Only results published at or before this time. A time without a timezone is read as UTC.',
+ required: false,
+ }),
+ sortBy: Property.StaticDropdown({
+ displayName: 'Sort By',
+ required: false,
+ defaultValue: 'id',
+ options: {
+ options: [
+ { label: 'Newest (ID)', value: 'id' },
+ { label: 'Created date', value: 'created_at' },
+ { label: 'Likes', value: 'likes' },
+ { label: 'Comments', value: 'comments' },
+ { label: 'Shares', value: 'shares' },
+ ],
+ },
+ }),
+ sortOrder: nuelinkProps.sortOrder(),
+ page: nuelinkProps.page(),
+ perPage: nuelinkProps.perPage(),
+ },
+ outputSchema: nuelinkOutputSchemas.listPublishedPosts,
+ async run(context) {
+ const apiKey = nuelinkClient.apiKeyOf({ auth: context.auth });
+ const props = context.propsValue;
+ const brandId = nuelinkClient.numericId({ value: props.brand, label: 'Brand' });
+ return nuelinkPosts.listPublished({ apiKey, brandId, props, ids: { collection: props.collection, channel: props.channel, post: props.postId } });
+ },
+});
diff --git a/packages/pieces/community/nuelink/src/lib/actions/update-post.ts b/packages/pieces/community/nuelink/src/lib/actions/update-post.ts
new file mode 100644
index 00000000000..6f2a5f6b732
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/actions/update-post.ts
@@ -0,0 +1,68 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { nuelinkAuths } from '../auth';
+import { nuelinkClient } from '../common/client';
+import { nuelinkPosts } from '../common/operations';
+import { nuelinkProps } from '../common/props';
+import { nuelinkOutputSchemas } from '../output-schemas';
+
+export const updatePost = createAction({
+ name: 'update_post',
+ classification: 'WRITE',
+ auth: nuelinkAuths,
+ displayName: 'Update Post',
+ description: 'Changes the caption of a post that is not published yet, turns it back into a draft, reschedules it or moves it in the queue.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Edits a post that has not been published yet: change its caption, turn it back into a draft, reschedule it, re-queue it, or move it to the front or back of its queue. Published posts (409) and polls cannot be edited. To stop a post from going out, set publishMode DRAFT rather than deleting it. Setting the same values again changes nothing.',
+ idempotent: true,
+ },
+ props: {
+ brand: nuelinkProps.brand(),
+ postId: Property.ShortText({
+ displayName: 'Post ID',
+ description: 'The numeric ID of the post, from Create Post in Collection or List Posts.',
+ required: true,
+ }),
+ caption: Property.LongText({
+ displayName: 'New Caption',
+ description: 'Replaces the post text (up to 3,000 characters). Leave empty to keep the current caption. Media is not changed.',
+ required: false,
+ }),
+ publishMode: Property.StaticDropdown({
+ displayName: 'New Publish Mode',
+ description: 'Leave empty to keep the current mode.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Draft (stop it from publishing)', value: 'DRAFT' },
+ { label: 'Add to Queue', value: 'QUEUE' },
+ { label: 'Schedule', value: 'SCHEDULE' },
+ ],
+ },
+ }),
+ scheduledAt: Property.DateTime({
+ displayName: 'Scheduled Time',
+ description: 'Required when New Publish Mode is Schedule, at least 10 minutes ahead; not allowed otherwise. Include a timezone offset.',
+ required: false,
+ }),
+ queuePosition: Property.StaticDropdown({
+ displayName: 'Queue Position',
+ description: 'Move a queued post to the front or back of its collection queue. Works on its own or with New Publish Mode = Add to Queue.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Front (publish next)', value: 'FRONT' },
+ { label: 'Back', value: 'BACK' },
+ ],
+ },
+ }),
+ },
+ outputSchema: nuelinkOutputSchemas.updatePost,
+ async run(context) {
+ const apiKey = nuelinkClient.apiKeyOf({ auth: context.auth });
+ const brandId = nuelinkClient.numericId({ value: context.propsValue.brand, label: 'Brand' });
+ const postId = nuelinkClient.numericId({ value: context.propsValue.postId, label: 'Post ID' });
+ return nuelinkPosts.update({ apiKey, brandId, postId, props: context.propsValue });
+ },
+});
diff --git a/packages/pieces/community/nuelink/src/lib/actions/upload-media.ts b/packages/pieces/community/nuelink/src/lib/actions/upload-media.ts
new file mode 100644
index 00000000000..36f3956252a
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/actions/upload-media.ts
@@ -0,0 +1,34 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { nuelinkAuths } from '../auth';
+import { nuelinkClient } from '../common/client';
+import { nuelinkPosts } from '../common/operations';
+import { nuelinkProps } from '../common/props';
+import { nuelinkOutputSchemas } from '../output-schemas';
+
+export const uploadMedia = createAction({
+ name: 'upload_media',
+ classification: 'WRITE',
+ auth: nuelinkAuths,
+ displayName: 'Upload Media',
+ description: 'Uploads an image, video or PDF to the brand\'s Nuelink media library and returns its media ID for Create Post in Collection.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Uploads one image, video or PDF (jpg, jpeg, png, bmp, mp4, mov, pdf; up to 100 MB) to the brand\'s Nuelink media library and returns its media ID for Create Post in Collection. Not needed when the file already has a public URL, since Create Post in Collection accepts URLs directly. Each call stores a new copy.',
+ idempotent: false,
+ },
+ props: {
+ brand: nuelinkProps.brand(),
+ file: Property.File({
+ displayName: 'File',
+ description: 'A JPG, PNG, BMP, MP4, MOV or PDF file, up to 100 MB.',
+ required: true,
+ }),
+ },
+ outputSchema: nuelinkOutputSchemas.uploadMedia,
+ async run(context) {
+ const apiKey = nuelinkClient.apiKeyOf({ auth: context.auth });
+ const brandId = nuelinkClient.numericId({ value: context.propsValue.brand, label: 'Brand' });
+ return nuelinkPosts.upload({ apiKey, brandId, file: context.propsValue.file });
+ },
+});
diff --git a/packages/pieces/community/nuelink/src/lib/auth.ts b/packages/pieces/community/nuelink/src/lib/auth.ts
new file mode 100644
index 00000000000..575cb7de1a1
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/auth.ts
@@ -0,0 +1,39 @@
+import { AppConnectionValueForAuthProperty, PieceAuth } from '@activepieces/pieces-framework';
+import { nuelinkClient } from './common/client';
+
+export const nuelinkAuth = PieceAuth.SecretText({
+ displayName: 'Automation Token (legacy)',
+ required: true,
+ description: `Works only with **Create Post**, which adds posts to the one collection chosen when the token was made. For every other action, add an **API Key** connection instead.
+
+To get an automation token:
+1. Sign in to Nuelink and open **Automations**.
+2. Create a new automation for **Activepieces** and pick the collection the posts should go to.
+3. Copy the token Nuelink shows and paste it here.`,
+ validate: async ({ auth }) => nuelinkClient.validateLegacyToken({ token: auth }),
+});
+
+export const nuelinkApiKeyAuth = PieceAuth.CustomAuth({
+ displayName: 'API Key (recommended)',
+ required: true,
+ description: `Works with every Nuelink action: choose the brand and collection, schedule, edit, delete and track posts.
+
+To get an API key:
+1. Sign in to Nuelink and open **Settings → API**.
+2. Click **Generate API key**, choose how long it stays valid (up to 1 year) and copy it. Nuelink shows it only once.
+3. Paste it below. The key acts as your Nuelink user and sees the same brands you do.
+
+To use **Delete Post**, also turn on **Allow AI to perform sensitive actions** on the same page.`,
+ props: {
+ apiKey: PieceAuth.SecretText({
+ displayName: 'API Key',
+ description: 'The key from Nuelink Settings → API.',
+ required: true,
+ }),
+ },
+ validate: async ({ auth }) => nuelinkClient.validateApiKey({ apiKey: auth.apiKey }),
+});
+
+export const nuelinkAuths = [nuelinkAuth, nuelinkApiKeyAuth];
+
+export type NuelinkAuthValue = AppConnectionValueForAuthProperty<typeof nuelinkAuths>;
diff --git a/packages/pieces/community/nuelink/src/lib/common/ai-props.ts b/packages/pieces/community/nuelink/src/lib/common/ai-props.ts
new file mode 100644
index 00000000000..08b270a602f
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/common/ai-props.ts
@@ -0,0 +1,27 @@
+import { Property } from '@activepieces/pieces-framework';
+
+export const nuelinkAiProps = {
+ brandId,
+ collectionId,
+ idText,
+};
+
+function brandId() {
+ return Property.ShortText({
+ displayName: 'Brand ID',
+ description: 'The numeric brand ID from nuelink_list_brands.',
+ required: true,
+ });
+}
+
+function collectionId<R extends boolean>({ required, description }: { required: R; description: string }) {
+ return Property.ShortText({
+ displayName: 'Collection ID',
+ description,
+ required,
+ });
+}
+
+function idText<R extends boolean>({ displayName, description, required }: { displayName: string; description: string; required: R }) {
+ return Property.ShortText({ displayName, description, required });
+}
diff --git a/packages/pieces/community/nuelink/src/lib/common/client.ts b/packages/pieces/community/nuelink/src/lib/common/client.ts
new file mode 100644
index 00000000000..dd5bd974755
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/common/client.ts
@@ -0,0 +1,481 @@
+import { httpClient, HttpMethod, HttpResponse } from '@activepieces/pieces-common';
+import { AppConnectionType } from '@activepieces/pieces-framework';
+import type { NuelinkAuthValue } from '../auth';
+
+export class NuelinkApiError extends Error {
+ readonly status: number;
+ readonly responseBody: unknown;
+
+ constructor({ status, message, responseBody }: { status: number; message: string; responseBody: unknown }) {
+ super(message);
+ this.name = 'NuelinkApiError';
+ this.status = status;
+ this.responseBody = responseBody;
+ }
+}
+
+export const nuelinkClient = {
+ apiKeyOf,
+ legacyTokenOf,
+ numericId,
+ bodyId,
+ request,
+ getPage,
+ listAllPages,
+ findBrand,
+ legacyCreatePost,
+ validateApiKey,
+ validateLegacyToken,
+ describeError,
+ isRecord,
+};
+
+function apiKeyOf({ auth }: { auth: NuelinkAuthValue | undefined }): string {
+ if (auth !== undefined && auth.type === AppConnectionType.CUSTOM_AUTH) {
+ const key = auth.props.apiKey;
+ if (typeof key === 'string' && key.trim().length > 0) {
+ return key.trim();
+ }
+ }
+ throw new Error(
+ 'This action needs a Nuelink API Key connection. Automation tokens only work with Create Post. Add a connection of type "API Key" (Nuelink Settings → API → Generate API key) and select it in this step.'
+ );
+}
+
+function legacyTokenOf({ auth }: { auth: NuelinkAuthValue | undefined }): string {
+ if (auth !== undefined && auth.type === AppConnectionType.SECRET_TEXT && auth.secret_text.trim().length > 0) {
+ return auth.secret_text.trim();
+ }
+ throw new Error('Create Post needs an Automation Token connection. With an API Key connection, use Create Post in Collection instead.');
+}
+
+function numericId({ value, label }: { value: unknown; label: string }): string {
+ const text = typeof value === 'number' && Number.isSafeInteger(value) ? String(value) : typeof value === 'string' ? value.trim() : '';
+ if (!/^[1-9]\d{0,17}$/.test(text)) {
+ throw new Error(`${label} must be a numeric Nuelink ID, for example 8801.`);
+ }
+ return text;
+}
+
+function bodyId({ value, label }: { value: unknown; label: string }): number {
+ const text = typeof value === 'number' ? (Number.isInteger(value) ? String(value) : '') : typeof value === 'string' ? value.trim() : '';
+ if (!/^[1-9]\d{0,17}$/.test(text)) {
+ throw new Error(`${label} must be a numeric Nuelink ID, for example 8801.`);
+ }
+ const number = Number(text);
+ if (!Number.isSafeInteger(number)) {
+ throw new Error(`${label} ${text} is too large to send safely; Nuelink IDs this large are not supported by this step.`);
+ }
+ return number;
+}
+
+async function request({
+ apiKey,
+ method,
+ path,
+ query,
+ body,
+ timeoutMs = DEFAULT_TIMEOUT_MS,
+ timeoutHint,
+}: {
+ apiKey: string;
+ method: HttpMethod;
+ path: string[];
+ query?: Record<string, QueryValue>;
+ body?: Record<string, unknown> | FormData;
+ timeoutMs?: number;
+ timeoutHint?: string;
+}): Promise<unknown> {
+ const url = `${API_BASE_URL}/${safePath({ path })}`;
+ const response = await send({ url, method, token: apiKey, query, body, timeoutMs, timeoutHint, unauthorizedHint: API_KEY_HINT });
+ return dataOf({ body: response.body, status: response.status });
+}
+
+async function getPage({
+ apiKey,
+ path,
+ query,
+ page,
+ perPage,
+}: {
+ apiKey: string;
+ path: string[];
+ query?: Record<string, QueryValue>;
+ page: number;
+ perPage: number;
+}): Promise<ListPage> {
+ const url = `${API_BASE_URL}/${safePath({ path })}`;
+ const response = await send({
+ url,
+ method: HttpMethod.GET,
+ token: apiKey,
+ query: { ...(query ?? {}), page, per_page: perPage },
+ timeoutMs: DEFAULT_TIMEOUT_MS,
+ unauthorizedHint: API_KEY_HINT,
+ });
+ const items = dataOf({ body: response.body, status: response.status });
+ if (!Array.isArray(items)) {
+ throw new Error('Nuelink returned an unexpected list response (no data array).');
+ }
+ const pagination = paginationOf({ body: response.body, fallbackPage: page, fallbackPerPage: perPage, itemCount: items.length });
+ return {
+ items: items.filter(isRecord),
+ page: pagination.currentPage,
+ perPage: pagination.perPage,
+ total: pagination.total,
+ lastPage: pagination.lastPage,
+ hasMore: pagination.currentPage < pagination.lastPage,
+ };
+}
+
+async function listAllPages({
+ apiKey,
+ path,
+ query,
+ maxPages = MAX_DROPDOWN_PAGES,
+}: {
+ apiKey: string;
+ path: string[];
+ query?: Record<string, QueryValue>;
+ maxPages?: number;
+}): Promise<{ items: Record<string, unknown>[]; truncated: boolean }> {
+ const pages: Record<string, unknown>[][] = [];
+ for (let page = 1; page <= maxPages; page++) {
+ const result = await getPage({ apiKey, path, query, page, perPage: MAX_PER_PAGE });
+ pages.push(result.items);
+ if (!result.hasMore) {
+ return { items: pages.flat(), truncated: false };
+ }
+ }
+ return { items: pages.flat(), truncated: true };
+}
+
+async function findBrand({ apiKey, brandId }: { apiKey: string; brandId: string }): Promise<BrandRecord> {
+ const { items } = await listAllPages({ apiKey, path: ['brands'] });
+ const brand = items.find((item) => String(item['id']) === brandId);
+ if (brand === undefined) {
+ throw new Error(`Brand ${brandId} is not one of the brands this Nuelink API key can access.`);
+ }
+ return {
+ id: brandId,
+ title: typeof brand['title'] === 'string' ? brand['title'] : `Brand ${brandId}`,
+ timezone: typeof brand['timezone'] === 'string' ? brand['timezone'] : null,
+ };
+}
+
+async function legacyCreatePost({ token, body }: { token: string; body: Record<string, unknown> }): Promise<unknown> {
+ const response = await send({
+ url: `${LEGACY_BASE_URL}/pabbly`,
+ method: HttpMethod.POST,
+ token,
+ body,
+ timeoutMs: CREATE_TIMEOUT_MS,
+ timeoutHint: CREATE_TIMEOUT_HINT,
+ unauthorizedHint: LEGACY_TOKEN_HINT,
+ });
+ if (isRecord(response.body) && response.body['status'] === 'error') {
+ throw new NuelinkApiError({
+ status: response.status,
+ responseBody: response.body,
+ message: describeError({ status: 400, responseBody: response.body, unauthorizedHint: LEGACY_TOKEN_HINT }),
+ });
+ }
+ return response.body;
+}
+
+async function validateApiKey({ apiKey }: { apiKey: unknown }): Promise<ValidationResult> {
+ const key = typeof apiKey === 'string' ? apiKey.trim() : '';
+ if (key.length === 0) {
+ return { valid: false, error: 'Enter the API key from Nuelink Settings → API.' };
+ }
+ return validateToken({
+ url: `${API_BASE_URL}/auth`,
+ token: key,
+ invalidMessage: 'Nuelink did not accept this API key. It may be mistyped or expired (keys last 30 days to 1 year). Generate a new one in Nuelink Settings → API.',
+ what: 'API key',
+ });
+}
+
+async function validateLegacyToken({ token }: { token: unknown }): Promise<ValidationResult> {
+ const value = typeof token === 'string' ? token.trim() : '';
+ if (value.length === 0) {
+ return { valid: false, error: 'Enter the automation token from your Nuelink automation.' };
+ }
+ return validateToken({
+ url: `${LEGACY_BASE_URL}/user`,
+ token: value,
+ invalidMessage: 'Nuelink did not accept this automation token. Copy it again from your Nuelink automation, or create a new automation for Activepieces.',
+ what: 'automation token',
+ });
+}
+
+function describeError({ status, responseBody, unauthorizedHint = API_KEY_HINT }: { status: number; responseBody: unknown; unauthorizedHint?: string }): string {
+ const detail = vendorDetail({ body: responseBody });
+ switch (status) {
+ case 400:
+ return `Nuelink rejected the request (400): ${detail}. If a media URL is involved, check that it opens without a login.`;
+ case 401:
+ return `Nuelink did not accept the connection (401): ${detail}. ${unauthorizedHint}`;
+ case 403:
+ return `Nuelink refused the request (403): ${detail}. ${forbiddenHint({ responseBody })}`;
+ case 404:
+ return `Nuelink could not find it (404): ${detail}. Check the brand, collection, channel or post ID, and that the API key's user is a member of the brand.`;
+ case 409:
+ return `Nuelink refused the change (409): ${detail}. Published posts can no longer be edited.`;
+ case 422:
+ return `Nuelink rejected the values (422): ${detail}.`;
+ case 429:
+ return `Nuelink rate limit reached (429): ${detail}. Nuelink allows 30 requests a minute per user across all of that user's keys; wait a minute and try again.`;
+ default:
+ if (status >= 500) {
+ return `Nuelink had a server error (HTTP ${status}): ${detail}. Try again later.`;
+ }
+ return `Nuelink request failed (HTTP ${status}): ${detail}.`;
+ }
+}
+
+async function validateToken({ url, token, invalidMessage, what }: { url: string; token: string; invalidMessage: string; what: string }): Promise<ValidationResult> {
+ try {
+ await send({ url, method: HttpMethod.GET, token, timeoutMs: VALIDATE_TIMEOUT_MS, unauthorizedHint: '' });
+ return { valid: true };
+ } catch (error) {
+ if (error instanceof NuelinkApiError && (error.status === 401 || error.status === 403)) {
+ return { valid: false, error: invalidMessage };
+ }
+ const status = error instanceof NuelinkApiError ? ` (HTTP ${error.status})` : '';
+ return { valid: false, error: `Could not reach Nuelink to check the ${what}${status}. Try again in a minute.` };
+ }
+}
+
+async function send({
+ url,
+ method,
+ token,
+ query,
+ body,
+ timeoutMs,
+ timeoutHint,
+ unauthorizedHint,
+}: {
+ url: string;
+ method: HttpMethod;
+ token: string;
+ query?: Record<string, QueryValue>;
+ body?: Record<string, unknown> | FormData;
+ timeoutMs: number;
+ timeoutHint?: string;
+ unauthorizedHint: string;
+}): Promise<HttpResponse<unknown>> {
+ const dispatcher = await verifiedTls();
+ const isForm = typeof FormData !== 'undefined' && body instanceof FormData;
+ try {
+ const response = await httpClient.sendRequest<unknown>(
+ {
+ method,
+ url,
+ headers: {
+ Authorization: `Bearer ${token}`,
+ Accept: 'application/json',
+ 'Content-Type': body === undefined || isForm ? undefined : 'application/json',
+ },
+ queryParams: toQueryParams({ query }),
+ body,
+ timeout: timeoutMs,
+ followRedirects: false,
+ },
+ { dispatcher }
+ );
+ if (response.status >= 300) {
+ throw new NuelinkApiError({
+ status: response.status,
+ responseBody: undefined,
+ message: `Nuelink answered with an unexpected redirect (HTTP ${response.status}). The request was not followed so your credentials stay on ${new URL(url).host}.`,
+ });
+ }
+ return response;
+ } catch (error) {
+ if (error instanceof NuelinkApiError) {
+ throw error;
+ }
+ if (isTimeout({ error })) {
+ throw new Error(`Nuelink did not answer within ${Math.round(timeoutMs / 1000)} seconds.${timeoutHint === undefined ? '' : ` ${timeoutHint}`}`);
+ }
+ const failure = failureOf({ error });
+ if (failure === undefined) {
+ throw error;
+ }
+ throw new NuelinkApiError({
+ status: failure.status,
+ responseBody: failure.responseBody,
+ message: describeError({ status: failure.status, responseBody: failure.responseBody, unauthorizedHint }),
+ });
+ }
+}
+
+function verifiedTls(): Promise<unknown> {
+ verifiedTlsAgent ??= import('undici')
+ .then(({ Agent }) => new Agent({ connect: { rejectUnauthorized: true } }))
+ .catch((error: unknown) => {
+ verifiedTlsAgent = undefined;
+ throw error;
+ });
+ return verifiedTlsAgent;
+}
+
+function safePath({ path }: { path: string[] }): string {
+ if (path.length === 0 || path.some((segment) => !/^(?:[a-z][a-z-]*|[1-9]\d{0,17})$/.test(segment))) {
+ throw new Error(`Refusing to call an unexpected Nuelink path: /${path.join('/')}`);
+ }
+ return path.join('/');
+}
+
+function toQueryParams({ query }: { query: Record<string, QueryValue> | undefined }): Record<string, string> {
+ const entries = Object.entries(query ?? {}).flatMap(([key, value]) => (value === undefined ? [] : [[key, String(value)]]));
+ return Object.fromEntries(entries);
+}
+
+function dataOf({ body, status }: { body: unknown; status: number }): unknown {
+ if (!isRecord(body)) {
+ throw new Error(`Nuelink returned an unexpected response (HTTP ${status}, no JSON body).`);
+ }
+ if (body['status'] === 'error') {
+ throw new NuelinkApiError({ status, responseBody: body, message: describeError({ status: 400, responseBody: body }) });
+ }
+ if (!('data' in body)) {
+ throw new Error(`Nuelink returned an unexpected response (HTTP ${status}, no data field).`);
+ }
+ return body['data'];
+}
+
+function paginationOf({
+ body,
+ fallbackPage,
+ fallbackPerPage,
+ itemCount,
+}: {
+ body: unknown;
+ fallbackPage: number;
+ fallbackPerPage: number;
+ itemCount: number;
+}): { currentPage: number; perPage: number; total: number; lastPage: number } {
+ const pagination = isRecord(body) && isRecord(body['pagination']) ? body['pagination'] : undefined;
+ const numberOr = ({ value, fallback }: { value: unknown; fallback: number }) => (typeof value === 'number' && Number.isFinite(value) ? value : fallback);
+ const currentPage = numberOr({ value: pagination?.['currentPage'], fallback: fallbackPage });
+ return {
+ currentPage,
+ perPage: numberOr({ value: pagination?.['perPage'], fallback: fallbackPerPage }),
+ total: numberOr({ value: pagination?.['total'], fallback: itemCount }),
+ lastPage: numberOr({ value: pagination?.['lastPage'], fallback: currentPage }),
+ };
+}
+
+function vendorDetail({ body }: { body: unknown }): string {
+ if (isRecord(body)) {
+ const errors = body['errors'];
+ const fieldMessages = isRecord(errors)
+ ? Object.entries(errors).flatMap(([field, value]) => messagesOf({ value }).map((message) => `${field}: ${message}`))
+ : [];
+ if (fieldMessages.length > 0) {
+ return clip({ text: fieldMessages.join('; ') });
+ }
+ const message = body['message'];
+ if (typeof message === 'string' && message.trim().length > 0) {
+ return clip({ text: message.trim() });
+ }
+ return clip({ text: JSON.stringify(body) });
+ }
+ if (typeof body === 'string' && body.trim().length > 0) {
+ return clip({ text: body.trim() });
+ }
+ return 'no details returned';
+}
+
+function messagesOf({ value }: { value: unknown }): string[] {
+ if (typeof value === 'string') {
+ return value.trim().length > 0 ? [value.trim()] : [];
+ }
+ if (Array.isArray(value)) {
+ return value.filter((item): item is string => typeof item === 'string' && item.trim().length > 0).map((item) => item.trim());
+ }
+ return [];
+}
+
+function clip({ text }: { text: string }): string {
+ const short = text.length > MAX_DETAIL_LENGTH ? `${text.slice(0, MAX_DETAIL_LENGTH)}…` : text;
+ let end = short.length;
+ while (end > 0 && short[end - 1] === '.') {
+ end--;
+ }
+ return short.slice(0, end);
+}
+
+function forbiddenHint({ responseBody }: { responseBody: unknown }): string {
+ const errors = isRecord(responseBody) && isRecord(responseBody['errors']) ? responseBody['errors'] : {};
+ if ('permissions' in errors) {
+ return 'The Nuelink account owner must turn on "Allow AI to perform sensitive actions" in Nuelink Settings → API.';
+ }
+ if ('limits' in errors) {
+ return 'A Nuelink plan or brand limit was reached; free up space or upgrade the plan.';
+ }
+ return "Check that the API key's user is a member of this brand.";
+}
+
+function failureOf({ error }: { error: unknown }): { status: number; responseBody: unknown } | undefined {
+ if (!isRecord(error)) {
+ return undefined;
+ }
+ const response = error['response'];
+ if (!isRecord(response) || typeof response['status'] !== 'number') {
+ return undefined;
+ }
+ return { status: response['status'], responseBody: response['body'] };
+}
+
+function isTimeout({ error }: { error: unknown }): boolean {
+ return error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError');
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+let verifiedTlsAgent: Promise<unknown> | undefined;
+
+const API_BASE_URL = 'https://app.nuelink.com/api/public/v1';
+const LEGACY_BASE_URL = 'https://nuelink.com/api/v1';
+
+const DEFAULT_TIMEOUT_MS = 30_000;
+const VALIDATE_TIMEOUT_MS = 15_000;
+const CREATE_TIMEOUT_MS = 120_000;
+const MAX_PER_PAGE = 100;
+const MAX_DROPDOWN_PAGES = 10;
+const MAX_DETAIL_LENGTH = 500;
+const API_KEY_HINT = 'API keys expire after 30 days to 1 year. Generate a new key in Nuelink Settings → API and update the connection.';
+const LEGACY_TOKEN_HINT = 'Copy the automation token again from your Nuelink automation, or create a new automation for Activepieces and update the connection.';
+const CREATE_TIMEOUT_HINT = 'The post may still have been created. Check Nuelink before running this step again, so the post is not published twice.';
+
+export const NUELINK_LIMITS = {
+ createTimeoutMs: CREATE_TIMEOUT_MS,
+ uploadTimeoutMs: 300_000,
+ createTimeoutHint: CREATE_TIMEOUT_HINT,
+ maxPerPage: MAX_PER_PAGE,
+};
+
+type QueryValue = string | number | undefined;
+
+type ValidationResult = { valid: true } | { valid: false; error: string };
+
+export type ListPage = {
+ items: Record<string, unknown>[];
+ page: number;
+ perPage: number;
+ total: number;
+ lastPage: number;
+ hasMore: boolean;
+};
+
+export type BrandRecord = {
+ id: string;
+ title: string;
+ timezone: string | null;
+};
diff --git a/packages/pieces/community/nuelink/src/lib/common/inputs.ts b/packages/pieces/community/nuelink/src/lib/common/inputs.ts
new file mode 100644
index 00000000000..fa4a8ad7421
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/common/inputs.ts
@@ -0,0 +1,203 @@
+import { nuelinkClient } from './client';
+
+export const nuelinkInputs = {
+ paging,
+ oneOf,
+ optionalText,
+ requiredText,
+ optionalId,
+ isChecked,
+ optionalInteger,
+ stringList,
+ httpUrl,
+ mediaItems,
+ hasValue,
+ queueSlot,
+ queueSlots,
+ bodyIds,
+ poll,
+};
+
+function paging({ page, perPage }: { page: unknown; perPage: unknown }): { page: number; perPage: number } {
+ const pageNumber = optionalInteger({ value: page, label: 'Page', min: 1, max: 100000 }) ?? 1;
+ const size = optionalInteger({ value: perPage, label: 'Results per Page', min: 1, max: 100 }) ?? 25;
+ return { page: pageNumber, perPage: size };
+}
+
+function oneOf<T extends string>({ value, label, allowed }: { value: unknown; label: string; allowed: readonly T[] }): T | undefined {
+ if (!hasValue({ value })) {
+ return undefined;
+ }
+ const text = typeof value === 'string' ? value.trim().toUpperCase() : '';
+ const match = allowed.find((option) => option.toUpperCase() === text);
+ if (match === undefined) {
+ throw new Error(`${label} must be one of: ${allowed.join(', ')}.`);
+ }
+ return match;
+}
+
+function optionalText({ value, label, max }: { value: unknown; label: string; max: number }): string | undefined {
+ if (value === undefined || value === null) {
+ return undefined;
+ }
+ const text = typeof value === 'string' ? value : typeof value === 'number' ? String(value) : undefined;
+ if (text === undefined) {
+ throw new Error(`${label} must be text.`);
+ }
+ if (text.trim().length === 0) {
+ return undefined;
+ }
+ if (text.length > max) {
+ throw new Error(`${label} is ${text.length} characters long; Nuelink allows at most ${max}.`);
+ }
+ return text;
+}
+
+function requiredText({ value, label, max }: { value: unknown; label: string; max: number }): string {
+ const text = optionalText({ value, label, max });
+ if (text === undefined) {
+ throw new Error(`${label} is required.`);
+ }
+ return text;
+}
+
+function optionalId({ value, label }: { value: unknown; label: string }): string | undefined {
+ return hasValue({ value }) ? nuelinkClient.numericId({ value, label }) : undefined;
+}
+
+function isChecked({ value }: { value: unknown }): boolean {
+ return value === true || value === 'true';
+}
+
+function optionalInteger({ value, label, min, max }: { value: unknown; label: string; min: number; max: number }): number | undefined {
+ if (!hasValue({ value })) {
+ return undefined;
+ }
+ const number = typeof value === 'number' ? value : typeof value === 'string' && /^-?\d+$/.test(value.trim()) ? Number(value.trim()) : Number.NaN;
+ if (!Number.isInteger(number) || number < min || number > max) {
+ throw new Error(`${label} must be a whole number from ${min} to ${max}.`);
+ }
+ return number;
+}
+
+function stringList({ value, label, maxItems, maxLength }: { value: unknown; label: string; maxItems: number; maxLength: number }): string[] {
+ if (!hasValue({ value })) {
+ return [];
+ }
+ const raw = Array.isArray(value) ? value : typeof value === 'string' ? [value] : undefined;
+ if (raw === undefined) {
+ throw new Error(`${label} must be a list of text values.`);
+ }
+ const items = raw
+ .map((item) => (typeof item === 'string' ? item.trim() : typeof item === 'number' ? String(item) : ''))
+ .filter((item) => item.length > 0);
+ if (items.length > maxItems) {
+ throw new Error(`${label} has ${items.length} entries; at most ${maxItems} are allowed.`);
+ }
+ const tooLong = items.find((item) => item.length > maxLength);
+ if (tooLong !== undefined) {
+ throw new Error(`${label} entries must be at most ${maxLength} characters long.`);
+ }
+ return items;
+}
+
+function httpUrl({ value, label }: { value: string; label: string }): string {
+ const text = value.trim();
+ if (text.length > MAX_URL_LENGTH) {
+ throw new Error(`${label} is longer than ${MAX_URL_LENGTH} characters.`);
+ }
+ try {
+ const url = new URL(text);
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {
+ throw new Error('bad scheme');
+ }
+ } catch {
+ throw new Error(`${label} must be a full http(s) URL, for example https://example.com/image.jpg. Got "${text.slice(0, 100)}".`);
+ }
+ return text;
+}
+
+function mediaItems({ value }: { value: unknown }): MediaItem[] {
+ const entries = stringList({ value, label: 'Media', maxItems: MAX_MEDIA_PER_POST, maxLength: MAX_URL_LENGTH });
+ return entries.map((entry) => {
+ if (/^https?:\/\//i.test(entry)) {
+ return { url: httpUrl({ value: entry, label: 'Media URL' }) };
+ }
+ if (/^[a-z][a-z0-9+.-]*:/i.test(entry) || entry.startsWith('//')) {
+ throw new Error(`Media "${entry.slice(0, 100)}" is neither an http(s) URL nor a Nuelink media ID.`);
+ }
+ return { id: entry };
+ });
+}
+
+function hasValue({ value }: { value: unknown }): boolean {
+ if (value === undefined || value === null) {
+ return false;
+ }
+ if (typeof value === 'string') {
+ return value.trim().length > 0;
+ }
+ if (Array.isArray(value)) {
+ return value.length > 0;
+ }
+ return true;
+}
+
+function queueSlot({ value, label }: { value: unknown; label: string }): string {
+ const text = typeof value === 'string' ? value.trim().replace(/\s+/g, ' ') : '';
+ const match = /^(mon|tue|wed|thu|fri|sat|sun) ([01]\d|2[0-3]):([0-5]\d)$/i.exec(text);
+ if (match === null) {
+ throw new Error(`${label} must be a weekday and 24-hour brand-local time like "Tue 09:00". Got "${text.slice(0, 40)}".`);
+ }
+ const day = match[1].charAt(0).toUpperCase() + match[1].slice(1).toLowerCase();
+ return `${day} ${match[2]}:${match[3]}`;
+}
+
+function queueSlots({ value, label }: { value: unknown; label: string }): string[] {
+ const entries = stringList({ value, label, maxItems: MAX_QUEUE_SLOTS, maxLength: 40 });
+ return [...new Set(entries.map((entry) => queueSlot({ value: entry, label })))];
+}
+
+function bodyIds({ value, label, maxItems }: { value: unknown; label: string; maxItems: number }): number[] {
+ if (!hasValue({ value })) {
+ return [];
+ }
+ const raw = Array.isArray(value) ? value : typeof value === 'string' ? value.split(',') : [value];
+ const ids = raw.filter((item) => hasValue({ value: item })).map((item) => nuelinkClient.bodyId({ value: item, label }));
+ const unique = [...new Set(ids)];
+ if (unique.length > maxItems) {
+ throw new Error(`${label} has ${unique.length} distinct IDs; at most ${maxItems} are allowed.`);
+ }
+ return unique;
+}
+
+function poll({ question, options, period, correctOptionIndex, explanation }: { question: unknown; options: unknown; period: unknown; correctOptionIndex: unknown; explanation: unknown }): PollInput | undefined {
+ const anySet = [question, options, period, correctOptionIndex, explanation].some((value) => hasValue({ value }));
+ if (!anySet) {
+ return undefined;
+ }
+ const text = optionalText({ value: question, label: 'Poll Question', max: 280 });
+ const choices = stringList({ value: options, label: 'Poll Options', maxItems: 4, maxLength: 30 });
+ const duration = oneOf({ value: period, label: 'Poll Duration', allowed: POLL_PERIODS.map((item) => item.toUpperCase()) });
+ if (text === undefined || choices.length < 2 || duration === undefined) {
+ throw new Error('A poll needs Poll Question, 2 to 4 Poll Options and Poll Duration (1d, 3d or 7d) together.');
+ }
+ const correct = optionalInteger({ value: correctOptionIndex, label: 'Poll Correct Option Index', min: 0, max: choices.length - 1 });
+ const note = optionalText({ value: explanation, label: 'Poll Explanation', max: 512 });
+ return {
+ question: text,
+ options: choices,
+ period: duration.toLowerCase(),
+ ...(correct === undefined ? {} : { correctOptionIndex: correct }),
+ ...(note === undefined ? {} : { explanation: note }),
+ };
+}
+
+const MAX_URL_LENGTH = 1000;
+const MAX_MEDIA_PER_POST = 10;
+const MAX_QUEUE_SLOTS = 70;
+const POLL_PERIODS = ['1d', '3d', '7d'] as const;
+
+type MediaItem = { url: string } | { id: string };
+
+export type PollInput = { question: string; options: string[]; period: string; correctOptionIndex?: number; explanation?: string };
diff --git a/packages/pieces/community/nuelink/src/lib/common/operations.ts b/packages/pieces/community/nuelink/src/lib/common/operations.ts
new file mode 100644
index 00000000000..78f0fe65672
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/common/operations.ts
@@ -0,0 +1,306 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { NUELINK_LIMITS, nuelinkClient } from './client';
+import { nuelinkInputs } from './inputs';
+import { nuelinkTime } from './time';
+
+export const nuelinkPosts = {
+ create,
+ update,
+ remove,
+ list,
+ listPublished,
+ upload,
+};
+
+async function create({ apiKey, brandId, collectionId, props, pollAllowed }: { apiKey: string; brandId: string; collectionId: string; props: Record<string, unknown>; pollAllowed: boolean }) {
+ const publishMode = nuelinkInputs.oneOf({ value: props['publishMode'], label: 'Publish Mode', allowed: PUBLISH_MODES }) ?? 'DRAFT';
+ const poll = pollAllowed
+ ? nuelinkInputs.poll({
+ question: props['pollQuestion'],
+ options: props['pollOptions'],
+ period: props['pollPeriod'],
+ correctOptionIndex: props['pollCorrectOptionIndex'],
+ explanation: props['pollExplanation'],
+ })
+ : undefined;
+ const caption = poll === undefined ? nuelinkInputs.requiredText({ value: props['caption'], label: 'Caption', max: 3000 }) : nuelinkInputs.optionalText({ value: props['caption'], label: 'Caption', max: 3000 });
+ if (pollAllowed && caption === undefined && poll === undefined) {
+ throw new Error('Set a caption, a poll, or both.');
+ }
+ const title = nuelinkInputs.optionalText({ value: props['title'], label: 'Title', max: 255 });
+ const alt = nuelinkInputs.optionalText({ value: props['alt'], label: 'Alt Text', max: 255 });
+ const linkText = nuelinkInputs.optionalText({ value: props['link'], label: 'Link', max: 1000 });
+ const link = linkText === undefined ? undefined : nuelinkInputs.httpUrl({ value: linkText, label: 'Link' });
+ const media = nuelinkInputs.mediaItems({ value: props['media'] });
+ const comment = firstComment({ text: props['firstComment'], delay: props['firstCommentDelaySeconds'] });
+ const platforms = platformOptions({ props });
+ const hasSchedule = nuelinkInputs.hasValue({ value: props['scheduledAt'] });
+ if (publishMode === 'SCHEDULE' && !hasSchedule) {
+ throw new Error('Publish Mode is Schedule, so set Scheduled Time (at least 10 minutes ahead).');
+ }
+ if (publishMode !== 'SCHEDULE' && hasSchedule) {
+ throw new Error('Scheduled Time is only used when Publish Mode is Schedule. Clear it or switch Publish Mode to Schedule.');
+ }
+ const schedule = publishMode === 'SCHEDULE' ? await nuelinkTime.scheduleForBrand({ apiKey, brandId, value: props['scheduledAt'], label: 'Scheduled Time' }) : undefined;
+ const data = await nuelinkClient.request({
+ apiKey,
+ method: HttpMethod.POST,
+ path: ['brands', brandId, 'collections', collectionId, 'posts'],
+ body: {
+ ...(caption === undefined ? {} : { caption }),
+ ...(poll === undefined ? {} : { poll }),
+ publishMode,
+ ...(schedule === undefined ? {} : { scheduledAt: schedule.local }),
+ ...(title === undefined ? {} : { title }),
+ ...(alt === undefined ? {} : { alt }),
+ ...(link === undefined ? {} : { link }),
+ ...(media.length === 0 ? {} : { media }),
+ ...(nuelinkInputs.isChecked({ value: props['postAsStory'] }) ? { postAsStory: true } : {}),
+ ...(nuelinkInputs.isChecked({ value: props['autoThreadText'] }) ? { autoThreadText: true } : {}),
+ ...(comment === undefined ? {} : { comment }),
+ ...(platforms === undefined ? {} : { platforms }),
+ },
+ timeoutMs: NUELINK_LIMITS.createTimeoutMs,
+ timeoutHint: NUELINK_LIMITS.createTimeoutHint,
+ });
+ const record = nuelinkClient.isRecord(data) ? data : {};
+ return {
+ id: record['id'] ?? null,
+ message: record['message'] ?? null,
+ brandId,
+ collectionId,
+ publishMode,
+ scheduledAt: schedule?.local ?? null,
+ scheduledAtUtc: schedule?.utc ?? null,
+ brandTimezone: schedule?.timeZone ?? null,
+ };
+}
+
+async function update({ apiKey, brandId, postId, props }: { apiKey: string; brandId: string; postId: string; props: Record<string, unknown> }) {
+ const caption = nuelinkInputs.optionalText({ value: props['caption'], label: 'New Caption', max: 3000 });
+ const publishMode = nuelinkInputs.oneOf({ value: props['publishMode'], label: 'New Publish Mode', allowed: UPDATE_MODES });
+ const queuePosition = nuelinkInputs.oneOf({ value: props['queuePosition'], label: 'Queue Position', allowed: QUEUE_POSITIONS });
+ const hasSchedule = nuelinkInputs.hasValue({ value: props['scheduledAt'] });
+ if (caption === undefined && publishMode === undefined && queuePosition === undefined) {
+ throw new Error('Nothing to update. Set New Caption, New Publish Mode or Queue Position.');
+ }
+ if (publishMode === 'SCHEDULE' && !hasSchedule) {
+ throw new Error('New Publish Mode is Schedule, so set Scheduled Time (at least 10 minutes ahead).');
+ }
+ if (publishMode !== 'SCHEDULE' && hasSchedule) {
+ throw new Error('Scheduled Time is only used when New Publish Mode is Schedule. Clear it or switch the mode to Schedule.');
+ }
+ if (queuePosition !== undefined && publishMode !== undefined && publishMode !== 'QUEUE') {
+ throw new Error('Queue Position only works on its own or with New Publish Mode = Add to Queue.');
+ }
+ const scheduledAt = publishMode === 'SCHEDULE' ? (await nuelinkTime.scheduleForBrand({ apiKey, brandId, value: props['scheduledAt'], label: 'Scheduled Time' })).local : undefined;
+ return nuelinkClient.request({
+ apiKey,
+ method: HttpMethod.PATCH,
+ path: ['brands', brandId, 'posts', postId],
+ body: {
+ ...(caption === undefined ? {} : { caption }),
+ ...(publishMode === undefined ? {} : { publishMode }),
+ ...(scheduledAt === undefined ? {} : { scheduledAt }),
+ ...(queuePosition === undefined ? {} : { queuePosition }),
+ },
+ });
+}
+
+async function remove({ apiKey, brandId, postId }: { apiKey: string; brandId: string; postId: string }) {
+ return nuelinkClient.request({
+ apiKey,
+ method: HttpMethod.DELETE,
+ path: ['brands', brandId, 'posts', postId],
+ });
+}
+
+async function list({ apiKey, brandId, collectionId, props }: { apiKey: string; brandId: string; collectionId: string | undefined; props: Record<string, unknown> }) {
+ const createdFrom = nuelinkInputs.hasValue({ value: props['createdFrom'] }) ? nuelinkTime.toUtcFilter({ value: props['createdFrom'], label: 'Created From' }) : undefined;
+ const createdTo = nuelinkInputs.hasValue({ value: props['createdTo'] }) ? nuelinkTime.toUtcFilter({ value: props['createdTo'], label: 'Created To' }) : undefined;
+ if (createdFrom !== undefined && createdTo !== undefined && createdFrom > createdTo) {
+ throw new Error('Created To must not be earlier than Created From.');
+ }
+ const { page, perPage } = nuelinkInputs.paging({ page: props['page'], perPage: props['perPage'] });
+ return nuelinkClient.getPage({
+ apiKey,
+ path: ['brands', brandId, 'posts'],
+ page,
+ perPage,
+ query: {
+ collection_id: collectionId,
+ view: nuelinkInputs.oneOf({ value: props['view'], label: 'Show', allowed: VIEWS }),
+ status: nuelinkInputs.oneOf({ value: props['status'], label: 'Status', allowed: POST_STATUSES }),
+ post_type: nuelinkInputs.oneOf({ value: props['postType'], label: 'Post Type', allowed: POST_TYPES }),
+ posting_type: nuelinkInputs.oneOf({ value: props['postingType'], label: 'Posting Type', allowed: POSTING_TYPES }),
+ created_from: createdFrom,
+ created_to: createdTo,
+ sort_by: nuelinkInputs.oneOf({ value: props['sortBy'], label: 'Sort By', allowed: POST_SORT_FIELDS }),
+ sort_order: nuelinkInputs.oneOf({ value: props['sortOrder'], label: 'Sort Order', allowed: SORT_ORDERS }),
+ },
+ });
+}
+
+async function listPublished({ apiKey, brandId, props, ids }: { apiKey: string; brandId: string; props: Record<string, unknown>; ids: { collection: unknown; channel: unknown; post: unknown } }) {
+ const publishedFrom = nuelinkInputs.hasValue({ value: props['publishedFrom'] }) ? nuelinkTime.toUtcFilter({ value: props['publishedFrom'], label: 'Published From' }) : undefined;
+ const publishedTo = nuelinkInputs.hasValue({ value: props['publishedTo'] }) ? nuelinkTime.toUtcFilter({ value: props['publishedTo'], label: 'Published To' }) : undefined;
+ if (publishedFrom !== undefined && publishedTo !== undefined && publishedFrom > publishedTo) {
+ throw new Error('Published To must not be earlier than Published From.');
+ }
+ const { page, perPage } = nuelinkInputs.paging({ page: props['page'], perPage: props['perPage'] });
+ return nuelinkClient.getPage({
+ apiKey,
+ path: ['brands', brandId, 'published-posts'],
+ page,
+ perPage,
+ query: {
+ status: nuelinkInputs.oneOf({ value: props['status'], label: 'Delivery Status', allowed: DELIVERY_STATUSES }),
+ collection_id: nuelinkInputs.optionalId({ value: ids.collection, label: 'Collection' }),
+ channel_id: nuelinkInputs.optionalId({ value: ids.channel, label: 'Channel' }),
+ post_id: nuelinkInputs.optionalId({ value: ids.post, label: 'Post ID' }),
+ post_type: nuelinkInputs.optionalText({ value: props['postType'], label: 'Post Type', max: 50 })?.trim(),
+ search: nuelinkInputs.optionalText({ value: props['search'], label: 'Search Text', max: 255 })?.trim(),
+ published_from: publishedFrom,
+ published_to: publishedTo,
+ sort_by: nuelinkInputs.oneOf({ value: props['sortBy'], label: 'Sort By', allowed: PUBLISHED_SORT_FIELDS }),
+ sort_order: nuelinkInputs.oneOf({ value: props['sortOrder'], label: 'Sort Order', allowed: SORT_ORDERS }),
+ },
+ });
+}
+
+async function upload({ apiKey, brandId, file }: { apiKey: string; brandId: string; file: unknown }) {
+ const checked = fileOf({ value: file });
+ const form = new FormData();
+ form.append('media', new Blob([new Uint8Array(checked.data)], { type: checked.mimeType }), checked.filename);
+ return nuelinkClient.request({
+ apiKey,
+ method: HttpMethod.POST,
+ path: ['brands', brandId, 'media'],
+ body: form,
+ timeoutMs: NUELINK_LIMITS.uploadTimeoutMs,
+ timeoutHint: 'The file may still have been uploaded; check the brand\'s media library in Nuelink before uploading it again.',
+ });
+}
+
+function firstComment({ text, delay }: { text: unknown; delay: unknown }): { comment: string; delay: number } | undefined {
+ const comment = nuelinkInputs.optionalText({ value: text, label: 'First Comment', max: 1000 });
+ const seconds = nuelinkInputs.optionalInteger({ value: delay, label: 'First Comment Delay (seconds)', min: 0, max: 31_536_000 });
+ if (comment === undefined && seconds === undefined) {
+ return undefined;
+ }
+ if (comment === undefined || seconds === undefined) {
+ throw new Error('Set First Comment and First Comment Delay together, or leave both empty.');
+ }
+ return { comment, delay: seconds };
+}
+
+function platformOptions({ props }: { props: Record<string, unknown> }): Record<string, Record<string, unknown>> | undefined {
+ const collab = nuelinkInputs.optionalText({ value: props['instagramCollab'], label: 'Instagram: Collaborator', max: 1000 });
+ const tags = nuelinkInputs.stringList({ value: props['youtubeTags'], label: 'YouTube: Tags', maxItems: 500, maxLength: 255 });
+ const instagram = {
+ ...(nuelinkInputs.isChecked({ value: props['instagramShareToFeed'] }) ? { shareToFeed: true } : {}),
+ ...(collab === undefined ? {} : { collab: collab.trim() }),
+ };
+ const tiktok = nuelinkInputs.isChecked({ value: props['tiktokAutoAddMusic'] }) ? { autoAddMusic: true } : {};
+ const youtube = tags.length === 0 ? {} : { tags };
+ const platforms = Object.fromEntries(Object.entries({ instagram, tiktok, youtube }).filter(([, options]) => Object.keys(options).length > 0));
+ return Object.keys(platforms).length === 0 ? undefined : platforms;
+}
+
+function fileOf({ value }: { value: unknown }): { filename: string; data: Buffer; mimeType: string } {
+ if (typeof value !== 'object' || value === null) {
+ throw new Error('Select a file to upload.');
+ }
+ const filename = Reflect.get(value, 'filename');
+ const data = Reflect.get(value, 'data');
+ if (typeof filename !== 'string' || !Buffer.isBuffer(data)) {
+ throw new Error('The File input did not contain a readable file. Map a file from an earlier step or upload one.');
+ }
+ const declared = Reflect.get(value, 'extension');
+ const extension = filename.includes('.')
+ ? filename.slice(filename.lastIndexOf('.') + 1).toLowerCase()
+ : typeof declared === 'string'
+ ? declared.replace(/^\./, '').toLowerCase()
+ : '';
+ const mimeType = MIME_TYPES[extension];
+ if (mimeType === undefined) {
+ throw new Error(`Nuelink accepts JPG, JPEG, PNG, BMP, MP4, MOV and PDF files; "${filename}" is not one of them.`);
+ }
+ if (data.length === 0) {
+ throw new Error(`"${filename}" is empty.`);
+ }
+ if (data.length > MAX_UPLOAD_BYTES) {
+ throw new Error(`"${filename}" is ${(data.length / 1048576).toFixed(1)} MB; Nuelink accepts files up to 100 MB.`);
+ }
+ return { filename, data, mimeType };
+}
+
+export const nuelinkCollectionChannels = {
+ add: addCollectionChannel,
+ remove: removeCollectionChannel,
+};
+
+async function addCollectionChannel({ apiKey, brandId, collectionId, channelId }: { apiKey: string; brandId: string; collectionId: string; channelId: number }) {
+ return nuelinkClient.request({ apiKey, method: HttpMethod.POST, path: ['brands', brandId, 'collections', collectionId, 'channels'], body: { channelId } });
+}
+
+async function removeCollectionChannel({ apiKey, brandId, collectionId, channelId }: { apiKey: string; brandId: string; collectionId: string; channelId: string }) {
+ return nuelinkClient.request({ apiKey, method: HttpMethod.DELETE, path: ['brands', brandId, 'collections', collectionId, 'channels', channelId] });
+}
+
+export const PUBLISH_MODES = ['DRAFT', 'QUEUE', 'SCHEDULE', 'IMMEDIATE'] as const;
+export const UPDATE_MODES = ['DRAFT', 'QUEUE', 'SCHEDULE'] as const;
+export const QUEUE_POSITIONS = ['FRONT', 'BACK'] as const;
+export const POST_TYPES = ['TEXT', 'IMAGE', 'VIDEO', 'MULTIMEDIA', 'SHORT', 'DOCUMENT', 'THREAD', 'SLIDES', 'REEL', 'TIKTOK', 'STORY', 'POLL', 'ENGAGE_COMMENT'] as const;
+export const VIEWS = ['QUEUE', 'SCHEDULED', 'DRAFT', 'PUBLISHED'] as const;
+export const POST_STATUSES = ['PENDING', 'DRAFT', 'PUBLISHED'] as const;
+export const POSTING_TYPES = ['NOW', 'SCHEDULE', 'QUEUE', 'DRAFT'] as const;
+export const POST_SORT_FIELDS = ['id', 'title', 'post_date', 'created_at', 'updated_at'] as const;
+export const DELIVERY_STATUSES = ['PUBLISHED', 'FAILED', 'RETRYING', 'SKIPPED', 'SENT'] as const;
+export const PUBLISHED_SORT_FIELDS = ['id', 'created_at', 'likes', 'comments', 'shares'] as const;
+export const SORT_ORDERS = ['asc', 'desc'] as const;
+
+export const FEED_TYPES = [
+ 'RSS',
+ 'ATOM',
+ 'YOUTUBE',
+ 'MEDIUM',
+ 'SHOPIFY',
+ 'WORDPRESS',
+ 'WOOCOMMERCE',
+ 'ETSY',
+ 'GHOST',
+ 'SUBSTACK',
+ 'ANCHOR',
+ 'TRANSISTOR',
+ 'CAPTIVATE',
+ 'SOUNDCLOUD',
+ 'BLOGGER',
+ 'WIX',
+ 'SQUARESPACEBLOG',
+ 'SQUARESPACESHOP',
+ 'WEEBLY',
+ 'TUMBLR',
+ 'SHOPIFY2',
+ 'WOOCOMMERCE2',
+ 'PRESTASHOP',
+ 'BUZZSPROUT',
+ 'RSSCOM',
+ 'CASTOS',
+ 'PODCASTCO',
+] as const;
+export const IMPORT_TYPES = ['LINK', 'IMAGE', 'VIDEO', 'CAROUSEL'] as const;
+export const REFRESH_RATES: readonly number[] = [1, 6, 12, 24];
+
+export const MEDIA_TYPES = ['IMAGE', 'VIDEO', 'GIF', 'APPLICATION', 'DOCUMENT', 'CSV'] as const;
+
+const MAX_UPLOAD_BYTES = 104_857_600;
+const MIME_TYPES: Record<string, string | undefined> = {
+ jpg: 'image/jpeg',
+ jpeg: 'image/jpeg',
+ png: 'image/png',
+ bmp: 'image/bmp',
+ mp4: 'video/mp4',
+ mov: 'video/quicktime',
+ pdf: 'application/pdf',
+};
diff --git a/packages/pieces/community/nuelink/src/lib/common/props.ts b/packages/pieces/community/nuelink/src/lib/common/props.ts
new file mode 100644
index 00000000000..e10d48cf554
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/common/props.ts
@@ -0,0 +1,204 @@
+import { AppConnectionType, Property } from '@activepieces/pieces-framework';
+import { NuelinkAuthValue, nuelinkAuths } from '../auth';
+import { NuelinkApiError, nuelinkClient } from './client';
+
+export const nuelinkProps = {
+ brand,
+ collection,
+ channel,
+ page,
+ perPage,
+ sortOrder,
+};
+
+function brand() {
+ return Property.Dropdown<number, true, typeof nuelinkAuths>({
+ auth: nuelinkAuths,
+ displayName: 'Brand',
+ description: 'The Nuelink brand (workspace) to use.',
+ required: true,
+ refreshers: [],
+ options: async ({ auth }) =>
+ dropdownOptions({
+ auth,
+ what: 'brands',
+ needsBrand: false,
+ load: async ({ apiKey }) => {
+ const { items, truncated } = await nuelinkClient.listAllPages({ apiKey, path: ['brands'] });
+ return {
+ truncated,
+ options: items.flatMap((item) => {
+ const id = item['id'];
+ if (typeof id !== 'number') {
+ return [];
+ }
+ const title = textOr({ value: item['title'], fallback: `Brand ${id}` });
+ const timezone = typeof item['timezone'] === 'string' ? ` (${item['timezone']})` : '';
+ return [{ label: `${title}${timezone}`, value: id }];
+ }),
+ };
+ },
+ }),
+ });
+}
+
+function collection<R extends boolean>({ required, description }: { required: R; description: string }) {
+ return Property.Dropdown<number, R, typeof nuelinkAuths>({
+ auth: nuelinkAuths,
+ displayName: 'Collection',
+ description,
+ required,
+ refreshers: ['brand'],
+ options: async ({ auth, brand }) =>
+ dropdownOptions({
+ auth,
+ what: 'collections',
+ needsBrand: true,
+ brand,
+ load: async ({ apiKey, brandId }) => {
+ const { items, truncated } = await nuelinkClient.listAllPages({ apiKey, path: ['brands', brandId, 'collections'] });
+ return {
+ truncated,
+ options: items.flatMap((item) => {
+ const id = item['id'];
+ if (typeof id !== 'number') {
+ return [];
+ }
+ const title = textOr({ value: item['title'], fallback: `Collection ${id}` });
+ const channels = Array.isArray(item['channels']) ? item['channels'].length : 0;
+ const paused = item['status'] === 'PAUSED' ? ', paused' : '';
+ return [{ label: `${title} (${channels} ${channels === 1 ? 'channel' : 'channels'}${paused})`, value: id }];
+ }),
+ };
+ },
+ }),
+ });
+}
+
+function channel() {
+ return Property.Dropdown<number, false, typeof nuelinkAuths>({
+ auth: nuelinkAuths,
+ displayName: 'Channel',
+ description: 'Only return results for this social channel.',
+ required: false,
+ refreshers: ['brand'],
+ options: async ({ auth, brand }) =>
+ dropdownOptions({
+ auth,
+ what: 'channels',
+ needsBrand: true,
+ brand,
+ load: async ({ apiKey, brandId }) => {
+ const { items, truncated } = await nuelinkClient.listAllPages({ apiKey, path: ['brands', brandId, 'channels'] });
+ return {
+ truncated,
+ options: items.flatMap((item) => {
+ const id = item['id'];
+ if (typeof id !== 'number') {
+ return [];
+ }
+ const name = textOr({ value: item['name'], fallback: `Channel ${id}` });
+ const type = typeof item['type'] === 'string' ? ` (${item['type']})` : '';
+ return [{ label: `${name}${type}`, value: id }];
+ }),
+ };
+ },
+ }),
+ });
+}
+
+function page() {
+ return Property.Number({
+ displayName: 'Page',
+ description: 'Which page of results to return, starting at 1. When the output says hasMore is true, run again with the next page number.',
+ required: false,
+ defaultValue: 1,
+ });
+}
+
+function perPage() {
+ return Property.Number({
+ displayName: 'Results per Page',
+ description: 'How many results to return per page (1 to 100).',
+ required: false,
+ defaultValue: 25,
+ });
+}
+
+function sortOrder() {
+ return Property.StaticDropdown({
+ displayName: 'Sort Order',
+ required: false,
+ defaultValue: 'desc',
+ options: {
+ options: [
+ { label: 'Newest / highest first', value: 'desc' },
+ { label: 'Oldest / lowest first', value: 'asc' },
+ ],
+ },
+ });
+}
+
+async function dropdownOptions({
+ auth,
+ what,
+ needsBrand,
+ brand,
+ load,
+}: {
+ auth: NuelinkAuthValue | undefined;
+ what: string;
+ needsBrand: boolean;
+ brand?: unknown;
+ load: (params: { apiKey: string; brandId: string }) => Promise<{ options: { label: string; value: number }[]; truncated: boolean }>;
+}) {
+ if (auth === undefined) {
+ return { disabled: true, options: [], placeholder: 'Connect your Nuelink account first.' };
+ }
+ if (auth.type !== AppConnectionType.CUSTOM_AUTH) {
+ return { disabled: true, options: [], placeholder: 'This needs a Nuelink API Key connection. Automation tokens only work with Create Post.' };
+ }
+ const brandId = needsBrand ? brandIdOf({ value: brand }) : '';
+ if (needsBrand && brandId.length === 0) {
+ return { disabled: true, options: [], placeholder: 'Select a brand first.' };
+ }
+ try {
+ const apiKey = nuelinkClient.apiKeyOf({ auth });
+ const { options, truncated } = await load({ apiKey, brandId });
+ if (options.length === 0) {
+ return { disabled: false, options: [], placeholder: `No ${what} found in Nuelink.` };
+ }
+ return {
+ disabled: false,
+ options,
+ placeholder: truncated ? `Showing the first ${options.length} ${what}. Use the ${what} ID in a custom value for others.` : undefined,
+ };
+ } catch (error) {
+ return { disabled: true, options: [], placeholder: dropdownError({ error, what }) };
+ }
+}
+
+function brandIdOf({ value }: { value: unknown }): string {
+ try {
+ return nuelinkClient.numericId({ value, label: 'Brand' });
+ } catch {
+ return '';
+ }
+}
+
+function dropdownError({ error, what }: { error: unknown; what: string }): string {
+ if (error instanceof NuelinkApiError) {
+ if (error.status === 401) {
+ return 'Nuelink did not accept the API key (401). It may have expired; generate a new one and update the connection.';
+ }
+ if (error.status === 429) {
+ return 'Nuelink rate limit reached (429). Wait a minute and reopen this list.';
+ }
+ return `Could not load ${what} from Nuelink (HTTP ${error.status}).`;
+ }
+ return `Could not load ${what} from Nuelink. Check the connection and try again.`;
+}
+
+function textOr({ value, fallback }: { value: unknown; fallback: string }): string {
+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : fallback;
+}
diff --git a/packages/pieces/community/nuelink/src/lib/common/time.ts b/packages/pieces/community/nuelink/src/lib/common/time.ts
new file mode 100644
index 00000000000..703f3c0e24c
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/common/time.ts
@@ -0,0 +1,104 @@
+import { nuelinkClient } from './client';
+
+export const nuelinkTime = {
+ parseInstant,
+ assertTimeZone,
+ formatInZone,
+ toBrandSchedule,
+ toUtcFilter,
+ scheduleForBrand,
+ parseZonedInstant,
+};
+
+function parseInstant({ value, label }: { value: unknown; label: string }): Date {
+ const text = typeof value === 'string' ? value.trim() : '';
+ if (text.length === 0) {
+ throw new Error(`${label} is empty. Use an ISO 8601 date and time, for example 2026-10-12T09:00:00Z.`);
+ }
+ const normalized = NAIVE_DATE.test(text) ? `${text}T00:00:00Z` : NAIVE_DATE_TIME.test(text) ? `${text.replace(' ', 'T')}Z` : text;
+ const date = new Date(normalized);
+ if (Number.isNaN(date.getTime())) {
+ throw new Error(`${label} is not a valid date and time: "${text}". Use ISO 8601, for example 2026-10-12T09:00:00Z.`);
+ }
+ return date;
+}
+
+function assertTimeZone({ timeZone, brandTitle }: { timeZone: string | null; brandTitle: string }): string {
+ if (timeZone === null || timeZone.trim().length === 0) {
+ throw new Error(
+ `The Nuelink brand "${brandTitle}" has no timezone set, so the scheduled time cannot be converted to brand time. Set the brand's timezone in Nuelink and try again.`
+ );
+ }
+ try {
+ new Intl.DateTimeFormat('en-US', { timeZone: timeZone.trim() });
+ } catch {
+ throw new Error(`The Nuelink brand "${brandTitle}" has a timezone this step does not recognise ("${timeZone}"). Set an IANA timezone such as Europe/London in Nuelink.`);
+ }
+ return timeZone.trim();
+}
+
+function formatInZone({ date, timeZone }: { date: Date; timeZone: string }): string {
+ const parts = new Intl.DateTimeFormat('en-US', {
+ timeZone,
+ year: 'numeric',
+ month: '2-digit',
+ day: '2-digit',
+ hour: '2-digit',
+ minute: '2-digit',
+ second: '2-digit',
+ hourCycle: 'h23',
+ }).formatToParts(date);
+ const part = (type: Intl.DateTimeFormatPartTypes) => parts.find((item) => item.type === type)?.value ?? '00';
+ return `${part('year')}-${part('month')}-${part('day')} ${part('hour')}:${part('minute')}:${part('second')}`;
+}
+
+function toBrandSchedule({ value, timeZone, now, label }: { value: unknown; timeZone: string; now: number; label: string }): BrandSchedule {
+ const date = assertLead({ value, label, now });
+ const local = formatInZone({ date, timeZone });
+ const hourBefore = formatInZone({ date: new Date(date.getTime() - HOUR_MS), timeZone });
+ const hourAfter = formatInZone({ date: new Date(date.getTime() + HOUR_MS), timeZone });
+ if (hourBefore === local || hourAfter === local) {
+ throw new Error(
+ `${label} (${date.toISOString()}) falls in the hour that repeats when ${timeZone} leaves daylight saving time, so Nuelink could publish it an hour off. Pick a time outside that hour.`
+ );
+ }
+ return { local, utc: date.toISOString() };
+}
+
+function toUtcFilter({ value, label }: { value: unknown; label: string }): string {
+ return parseInstant({ value, label }).toISOString().slice(0, 19).replace('T', ' ');
+}
+
+async function scheduleForBrand({ apiKey, brandId, value, label }: { apiKey: string; brandId: string; value: unknown; label: string }): Promise<BrandSchedule & { timeZone: string }> {
+ assertLead({ value, label, now: Date.now() });
+ const brand = await nuelinkClient.findBrand({ apiKey, brandId });
+ const timeZone = assertTimeZone({ timeZone: brand.timezone, brandTitle: brand.title });
+ return { ...toBrandSchedule({ value, timeZone, now: Date.now(), label }), timeZone };
+}
+
+function parseZonedInstant({ value, label }: { value: unknown; label: string }): Date {
+ const text = typeof value === 'string' ? value.trim() : '';
+ if (text.length > 0 && !EXPLICIT_ZONE.test(text)) {
+ throw new Error(`${label} "${text.slice(0, 40)}" has no timezone. Send an ISO-8601 time with an offset, e.g. 2026-10-12T09:00:00+03:00.`);
+ }
+ return parseInstant({ value, label });
+}
+
+function assertLead({ value, label, now }: { value: unknown; label: string; now: number }): Date {
+ const date = parseZonedInstant({ value, label });
+ if (date.getTime() - now < MIN_SCHEDULE_LEAD_MS) {
+ throw new Error(`${label} must be at least 10 minutes in the future (Nuelink rule). It was ${date.toISOString()}.`);
+ }
+ return date;
+}
+
+const NAIVE_DATE = /^\d{4}-\d{2}-\d{2}$/;
+const NAIVE_DATE_TIME = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(:\d{2}(\.\d{1,9})?)?$/;
+const EXPLICIT_ZONE = /T\d{2}:\d{2}(:\d{2}(\.\d{1,9})?)?(Z|[+-]\d{2}:?\d{2})$/i;
+const MIN_SCHEDULE_LEAD_MS = 10 * 60 * 1000;
+const HOUR_MS = 60 * 60 * 1000;
+
+type BrandSchedule = {
+ local: string;
+ utc: string;
+};
diff --git a/packages/pieces/community/nuelink/src/lib/output-schemas.ts b/packages/pieces/community/nuelink/src/lib/output-schemas.ts
new file mode 100644
index 00000000000..18ee738032b
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/output-schemas.ts
@@ -0,0 +1,307 @@
+import { OutputSchema } from '@activepieces/pieces-framework';
+
+const pagingFields: OutputSchema['fields'] = [
+ { key: 'page', label: 'Page', format: 'number' },
+ { key: 'perPage', label: 'Results per Page', format: 'number' },
+ { key: 'total', label: 'Total Matching', format: 'number' },
+ { key: 'lastPage', label: 'Last Page', format: 'number' },
+ { key: 'hasMore', label: 'Has More Pages', format: 'boolean' },
+];
+
+const postFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Post ID', format: 'number' },
+ { key: 'collectionId', label: 'Collection ID', format: 'number' },
+ { key: 'title', label: 'Title' },
+ { key: 'body', label: 'Caption' },
+ { key: 'media', label: 'Media', labelKey: 'id', listItems: [{ key: 'id', label: 'Media ID' }] },
+ { key: 'postType', label: 'Post Type' },
+ { key: 'postingType', label: 'Publish Mode' },
+ { key: 'status', label: 'Status' },
+ { key: 'postDate', label: 'Scheduled For (UTC)', description: 'UTC time in the format YYYY-MM-DD HH:MM:SS; empty unless the post is scheduled.' },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+ { key: 'updatedAt', label: 'Updated At', format: 'datetime' },
+ {
+ key: 'poll',
+ label: 'Poll',
+ children: [
+ { key: 'question', label: 'Question' },
+ { key: 'options', label: 'Options' },
+ { key: 'caption', label: 'Caption' },
+ { key: 'period', label: 'Duration' },
+ { key: 'correctOptionIndex', label: 'Correct Option Index', format: 'number' },
+ { key: 'explanation', label: 'Explanation' },
+ ],
+ },
+];
+
+const publishedPostFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Published Result ID', format: 'number' },
+ { key: 'postId', label: 'Post ID', format: 'number' },
+ { key: 'collectionId', label: 'Collection ID', format: 'number' },
+ {
+ key: 'channel',
+ label: 'Channel',
+ children: [
+ { key: 'id', label: 'Channel ID', format: 'number' },
+ { key: 'name', label: 'Channel Name' },
+ { key: 'type', label: 'Platform' },
+ ],
+ },
+ { key: 'postType', label: 'Post Type' },
+ { key: 'body', label: 'Published Text' },
+ { key: 'url', label: 'Post URL', format: 'url' },
+ { key: 'status', label: 'Delivery Status' },
+ { key: 'message', label: 'Delivery Message' },
+ { key: 'publishedAt', label: 'Published At', format: 'datetime' },
+ {
+ key: 'results',
+ label: 'Engagement',
+ children: [
+ { key: 'likes', label: 'Likes', format: 'number' },
+ { key: 'comments', label: 'Comments', format: 'number' },
+ { key: 'shares', label: 'Shares', format: 'number' },
+ { key: 'views', label: 'Views', format: 'number' },
+ { key: 'saves', label: 'Saves', format: 'number' },
+ { key: 'engagement', label: 'Engagement', format: 'number' },
+ { key: 'clicks', label: 'Clicks', format: 'number' },
+ { key: 'impressions', label: 'Impressions', format: 'number' },
+ { key: 'reach', label: 'Reach', format: 'number' },
+ ],
+ },
+];
+
+const brandFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Brand ID', format: 'number' },
+ { key: 'title', label: 'Name' },
+ { key: 'description', label: 'Description' },
+ { key: 'timezone', label: 'Timezone' },
+ { key: 'queueStatus', label: 'Queue Status' },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+ { key: 'updatedAt', label: 'Updated At', format: 'datetime' },
+];
+
+const collectionFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Collection ID', format: 'number' },
+ { key: 'title', label: 'Name' },
+ { key: 'description', label: 'Description' },
+ { key: 'status', label: 'Status' },
+ { key: 'timezone', label: 'Timezone' },
+ {
+ key: 'evergreen',
+ label: 'Evergreen',
+ children: [
+ { key: 'enabled', label: 'Enabled', format: 'boolean' },
+ { key: 'maxRepublish', label: 'Max Republish', format: 'number' },
+ ],
+ },
+ {
+ key: 'channels',
+ label: 'Channels',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Channel ID', format: 'number' },
+ { key: 'name', label: 'Name' },
+ { key: 'status', label: 'Status' },
+ { key: 'type', label: 'Platform' },
+ ],
+ },
+ {
+ key: 'queues',
+ label: 'Queue Slots',
+ labelKey: 'date',
+ listItems: [
+ { key: 'id', label: 'Slot ID', format: 'number' },
+ { key: 'day', label: 'Day' },
+ { key: 'time', label: 'Time (Brand Timezone)' },
+ { key: 'date', label: 'Day and Time' },
+ { key: 'status', label: 'Status' },
+ ],
+ },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+ { key: 'updatedAt', label: 'Updated At', format: 'datetime' },
+];
+
+const collectionPostCountsField: OutputSchema['fields'][number] = {
+ key: 'postsCount',
+ label: 'Post Counts',
+ children: [
+ { key: 'queued', label: 'Queued', format: 'number' },
+ { key: 'scheduled', label: 'Scheduled', format: 'number' },
+ { key: 'drafts', label: 'Drafts', format: 'number' },
+ { key: 'published', label: 'Published', format: 'number' },
+ ],
+};
+
+const evergreenIntervalField: OutputSchema['fields'][number] = { key: 'maxRepublish', label: 'Evergreen Interval (weeks)', format: 'number' };
+
+const WEEKDAYS: Array<[string, string]> = [
+ ['MON', 'Monday'],
+ ['TUE', 'Tuesday'],
+ ['WED', 'Wednesday'],
+ ['THU', 'Thursday'],
+ ['FRI', 'Friday'],
+ ['SAT', 'Saturday'],
+ ['SUN', 'Sunday'],
+];
+
+const automationFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Automation ID', format: 'number' },
+ { key: 'name', label: 'Name' },
+ { key: 'collectionId', label: 'Collection ID', format: 'number' },
+ { key: 'status', label: 'Status', description: 'ACTIVE, or INACTIVE when paused.' },
+ { key: 'type', label: 'Feed Type' },
+ { key: 'feedUrl', label: 'Feed URL', format: 'url' },
+ { key: 'runCount', label: 'Run Count', format: 'number' },
+ { key: 'importAsType', label: 'Import As' },
+ { key: 'lastRun', label: 'Last Run (Unix Time)', format: 'number', description: '0 means it has not run yet.' },
+ { key: 'title', label: 'Title Template' },
+ { key: 'caption', label: 'Caption Template' },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+ { key: 'updatedAt', label: 'Updated At', format: 'datetime' },
+];
+
+const scheduleSlotFields: OutputSchema['fields'] = [
+ { key: 'time', label: 'Time (Brand Timezone)' },
+ { key: 'queueId', label: 'Slot ID', format: 'number' },
+ { key: 'collectionId', label: 'Collection ID', format: 'number' },
+ { key: 'collectionTitle', label: 'Collection' },
+ { key: 'collectionStatus', label: 'Collection Status' },
+];
+
+const queueSlotFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Slot ID', format: 'number' },
+ { key: 'day', label: 'Day' },
+ { key: 'time', label: 'Time (Brand Timezone)' },
+ { key: 'date', label: 'Day and Time' },
+ { key: 'status', label: 'Status' },
+];
+
+export const nuelinkOutputSchemas = {
+ createCollectionPost: {
+ fields: [
+ { key: 'id', label: 'Post ID', format: 'number' },
+ { key: 'message', label: 'Message' },
+ { key: 'brandId', label: 'Brand ID' },
+ { key: 'collectionId', label: 'Collection ID' },
+ { key: 'publishMode', label: 'Publish Mode' },
+ { key: 'scheduledAt', label: 'Scheduled For (Brand Time)', description: 'The brand-local time sent to Nuelink; empty unless Publish Mode is Schedule.' },
+ { key: 'scheduledAtUtc', label: 'Scheduled For (UTC)', format: 'datetime' },
+ { key: 'brandTimezone', label: 'Brand Timezone' },
+ ],
+ },
+ updatePost: { fields: postFields },
+ deletePost: {
+ fields: [
+ { key: 'id', label: 'Deleted Post ID', format: 'number' },
+ { key: 'message', label: 'Message' },
+ ],
+ },
+ listPosts: {
+ fields: [{ key: 'items', label: 'Posts', labelKey: 'id', listItems: postFields }, ...pagingFields],
+ },
+ listPublishedPosts: {
+ fields: [{ key: 'items', label: 'Published Results', labelKey: 'status', listItems: publishedPostFields }, ...pagingFields],
+ },
+ uploadMedia: {
+ fields: [
+ { key: 'id', label: 'Media ID' },
+ { key: 'type', label: 'MIME Type' },
+ { key: 'size', label: 'Size', format: 'filesize' },
+ ],
+ },
+ listBrands: {
+ fields: [{ key: 'items', label: 'Brands', labelKey: 'title', listItems: brandFields }, ...pagingFields],
+ },
+ listCollections: {
+ fields: [{ key: 'items', label: 'Collections', labelKey: 'title', listItems: [...collectionFields, evergreenIntervalField, collectionPostCountsField] }, ...pagingFields],
+ },
+ newPublishedPost: { fields: publishedPostFields },
+ profile: {
+ fields: [
+ { key: 'id', label: 'User ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'joinedAt', label: 'Joined At', format: 'datetime' },
+ { key: 'timezone', label: 'User Timezone', description: 'May be empty or an internal ID; not used for scheduling.' },
+ ],
+ },
+ schedule: {
+ fields: [
+ { key: 'timezone', label: 'Brand Timezone', description: 'May be an offset such as +03:00.' },
+ { key: 'queueStatus', label: 'Queue Status' },
+ {
+ key: 'schedule',
+ label: 'Weekly Slots',
+ children: WEEKDAYS.map(([key, label]) => ({ key, label, labelKey: 'time', listItems: scheduleSlotFields })),
+ },
+ ],
+ },
+ collection: { fields: [...collectionFields, evergreenIntervalField] },
+ queueSlot: { fields: queueSlotFields },
+ deletedQueueSlot: {
+ fields: [
+ { key: 'collectionId', label: 'Collection ID', format: 'number' },
+ { key: 'queueId', label: 'Deleted Slot ID', format: 'number' },
+ ],
+ },
+ automation: { fields: automationFields },
+ listAutomations: {
+ fields: [{ key: 'items', label: 'Automations', labelKey: 'name', listItems: automationFields }, ...pagingFields],
+ },
+ automationStatus: {
+ fields: [
+ { key: 'id', label: 'Automation ID', format: 'number' },
+ { key: 'name', label: 'Name' },
+ { key: 'status', label: 'Status', description: 'ACTIVE, or INACTIVE when paused.' },
+ ],
+ },
+ listChannels: {
+ fields: [
+ {
+ key: 'items',
+ label: 'Channels',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Channel ID', format: 'number' },
+ { key: 'name', label: 'Name' },
+ { key: 'status', label: 'Status' },
+ { key: 'type', label: 'Platform' },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+ { key: 'updatedAt', label: 'Updated At', format: 'datetime' },
+ ],
+ },
+ ...pagingFields,
+ ],
+ },
+ collectionChannel: {
+ fields: [
+ { key: 'collectionId', label: 'Collection ID', format: 'number' },
+ { key: 'channelId', label: 'Channel ID', format: 'number' },
+ ],
+ },
+ movePosts: {
+ fields: [
+ { key: 'moved', label: 'Posts Moved', format: 'number' },
+ { key: 'sourceCollectionId', label: 'Source Collection ID', format: 'number' },
+ { key: 'destinationCollectionId', label: 'Destination Collection ID', format: 'number' },
+ { key: 'message', label: 'Message' },
+ ],
+ },
+ listMedia: {
+ fields: [
+ {
+ key: 'items',
+ label: 'Media',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Media ID' },
+ { key: 'name', label: 'File Name' },
+ { key: 'type', label: 'MIME Type' },
+ { key: 'size', label: 'Size', format: 'filesize' },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+ { key: 'updatedAt', label: 'Updated At', format: 'datetime' },
+ ],
+ },
+ ...pagingFields,
+ ],
+ },
+} satisfies Record<string, OutputSchema>;
diff --git a/packages/pieces/community/nuelink/src/lib/triggers/new-published-post.ts b/packages/pieces/community/nuelink/src/lib/triggers/new-published-post.ts
new file mode 100644
index 00000000000..0e7ee716f27
--- /dev/null
+++ b/packages/pieces/community/nuelink/src/lib/triggers/new-published-post.ts
@@ -0,0 +1,256 @@
+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';
+import { NuelinkAuthValue, nuelinkAuths } from '../auth';
+import { nuelinkClient } from '../common/client';
+import { nuelinkInputs } from '../common/inputs';
+import { nuelinkProps } from '../common/props';
+import { nuelinkOutputSchemas } from '../output-schemas';
+
+export const newPublishedPost = createTrigger({
+ auth: nuelinkAuths,
+ name: 'new_published_post',
+ classification: 'READ',
+ displayName: 'New Published Post',
+ description: 'Fires when Nuelink publishes a post to a channel (or fails to, if you choose Failed). Runs once per channel.',
+ aiMetadata: {
+ description:
+ 'Fires once per channel delivery when Nuelink publishes a post (or fails to, if the Failed status is chosen); the payload is one channel result with its platform URL and the engagement counts at that moment. Checked by polling, so it can lag a few minutes.',
+ },
+ props: {
+ brand: nuelinkProps.brand(),
+ status: Property.StaticDropdown({
+ displayName: 'Trigger On',
+ required: true,
+ defaultValue: 'PUBLISHED',
+ options: {
+ options: [
+ { label: 'Published', value: 'PUBLISHED' },
+ { label: 'Failed to publish', value: 'FAILED' },
+ ],
+ },
+ }),
+ collection: nuelinkProps.collection({ required: false, description: 'Only fire for posts from this collection. Leave empty for all collections.' }),
+ },
+ sampleData: {
+ id: 120045,
+ postId: 8801,
+ collectionId: 77,
+ channel: { id: 501, name: 'Acme on LinkedIn', type: 'LinkedIn' },
+ postType: 'IMAGE',
+ body: 'Our new product is live.',
+ url: 'https://www.linkedin.com/feed/update/urn:li:share:123',
+ status: 'PUBLISHED',
+ message: null,
+ publishedAt: '2026-10-10T14:00:00.000000Z',
+ results: { likes: 42, comments: 5, shares: 3, views: 1200, saves: 18, engagement: 68, clicks: 27, impressions: 1540, reach: 1310 },
+ },
+ outputSchema: nuelinkOutputSchemas.newPublishedPost,
+ type: TriggerStrategy.POLLING,
+ async onEnable(context) {
+ const query = pollQuery({ auth: context.auth, propsValue: context.propsValue });
+ if (context.isRepublish && isPollState(await context.store.get<unknown>(STORE_KEY))) {
+ return;
+ }
+ await seed({ query, store: context.store });
+ },
+ async onDisable(context) {
+ await context.store.delete(STORE_KEY);
+ },
+ async test(context) {
+ const query = pollQuery({ auth: context.auth, propsValue: context.propsValue });
+ const result = await nuelinkClient.getPage({
+ apiKey: query.apiKey,
+ path: ['brands', query.brandId, 'published-posts'],
+ page: 1,
+ perPage: TEST_SAMPLE_SIZE,
+ query: { ...query.filters, sort_by: 'id', sort_order: 'desc' },
+ });
+ return result.items;
+ },
+ async run(context) {
+ const query = pollQuery({ auth: context.auth, propsValue: context.propsValue });
+ const state = await context.store.get<unknown>(STORE_KEY);
+ if (!isPollState(state)) {
+ await seed({ query, store: context.store });
+ return [];
+ }
+ const startedAt = Date.now();
+ const since = state.resume?.since ?? state.lastPoll - OVERLAP_MS;
+ const firstPage = state.resume?.page ?? 1;
+ const { items, truncated } = await collect({ query, since, firstPage });
+ const recent = unpack({ groups: state.recent ?? [] });
+ const seen = new Set([...state.seen, ...recent.map(([id]) => id)]);
+ const fresh = uniqueById({ items }).filter((item) => !seen.has(idOf({ item })));
+ const lastPoll = truncated ? state.lastPoll : startedAt;
+ const nextState: PollState = {
+ seen: [...fresh.map((item) => idOf({ item })).reverse(), ...state.seen].slice(0, SEEN_CAP),
+ recent: keepRecent({ entries: [...recent, ...entriesOf({ items: fresh, fallback: startedAt })], floor: truncated ? since : lastPoll - OVERLAP_MS }),
+ lastPoll,
+ ...(truncated ? { resume: { since, page: firstPage + MAX_PAGES } } : {}),
+ };
+ await context.store.put<PollState>(STORE_KEY, nextState);
+ return fresh;
+ },
+});
+
+function pollQuery({ auth, propsValue }: { auth: NuelinkAuthValue | undefined; propsValue: Record<string, unknown> }): PollQuery {
+ const apiKey = nuelinkClient.apiKeyOf({ auth });
+ const brandId = nuelinkClient.numericId({ value: propsValue['brand'], label: 'Brand' });
+ const status = nuelinkInputs.oneOf({ value: propsValue['status'], label: 'Trigger On', allowed: STATUSES }) ?? 'PUBLISHED';
+ const collectionId = nuelinkInputs.optionalId({ value: propsValue['collection'], label: 'Collection' });
+ return { apiKey, brandId, filters: { status, collection_id: collectionId } };
+}
+
+async function seed({ query, store }: { query: PollQuery; store: PollStore }): Promise<void> {
+ const startedAt = Date.now();
+ const { items } = await collect({ query, since: startedAt - OVERLAP_MS, firstPage: 1 });
+ const unique = uniqueById({ items });
+ const seen = unique
+ .map((item) => idOf({ item }))
+ .reverse()
+ .slice(0, SEEN_CAP);
+ const recent = keepRecent({ entries: entriesOf({ items: unique, fallback: startedAt }), floor: startedAt - OVERLAP_MS });
+ await store.put<PollState>(STORE_KEY, { seen, recent, lastPoll: startedAt });
+}
+
+async function collect({ query, since, firstPage }: { query: PollQuery; since: number; firstPage: number }): Promise<{ items: Record<string, unknown>[]; truncated: boolean }> {
+ const publishedFrom = new Date(since).toISOString().slice(0, 19).replace('T', ' ');
+ const pages: Record<string, unknown>[][] = [];
+ for (let page = firstPage; page < firstPage + MAX_PAGES; page++) {
+ const result = await nuelinkClient.getPage({
+ apiKey: query.apiKey,
+ path: ['brands', query.brandId, 'published-posts'],
+ page,
+ perPage: PAGE_SIZE,
+ query: { ...query.filters, published_from: publishedFrom, sort_by: 'id', sort_order: 'asc' },
+ });
+ pages.push(result.items);
+ if (!result.hasMore) {
+ return { items: pages.flat(), truncated: false };
+ }
+ }
+ return { items: pages.flat(), truncated: true };
+}
+
+function uniqueById({ items }: { items: Record<string, unknown>[] }): Record<string, unknown>[] {
+ const byId = new Map<string, Record<string, unknown>>();
+ for (const item of items) {
+ const id = idOf({ item });
+ if (id.length > 0 && !byId.has(id)) {
+ byId.set(id, item);
+ }
+ }
+ return [...byId.values()];
+}
+
+function idOf({ item }: { item: Record<string, unknown> }): string {
+ const id = item['id'];
+ return typeof id === 'number' || typeof id === 'string' ? String(id) : '';
+}
+
+function entriesOf({ items, fallback }: { items: Record<string, unknown>[]; fallback: number }): RecentEntry[] {
+ return items.map((item) => {
+ const value = item['publishedAt'];
+ const time = typeof value === 'string' ? Date.parse(value) : Number.NaN;
+ return [idOf({ item }), Number.isFinite(time) ? time : fallback];
+ });
+}
+
+function keepRecent({ entries, floor }: { entries: RecentEntry[]; floor: number }): RecentGroup[] {
+ const kept = withinBudget({ entries: entries.filter(([, time]) => time >= floor).slice(-RECENT_CAP) });
+ const byTime = new Map<number, string[]>();
+ for (const [id, time] of kept) {
+ const ids = byTime.get(time);
+ if (ids === undefined) {
+ byTime.set(time, [id]);
+ } else {
+ ids.push(id);
+ }
+ }
+ return [...byTime.entries()];
+}
+
+function withinBudget({ entries }: { entries: RecentEntry[] }): RecentEntry[] {
+ const times = new Set<number>();
+ let bytes = 0;
+ for (let index = entries.length - 1; index >= 0; index--) {
+ const [id, time] = entries[index];
+ const cost = id.length + 3 + (times.has(time) ? 0 : String(time).length + 6);
+ if (bytes + cost > RECENT_BYTE_BUDGET) {
+ return entries.slice(index + 1);
+ }
+ bytes += cost;
+ times.add(time);
+ }
+ return entries;
+}
+
+function unpack({ groups }: { groups: RecentGroup[] }): RecentEntry[] {
+ return groups.flatMap(([time, ids]) => ids.map((id): RecentEntry => [id, time]));
+}
+
+function isPollState(value: unknown): value is PollState {
+ if (typeof value !== 'object' || value === null) {
+ return false;
+ }
+ const seen = Reflect.get(value, 'seen');
+ const lastPoll = Reflect.get(value, 'lastPoll');
+ const resume = Reflect.get(value, 'resume');
+ const recent = Reflect.get(value, 'recent');
+ return (
+ Array.isArray(seen) &&
+ seen.every((id: unknown) => typeof id === 'string') &&
+ typeof lastPoll === 'number' &&
+ Number.isFinite(lastPoll) &&
+ (resume === undefined || isResumePoint(resume)) &&
+ (recent === undefined || (Array.isArray(recent) && recent.every(isRecentGroup)))
+ );
+}
+
+function isRecentGroup(value: unknown): value is RecentGroup {
+ return Array.isArray(value) && value.length === 2 && typeof value[0] === 'number' && Number.isFinite(value[0]) && Array.isArray(value[1]) && value[1].every((id: unknown) => typeof id === 'string');
+}
+
+function isResumePoint(value: unknown): value is ResumePoint {
+ if (typeof value !== 'object' || value === null) {
+ return false;
+ }
+ const since = Reflect.get(value, 'since');
+ const page = Reflect.get(value, 'page');
+ return typeof since === 'number' && Number.isFinite(since) && typeof page === 'number' && Number.isInteger(page) && page > 1;
+}
+
+const STORE_KEY = 'nuelink_new_published_post';
+const OVERLAP_MS = 15 * 60 * 1000;
+const MAX_PAGES = 5;
+const PAGE_SIZE = 100;
+const SEEN_CAP = 1000;
+const RECENT_CAP = 20000;
+const RECENT_BYTE_BUDGET = 400 * 1024;
+const TEST_SAMPLE_SIZE = 5;
+const STATUSES = ['PUBLISHED', 'FAILED'] as const;
+
+type PollState = {
+ seen: string[];
+ recent?: RecentGroup[];
+ lastPoll: number;
+ resume?: ResumePoint;
+};
+
+type RecentEntry = [string, number];
+
+type RecentGroup = [number, string[]];
+
+type ResumePoint = {
+ since: number;
+ page: number;
+};
+
+type PollQuery = {
+ apiKey: string;
+ brandId: string;
+ filters: Record<string, string | undefined>;
+};
+
+type PollStore = {
+ put: <T>(key: string, value: T) => Promise<T>;
+};
diff --git a/packages/pieces/community/nuelink/test/actions.test.ts b/packages/pieces/community/nuelink/test/actions.test.ts
new file mode 100644
index 00000000000..7df86aa5396
--- /dev/null
+++ b/packages/pieces/community/nuelink/test/actions.test.ts
@@ -0,0 +1,381 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createPost } from '../src/lib/actions/create-post';
+import { createCollectionPost } from '../src/lib/actions/create-collection-post';
+import { updatePost } from '../src/lib/actions/update-post';
+import { deletePost } from '../src/lib/actions/delete-post';
+import { listPosts } from '../src/lib/actions/list-posts';
+import { listPublishedPosts } from '../src/lib/actions/list-published-posts';
+import { uploadMedia } from '../src/lib/actions/upload-media';
+import { aiListBrands } from '../src/lib/actions/ai/list-brands';
+import { aiListCollections } from '../src/lib/actions/ai/list-collections';
+import { BRAND, POST, apiKeyAuth, installFetch, jsonResponse, legacyAuth, listBody, publishedPost, requestOf, runAction } from './helpers';
+
+let fetchMock: ReturnType<typeof installFetch>;
+const BASE = 'https://app.nuelink.com/api/public/v1';
+
+beforeEach(() => {
+ fetchMock = installFetch();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+describe('Create Post (legacy, automation token)', () => {
+ it('sends the same five fields to the legacy endpoint and returns the body unchanged', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: { status: 'success', post: 1 } }));
+ const result = await runAction({
+ action: createPost,
+ auth: legacyAuth(),
+ propsValue: { body: 'Hello', media: ' https://cdn.example.com/a.jpg ', title: 'T', altText: 'A', shareToFeed: true, postAsShort: false },
+ });
+ expect(result).toEqual({ status: 'success', post: 1 });
+ const request = requestOf({ fetchMock, call: 0 });
+ expect(request.url).toBe('https://nuelink.com/api/v1/pabbly');
+ expect(request.method).toBe('POST');
+ expect(request.headers['authorization']).toBe('Bearer tok_legacy');
+ expect(request.body).toEqual({ body: 'Hello', media: 'https://cdn.example.com/a.jpg', title: 'T', altText: 'A', shareToFeed: true, postAsShort: false });
+ expect(request.dispatcher).toBeDefined();
+ });
+
+ it('omits a blank media URL', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: { status: 'success' } }));
+ await runAction({ action: createPost, auth: legacyAuth(), propsValue: { body: 'Hello', media: ' ', shareToFeed: false, postAsShort: false } });
+ expect(requestOf({ fetchMock, call: 0 }).body).toEqual({ body: 'Hello', shareToFeed: false, postAsShort: false });
+ });
+
+ it('maps a 401 to a token message', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ status: 401, body: { status: 'error', errors: { token: 'Invalid token' } } }));
+ await expect(runAction({ action: createPost, auth: legacyAuth(), propsValue: { body: 'Hello' } })).rejects.toThrow(
+ 'Nuelink did not accept the connection (401): token: Invalid token. Copy the automation token again'
+ );
+ });
+
+ it('refuses an API key connection before any request', async () => {
+ await expect(runAction({ action: createPost, auth: apiKeyAuth(), propsValue: { body: 'Hello' } })).rejects.toThrow('use Create Post in Collection');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('new actions refuse the legacy token', () => {
+ it.each([
+ ['create', createCollectionPost, { brand: 42, collection: 77, caption: 'x' }],
+ ['list', listPosts, { brand: 42 }],
+ ['brands', aiListBrands, {}],
+ ])('%s', async (_name, action, propsValue) => {
+ await expect(runAction({ action, auth: legacyAuth(), propsValue })).rejects.toThrow('needs a Nuelink API Key connection');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('Create Post in Collection', () => {
+ it('returns brand and collection IDs as exact strings', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ status: 201, body: { status: 'success', data: { id: 1, message: 'Post created successfully' } } }));
+ const result = await runAction({ action: createCollectionPost, propsValue: { brand: '9007199254740993', collection: '9007199254740995', caption: 'Hi' } });
+ expect(result).toMatchObject({ brandId: '9007199254740993', collectionId: '9007199254740995' });
+ expect(requestOf({ fetchMock, call: 0 }).url).toBe(`${BASE}/brands/9007199254740993/collections/9007199254740995/posts`);
+ });
+
+ it('defaults to DRAFT and sends only what was set', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ status: 201, body: { status: 'success', data: { id: 8801, message: 'Post created successfully' } } }));
+ const result = await runAction({ action: createCollectionPost, propsValue: { brand: 42, collection: '77', caption: 'Hello world', postAsStory: false } });
+ expect(result).toEqual({
+ id: 8801,
+ message: 'Post created successfully',
+ brandId: '42',
+ collectionId: '77',
+ publishMode: 'DRAFT',
+ scheduledAt: null,
+ scheduledAtUtc: null,
+ brandTimezone: null,
+ });
+ const request = requestOf({ fetchMock, call: 0 });
+ expect(request.url).toBe(`${BASE}/brands/42/collections/77/posts`);
+ expect(request.method).toBe('POST');
+ expect(request.headers['content-type']).toBe('application/json');
+ expect(request.body).toEqual({ caption: 'Hello world', publishMode: 'DRAFT' });
+ });
+
+ it('splits media into URLs and IDs and maps every option', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ status: 201, body: { status: 'success', data: { id: 1, message: 'Post created successfully' } } }));
+ await runAction({
+ action: createCollectionPost,
+ propsValue: {
+ brand: 42,
+ collection: 77,
+ publishMode: 'QUEUE',
+ caption: 'Hi',
+ title: 'Launch',
+ media: ['https://cdn.example.com/a.jpg', ' 9b8c7d6e5f4a.jpg ', ''],
+ alt: 'Alt',
+ link: 'https://example.com/p',
+ postAsStory: true,
+ autoThreadText: true,
+ firstComment: 'More on our site',
+ firstCommentDelaySeconds: '10',
+ instagramShareToFeed: true,
+ instagramCollab: 'partner',
+ tiktokAutoAddMusic: true,
+ youtubeTags: ['product', 'launch'],
+ },
+ });
+ expect(requestOf({ fetchMock, call: 0 }).body).toEqual({
+ caption: 'Hi',
+ publishMode: 'QUEUE',
+ title: 'Launch',
+ alt: 'Alt',
+ link: 'https://example.com/p',
+ media: [{ url: 'https://cdn.example.com/a.jpg' }, { id: '9b8c7d6e5f4a.jpg' }],
+ postAsStory: true,
+ autoThreadText: true,
+ comment: { comment: 'More on our site', delay: 10 },
+ platforms: { instagram: { shareToFeed: true, collab: 'partner' }, tiktok: { autoAddMusic: true }, youtube: { tags: ['product', 'launch'] } },
+ });
+ });
+
+ it('converts Scheduled Time to the brand timezone', async () => {
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(new Date('2026-07-01T00:00:00Z'));
+ fetchMock
+ .mockResolvedValueOnce(jsonResponse({ body: listBody({ data: [{ ...BRAND, id: 7, timezone: 'UTC' }], currentPage: 1, lastPage: 2 }) }))
+ .mockResolvedValueOnce(jsonResponse({ body: listBody({ data: [BRAND], currentPage: 2, lastPage: 2 }) }))
+ .mockResolvedValueOnce(jsonResponse({ status: 201, body: { status: 'success', data: { id: 5, message: 'Post created successfully' } } }));
+ const result = await runAction({
+ action: createCollectionPost,
+ propsValue: { brand: 42, collection: 77, publishMode: 'SCHEDULE', scheduledAt: '2026-07-02T08:00:00.000Z', caption: 'Hi' },
+ });
+ expect(requestOf({ fetchMock, call: 0 }).url).toBe(`${BASE}/brands?page=1&per_page=100`);
+ expect(requestOf({ fetchMock, call: 1 }).url).toBe(`${BASE}/brands?page=2&per_page=100`);
+ expect(requestOf({ fetchMock, call: 2 }).body).toEqual({ caption: 'Hi', publishMode: 'SCHEDULE', scheduledAt: '2026-07-02 09:00:00' });
+ expect(result).toMatchObject({ publishMode: 'SCHEDULE', scheduledAt: '2026-07-02 09:00:00', scheduledAtUtc: '2026-07-02T08:00:00.000Z', brandTimezone: 'Europe/London' });
+ });
+
+ it('fails clearly when the brand has no timezone', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: listBody({ data: [{ ...BRAND, timezone: null }] }) }));
+ await expect(
+ runAction({ action: createCollectionPost, propsValue: { brand: 42, collection: 77, publishMode: 'SCHEDULE', scheduledAt: '2099-01-01T09:00:00Z', caption: 'Hi' } })
+ ).rejects.toThrow('has no timezone set');
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([
+ [{ publishMode: 'SCHEDULE' }, 'set Scheduled Time'],
+ [{ publishMode: 'DRAFT', scheduledAt: '2099-01-01T09:00:00Z' }, 'only used when Publish Mode is Schedule'],
+ [{ publishMode: 'SCHEDULE', scheduledAt: '2000-01-01T09:00:00Z' }, 'at least 10 minutes in the future'],
+ [{ publishMode: 'LATER' }, 'Publish Mode must be one of'],
+ [{ caption: ' ' }, 'Caption is required'],
+ [{ caption: 'x'.repeat(3001) }, 'at most 3000'],
+ [{ media: Array.from({ length: 11 }, (_, i) => `https://cdn.example.com/${i}.jpg`) }, 'at most 10'],
+ [{ media: ['ftp://cdn.example.com/a.jpg'] }, 'neither an http(s) URL nor a Nuelink media ID'],
+ [{ link: 'javascript:alert(1)' }, 'Link must be a full http(s) URL'],
+ [{ firstComment: 'hi' }, 'Set First Comment and First Comment Delay together'],
+ [{ firstCommentDelaySeconds: 5 }, 'Set First Comment and First Comment Delay together'],
+ [{ firstComment: 'hi', firstCommentDelaySeconds: -1 }, 'whole number from 0'],
+ [{ brand: '42/../1' }, 'Brand must be a numeric Nuelink ID'],
+ ])('rejects %j before any request', async (overrides, message) => {
+ await expect(runAction({ action: createCollectionPost, propsValue: { brand: 42, collection: 77, caption: 'Hi', ...overrides } })).rejects.toThrow(message);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('does not retry a create that timed out and says to check first', async () => {
+ fetchMock.mockImplementation(async () => {
+ throw new DOMException('aborted', 'AbortError');
+ });
+ await expect(runAction({ action: createCollectionPost, propsValue: { brand: 42, collection: 77, caption: 'Hi' } })).rejects.toThrow(
+ 'did not answer within 120 seconds. The post may still have been created'
+ );
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('surfaces the vendor message when Nuelink cannot download media', async () => {
+ fetchMock.mockResolvedValueOnce(
+ jsonResponse({ status: 400, body: { status: 'error', message: 'Failed to download media from url: https://cdn.example.com/missing.jpg', errors: { media: 'Failed to download media from url: https://cdn.example.com/missing.jpg' } } })
+ );
+ await expect(runAction({ action: createCollectionPost, propsValue: { brand: 42, collection: 77, caption: 'Hi', media: ['https://cdn.example.com/missing.jpg'] } })).rejects.toThrow(
+ 'Nuelink rejected the request (400): media: Failed to download media'
+ );
+ });
+});
+
+describe('Update Post', () => {
+ it('reschedules in brand time and returns the updated post', async () => {
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(new Date('2026-10-01T00:00:00Z'));
+ fetchMock
+ .mockResolvedValueOnce(jsonResponse({ body: listBody({ data: [BRAND] }) }))
+ .mockResolvedValueOnce(jsonResponse({ body: { status: 'success', data: POST } }));
+ const result = await runAction({ action: updatePost, propsValue: { brand: 42, postId: '8801', publishMode: 'SCHEDULE', scheduledAt: '2026-10-12T08:00:00Z' } });
+ expect(result).toEqual(POST);
+ const request = requestOf({ fetchMock, call: 1 });
+ expect(request.url).toBe(`${BASE}/brands/42/posts/8801`);
+ expect(request.method).toBe('PATCH');
+ expect(request.body).toEqual({ publishMode: 'SCHEDULE', scheduledAt: '2026-10-12 09:00:00' });
+ });
+
+ it('sends only the fields that were set', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: { status: 'success', data: POST } }));
+ await runAction({ action: updatePost, propsValue: { brand: 42, postId: 8801, caption: 'New text', queuePosition: 'FRONT' } });
+ expect(requestOf({ fetchMock, call: 0 }).body).toEqual({ caption: 'New text', queuePosition: 'FRONT' });
+ });
+
+ it.each([
+ [{}, 'Nothing to update'],
+ [{ caption: '' }, 'Nothing to update'],
+ [{ publishMode: 'SCHEDULE' }, 'set Scheduled Time'],
+ [{ publishMode: 'QUEUE', scheduledAt: '2099-01-01T00:00:00Z' }, 'only used when New Publish Mode is Schedule'],
+ [{ publishMode: 'DRAFT', queuePosition: 'FRONT' }, 'Queue Position only works'],
+ [{ postId: '8801?x=1', caption: 'x' }, 'Post ID must be a numeric'],
+ ])('rejects %j before any request', async (overrides, message) => {
+ await expect(runAction({ action: updatePost, propsValue: { brand: 42, postId: '8801', ...overrides } })).rejects.toThrow(message);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('explains a 409 on a published post', async () => {
+ fetchMock.mockResolvedValueOnce(
+ jsonResponse({ status: 409, body: { status: 'error', message: 'Only draft, queued or scheduled posts can be edited', errors: { post_id: 'Only draft, queued or scheduled posts can be edited' } } })
+ );
+ await expect(runAction({ action: updatePost, propsValue: { brand: 42, postId: 8801, caption: 'x' } })).rejects.toThrow('(409): post_id: Only draft');
+ });
+});
+
+describe('Delete Post', () => {
+ it('sends DELETE and returns id and message', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: { status: 'success', data: { id: 8801, message: 'Post deleted successfully' } } }));
+ const result = await runAction({ action: deletePost, propsValue: { brand: 42, postId: '8801' } });
+ expect(result).toEqual({ id: 8801, message: 'Post deleted successfully' });
+ expect(requestOf({ fetchMock, call: 0 })).toMatchObject({ url: `${BASE}/brands/42/posts/8801`, method: 'DELETE' });
+ });
+
+ it('names the sensitive-actions setting on 403', async () => {
+ fetchMock.mockResolvedValueOnce(
+ jsonResponse({
+ status: 403,
+ body: { status: 'error', message: 'Deleting posts through the API is disabled.', errors: { permissions: 'Deleting posts through the API is disabled.' } },
+ })
+ );
+ await expect(runAction({ action: deletePost, propsValue: { brand: 42, postId: 1 } })).rejects.toThrow('Allow AI to perform sensitive actions');
+ });
+});
+
+describe('List Posts', () => {
+ it('maps filters to the query, formats dates in UTC and returns one page with hasMore', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: listBody({ data: [POST], currentPage: 2, lastPage: 3, perPage: 10, total: 25 }) }));
+ const result = await runAction({
+ action: listPosts,
+ propsValue: {
+ brand: 42,
+ collection: 77,
+ view: 'DRAFT',
+ postType: 'IMAGE',
+ createdFrom: '2026-10-01T02:00:00+02:00',
+ createdTo: '2026-10-31T23:59:59Z',
+ sortBy: 'post_date',
+ sortOrder: 'asc',
+ page: 2,
+ perPage: '10',
+ },
+ });
+ expect(result).toEqual({ items: [POST], page: 2, perPage: 10, total: 25, lastPage: 3, hasMore: true });
+ const request = requestOf({ fetchMock, call: 0 });
+ expect(request.path).toBe('/api/public/v1/brands/42/posts');
+ expect(request.query).toEqual({
+ collection_id: '77',
+ view: 'DRAFT',
+ post_type: 'IMAGE',
+ created_from: '2026-10-01 00:00:00',
+ created_to: '2026-10-31 23:59:59',
+ sort_by: 'post_date',
+ sort_order: 'asc',
+ page: '2',
+ per_page: '10',
+ });
+ });
+
+ it.each([
+ [{ perPage: 101 }, 'Results per Page must be a whole number from 1 to 100'],
+ [{ page: 0 }, 'Page must be a whole number'],
+ [{ createdFrom: '2026-10-02T00:00:00Z', createdTo: '2026-10-01T00:00:00Z' }, 'Created To must not be earlier'],
+ ])('rejects %j', async (overrides, message) => {
+ await expect(runAction({ action: listPosts, propsValue: { brand: 42, ...overrides } })).rejects.toThrow(message);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('List Published Posts', () => {
+ it('maps every filter', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: listBody({ data: [publishedPost({ id: 1 })] }) }));
+ const result = await runAction({
+ action: listPublishedPosts,
+ propsValue: { brand: 42, status: 'FAILED', collection: 77, channel: 501, postId: '8801', search: ' launch ', publishedFrom: '2026-10-01', sortBy: 'likes', sortOrder: 'desc' },
+ });
+ expect(result).toMatchObject({ items: [publishedPost({ id: 1 })], hasMore: false });
+ expect(requestOf({ fetchMock, call: 0 }).query).toEqual({
+ status: 'FAILED',
+ collection_id: '77',
+ channel_id: '501',
+ post_id: '8801',
+ search: 'launch',
+ published_from: '2026-10-01 00:00:00',
+ sort_by: 'likes',
+ sort_order: 'desc',
+ page: '1',
+ per_page: '25',
+ });
+ });
+});
+
+describe('Upload Media', () => {
+ it('posts multipart field media with a 300 s budget', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ status: 201, body: { status: 'success', data: { id: '9b8c.jpg', type: 'image/jpeg', size: 3 } } }));
+ const result = await runAction({ action: uploadMedia, propsValue: { brand: 42, file: { filename: 'photo.JPG', extension: 'jpg', data: Buffer.from('abc') } } });
+ expect(result).toEqual({ id: '9b8c.jpg', type: 'image/jpeg', size: 3 });
+ const request = requestOf({ fetchMock, call: 0 });
+ expect(request.url).toBe(`${BASE}/brands/42/media`);
+ expect(request.headers['content-type']).toBeUndefined();
+ expect(request.body).toBeInstanceOf(FormData);
+ const body = request.body;
+ if (!(body instanceof FormData)) {
+ throw new Error('expected a FormData body');
+ }
+ const part = body.get('media');
+ expect(part).toBeInstanceOf(File);
+ expect(part).toMatchObject({ name: 'photo.JPG', type: 'image/jpeg' });
+ const wire = new Request(request.url, { method: 'POST', body, headers: request.headers });
+ expect(wire.headers.get('content-type')).toMatch(/^multipart\/form-data; boundary=/);
+ expect(await wire.text()).toContain('name="media"; filename="photo.JPG"');
+ });
+
+ it.each([
+ [{ filename: 'anim.gif', data: Buffer.from('x') }, 'Nuelink accepts JPG'],
+ [{ filename: 'empty.png', data: Buffer.alloc(0) }, 'is empty'],
+ [{ filename: 'big.mp4', data: Buffer.alloc(104_857_601) }, 'up to 100 MB'],
+ [{ name: 'x' }, 'did not contain a readable file'],
+ ])('rejects %#', async (file, message) => {
+ await expect(runAction({ action: uploadMedia, propsValue: { brand: 42, file } })).rejects.toThrow(message);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('AI list atomics', () => {
+ it('List Brands returns one page', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: listBody({ data: [BRAND] }) }));
+ await expect(runAction({ action: aiListBrands, propsValue: { page: 1, perPage: 50 } })).resolves.toEqual({
+ items: [BRAND],
+ page: 1,
+ perPage: 25,
+ total: 1,
+ lastPage: 1,
+ hasMore: false,
+ });
+ expect(requestOf({ fetchMock, call: 0 }).url).toBe(`${BASE}/brands?page=1&per_page=50`);
+ });
+
+ it('List Collections takes a ShortText brand ID and guards it', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: listBody({ data: [] }) }));
+ await runAction({ action: aiListCollections, propsValue: { brandId: ' 42 ' } });
+ expect(requestOf({ fetchMock, call: 0 }).url).toBe(`${BASE}/brands/42/collections?page=1&per_page=25`);
+ await expect(runAction({ action: aiListCollections, propsValue: { brandId: '42/../../auth' } })).rejects.toThrow('Brand ID must be a numeric');
+ });
+});
diff --git a/packages/pieces/community/nuelink/test/ai-atomics.test.ts b/packages/pieces/community/nuelink/test/ai-atomics.test.ts
new file mode 100644
index 00000000000..7d00fea297d
--- /dev/null
+++ b/packages/pieces/community/nuelink/test/ai-atomics.test.ts
@@ -0,0 +1,331 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { nuelink } from '../src/index';
+import { createCollectionPost } from '../src/lib/actions/create-collection-post';
+import { updatePost } from '../src/lib/actions/update-post';
+import { deletePost } from '../src/lib/actions/delete-post';
+import { listPosts } from '../src/lib/actions/list-posts';
+import { listPublishedPosts } from '../src/lib/actions/list-published-posts';
+import { uploadMedia } from '../src/lib/actions/upload-media';
+import { aiGetMe } from '../src/lib/actions/ai/get-me';
+import { aiGetSchedule } from '../src/lib/actions/ai/get-schedule';
+import { aiListChannels } from '../src/lib/actions/ai/list-channels';
+import { aiCreateCollection } from '../src/lib/actions/ai/create-collection';
+import { aiUpdateCollection } from '../src/lib/actions/ai/update-collection';
+import { aiAddCollectionChannel } from '../src/lib/actions/ai/add-collection-channel';
+import { aiRemoveCollectionChannel } from '../src/lib/actions/ai/remove-collection-channel';
+import { aiAddCollectionQueueSlot } from '../src/lib/actions/ai/add-collection-queue-slot';
+import { aiDeleteCollectionQueueSlot } from '../src/lib/actions/ai/delete-collection-queue-slot';
+import { aiListAutomations } from '../src/lib/actions/ai/list-automations';
+import { aiCreateAutomation } from '../src/lib/actions/ai/create-automation';
+import { aiUpdateAutomationStatus } from '../src/lib/actions/ai/update-automation-status';
+import { aiListMedia } from '../src/lib/actions/ai/list-media';
+import { aiUploadFile } from '../src/lib/actions/ai/upload-file';
+import { aiCreatePost } from '../src/lib/actions/ai/create-post';
+import { aiUpdatePost } from '../src/lib/actions/ai/update-post';
+import { aiMovePosts } from '../src/lib/actions/ai/move-posts';
+import { aiDeletePost } from '../src/lib/actions/ai/delete-post';
+import { aiListBrandPosts } from '../src/lib/actions/ai/list-brand-posts';
+import { aiListPublishedPosts } from '../src/lib/actions/ai/list-published-posts';
+import { BRAND, POST, installFetch, jsonResponse, legacyAuth, listBody, requestOf, runAction } from './helpers';
+
+let fetchMock: ReturnType<typeof installFetch>;
+const BASE = 'https://app.nuelink.com/api/public/v1';
+const ok = ({ data, status = 200 }: { data: unknown; status?: number }) => jsonResponse({ status, body: { status: 'success', data } });
+
+beforeEach(() => {
+ fetchMock = installFetch();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+describe('piece surface', () => {
+ it('registers 22 ai actions, 7 human actions and no both', () => {
+ const actions = Object.values(nuelink.actions());
+ const count = (audience: string) => actions.filter((action) => action.audience === audience).length;
+ expect(count('ai')).toBe(22);
+ expect(count('human')).toBe(7);
+ expect(count('both')).toBe(0);
+ });
+
+ it('ai aiMetadata never names a demoted action', () => {
+ const ai = Object.values(nuelink.actions()).filter((action) => action.audience === 'ai');
+ for (const action of ai) {
+ const text = action.aiMetadata?.description ?? '';
+ expect(text).not.toMatch(/Create Post in Collection|List Posts\b|Upload Media\b/);
+ }
+ });
+});
+
+describe('read atomics', () => {
+ it('get_me calls /me', async () => {
+ fetchMock.mockResolvedValueOnce(ok({ data: { id: 'abc', name: 'Odai', joinedAt: '2026-01-01T00:00:00Z', timezone: null } }));
+ const result = await runAction({ action: aiGetMe, propsValue: {} });
+ expect(result).toEqual({ id: 'abc', name: 'Odai', joinedAt: '2026-01-01T00:00:00Z', timezone: null });
+ expect(requestOf({ fetchMock, call: 0 }).url).toBe(`${BASE}/me`);
+ });
+
+ it('get_schedule calls the brand schedule', async () => {
+ fetchMock.mockResolvedValueOnce(ok({ data: { timezone: 'Asia/Amman', queueStatus: 'ACTIVE', schedule: { MON: [] } } }));
+ await runAction({ action: aiGetSchedule, propsValue: { brandId: ' 42 ' } });
+ expect(requestOf({ fetchMock, call: 0 }).path).toBe('/api/public/v1/brands/42/schedule');
+ });
+
+ it('list_channels takes hasMore from lastPage even on a short page', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: listBody({ data: [], currentPage: 1, lastPage: 2, total: 30 }) }));
+ const result = await runAction({ action: aiListChannels, propsValue: { brandId: '42', perPage: 10 } });
+ expect(result).toMatchObject({ items: [], hasMore: true, total: 30 });
+ expect(requestOf({ fetchMock, call: 0 }).query).toEqual({ page: '1', per_page: '10' });
+ });
+
+ it('list_automations pages', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: listBody({ data: [{ id: 315, name: 'Blog' }] }) }));
+ const result = await runAction({ action: aiListAutomations, propsValue: { brandId: '42' } });
+ expect(result).toMatchObject({ items: [{ id: 315 }], hasMore: false });
+ expect(requestOf({ fetchMock, call: 0 }).path).toBe('/api/public/v1/brands/42/automations');
+ });
+
+ it('list_media sends the type filter and rejects an unknown one', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: listBody({ data: [{ id: 'a.jpg' }] }) }));
+ await runAction({ action: aiListMedia, propsValue: { brandId: '42', type: 'image' } });
+ expect(requestOf({ fetchMock, call: 0 }).query).toMatchObject({ type: 'IMAGE' });
+ await expect(runAction({ action: aiListMedia, propsValue: { brandId: '42', type: 'AUDIO' } })).rejects.toThrow('Type must be one of');
+ });
+
+ it('refuses a non-numeric brand ID and the legacy token before any request', async () => {
+ await expect(runAction({ action: aiGetSchedule, propsValue: { brandId: '../1' } })).rejects.toThrow('numeric Nuelink ID');
+ await expect(runAction({ action: aiGetMe, auth: legacyAuth(), propsValue: {} })).rejects.toThrow('needs a Nuelink API Key connection');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('collections', () => {
+ it('create_collection normalizes and deduplicates slots and channels', async () => {
+ fetchMock.mockResolvedValueOnce(ok({ data: { id: 9, title: 'AP Test' }, status: 201 }));
+ await runAction({
+ action: aiCreateCollection,
+ propsValue: { brandId: '42', title: ' AP Test ', maxRepublish: 0, channels: ['5', 5, '6'], queues: ['tue 09:00', 'Tue 09:00', 'MON 18:30'] },
+ });
+ const request = requestOf({ fetchMock, call: 0 });
+ expect(request.method).toBe('POST');
+ expect(request.path).toBe('/api/public/v1/brands/42/collections');
+ expect(request.body).toEqual({ title: 'AP Test', maxRepublish: 0, channels: [5, 6], queues: ['Tue 09:00', 'Mon 18:30'] });
+ });
+
+ it('create_collection rejects a bad slot and an unsafe channel ID', async () => {
+ await expect(runAction({ action: aiCreateCollection, propsValue: { brandId: '42', title: 'X', queues: ['Tue 9am'] } })).rejects.toThrow('like "Tue 09:00"');
+ await expect(runAction({ action: aiCreateCollection, propsValue: { brandId: '42', title: 'X', channels: ['123456789012345678'] } })).rejects.toThrow('too large');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('update_collection sends only set fields', async () => {
+ fetchMock.mockResolvedValueOnce(ok({ data: { id: 9 } }));
+ await runAction({ action: aiUpdateCollection, propsValue: { brandId: '42', collectionId: '9', status: 'paused' } });
+ const request = requestOf({ fetchMock, call: 0 });
+ expect(request.method).toBe('PATCH');
+ expect(request.path).toBe('/api/public/v1/brands/42/collections/9');
+ expect(request.body).toEqual({ status: 'PAUSED' });
+ });
+
+ it('update_collection clears the description with null', async () => {
+ fetchMock.mockResolvedValueOnce(ok({ data: { id: 9 } }));
+ await runAction({ action: aiUpdateCollection, propsValue: { brandId: '42', collectionId: '9', clearDescription: true } });
+ expect(requestOf({ fetchMock, call: 0 }).body).toEqual({ description: null });
+ });
+
+ it('update_collection refuses empty and conflicting updates', async () => {
+ await expect(runAction({ action: aiUpdateCollection, propsValue: { brandId: '42', collectionId: '9', clearDescription: false } })).rejects.toThrow('Nothing to update');
+ await expect(runAction({ action: aiUpdateCollection, propsValue: { brandId: '42', collectionId: '9', description: 'x', clearDescription: true } })).rejects.toThrow('not both');
+ await expect(runAction({ action: aiUpdateCollection, propsValue: { brandId: '42', collectionId: '9', maxRepublish: -1 } })).rejects.toThrow('whole number');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('add_collection_channel sends a numeric channelId', async () => {
+ fetchMock.mockResolvedValueOnce(ok({ data: { collectionId: 9, channelId: 5 } }));
+ await runAction({ action: aiAddCollectionChannel, propsValue: { brandId: '42', collectionId: '9', channelId: '5' } });
+ const request = requestOf({ fetchMock, call: 0 });
+ expect(request.path).toBe('/api/public/v1/brands/42/collections/9/channels');
+ expect(request.body).toEqual({ channelId: 5 });
+ });
+
+ it('remove_collection_channel deletes by path', async () => {
+ fetchMock.mockResolvedValueOnce(ok({ data: { collectionId: 9, channelId: 5 } }));
+ await runAction({ action: aiRemoveCollectionChannel, propsValue: { brandId: '42', collectionId: '9', channelId: '5' } });
+ const request = requestOf({ fetchMock, call: 0 });
+ expect(request.method).toBe('DELETE');
+ expect(request.path).toBe('/api/public/v1/brands/42/collections/9/channels/5');
+ });
+
+ it('add_collection_queue_slot sends a brand-local slot without conversion', async () => {
+ fetchMock.mockResolvedValueOnce(ok({ data: { id: 910, day: 'TUE', time: '09:00', date: 'TUE 09:00', status: 'PENDING' }, status: 201 }));
+ await runAction({ action: aiAddCollectionQueueSlot, propsValue: { brandId: '42', collectionId: '9', slot: 'TUE 09:00' } });
+ expect(requestOf({ fetchMock, call: 0 }).body).toEqual({ date: 'Tue 09:00' });
+ await expect(runAction({ action: aiAddCollectionQueueSlot, propsValue: { brandId: '42', collectionId: '9', slot: 'Tue 24:00' } })).rejects.toThrow('like "Tue 09:00"');
+ });
+
+ it('delete_collection_queue_slot deletes by path', async () => {
+ fetchMock.mockResolvedValueOnce(ok({ data: { collectionId: 9, queueId: 910 } }));
+ await runAction({ action: aiDeleteCollectionQueueSlot, propsValue: { brandId: '42', collectionId: '9', queueId: '910' } });
+ const request = requestOf({ fetchMock, call: 0 });
+ expect(request.method).toBe('DELETE');
+ expect(request.path).toBe('/api/public/v1/brands/42/collections/9/queues/910');
+ });
+});
+
+describe('automations', () => {
+ const base = { brandId: '42', collectionId: '9', name: 'Blog', type: 'rss', feedUrl: 'https://example.com/feed.xml', importAsType: 'LINK' };
+
+ it('create_automation defaults to drafts and no back-fill, always sending both', async () => {
+ fetchMock.mockResolvedValueOnce(ok({ data: { id: 315 }, status: 201 }));
+ await runAction({ action: aiCreateAutomation, propsValue: base });
+ expect(requestOf({ fetchMock, call: 0 }).body).toEqual({
+ name: 'Blog',
+ collectionId: 9,
+ type: 'RSS',
+ feedUrl: 'https://example.com/feed.xml',
+ importAsType: 'LINK',
+ addPostsAsDraft: true,
+ loadOldPosts: false,
+ });
+ });
+
+ it('create_automation refuses a back-fill straight into the queue and bad refresh rates', async () => {
+ await expect(runAction({ action: aiCreateAutomation, propsValue: { ...base, loadOldPosts: true, addPostsAsDraft: false } })).rejects.toThrow('only allowed with Add Posts as Drafts');
+ await expect(runAction({ action: aiCreateAutomation, propsValue: { ...base, refreshRate: 3 } })).rejects.toThrow('1, 6, 12 or 24');
+ await expect(runAction({ action: aiCreateAutomation, propsValue: { ...base, feedUrl: 'ftp://x' } })).rejects.toThrow('http(s) URL');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('update_automation_status patches the status', async () => {
+ fetchMock.mockResolvedValueOnce(ok({ data: { id: 315, name: 'Blog', status: 'INACTIVE' } }));
+ const result = await runAction({ action: aiUpdateAutomationStatus, propsValue: { brandId: '42', automationId: '315', status: 'PAUSED' } });
+ expect(result).toEqual({ id: 315, name: 'Blog', status: 'INACTIVE' });
+ const request = requestOf({ fetchMock, call: 0 });
+ expect(request.method).toBe('PATCH');
+ expect(request.path).toBe('/api/public/v1/brands/42/automations/315');
+ expect(request.body).toEqual({ status: 'PAUSED' });
+ await expect(runAction({ action: aiUpdateAutomationStatus, propsValue: { brandId: '42', automationId: '315', status: 'INACTIVE' } })).rejects.toThrow('Status must be one of');
+ });
+});
+
+describe('move_posts', () => {
+ it('normalizes and deduplicates post IDs', async () => {
+ fetchMock.mockResolvedValueOnce(ok({ data: { moved: 2, sourceCollectionId: 1, destinationCollectionId: 2, message: 'Post(s) moved successfully' } }));
+ await runAction({ action: aiMovePosts, propsValue: { brandId: '42', sourceCollectionId: '1', destinationCollectionId: 2, postIds: ['10', 10, ' 11 '] } });
+ const request = requestOf({ fetchMock, call: 0 });
+ expect(request.method).toBe('PATCH');
+ expect(request.path).toBe('/api/public/v1/brands/42/posts/move');
+ expect(request.body).toEqual({ sourceCollectionId: 1, destinationCollectionId: 2, postIds: [10, 11] });
+ });
+
+ it('refuses same source and destination, empty and oversize lists', async () => {
+ await expect(runAction({ action: aiMovePosts, propsValue: { brandId: '42', sourceCollectionId: '1', destinationCollectionId: ' 1', postIds: [1] } })).rejects.toThrow('must be different');
+ await expect(runAction({ action: aiMovePosts, propsValue: { brandId: '42', sourceCollectionId: '1', destinationCollectionId: '2', postIds: [] } })).rejects.toThrow('at least one');
+ const many = Array.from({ length: 101 }, (_, index) => index + 1);
+ await expect(runAction({ action: aiMovePosts, propsValue: { brandId: '42', sourceCollectionId: '1', destinationCollectionId: '2', postIds: many } })).rejects.toThrow('at most 100');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('twins send the identical request as the human actions', () => {
+ it('create post', async () => {
+ fetchMock.mockImplementation(async () => ok({ data: { id: 8801, message: 'Post created successfully' }, status: 201 }));
+ const shared = { caption: 'Hello', media: ['https://cdn.example.com/a.jpg', 'abc.jpg'], firstComment: 'c', firstCommentDelaySeconds: 30, youtubeTags: ['t'] };
+ const human = await runAction({ action: createCollectionPost, propsValue: { brand: 42, collection: 77, ...shared } });
+ const ai = await runAction({ action: aiCreatePost, propsValue: { brandId: '42', collectionId: '77', ...shared } });
+ expect(ai).toEqual(human);
+ expect(requestOf({ fetchMock, call: 1 }).url).toBe(requestOf({ fetchMock, call: 0 }).url);
+ expect(requestOf({ fetchMock, call: 1 }).body).toEqual(requestOf({ fetchMock, call: 0 }).body);
+ expect(requestOf({ fetchMock, call: 0 }).body).toMatchObject({ publishMode: 'DRAFT' });
+ });
+
+ it('update, delete, list, published, upload', async () => {
+ const pairs: Array<[{ run: (context: never) => Promise<unknown> }, Record<string, unknown>, { run: (context: never) => Promise<unknown> }, Record<string, unknown>, unknown]> = [
+ [updatePost, { brand: 42, postId: '8801', publishMode: 'DRAFT' }, aiUpdatePost, { brandId: '42', postId: '8801', publishMode: 'DRAFT' }, ok({ data: POST })],
+ [deletePost, { brand: 42, postId: '8801' }, aiDeletePost, { brandId: '42', postId: '8801' }, ok({ data: { id: 8801, message: 'deleted' } })],
+ [listPosts, { brand: 42, collection: 77, view: 'DRAFT' }, aiListBrandPosts, { brandId: '42', collectionId: '77', view: 'DRAFT' }, jsonResponse({ body: listBody({ data: [POST] }) })],
+ [listPublishedPosts, { brand: 42, status: 'FAILED', postId: '8801' }, aiListPublishedPosts, { brandId: '42', status: 'FAILED', postId: '8801' }, jsonResponse({ body: listBody({ data: [] }) })],
+ ];
+ for (const [human, humanProps, ai, aiProps, response] of pairs) {
+ fetchMock.mockReset();
+ fetchMock.mockResolvedValueOnce(response).mockResolvedValueOnce(response instanceof Response ? response.clone() : response);
+ const first = await runAction({ action: human, propsValue: humanProps });
+ const second = await runAction({ action: ai, propsValue: aiProps });
+ expect(second).toEqual(first);
+ const [a, b] = [requestOf({ fetchMock, call: 0 }), requestOf({ fetchMock, call: 1 })];
+ expect(b.url).toBe(a.url);
+ expect(b.method).toBe(a.method);
+ expect(b.body).toEqual(a.body);
+ }
+ });
+
+ it('upload', async () => {
+ const file = { filename: 'a.jpg', extension: 'jpg', data: Buffer.from('img') };
+ fetchMock.mockResolvedValueOnce(ok({ data: { id: 'x.jpg', type: 'image/jpeg', size: 3 }, status: 201 })).mockResolvedValueOnce(ok({ data: { id: 'x.jpg', type: 'image/jpeg', size: 3 }, status: 201 }));
+ const human = await runAction({ action: uploadMedia, propsValue: { brand: 42, file } });
+ const ai = await runAction({ action: aiUploadFile, propsValue: { brandId: '42', file } });
+ expect(ai).toEqual(human);
+ expect(requestOf({ fetchMock, call: 1 }).url).toBe(`${BASE}/brands/42/media`);
+ await expect(runAction({ action: aiUploadFile, propsValue: { brandId: '42', file: { filename: 'a.gif', data: Buffer.from('x') } } })).rejects.toThrow('not one of them');
+ });
+});
+
+describe('twin supersets', () => {
+ it('create post with a poll and no caption', async () => {
+ fetchMock.mockResolvedValueOnce(ok({ data: { id: 1 }, status: 201 }));
+ await runAction({ action: aiCreatePost, propsValue: { brandId: '42', collectionId: '77', pollQuestion: 'Q?', pollOptions: ['A', 'B'], pollPeriod: '3d', pollCorrectOptionIndex: 1 } });
+ expect(requestOf({ fetchMock, call: 0 }).body).toEqual({ poll: { question: 'Q?', options: ['A', 'B'], period: '3d', correctOptionIndex: 1 }, publishMode: 'DRAFT' });
+ });
+
+ it('create post with caption and poll together', async () => {
+ fetchMock.mockResolvedValueOnce(ok({ data: { id: 1 }, status: 201 }));
+ await runAction({ action: aiCreatePost, propsValue: { brandId: '42', collectionId: '77', caption: 'Vote', pollQuestion: 'Q?', pollOptions: ['A', 'B'], pollPeriod: '1d' } });
+ expect(requestOf({ fetchMock, call: 0 }).body).toMatchObject({ caption: 'Vote', poll: { question: 'Q?' } });
+ });
+
+ it('create post rejects neither, an incomplete poll and an out-of-range answer', async () => {
+ await expect(runAction({ action: aiCreatePost, propsValue: { brandId: '42', collectionId: '77' } })).rejects.toThrow('Caption is required');
+ await expect(runAction({ action: aiCreatePost, propsValue: { brandId: '42', collectionId: '77', caption: 'x', pollQuestion: 'Q?' } })).rejects.toThrow('A poll needs');
+ await expect(
+ runAction({ action: aiCreatePost, propsValue: { brandId: '42', collectionId: '77', pollQuestion: 'Q?', pollOptions: ['A', 'B'], pollPeriod: '1d', pollCorrectOptionIndex: 2 } })
+ ).rejects.toThrow('from 0 to 1');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('the human create action has no poll path', async () => {
+ await expect(runAction({ action: createCollectionPost, propsValue: { brand: 42, collection: 77, pollQuestion: 'Q?' } })).rejects.toThrow('Caption is required');
+ });
+
+ it('create post rejects a scheduled time without an offset, in both shapes', async () => {
+ await expect(runAction({ action: aiCreatePost, propsValue: { brandId: '42', collectionId: '77', caption: 'x', publishMode: 'SCHEDULE', scheduledAt: '2030-10-12 09:00:00' } })).rejects.toThrow(
+ 'with an offset'
+ );
+ await expect(runAction({ action: createCollectionPost, propsValue: { brand: 42, collection: 77, caption: 'x', publishMode: 'SCHEDULE', scheduledAt: '2030-10-12T09:00:00' } })).rejects.toThrow(
+ 'with an offset'
+ );
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('create post converts an offset time to brand-local', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: listBody({ data: [{ ...BRAND, timezone: 'Asia/Amman' }] }) })).mockResolvedValueOnce(ok({ data: { id: 1 }, status: 201 }));
+ const result = await runAction({ action: aiCreatePost, propsValue: { brandId: '42', collectionId: '77', caption: 'x', publishMode: 'SCHEDULE', scheduledAt: '2030-10-12T06:00:00Z' } });
+ expect(requestOf({ fetchMock, call: 1 }).body).toMatchObject({ scheduledAt: '2030-10-12 09:00:00', publishMode: 'SCHEDULE' });
+ expect(result).toMatchObject({ scheduledAt: '2030-10-12 09:00:00', brandTimezone: 'Asia/Amman' });
+ });
+
+ it('list brand posts sends status and posting type', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: listBody({ data: [] }) }));
+ await runAction({ action: aiListBrandPosts, propsValue: { brandId: '42', status: 'pending', postingType: 'QUEUE' } });
+ expect(requestOf({ fetchMock, call: 0 }).query).toMatchObject({ status: 'PENDING', posting_type: 'QUEUE' });
+ });
+
+ it('list published posts sends post type and checks query IDs', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: listBody({ data: [] }) }));
+ await runAction({ action: aiListPublishedPosts, propsValue: { brandId: '42', postType: ' IMAGE ', channelId: '5' } });
+ expect(requestOf({ fetchMock, call: 0 }).query).toMatchObject({ post_type: 'IMAGE', channel_id: '5' });
+ await expect(runAction({ action: aiListPublishedPosts, propsValue: { brandId: '42', channelId: 'x' } })).rejects.toThrow('numeric Nuelink ID');
+ });
+});
diff --git a/packages/pieces/community/nuelink/test/client.test.ts b/packages/pieces/community/nuelink/test/client.test.ts
new file mode 100644
index 00000000000..37fe0d09a30
--- /dev/null
+++ b/packages/pieces/community/nuelink/test/client.test.ts
@@ -0,0 +1,185 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { nuelinkApiKeyAuth, nuelinkAuth } from '../src/lib/auth';
+import { NuelinkApiError, nuelinkClient } from '../src/lib/common/client';
+import { installFetch, jsonResponse, requestOf } from './helpers';
+
+let fetchMock: ReturnType<typeof installFetch>;
+
+beforeEach(() => {
+ fetchMock = installFetch();
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+describe('error parser handles all four Nuelink error shapes', () => {
+ it('Laravel 422 with array messages', () => {
+ const message = nuelinkClient.describeError({
+ status: 422,
+ responseBody: { message: 'The given data was invalid.', errors: { per_page: ['The per page must not be greater than 100.'] } },
+ });
+ expect(message).toBe('Nuelink rejected the values (422): per_page: The per page must not be greater than 100.');
+ });
+
+ it('domain error with string messages', () => {
+ const message = nuelinkClient.describeError({
+ status: 422,
+ responseBody: { status: 'error', message: 'Scheduled post date must be at least 10 minutes in the future', errors: { scheduledAt: 'Scheduled post date must be at least 10 minutes in the future' } },
+ });
+ expect(message).toContain('scheduledAt: Scheduled post date must be at least 10 minutes in the future');
+ });
+
+ it('resource 429 with rate_limit field', () => {
+ const message = nuelinkClient.describeError({ status: 429, responseBody: { message: 'Too many requests. Please try again later.', errors: { rate_limit: 'Too many requests. Please try again later' } } });
+ expect(message).toContain('Nuelink rate limit reached (429): rate_limit: Too many requests');
+ expect(message).toContain('30 requests a minute');
+ });
+
+ it('route 429 with message only', () => {
+ expect(nuelinkClient.describeError({ status: 429, responseBody: { message: 'Too Many Attempts.' } })).toContain('(429): Too Many Attempts. Nuelink allows');
+ });
+
+ it('missing or odd bodies do not crash', () => {
+ expect(nuelinkClient.describeError({ status: 500, responseBody: undefined })).toBe('Nuelink had a server error (HTTP 500): no details returned. Try again later.');
+ expect(nuelinkClient.describeError({ status: 502, responseBody: '<html>Bad gateway</html>' })).toContain('<html>Bad gateway</html>');
+ expect(nuelinkClient.describeError({ status: 400, responseBody: { errors: { media: 42 } } })).toContain('{"errors":{"media":42}}');
+ });
+
+ it('401 explains key expiry and 403 names the sensitive-actions setting', () => {
+ expect(nuelinkClient.describeError({ status: 401, responseBody: { status: 'error', message: 'Token has expired', errors: { authorization: 'Token has expired' } } })).toContain(
+ 'expire after 30 days to 1 year'
+ );
+ expect(
+ nuelinkClient.describeError({
+ status: 403,
+ responseBody: { status: 'error', message: 'Deleting posts through the API is disabled.', errors: { permissions: 'Deleting posts through the API is disabled.' } },
+ })
+ ).toContain('Allow AI to perform sensitive actions');
+ });
+
+ it('thrown error keeps status and responseBody but never a body field', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ status: 404, body: { status: 'error', message: 'Brand not found', errors: { brand_id: 'Brand not found' } } }));
+ const error = await nuelinkClient.request({ apiKey: 'k', method: HttpMethod.GET, path: ['brands', '42', 'channels'] }).catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(NuelinkApiError);
+ expect(error).toMatchObject({ status: 404, responseBody: { message: 'Brand not found' } });
+ expect(error).not.toHaveProperty('body');
+ expect(error).toHaveProperty('message', expect.stringContaining('Nuelink could not find it (404): brand_id: Brand not found'));
+ });
+});
+
+describe('request safety', () => {
+ it('sends the bearer key to the fixed host with a TLS-verifying dispatcher and no redirects', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: { status: 'success', data: { id: 1 } } }));
+ await nuelinkClient.request({ apiKey: 'abc', method: HttpMethod.GET, path: ['brands'] });
+ const request = requestOf({ fetchMock, call: 0 });
+ expect(request.url).toBe('https://app.nuelink.com/api/public/v1/brands');
+ expect(request.headers['authorization']).toBe('Bearer abc');
+ expect(request.headers['accept']).toBe('application/json');
+ expect(request.redirect).toBe('manual');
+ expect(request.dispatcher).toBeDefined();
+ expect(request.dispatcher?.constructor?.name).toBe('Agent');
+ });
+
+ it('refuses a redirect instead of following it', async () => {
+ fetchMock.mockResolvedValueOnce(new Response(null, { status: 302, headers: { location: 'https://evil.example.com' } }));
+ await expect(nuelinkClient.request({ apiKey: 'abc', method: HttpMethod.GET, path: ['brands'] })).rejects.toThrow('unexpected redirect (HTTP 302)');
+ });
+
+ it('rejects path segments that are not digits or fixed words', async () => {
+ await expect(nuelinkClient.request({ apiKey: 'abc', method: HttpMethod.GET, path: ['brands', '../auth'] })).rejects.toThrow('unexpected Nuelink path');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it.each(['42/../x', '42?x=1', ' ', '0', '-1', 'abc', '4.2', '1e5', '//evil.com'])('numericId rejects %j', (value) => {
+ expect(() => nuelinkClient.numericId({ value, label: 'Brand' })).toThrow('Brand must be a numeric Nuelink ID');
+ });
+
+ it('numericId accepts numbers and padded digit strings', () => {
+ expect(nuelinkClient.numericId({ value: 42, label: 'Brand' })).toBe('42');
+ expect(nuelinkClient.numericId({ value: ' 8801 ', label: 'Post' })).toBe('8801');
+ });
+
+ it('treats a 200 body with status error as a failure', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: { status: 'error', message: 'nope', errors: { post: 'nope' } } }));
+ await expect(nuelinkClient.request({ apiKey: 'abc', method: HttpMethod.GET, path: ['brands'] })).rejects.toThrow('post: nope');
+ });
+
+ it('reports a timeout with the caller hint and does not retry', async () => {
+ fetchMock.mockImplementation(async () => {
+ throw new DOMException('aborted', 'AbortError');
+ });
+ await expect(
+ nuelinkClient.request({ apiKey: 'abc', method: HttpMethod.POST, path: ['brands'], body: {}, timeoutMs: 120000, timeoutHint: 'Check first.' })
+ ).rejects.toThrow('Nuelink did not answer within 120 seconds. Check first.');
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('paging', () => {
+ it('walks pages by number and never follows nextPageUrl', async () => {
+ fetchMock
+ .mockResolvedValueOnce(jsonResponse({ body: { status: 'success', data: [{ id: 1 }], pagination: { currentPage: 1, perPage: 100, total: 2, lastPage: 2, nextPageUrl: 'https://evil.example.com/p2', prevPageUrl: null } } }))
+ .mockResolvedValueOnce(jsonResponse({ body: { status: 'success', data: [], pagination: { currentPage: 2, perPage: 100, total: 2, lastPage: 3, nextPageUrl: 'https://evil.example.com/p3', prevPageUrl: null } } }))
+ .mockResolvedValueOnce(jsonResponse({ body: { status: 'success', data: [{ id: 3 }], pagination: { currentPage: 3, perPage: 100, total: 2, lastPage: 3, nextPageUrl: null, prevPageUrl: null } } }));
+ const result = await nuelinkClient.listAllPages({ apiKey: 'abc', path: ['brands', '42', 'channels'] });
+ expect(result).toEqual({ items: [{ id: 1 }, { id: 3 }], truncated: false });
+ expect(fetchMock.mock.calls.map((_, call) => requestOf({ fetchMock, call }).url)).toEqual([
+ 'https://app.nuelink.com/api/public/v1/brands/42/channels?page=1&per_page=100',
+ 'https://app.nuelink.com/api/public/v1/brands/42/channels?page=2&per_page=100',
+ 'https://app.nuelink.com/api/public/v1/brands/42/channels?page=3&per_page=100',
+ ]);
+ });
+
+ it('reports truncation after the page cap', async () => {
+ fetchMock.mockImplementation(async (input: string) => {
+ const page = Number(new URL(input).searchParams.get('page'));
+ return jsonResponse({ body: { status: 'success', data: [{ id: page }], pagination: { currentPage: page, perPage: 100, total: 5000, lastPage: 50 } } });
+ });
+ const result = await nuelinkClient.listAllPages({ apiKey: 'abc', path: ['brands'], maxPages: 3 });
+ expect(result.truncated).toBe(true);
+ expect(result.items).toHaveLength(3);
+ });
+});
+
+describe('auth validation', () => {
+ it('API key: valid on 200 from /auth, with trimmed key', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: { status: 'success', data: { id: 'x', name: 'A', joinedAt: '2025-06-20T10:15:30.000000Z', timezone: null } } }));
+ await expect(nuelinkApiKeyAuth.validate?.({ auth: { apiKey: ' key ' }, server: { apiUrl: '', publicUrl: '' } })).resolves.toEqual({ valid: true });
+ const request = requestOf({ fetchMock, call: 0 });
+ expect(request.url).toBe('https://app.nuelink.com/api/public/v1/auth');
+ expect(request.headers['authorization']).toBe('Bearer key');
+ });
+
+ it('API key: invalid only on 401/403', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ status: 401, body: { status: 'error', message: 'Invalid Token', errors: { authorization: 'Invalid Token' } } }));
+ const result = await nuelinkApiKeyAuth.validate?.({ auth: { apiKey: 'bad' }, server: { apiUrl: '', publicUrl: '' } });
+ expect(result).toMatchObject({ valid: false, error: expect.stringContaining('did not accept this API key') });
+ });
+
+ it('API key: an outage is not reported as a bad key', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ status: 503, body: { message: 'down' } }));
+ const result = await nuelinkApiKeyAuth.validate?.({ auth: { apiKey: 'key' }, server: { apiUrl: '', publicUrl: '' } });
+ expect(result).toEqual({ valid: false, error: 'Could not reach Nuelink to check the API key (HTTP 503). Try again in a minute.' });
+ });
+
+ it('legacy token: checks /api/v1/user on the legacy host', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: { id: 1 } }));
+ await expect(nuelinkAuth.validate?.({ auth: ' tok ', server: { apiUrl: '', publicUrl: '' } })).resolves.toEqual({ valid: true });
+ const request = requestOf({ fetchMock, call: 0 });
+ expect(request.url).toBe('https://nuelink.com/api/v1/user');
+ expect(request.headers['authorization']).toBe('Bearer tok');
+ });
+
+ it('legacy token: 401 is invalid, network error is "could not reach"', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ status: 401, body: { status: 'error', errors: { token: 'Invalid token' } } }));
+ expect(await nuelinkAuth.validate?.({ auth: 'bad', server: { apiUrl: '', publicUrl: '' } })).toMatchObject({ valid: false, error: expect.stringContaining('automation token') });
+ fetchMock.mockRejectedValueOnce(new TypeError('fetch failed'));
+ expect(await nuelinkAuth.validate?.({ auth: 'tok', server: { apiUrl: '', publicUrl: '' } })).toEqual({
+ valid: false,
+ error: 'Could not reach Nuelink to check the automation token. Try again in a minute.',
+ });
+ });
+});
diff --git a/packages/pieces/community/nuelink/test/helpers.ts b/packages/pieces/community/nuelink/test/helpers.ts
new file mode 100644
index 00000000000..b734efb081c
--- /dev/null
+++ b/packages/pieces/community/nuelink/test/helpers.ts
@@ -0,0 +1,131 @@
+import { AppConnectionType } from '@activepieces/pieces-framework';
+import { vi } from 'vitest';
+import { createMockActionContext } from '../../../framework/src/lib/test';
+
+export function apiKeyAuth() {
+ return { type: AppConnectionType.CUSTOM_AUTH as const, props: { apiKey: ' key_test ' } };
+}
+
+export function legacyAuth() {
+ return { type: AppConnectionType.SECRET_TEXT as const, secret_text: ' tok_legacy ' };
+}
+
+export function runAction({
+ action,
+ propsValue,
+ auth = apiKeyAuth(),
+}: {
+ action: { run: (context: never) => Promise<unknown> };
+ propsValue: Record<string, unknown>;
+ auth?: ReturnType<typeof apiKeyAuth> | ReturnType<typeof legacyAuth>;
+}): Promise<unknown> {
+ const context = { ...createMockActionContext({ propsValue: {} }), propsValue, auth };
+ return Reflect.apply(action.run, action, [context]);
+}
+
+export function memoryStore() {
+ const data = new Map<string, string>();
+ return {
+ data,
+ store: {
+ put: async <T>(key: string, value: 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) => {
+ data.delete(key);
+ },
+ },
+ };
+}
+
+export function jsonResponse({ status = 200, body }: { status?: number; body: unknown }): Response {
+ return new Response(body === undefined ? null : JSON.stringify(body), {
+ status,
+ headers: { 'content-type': 'application/json' },
+ });
+}
+
+export function listBody({ data, currentPage = 1, lastPage = 1, perPage = 25, total }: { data: unknown[]; currentPage?: number; lastPage?: number; perPage?: number; total?: number }) {
+ return {
+ status: 'success',
+ data,
+ pagination: {
+ currentPage,
+ perPage,
+ total: total ?? data.length,
+ lastPage,
+ nextPageUrl: currentPage < lastPage ? `https://evil.example.com/steal?page=${currentPage + 1}` : null,
+ prevPageUrl: null,
+ },
+ };
+}
+
+export function installFetch() {
+ const fetchMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+ vi.spyOn(console, 'error').mockImplementation(() => undefined);
+ return fetchMock;
+}
+
+export function requestOf({ fetchMock, call }: { fetchMock: ReturnType<typeof vi.fn>; call: number }) {
+ const [input, init] = fetchMock.mock.calls[call];
+ const headers = new Headers(init?.headers);
+ const url = new URL(String(input));
+ const rawBody = init?.body;
+ return {
+ url: String(input),
+ origin: url.origin,
+ path: url.pathname,
+ query: Object.fromEntries(url.searchParams.entries()),
+ method: String(init?.method ?? 'GET'),
+ headers: Object.fromEntries(headers.entries()),
+ body: typeof rawBody === 'string' ? JSON.parse(rawBody) : rawBody,
+ dispatcher: init?.dispatcher,
+ redirect: init?.redirect,
+ };
+}
+
+export const BRAND = {
+ id: 42,
+ title: 'Acme Marketing',
+ description: 'Social channels for the Acme team',
+ timezone: 'Europe/London',
+ queueStatus: 'ACTIVE',
+ createdAt: '2026-09-15T10:20:30.000000Z',
+ updatedAt: '2026-10-01T14:05:00.000000Z',
+};
+
+export const POST = {
+ id: 8801,
+ collectionId: 77,
+ title: 'Product launch',
+ body: 'Our new product is live.',
+ media: [],
+ postType: 'TEXT',
+ postingType: 'SCHEDULE',
+ status: 'PENDING',
+ postDate: '2026-10-12 08:00:00',
+ createdAt: '2026-10-05T12:00:00.000000Z',
+ updatedAt: '2026-10-05T14:00:00.000000Z',
+};
+
+export function publishedPost({ id, publishedAt = '2026-10-10T14:00:00.000000Z' }: { id: number; publishedAt?: string }) {
+ return {
+ id,
+ postId: 8801,
+ collectionId: 77,
+ channel: { id: 501, name: 'Acme on LinkedIn', type: 'LinkedIn' },
+ postType: 'IMAGE',
+ body: 'Our new product is live.',
+ url: 'https://www.linkedin.com/feed/update/urn:li:share:123',
+ status: 'PUBLISHED',
+ message: null,
+ publishedAt,
+ results: { likes: 42, comments: 5, shares: 3, views: 1200, saves: 18, engagement: 68, clicks: 27, impressions: 1540, reach: 1310 },
+ };
+}
diff --git a/packages/pieces/community/nuelink/test/output-schemas.test.ts b/packages/pieces/community/nuelink/test/output-schemas.test.ts
new file mode 100644
index 00000000000..15a3fce13ea
--- /dev/null
+++ b/packages/pieces/community/nuelink/test/output-schemas.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it } from 'vitest';
+import { nuelinkOutputSchemas } from '../src/lib/output-schemas';
+
+describe('collection output schemas match what Nuelink returns', () => {
+ it('lists post counts and the evergreen interval on List Collections items', () => {
+ const items = nuelinkOutputSchemas.listCollections.fields.find((field) => field.key === 'items');
+ const keys = (items?.listItems ?? []).map((field) => field.key);
+ expect(keys).toEqual(expect.arrayContaining(['postsCount', 'maxRepublish']));
+ });
+
+ it('does not promise post counts on a created or updated collection', () => {
+ const keys = nuelinkOutputSchemas.collection.fields.map((field) => field.key);
+ expect(keys).toContain('maxRepublish');
+ expect(keys).not.toContain('postsCount');
+ });
+});
diff --git a/packages/pieces/community/nuelink/test/props.test.ts b/packages/pieces/community/nuelink/test/props.test.ts
new file mode 100644
index 00000000000..8a7efa4cbbb
--- /dev/null
+++ b/packages/pieces/community/nuelink/test/props.test.ts
@@ -0,0 +1,69 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { nuelinkProps } from '../src/lib/common/props';
+import { BRAND, apiKeyAuth, installFetch, jsonResponse, legacyAuth, listBody, requestOf } from './helpers';
+
+let fetchMock: ReturnType<typeof installFetch>;
+
+beforeEach(() => {
+ fetchMock = installFetch();
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+function options({ property, params }: { property: { options: unknown }; params: Record<string, unknown> }): Promise<unknown> {
+ const fn = property.options;
+ if (typeof fn !== 'function') {
+ throw new Error('not a dynamic dropdown');
+ }
+ return Reflect.apply(fn, property, [params, {}]);
+}
+
+describe('dropdowns', () => {
+ it('Brand walks every page', async () => {
+ fetchMock
+ .mockResolvedValueOnce(jsonResponse({ body: listBody({ data: [BRAND], currentPage: 1, lastPage: 2 }) }))
+ .mockResolvedValueOnce(jsonResponse({ body: listBody({ data: [{ ...BRAND, id: 43, title: 'Beta', timezone: null }], currentPage: 2, lastPage: 2 }) }));
+ const result = await options({ property: nuelinkProps.brand(), params: { auth: apiKeyAuth() } });
+ expect(result).toEqual({
+ disabled: false,
+ options: [
+ { label: 'Acme Marketing (Europe/London)', value: 42 },
+ { label: 'Beta', value: 43 },
+ ],
+ placeholder: undefined,
+ });
+ });
+
+ it('Collection needs a brand and lists channel counts', async () => {
+ expect(await options({ property: nuelinkProps.collection({ required: true, description: '' }), params: { auth: apiKeyAuth(), brand: undefined } })).toMatchObject({ disabled: true, placeholder: 'Select a brand first.' });
+ fetchMock.mockResolvedValueOnce(
+ jsonResponse({ body: listBody({ data: [{ id: 77, title: 'AP Test – no channels', status: 'ACTIVE', channels: [] }, { id: 78, title: 'Main', status: 'PAUSED', channels: [{ id: 1 }] }] }) })
+ );
+ const result = await options({ property: nuelinkProps.collection({ required: true, description: '' }), params: { auth: apiKeyAuth(), brand: 42 } });
+ expect(result).toMatchObject({
+ options: [
+ { label: 'AP Test – no channels (0 channels)', value: 77 },
+ { label: 'Main (1 channel, paused)', value: 78 },
+ ],
+ });
+ expect(requestOf({ fetchMock, call: 0 }).url).toBe('https://app.nuelink.com/api/public/v1/brands/42/collections?page=1&per_page=100');
+ });
+
+ it('Channel keeps walking past short and empty pages', async () => {
+ fetchMock
+ .mockResolvedValueOnce(jsonResponse({ body: listBody({ data: [], currentPage: 1, lastPage: 2, total: 3 }) }))
+ .mockResolvedValueOnce(jsonResponse({ body: listBody({ data: [{ id: 501, name: 'Acme on LinkedIn', type: 'LinkedIn' }], currentPage: 2, lastPage: 2 }) }));
+ const result = await options({ property: nuelinkProps.channel(), params: { auth: apiKeyAuth(), brand: 42 } });
+ expect(result).toMatchObject({ options: [{ label: 'Acme on LinkedIn (LinkedIn)', value: 501 }] });
+ });
+
+ it('legacy token and errors give a disabled dropdown with a reason', async () => {
+ expect(await options({ property: nuelinkProps.brand(), params: { auth: legacyAuth() } })).toMatchObject({ disabled: true, placeholder: expect.stringContaining('API Key connection') });
+ expect(await options({ property: nuelinkProps.brand(), params: { auth: undefined } })).toMatchObject({ disabled: true });
+ fetchMock.mockResolvedValueOnce(jsonResponse({ status: 401, body: { status: 'error', message: 'Token has expired', errors: { authorization: 'Token has expired' } } }));
+ expect(await options({ property: nuelinkProps.brand(), params: { auth: apiKeyAuth() } })).toMatchObject({ disabled: true, placeholder: expect.stringContaining('(401)') });
+ });
+});
diff --git a/packages/pieces/community/nuelink/test/time.test.ts b/packages/pieces/community/nuelink/test/time.test.ts
new file mode 100644
index 00000000000..880ac079b30
--- /dev/null
+++ b/packages/pieces/community/nuelink/test/time.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from 'vitest';
+import { nuelinkTime } from '../src/lib/common/time';
+
+const NOW = Date.parse('2026-01-01T00:00:00Z');
+
+describe('brand-local schedule conversion', () => {
+ it.each([
+ ['2026-07-01T08:00:00Z', 'Europe/London', '2026-07-01 09:00:00'],
+ ['2026-12-01T09:00:00Z', 'Europe/London', '2026-12-01 09:00:00'],
+ ['2026-03-29T00:30:00Z', 'Europe/London', '2026-03-29 00:30:00'],
+ ['2026-03-29T01:30:00Z', 'Europe/London', '2026-03-29 02:30:00'],
+ ['2026-07-01T13:00:00Z', 'America/New_York', '2026-07-01 09:00:00'],
+ ['2026-12-01T14:00:00Z', 'America/New_York', '2026-12-01 09:00:00'],
+ ['2026-03-08T07:30:00Z', 'America/New_York', '2026-03-08 03:30:00'],
+ ['2026-07-01T09:00:00+02:00', 'Africa/Casablanca', '2026-07-01 08:00:00'],
+ ['2026-10-12T09:00:00+03:00', 'Asia/Amman', '2026-10-12 09:00:00'],
+ ['2026-10-12T06:00:00Z', 'Asia/Amman', '2026-10-12 09:00:00'],
+ ['2026-10-12T23:30:00Z', 'Asia/Tokyo', '2026-10-13 08:30:00'],
+ ])('%s in %s becomes %s', (value, timeZone, expected) => {
+ expect(nuelinkTime.toBrandSchedule({ value, timeZone, now: NOW, label: 'Scheduled Time' }).local).toBe(expected);
+ });
+
+ it('refuses the repeated hour when daylight saving ends', () => {
+ expect(() => nuelinkTime.toBrandSchedule({ value: '2026-11-01T05:30:00Z', timeZone: 'America/New_York', now: NOW, label: 'Scheduled Time' })).toThrow('repeats');
+ expect(() => nuelinkTime.toBrandSchedule({ value: '2026-11-01T06:30:00Z', timeZone: 'America/New_York', now: NOW, label: 'Scheduled Time' })).toThrow('repeats');
+ expect(nuelinkTime.toBrandSchedule({ value: '2026-11-01T07:30:00Z', timeZone: 'America/New_York', now: NOW, label: 'Scheduled Time' }).local).toBe('2026-11-01 02:30:00');
+ });
+
+ it('requires at least 10 minutes of lead time', () => {
+ expect(() => nuelinkTime.toBrandSchedule({ value: '2026-01-01T00:09:59Z', timeZone: 'UTC', now: NOW, label: 'Scheduled Time' })).toThrow('at least 10 minutes');
+ expect(nuelinkTime.toBrandSchedule({ value: '2026-01-01T00:10:00Z', timeZone: 'UTC', now: NOW, label: 'Scheduled Time' }).local).toBe('2026-01-01 00:10:00');
+ });
+
+ it.each(['2026-10-12 09:00:00', '2026-10-12T09:00', '2026-10-12', '2026-10-12T09:00:00.000'])('rejects a scheduled time without an offset: %s', (value) => {
+ expect(() => nuelinkTime.toBrandSchedule({ value, timeZone: 'Asia/Amman', now: NOW, label: 'Scheduled Time' })).toThrow('Send an ISO-8601 time with an offset');
+ });
+
+ it('rejects unparseable values', () => {
+ expect(() => nuelinkTime.parseInstant({ value: 'tomorrow 9am', label: 'Scheduled Time' })).toThrow('not a valid date and time');
+ expect(() => nuelinkTime.parseInstant({ value: '', label: 'Scheduled Time' })).toThrow('is empty');
+ });
+
+ it('throws when the brand has no or an unknown timezone', () => {
+ expect(() => nuelinkTime.assertTimeZone({ timeZone: null, brandTitle: 'Acme' })).toThrow('has no timezone set');
+ expect(() => nuelinkTime.assertTimeZone({ timeZone: '0c7f6a8e-uuid', brandTitle: 'Acme' })).toThrow('does not recognise');
+ expect(nuelinkTime.assertTimeZone({ timeZone: ' Europe/London ', brandTitle: 'Acme' })).toBe('Europe/London');
+ });
+
+ it('formats filters in UTC, not brand time', () => {
+ expect(nuelinkTime.toUtcFilter({ value: '2026-10-01T02:00:00+02:00', label: 'From' })).toBe('2026-10-01 00:00:00');
+ expect(nuelinkTime.toUtcFilter({ value: '2026-10-01', label: 'From' })).toBe('2026-10-01 00:00:00');
+ });
+});
diff --git a/packages/pieces/community/nuelink/test/trigger.test.ts b/packages/pieces/community/nuelink/test/trigger.test.ts
new file mode 100644
index 00000000000..ec07f6ab2d5
--- /dev/null
+++ b/packages/pieces/community/nuelink/test/trigger.test.ts
@@ -0,0 +1,210 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { newPublishedPost } from '../src/lib/triggers/new-published-post';
+import { apiKeyAuth, installFetch, jsonResponse, legacyAuth, listBody, memoryStore, publishedPost, requestOf } from './helpers';
+
+let fetchMock: ReturnType<typeof installFetch>;
+const STORE_KEY = 'nuelink_new_published_post';
+
+beforeEach(() => {
+ fetchMock = installFetch();
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(new Date('2026-10-11T12:00:00Z'));
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+function hookContext({ store, propsValue = { brand: 42, status: 'PUBLISHED' }, isRepublish, auth = apiKeyAuth() }: { store: ReturnType<typeof memoryStore>['store']; propsValue?: Record<string, unknown>; isRepublish?: boolean; auth?: ReturnType<typeof apiKeyAuth> | ReturnType<typeof legacyAuth> }) {
+ return { auth, propsValue, store, isRepublish, setSchedule: () => undefined };
+}
+
+function call<K extends 'onEnable' | 'onDisable' | 'run' | 'test'>({ hook, context }: { hook: K; context: ReturnType<typeof hookContext> }): Promise<unknown> {
+ const fn = newPublishedPost[hook];
+ return Reflect.apply(fn, newPublishedPost, [context]);
+}
+
+function idsOf(value: unknown): unknown[] {
+ if (!Array.isArray(value)) {
+ throw new Error('expected an array of emitted items');
+ }
+ return value.map((item: unknown) => (typeof item === 'object' && item !== null && 'id' in item ? item.id : undefined));
+}
+
+describe('New Published Post trigger', () => {
+ it('onEnable seeds the seen set from the last 15 minutes and emits nothing', async () => {
+ const { store, data } = memoryStore();
+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: listBody({ data: [publishedPost({ id: 10 }), publishedPost({ id: 11 })] }) }));
+ await call({ hook: 'onEnable', context: hookContext({ store }) });
+ const request = requestOf({ fetchMock, call: 0 });
+ expect(request.path).toBe('/api/public/v1/brands/42/published-posts');
+ expect(request.query).toEqual({ status: 'PUBLISHED', published_from: '2026-10-11 11:45:00', sort_by: 'id', sort_order: 'asc', page: '1', per_page: '100' });
+ expect(JSON.parse(data.get(STORE_KEY) ?? '{}')).toEqual({ seen: ['11', '10'], recent: [], lastPoll: Date.parse('2026-10-11T12:00:00Z') });
+ });
+
+ it('emits only unseen results and does not repeat them on the next overlapping poll', async () => {
+ const { store, data } = memoryStore();
+ data.set(STORE_KEY, JSON.stringify({ seen: ['10'], lastPoll: Date.parse('2026-10-11T11:55:00Z') }));
+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: listBody({ data: [publishedPost({ id: 10 }), publishedPost({ id: 12 }), publishedPost({ id: 13 })] }) }));
+ const first = await call({ hook: 'run', context: hookContext({ store, propsValue: { brand: 42, status: 'FAILED', collection: 77 } }) });
+ expect(idsOf(first)).toEqual([12, 13]);
+ expect(requestOf({ fetchMock, call: 0 }).query).toMatchObject({ status: 'FAILED', collection_id: '77', published_from: '2026-10-11 11:40:00' });
+
+ vi.setSystemTime(new Date('2026-10-11T12:05:00Z'));
+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: listBody({ data: [publishedPost({ id: 12 }), publishedPost({ id: 13 }), publishedPost({ id: 14 })] }) }));
+ const second = await call({ hook: 'run', context: hookContext({ store, propsValue: { brand: 42, status: 'FAILED', collection: 77 } }) });
+ expect(idsOf(second)).toEqual([14]);
+ expect(requestOf({ fetchMock, call: 1 }).query).toMatchObject({ published_from: '2026-10-11 11:45:00' });
+ expect(JSON.parse(data.get(STORE_KEY) ?? '{}').seen).toEqual(['14', '13', '12', '10']);
+ });
+
+ it('a late result with an old ID inside the overlap window still fires once', async () => {
+ const { store, data } = memoryStore();
+ data.set(STORE_KEY, JSON.stringify({ seen: ['20', '21'], lastPoll: Date.parse('2026-10-11T11:55:00Z') }));
+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: listBody({ data: [publishedPost({ id: 5, publishedAt: '2026-10-11T11:54:00.000000Z' }), publishedPost({ id: 20 })] }) }));
+ const emitted = await call({ hook: 'run', context: hookContext({ store }) });
+ expect(idsOf(emitted)).toEqual([5]);
+ });
+
+ it('drains a backlog larger than 500 that shares one publishedAt across consecutive polls', async () => {
+ const { store, data } = memoryStore();
+ data.set(STORE_KEY, JSON.stringify({ seen: [], lastPoll: Date.parse('2026-10-11T11:55:00Z') }));
+ const backlog = Array.from({ length: 1234 }, (_, i) => publishedPost({ id: i + 1, publishedAt: '2026-10-11T11:50:00.000000Z' }));
+ fetchMock.mockImplementation(async (input: string) => {
+ const params = new URL(input).searchParams;
+ const page = Number(params.get('page'));
+ const perPage = Number(params.get('per_page'));
+ const lastPage = Math.ceil(backlog.length / perPage);
+ return jsonResponse({ body: listBody({ data: backlog.slice((page - 1) * perPage, page * perPage), currentPage: page, lastPage }) });
+ });
+ const emitted: unknown[] = [];
+ const startedFrom: string[] = [];
+ for (let poll = 0; poll < 6; poll++) {
+ vi.setSystemTime(new Date(Date.parse('2026-10-11T12:00:00Z') + poll * 60_000));
+ const before = fetchMock.mock.calls.length;
+ emitted.push(...idsOf(await call({ hook: 'run', context: hookContext({ store }) })));
+ startedFrom.push(new URL(String(fetchMock.mock.calls[before][0])).searchParams.get('page') ?? '');
+ }
+ expect(emitted).toEqual(backlog.map((item) => item.id));
+ expect(startedFrom).toEqual(['1', '6', '11', '1', '6', '11']);
+ const state = JSON.parse(data.get(STORE_KEY) ?? '{}');
+ expect(state.resume).toBeUndefined();
+ expect(state.recent).toEqual([[Date.parse('2026-10-11T11:50:00Z'), backlog.map((item) => String(item.id))]]);
+ expect(state.lastPoll).toBe(Date.parse('2026-10-11T12:05:00Z'));
+
+ vi.setSystemTime(new Date('2026-10-11T12:20:00Z'));
+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: listBody({ data: [] }) }));
+ await expect(call({ hook: 'run', context: hookContext({ store }) })).resolves.toEqual([]);
+ expect(JSON.parse(data.get(STORE_KEY) ?? '{}').recent).toEqual([]);
+ });
+
+ it('keeps the window fixed while a capped batch is unfinished', async () => {
+ const { store, data } = memoryStore();
+ data.set(STORE_KEY, JSON.stringify({ seen: [], lastPoll: Date.parse('2026-10-11T11:55:00Z') }));
+ fetchMock.mockImplementation(async (input: string) => {
+ const page = Number(new URL(input).searchParams.get('page'));
+ return jsonResponse({ body: listBody({ data: [publishedPost({ id: page, publishedAt: `2026-10-11T11:4${page}:00.000000Z` })], currentPage: page, lastPage: 9 }) });
+ });
+ const emitted = await call({ hook: 'run', context: hookContext({ store }) });
+ expect(fetchMock).toHaveBeenCalledTimes(5);
+ expect(Array.isArray(emitted) ? emitted.length : -1).toBe(5);
+ expect(JSON.parse(data.get(STORE_KEY) ?? '{}')).toMatchObject({ lastPoll: Date.parse('2026-10-11T11:55:00Z'), resume: { since: Date.parse('2026-10-11T11:40:00Z'), page: 6 } });
+ });
+
+ it('keeps the saved state under the 512 KiB store limit at the recent-ID cap', async () => {
+ const { store, data } = memoryStore();
+ data.set(STORE_KEY, JSON.stringify({ seen: [], lastPoll: Date.parse('2026-10-11T11:55:00Z') }));
+ const ids = Array.from({ length: 25000 }, (_, i) => 1_000_000_000 + i);
+ fetchMock.mockImplementation(async (input: string) => {
+ const page = Number(new URL(input).searchParams.get('page'));
+ const start = (page - 1) * 100;
+ const slice = ids.slice(start, start + 100).map((id, i) => publishedPost({ id, publishedAt: `2026-10-11T11:50:${String((start + i) % 60).padStart(2, '0')}.000000Z` }));
+ return jsonResponse({ body: listBody({ data: slice, currentPage: page, lastPage: 250 }) });
+ });
+ for (let poll = 0; poll < 50; poll++) {
+ await call({ hook: 'run', context: hookContext({ store }) });
+ }
+ const raw = data.get(STORE_KEY) ?? '';
+ const state = JSON.parse(raw);
+ expect(state.recent.reduce((total: number, group: [number, string[]]) => total + group[1].length, 0)).toBe(20000);
+ expect(new TextEncoder().encode(raw).length).toBeLessThan(512 * 1024 * 0.6);
+ });
+
+ it('stays under the 512 KiB store limit when every delivery has its own publish time', async () => {
+ const { store, data } = memoryStore();
+ const since = Date.parse('2026-10-11T06:00:00Z');
+ data.set(STORE_KEY, JSON.stringify({ seen: [], lastPoll: since }));
+ const ids = Array.from({ length: 25000 }, (_, i) => 100_000_000_000_000 + i);
+ fetchMock.mockImplementation(async (input: string) => {
+ const page = Number(new URL(input).searchParams.get('page'));
+ const start = (page - 1) * 100;
+ const slice = ids.slice(start, start + 100).map((id, i) => publishedPost({ id, publishedAt: new Date(since + (start + i) * 1000).toISOString() }));
+ return jsonResponse({ body: listBody({ data: slice, currentPage: page, lastPage: 250 }) });
+ });
+ for (let poll = 0; poll < 40; poll++) {
+ await call({ hook: 'run', context: hookContext({ store }) });
+ expect(new TextEncoder().encode(data.get(STORE_KEY) ?? '').length).toBeLessThan(512 * 1024);
+ }
+ const state = JSON.parse(data.get(STORE_KEY) ?? '{}');
+ const kept: string[] = state.recent.flatMap((group: [number, string[]]) => group[1]);
+ expect(state.resume).toMatchObject({ page: 201 });
+ expect(kept.length).toBeGreaterThan(10000);
+ expect(kept[kept.length - 1]).toBe(String(ids[19999]));
+ });
+
+ it('keeps the seen set bounded', async () => {
+ const { store, data } = memoryStore();
+ data.set(STORE_KEY, JSON.stringify({ seen: Array.from({ length: 1000 }, (_, i) => String(5000 - i)), lastPoll: Date.parse('2026-10-11T11:55:00Z') }));
+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: listBody({ data: [publishedPost({ id: 9000 })] }) }));
+ await call({ hook: 'run', context: hookContext({ store }) });
+ const seen = JSON.parse(data.get(STORE_KEY) ?? '{}').seen;
+ expect(seen).toHaveLength(1000);
+ expect(seen[0]).toBe('9000');
+ });
+
+ it('a run without state seeds instead of emitting history', async () => {
+ const { store, data } = memoryStore();
+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: listBody({ data: [publishedPost({ id: 1 })] }) }));
+ await expect(call({ hook: 'run', context: hookContext({ store }) })).resolves.toEqual([]);
+ expect(data.has(STORE_KEY)).toBe(true);
+ });
+
+ it('republish keeps the existing checkpoint', async () => {
+ const { store, data } = memoryStore();
+ const state = { seen: ['1'], lastPoll: 123 };
+ data.set(STORE_KEY, JSON.stringify(state));
+ await call({ hook: 'onEnable', context: hookContext({ store, isRepublish: true }) });
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(JSON.parse(data.get(STORE_KEY) ?? '{}')).toEqual(state);
+ });
+
+ it('a failing poll does not move the checkpoint', async () => {
+ const { store, data } = memoryStore();
+ const state = { seen: ['1'], lastPoll: Date.parse('2026-10-11T11:55:00Z') };
+ data.set(STORE_KEY, JSON.stringify(state));
+ fetchMock.mockResolvedValueOnce(jsonResponse({ status: 429, body: { message: 'Too Many Attempts.' } }));
+ await expect(call({ hook: 'run', context: hookContext({ store }) })).rejects.toThrow('rate limit');
+ expect(JSON.parse(data.get(STORE_KEY) ?? '{}')).toEqual(state);
+ });
+
+ it('test returns the five most recent results', async () => {
+ const { store } = memoryStore();
+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: listBody({ data: [publishedPost({ id: 3 })] }) }));
+ await expect(call({ hook: 'test', context: hookContext({ store }) })).resolves.toEqual([publishedPost({ id: 3 })]);
+ expect(requestOf({ fetchMock, call: 0 }).query).toEqual({ status: 'PUBLISHED', sort_by: 'id', sort_order: 'desc', page: '1', per_page: '5' });
+ });
+
+ it('refuses the legacy token on enable', async () => {
+ const { store } = memoryStore();
+ await expect(call({ hook: 'onEnable', context: hookContext({ store, auth: legacyAuth() }) })).rejects.toThrow('needs a Nuelink API Key connection');
+ });
+
+ it('onDisable clears the state', async () => {
+ const { store, data } = memoryStore();
+ data.set(STORE_KEY, '{}');
+ await call({ hook: 'onDisable', context: hookContext({ store }) });
+ expect(data.has(STORE_KEY)).toBe(false);
+ });
+});
diff --git a/packages/pieces/community/nuelink/vitest.config.ts b/packages/pieces/community/nuelink/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/nuelink/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'),
+ },
+ },
+})