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(canva): create, export and import designs and manage assets and folders from flows and AI agents (#16956)
Odai Ahmadc41ae21b2b0f
diff --git a/bun.lock b/bun.lockindex 833727c9b90..604e242e87b 100644--- a/bun.lock+++ b/bun.lock@@ -1585,15 +1585,17 @@},"packages/pieces/community/canva": {"name": "@activepieces/piece-canva",- "version": "0.2.1",+ "version": "0.3.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*","@activepieces/pieces-common": "workspace:*","@activepieces/pieces-framework": "workspace:*",+ "undici": "7.29.1",},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/capsule-crm": {diff --git a/docs/install/reference/breaking-changes-unreleased.mdx b/docs/install/reference/breaking-changes-unreleased.mdxindex ef0c750a0eb..c2db1e14675 100644--- a/docs/install/reference/breaking-changes-unreleased.mdx+++ b/docs/install/reference/breaking-changes-unreleased.mdx@@ -8,6 +8,19 @@ Entries here move to [Breaking Changes](/install/reference/breaking-changes) aut## What has changed?+#### Canva 0.3.0: nine actions are builder-only, and Export, Upload and Import wait for the job++Create Design, Export Design, Find Design, Get Asset, Get Design, Get Folder, Import Design, Move Folder Item and Upload Asset are no longer offered to AI agents. They keep working in flows, but an agent or MCP client that used them as tools loses them after the upgrade.++**Export Design**, **Upload Asset** and **Import Design** now wait for Canva's job to finish (up to 120 seconds by default) and return the finished result. The step fails when Canva reports the job failed or the wait runs out. Before, they returned the running job right away. The `next_steps` field is no longer in their output.++#### What you need to do++- Agents that used these actions as tools switch to the new agent tools: **Create Design**, **Export Design**, **Get Design**, **Get Asset** and **Move Folder Item** (same names), **List Designs** for Find Design, **List Folder Items** for Get Folder, and **Upload Asset From URL** and **Import Design From URL** for the two file actions (they take a public URL, not a file).+- To keep the old behaviour of Export Design, Upload Asset or Import Design, turn off **Wait for Completion** and check the job later with **Get Job Status**. If a later step read `next_steps`, remove that mapping.++Flow steps keep running on the version they were built with until you upgrade them.+#### NinjaPipe 0.2.0: 17 actions are builder-only, outputs change shape, and fields the API rejected or ignored are removedNinjaPipe 0.2.0 changes what existing steps take and return once they are upgraded to that version. Steps keep running on the version they were built with until you upgrade them, but AI agents lose the old tools as soon as 0.2.0 is published.diff --git a/packages/pieces/community/canva/package.json b/packages/pieces/community/canva/package.jsonindex 9eabf73c56c..bea106abdaf 100644--- a/packages/pieces/community/canva/package.json+++ b/packages/pieces/community/canva/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-canva",- "version": "0.2.1",+ "version": "0.3.0","type": "commonjs","main": "./dist/src/index.js","types": "./dist/src/index.d.ts",@@ -8,14 +8,17 @@"@activepieces/pieces-common": "workspace:*","@activepieces/pieces-framework": "workspace:*","@activepieces/core-piece-types": "workspace:*",- "@activepieces/core-utils": "workspace:*"+ "@activepieces/core-utils": "workspace:*",+ "undici": "7.29.1"},"devDependencies": {- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"},"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/canva/src/i18n/translation.json b/packages/pieces/community/canva/src/i18n/translation.jsonindex 9e621ec3b29..f20b0153b62 100644--- a/packages/pieces/community/canva/src/i18n/translation.json+++ b/packages/pieces/community/canva/src/i18n/translation.json@@ -1,5 +1,5 @@{- "Create stunning designs with Canva's powerful design automation tools": "Create stunning designs with Canva's powerful design automation tools",+ "Create, export and organize Canva designs and assets": "Create, export and organize Canva designs and assets","\nTo connect Canva, follow these steps:\n1. Go to https://www.canva.com/developers/integrations and sign in.\n2. Click **Create an integration** and fill in the app name and description.\n3. Under **Configure** → **Authentication**, set the redirect URL to the one shown above.\n4. Under **Configure** → **Scopes**, enable: `design:content:read`, `design:content:write`, `design:meta:read`, `asset:read`, `asset:write`, `folder:read`, `folder:write`, `profile:read`.\n5. Copy the **Client ID** and **Client secret** an": "\nTo connect Canva, follow these steps:\n1. Go to https://www.canva.com/developers/integrations and sign in.\n2. Click **Create an integration** and fill in the app name and description.\n3. Under **Configure** → **Authentication**, set the redirect URL to the one shown above.\n4. Under **Configure** → **Scopes**, enable: `design:content:read`, `design:content:write`, `design:meta:read`, `asset:read`, `asset:write`, `folder:read`, `folder:write`, `profile:read`.\n5. Copy the **Client ID** and **Client secret** and paste them above.\n","Create Design": "Create Design","Get Design": "Get Design",@@ -10,49 +10,110 @@"Find Design": "Find Design","Get Folder": "Get Folder","Get Asset": "Get Asset",+ "List Folder Items": "List Folder Items",+ "Create Folder": "Create Folder",+ "Get Job Status": "Get Job Status",+ "List Designs": "List Designs",+ "Get Export Job": "Get Export Job",+ "Upload Asset From URL": "Upload Asset From URL",+ "Get Asset Upload Job": "Get Asset Upload Job",+ "Import Design From URL": "Import Design From URL",+ "Get Import Job": "Get Import Job",+ "Update Asset": "Update Asset",+ "Get Design Pages": "Get Design Pages",+ "Get Export Formats": "Get Export Formats",+ "Delete Asset": "Delete Asset","Custom API Call": "Custom API Call",- "Create a new Canva design using preset design types or custom dimensions. Blank designs are automatically deleted if not edited within 7 days.": "Create a new Canva design using preset design types or custom dimensions. Blank designs are automatically deleted if not edited within 7 days.",- "Get the metadata for one of your designs, including owner information, URLs for editing and viewing, and thumbnail information.": "Get the metadata for one of your designs, including owner information, URLs for editing and viewing, and thumbnail information.",- "Upload an image or video asset to your Canva library. This creates an asynchronous job that you can monitor for completion.": "Upload an image or video asset to your Canva library. This creates an asynchronous job that you can monitor for completion.",- "Import an external file (PDF, PSD, DOCX, PPTX, etc.) into Canva as a new design. This creates an asynchronous job that you can monitor for completion.": "Import an external file (PDF, PSD, DOCX, PPTX, etc.) into Canva as a new design. This creates an asynchronous job that you can monitor for completion.",- "Export a Canva design to various formats (PDF, JPG, PNG, GIF, PPTX, MP4). This creates an asynchronous job with download URLs valid for 24 hours.": "Export a Canva design to various formats (PDF, JPG, PNG, GIF, PPTX, MP4). This creates an asynchronous job with download URLs valid for 24 hours.",- "Move an item from one folder to another in Canva": "Move an item from one folder to another in Canva",- "Search and list designs from your Canva library. Use this to find existing designs before creating new ones.": "Search and list designs from your Canva library. Use this to find existing designs before creating new ones.",- "Retrieve metadata for a specific folder, including name, creation date, and thumbnail.": "Retrieve metadata for a specific folder, including name, creation date, and thumbnail.",- "Retrieve metadata for a specific asset (image or video), including name, tags, creation date, and thumbnail.": "Retrieve metadata for a specific asset (image or video), including name, tags, creation date, and thumbnail.",+ "Create a new Canva design from a preset type or custom size. Blank designs are deleted by Canva if not edited within 7 days.": "Create a new Canva design from a preset type or custom size. Blank designs are deleted by Canva if not edited within 7 days.",+ "Get the details of a design, including owner, edit and view links, and thumbnail.": "Get the details of a design, including owner, edit and view links, and thumbnail.",+ "Upload an image or video to your Canva library and wait until Canva has processed it.": "Upload an image or video to your Canva library and wait until Canva has processed it.",+ "Import a file (PDF, PPTX, DOCX, PSD, AI and more) into Canva as a new design and wait for the result.": "Import a file (PDF, PPTX, DOCX, PSD, AI and more) into Canva as a new design and wait for the result.",+ "Export a design as PDF, JPG, PNG, GIF, PPTX or MP4 and wait for the download links (valid for 24 hours).": "Export a design as PDF, JPG, PNG, GIF, PPTX or MP4 and wait for the download links (valid for 24 hours).",+ "Move a design or image into another folder.": "Move a design or image into another folder.",+ "Search your Canva designs by keyword, or list them all. Returns one page; use the continuation token for the next page.": "Search your Canva designs by keyword, or list them all. Returns one page; use the continuation token for the next page.",+ "Get the details of a folder, including name, dates and thumbnail.": "Get the details of a folder, including name, dates and thumbnail.",+ "Get the details of an image or video in your Canva library, including name, tags, dates and thumbnail.": "Get the details of an image or video in your Canva library, including name, tags, dates and thumbnail.",+ "List the designs, images and subfolders in a folder. Returns one page; use the continuation token for the next page.": "List the designs, images and subfolders in a folder. Returns one page; use the continuation token for the next page.",+ "Create a folder in your Canva projects, in Uploads, or inside another folder.": "Create a folder in your Canva projects, in Uploads, or inside another folder.",+ "Check an export, upload or import job and get its result (download links, asset or designs).": "Check an export, upload or import job and get its result (download links, asset or designs).",+ "Searches or lists Canva designs, one page at a time.": "Searches or lists Canva designs, one page at a time.",+ "Gets one Canva design by ID.": "Gets one Canva design by ID.",+ "Creates a new blank Canva design.": "Creates a new blank Canva design.",+ "Starts a Canva export job and waits briefly for the download links.": "Starts a Canva export job and waits briefly for the download links.",+ "Get Export Job by job ID.": "Get Export Job by job ID.",+ "Uploads an image or video from a public URL to the Canva library.": "Uploads an image or video from a public URL to the Canva library.",+ "Get Asset Upload Job by job ID.": "Get Asset Upload Job by job ID.",+ "Imports a file from a public URL as a new Canva design.": "Imports a file from a public URL as a new Canva design.",+ "Get Import Job by job ID.": "Get Import Job by job ID.",+ "Lists designs, images and subfolders in a Canva folder.": "Lists designs, images and subfolders in a Canva folder.",+ "Creates a Canva folder.": "Creates a Canva folder.",+ "Moves a design, image or folder into another folder.": "Moves a design, image or folder into another folder.",+ "Gets one Canva library asset by ID.": "Gets one Canva library asset by ID.",+ "Renames a Canva asset or replaces its tags.": "Renames a Canva asset or replaces its tags.",+ "Lists the pages of a Canva design with thumbnails and sizes.": "Lists the pages of a Canva design with thumbnails and sizes.",+ "Lists the file formats a Canva design can be exported to.": "Lists the file formats a Canva design can be exported to.",+ "Deletes an image or video from the Canva library.": "Deletes an image or video from the Canva library.","Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",- "🎨 Design Type": "🎨 Design Type",+ "Design Type": "Design Type","Preset Design Type": "Preset Design Type","Custom Width (pixels)": "Custom Width (pixels)","Custom Height (pixels)": "Custom Height (pixels)",- "🏷️ Design Title": "🏷️ Design Title",- "Asset": "Asset",+ "Design Title": "Design Title",+ "Image Asset": "Image Asset","Design": "Design","Asset File": "Asset File","Asset Name": "Asset Name",+ "Wait for Completion": "Wait for Completion",+ "Maximum Wait (seconds)": "Maximum Wait (seconds)","Design File": "Design File",- "Design Title": "Design Title",- "🔍 Auto-detect File Type": "🔍 Auto-detect File Type",+ "Auto-detect File Type": "Auto-detect File Type","Export Format": "Export Format","Export Quality": "Export Quality","Specific Pages": "Specific Pages",- "📸 JPEG Quality": "📸 JPEG Quality",- "📄 PDF Paper Size": "📄 PDF Paper Size",- "🎬 MP4 Quality": "🎬 MP4 Quality",- "📐 Custom Width (pixels)": "📐 Custom Width (pixels)",- "📐 Custom Height (pixels)": "📐 Custom Height (pixels)",- "🔧 PNG Lossless Compression": "🔧 PNG Lossless Compression",- "🫥 PNG Transparent Background": "🫥 PNG Transparent Background",- "📑 PNG Merge Multi-page": "📑 PNG Merge Multi-page",+ "JPEG Quality": "JPEG Quality",+ "PDF Paper Size": "PDF Paper Size",+ "MP4 Quality": "MP4 Quality",+ "PNG Lossless": "PNG Lossless",+ "PNG Transparent Background": "PNG Transparent Background",+ "PNG Merge Pages": "PNG Merge Pages","Destination Folder": "Destination Folder","Item Type": "Item Type","Item to Move": "Item to Move",- "🔍 Search Query": "🔍 Search Query",- "👥 Ownership Filter": "👥 Ownership Filter",- "📊 Sort By": "📊 Sort By",- "⚙️ Result Limit (Advanced)": "⚙️ Result Limit (Advanced)",- "⚙️ Continuation Token (Advanced)": "⚙️ Continuation Token (Advanced)",+ "Search Query": "Search Query",+ "Ownership": "Ownership",+ "Sort By": "Sort By",+ "Result Limit": "Result Limit",+ "Continuation Token": "Continuation Token","Folder": "Folder",+ "Asset": "Asset",+ "Item Types": "Item Types",+ "Limit": "Limit",+ "Folder Name": "Folder Name",+ "Parent Folder": "Parent Folder",+ "Job Type": "Job Type",+ "Job ID": "Job ID",+ "Query": "Query",+ "Continuation": "Continuation",+ "Design ID": "Design ID",+ "Preset Name": "Preset Name",+ "Width": "Width",+ "Height": "Height",+ "Title": "Title",+ "Asset ID": "Asset ID",+ "Format": "Format",+ "Pages": "Pages",+ "JPG Quality": "JPG Quality",+ "PDF Size": "PDF Size",+ "URL": "URL",+ "Name": "Name",+ "MIME Type": "MIME Type",+ "Folder ID": "Folder ID",+ "Parent Folder ID": "Parent Folder ID",+ "Item ID": "Item ID",+ "To Folder ID": "To Folder ID",+ "Tags": "Tags",+ "Clear Tags": "Clear Tags",+ "Offset": "Offset","Method": "Method","Headers": "Headers","Query Parameters": "Query Parameters",@@ -62,58 +123,109 @@"Return Error as Output": "Return Error as Output","Timeout": "Timeout","Follow redirects": "Follow redirects",- "Choose how to create your design - preset templates or custom dimensions": "Choose how to create your design - preset templates or custom dimensions",- "⚠️ Only fill this if you selected \"Preset Design Type\" above": "⚠️ Only fill this if you selected \"Preset Design Type\" above",- "⚠️ Only fill this if you selected \"Custom Dimensions\" above. Min: 40, Max: 8000": "⚠️ Only fill this if you selected \"Custom Dimensions\" above. Min: 40, Max: 8000",- "Optional: Name for your design (1-255 characters). If empty, Canva will auto-generate a title.": "Optional: Name for your design (1-255 characters). If empty, Canva will auto-generate a title.",- "Optional: Select an existing image asset to add to the design": "Optional: Select an existing image asset to add to the design",- "Select the design to retrieve metadata for": "Select the design to retrieve metadata for",- "📁 Supported formats:\n 🖼️ Images (max 50MB): JPG, JPEG, PNG, HEIC, GIF, TIFF, WEBP\n 🎬 Videos (max 500MB): M4V, MKV, MP4, MPEG, MOV, WEBM": "📁 Supported formats:\n 🖼️ Images (max 50MB): JPG, JPEG, PNG, HEIC, GIF, TIFF, WEBP\n 🎬 Videos (max 500MB): M4V, MKV, MP4, MPEG, MOV, WEBM",- "🏷️ Name for the asset (max 50 characters, supports emojis and special characters)": "🏷️ Name for the asset (max 50 characters, supports emojis and special characters)",- "📄 Supported formats:\n 📋 Documents: PDF, DOC, DOCX, ODT, Pages\n 📊 Presentations: PPT, PPTX, ODP, Keynote \n 📈 Spreadsheets: XLS, XLSX, ODS, Numbers\n 🎨 Design Files: AI (Illustrator), PSD (Photoshop), ODG": "📄 Supported formats:\n 📋 Documents: PDF, DOC, DOCX, ODT, Pages\n 📊 Presentations: PPT, PPTX, ODP, Keynote \n 📈 Spreadsheets: XLS, XLSX, ODS, Numbers\n 🎨 Design Files: AI (Illustrator), PSD (Photoshop), ODG",- "🏷️ Title for the imported design (max 50 characters, supports emojis and special characters)": "🏷️ Title for the imported design (max 50 characters, supports emojis and special characters)",- "✅ Recommended: Let Canva automatically detect the file type. Uncheck to manually specify MIME type from file extension.": "✅ Recommended: Let Canva automatically detect the file type. Uncheck to manually specify MIME type from file extension.",- "Select the design to export": "Select the design to export",- "The format to export the design to": "The format to export the design to",- "Export quality level (Pro quality may require premium elements license)": "Export quality level (Pro quality may require premium elements license)",- "Page numbers to export (leave empty to export all pages). First page is 1.": "Page numbers to export (leave empty to export all pages). First page is 1.",- "🎯 JPEG ONLY: Compression quality (1-100, higher = better quality, larger file)": "🎯 JPEG ONLY: Compression quality (1-100, higher = better quality, larger file)",- "🎯 PDF ONLY: Paper size for PDF export (only for Canva Docs)": "🎯 PDF ONLY: Paper size for PDF export (only for Canva Docs)",- "🎯 MP4 ONLY: Video orientation and resolution for MP4 export": "🎯 MP4 ONLY: Video orientation and resolution for MP4 export",- "🎯 IMAGES ONLY (JPG/PNG/GIF): Custom width (40-25000px). Leave empty for original size.": "🎯 IMAGES ONLY (JPG/PNG/GIF): Custom width (40-25000px). Leave empty for original size.",- "🎯 IMAGES ONLY (JPG/PNG/GIF): Custom height (40-25000px). Leave empty for original size.": "🎯 IMAGES ONLY (JPG/PNG/GIF): Custom height (40-25000px). Leave empty for original size.",- "🎯 PNG ONLY: Export PNG without compression (default: true). Lossy compression requires Pro plan.": "🎯 PNG ONLY: Export PNG without compression (default: true). Lossy compression requires Pro plan.",- "🎯 PNG ONLY: Export PNG with transparent background (Pro feature)": "🎯 PNG ONLY: Export PNG with transparent background (Pro feature)",- "🎯 PNG ONLY: Merge multi-page designs into a single image (default: separate images per page)": "🎯 PNG ONLY: Merge multi-page designs into a single image (default: separate images per page)",- "Select the folder to move the item to": "Select the folder to move the item to",- "Select the type of item you want to move": "Select the type of item you want to move",- "Select the item you want to move": "Select the item you want to move",- "Enter keywords to search designs by title or content (leave empty to get all designs)": "Enter keywords to search designs by title or content (leave empty to get all designs)",- "Filter designs by who owns them": "Filter designs by who owns them",- "How to order the search results": "How to order the search results",- "Max designs to return (default: 20, max: 100). Higher numbers may be slower.": "Max designs to return (default: 20, max: 100). Higher numbers may be slower.",- "For pagination: token from previous search to get next page of results": "For pagination: token from previous search to get next page of results",- "Select the folder to retrieve metadata for": "Select the folder to retrieve metadata for",- "Select the asset to retrieve metadata for": "Select the asset to retrieve metadata for",+ "Choose a preset design type or custom dimensions.": "Choose a preset design type or custom dimensions.",+ "Used when Design Type is Preset.": "Used when Design Type is Preset.",+ "Used when Design Type is Custom size. 40-8000. Width x height must not exceed 25,000,000.": "Used when Design Type is Custom size. 40-8000. Width x height must not exceed 25,000,000.",+ "Used when Design Type is Custom size. 40-8000.": "Used when Design Type is Custom size. 40-8000.",+ "Optional name for the design (1-255 characters). Canva picks one if empty.": "Optional name for the design (1-255 characters). Canva picks one if empty.",+ "Optional image from your Canva library to add to the design.": "Optional image from your Canva library to add to the design.",+ "The design to look up. Type to search.": "The design to look up. Type to search.",+ "Images (max 50MB): JPG, JPEG, PNG, HEIC, GIF, TIFF, WEBP. Videos (max 500MB): M4V, MKV, MP4, MPEG, MOV, WEBM.": "Images (max 50MB): JPG, JPEG, PNG, HEIC, GIF, TIFF, WEBP. Videos (max 500MB): M4V, MKV, MP4, MPEG, MOV, WEBM.",+ "Name for the asset (max 50 characters).": "Name for the asset (max 50 characters).",+ "Wait until Canva finishes the job and return the result. Turn off to return the job ID right away and check it later with Get Job Status.": "Wait until Canva finishes the job and return the result. Turn off to return the job ID right away and check it later with Get Job Status.",+ "How long to wait for Canva before failing with the job ID (5-300, default 120).": "How long to wait for Canva before failing with the job ID (5-300, default 120).",+ "Supported: AI, PSD, KEY, NUMBERS, PAGES, XLS, XLSX, PPT, PPTX, DOC, DOCX, ODG, ODP, ODS, ODT, PDF.": "Supported: AI, PSD, KEY, NUMBERS, PAGES, XLS, XLSX, PPT, PPTX, DOC, DOCX, ODG, ODP, ODS, ODT, PDF.",+ "Title for the imported design (max 50 characters).": "Title for the imported design (max 50 characters).",+ "Let Canva detect the file type. Turn off to send the type based on the file extension.": "Let Canva detect the file type. Turn off to send the type based on the file extension.",+ "The design to export. Type to search.": "The design to export. Type to search.",+ "The file format to export to.": "The file format to export to.",+ "Pro quality can fail if the design has premium elements you have not licensed.": "Pro quality can fail if the design has premium elements you have not licensed.",+ "Page numbers to export (first page is 1). Leave empty for all pages.": "Page numbers to export (first page is 1). Leave empty for all pages.",+ "JPG only: compression quality from 1 to 100 (default 80).": "JPG only: compression quality from 1 to 100 (default 80).",+ "PDF only, Canva Docs only.": "PDF only, Canva Docs only.",+ "MP4 only: orientation and resolution.": "MP4 only: orientation and resolution.",+ "JPG, PNG and GIF only (40-25000). Leave empty for the design size.": "JPG, PNG and GIF only (40-25000). Leave empty for the design size.",+ "PNG only: export without compression. Lossy PNG needs a Canva Pro plan.": "PNG only: export without compression. Lossy PNG needs a Canva Pro plan.",+ "PNG only: transparent background (Canva Pro feature).": "PNG only: transparent background (Canva Pro feature).",+ "PNG only: merge a multi-page design into one image.": "PNG only: merge a multi-page design into one image.",+ "The folder to move the item to.": "The folder to move the item to.",+ "The kind of item to move.": "The kind of item to move.",+ "The design or image to move.": "The design or image to move.",+ "Keywords to search designs by. Leave empty to list all designs.": "Keywords to search designs by. Leave empty to list all designs.",+ "Which designs to include.": "Which designs to include.",+ "How to order the results.": "How to order the results.",+ "How many designs to return (1-100, default 20).": "How many designs to return (1-100, default 20).",+ "Token from a previous run to get the next page.": "Token from a previous run to get the next page.",+ "The folder to look up.": "The folder to look up.",+ "The asset to look up.": "The asset to look up.",+ "The folder to list.": "The folder to list.",+ "Only return these kinds of items. Leave empty for designs, folders and images.": "Only return these kinds of items. Leave empty for designs, folders and images.",+ "How to order the items.": "How to order the items.",+ "How many items to return (1-100, default 50).": "How many items to return (1-100, default 50).",+ "Name of the new folder (1-255 characters).": "Name of the new folder (1-255 characters).",+ "Where to create the folder.": "Where to create the folder.",+ "The action that started the job.": "The action that started the job.",+ "The job ID returned by the action that started the job.": "The job ID returned by the action that started the job.",+ "Search words (max 255 characters). Empty lists all designs.": "Search words (max 255 characters). Empty lists all designs.",+ "any, owned or shared. Default any.": "any, owned or shared. Default any.",+ "Default relevance.": "Default relevance.",+ "Designs per page, 1-100. Default 25.": "Designs per page, 1-100. Default 25.",+ "Continuation token from the previous page.": "Continuation token from the previous page.",+ "The Canva design ID.": "The Canva design ID.",+ "Preset design type. Leave empty when giving width and height.": "Preset design type. Leave empty when giving width and height.",+ "Custom width in pixels (40-8000). Needs height too.": "Custom width in pixels (40-8000). Needs height too.",+ "Custom height in pixels (40-8000). Needs width too.": "Custom height in pixels (40-8000). Needs width too.",+ "Design title, 1-255 characters.": "Design title, 1-255 characters.",+ "Optional image asset ID to insert.": "Optional image asset ID to insert.",+ "Export file type.": "Export file type.",+ "Page numbers to export, first page is 1. Empty exports all pages.": "Page numbers to export, first page is 1. Empty exports all pages.",+ "regular (default) or pro.": "regular (default) or pro.",+ "jpg only, 1-100. Default 80.": "jpg only, 1-100. Default 80.",+ "jpg, png or gif only: width in pixels (40-25000).": "jpg, png or gif only: width in pixels (40-25000).",+ "jpg, png or gif only: height in pixels (40-25000).": "jpg, png or gif only: height in pixels (40-25000).",+ "pdf only, Canva Docs only. Default a4.": "pdf only, Canva Docs only. Default a4.",+ "mp4 only. Default horizontal_1080p.": "mp4 only. Default horizontal_1080p.",+ "The job_id returned when the job was started.": "The job_id returned when the job was started.",+ "Public http(s) URL of the file (8-2048 characters).": "Public http(s) URL of the file (8-2048 characters).",+ "Asset name, 1-255 characters.": "Asset name, 1-255 characters.",+ "Public http(s) URL of the file (max 2048 characters).": "Public http(s) URL of the file (max 2048 characters).",+ "Title for the new design, 1-255 characters.": "Title for the new design, 1-255 characters.",+ "Optional MIME type of the file. Canva detects it when empty.": "Optional MIME type of the file. Canva detects it when empty.",+ "Folder ID, or root, or uploads.": "Folder ID, or root, or uploads.",+ "Any of design, folder, image. Empty returns all three.": "Any of design, folder, image. Empty returns all three.",+ "Default modified_descending.": "Default modified_descending.",+ "Items per page, 1-100. Default 50.": "Items per page, 1-100. Default 50.",+ "Folder name, 1-255 characters.": "Folder name, 1-255 characters.",+ "root, uploads, or a folder ID.": "root, uploads, or a folder ID.",+ "ID of the design, image or folder to move.": "ID of the design, image or folder to move.",+ "Destination folder ID, or root.": "Destination folder ID, or root.",+ "The Canva asset ID.": "The Canva asset ID.",+ "New name, max 50 characters. Empty leaves it unchanged.": "New name, max 50 characters. Empty leaves it unchanged.",+ "Full replacement list of tags (max 50). Empty leaves tags unchanged.": "Full replacement list of tags (max 50). Empty leaves tags unchanged.",+ "Remove all tags from the asset.": "Remove all tags from the asset.",+ "First page number to return, 1-500. Default 1.": "First page number to return, 1-500. Default 1.",+ "How many pages to return, 1-200. Default 50.": "How many pages to return, 1-200. Default 50.",+ "The Canva asset ID to delete.": "The Canva asset ID to delete.","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.",- "📋 Preset Design Type (Document, Whiteboard, Presentation)": "📋 Preset Design Type (Document, Whiteboard, Presentation)",- "📐 Custom Dimensions (Specify width & height)": "📐 Custom Dimensions (Specify width & height)",+ "Preset (Doc, Whiteboard, Presentation, Email)": "Preset (Doc, Whiteboard, Presentation, Email)",+ "Custom size (width and height)": "Custom size (width and height)","Document (Canva Docs)": "Document (Canva Docs)","Whiteboard": "Whiteboard","Presentation": "Presentation",+ "Email": "Email","PDF": "PDF","JPEG": "JPEG","PNG": "PNG","GIF": "GIF","PowerPoint (PPTX)": "PowerPoint (PPTX)","MP4 Video": "MP4 Video",- "Regular Quality": "Regular Quality",- "Pro Quality (Premium)": "Pro Quality (Premium)",+ "Regular": "Regular",+ "Pro": "Pro","A4": "A4","A3": "A3","Letter": "Letter",@@ -126,15 +238,57 @@"Vertical 720p": "Vertical 720p","Vertical 1080p": "Vertical 1080p","Vertical 4K": "Vertical 4K",- "Image Asset": "Image Asset",- "Any (owned + shared)": "Any (owned + shared)",+ "Any (owned and shared)": "Any (owned and shared)","Owned by me": "Owned by me","Shared with me": "Shared with me",- "📅 Recently Modified (Recommended)": "📅 Recently Modified (Recommended)",- "🔍 Relevance": "🔍 Relevance",- "📅 Oldest Modified": "📅 Oldest Modified",- "🔤 Title A-Z": "🔤 Title A-Z",- "🔤 Title Z-A": "🔤 Title Z-A",+ "Recently modified": "Recently modified",+ "Relevance": "Relevance",+ "Oldest modified": "Oldest modified",+ "Title A-Z": "Title A-Z",+ "Title Z-A": "Title Z-A",+ "Designs": "Designs",+ "Folders": "Folders",+ "Images": "Images",+ "Newest created": "Newest created",+ "Oldest created": "Oldest created",+ "Upload Asset (file)": "Upload Asset (file)",+ "Upload Asset (URL)": "Upload Asset (URL)",+ "Import Design (file)": "Import Design (file)",+ "Import Design (URL)": "Import Design (URL)",+ "any": "any",+ "owned": "owned",+ "shared": "shared",+ "relevance": "relevance",+ "modified_descending": "modified_descending",+ "modified_ascending": "modified_ascending",+ "title_ascending": "title_ascending",+ "title_descending": "title_descending",+ "doc": "doc",+ "whiteboard": "whiteboard",+ "presentation": "presentation",+ "email": "email",+ "pdf": "pdf",+ "jpg": "jpg",+ "png": "png",+ "gif": "gif",+ "pptx": "pptx",+ "mp4": "mp4",+ "regular": "regular",+ "pro": "pro",+ "a4": "a4",+ "a3": "a3",+ "letter": "letter",+ "legal": "legal",+ "horizontal_480p": "horizontal_480p",+ "horizontal_720p": "horizontal_720p",+ "horizontal_1080p": "horizontal_1080p",+ "horizontal_4k": "horizontal_4k",+ "vertical_480p": "vertical_480p",+ "vertical_720p": "vertical_720p",+ "vertical_1080p": "vertical_1080p",+ "vertical_4k": "vertical_4k",+ "created_descending": "created_descending",+ "created_ascending": "created_ascending","GET": "GET","POST": "POST","PATCH": "PATCH",diff --git a/packages/pieces/community/canva/src/index.ts b/packages/pieces/community/canva/src/index.tsindex 62221587aaa..d3fbaf9829b 100644--- a/packages/pieces/community/canva/src/index.ts+++ b/packages/pieces/community/canva/src/index.ts@@ -1,11 +1,6 @@-import {- OAuth2PropertyValue,- PieceAuth,- createPiece,-} from '@activepieces/pieces-framework';-import { PieceCategory } from '@activepieces/pieces-framework';-import { createCustomApiCallAction, httpClient, HttpMethod } from '@activepieces/pieces-common';-import { canvaCommon } from './lib/common';+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';+import { createCustomApiCallAction } from '@activepieces/pieces-common';+import { canvaAuth, canvaCommon } from './lib/common';import { createDesign } from './lib/actions/create-design';import { getDesign } from './lib/actions/get-design';import { uploadAsset } from './lib/actions/upload-asset';@@ -15,83 +10,35 @@ import { moveFolderItem } from './lib/actions/move-folder-item';import { findDesign } from './lib/actions/find-design';import { getFolder } from './lib/actions/get-folder';import { getAsset } from './lib/actions/get-asset';--const canvaAuthDescription = `-To connect Canva, follow these steps:-1. Go to https://www.canva.com/developers/integrations and sign in.-2. Click **Create an integration** and fill in the app name and description.-3. Under **Configure** → **Authentication**, set the redirect URL to the one shown above.-4. Under **Configure** → **Scopes**, enable: \`design:content:read\`, \`design:content:write\`, \`design:meta:read\`, \`asset:read\`, \`asset:write\`, \`folder:read\`, \`folder:write\`, \`profile:read\`.-5. Copy the **Client ID** and **Client secret** and paste them above.-`;--export const canvaAuth = PieceAuth.OAuth2({- description: canvaAuthDescription,- authUrl: 'https://www.canva.com/api/oauth/authorize',- tokenUrl: 'https://api.canva.com/rest/v1/oauth/token',- required: true,- pkce: true,- pkceMethod: 'S256',- scope: [- 'design:content:read',- 'design:content:write',- 'design:meta:read',- 'asset:read',- 'asset:write',- 'folder:read',- 'folder:write',- 'profile:read',- ],- getConnectionIdentifier: async ({ auth }) => {- try {- const response = await httpClient.sendRequest<{ profile?: { display_name?: string } }>({- method: HttpMethod.GET,- url: `${canvaCommon.baseUrl}/users/me/profile`,- headers: { Authorization: `Bearer ${auth.access_token}` },- timeout: 5000,- });- return response.body.profile?.display_name || undefined;- } catch {- return undefined;- }- },- validate: async ({ auth }) => {- try {- const authValue = auth as OAuth2PropertyValue;- if (!authValue.access_token) {- return { valid: false, error: 'No access token found' };- }-- const response = await httpClient.sendRequest({- method: HttpMethod.GET,- url: `${canvaCommon.baseUrl}/users/me`,- headers: {- Authorization: `Bearer ${authValue.access_token}`,- },- });-- if (response.status === 200) {- return { valid: true };- }-- return { valid: false, error: 'Invalid or expired access token' };- } catch (error: any) {- if (error.response?.status === 401) {- return { valid: false, error: 'Access token is invalid or expired' };- }- return { valid: false, error: 'Failed to validate authentication credentials' };- }- },-});+import { listFolderItems } from './lib/actions/list-folder-items';+import { createFolder } from './lib/actions/create-folder';+import { getJobStatus } from './lib/actions/get-job-status';+import { canvaListDesignsAi } from './lib/actions/ai/list-designs';+import { canvaGetDesignAi } from './lib/actions/ai/get-design';+import { canvaCreateDesignAi } from './lib/actions/ai/create-design';+import { canvaExportDesignAi } from './lib/actions/ai/export-design';+import { canvaGetExportJobAi } from './lib/actions/ai/get-export-job';+import { canvaUploadAssetFromUrlAi } from './lib/actions/ai/upload-asset-from-url';+import { canvaGetAssetUploadJobAi } from './lib/actions/ai/get-asset-upload-job';+import { canvaImportDesignFromUrlAi } from './lib/actions/ai/import-design-from-url';+import { canvaGetImportJobAi } from './lib/actions/ai/get-import-job';+import { canvaListFolderItemsAi } from './lib/actions/ai/list-folder-items';+import { canvaCreateFolderAi } from './lib/actions/ai/create-folder';+import { canvaMoveFolderItemAi } from './lib/actions/ai/move-folder-item';+import { canvaGetAssetAi } from './lib/actions/ai/get-asset';+import { canvaUpdateAssetAi } from './lib/actions/ai/update-asset';+import { canvaGetDesignPagesAi } from './lib/actions/ai/get-design-pages';+import { canvaGetExportFormatsAi } from './lib/actions/ai/get-export-formats';+import { canvaDeleteAssetAi } from './lib/actions/ai/delete-asset';export const canva = createPiece({displayName: 'Canva',- description: 'Create stunning designs with Canva\'s powerful design automation tools',+ description: "Create, export and organize Canva designs and assets",auth: canvaAuth,- minimumSupportedRelease: '0.36.1',+ minimumSupportedRelease: '0.86.4',logoUrl: 'https://cdn.activepieces.com/pieces/canva.png',categories: [PieceCategory.CONTENT_AND_FILES],- authors: ['onyedikachi-david'],+ authors: ['onyedikachi-david', 'OdaiAhmed99'],actions: [createDesign,getDesign,@@ -102,17 +49,35 @@ export const canva = createPiece({findDesign,getFolder,getAsset,+ listFolderItems,+ createFolder,+ getJobStatus,+ canvaListDesignsAi,+ canvaGetDesignAi,+ canvaCreateDesignAi,+ canvaExportDesignAi,+ canvaGetExportJobAi,+ canvaUploadAssetFromUrlAi,+ canvaGetAssetUploadJobAi,+ canvaImportDesignFromUrlAi,+ canvaGetImportJobAi,+ canvaListFolderItemsAi,+ canvaCreateFolderAi,+ canvaMoveFolderItemAi,+ canvaGetAssetAi,+ canvaUpdateAssetAi,+ canvaGetDesignPagesAi,+ canvaGetExportFormatsAi,+ canvaDeleteAssetAi,createCustomApiCallAction({- baseUrl: () => 'https://api.canva.com/rest/v1',+ baseUrl: () => canvaCommon.baseUrl,auth: canvaAuth,- authMapping: async (auth) => {- const authValue = auth as OAuth2PropertyValue;- return {- Authorization: `Bearer ${authValue.access_token}`,- };- },+ authMapping: async (auth) => ({+ Authorization: `Bearer ${auth.access_token}`,+ }),}),],triggers: [],});-\ No newline at end of file++export { canvaAuth };diff --git a/packages/pieces/community/canva/src/lib/actions/ai/create-design.ts b/packages/pieces/community/canva/src/lib/actions/ai/create-design.tsnew file mode 100644index 00000000000..274a0a3d670--- /dev/null+++ b/packages/pieces/community/canva/src/lib/actions/ai/create-design.ts@@ -0,0 +1,62 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { canvaAuth, CanvaDesignResponse } from '../../common';+import { canvaClient } from '../../common/client';+import { canvaOutputSchemas } from '../../common/output-schemas';+import { createDesignBody } from '../create-design';++export const canvaCreateDesignAi = createAction({+ auth: canvaAuth,+ name: 'canva_create_design',+ displayName: 'Create Design',+ description: 'Creates a new blank Canva design.',+ audience: 'ai',+ classification: 'WRITE',+ outputSchema: canvaOutputSchemas.aiDesign,+ aiMetadata: {+ description:+ 'Creates a new blank Canva design. Give either presetName (doc, whiteboard, presentation, email) or width and height in pixels (40-8000 each, area at most 25,000,000), and optionally a title and an image assetId to place in it. Returns the design with its ID and edit link. Untouched blank designs are deleted by Canva after 7 days. To turn an existing file into a design use canva_import_design_from_url instead.',+ idempotent: false,+ },+ props: {+ presetName: Property.StaticDropdown({+ displayName: 'Preset Name',+ description: 'Preset design type. Leave empty when giving width and height.',+ required: false,+ options: {+ options: [+ { label: 'doc', value: 'doc' },+ { label: 'whiteboard', value: 'whiteboard' },+ { label: 'presentation', value: 'presentation' },+ { label: 'email', value: 'email' },+ ],+ },+ }),+ width: Property.Number({ displayName: 'Width', description: 'Custom width in pixels (40-8000). Needs height too.', required: false }),+ height: Property.Number({ displayName: 'Height', description: 'Custom height in pixels (40-8000). Needs width too.', required: false }),+ title: Property.ShortText({ displayName: 'Title', description: 'Design title, 1-255 characters.', required: false }),+ assetId: Property.ShortText({ displayName: 'Asset ID', description: 'Optional image asset ID to insert.', required: false }),+ },+ async run(context) {+ const { presetName, width, height, title, assetId } = context.propsValue;+ const hasSize = (width !== undefined && width !== null) || (height !== undefined && height !== null);+ if (presetName && hasSize) {+ throw new Error('Give either presetName or width and height, not both.');+ }+ const body = createDesignBody({+ designType: presetName ? 'preset' : hasSize ? 'custom' : 'none',+ presetName: presetName ?? undefined,+ width: width ?? undefined,+ height: height ?? undefined,+ title: title ?? undefined,+ assetId: assetId ?? undefined,+ });+ const response = await canvaClient.request<CanvaDesignResponse>({+ token: context.auth.access_token,+ method: HttpMethod.POST,+ path: '/designs',+ body,+ });+ return { design: response.design };+ },+});diff --git a/packages/pieces/community/canva/src/lib/actions/ai/create-folder.ts b/packages/pieces/community/canva/src/lib/actions/ai/create-folder.tsnew file mode 100644index 00000000000..b9191a1504a--- /dev/null+++ b/packages/pieces/community/canva/src/lib/actions/ai/create-folder.ts@@ -0,0 +1,26 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { canvaAuth } from '../../common';+import { canvaOutputSchemas } from '../../common/output-schemas';+import { createFolderRequest } from '../create-folder';++export const canvaCreateFolderAi = createAction({+ auth: canvaAuth,+ name: 'canva_create_folder',+ displayName: 'Create Folder',+ description: 'Creates a Canva folder.',+ audience: 'ai',+ classification: 'WRITE',+ outputSchema: canvaOutputSchemas.folderResult,+ aiMetadata: {+ description:+ 'Creates a folder and returns its ID. parentFolderId is "root" for the top level of Projects, "uploads" for the Uploads folder, or another folder ID. Canva allows duplicate names, so each call creates another folder; check canva_list_folder_items first to reuse an existing one.',+ idempotent: false,+ },+ props: {+ name: Property.ShortText({ displayName: 'Name', description: 'Folder name, 1-255 characters.', required: true }),+ parentFolderId: Property.ShortText({ displayName: 'Parent Folder ID', description: 'root, uploads, or a folder ID.', required: true }),+ },+ async run(context) {+ return createFolderRequest({ token: context.auth.access_token, name: context.propsValue.name, parentFolderId: context.propsValue.parentFolderId });+ },+});diff --git a/packages/pieces/community/canva/src/lib/actions/ai/delete-asset.ts b/packages/pieces/community/canva/src/lib/actions/ai/delete-asset.tsnew file mode 100644index 00000000000..bb212b99b48--- /dev/null+++ b/packages/pieces/community/canva/src/lib/actions/ai/delete-asset.ts@@ -0,0 +1,35 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { canvaAuth } from '../../common';+import { canvaClient } from '../../common/client';+import { canvaOutputSchemas } from '../../common/output-schemas';++export const canvaDeleteAssetAi = createAction({+ auth: canvaAuth,+ name: 'canva_delete_asset',+ displayName: 'Delete Asset',+ description: 'Deletes an image or video from the Canva library.',+ audience: 'ai',+ classification: 'DESTRUCTIVE',+ outputSchema: canvaOutputSchemas.aiDeleteAsset,+ aiMetadata: {+ description:+ "Deletes one image or video from the user's Canva library by asset ID (moves it to Canva's trash). Only use when the user clearly asked to delete that asset; confirm the ID with canva_get_asset first. Not idempotent: a second call for the same ID fails with not found.",+ idempotent: false,+ },+ props: {+ assetId: Property.ShortText({ displayName: 'Asset ID', description: 'The Canva asset ID to delete.', required: true }),+ },+ async run(context) {+ const assetId = context.propsValue.assetId.trim();+ if (!assetId) {+ throw new Error('Asset ID is required.');+ }+ await canvaClient.request<unknown>({+ token: context.auth.access_token,+ method: HttpMethod.DELETE,+ path: `/assets/${encodeURIComponent(assetId)}`,+ });+ return { deleted: true, asset_id: assetId };+ },+});diff --git a/packages/pieces/community/canva/src/lib/actions/ai/export-design.ts b/packages/pieces/community/canva/src/lib/actions/ai/export-design.tsnew file mode 100644index 00000000000..c96d3545251--- /dev/null+++ b/packages/pieces/community/canva/src/lib/actions/ai/export-design.ts@@ -0,0 +1,78 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { AI_WAIT_SECONDS, canvaAuth, canvaCommon, EXPORT_FORMATS, ExportJob, MP4_QUALITIES, PDF_SIZES } from '../../common';+import { canvaClient } from '../../common/client';+import { canvaOutputSchemas } from '../../common/output-schemas';+import { exportFormatBuilder } from '../export-design';++export const canvaExportDesignAi = createAction({+ auth: canvaAuth,+ name: 'canva_export_design',+ displayName: 'Export Design',+ description: 'Starts a Canva export job and waits briefly for the download links.',+ audience: 'ai',+ classification: 'READ',+ outputSchema: canvaOutputSchemas.job,+ aiMetadata: {+ description:+ 'Exports a Canva design to pdf, jpg, png, gif, pptx or mp4. Starts an export job and waits up to about 25 seconds. If status is success, urls holds one download link per page (valid 24 hours). If status is still in_progress, call canva_get_export_job with job_id. Fails when Canva reports the job failed (for example license_required for premium elements; retry with exportQuality regular). Call canva_get_export_formats first if unsure which formats a design supports. Each call starts a new job.',+ idempotent: false,+ },+ props: {+ designId: Property.ShortText({ displayName: 'Design ID', description: 'The Canva design ID.', required: true }),+ format: Property.StaticDropdown({+ displayName: 'Format',+ description: 'Export file type.',+ required: true,+ options: { options: EXPORT_FORMATS.map((f) => ({ label: f.value, value: f.value })) },+ }),+ pages: Property.Array({ displayName: 'Pages', description: 'Page numbers to export, first page is 1. Empty exports all pages.', required: false }),+ exportQuality: Property.StaticDropdown({+ displayName: 'Export Quality',+ description: 'regular (default) or pro.',+ required: false,+ options: { options: [{ label: 'regular', value: 'regular' }, { label: 'pro', value: 'pro' }] },+ }),+ jpgQuality: Property.Number({ displayName: 'JPG Quality', description: 'jpg only, 1-100. Default 80.', required: false }),+ width: Property.Number({ displayName: 'Width', description: 'jpg, png or gif only: width in pixels (40-25000).', required: false }),+ height: Property.Number({ displayName: 'Height', description: 'jpg, png or gif only: height in pixels (40-25000).', required: false }),+ pdfSize: Property.StaticDropdown({+ displayName: 'PDF Size',+ description: 'pdf only, Canva Docs only. Default a4.',+ required: false,+ options: { options: PDF_SIZES.map((s) => ({ label: s.value, value: s.value })) },+ }),+ mp4Quality: Property.StaticDropdown({+ displayName: 'MP4 Quality',+ description: 'mp4 only. Default horizontal_1080p.',+ required: false,+ options: { options: MP4_QUALITIES.map((q) => ({ label: q.value, value: q.value })) },+ }),+ },+ async run(context) {+ const p = context.propsValue;+ const designId = p.designId.trim();+ if (!designId) {+ throw new Error('Design ID is required.');+ }+ const format = exportFormatBuilder({+ type: p.format,+ exportQuality: p.exportQuality ?? undefined,+ pages: canvaCommon.parsePageNumbers(p.pages ?? undefined),+ jpegQuality: p.jpgQuality ?? undefined,+ width: p.width ?? undefined,+ height: p.height ?? undefined,+ pdfSize: p.pdfSize ?? undefined,+ mp4Quality: p.mp4Quality ?? undefined,+ });+ const token = context.auth.access_token;+ const started = await canvaClient.request<{ job: ExportJob }>({+ token,+ method: HttpMethod.POST,+ path: '/exports',+ body: { design_id: designId, format },+ });+ const job = await canvaCommon.settleJob<ExportJob>({ token, kind: 'export', initial: started.job, timeoutSeconds: AI_WAIT_SECONDS, failOnTimeout: false, statusAction: 'the canva_get_export_job tool' });+ return canvaCommon.flattenJob({ kind: 'export', job });+ },+});diff --git a/packages/pieces/community/canva/src/lib/actions/ai/get-asset-upload-job.ts b/packages/pieces/community/canva/src/lib/actions/ai/get-asset-upload-job.tsnew file mode 100644index 00000000000..2b578ef18a9--- /dev/null+++ b/packages/pieces/community/canva/src/lib/actions/ai/get-asset-upload-job.ts@@ -0,0 +1,29 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { AnyJob, canvaAuth, canvaCommon } from '../../common';+import { canvaOutputSchemas } from '../../common/output-schemas';++export const canvaGetAssetUploadJobAi = createAction({+ auth: canvaAuth,+ name: 'canva_get_asset_upload_job',+ displayName: 'Get Asset Upload Job',+ description: 'Get Asset Upload Job by job ID.',+ audience: 'ai',+ classification: 'READ',+ outputSchema: canvaOutputSchemas.job,+ aiMetadata: {+ description:+ 'Checks an asset upload job started by canva_upload_asset_from_url. status is in_progress, success or failed. On success, asset holds the new asset with its ID. On failure, error_code and error_message say why. Wait a few seconds between checks while in_progress.',+ idempotent: true,+ },+ props: {+ jobId: Property.ShortText({ displayName: 'Job ID', description: 'The job_id returned when the job was started.', required: true }),+ },+ async run(context) {+ const jobId = context.propsValue.jobId.trim();+ if (!jobId) {+ throw new Error('Job ID is required.');+ }+ const job = await canvaCommon.fetchJob<AnyJob>({ token: context.auth.access_token, kind: 'url_asset_upload', jobId });+ return canvaCommon.flattenJob({ kind: 'url_asset_upload', job });+ },+});diff --git a/packages/pieces/community/canva/src/lib/actions/ai/get-asset.ts b/packages/pieces/community/canva/src/lib/actions/ai/get-asset.tsnew file mode 100644index 00000000000..9fc6e71052d--- /dev/null+++ b/packages/pieces/community/canva/src/lib/actions/ai/get-asset.ts@@ -0,0 +1,35 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { AssetResponse, canvaAuth } from '../../common';+import { canvaClient } from '../../common/client';+import { canvaOutputSchemas } from '../../common/output-schemas';++export const canvaGetAssetAi = createAction({+ auth: canvaAuth,+ name: 'canva_get_asset',+ displayName: 'Get Asset',+ description: 'Gets one Canva library asset by ID.',+ audience: 'ai',+ classification: 'READ',+ outputSchema: canvaOutputSchemas.aiAsset,+ aiMetadata: {+ description:+ 'Returns one image or video from the Canva library: name, type, tags, timestamps and thumbnail. Needs the asset ID (from canva_list_folder_items or canva_upload_asset_from_url). Assets are media, not designs; use canva_get_design for designs.',+ idempotent: true,+ },+ props: {+ assetId: Property.ShortText({ displayName: 'Asset ID', description: 'The Canva asset ID.', required: true }),+ },+ async run(context) {+ const assetId = context.propsValue.assetId.trim();+ if (!assetId) {+ throw new Error('Asset ID is required.');+ }+ const body = await canvaClient.request<AssetResponse>({+ token: context.auth.access_token,+ method: HttpMethod.GET,+ path: `/assets/${encodeURIComponent(assetId)}`,+ });+ return { asset: body.asset };+ },+});diff --git a/packages/pieces/community/canva/src/lib/actions/ai/get-design-pages.ts b/packages/pieces/community/canva/src/lib/actions/ai/get-design-pages.tsnew file mode 100644index 00000000000..1be82fc425b--- /dev/null+++ b/packages/pieces/community/canva/src/lib/actions/ai/get-design-pages.ts@@ -0,0 +1,70 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { canvaAuth } from '../../common';+import { canvaClient } from '../../common/client';+import { canvaOutputSchemas } from '../../common/output-schemas';++export const canvaGetDesignPagesAi = createAction({+ auth: canvaAuth,+ name: 'canva_get_design_pages',+ displayName: 'Get Design Pages',+ description: 'Lists the pages of a Canva design with thumbnails and sizes.',+ audience: 'ai',+ classification: 'READ',+ outputSchema: canvaOutputSchemas.aiDesignPages,+ aiMetadata: {+ description:+ 'Lists pages of a Canva design: page number, page ID, design type, width/height in pixels (bounded designs only) and a thumbnail URL valid 15 minutes. Use offset (first page 1, max 500) and limit (1-200, default 50) for long designs. Some design types (for example Canva Docs) have no pages and return an empty list. This Canva API is in preview and may change.',+ idempotent: true,+ },+ props: {+ designId: Property.ShortText({ displayName: 'Design ID', description: 'The Canva design ID.', required: true }),+ offset: Property.Number({ displayName: 'Offset', description: 'First page number to return, 1-500. Default 1.', required: false }),+ limit: Property.Number({ displayName: 'Limit', description: 'How many pages to return, 1-200. Default 50.', required: false }),+ },+ async run(context) {+ const { designId, offset, limit } = context.propsValue;+ const id = designId.trim();+ if (!id) {+ throw new Error('Design ID is required.');+ }+ const queryParams: Record<string, string> = {};+ if (offset !== undefined && offset !== null) {+ if (!Number.isInteger(offset) || offset < 1 || offset > 500) {+ throw new Error('Offset must be a whole number between 1 and 500.');+ }+ queryParams['offset'] = String(offset);+ }+ if (limit !== undefined && limit !== null) {+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) {+ throw new Error('Limit must be a whole number between 1 and 200.');+ }+ queryParams['limit'] = String(limit);+ }+ const body = await canvaClient.request<{ items?: DesignPage[] }>({+ token: context.auth.access_token,+ method: HttpMethod.GET,+ path: `/designs/${encodeURIComponent(id)}/pages`,+ queryParams,+ });+ return {+ pages: (body?.items ?? []).map((page) => ({+ page_number: page.page_number ?? page.index ?? null,+ id: page.id ?? null,+ design_type: page.design_type ?? null,+ width: page.dimensions?.width ?? null,+ height: page.dimensions?.height ?? null,+ thumbnail_url: page.thumbnail?.url ?? null,+ })),+ };+ },+});++type DesignPage = {+ page_number?: number;+ index?: number;+ id?: string;+ design_type?: string;+ dimensions?: { width: number; height: number };+ thumbnail?: { url: string };+};diff --git a/packages/pieces/community/canva/src/lib/actions/ai/get-design.ts b/packages/pieces/community/canva/src/lib/actions/ai/get-design.tsnew file mode 100644index 00000000000..cf7b1215667--- /dev/null+++ b/packages/pieces/community/canva/src/lib/actions/ai/get-design.ts@@ -0,0 +1,35 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { canvaAuth, CanvaDesignResponse } from '../../common';+import { canvaClient } from '../../common/client';+import { canvaOutputSchemas } from '../../common/output-schemas';++export const canvaGetDesignAi = createAction({+ auth: canvaAuth,+ name: 'canva_get_design',+ displayName: 'Get Design',+ description: 'Gets one Canva design by ID.',+ audience: 'ai',+ classification: 'READ',+ outputSchema: canvaOutputSchemas.aiDesign,+ aiMetadata: {+ description:+ 'Returns metadata for one Canva design: title, owner, temporary edit/view links (valid 30 days), page count and thumbnail. Needs the design ID; use canva_list_designs to find it. Fails with 404 when the design does not exist or is not shared with the user.',+ idempotent: true,+ },+ props: {+ designId: Property.ShortText({ displayName: 'Design ID', description: 'The Canva design ID.', required: true }),+ },+ async run(context) {+ const designId = context.propsValue.designId.trim();+ if (!designId) {+ throw new Error('Design ID is required.');+ }+ const body = await canvaClient.request<CanvaDesignResponse>({+ token: context.auth.access_token,+ method: HttpMethod.GET,+ path: `/designs/${encodeURIComponent(designId)}`,+ });+ return { design: body.design };+ },+});diff --git a/packages/pieces/community/canva/src/lib/actions/ai/get-export-formats.ts b/packages/pieces/community/canva/src/lib/actions/ai/get-export-formats.tsnew file mode 100644index 00000000000..dbc016825c7--- /dev/null+++ b/packages/pieces/community/canva/src/lib/actions/ai/get-export-formats.ts@@ -0,0 +1,43 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { canvaAuth } from '../../common';+import { canvaClient } from '../../common/client';+import { canvaOutputSchemas } from '../../common/output-schemas';++export const canvaGetExportFormatsAi = createAction({+ auth: canvaAuth,+ name: 'canva_get_export_formats',+ displayName: 'Get Export Formats',+ description: 'Lists the file formats a Canva design can be exported to.',+ audience: 'ai',+ classification: 'READ',+ outputSchema: canvaOutputSchemas.aiExportFormats,+ aiMetadata: {+ description:+ 'Returns which export formats a design supports (for example pdf, jpg, png, gif, pptx, mp4, svg). For each format, all_pages is true when every page supports it, otherwise page_numbers lists the pages that do. Call this before canva_export_design when unsure; canva_export_design accepts pdf, jpg, png, gif, pptx and mp4.',+ idempotent: true,+ },+ props: {+ designId: Property.ShortText({ displayName: 'Design ID', description: 'The Canva design ID.', required: true }),+ },+ async run(context) {+ const id = context.propsValue.designId.trim();+ if (!id) {+ throw new Error('Design ID is required.');+ }+ const body = await canvaClient.request<{ formats?: Record<string, { page_numbers?: number[] } | undefined> }>({+ token: context.auth.access_token,+ method: HttpMethod.GET,+ path: `/designs/${encodeURIComponent(id)}/export-formats`,+ });+ return {+ formats: Object.entries(body?.formats ?? {})+ .filter(([, option]) => option !== undefined && option !== null)+ .map(([format, option]) => ({+ format,+ all_pages: !option?.page_numbers,+ page_numbers: option?.page_numbers ?? [],+ })),+ };+ },+});diff --git a/packages/pieces/community/canva/src/lib/actions/ai/get-export-job.ts b/packages/pieces/community/canva/src/lib/actions/ai/get-export-job.tsnew file mode 100644index 00000000000..b01da8c9d34--- /dev/null+++ b/packages/pieces/community/canva/src/lib/actions/ai/get-export-job.ts@@ -0,0 +1,29 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { AnyJob, canvaAuth, canvaCommon } from '../../common';+import { canvaOutputSchemas } from '../../common/output-schemas';++export const canvaGetExportJobAi = createAction({+ auth: canvaAuth,+ name: 'canva_get_export_job',+ displayName: 'Get Export Job',+ description: 'Get Export Job by job ID.',+ audience: 'ai',+ classification: 'READ',+ outputSchema: canvaOutputSchemas.job,+ aiMetadata: {+ description:+ 'Checks an export job started by canva_export_design. status is in_progress, success or failed. On success, urls holds the download links (valid 24 hours, one per page). On failure, error_code and error_message say why. Wait a few seconds between checks while in_progress.',+ idempotent: true,+ },+ props: {+ jobId: Property.ShortText({ displayName: 'Job ID', description: 'The job_id returned when the job was started.', required: true }),+ },+ async run(context) {+ const jobId = context.propsValue.jobId.trim();+ if (!jobId) {+ throw new Error('Job ID is required.');+ }+ const job = await canvaCommon.fetchJob<AnyJob>({ token: context.auth.access_token, kind: 'export', jobId });+ return canvaCommon.flattenJob({ kind: 'export', job });+ },+});diff --git a/packages/pieces/community/canva/src/lib/actions/ai/get-import-job.ts b/packages/pieces/community/canva/src/lib/actions/ai/get-import-job.tsnew file mode 100644index 00000000000..c081198cd36--- /dev/null+++ b/packages/pieces/community/canva/src/lib/actions/ai/get-import-job.ts@@ -0,0 +1,29 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { AnyJob, canvaAuth, canvaCommon } from '../../common';+import { canvaOutputSchemas } from '../../common/output-schemas';++export const canvaGetImportJobAi = createAction({+ auth: canvaAuth,+ name: 'canva_get_import_job',+ displayName: 'Get Import Job',+ description: 'Get Import Job by job ID.',+ audience: 'ai',+ classification: 'READ',+ outputSchema: canvaOutputSchemas.job,+ aiMetadata: {+ description:+ 'Checks a design import job started by canva_import_design_from_url. status is in_progress, success or failed. On success, designs holds the new design(s); large files can be split into several designs. On failure, error_code and error_message say why. Wait a few seconds between checks while in_progress.',+ idempotent: true,+ },+ props: {+ jobId: Property.ShortText({ displayName: 'Job ID', description: 'The job_id returned when the job was started.', required: true }),+ },+ async run(context) {+ const jobId = context.propsValue.jobId.trim();+ if (!jobId) {+ throw new Error('Job ID is required.');+ }+ const job = await canvaCommon.fetchJob<AnyJob>({ token: context.auth.access_token, kind: 'url_import', jobId });+ return canvaCommon.flattenJob({ kind: 'url_import', job });+ },+});diff --git a/packages/pieces/community/canva/src/lib/actions/ai/import-design-from-url.ts b/packages/pieces/community/canva/src/lib/actions/ai/import-design-from-url.tsnew file mode 100644index 00000000000..cfb540fec62--- /dev/null+++ b/packages/pieces/community/canva/src/lib/actions/ai/import-design-from-url.ts@@ -0,0 +1,44 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { AI_WAIT_SECONDS, canvaAuth, canvaCommon, DesignImportJob } from '../../common';+import { canvaClient } from '../../common/client';+import { canvaOutputSchemas } from '../../common/output-schemas';++export const canvaImportDesignFromUrlAi = createAction({+ auth: canvaAuth,+ name: 'canva_import_design_from_url',+ displayName: 'Import Design From URL',+ description: 'Imports a file from a public URL as a new Canva design.',+ audience: 'ai',+ classification: 'WRITE',+ outputSchema: canvaOutputSchemas.job,+ aiMetadata: {+ description:+ 'Turns a file at a public URL (PDF, PPTX, DOCX, XLSX, Keynote, Pages, Numbers, PSD, AI, OpenDocument) into a new editable Canva design. Starts an import job and waits up to about 25 seconds. If status is success, designs holds the new design(s). If still in_progress, call canva_get_import_job with job_id. Fails when Canva reports the import failed. Each call creates new designs.',+ idempotent: false,+ },+ props: {+ url: Property.ShortText({ displayName: 'URL', description: 'Public http(s) URL of the file (max 2048 characters).', required: true }),+ title: Property.ShortText({ displayName: 'Title', description: 'Title for the new design, 1-255 characters.', required: true }),+ mimeType: Property.ShortText({ displayName: 'MIME Type', description: 'Optional MIME type of the file. Canva detects it when empty.', required: false }),+ },+ async run(context) {+ const url = context.propsValue.url.trim();+ const title = context.propsValue.title.trim();+ const mimeType = context.propsValue.mimeType?.trim();+ if (!/^https?:\/\//i.test(url) || url.length > 2048) {+ throw new Error('URL must be a public http(s) link of at most 2048 characters.');+ }+ if (!title || title.length > 255) {+ throw new Error('Title must be 1-255 characters.');+ }+ const body: Record<string, string> = { title, url };+ if (mimeType) {+ body['mime_type'] = mimeType;+ }+ const token = context.auth.access_token;+ const started = await canvaClient.request<{ job: DesignImportJob }>({ token, method: HttpMethod.POST, path: '/url-imports', body });+ const job = await canvaCommon.settleJob<DesignImportJob>({ token, kind: 'url_import', initial: started.job, timeoutSeconds: AI_WAIT_SECONDS, failOnTimeout: false, statusAction: 'the canva_get_import_job tool' });+ return canvaCommon.flattenJob({ kind: 'url_import', job });+ },+});diff --git a/packages/pieces/community/canva/src/lib/actions/ai/list-designs.ts b/packages/pieces/community/canva/src/lib/actions/ai/list-designs.tsnew file mode 100644index 00000000000..9c4358ba553--- /dev/null+++ b/packages/pieces/community/canva/src/lib/actions/ai/list-designs.ts@@ -0,0 +1,56 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { canvaAuth } from '../../common';+import { canvaOutputSchemas } from '../../common/output-schemas';+import { listDesignsRequest } from '../find-design';++export const canvaListDesignsAi = createAction({+ auth: canvaAuth,+ name: 'canva_list_designs',+ displayName: 'List Designs',+ description: 'Searches or lists Canva designs, one page at a time.',+ audience: 'ai',+ classification: 'SEARCH',+ outputSchema: canvaOutputSchemas.aiListDesigns,+ aiMetadata: {+ description:+ "Searches the user's Canva designs by keyword (title or content), or lists all designs when query is empty. Returns up to limit designs (1-100) with IDs, titles, edit/view links and page counts, plus a continuation token when more exist. Use this to find a design ID before canva_get_design, canva_export_design or canva_move_folder_item.",+ idempotent: true,+ },+ props: {+ query: Property.ShortText({ displayName: 'Query', description: 'Search words (max 255 characters). Empty lists all designs.', required: false }),+ ownership: Property.StaticDropdown({+ displayName: 'Ownership',+ description: 'any, owned or shared. Default any.',+ required: false,+ options: { options: [{ label: 'any', value: 'any' }, { label: 'owned', value: 'owned' }, { label: 'shared', value: 'shared' }] },+ }),+ sortBy: Property.StaticDropdown({+ displayName: 'Sort By',+ description: 'Default relevance.',+ required: false,+ options: {+ options: [+ { label: 'relevance', value: 'relevance' },+ { label: 'modified_descending', value: 'modified_descending' },+ { label: 'modified_ascending', value: 'modified_ascending' },+ { label: 'title_ascending', value: 'title_ascending' },+ { label: 'title_descending', value: 'title_descending' },+ ],+ },+ }),+ limit: Property.Number({ displayName: 'Limit', description: 'Designs per page, 1-100. Default 25.', required: false }),+ continuation: Property.ShortText({ displayName: 'Continuation', description: 'Continuation token from the previous page.', required: false }),+ },+ async run(context) {+ const { query, ownership, sortBy, limit, continuation } = context.propsValue;+ const page = await listDesignsRequest({+ token: context.auth.access_token,+ query: query ?? undefined,+ ownership: ownership ?? undefined,+ sortBy: sortBy ?? undefined,+ limit: limit ?? undefined,+ continuation: continuation ?? undefined,+ });+ return { designs: page.items, has_more: Boolean(page.continuation), continuation: page.continuation ?? null };+ },+});diff --git a/packages/pieces/community/canva/src/lib/actions/ai/list-folder-items.ts b/packages/pieces/community/canva/src/lib/actions/ai/list-folder-items.tsnew file mode 100644index 00000000000..825290b69fc--- /dev/null+++ b/packages/pieces/community/canva/src/lib/actions/ai/list-folder-items.ts@@ -0,0 +1,44 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { canvaAuth } from '../../common';+import { canvaOutputSchemas } from '../../common/output-schemas';+import { listFolderItemsRequest } from '../list-folder-items';++export const canvaListFolderItemsAi = createAction({+ auth: canvaAuth,+ name: 'canva_list_folder_items',+ displayName: 'List Folder Items',+ description: 'Lists designs, images and subfolders in a Canva folder.',+ audience: 'ai',+ classification: 'SEARCH',+ outputSchema: canvaOutputSchemas.listFolderItems,+ aiMetadata: {+ description:+ 'Lists the items in a Canva folder, one page at a time: each item has type (design, folder, image), id and name. Use folderId "root" for the top level of Projects and "uploads" for the Uploads folder; pass a returned folder id to go deeper. Video assets are not listed by Canva. Use the continuation token for the next page.',+ idempotent: true,+ },+ props: {+ folderId: Property.ShortText({ displayName: 'Folder ID', description: 'Folder ID, or root, or uploads.', required: true }),+ itemTypes: Property.Array({ displayName: 'Item Types', description: 'Any of design, folder, image. Empty returns all three.', required: false }),+ sortBy: Property.StaticDropdown({+ displayName: 'Sort By',+ description: 'Default modified_descending.',+ required: false,+ options: {+ options: ['modified_descending', 'modified_ascending', 'created_descending', 'created_ascending', 'title_ascending', 'title_descending'].map((v) => ({ label: v, value: v })),+ },+ }),+ limit: Property.Number({ displayName: 'Limit', description: 'Items per page, 1-100. Default 50.', required: false }),+ continuation: Property.ShortText({ displayName: 'Continuation', description: 'Continuation token from the previous page.', required: false }),+ },+ async run(context) {+ const { folderId, itemTypes, sortBy, limit, continuation } = context.propsValue;+ return listFolderItemsRequest({+ token: context.auth.access_token,+ folderId,+ itemTypes: (itemTypes ?? []).map((t) => String(t)),+ sortBy: sortBy ?? undefined,+ limit: limit ?? undefined,+ continuation: continuation ?? undefined,+ });+ },+});diff --git a/packages/pieces/community/canva/src/lib/actions/ai/move-folder-item.ts b/packages/pieces/community/canva/src/lib/actions/ai/move-folder-item.tsnew file mode 100644index 00000000000..dfe8493f762--- /dev/null+++ b/packages/pieces/community/canva/src/lib/actions/ai/move-folder-item.ts@@ -0,0 +1,32 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { canvaAuth } from '../../common';+import { canvaOutputSchemas } from '../../common/output-schemas';+import { moveFolderItemRequest } from '../move-folder-item';++export const canvaMoveFolderItemAi = createAction({+ auth: canvaAuth,+ name: 'canva_move_folder_item',+ displayName: 'Move Folder Item',+ description: 'Moves a design, image or folder into another folder.',+ audience: 'ai',+ classification: 'WRITE',+ outputSchema: canvaOutputSchemas.moveFolderItem,+ aiMetadata: {+ description:+ 'Moves a design, image asset or folder (by itemId) into the folder toFolderId ("root" for the top level of Projects). Videos are not supported. Fails when the item is in several folders; that item must be moved in the Canva app. Repeating the same move leaves the item where it is.',+ idempotent: true,+ },+ props: {+ itemId: Property.ShortText({ displayName: 'Item ID', description: 'ID of the design, image or folder to move.', required: true }),+ toFolderId: Property.ShortText({ displayName: 'To Folder ID', description: 'Destination folder ID, or root.', required: true }),+ },+ async run(context) {+ const itemId = context.propsValue.itemId.trim();+ const toFolderId = context.propsValue.toFolderId.trim();+ if (!itemId || !toFolderId || itemId.length > 50 || toFolderId.length > 50) {+ throw new Error('Item ID and destination folder ID are required (max 50 characters each).');+ }+ await moveFolderItemRequest({ token: context.auth.access_token, itemId, toFolderId });+ return { moved_item_id: itemId, destination_folder_id: toFolderId, message: `Item ${itemId} moved to folder ${toFolderId}` };+ },+});diff --git a/packages/pieces/community/canva/src/lib/actions/ai/update-asset.ts b/packages/pieces/community/canva/src/lib/actions/ai/update-asset.tsnew file mode 100644index 00000000000..54e3d503626--- /dev/null+++ b/packages/pieces/community/canva/src/lib/actions/ai/update-asset.ts@@ -0,0 +1,63 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { AssetResponse, canvaAuth, MAX_ASSET_NAME_LENGTH } from '../../common';+import { canvaClient } from '../../common/client';+import { canvaOutputSchemas } from '../../common/output-schemas';++export const canvaUpdateAssetAi = createAction({+ auth: canvaAuth,+ name: 'canva_update_asset',+ displayName: 'Update Asset',+ description: 'Renames a Canva asset or replaces its tags.',+ audience: 'ai',+ classification: 'WRITE',+ outputSchema: canvaOutputSchemas.aiAsset,+ aiMetadata: {+ description:+ 'Changes the name and/or tags of an image or video in the Canva library. tags REPLACES all existing tags (send the full list); set clearTags to remove every tag. Omitted fields are left unchanged. Returns the updated asset. Repeating the same update gives the same result.',+ idempotent: true,+ },+ props: {+ assetId: Property.ShortText({ displayName: 'Asset ID', description: 'The Canva asset ID.', required: true }),+ name: Property.ShortText({ displayName: 'Name', description: `New name, max ${MAX_ASSET_NAME_LENGTH} characters. Empty leaves it unchanged.`, required: false }),+ tags: Property.Array({ displayName: 'Tags', description: 'Full replacement list of tags (max 50). Empty leaves tags unchanged.', required: false }),+ clearTags: Property.Checkbox({ displayName: 'Clear Tags', description: 'Remove all tags from the asset.', required: false, defaultValue: false }),+ },+ async run(context) {+ const { assetId, name, tags, clearTags } = context.propsValue;+ const id = assetId.trim();+ if (!id) {+ throw new Error('Asset ID is required.');+ }+ const body: { name?: string; tags?: string[] } = {};+ const trimmedName = name?.trim();+ if (trimmedName) {+ if (trimmedName.length > MAX_ASSET_NAME_LENGTH) {+ throw new Error(`Name must be ${MAX_ASSET_NAME_LENGTH} characters or fewer.`);+ }+ body.name = trimmedName;+ }+ const tagList = (tags ?? []).map((t) => String(t).trim()).filter((t) => t.length > 0);+ if (clearTags === true && tagList.length > 0) {+ throw new Error('Give tags or set Clear Tags, not both.');+ }+ if (clearTags === true) {+ body.tags = [];+ } else if (tagList.length > 0) {+ if (tagList.length > 50) {+ throw new Error('An asset can have at most 50 tags.');+ }+ body.tags = tagList;+ }+ if (body.name === undefined && body.tags === undefined) {+ throw new Error('Nothing to update. Give a name, tags, or set Clear Tags.');+ }+ const response = await canvaClient.request<AssetResponse>({+ token: context.auth.access_token,+ method: HttpMethod.PATCH,+ path: `/assets/${encodeURIComponent(id)}`,+ body,+ });+ return { asset: response.asset };+ },+});diff --git a/packages/pieces/community/canva/src/lib/actions/ai/upload-asset-from-url.ts b/packages/pieces/community/canva/src/lib/actions/ai/upload-asset-from-url.tsnew file mode 100644index 00000000000..a01b2ecbe85--- /dev/null+++ b/packages/pieces/community/canva/src/lib/actions/ai/upload-asset-from-url.ts@@ -0,0 +1,43 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { AI_WAIT_SECONDS, AssetUploadJob, canvaAuth, canvaCommon } from '../../common';+import { canvaClient } from '../../common/client';+import { canvaOutputSchemas } from '../../common/output-schemas';++export const canvaUploadAssetFromUrlAi = createAction({+ auth: canvaAuth,+ name: 'canva_upload_asset_from_url',+ displayName: 'Upload Asset From URL',+ description: 'Uploads an image or video from a public URL to the Canva library.',+ audience: 'ai',+ classification: 'WRITE',+ outputSchema: canvaOutputSchemas.job,+ aiMetadata: {+ description:+ "Adds an image or video from a public URL to the user's Canva library (videos up to 100MB). Starts an upload job and waits up to about 25 seconds. If status is success, asset holds the new asset and its ID. If still in_progress, call canva_get_asset_upload_job with job_id. Fails when Canva reports the upload failed (file_too_big, fetch_failed, import_failed). Each call creates another asset. To turn a document into an editable design use canva_import_design_from_url instead.",+ idempotent: false,+ },+ props: {+ url: Property.ShortText({ displayName: 'URL', description: 'Public http(s) URL of the file (8-2048 characters).', required: true }),+ name: Property.ShortText({ displayName: 'Name', description: 'Asset name, 1-255 characters.', required: true }),+ },+ async run(context) {+ const url = context.propsValue.url.trim();+ const name = context.propsValue.name.trim();+ if (!/^https?:\/\//i.test(url) || url.length < 8 || url.length > 2048) {+ throw new Error('URL must be a public http(s) link of 8-2048 characters.');+ }+ if (!name || name.length > 255) {+ throw new Error('Name must be 1-255 characters.');+ }+ const token = context.auth.access_token;+ const started = await canvaClient.request<{ job: AssetUploadJob }>({+ token,+ method: HttpMethod.POST,+ path: '/url-asset-uploads',+ body: { name, url },+ });+ const job = await canvaCommon.settleJob<AssetUploadJob>({ token, kind: 'url_asset_upload', initial: started.job, timeoutSeconds: AI_WAIT_SECONDS, failOnTimeout: false, statusAction: 'the canva_get_asset_upload_job tool' });+ return canvaCommon.flattenJob({ kind: 'url_asset_upload', job });+ },+});diff --git a/packages/pieces/community/canva/src/lib/actions/create-design.ts b/packages/pieces/community/canva/src/lib/actions/create-design.tsindex b1669ff23f2..b317570f229 100644--- a/packages/pieces/community/canva/src/lib/actions/create-design.ts+++ b/packages/pieces/community/canva/src/lib/actions/create-design.ts@@ -1,179 +1,146 @@import { createAction, Property } from '@activepieces/pieces-framework';-import {- AuthenticationType,- httpClient,- HttpMethod,-} from '@activepieces/pieces-common';-import { canvaAuth } from '../../index';-import { canvaCommon, CanvaDesignCreateRequest, CanvaDesignResponse, fetchUserAssets } from '../common';+import { HttpMethod } from '@activepieces/pieces-common';+import { canvaAuth, canvaProps, CanvaDesignResponse } from '../common';+import { canvaClient } from '../common/client';+import { canvaOutputSchemas } from '../common/output-schemas';export const createDesign = createAction({auth: canvaAuth,name: 'create_design',classification: 'WRITE',displayName: 'Create Design',- description: 'Create a new Canva design using preset design types or custom dimensions. Blank designs are automatically deleted if not edited within 7 days.',- audience: 'both',+ description: 'Create a new Canva design from a preset type or custom size. Blank designs are deleted by Canva if not edited within 7 days.',+ audience: 'human',aiMetadata: {description:- 'Creates a brand-new Canva design, either from a preset type (doc, whiteboard, presentation) or with custom pixel dimensions (40-8000px), optionally titled and seeded with an existing image asset. Pick this to start a fresh design; use Import Design instead when converting an existing file like a PDF or PPTX. Not idempotent: every call creates another design, and untouched blank designs are auto-deleted after 7 days.',+ 'Creates a new Canva design from a preset type or custom pixel size. Human step; agents use canva_create_design. Not idempotent: each run creates another design.',idempotent: false,},+ outputSchema: canvaOutputSchemas.designResult,props: {designTypeOption: Property.StaticDropdown({- displayName: '🎨 Design Type',- description: 'Choose how to create your design - preset templates or custom dimensions',+ displayName: 'Design Type',+ description: 'Choose a preset design type or custom dimensions.',required: true,defaultValue: 'preset',options: {options: [- { label: '📋 Preset Design Type (Document, Whiteboard, Presentation)', value: 'preset' },- { label: '📐 Custom Dimensions (Specify width & height)', value: 'custom' },+ { label: 'Preset (Doc, Whiteboard, Presentation, Email)', value: 'preset' },+ { label: 'Custom size (width and height)', value: 'custom' },],},}),presetName: Property.StaticDropdown({displayName: 'Preset Design Type',- description: '⚠️ Only fill this if you selected "Preset Design Type" above',+ description: 'Used when Design Type is Preset.',required: false,options: {options: [{ label: 'Document (Canva Docs)', value: 'doc' },{ label: 'Whiteboard', value: 'whiteboard' },{ label: 'Presentation', value: 'presentation' },+ { label: 'Email', value: 'email' },],},}),customWidth: Property.Number({displayName: 'Custom Width (pixels)',- description: '⚠️ Only fill this if you selected "Custom Dimensions" above. Min: 40, Max: 8000',+ description: 'Used when Design Type is Custom size. 40-8000. Width x height must not exceed 25,000,000.',required: false,}),customHeight: Property.Number({displayName: 'Custom Height (pixels)',- description: '⚠️ Only fill this if you selected "Custom Dimensions" above. Min: 40, Max: 8000',+ description: 'Used when Design Type is Custom size. 40-8000.',required: false,}),title: Property.ShortText({- displayName: '🏷️ Design Title',- description: 'Optional: Name for your design (1-255 characters). If empty, Canva will auto-generate a title.',+ displayName: 'Design Title',+ description: 'Optional name for the design (1-255 characters). Canva picks one if empty.',required: false,}),- assetId: Property.Dropdown({- displayName: 'Asset',- description: 'Optional: Select an existing image asset to add to the design',+ assetId: canvaProps.assetDropdown({+ displayName: 'Image Asset',+ description: 'Optional image from your Canva library to add to the design.',required: false,- refreshers: [],- auth:canvaAuth,- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Please authenticate with Canva first',- options: [],- };- }-- try {- const assets = await fetchUserAssets(auth, 'image');- return {- disabled: false,- options: assets,- };- } catch (error) {- console.error('Error fetching assets:', error);- return {- disabled: true,- placeholder: 'Error loading assets',- options: [],- };- }- },}),},async run(context) {const { designTypeOption, presetName, customWidth, customHeight, title, assetId } = context.propsValue;-- if (designTypeOption === 'preset' && !presetName) {- throw new Error('Preset design type is required when using preset option');- }-- if (designTypeOption === 'custom') {- if (!customWidth || !customHeight) {- throw new Error('Both custom width and height are required when using custom dimensions');- }- if (customWidth < 40 || customWidth > 8000) {- throw new Error('Custom width must be between 40 and 8000 pixels');- }- if (customHeight < 40 || customHeight > 8000) {- throw new Error('Custom height must be between 40 and 8000 pixels');- }+ const body = buildCreateDesignBody({+ designType: designTypeOption,+ presetName: presetName ?? undefined,+ width: customWidth ?? undefined,+ height: customHeight ?? undefined,+ title: title ?? undefined,+ assetId: assetId ?? undefined,+ });+ const response = await canvaClient.request<CanvaDesignResponse>({+ token: context.auth.access_token,+ method: HttpMethod.POST,+ path: '/designs',+ body,+ });+ return {+ success: true,+ design: response.design,+ message: `Design "${response.design.title || response.design.id}" created successfully`,+ };+ },+});++function buildCreateDesignBody({+ designType,+ presetName,+ width,+ height,+ title,+ assetId,+}: {+ designType: string;+ presetName?: string;+ width?: number;+ height?: number;+ title?: string;+ assetId?: string;+}): Record<string, unknown> {+ const body: Record<string, unknown> = { type: 'type_and_asset' };+ if (designType === 'preset') {+ if (!presetName) {+ throw new Error('Pick a Preset Design Type, or switch Design Type to Custom size.');}-- if (title && (title.length < 1 || title.length > 255)) {- throw new Error('Title must be between 1 and 255 characters');+ body['design_type'] = { type: 'preset', name: presetName };+ } else if (designType === 'custom') {+ if (width === undefined || height === undefined) {+ throw new Error('Both custom width and height are required for a custom size.');}-- const requestBody: CanvaDesignCreateRequest = {};-- if (designTypeOption === 'preset') {- requestBody.design_type = {- type: 'preset',- name: presetName as 'doc' | 'whiteboard' | 'presentation',- };- } else if (designTypeOption === 'custom') {- requestBody.design_type = {- type: 'custom',- width: customWidth!,- height: customHeight!,- };+ const dimensions: Array<{ label: string; value: number }> = [+ { label: 'width', value: width },+ { label: 'height', value: height },+ ];+ for (const { label, value } of dimensions) {+ if (!Number.isInteger(value) || value < 40 || value > 8000) {+ throw new Error(`Custom ${label} must be a whole number between 40 and 8000 pixels.`);+ }}-- if (title) {- requestBody.title = title;+ if (width * height > 25_000_000) {+ throw new Error('Custom width x height must not exceed 25,000,000 pixels.');}-- if (assetId) {- requestBody.asset_id = assetId;+ body['design_type'] = { type: 'custom', width, height };+ } else if (!assetId) {+ throw new Error('Choose a design type or an image asset.');+ }+ const trimmedTitle = title?.trim();+ if (trimmedTitle) {+ if (trimmedTitle.length > 255) {+ throw new Error('Title must be 255 characters or fewer.');}+ body['title'] = trimmedTitle;+ }+ const trimmedAsset = assetId?.trim();+ if (trimmedAsset) {+ body['asset_id'] = trimmedAsset;+ }+ return body;+}- try {- const response = await httpClient.sendRequest<CanvaDesignResponse>({- method: HttpMethod.POST,- url: `${canvaCommon.baseUrl}/designs`,- headers: {- 'Content-Type': 'application/json',- },- authentication: {- type: AuthenticationType.BEARER_TOKEN,- token: context.auth.access_token,- },- body: requestBody,- });-- return {- success: true,- design: response.body.design,- message: `Design "${response.body.design.title || response.body.design.id}" created successfully`,- };- } catch (error: any) {- if (error.response?.status === 429) {- throw new Error('Rate limit exceeded. Please wait before making another request (20 requests per minute limit).');- }-- if (error.response?.status === 401) {- throw new Error('Authentication failed. Please check your Canva connection.');- }-- if (error.response?.status === 403) {- throw new Error('Access forbidden. Make sure your integration has the required scope: design:content:write');- }-- if (error.response?.data?.message) {- throw new Error(`Canva API error: ${error.response.data.message}`);- }-- throw new Error(`Failed to create design: ${error.message || 'Unknown error'}`);- }- },-});\ No newline at end of file+export const createDesignBody = buildCreateDesignBody;diff --git a/packages/pieces/community/canva/src/lib/actions/create-folder.ts b/packages/pieces/community/canva/src/lib/actions/create-folder.tsnew file mode 100644index 00000000000..89530c8acbc--- /dev/null+++ b/packages/pieces/community/canva/src/lib/actions/create-folder.ts@@ -0,0 +1,54 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { canvaAuth, canvaProps, FolderResponse } from '../common';+import { canvaClient } from '../common/client';+import { canvaOutputSchemas } from '../common/output-schemas';++export const createFolder = createAction({+ auth: canvaAuth,+ name: 'create_folder',+ classification: 'WRITE',+ displayName: 'Create Folder',+ description: 'Create a folder in your Canva projects, in Uploads, or inside another folder.',+ audience: 'human',+ aiMetadata: {+ description: 'Creates a Canva folder. Human step; agents use canva_create_folder. Not idempotent: each run creates another folder, even with the same name.',+ idempotent: false,+ },+ outputSchema: canvaOutputSchemas.folderResult,+ props: {+ name: Property.ShortText({+ displayName: 'Folder Name',+ description: 'Name of the new folder (1-255 characters).',+ required: true,+ }),+ parentFolderId: canvaProps.folderDropdown({ displayName: 'Parent Folder', description: 'Where to create the folder.' }),+ },+ async run(context) {+ return createFolderRequest({+ token: context.auth.access_token,+ name: context.propsValue.name,+ parentFolderId: context.propsValue.parentFolderId,+ });+ },+});++async function create({ token, name, parentFolderId }: { token: string; name: string; parentFolderId: string }) {+ const trimmedName = name.trim();+ const parent = parentFolderId.trim();+ if (!trimmedName || trimmedName.length > 255) {+ throw new Error('Folder name must be 1-255 characters.');+ }+ if (!parent || parent.length > 50) {+ throw new Error('Parent folder ID must be 1-50 characters. Use "root" for the top level or "uploads" for Uploads.');+ }+ const body = await canvaClient.request<FolderResponse>({+ token,+ method: HttpMethod.POST,+ path: '/folders',+ body: { name: trimmedName, parent_folder_id: parent },+ });+ return { folder: body.folder };+}++export const createFolderRequest = create;diff --git a/packages/pieces/community/canva/src/lib/actions/export-design.ts b/packages/pieces/community/canva/src/lib/actions/export-design.tsindex 654b228028a..80b4844c1ee 100644--- a/packages/pieces/community/canva/src/lib/actions/export-design.ts+++ b/packages/pieces/community/canva/src/lib/actions/export-design.ts@@ -1,286 +1,238 @@import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';import {- AuthenticationType,- httpClient,- HttpMethod,-} from '@activepieces/pieces-common';-import { canvaAuth } from '../../index';-import {- canvaCommon,- ExportResponse,- ExportRequest,- ExportFormat,+ canvaAuth,+ canvaCommon,+ canvaProps,EXPORT_FORMATS,- PDF_SIZES,- MP4_QUALITIES,- MIN_EXPORT_DIMENSION,+ ExportFormat,+ ExportJob,MAX_EXPORT_DIMENSION,- fetchUserDesigns+ MIN_EXPORT_DIMENSION,+ MP4_QUALITIES,+ PDF_SIZES,} from '../common';+import { canvaClient } from '../common/client';+import { canvaOutputSchemas } from '../common/output-schemas';export const exportDesign = createAction({auth: canvaAuth,name: 'export_design',classification: 'READ',displayName: 'Export Design',- description: 'Export a Canva design to various formats (PDF, JPG, PNG, GIF, PPTX, MP4). This creates an asynchronous job with download URLs valid for 24 hours.',- audience: 'both',+ description: 'Export a design as PDF, JPG, PNG, GIF, PPTX or MP4 and wait for the download links (valid for 24 hours).',+ audience: 'human',aiMetadata: {- description:- 'Starts an asynchronous export job that renders an existing Canva design as PDF, JPG, PNG, GIF, PPTX, or MP4, with format-specific options (quality, page selection, custom image dimensions, PDF paper size). Pick this when you need downloadable output files from a design; download URLs expire after 24 hours and the job may need to be polled for completion. Not idempotent: each call queues a new export job.',+ description: 'Exports a Canva design to files. Human step; agents use canva_export_design. Not idempotent: each run starts a new export job.',idempotent: false,},+ outputSchema: canvaOutputSchemas.exportDesign,props: {- designId: Property.Dropdown({- displayName: 'Design',- description: 'Select the design to export',- required: true,- auth:canvaAuth,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Please authenticate with Canva first',- options: [],- };- }-- try {- const designs = await fetchUserDesigns(auth);- return {- disabled: false,- options: designs,- };- } catch (error) {- console.error('Error fetching designs:', error);- return {- disabled: true,- placeholder: 'Error loading designs',- options: [],- };- }- },- }),+ designId: canvaProps.designDropdown({ displayName: 'Design', description: 'The design to export. Type to search.' }),exportFormat: Property.StaticDropdown({displayName: 'Export Format',- description: 'The format to export the design to',+ description: 'The file format to export to.',required: true,- options: {- options: EXPORT_FORMATS,- },+ options: { options: EXPORT_FORMATS },}),exportQuality: Property.StaticDropdown({displayName: 'Export Quality',- description: 'Export quality level (Pro quality may require premium elements license)',+ description: 'Pro quality can fail if the design has premium elements you have not licensed.',required: false,defaultValue: 'regular',options: {options: [- { label: 'Regular Quality', value: 'regular' },- { label: 'Pro Quality (Premium)', value: 'pro' },+ { label: 'Regular', value: 'regular' },+ { label: 'Pro', value: 'pro' },],},}),pages: Property.Array({displayName: 'Specific Pages',- description: 'Page numbers to export (leave empty to export all pages). First page is 1.',+ description: 'Page numbers to export (first page is 1). Leave empty for all pages.',required: false,}),jpegQuality: Property.Number({- displayName: '📸 JPEG Quality',- description: '🎯 JPEG ONLY: Compression quality (1-100, higher = better quality, larger file)',+ displayName: 'JPEG Quality',+ description: 'JPG only: compression quality from 1 to 100 (default 80).',required: false,defaultValue: 80,}),pdfSize: Property.StaticDropdown({- displayName: '📄 PDF Paper Size',- description: '🎯 PDF ONLY: Paper size for PDF export (only for Canva Docs)',+ displayName: 'PDF Paper Size',+ description: 'PDF only, Canva Docs only.',required: false,defaultValue: 'a4',- options: {- options: PDF_SIZES,- },+ options: { options: PDF_SIZES },}),mp4Quality: Property.StaticDropdown({- displayName: '🎬 MP4 Quality',- description: '🎯 MP4 ONLY: Video orientation and resolution for MP4 export',+ displayName: 'MP4 Quality',+ description: 'MP4 only: orientation and resolution.',required: false,defaultValue: 'horizontal_1080p',- options: {- options: MP4_QUALITIES,- },+ options: { options: MP4_QUALITIES },}),customWidth: Property.Number({- displayName: '📐 Custom Width (pixels)',- description: `🎯 IMAGES ONLY (JPG/PNG/GIF): Custom width (${MIN_EXPORT_DIMENSION}-${MAX_EXPORT_DIMENSION}px). Leave empty for original size.`,+ displayName: 'Custom Width (pixels)',+ description: `JPG, PNG and GIF only (${MIN_EXPORT_DIMENSION}-${MAX_EXPORT_DIMENSION}). Leave empty for the design size.`,required: false,}),customHeight: Property.Number({- displayName: '📐 Custom Height (pixels)',- description: `🎯 IMAGES ONLY (JPG/PNG/GIF): Custom height (${MIN_EXPORT_DIMENSION}-${MAX_EXPORT_DIMENSION}px). Leave empty for original size.`,+ displayName: 'Custom Height (pixels)',+ description: `JPG, PNG and GIF only (${MIN_EXPORT_DIMENSION}-${MAX_EXPORT_DIMENSION}). Leave empty for the design size.`,required: false,}),pngLossless: Property.Checkbox({- displayName: '🔧 PNG Lossless Compression',- description: '🎯 PNG ONLY: Export PNG without compression (default: true). Lossy compression requires Pro plan.',+ displayName: 'PNG Lossless',+ description: 'PNG only: export without compression. Lossy PNG needs a Canva Pro plan.',required: false,defaultValue: true,}),pngTransparentBackground: Property.Checkbox({- displayName: '🫥 PNG Transparent Background',- description: '🎯 PNG ONLY: Export PNG with transparent background (Pro feature)',+ displayName: 'PNG Transparent Background',+ description: 'PNG only: transparent background (Canva Pro feature).',required: false,defaultValue: false,}),pngSingleImage: Property.Checkbox({- displayName: '📑 PNG Merge Multi-page',- description: '🎯 PNG ONLY: Merge multi-page designs into a single image (default: separate images per page)',+ displayName: 'PNG Merge Pages',+ description: 'PNG only: merge a multi-page design into one image.',required: false,defaultValue: false,}),+ ...canvaProps.waitProps(),},async run(context) {- const {- designId,- exportFormat,- exportQuality,- pages,- jpegQuality,- pdfSize,- mp4Quality,- customWidth,- customHeight,- pngLossless,- pngTransparentBackground,- pngSingleImage- } = context.propsValue;-- if (!designId || designId.trim().length === 0) {- throw new Error('Design ID is required');- }-- if (customWidth && (customWidth < MIN_EXPORT_DIMENSION || customWidth > MAX_EXPORT_DIMENSION)) {- throw new Error(`Custom width must be between ${MIN_EXPORT_DIMENSION} and ${MAX_EXPORT_DIMENSION} pixels`);- }-- if (customHeight && (customHeight < MIN_EXPORT_DIMENSION || customHeight > MAX_EXPORT_DIMENSION)) {- throw new Error(`Custom height must be between ${MIN_EXPORT_DIMENSION} and ${MAX_EXPORT_DIMENSION} pixels`);+ const p = context.propsValue;+ const designId = p.designId.trim();+ if (!designId) {+ throw new Error('Design is required.');}-- if (exportFormat === 'jpg' && (!jpegQuality || jpegQuality < 1 || jpegQuality > 100)) {- throw new Error('JPEG quality must be between 1 and 100');- }-- if (exportFormat === 'mp4' && !mp4Quality) {- throw new Error('MP4 quality is required when exporting as MP4');- }-- const format: ExportFormat = {- type: exportFormat as 'pdf' | 'jpg' | 'png' | 'gif' | 'pptx' | 'mp4',+ const format = buildExportFormat({+ type: p.exportFormat,+ exportQuality: p.exportQuality ?? undefined,+ pages: canvaCommon.parsePageNumbers(p.pages ?? undefined),+ jpegQuality: p.jpegQuality ?? undefined,+ pdfSize: p.pdfSize ?? undefined,+ mp4Quality: p.mp4Quality ?? undefined,+ width: p.customWidth ?? undefined,+ height: p.customHeight ?? undefined,+ pngLossless: p.pngLossless ?? undefined,+ pngTransparentBackground: p.pngTransparentBackground ?? undefined,+ pngSingleImage: p.pngSingleImage ?? undefined,+ });+ const token = context.auth.access_token;+ const started = await canvaClient.request<{ job: ExportJob }>({+ token,+ method: HttpMethod.POST,+ path: '/exports',+ body: { design_id: designId, format },+ });+ const job = p.waitForCompletion === false+ ? started.job+ : await canvaCommon.settleJob<ExportJob>({+ token,+ kind: 'export',+ initial: started.job,+ timeoutSeconds: canvaCommon.clampWaitSeconds(p.maxWaitSeconds ?? undefined),+ failOnTimeout: true,+ });+ const urls = job.urls ?? [];+ return {+ success: job.status !== 'failed',+ job,+ download_urls: urls,+ export_info: {+ design_id: designId,+ format: format.type.toUpperCase(),+ quality: format.export_quality ?? 'regular',+ pages: format.pages ? `Pages: ${format.pages.join(', ')}` : 'All pages',+ dimensions: format.width || format.height ? `${format.width ?? 'auto'}x${format.height ?? 'auto'} pixels` : 'Original size',+ },+ message: job.status === 'success'+ ? `Export finished: ${urls.length} file(s) ready (links valid for 24 hours).`+ : `Export job ${job.id} is ${job.status}. Check it later with Get Job Status.`,};-- if (exportQuality) {- format.export_quality = exportQuality as 'regular' | 'pro';+ },+});++function checkDimension({ label, value }: { label: string; value: number | undefined }): number | undefined {+ if (value === undefined) {+ return undefined;+ }+ if (!Number.isInteger(value) || value < MIN_EXPORT_DIMENSION || value > MAX_EXPORT_DIMENSION) {+ throw new Error(`Custom ${label} must be a whole number between ${MIN_EXPORT_DIMENSION} and ${MAX_EXPORT_DIMENSION} pixels.`);+ }+ return value;+}++function buildExportFormat({+ type,+ exportQuality,+ pages,+ jpegQuality,+ pdfSize,+ mp4Quality,+ width,+ height,+ pngLossless,+ pngTransparentBackground,+ pngSingleImage,+}: {+ type: string;+ exportQuality?: string;+ pages?: number[];+ jpegQuality?: number;+ pdfSize?: string;+ mp4Quality?: string;+ width?: number;+ height?: number;+ pngLossless?: boolean;+ pngTransparentBackground?: boolean;+ pngSingleImage?: boolean;+}): ExportFormat {+ if (!EXPORT_FORMATS.some((f) => f.value === type)) {+ throw new Error(`Unsupported export format "${type}". Use one of: ${EXPORT_FORMATS.map((f) => f.value).join(', ')}.`);+ }+ if (exportQuality !== undefined && exportQuality !== 'regular' && exportQuality !== 'pro') {+ throw new Error('Export quality must be "regular" or "pro".');+ }+ const format: ExportFormat = { type };+ if (exportQuality) format.export_quality = exportQuality;+ if (pages && pages.length > 0) format.pages = pages;+ const isImage = type === 'jpg' || type === 'png' || type === 'gif';+ if (isImage) {+ const w = checkDimension({ label: 'width', value: width });+ const h = checkDimension({ label: 'height', value: height });+ if (w !== undefined) format.width = w;+ if (h !== undefined) format.height = h;+ }+ if (type === 'jpg') {+ const quality = jpegQuality ?? 80;+ if (!Number.isInteger(quality) || quality < 1 || quality > 100) {+ throw new Error('JPEG quality must be a whole number between 1 and 100.');}-- if (pages && Array.isArray(pages) && pages.length > 0) {- format.pages = pages.map(p => Number(p)).filter(p => p > 0);+ format.quality = quality;+ }+ if (type === 'png') {+ if (pngLossless !== undefined) format.lossless = pngLossless;+ if (pngTransparentBackground !== undefined) format.transparent_background = pngTransparentBackground;+ if (pngSingleImage !== undefined) format.as_single_image = pngSingleImage;+ }+ if (type === 'pdf' && pdfSize) {+ if (!PDF_SIZES.some((s) => s.value === pdfSize)) {+ throw new Error(`PDF size must be one of: ${PDF_SIZES.map((s) => s.value).join(', ')}.`);}-- switch (exportFormat) {- case 'jpg':- if (jpegQuality) format.quality = jpegQuality;- if (customWidth) format.width = customWidth;- if (customHeight) format.height = customHeight;- break;-- case 'png':- if (customWidth) format.width = customWidth;- if (customHeight) format.height = customHeight;- if (typeof pngLossless === 'boolean') format.lossless = pngLossless;- if (typeof pngTransparentBackground === 'boolean') format.transparent_background = pngTransparentBackground;- if (typeof pngSingleImage === 'boolean') format.as_single_image = pngSingleImage;- break;-- case 'gif':- if (customWidth) format.width = customWidth;- if (customHeight) format.height = customHeight;- break;-- case 'pdf':- if (pdfSize) format.size = pdfSize as 'a4' | 'a3' | 'letter' | 'legal';- break;-- case 'mp4':- if (mp4Quality) format.quality = mp4Quality;- break;-- case 'pptx':- break;+ format.size = pdfSize;+ }+ if (type === 'mp4') {+ const quality = mp4Quality ?? 'horizontal_1080p';+ if (!MP4_QUALITIES.some((q) => q.value === quality)) {+ throw new Error(`MP4 quality must be one of: ${MP4_QUALITIES.map((q) => q.value).join(', ')}.`);}-- const requestBody: ExportRequest = {- design_id: designId.trim(),- format,- };+ format.quality = quality;+ }+ return format;+}- try {- const response = await httpClient.sendRequest<ExportResponse>({- method: HttpMethod.POST,- url: `${canvaCommon.baseUrl}/exports`,- headers: {- 'Content-Type': 'application/json',- },- authentication: {- type: AuthenticationType.BEARER_TOKEN,- token: context.auth.access_token,- },- body: requestBody,- });-- return {- success: true,- job: response.body.job,- export_info: {- design_id: designId.trim(),- format: exportFormat.toUpperCase(),- quality: exportQuality || 'regular',- pages: format.pages ? `Pages: ${format.pages.join(', ')}` : 'All pages',- dimensions: customWidth || customHeight- ? `${customWidth || 'auto'}x${customHeight || 'auto'} pixels`- : 'Original size',- },- message: `Export job created successfully. Job ID: ${response.body.job.id}. Status: ${response.body.job.status}`,- next_steps: response.body.job.status === 'in_progress'- ? 'Use the "Get Design Export Job" action to check the status and get download URLs (valid for 24 hours).'- : response.body.job.status === 'success' && response.body.job.urls- ? `Export completed! ${response.body.job.urls.length} file(s) ready for download.`- : undefined,- download_urls: response.body.job.urls || undefined,- };- } catch (error: any) {- if (error.response?.status === 429) {- throw new Error('Rate limit exceeded. Please wait before making another request (20 requests per minute limit).');- }-- if (error.response?.status === 401) {- throw new Error('Authentication failed. Please check your Canva connection.');- }-- if (error.response?.status === 403) {- throw new Error('Access forbidden. Make sure your integration has the required scope: design:content:read');- }-- if (error.response?.status === 404) {- throw new Error(`Design with ID "${designId}" was not found or you don't have access to it.`);- }-- if (error.response?.data?.message) {- throw new Error(`Canva API error: ${error.response.data.message}`);- }-- throw new Error(`Failed to export design: ${error.message || 'Unknown error'}`);- }- },-});\ No newline at end of file+export const exportFormatBuilder = buildExportFormat;diff --git a/packages/pieces/community/canva/src/lib/actions/find-design.ts b/packages/pieces/community/canva/src/lib/actions/find-design.tsindex 4a24c8c75d3..c44a0da6bf3 100644--- a/packages/pieces/community/canva/src/lib/actions/find-design.ts+++ b/packages/pieces/community/canva/src/lib/actions/find-design.ts@@ -1,152 +1,127 @@-import {- Property,- createAction,- OAuth2PropertyValue,-} from '@activepieces/pieces-framework';-import { canvaAuth } from '../../index';-import { canvaCommon, Design } from '../common';--interface ListDesignsResponse {- items: Design[];- continuation?: string;-}+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { canvaAuth, ListDesignsResponse } from '../common';+import { canvaClient } from '../common/client';+import { canvaOutputSchemas } from '../common/output-schemas';export const findDesign = createAction({auth: canvaAuth,name: 'find_design',classification: 'SEARCH',displayName: 'Find Design',- description: 'Search and list designs from your Canva library. Use this to find existing designs before creating new ones.',- audience: 'both',+ description: 'Search your Canva designs by keyword, or list them all. Returns one page; use the continuation token for the next page.',+ audience: 'human',aiMetadata: {- description:- "Searches the user's Canva design library by keyword, with ownership (owned/shared) and sort filters plus continuation-token pagination; an empty query lists all designs. Pick this to discover or look up design IDs before getting, exporting, or moving a design, rather than creating a duplicate. Read-only and idempotent.",+ description: 'Searches Canva designs. Human step; agents use canva_list_designs. Read-only.',idempotent: true,},+ outputSchema: canvaOutputSchemas.findDesign,props: {query: Property.ShortText({- displayName: '🔍 Search Query',- description: 'Enter keywords to search designs by title or content (leave empty to get all designs)',+ displayName: 'Search Query',+ description: 'Keywords to search designs by. Leave empty to list all designs.',required: false,}),ownership: Property.StaticDropdown({- displayName: '👥 Ownership Filter',- description: 'Filter designs by who owns them',+ displayName: 'Ownership',+ description: 'Which designs to include.',required: false,defaultValue: 'any',options: {options: [- { label: 'Any (owned + shared)', value: 'any' },+ { label: 'Any (owned and shared)', value: 'any' },{ label: 'Owned by me', value: 'owned' },{ label: 'Shared with me', value: 'shared' },],},}),sort_by: Property.StaticDropdown({- displayName: '📊 Sort By',- description: 'How to order the search results',+ displayName: 'Sort By',+ description: 'How to order the results.',required: false,defaultValue: 'modified_descending',options: {options: [- { label: '📅 Recently Modified (Recommended)', value: 'modified_descending' },- { label: '🔍 Relevance', value: 'relevance' },- { label: '📅 Oldest Modified', value: 'modified_ascending' },- { label: '🔤 Title A-Z', value: 'title_ascending' },- { label: '🔤 Title Z-A', value: 'title_descending' },+ { label: 'Recently modified', value: 'modified_descending' },+ { label: 'Relevance', value: 'relevance' },+ { label: 'Oldest modified', value: 'modified_ascending' },+ { label: 'Title A-Z', value: 'title_ascending' },+ { label: 'Title Z-A', value: 'title_descending' },],},}),limit: Property.Number({- displayName: '⚙️ Result Limit (Advanced)',- description: 'Max designs to return (default: 20, max: 100). Higher numbers may be slower.',+ displayName: 'Result Limit',+ description: 'How many designs to return (1-100, default 20).',required: false,defaultValue: 20,}),continuation: Property.ShortText({- displayName: '⚙️ Continuation Token (Advanced)',- description: 'For pagination: token from previous search to get next page of results',+ displayName: 'Continuation Token',+ description: 'Token from a previous run to get the next page.',required: false,}),},async run(context) {const { query, ownership, sort_by, limit, continuation } = context.propsValue;- const authValue = context.auth as OAuth2PropertyValue;-- try {- const params = new URLSearchParams();-- if (query && query.trim()) {- params.append('query', query.trim());- }-- if (ownership && ownership !== 'any') {- params.append('ownership', ownership);- }-- if (sort_by && sort_by !== 'relevance') {- params.append('sort_by', sort_by);- }-- if (continuation && continuation.trim()) {- params.append('continuation', continuation.trim());- }-- const queryString = params.toString();- const url = `${canvaCommon.baseUrl}/designs${queryString ? `?${queryString}` : ''}`;-- const response = await fetch(url, {- method: 'GET',- headers: {- 'Authorization': `Bearer ${authValue.access_token}`,- },- });-- if (!response.ok) {- const errorData = await response.json().catch(() => ({}));-- if (response.status === 400) {- throw new Error(`Bad Request: ${errorData.message || 'Invalid search parameters'}`);- }-- if (response.status === 401) {- throw new Error('Unauthorized: Please check your authentication credentials');- }-- if (response.status === 403) {- throw new Error('Forbidden: Insufficient permissions to access designs');- }-- if (response.status === 429) {- throw new Error('Rate limit exceeded: Too many requests (limit: 100 per minute)');- }-- throw new Error(`HTTP ${response.status}: ${errorData.message || 'Request failed'}`);- }-- const data: ListDesignsResponse = await response.json();-- let designs = data.items || [];- if (limit && limit > 0) {- designs = designs.slice(0, Math.min(limit, 100));- }+ const page = await listDesigns({+ token: context.auth.access_token,+ query: query ?? undefined,+ ownership: ownership ?? undefined,+ sortBy: sort_by ?? undefined,+ limit: limit ?? 20,+ continuation: continuation ?? undefined,+ });+ const designs = page.items;+ return {+ designs,+ total_found: designs.length,+ has_more: Boolean(page.continuation),+ continuation_token: page.continuation ?? null,+ search_query: query || null,+ ownership_filter: ownership || 'any',+ sort_order: sort_by || 'relevance',+ design_ids: designs.map((d) => d.id),+ design_titles: designs.map((d) => d.title).filter(Boolean),+ };+ },+});- return {- designs,- total_found: designs.length,- has_more: !!data.continuation,- continuation_token: data.continuation,- search_query: query || null,- ownership_filter: ownership || 'any',- sort_order: sort_by || 'relevance',- design_ids: designs.map(d => d.id),- design_titles: designs.map(d => d.title).filter(Boolean),- };- } catch (error) {- if (error instanceof Error) {- throw error;- }- throw new Error(`Failed to find designs: ${String(error)}`);+async function listDesigns({+ token,+ query,+ ownership,+ sortBy,+ limit,+ continuation,+}: {+ token: string;+ query?: string;+ ownership?: string;+ sortBy?: string;+ limit?: number;+ continuation?: string;+}): Promise<{ items: ListDesignsResponse['items']; continuation?: string }> {+ const queryParams: Record<string, string> = {};+ const term = query?.trim();+ if (term) {+ if (term.length > 255) {+ throw new Error('Search query must be 255 characters or fewer.');}- },-});\ No newline at end of file+ queryParams['query'] = term;+ }+ if (ownership && ownership !== 'any') queryParams['ownership'] = ownership;+ if (sortBy) queryParams['sort_by'] = sortBy;+ if (limit !== undefined) {+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) {+ throw new Error('Result limit must be a whole number between 1 and 100.');+ }+ queryParams['limit'] = String(limit);+ }+ const cursor = continuation?.trim();+ if (cursor) queryParams['continuation'] = cursor;+ const body = await canvaClient.request<ListDesignsResponse>({ token, method: HttpMethod.GET, path: '/designs', queryParams });+ return { items: body?.items ?? [], continuation: body?.continuation };+}++export const listDesignsRequest = listDesigns;diff --git a/packages/pieces/community/canva/src/lib/actions/get-asset.ts b/packages/pieces/community/canva/src/lib/actions/get-asset.tsindex 037078efae9..285a7125524 100644--- a/packages/pieces/community/canva/src/lib/actions/get-asset.ts+++ b/packages/pieces/community/canva/src/lib/actions/get-asset.ts@@ -1,135 +1,59 @@-import {- Property,- createAction,- OAuth2PropertyValue,-} from '@activepieces/pieces-framework';-import { canvaAuth } from '../../index';-import { canvaCommon, AssetResponse, fetchUserAssets } from '../common';+import { createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { AssetResponse, canvaAuth, canvaProps } from '../common';+import { canvaClient } from '../common/client';+import { canvaOutputSchemas } from '../common/output-schemas';export const getAsset = createAction({auth: canvaAuth,name: 'get_asset',classification: 'READ',displayName: 'Get Asset',- description: 'Retrieve metadata for a specific asset (image or video), including name, tags, creation date, and thumbnail.',- audience: 'both',+ description: 'Get the details of an image or video in your Canva library, including name, tags, dates and thumbnail.',+ audience: 'human',aiMetadata: {- description:- 'Fetches metadata for a single Canva library asset (image or video) by asset ID, including name, tags, timestamps, thumbnail, and import status. Pick this when you already have an asset ID and need its details or to confirm an upload finished importing; it is about library assets, not designs (use Get Design for those). Read-only and idempotent.',+ description: 'Gets one Canva library asset by ID. Human step; agents use canva_get_asset. Read-only.',idempotent: true,},+ outputSchema: canvaOutputSchemas.getAsset,props: {- asset_id: Property.Dropdown({- displayName: 'Asset',- description: 'Select the asset to retrieve metadata for',- required: true,- auth:canvaAuth,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Please authenticate with Canva first',- options: [],- };- }-- try {- const assets = await fetchUserAssets(auth);- return {- disabled: false,- options: assets,- };- } catch (error) {- console.error('Error fetching assets:', error);- return {- disabled: true,- placeholder: 'Error loading assets',- options: [],- };- }- },- }),+ asset_id: canvaProps.assetDropdown({ displayName: 'Asset', description: 'The asset to look up.', required: true }),},async run(context) {- const { asset_id } = context.propsValue;- const authValue = context.auth as OAuth2PropertyValue;-- if (!asset_id || !asset_id.trim()) {- throw new Error('Asset ID is required');- }-- const cleanAssetId = asset_id.trim();-- try {- const response = await fetch(`${canvaCommon.baseUrl}/assets/${cleanAssetId}`, {- method: 'GET',- headers: {- 'Authorization': `Bearer ${authValue.access_token}`,- },- });-- if (!response.ok) {- const errorData = await response.json().catch(() => ({}));-- if (response.status === 400) {- throw new Error(`Bad Request: ${errorData.message || 'Invalid asset ID format'}`);- }-- if (response.status === 401) {- throw new Error('Unauthorized: Please check your authentication credentials');- }-- if (response.status === 403) {- throw new Error('Forbidden: You do not have permission to access this asset');- }-- if (response.status === 404) {- throw new Error(`Asset not found: The asset with ID "${cleanAssetId}" does not exist or you do not have access to it`);- }-- if (response.status === 429) {- throw new Error('Rate limit exceeded: Too many requests (limit: 100 per minute)');- }-- throw new Error(`HTTP ${response.status}: ${errorData.message || 'Request failed'}`);- }-- const data: AssetResponse = await response.json();- const asset = data.asset;-- return {- asset: {- type: asset.type,- id: asset.id,- name: asset.name,- tags: asset.tags,- created_at: asset.created_at,- updated_at: asset.updated_at,- thumbnail: asset.thumbnail || null,- import_status: asset.import_status || null,- },- asset_id: asset.id,- asset_name: asset.name,- asset_type: asset.type,- tags_count: asset.tags.length,- tags_list: asset.tags.join(', '),- created_date: new Date(asset.created_at * 1000).toISOString(),- updated_date: new Date(asset.updated_at * 1000).toISOString(),- has_thumbnail: !!asset.thumbnail,- thumbnail_url: asset.thumbnail?.url || null,- thumbnail_dimensions: asset.thumbnail- ? `${asset.thumbnail.width}x${asset.thumbnail.height}`- : null,- is_imported_successfully: !asset.import_status || asset.import_status.state === 'success',- import_status_state: asset.import_status?.state || 'success',- import_error_message: asset.import_status?.error?.message || null,- };- } catch (error) {- if (error instanceof Error) {- throw error;- }- throw new Error(`Failed to get asset: ${String(error)}`);+ const assetId = (context.propsValue.asset_id ?? '').trim();+ if (!assetId) {+ throw new Error('Asset is required.');}+ const { asset } = await canvaClient.request<AssetResponse>({+ token: context.auth.access_token,+ method: HttpMethod.GET,+ path: `/assets/${encodeURIComponent(assetId)}`,+ });+ const tags = asset.tags ?? [];+ return {+ asset: {+ type: asset.type,+ id: asset.id,+ name: asset.name,+ tags,+ created_at: asset.created_at,+ updated_at: asset.updated_at,+ thumbnail: asset.thumbnail ?? null,+ import_status: asset.import_status ?? null,+ },+ asset_id: asset.id,+ asset_name: asset.name,+ asset_type: asset.type,+ tags_count: tags.length,+ tags_list: tags.join(', '),+ created_date: new Date(asset.created_at * 1000).toISOString(),+ updated_date: new Date(asset.updated_at * 1000).toISOString(),+ has_thumbnail: Boolean(asset.thumbnail),+ thumbnail_url: asset.thumbnail?.url ?? null,+ thumbnail_dimensions: asset.thumbnail ? `${asset.thumbnail.width}x${asset.thumbnail.height}` : null,+ is_imported_successfully: !asset.import_status || asset.import_status.state === 'success',+ import_status_state: asset.import_status?.state ?? 'success',+ import_error_message: asset.import_status?.error?.message ?? null,+ };},-});\ No newline at end of file+});diff --git a/packages/pieces/community/canva/src/lib/actions/get-design.ts b/packages/pieces/community/canva/src/lib/actions/get-design.tsindex a96052b0cf0..7fd93f459cf 100644--- a/packages/pieces/community/canva/src/lib/actions/get-design.ts+++ b/packages/pieces/community/canva/src/lib/actions/get-design.ts@@ -1,101 +1,38 @@-import { createAction, Property } from '@activepieces/pieces-framework';-import {- AuthenticationType,- httpClient,- HttpMethod,-} from '@activepieces/pieces-common';-import { canvaAuth } from '../../index';-import { canvaCommon, CanvaDesignResponse, fetchUserDesigns } from '../common';+import { createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { canvaAuth, canvaProps, CanvaDesignResponse } from '../common';+import { canvaClient } from '../common/client';+import { canvaOutputSchemas } from '../common/output-schemas';export const getDesign = createAction({auth: canvaAuth,name: 'get_design',classification: 'READ',displayName: 'Get Design',- description: 'Get the metadata for one of your designs, including owner information, URLs for editing and viewing, and thumbnail information.',- audience: 'both',+ description: 'Get the details of a design, including owner, edit and view links, and thumbnail.',+ audience: 'human',aiMetadata: {- description:- 'Fetches metadata for a single Canva design by design ID, including owner, edit/view URLs, and thumbnail. Pick this when you already know the design ID; use Find Design first if you only have a title or keywords. Read-only and idempotent; fails with 404 if the design does not exist or is inaccessible.',+ description: 'Gets one Canva design by ID. Human step; agents use canva_get_design. Read-only.',idempotent: true,},+ outputSchema: canvaOutputSchemas.designResult,props: {- designId: Property.Dropdown({- displayName: 'Design',- description: 'Select the design to retrieve metadata for',- required: true,- refreshers: [],- auth:canvaAuth,- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Please authenticate with Canva first',- options: [],- };- }-- try {- const designs = await fetchUserDesigns(auth);- return {- disabled: false,- options: designs,- };- } catch (error) {- console.error('Error fetching designs:', error);- return {- disabled: true,- placeholder: 'Error loading designs',- options: [],- };- }- },- }),+ designId: canvaProps.designDropdown({ displayName: 'Design', description: 'The design to look up. Type to search.' }),},async run(context) {- const { designId } = context.propsValue;-- if (!designId || designId.trim().length === 0) {- throw new Error('Design ID is required');- }-- try {- const response = await httpClient.sendRequest<CanvaDesignResponse>({- method: HttpMethod.GET,- url: `${canvaCommon.baseUrl}/designs/${designId.trim()}`,- authentication: {- type: AuthenticationType.BEARER_TOKEN,- token: context.auth.access_token,- },- });-- return {- success: true,- design: response.body.design,- message: `Design "${response.body.design.title || response.body.design.id}" retrieved successfully`,- };- } catch (error: any) {- if (error.response?.status === 429) {- throw new Error('Rate limit exceeded. Please wait before making another request (100 requests per minute limit).');- }-- if (error.response?.status === 401) {- throw new Error('Authentication failed. Please check your Canva connection.');- }-- if (error.response?.status === 403) {- throw new Error('Access forbidden. Make sure your integration has the required scope: design:meta:read');- }-- if (error.response?.status === 404) {- throw new Error(`Design with ID "${designId}" was not found or you don't have access to it.`);- }-- if (error.response?.data?.message) {- throw new Error(`Canva API error: ${error.response.data.message}`);- }-- throw new Error(`Failed to retrieve design: ${error.message || 'Unknown error'}`);+ const designId = context.propsValue.designId.trim();+ if (!designId) {+ throw new Error('Design is required.');}+ const response = await canvaClient.request<CanvaDesignResponse>({+ token: context.auth.access_token,+ method: HttpMethod.GET,+ path: `/designs/${encodeURIComponent(designId)}`,+ });+ return {+ success: true,+ design: response.design,+ message: `Design "${response.design.title || response.design.id}" retrieved successfully`,+ };},-});\ No newline at end of file+});diff --git a/packages/pieces/community/canva/src/lib/actions/get-folder.ts b/packages/pieces/community/canva/src/lib/actions/get-folder.tsindex 598ea2790c0..18b7a1f5391 100644--- a/packages/pieces/community/canva/src/lib/actions/get-folder.ts+++ b/packages/pieces/community/canva/src/lib/actions/get-folder.ts@@ -1,123 +1,48 @@-import {- Property,- createAction,- OAuth2PropertyValue,-} from '@activepieces/pieces-framework';-import { canvaAuth } from '../../index';-import { canvaCommon, FolderResponse, fetchUserFolders } from '../common';+import { createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { canvaAuth, canvaProps, FolderResponse } from '../common';+import { canvaClient } from '../common/client';+import { canvaOutputSchemas } from '../common/output-schemas';export const getFolder = createAction({auth: canvaAuth,name: 'get_folder',classification: 'READ',displayName: 'Get Folder',- description: 'Retrieve metadata for a specific folder, including name, creation date, and thumbnail.',- audience: 'both',+ description: 'Get the details of a folder, including name, dates and thumbnail.',+ audience: 'human',aiMetadata: {- description:- 'Fetches metadata for a single Canva folder by folder ID, including its name, created/updated timestamps, and thumbnail. Pick this to verify a folder exists or get its details before moving items into it; it returns folder metadata only, not the folder contents. Read-only and idempotent.',+ description: 'Gets one Canva folder by ID. Human step; agents use canva_list_folder_items. Read-only.',idempotent: true,},+ outputSchema: canvaOutputSchemas.getFolder,props: {- folder_id: Property.Dropdown({- displayName: 'Folder',- description: 'Select the folder to retrieve metadata for',- required: true,- auth:canvaAuth,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Please authenticate with Canva first',- options: [],- };- }-- try {- const folders = await fetchUserFolders(auth);- return {- disabled: false,- options: folders,- };- } catch (error) {- console.error('Error fetching folders:', error);- return {- disabled: true,- placeholder: 'Error loading folders',- options: [],- };- }- },- }),+ folder_id: canvaProps.folderDropdown({ displayName: 'Folder', description: 'The folder to look up.' }),},async run(context) {- const { folder_id } = context.propsValue;- const authValue = context.auth as OAuth2PropertyValue;-- if (!folder_id || !folder_id.trim()) {- throw new Error('Folder ID is required');- }-- const cleanFolderId = folder_id.trim();-- try {- const response = await fetch(`${canvaCommon.baseUrl}/folders/${cleanFolderId}`, {- method: 'GET',- headers: {- 'Authorization': `Bearer ${authValue.access_token}`,- },- });-- if (!response.ok) {- const errorData = await response.json().catch(() => ({}));-- if (response.status === 400) {- throw new Error(`Bad Request: ${errorData.message || 'Invalid folder ID format'}`);- }-- if (response.status === 401) {- throw new Error('Unauthorized: Please check your authentication credentials');- }-- if (response.status === 403) {- throw new Error('Forbidden: You do not have permission to access this folder');- }-- if (response.status === 404) {- throw new Error(`Folder not found: The folder with ID "${cleanFolderId}" does not exist or you do not have access to it`);- }-- if (response.status === 429) {- throw new Error('Rate limit exceeded: Too many requests (limit: 100 per minute)');- }-- throw new Error(`HTTP ${response.status}: ${errorData.message || 'Request failed'}`);- }-- const data: FolderResponse = await response.json();- const folder = data.folder;-- return {- folder: {- id: folder.id,- name: folder.name,- created_at: folder.created_at,- updated_at: folder.updated_at,- thumbnail: folder.thumbnail || null,- },- folder_id: folder.id,- folder_name: folder.name,- created_date: new Date(folder.created_at * 1000).toISOString(),- updated_date: new Date(folder.updated_at * 1000).toISOString(),- has_thumbnail: !!folder.thumbnail,- thumbnail_url: folder.thumbnail?.url || null,- };- } catch (error) {- if (error instanceof Error) {- throw error;- }- throw new Error(`Failed to get folder: ${String(error)}`);+ const folderId = context.propsValue.folder_id.trim();+ if (!folderId) {+ throw new Error('Folder is required.');}+ const { folder } = await canvaClient.request<FolderResponse>({+ token: context.auth.access_token,+ method: HttpMethod.GET,+ path: `/folders/${encodeURIComponent(folderId)}`,+ });+ return {+ folder: {+ id: folder.id,+ name: folder.name,+ created_at: folder.created_at,+ updated_at: folder.updated_at,+ thumbnail: folder.thumbnail ?? null,+ },+ folder_id: folder.id,+ folder_name: folder.name,+ created_date: new Date(folder.created_at * 1000).toISOString(),+ updated_date: new Date(folder.updated_at * 1000).toISOString(),+ has_thumbnail: Boolean(folder.thumbnail),+ thumbnail_url: folder.thumbnail?.url ?? null,+ };},-});\ No newline at end of file+});diff --git a/packages/pieces/community/canva/src/lib/actions/get-job-status.ts b/packages/pieces/community/canva/src/lib/actions/get-job-status.tsnew file mode 100644index 00000000000..73744c0aaf5--- /dev/null+++ b/packages/pieces/community/canva/src/lib/actions/get-job-status.ts@@ -0,0 +1,60 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { AnyJob, canvaAuth, canvaCommon, JobKind } from '../common';+import { canvaOutputSchemas } from '../common/output-schemas';++export const getJobStatus = createAction({+ auth: canvaAuth,+ name: 'get_job_status',+ classification: 'READ',+ displayName: 'Get Job Status',+ description: 'Check an export, upload or import job and get its result (download links, asset or designs).',+ audience: 'human',+ aiMetadata: {+ description: 'Checks a Canva async job. Human step; agents use canva_get_export_job, canva_get_asset_upload_job or canva_get_import_job. Read-only.',+ idempotent: true,+ },+ outputSchema: canvaOutputSchemas.job,+ props: {+ jobType: Property.StaticDropdown({+ displayName: 'Job Type',+ description: 'The action that started the job.',+ required: true,+ options: {+ options: [+ { label: 'Export Design', value: 'export' },+ { label: 'Upload Asset (file)', value: 'asset_upload' },+ { label: 'Upload Asset (URL)', value: 'url_asset_upload' },+ { label: 'Import Design (file)', value: 'import' },+ { label: 'Import Design (URL)', value: 'url_import' },+ ],+ },+ }),+ jobId: Property.ShortText({+ displayName: 'Job ID',+ description: 'The job ID returned by the action that started the job.',+ required: true,+ }),+ },+ async run(context) {+ const kind = toJobKind(context.propsValue.jobType);+ const jobId = context.propsValue.jobId.trim();+ if (!jobId) {+ throw new Error('Job ID is required.');+ }+ const job = await canvaCommon.fetchJob<AnyJob>({ token: context.auth.access_token, kind, jobId });+ return canvaCommon.flattenJob({ kind, job });+ },+});++function toJobKind(value: string): JobKind {+ switch (value) {+ case 'export':+ case 'asset_upload':+ case 'url_asset_upload':+ case 'import':+ case 'url_import':+ return value;+ default:+ throw new Error(`Unknown job type "${value}".`);+ }+}diff --git a/packages/pieces/community/canva/src/lib/actions/import-design.ts b/packages/pieces/community/canva/src/lib/actions/import-design.tsindex 39201d54e23..723bc5ff796 100644--- a/packages/pieces/community/canva/src/lib/actions/import-design.ts+++ b/packages/pieces/community/canva/src/lib/actions/import-design.ts@@ -1,149 +1,102 @@import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';import {- AuthenticationType,- httpClient,- HttpMethod,-} from '@activepieces/pieces-common';-import { canvaAuth } from '../../index';-import {- canvaCommon,- DesignImportResponse,- DesignImportMetadata,+ canvaAuth,+ canvaCommon,+ canvaProps,+ DesignImportJob,+ MAX_DESIGN_TITLE_LENGTH,SUPPORTED_IMPORT_FORMATS,- MAX_DESIGN_TITLE_LENGTH} from '../common';+import { canvaClient } from '../common/client';+import { canvaOutputSchemas } from '../common/output-schemas';export const importDesign = createAction({auth: canvaAuth,name: 'import_design',classification: 'WRITE',displayName: 'Import Design',- description: 'Import an external file (PDF, PSD, DOCX, PPTX, etc.) into Canva as a new design. This creates an asynchronous job that you can monitor for completion.',- audience: 'both',+ description: 'Import a file (PDF, PPTX, DOCX, PSD, AI and more) into Canva as a new design and wait for the result.',+ audience: 'human',aiMetadata: {- description:- 'Uploads an external document or design file (PDF, DOCX, PPTX, XLSX, PSD, AI, and similar) and converts it into a new Canva design via an asynchronous import job, with a required title of at most 50 characters. Pick this to bring existing files into Canva as editable designs; use Create Design for a blank design and Upload Asset for images/videos meant for the media library. Not idempotent: each call starts a new import and can create duplicate designs.',+ description: 'Imports a file as a new Canva design. Human step; agents use canva_import_design_from_url. Not idempotent: each run creates new designs.',idempotent: false,},+ outputSchema: canvaOutputSchemas.importDesign,props: {file: Property.File({displayName: 'Design File',- description: `📄 Supported formats:- 📋 Documents: PDF, DOC, DOCX, ODT, Pages- 📊 Presentations: PPT, PPTX, ODP, Keynote- 📈 Spreadsheets: XLS, XLSX, ODS, Numbers- 🎨 Design Files: AI (Illustrator), PSD (Photoshop), ODG`,+ description: `Supported: ${SUPPORTED_IMPORT_FORMATS.map((f) => f.ext.toUpperCase()).join(', ')}.`,required: true,}),designTitle: Property.ShortText({displayName: 'Design Title',- description: '🏷️ Title for the imported design (max 50 characters, supports emojis and special characters)',+ description: `Title for the imported design (max ${MAX_DESIGN_TITLE_LENGTH} characters).`,required: true,}),autoDetectMimeType: Property.Checkbox({- displayName: '🔍 Auto-detect File Type',- description: '✅ Recommended: Let Canva automatically detect the file type. Uncheck to manually specify MIME type from file extension.',+ displayName: 'Auto-detect File Type',+ description: 'Let Canva detect the file type. Turn off to send the type based on the file extension.',required: false,defaultValue: true,}),+ ...canvaProps.waitProps(),},async run(context) {- const { file, designTitle, autoDetectMimeType } = context.propsValue;-- if (!designTitle || designTitle.trim().length === 0) {- throw new Error('Design title is required');+ const { file, designTitle, autoDetectMimeType, waitForCompletion, maxWaitSeconds } = context.propsValue;+ const title = designTitle.trim();+ if (!title) {+ throw new Error('Design title is required.');}-- if (designTitle.length > MAX_DESIGN_TITLE_LENGTH) {- throw new Error(`Design title must be ${MAX_DESIGN_TITLE_LENGTH} characters or less`);+ if (title.length > MAX_DESIGN_TITLE_LENGTH) {+ throw new Error(`Design title must be ${MAX_DESIGN_TITLE_LENGTH} characters or fewer.`);}-- if (!file) {- throw new Error('File is required');+ const extension = file.filename?.split('.').pop()?.toLowerCase();+ const format = SUPPORTED_IMPORT_FORMATS.find((f) => f.ext === extension);+ if (!format) {+ throw new Error(`Unsupported file format: ${extension ?? 'unknown'}. Supported: ${SUPPORTED_IMPORT_FORMATS.map((f) => f.ext).join(', ')}.`);}-- const fileExtension = file.filename?.split('.').pop()?.toLowerCase();- if (!fileExtension) {- throw new Error('Unable to determine file type from filename');+ const buffer = Buffer.from(file.base64, 'base64');+ const metadata: Record<string, string> = { title_base64: canvaCommon.base64Utf8(title) };+ if (autoDetectMimeType === false) {+ metadata['mime_type'] = format.mime;}-- const supportedFormat = SUPPORTED_IMPORT_FORMATS.find(format => format.ext === fileExtension);- if (!supportedFormat) {- const supportedExts = SUPPORTED_IMPORT_FORMATS.map(f => f.ext.toUpperCase()).join(', ');- throw new Error(`Unsupported file format: ${fileExtension.toUpperCase()}. Supported formats: ${supportedExts}`);- }-- const fileBuffer = Buffer.from(file.base64, 'base64');- const fileSizeMB = fileBuffer.length / (1024 * 1024);-- const titleBase64 = Buffer.from(designTitle.trim()).toString('base64');-- const importMetadata: DesignImportMetadata = {- title_base64: titleBase64,+ const token = context.auth.access_token;+ const started = await canvaClient.request<{ job: DesignImportJob }>({+ token,+ method: HttpMethod.POST,+ path: '/imports',+ headers: {+ 'Content-Type': 'application/octet-stream',+ 'Import-Metadata': JSON.stringify(metadata),+ },+ body: buffer,+ timeoutMs: 300_000,+ });+ const job = waitForCompletion === false+ ? started.job+ : await canvaCommon.settleJob<DesignImportJob>({+ token,+ kind: 'import',+ initial: started.job,+ timeoutSeconds: canvaCommon.clampWaitSeconds(maxWaitSeconds ?? undefined),+ failOnTimeout: true,+ });+ const designs = job.result?.designs ?? [];+ return {+ success: job.status !== 'failed',+ job,+ designs,+ file_info: {+ title,+ size_mb: Math.round((buffer.length / (1024 * 1024)) * 100) / 100,+ format: format.name,+ extension: format.ext.toUpperCase(),+ mime_type: autoDetectMimeType === false ? format.mime : 'auto-detected',+ },+ message: job.status === 'success'+ ? `Import finished: ${designs.length} design(s) created.`+ : `Import job ${job.id} is ${job.status}. Check it later with Get Job Status.`,};-- if (!autoDetectMimeType) {- importMetadata.mime_type = supportedFormat.mime;- }-- try {- const response = await httpClient.sendRequest<DesignImportResponse>({- method: HttpMethod.POST,- url: `${canvaCommon.baseUrl}/imports`,- headers: {- 'Content-Type': 'application/octet-stream',- 'Import-Metadata': JSON.stringify(importMetadata),- },- authentication: {- type: AuthenticationType.BEARER_TOKEN,- token: context.auth.access_token,- },- body: fileBuffer,- });-- return {- success: true,- job: response.body.job,- file_info: {- title: designTitle.trim(),- size_mb: Math.round(fileSizeMB * 100) / 100,- format: supportedFormat.name,- extension: fileExtension.toUpperCase(),- mime_type: autoDetectMimeType ? 'auto-detected' : supportedFormat.mime,- },- message: `Design import job created successfully. Job ID: ${response.body.job.id}. Status: ${response.body.job.status}`,- next_steps: response.body.job.status === 'in_progress'- ? 'Use the "Get Design Import Job" action to check the status and get the imported design details.'- : response.body.job.status === 'success' && response.body.job.result- ? `Import completed! ${response.body.job.result.designs.length} design(s) created.`- : undefined,- };- } catch (error: any) {- if (error.response?.status === 429) {- throw new Error('Rate limit exceeded. Please wait before making another request (20 requests per minute limit).');- }-- if (error.response?.status === 401) {- throw new Error('Authentication failed. Please check your Canva connection.');- }-- if (error.response?.status === 403) {- throw new Error('Access forbidden. Make sure your integration has the required scope: design:content:write');- }-- if (error.response?.status === 413) {- throw new Error('File too large. Check the upload requirements for your file type.');- }-- if (error.response?.status === 415) {- throw new Error(`Unsupported media type. File format ${fileExtension.toUpperCase()} may not be supported or the file may be corrupted.`);- }-- if (error.response?.data?.message) {- throw new Error(`Canva API error: ${error.response.data.message}`);- }-- throw new Error(`Failed to import design: ${error.message || 'Unknown error'}`);- }},-});\ No newline at end of file+});diff --git a/packages/pieces/community/canva/src/lib/actions/list-folder-items.ts b/packages/pieces/community/canva/src/lib/actions/list-folder-items.tsnew file mode 100644index 00000000000..81bbe21670a--- /dev/null+++ b/packages/pieces/community/canva/src/lib/actions/list-folder-items.ts@@ -0,0 +1,115 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { canvaAuth, canvaCommon, canvaProps } from '../common';+import { canvaOutputSchemas } from '../common/output-schemas';++export const listFolderItems = createAction({+ auth: canvaAuth,+ name: 'list_folder_items',+ classification: 'SEARCH',+ displayName: 'List Folder Items',+ description: 'List the designs, images and subfolders in a folder. Returns one page; use the continuation token for the next page.',+ audience: 'human',+ aiMetadata: {+ description: 'Lists items in a Canva folder. Human step; agents use canva_list_folder_items. Read-only.',+ idempotent: true,+ },+ outputSchema: canvaOutputSchemas.listFolderItems,+ props: {+ folderId: canvaProps.folderDropdown({ displayName: 'Folder', description: 'The folder to list.' }),+ itemTypes: Property.StaticMultiSelectDropdown({+ displayName: 'Item Types',+ description: 'Only return these kinds of items. Leave empty for designs, folders and images.',+ required: false,+ options: {+ options: [+ { label: 'Designs', value: 'design' },+ { label: 'Folders', value: 'folder' },+ { label: 'Images', value: 'image' },+ ],+ },+ }),+ sortBy: Property.StaticDropdown({+ displayName: 'Sort By',+ description: 'How to order the items.',+ required: false,+ defaultValue: 'modified_descending',+ options: {+ options: [+ { label: 'Recently modified', value: 'modified_descending' },+ { label: 'Oldest modified', value: 'modified_ascending' },+ { label: 'Newest created', value: 'created_descending' },+ { label: 'Oldest created', value: 'created_ascending' },+ { label: 'Title A-Z', value: 'title_ascending' },+ { label: 'Title Z-A', value: 'title_descending' },+ ],+ },+ }),+ limit: Property.Number({+ displayName: 'Limit',+ description: 'How many items to return (1-100, default 50).',+ required: false,+ defaultValue: 50,+ }),+ continuation: Property.ShortText({+ displayName: 'Continuation Token',+ description: 'Token from a previous run to get the next page.',+ required: false,+ }),+ },+ async run(context) {+ const { folderId, itemTypes, sortBy, limit, continuation } = context.propsValue;+ return listItems({+ token: context.auth.access_token,+ folderId,+ itemTypes: itemTypes ?? undefined,+ sortBy: sortBy ?? undefined,+ limit: limit ?? undefined,+ continuation: continuation ?? undefined,+ });+ },+});++async function listItems({+ token,+ folderId,+ itemTypes,+ sortBy,+ limit,+ continuation,+}: {+ token: string;+ folderId: string;+ itemTypes?: string[];+ sortBy?: string;+ limit?: number;+ continuation?: string;+}) {+ const id = folderId.trim();+ if (!id) {+ throw new Error('Folder is required.');+ }+ if (limit !== undefined && (!Number.isInteger(limit) || limit < 1 || limit > 100)) {+ throw new Error('Limit must be a whole number between 1 and 100.');+ }+ const allowed = ['design', 'folder', 'image'];+ const types = (itemTypes ?? []).map((t) => t.trim()).filter((t) => t.length > 0);+ const invalid = types.find((t) => !allowed.includes(t));+ if (invalid) {+ throw new Error(`Unknown item type "${invalid}". Use design, folder or image.`);+ }+ const page = await canvaCommon.listFolderPage({+ token,+ folderId: id,+ itemTypes: types.length > 0 ? types.join(',') : undefined,+ sortBy,+ limit,+ continuation: continuation?.trim() || undefined,+ });+ return {+ items: page.items.map((item) => canvaCommon.flattenFolderItem(item)),+ has_more: Boolean(page.continuation),+ continuation: page.continuation ?? null,+ };+}++export const listFolderItemsRequest = listItems;diff --git a/packages/pieces/community/canva/src/lib/actions/move-folder-item.ts b/packages/pieces/community/canva/src/lib/actions/move-folder-item.tsindex 4bbd2b94e90..1e28a186e7d 100644--- a/packages/pieces/community/canva/src/lib/actions/move-folder-item.ts+++ b/packages/pieces/community/canva/src/lib/actions/move-folder-item.ts@@ -1,58 +1,26 @@-import {- Property,- createAction,- OAuth2PropertyValue,-} from '@activepieces/pieces-framework';-import { canvaAuth } from '../../index';-import { canvaCommon, fetchUserFolders, fetchUserDesigns, fetchUserAssets } from '../common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { canvaAuth, canvaCommon, canvaProps } from '../common';+import { canvaClient } from '../common/client';+import { canvaOutputSchemas } from '../common/output-schemas';export const moveFolderItem = createAction({auth: canvaAuth,name: 'move_folder_item',classification: 'WRITE',displayName: 'Move Folder Item',- description: 'Move an item from one folder to another in Canva',- audience: 'both',+ description: 'Move a design or image into another folder.',+ audience: 'human',aiMetadata: {- description:- 'Moves a design or image asset into a specified destination folder in Canva, identified by item ID and folder ID. Pick this to reorganize library content; it fails for items that currently live in multiple folders (those must be moved in the Canva UI). Effectively idempotent: repeating the same move leaves the item in the same destination folder.',+ description: 'Moves a Canva design or image into a folder. Human step; agents use canva_move_folder_item. Repeating the same move leaves the item in the same folder.',idempotent: true,},+ outputSchema: canvaOutputSchemas.moveFolderItem,props: {- to_folder_id: Property.Dropdown({- displayName: 'Destination Folder',- description: 'Select the folder to move the item to',- required: true,- refreshers: [],- auth:canvaAuth,- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Please authenticate with Canva first',- options: [],- };- }-- try {- const folders = await fetchUserFolders(auth);- return {- disabled: false,- options: folders,- };- } catch (error) {- console.error('Error fetching folders:', error);- return {- disabled: true,- placeholder: 'Error loading folders',- options: [],- };- }- },- }),+ to_folder_id: canvaProps.folderDropdown({ displayName: 'Destination Folder', description: 'The folder to move the item to.' }),item_type: Property.StaticDropdown({displayName: 'Item Type',- description: 'Select the type of item you want to move',+ description: 'The kind of item to move.',required: true,defaultValue: 'design',options: {@@ -63,111 +31,50 @@ export const moveFolderItem = createAction({},}),item_id: Property.Dropdown({+ auth: canvaAuth,displayName: 'Item to Move',- description: 'Select the item you want to move',+ description: 'The design or image to move.',required: true,- auth:canvaAuth,refreshers: ['item_type'],options: async ({ auth, item_type }) => {if (!auth) {- return {- disabled: true,- placeholder: 'Please authenticate with Canva first',- options: [],- };+ return { disabled: true, placeholder: 'Connect your Canva account first', options: [] };}-if (!item_type) {- return {- disabled: true,- placeholder: 'Please select an item type first',- options: [],- };+ return { disabled: true, placeholder: 'Select an item type first', options: [] };}-try {- let items: Array<{ label: string; value: string }> = [];-- if (item_type === 'design') {- items = await fetchUserDesigns(auth);- } else if (item_type === 'image') {- items = await fetchUserAssets(auth, 'image');- }-- return {- disabled: false,- options: items,- };+ const result = item_type === 'image' ? await canvaCommon.fetchUserAssets({ auth }) : await canvaCommon.fetchUserDesigns({ auth });+ return canvaCommon.dropdownState({ result });} catch (error) {- console.error('Error fetching items:', error);- return {- disabled: true,- placeholder: 'Error loading items',- options: [],- };+ return canvaCommon.dropdownError({ error, what: 'items' });}},}),},async run(context) {- const { to_folder_id, item_id } = context.propsValue;- const authValue = context.auth as OAuth2PropertyValue;-- try {- const response = await fetch(`${canvaCommon.baseUrl}/folders/move`, {- method: 'POST',- headers: {- 'Authorization': `Bearer ${authValue.access_token}`,- 'Content-Type': 'application/json',- },- body: JSON.stringify({- to_folder_id,- item_id,- }),- });-- if (!response.ok) {- const errorData = await response.json().catch(() => ({}));-- if (response.status === 400) {- if (errorData.type === 'item_in_multiple_folders') {- throw new Error(- 'This item exists in multiple folders. Please use the Canva UI to move the item to another folder.'- );- }- throw new Error(`Bad Request: ${errorData.message || 'Invalid request parameters'}`);- }-- if (response.status === 401) {- throw new Error('Unauthorized: Please check your authentication credentials');- }-- if (response.status === 403) {- throw new Error('Forbidden: Insufficient permissions or invalid folder/item access');- }-- if (response.status === 404) {- throw new Error('Not Found: The specified folder or item does not exist');- }-- if (response.status === 429) {- throw new Error('Rate limit exceeded: Too many requests (limit: 100 per minute)');- }-- throw new Error(`HTTP ${response.status}: ${errorData.message || 'Request failed'}`);- }-- return {- success: true,- message: `Item ${item_id} successfully moved to folder ${to_folder_id}`,- moved_item_id: item_id,- destination_folder_id: to_folder_id,- };- } catch (error) {- if (error instanceof Error) {- throw error;- }- throw new Error(`Failed to move folder item: ${String(error)}`);+ const toFolderId = context.propsValue.to_folder_id.trim();+ const itemId = String(context.propsValue.item_id ?? '').trim();+ if (!toFolderId || !itemId) {+ throw new Error('Destination folder and item are required.');}+ await moveItem({ token: context.auth.access_token, toFolderId, itemId });+ return {+ success: true,+ message: `Item ${itemId} moved to folder ${toFolderId}`,+ moved_item_id: itemId,+ destination_folder_id: toFolderId,+ };},-});\ No newline at end of file+});++async function moveItem({ token, toFolderId, itemId }: { token: string; toFolderId: string; itemId: string }): Promise<void> {+ await canvaClient.request<unknown>({+ token,+ method: HttpMethod.POST,+ path: '/folders/move',+ body: { to_folder_id: toFolderId, item_id: itemId },+ });+}++export const moveFolderItemRequest = moveItem;diff --git a/packages/pieces/community/canva/src/lib/actions/upload-asset.ts b/packages/pieces/community/canva/src/lib/actions/upload-asset.tsindex 484254b13cb..742377590d1 100644--- a/packages/pieces/community/canva/src/lib/actions/upload-asset.ts+++ b/packages/pieces/community/canva/src/lib/actions/upload-asset.ts@@ -1,142 +1,102 @@import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';import {- AuthenticationType,- httpClient,- HttpMethod,-} from '@activepieces/pieces-common';-import { canvaAuth } from '../../index';-import {- canvaCommon,- AssetUploadResponse,- AssetUploadMetadata,- SUPPORTED_IMAGE_FORMATS,- SUPPORTED_VIDEO_FORMATS,+ AssetUploadJob,+ canvaAuth,+ canvaCommon,+ canvaProps,+ MAX_ASSET_NAME_LENGTH,MAX_IMAGE_SIZE_MB,MAX_VIDEO_SIZE_MB,- MAX_ASSET_NAME_LENGTH+ SUPPORTED_IMAGE_FORMATS,+ SUPPORTED_VIDEO_FORMATS,} from '../common';+import { canvaClient } from '../common/client';+import { canvaOutputSchemas } from '../common/output-schemas';export const uploadAsset = createAction({auth: canvaAuth,name: 'upload_asset',classification: 'WRITE',displayName: 'Upload Asset',- description: 'Upload an image or video asset to your Canva library. This creates an asynchronous job that you can monitor for completion.',- audience: 'both',+ description: 'Upload an image or video to your Canva library and wait until Canva has processed it.',+ audience: 'human',aiMetadata: {- description:- "Uploads an image (max 50MB) or video (max 500MB) file into the user's Canva media library via an asynchronous job, with a required asset name of at most 50 characters. Pick this to add media for later use in designs; use Import Design instead when the file should become an editable design itself. Not idempotent: each call starts a new upload and creates a duplicate asset.",+ description: 'Uploads a file to the Canva library. Human step; agents use canva_upload_asset_from_url. Not idempotent: each run creates another asset.',idempotent: false,},+ outputSchema: canvaOutputSchemas.uploadAsset,props: {file: Property.File({displayName: 'Asset File',- description: `📁 Supported formats:- 🖼️ Images (max 50MB): ${SUPPORTED_IMAGE_FORMATS.map(f => f.toUpperCase()).join(', ')}- 🎬 Videos (max 500MB): ${SUPPORTED_VIDEO_FORMATS.map(f => f.toUpperCase()).join(', ')}`,+ description: `Images (max ${MAX_IMAGE_SIZE_MB}MB): ${SUPPORTED_IMAGE_FORMATS.join(', ').toUpperCase()}. Videos (max ${MAX_VIDEO_SIZE_MB}MB): ${SUPPORTED_VIDEO_FORMATS.join(', ').toUpperCase()}.`,required: true,}),assetName: Property.ShortText({displayName: 'Asset Name',- description: '🏷️ Name for the asset (max 50 characters, supports emojis and special characters)',+ description: `Name for the asset (max ${MAX_ASSET_NAME_LENGTH} characters).`,required: true,}),+ ...canvaProps.waitProps(),},async run(context) {- const { file, assetName } = context.propsValue;-- if (!assetName || assetName.trim().length === 0) {- throw new Error('Asset name is required');- }-- if (assetName.length > MAX_ASSET_NAME_LENGTH) {- throw new Error(`Asset name must be ${MAX_ASSET_NAME_LENGTH} characters or less`);+ const { file, assetName, waitForCompletion, maxWaitSeconds } = context.propsValue;+ const name = assetName.trim();+ if (!name) {+ throw new Error('Asset name is required.');}-- if (!file) {- throw new Error('File is required');+ if (name.length > MAX_ASSET_NAME_LENGTH) {+ throw new Error(`Asset name must be ${MAX_ASSET_NAME_LENGTH} characters or fewer.`);}-- const fileExtension = file.filename?.split('.').pop()?.toLowerCase();- if (!fileExtension) {- throw new Error('Unable to determine file type from filename');+ const extension = file.filename?.split('.').pop()?.toLowerCase();+ if (!extension) {+ throw new Error('Could not tell the file type from the file name.');}-- const isImage = SUPPORTED_IMAGE_FORMATS.includes(fileExtension);- const isVideo = SUPPORTED_VIDEO_FORMATS.includes(fileExtension);-+ const isImage = SUPPORTED_IMAGE_FORMATS.includes(extension);+ const isVideo = SUPPORTED_VIDEO_FORMATS.includes(extension);if (!isImage && !isVideo) {- throw new Error(`Unsupported file format: ${fileExtension}. Supported formats - Images: ${SUPPORTED_IMAGE_FORMATS.join(', ')}. Videos: ${SUPPORTED_VIDEO_FORMATS.join(', ')}`);+ throw new Error(`Unsupported file format: ${extension}. Images: ${SUPPORTED_IMAGE_FORMATS.join(', ')}. Videos: ${SUPPORTED_VIDEO_FORMATS.join(', ')}.`);}-- const fileBuffer = Buffer.from(file.base64, 'base64');- const fileSizeMB = fileBuffer.length / (1024 * 1024);-- if (isImage && fileSizeMB > MAX_IMAGE_SIZE_MB) {- throw new Error(`Image file size (${fileSizeMB.toFixed(2)}MB) exceeds maximum limit of ${MAX_IMAGE_SIZE_MB}MB`);+ const buffer = Buffer.from(file.base64, 'base64');+ const sizeMb = buffer.length / (1024 * 1024);+ const limitMb = isImage ? MAX_IMAGE_SIZE_MB : MAX_VIDEO_SIZE_MB;+ if (sizeMb > limitMb) {+ throw new Error(`File size (${sizeMb.toFixed(2)}MB) is over the ${limitMb}MB limit for ${isImage ? 'images' : 'videos'}.`);}-- if (isVideo && fileSizeMB > MAX_VIDEO_SIZE_MB) {- throw new Error(`Video file size (${fileSizeMB.toFixed(2)}MB) exceeds maximum limit of ${MAX_VIDEO_SIZE_MB}MB`);- }-- const nameBase64 = Buffer.from(assetName.trim()).toString('base64');-- const uploadMetadata: AssetUploadMetadata = {- name_base64: nameBase64,+ const token = context.auth.access_token;+ const started = await canvaClient.request<{ job: AssetUploadJob }>({+ token,+ method: HttpMethod.POST,+ path: '/asset-uploads',+ headers: {+ 'Content-Type': 'application/octet-stream',+ 'Asset-Upload-Metadata': JSON.stringify({ name_base64: canvaCommon.base64Utf8(name) }),+ },+ body: buffer,+ timeoutMs: 300_000,+ });+ const job = waitForCompletion === false+ ? started.job+ : await canvaCommon.settleJob<AssetUploadJob>({+ token,+ kind: 'asset_upload',+ initial: started.job,+ timeoutSeconds: canvaCommon.clampWaitSeconds(maxWaitSeconds ?? undefined),+ failOnTimeout: true,+ });+ return {+ success: job.status !== 'failed',+ job,+ asset: job.asset ?? null,+ file_info: {+ name,+ size_mb: Math.round(sizeMb * 100) / 100,+ type: isImage ? 'image' : 'video',+ format: extension.toUpperCase(),+ },+ message: job.status === 'success'+ ? `Asset "${job.asset?.name ?? name}" uploaded. Asset ID: ${job.asset?.id ?? 'unknown'}`+ : `Upload job ${job.id} is ${job.status}. Check it later with Get Job Status.`,};-- try {- const response = await httpClient.sendRequest<AssetUploadResponse>({- method: HttpMethod.POST,- url: `${canvaCommon.baseUrl}/asset-uploads`,- headers: {- 'Content-Type': 'application/octet-stream',- 'Asset-Upload-Metadata': JSON.stringify(uploadMetadata),- },- authentication: {- type: AuthenticationType.BEARER_TOKEN,- token: context.auth.access_token,- },- body: fileBuffer,- });-- return {- success: true,- job: response.body.job,- file_info: {- name: assetName.trim(),- size_mb: Math.round(fileSizeMB * 100) / 100,- type: isImage ? 'image' : 'video',- format: fileExtension.toUpperCase(),- },- message: `Asset upload job created successfully. Job ID: ${response.body.job.id}. Status: ${response.body.job.status}`,- next_steps: response.body.job.status === 'in_progress'- ? 'Use the "Get Asset Upload Job" action to check the status and get the final asset details.'- : undefined,- };- } catch (error: any) {- if (error.response?.status === 429) {- throw new Error('Rate limit exceeded. Please wait before making another request (30 requests per minute limit).');- }-- if (error.response?.status === 401) {- throw new Error('Authentication failed. Please check your Canva connection.');- }-- if (error.response?.status === 403) {- throw new Error('Access forbidden. Make sure your integration has the required scope: asset:write');- }-- if (error.response?.status === 413) {- throw new Error('File too large. Check file size limits: Images max 50MB, Videos max 500MB.');- }-- if (error.response?.data?.message) {- throw new Error(`Canva API error: ${error.response.data.message}`);- }-- throw new Error(`Failed to upload asset: ${error.message || 'Unknown error'}`);- }},-});\ No newline at end of file+});diff --git a/packages/pieces/community/canva/src/lib/common/client.ts b/packages/pieces/community/canva/src/lib/common/client.tsnew file mode 100644index 00000000000..46891977667--- /dev/null+++ b/packages/pieces/community/canva/src/lib/common/client.ts@@ -0,0 +1,195 @@+import { httpClient, HttpMethod, HttpRequest, QueryParams } from '@activepieces/pieces-common';++const BASE_URL = 'https://api.canva.com/rest/v1';+const DEFAULT_TIMEOUT_MS = 30_000;+const FIRST_POLL_DELAY_MS = 1_000;+const MAX_POLL_DELAY_MS = 5_000;+const POLL_BACKOFF = 1.5;+let verifiedTlsAgent: Promise<unknown> | undefined;++const STATUS_HINTS: Record<number, string> = {+ 400: 'Canva rejected the request (HTTP 400).',+ 401: 'Canva rejected the connection (HTTP 401). Reconnect your Canva account.',+ 403: 'Canva denied access (HTTP 403). Check that you can access this item and that the connection has the needed permission.',+ 404: 'Canva could not find that item (HTTP 404). Check the ID.',+ 409: 'Canva reported a conflict (HTTP 409).',+ 413: 'The file is too large for Canva (HTTP 413).',+ 415: 'Canva does not support this file type (HTTP 415).',+ 429: 'Canva rate limit reached (HTTP 429). Wait a minute and try again.',+};++class CanvaApiError extends Error {+ public readonly status: number | undefined;+ public readonly code: string | undefined;+ public readonly responseBody: unknown;++ constructor({ message, status, code, responseBody }: { message: string; status?: number; code?: string; responseBody: unknown }) {+ super(message);+ this.name = 'CanvaApiError';+ this.status = status;+ this.code = code;+ this.responseBody = responseBody;+ }+}++function readHttpFailure(error: unknown): { status: number; body: unknown } | null {+ if (typeof error !== 'object' || error === null) {+ return null;+ }+ const response: unknown = Reflect.get(error, 'response');+ if (typeof response !== 'object' || response === null) {+ return null;+ }+ const status: unknown = Reflect.get(response, 'status');+ if (typeof status !== 'number') {+ return null;+ }+ return { status, body: Reflect.get(response, 'body') };+}++function readString({ source, key }: { source: unknown; key: string }): string | undefined {+ if (typeof source !== 'object' || source === null) {+ return undefined;+ }+ const value: unknown = Reflect.get(source, key);+ return typeof value === 'string' && value.length > 0 ? value : undefined;+}++function toCanvaError({ status, body }: { status: number; body: unknown }): CanvaApiError {+ const prefix = STATUS_HINTS[status] ?? `Canva API request failed (HTTP ${status}).`;+ const code = readString({ source: body, key: 'code' });+ const vendorMessage = typeof body === 'string' && body.length > 0 ? body.slice(0, 500) : readString({ source: body, key: 'message' });+ const detail = vendorMessage ? ` Canva says: ${vendorMessage}${code ? ` (${code})` : ''}` : code ? ` Canva error code: ${code}` : '';+ return new CanvaApiError({ message: `${prefix}${detail}`, status, code, responseBody: body });+}++function verifiedTls(): Promise<unknown> {+ verifiedTlsAgent ??= import('undici').then(({ Agent }) => new Agent({ connect: { rejectUnauthorized: true } }));+ return verifiedTlsAgent;+}++async function request<T>({+ token,+ method,+ path,+ body,+ queryParams,+ headers,+ timeoutMs,+}: {+ token: string;+ method: HttpMethod;+ path: string;+ body?: HttpRequest['body'];+ queryParams?: QueryParams;+ headers?: Record<string, string>;+ timeoutMs?: number;+}): Promise<T> {+ const finalHeaders: Record<string, string> = {+ Authorization: `Bearer ${token}`,+ Accept: 'application/json',+ ...headers,+ };+ if (body !== undefined && finalHeaders['Content-Type'] === undefined) {+ finalHeaders['Content-Type'] = 'application/json';+ }+ try {+ const response = await httpClient.sendRequest<T>({+ method,+ url: `${BASE_URL}${path}`,+ headers: finalHeaders,+ body,+ queryParams,+ timeout: timeoutMs ?? DEFAULT_TIMEOUT_MS,+ redactBodyInErrors: Buffer.isBuffer(body),+ }, { dispatcher: await canvaClient.verifiedTls() });+ return response.body;+ } catch (error) {+ const failure = readHttpFailure(error);+ if (failure) {+ throw toCanvaError(failure);+ }+ throw error;+ }+}++function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++async function waitForJob<J extends { id: string; status: string }>({+ initial,+ fetchJob,+ timeoutSeconds,+ jobLabel,+ statusAction,+}: {+ jobLabel: string;+ statusAction?: string;+ initial: J;+ fetchJob: (jobId: string) => Promise<J>;+ timeoutSeconds: number;+}): Promise<{ job: J; timedOut: boolean }> {+ let job = initial;+ const started = Date.now();+ const budgetMs = Math.max(0, timeoutSeconds) * 1000;+ let slept = 0;+ let delay = FIRST_POLL_DELAY_MS;+ while (job.status === 'in_progress') {+ const elapsed = Math.max(Date.now() - started, slept);+ const remaining = budgetMs - elapsed;+ if (remaining <= 0) {+ return { job, timedOut: true };+ }+ const wait = Math.min(delay, remaining);+ await canvaClient.sleep(wait);+ slept += wait;+ delay = Math.min(Math.round(delay * POLL_BACKOFF), MAX_POLL_DELAY_MS);+ job = await fetchStatus({ fetchJob, jobId: job.id, jobLabel, statusAction });+ }+ return { job, timedOut: false };+}++async function fetchStatus<J>({ fetchJob, jobId, jobLabel, statusAction }: { fetchJob: (jobId: string) => Promise<J>; jobId: string; jobLabel: string; statusAction?: string }): Promise<J> {+ try {+ return await fetchJob(jobId);+ } catch (error) {+ throw jobPollError({ jobLabel, jobId, error, statusAction });+ }+}++function jobPollError({ jobLabel, jobId, error, statusAction }: { jobLabel: string; jobId: string; error: unknown; statusAction?: string }): CanvaApiError {+ const reason = error instanceof Error ? error.message : String(error);+ const message = `Checking the status of the Canva ${jobLabel} job ${jobId} failed: ${reason} The job may still be running in Canva. Use ${statusAction ?? 'the Get Job Status action'} with job ID ${jobId} instead of starting the job again.`;+ if (error instanceof CanvaApiError) {+ return new CanvaApiError({ message, status: error.status, code: error.code, responseBody: error.responseBody });+ }+ return new CanvaApiError({ message, responseBody: undefined });+}++function jobFailureError({ jobLabel, jobId, error }: { jobLabel: string; jobId: string; error?: { code?: string; message?: string } }): CanvaApiError {+ const reason = error?.message ? ` Canva says: ${error.message}${error.code ? ` (${error.code})` : ''}` : '';+ return new CanvaApiError({+ message: `The Canva ${jobLabel} job ${jobId} failed.${reason}`,+ code: error?.code,+ responseBody: error,+ });+}++function jobTimeoutError({ jobLabel, jobId, timeoutSeconds }: { jobLabel: string; jobId: string; timeoutSeconds: number }): Error {+ return new Error(+ `The Canva ${jobLabel} job ${jobId} was still running after ${timeoutSeconds} seconds. Use the Get Job Status action with this job ID to fetch the result later, or raise the maximum wait.`+ );+}++export const canvaClient = {+ baseUrl: BASE_URL,+ request,+ sleep,+ verifiedTls,+ waitForJob,+ jobFailureError,+ jobTimeoutError,+};++export { CanvaApiError };diff --git a/packages/pieces/community/canva/src/lib/common/index.ts b/packages/pieces/community/canva/src/lib/common/index.tsindex 3cb845611d4..ae93d7e5aa2 100644--- a/packages/pieces/community/canva/src/lib/common/index.ts+++ b/packages/pieces/community/canva/src/lib/common/index.ts@@ -1,258 +1,419 @@-import { AppConnectionValueForAuthProperty } from "@activepieces/pieces-framework";-import { canvaAuth } from "src";--export const canvaCommon = {- baseUrl: 'https://api.canva.com/rest/v1',-};--export type canvaAuthType = AppConnectionValueForAuthProperty<typeof canvaAuth>--export interface DesignTypeInput {- type: 'preset' | 'custom';- name?: 'doc' | 'whiteboard' | 'presentation'; // Required if type is 'preset'- width?: number; // Required if type is 'custom', min: 40, max: 8000- height?: number; // Required if type is 'custom', min: 40, max: 8000-}--// Request body for create design API-export interface CanvaDesignCreateRequest {- design_type?: DesignTypeInput;- asset_id?: string;- title?: string; // Min length: 1, Max length: 255-}--// Owner information-export interface TeamUserSummary {- user_id: string;- team_id: string;-}--// Design URLs-export interface DesignLinks {- edit_url: string;- view_url: string;-}--// Thumbnail information-export interface Thumbnail {- width: number;- height: number;- url: string;-}--// Design response structure-export interface Design {- id: string;- title?: string;- owner: TeamUserSummary;- urls: DesignLinks;- created_at: number; // Unix timestamp- updated_at: number; // Unix timestamp- thumbnail?: Thumbnail;- page_count?: number;-}--// API response wrapper-export interface CanvaDesignResponse {- design: Design;-}--// Folder information-export interface Folder {- id: string;- name: string;- created_at: number; // Unix timestamp- updated_at: number; // Unix timestamp- thumbnail?: Thumbnail;-}--// Folder response wrapper-export interface FolderResponse {- folder: Folder;-}--// Asset summary for folder items-export interface AssetSummary {- type: 'image' | 'video';- id: string;- name: string;- tags: string[];- created_at: number; // Unix timestamp- updated_at: number; // Unix timestamp- thumbnail?: Thumbnail;-}--// Folder item summary - polymorphic structure-export interface FolderItemSummary {- type: 'folder' | 'design' | 'image';- folder?: Folder; // Present when type is 'folder'- design?: DesignSummary; // Present when type is 'design'- image?: AssetSummary; // Present when type is 'image'-}--// List folder items response-export interface ListFolderItemsResponse {- items: FolderItemSummary[];+import { AppConnectionValueForAuthProperty, PieceAuth, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { canvaClient } from './client';++const MAX_DROPDOWN_PAGES = 5;+const DROPDOWN_PAGE_SIZE = 100;++const canvaAuthDescription = `+To connect Canva, follow these steps:+1. Go to https://www.canva.com/developers/integrations and sign in.+2. Click **Create an integration** and fill in the app name and description.+3. Under **Configure** → **Authentication**, set the redirect URL to the one shown above.+4. Under **Configure** → **Scopes**, enable: \`design:content:read\`, \`design:content:write\`, \`design:meta:read\`, \`asset:read\`, \`asset:write\`, \`folder:read\`, \`folder:write\`, \`profile:read\`.+5. Copy the **Client ID** and **Client secret** and paste them above.+`;++const canvaAuth = PieceAuth.OAuth2({+ description: canvaAuthDescription,+ authUrl: 'https://www.canva.com/api/oauth/authorize',+ tokenUrl: 'https://api.canva.com/rest/v1/oauth/token',+ required: true,+ pkce: true,+ pkceMethod: 'S256',+ scope: [+ 'design:content:read',+ 'design:content:write',+ 'design:meta:read',+ 'asset:read',+ 'asset:write',+ 'folder:read',+ 'folder:write',+ 'profile:read',+ ],+ getConnectionIdentifier: async ({ auth }) => {+ try {+ const body = await canvaClient.request<{ profile?: { display_name?: string } }>({+ token: auth.access_token,+ method: HttpMethod.GET,+ path: '/users/me/profile',+ timeoutMs: 5000,+ });+ return body?.profile?.display_name || undefined;+ } catch {+ return undefined;+ }+ },+ validate: async ({ auth }) => {+ if (!auth.access_token) {+ return { valid: false, error: 'No access token found' };+ }+ try {+ await canvaClient.request<unknown>({ token: auth.access_token, method: HttpMethod.GET, path: '/users/me' });+ return { valid: true };+ } catch (error) {+ const status: unknown = typeof error === 'object' && error !== null ? Reflect.get(error, 'status') : undefined;+ if (status === 401 || status === 403) {+ return { valid: false, error: 'Access token is invalid or expired' };+ }+ return { valid: false, error: 'Failed to validate authentication credentials' };+ }+ },+});++async function listFolderPage({+ token,+ folderId,+ itemTypes,+ continuation,+ limit,+ sortBy,+}: {+ token: string;+ folderId: string;+ itemTypes?: string;continuation?: string;+ limit?: number;+ sortBy?: string;+}): Promise<ListFolderItemsResponse> {+ const queryParams: Record<string, string> = {};+ if (itemTypes) queryParams['item_types'] = itemTypes;+ if (continuation) queryParams['continuation'] = continuation;+ if (limit !== undefined) queryParams['limit'] = String(limit);+ if (sortBy) queryParams['sort_by'] = sortBy;+ const body = await canvaClient.request<ListFolderItemsResponse>({+ token,+ method: HttpMethod.GET,+ path: `/folders/${encodeURIComponent(folderId)}/items`,+ queryParams,+ });+ return { items: body?.items ?? [], continuation: body?.continuation };+}++async function collectFolderItems({ token, folderId, itemTypes }: { token: string; folderId: string; itemTypes: string }): Promise<{ items: FolderItemSummary[]; truncated: boolean }> {+ const collected: FolderItemSummary[] = [];+ let continuation: string | undefined;+ for (let page = 0; page < MAX_DROPDOWN_PAGES; page++) {+ const result = await listFolderPage({ token, folderId, itemTypes, continuation, limit: DROPDOWN_PAGE_SIZE });+ collected.push(...result.items);+ continuation = result.continuation;+ if (!continuation) {+ return { items: collected, truncated: false };+ }+ }+ return { items: collected, truncated: true };+}++async function fetchUserDesigns({ auth, query }: { auth: CanvaAuthValue; query?: string }): Promise<DropdownOptionList> {+ const options: Array<{ label: string; value: string }> = [];+ let continuation: string | undefined;+ for (let page = 0; page < MAX_DROPDOWN_PAGES; page++) {+ const queryParams: Record<string, string> = { limit: String(DROPDOWN_PAGE_SIZE) };+ const term = query?.trim();+ if (term) {+ queryParams['query'] = term;+ } else {+ queryParams['sort_by'] = 'modified_descending';+ }+ if (continuation) queryParams['continuation'] = continuation;+ const body = await canvaClient.request<ListDesignsResponse>({+ token: auth.access_token,+ method: HttpMethod.GET,+ path: '/designs',+ queryParams,+ });+ options.push(...(body?.items ?? []).map((design) => ({ label: design.title || `Design ${design.id}`, value: design.id })));+ continuation = body?.continuation;+ if (!continuation) {+ return { options, truncated: false };+ }+ }+ return { options, truncated: true };+}++async function fetchUserAssets({ auth }: { auth: CanvaAuthValue }): Promise<DropdownOptionList> {+ const seen = new Set<string>();+ const options: Array<{ label: string; value: string }> = [];+ let truncated = false;+ for (const folderId of ['root', 'uploads']) {+ const result = await collectFolderItems({ token: auth.access_token, folderId, itemTypes: 'image' });+ truncated = truncated || result.truncated;+ for (const item of result.items) {+ const id = item.image?.id;+ if (id && !seen.has(id)) {+ seen.add(id);+ options.push({ label: item.image?.name || `Asset ${id}`, value: id });+ }+ }+ }+ return { options, truncated };+}++async function fetchUserFolders({ auth }: { auth: CanvaAuthValue }): Promise<DropdownOptionList> {+ const options = [+ { label: 'Projects (top level)', value: 'root' },+ { label: 'Uploads', value: 'uploads' },+ ];+ let truncated = false;+ for (const parent of ['root', 'uploads']) {+ const result = await collectFolderItems({ token: auth.access_token, folderId: parent, itemTypes: 'folder' });+ truncated = truncated || result.truncated;+ for (const item of result.items) {+ if (item.folder?.id) {+ options.push({ label: item.folder.name || `Folder ${item.folder.id}`, value: item.folder.id });+ }+ }+ }+ return { options, truncated };+}++function dropdownState({ result }: { result: DropdownOptionList }) {+ return {+ disabled: false,+ options: result.options,+ placeholder: result.truncated ? 'Showing the first items only. Use a custom ID for others.' : undefined,+ };+}++function dropdownError({ error, what }: { error: unknown; what: string }) {+ const reason = error instanceof Error ? error.message : String(error);+ return {+ disabled: true,+ placeholder: `Could not load ${what}: ${reason}`.slice(0, 200),+ options: [],+ };+}++function flattenFolderItem(item: FolderItemSummary): FlatFolderItem {+ if (item.type === 'folder' && item.folder) {+ return {+ type: 'folder',+ id: item.folder.id,+ name: item.folder.name,+ created_at: item.folder.created_at,+ updated_at: item.folder.updated_at,+ thumbnail_url: item.folder.thumbnail?.url ?? null,+ edit_url: null,+ view_url: null,+ tags: [],+ };+ }+ if (item.type === 'design' && item.design) {+ return {+ type: 'design',+ id: item.design.id,+ name: item.design.title ?? null,+ created_at: item.design.created_at,+ updated_at: item.design.updated_at,+ thumbnail_url: item.design.thumbnail?.url ?? null,+ edit_url: item.design.urls?.edit_url ?? null,+ view_url: item.design.urls?.view_url ?? null,+ tags: [],+ };+ }+ if (item.type === 'image' && item.image) {+ return {+ type: 'image',+ id: item.image.id,+ name: item.image.name,+ created_at: item.image.created_at,+ updated_at: item.image.updated_at,+ thumbnail_url: item.image.thumbnail?.url ?? null,+ edit_url: null,+ view_url: null,+ tags: item.image.tags ?? [],+ };+ }+ const other = item.brand_template;+ return {+ type: item.type,+ id: other?.id ?? '',+ name: other?.title ?? null,+ created_at: other?.created_at ?? null,+ updated_at: other?.updated_at ?? null,+ thumbnail_url: other?.thumbnail?.url ?? null,+ edit_url: null,+ view_url: other?.view_url ?? null,+ tags: [],+ };+}++function parsePageNumbers(pages: unknown[] | undefined): number[] | undefined {+ if (!pages || pages.length === 0) {+ return undefined;+ }+ return pages.map((raw) => {+ const value = typeof raw === 'number' ? raw : Number(String(raw).trim());+ if (!Number.isInteger(value) || value < 1) {+ throw new Error(`Page numbers must be whole numbers starting at 1. "${String(raw)}" is not valid.`);+ }+ return value;+ });+}++function base64Utf8(value: string): string {+ return Buffer.from(value, 'utf8').toString('base64');+}++async function fetchJob<J extends { id: string; status: string }>({ token, kind, jobId }: { token: string; kind: JobKind; jobId: string }): Promise<J> {+ const body = await canvaClient.request<{ job: J }>({+ token,+ method: HttpMethod.GET,+ path: `${JOB_PATHS[kind].path}/${encodeURIComponent(jobId)}`,+ });+ return body.job;+}++async function settleJob<J extends { id: string; status: string; error?: JobError }>({+ token,+ kind,+ initial,+ timeoutSeconds,+ failOnTimeout,+ statusAction,+}: {+ statusAction?: string;+ token: string;+ kind: JobKind;+ initial: J;+ timeoutSeconds: number;+ failOnTimeout: boolean;+}): Promise<J> {+ const { job, timedOut } = await canvaClient.waitForJob<J>({+ initial,+ timeoutSeconds,+ jobLabel: JOB_PATHS[kind].label,+ statusAction,+ fetchJob: (jobId) => fetchJob<J>({ token, kind, jobId }),+ });+ if (job.status === 'failed') {+ throw canvaClient.jobFailureError({ jobLabel: JOB_PATHS[kind].label, jobId: job.id, error: job.error });+ }+ if (timedOut && failOnTimeout) {+ throw canvaClient.jobTimeoutError({ jobLabel: JOB_PATHS[kind].label, jobId: job.id, timeoutSeconds });+ }+ return job;}-// Asset upload metadata for header-export interface AssetUploadMetadata {- name_base64: string; // Asset name encoded in Base64, max 50 chars unencoded-}--// Asset upload error-export interface AssetUploadError {- code: 'file_too_big' | 'import_failed' | 'fetch_failed';- message: string;-}--export interface ImportError {- code: 'file_too_big' | 'import_failed';- message: string;-}--export interface ImportStatus {- state: 'failed' | 'in_progress' | 'success';- error?: ImportError;-}--// Asset information-export interface Asset {- type: 'image' | 'video';- id: string;- name: string;- tags: string[];- created_at: number; // Unix timestamp- updated_at: number; // Unix timestamp- thumbnail?: Thumbnail;- import_status?: ImportStatus; // deprecated-}--// Asset upload job-export interface AssetUploadJob {- id: string;- status: 'failed' | 'in_progress' | 'success';- error?: AssetUploadError;- asset?: Asset;-}--// Asset upload response-export interface AssetUploadResponse {- job: AssetUploadJob;-}--// Asset response wrapper-export interface AssetResponse {- asset: Asset;-}--// Design import metadata for header-export interface DesignImportMetadata {- title_base64: string; // Design title encoded in Base64, max 50 chars unencoded- mime_type?: string; // Optional MIME type-}--// Design summary for import results-export interface DesignSummary {- id: string;- title?: string;- url?: string;- urls: DesignLinks;- created_at: number; // Unix timestamp- updated_at: number; // Unix timestamp- thumbnail?: Thumbnail;- page_count?: number;-}--// Design import job result-export interface DesignImportJobResult {- designs: DesignSummary[]; // Usually contains one item, may be split for large files-}--// Design import error-export interface DesignImportError {- code: 'design_creation_throttled' | 'design_import_throttled' | 'duplicate_import' | 'internal_error' | 'invalid_file' | 'fetch_failed';- message: string;-}--// Design import job-export interface DesignImportJob {- id: string;- status: 'failed' | 'in_progress' | 'success';- result?: DesignImportJobResult;- error?: DesignImportError;-}--// Design import response-export interface DesignImportResponse {- job: DesignImportJob;-}--// Export format structure-export interface ExportFormat {- type: 'pdf' | 'jpg' | 'png' | 'gif' | 'pptx' | 'mp4';- quality?: number | string; // Required for jpg (1-100) and mp4 (e.g., 'horizontal_1080p')- pages?: number[]; // Specific pages to export- export_quality?: 'regular' | 'pro'; // Export quality level- size?: 'a4' | 'a3' | 'letter' | 'legal'; // PDF paper size (for Canva Docs)- height?: number; // For jpg, png, gif (40-25000)- width?: number; // For jpg, png, gif (40-25000)- lossless?: boolean; // PNG compression (default true)- transparent_background?: boolean; // PNG transparent background (Pro feature)- as_single_image?: boolean; // PNG multi-page merge (default false)-}--// Export error-export interface ExportError {- code: 'license_required' | 'approval_required' | 'internal_failure';- message: string;-}--// Export job-export interface ExportJob {- id: string;- status: 'failed' | 'in_progress' | 'success';- urls?: string[]; // Download URLs, expire after 24 hours- error?: ExportError;-}--// Export request-export interface ExportRequest {- design_id: string;- format: ExportFormat;-}--// Export response-export interface ExportResponse {- job: ExportJob;-}+function clampWaitSeconds(value: number | undefined): number {+ if (value === undefined || value === null || Number.isNaN(value)) {+ return DEFAULT_WAIT_SECONDS;+ }+ return Math.min(Math.max(Math.round(value), 5), MAX_WAIT_SECONDS);+}++function flattenJob({ kind, job }: { kind: JobKind; job: AnyJob }): FlatJob {+ return {+ job_type: kind,+ job_id: job.id,+ status: job.status,+ urls: 'urls' in job && job.urls ? job.urls : [],+ asset: 'asset' in job && job.asset ? job.asset : null,+ designs: 'result' in job && job.result ? job.result.designs : [],+ error_code: job.error?.code ?? null,+ error_message: job.error?.message ?? null,+ };+}++function designDropdown({ displayName, description }: { displayName: string; description: string }) {+ return Property.Dropdown({+ auth: canvaAuth,+ displayName,+ description,+ required: true,+ refreshers: [],+ refreshOnSearch: true,+ options: async ({ auth }, { searchValue }) => {+ if (!auth) {+ return { disabled: true, placeholder: 'Connect your Canva account first', options: [] };+ }+ try {+ return dropdownState({ result: await fetchUserDesigns({ auth, query: searchValue }) });+ } catch (error) {+ return dropdownError({ error, what: 'designs' });+ }+ },+ });+}++function assetDropdown({ displayName, description, required }: { displayName: string; description: string; required: boolean }) {+ return Property.Dropdown({+ auth: canvaAuth,+ displayName,+ description,+ required,+ refreshers: [],+ options: async ({ auth }) => {+ if (!auth) {+ return { disabled: true, placeholder: 'Connect your Canva account first', options: [] };+ }+ try {+ return dropdownState({ result: await fetchUserAssets({ auth }) });+ } catch (error) {+ return dropdownError({ error, what: 'assets' });+ }+ },+ });+}++function folderDropdown({ displayName, description }: { displayName: string; description: string }) {+ return Property.Dropdown({+ auth: canvaAuth,+ displayName,+ description,+ required: true,+ refreshers: [],+ options: async ({ auth }) => {+ if (!auth) {+ return { disabled: true, placeholder: 'Connect your Canva account first', options: [] };+ }+ try {+ return dropdownState({ result: await fetchUserFolders({ auth }) });+ } catch (error) {+ return dropdownError({ error, what: 'folders' });+ }+ },+ });+}++function waitProps() {+ return {+ waitForCompletion: Property.Checkbox({+ displayName: 'Wait for Completion',+ description: 'Wait until Canva finishes the job and return the result. Turn off to return the job ID right away and check it later with Get Job Status.',+ required: false,+ defaultValue: true,+ }),+ maxWaitSeconds: Property.Number({+ displayName: 'Maximum Wait (seconds)',+ description: `How long to wait for Canva before failing with the job ID (5-${MAX_WAIT_SECONDS}, default ${DEFAULT_WAIT_SECONDS}).`,+ required: false,+ defaultValue: DEFAULT_WAIT_SECONDS,+ }),+ };+}++export const canvaProps = { designDropdown, assetDropdown, folderDropdown, waitProps };-// File format validation-export const SUPPORTED_IMAGE_FORMATS = ['jpg', 'jpeg', 'png', 'heic', 'gif', 'tiff', 'webp'];-export const SUPPORTED_VIDEO_FORMATS = ['m4v', 'mkv', 'mp4', 'mpeg', 'mov', 'webm'];+export const canvaCommon = {+ baseUrl: canvaClient.baseUrl,+ fetchUserDesigns,+ fetchUserAssets,+ fetchUserFolders,+ listFolderPage,+ flattenFolderItem,+ dropdownState,+ dropdownError,+ parsePageNumbers,+ base64Utf8,+ fetchJob,+ settleJob,+ clampWaitSeconds,+ flattenJob,+};-// Supported import file formats with MIME types-export const SUPPORTED_IMPORT_FORMATS = [- { ext: 'ai', mime: 'application/illustrator', name: 'Adobe Illustrator' },- { ext: 'psd', mime: 'image/vnd.adobe.photoshop', name: 'Adobe Photoshop' },- { ext: 'key', mime: 'application/vnd.apple.keynote', name: 'Apple Keynote' },- { ext: 'numbers', mime: 'application/vnd.apple.numbers', name: 'Apple Numbers' },- { ext: 'pages', mime: 'application/vnd.apple.pages', name: 'Apple Pages' },- { ext: 'xls', mime: 'application/vnd.ms-excel', name: 'Microsoft Excel (pre 2007)' },- { ext: 'xlsx', mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', name: 'Microsoft Excel' },- { ext: 'ppt', mime: 'application/vnd.ms-powerpoint', name: 'Microsoft PowerPoint (pre 2007)' },- { ext: 'pptx', mime: 'application/vnd.openxmlformats-officedocument.presentationml.presentation', name: 'Microsoft PowerPoint' },- { ext: 'doc', mime: 'application/msword', name: 'Microsoft Word (pre 2007)' },- { ext: 'docx', mime: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', name: 'Microsoft Word' },- { ext: 'odg', mime: 'application/vnd.oasis.opendocument.graphics', name: 'OpenOffice Draw' },- { ext: 'odp', mime: 'application/vnd.oasis.opendocument.presentation', name: 'OpenOffice Presentation' },- { ext: 'ods', mime: 'application/vnd.oasis.opendocument.spreadsheet', name: 'OpenOffice Sheets' },- { ext: 'odt', mime: 'application/vnd.oasis.opendocument.text', name: 'OpenOffice Text' },- { ext: 'pdf', mime: 'application/pdf', name: 'PDF' },-];+export { canvaAuth };-// Export format constantsexport const EXPORT_FORMATS = [{ value: 'pdf', label: 'PDF' },{ value: 'jpg', label: 'JPEG' },@@ -280,92 +441,148 @@ export const MP4_QUALITIES = [{ value: 'vertical_4k', label: 'Vertical 4K' },];-// File size limits+export const SUPPORTED_IMAGE_FORMATS = ['jpg', 'jpeg', 'png', 'heic', 'gif', 'tiff', 'webp'];+export const SUPPORTED_VIDEO_FORMATS = ['m4v', 'mkv', 'mp4', 'mpeg', 'mov', 'webm'];++export const SUPPORTED_IMPORT_FORMATS = [+ { ext: 'ai', mime: 'application/illustrator', name: 'Adobe Illustrator' },+ { ext: 'psd', mime: 'image/vnd.adobe.photoshop', name: 'Adobe Photoshop' },+ { ext: 'key', mime: 'application/vnd.apple.keynote', name: 'Apple Keynote' },+ { ext: 'numbers', mime: 'application/vnd.apple.numbers', name: 'Apple Numbers' },+ { ext: 'pages', mime: 'application/vnd.apple.pages', name: 'Apple Pages' },+ { ext: 'xls', mime: 'application/vnd.ms-excel', name: 'Microsoft Excel (pre 2007)' },+ { ext: 'xlsx', mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', name: 'Microsoft Excel' },+ { ext: 'ppt', mime: 'application/vnd.ms-powerpoint', name: 'Microsoft PowerPoint (pre 2007)' },+ { ext: 'pptx', mime: 'application/vnd.openxmlformats-officedocument.presentationml.presentation', name: 'Microsoft PowerPoint' },+ { ext: 'doc', mime: 'application/msword', name: 'Microsoft Word (pre 2007)' },+ { ext: 'docx', mime: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', name: 'Microsoft Word' },+ { ext: 'odg', mime: 'application/vnd.oasis.opendocument.graphics', name: 'OpenOffice Draw' },+ { ext: 'odp', mime: 'application/vnd.oasis.opendocument.presentation', name: 'OpenOffice Presentation' },+ { ext: 'ods', mime: 'application/vnd.oasis.opendocument.spreadsheet', name: 'OpenOffice Sheets' },+ { ext: 'odt', mime: 'application/vnd.oasis.opendocument.text', name: 'OpenOffice Text' },+ { ext: 'pdf', mime: 'application/pdf', name: 'PDF' },+];++export const JOB_PATHS: Record<JobKind, { path: string; label: string }> = {+ export: { path: '/exports', label: 'export' },+ asset_upload: { path: '/asset-uploads', label: 'asset upload' },+ url_asset_upload: { path: '/url-asset-uploads', label: 'asset upload from URL' },+ import: { path: '/imports', label: 'design import' },+ url_import: { path: '/url-imports', label: 'design import from URL' },+};+export const MAX_IMAGE_SIZE_MB = 50;export const MAX_VIDEO_SIZE_MB = 500;export const MAX_ASSET_NAME_LENGTH = 50;export const MAX_DESIGN_TITLE_LENGTH = 50;--// Export dimension limitsexport const MIN_EXPORT_DIMENSION = 40;export const MAX_EXPORT_DIMENSION = 25000;+export const DEFAULT_WAIT_SECONDS = 120;+export const MAX_WAIT_SECONDS = 300;+export const AI_WAIT_SECONDS = 25;-// Dynamic field helpers-export async function fetchUserDesigns(auth: canvaAuthType, query?: string): Promise<Array<{ label: string; value: string }>> {- try {- const params = new URLSearchParams();- if (query && query.trim()) {- params.append('query', query.trim());- }- params.append('sort_by', 'modified_descending');+export type CanvaAuthValue = AppConnectionValueForAuthProperty<typeof canvaAuth>;- const response = await fetch(`${canvaCommon.baseUrl}/designs?${params.toString()}`, {- headers: {- 'Authorization': `Bearer ${auth.access_token}`,- },- });+export type DropdownOptionList = { options: Array<{ label: string; value: string }>; truncated: boolean };- if (!response.ok) return [];+export type Thumbnail = { width: number; height: number; url: string };- const data = await response.json();- return (data.items || []).map((design: any) => ({- label: design.title || `Design ${design.id}`,- value: design.id,- }));- } catch (error) {- console.error('Failed to fetch designs:', error);- return [];- }-}+export type DesignLinks = { edit_url: string; view_url: string };-export async function fetchUserAssets(auth: canvaAuthType, assetType?: 'image' | 'video'): Promise<Array<{ label: string; value: string }>> {- try {- const response = await fetch(`${canvaCommon.baseUrl}/folders/root/items?item_types=image`, {- headers: {- 'Authorization': `Bearer ${auth.access_token}`,- },- });+export type Design = {+ id: string;+ title?: string;+ owner?: { user_id: string; team_id: string };+ urls: DesignLinks;+ created_at: number;+ updated_at: number;+ thumbnail?: Thumbnail;+ page_count?: number;+ design_types?: string[];+};- if (!response.ok) return [];-- const data = await response.json();- return (data.items || [])- .filter((item: any) => item.type === 'image' && (!assetType || item.image?.type === assetType))- .map((item: any) => ({- label: item.image?.name || `Asset ${item.image?.id}`,- value: item.image?.id || '',- }))- .filter((item: any) => item.value);- } catch (error) {- console.error('Failed to fetch assets:', error);- return [];- }-}+export type CanvaDesignResponse = { design: Design };-export async function fetchUserFolders(auth: canvaAuthType): Promise<Array<{ label: string; value: string }>> {- try {- const folders = [{ label: 'Root (Top Level)', value: 'root' }];-- const response = await fetch(`${canvaCommon.baseUrl}/folders/root/items?item_types=folder`, {- headers: {- 'Authorization': `Bearer ${auth.access_token}`,- },- });+export type ListDesignsResponse = { items: Design[]; continuation?: string };- if (!response.ok) return folders;-- const data = await response.json();- const subfolders = (data.items || [])- .filter((item: any) => item.type === 'folder')- .map((item: any) => ({- label: item.folder?.name || `Folder ${item.folder?.id}`,- value: item.folder?.id || '',- }))- .filter((item: any) => item.value);-- return [...folders, ...subfolders];- } catch (error) {- console.error('Failed to fetch folders:', error);- return [{ label: 'Root (Top Level)', value: 'root' }];- }-}\ No newline at end of file+export type Folder = { id: string; name: string; created_at: number; updated_at: number; thumbnail?: Thumbnail };++export type FolderResponse = { folder: Folder };++export type AssetSummary = {+ type: 'image' | 'video';+ id: string;+ name: string;+ tags: string[];+ created_at: number;+ updated_at: number;+ thumbnail?: Thumbnail;+};++export type FolderItemSummary = {+ type: string;+ folder?: Folder;+ design?: Design;+ image?: AssetSummary;+ brand_template?: { id: string; title?: string; view_url?: string; created_at?: number; updated_at?: number; thumbnail?: Thumbnail };+};++export type ListFolderItemsResponse = { items: FolderItemSummary[]; continuation?: string };++export type FlatFolderItem = {+ type: string;+ id: string;+ name: string | null;+ created_at: number | null;+ updated_at: number | null;+ thumbnail_url: string | null;+ edit_url: string | null;+ view_url: string | null;+ tags: string[];+};++export type Asset = AssetSummary & {+ owner?: { user_id: string; team_id: string };+ metadata?: { type: string; width?: number; height?: number; duration?: number; smart_tags?: string[] };+ import_status?: { state: 'failed' | 'in_progress' | 'success'; error?: { code: string; message: string } };+};++export type AssetResponse = { asset: Asset };++export type JobError = { code: string; message: string };++export type AssetUploadJob = { id: string; status: JobStatus; error?: JobError; asset?: Asset };++export type DesignImportJob = { id: string; status: JobStatus; result?: { designs: Design[] }; error?: JobError };++export type ExportJob = { id: string; status: JobStatus; urls?: string[]; error?: JobError };++export type JobStatus = 'failed' | 'in_progress' | 'success';++export type ExportFormat = {+ type: string;+ quality?: number | string;+ pages?: number[];+ export_quality?: string;+ size?: string;+ height?: number;+ width?: number;+ lossless?: boolean;+ transparent_background?: boolean;+ as_single_image?: boolean;+};++export type JobKind = 'export' | 'asset_upload' | 'url_asset_upload' | 'import' | 'url_import';++export type AnyJob = ExportJob | AssetUploadJob | DesignImportJob;++export type FlatJob = {+ job_type: JobKind;+ job_id: string;+ status: string;+ urls: string[];+ asset: Asset | null;+ designs: Design[];+ error_code: string | null;+ error_message: string | null;+};diff --git a/packages/pieces/community/canva/src/lib/common/output-schemas.ts b/packages/pieces/community/canva/src/lib/common/output-schemas.tsnew file mode 100644index 00000000000..64cea9c31ac--- /dev/null+++ b/packages/pieces/community/canva/src/lib/common/output-schemas.ts@@ -0,0 +1,309 @@+import { OutputSchema, OutputSchemaField } from '@activepieces/pieces-framework';++const thumbnailFields: OutputSchemaField[] = [+ { key: 'url', label: 'Thumbnail URL', format: 'image' },+ { key: 'width', label: 'Thumbnail Width', format: 'number' },+ { key: 'height', label: 'Thumbnail Height', format: 'number' },+];++const designFields: OutputSchemaField[] = [+ { key: 'id', label: 'Design ID' },+ { key: 'title', label: 'Title' },+ {+ key: 'urls',+ label: 'Links',+ children: [+ { key: 'edit_url', label: 'Edit URL', format: 'url' },+ { key: 'view_url', label: 'View URL', format: 'url' },+ ],+ },+ {+ key: 'owner',+ label: 'Owner',+ children: [+ { key: 'user_id', label: 'User ID' },+ { key: 'team_id', label: 'Team ID' },+ ],+ },+ { key: 'page_count', label: 'Page Count', format: 'number' },+ { key: 'design_types', label: 'Design Types' },+ { key: 'created_at', label: 'Created At (Unix seconds)', format: 'number' },+ { key: 'updated_at', label: 'Updated At (Unix seconds)', format: 'number' },+ { key: 'thumbnail', label: 'Thumbnail', children: thumbnailFields },+];++const assetFields: OutputSchemaField[] = [+ { key: 'id', label: 'Asset ID' },+ { key: 'name', label: 'Name' },+ { key: 'type', label: 'Type' },+ { key: 'tags', label: 'Tags' },+ {+ key: 'import_status',+ label: 'Import Status',+ children: [+ { key: 'state', label: 'State' },+ { key: 'error', label: 'Error', children: [{ key: 'code', label: 'Error Code' }, { key: 'message', label: 'Error Message' }] },+ ],+ },+ { key: 'created_at', label: 'Created At (Unix seconds)', format: 'number' },+ { key: 'updated_at', label: 'Updated At (Unix seconds)', format: 'number' },+ { key: 'thumbnail', label: 'Thumbnail', children: thumbnailFields },+];++const folderFields: OutputSchemaField[] = [+ { key: 'id', label: 'Folder ID' },+ { key: 'name', label: 'Name' },+ { key: 'created_at', label: 'Created At (Unix seconds)', format: 'number' },+ { key: 'updated_at', label: 'Updated At (Unix seconds)', format: 'number' },+ { key: 'thumbnail', label: 'Thumbnail', children: thumbnailFields },+];++const flatFolderItemFields: OutputSchemaField[] = [+ { key: 'type', label: 'Item Type' },+ { key: 'id', label: 'Item ID' },+ { key: 'name', label: 'Name' },+ { key: 'created_at', label: 'Created At (Unix seconds)', format: 'number' },+ { key: 'updated_at', label: 'Updated At (Unix seconds)', format: 'number' },+ { key: 'thumbnail_url', label: 'Thumbnail URL', format: 'image' },+ { key: 'edit_url', label: 'Edit URL', format: 'url' },+ { key: 'view_url', label: 'View URL', format: 'url' },+ { key: 'tags', label: 'Tags' },+];++const flatJobFields: OutputSchemaField[] = [+ { key: 'job_type', label: 'Job Type' },+ { key: 'job_id', label: 'Job ID' },+ { key: 'status', label: 'Status' },+ { key: 'urls', label: 'Download URLs (valid 24 hours)' },+ { key: 'asset', label: 'Asset', children: assetFields },+ { key: 'designs', label: 'Designs', labelKey: 'title', listItems: designFields },+ { key: 'error_code', label: 'Error Code' },+ { key: 'error_message', label: 'Error Message' },+];++const designResultSchema: OutputSchema = {+ fields: [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'design', label: 'Design', children: designFields },+ { key: 'message', label: 'Message' },+ ],+};++const findDesignSchema: OutputSchema = {+ fields: [+ { key: 'designs', label: 'Designs', labelKey: 'title', listItems: designFields },+ { key: 'total_found', label: 'Designs Returned', format: 'number' },+ { key: 'has_more', label: 'Has More', format: 'boolean' },+ { key: 'continuation_token', label: 'Continuation Token' },+ { key: 'search_query', label: 'Search Query' },+ { key: 'ownership_filter', label: 'Ownership Filter' },+ { key: 'sort_order', label: 'Sort Order' },+ { key: 'design_ids', label: 'Design IDs' },+ { key: 'design_titles', label: 'Design Titles' },+ ],+};++const getFolderSchema: OutputSchema = {+ fields: [+ { key: 'folder', label: 'Folder', children: folderFields },+ { key: 'folder_id', label: 'Folder ID' },+ { key: 'folder_name', label: 'Folder Name' },+ { key: 'created_date', label: 'Created', format: 'datetime' },+ { key: 'updated_date', label: 'Updated', format: 'datetime' },+ { key: 'has_thumbnail', label: 'Has Thumbnail', format: 'boolean' },+ { key: 'thumbnail_url', label: 'Thumbnail URL', format: 'image' },+ ],+};++const getAssetSchema: OutputSchema = {+ fields: [+ { key: 'asset', label: 'Asset', children: assetFields },+ { key: 'asset_id', label: 'Asset ID' },+ { key: 'asset_name', label: 'Asset Name' },+ { key: 'asset_type', label: 'Asset Type' },+ { key: 'tags_count', label: 'Tag Count', format: 'number' },+ { key: 'tags_list', label: 'Tags (comma separated)' },+ { key: 'created_date', label: 'Created', format: 'datetime' },+ { key: 'updated_date', label: 'Updated', format: 'datetime' },+ { key: 'has_thumbnail', label: 'Has Thumbnail', format: 'boolean' },+ { key: 'thumbnail_url', label: 'Thumbnail URL', format: 'image' },+ { key: 'thumbnail_dimensions', label: 'Thumbnail Dimensions' },+ { key: 'is_imported_successfully', label: 'Imported Successfully', format: 'boolean' },+ { key: 'import_status_state', label: 'Import Status' },+ { key: 'import_error_message', label: 'Import Error Message' },+ ],+};++const moveFolderItemSchema: OutputSchema = {+ fields: [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'moved_item_id', label: 'Moved Item ID' },+ { key: 'destination_folder_id', label: 'Destination Folder ID' },+ { key: 'message', label: 'Message' },+ ],+};++const uploadAssetSchema: OutputSchema = {+ fields: [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'asset', label: 'Asset', children: assetFields },+ {+ key: 'job',+ label: 'Job',+ children: [{ key: 'id', label: 'Job ID' }, { key: 'status', label: 'Status' }, { key: 'asset', label: 'Asset', children: assetFields }],+ },+ {+ key: 'file_info',+ label: 'File Info',+ children: [+ { key: 'name', label: 'File Name' },+ { key: 'size_mb', label: 'Size (MB)', format: 'number' },+ { key: 'type', label: 'Asset Type' },+ { key: 'format', label: 'Format' },+ ],+ },+ { key: 'message', label: 'Message' },+ ],+};++const importDesignSchema: OutputSchema = {+ fields: [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'designs', label: 'Imported Designs', labelKey: 'title', listItems: designFields },+ {+ key: 'job',+ label: 'Job',+ children: [+ { key: 'id', label: 'Job ID' },+ { key: 'status', label: 'Status' },+ { key: 'result', label: 'Result', children: [{ key: 'designs', label: 'Designs', labelKey: 'title', listItems: designFields }] },+ ],+ },+ {+ key: 'file_info',+ label: 'File Info',+ children: [+ { key: 'title', label: 'Title' },+ { key: 'size_mb', label: 'Size (MB)', format: 'number' },+ { key: 'format', label: 'Format' },+ { key: 'extension', label: 'Extension' },+ { key: 'mime_type', label: 'MIME Type' },+ ],+ },+ { key: 'message', label: 'Message' },+ ],+};++const exportDesignSchema: OutputSchema = {+ fields: [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'download_urls', label: 'Download URLs (valid 24 hours)' },+ {+ key: 'job',+ label: 'Job',+ children: [{ key: 'id', label: 'Job ID' }, { key: 'status', label: 'Status' }, { key: 'urls', label: 'Download URLs' }],+ },+ {+ key: 'export_info',+ label: 'Export Info',+ children: [+ { key: 'design_id', label: 'Design ID' },+ { key: 'format', label: 'Format' },+ { key: 'quality', label: 'Quality' },+ { key: 'pages', label: 'Pages' },+ { key: 'dimensions', label: 'Dimensions' },+ ],+ },+ { key: 'message', label: 'Message' },+ ],+};++const listFolderItemsSchema: OutputSchema = {+ fields: [+ { key: 'items', label: 'Items', labelKey: 'name', listItems: flatFolderItemFields },+ { key: 'has_more', label: 'Has More', format: 'boolean' },+ { key: 'continuation', label: 'Continuation Token' },+ ],+};++const folderResultSchema: OutputSchema = {+ fields: [{ key: 'folder', label: 'Folder', children: folderFields }],+};++const jobSchema: OutputSchema = { fields: flatJobFields };++const aiListDesignsSchema: OutputSchema = {+ fields: [+ { key: 'designs', label: 'Designs', labelKey: 'title', listItems: designFields },+ { key: 'has_more', label: 'Has More', format: 'boolean' },+ { key: 'continuation', label: 'Continuation Token' },+ ],+};++const aiDesignSchema: OutputSchema = {+ fields: [{ key: 'design', label: 'Design', children: designFields }],+};++const aiAssetSchema: OutputSchema = {+ fields: [{ key: 'asset', label: 'Asset', children: assetFields }],+};++const aiDeleteAssetSchema: OutputSchema = {+ fields: [+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ { key: 'asset_id', label: 'Asset ID' },+ ],+};++const aiDesignPagesSchema: OutputSchema = {+ fields: [+ {+ key: 'pages',+ label: 'Pages',+ labelKey: 'page_number',+ listItems: [+ { key: 'page_number', label: 'Page Number', format: 'number' },+ { key: 'id', label: 'Page ID' },+ { key: 'design_type', label: 'Design Type' },+ { key: 'width', label: 'Width (px)', format: 'number' },+ { key: 'height', label: 'Height (px)', format: 'number' },+ { key: 'thumbnail_url', label: 'Thumbnail URL', format: 'image' },+ ],+ },+ ],+};++const aiExportFormatsSchema: OutputSchema = {+ fields: [+ {+ key: 'formats',+ label: 'Formats',+ labelKey: 'format',+ listItems: [+ { key: 'format', label: 'Format' },+ { key: 'all_pages', label: 'Supported By All Pages', format: 'boolean' },+ { key: 'page_numbers', label: 'Supported Page Numbers' },+ ],+ },+ ],+};++export const canvaOutputSchemas = {+ designResult: designResultSchema,+ findDesign: findDesignSchema,+ getFolder: getFolderSchema,+ getAsset: getAssetSchema,+ moveFolderItem: moveFolderItemSchema,+ uploadAsset: uploadAssetSchema,+ importDesign: importDesignSchema,+ exportDesign: exportDesignSchema,+ listFolderItems: listFolderItemsSchema,+ folderResult: folderResultSchema,+ job: jobSchema,+ aiListDesigns: aiListDesignsSchema,+ aiDesign: aiDesignSchema,+ aiAsset: aiAssetSchema,+ aiDeleteAsset: aiDeleteAssetSchema,+ aiDesignPages: aiDesignPagesSchema,+ aiExportFormats: aiExportFormatsSchema,+};diff --git a/packages/pieces/community/canva/test/canva.test.ts b/packages/pieces/community/canva/test/canva.test.tsnew file mode 100644index 00000000000..5d5378a3d69--- /dev/null+++ b/packages/pieces/community/canva/test/canva.test.ts@@ -0,0 +1,322 @@+import { httpClient, HttpError, HttpMethod } from '@activepieces/pieces-common';+import { createMockActionContext, InputPropertyMap } from '@activepieces/pieces-framework';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { canva } from '../src/index';+import { canvaClient } from '../src/lib/common/client';+import { exportDesign } from '../src/lib/actions/export-design';+import { findDesign } from '../src/lib/actions/find-design';+import { uploadAsset } from '../src/lib/actions/upload-asset';+import { moveFolderItem } from '../src/lib/actions/move-folder-item';+import { getJobStatus } from '../src/lib/actions/get-job-status';+import { canvaExportDesignAi } from '../src/lib/actions/ai/export-design';+import { canvaUpdateAssetAi } from '../src/lib/actions/ai/update-asset';+import { canvaDeleteAssetAi } from '../src/lib/actions/ai/delete-asset';+import { canvaCreateDesignAi } from '../src/lib/actions/ai/create-design';+import { canvaGetExportFormatsAi } from '../src/lib/actions/ai/get-export-formats';+import { canvaImportDesignFromUrlAi } from '../src/lib/actions/ai/import-design-from-url';++const AUTH = { access_token: 'tok', type: 'OAUTH2' };++function run({ action, propsValue }: { action: { run: unknown }; propsValue: Record<string, unknown> }): Promise<unknown> {+ const base = createMockActionContext<InputPropertyMap>({ propsValue: {} });+ const runFn = action.run;+ if (typeof runFn !== 'function') {+ throw new Error('action has no run');+ }+ return Promise.resolve(Reflect.apply(runFn, action, [{ ...base, propsValue, auth: AUTH }]));+}++function mockResponses(bodies: unknown[]) {+ const spy = vi.spyOn(httpClient, 'sendRequest');+ for (const body of bodies) {+ if (body instanceof HttpError) {+ spy.mockRejectedValueOnce(body);+ } else {+ spy.mockResolvedValueOnce({ status: 200, headers: {}, body });+ }+ }+ return spy;+}++function noSleep() {+ return vi.spyOn(canvaClient, 'sleep').mockResolvedValue(undefined);+}++afterEach(() => {+ vi.restoreAllMocks();+});++describe('piece metadata', () => {+ const actions = Object.values(canva.actions());++ it('has 13 human and 17 ai actions and no both', () => {+ const count = (a: string) => actions.filter((x) => (x.audience ?? 'both') === a).length;+ expect(count('human')).toBe(13);+ expect(count('ai')).toBe(17);+ expect(count('both')).toBe(0);+ });++ it('gives every action except custom api call an outputSchema and a classification', () => {+ for (const action of actions) {+ if (action.name === 'custom_api_call') continue;+ expect(action.outputSchema, action.name).toBeDefined();+ expect(action.classification, action.name).toBeDefined();+ }+ });++ it('classifies export as READ and delete asset as DESTRUCTIVE', () => {+ expect(exportDesign.classification).toBe('READ');+ expect(canvaExportDesignAi.classification).toBe('READ');+ expect(canvaDeleteAssetAi.classification).toBe('DESTRUCTIVE');+ });++ it('lists every top-level and nested key the human actions return in their outputSchema', () => {+ const expected: Record<string, string[]> = {+ export_design: ['success', 'job', 'job.urls', 'download_urls', 'export_info', 'export_info.format', 'export_info.dimensions', 'message'],+ upload_asset: ['success', 'job', 'job.asset', 'asset', 'asset.import_status', 'file_info', 'file_info.size_mb', 'file_info.format', 'message'],+ import_design: ['success', 'job', 'job.result', 'designs', 'designs.design_types', 'file_info', 'file_info.mime_type', 'message'],+ get_design: ['success', 'design', 'design.design_types', 'message'],+ create_design: ['success', 'design', 'message'],+ find_design: ['designs', 'total_found', 'has_more', 'continuation_token', 'search_query', 'ownership_filter', 'sort_order', 'design_ids', 'design_titles'],+ get_folder: ['folder', 'folder_id', 'folder_name', 'created_date', 'updated_date', 'has_thumbnail', 'thumbnail_url'],+ get_asset: ['asset', 'asset_id', 'asset_name', 'asset_type', 'tags_count', 'tags_list', 'created_date', 'updated_date', 'has_thumbnail', 'thumbnail_url', 'thumbnail_dimensions', 'is_imported_successfully', 'import_status_state', 'import_error_message'],+ move_folder_item: ['success', 'message', 'moved_item_id', 'destination_folder_id'],+ create_folder: ['folder'],+ list_folder_items: ['items', 'has_more', 'continuation'],+ };+ const actions = canva.actions();+ for (const [name, keys] of Object.entries(expected)) {+ const fields = actions[name]?.outputSchema?.fields ?? [];+ const paths = fields.flatMap((field) => [field.key, ...[...(field.children ?? []), ...(field.listItems ?? [])].map((child) => `${field.key}.${child.key}`)]);+ for (const key of keys) {+ expect(paths, `${name} ${key}`).toContain(key);+ }+ }+ });++ it('requires engine 0.86.4', () => {+ expect(canva.minimumSupportedRelease).toBe('0.86.4');+ });++ it('never points an agent at a removed or missing action name', () => {+ const names = new Set(actions.map((a) => a.name));+ const text = JSON.stringify(actions.map((a) => [a.description, a.aiMetadata?.description]));+ for (const ref of text.match(/canva_[a-z_]+/g) ?? []) {+ expect(names.has(ref), ref).toBe(true);+ }+ expect(text).not.toContain('Get Design Export Job');+ expect(text).not.toContain('Get Asset Upload Job" action');+ });+});++describe('find design', () => {+ it('sends limit, sort and continuation to the API', async () => {+ const spy = mockResponses([{ items: [{ id: 'D1', title: 'One' }], continuation: 'next' }]);+ const out = await run({ action: findDesign, propsValue: { query: ' cats ', sort_by: 'relevance', limit: 5, ownership: 'owned', continuation: 'c0' } });+ const req = spy.mock.calls[0][0];+ expect(req.url).toBe('https://api.canva.com/rest/v1/designs');+ expect(req.method).toBe(HttpMethod.GET);+ expect(req.queryParams).toEqual({ query: 'cats', sort_by: 'relevance', limit: '5', ownership: 'owned', continuation: 'c0' });+ expect(req.headers?.['Authorization']).toBe('Bearer tok');+ expect(out).toMatchObject({ total_found: 1, has_more: true, continuation_token: 'next', design_ids: ['D1'] });+ });++ it('rejects an out-of-range limit before calling Canva', async () => {+ const spy = mockResponses([]);+ await expect(run({ action: findDesign, propsValue: { limit: 500 } })).rejects.toThrow('between 1 and 100');+ expect(spy).not.toHaveBeenCalled();+ });+});++describe('export design (human)', () => {+ it('polls until success and returns the download urls', async () => {+ noSleep();+ const spy = mockResponses([+ { job: { id: 'E1', status: 'in_progress' } },+ { job: { id: 'E1', status: 'in_progress' } },+ { job: { id: 'E1', status: 'success', urls: ['https://x/1.png'] } },+ ]);+ const out = await run({ action: exportDesign, propsValue: { designId: 'D1', exportFormat: 'jpg', pages: ['1', 2] } });+ expect(spy.mock.calls[0][0].body).toEqual({ design_id: 'D1', format: { type: 'jpg', quality: 80, pages: [1, 2] } });+ expect(spy.mock.calls[1][0].url).toBe('https://api.canva.com/rest/v1/exports/E1');+ expect(out).toMatchObject({ download_urls: ['https://x/1.png'], job: { status: 'success' } });+ });++ it('fails with the job id when the deadline passes', async () => {+ noSleep();+ mockResponses(Array.from({ length: 200 }, () => ({ job: { id: 'E2', status: 'in_progress' } })));+ await expect(run({ action: exportDesign, propsValue: { designId: 'D1', exportFormat: 'pdf', maxWaitSeconds: 5 } })).rejects.toThrow(/E2.*Get Job Status/);+ });++ it('fails with Canva\'s reason when the job fails', async () => {+ noSleep();+ mockResponses([{ job: { id: 'E3', status: 'failed', error: { code: 'license_required', message: 'Buy it' } } }]);+ await expect(run({ action: exportDesign, propsValue: { designId: 'D1', exportFormat: 'pdf' } })).rejects.toThrow(/Buy it \(license_required\)/);+ });++ it('keeps the job id and http details when a status poll fails', async () => {+ noSleep();+ mockResponses([+ { job: { id: 'E6', status: 'in_progress' } },+ new HttpError({}, { status: 429, responseBody: { code: 'too_many_requests', message: 'Slow down' } }),+ ]);+ const error: unknown = await run({ action: exportDesign, propsValue: { designId: 'D1', exportFormat: 'pdf' } }).catch((e: unknown) => e);+ const message = String(Reflect.get(Object(error), 'message'));+ expect(message).toContain('job E6');+ expect(message).toContain('Get Job Status');+ expect(message).toContain('rate limit');+ expect(Reflect.get(Object(error), 'status')).toBe(429);+ expect(Reflect.get(Object(error), 'code')).toBe('too_many_requests');+ });++ it('returns the job immediately when waiting is off', async () => {+ const spy = mockResponses([{ job: { id: 'E4', status: 'in_progress' } }]);+ const out = await run({ action: exportDesign, propsValue: { designId: 'D1', exportFormat: 'pdf', waitForCompletion: false } });+ expect(spy).toHaveBeenCalledTimes(1);+ expect(out).toMatchObject({ job: { id: 'E4', status: 'in_progress' } });+ });++ it('rejects non-numeric pages', async () => {+ await expect(run({ action: exportDesign, propsValue: { designId: 'D1', exportFormat: 'pdf', pages: ['abc'] } })).rejects.toThrow('whole numbers');+ });+});++describe('tls', () => {+ it('passes a verifying undici dispatcher on every Canva request', async () => {+ const spy = mockResponses([{ design: { id: 'D1' } }]);+ await run({ action: canvaCreateDesignAi, propsValue: { presetName: 'doc' } });+ const dispatcher: unknown = spy.mock.calls[0][1]?.dispatcher;+ const { Agent } = await import('undici');+ expect(dispatcher).toBeInstanceOf(Agent);+ expect(await canvaClient.verifiedTls()).toBe(dispatcher);+ });+});++describe('errors', () => {+ it('keeps Canva\'s message and exposes responseBody but no body field', async () => {+ mockResponses([new HttpError({}, { status: 404, responseBody: { code: 'design_not_found', message: 'Design not found' } })]);+ const error: unknown = await run({ action: canvaGetExportFormatsAi, propsValue: { designId: 'X' } }).catch((e: unknown) => e);+ expect(error).toBeInstanceOf(Error);+ expect(String(Reflect.get(Object(error), 'message'))).toContain('Canva says: Design not found (design_not_found)');+ expect(Reflect.get(Object(error), 'responseBody')).toEqual({ code: 'design_not_found', message: 'Design not found' });+ expect(Reflect.has(Object(error), 'body')).toBe(false);+ });+});++describe('upload asset (human)', () => {+ it('sends octet-stream with base64 name metadata and waits for the asset', async () => {+ noSleep();+ const spy = mockResponses([+ { job: { id: 'U1', status: 'in_progress' } },+ { job: { id: 'U1', status: 'success', asset: { id: 'A1', name: 'Logo' } } },+ ]);+ const out = await run({ action: uploadAsset, propsValue: { file: { filename: 'logo.png', base64: Buffer.from('abc').toString('base64') }, assetName: 'Logo' } });+ const req = spy.mock.calls[0][0];+ expect(req.url).toBe('https://api.canva.com/rest/v1/asset-uploads');+ expect(req.headers?.['Content-Type']).toBe('application/octet-stream');+ expect(req.headers?.['Asset-Upload-Metadata']).toBe(JSON.stringify({ name_base64: Buffer.from('Logo').toString('base64') }));+ expect(req.redactBodyInErrors).toBe(true);+ expect(spy.mock.calls[1][0].url).toBe('https://api.canva.com/rest/v1/asset-uploads/U1');+ expect(out).toMatchObject({ asset: { id: 'A1' } });+ });+});++describe('move folder item', () => {+ it('handles the 204 response', async () => {+ const spy = mockResponses([undefined]);+ const out = await run({ action: moveFolderItem, propsValue: { to_folder_id: 'F1', item_type: 'design', item_id: 'D1' } });+ expect(spy.mock.calls[0][0].body).toEqual({ to_folder_id: 'F1', item_id: 'D1' });+ expect(out).toMatchObject({ moved_item_id: 'D1', destination_folder_id: 'F1' });+ });+});++describe('get job status', () => {+ it('routes url imports to /url-imports and flattens the result', async () => {+ const spy = mockResponses([{ job: { id: 'J1', status: 'success', result: { designs: [{ id: 'D9' }] } } }]);+ const out = await run({ action: getJobStatus, propsValue: { jobType: 'url_import', jobId: 'J1' } });+ expect(spy.mock.calls[0][0].url).toBe('https://api.canva.com/rest/v1/url-imports/J1');+ expect(out).toMatchObject({ job_type: 'url_import', status: 'success', designs: [{ id: 'D9' }], error_code: null });+ });+});++describe('ai atomics', () => {+ it('export returns in_progress with the job id after the short wait instead of failing', async () => {+ noSleep();+ mockResponses(Array.from({ length: 200 }, () => ({ job: { id: 'E5', status: 'in_progress' } })));+ const out = await run({ action: canvaExportDesignAi, propsValue: { designId: 'D1', format: 'png' } });+ expect(out).toMatchObject({ job_id: 'E5', status: 'in_progress', urls: [] });+ });++ it('export names the job id when a status poll fails', async () => {+ noSleep();+ mockResponses([+ { job: { id: 'E7', status: 'in_progress' } },+ new HttpError({}, { status: 500, responseBody: { code: 'internal_error', message: 'Oops' } }),+ ]);+ await expect(run({ action: canvaExportDesignAi, propsValue: { designId: 'D1', format: 'png' } })).rejects.toThrow(/E7.*the canva_get_export_job tool/);+ });++ it('update asset sends only provided fields and supports clearing tags', async () => {+ const spy = mockResponses([{ asset: { id: 'A1' } }, { asset: { id: 'A1' } }]);+ await run({ action: canvaUpdateAssetAi, propsValue: { assetId: 'A1', tags: ['a', ' b '] } });+ expect(spy.mock.calls[0][0].method).toBe(HttpMethod.PATCH);+ expect(spy.mock.calls[0][0].body).toEqual({ tags: ['a', 'b'] });+ await run({ action: canvaUpdateAssetAi, propsValue: { assetId: 'A1', clearTags: true } });+ expect(spy.mock.calls[1][0].body).toEqual({ tags: [] });+ });++ it('update asset refuses an empty update', async () => {+ await expect(run({ action: canvaUpdateAssetAi, propsValue: { assetId: 'A1' } })).rejects.toThrow('Nothing to update');+ });++ it('delete asset calls DELETE and reports the id', async () => {+ const spy = mockResponses([undefined]);+ const out = await run({ action: canvaDeleteAssetAi, propsValue: { assetId: 'A1' } });+ expect(spy.mock.calls[0][0].method).toBe(HttpMethod.DELETE);+ expect(spy.mock.calls[0][0].url).toBe('https://api.canva.com/rest/v1/assets/A1');+ expect(out).toEqual({ deleted: true, asset_id: 'A1' });+ });++ it('create design builds a custom design body', async () => {+ const spy = mockResponses([{ design: { id: 'D1' } }]);+ await run({ action: canvaCreateDesignAi, propsValue: { width: 800, height: 600, title: ' Hi ' } });+ expect(spy.mock.calls[0][0].body).toEqual({ type: 'type_and_asset', design_type: { type: 'custom', width: 800, height: 600 }, title: 'Hi' });+ });++ it('create design refuses preset plus size', async () => {+ await expect(run({ action: canvaCreateDesignAi, propsValue: { presetName: 'doc', width: 800, height: 600 } })).rejects.toThrow('not both');+ });++ it('export formats flattens page support', async () => {+ mockResponses([{ formats: { pdf: {}, png: { page_numbers: [1, 3] } } }]);+ const out = await run({ action: canvaGetExportFormatsAi, propsValue: { designId: 'D1' } });+ expect(out).toEqual({+ formats: [+ { format: 'pdf', all_pages: true, page_numbers: [] },+ { format: 'png', all_pages: false, page_numbers: [1, 3] },+ ],+ });+ });++ it('import from url posts json to /url-imports', async () => {+ const spy = mockResponses([{ job: { id: 'I1', status: 'success', result: { designs: [{ id: 'D2' }] } } }]);+ await run({ action: canvaImportDesignFromUrlAi, propsValue: { url: 'https://example.com/a.pdf', title: 'Doc' } });+ const req = spy.mock.calls[0][0];+ expect(req.url).toBe('https://api.canva.com/rest/v1/url-imports');+ expect(req.body).toEqual({ title: 'Doc', url: 'https://example.com/a.pdf' });+ expect(req.headers?.['Content-Type']).toBe('application/json');+ });+});++describe('job failure error', () => {+ it('keeps Canva reason and code without a success http status', () => {+ const error = canvaClient.jobFailureError({+ jobLabel: 'asset upload from URL',+ jobId: 'job-1',+ error: { code: 'fetch_failed', message: 'Failed to download file' },+ });+ expect(error.message).toBe('The Canva asset upload from URL job job-1 failed. Canva says: Failed to download file (fetch_failed)');+ expect(error.code).toBe('fetch_failed');+ expect(error.status).toBeUndefined();+ });+});diff --git a/packages/pieces/community/canva/vitest.config.ts b/packages/pieces/community/canva/vitest.config.tsnew file mode 100644index 00000000000..79c97261904--- /dev/null+++ b/packages/pieces/community/canva/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'),+ },+ },+})