AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(foreplay-co): let agents search ads, brands, boards and Spyder data (#16633)
Odai Ahmad8186792d246f
diff --git a/bun.lock b/bun.lockindex a3b6da5100f..bc84d2a6550 100644--- a/bun.lock+++ b/bun.lock@@ -3384,16 +3384,16 @@},"packages/pieces/community/foreplay-co": {"name": "@activepieces/piece-foreplay-co",- "version": "0.1.9",+ "version": "0.2.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*","@activepieces/pieces-common": "workspace:*","@activepieces/pieces-framework": "workspace:*",- "zod": "4.3.6",},"devDependencies": {"tslib": "^2.3.0",+ "vitest": "3.2.6",},},"packages/pieces/community/formbricks": {diff --git a/packages/pieces/community/foreplay-co/package.json b/packages/pieces/community/foreplay-co/package.jsonindex 9f4497695f5..d4f4c3d083a 100644--- a/packages/pieces/community/foreplay-co/package.json+++ b/packages/pieces/community/foreplay-co/package.json@@ -1,22 +1,23 @@{"name": "@activepieces/piece-foreplay-co",- "version": "0.1.9",+ "version": "0.2.0","type": "commonjs","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","dependencies": {"@activepieces/pieces-common": "workspace:*","@activepieces/pieces-framework": "workspace:*",- "zod": "4.3.6","@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*"},"devDependencies": {- "tslib": "^2.3.0"+ "tslib": "^2.3.0",+ "vitest": "3.2.6"},"scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"}}diff --git a/packages/pieces/community/foreplay-co/src/i18n/translation.json b/packages/pieces/community/foreplay-co/src/i18n/translation.jsonindex 86747b6e104..6c1873625db 100644--- a/packages/pieces/community/foreplay-co/src/i18n/translation.json+++ b/packages/pieces/community/foreplay-co/src/i18n/translation.json@@ -1,74 +1,333 @@{"Competitive advertising data and creative insights platform. Search, filter, and analyze ads and brands with live and historical ad creatives, metadata, and competitive intelligence.": "Competitive advertising data and creative insights platform. Search, filter, and analyze ads and brands with live and historical ad creatives, metadata, and competitive intelligence.",- "Your Foreplay.co API key": "Your Foreplay.co API key",+ "Your Foreplay API key. In Foreplay open the Data API dashboard (https://app.foreplay.co/api-overview) and generate a key.": "Your Foreplay API key. In Foreplay open the Data API dashboard (https://app.foreplay.co/api-overview) and generate a key.","Get Ad by ID": "Get Ad by ID","Get Ads by Page": "Get Ads by Page","Find Brands": "Find Brands","Find Ads": "Find Ads","Find Boards": "Find Boards",- "Get detailed information about a specific ad by its ID.": "Get detailed information about a specific ad by its ID.",- "Get all ads for a Facebook Page ID with filtering and pagination.": "Get all ads for a Facebook Page ID with filtering and pagination.",- "Search for brands by name with fuzzy matching.": "Search for brands by name with fuzzy matching.",- "Search and filter ads by text, dates, platforms, and categories.": "Search and filter ads by text, dates, platforms, and categories.",- "Get all boards for the authenticated user with pagination.": "Get all boards for the authenticated user with pagination.",- "Ad ID": "Ad ID",+ "Search Ads": "Search Ads",+ "Get Ad": "Get Ad",+ "List Ad Duplicates": "List Ad Duplicates",+ "List Page Ads": "List Page Ads",+ "List Brand Ads": "List Brand Ads",+ "Search Brands": "Search Brands",+ "Find Brands by Domain": "Find Brands by Domain",+ "Discover Brands by Ads": "Discover Brands by Ads",+ "Get Brand Analytics": "Get Brand Analytics",+ "List Boards": "List Boards",+ "List Board Brands": "List Board Brands",+ "List Board Ads": "List Board Ads",+ "List Swipe File Ads": "List Swipe File Ads",+ "List Spyder Brands": "List Spyder Brands",+ "Get Spyder Brand": "Get Spyder Brand",+ "List Spyder Brand Ads": "List Spyder Brand Ads",+ "Get Spyder Top Ads": "Get Spyder Top Ads",+ "List Spyder Ranked Ads": "List Spyder Ranked Ads",+ "List Spyder Related Pages": "List Spyder Related Pages",+ "Get Credit Usage": "Get Credit Usage",+ "Get Lens Report": "Get Lens Report",+ "Custom API Call": "Custom API Call",+ "Get detailed information about a specific ad by its public ad library ID. Costs 1 Foreplay credit.": "Get detailed information about a specific ad by its public ad library ID. Costs 1 Foreplay credit.",+ "Get ads for a Facebook Page ID with filtering and pagination. Costs 1 Foreplay credit per ad returned.": "Get ads for a Facebook Page ID with filtering and pagination. Costs 1 Foreplay credit per ad returned.",+ "Search for brands by name. Costs 1 Foreplay credit per search.": "Search for brands by name. Costs 1 Foreplay credit per search.",+ "Search and filter ads by text, dates, platforms, and categories. Costs 1 Foreplay credit per ad returned.": "Search and filter ads by text, dates, platforms, and categories. Costs 1 Foreplay credit per ad returned.",+ "Get the boards of your Foreplay account. Leave Limit empty to get all boards.": "Get the boards of your Foreplay account. Leave Limit empty to get all boards.",+ "Search the Foreplay ad library with text and filters.": "Search the Foreplay ad library with text and filters.",+ "Get one ad by its public ad library ID.": "Get one ad by its public ad library ID.",+ "Find ads that reuse the same image or video as a given ad.": "Find ads that reuse the same image or video as a given ad.",+ "List the ads of one Facebook page.": "List the ads of one Facebook page.",+ "List ads for one or more Foreplay brand IDs.": "List ads for one or more Foreplay brand IDs.",+ "Search Foreplay brands by name.": "Search Foreplay brands by name.",+ "Find brands that advertise from a website domain.": "Find brands that advertise from a website domain.",+ "Find brands whose ads match filters such as niche, format or platform.": "Find brands whose ads match filters such as niche, format or platform.",+ "Daily active/inactive ad counts and formats for a brand Facebook page.": "Daily active/inactive ad counts and formats for a brand Facebook page.",+ "List all boards in your Foreplay account.": "List all boards in your Foreplay account.",+ "List the brands saved in a board.": "List the brands saved in a board.",+ "List the ads saved in a board.": "List the ads saved in a board.",+ "List the ads saved in your swipe file.": "List the ads saved in your swipe file.",+ "List the brands you track in Spyder.": "List the brands you track in Spyder.",+ "Get one brand from your Spyder watchlist.": "Get one brand from your Spyder watchlist.",+ "List ads of a brand you track in Spyder.": "List ads of a brand you track in Spyder.",+ "Top-ranked ads of a tracked page compared with an earlier date.": "Top-ranked ads of a tracked page compared with an earlier date.",+ "Ranked ads of a tracked page, filtered to breakout or evergreen.": "Ranked ads of a tracked page, filtered to breakout or evergreen.",+ "Pages and brands often seen alongside a tracked page (lookalikes, competitors).": "Pages and brands often seen alongside a tracked page (lookalikes, competitors).",+ "Show total and remaining Foreplay API credits for this billing period.": "Show total and remaining Foreplay API credits for this billing period.",+ "Get reporting rows from a Foreplay Lens.": "Get reporting rows from a Foreplay Lens.",+ "Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",+ "Public Ad ID": "Public Ad ID","Page ID": "Page ID","Start Date": "Start Date","End Date": "End Date",- "Order": "Order","Live Status": "Live Status","Display Format": "Display Format","Publisher Platform": "Publisher Platform","Niches": "Niches","Market Target": "Market Target","Languages": "Languages",+ "Order": "Order","Cursor": "Cursor","Limit": "Limit","Brand Name": "Brand Name","Search Query": "Search Query","Offset": "Offset",- "The unique identifier of the ad (e.g., \"ad_1234567890\"). You can find this ID from other Foreplay actions or the platform.": "The unique identifier of the ad (e.g., \"ad_1234567890\"). You can find this ID from other Foreplay actions or the platform.",- "The numeric Facebook page ID (e.g., \"123456789\"). You can find this in your Facebook page settings or from other Foreplay actions.": "The numeric Facebook page ID (e.g., \"123456789\"). You can find this in your Facebook page settings or from other Foreplay actions.",- "Start date (inclusive). Format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS": "Start date (inclusive). Format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS",- "End date (inclusive). Format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS": "End date (inclusive). Format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS",- "Order of results: newest (default), oldest, longest_running, or most_relevant": "Order of results: newest (default), oldest, longest_running, or most_relevant",- "Filter ads by live status. true means currently active ads, false means inactive ads.": "Filter ads by live status. true means currently active ads, false means inactive ads.",- "Filter by one or more display formats": "Filter by one or more display formats",- "Filter by one or more publisher platforms": "Filter by one or more publisher platforms",- "Filter by one or more niches": "Filter by one or more niches",- "Filter by market target": "Filter by market target",- "Filter by languages. Accepts various language formats.": "Filter by languages. Accepts various language formats.",- "Cursor for pagination. Use the cursor value from the previous response.": "Cursor for pagination. Use the cursor value from the previous response.",- "Pagination limit (default 10, max 250). Controls the number of ads returned per request.": "Pagination limit (default 10, max 250). Controls the number of ads returned per request.",- "Brand name to search for (e.g., \"Nike\", \"Apple\"). Supports fuzzy matching for partial names.": "Brand name to search for (e.g., \"Nike\", \"Apple\"). Supports fuzzy matching for partial names.",- "Number of brands to return (max 10).": "Number of brands to return (max 10).",- "Search text for ad name or description. Leave empty to search all ads with filters only.": "Search text for ad name or description. Leave empty to search all ads with filters only.",- "The offset for pagination (default 0).": "The offset for pagination (default 0).",- "The limit for pagination (default 10, max 10).": "The limit for pagination (default 10, max 10).",+ "Search Text": "Search Text",+ "Display Formats": "Display Formats",+ "Publisher Platforms": "Publisher Platforms",+ "Market Targets": "Market Targets",+ "Min Video Duration (seconds)": "Min Video Duration (seconds)",+ "Max Video Duration (seconds)": "Max Video Duration (seconds)",+ "Min Running Days": "Min Running Days",+ "Max Running Days": "Max Running Days",+ "Facebook Page ID": "Facebook Page ID",+ "Collect If Empty": "Collect If Empty",+ "Brand IDs": "Brand IDs",+ "Include Brands Without Ads": "Include Brands Without Ads",+ "Min Ads": "Min Ads",+ "Max Ads": "Max Ads",+ "Domain": "Domain",+ "Board ID": "Board ID",+ "Brand ID": "Brand ID",+ "Date": "Date",+ "Compare With (days ago)": "Compare With (days ago)",+ "Category": "Category",+ "Lens ID": "Lens ID",+ "From": "From",+ "To": "To",+ "Breakdown": "Breakdown",+ "Provider": "Provider",+ "Click Attribution": "Click Attribution",+ "View Attribution": "View Attribution",+ "Page": "Page",+ "Method": "Method",+ "Headers": "Headers",+ "Query Parameters": "Query Parameters",+ "Body Type": "Body Type",+ "Body": "Body",+ "Response is Binary": "Response is Binary",+ "Return Error as Output": "Return Error as Output",+ "Timeout": "Timeout",+ "Follow redirects": "Follow redirects",+ "The public ad library ID: the ad_id field of ads returned by other Foreplay steps (not the internal id field).": "The public ad library ID: the ad_id field of ads returned by other Foreplay steps (not the internal id field).",+ "The numeric Facebook page ID, e.g. 123456789.": "The numeric Facebook page ID, e.g. 123456789.",+ "Only ads from this date (inclusive).": "Only ads from this date (inclusive).",+ "Only ads up to this date (inclusive).": "Only ads up to this date (inclusive).",+ "Filter by whether the ad is running now.": "Filter by whether the ad is running now.",+ "Filter by one or more display formats.": "Filter by one or more display formats.",+ "Filter by one or more publisher platforms.": "Filter by one or more publisher platforms.",+ "Filter by one or more niches.": "Filter by one or more niches.",+ "Filter by market target.": "Filter by market target.",+ "Filter by ad language.": "Filter by ad language.",+ "newest, oldest, longest_running, most_relevant. Default newest.": "newest, oldest, longest_running, most_relevant. Default newest.",+ "Cursor from the previous response, for the next page.": "Cursor from the previous response, for the next page.",+ "Ads per request (1 to 250). 1 credit per ad returned.": "Ads per request (1 to 250). 1 credit per ad returned.",+ "Brand name to search for, e.g. Nike.": "Brand name to search for, e.g. Nike.",+ "Number of brands to return (1 to 100).": "Number of brands to return (1 to 100).",+ "Words in the ad name or copy. Leave empty to use filters only.": "Words in the ad name or copy. Leave empty to use filters only.",+ "Boards to skip (only used when Limit is set).": "Boards to skip (only used when Limit is set).",+ "Boards per request. Leave empty for all boards.": "Boards per request. Leave empty for all boards.",+ "Words in the ad name or copy. Empty = filters only.": "Words in the ad name or copy. Empty = filters only.",+ "Inclusive, YYYY-MM-DD or ISO 8601 date-time.": "Inclusive, YYYY-MM-DD or ISO 8601 date-time.",+ "true = running now, false = stopped; empty = both.": "true = running now, false = stopped; empty = both.",+ "1 to 250, default 10. 1 credit per ad returned.": "1 to 250, default 10. 1 credit per ad returned.",+ "nextCursor from the previous page.": "nextCursor from the previous page.",+ "The adId field of an ad from search results (not the internal id).": "The adId field of an ad from search results (not the internal id).",+ "Numeric page ID.": "Numeric page ID.",+ "Fetch from Meta when nothing is cached (waits up to ~30 s).": "Fetch from Meta when nothing is cached (waits up to ~30 s).",+ "1 to 100, default 10.": "1 to 100, default 10.",+ "example.com or https://example.com": "example.com or https://example.com",+ "1 to 10, default 10.": "1 to 10, default 10.",+ "Numeric Facebook page ID, e.g. 373652569755921 (the pageId field of a brand).": "Numeric Facebook page ID, e.g. 373652569755921 (the pageId field of a brand).",+ "YYYY-MM-DD, inclusive.": "YYYY-MM-DD, inclusive.",+ "nextOffset from the previous page.": "nextOffset from the previous page.",+ "saved_newest, newest, oldest, longest_running, most_relevant. Default saved_newest.": "saved_newest, newest, oldest, longest_running, most_relevant. Default saved_newest.",+ "YYYY-MM-DD, default today (UTC).": "YYYY-MM-DD, default today (UTC).",+ "1 to 365, default 7.": "1 to 365, default 7.",+ "1 to 100, default 20.": "1 to 100, default 20.",+ "1 to 50, default 5.": "1 to 50, default 5.",+ "YYYY-MM-DD": "YYYY-MM-DD",+ "1-based, default 1.": "1-based, default 1.",+ "Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.",+ "Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.",+ "Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.",+ "On a failed request, output the error instead of failing the step.": "On a failed request, output the error instead of failing the step.",+ "Seconds to wait for a response. Empty: up to the flow limit (10 min).": "Seconds to wait for a response. Empty: up to the flow limit (10 min).",+ "Follow 3xx redirects instead of returning them as the response.": "Follow 3xx redirects instead of returning them as the response.",+ "Active Only": "Active Only",+ "Inactive Only": "Inactive Only",+ "Video": "Video",+ "Image": "Image",+ "Carousel": "Carousel",+ "Dco": "Dco",+ "Dpa": "Dpa",+ "Multi Images": "Multi Images",+ "Multi Videos": "Multi Videos",+ "Multi Medias": "Multi Medias",+ "Event": "Event",+ "Text": "Text",+ "Page Like": "Page Like",+ "Facebook": "Facebook",+ "Instagram": "Instagram",+ "Audience Network": "Audience Network",+ "Messenger": "Messenger",+ "Tiktok": "Tiktok",+ "Youtube": "Youtube",+ "Linkedin": "Linkedin",+ "Threads": "Threads",+ "Whatsapp": "Whatsapp",+ "Accessories": "Accessories",+ "App/Software": "App/Software",+ "Beauty": "Beauty",+ "Business/Professional": "Business/Professional",+ "Charity/Nfp": "Charity/Nfp",+ "Education": "Education",+ "Entertainment": "Entertainment",+ "Fashion": "Fashion",+ "Food/Drink": "Food/Drink",+ "Health/Wellness": "Health/Wellness",+ "Home/Garden": "Home/Garden",+ "Jewelry/Watches": "Jewelry/Watches",+ "Kids/Baby": "Kids/Baby",+ "Medical": "Medical",+ "Other": "Other",+ "Parenting": "Parenting",+ "Pets": "Pets",+ "Real Estate": "Real Estate",+ "Service Business": "Service Business",+ "Food (legacy)": "Food (legacy)",+ "Health (legacy)": "Health (legacy)",+ "Home (legacy)": "Home (legacy)",+ "Technology (legacy)": "Technology (legacy)",+ "Finance (legacy)": "Finance (legacy)",+ "Sports (legacy)": "Sports (legacy)",+ "Travel (legacy)": "Travel (legacy)",+ "Automotive (legacy)": "Automotive (legacy)",+ "B2B (Business-to-Business)": "B2B (Business-to-Business)",+ "B2C (Business-to-Consumer)": "B2C (Business-to-Consumer)",+ "English": "English",+ "French": "French",+ "German": "German",+ "Italian": "Italian",+ "Dutch/Flemish": "Dutch/Flemish",+ "Spanish": "Spanish",+ "Portuguese": "Portuguese",+ "Romanian": "Romanian",+ "Russian": "Russian",+ "Chinese": "Chinese",+ "Japanese": "Japanese",+ "Korean": "Korean",+ "Arabic": "Arabic",+ "Hindi": "Hindi","Newest": "Newest","Oldest": "Oldest","Longest Running": "Longest Running","Most Relevant": "Most Relevant",- "Active Only": "Active Only",- "Inactive Only": "Inactive Only",+ "Active only": "Active only",+ "Inactive only": "Inactive only",+ "B2B": "B2B",+ "B2C": "B2C",+ "Afrikaans": "Afrikaans",+ "Albanian": "Albanian",+ "Armenian": "Armenian",+ "Azerbaijani": "Azerbaijani",+ "Bambara": "Bambara",+ "Basque": "Basque",+ "Bengali": "Bengali",+ "Bosnian": "Bosnian",+ "Bulgarian": "Bulgarian",+ "Burmese": "Burmese",+ "Catalan, Valencian": "Catalan, Valencian",+ "Central Khmer": "Central Khmer",+ "Chichewa, Chewa, Nyanja": "Chichewa, Chewa, Nyanja",+ "Corsican": "Corsican",+ "Croatian": "Croatian",+ "Czech": "Czech",+ "Danish": "Danish",+ "Dutch, Flemish": "Dutch, Flemish",+ "Estonian": "Estonian",+ "Finnish": "Finnish",+ "Galician": "Galician",+ "Georgian": "Georgian",+ "Greek (modern)": "Greek (modern)",+ "Guaraní": "Guaraní",+ "Hausa": "Hausa",+ "Hebrew (modern)": "Hebrew (modern)",+ "Hungarian": "Hungarian",+ "Icelandic": "Icelandic",+ "Indonesian": "Indonesian",+ "Javanese": "Javanese",+ "Kannada": "Kannada",+ "Kazakh": "Kazakh",+ "Latin": "Latin",+ "Latvian": "Latvian",+ "Lingala": "Lingala",+ "Lithuanian": "Lithuanian",+ "Luxembourgish, Letzeburgesch": "Luxembourgish, Letzeburgesch",+ "Macedonian": "Macedonian",+ "Malagasy": "Malagasy",+ "Malay": "Malay",+ "Malayalam": "Malayalam",+ "Maltese": "Maltese",+ "Maori": "Maori",+ "Marathi": "Marathi",+ "Mongolian": "Mongolian",+ "Norwegian": "Norwegian",+ "Oriya": "Oriya",+ "Oromo": "Oromo",+ "Persian": "Persian",+ "Polish": "Polish",+ "Romanian, Moldavian, Moldovan": "Romanian, Moldavian, Moldovan",+ "Serbian": "Serbian",+ "Shona": "Shona",+ "Sinhala, Sinhalese": "Sinhala, Sinhalese",+ "Slovak": "Slovak",+ "Slovene": "Slovene",+ "Spanish, Castilian": "Spanish, Castilian",+ "Sundanese": "Sundanese",+ "Swedish": "Swedish",+ "Telugu": "Telugu",+ "Thai": "Thai",+ "Turkish": "Turkish",+ "Turkmen": "Turkmen",+ "Ukrainian": "Ukrainian",+ "Urdu": "Urdu",+ "Uzbek": "Uzbek",+ "Vietnamese": "Vietnamese",+ "Welsh": "Welsh",+ "Western Frisian": "Western Frisian",+ "Most ranked": "Most ranked",+ "Least ranked": "Least ranked",+ "Saved Newest": "Saved Newest",+ "All": "All",+ "Breakout": "Breakout",+ "Evergreen": "Evergreen",+ "overall": "overall",+ "country": "country",+ "age,gender": "age,gender",+ "user_segment_key": "user_segment_key",+ "publisher_platform,platform_position": "publisher_platform,platform_position",+ "TikTok": "TikTok",+ "1d": "1d",+ "7d": "7d",+ "28d": "28d",+ "GET": "GET",+ "POST": "POST",+ "PATCH": "PATCH",+ "PUT": "PUT",+ "DELETE": "DELETE",+ "HEAD": "HEAD","New Ad in Spyder": "New Ad in Spyder","New Ad in Board": "New Ad in Board","New Swipefile Ad": "New Swipefile Ad",- "Triggers when new ads are added for a brand in Spyder.": "Triggers when new ads are added for a brand in Spyder.",- "Triggers when a new ad is added to the selected board.": "Triggers when a new ad is added to the selected board.",- "Triggers when a new ad is added to your swipefile collection.": "Triggers when a new ad is added to your swipefile collection.",+ "Triggers when Spyder finds a new ad for a tracked brand.": "Triggers when Spyder finds a new ad for a tracked brand.",+ "Triggers when a new ad shows up in the selected board.": "Triggers when a new ad shows up in the selected board.",+ "Triggers when a new ad is saved to your swipe file.": "Triggers when a new ad is saved to your swipe file.","Brand": "Brand",+ "Ads Checked per Poll": "Ads Checked per Poll","Polling Interval (minutes)": "Polling Interval (minutes)","Board": "Board",- "Select the brand to monitor for new ads.": "Select the brand to monitor for new ads.",- "How often to check for new ads (in minutes).": "How often to check for new ads (in minutes).",- "Select the board to monitor for new ads.": "Select the board to monitor for new ads.",- "Filter ads published after this date.": "Filter ads published after this date.",- "Filter ads published before this date.": "Filter ads published before this date.",- "Filter by ad status (active/inactive).": "Filter by ad status (active/inactive).",- "Filter by ad format (video, image, carousel, etc.).": "Filter by ad format (video, image, carousel, etc.).",- "Filter by platform (Facebook, Instagram, etc.).": "Filter by platform (Facebook, Instagram, etc.).",- "Filter by industry/category.": "Filter by industry/category.",- "Filter by target audience (B2B, B2C).": "Filter by target audience (B2B, B2C).",- "Filter by ad language.": "Filter by ad language."+ "A brand from your Spyder watchlist.": "A brand from your Spyder watchlist.",+ "How many of the newest ads to check each time (1 to 50, default 10). Foreplay charges 1 credit per ad returned, so every poll can cost up to this many credits.": "How many of the newest ads to check each time (1 to 50, default 10). Foreplay charges 1 credit per ad returned, so every poll can cost up to this many credits.",+ "No longer used; Activepieces sets the polling schedule.": "No longer used; Activepieces sets the polling schedule.",+ "The board to watch.": "The board to watch."}\ No newline at end of filediff --git a/packages/pieces/community/foreplay-co/src/index.ts b/packages/pieces/community/foreplay-co/src/index.tsindex 3d47028ae75..2d2ac2e53e3 100644--- a/packages/pieces/community/foreplay-co/src/index.ts+++ b/packages/pieces/community/foreplay-co/src/index.ts@@ -1,23 +1,91 @@+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';+import { createCustomApiCallAction } from '@activepieces/pieces-common';+import { findAds, findBoards, findBrands, getAdById, getAdsByPage } from './lib/actions';+import { discoverBrandsByAds } from './lib/actions/ai/discover-brands-by-ads';+import { findBrandsByDomain } from './lib/actions/ai/find-brands-by-domain';+import { getAd } from './lib/actions/ai/get-ad';+import { getBrandAnalytics } from './lib/actions/ai/get-brand-analytics';+import { getCreditUsage } from './lib/actions/ai/get-credit-usage';+import { getLensReport } from './lib/actions/ai/get-lens-report';+import { getSpyderBrand } from './lib/actions/ai/get-spyder-brand';+import { getSpyderTopAds } from './lib/actions/ai/get-spyder-top-ads';+import { listAdDuplicates } from './lib/actions/ai/list-ad-duplicates';+import { listBoardAds } from './lib/actions/ai/list-board-ads';+import { listBoardBrands } from './lib/actions/ai/list-board-brands';+import { listBoards } from './lib/actions/ai/list-boards';+import { listBrandAds } from './lib/actions/ai/list-brand-ads';+import { listPageAds } from './lib/actions/ai/list-page-ads';+import { listSpyderBrandAds } from './lib/actions/ai/list-spyder-brand-ads';+import { listSpyderBrands } from './lib/actions/ai/list-spyder-brands';+import { listSpyderRankedAds } from './lib/actions/ai/list-spyder-ranked-ads';+import { listSpyderRelatedPages } from './lib/actions/ai/list-spyder-related-pages';+import { listSwipefileAds } from './lib/actions/ai/list-swipefile-ads';+import { searchAds } from './lib/actions/ai/search-ads';+import { searchBrands } from './lib/actions/ai/search-brands';+import { foreplayCoAuth } from './lib/auth';+import { FOREPLAY_API_URL, foreplayClient } from './lib/common/client';+import { newAdInBoard, newAdInSpyder, newSwipefileAd } from './lib/triggers';-import { createPiece, PieceAuth } from "@activepieces/pieces-framework";-import { PieceCategory } from '@activepieces/pieces-framework';-import { getAdById, getAdsByPage, findBrands, findAds, findBoards } from "./lib/actions";-import { newAdInSpyder, newAdInBoard, newSwipefileAd } from "./lib/triggers";--export const foreplayCoAuth = PieceAuth.SecretText({- displayName: "API Key",- description: "Your Foreplay.co API key",- required: true,-})-export const foreplayCo = createPiece({- displayName: "Foreplay",- description: "Competitive advertising data and creative insights platform. Search, filter, and analyze ads and brands with live and historical ad creatives, metadata, and competitive intelligence.",- auth: foreplayCoAuth,- minimumSupportedRelease: '0.36.1',- logoUrl: "https://cdn.activepieces.com/pieces/foreplay-co.png",+const foreplayCo = createPiece({+ displayName: 'Foreplay',+ description: 'Competitive advertising data and creative insights platform. Search, filter, and analyze ads and brands with live and historical ad creatives, metadata, and competitive intelligence.',+ auth: foreplayCoAuth,+ minimumSupportedRelease: '0.88.2',+ logoUrl: 'https://cdn.activepieces.com/pieces/foreplay-co.png',categories: [PieceCategory.MARKETING],- authors: ['fortunamide', 'onyedikachi-david'],- actions: [getAdById, getAdsByPage, findBrands, findAds, findBoards],+ authors: ['fortunamide', 'onyedikachi-david', 'OdaiAhmed99'],+ actions: [+ getAdById,+ getAdsByPage,+ findBrands,+ findAds,+ findBoards,+ searchAds,+ getAd,+ listAdDuplicates,+ listPageAds,+ listBrandAds,+ searchBrands,+ findBrandsByDomain,+ discoverBrandsByAds,+ getBrandAnalytics,+ listBoards,+ listBoardBrands,+ listBoardAds,+ listSwipefileAds,+ listSpyderBrands,+ getSpyderBrand,+ listSpyderBrandAds,+ getSpyderTopAds,+ listSpyderRankedAds,+ listSpyderRelatedPages,+ getCreditUsage,+ getLensReport,+ createCustomApiCallAction({+ baseUrl: () => FOREPLAY_API_URL,+ auth: foreplayCoAuth,+ authMapping: async (auth, propsValue) => {+ const urlProp = propsValue['url'];+ const url = foreplayClient.isRecord(urlProp) && typeof urlProp['url'] === 'string' ? urlProp['url'].trim() : '';+ if (/^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith('//')) {+ let parsed: URL | undefined;+ try {+ parsed = new URL(url);+ } catch {+ parsed = undefined;+ }+ if (!parsed || parsed.username || parsed.password || parsed.origin !== new URL(FOREPLAY_API_URL).origin) {+ throw new Error(`The URL must be relative or start with ${FOREPLAY_API_URL}/.`);+ }+ }+ if (url.split(/[/?#]/).some((part) => part === '..' || part.toLowerCase() === '%2e%2e')) {+ throw new Error('The URL must not contain ".." segments.');+ }+ return { Authorization: foreplayClient.keyOf(auth) };+ },+ }),+ ],triggers: [newAdInSpyder, newAdInBoard, newSwipefileAd],});-\ No newline at end of file++export { foreplayCo, foreplayCoAuth };diff --git a/packages/pieces/community/foreplay-co/src/lib/actions/ai/discover-brands-by-ads.ts b/packages/pieces/community/foreplay-co/src/lib/actions/ai/discover-brands-by-ads.tsnew file mode 100644index 00000000000..a30d29cf075--- /dev/null+++ b/packages/pieces/community/foreplay-co/src/lib/actions/ai/discover-brands-by-ads.ts@@ -0,0 +1,37 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { foreplayCoAuth } from '../../auth';+import { foreplayClient } from '../../common/client';+import { foreplayMappers } from '../../common/mappers';+import { foreplayOutputSchemas } from '../../common/output-schemas';+import { foreplayProps } from '../../common/props';++const discoverBrandsByAds = createAction({+ auth: foreplayCoAuth,+ name: 'discover_brands_by_ads',+ classification: 'SEARCH',+ displayName: 'Discover Brands by Ads',+ description: 'Find brands whose ads match filters such as niche, format or platform.',+ audience: 'ai',+ aiMetadata: {+ description: 'Discovers brands by the characteristics of their ads, e.g. brands running live video ads on TikTok in the beauty niche. At least one filter is required (running-day filters are not supported by this endpoint). Costs 1 credit per call regardless of how many brands come back (limit default 10, max 100 here).',+ idempotent: true,+ },+ outputSchema: foreplayOutputSchemas.brandList,+ props: {+ ...foreplayProps.aiAdFilterProps({ withRunningDays: false }),+ limit: Property.Number({ displayName: 'Limit', description: '1 to 100, default 10.', required: false }),+ },+ async run({ auth, propsValue }) {+ const filters = foreplayProps.adFilterQuery({ ...foreplayProps.aiAdFilterInput(propsValue), runningDurationMinDays: undefined, runningDurationMaxDays: undefined });+ if (Object.values(filters).every((v) => v === undefined)) throw new Error('Set at least one filter (date, live status, format, platform, niche, market target, language or video length).');+ const response = await foreplayClient.request({+ auth,+ path: '/api/discovery/brands/explore',+ query: { ...filters, limit: foreplayProps.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 100 }) ?? 10 },+ });+ const items = foreplayMappers.listOf(response.body).map(foreplayMappers.brand);+ return { items, count: items.length, ...foreplayMappers.credits(response) };+ },+});++export { discoverBrandsByAds };diff --git a/packages/pieces/community/foreplay-co/src/lib/actions/ai/find-brands-by-domain.ts b/packages/pieces/community/foreplay-co/src/lib/actions/ai/find-brands-by-domain.tsnew file mode 100644index 00000000000..3689774a2d1--- /dev/null+++ b/packages/pieces/community/foreplay-co/src/lib/actions/ai/find-brands-by-domain.ts@@ -0,0 +1,44 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { foreplayCoAuth } from '../../auth';+import { foreplayClient } from '../../common/client';+import { foreplayMappers } from '../../common/mappers';+import { foreplayOutputSchemas } from '../../common/output-schemas';+import { foreplayProps } from '../../common/props';++const DOMAIN_RE = /^(https?:\/\/)?[A-Za-z0-9.-]+\.[A-Za-z]{2,}(\/\S*)?$/;++const findBrandsByDomain = createAction({+ auth: foreplayCoAuth,+ name: 'find_brands_by_domain',+ classification: 'SEARCH',+ displayName: 'Find Brands by Domain',+ description: 'Find brands that advertise from a website domain.',+ audience: 'ai',+ aiMetadata: {+ description: 'Finds brands whose ads point to a website domain (e.g. allbirds.com or a full URL). Use it to turn a company website into Foreplay brand IDs and Facebook page IDs. Costs 1 credit per call.',+ idempotent: true,+ },+ outputSchema: foreplayOutputSchemas.brandList,+ props: {+ domain: Property.ShortText({ displayName: 'Domain', description: 'example.com or https://example.com', required: true }),+ limit: Property.Number({ displayName: 'Limit', description: '1 to 10, default 10.', required: false }),+ order: Property.StaticDropdown({ displayName: 'Order', required: false, options: { options: [{ label: 'Most ranked', value: 'most_ranked' }, { label: 'Least ranked', value: 'least_ranked' }] } }),+ },+ async run({ auth, propsValue }) {+ const domain = foreplayProps.requiredText({ value: propsValue.domain, label: 'Domain' });+ if (!DOMAIN_RE.test(domain)) throw new Error('Domain must look like example.com or https://example.com.');+ const response = await foreplayClient.request({+ auth,+ path: '/api/brand/getBrandsByDomain',+ query: {+ domain,+ limit: foreplayProps.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 10 }) ?? 10,+ order: foreplayProps.enumValue({ value: propsValue.order, label: 'Order', allowed: foreplayProps.BRAND_ORDERS }),+ },+ });+ const items = foreplayMappers.listOf(response.body).map(foreplayMappers.brand);+ return { items, count: items.length, ...foreplayMappers.credits(response) };+ },+});++export { findBrandsByDomain };diff --git a/packages/pieces/community/foreplay-co/src/lib/actions/ai/get-ad.ts b/packages/pieces/community/foreplay-co/src/lib/actions/ai/get-ad.tsnew file mode 100644index 00000000000..162539694c5--- /dev/null+++ b/packages/pieces/community/foreplay-co/src/lib/actions/ai/get-ad.ts@@ -0,0 +1,30 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { foreplayCoAuth } from '../../auth';+import { foreplayClient } from '../../common/client';+import { foreplayMappers } from '../../common/mappers';+import { foreplayOutputSchemas } from '../../common/output-schemas';+import { foreplayProps } from '../../common/props';++const getAd = createAction({+ auth: foreplayCoAuth,+ name: 'get_ad',+ classification: 'READ',+ displayName: 'Get Ad',+ description: 'Get one ad by its public ad library ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns the full details of one ad: copy, headline, CTA, landing page, media URLs, transcription, platforms, niches, live status and the Open in Foreplay link. Pass the public ad library ID: the adId field of any ad list item (not the id field, which is the Foreplay internal id and is not accepted here). Costs 1 credit.',+ idempotent: true,+ },+ outputSchema: foreplayOutputSchemas.ad,+ props: {+ adId: Property.ShortText({ displayName: 'Public Ad ID', description: 'The adId field of an ad from search results (not the internal id).', required: true }),+ },+ async run({ auth, propsValue }) {+ const id = foreplayProps.foreplayId({ value: propsValue.adId, label: 'Public Ad ID' });+ const response = await foreplayClient.request({ auth, path: `/api/ad/${foreplayClient.pathId(id)}` });+ return foreplayMappers.single({ response, map: foreplayMappers.ad });+ },+});++export { getAd };diff --git a/packages/pieces/community/foreplay-co/src/lib/actions/ai/get-brand-analytics.ts b/packages/pieces/community/foreplay-co/src/lib/actions/ai/get-brand-analytics.tsnew file mode 100644index 00000000000..2385b8a698d--- /dev/null+++ b/packages/pieces/community/foreplay-co/src/lib/actions/ai/get-brand-analytics.ts@@ -0,0 +1,39 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { foreplayCoAuth } from '../../auth';+import { foreplayClient } from '../../common/client';+import { foreplayMappers } from '../../common/mappers';+import { foreplayOutputSchemas } from '../../common/output-schemas';+import { foreplayProps } from '../../common/props';++const getBrandAnalytics = createAction({+ auth: foreplayCoAuth,+ name: 'get_brand_analytics',+ classification: 'READ',+ displayName: 'Get Brand Analytics',+ description: 'Daily active/inactive ad counts and formats for a brand Facebook page.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns one row per day with the number of active and inactive ads and the ads per display format for a brand, i.e. its creative velocity. Pass the numeric Facebook page ID (the pageId field from search_brands; a Foreplay brand ID is rejected by the API), plus an optional date range (YYYY-MM-DD). Costs 1 credit per call.',+ idempotent: true,+ },+ outputSchema: foreplayOutputSchemas.analytics,+ props: {+ id: Property.ShortText({ displayName: 'Page ID', description: 'Numeric Facebook page ID, e.g. 373652569755921 (the pageId field of a brand).', required: true }),+ startDate: Property.ShortText({ displayName: 'Start Date', description: 'YYYY-MM-DD, inclusive.', required: false }),+ endDate: Property.ShortText({ displayName: 'End Date', description: 'YYYY-MM-DD, inclusive.', required: false }),+ },+ async run({ auth, propsValue }) {+ const startDate = foreplayProps.dayOnly({ value: propsValue.startDate, label: 'Start Date' });+ const endDate = foreplayProps.dayOnly({ value: propsValue.endDate, label: 'End Date' });+ if (startDate !== undefined && endDate !== undefined && startDate > endDate) throw new Error('Start Date must be on or before End Date.');+ const response = await foreplayClient.request({+ auth,+ path: '/api/brand/analytics',+ query: { id: foreplayProps.pageId({ value: propsValue.id, label: 'Page ID' }), start_date: startDate, end_date: endDate },+ });+ const items = foreplayMappers.listOf(response.body).map(foreplayMappers.analyticsRow);+ return { items, count: items.length, ...foreplayMappers.credits(response) };+ },+});++export { getBrandAnalytics };diff --git a/packages/pieces/community/foreplay-co/src/lib/actions/ai/get-credit-usage.ts b/packages/pieces/community/foreplay-co/src/lib/actions/ai/get-credit-usage.tsnew file mode 100644index 00000000000..4dcff617a5d--- /dev/null+++ b/packages/pieces/community/foreplay-co/src/lib/actions/ai/get-credit-usage.ts@@ -0,0 +1,26 @@+import { createAction } from '@activepieces/pieces-framework';+import { foreplayCoAuth } from '../../auth';+import { foreplayClient } from '../../common/client';+import { foreplayMappers } from '../../common/mappers';+import { foreplayOutputSchemas } from '../../common/output-schemas';++const getCreditUsage = createAction({+ auth: foreplayCoAuth,+ name: 'get_credit_usage',+ classification: 'READ',+ displayName: 'Get Credit Usage',+ description: 'Show total and remaining Foreplay API credits for this billing period.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns the Foreplay API credits for the current billing period: total, remaining, used, and the period start and end. Free (costs no credits); call it before large ad pulls, which cost 1 credit per ad.',+ idempotent: true,+ },+ outputSchema: foreplayOutputSchemas.usage,+ props: {},+ async run({ auth }) {+ const response = await foreplayClient.request({ auth, path: '/api/usage' });+ return foreplayMappers.usage(foreplayMappers.dataOf(response.body));+ },+});++export { getCreditUsage };diff --git a/packages/pieces/community/foreplay-co/src/lib/actions/ai/get-lens-report.ts b/packages/pieces/community/foreplay-co/src/lib/actions/ai/get-lens-report.tsnew file mode 100644index 00000000000..ddfe4aad13f--- /dev/null+++ b/packages/pieces/community/foreplay-co/src/lib/actions/ai/get-lens-report.ts@@ -0,0 +1,65 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { foreplayCoAuth } from '../../auth';+import { foreplayClient } from '../../common/client';+import { foreplayMappers } from '../../common/mappers';+import { foreplayOutputSchemas } from '../../common/output-schemas';+import { foreplayProps } from '../../common/props';++const BREAKDOWNS = ['overall', 'country', 'age,gender', 'user_segment_key', 'publisher_platform,platform_position'];+const PROVIDERS = ['facebook', 'tiktok'];+const WINDOWS = ['1d', '7d', '28d'];++const getLensReport = createAction({+ auth: foreplayCoAuth,+ name: 'get_lens_report',+ classification: 'READ',+ displayName: 'Get Lens Report',+ description: 'Get reporting rows from a Foreplay Lens.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns ad-account reporting rows (core metrics, actions, action values) from a Foreplay Lens for a date range, broken down by overall, country, "age,gender", user_segment_key or "publisher_platform,platform_position", for provider facebook or tiktok. Attribution windows 1d/7d/28d (click default 7d, view default 1d). Up to 10 rows per page; when hasMore is true call again with page set to nextPage. Costs 1 credit per call.',+ idempotent: true,+ },+ outputSchema: foreplayOutputSchemas.lensReport,+ props: {+ lensId: Property.ShortText({ displayName: 'Lens ID', required: true }),+ from: Property.ShortText({ displayName: 'From', description: 'YYYY-MM-DD', required: true }),+ to: Property.ShortText({ displayName: 'To', description: 'YYYY-MM-DD', required: true }),+ breakdownType: Property.StaticDropdown({ displayName: 'Breakdown', required: true, options: { options: BREAKDOWNS.map((b) => ({ label: b, value: b })) } }),+ provider: Property.StaticDropdown({ displayName: 'Provider', required: true, options: { options: [{ label: 'Facebook', value: 'facebook' }, { label: 'TikTok', value: 'tiktok' }] } }),+ attrClick: Property.StaticDropdown({ displayName: 'Click Attribution', required: false, options: { options: WINDOWS.map((w) => ({ label: w, value: w })) } }),+ attrView: Property.StaticDropdown({ displayName: 'View Attribution', required: false, options: { options: WINDOWS.map((w) => ({ label: w, value: w })) } }),+ page: Property.Number({ displayName: 'Page', description: '1-based, default 1.', required: false }),+ limit: Property.Number({ displayName: 'Limit', description: '1 to 10, default 10.', required: false }),+ },+ async run({ auth, propsValue }) {+ const from = foreplayProps.dayOnly({ value: propsValue.from, label: 'From' });+ const to = foreplayProps.dayOnly({ value: propsValue.to, label: 'To' });+ if (from === undefined || to === undefined) throw new Error('From and To are required.');+ if (from > to) throw new Error('From must be on or before To.');+ const page = foreplayProps.parseInteger({ value: propsValue.page, label: 'Page', min: 1, max: 100_000 }) ?? 1;+ const limit = foreplayProps.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 10 }) ?? 10;+ const response = await foreplayClient.request({+ auth,+ path: '/api/lens/reporting',+ query: {+ lens_id: foreplayProps.foreplayId({ value: propsValue.lensId, label: 'Lens ID' }),+ from,+ to,+ breakdown_type: foreplayProps.enumValue({ value: propsValue.breakdownType, label: 'Breakdown', allowed: BREAKDOWNS }),+ provider: foreplayProps.enumValue({ value: propsValue.provider, label: 'Provider', allowed: PROVIDERS }),+ attr_click: foreplayProps.enumValue({ value: propsValue.attrClick, label: 'Click Attribution', allowed: WINDOWS }),+ attr_view: foreplayProps.enumValue({ value: propsValue.attrView, label: 'View Attribution', allowed: WINDOWS }),+ page,+ limit,+ },+ });+ const items = foreplayMappers.listOf(response.body).filter(foreplayClient.isRecord);+ const meta = foreplayMappers.metadataOf(response.body);+ const pages = foreplayMappers.num(meta['pages']);+ const hasMore = items.length > 0 && (pages !== null ? page < pages : items.length >= limit);+ return { items, count: items.length, total: foreplayMappers.num(meta['count']), page, hasMore, nextPage: hasMore ? page + 1 : null, ...foreplayMappers.credits(response) };+ },+});++export { getLensReport };diff --git a/packages/pieces/community/foreplay-co/src/lib/actions/ai/get-spyder-brand.ts b/packages/pieces/community/foreplay-co/src/lib/actions/ai/get-spyder-brand.tsnew file mode 100644index 00000000000..9e802ad6a6c--- /dev/null+++ b/packages/pieces/community/foreplay-co/src/lib/actions/ai/get-spyder-brand.ts@@ -0,0 +1,33 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { foreplayCoAuth } from '../../auth';+import { foreplayClient } from '../../common/client';+import { foreplayMappers } from '../../common/mappers';+import { foreplayOutputSchemas } from '../../common/output-schemas';+import { foreplayProps } from '../../common/props';++const getSpyderBrand = createAction({+ auth: foreplayCoAuth,+ name: 'get_spyder_brand',+ classification: 'READ',+ displayName: 'Get Spyder Brand',+ description: 'Get one brand from your Spyder watchlist.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns one brand from the user\'s Spyder watchlist by Foreplay brand ID (from List Spyder Brands). Fails with 403/404 if the brand is not tracked. Costs 1 credit.',+ idempotent: true,+ },+ outputSchema: foreplayOutputSchemas.brand,+ props: {+ brandId: Property.ShortText({ displayName: 'Brand ID', required: true }),+ },+ async run({ auth, propsValue }) {+ const response = await foreplayClient.request({+ auth,+ path: '/api/spyder/brand',+ query: { brand_id: foreplayProps.foreplayId({ value: propsValue.brandId, label: 'Brand ID' }) },+ });+ return foreplayMappers.single({ response, map: foreplayMappers.brand });+ },+});++export { getSpyderBrand };diff --git a/packages/pieces/community/foreplay-co/src/lib/actions/ai/get-spyder-top-ads.ts b/packages/pieces/community/foreplay-co/src/lib/actions/ai/get-spyder-top-ads.tsnew file mode 100644index 00000000000..5aa267986d7--- /dev/null+++ b/packages/pieces/community/foreplay-co/src/lib/actions/ai/get-spyder-top-ads.ts@@ -0,0 +1,52 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { foreplayCoAuth } from '../../auth';+import { foreplayClient } from '../../common/client';+import { foreplayMappers } from '../../common/mappers';+import { foreplayOutputSchemas } from '../../common/output-schemas';+import { foreplayProps } from '../../common/props';++function today(): string {+ return new Date().toISOString().slice(0, 10);+}++const getSpyderTopAds = createAction({+ auth: foreplayCoAuth,+ name: 'get_spyder_top_ads',+ classification: 'READ',+ displayName: 'Get Spyder Top Ads',+ description: 'Top-ranked ads of a tracked page compared with an earlier date.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns the top-ranked ads of a page on the user\'s Spyder watchlist with their rank now and N days ago (compareDaysAgo, default 7), so you can say which ads climbed or dropped. Takes the numeric Facebook page ID (pageId from List Spyder Brands) and an anchor date (YYYY-MM-DD, default today UTC). Fails with 403 if the page is not tracked in Spyder. Costs 1 credit.',+ idempotent: true,+ },+ outputSchema: foreplayOutputSchemas.topAds,+ props: {+ pageId: Property.ShortText({ displayName: 'Facebook Page ID', required: true }),+ date: Property.ShortText({ displayName: 'Date', description: 'YYYY-MM-DD, default today (UTC).', required: false }),+ compareDaysAgo: Property.Number({ displayName: 'Compare With (days ago)', description: '1 to 365, default 7.', required: false }),+ },+ async run({ auth, propsValue }) {+ const pageId = foreplayProps.pageId({ value: propsValue.pageId, label: 'Facebook Page ID' });+ const response = await foreplayClient.request({+ auth,+ path: `/api/spyder/brand/rankings/${foreplayClient.pathId(pageId)}/top-overview`,+ query: {+ date: foreplayProps.dayOnly({ value: propsValue.date, label: 'Date' }) ?? today(),+ compareDaysAgo: foreplayProps.parseInteger({ value: propsValue.compareDaysAgo, label: 'Compare With (days ago)', min: 1, max: 365 }) ?? 7,+ },+ });+ const data = foreplayMappers.recordOf(foreplayMappers.dataOf(response.body));+ const items = foreplayMappers.arrayOf(data['ads']).map(foreplayMappers.rankedAd);+ return {+ pageId: foreplayMappers.str(data['pageId']) ?? foreplayMappers.str(data['page_id']) ?? pageId,+ date: foreplayMappers.str(data['date']),+ compareDaysAgo: foreplayMappers.num(data['compareDaysAgo']) ?? foreplayMappers.num(data['compare_days_ago']),+ items,+ count: items.length,+ ...foreplayMappers.credits(response),+ };+ },+});++export { getSpyderTopAds };diff --git a/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-ad-duplicates.ts b/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-ad-duplicates.tsnew file mode 100644index 00000000000..c518cdf3a0b--- /dev/null+++ b/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-ad-duplicates.ts@@ -0,0 +1,36 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { foreplayCoAuth } from '../../auth';+import { foreplayClient } from '../../common/client';+import { foreplayMappers } from '../../common/mappers';+import { foreplayOutputSchemas } from '../../common/output-schemas';+import { foreplayProps } from '../../common/props';++const INTERNAL_ID_PATTERN = /^[A-Za-z0-9]{20}$/;++const listAdDuplicates = createAction({+ auth: foreplayCoAuth,+ name: 'list_ad_duplicates',+ classification: 'SEARCH',+ displayName: 'List Ad Duplicates',+ description: 'Find ads that reuse the same image or video as a given ad.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns every ad in the Foreplay index that uses the same image or video as the given ad (the same creative reused across placements or brands). Pass the public ad library ID: the adId field of any ad list item (not the id field; an internal id returns an empty list). The result includes the given ad itself. Costs 1 credit per ad returned and has no limit parameter, so use it only when creative reuse matters.',+ idempotent: true,+ },+ outputSchema: foreplayOutputSchemas.adList,+ props: {+ adId: Property.ShortText({ displayName: 'Public Ad ID', description: 'The adId field of an ad from search results (not the internal id).', required: true }),+ },+ async run({ auth, propsValue }) {+ const id = foreplayProps.foreplayId({ value: propsValue.adId, label: 'Public Ad ID' });+ if (INTERNAL_ID_PATTERN.test(id) && !/^\d+$/.test(id)) {+ throw new Error('This looks like a Foreplay internal id. List Ad Duplicates needs the public ad library ID (the adId field of search results).');+ }+ const response = await foreplayClient.request({ auth, path: `/api/ad/duplicates/${foreplayClient.pathId(id)}` });+ const items = foreplayMappers.listOf(response.body).map(foreplayMappers.ad);+ return { items, count: items.length, ...foreplayMappers.credits(response) };+ },+});++export { listAdDuplicates };diff --git a/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-board-ads.ts b/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-board-ads.tsnew file mode 100644index 00000000000..815848d22da--- /dev/null+++ b/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-board-ads.ts@@ -0,0 +1,44 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { foreplayCoAuth } from '../../auth';+import { foreplayClient } from '../../common/client';+import { foreplayMappers } from '../../common/mappers';+import { foreplayOutputSchemas } from '../../common/output-schemas';+import { foreplayProps } from '../../common/props';++const listBoardAds = createAction({+ auth: foreplayCoAuth,+ name: 'list_board_ads',+ classification: 'SEARCH',+ displayName: 'List Board Ads',+ description: 'List the ads saved in a board.',+ audience: 'ai',+ aiMetadata: {+ description: 'Lists ads saved in one board (board ID from List Boards) with optional filters. Costs 1 credit per ad returned (default limit 10, max 250). When hasMore is true call again with cursor set to nextCursor.',+ idempotent: true,+ },+ outputSchema: foreplayOutputSchemas.adCursorPage,+ props: {+ boardId: Property.ShortText({ displayName: 'Board ID', required: true }),+ ...foreplayProps.aiAdFilterProps(),+ order: foreplayProps.sortOrderProp(),+ limit: Property.Number({ displayName: 'Limit', description: '1 to 250, default 10. 1 credit per ad returned.', required: false }),+ cursor: Property.ShortText({ displayName: 'Cursor', description: 'nextCursor from the previous page.', required: false }),+ },+ async run({ auth, propsValue }) {+ const limit = foreplayProps.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 250 }) ?? 10;+ const response = await foreplayClient.request({+ auth,+ path: '/api/board/ads',+ query: {+ board_id: foreplayProps.foreplayId({ value: propsValue.boardId, label: 'Board ID' }),+ ...foreplayProps.adFilterQuery(foreplayProps.aiAdFilterInput(propsValue)),+ order: foreplayProps.enumValue({ value: propsValue.order, label: 'Order', allowed: foreplayProps.SORT_ORDERS }),+ cursor: foreplayProps.optionalText(propsValue.cursor),+ limit,+ },+ });+ return foreplayMappers.cursorPage({ response, map: foreplayMappers.ad, limit });+ },+});++export { listBoardAds };diff --git a/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-board-brands.ts b/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-board-brands.tsnew file mode 100644index 00000000000..368eb760450--- /dev/null+++ b/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-board-brands.ts@@ -0,0 +1,37 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { foreplayCoAuth } from '../../auth';+import { foreplayClient } from '../../common/client';+import { foreplayMappers } from '../../common/mappers';+import { foreplayOutputSchemas } from '../../common/output-schemas';+import { foreplayProps } from '../../common/props';++const listBoardBrands = createAction({+ auth: foreplayCoAuth,+ name: 'list_board_brands',+ classification: 'SEARCH',+ displayName: 'List Board Brands',+ description: 'List the brands saved in a board.',+ audience: 'ai',+ aiMetadata: {+ description: 'Lists the brands whose ads are saved in one board (board ID from List Boards), up to 10 per page. When hasMore is true call again with offset set to nextOffset. Costs 1 credit per call.',+ idempotent: true,+ },+ outputSchema: foreplayOutputSchemas.brandOffsetPage,+ props: {+ boardId: Property.ShortText({ displayName: 'Board ID', required: true }),+ limit: Property.Number({ displayName: 'Limit', description: '1 to 10, default 10.', required: false }),+ offset: Property.Number({ displayName: 'Offset', description: 'nextOffset from the previous page.', required: false }),+ },+ async run({ auth, propsValue }) {+ const limit = foreplayProps.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 10 }) ?? 10;+ const offset = foreplayProps.parseInteger({ value: propsValue.offset, label: 'Offset', min: 0, max: Number.MAX_SAFE_INTEGER }) ?? 0;+ const response = await foreplayClient.request({+ auth,+ path: '/api/board/brands',+ query: { board_id: foreplayProps.foreplayId({ value: propsValue.boardId, label: 'Board ID' }), limit, offset },+ });+ return foreplayMappers.offsetPage({ response, map: foreplayMappers.brand, limit, offset });+ },+});++export { listBoardBrands };diff --git a/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-boards.ts b/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-boards.tsnew file mode 100644index 00000000000..c6d33ba8a92--- /dev/null+++ b/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-boards.ts@@ -0,0 +1,27 @@+import { createAction } from '@activepieces/pieces-framework';+import { foreplayCoAuth } from '../../auth';+import { foreplayClient } from '../../common/client';+import { foreplayMappers } from '../../common/mappers';+import { foreplayOutputSchemas } from '../../common/output-schemas';++const listBoards = createAction({+ auth: foreplayCoAuth,+ name: 'list_boards',+ classification: 'SEARCH',+ displayName: 'List Boards',+ description: 'List all boards in your Foreplay account.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns every board the Foreplay user or team can access (ID, name, description, created date) in one call. Use the board ID with List Board Ads or List Board Brands. Costs 1 credit per call.',+ idempotent: true,+ },+ outputSchema: foreplayOutputSchemas.boardList,+ props: {},+ async run({ auth }) {+ const response = await foreplayClient.request({ auth, path: '/api/boards' });+ const items = foreplayMappers.listOf(response.body).map(foreplayMappers.board);+ return { items, count: items.length, ...foreplayMappers.credits(response) };+ },+});++export { listBoards };diff --git a/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-brand-ads.ts b/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-brand-ads.tsnew file mode 100644index 00000000000..d2408bf5356--- /dev/null+++ b/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-brand-ads.ts@@ -0,0 +1,49 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { foreplayCoAuth } from '../../auth';+import { foreplayClient } from '../../common/client';+import { foreplayMappers } from '../../common/mappers';+import { foreplayOutputSchemas } from '../../common/output-schemas';+import { foreplayProps } from '../../common/props';++const listBrandAds = createAction({+ auth: foreplayCoAuth,+ name: 'list_brand_ads',+ classification: 'SEARCH',+ displayName: 'List Brand Ads',+ description: 'List ads for one or more Foreplay brand IDs.',+ audience: 'ai',+ aiMetadata: {+ description: 'Lists ads of one or more brands by Foreplay brand ID (id field from Search Brands or Find Brands by Domain), with optional filters. Costs 1 credit per ad returned (default limit 10, max 250). If empty because the brand is not indexed yet, call again with collectIfEmpty true (waits up to ~30 s). When hasMore is true call again with cursor set to nextCursor.',+ idempotent: true,+ },+ outputSchema: foreplayOutputSchemas.adCursorPage,+ props: {+ brandIds: Property.Array({ displayName: 'Brand IDs', required: true }),+ ...foreplayProps.aiAdFilterProps(),+ order: foreplayProps.sortOrderProp(),+ collectIfEmpty: Property.Checkbox({ displayName: 'Collect If Empty', description: 'Fetch from Meta when nothing is cached (waits up to ~30 s).', required: false, defaultValue: false }),+ limit: Property.Number({ displayName: 'Limit', description: '1 to 250, default 10. 1 credit per ad returned.', required: false }),+ cursor: Property.ShortText({ displayName: 'Cursor', description: 'nextCursor from the previous page.', required: false }),+ },+ async run({ auth, propsValue }) {+ const brandIds = (foreplayProps.stringList({ value: propsValue.brandIds, label: 'Brand IDs' }) ?? []).map((value) => foreplayProps.foreplayId({ value, label: 'Brand ID' }));+ if (brandIds.length === 0) throw new Error('Brand IDs is required.');+ if (brandIds.length > 50) throw new Error('Pass at most 50 brand IDs per call.');+ const limit = foreplayProps.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 250 }) ?? 10;+ const response = await foreplayClient.request({+ auth,+ path: '/api/brand/getAdsByBrandId',+ query: {+ brand_ids: brandIds,+ ...foreplayProps.adFilterQuery(foreplayProps.aiAdFilterInput(propsValue)),+ order: foreplayProps.enumValue({ value: propsValue.order, label: 'Order', allowed: foreplayProps.SORT_ORDERS }),+ collect: propsValue.collectIfEmpty === true ? true : undefined,+ cursor: foreplayProps.optionalText(propsValue.cursor),+ limit,+ },+ });+ return foreplayMappers.cursorPage({ response, map: foreplayMappers.ad, limit });+ },+});++export { listBrandAds };diff --git a/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-page-ads.ts b/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-page-ads.tsnew file mode 100644index 00000000000..d75cad1ce3b--- /dev/null+++ b/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-page-ads.ts@@ -0,0 +1,46 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { foreplayCoAuth } from '../../auth';+import { foreplayClient } from '../../common/client';+import { foreplayMappers } from '../../common/mappers';+import { foreplayOutputSchemas } from '../../common/output-schemas';+import { foreplayProps } from '../../common/props';++const listPageAds = createAction({+ auth: foreplayCoAuth,+ name: 'list_page_ads',+ classification: 'SEARCH',+ displayName: 'List Page Ads',+ description: 'List the ads of one Facebook page.',+ audience: 'ai',+ aiMetadata: {+ description: 'Lists ads run by one advertiser, identified by its numeric Facebook page ID (the pageId field of a brand), with optional filters. Costs 1 credit per ad returned (default limit 10, max 250). If the result is empty because Foreplay has not indexed the page yet, call again with collectIfEmpty true: Foreplay then fetches from Meta and the call can take about 30 seconds. When hasMore is true call again with cursor set to nextCursor.',+ idempotent: true,+ },+ outputSchema: foreplayOutputSchemas.adCursorPage,+ props: {+ pageId: Property.ShortText({ displayName: 'Facebook Page ID', description: 'Numeric page ID.', required: true }),+ ...foreplayProps.aiAdFilterProps(),+ order: foreplayProps.sortOrderProp(),+ collectIfEmpty: Property.Checkbox({ displayName: 'Collect If Empty', description: 'Fetch from Meta when nothing is cached (waits up to ~30 s).', required: false, defaultValue: false }),+ limit: Property.Number({ displayName: 'Limit', description: '1 to 250, default 10. 1 credit per ad returned.', required: false }),+ cursor: Property.ShortText({ displayName: 'Cursor', description: 'nextCursor from the previous page.', required: false }),+ },+ async run({ auth, propsValue }) {+ const limit = foreplayProps.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 250 }) ?? 10;+ const response = await foreplayClient.request({+ auth,+ path: '/api/brand/getAdsByPageId',+ query: {+ page_id: foreplayProps.pageId({ value: propsValue.pageId, label: 'Facebook Page ID' }),+ ...foreplayProps.adFilterQuery(foreplayProps.aiAdFilterInput(propsValue)),+ order: foreplayProps.enumValue({ value: propsValue.order, label: 'Order', allowed: foreplayProps.SORT_ORDERS }),+ collect: propsValue.collectIfEmpty === true ? true : undefined,+ cursor: foreplayProps.optionalText(propsValue.cursor),+ limit,+ },+ });+ return foreplayMappers.cursorPage({ response, map: foreplayMappers.ad, limit });+ },+});++export { listPageAds };diff --git a/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-spyder-brand-ads.ts b/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-spyder-brand-ads.tsnew file mode 100644index 00000000000..6e356cc9840--- /dev/null+++ b/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-spyder-brand-ads.ts@@ -0,0 +1,44 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { foreplayCoAuth } from '../../auth';+import { foreplayClient } from '../../common/client';+import { foreplayMappers } from '../../common/mappers';+import { foreplayOutputSchemas } from '../../common/output-schemas';+import { foreplayProps } from '../../common/props';++const listSpyderBrandAds = createAction({+ auth: foreplayCoAuth,+ name: 'list_spyder_brand_ads',+ classification: 'SEARCH',+ displayName: 'List Spyder Brand Ads',+ description: 'List ads of a brand you track in Spyder.',+ audience: 'ai',+ aiMetadata: {+ description: 'Lists ads of one brand on the user\'s Spyder watchlist (brand ID from List Spyder Brands), newest first by default, with optional filters. Costs 1 credit per ad returned (default limit 10, max 250). When hasMore is true call again with cursor set to nextCursor.',+ idempotent: true,+ },+ outputSchema: foreplayOutputSchemas.adCursorPage,+ props: {+ brandId: Property.ShortText({ displayName: 'Brand ID', required: true }),+ ...foreplayProps.aiAdFilterProps(),+ order: foreplayProps.sortOrderProp(),+ limit: Property.Number({ displayName: 'Limit', description: '1 to 250, default 10. 1 credit per ad returned.', required: false }),+ cursor: Property.ShortText({ displayName: 'Cursor', description: 'nextCursor from the previous page.', required: false }),+ },+ async run({ auth, propsValue }) {+ const limit = foreplayProps.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 250 }) ?? 10;+ const response = await foreplayClient.request({+ auth,+ path: '/api/spyder/brand/ads',+ query: {+ brand_id: foreplayProps.foreplayId({ value: propsValue.brandId, label: 'Brand ID' }),+ ...foreplayProps.adFilterQuery(foreplayProps.aiAdFilterInput(propsValue)),+ order: foreplayProps.enumValue({ value: propsValue.order, label: 'Order', allowed: foreplayProps.SORT_ORDERS }),+ cursor: foreplayProps.optionalText(propsValue.cursor),+ limit,+ },+ });+ return foreplayMappers.cursorPage({ response, map: foreplayMappers.ad, limit });+ },+});++export { listSpyderBrandAds };diff --git a/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-spyder-brands.ts b/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-spyder-brands.tsnew file mode 100644index 00000000000..b87257861da--- /dev/null+++ b/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-spyder-brands.ts@@ -0,0 +1,32 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { foreplayCoAuth } from '../../auth';+import { foreplayClient } from '../../common/client';+import { foreplayMappers } from '../../common/mappers';+import { foreplayOutputSchemas } from '../../common/output-schemas';+import { foreplayProps } from '../../common/props';++const listSpyderBrands = createAction({+ auth: foreplayCoAuth,+ name: 'list_spyder_brands',+ classification: 'SEARCH',+ displayName: 'List Spyder Brands',+ description: 'List the brands you track in Spyder.',+ audience: 'ai',+ aiMetadata: {+ description: 'Lists brands on the user\'s Spyder watchlist, 10 per page. The brand ID works with Get Spyder Brand and List Spyder Brand Ads; the pageId works with the Spyder ranking actions. When hasMore is true call again with offset set to nextOffset. Costs 1 credit per call.',+ idempotent: true,+ },+ outputSchema: foreplayOutputSchemas.brandOffsetPage,+ props: {+ limit: Property.Number({ displayName: 'Limit', description: '1 to 10, default 10.', required: false }),+ offset: Property.Number({ displayName: 'Offset', description: 'nextOffset from the previous page.', required: false }),+ },+ async run({ auth, propsValue }) {+ const limit = foreplayProps.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 10 }) ?? 10;+ const offset = foreplayProps.parseInteger({ value: propsValue.offset, label: 'Offset', min: 0, max: Number.MAX_SAFE_INTEGER }) ?? 0;+ const response = await foreplayClient.request({ auth, path: '/api/spyder/brands', query: { limit, offset } });+ return foreplayMappers.offsetPage({ response, map: foreplayMappers.brand, limit, offset });+ },+});++export { listSpyderBrands };diff --git a/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-spyder-ranked-ads.ts b/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-spyder-ranked-ads.tsnew file mode 100644index 00000000000..76e32d6cd33--- /dev/null+++ b/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-spyder-ranked-ads.ts@@ -0,0 +1,59 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { foreplayCoAuth } from '../../auth';+import { foreplayClient } from '../../common/client';+import { foreplayMappers } from '../../common/mappers';+import { foreplayOutputSchemas } from '../../common/output-schemas';+import { foreplayProps } from '../../common/props';++const CATEGORIES = ['all', 'breakout', 'evergreen'];++const listSpyderRankedAds = createAction({+ auth: foreplayCoAuth,+ name: 'list_spyder_ranked_ads',+ classification: 'SEARCH',+ displayName: 'List Spyder Ranked Ads',+ description: 'Ranked ads of a tracked page, filtered to breakout or evergreen.',+ audience: 'ai',+ aiMetadata: {+ description: 'Lists the ranked ads of a page on the user\'s Spyder watchlist, one page at a time, with each ad\'s rank, previous rank, peak rank and days running. category: all (default), breakout (fast risers) or evergreen (long-running performers). Takes the numeric Facebook page ID. When hasMore is true call again with offset set to nextOffset. Fails with 403 if the page is not tracked. Costs 1 credit per call.',+ idempotent: true,+ },+ outputSchema: foreplayOutputSchemas.rankedAds,+ props: {+ pageId: Property.ShortText({ displayName: 'Facebook Page ID', required: true }),+ category: Property.StaticDropdown({ displayName: 'Category', required: false, options: { options: [{ label: 'All', value: 'all' }, { label: 'Breakout', value: 'breakout' }, { label: 'Evergreen', value: 'evergreen' }] } }),+ limit: Property.Number({ displayName: 'Limit', description: '1 to 100, default 20.', required: false }),+ offset: Property.Number({ displayName: 'Offset', description: 'nextOffset from the previous page.', required: false }),+ },+ async run({ auth, propsValue }) {+ const pageId = foreplayProps.pageId({ value: propsValue.pageId, label: 'Facebook Page ID' });+ const limit = foreplayProps.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 100 }) ?? 20;+ const offset = foreplayProps.parseInteger({ value: propsValue.offset, label: 'Offset', min: 0, max: Number.MAX_SAFE_INTEGER }) ?? 0;+ const response = await foreplayClient.request({+ auth,+ path: `/api/spyder/brand/rankings/${foreplayClient.pathId(pageId)}/list`,+ query: { category: foreplayProps.enumValue({ value: propsValue.category, label: 'Category', allowed: CATEGORIES }), limit, offset },+ });+ const { recordOf, arrayOf, str, num } = foreplayMappers;+ const data = recordOf(foreplayMappers.dataOf(response.body));+ const items = arrayOf(data['ads']).map(foreplayMappers.rankedAd);+ const pagination = recordOf(data['pagination']);+ const total = num(pagination['total']);+ const hasMore = pagination['hasMore'] === true || pagination['has_more'] === true || (total !== null && offset + items.length < total);+ const counts = data['counts'];+ return {+ pageId: str(data['pageId']) ?? str(data['page_id']) ?? pageId,+ date: str(data['date']),+ category: str(data['category']),+ items,+ count: items.length,+ total,+ hasMore: hasMore && items.length > 0,+ nextOffset: hasMore && items.length > 0 ? offset + items.length : null,+ counts: foreplayClient.isRecord(counts) ? counts : null,+ ...foreplayMappers.credits(response),+ };+ },+});++export { listSpyderRankedAds };diff --git a/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-spyder-related-pages.ts b/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-spyder-related-pages.tsnew file mode 100644index 00000000000..d59b23ac1e8--- /dev/null+++ b/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-spyder-related-pages.ts@@ -0,0 +1,40 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { foreplayCoAuth } from '../../auth';+import { foreplayClient } from '../../common/client';+import { foreplayMappers } from '../../common/mappers';+import { foreplayOutputSchemas } from '../../common/output-schemas';+import { foreplayProps } from '../../common/props';++const listSpyderRelatedPages = createAction({+ auth: foreplayCoAuth,+ name: 'list_spyder_related_pages',+ classification: 'SEARCH',+ displayName: 'List Spyder Related Pages',+ description: 'Pages and brands often seen alongside a tracked page (lookalikes, competitors).',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns pages/brands frequently seen alongside a page on the user\'s Spyder watchlist, useful for competitor and lookalike research. Each result has the page ID, name, Foreplay brand ID, likes and ad counts. Takes the numeric Facebook page ID; limit 1 to 50 (default 5). Fails with 403 if the page is not tracked. Costs 1 credit.',+ idempotent: true,+ },+ outputSchema: foreplayOutputSchemas.relatedPages,+ props: {+ pageId: Property.ShortText({ displayName: 'Facebook Page ID', required: true }),+ limit: Property.Number({ displayName: 'Limit', description: '1 to 50, default 5.', required: false }),+ },+ async run({ auth, propsValue }) {+ const response = await foreplayClient.request({+ auth,+ path: '/api/spyder/brand/partners',+ query: {+ pageId: foreplayProps.pageId({ value: propsValue.pageId, label: 'Facebook Page ID' }),+ limit: foreplayProps.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 50 }) ?? 5,+ },+ });+ const data = foreplayMappers.dataOf(response.body);+ const rows = Array.isArray(data) ? data : foreplayMappers.arrayOf(foreplayMappers.recordOf(data)['results']);+ const items = rows.map(foreplayMappers.relatedPage);+ return { items, count: items.length, ...foreplayMappers.credits(response) };+ },+});++export { listSpyderRelatedPages };diff --git a/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-swipefile-ads.ts b/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-swipefile-ads.tsnew file mode 100644index 00000000000..318c759594f--- /dev/null+++ b/packages/pieces/community/foreplay-co/src/lib/actions/ai/list-swipefile-ads.ts@@ -0,0 +1,43 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { foreplayCoAuth } from '../../auth';+import { foreplayClient } from '../../common/client';+import { foreplayMappers } from '../../common/mappers';+import { foreplayOutputSchemas } from '../../common/output-schemas';+import { foreplayProps } from '../../common/props';++const listSwipefileAds = createAction({+ auth: foreplayCoAuth,+ name: 'list_swipefile_ads',+ classification: 'SEARCH',+ displayName: 'List Swipe File Ads',+ description: 'List the ads saved in your swipe file.',+ audience: 'ai',+ aiMetadata: {+ description: 'Lists ads the user saved to their Foreplay swipe file, newest saved first by default, with optional filters. Costs 1 credit per ad returned (default limit 10, max 250). When hasMore is true call again with offset set to nextOffset.',+ idempotent: true,+ },+ outputSchema: foreplayOutputSchemas.adOffsetPage,+ props: {+ ...foreplayProps.aiAdFilterProps(),+ order: foreplayProps.sortOrderProp({ allowed: foreplayProps.SWIPEFILE_ORDERS }),+ limit: Property.Number({ displayName: 'Limit', description: '1 to 250, default 10. 1 credit per ad returned.', required: false }),+ offset: Property.Number({ displayName: 'Offset', description: 'nextOffset from the previous page.', required: false }),+ },+ async run({ auth, propsValue }) {+ const limit = foreplayProps.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 250 }) ?? 10;+ const offset = foreplayProps.parseInteger({ value: propsValue.offset, label: 'Offset', min: 0, max: Number.MAX_SAFE_INTEGER }) ?? 0;+ const response = await foreplayClient.request({+ auth,+ path: '/api/swipefile/ads',+ query: {+ ...foreplayProps.adFilterQuery(foreplayProps.aiAdFilterInput(propsValue)),+ order: foreplayProps.enumValue({ value: propsValue.order, label: 'Order', allowed: foreplayProps.SWIPEFILE_ORDERS }),+ limit,+ offset,+ },+ });+ return foreplayMappers.offsetPage({ response, map: foreplayMappers.ad, limit, offset });+ },+});++export { listSwipefileAds };diff --git a/packages/pieces/community/foreplay-co/src/lib/actions/ai/search-ads.ts b/packages/pieces/community/foreplay-co/src/lib/actions/ai/search-ads.tsnew file mode 100644index 00000000000..756230007cc--- /dev/null+++ b/packages/pieces/community/foreplay-co/src/lib/actions/ai/search-ads.ts@@ -0,0 +1,44 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { foreplayCoAuth } from '../../auth';+import { foreplayClient } from '../../common/client';+import { foreplayMappers } from '../../common/mappers';+import { foreplayOutputSchemas } from '../../common/output-schemas';+import { foreplayProps } from '../../common/props';++const searchAds = createAction({+ auth: foreplayCoAuth,+ name: 'search_ads',+ classification: 'SEARCH',+ displayName: 'Search Ads',+ description: 'Search the Foreplay ad library with text and filters.',+ audience: 'ai',+ aiMetadata: {+ description: 'Searches the whole Foreplay ad index (all advertisers) by free text in the ad name or copy, with optional filters: date range, live status, display format, platform, niche, market target, language, video length and running days. Costs 1 Foreplay credit per ad returned, so keep limit small (default 10, max 250). Returns one page; when hasMore is true call again with cursor set to nextCursor. To list ads of one known advertiser use List Page Ads or List Brand Ads instead.',+ idempotent: true,+ },+ outputSchema: foreplayOutputSchemas.adCursorPage,+ props: {+ query: Property.ShortText({ displayName: 'Search Text', description: 'Words in the ad name or copy. Empty = filters only.', required: false }),+ ...foreplayProps.aiAdFilterProps(),+ order: foreplayProps.sortOrderProp(),+ limit: Property.Number({ displayName: 'Limit', description: '1 to 250, default 10. 1 credit per ad returned.', required: false }),+ cursor: Property.ShortText({ displayName: 'Cursor', description: 'nextCursor from the previous page.', required: false }),+ },+ async run({ auth, propsValue }) {+ const limit = foreplayProps.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 250 }) ?? 10;+ const response = await foreplayClient.request({+ auth,+ path: '/api/discovery/ads',+ query: {+ query: foreplayProps.optionalText(propsValue.query),+ ...foreplayProps.adFilterQuery(foreplayProps.aiAdFilterInput(propsValue)),+ order: foreplayProps.enumValue({ value: propsValue.order, label: 'Order', allowed: foreplayProps.SORT_ORDERS }),+ cursor: foreplayProps.optionalText(propsValue.cursor),+ limit,+ },+ });+ return foreplayMappers.cursorPage({ response, map: foreplayMappers.ad, limit });+ },+});++export { searchAds };diff --git a/packages/pieces/community/foreplay-co/src/lib/actions/ai/search-brands.ts b/packages/pieces/community/foreplay-co/src/lib/actions/ai/search-brands.tsnew file mode 100644index 00000000000..e524cf5ac2b--- /dev/null+++ b/packages/pieces/community/foreplay-co/src/lib/actions/ai/search-brands.ts@@ -0,0 +1,47 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { foreplayCoAuth } from '../../auth';+import { foreplayClient } from '../../common/client';+import { foreplayMappers } from '../../common/mappers';+import { foreplayOutputSchemas } from '../../common/output-schemas';+import { foreplayProps } from '../../common/props';++const searchBrands = createAction({+ auth: foreplayCoAuth,+ name: 'search_brands',+ classification: 'SEARCH',+ displayName: 'Search Brands',+ description: 'Search Foreplay brands by name.',+ audience: 'ai',+ aiMetadata: {+ description: 'Finds brands in the Foreplay index by name (exact phrase first, then starts-with, then contains, ranked by popularity). Each brand has its Foreplay brand ID (for List Brand Ads), Facebook page ID (pageId, for List Page Ads), websites and ad counts. Brands with no indexed ads are hidden unless includeEmpty is true. Costs 1 credit per call regardless of results.',+ idempotent: true,+ },+ outputSchema: foreplayOutputSchemas.brandList,+ props: {+ query: Property.ShortText({ displayName: 'Brand Name', required: true }),+ limit: Property.Number({ displayName: 'Limit', description: '1 to 100, default 10.', required: false }),+ includeEmpty: Property.Checkbox({ displayName: 'Include Brands Without Ads', required: false, defaultValue: false }),+ minAds: Property.Number({ displayName: 'Min Ads', required: false }),+ maxAds: Property.Number({ displayName: 'Max Ads', required: false }),+ },+ async run({ auth, propsValue }) {+ const minAds = foreplayProps.parseInteger({ value: propsValue.minAds, label: 'Min Ads', min: 0, max: Number.MAX_SAFE_INTEGER });+ const maxAds = foreplayProps.parseInteger({ value: propsValue.maxAds, label: 'Max Ads', min: 0, max: Number.MAX_SAFE_INTEGER });+ if (minAds !== undefined && maxAds !== undefined && minAds > maxAds) throw new Error('Min Ads must not be greater than Max Ads.');+ const response = await foreplayClient.request({+ auth,+ path: '/api/discovery/brands',+ query: {+ query: foreplayProps.requiredText({ value: propsValue.query, label: 'Brand Name' }),+ limit: foreplayProps.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 100 }) ?? 10,+ include_empty: propsValue.includeEmpty === true ? true : undefined,+ min_ads: minAds,+ max_ads: maxAds,+ },+ });+ const items = foreplayMappers.listOf(response.body).map(foreplayMappers.brand);+ return { items, count: items.length, ...foreplayMappers.credits(response) };+ },+});++export { searchBrands };diff --git a/packages/pieces/community/foreplay-co/src/lib/actions/find-ads.ts b/packages/pieces/community/foreplay-co/src/lib/actions/find-ads.tsindex 1c2eb6fb547..87f79d197db 100644--- a/packages/pieces/community/foreplay-co/src/lib/actions/find-ads.ts+++ b/packages/pieces/community/foreplay-co/src/lib/actions/find-ads.ts@@ -1,111 +1,43 @@-import { createAction } from '@activepieces/pieces-framework';-import { foreplayCoApiCall } from '../common';-import { HttpMethod } from '@activepieces/pieces-common';-import { findAds as findAdsProperties } from '../properties';-import { findAdsSchema } from '../schemas';-import { foreplayCoAuth } from '../..';--export const findAds = createAction({+import { createAction, Property } from '@activepieces/pieces-framework';+import { foreplayCoAuth } from '../auth';+import { foreplayClient } from '../common/client';+import { foreplayMappers } from '../common/mappers';+import { foreplayOutputSchemas } from '../common/output-schemas';+import { foreplayProps } from '../common/props';++const findAds = createAction({auth: foreplayCoAuth,name: 'findAds',classification: 'SEARCH',displayName: 'Find Ads',- description:- 'Search and filter ads by text, dates, platforms, and categories.',- audience: 'both',- aiMetadata: { description: 'Search the Foreplay ad discovery library across all advertisers, optionally filtered by free-text query, date range, platform, display format, niche, market, language, and live-only status, with cursor pagination. With no query or filters it returns the broad feed; supply filters to narrow to matching ads. Use for cross-advertiser ad research rather than pulling ads for one known page. Read-only, so repeating the call is safe.', idempotent: true },- props: findAdsProperties(),+ description: 'Search and filter ads by text, dates, platforms, and categories. Costs 1 Foreplay credit per ad returned.',+ audience: 'human',+ aiMetadata: {+ description: 'Search the Foreplay ad library across all advertisers by free text and filters (dates, platform, format, niche, market, language, live status) with cursor pagination. Returns raw Foreplay ad objects. Costs 1 credit per ad returned.',+ idempotent: true,+ },+ outputSchema: foreplayOutputSchemas.rawAds,+ props: {+ query: Property.ShortText({ displayName: 'Search Query', description: 'Words in the ad name or copy. Leave empty to use filters only.', required: false }),+ ...foreplayProps.humanAdFilterProps(),+ order: foreplayProps.sortOrderProp(),+ cursor: Property.ShortText({ displayName: 'Cursor', description: 'Cursor from the previous response, for the next page.', required: false }),+ limit: Property.Number({ displayName: 'Limit', description: 'Ads per request (1 to 250). 1 credit per ad returned.', required: false, defaultValue: 10 }),+ },async run({ auth, propsValue }) {- // Validate props using Zod schema- const validation = findAdsSchema.safeParse(propsValue);- if (!validation.success) {- throw new Error(`Validation failed: ${validation.error.message}`);- }-- const values = propsValue;-- // Build query parameters properly handling arrays for API- const queryParams = new URLSearchParams();-- // Add optional parameters if provided- if (values['query']) {- queryParams.append('query', String(values['query']));- }- if (values['start_date']) {- queryParams.append('start_date', String(values['start_date']));- }- if (values['end_date']) {- queryParams.append('end_date', String(values['end_date']));- }- if (values['order']) {- queryParams.append('order', String(values['order']));- }- if (values['live']) {- queryParams.append('live', String(values['live']));- }-- // Handle array parameters - repeat parameter name for each value- if (values['display_format'] && values['display_format'].length > 0) {- values['display_format'].forEach((format: unknown) => {- queryParams.append('display_format', String(format));- });- }- if (- values['publisher_platform'] &&- values['publisher_platform'].length > 0- ) {- values['publisher_platform'].forEach((platform: unknown) => {- queryParams.append('publisher_platform', String(platform));- });- }- if (values['niches'] && values['niches'].length > 0) {- values['niches'].forEach((niche: unknown) => {- queryParams.append('niches', String(niche));- });- }- if (values['market_target'] && values['market_target'].length > 0) {- values['market_target'].forEach((target: unknown) => {- queryParams.append('market_target', String(target));- });- }- if (values['languages'] && values['languages'].length > 0) {- values['languages'].forEach((language: unknown) => {- queryParams.append('languages', String(language));- });- }-- if (values['cursor']) {- queryParams.append('cursor', String(values['cursor']));- }- if (values['limit']) {- queryParams.append('limit', String(values['limit']));- }-- // Build the full URL with query parameters manually to handle arrays properly- const queryString = queryParams.toString();- const fullUrl = queryString- ? `/api/discovery/ads?${queryString}`- : '/api/discovery/ads';-- const response = await foreplayCoApiCall({- apiKey: auth,- method: HttpMethod.GET,- resourceUri: fullUrl,+ const response = await foreplayClient.request({+ auth,+ path: '/api/discovery/ads',+ query: {+ query: foreplayProps.optionalText(propsValue.query),+ ...foreplayProps.adFilterQuery(foreplayProps.humanAdFilterInput(propsValue)),+ order: foreplayProps.enumValue({ value: propsValue.order, label: 'Order', allowed: foreplayProps.SORT_ORDERS }),+ cursor: foreplayProps.optionalText(propsValue.cursor),+ limit: foreplayProps.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 250 }),+ },});-- const responseBody = response.body;-- // Check if the response is successful- if (responseBody.metadata && responseBody.metadata.success === true) {- // Return just the ads data for clean automation workflows- return responseBody.data;- } else {- // Handle error responses by throwing an error- const errorMessage =- responseBody.error ||- responseBody.metadata?.message ||- 'Failed to find ads';- throw new Error(`Foreplay.co API Error: ${errorMessage}`);- }+ return foreplayMappers.listOf(response.body);},});++export { findAds };diff --git a/packages/pieces/community/foreplay-co/src/lib/actions/find-boards.ts b/packages/pieces/community/foreplay-co/src/lib/actions/find-boards.tsindex 1fea2b32e7b..fd337efb9b4 100644--- a/packages/pieces/community/foreplay-co/src/lib/actions/find-boards.ts+++ b/packages/pieces/community/foreplay-co/src/lib/actions/find-boards.ts@@ -1,57 +1,36 @@-import { createAction } from '@activepieces/pieces-framework';-import { foreplayCoApiCall } from '../common';-import { HttpMethod } from '@activepieces/pieces-common';-import { findBoards as findBoardsProperties } from '../properties';-import { findBoardsSchema } from '../schemas';-import { foreplayCoAuth } from '../..';+import { createAction, Property } from '@activepieces/pieces-framework';+import { foreplayCoAuth } from '../auth';+import { foreplayClient } from '../common/client';+import { foreplayMappers } from '../common/mappers';+import { foreplayOutputSchemas } from '../common/output-schemas';+import { foreplayProps } from '../common/props';-export const findBoards = createAction({+const findBoards = createAction({+ auth: foreplayCoAuth,name: 'findBoards',classification: 'SEARCH',displayName: 'Find Boards',- description: 'Get all boards for the authenticated user with pagination.',- audience: 'both',- aiMetadata: { description: 'List the saved ad boards belonging to the authenticated Foreplay account, with offset/limit pagination. Use to discover available board IDs and names, for example before watching a board for new ads. Read-only, so repeating the call is safe.', idempotent: true },- props: findBoardsProperties(),- auth: foreplayCoAuth,+ description: 'Get the boards of your Foreplay account. Leave Limit empty to get all boards.',+ audience: 'human',+ aiMetadata: {+ description: 'List the boards of the Foreplay account; with no limit it returns every board. Returns raw board objects (id, name, description). Costs 1 credit per call.',+ idempotent: true,+ },+ outputSchema: foreplayOutputSchemas.rawBoards,+ props: {+ offset: Property.Number({ displayName: 'Offset', description: 'Boards to skip (only used when Limit is set).', required: false }),+ limit: Property.Number({ displayName: 'Limit', description: 'Boards per request. Leave empty for all boards.', required: false }),+ },async run({ auth, propsValue }) {- // Validate props using Zod schema- const validation = findBoardsSchema.safeParse(propsValue);- if (!validation.success) {- throw new Error(`Validation failed: ${validation.error.message}`);- }-- const values = propsValue;- const queryParams: Record<string, string> = {};-- // Add optional parameters if provided- if (values['offset'] !== undefined) {- queryParams['offset'] = String(values['offset']);- }- if (values['limit'] !== undefined) {- queryParams['limit'] = String(values['limit']);- }-- const response = await foreplayCoApiCall({- apiKey: auth,- method: HttpMethod.GET,- resourceUri: '/api/boards',- queryParams,+ const limit = foreplayProps.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 10_000 });+ const offset = foreplayProps.parseInteger({ value: propsValue.offset, label: 'Offset', min: 0, max: Number.MAX_SAFE_INTEGER });+ const response = await foreplayClient.request({+ auth,+ path: '/api/boards',+ query: limit === undefined ? {} : { limit, offset },});-- const responseBody = response.body;-- // Check if the response is successful- if (responseBody.metadata && responseBody.metadata.success === true) {- // Return just the boards data for clean automation workflows- return responseBody.data;- } else {- // Handle error responses by throwing an error- const errorMessage =- responseBody.error ||- responseBody.metadata?.message ||- 'Failed to retrieve boards';- throw new Error(`Foreplay.co API Error: ${errorMessage}`);- }+ return foreplayMappers.listOf(response.body);},});++export { findBoards };diff --git a/packages/pieces/community/foreplay-co/src/lib/actions/find-brands.ts b/packages/pieces/community/foreplay-co/src/lib/actions/find-brands.tsindex f405f5b1543..21f59026031 100644--- a/packages/pieces/community/foreplay-co/src/lib/actions/find-brands.ts+++ b/packages/pieces/community/foreplay-co/src/lib/actions/find-brands.ts@@ -1,56 +1,37 @@-import { createAction } from '@activepieces/pieces-framework';-import { foreplayCoApiCall } from '../common';-import { HttpMethod } from '@activepieces/pieces-common';-import { findBrands as findBrandsProperties } from '../properties';-import { findBrandsSchema } from '../schemas';-import { foreplayCoAuth } from '../..';+import { createAction, Property } from '@activepieces/pieces-framework';+import { foreplayCoAuth } from '../auth';+import { foreplayClient } from '../common/client';+import { foreplayMappers } from '../common/mappers';+import { foreplayOutputSchemas } from '../common/output-schemas';+import { foreplayProps } from '../common/props';-export const findBrands = createAction({+const findBrands = createAction({+ auth: foreplayCoAuth,name: 'findBrands',classification: 'SEARCH',displayName: 'Find Brands',- description: 'Search for brands by name with fuzzy matching.',- audience: 'both',- aiMetadata: { description: 'Search the Foreplay brand directory by name using fuzzy matching, returning matching brands. Use to resolve a brand name to its Foreplay brand record (e.g. to discover a brand ID before fetching its ads). Requires a query string; read-only, so repeating the call is safe.', idempotent: true },- props: findBrandsProperties(),- auth: foreplayCoAuth,+ description: 'Search for brands by name. Costs 1 Foreplay credit per search.',+ audience: 'human',+ aiMetadata: {+ description: 'Search Foreplay brands by name and return raw brand objects with their IDs and Facebook page IDs. Costs 1 credit per call.',+ idempotent: true,+ },+ outputSchema: foreplayOutputSchemas.rawBrands,+ props: {+ query: Property.ShortText({ displayName: 'Brand Name', description: 'Brand name to search for, e.g. Nike.', required: true }),+ limit: Property.Number({ displayName: 'Limit', description: 'Number of brands to return (1 to 100).', required: false, defaultValue: 10 }),+ },async run({ auth, propsValue }) {- // Validate props using Zod schema- const validation = findBrandsSchema.safeParse(propsValue);- if (!validation.success) {- throw new Error(`Validation failed: ${validation.error.message}`);- }-- const values = propsValue;- const queryParams: Record<string, string> = {- query: String(values['query']),- };-- // Add optional limit parameter if provided- if (values['limit']) {- queryParams['limit'] = String(values['limit']);- }-- const response = await foreplayCoApiCall({- apiKey: auth,- method: HttpMethod.GET,- resourceUri: '/api/discovery/brands',- queryParams,+ const response = await foreplayClient.request({+ auth,+ path: '/api/discovery/brands',+ query: {+ query: foreplayProps.requiredText({ value: propsValue.query, label: 'Brand Name' }),+ limit: foreplayProps.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 100 }),+ },});-- const responseBody = response.body;-- // Check if the response is successful- if (responseBody.metadata && responseBody.metadata.success === true) {- // Return just the brands data for clean automation workflows- return responseBody.data;- } else {- // Handle error responses by throwing an error- const errorMessage =- responseBody.error ||- responseBody.metadata?.message ||- 'Failed to find brands';- throw new Error(`Foreplay.co API Error: ${errorMessage}`);- }+ return foreplayMappers.listOf(response.body);},});++export { findBrands };diff --git a/packages/pieces/community/foreplay-co/src/lib/actions/get-ad-by-id.ts b/packages/pieces/community/foreplay-co/src/lib/actions/get-ad-by-id.tsindex 5f691ebe40b..26fbaf0856a 100644--- a/packages/pieces/community/foreplay-co/src/lib/actions/get-ad-by-id.ts+++ b/packages/pieces/community/foreplay-co/src/lib/actions/get-ad-by-id.ts@@ -1,47 +1,33 @@-import { createAction } from '@activepieces/pieces-framework';-import { foreplayCoApiCall } from '../common';-import { HttpMethod } from '@activepieces/pieces-common';-import { getAdById as getAdByIdProperties } from '../properties';-import { getAdByIdSchema } from '../schemas';-import { foreplayCoAuth } from '../..';+import { createAction, Property } from '@activepieces/pieces-framework';+import { foreplayCoAuth } from '../auth';+import { foreplayClient } from '../common/client';+import { foreplayMappers } from '../common/mappers';+import { foreplayOutputSchemas } from '../common/output-schemas';+import { foreplayProps } from '../common/props';-export const getAdById = createAction({+const getAdById = createAction({+ auth: foreplayCoAuth,name: 'getAdById',classification: 'READ',displayName: 'Get Ad by ID',- description: 'Get detailed information about a specific ad by its ID.',- audience: 'both',- aiMetadata: { description: 'Fetch the full details of one Foreplay ad by its ad ID. Use when you already have a specific ad ID (e.g. from a search or a trigger) and need its complete metadata. Requires the exact ad ID; read-only, so repeating the call is safe.', idempotent: true },- props: getAdByIdProperties(),- auth: foreplayCoAuth,+ description: 'Get detailed information about a specific ad by its public ad library ID. Costs 1 Foreplay credit.',+ audience: 'human',+ aiMetadata: {+ description: 'Fetch one Foreplay ad by its public ad library ID (the ad_id field of ads returned by other Foreplay steps, not the internal id) and return the raw ad object. Costs 1 credit.',+ idempotent: true,+ },+ outputSchema: foreplayOutputSchemas.rawAd,+ props: {+ ad_id: Property.ShortText({ displayName: 'Public Ad ID', description: 'The public ad library ID: the ad_id field of ads returned by other Foreplay steps (not the internal id field).', required: true }),+ },async run({ auth, propsValue }) {- // Validate props using Zod schema- const validation = getAdByIdSchema.safeParse(propsValue);- if (!validation.success) {- throw new Error(`Validation failed: ${validation.error.message}`);- }-- const adId = propsValue.ad_id;-- const response = await foreplayCoApiCall({- apiKey: auth,- method: HttpMethod.GET,- resourceUri: `/api/ad/${adId}`,- });-- const responseBody = response.body;-- // Check if the response is successful- if (responseBody.metadata && responseBody.metadata.success === true) {- // Return just the ad data for clean automation workflows- return responseBody.data;- } else {- // Handle error responses by throwing an error- const errorMessage =- responseBody.error ||- responseBody.metadata?.message ||- 'Failed to retrieve ad';- throw new Error(`Foreplay.co API Error: ${errorMessage}`);- }+ const id = foreplayProps.foreplayId({ value: propsValue.ad_id, label: 'Public Ad ID' });+ const response = await foreplayClient.request({ auth, path: `/api/ad/${foreplayClient.pathId(id)}` });+ const data = foreplayMappers.dataOf(response.body);+ const item = Array.isArray(data) ? data[0] : data;+ if (item === null || item === undefined || typeof item !== 'object') throw new Error(foreplayMappers.notFoundMessage);+ return item;},});++export { getAdById };diff --git a/packages/pieces/community/foreplay-co/src/lib/actions/get-ads-by-page.ts b/packages/pieces/community/foreplay-co/src/lib/actions/get-ads-by-page.tsindex cd394602d8c..eaf38c8791a 100644--- a/packages/pieces/community/foreplay-co/src/lib/actions/get-ads-by-page.ts+++ b/packages/pieces/community/foreplay-co/src/lib/actions/get-ads-by-page.ts@@ -1,106 +1,43 @@-import { createAction } from '@activepieces/pieces-framework';-import { foreplayCoApiCall } from '../common';-import { HttpMethod } from '@activepieces/pieces-common';-import { getAdsByPage as getAdsByPageProperties } from '../properties';-import { getAdsByPageSchema } from '../schemas';-import { foreplayCoAuth } from '../..';--export const getAdsByPage = createAction({+import { createAction, Property } from '@activepieces/pieces-framework';+import { foreplayCoAuth } from '../auth';+import { foreplayClient } from '../common/client';+import { foreplayMappers } from '../common/mappers';+import { foreplayOutputSchemas } from '../common/output-schemas';+import { foreplayProps } from '../common/props';++const getAdsByPage = createAction({+ auth: foreplayCoAuth,name: 'getAdsByPage',classification: 'SEARCH',displayName: 'Get Ads by Page',- description:- 'Get all ads for a Facebook Page ID with filtering and pagination.',- audience: 'both',- aiMetadata: { description: 'List the ads run by a specific advertiser, keyed by their Facebook Page ID, with optional filters (date range, platform, format, niche, market, language, live-only) and cursor pagination. Use when you want every ad from one known page rather than a free-text search across all advertisers. Requires the Facebook Page ID; read-only, so repeating the call is safe.', idempotent: true },- props: getAdsByPageProperties(),- auth: foreplayCoAuth,+ description: 'Get ads for a Facebook Page ID with filtering and pagination. Costs 1 Foreplay credit per ad returned.',+ audience: 'human',+ aiMetadata: {+ description: 'List the ads of one advertiser by numeric Facebook page ID, with optional filters and cursor pagination. Returns raw ad objects. Costs 1 credit per ad returned.',+ idempotent: true,+ },+ outputSchema: foreplayOutputSchemas.rawAds,+ props: {+ page_id: Property.ShortText({ displayName: 'Page ID', description: 'The numeric Facebook page ID, e.g. 123456789.', required: true }),+ ...foreplayProps.humanAdFilterProps(),+ order: foreplayProps.sortOrderProp(),+ cursor: Property.ShortText({ displayName: 'Cursor', description: 'Cursor from the previous response, for the next page.', required: false }),+ limit: Property.Number({ displayName: 'Limit', description: 'Ads per request (1 to 250). 1 credit per ad returned.', required: false, defaultValue: 10 }),+ },async run({ auth, propsValue }) {- // Validate props using Zod schema- const validation = getAdsByPageSchema.safeParse(propsValue);- if (!validation.success) {- throw new Error(`Validation failed: ${validation.error.message}`);- }-- const values = propsValue;-- // Build query parameters properly handling arrays for API- const queryParams = new URLSearchParams();- queryParams.append('page_id', String(values.page_id));-- // Add optional parameters if provided- if (values.start_date) {- queryParams.append('start_date', String(values.start_date));- }- if (values.end_date) {- queryParams.append('end_date', String(values.end_date));- }- if (values.order) {- queryParams.append('order', String(values.order));- }- if (values.live) {- queryParams.append('live', String(values.live));- }-- // Handle array parameters - repeat parameter name for each value- if (values.display_format && values.display_format.length > 0) {- values.display_format.forEach((format: unknown) => {- queryParams.append('display_format', String(format));- });- }- if (values.publisher_platform && values.publisher_platform.length > 0) {- values.publisher_platform.forEach((platform: unknown) => {- queryParams.append('publisher_platform', String(platform));- });- }- if (values.niches && values.niches.length > 0) {- values.niches.forEach((niche: unknown) => {- queryParams.append('niches', String(niche));- });- }- if (values.market_target && values.market_target.length > 0) {- values.market_target.forEach((target: unknown) => {- queryParams.append('market_target', String(target));- });- }- if (values.languages && values.languages.length > 0) {- values.languages.forEach((language: unknown) => {- queryParams.append('languages', String(language));- });- }-- if (values.cursor) {- queryParams.append('cursor', String(values.cursor));- }- if (values.limit) {- queryParams.append('limit', String(values.limit));- }-- // Build the full URL with query parameters manually to handle arrays properly- const queryString = queryParams.toString();- const fullUrl = queryString- ? `/api/brand/getAdsByPageId?${queryString}`- : '/api/brand/getAdsByPageId';-- const response = await foreplayCoApiCall({- apiKey: auth,- method: HttpMethod.GET,- resourceUri: fullUrl,+ const response = await foreplayClient.request({+ auth,+ path: '/api/brand/getAdsByPageId',+ query: {+ page_id: foreplayProps.pageId({ value: propsValue.page_id, label: 'Page ID' }),+ ...foreplayProps.adFilterQuery(foreplayProps.humanAdFilterInput(propsValue)),+ order: foreplayProps.enumValue({ value: propsValue.order, label: 'Order', allowed: foreplayProps.SORT_ORDERS }),+ cursor: foreplayProps.optionalText(propsValue.cursor),+ limit: foreplayProps.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 250 }),+ },});-- const responseBody = response.body;-- // Check if the response is successful- if (responseBody.metadata && responseBody.metadata.success === true) {- // Return just the ads data for clean automation workflows- return responseBody.data;- } else {- // Handle error responses by throwing an error- const errorMessage =- responseBody.error ||- responseBody.metadata?.message ||- 'Failed to retrieve ads for page';- throw new Error(`Foreplay.co API Error: ${errorMessage}`);- }+ return foreplayMappers.listOf(response.body);},});++export { getAdsByPage };diff --git a/packages/pieces/community/foreplay-co/src/lib/actions/index.ts b/packages/pieces/community/foreplay-co/src/lib/actions/index.tsindex 8760fac90ab..934968c6671 100644--- a/packages/pieces/community/foreplay-co/src/lib/actions/index.ts+++ b/packages/pieces/community/foreplay-co/src/lib/actions/index.ts@@ -1,5 +1,7 @@-export { getAdById } from './get-ad-by-id';-export { getAdsByPage } from './get-ads-by-page';-export { findBrands } from './find-brands';-export { findAds } from './find-ads';-export { findBoards } from './find-boards';+import { findAds } from './find-ads';+import { findBoards } from './find-boards';+import { findBrands } from './find-brands';+import { getAdById } from './get-ad-by-id';+import { getAdsByPage } from './get-ads-by-page';++export { getAdById, getAdsByPage, findBrands, findAds, findBoards };diff --git a/packages/pieces/community/foreplay-co/src/lib/auth.ts b/packages/pieces/community/foreplay-co/src/lib/auth.tsnew file mode 100644index 00000000000..5ccbacf9719--- /dev/null+++ b/packages/pieces/community/foreplay-co/src/lib/auth.ts@@ -0,0 +1,21 @@+import { PieceAuth } from '@activepieces/pieces-framework';+import { ForeplayApiError, foreplayClient } from './common/client';++const foreplayCoAuth = PieceAuth.SecretText({+ displayName: 'API Key',+ description: 'Your Foreplay API key. In Foreplay open the Data API dashboard (https://app.foreplay.co/api-overview) and generate a key.',+ required: true,+ validate: async ({ auth }) => {+ try {+ await foreplayClient.request({ auth, path: '/api/usage' });+ return { valid: true };+ } catch (error) {+ if (error instanceof ForeplayApiError && (error.status === 401 || error.status === 403)) {+ return { valid: false, error: 'Invalid credentials: Foreplay rejected the API key. Generate a new key at https://app.foreplay.co/api-overview.' };+ }+ return { valid: false, error: error instanceof Error ? error.message : 'Could not reach Foreplay.' };+ }+ },+});++export { foreplayCoAuth };diff --git a/packages/pieces/community/foreplay-co/src/lib/common.ts b/packages/pieces/community/foreplay-co/src/lib/common.tsdeleted file mode 100644index 1e1645f4088..00000000000--- a/packages/pieces/community/foreplay-co/src/lib/common.ts+++ /dev/null@@ -1,32 +0,0 @@-import { httpClient, HttpMethod, AuthenticationType } from "@activepieces/pieces-common";-import { AppConnectionValueForAuthProperty } from "@activepieces/pieces-framework";-import { foreplayCoAuth } from "..";--export interface ForeplayCoApiCallProps {- apiKey: AppConnectionValueForAuthProperty<typeof foreplayCoAuth>;- method: HttpMethod;- resourceUri: string;- queryParams?: Record<string, string>;- body?: any;-}--export async function foreplayCoApiCall({- apiKey,- method,- resourceUri,- queryParams,- body,-}: ForeplayCoApiCallProps) {- const baseUrl = "https://public.api.foreplay.co";-- return httpClient.sendRequest({- method,- url: `${baseUrl}${resourceUri}`,- authentication: {- type: AuthenticationType.BEARER_TOKEN,- token: apiKey.secret_text,- },- queryParams,- body,- });-}diff --git a/packages/pieces/community/foreplay-co/src/lib/common/client.ts b/packages/pieces/community/foreplay-co/src/lib/common/client.tsnew file mode 100644index 00000000000..133af8a235b--- /dev/null+++ b/packages/pieces/community/foreplay-co/src/lib/common/client.ts@@ -0,0 +1,188 @@+import { httpClient, HttpMessageBody, HttpMethod } from '@activepieces/pieces-common';++const FOREPLAY_API_URL = 'https://public.api.foreplay.co';+const REQUEST_TIMEOUT_MS = 60_000;+const MAX_RATE_LIMIT_RETRIES = 2;+const MAX_RATE_LIMIT_WAIT_MS = 30_000;+const RATE_LIMIT_BASE_WAIT_MS = 2_000;++class ForeplayApiError extends Error {+ constructor(+ message: string,+ public readonly status: number,+ public readonly responseBody: unknown,+ ) {+ super(message);+ this.name = 'ForeplayApiError';+ }+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}++function keyOf(auth: ForeplayAuthInput): string {+ const raw = typeof auth === 'string' ? auth : isRecord(auth) ? auth['secret_text'] : undefined;+ const key = typeof raw === 'string' ? raw.trim() : '';+ if (key === '') throw new Error('The Foreplay connection has no API key. Reconnect Foreplay with a key from https://app.foreplay.co/api-overview.');+ return key;+}++function hintFor(status: number): string {+ if (status === 401) return ' The API key is invalid or revoked; reconnect Foreplay.';+ if (status === 402) return ' Your Foreplay account is out of API credits.';+ if (status === 403) return ' Your Foreplay plan does not include this, or the page/brand is not in your Spyder watchlist.';+ if (status === 404) return ' Check the ID you passed.';+ if (status === 429) return ' Foreplay is rate limiting this API key; try again later.';+ return '';+}++function messageOf(body: unknown): string | undefined {+ if (typeof body === 'string') return body.trim() === '' ? undefined : body.trim().slice(0, 300);+ if (!isRecord(body)) return undefined;+ const parts: string[] = [];+ const err = body['error'];+ if (typeof err === 'string' && err.trim() !== '') parts.push(err.trim());+ else if (isRecord(err) && typeof err['message'] === 'string' && err['message'].trim() !== '') parts.push(err['message'].trim());+ const detail = body['detail'];+ if (typeof detail === 'string' && detail.trim() !== '') parts.push(detail.trim());+ else if (Array.isArray(detail)) {+ const lines = detail.map((d) => {+ if (!isRecord(d)) return String(d);+ const loc = Array.isArray(d['loc']) ? d['loc'].filter((l) => l !== 'query' && l !== 'path').join('.') : '';+ return `${loc ? `${loc}: ` : ''}${typeof d['msg'] === 'string' ? d['msg'] : JSON.stringify(d)}`;+ });+ if (lines.length > 0) parts.push(lines.join('; '));+ }+ const metadata = body['metadata'];+ if (parts.length === 0 && isRecord(metadata) && typeof metadata['message'] === 'string') parts.push(metadata['message']);+ if (parts.length === 0 && Object.keys(body).length > 0) parts.push(JSON.stringify(body).slice(0, 300));+ return parts.length > 0 ? parts.join(' — ') : undefined;+}++function toApiError({ status, body }: { status: number; body: unknown }): ForeplayApiError {+ const text = status >= 300 && status < 400 ? 'unexpected redirect' : messageOf(body) ?? 'request failed';+ return new ForeplayApiError(`Foreplay API error (${status}): ${text.replace(/\.+$/, '')}.${hintFor(status)}`, status, body);+}++function failureOf(error: unknown): { status: number; body: unknown } | null {+ if (error === null || typeof error !== 'object') return null;+ const response = Reflect.get(error, 'response');+ if (!isRecord(response)) return null;+ const status = response['status'];+ return typeof status === 'number' ? { status, body: response['body'] } : null;+}++function headerOf({ headers, name }: { headers: unknown; name: string }): string | undefined {+ if (!isRecord(headers)) return undefined;+ for (const [key, value] of Object.entries(headers)) {+ if (key.toLowerCase() !== name) continue;+ const v = Array.isArray(value) ? value[0] : value;+ if (typeof v === 'string' || typeof v === 'number') return String(v);+ }+ return undefined;+}++function rateLimitWaitMs(attempt: number): number {+ return Math.min(RATE_LIMIT_BASE_WAIT_MS * 2 ** attempt, MAX_RATE_LIMIT_WAIT_MS);+}++const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));++function normalizePath(path: string): string {+ if (!path.startsWith('/') || path.startsWith('//') || /^[a-z][a-z0-9+.-]*:/i.test(path)) {+ throw new Error('Foreplay request paths must be relative to the Foreplay API (start with a single "/").');+ }+ if (path.split(/[/?#]/).some((part) => part === '..' || part.toLowerCase() === '%2e%2e')) {+ throw new Error('Foreplay request paths must not contain ".." segments.');+ }+ return path;+}++function queryString(query?: ForeplayQuery): string {+ const params = new URLSearchParams();+ for (const [key, value] of Object.entries(query ?? {})) {+ if (value === undefined || value === null) continue;+ if (Array.isArray(value)) {+ for (const item of value) params.append(key, item);+ } else {+ params.append(key, String(value));+ }+ }+ const text = params.toString();+ return text === '' ? '' : `?${text}`;+}++function numberOrNull(value: string | undefined): number | null {+ if (value === undefined || value.trim() === '') return null;+ const n = Number(value);+ return Number.isFinite(n) ? n : null;+}++async function request({ auth, path, query }: ForeplayRequest): Promise<ForeplayResponse> {+ const apiKey = keyOf(auth);+ const url = `${FOREPLAY_API_URL}${normalizePath(path)}${queryString(query)}`;+ for (let attempt = 0; ; attempt++) {+ try {+ const response = await httpClient.sendRequest<HttpMessageBody>({+ method: HttpMethod.GET,+ url,+ headers: { Authorization: apiKey, accept: 'application/json' },+ timeout: REQUEST_TIMEOUT_MS,+ followRedirects: false,+ });+ if (response.status < 200 || response.status >= 300) throw toApiError({ status: response.status, body: response.body });+ const body: unknown = response.body;+ if (isRecord(body) && isRecord(body['metadata']) && body['metadata']['success'] === false) {+ const status = typeof body['metadata']['status_code'] === 'number' ? body['metadata']['status_code'] : response.status;+ throw toApiError({ status, body });+ }+ return {+ body,+ creditCost: numberOrNull(headerOf({ headers: response.headers, name: 'x-credit-cost' })),+ creditsRemaining: numberOrNull(headerOf({ headers: response.headers, name: 'x-credits-remaining' })),+ };+ } catch (error) {+ if (error instanceof ForeplayApiError) throw error;+ const failure = failureOf(error);+ if (!failure) throw error;+ if (failure.status === 429 && attempt < MAX_RATE_LIMIT_RETRIES) {+ await sleep(rateLimitWaitMs(attempt));+ continue;+ }+ throw toApiError(failure);+ }+ }+}++function pathId(id: string): string {+ return encodeURIComponent(id);+}++const foreplayClient = {+ request,+ keyOf,+ isRecord,+ normalizePath,+ pathId,+ FOREPLAY_API_URL,+};++type ForeplayAuthInput = string | { secret_text: string };++type ForeplayQuery = Record<string, string | number | boolean | string[] | null | undefined>;++type ForeplayRequest = {+ auth: ForeplayAuthInput;+ path: string;+ query?: ForeplayQuery;+};++type ForeplayResponse = {+ body: unknown;+ creditCost: number | null;+ creditsRemaining: number | null;+};++export { foreplayClient, ForeplayApiError, FOREPLAY_API_URL };+export type { ForeplayAuthInput, ForeplayQuery, ForeplayResponse };diff --git a/packages/pieces/community/foreplay-co/src/lib/common/mappers.ts b/packages/pieces/community/foreplay-co/src/lib/common/mappers.tsnew file mode 100644index 00000000000..79f89dc0599--- /dev/null+++ b/packages/pieces/community/foreplay-co/src/lib/common/mappers.ts@@ -0,0 +1,224 @@+import { ForeplayResponse, foreplayClient } from './client';++const { isRecord } = foreplayClient;++function recordOf(value: unknown): Record<string, unknown> {+ return isRecord(value) ? value : {};+}++function arrayOf(value: unknown): unknown[] {+ return Array.isArray(value) ? value : [];+}++function str(value: unknown): string | null {+ if (typeof value === 'string') return value;+ if (typeof value === 'number' && Number.isFinite(value)) return String(value);+ return null;+}++function num(value: unknown): number | null {+ if (typeof value === 'number' && Number.isFinite(value)) return value;+ if (typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value))) return Number(value);+ return null;+}++function bool(value: unknown): boolean | null {+ return typeof value === 'boolean' ? value : null;+}++function strings(value: unknown): string[] {+ return arrayOf(value).filter((v): v is string => typeof v === 'string');+}++function epochToIso(value: unknown): string | null {+ const n = num(value);+ if (n === null) return null;+ const ms = n < 100_000_000_000 ? n * 1000 : n;+ const d = new Date(ms);+ return Number.isNaN(d.getTime()) ? null : d.toISOString();+}++function dataOf(body: unknown): unknown {+ return recordOf(body)['data'];+}++function metadataOf(body: unknown): Record<string, unknown> {+ return recordOf(recordOf(body)['metadata']);+}++function listOf(body: unknown): unknown[] {+ return arrayOf(dataOf(body));+}++function ad(raw: unknown) {+ const a = recordOf(raw);+ const brand = a['brand_id'];+ return {+ id: str(a['id']),+ adId: str(a['ad_id']),+ name: str(a['name']),+ brandId: str(brand),+ description: str(a['description']),+ headline: str(a['headline']),+ ctaTitle: str(a['cta_title']),+ ctaType: str(a['cta_type']),+ linkUrl: str(a['link_url']),+ displayFormat: str(a['display_format']),+ type: str(a['type']),+ publisherPlatforms: strings(a['publisher_platform']),+ niches: strings(a['niches']),+ languages: strings(a['languages']),+ marketTarget: str(a['market_target']),+ productCategory: str(a['product_category']),+ categories: arrayOf(a['categories']),+ live: bool(a['live']),+ startedRunning: epochToIso(a['started_running']),+ runningDuration: isRecord(a['running_duration']) ? a['running_duration'] : null,+ thumbnail: str(a['thumbnail']),+ image: str(a['image']),+ video: str(a['video']),+ videoDuration: num(a['video_duration']),+ avatar: str(a['avatar']),+ fullTranscription: str(a['full_transcription']),+ cardCount: arrayOf(a['cards']).length,+ cards: arrayOf(a['cards']).map((c) => {+ const card = recordOf(c);+ return { title: str(card['title']), headline: str(card['headline']), description: str(card['description']), image: str(card['image']), video: str(card['video']), ctaText: str(card['cta_text']) };+ }),+ emotionalDrivers: isRecord(a['emotional_drivers']) ? a['emotional_drivers'] : null,+ persona: isRecord(a['persona']) ? a['persona'] : null,+ foreplayUrl: str(a['foreplay_url']),+ };+}++function brand(raw: unknown) {+ const b = recordOf(raw);+ const description = b['description'];+ return {+ id: str(b['id']),+ name: str(b['name']),+ description: isRecord(description) ? str(description['text']) : str(description),+ category: str(b['category']),+ niches: strings(b['niches']),+ url: str(b['url']),+ websites: strings(b['websites']),+ avatar: str(b['avatar']),+ pageId: str(b['ad_library_id']),+ verificationStatus: str(b['verification_status']),+ adsCount: num(b['ads_count']),+ activeAdsCount: num(b['active_ads_count']),+ };+}++function board(raw: unknown) {+ const b = recordOf(raw);+ return { id: str(b['id']), name: str(b['name']), description: str(b['description']), createdAt: epochToIso(b['created_at']) };+}++function credits(response: ForeplayResponse) {+ return { creditCost: response.creditCost, creditsRemaining: response.creditsRemaining };+}++function cursorPage<T>({ response, map, limit }: { response: ForeplayResponse; map: (raw: unknown) => T; limit: number }) {+ const items = listOf(response.body).map(map);+ const cursor = metadataOf(response.body)['cursor'];+ const next = typeof cursor === 'string' && cursor !== '' ? cursor : typeof cursor === 'number' ? String(cursor) : null;+ const hasMore = next !== null && items.length >= limit;+ return { items, count: items.length, hasMore, nextCursor: hasMore ? next : null, ...credits(response) };+}++function offsetPage<T>({ response, map, limit, offset }: { response: ForeplayResponse; map: (raw: unknown) => T; limit: number; offset: number }) {+ const items = listOf(response.body).map(map);+ const hasMore = items.length >= limit;+ return { items, count: items.length, hasMore, nextOffset: hasMore ? offset + items.length : null, ...credits(response) };+}++const notFoundMessage = 'Foreplay returned no record for this ID. Ad lookups need the public ad library ID (the adId / ad_id field of search results), not the Foreplay internal id.';++function single<T>({ response, map }: { response: ForeplayResponse; map: (raw: unknown) => T }) {+ const data = dataOf(response.body);+ const item = Array.isArray(data) ? data[0] : data;+ if (!isRecord(item)) throw new Error(notFoundMessage);+ return { ...map(item), ...credits(response) };+}++function analyticsRow(raw: unknown) {+ const r = recordOf(raw);+ const formats: Record<string, number> = {};+ for (const key of ['video', 'image', 'carousel', 'dco', 'dpa', 'multi_images', 'multi_videos', 'multi_medias', 'event', 'text', 'page_like']) {+ const n = num(r[key]);+ if (n !== null) formats[key] = n;+ }+ return { date: str(r['date']), activeCount: num(r['active_count']), inactiveCount: num(r['inactive_count']), formats };+}++function rankedAd(raw: unknown) {+ const r = recordOf(raw);+ const ranking = isRecord(r['ranking']) ? r['ranking'] : r;+ const base = isRecord(r['ranking']) ? ad(r) : null;+ return {+ id: str(r['id']),+ adId: str(r['ad_id']),+ rank: num(ranking['rank']),+ previousRank: num(ranking['previous_rank']),+ peakRank: num(ranking['peak_rank']),+ daysRunning: num(ranking['days_running']),+ category: str(ranking['category']),+ asset: str(ranking['asset']),+ type: str(ranking['type']),+ ad: base,+ };+}++function relatedPage(raw: unknown) {+ const p = recordOf(raw);+ return {+ pageId: str(p['pageId']),+ name: str(p['currentPageName']) ?? str(p['pageName']),+ brandId: str(p['brandId']),+ profileUrl: str(p['profileUri']),+ profilePicUrl: str(p['profilePicUrl']),+ categories: strings(p['categories']),+ likeCount: num(p['likeCount']),+ adsCount: num(p['adsCount']),+ liveAdsCount: num(p['liveAdsCount']),+ firstSeenAt: str(p['firstSeenAt']),+ lastSeenAt: str(p['lastSeenAt']),+ };+}++function usage(raw: unknown) {+ const u = recordOf(raw);+ return {+ totalCredits: num(u['total_credits']),+ remainingCredits: num(u['remaining_credits']),+ usedCredits: num(u['total_credits']) !== null && num(u['remaining_credits']) !== null ? (num(u['total_credits']) ?? 0) - (num(u['remaining_credits']) ?? 0) : null,+ periodStart: str(u['start_date']),+ periodEnd: str(u['end_date']),+ userId: str(recordOf(u['user'])['id']),+ };+}++const foreplayMappers = {+ notFoundMessage,+ recordOf,+ arrayOf,+ str,+ num,+ dataOf,+ metadataOf,+ listOf,+ ad,+ brand,+ board,+ credits,+ cursorPage,+ offsetPage,+ single,+ analyticsRow,+ rankedAd,+ relatedPage,+ usage,+};++export { foreplayMappers };diff --git a/packages/pieces/community/foreplay-co/src/lib/common/output-schemas.ts b/packages/pieces/community/foreplay-co/src/lib/common/output-schemas.tsnew file mode 100644index 00000000000..42a9f5979a9--- /dev/null+++ b/packages/pieces/community/foreplay-co/src/lib/common/output-schemas.ts@@ -0,0 +1,273 @@+import { OutputSchema, OutputSchemaField } from '@activepieces/pieces-framework';++const creditFields: OutputSchemaField[] = [+ { key: 'creditCost', label: 'Credits Used', format: 'number', description: 'Foreplay credits this call consumed (X-Credit-Cost).' },+ { key: 'creditsRemaining', label: 'Credits Remaining', format: 'number' },+];++const adFields: OutputSchemaField[] = [+ { key: 'id', label: 'Foreplay Ad ID', description: 'Internal Foreplay ID (not accepted by Get Ad or List Ad Duplicates; use the Public Ad ID for those).' },+ { key: 'adId', label: 'Public Ad ID', description: 'Ad library ID from the platform. Use it with Get Ad, Get Ad by ID and List Ad Duplicates.' },+ { key: 'name', label: 'Name' },+ { key: 'brandId', label: 'Brand ID' },+ { key: 'description', label: 'Ad Copy' },+ { key: 'headline', label: 'Headline' },+ { key: 'ctaTitle', label: 'CTA Text' },+ { key: 'ctaType', label: 'CTA Type' },+ { key: 'linkUrl', label: 'Landing Page', format: 'url' },+ { key: 'displayFormat', label: 'Display Format' },+ { key: 'type', label: 'Type' },+ { key: 'publisherPlatforms', label: 'Platforms' },+ { key: 'niches', label: 'Niches' },+ { key: 'languages', label: 'Languages' },+ { key: 'marketTarget', label: 'Market Target' },+ { key: 'productCategory', label: 'Product Category' },+ { key: 'categories', label: 'Categories' },+ { key: 'live', label: 'Live', format: 'boolean' },+ { key: 'startedRunning', label: 'Started Running', format: 'datetime' },+ { key: 'runningDuration', label: 'Running Duration', dynamicKey: true },+ { key: 'thumbnail', label: 'Thumbnail', format: 'url' },+ { key: 'image', label: 'Image', format: 'url' },+ { key: 'video', label: 'Video', format: 'url' },+ { key: 'videoDuration', label: 'Video Duration (s)', format: 'number' },+ { key: 'avatar', label: 'Brand Avatar', format: 'url' },+ { key: 'fullTranscription', label: 'Transcription' },+ { key: 'cardCount', label: 'Card Count', format: 'number' },+ {+ key: 'cards',+ label: 'Carousel Cards',+ labelKey: 'title',+ listItems: [+ { key: 'title', label: 'Title' },+ { key: 'headline', label: 'Headline' },+ { key: 'description', label: 'Description' },+ { key: 'image', label: 'Image', format: 'url' },+ { key: 'video', label: 'Video', format: 'url' },+ { key: 'ctaText', label: 'CTA Text' },+ ],+ },+ { key: 'emotionalDrivers', label: 'Emotional Drivers', dynamicKey: true },+ { key: 'persona', label: 'Persona', dynamicKey: true },+ { key: 'foreplayUrl', label: 'Open in Foreplay', format: 'url' },+];++const brandFields: OutputSchemaField[] = [+ { key: 'id', label: 'Brand ID' },+ { key: 'name', label: 'Name' },+ { key: 'description', label: 'Description' },+ { key: 'category', label: 'Category' },+ { key: 'niches', label: 'Niches' },+ { key: 'url', label: 'Website', format: 'url' },+ { key: 'websites', label: 'Websites' },+ { key: 'avatar', label: 'Avatar', format: 'url' },+ { key: 'pageId', label: 'Facebook Page ID', description: 'Use it with List Page Ads and the Spyder ranking actions.' },+ { key: 'verificationStatus', label: 'Verification Status' },+ { key: 'adsCount', label: 'Ads Indexed', format: 'number' },+ { key: 'activeAdsCount', label: 'Active Ads', format: 'number' },+];++const boardFields: OutputSchemaField[] = [+ { key: 'id', label: 'Board ID' },+ { key: 'name', label: 'Name' },+ { key: 'description', label: 'Description' },+ { key: 'createdAt', label: 'Created', format: 'datetime' },+];++const rankedAdFields: OutputSchemaField[] = [+ { key: 'id', label: 'Foreplay Ad ID' },+ { key: 'adId', label: 'Public Ad ID' },+ { key: 'rank', label: 'Rank', format: 'number' },+ { key: 'previousRank', label: 'Previous Rank', format: 'number' },+ { key: 'peakRank', label: 'Peak Rank', format: 'number' },+ { key: 'daysRunning', label: 'Days Running', format: 'number' },+ { key: 'category', label: 'Category' },+ { key: 'asset', label: 'Asset', format: 'url' },+ { key: 'type', label: 'Type' },+ { key: 'ad', label: 'Ad', children: adFields },+];++function cursorPage({ itemsLabel, labelKey, items }: { itemsLabel: string; labelKey: string; items: OutputSchemaField[] }): OutputSchema {+ return {+ fields: [+ { key: 'items', label: itemsLabel, labelKey, listItems: items },+ { key: 'count', label: 'Returned', format: 'number' },+ { key: 'hasMore', label: 'Has More', format: 'boolean' },+ { key: 'nextCursor', label: 'Next Cursor', description: 'Pass as cursor to get the next page; null when there is none.' },+ ...creditFields,+ ],+ };+}++function offsetPage({ itemsLabel, labelKey, items }: { itemsLabel: string; labelKey: string; items: OutputSchemaField[] }): OutputSchema {+ return {+ fields: [+ { key: 'items', label: itemsLabel, labelKey, listItems: items },+ { key: 'count', label: 'Returned', format: 'number' },+ { key: 'hasMore', label: 'Has More', format: 'boolean' },+ { key: 'nextOffset', label: 'Next Offset', format: 'number', description: 'Pass as offset to get the next page; null when there is none.' },+ ...creditFields,+ ],+ };+}++function list({ itemsLabel, labelKey, items }: { itemsLabel: string; labelKey: string; items: OutputSchemaField[] }): OutputSchema {+ return {+ fields: [+ { key: 'items', label: itemsLabel, labelKey, listItems: items },+ { key: 'count', label: 'Returned', format: 'number' },+ ...creditFields,+ ],+ };+}++const rawAdFields: OutputSchemaField[] = [+ { key: 'id', label: 'Foreplay Ad ID' },+ { key: 'ad_id', label: 'Public Ad ID' },+ { key: 'name', label: 'Name' },+ { key: 'brand_id', label: 'Brand ID' },+ { key: 'description', label: 'Ad Copy' },+ { key: 'headline', label: 'Headline' },+ { key: 'cta_title', label: 'CTA Text' },+ { key: 'link_url', label: 'Landing Page', format: 'url' },+ { key: 'display_format', label: 'Display Format' },+ { key: 'publisher_platform', label: 'Platforms' },+ { key: 'niches', label: 'Niches' },+ { key: 'languages', label: 'Languages' },+ { key: 'market_target', label: 'Market Target' },+ { key: 'live', label: 'Live', format: 'boolean' },+ { key: 'started_running', label: 'Started Running (epoch)', format: 'number' },+ { key: 'thumbnail', label: 'Thumbnail', format: 'url' },+ { key: 'image', label: 'Image', format: 'url' },+ { key: 'video', label: 'Video', format: 'url' },+ { key: 'video_duration', label: 'Video Duration (s)', format: 'number' },+ { key: 'full_transcription', label: 'Transcription' },+ { key: 'foreplay_url', label: 'Open in Foreplay', format: 'url' },+];++const rawBrandFields: OutputSchemaField[] = [+ { key: 'id', label: 'Brand ID' },+ { key: 'name', label: 'Name' },+ { key: 'category', label: 'Category' },+ { key: 'niches', label: 'Niches' },+ { key: 'url', label: 'Website', format: 'url' },+ { key: 'avatar', label: 'Avatar', format: 'url' },+ { key: 'ad_library_id', label: 'Facebook Page ID' },+ { key: 'ads_count', label: 'Ads Indexed', format: 'number' },+ { key: 'active_ads_count', label: 'Active Ads', format: 'number' },+];++const rawBoardFields: OutputSchemaField[] = [+ { key: 'id', label: 'Board ID' },+ { key: 'name', label: 'Name' },+ { key: 'description', label: 'Description' },+ { key: 'created_at', label: 'Created (epoch)', format: 'number' },+];++const legacyEventMetadataFields: OutputSchemaField[] = [+ { key: 'metadata.success', label: 'Detected', format: 'boolean' },+ { key: 'metadata.message', label: 'Detection Message' },+];++const foreplayOutputSchemas = {+ ad: { fields: [...adFields, ...creditFields] } satisfies OutputSchema,+ adEvent: { fields: adFields } satisfies OutputSchema,+ adCursorPage: cursorPage({ itemsLabel: 'Ads', labelKey: 'name', items: adFields }),+ adOffsetPage: offsetPage({ itemsLabel: 'Ads', labelKey: 'name', items: adFields }),+ adList: list({ itemsLabel: 'Ads', labelKey: 'name', items: adFields }),+ brand: { fields: [...brandFields, ...creditFields] } satisfies OutputSchema,+ brandList: list({ itemsLabel: 'Brands', labelKey: 'name', items: brandFields }),+ brandOffsetPage: offsetPage({ itemsLabel: 'Brands', labelKey: 'name', items: brandFields }),+ boardList: list({ itemsLabel: 'Boards', labelKey: 'name', items: boardFields }),+ boardOffsetPage: offsetPage({ itemsLabel: 'Boards', labelKey: 'name', items: boardFields }),+ analytics: {+ fields: [+ {+ key: 'items',+ label: 'Days',+ labelKey: 'date',+ listItems: [+ { key: 'date', label: 'Date', format: 'date' },+ { key: 'activeCount', label: 'Active Ads', format: 'number' },+ { key: 'inactiveCount', label: 'Inactive Ads', format: 'number' },+ { key: 'formats', label: 'Ads by Format', dynamicKey: true },+ ],+ },+ { key: 'count', label: 'Days Returned', format: 'number' },+ ...creditFields,+ ],+ } satisfies OutputSchema,+ topAds: {+ fields: [+ { key: 'pageId', label: 'Page ID' },+ { key: 'date', label: 'Date', format: 'date' },+ { key: 'compareDaysAgo', label: 'Compared With (days ago)', format: 'number' },+ { key: 'items', label: 'Ranked Ads', labelKey: 'rank', listItems: rankedAdFields },+ { key: 'count', label: 'Returned', format: 'number' },+ ...creditFields,+ ],+ } satisfies OutputSchema,+ rankedAds: {+ fields: [+ { key: 'pageId', label: 'Page ID' },+ { key: 'date', label: 'Date', format: 'date' },+ { key: 'category', label: 'Category' },+ { key: 'items', label: 'Ranked Ads', labelKey: 'rank', listItems: rankedAdFields },+ { key: 'count', label: 'Returned', format: 'number' },+ { key: 'total', label: 'Total', format: 'number' },+ { key: 'hasMore', label: 'Has More', format: 'boolean' },+ { key: 'nextOffset', label: 'Next Offset', format: 'number' },+ { key: 'counts', label: 'Counts by Category', dynamicKey: true },+ ...creditFields,+ ],+ } satisfies OutputSchema,+ relatedPages: list({+ itemsLabel: 'Related Pages',+ labelKey: 'name',+ items: [+ { key: 'pageId', label: 'Page ID' },+ { key: 'name', label: 'Name' },+ { key: 'brandId', label: 'Brand ID' },+ { key: 'profileUrl', label: 'Profile', format: 'url' },+ { key: 'profilePicUrl', label: 'Picture', format: 'url' },+ { key: 'categories', label: 'Categories' },+ { key: 'likeCount', label: 'Likes', format: 'number' },+ { key: 'adsCount', label: 'Ads', format: 'number' },+ { key: 'liveAdsCount', label: 'Live Ads', format: 'number' },+ { key: 'firstSeenAt', label: 'First Seen', format: 'datetime' },+ { key: 'lastSeenAt', label: 'Last Seen', format: 'datetime' },+ ],+ }),+ usage: {+ fields: [+ { key: 'totalCredits', label: 'Total Credits', format: 'number' },+ { key: 'remainingCredits', label: 'Remaining Credits', format: 'number' },+ { key: 'usedCredits', label: 'Used Credits', format: 'number' },+ { key: 'periodStart', label: 'Billing Period Start', format: 'datetime' },+ { key: 'periodEnd', label: 'Billing Period End', format: 'datetime' },+ { key: 'userId', label: 'User ID' },+ ],+ } satisfies OutputSchema,+ lensReport: {+ fields: [+ { key: 'items', label: 'Rows', listItems: [+ { key: 'core_metrics', label: 'Core Metrics', dynamicKey: true },+ { key: 'actions', label: 'Actions', dynamicKey: true },+ { key: 'action_values', label: 'Action Values', dynamicKey: true },+ ] },+ { key: 'count', label: 'Returned', format: 'number' },+ { key: 'total', label: 'Total Rows', format: 'number' },+ { key: 'page', label: 'Page', format: 'number' },+ { key: 'hasMore', label: 'Has More', format: 'boolean' },+ { key: 'nextPage', label: 'Next Page', format: 'number' },+ ...creditFields,+ ],+ } satisfies OutputSchema,+ rawAds: { itemLabel: '{name}', fields: rawAdFields } satisfies OutputSchema,+ rawAd: { fields: rawAdFields } satisfies OutputSchema,+ boardAd: { fields: [...rawAdFields, { key: 'title', label: 'Title' }, { key: 'board_id', label: 'Board ID' }, ...legacyEventMetadataFields] } satisfies OutputSchema,+ swipefileAd: { fields: [...rawAdFields, ...legacyEventMetadataFields] } satisfies OutputSchema,+ rawBrands: { itemLabel: '{name}', fields: rawBrandFields } satisfies OutputSchema,+ rawBoards: { itemLabel: '{name}', fields: rawBoardFields } satisfies OutputSchema,+};++export { foreplayOutputSchemas };diff --git a/packages/pieces/community/foreplay-co/src/lib/common/polling.ts b/packages/pieces/community/foreplay-co/src/lib/common/polling.tsnew file mode 100644index 00000000000..8c4344b7479--- /dev/null+++ b/packages/pieces/community/foreplay-co/src/lib/common/polling.ts@@ -0,0 +1,218 @@+import { Property, Store } from '@activepieces/pieces-framework';+import { ForeplayAuthInput, foreplayClient, ForeplayQuery } from './client';+import { foreplayMappers } from './mappers';+import { foreplayProps } from './props';++const SEEN_KEY = 'foreplay_seen_ad_ids';+const MAX_SEEN = 1000;+const TEST_LIMIT = 5;+const MAX_POLL_PAGES = 5;+const MAX_PAGE_SIZE = 50;+const LEGACY_LAST_POLL_KEY = 'lastPoll';+const BACKLOG_KEY = 'foreplay_backlog_cursor';++function idOf(raw: unknown): string | null {+ const record = foreplayMappers.recordOf(raw);+ return foreplayMappers.str(record['id']) ?? foreplayMappers.str(record['ad_id']);+}++function legacyPollingIntervalProp() {+ return Property.Number({+ displayName: 'Polling Interval (minutes)',+ description: 'No longer used; Activepieces sets the polling schedule.',+ required: false,+ defaultValue: 5,+ });+}++function pageSizeProp() {+ return Property.Number({+ displayName: 'Ads Checked per Poll',+ description: `How many of the newest ads to check per page (1 to 50, default 10). Foreplay charges 1 credit per ad returned. A quiet poll costs one page; if a whole page is new, the trigger reads further pages until it reaches an ad it has already seen, up to ${MAX_POLL_PAGES} pages per poll (worst case ${MAX_POLL_PAGES} × this many credits), and carries on from where it stopped on the next poll so no ad is skipped.`,+ required: false,+ defaultValue: 10,+ });+}++function pageSizeOf(value: unknown): number {+ return foreplayProps.parseInteger({ value, label: 'Ads Checked per Poll', min: 1, max: MAX_PAGE_SIZE }) ?? 10;+}++async function seenIds(store: Store): Promise<string[] | null> {+ const value = await store.get<unknown>(SEEN_KEY);+ return Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : null;+}++function epochMsOf(raw: unknown): number | null {+ const value = foreplayMappers.recordOf(raw)['created_at'];+ if (typeof value === 'number' && Number.isFinite(value)) return value < 100_000_000_000 ? value * 1000 : value;+ if (typeof value === 'string' && value.trim() !== '') {+ const ms = new Date(value).getTime();+ return Number.isNaN(ms) ? null : ms;+ }+ return null;+}++async function scan({ fetchAds, start, pages, seenBefore, known, before, anchorIds, boundaryId, shifting }: ScanParams): Promise<ScanResult> {+ const fresh: unknown[] = [];+ const skipped: unknown[] = [];+ const scannedIds: string[] = [];+ const anchors = new Set(anchorIds);+ let anchorPending = anchors.size > 0;+ const finish = ({ resume, pagesUsed }: { resume: Resume | null; pagesUsed: number }): ScanResult => {+ if (anchorPending && resume === null) {+ for (const ad of skipped) {+ const id = idOf(ad);+ if (id === null || anchors.has(id) || known.has(id)) continue;+ known.add(id);+ fresh.push(ad);+ }+ }+ return { fresh, scannedIds, resume, pagesUsed };+ };+ let cursor = start;+ for (let page = 1; page <= pages; page++) {+ const result = await fetchAds({ limit: undefined, cursor });+ const pageIds = idsOf(result.ads);+ scannedIds.push(...pageIds);+ let reachedBoundary = false;+ for (const ad of result.ads) {+ const id = idOf(ad);+ const ms = epochMsOf(ad);+ if (id !== null && anchors.has(id)) {+ anchorPending = false;+ skipped.length = 0;+ continue;+ }+ const pastBoundary = id !== null && (id === boundaryId || (!anchorPending && seenBefore.has(id)));+ if (pastBoundary || (!anchorPending && before !== null && ms !== null && ms <= before)) {+ reachedBoundary = true;+ break;+ }+ if (anchorPending) {+ skipped.push(ad);+ continue;+ }+ if (id === null || known.has(id) || (before !== null && ms === null)) continue;+ known.add(id);+ fresh.push(ad);+ }+ if (reachedBoundary || result.next === null || result.ads.length === 0) return finish({ resume: null, pagesUsed: page });+ if (page === pages) return finish({ resume: resumeAfterCap({ shifting, anchorPending, anchorIds, pageIds, current: cursor, next: result.next }), pagesUsed: page });+ cursor = result.next;+ }+ return finish({ resume: null, pagesUsed: pages });+}++function resumeAfterCap({ shifting, anchorPending, anchorIds, pageIds, current, next }: { shifting: boolean; anchorPending: boolean; anchorIds: string[]; pageIds: string[]; current: string | undefined; next: string }): Resume {+ if (!shifting) return { cursor: next, anchorIds: [] };+ if (anchorPending) return { cursor: next, anchorIds };+ if (pageIds.length === 0) return { cursor: next, anchorIds: [] };+ return { cursor: current ?? '0', anchorIds: pageIds };+}++function idsOf(ads: unknown[]): string[] {+ return ads.map(idOf).filter((id): id is string => id !== null);+}++async function seed({ store, fetchAds, isRepublish = false }: { store: Store; fetchAds: FetchAds; isRepublish?: boolean }): Promise<void> {+ if (isRepublish && (await seenIds(store)) !== null) return;+ const { ads } = await fetchAds({ limit: undefined, cursor: undefined });+ await store.put(SEEN_KEY, idsOf(ads).slice(0, MAX_SEEN));+ await store.delete(LEGACY_LAST_POLL_KEY);+ await store.delete(BACKLOG_KEY);+}++function backlogOf(value: unknown): Backlog | null {+ const record = foreplayMappers.recordOf(value);+ const cursor = record['cursor'];+ const before = record['before'];+ const anchorIds = record['anchorIds'];+ const boundaryId = record['boundaryId'];+ if (typeof cursor !== 'string' || cursor === '') return null;+ return {+ cursor,+ before: typeof before === 'number' && Number.isFinite(before) ? before : null,+ anchorIds: Array.isArray(anchorIds) ? anchorIds.filter((v): v is string => typeof v === 'string').slice(0, MAX_PAGE_SIZE) : [],+ boundaryId: typeof boundaryId === 'string' && boundaryId !== '' ? boundaryId : null,+ };+}++async function pollNewAds({ store, fetchAds, shifting = false }: { store: Store; fetchAds: FetchAds; shifting?: boolean }): Promise<unknown[]> {+ let seen = await seenIds(store);+ let legacyBefore: number | null = null;+ if (seen === null) {+ const lastPoll = await store.get<unknown>(LEGACY_LAST_POLL_KEY);+ if (typeof lastPoll !== 'number' || !Number.isFinite(lastPoll)) {+ await seed({ store, fetchAds });+ return [];+ }+ seen = [];+ legacyBefore = lastPoll;+ }+ const seenBefore = new Set(seen);+ const known = new Set(seen);+ let budget = MAX_POLL_PAGES;+ let olderFresh: unknown[] = [];+ let newerFresh: unknown[] = [];+ let legacyBoundaryIds: string[] = [];+ let nextBacklog: Backlog | null = null;+ const backlog = backlogOf(await store.get<unknown>(BACKLOG_KEY));+ if (backlog !== null) {+ const result = await scan({ fetchAds, start: backlog.cursor, pages: budget, seenBefore, known, before: backlog.before, anchorIds: backlog.anchorIds, boundaryId: backlog.boundaryId, shifting });+ olderFresh = result.fresh;+ budget -= result.pagesUsed;+ if (result.resume !== null) nextBacklog = { ...result.resume, before: backlog.before, boundaryId: backlog.boundaryId };+ }+ if (nextBacklog === null && budget > 0) {+ const result = await scan({ fetchAds, start: undefined, pages: budget, seenBefore, known, before: legacyBefore, anchorIds: [], boundaryId: null, shifting });+ newerFresh = result.fresh;+ if (legacyBefore !== null) legacyBoundaryIds = result.scannedIds;+ if (result.resume !== null) nextBacklog = { ...result.resume, before: legacyBefore, boundaryId: seen[0] ?? null };+ }+ if (nextBacklog === null) await store.delete(BACKLOG_KEY);+ else await store.put(BACKLOG_KEY, nextBacklog);+ const newerIds = idsOf(newerFresh);+ if (newerIds.length > 0 || legacyBefore !== null) await store.put(SEEN_KEY, [...new Set([...newerIds, ...legacyBoundaryIds, ...seen])].slice(0, MAX_SEEN));+ if (legacyBefore !== null) await store.delete(LEGACY_LAST_POLL_KEY);+ return [...olderFresh.reverse(), ...newerFresh.reverse()];+}++async function testAds({ fetchAds }: { fetchAds: FetchAds }): Promise<unknown[]> {+ const { ads } = await fetchAds({ limit: TEST_LIMIT, cursor: undefined });+ return ads;+}++async function fetchAdPage({ auth, path, query, pageSize }: { auth: ForeplayAuthInput; path: string; query: ForeplayQuery; pageSize: number }): Promise<AdPage> {+ const response = await foreplayClient.request({ auth, path, query });+ const ads = foreplayMappers.listOf(response.body);+ const cursor = foreplayMappers.metadataOf(response.body)['cursor'];+ const next = typeof cursor === 'string' && cursor !== '' ? cursor : typeof cursor === 'number' ? String(cursor) : null;+ return { ads, next: ads.length >= pageSize ? next : null };+}++type Resume = { cursor: string; anchorIds: string[] };++type Backlog = Resume & { before: number | null; boundaryId: string | null };++type ScanParams = { fetchAds: FetchAds; start: string | undefined; pages: number; seenBefore: Set<string>; known: Set<string>; before: number | null; anchorIds: string[]; boundaryId: string | null; shifting: boolean };++type ScanResult = { fresh: unknown[]; scannedIds: string[]; resume: Resume | null; pagesUsed: number };++type AdPage = { ads: unknown[]; next: string | null };++type FetchAds = (params: { limit: number | undefined; cursor: string | undefined }) => Promise<AdPage>;++const foreplayPolling = {+ pageSizeProp,+ legacyPollingIntervalProp,+ pageSizeOf,+ seed,+ pollNewAds,+ testAds,+ fetchAdPage,+ MAX_POLL_PAGES,+};++export { foreplayPolling };+export type { FetchAds, AdPage };diff --git a/packages/pieces/community/foreplay-co/src/lib/common/props.ts b/packages/pieces/community/foreplay-co/src/lib/common/props.tsnew file mode 100644index 00000000000..d37f2a6c63a--- /dev/null+++ b/packages/pieces/community/foreplay-co/src/lib/common/props.ts@@ -0,0 +1,309 @@+import { Property } from '@activepieces/pieces-framework';+import { ForeplayQuery } from './client';++const SORT_ORDERS = ['newest', 'oldest', 'longest_running', 'most_relevant'];+const SWIPEFILE_ORDERS = ['saved_newest', 'newest', 'oldest', 'longest_running', 'most_relevant'];+const BRAND_ORDERS = ['most_ranked', 'least_ranked'];+const DISPLAY_FORMATS = ['video', 'image', 'carousel', 'dco', 'dpa', 'multi_images', 'multi_videos', 'multi_medias', 'event', 'text', 'page_like'];+const PUBLISHER_PLATFORMS = ['facebook', 'instagram', 'audience_network', 'messenger', 'tiktok', 'youtube', 'linkedin', 'threads', 'whatsapp'];+const NICHES = ['accessories', 'app/software', 'beauty', 'business/professional', 'charity/nfp', 'education', 'entertainment', 'fashion', 'food/drink', 'health/wellness', 'home/garden', 'jewelry/watches', 'kids/baby', 'medical', 'other', 'parenting', 'pets', 'real estate', 'service business'];+const LEGACY_NICHES: Record<string, string> = { food: 'food/drink', health: 'health/wellness', home: 'home/garden', technology: 'app/software' };+const DROPPED_NICHES = ['finance', 'sports', 'travel', 'automotive'];+const HUMAN_NICHE_OPTIONS = [+ ...options(NICHES),+ ...[...Object.keys(LEGACY_NICHES), ...DROPPED_NICHES].map((n) => ({ label: `${label(n)} (legacy)`, value: n })),+];+const MARKET_TARGETS = ['b2b', 'b2c'];+const LANGUAGES = ['Afrikaans', 'Albanian', 'Arabic', 'Armenian', 'Azerbaijani', 'Bambara', 'Basque', 'Bengali', 'Bosnian', 'Bulgarian', 'Burmese', 'Catalan, Valencian', 'Central Khmer', 'Chichewa, Chewa, Nyanja', 'Corsican', 'Croatian', 'Czech', 'Danish', 'Dutch, Flemish', 'English', 'Estonian', 'Finnish', 'French', 'Galician', 'Georgian', 'German', 'Greek (modern)', 'Guaraní', 'Hausa', 'Hebrew (modern)', 'Hindi', 'Hungarian', 'Icelandic', 'Indonesian', 'Italian', 'Japanese', 'Javanese', 'Kannada', 'Kazakh', 'Korean', 'Latin', 'Latvian', 'Lingala', 'Lithuanian', 'Luxembourgish, Letzeburgesch', 'Macedonian', 'Malagasy', 'Malay', 'Malayalam', 'Maltese', 'Maori', 'Marathi', 'Mongolian', 'Norwegian', 'Oriya', 'Oromo', 'Persian', 'Polish', 'Portuguese', 'Romanian, Moldavian, Moldovan', 'Russian', 'Serbian', 'Shona', 'Sinhala, Sinhalese', 'Slovak', 'Slovene', 'Spanish, Castilian', 'Sundanese', 'Swedish', 'Telugu', 'Thai', 'Turkish', 'Turkmen', 'Ukrainian', 'Urdu', 'Uzbek', 'Vietnamese', 'Welsh', 'Western Frisian'];+const LANGUAGE_RE = /^[\p{L} ,()-]{2,60}$/u;+const ID_RE = /^[A-Za-z0-9_.:-]{1,128}$/;+const NUMERIC_ID_RE = /^\d{1,30}$/;++function label(value: string): string {+ return value.replace(/_/g, ' ').replace(/(^|[ /])([a-z])/g, (_m, sep: string, ch: string) => `${sep}${ch.toUpperCase()}`);+}++function options(values: string[]) {+ return values.map((value) => ({ label: label(value), value }));+}++function optionalText(value: unknown): string | undefined {+ if (typeof value === 'number' && Number.isFinite(value)) return String(value);+ if (typeof value !== 'string') return undefined;+ const text = value.trim();+ return text === '' ? undefined : text;+}++function requiredText({ value, label }: { value: unknown; label: string }): string {+ const text = optionalText(value);+ if (text === undefined) throw new Error(`${label} is required.`);+ return text;+}++function foreplayId({ value, label }: { value: unknown; label: string }): string {+ const text = requiredText({ value, label });+ if (!ID_RE.test(text)) throw new Error(`${label} must be a Foreplay ID (letters, digits, "_", "-", "." or ":").`);+ return text;+}++function pageId({ value, label }: { value: unknown; label: string }): string {+ const text = requiredText({ value, label });+ if (!NUMERIC_ID_RE.test(text)) throw new Error(`${label} must be a numeric Facebook page ID, e.g. 373652569755921.`);+ return text;+}++function parseInteger({ value, label, min, max }: { value: unknown; label: string; min: number; max: number }): number | undefined {+ if (value === undefined || value === null || value === '') return undefined;+ const parsed = typeof value === 'string' ? Number(value.trim()) : value;+ if (typeof parsed !== 'number' || !Number.isInteger(parsed) || parsed < min || parsed > max) {+ throw new Error(`${label} must be a whole number from ${min} to ${max}.`);+ }+ return parsed;+}++function parseNumber({ value, label, min }: { value: unknown; label: string; min: number }): number | undefined {+ if (value === undefined || value === null || value === '') return undefined;+ const parsed = typeof value === 'string' ? Number(value.trim()) : value;+ if (typeof parsed !== 'number' || !Number.isFinite(parsed) || parsed < min) throw new Error(`${label} must be a number of at least ${min}.`);+ return parsed;+}++function parseBoolean({ value, label }: { value: unknown; label: string }): boolean | undefined {+ const v = Array.isArray(value) && value.length === 1 ? value[0] : value;+ if (v === undefined || v === null || v === '') return undefined;+ if (v === true || v === 'true') return true;+ if (v === false || v === 'false') return false;+ throw new Error(`${label} must be true or false.`);+}++function pad(n: number): string {+ return String(n).padStart(2, '0');+}++function apiDate({ value, label }: { value: unknown; label: string }): string | undefined {+ const text = optionalText(value);+ if (text === undefined) return undefined;+ if (/^\d{4}-\d{2}-\d{2}$/.test(text) && !Number.isNaN(Date.parse(`${text}T00:00:00Z`))) return text;+ const time = Date.parse(text);+ if (Number.isNaN(time)) throw new Error(`${label} must be a date like 2026-10-18 or 2026-10-18T12:00:00Z.`);+ const d = new Date(time);+ return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}:${pad(d.getUTCSeconds())}`;+}++function dayOnly({ value, label }: { value: unknown; label: string }): string | undefined {+ const text = apiDate({ value, label });+ return text === undefined ? undefined : text.slice(0, 10);+}++function stringList({ value, label }: { value: unknown; label: string }): string[] | undefined {+ if (value === undefined || value === null || value === '') return undefined;+ const raw = Array.isArray(value) ? value : typeof value === 'string' ? value.split(',') : null;+ if (raw === null) throw new Error(`${label} must be a list of text values.`);+ const list = raw.map((v) => (typeof v === 'string' ? v.trim() : typeof v === 'number' ? String(v) : '')).filter((v) => v !== '');+ return list.length > 0 ? list : undefined;+}++function enumList({ value, label, allowed, aliases, dropped }: { value: unknown; label: string; allowed: string[]; aliases?: Record<string, string>; dropped?: string[] }): string[] | undefined {+ const list = stringList({ value, label });+ if (list === undefined) return undefined;+ const out: string[] = [];+ const droppedUsed: string[] = [];+ for (const v of list) {+ const lower = v.toLowerCase();+ if (dropped?.includes(lower)) {+ droppedUsed.push(v);+ continue;+ }+ const mapped = aliases?.[lower] ?? lower;+ if (!allowed.includes(mapped)) throw new Error(`${label}: "${v}" is not supported. Use one of: ${allowed.join(', ')}.`);+ out.push(mapped);+ }+ const unique = [...new Set(out)];+ if (unique.length === 0 && droppedUsed.length > 0) throw new Error(`${label}: ${droppedUsed.map((v) => `"${v}"`).join(', ')} ${droppedUsed.length === 1 ? 'is' : 'are'} no longer supported by Foreplay, so this filter would match every ad. Pick one of: ${allowed.join(', ')}, or clear the filter.`);+ return unique.length === 0 ? undefined : unique;+}++function enumValue({ value, label, allowed }: { value: unknown; label: string; allowed: string[] }): string | undefined {+ const text = optionalText(value);+ if (text === undefined) return undefined;+ if (!allowed.includes(text)) throw new Error(`${label} must be one of: ${allowed.join(', ')}.`);+ return text;+}++function languageList({ value, label }: { value: unknown; label: string }): string[] | undefined {+ const list = stringList({ value, label });+ if (list === undefined) return undefined;+ for (const v of list) {+ if (!LANGUAGE_RE.test(v)) throw new Error(`${label}: "${v}" is not a language name or code, e.g. English, french or FR.`);+ }+ return list;+}++function liveValue(value: unknown): string | undefined {+ const live = parseBoolean({ value, label: 'Live Status' });+ return live === undefined ? undefined : String(live);+}++function adFilterQuery(filters: AdFilterInput): ForeplayQuery {+ const query: ForeplayQuery = {+ start_date: apiDate({ value: filters.startDate, label: 'Start Date' }),+ end_date: apiDate({ value: filters.endDate, label: 'End Date' }),+ live: liveValue(filters.live),+ display_format: enumList({ value: filters.displayFormats, label: 'Display Format', allowed: DISPLAY_FORMATS }),+ publisher_platform: enumList({ value: filters.publisherPlatforms, label: 'Publisher Platform', allowed: PUBLISHER_PLATFORMS }),+ niches: enumList({ value: filters.niches, label: 'Niches', allowed: NICHES, aliases: LEGACY_NICHES, dropped: DROPPED_NICHES }),+ market_target: enumList({ value: filters.marketTargets, label: 'Market Target', allowed: MARKET_TARGETS }),+ languages: languageList({ value: filters.languages, label: 'Languages' }),+ video_duration_min: parseNumber({ value: filters.videoDurationMin, label: 'Min Video Duration', min: 0 }),+ video_duration_max: parseNumber({ value: filters.videoDurationMax, label: 'Max Video Duration', min: 0 }),+ running_duration_min_days: parseInteger({ value: filters.runningDurationMinDays, label: 'Min Running Days', min: 0, max: 100_000 }),+ running_duration_max_days: parseInteger({ value: filters.runningDurationMaxDays, label: 'Max Running Days', min: 0, max: 100_000 }),+ };+ const vMin = query['video_duration_min'];+ const vMax = query['video_duration_max'];+ if (typeof vMin === 'number' && typeof vMax === 'number' && vMin > vMax) throw new Error('Min Video Duration must not be greater than Max Video Duration.');+ const rMin = query['running_duration_min_days'];+ const rMax = query['running_duration_max_days'];+ if (typeof rMin === 'number' && typeof rMax === 'number' && rMin > rMax) throw new Error('Min Running Days must not be greater than Max Running Days.');+ const start = query['start_date'];+ const end = query['end_date'];+ if (typeof start === 'string' && typeof end === 'string' && start.slice(0, 10) > end.slice(0, 10)) throw new Error('Start Date must be on or before End Date.');+ return query;+}++function aiAdFilterProps({ withDates = true, withRunningDays = true }: { withDates?: boolean; withRunningDays?: boolean } = {}) {+ return {+ ...(withDates+ ? {+ startDate: Property.ShortText({ displayName: 'Start Date', description: 'Inclusive, YYYY-MM-DD or ISO 8601 date-time.', required: false }),+ endDate: Property.ShortText({ displayName: 'End Date', description: 'Inclusive, YYYY-MM-DD or ISO 8601 date-time.', required: false }),+ }+ : {}),+ live: Property.StaticDropdown({ displayName: 'Live Status', description: 'true = running now, false = stopped; empty = both.', required: false, options: { options: [{ label: 'Active only', value: 'true' }, { label: 'Inactive only', value: 'false' }] } }),+ displayFormats: Property.StaticMultiSelectDropdown({ displayName: 'Display Formats', required: false, options: { options: options(DISPLAY_FORMATS) } }),+ publisherPlatforms: Property.StaticMultiSelectDropdown({ displayName: 'Publisher Platforms', required: false, options: { options: options(PUBLISHER_PLATFORMS) } }),+ niches: Property.StaticMultiSelectDropdown({ displayName: 'Niches', required: false, options: { options: options(NICHES) } }),+ marketTargets: Property.StaticMultiSelectDropdown({ displayName: 'Market Targets', required: false, options: { options: [{ label: 'B2B', value: 'b2b' }, { label: 'B2C', value: 'b2c' }] } }),+ languages: Property.StaticMultiSelectDropdown({ displayName: 'Languages', required: false, options: { options: LANGUAGES.map((l) => ({ label: l, value: l })) } }),+ videoDurationMin: Property.Number({ displayName: 'Min Video Duration (seconds)', required: false }),+ videoDurationMax: Property.Number({ displayName: 'Max Video Duration (seconds)', required: false }),+ ...(withRunningDays+ ? {+ runningDurationMinDays: Property.Number({ displayName: 'Min Running Days', required: false }),+ runningDurationMaxDays: Property.Number({ displayName: 'Max Running Days', required: false }),+ }+ : {}),+ };+}++function aiAdFilterInput(props: Record<string, unknown>): AdFilterInput {+ return {+ startDate: props['startDate'],+ endDate: props['endDate'],+ live: props['live'],+ displayFormats: props['displayFormats'],+ publisherPlatforms: props['publisherPlatforms'],+ niches: props['niches'],+ marketTargets: props['marketTargets'],+ languages: props['languages'],+ videoDurationMin: props['videoDurationMin'],+ videoDurationMax: props['videoDurationMax'],+ runningDurationMinDays: props['runningDurationMinDays'],+ runningDurationMaxDays: props['runningDurationMaxDays'],+ };+}++const HUMAN_LANGUAGE_OPTIONS = [+ { label: 'English', value: 'english' },+ { label: 'French', value: 'french' },+ { label: 'German', value: 'german' },+ { label: 'Italian', value: 'italian' },+ { label: 'Dutch/Flemish', value: 'dutch, flemish' },+ { label: 'Spanish', value: 'spanish' },+ { label: 'Portuguese', value: 'portuguese' },+ { label: 'Romanian', value: 'romanian' },+ { label: 'Russian', value: 'russian' },+ { label: 'Chinese', value: 'chinese' },+ { label: 'Japanese', value: 'japanese' },+ { label: 'Korean', value: 'korean' },+ { label: 'Arabic', value: 'arabic' },+ { label: 'Hindi', value: 'hindi' },+];++function humanAdFilterProps({ withDates = true }: { withDates?: boolean } = {}) {+ return {+ ...(withDates+ ? {+ start_date: Property.DateTime({ displayName: 'Start Date', description: 'Only ads from this date (inclusive).', required: false }),+ end_date: Property.DateTime({ displayName: 'End Date', description: 'Only ads up to this date (inclusive).', required: false }),+ }+ : {}),+ live: Property.StaticDropdown({ displayName: 'Live Status', description: 'Filter by whether the ad is running now.', required: false, options: { options: [{ label: 'Active Only', value: 'true' }, { label: 'Inactive Only', value: 'false' }] } }),+ display_format: Property.StaticMultiSelectDropdown({ displayName: 'Display Format', description: 'Filter by one or more display formats.', required: false, options: { options: options(DISPLAY_FORMATS) } }),+ publisher_platform: Property.StaticMultiSelectDropdown({ displayName: 'Publisher Platform', description: 'Filter by one or more publisher platforms.', required: false, options: { options: options(PUBLISHER_PLATFORMS) } }),+ niches: Property.StaticMultiSelectDropdown({ displayName: 'Niches', description: 'Filter by one or more niches.', required: false, options: { options: HUMAN_NICHE_OPTIONS } }),+ market_target: Property.StaticMultiSelectDropdown({ displayName: 'Market Target', description: 'Filter by market target.', required: false, options: { options: [{ label: 'B2B (Business-to-Business)', value: 'b2b' }, { label: 'B2C (Business-to-Consumer)', value: 'b2c' }] } }),+ languages: Property.StaticMultiSelectDropdown({ displayName: 'Languages', description: 'Filter by ad language.', required: false, options: { options: HUMAN_LANGUAGE_OPTIONS } }),+ };+}++function humanAdFilterInput(props: Record<string, unknown>): AdFilterInput {+ return {+ startDate: props['start_date'],+ endDate: props['end_date'],+ live: props['live'],+ displayFormats: props['display_format'],+ publisherPlatforms: props['publisher_platform'],+ niches: props['niches'],+ marketTargets: props['market_target'],+ languages: props['languages'],+ };+}++function sortOrderProp({ allowed = SORT_ORDERS }: { allowed?: string[] } = {}) {+ return Property.StaticDropdown({ displayName: 'Order', description: `${allowed.join(', ')}. Default ${allowed[0]}.`, required: false, options: { options: options(allowed) } });+}++type AdFilterInput = {+ startDate?: unknown;+ endDate?: unknown;+ live?: unknown;+ displayFormats?: unknown;+ publisherPlatforms?: unknown;+ niches?: unknown;+ marketTargets?: unknown;+ languages?: unknown;+ videoDurationMin?: unknown;+ videoDurationMax?: unknown;+ runningDurationMinDays?: unknown;+ runningDurationMaxDays?: unknown;+};++const foreplayProps = {+ SORT_ORDERS,+ SWIPEFILE_ORDERS,+ BRAND_ORDERS,+ DISPLAY_FORMATS,+ PUBLISHER_PLATFORMS,+ NICHES,+ MARKET_TARGETS,+ optionalText,+ requiredText,+ foreplayId,+ pageId,+ parseInteger,+ parseBoolean,+ apiDate,+ dayOnly,+ stringList,+ enumValue,+ adFilterQuery,+ aiAdFilterProps,+ aiAdFilterInput,+ humanAdFilterProps,+ humanAdFilterInput,+ sortOrderProp,+};++export { foreplayProps };+export type { AdFilterInput };diff --git a/packages/pieces/community/foreplay-co/src/lib/properties.ts b/packages/pieces/community/foreplay-co/src/lib/properties.tsdeleted file mode 100644index b4b9ab62fd5..00000000000--- a/packages/pieces/community/foreplay-co/src/lib/properties.ts+++ /dev/null@@ -1,585 +0,0 @@-import { Property } from '@activepieces/pieces-framework';-import { foreplayCoApiCall } from './common';-import { HttpMethod } from '@activepieces/pieces-common';-import { foreplayCoAuth } from '..';--// Common dropdown options (keeping existing functionality)-const orderOptions = () => ({- options: [- { label: 'Newest', value: 'newest' },- { label: 'Oldest', value: 'oldest' },- { label: 'Longest Running', value: 'longest_running' },- { label: 'Most Relevant', value: 'most_relevant' },- ],-});--const liveStatusOptions = () => ({- options: [- { label: 'Active Only', value: 'true' },- { label: 'Inactive Only', value: 'false' },- ],-});--const displayFormatOptions = () => ({- options: [- { label: 'Video', value: 'video' },- { label: 'Carousel', value: 'carousel' },- { label: 'Image', value: 'image' },- { label: 'DCO', value: 'dco' },- { label: 'DPA', value: 'dpa' },- { label: 'Multi Images', value: 'multi_images' },- { label: 'Multi Videos', value: 'multi_videos' },- { label: 'Multi Medias', value: 'multi_medias' },- { label: 'Event', value: 'event' },- { label: 'Text', value: 'text' },- ],-});--const publisherPlatformOptions = () => ({- options: [- { label: 'Facebook', value: 'facebook' },- { label: 'Instagram', value: 'instagram' },- { label: 'Audience Network', value: 'audience_network' },- { label: 'Messenger', value: 'messenger' },- { label: 'TikTok', value: 'tiktok' },- { label: 'YouTube', value: 'youtube' },- { label: 'LinkedIn', value: 'linkedin' },- { label: 'Threads', value: 'threads' },- ],-});--const nicheOptions = () => ({- options: [- { label: 'Accessories', value: 'accessories' },- { label: 'App/Software', value: 'app/software' },- { label: 'Beauty', value: 'beauty' },- { label: 'Business/Professional', value: 'business/professional' },- { label: 'Education', value: 'education' },- { label: 'Entertainment', value: 'entertainment' },- { label: 'Fashion', value: 'fashion' },- { label: 'Finance', value: 'finance' },- { label: 'Food', value: 'food' },- { label: 'Health', value: 'health' },- { label: 'Home', value: 'home' },- { label: 'Pets', value: 'pets' },- { label: 'Sports', value: 'sports' },- { label: 'Technology', value: 'technology' },- { label: 'Travel', value: 'travel' },- { label: 'Automotive', value: 'automotive' },- { label: 'Other', value: 'other' },- ],-});--const marketTargetOptions = () => ({- options: [- { label: 'B2B (Business-to-Business)', value: 'b2b' },- { label: 'B2C (Business-to-Consumer)', value: 'b2c' },- ],-});--const languageOptions = () => ({- options: [- { label: 'English', value: 'english' },- { label: 'French', value: 'french' },- { label: 'German', value: 'german' },- { label: 'Italian', value: 'italian' },- { label: 'Dutch/Flemish', value: 'dutch, flemish' },- { label: 'Spanish', value: 'spanish' },- { label: 'Portuguese', value: 'portuguese' },- { label: 'Romanian', value: 'romanian' },- { label: 'Russian', value: 'russian' },- { label: 'Chinese', value: 'chinese' },- { label: 'Japanese', value: 'japanese' },- { label: 'Korean', value: 'korean' },- { label: 'Arabic', value: 'arabic' },- { label: 'Hindi', value: 'hindi' },- ],-});--// Action Properties-export const findAds = () => ({- query: Property.ShortText({- displayName: 'Search Query',- description:- 'Search text for ad name or description. Leave empty to search all ads with filters only.',- required: false,- }),- start_date: Property.DateTime({- displayName: 'Start Date',- description:- 'Start date (inclusive). Format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS',- required: false,- }),- end_date: Property.DateTime({- displayName: 'End Date',- description:- 'End date (inclusive). Format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS',- required: false,- }),- order: Property.StaticDropdown({- displayName: 'Order',- description:- 'Order of results: newest (default), oldest, longest_running, or most_relevant',- required: false,- options: orderOptions(),- }),- live: Property.StaticDropdown({- displayName: 'Live Status',- description:- 'Filter ads by live status. true means currently active ads, false means inactive ads.',- required: false,- options: liveStatusOptions(),- }),- display_format: Property.MultiSelectDropdown({- auth: foreplayCoAuth,- displayName: 'Display Format',- description: 'Filter by one or more display formats',- required: false,- refreshers: [],- options: async () => displayFormatOptions(),- }),- publisher_platform: Property.MultiSelectDropdown({- auth: foreplayCoAuth,- displayName: 'Publisher Platform',- description: 'Filter by one or more publisher platforms',- required: false,- refreshers: [],- options: async () => publisherPlatformOptions(),- }),- niches: Property.MultiSelectDropdown({- auth: foreplayCoAuth,- displayName: 'Niches',- description: 'Filter by one or more niches',- required: false,- refreshers: [],- options: async () => nicheOptions(),- }),- market_target: Property.MultiSelectDropdown({- auth: foreplayCoAuth,- displayName: 'Market Target',- description: 'Filter by market target',- required: false,- refreshers: [],- options: async () => marketTargetOptions(),- }),- languages: Property.MultiSelectDropdown({- auth: foreplayCoAuth,- displayName: 'Languages',- description: 'Filter by languages. Accepts various language formats.',- required: false,- refreshers: [],- options: async () => languageOptions(),- }),- cursor: Property.ShortText({- displayName: 'Cursor',- description:- 'Cursor for pagination. Use the cursor value from the previous response.',- required: false,- }),- limit: Property.Number({- displayName: 'Limit',- description:- 'Pagination limit (default 10, max 250). Controls the number of ads returned per request.',- required: false,- defaultValue: 10,- }),-});--export const getAdById = () => ({- ad_id: Property.ShortText({- displayName: 'Ad ID',- description:- 'The unique identifier of the ad (e.g., "ad_1234567890"). You can find this ID from other Foreplay actions or the platform.',- required: true,- }),-});--export const getAdsByPage = () => ({- page_id: Property.ShortText({- displayName: 'Page ID',- description:- 'The numeric Facebook page ID (e.g., "123456789"). You can find this in your Facebook page settings or from other Foreplay actions.',- required: true,- }),- start_date: Property.DateTime({- displayName: 'Start Date',- description:- 'Start date (inclusive). Format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS',- required: false,- }),- end_date: Property.DateTime({- displayName: 'End Date',- description:- 'End date (inclusive). Format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS',- required: false,- }),- order: Property.StaticDropdown({- displayName: 'Order',- description:- 'Order of results: newest (default), oldest, longest_running, or most_relevant',- required: false,- options: orderOptions(),- }),- live: Property.StaticDropdown({- displayName: 'Live Status',- description:- 'Filter ads by live status. true means currently active ads, false means inactive ads.',- required: false,- options: liveStatusOptions(),- }),- display_format: Property.MultiSelectDropdown({- auth: foreplayCoAuth,- displayName: 'Display Format',- description: 'Filter by one or more display formats',- required: false,- refreshers: [],- options: async () => displayFormatOptions(),- }),- publisher_platform: Property.MultiSelectDropdown({- auth: foreplayCoAuth,- displayName: 'Publisher Platform',- description: 'Filter by one or more publisher platforms',- required: false,- refreshers: [],- options: async () => publisherPlatformOptions(),- }),- niches: Property.MultiSelectDropdown({- auth: foreplayCoAuth,- displayName: 'Niches',- description: 'Filter by one or more niches',- required: false,- refreshers: [],- options: async () => nicheOptions(),- }),- market_target: Property.MultiSelectDropdown({- auth: foreplayCoAuth,- displayName: 'Market Target',- description: 'Filter by market target',- required: false,- refreshers: [],- options: async () => marketTargetOptions(),- }),- languages: Property.MultiSelectDropdown({- auth: foreplayCoAuth,- displayName: 'Languages',- description: 'Filter by languages. Accepts various language formats.',- required: false,- refreshers: [],- options: async () => languageOptions(),- }),- cursor: Property.ShortText({- displayName: 'Cursor',- description:- 'Cursor for pagination. Use the cursor value from the previous response.',- required: false,- }),- limit: Property.Number({- displayName: 'Limit',- description:- 'Pagination limit (default 10, max 250). Controls the number of ads returned per request.',- required: false,- defaultValue: 10,- }),-});--export const findBrands = () => ({- query: Property.ShortText({- displayName: 'Brand Name',- description:- 'Brand name to search for (e.g., "Nike", "Apple"). Supports fuzzy matching for partial names.',- required: true,- }),- limit: Property.Number({- displayName: 'Limit',- description: 'Number of brands to return (max 10).',- required: false,- defaultValue: 10,- }),-});--export const findBoards = () => ({- offset: Property.Number({- displayName: 'Offset',- description: 'The offset for pagination (default 0).',- required: false,- defaultValue: 0,- }),- limit: Property.Number({- displayName: 'Limit',- description: 'The limit for pagination (default 10, max 10).',- required: false,- defaultValue: 10,- }),-});--// Trigger Properties-export const newAdInBoard = () => ({- board_id: Property.Dropdown({- auth: foreplayCoAuth,- displayName: 'Board',- description: 'Select the board to monitor for new ads.',- required: true,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- options: [],- placeholder: 'Please connect your account first',- };- }-- try {- const response = await foreplayCoApiCall({- apiKey: auth,- method: HttpMethod.GET,- resourceUri: '/api/boards',- });-- const responseBody = response.body;- if (responseBody.metadata && responseBody.metadata.success === true) {- const boards = responseBody.data || [];- return {- options: boards.map((board: any) => ({- label: board.name || board.title || `Board ${board.id}`,- value: board.id,- })),- };- } else {- return {- disabled: true,- options: [],- placeholder: 'Failed to load boards',- };- }- } catch (error) {- return {- disabled: true,- options: [],- placeholder: 'Error loading boards',- };- }- },- }),- polling_interval: Property.Number({- displayName: 'Polling Interval (minutes)',- description: 'How often to check for new ads (in minutes).',- required: false,- defaultValue: 5,- }),- live: Property.StaticDropdown({- displayName: 'Live Status',- description:- 'Filter ads by live status. true means currently active ads, false means inactive ads.',- required: false,- options: liveStatusOptions(),- }),- display_format: Property.MultiSelectDropdown({- auth: foreplayCoAuth,- displayName: 'Display Format',- description: 'Filter by one or more display formats',- required: false,- refreshers: [],- options: async () => displayFormatOptions(),- }),- publisher_platform: Property.MultiSelectDropdown({- auth: foreplayCoAuth,- displayName: 'Publisher Platform',- description: 'Filter by one or more publisher platforms',- required: false,- refreshers: [],- options: async () => publisherPlatformOptions(),- }),- niches: Property.MultiSelectDropdown({- auth: foreplayCoAuth,- displayName: 'Niches',- description: 'Filter by one or more niches',- required: false,- refreshers: [],- options: async () => nicheOptions(),- }),- market_target: Property.MultiSelectDropdown({- auth: foreplayCoAuth,- displayName: 'Market Target',- description: 'Filter by market target',- required: false,- refreshers: [],- options: async () => marketTargetOptions(),- }),- languages: Property.MultiSelectDropdown({- auth: foreplayCoAuth,- displayName: 'Languages',- description: 'Filter by languages. Accepts various language formats.',- required: false,- refreshers: [],- options: async () => languageOptions(),- }),-});--export const newAdInSpyder = () => ({- brand_id: Property.Dropdown({- auth: foreplayCoAuth,- displayName: 'Brand',- description: 'Select the brand to monitor for new ads.',- required: true,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- options: [],- placeholder: 'Please connect your account first',- };- }-- try {- const response = await foreplayCoApiCall({- apiKey: auth,- method: HttpMethod.GET,- resourceUri: '/api/spyder/brands',- });-- const responseBody = response.body;- if (responseBody.metadata && responseBody.metadata.success === true) {- const brands = responseBody.data || [];- return {- options: brands.map((brand: any) => ({- label: brand.name || brand.id,- value: brand.id,- })),- };- } else {- return {- disabled: true,- options: [],- placeholder: 'Failed to load brands',- };- }- } catch (error) {- return {- disabled: true,- options: [],- placeholder: 'Error loading brands',- };- }- },- }),- polling_interval: Property.Number({- displayName: 'Polling Interval (minutes)',- description: 'How often to check for new ads (in minutes).',- required: false,- defaultValue: 5,- }),- live: Property.StaticDropdown({- displayName: 'Live Status',- description:- 'Filter ads by live status. true means currently active ads, false means inactive ads.',- required: false,- options: liveStatusOptions(),- }),- display_format: Property.MultiSelectDropdown({- auth: foreplayCoAuth,- displayName: 'Display Format',- description: 'Filter by one or more display formats',- required: false,- refreshers: [],- options: async () => displayFormatOptions(),- }),- publisher_platform: Property.MultiSelectDropdown({- auth: foreplayCoAuth,- displayName: 'Publisher Platform',- description: 'Filter by one or more publisher platforms',- required: false,- refreshers: [],- options: async () => publisherPlatformOptions(),- }),- niches: Property.MultiSelectDropdown({- auth: foreplayCoAuth,- displayName: 'Niches',- description: 'Filter by one or more niches',- required: false,- refreshers: [],- options: async () => nicheOptions(),- }),- market_target: Property.MultiSelectDropdown({- auth: foreplayCoAuth,- displayName: 'Market Target',- description: 'Filter by market target',- required: false,- refreshers: [],- options: async () => marketTargetOptions(),- }),- languages: Property.MultiSelectDropdown({- auth: foreplayCoAuth,- displayName: 'Languages',- description: 'Filter by languages. Accepts various language formats.',- required: false,- refreshers: [],- options: async () => languageOptions(),- }),-});--export const newSwipefileAd = () => ({- polling_interval: Property.Number({- displayName: 'Polling Interval (minutes)',- description: 'How often to check for new ads (in minutes).',- required: false,- defaultValue: 5,- }),- start_date: Property.DateTime({- displayName: 'Start Date',- description: 'Filter ads published after this date.',- required: false,- }),- end_date: Property.DateTime({- displayName: 'End Date',- description: 'Filter ads published before this date.',- required: false,- }),- live: Property.StaticDropdown({- displayName: 'Live Status',- description: 'Filter by ad status (active/inactive).',- required: false,- options: liveStatusOptions(),- }),- display_format: Property.MultiSelectDropdown({- auth: foreplayCoAuth,- displayName: 'Display Format',- description: 'Filter by ad format (video, image, carousel, etc.).',- required: false,- refreshers: [],- options: async () => displayFormatOptions(),- }),- publisher_platform: Property.MultiSelectDropdown({- auth: foreplayCoAuth,- displayName: 'Publisher Platform',- description: 'Filter by platform (Facebook, Instagram, etc.).',- required: false,- refreshers: [],- options: async () => publisherPlatformOptions(),- }),- niches: Property.MultiSelectDropdown({- auth: foreplayCoAuth,- displayName: 'Niches',- description: 'Filter by industry/category.',- required: false,- refreshers: [],- options: async () => nicheOptions(),- }),- market_target: Property.MultiSelectDropdown({- auth: foreplayCoAuth,- displayName: 'Market Target',- description: 'Filter by target audience (B2B, B2C).',- required: false,- refreshers: [],- options: async () => marketTargetOptions(),- }),- languages: Property.MultiSelectDropdown({- auth: foreplayCoAuth,- displayName: 'Languages',- description: 'Filter by ad language.',- required: false,- refreshers: [],- options: async () => languageOptions(),- }),-});diff --git a/packages/pieces/community/foreplay-co/src/lib/schemas.ts b/packages/pieces/community/foreplay-co/src/lib/schemas.tsdeleted file mode 100644index cab3e3a0a07..00000000000--- a/packages/pieces/community/foreplay-co/src/lib/schemas.ts+++ /dev/null@@ -1,149 +0,0 @@-import * as z from 'zod/mini'--// Common validation schemas for dropdown options-const orderOptions = z.enum([- 'newest',- 'oldest',- 'longest_running',- 'most_relevant',-]);-const liveStatusOptions = z.enum(['true', 'false']);-const displayFormatOptions = z.enum([- 'video',- 'carousel',- 'image',- 'dco',- 'dpa',- 'multi_images',- 'multi_videos',- 'multi_medias',- 'event',- 'text',-]);-const publisherPlatformOptions = z.enum([- 'facebook',- 'instagram',- 'audience_network',- 'messenger',- 'tiktok',- 'youtube',- 'linkedin',- 'threads',-]);-const nicheOptions = z.enum([- 'accessories',- 'app/software',- 'beauty',- 'business/professional',- 'education',- 'entertainment',- 'fashion',- 'finance',- 'food',- 'health',- 'home',- 'pets',- 'sports',- 'technology',- 'travel',- 'automotive',- 'other',-]);-const marketTargetOptions = z.enum(['b2b', 'b2c']);-const languageOptions = z.enum([- 'english',- 'french',- 'german',- 'italian',- 'dutch, flemish',- 'spanish',- 'portuguese',- 'romanian',- 'russian',- 'chinese',- 'japanese',- 'korean',- 'arabic',- 'hindi',-]);-const brandOrderOptions = z.enum(['most_ranked', 'least_ranked']);--// Action Schemas (Zod objects for validation)-export const findAdsSchema = z.object({- query: z.optional(z.string()),- start_date: z.optional(z.string()),- end_date: z.optional(z.string()),- order: z.optional(orderOptions),- live: z.optional(liveStatusOptions),- display_format: z.optional(z.array(displayFormatOptions)),- publisher_platform: z.optional(z.array(publisherPlatformOptions)),- niches: z.optional(z.array(nicheOptions)),- market_target: z.optional(z.array(marketTargetOptions)),- languages: z.optional(z.array(languageOptions)),- cursor: z.optional(z.string()),- limit: z.optional(z.number().check(z.minimum(1), z.maximum(250))),-});--export const getAdByIdSchema = z.object({- ad_id: z.string().check(z.minLength(1, 'Ad ID is required')),-});--export const getAdsByPageSchema = z.object({- page_id: z.string().check(z.minLength(1, 'Page ID is required')),- start_date: z.optional(z.string()),- end_date: z.optional(z.string()),- order: z.optional(orderOptions),- live: z.optional(liveStatusOptions),- display_format: z.optional(z.array(displayFormatOptions)),- publisher_platform: z.optional(z.array(publisherPlatformOptions)),- niches: z.optional(z.array(nicheOptions)),- market_target: z.optional(z.array(marketTargetOptions)),- languages: z.optional(z.array(languageOptions)),- cursor: z.optional(z.string()),- limit: z.optional(z.number().check(z.minimum(1), z.maximum(250))),-});--export const findBrandsSchema = z.object({- query: z.string().check(z.minLength(1, 'Brand name is required')),- limit: z.optional(z.number().check(z.minimum(1), z.maximum(10))),-});--export const findBoardsSchema = z.object({- offset: z.optional(z.number().check(z.minimum(0))),- limit: z.optional(z.number().check(z.minimum(1), z.maximum(10))),-});--// Trigger Schemas-export const newAdInBoardSchema = z.object({- board_id: z.string().check(z.minLength(1, 'Board ID is required')),- polling_interval: z.optional(z.number().check(z.minimum(1), z.maximum(1440))),- live: z.optional(liveStatusOptions),- display_format: z.optional(z.array(displayFormatOptions)),- publisher_platform: z.optional(z.array(publisherPlatformOptions)),- niches: z.optional(z.array(nicheOptions)),- market_target: z.optional(z.array(marketTargetOptions)),- languages: z.optional(z.array(languageOptions)),-});--export const newAdInSpyderSchema = z.object({- brand_id: z.string().check(z.minLength(1, 'Brand ID is required')),- polling_interval: z.optional(z.number().check(z.minimum(1), z.maximum(1440))),- live: z.optional(liveStatusOptions),- display_format: z.optional(z.array(displayFormatOptions)),- publisher_platform: z.optional(z.array(publisherPlatformOptions)),- niches: z.optional(z.array(nicheOptions)),- market_target: z.optional(z.array(marketTargetOptions)),- languages: z.optional(z.array(languageOptions)),-});--export const newSwipefileAdSchema = z.object({- polling_interval: z.optional(z.number().check(z.minimum(1), z.maximum(1440))),- start_date: z.optional(z.string()),- end_date: z.optional(z.string()),- live: z.optional(liveStatusOptions),- display_format: z.optional(z.array(displayFormatOptions)),- publisher_platform: z.optional(z.array(publisherPlatformOptions)),- niches: z.optional(z.array(nicheOptions)),- market_target: z.optional(z.array(marketTargetOptions)),- languages: z.optional(z.array(languageOptions)),-});diff --git a/packages/pieces/community/foreplay-co/src/lib/triggers/index.ts b/packages/pieces/community/foreplay-co/src/lib/triggers/index.tsindex bff98c331a0..62680f44aff 100644--- a/packages/pieces/community/foreplay-co/src/lib/triggers/index.ts+++ b/packages/pieces/community/foreplay-co/src/lib/triggers/index.ts@@ -1,3 +1,5 @@-export { newAdInSpyder } from './new-ad-in-spyder';-export { newAdInBoard } from './new-ad-in-board';-export { newSwipefileAd } from './new-swipefile-ad';+import { newAdInBoard } from './new-ad-in-board';+import { newAdInSpyder } from './new-ad-in-spyder';+import { newSwipefileAd } from './new-swipefile-ad';++export { newAdInSpyder, newAdInBoard, newSwipefileAd };diff --git a/packages/pieces/community/foreplay-co/src/lib/triggers/new-ad-in-board.ts b/packages/pieces/community/foreplay-co/src/lib/triggers/new-ad-in-board.tsindex 8834e916b91..967da4b7bdc 100644--- a/packages/pieces/community/foreplay-co/src/lib/triggers/new-ad-in-board.ts+++ b/packages/pieces/community/foreplay-co/src/lib/triggers/new-ad-in-board.ts@@ -1,182 +1,79 @@-import { createTrigger, TriggerStrategy, Property, AppConnectionValueForAuthProperty } from "@activepieces/pieces-framework";-import { foreplayCoApiCall } from "../common";-import { HttpMethod, Polling, DedupeStrategy, pollingHelper } from "@activepieces/pieces-common";-import { newAdInBoard as newAdInBoardProperties } from "../properties";-import { newAdInBoardSchema } from "../schemas";-import { foreplayCoAuth } from "../..";--const getBoardsDropdown = async (auth: AppConnectionValueForAuthProperty<typeof foreplayCoAuth>) => {- try {- const response = await foreplayCoApiCall({- apiKey: auth,- method: HttpMethod.GET,- resourceUri: '/api/boards',- });-- const responseBody = response.body;-- if (responseBody.metadata && responseBody.metadata.success === true && responseBody.data) {- return {- options: responseBody.data.map((board: any) => ({- label: board.name || board.title || `Board ${board.id}`,- value: board.id- }))- };- }-- return { options: [] };- } catch (error) {- console.error('Error fetching boards for dropdown:', error);- return { options: [] };- }-};--const polling: Polling<AppConnectionValueForAuthProperty<typeof foreplayCoAuth>, Record<string, any>> = {- strategy: DedupeStrategy.TIMEBASED,- items: async ({ auth, propsValue, lastFetchEpochMS }) => {- const { board_id } = propsValue;-- console.log(`[New Ad in Board Polling] Fetching ads for board: ${board_id}, lastFetch: ${new Date(lastFetchEpochMS || 0).toISOString()}`);-- const queryParams: Record<string, string> = {- board_id: board_id,- limit: String(250), // Max limit to get more ads- order: 'newest'- };-- // Add optional filters if provided- if (propsValue['live'] !== undefined) {- queryParams['live'] = String(propsValue['live'] === 'true');- }- if (propsValue['display_format'] && propsValue['display_format'].length > 0) {- (queryParams as any).display_format = propsValue['display_format'];- }- if (propsValue['publisher_platform'] && propsValue['publisher_platform'].length > 0) {- (queryParams as any).publisher_platform = propsValue['publisher_platform'];- }- if (propsValue['niches'] && propsValue['niches'].length > 0) {- (queryParams as any).niches = propsValue['niches'];- }- if (propsValue['market_target'] && propsValue['market_target'].length > 0) {- (queryParams as any).market_target = propsValue['market_target'];- }- if (propsValue['languages'] && propsValue['languages'].length > 0) {- (queryParams as any).languages = propsValue['languages'];- }-- const response = await foreplayCoApiCall({- apiKey: auth,- method: HttpMethod.GET,- resourceUri: '/api/board/ads',- queryParams,- });-- const responseBody = response.body;-- if (!responseBody.metadata || !responseBody.metadata.success) {- console.log(`[New Ad in Board Polling] API call failed:`, responseBody);- return [];- }-- const ads = responseBody.data || [];- console.log(`[New Ad in Board Polling] Found ${ads.length} ads for board ${board_id}`);-- return ads.map((ad: any) => ({- epochMilliSeconds: new Date(ad.created_at).getTime(),- data: ad,- }));- }-};--export const newAdInBoard = createTrigger({+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';+import { foreplayCoAuth } from '../auth';+import { ForeplayAuthInput, foreplayClient } from '../common/client';+import { foreplayMappers } from '../common/mappers';+import { foreplayOutputSchemas } from '../common/output-schemas';+import { foreplayPolling } from '../common/polling';+import { foreplayProps } from '../common/props';+import { legacyEventMetadata, sampleAd } from './sample-ad';++function fetcher({ auth, propsValue }: { auth: ForeplayAuthInput; propsValue: Record<string, unknown> }) {+ const boardId = foreplayProps.foreplayId({ value: propsValue['board_id'], label: 'Board' });+ const filters = foreplayProps.adFilterQuery(foreplayProps.humanAdFilterInput(propsValue));+ const pageSize = foreplayPolling.pageSizeOf(propsValue['page_size']);+ return async ({ limit, cursor }: { limit: number | undefined; cursor: string | undefined }) => {+ const size = limit ?? pageSize;+ const page = await foreplayPolling.fetchAdPage({ auth, path: '/api/board/ads', query: { board_id: boardId, ...filters, order: 'newest', limit: size, cursor }, pageSize: size });+ return { ...page, ads: page.ads.map((ad) => withBoard({ ad, boardId })) };+ };+}++function withBoard({ ad, boardId }: { ad: unknown; boardId: string }) {+ const record = foreplayMappers.recordOf(ad);+ const title = foreplayMappers.str(record['title']) ?? foreplayMappers.str(record['name']);+ return { ...record, title, board_id: boardId, metadata: legacyEventMetadata };+}++const newAdInBoard = createTrigger({+ auth: foreplayCoAuth,name: 'newAdInBoard',- classification: 'READ',displayName: 'New Ad in Board',- auth: foreplayCoAuth,- description: 'Triggers when a new ad is added to the selected board.',+ description: 'Triggers when a new ad shows up in the selected board.',aiMetadata: {- description: 'Fires when a new ad is added to the selected Foreplay board, optionally narrowed by filters such as platform, format, niche, market, language, and live-only status. Each event represents one ad newly saved to that board.',+ description: 'Fires when an ad that was not there before appears among the newest ads of the selected Foreplay board, optionally narrowed by platform, format, niche, market, language and live status. Each event is one ad. Costs 1 Foreplay credit per ad checked on every poll.',},+ classification: 'READ',type: TriggerStrategy.POLLING,- sampleData: {- id: "ad_789",- board_id: "board_456",- brand_id: "brand_456",- title: "New Campaign Ad",- description: "Latest marketing campaign",- live: true,- display_format: "video",- publisher_platform: ["facebook"],- niches: ["fashion"],- market_target: "b2c",- languages: ["en"],- created_at: "2024-01-15T10:30:00Z",- updated_at: "2024-01-15T10:30:00Z"+ sampleData: { ...sampleAd, title: sampleAd.name, board_id: 'aBcD1234EfGh5678', metadata: legacyEventMetadata },+ outputSchema: foreplayOutputSchemas.boardAd,+ props: {+ board_id: Property.Dropdown({+ auth: foreplayCoAuth,+ displayName: 'Board',+ description: 'The board to watch.',+ required: true,+ refreshers: [],+ options: async ({ auth }) => {+ if (!auth) return { disabled: true, options: [], placeholder: 'Connect your Foreplay account first.' };+ try {+ const response = await foreplayClient.request({ auth, path: '/api/boards' });+ const boards = foreplayMappers.listOf(response.body).map(foreplayMappers.board);+ return {+ disabled: false,+ options: boards.filter((b) => b.id !== null).map((b) => ({ label: b.name ?? `Board ${b.id}`, value: b.id ?? '' })),+ placeholder: boards.length === 0 ? 'No boards found in this Foreplay account.' : undefined,+ };+ } catch (error) {+ return { disabled: true, options: [], placeholder: error instanceof Error ? error.message : 'Could not load boards.' };+ }+ },+ }),+ page_size: foreplayPolling.pageSizeProp(),+ polling_interval: foreplayPolling.legacyPollingIntervalProp(),+ ...foreplayProps.humanAdFilterProps({ withDates: false }),},-- props: newAdInBoardProperties(),-- async test(context) {- // Validate props using Zod schema- const validation = newAdInBoardSchema.safeParse(context.propsValue);- if (!validation.success) {- throw new Error(`Validation failed: ${validation.error.message}`);- }-- return await pollingHelper.test(polling, {- auth: context.auth,- store: context.store,- propsValue: context.propsValue,- files: context.files,- });+ async onEnable({ auth, propsValue, store, isRepublish }) {+ await foreplayPolling.seed({ store, fetchAds: fetcher({ auth, propsValue }), isRepublish });},-- async onEnable(context) {- await pollingHelper.onEnable(polling, {- auth: context.auth,- store: context.store,- propsValue: context.propsValue,- });+ async onDisable() {+ return;},-- async onDisable(context) {- await pollingHelper.onDisable(polling, {- store: context.store,- propsValue: context.propsValue,- auth: context.auth,- });+ async test({ auth, propsValue }) {+ return foreplayPolling.testAds({ fetchAds: fetcher({ auth, propsValue }) });},+ async run({ auth, propsValue, store }) {+ return foreplayPolling.pollNewAds({ store, fetchAds: fetcher({ auth, propsValue }) });+ },+});- async run(context) {- // Validate props using Zod schema- const validation = newAdInBoardSchema.safeParse(context.propsValue);- if (!validation.success) {- throw new Error(`Validation failed: ${validation.error.message}`);- }-- const result = await pollingHelper.poll(polling, {- auth: context.auth,- store: context.store,- propsValue: context.propsValue,- files: context.files,- });-- // Transform the result to match our expected format- return result.map((item: any) => ({- id: item.data.id,- board_id: context.propsValue.board_id,- brand_id: item.data.brand_id,- title: item.data.title || item.data.name,- description: item.data.description,- live: item.data.live,- display_format: item.data.display_format,- publisher_platform: item.data.publisher_platform,- niches: item.data.niches,- market_target: item.data.market_target,- languages: item.data.languages,- created_at: item.data.created_at,- updated_at: item.data.updated_at,- metadata: { success: true, message: 'New ad detected' }- }));- }-});\ No newline at end of file+export { newAdInBoard };diff --git a/packages/pieces/community/foreplay-co/src/lib/triggers/new-ad-in-spyder.ts b/packages/pieces/community/foreplay-co/src/lib/triggers/new-ad-in-spyder.tsindex 00e0ea174e0..adc05c9b0c3 100644--- a/packages/pieces/community/foreplay-co/src/lib/triggers/new-ad-in-spyder.ts+++ b/packages/pieces/community/foreplay-co/src/lib/triggers/new-ad-in-spyder.ts@@ -1,158 +1,75 @@-import { AppConnectionValueForAuthProperty, createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';-import { foreplayCoApiCall } from '../common';-import {- HttpMethod,- Polling,- DedupeStrategy,- pollingHelper,-} from '@activepieces/pieces-common';-import { newAdInSpyder as newAdInSpyderProperties } from '../properties';-import { newAdInSpyderSchema } from '../schemas';-import { foreplayCoAuth } from '../..';--const polling: Polling<AppConnectionValueForAuthProperty<typeof foreplayCoAuth>, Record<string, any>> = {- strategy: DedupeStrategy.TIMEBASED,- items: async ({ auth, propsValue }) => {- const { brand_id } = propsValue;-- // Build query parameters with user's filter preferences- const queryParams = new URLSearchParams();- queryParams.append('brand_id', brand_id);- queryParams.append('limit', String(50)); // Reasonable default for polling- queryParams.append('order', 'newest');-- // Add optional filters if provided- if (propsValue['live']) {- queryParams.append('live', String(propsValue['live']));- }- if (- propsValue['display_format'] &&- propsValue['display_format'].length > 0- ) {- propsValue['display_format'].forEach((format: unknown) => {- queryParams.append('display_format', String(format));- });- }- if (- propsValue['publisher_platform'] &&- propsValue['publisher_platform'].length > 0- ) {- propsValue['publisher_platform'].forEach((platform: unknown) => {- queryParams.append('publisher_platform', String(platform));- });- }- if (propsValue['niches'] && propsValue['niches'].length > 0) {- propsValue['niches'].forEach((niche: unknown) => {- queryParams.append('niches', String(niche));- });- }- if (propsValue['market_target'] && propsValue['market_target'].length > 0) {- propsValue['market_target'].forEach((target: unknown) => {- queryParams.append('market_target', String(target));- });- }- if (propsValue['languages'] && propsValue['languages'].length > 0) {- propsValue['languages'].forEach((language: unknown) => {- queryParams.append('languages', String(language));- });- }-- const queryString = queryParams.toString();- const fullUrl = `/api/spyder/brand/ads?${queryString}`;-- const response = await foreplayCoApiCall({- apiKey: auth,- method: HttpMethod.GET,- resourceUri: fullUrl,- });-- const responseBody = response.body;-- if (!responseBody.metadata || !responseBody.metadata.success) {- return [];- }-- const ads = responseBody.data || [];-- return ads.map((ad: any) => ({- epochMilliSeconds: new Date(ad.created_at).getTime(),- data: ad,- }));- },-};--export const newAdInSpyder = createTrigger({+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';+import { foreplayCoAuth } from '../auth';+import { ForeplayAuthInput, foreplayClient } from '../common/client';+import { foreplayMappers } from '../common/mappers';+import { foreplayOutputSchemas } from '../common/output-schemas';+import { foreplayPolling } from '../common/polling';+import { foreplayProps } from '../common/props';+import { sampleAd } from './sample-ad';++const MAX_DROPDOWN_PAGES = 30;++function fetcher({ auth, propsValue }: { auth: ForeplayAuthInput; propsValue: Record<string, unknown> }) {+ const brandId = foreplayProps.foreplayId({ value: propsValue['brand_id'], label: 'Brand' });+ const filters = foreplayProps.adFilterQuery(foreplayProps.humanAdFilterInput(propsValue));+ const pageSize = foreplayPolling.pageSizeOf(propsValue['page_size']);+ return async ({ limit, cursor }: { limit: number | undefined; cursor: string | undefined }) => {+ const size = limit ?? pageSize;+ return foreplayPolling.fetchAdPage({ auth, path: '/api/spyder/brand/ads', query: { brand_id: brandId, ...filters, order: 'newest', limit: size, cursor }, pageSize: size });+ };+}++const newAdInSpyder = createTrigger({+ auth: foreplayCoAuth,name: 'newAdInSpyder',- classification: 'READ',displayName: 'New Ad in Spyder',- description: 'Triggers when new ads are added for a brand in Spyder.',+ description: 'Triggers when Spyder finds a new ad for a tracked brand.',aiMetadata: {- description: 'Fires when Foreplay Spyder detects a newly tracked ad for the specified brand, optionally narrowed by filters such as platform, format, niche, market, language, and live-only status. Each event represents one newly surfaced ad for that brand.',+ description: 'Fires when a new ad appears among the newest ads Foreplay Spyder has collected for the selected tracked brand, optionally narrowed by platform, format, niche, market, language and live status. Each event is one ad. Costs 1 Foreplay credit per ad checked on every poll.',},+ classification: 'READ',type: TriggerStrategy.POLLING,- sampleData: {- id: 'ad_123456789',- brand_id: 'brand_987654321',- title: 'New Summer Sale Ad',- description: 'A great summer sale ad.',- live: true,- display_format: 'video',- publisher_platform: ['facebook'],- niches: ['fashion'],- market_target: 'b2c',- languages: ['en'],- created_at: '2024-01-15T10:30:00Z',- updated_at: '2024-01-15T10:30:00Z',+ sampleData: sampleAd,+ outputSchema: foreplayOutputSchemas.rawAd,+ props: {+ brand_id: Property.Dropdown({+ auth: foreplayCoAuth,+ displayName: 'Brand',+ description: 'A brand from your Spyder watchlist.',+ required: true,+ refreshers: [],+ options: async ({ auth }) => {+ if (!auth) return { disabled: true, options: [], placeholder: 'Connect your Foreplay account first.' };+ try {+ const options: { label: string; value: string }[] = [];+ for (let page = 0; page < MAX_DROPDOWN_PAGES; page++) {+ const response = await foreplayClient.request({ auth, path: '/api/spyder/brands', query: { offset: page * 10, limit: 10 } });+ const brands = foreplayMappers.listOf(response.body).map(foreplayMappers.brand);+ for (const b of brands) if (b.id !== null) options.push({ label: b.name ?? b.id, value: b.id });+ if (brands.length < 10) break;+ }+ return { disabled: false, options, placeholder: options.length === 0 ? 'No brands in your Spyder watchlist.' : undefined };+ } catch (error) {+ return { disabled: true, options: [], placeholder: error instanceof Error ? error.message : 'Could not load Spyder brands.' };+ }+ },+ }),+ page_size: foreplayPolling.pageSizeProp(),+ polling_interval: foreplayPolling.legacyPollingIntervalProp(),+ ...foreplayProps.humanAdFilterProps({ withDates: false }),},-- props: newAdInSpyderProperties(),- auth: foreplayCoAuth,- async test(context) {- // Validate props using Zod schema- const validation = newAdInSpyderSchema.safeParse(context.propsValue);- if (!validation.success) {- throw new Error(`Validation failed: ${validation.error.message}`);- }-- return await pollingHelper.test(polling, {- auth: context.auth,- store: context.store,- propsValue: context.propsValue,- files: context.files,- });+ async onEnable({ auth, propsValue, store, isRepublish }) {+ await foreplayPolling.seed({ store, fetchAds: fetcher({ auth, propsValue }), isRepublish });},-- async onEnable(context) {- await pollingHelper.onEnable(polling, {- auth: context.auth,- store: context.store,- propsValue: context.propsValue,- });+ async onDisable() {+ return;},-- async onDisable(context) {- await pollingHelper.onDisable(polling, {- store: context.store,- propsValue: context.propsValue,- auth: context.auth,- });+ async test({ auth, propsValue }) {+ return foreplayPolling.testAds({ fetchAds: fetcher({ auth, propsValue }) });},-- async run(context) {- // Validate props using Zod schema- const validation = newAdInSpyderSchema.safeParse(context.propsValue);- if (!validation.success) {- throw new Error(`Validation failed: ${validation.error.message}`);- }-- const result = await pollingHelper.poll(polling, {- auth: context.auth,- store: context.store,- propsValue: context.propsValue,- files: context.files,- });-- // Return clean ad data for automation workflows- return result.map((item: any) => item.data);+ async run({ auth, propsValue, store }) {+ return foreplayPolling.pollNewAds({ store, fetchAds: fetcher({ auth, propsValue }) });},});++export { newAdInSpyder };diff --git a/packages/pieces/community/foreplay-co/src/lib/triggers/new-swipefile-ad.ts b/packages/pieces/community/foreplay-co/src/lib/triggers/new-swipefile-ad.tsindex c9a2900eb71..4863e270fcc 100644--- a/packages/pieces/community/foreplay-co/src/lib/triggers/new-swipefile-ad.ts+++ b/packages/pieces/community/foreplay-co/src/lib/triggers/new-swipefile-ad.ts@@ -1,167 +1,52 @@-import { createTrigger, TriggerStrategy, Property, AppConnectionValueForAuthProperty } from "@activepieces/pieces-framework";-import { foreplayCoApiCall } from "../common";-import { HttpMethod, Polling, DedupeStrategy, pollingHelper } from "@activepieces/pieces-common";-import { newSwipefileAd as newSwipefileAdProperties } from "../properties";-import { newSwipefileAdSchema } from "../schemas";-import { foreplayCoAuth } from "../..";--const polling: Polling<AppConnectionValueForAuthProperty<typeof foreplayCoAuth>, Record<string, any>> = {- strategy: DedupeStrategy.TIMEBASED,- items: async ({ auth, propsValue, lastFetchEpochMS }) => {- console.log(`[New Swipefile Ad Polling] Fetching swipefile ads, lastFetch: ${new Date(lastFetchEpochMS || 0).toISOString()}`);-- const queryParams: Record<string, string> = {- limit: String(250), // Max limit to get more ads- order: 'newest'- };-- // Add optional filters if provided- if (propsValue['start_date']) {- queryParams['start_date'] = propsValue['start_date'];- }- if (propsValue['end_date']) {- queryParams['end_date'] = propsValue['end_date'];- }- if (propsValue['live'] !== undefined) {- queryParams['live'] = String(propsValue['live'] === 'true');- }- if (propsValue['display_format'] && propsValue['display_format'].length > 0) {- (queryParams as any).display_format = propsValue['display_format'];- }- if (propsValue['publisher_platform'] && propsValue['publisher_platform'].length > 0) {- (queryParams as any).publisher_platform = propsValue['publisher_platform'];- }- if (propsValue['niches'] && propsValue['niches'].length > 0) {- (queryParams as any).niches = propsValue['niches'];- }- if (propsValue['market_target'] && propsValue['market_target'].length > 0) {- (queryParams as any).market_target = propsValue['market_target'];- }- if (propsValue['languages'] && propsValue['languages'].length > 0) {- (queryParams as any).languages = propsValue['languages'];- }-- const response = await foreplayCoApiCall({- apiKey: auth,- method: HttpMethod.GET,- resourceUri: '/api/swipefile/ads',- queryParams,- });-- const responseBody = response.body;-- if (!responseBody.metadata || !responseBody.metadata.success) {- console.log(`[New Swipefile Ad Polling] API call failed:`, responseBody);- return [];- }-- const ads = responseBody.data || [];- console.log(`[New Swipefile Ad Polling] Found ${ads.length} swipefile ads`);-- return ads.map((ad: any) => ({- epochMilliSeconds: new Date(ad.created_at).getTime(),- data: ad,- }));- }-};--export const newSwipefileAd = createTrigger({+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';+import { foreplayCoAuth } from '../auth';+import { ForeplayAuthInput } from '../common/client';+import { foreplayMappers } from '../common/mappers';+import { foreplayOutputSchemas } from '../common/output-schemas';+import { foreplayPolling } from '../common/polling';+import { foreplayProps } from '../common/props';+import { legacyEventMetadata, sampleAd } from './sample-ad';++function fetcher({ auth, propsValue }: { auth: ForeplayAuthInput; propsValue: Record<string, unknown> }) {+ const filters = foreplayProps.adFilterQuery(foreplayProps.humanAdFilterInput(propsValue));+ const pageSize = foreplayPolling.pageSizeOf(propsValue['page_size']);+ return async ({ limit, cursor }: { limit: number | undefined; cursor: string | undefined }) => {+ const size = limit ?? pageSize;+ const offset = cursor === undefined ? 0 : Number(cursor);+ const { ads } = await foreplayPolling.fetchAdPage({ auth, path: '/api/swipefile/ads', query: { ...filters, order: 'saved_newest', limit: size, offset }, pageSize: size });+ return { ads: ads.map((ad) => ({ ...foreplayMappers.recordOf(ad), metadata: legacyEventMetadata })), next: ads.length >= size ? String(offset + ads.length) : null };+ };+}++const newSwipefileAd = createTrigger({+ auth: foreplayCoAuth,name: 'newSwipefileAd',- classification: 'READ',displayName: 'New Swipefile Ad',- description: 'Triggers when a new ad is added to your swipefile collection.',+ description: 'Triggers when a new ad is saved to your swipe file.',aiMetadata: {- description: 'Fires when a new ad is saved to the authenticated account\'s swipefile collection, optionally narrowed by filters such as date range, platform, format, niche, market, language, and live-only status. Each event represents one ad newly added to the swipefile.',+ description: 'Fires when an ad is newly saved to the Foreplay user\'s swipe file (checked newest saved first), optionally narrowed by ad date range, platform, format, niche, market, language and live status. Each event is one ad. Costs 1 Foreplay credit per ad checked on every poll (at most 5 pages per poll). Known limit: Foreplay pages the swipe file only by offset, with no stable cursor or saved-after filter, so if ads are saved or removed while a burst larger than 5 pages is still being worked through, one ad may be missed or repeated.',},+ classification: 'READ',type: TriggerStrategy.POLLING,- sampleData: {- id: "ad_123456789",- brand_id: "brand_987654321",- brand_name: "Nike",- title: "Just Do It - New Collection",- description: "Discover our latest athletic wear collection",- live: true,- display_format: "video",- publisher_platform: ["facebook"],- niches: ["sports", "fashion"],- market_target: "b2c",- languages: ["en"],- created_at: "2024-01-15T10:30:00Z",- updated_at: "2024-01-15T10:30:00Z",- media_urls: [- "https://example.com/video1.mp4",- "https://example.com/image1.jpg"- ],- ad_library_id: "123456789",- ad_library_url: "https://www.facebook.com/ads/library/?active_status=all&ad_type=all&country=US&view_all_page_id=123456789"+ sampleData: { ...sampleAd, metadata: legacyEventMetadata },+ outputSchema: foreplayOutputSchemas.swipefileAd,+ props: {+ page_size: foreplayPolling.pageSizeProp(),+ polling_interval: foreplayPolling.legacyPollingIntervalProp(),+ ...foreplayProps.humanAdFilterProps(),},-- props: newSwipefileAdProperties(),- auth: foreplayCoAuth,- async test(context) {- // Validate props using Zod schema- const validation = newSwipefileAdSchema.safeParse(context.propsValue);- if (!validation.success) {- throw new Error(`Validation failed: ${validation.error.message}`);- }-- return await pollingHelper.test(polling, {- auth: context.auth,- store: context.store,- propsValue: context.propsValue,- files: context.files,- });+ async onEnable({ auth, propsValue, store, isRepublish }) {+ await foreplayPolling.seed({ store, fetchAds: fetcher({ auth, propsValue }), isRepublish });},-- async onEnable(context) {- await pollingHelper.onEnable(polling, {- auth: context.auth,- store: context.store,- propsValue: context.propsValue,- });+ async onDisable() {+ return;},-- async onDisable(context) {- await pollingHelper.onDisable(polling, {- store: context.store,- propsValue: context.propsValue,- auth: context.auth,- });+ async test({ auth, propsValue }) {+ return foreplayPolling.testAds({ fetchAds: fetcher({ auth, propsValue }) });},+ async run({ auth, propsValue, store }) {+ return foreplayPolling.pollNewAds({ store, fetchAds: fetcher({ auth, propsValue }), shifting: true });+ },+});- async run(context) {- // Validate props using Zod schema- const validation = newSwipefileAdSchema.safeParse(context.propsValue);- if (!validation.success) {- throw new Error(`Validation failed: ${validation.error.message}`);- }-- const result = await pollingHelper.poll(polling, {- auth: context.auth,- store: context.store,- propsValue: context.propsValue,- files: context.files,- });-- // Transform the result to match our expected format- return result.map((item: any) => ({- id: item.data.id,- brand_id: item.data.brand_id,- brand_name: item.data.brand_name,- title: item.data.title,- description: item.data.description,- live: item.data.live,- display_format: item.data.display_format,- publisher_platform: item.data.publisher_platform,- niches: item.data.niches,- market_target: item.data.market_target,- languages: item.data.languages,- created_at: item.data.created_at,- updated_at: item.data.updated_at,- media_urls: item.data.media_urls,- ad_library_id: item.data.ad_library_id,- ad_library_url: item.data.ad_library_url,- metadata: { success: true, message: 'New ad detected' }- }));- }-});\ No newline at end of file+export { newSwipefileAd };diff --git a/packages/pieces/community/foreplay-co/src/lib/triggers/sample-ad.ts b/packages/pieces/community/foreplay-co/src/lib/triggers/sample-ad.tsnew file mode 100644index 00000000000..b9a78ff56e8--- /dev/null+++ b/packages/pieces/community/foreplay-co/src/lib/triggers/sample-ad.ts@@ -0,0 +1,28 @@+const sampleAd = {+ id: 'Xk2mP9qLr4TzW8vN1aBc',+ ad_id: '1234567890123456',+ name: 'Summer Sale - Video 1',+ brand_id: 'Br4nD1d5aMpLe00xYz12',+ description: 'Our biggest summer sale is here. Up to 50% off everything.',+ headline: 'Shop the Summer Sale',+ cta_title: 'Shop Now',+ cta_type: 'SHOP_NOW',+ link_url: 'https://example.com/summer-sale',+ display_format: 'video',+ publisher_platform: ['facebook', 'instagram'],+ niches: ['fashion'],+ languages: ['English'],+ market_target: 'b2c',+ live: true,+ started_running: 1760745600000,+ thumbnail: 'https://cdn.example.com/thumb.jpg',+ image: null,+ video: 'https://cdn.example.com/video.mp4',+ video_duration: 28.5,+ full_transcription: 'Summer is here and so are the savings.',+ foreplay_url: 'https://app.foreplay.co/share/ad/Xk2mP9qLr4TzW8vN1aBc',+};++const legacyEventMetadata = { success: true, message: 'New ad detected' };++export { sampleAd, legacyEventMetadata };diff --git a/packages/pieces/community/foreplay-co/test/foreplay.test.ts b/packages/pieces/community/foreplay-co/test/foreplay.test.tsnew file mode 100644index 00000000000..c6678b7b6ee--- /dev/null+++ b/packages/pieces/community/foreplay-co/test/foreplay.test.ts@@ -0,0 +1,668 @@+import { httpClient, HttpMethod } from '@activepieces/pieces-common';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { foreplayCo } from '../src';+import { findAds, findBoards, findBrands, getAdById, getAdsByPage } from '../src/lib/actions';+import { discoverBrandsByAds } from '../src/lib/actions/ai/discover-brands-by-ads';+import { findBrandsByDomain } from '../src/lib/actions/ai/find-brands-by-domain';+import { getAd } from '../src/lib/actions/ai/get-ad';+import { getBrandAnalytics } from '../src/lib/actions/ai/get-brand-analytics';+import { getCreditUsage } from '../src/lib/actions/ai/get-credit-usage';+import { getLensReport } from '../src/lib/actions/ai/get-lens-report';+import { getSpyderBrand } from '../src/lib/actions/ai/get-spyder-brand';+import { getSpyderTopAds } from '../src/lib/actions/ai/get-spyder-top-ads';+import { listAdDuplicates } from '../src/lib/actions/ai/list-ad-duplicates';+import { listBoardAds } from '../src/lib/actions/ai/list-board-ads';+import { listBoardBrands } from '../src/lib/actions/ai/list-board-brands';+import { listBoards } from '../src/lib/actions/ai/list-boards';+import { listBrandAds } from '../src/lib/actions/ai/list-brand-ads';+import { listPageAds } from '../src/lib/actions/ai/list-page-ads';+import { listSpyderBrandAds } from '../src/lib/actions/ai/list-spyder-brand-ads';+import { listSpyderBrands } from '../src/lib/actions/ai/list-spyder-brands';+import { listSpyderRankedAds } from '../src/lib/actions/ai/list-spyder-ranked-ads';+import { listSpyderRelatedPages } from '../src/lib/actions/ai/list-spyder-related-pages';+import { listSwipefileAds } from '../src/lib/actions/ai/list-swipefile-ads';+import { searchAds } from '../src/lib/actions/ai/search-ads';+import { searchBrands } from '../src/lib/actions/ai/search-brands';+import { foreplayCoAuth } from '../src/lib/auth';+import { newAdInBoard, newAdInSpyder, newSwipefileAd } from '../src/lib/triggers';++const auth = { secret_text: ' fp_key ' };+const BASE = 'https://public.api.foreplay.co';++function call({ target, method, args }: { target: unknown; method: string; args: Record<string, unknown> }) {+ return Reflect.apply(Reflect.get(Object(target), method), target, [args]);+}++function run({ action, propsValue }: { action: unknown; propsValue: Record<string, unknown> }) {+ return call({ target: action, method: 'run', args: { auth, propsValue } });+}++function okWith({ data, metadata = {}, headers = {} }: { data: unknown; metadata?: Record<string, unknown>; headers?: Record<string, string> }) {+ return { status: 200, headers, body: { metadata: { success: true, status_code: 200, ...metadata }, data } };+}++function ok(data: unknown) {+ return okWith({ data });+}++function mock(...responses: unknown[]) {+ const spy = vi.spyOn(httpClient, 'sendRequest');+ for (const r of responses) spy.mockResolvedValueOnce(Object(r));+ return spy;+}++function httpFailure({ status, body }: { status: number; body: unknown }) {+ return Object.assign(new Error('http failure'), { response: { status, body } });+}++function urlOf(spy: ReturnType<typeof mock>): URL {+ return nthUrl({ spy, index: 0 });+}++function nthUrl({ spy, index }: { spy: ReturnType<typeof mock>; index: number }): URL {+ return new URL(String(spy.mock.calls[index][0].url));+}++function memoryStore() {+ const data = new Map<string, unknown>();+ return {+ data,+ get: async (key: string) => (data.has(key) ? data.get(key) : null),+ put: async (key: string, value: unknown) => {+ data.set(key, value);+ return value;+ },+ delete: async (key: string) => {+ data.delete(key);+ },+ };+}++const rawAd = (id: string) => ({ id, ad_id: `pub_${id}`, name: `Ad ${id}`, brand_id: 'brand_1', publisher_platform: ['facebook'], live: true, started_running: 1760745600, foreplay_url: `https://app.foreplay.co/x/${id}` });++afterEach(() => vi.restoreAllMocks());++const aiActions = [searchAds, getAd, listAdDuplicates, listPageAds, listBrandAds, searchBrands, findBrandsByDomain, discoverBrandsByAds, getBrandAnalytics, listBoards, listBoardBrands, listBoardAds, listSwipefileAds, listSpyderBrands, getSpyderBrand, listSpyderBrandAds, getSpyderTopAds, listSpyderRankedAds, listSpyderRelatedPages, getCreditUsage, getLensReport];+const humanActions = [findAds, findBoards, findBrands, getAdById, getAdsByPage];++describe('metadata', () => {+ it.each(aiActions)('$name is ai, read-only, with schema', (a) => {+ expect(a.audience).toBe('ai');+ expect(a.outputSchema).toBeDefined();+ expect(typeof a.aiMetadata?.description).toBe('string');+ expect(a.aiMetadata?.idempotent).toBe(true);+ expect(['READ', 'SEARCH']).toContain(a.classification);+ });+ it.each(humanActions)('$name is human with schema', (a) => {+ expect(a.audience).toBe('human');+ expect(a.outputSchema).toBeDefined();+ });+ it('registers every action and the custom api call', () => {+ const actions = Object.values(foreplayCo.actions());+ expect(actions).toHaveLength(27);+ expect(actions.filter((a) => a.audience === 'ai')).toHaveLength(21);+ expect(foreplayCo.minimumSupportedRelease).toBe('0.88.2');+ });+});++describe('client', () => {+ it('sends the raw API key, GET, no redirects, repeated array params', async () => {+ const spy = mock(okWith({ data: [rawAd('a1')], metadata: { cursor: 'c2' }, headers: { 'x-credit-cost': '1', 'x-credits-remaining': '99' } }));+ const out = await run({ action: searchAds, propsValue: { query: ' shoes ', displayFormats: ['video', 'image'], niches: ['food'], live: 'false', startDate: '2026-01-02T03:04:05.000Z', endDate: '2026-02-01', limit: 1 } });+ const req = spy.mock.calls[0][0];+ expect(req.method).toBe(HttpMethod.GET);+ expect(req.headers).toMatchObject({ Authorization: 'fp_key' });+ expect(req.followRedirects).toBe(false);+ const url = urlOf(spy);+ expect(url.origin + url.pathname).toBe(`${BASE}/api/discovery/ads`);+ expect(url.searchParams.getAll('display_format')).toEqual(['video', 'image']);+ expect(url.searchParams.getAll('niches')).toEqual(['food/drink']);+ expect(url.searchParams.get('query')).toBe('shoes');+ expect(url.searchParams.get('live')).toBe('false');+ expect(url.searchParams.get('start_date')).toBe('2026-01-02 03:04:05');+ expect(url.searchParams.get('end_date')).toBe('2026-02-01');+ expect(url.searchParams.get('limit')).toBe('1');+ expect(out).toMatchObject({ count: 1, hasMore: true, nextCursor: 'c2', creditCost: 1, creditsRemaining: 99 });+ expect(out.items[0]).toMatchObject({ id: 'a1', adId: 'pub_a1', publisherPlatforms: ['facebook'], startedRunning: '2025-10-18T00:00:00.000Z', foreplayUrl: 'https://app.foreplay.co/x/a1' });+ });+ it('reports no next page when fewer items than the limit come back', async () => {+ mock(okWith({ data: [rawAd('a1')], metadata: { cursor: 'c2' } }));+ const out = await run({ action: searchAds, propsValue: { limit: 5 } });+ expect(out).toMatchObject({ hasMore: false, nextCursor: null });+ });+ it('surfaces the Foreplay error message with a hint', async () => {+ vi.spyOn(httpClient, 'sendRequest').mockRejectedValueOnce(httpFailure({ status: 402, body: { metadata: { success: false, message: 'An error occurred' }, error: { message: 'Not enough credits' } } }));+ await expect(run({ action: getAd, propsValue: { adId: 'a1' } })).rejects.toThrow('Foreplay API error (402): Not enough credits. Your Foreplay account is out of API credits.');+ });+ it('formats 422 validation details', async () => {+ vi.spyOn(httpClient, 'sendRequest').mockRejectedValueOnce(httpFailure({ status: 422, body: { detail: [{ loc: ['query', 'limit'], msg: 'Input should be less than or equal to 250' }] } }));+ await expect(run({ action: getAd, propsValue: { adId: 'a1' } })).rejects.toThrow('limit: Input should be less than or equal to 250');+ });+ it('throws on a 200 with success false', async () => {+ mock({ status: 200, headers: {}, body: { metadata: { success: false, status_code: 404, message: 'Ad not found' }, data: [] } });+ await expect(run({ action: getAd, propsValue: { adId: 'a1' } })).rejects.toThrow('Foreplay API error (404): Ad not found');+ });+ it('retries a 429 after a fixed backoff (HttpError has no headers) then succeeds', async () => {+ vi.useFakeTimers();+ const spy = vi.spyOn(httpClient, 'sendRequest');+ spy.mockRejectedValueOnce(httpFailure({ status: 429, body: { error: { message: 'slow down' } } }));+ spy.mockResolvedValueOnce(Object(ok([])));+ const pending = run({ action: listBoards, propsValue: {} });+ await vi.advanceTimersByTimeAsync(1_999);+ expect(spy).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(1);+ const out = await pending;+ vi.useRealTimers();+ expect(spy).toHaveBeenCalledTimes(2);+ expect(out).toMatchObject({ items: [], count: 0 });+ });+ it('gives up after repeated 429s with the vendor text', async () => {+ const spy = vi.spyOn(httpClient, 'sendRequest');+ vi.useFakeTimers();+ for (let i = 0; i < 3; i++) spy.mockRejectedValueOnce(httpFailure({ status: 429, body: { error: { message: 'rate limited' } } }));+ const pending = expect(run({ action: listBoards, propsValue: {} })).rejects.toThrow('Foreplay API error (429): rate limited');+ await vi.advanceTimersByTimeAsync(6_000);+ await pending;+ vi.useRealTimers();+ expect(spy).toHaveBeenCalledTimes(3);+ });+ it('rejects a missing key before calling Foreplay', async () => {+ const spy = vi.spyOn(httpClient, 'sendRequest');+ await expect(call({ target: listBoards, method: 'run', args: { auth: { secret_text: ' ' }, propsValue: {} } })).rejects.toThrow('no API key');+ expect(spy).not.toHaveBeenCalled();+ });+});++describe('validation', () => {+ it.each([+ [searchAds, { limit: 251 }, 'Limit'],+ [searchAds, { niches: ['bogus'] }, 'Niches: "bogus" is not supported'],+ [searchAds, { startDate: '2026-02-02', endDate: '2026-01-01' }, 'Start Date must be on or before End Date'],+ [searchAds, { videoDurationMin: 30, videoDurationMax: 10 }, 'Min Video Duration'],+ [searchAds, { live: 'maybe' }, 'true or false'],+ [getAd, { adId: '../x' }, 'Foreplay ID'],+ [listPageAds, { pageId: 'nike' }, 'numeric Facebook page ID'],+ [listBrandAds, { brandIds: [] }, 'Brand IDs is required'],+ [findBrandsByDomain, { domain: 'not a domain' }, 'Domain'],+ [discoverBrandsByAds, {}, 'at least one filter'],+ [getLensReport, { lensId: '5', from: '2026-02-01', to: '2026-01-01', breakdownType: 'overall', provider: 'facebook' }, 'From must be on or before To'],+ [getLensReport, { lensId: '5', from: '2026-01-01', to: '2026-01-02', breakdownType: 'bad', provider: 'facebook' }, 'Breakdown'],+ ])('%#', async (action, propsValue, message) => {+ const spy = vi.spyOn(httpClient, 'sendRequest');+ await expect(run({ action, propsValue })).rejects.toThrow(message);+ expect(spy).not.toHaveBeenCalled();+ });+});++describe('ai actions', () => {+ it('get_ad by public id encodes the path', async () => {+ const spy = mock(ok(rawAd('a:1')));+ const out = await run({ action: getAd, propsValue: { adId: 'a:1' } });+ expect(spy.mock.calls[0][0].url).toBe(`${BASE}/api/ad/a%3A1`);+ expect(out).toMatchObject({ id: 'a:1', name: 'Ad a:1' });+ });+ it('get_ad null data (internal id) explains the public id', async () => {+ mock(ok(null));+ await expect(run({ action: getAd, propsValue: { adId: 'a1' } })).rejects.toThrow('public ad library ID');+ });+ it('get_ad fails clearly on empty data', async () => {+ mock(ok([]));+ await expect(run({ action: getAd, propsValue: { adId: 'a1' } })).rejects.toThrow('no record');+ });+ it('list_ad_duplicates', async () => {+ const spy = mock(ok([rawAd('d1'), rawAd('d2')]));+ const out = await run({ action: listAdDuplicates, propsValue: { adId: 'a1' } });+ expect(spy.mock.calls[0][0].url).toBe(`${BASE}/api/ad/duplicates/a1`);+ expect(out.count).toBe(2);+ });+ it('list_ad_duplicates rejects an internal id', async () => {+ const spy = mock(ok([]));+ await expect(run({ action: listAdDuplicates, propsValue: { adId: 'ypIh0DwLFjabd6aDqxGo' } })).rejects.toThrow(/public ad library ID/);+ expect(spy).not.toHaveBeenCalled();+ });+ it('list_page_ads sends page id and collect', async () => {+ const spy = mock(ok([]));+ await run({ action: listPageAds, propsValue: { pageId: ' 123 ', collectIfEmpty: true, order: 'oldest' } });+ const url = urlOf(spy);+ expect(url.pathname).toBe('/api/brand/getAdsByPageId');+ expect(Object.fromEntries(url.searchParams)).toEqual({ page_id: '123', collect: 'true', order: 'oldest', limit: '10' });+ });+ it('list_brand_ads repeats brand_ids', async () => {+ const spy = mock(ok([]));+ await run({ action: listBrandAds, propsValue: { brandIds: ['b1', 'b2'] } });+ expect(urlOf(spy).searchParams.getAll('brand_ids')).toEqual(['b1', 'b2']);+ });+ it('search_brands maps brands', async () => {+ const spy = mock(ok([{ id: 'b1', name: 'Nike', description: { text: 'Just do it' }, ad_library_id: '15087023444', ads_count: 5, active_ads_count: 2, niches: [], websites: ['nike.com'] }]));+ const out = await run({ action: searchBrands, propsValue: { query: 'nike', includeEmpty: true, minAds: 1 } });+ expect(Object.fromEntries(urlOf(spy).searchParams)).toEqual({ query: 'nike', limit: '10', include_empty: 'true', min_ads: '1' });+ expect(out.items[0]).toMatchObject({ id: 'b1', description: 'Just do it', pageId: '15087023444', adsCount: 5, activeAdsCount: 2 });+ });+ it('find_brands_by_domain', async () => {+ const spy = mock(ok([]));+ await run({ action: findBrandsByDomain, propsValue: { domain: 'https://allbirds.com', order: 'least_ranked' } });+ expect(Object.fromEntries(urlOf(spy).searchParams)).toEqual({ domain: 'https://allbirds.com', limit: '10', order: 'least_ranked' });+ });+ it('discover_brands_by_ads', async () => {+ const spy = mock(ok([]));+ await run({ action: discoverBrandsByAds, propsValue: { niches: ['beauty'], publisherPlatforms: ['tiktok'] } });+ expect(urlOf(spy).pathname).toBe('/api/discovery/brands/explore');+ expect(urlOf(spy).searchParams.get('publisher_platform')).toBe('tiktok');+ });+ it('discover_brands_by_ads does not offer running-day filters the endpoint ignores', () => {+ expect(discoverBrandsByAds.props).not.toHaveProperty('runningDurationMinDays');+ expect(discoverBrandsByAds.props).not.toHaveProperty('runningDurationMaxDays');+ expect(listBoardAds.props).toHaveProperty('runningDurationMinDays');+ });+ it('get_brand_analytics only points agents at search_brands for pageId', () => {+ expect(getBrandAnalytics.aiMetadata?.description).not.toContain('or ads');+ });+ it('get_brand_analytics', async () => {+ const spy = mock(ok([{ date: '2026-10-01', active_count: 3, inactive_count: 1, video: 2, image: 1 }]));+ const out = await run({ action: getBrandAnalytics, propsValue: { id: ' 2029 ', startDate: '2026-10-01' } });+ expect(Object.fromEntries(urlOf(spy).searchParams)).toEqual({ id: '2029', start_date: '2026-10-01' });+ expect(out.items[0]).toEqual({ date: '2026-10-01', activeCount: 3, inactiveCount: 1, formats: { video: 2, image: 1 } });+ });+ it('get_brand_analytics rejects a non-numeric brand id', async () => {+ const spy = mock(ok([]));+ await expect(run({ action: getBrandAnalytics, propsValue: { id: 'b1' } })).rejects.toThrow('numeric Facebook page ID');+ expect(spy).not.toHaveBeenCalled();+ });+ it('list_boards returns all boards', async () => {+ const spy = mock(ok([{ id: 'bd1', name: 'Inspo', description: '', created_at: 1737912010 }]));+ const out = await run({ action: listBoards, propsValue: {} });+ expect(spy.mock.calls[0][0].url).toBe(`${BASE}/api/boards`);+ expect(out.items[0]).toEqual({ id: 'bd1', name: 'Inspo', description: '', createdAt: '2025-01-26T17:20:10.000Z' });+ });+ it('list_board_brands pages by offset', async () => {+ const spy = mock(ok(Array.from({ length: 10 }, (_, i) => ({ id: `b${i}`, name: `B${i}` }))));+ const out = await run({ action: listBoardBrands, propsValue: { boardId: 'bd1', offset: 10 } });+ expect(Object.fromEntries(urlOf(spy).searchParams)).toEqual({ board_id: 'bd1', limit: '10', offset: '10' });+ expect(out).toMatchObject({ count: 10, hasMore: true, nextOffset: 20 });+ });+ it('list_board_ads', async () => {+ const spy = mock(ok([]));+ await run({ action: listBoardAds, propsValue: { boardId: 'bd1', cursor: 'abc' } });+ expect(Object.fromEntries(urlOf(spy).searchParams)).toEqual({ board_id: 'bd1', cursor: 'abc', limit: '10' });+ });+ it('list_swipefile_ads', async () => {+ const spy = mock(ok([rawAd('s1')]));+ const out = await run({ action: listSwipefileAds, propsValue: { order: 'saved_newest', limit: 1 } });+ expect(Object.fromEntries(urlOf(spy).searchParams)).toEqual({ order: 'saved_newest', limit: '1', offset: '0' });+ expect(out).toMatchObject({ hasMore: true, nextOffset: 1 });+ });+ it('list_spyder_brands', async () => {+ const spy = mock(ok([{ id: 'b1', name: 'Nike' }]));+ const out = await run({ action: listSpyderBrands, propsValue: {} });+ expect(urlOf(spy).pathname).toBe('/api/spyder/brands');+ expect(out).toMatchObject({ count: 1, hasMore: false, nextOffset: null });+ });+ it('get_spyder_brand', async () => {+ const spy = mock(ok({ id: 'b1', name: 'Nike' }));+ const out = await run({ action: getSpyderBrand, propsValue: { brandId: 'b1' } });+ expect(spy.mock.calls[0][0].url).toBe(`${BASE}/api/spyder/brand?brand_id=b1`);+ expect(out).toMatchObject({ id: 'b1', name: 'Nike' });+ });+ it('list_spyder_brand_ads', async () => {+ const spy = mock(ok([]));+ await run({ action: listSpyderBrandAds, propsValue: { brandId: 'b1', languages: ['English'] } });+ expect(Object.fromEntries(urlOf(spy).searchParams)).toEqual({ brand_id: 'b1', languages: 'English', limit: '10' });+ });+ it('get_spyder_top_ads', async () => {+ const spy = mock(ok({ pageId: '123', date: '2026-10-01', compareDaysAgo: 7, ads: [{ id: 'a1', ad_id: 'p1', rank: 1, previous_rank: 4 }] }));+ const out = await run({ action: getSpyderTopAds, propsValue: { pageId: '123', date: '2026-10-01' } });+ expect(spy.mock.calls[0][0].url).toBe(`${BASE}/api/spyder/brand/rankings/123/top-overview?date=2026-10-01&compareDaysAgo=7`);+ expect(out).toMatchObject({ pageId: '123', compareDaysAgo: 7, count: 1 });+ expect(out.items[0]).toMatchObject({ id: 'a1', rank: 1, previousRank: 4, ad: null });+ });+ it('list_spyder_ranked_ads reads nested ranking and pagination', async () => {+ const spy = mock(ok({ page_id: '123', category: 'breakout', ads: [{ ...rawAd('a1'), ranking: { rank: 2, previous_rank: 9, peak_rank: 1, days_running: 12 } }], pagination: { offset: 0, limit: 1, total: 5, has_more: true }, counts: { all: 5 } }));+ const out = await run({ action: listSpyderRankedAds, propsValue: { pageId: '123', category: 'breakout', limit: 1 } });+ expect(Object.fromEntries(urlOf(spy).searchParams)).toEqual({ category: 'breakout', limit: '1', offset: '0' });+ expect(out).toMatchObject({ pageId: '123', total: 5, hasMore: true, nextOffset: 1, counts: { all: 5 } });+ expect(out.items[0]).toMatchObject({ rank: 2, previousRank: 9, peakRank: 1, daysRunning: 12, ad: { id: 'a1' } });+ });+ it('list_spyder_related_pages', async () => {+ const spy = mock(ok({ results: [{ pageId: '9', pageName: 'Old', currentPageName: 'New', adsCount: 3 }] }));+ const out = await run({ action: listSpyderRelatedPages, propsValue: { pageId: '123' } });+ expect(Object.fromEntries(urlOf(spy).searchParams)).toEqual({ pageId: '123', limit: '5' });+ expect(out.items[0]).toMatchObject({ pageId: '9', name: 'New', adsCount: 3 });+ });+ it('get_credit_usage omits the email', async () => {+ mock(ok({ start_date: '2026-10-01', end_date: '2026-11-01', total_credits: 1000, remaining_credits: 900, user: { id: 'u1', email: '[email protected]' } }));+ const out = await run({ action: getCreditUsage, propsValue: {} });+ expect(out).toEqual({ totalCredits: 1000, remainingCredits: 900, usedCredits: 100, periodStart: '2026-10-01', periodEnd: '2026-11-01', userId: 'u1' });+ });+ it('get_lens_report', async () => {+ const spy = mock(okWith({ data: [{ core_metrics: { spend: 1 } }], metadata: { count: 11, pages: 2 } }));+ const out = await run({ action: getLensReport, propsValue: { lensId: '55', from: '2026-06-01', to: '2026-06-10', breakdownType: 'age,gender', provider: 'facebook', attrClick: '28d' } });+ expect(Object.fromEntries(urlOf(spy).searchParams)).toEqual({ lens_id: '55', from: '2026-06-01', to: '2026-06-10', breakdown_type: 'age,gender', provider: 'facebook', attr_click: '28d', page: '1', limit: '10' });+ expect(out).toMatchObject({ count: 1, total: 11, hasMore: true, nextPage: 2 });+ });+});++describe('human actions keep raw output', () => {+ it('findAds returns raw ads and converts DateTime', async () => {+ const spy = mock(ok([rawAd('a1')]));+ const out = await run({ action: findAds, propsValue: { start_date: '2026-01-02T00:00:00.000Z', languages: ['english'], niches: ['health'], limit: 10 } });+ const url = urlOf(spy);+ expect(url.searchParams.get('start_date')).toBe('2026-01-02 00:00:00');+ expect(url.searchParams.get('languages')).toBe('english');+ expect(url.searchParams.get('niches')).toBe('health/wellness');+ expect(out).toEqual([rawAd('a1')]);+ });+ it('findAds maps legacy niches and drops retired ones without throwing', async () => {+ const spy = mock(ok([]));+ await run({ action: findAds, propsValue: { niches: ['technology', 'food', 'travel', 'finance', 'sports', 'automotive', 'beauty'] } });+ expect(urlOf(spy).searchParams.getAll('niches')).toEqual(['app/software', 'food/drink', 'beauty']);+ });+ it('findAds with only retired niches throws naming them', async () => {+ const spy = mock(ok([]));+ await expect(run({ action: findAds, propsValue: { niches: ['travel', 'sports'] } })).rejects.toThrow('"travel", "sports" are no longer supported');+ expect(spy).not.toHaveBeenCalled();+ });+ it('every niche offered on 0.1.9 is still a dropdown option', () => {+ const offered = JSON.stringify(findAds.props['niches']);+ for (const v of ['accessories', 'app/software', 'beauty', 'business/professional', 'education', 'entertainment', 'fashion', 'finance', 'food', 'health', 'home', 'pets', 'sports', 'technology', 'travel', 'automotive', 'other']) expect(offered).toContain(`"value":"${v}"`);+ });+ it('getAdsByPage', async () => {+ const spy = mock(ok([]));+ await run({ action: getAdsByPage, propsValue: { page_id: '123', display_format: ['page_like'] } });+ expect(Object.fromEntries(urlOf(spy).searchParams)).toEqual({ page_id: '123', display_format: 'page_like' });+ });+ it('getAdById', async () => {+ const spy = mock(ok(rawAd('a1')));+ expect(await run({ action: getAdById, propsValue: { ad_id: 'a1' } })).toEqual(rawAd('a1'));+ expect(spy.mock.calls[0][0].url).toBe(`${BASE}/api/ad/a1`);+ });+ it('getAdById null data (internal id) throws a clear error', async () => {+ mock(ok(null));+ await expect(run({ action: getAdById, propsValue: { ad_id: 'internal1' } })).rejects.toThrow('public ad library ID');+ });+ it('findBrands allows up to 100', async () => {+ const spy = mock(ok([]));+ await run({ action: findBrands, propsValue: { query: 'nike', limit: 100 } });+ expect(urlOf(spy).searchParams.get('limit')).toBe('100');+ });+ it('findBoards without limit returns all boards', async () => {+ const spy = mock(ok([]));+ await run({ action: findBoards, propsValue: {} });+ expect(spy.mock.calls[0][0].url).toBe(`${BASE}/api/boards`);+ });+ it('findBoards with limit pages', async () => {+ const spy = mock(ok([]));+ await run({ action: findBoards, propsValue: { limit: 10, offset: 0 } });+ expect(spy.mock.calls[0][0].url).toBe(`${BASE}/api/boards?limit=10&offset=0`);+ });+});++describe('triggers', () => {+ const triggerArgs = ({ store, propsValue }: { store: ReturnType<typeof memoryStore>; propsValue: Record<string, unknown> }) => ({ auth, propsValue, store });++ it('keeps the legacy polling_interval prop on every trigger and ignores it', async () => {+ for (const t of [newAdInBoard, newAdInSpyder, newSwipefileAd]) expect(t.props['polling_interval']).toBeDefined();+ const store = memoryStore();+ const spy = mock(ok([]));+ await call({ target: newAdInBoard, method: 'onEnable', args: triggerArgs({ store, propsValue: { board_id: 'bd1', page_size: 3, polling_interval: 60 } }) });+ expect(Object.fromEntries(urlOf(spy).searchParams)).toEqual({ board_id: 'bd1', order: 'newest', limit: '3' });+ });+ it('board trigger seeds, then emits only unseen ads oldest first', async () => {+ const store = memoryStore();+ const propsValue = { board_id: 'bd1', page_size: 3, live: 'true' };+ const spy = mock(ok([rawAd('a2'), rawAd('a1')]), ok([rawAd('a4'), rawAd('a3'), rawAd('a2')]), ok([rawAd('a4'), rawAd('a3'), rawAd('a2')]));+ await call({ target: newAdInBoard, method: 'onEnable', args: triggerArgs({ store, propsValue }) });+ expect(Object.fromEntries(urlOf(spy).searchParams)).toEqual({ board_id: 'bd1', live: 'true', order: 'newest', limit: '3' });+ const first = await call({ target: newAdInBoard, method: 'run', args: triggerArgs({ store, propsValue }) });+ expect(first.map((a: { id: string }) => a.id)).toEqual(['a3', 'a4']);+ expect(first[0]).toMatchObject({ board_id: 'bd1' });+ const second = await call({ target: newAdInBoard, method: 'run', args: triggerArgs({ store, propsValue }) });+ expect(second).toEqual([]);+ });+ it('pages past a busy feed until it reaches a seen ad', async () => {+ const store = memoryStore();+ await store.put('foreplay_seen_ad_ids', ['a1']);+ const spy = mock(+ okWith({ data: [rawAd('a5'), rawAd('a4')], metadata: { cursor: 'c2' } }),+ okWith({ data: [rawAd('a3'), rawAd('a2')], metadata: { cursor: 'c3' } }),+ okWith({ data: [rawAd('a1'), rawAd('a0')], metadata: { cursor: 'c4' } }),+ );+ const out = await call({ target: newAdInBoard, method: 'run', args: triggerArgs({ store, propsValue: { board_id: 'bd1', page_size: 2 } }) });+ expect(out.map((a: { id: string }) => a.id)).toEqual(['a2', 'a3', 'a4', 'a5']);+ expect(spy).toHaveBeenCalledTimes(3);+ expect(nthUrl({ spy, index: 1 }).searchParams.get('cursor')).toBe('c2');+ expect(nthUrl({ spy, index: 2 }).searchParams.get('cursor')).toBe('c3');+ });+ it('stops at the page cap and resumes the backlog on the next poll without losing ads', async () => {+ const store = memoryStore();+ await store.put('foreplay_seen_ad_ids', ['old']);+ const page = ({ id, cursor }: { id: string; cursor: string }) => okWith({ data: [rawAd(id)], metadata: { cursor } });+ const spy = mock(+ page({ id: 'n0', cursor: 'c1' }), page({ id: 'n1', cursor: 'c2' }), page({ id: 'n2', cursor: 'c3' }), page({ id: 'n3', cursor: 'c4' }), page({ id: 'n4', cursor: 'c5' }),+ page({ id: 'n5', cursor: 'c6' }), page({ id: 'old', cursor: 'c7' }),+ page({ id: 'n0', cursor: 'c1' }),+ );+ const props = { brand_id: 'b1', page_size: 1 };+ const first = await call({ target: newAdInSpyder, method: 'run', args: triggerArgs({ store, propsValue: props }) });+ expect(first.map((a: { id: string }) => a.id)).toEqual(['n4', 'n3', 'n2', 'n1', 'n0']);+ expect(store.data.get('foreplay_backlog_cursor')).toEqual({ cursor: 'c5', anchorIds: [], before: null, boundaryId: 'old' });+ const second = await call({ target: newAdInSpyder, method: 'run', args: triggerArgs({ store, propsValue: props }) });+ expect(nthUrl({ spy, index: 5 }).searchParams.get('cursor')).toBe('c5');+ expect(second.map((a: { id: string }) => a.id)).toEqual(['n5']);+ expect(store.data.has('foreplay_backlog_cursor')).toBe(false);+ expect(spy).toHaveBeenCalledTimes(8);+ });+ it('swipefile trigger pages by offset', async () => {+ const store = memoryStore();+ await store.put('foreplay_seen_ad_ids', ['s0']);+ const spy = mock(ok([rawAd('s2')]), ok([rawAd('s1')]), ok([rawAd('s0')]));+ const out = await call({ target: newSwipefileAd, method: 'run', args: triggerArgs({ store, propsValue: { page_size: 1 } }) });+ expect(out.map((a: { id: string }) => a.id)).toEqual(['s1', 's2']);+ expect([0, 1, 2].map((i) => nthUrl({ spy, index: i }).searchParams.get('offset'))).toEqual(['0', '1', '2']);+ });+ it('an upgraded trigger with only the old lastPoll emits ads newer than it, then dedupes by ID', async () => {+ const store = memoryStore();+ const lastPoll = Date.parse('2026-10-10T00:00:00Z');+ await store.put('lastPoll', lastPoll);+ const ads = [+ { ...rawAd('a3'), created_at: '2026-10-12T00:00:00Z' },+ { ...rawAd('a2'), created_at: '2026-10-11T00:00:00Z' },+ { ...rawAd('a1'), created_at: '2026-10-09T00:00:00Z' },+ ];+ mock(ok(ads), ok(ads));+ const out = await call({ target: newAdInBoard, method: 'run', args: triggerArgs({ store, propsValue: { board_id: 'bd1' } }) });+ expect(out.map((a: { id: string }) => a.id)).toEqual(['a2', 'a3']);+ expect(store.data.get('foreplay_seen_ad_ids')).toEqual(['a3', 'a2', 'a1']);+ expect(store.data.has('lastPoll')).toBe(false);+ const again = await call({ target: newAdInBoard, method: 'run', args: triggerArgs({ store, propsValue: { board_id: 'bd1' } }) });+ expect(again).toEqual([]);+ });+ it('a quiet upgrade keeps the boundary IDs so old ads are not replayed', async () => {+ const store = memoryStore();+ await store.put('lastPoll', Date.parse('2026-10-10T00:00:00Z'));+ const ads = [{ ...rawAd('a2'), created_at: '2026-10-09T00:00:00Z' }, { ...rawAd('a1'), created_at: '2026-10-08T00:00:00Z' }];+ mock(ok(ads), ok(ads));+ const first = await call({ target: newAdInBoard, method: 'run', args: triggerArgs({ store, propsValue: { board_id: 'bd1' } }) });+ expect(first).toEqual([]);+ expect(store.data.get('foreplay_seen_ad_ids')).toEqual(['a2', 'a1']);+ const second = await call({ target: newAdInBoard, method: 'run', args: triggerArgs({ store, propsValue: { board_id: 'bd1' } }) });+ expect(second).toEqual([]);+ });+ it('swipe-file backlog resumes at its anchor ad, so new saves that shift offsets cause no repeats', async () => {+ const store = memoryStore();+ await store.put('foreplay_seen_ad_ids', ['old']);+ const props = { page_size: 1 };+ const feed1 = ['s9', 's8', 's7', 's6', 's5', 's4', 's3', 'old'];+ const feed2 = ['n2', 'n1', ...feed1];+ const at = ({ feed, offsets }: { feed: string[]; offsets: number[] }) => offsets.map((o) => ok([rawAd(feed[o])]));+ const spy = mock(...at({ feed: feed1, offsets: [0, 1, 2, 3, 4] }), ...at({ feed: feed2, offsets: [4, 5, 6, 7, 8] }), ...at({ feed: feed2, offsets: [8, 9, 0, 1, 2] }));+ const first = await call({ target: newSwipefileAd, method: 'run', args: triggerArgs({ store, propsValue: props }) });+ expect(first.map((a: { id: string }) => a.id)).toEqual(['s5', 's6', 's7', 's8', 's9']);+ expect(store.data.get('foreplay_backlog_cursor')).toEqual({ cursor: '4', anchorIds: ['s5'], before: null, boundaryId: 'old' });+ const second = await call({ target: newSwipefileAd, method: 'run', args: triggerArgs({ store, propsValue: props }) });+ expect(second.map((a: { id: string }) => a.id)).toEqual(['s3', 's4']);+ expect(store.data.get('foreplay_backlog_cursor')).toEqual({ cursor: '8', anchorIds: ['s3'], before: null, boundaryId: 'old' });+ const third = await call({ target: newSwipefileAd, method: 'run', args: triggerArgs({ store, propsValue: props }) });+ expect(third.map((a: { id: string }) => a.id)).toEqual(['n1', 'n2']);+ expect(store.data.has('foreplay_backlog_cursor')).toBe(false);+ expect(spy.mock.calls.map((c) => new URL(String(c[0].url)).searchParams.get('offset'))).toEqual(['0', '1', '2', '3', '4', '4', '5', '6', '7', '8', '8', '9', '0', '1', '2']);+ });+ it('a swipe-file backlog whose anchor ads vanished still delivers the unread ads', async () => {+ const store = memoryStore();+ await store.put('foreplay_seen_ad_ids', ['s9', 'old']);+ await store.put('foreplay_backlog_cursor', { cursor: '1', anchorIds: ['gone'], before: null, boundaryId: 'old' });+ const feed = ['s9', 's4', 's3', 'old'];+ mock(...[1, 2, 3].map((o) => ok([rawAd(feed[o])])), ok([rawAd('s9')]));+ const out = await call({ target: newSwipefileAd, method: 'run', args: triggerArgs({ store, propsValue: { page_size: 1 } }) });+ expect(out.map((a: { id: string }) => a.id)).toEqual(['s3', 's4']);+ expect(store.data.has('foreplay_backlog_cursor')).toBe(false);+ });+ it('a swipe-file backlog with page size 3 resumes past every anchor instead of stopping at a seen one', async () => {+ const store = memoryStore();+ await store.put('foreplay_seen_ad_ids', ['old']);+ const feed = Array.from({ length: 17 }, (_, i) => `s${17 - i}`).concat('old');+ const page = (offset: number) => ok(feed.slice(offset, offset + 3).map((id) => rawAd(id)));+ mock(...[0, 3, 6, 9, 12].map(page), ...[12, 15, 0].map(page));+ const first = await call({ target: newSwipefileAd, method: 'run', args: triggerArgs({ store, propsValue: { page_size: 3 } }) });+ expect(first).toHaveLength(15);+ expect(store.data.get('foreplay_backlog_cursor')).toEqual({ cursor: '12', anchorIds: ['s5', 's4', 's3'], before: null, boundaryId: 'old' });+ const second = await call({ target: newSwipefileAd, method: 'run', args: triggerArgs({ store, propsValue: { page_size: 3 } }) });+ expect(second.map((a: { id: string }) => a.id)).toEqual(['s1', 's2']);+ expect(store.data.has('foreplay_backlog_cursor')).toBe(false);+ });+ it('keeps searching for its anchors across capped polls instead of replaying skipped ads', async () => {+ const store = memoryStore();+ await store.put('foreplay_seen_ad_ids', ['d0', 'd1', 'd2', 'd3', 'd4', 'd5', 'old']);+ await store.put('foreplay_backlog_cursor', { cursor: '0', anchorIds: ['a'], before: null, boundaryId: 'old' });+ const feed = ['d0', 'd1', 'd2', 'd3', 'd4', 'd5', 'a', 'p1', 'old'];+ const at = (offsets: number[]) => offsets.map((o) => ok([rawAd(feed[o])]));+ mock(...at([0, 1, 2, 3, 4]), ...at([5, 6, 7, 8, 0]));+ const first = await call({ target: newSwipefileAd, method: 'run', args: triggerArgs({ store, propsValue: { page_size: 1 } }) });+ expect(first).toEqual([]);+ expect(store.data.get('foreplay_backlog_cursor')).toEqual({ cursor: '5', anchorIds: ['a'], before: null, boundaryId: 'old' });+ const second = await call({ target: newSwipefileAd, method: 'run', args: triggerArgs({ store, propsValue: { page_size: 1 } }) });+ expect(second.map((a: { id: string }) => a.id)).toEqual(['p1']);+ });+ it('every stored value stays far below the 512 KiB store limit', async () => {+ const store = memoryStore();+ const longId = ({ prefix, i }: { prefix: string; i: number }) => `${prefix}${String(i).padStart(63, '0')}`;+ await store.put('foreplay_seen_ad_ids', Array.from({ length: 1000 }, (_, i) => longId({ prefix: 'o', i })));+ const pages = Array.from({ length: 5 }, (_, p) => okWith({ data: Array.from({ length: 50 }, (_, i) => rawAd(longId({ prefix: 'n', i: p * 50 + i }))), metadata: { cursor: `c${p + 1}` } }));+ mock(...pages);+ await call({ target: newAdInBoard, method: 'run', args: triggerArgs({ store, propsValue: { board_id: 'bd1', page_size: 50 } }) });+ expect(store.data.get('foreplay_seen_ad_ids')).toHaveLength(1000);+ for (const value of store.data.values()) expect(JSON.stringify(value).length).toBeLessThan(100 * 1024);+ });+ it('a run without stored state (upgrade from 0.1.x) seeds silently', async () => {+ const store = memoryStore();+ mock(ok([rawAd('a1')]));+ const out = await call({ target: newAdInSpyder, method: 'run', args: triggerArgs({ store, propsValue: { brand_id: 'b1' } }) });+ expect(out).toEqual([]);+ expect(store.data.get('foreplay_seen_ad_ids')).toEqual(['a1']);+ });+ it('a failing poll throws instead of returning nothing', async () => {+ const store = memoryStore();+ await store.put('foreplay_seen_ad_ids', []);+ vi.spyOn(httpClient, 'sendRequest').mockRejectedValueOnce(httpFailure({ status: 401, body: { error: { message: 'Invalid or missing API key' } } }));+ await expect(call({ target: newSwipefileAd, method: 'run', args: triggerArgs({ store, propsValue: {} }) })).rejects.toThrow('Invalid or missing API key');+ });+ it('swipefile trigger orders by saved_newest and test fetches 5', async () => {+ const store = memoryStore();+ const spy = mock(ok([rawAd('s1')]));+ const out = await call({ target: newSwipefileAd, method: 'test', args: triggerArgs({ store, propsValue: {} }) });+ expect(Object.fromEntries(urlOf(spy).searchParams)).toEqual({ order: 'saved_newest', limit: '5', offset: '0' });+ expect(out).toEqual([{ ...rawAd('s1'), metadata: { success: true, message: 'New ad detected' } }]);+ });+ it('onDisable keeps state', async () => {+ const store = memoryStore();+ await store.put('foreplay_seen_ad_ids', ['x']);+ await call({ target: newAdInSpyder, method: 'onDisable', args: triggerArgs({ store, propsValue: {} }) });+ expect(store.data.get('foreplay_seen_ad_ids')).toEqual(['x']);+ });+ it('onDisable then onEnable on a republish keeps the seen list and backlog', async () => {+ const store = memoryStore();+ await store.put('foreplay_seen_ad_ids', ['x']);+ await store.put('foreplay_backlog_cursor', { cursor: 'c1' });+ const spy = mock(ok([rawAd('n1')]));+ await call({ target: newAdInSpyder, method: 'onDisable', args: triggerArgs({ store, propsValue: { brand_id: 'br1' } }) });+ await call({ target: newAdInSpyder, method: 'onEnable', args: { ...triggerArgs({ store, propsValue: { brand_id: 'br1' } }), isRepublish: true } });+ expect(spy).not.toHaveBeenCalled();+ expect(store.data.get('foreplay_seen_ad_ids')).toEqual(['x']);+ expect(store.data.get('foreplay_backlog_cursor')).toEqual({ cursor: 'c1' });+ });+ it('onEnable on a republish with no seen list seeds', async () => {+ const store = memoryStore();+ mock(ok([rawAd('n1')]));+ await call({ target: newAdInSpyder, method: 'onEnable', args: { ...triggerArgs({ store, propsValue: { brand_id: 'br1' } }), isRepublish: true } });+ expect(store.data.get('foreplay_seen_ad_ids')).toEqual(['n1']);+ });+ it('onEnable without republish reseeds', async () => {+ const store = memoryStore();+ await store.put('foreplay_seen_ad_ids', ['x']);+ mock(ok([rawAd('n1')]));+ await call({ target: newAdInSpyder, method: 'onEnable', args: triggerArgs({ store, propsValue: { brand_id: 'br1' } }) });+ expect(store.data.get('foreplay_seen_ad_ids')).toEqual(['n1']);+ });+ it('board events carry title from the ad name', async () => {+ const store = memoryStore();+ await store.put('foreplay_seen_ad_ids', ['old']);+ mock(ok([{ ...rawAd('n1'), name: 'Ad N1' }, rawAd('old')]));+ const out = await call({ target: newAdInBoard, method: 'run', args: triggerArgs({ store, propsValue: { board_id: 'bd1' } }) });+ expect(out).toMatchObject([{ id: 'n1', title: 'Ad N1', board_id: 'bd1' }]);+ });+ it('board and swipefile events keep the legacy metadata fields', async () => {+ const legacy = { success: true, message: 'New ad detected' };+ const boardStore = memoryStore();+ await boardStore.put('foreplay_seen_ad_ids', ['old']);+ mock(ok([rawAd('n1'), rawAd('old')]));+ const board = await call({ target: newAdInBoard, method: 'run', args: triggerArgs({ store: boardStore, propsValue: { board_id: 'bd1' } }) });+ expect(board).toMatchObject([{ id: 'n1', board_id: 'bd1', metadata: legacy }]);+ const swipeStore = memoryStore();+ await swipeStore.put('foreplay_seen_ad_ids', ['old']);+ mock(ok([rawAd('s1'), rawAd('old')]));+ const swipe = await call({ target: newSwipefileAd, method: 'run', args: triggerArgs({ store: swipeStore, propsValue: {} }) });+ expect(swipe).toMatchObject([{ id: 's1', metadata: legacy }]);+ expect(newAdInBoard.sampleData).toMatchObject({ metadata: legacy });+ expect(newSwipefileAd.sampleData).toMatchObject({ metadata: legacy });+ for (const t of [newAdInBoard, newSwipefileAd]) {+ expect(t.outputSchema?.fields.map((f) => f.key)).toEqual(expect.arrayContaining(['metadata.success', 'metadata.message']));+ }+ });+ it('rejects a page size above 50', async () => {+ const store = memoryStore();+ await expect(call({ target: newAdInBoard, method: 'onEnable', args: triggerArgs({ store, propsValue: { board_id: 'bd1', page_size: 250 } }) })).rejects.toThrow('Ads Checked per Poll');+ });+ it('spyder dropdown pages through every brand', async () => {+ const spy = mock(ok(Array.from({ length: 10 }, (_, i) => ({ id: `b${i}`, name: `B${i}` }))), ok([{ id: 'b10', name: 'B10' }]));+ const prop = newAdInSpyder.props['brand_id'];+ const out = await call({ target: prop, method: 'options', args: { auth } });+ expect(spy).toHaveBeenCalledTimes(2);+ expect(out.options).toHaveLength(11);+ });+ it('board dropdown shows the error reason', async () => {+ vi.spyOn(httpClient, 'sendRequest').mockRejectedValueOnce(httpFailure({ status: 401, body: { error: { message: 'Invalid or missing API key' } } }));+ const out = await call({ target: newAdInBoard.props['board_id'], method: 'options', args: { auth } });+ expect(out).toMatchObject({ disabled: true });+ expect(out.placeholder).toContain('Invalid or missing API key');+ });+});++describe('auth', () => {+ it('valid key passes via the free usage endpoint', async () => {+ const spy = mock(ok({ total_credits: 1, remaining_credits: 1 }));+ const out = await call({ target: foreplayCoAuth, method: 'validate', args: { auth: 'k' } });+ expect(out).toEqual({ valid: true });+ expect(spy.mock.calls[0][0].url).toBe(`${BASE}/api/usage`);+ });+ it('401 is invalid credentials', async () => {+ vi.spyOn(httpClient, 'sendRequest').mockRejectedValueOnce(httpFailure({ status: 401, body: { error: { message: 'Invalid or missing API key' } } }));+ const out = await call({ target: foreplayCoAuth, method: 'validate', args: { auth: 'k' } });+ expect(out.valid).toBe(false);+ expect(out.error).toContain('Invalid credentials');+ });+ it('500 is not reported as bad credentials', async () => {+ vi.spyOn(httpClient, 'sendRequest').mockRejectedValueOnce(httpFailure({ status: 500, body: { error: { message: 'boom' } } }));+ const out = await call({ target: foreplayCoAuth, method: 'validate', args: { auth: 'k' } });+ expect(out.error).toContain('boom');+ expect(out.error).not.toContain('Invalid credentials');+ });+});diff --git a/packages/pieces/community/foreplay-co/vitest.config.ts b/packages/pieces/community/foreplay-co/vitest.config.tsnew file mode 100644index 00000000000..79c97261904--- /dev/null+++ b/packages/pieces/community/foreplay-co/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'),+ },+ },+})