Skip to content

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

feat(iloveapi): edit, convert and watermark images and let agents run PDF tools and signatures (#16827)

Odai Ahmad5338b52f4903
diff --git a/bun.lock b/bun.lock
index ae1e457a222..5315f566533 100644
--- a/bun.lock
+++ b/bun.lock
@@ -4595,16 +4595,18 @@
},
"packages/pieces/community/iloveapi": {
"name": "@activepieces/piece-iloveapi",
- "version": "0.0.6",
+ "version": "0.1.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
"form-data": "4.0.6",
+ "undici": "7.29.1",
},
"devDependencies": {
"tslib": "2.6.2",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/image-router": {
diff --git a/docs/install/reference/breaking-changes-unreleased.mdx b/docs/install/reference/breaking-changes-unreleased.mdx
index b4511990dd9..98f930d8bb2 100644
--- a/docs/install/reference/breaking-changes-unreleased.mdx
+++ b/docs/install/reference/breaking-changes-unreleased.mdx
@@ -8,6 +8,18 @@ Entries here move to [Breaking Changes](/install/reference/breaking-changes) aut
## What has changed?
+#### iLoveAPI 0.1.0: Create Signature Request is no longer an agent tool, and triggers need a Webhook Secret
+
+iLoveAPI 0.1.0 changes what an existing step does once it is upgraded to that version. Steps keep running on the version they were built with until you upgrade them.
+
+**Create Signature Request** is no longer offered as a tool to AI agents. It still works as a normal flow step. Agents should use **Send PDF for Signature** instead, which takes the PDFs as URLs. Create Signature Request also checks its input more strictly: a signature element with a missing field, or with an email that matches no signer, used to be skipped and now fails the step.
+
+Every iLoveAPI trigger now has a required **Webhook Secret**, and a delivery whose URL does not carry that secret is ignored without an error.
+
+#### What you need to do
+
+Point any agent that used Create Signature Request at Send PDF for Signature. When you upgrade an iLoveAPI trigger, fill in a Webhook Secret of at least 16 characters, then change the endpoint URL in the iLoveAPI developer dashboard to `<trigger URL>?ap_secret=<secret>`. Until you do, deliveries are dropped and the flow stops running. Check that Create Signature Request steps give every signature element all its fields and use signer emails that match a signer.
+
#### SendIt 0.3.0: two scheduled-post actions leave AI agents, and publishing checks inputs before sending
From SendIt 0.3.0, **Cancel Scheduled Post** and **Trigger Scheduled Post Now** are no longer offered to AI agents and MCP clients. They stay available as flow steps. An agent or MCP client that called them by name no longer finds them.
diff --git a/packages/pieces/community/iloveapi/package.json b/packages/pieces/community/iloveapi/package.json
index a4337c69880..e2b2fc4f307 100644
--- a/packages/pieces/community/iloveapi/package.json
+++ b/packages/pieces/community/iloveapi/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/piece-iloveapi",
- "version": "0.0.6",
+ "version": "0.1.0",
"type": "commonjs",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
@@ -9,14 +9,17 @@
"@activepieces/pieces-framework": "workspace:*",
"form-data": "4.0.6",
"@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/iloveapi/src/i18n/translation.json b/packages/pieces/community/iloveapi/src/i18n/translation.json
index c8e3cf56663..b6e6809ead0 100644
--- a/packages/pieces/community/iloveapi/src/i18n/translation.json
+++ b/packages/pieces/community/iloveapi/src/i18n/translation.json
@@ -16,13 +16,27 @@
"Rotate PDF": "Rotate PDF",
"Extract Text from PDF": "Extract Text from PDF",
"Repair PDF": "Repair PDF",
+ "Convert PDF to PDF/A": "Convert PDF to PDF/A",
+ "Validate PDF/A": "Validate PDF/A",
+ "Compress Image": "Compress Image",
+ "Resize Image": "Resize Image",
+ "Crop Image": "Crop Image",
+ "Convert Image": "Convert Image",
+ "Upscale Image": "Upscale Image",
+ "Remove Image Background": "Remove Image Background",
+ "Watermark Image": "Watermark Image",
+ "Rotate Image": "Rotate Image",
"Create Signature Request": "Create Signature Request",
+ "Send PDF for Signature": "Send PDF for Signature",
+ "List Signature Requests": "List Signature Requests",
"Get Signature Status": "Get Signature Status",
+ "Get Signer Info": "Get Signer Info",
"Send Signer Reminder": "Send Signer Reminder",
"Void Signature": "Void Signature",
"Increase Expiration Days": "Increase Expiration Days",
"Download Signed Files": "Download Signed Files",
"Download Audit Trail": "Download Audit Trail",
+ "Custom API Call": "Custom API Call",
"Reduce the size of a PDF file using iLoveAPI.": "Reduce the size of a PDF file using iLoveAPI.",
"Combine multiple PDF files into a single document, in the order provided.": "Combine multiple PDF files into a single document, in the order provided.",
"Split a PDF by page ranges, fixed page batches, removed pages, or target file size.": "Split a PDF by page ranges, fixed page batches, removed pages, or target file size.",
@@ -38,17 +52,33 @@
"Rotate every page of a PDF by 90, 180, or 270 degrees.": "Rotate every page of a PDF by 90, 180, or 270 degrees.",
"Extract plain or detailed text (with positions and font metadata) from a PDF.": "Extract plain or detailed text (with positions and font metadata) from a PDF.",
"Attempt to fix a damaged or corrupted PDF file.": "Attempt to fix a damaged or corrupted PDF file.",
+ "Convert a PDF into an archival PDF/A document.": "Convert a PDF into an archival PDF/A document.",
+ "Check whether a PDF conforms to a PDF/A level.": "Check whether a PDF conforms to a PDF/A level.",
+ "Reduce the file size of a JPG, PNG, SVG or GIF image.": "Reduce the file size of a JPG, PNG, SVG or GIF image.",
+ "Resize an image by exact pixels or by percentage.": "Resize an image by exact pixels or by percentage.",
+ "Crop an image to a rectangle given in pixels.": "Crop an image to a rectangle given in pixels.",
+ "Convert an image to JPG, PNG, GIF, animated GIF or HEIC.": "Convert an image to JPG, PNG, GIF, animated GIF or HEIC.",
+ "Enlarge an image 2x or 4x with AI upscaling.": "Enlarge an image 2x or 4x with AI upscaling.",
+ "Remove the background from a photo and return a PNG with transparency.": "Remove the background from a photo and return a PNG with transparency.",
+ "Stamp a logo or picture as a watermark on an image.": "Stamp a logo or picture as a watermark on an image.",
+ "Rotate an image by 90, 180 or 270 degrees.": "Rotate an image by 90, 180 or 270 degrees.",
"Send one or more PDF documents for electronic signature, with custom signers and signature placeholders.": "Send one or more PDF documents for electronic signature, with custom signers and signature placeholders.",
+ "Send PDFs (by public URL) to signers by name and email. Signers place their own fields.": "Send PDFs (by public URL) to signers by name and email. Signers place their own fields.",
+ "List the signature requests of this project, one page at a time.": "List the signature requests of this project, one page at a time.",
"Look up the current status of a signature request, including each signer.": "Look up the current status of a signature request, including each signer.",
+ "Look up one signer of a signature request by the signer token.": "Look up one signer of a signature request by the signer token.",
"Email a reminder to signers who have not yet completed the signature. Limited to 2 calls per day.": "Email a reminder to signers who have not yet completed the signature. Limited to 2 calls per day.",
"Cancel an in-progress signature request. The document becomes inaccessible to all signers.": "Cancel an in-progress signature request. The document becomes inaccessible to all signers.",
"Extend the expiration of a signature request by a number of days. Total cannot exceed 130 days from now.": "Extend the expiration of a signature request by a number of days. Total cannot exceed 130 days from now.",
"Download the signed PDF (or ZIP if multiple files). The signature must be in \"completed\" status.": "Download the signed PDF (or ZIP if multiple files). The signature must be in \"completed\" status.",
"Download the audit-trail PDF for a completed signature request. Useful for compliance and dispute resolution.": "Download the audit-trail PDF for a completed signature request. Useful for compliance and dispute resolution.",
+ "Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",
"PDF File": "PDF File",
"Compression Level": "Compression Level",
"Output Filename": "Output Filename",
"Packaged ZIP Filename": "Packaged ZIP Filename",
+ "Processing Region": "Processing Region",
+ "Webhook URL": "Webhook URL",
"PDF Files": "PDF Files",
"Split Mode": "Split Mode",
"Ranges": "Ranges",
@@ -67,7 +97,6 @@
"OCR Languages": "OCR Languages",
"Watermark Mode": "Watermark Mode",
"Text": "Text",
- "Watermark Image": "Watermark Image",
"Pages": "Pages",
"Vertical Position": "Vertical Position",
"Horizontal Position": "Horizontal Position",
@@ -90,6 +119,23 @@
"Font Color": "Font Color",
"Rotation": "Rotation",
"Detailed Output": "Detailed Output",
+ "Conformance Level": "Conformance Level",
+ "Allow Downgrade": "Allow Downgrade",
+ "Image": "Image",
+ "Resize Mode": "Resize Mode",
+ "Width (px)": "Width (px)",
+ "Height (px)": "Height (px)",
+ "Keep Aspect Ratio": "Keep Aspect Ratio",
+ "Percentage": "Percentage",
+ "Do Not Enlarge Smaller Images": "Do Not Enlarge Smaller Images",
+ "X Offset (px)": "X Offset (px)",
+ "Y Offset (px)": "Y Offset (px)",
+ "Target Format": "Target Format",
+ "Scale": "Scale",
+ "Position": "Position",
+ "Width (% of image width)": "Width (% of image width)",
+ "Height (% of image height)": "Height (% of image height)",
+ "Opacity (%)": "Opacity (%)",
"Signers": "Signers",
"Signature Elements": "Signature Elements",
"Brand Name": "Brand Name",
@@ -101,12 +147,28 @@
"Auto Reminders": "Auto Reminders",
"Reminder Frequency (days)": "Reminder Frequency (days)",
"Certified Signature": "Certified Signature",
+ "PDF URLs": "PDF URLs",
+ "Page": "Page",
+ "Per Page": "Per Page",
"Requester Token": "Requester Token",
+ "Signer Token": "Signer Token",
"Additional Days": "Additional Days",
+ "Server": "Server",
"Output File Name": "Output File Name",
+ "Method": "Method",
+ "Headers": "Headers",
+ "Query Parameters": "Query Parameters",
+ "Body Type": "Body Type",
+ "Body": "Body",
+ "Response is Binary": "Response is Binary",
+ "Return Error as Output": "Return Error as Output",
+ "Timeout": "Timeout",
+ "Follow redirects": "Follow redirects",
"PDF file to compress.": "PDF file to compress.",
"Output file name without extension. Use {date}, {n} or {filename} placeholders.": "Output file name without extension. Use {date}, {n} or {filename} placeholders.",
"Name of the ZIP archive when the result contains multiple files. No extension.": "Name of the ZIP archive when the result contains multiple files. No extension.",
+ "Optional. Server region where iLoveAPI processes the files. Leave empty to let iLoveAPI choose (previous behaviour).": "Optional. Server region where iLoveAPI processes the files. Leave empty to let iLoveAPI choose (previous behaviour).",
+ "Optional. Paste the URL of an iLoveAPI \"Task Completed\" or \"Task Failed\" trigger (including ?ap_secret=...) to notify that flow when this task finishes. The URL must also be registered under Webhooks in the iLoveAPI dashboard.": "Optional. Paste the URL of an iLoveAPI \"Task Completed\" or \"Task Failed\" trigger (including ?ap_secret=...) to notify that flow when this task finishes. The URL must also be registered under Webhooks in the iLoveAPI dashboard.",
"List of PDF files to merge. The output preserves the listed order.": "List of PDF files to merge. The output preserves the listed order.",
"Used with mode \"Page Ranges\". Example: \"1-5,7,10-13\". Each range becomes a separate PDF.": "Used with mode \"Page Ranges\". Example: \"1-5,7,10-13\". Each range becomes a separate PDF.",
"Used with mode \"Fixed Range\". Number of pages per output PDF (e.g. 1 splits into one PDF per page).": "Used with mode \"Fixed Range\". Number of pages per output PDF (e.g. 1 splits into one PDF per page).",
@@ -135,6 +197,16 @@
"Alternate horizontal position for left/right pages, like a printed book.": "Alternate horizontal position for left/right pages, like a printed book.",
"Use {n} for current page and {p} for total pages. Example: \"{n} of {p}\".": "Use {n} for current page and {p} for total pages. Example: \"{n} of {p}\".",
"Include positional and font metadata for each text block. Useful for downstream layout-aware parsing.": "Include positional and font metadata for each text block. Useful for downstream layout-aware parsing.",
+ "Allow a lower conformance level when the file cannot reach the chosen one.": "Allow a lower conformance level when the file cannot reach the chosen one.",
+ "Used with \"By pixels\".": "Used with \"By pixels\".",
+ "Used with \"By percentage\". 1 to 1000.": "Used with \"By percentage\". 1 to 1000.",
+ "Distance from the left edge. Default 0.": "Distance from the left edge. Default 0.",
+ "Distance from the top edge. Default 0.": "Distance from the top edge. Default 0.",
+ "JPG or PNG to stamp on the image, for example a logo.": "JPG or PNG to stamp on the image, for example a logo.",
+ "1 to 100. Default 30.": "1 to 100. Default 30.",
+ "0 to 360.": "0 to 360.",
+ "1 (almost invisible) to 100 (solid). Default 100.": "1 (almost invisible) to 100 (solid). Default 100.",
+ "Repeat the watermark across the whole image.": "Repeat the watermark across the whole image.",
"Documents to send for signature.": "Documents to send for signature.",
"People who will receive the document.": "People who will receive the document.",
"Placeholders to drop on each PDF page. Match them to signers by email. If empty, iLovePDF will let signers place fields freely.": "Placeholders to drop on each PDF page. Match them to signers by email. If empty, iLovePDF will let signers place fields freely.",
@@ -146,16 +218,35 @@
"Send reminder emails to signers who have not yet signed.": "Send reminder emails to signers who have not yet signed.",
"Days between auto-reminders. Default 1.": "Days between auto-reminders. Default 1.",
"Apply a certified-signature seal to the final PDF.": "Apply a certified-signature seal to the final PDF.",
+ "Public https URLs of the PDFs to sign (1 to 5).": "Public https URLs of the PDFs to sign (1 to 5).",
+ "1 to 130. Default 120.": "1 to 130. Default 120.",
+ "Page number, starting at 1.": "Page number, starting at 1.",
+ "1 to 100. Default 20.": "1 to 100. Default 20.",
"The \"token_requester\" returned when the signature request was created.": "The \"token_requester\" returned when the signature request was created.",
+ "The signer's \"token_signer\" (or receiver token) from Get Signature Status.": "The signer's \"token_signer\" (or receiver token) from Get Signature Status.",
"The \"token_requester\" of the signature request.": "The \"token_requester\" of the signature request.",
"The \"token_requester\" of the signature request to void.": "The \"token_requester\" of the signature request to void.",
"Number of days to add. Must be between 1 and 130.": "Number of days to add. Must be between 1 and 130.",
"The \"token_requester\" of the completed signature request.": "The \"token_requester\" of the completed signature request.",
- "Name to store the downloaded file under. Defaults to \"signed-{token}.pdf\".": "Name to store the downloaded file under. Defaults to \"signed-{token}.pdf\".",
+ "Optional. The \"server\" value returned by Create Signature Request. When empty, the server is looked up from the signature request.": "Optional. The \"server\" value returned by Create Signature Request. When empty, the server is looked up from the signature request.",
+ "Name to store the downloaded file under. Defaults to \"signed-{token}.pdf\" (\".zip\" when several files were signed).": "Name to store the downloaded file under. Defaults to \"signed-{token}.pdf\" (\".zip\" when several files were signed).",
"Name to store the audit PDF under. Defaults to \"audit-{token}.pdf\".": "Name to store the audit PDF under. Defaults to \"audit-{token}.pdf\".",
+ "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.",
"Extreme (smallest, lower quality)": "Extreme (smallest, lower quality)",
"Recommended (balanced)": "Recommended (balanced)",
"Low (largest, best quality)": "Low (largest, best quality)",
+ "Europe": "Europe",
+ "United States": "United States",
+ "France": "France",
+ "Germany": "Germany",
+ "Poland": "Poland",
+ "India": "India",
+ "Singapore": "Singapore",
"Page Ranges": "Page Ranges",
"Fixed Range (every N pages)": "Fixed Range (every N pages)",
"By File Size": "By File Size",
@@ -166,7 +257,6 @@
"Fit to image": "Fit to image",
"A4": "A4",
"Letter": "Letter",
- "Image": "Image",
"Top": "Top",
"Middle": "Middle",
"Bottom": "Bottom",
@@ -189,6 +279,33 @@
"90° clockwise": "90° clockwise",
"180°": "180°",
"270° (90° counter-clockwise)": "270° (90° counter-clockwise)",
+ "PDF/A-1b": "PDF/A-1b",
+ "PDF/A-1a": "PDF/A-1a",
+ "PDF/A-2b (recommended)": "PDF/A-2b (recommended)",
+ "PDF/A-2u": "PDF/A-2u",
+ "PDF/A-2a": "PDF/A-2a",
+ "PDF/A-3b": "PDF/A-3b",
+ "PDF/A-3u": "PDF/A-3u",
+ "PDF/A-3a": "PDF/A-3a",
+ "By pixels": "By pixels",
+ "By percentage": "By percentage",
+ "JPG": "JPG",
+ "PNG": "PNG",
+ "GIF": "GIF",
+ "Animated GIF": "Animated GIF",
+ "HEIC": "HEIC",
+ "2x": "2x",
+ "4x": "4x",
+ "North": "North",
+ "NorthEast": "NorthEast",
+ "NorthWest": "NorthWest",
+ "CenterEast": "CenterEast",
+ "CenterWest": "CenterWest",
+ "East": "East",
+ "West": "West",
+ "South": "South",
+ "SouthEast": "SouthEast",
+ "SouthWest": "SouthWest",
"English (US)": "English (US)",
"Spanish": "Spanish",
"French": "French",
@@ -197,6 +314,14 @@
"Portuguese": "Portuguese",
"Catalan": "Catalan",
"Dutch": "Dutch",
+ "GET": "GET",
+ "POST": "POST",
+ "PATCH": "PATCH",
+ "PUT": "PUT",
+ "DELETE": "DELETE",
+ "HEAD": "HEAD",
+ "Request": "Request",
+ "Data to send": "Data to send",
"Task Completed": "Task Completed",
"Task Failed": "Task Failed",
"Signature Created": "Signature Created",
@@ -220,24 +345,25 @@
"Fires when an individual signer completes their signature.": "Fires when an individual signer completes their signature.",
"Fires when an individual signer declines to sign.": "Fires when an individual signer declines to sign.",
"Markdown": "Markdown",
+ "Webhook Secret": "Webhook Secret",
"Filter by Tool": "Filter by Tool",
- "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Paste the URL below into **Endpoint URL**:\n\n```text\n{{webhookUrl}}\n```\n\n4. In **Events**, select **Task Completed (task.completed)**.\n5. Save the webhook. The trigger will fire on every matching event.\n": "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Paste the URL below into **Endpoint URL**:\n\n```text\n{{webhookUrl}}\n```\n\n4. In **Events**, select **Task Completed (task.completed)**.\n5. Save the webhook. The trigger will fire on every matching event.\n",
+ "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Make up a long random secret (at least 16 letters and digits) and enter it in **Webhook Secret** below.\n4. Paste the URL below into **Endpoint URL** and replace `YOUR_SECRET` with that secret:\n\n```text\n{{webhookUrl}}?ap_secret=YOUR_SECRET\n```\n\n5. In **Events**, select **Task Completed (task.completed)**.\n6. Save the webhook. Deliveries without the right secret are ign": "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Make up a long random secret (at least 16 letters and digits) and enter it in **Webhook Secret** below.\n4. Paste the URL below into **Endpoint URL** and replace `YOUR_SECRET` with that secret:\n\n```text\n{{webhookUrl}}?ap_secret=YOUR_SECRET\n```\n\n5. In **Events**, select **Task Completed (task.completed)**.\n6. Save the webhook. Deliveries without the right secret are ignored, and a repeated delivery of the same event fires the flow only once.\n",
+ "A random secret of at least 16 characters. Add it to the endpoint URL as ?ap_secret=... (see the steps above).": "A random secret of at least 16 characters. Add it to the endpoint URL as ?ap_secret=... (see the steps above).",
"Optional. When set, only fires for tasks using one of the selected tools. Leave empty to fire for every tool.": "Optional. When set, only fires for tasks using one of the selected tools. Leave empty to fire for every tool.",
- "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Paste the URL below into **Endpoint URL**:\n\n```text\n{{webhookUrl}}\n```\n\n4. In **Events**, select **Task Failed (task.failed)**.\n5. Save the webhook. The trigger will fire on every matching event.\n": "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Paste the URL below into **Endpoint URL**:\n\n```text\n{{webhookUrl}}\n```\n\n4. In **Events**, select **Task Failed (task.failed)**.\n5. Save the webhook. The trigger will fire on every matching event.\n",
- "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Paste the URL below into **Endpoint URL**:\n\n```text\n{{webhookUrl}}\n```\n\n4. In **Events**, select **Signature Created (signature.created)**.\n5. Save the webhook. The trigger will fire on every matching event.\n": "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Paste the URL below into **Endpoint URL**:\n\n```text\n{{webhookUrl}}\n```\n\n4. In **Events**, select **Signature Created (signature.created)**.\n5. Save the webhook. The trigger will fire on every matching event.\n",
- "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Paste the URL below into **Endpoint URL**:\n\n```text\n{{webhookUrl}}\n```\n\n4. In **Events**, select **Signature Sent (signature.sent)**.\n5. Save the webhook. The trigger will fire on every matching event.\n": "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Paste the URL below into **Endpoint URL**:\n\n```text\n{{webhookUrl}}\n```\n\n4. In **Events**, select **Signature Sent (signature.sent)**.\n5. Save the webhook. The trigger will fire on every matching event.\n",
- "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Paste the URL below into **Endpoint URL**:\n\n```text\n{{webhookUrl}}\n```\n\n4. In **Events**, select **Signature Completed (signature.completed)**.\n5. Save the webhook. The trigger will fire on every matching event.\n": "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Paste the URL below into **Endpoint URL**:\n\n```text\n{{webhookUrl}}\n```\n\n4. In **Events**, select **Signature Completed (signature.completed)**.\n5. Save the webhook. The trigger will fire on every matching event.\n",
- "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Paste the URL below into **Endpoint URL**:\n\n```text\n{{webhookUrl}}\n```\n\n4. In **Events**, select **Signature Declined (signature.declined)**.\n5. Save the webhook. The trigger will fire on every matching event.\n": "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Paste the URL below into **Endpoint URL**:\n\n```text\n{{webhookUrl}}\n```\n\n4. In **Events**, select **Signature Declined (signature.declined)**.\n5. Save the webhook. The trigger will fire on every matching event.\n",
- "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Paste the URL below into **Endpoint URL**:\n\n```text\n{{webhookUrl}}\n```\n\n4. In **Events**, select **Signature Expired (signature.expired)**.\n5. Save the webhook. The trigger will fire on every matching event.\n": "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Paste the URL below into **Endpoint URL**:\n\n```text\n{{webhookUrl}}\n```\n\n4. In **Events**, select **Signature Expired (signature.expired)**.\n5. Save the webhook. The trigger will fire on every matching event.\n",
- "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Paste the URL below into **Endpoint URL**:\n\n```text\n{{webhookUrl}}\n```\n\n4. In **Events**, select **Signature Voided (signature.voided)**.\n5. Save the webhook. The trigger will fire on every matching event.\n": "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Paste the URL below into **Endpoint URL**:\n\n```text\n{{webhookUrl}}\n```\n\n4. In **Events**, select **Signature Voided (signature.voided)**.\n5. Save the webhook. The trigger will fire on every matching event.\n",
- "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Paste the URL below into **Endpoint URL**:\n\n```text\n{{webhookUrl}}\n```\n\n4. In **Events**, select **Signer Viewed Document (signature.signer.viewed)**.\n5. Save the webhook. The trigger will fire on every matching event.\n": "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Paste the URL below into **Endpoint URL**:\n\n```text\n{{webhookUrl}}\n```\n\n4. In **Events**, select **Signer Viewed Document (signature.signer.viewed)**.\n5. Save the webhook. The trigger will fire on every matching event.\n",
- "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Paste the URL below into **Endpoint URL**:\n\n```text\n{{webhookUrl}}\n```\n\n4. In **Events**, select **Signer Signed (signature.signer.completed)**.\n5. Save the webhook. The trigger will fire on every matching event.\n": "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Paste the URL below into **Endpoint URL**:\n\n```text\n{{webhookUrl}}\n```\n\n4. In **Events**, select **Signer Signed (signature.signer.completed)**.\n5. Save the webhook. The trigger will fire on every matching event.\n",
- "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Paste the URL below into **Endpoint URL**:\n\n```text\n{{webhookUrl}}\n```\n\n4. In **Events**, select **Signer Declined (signature.signer.declined)**.\n5. Save the webhook. The trigger will fire on every matching event.\n": "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Paste the URL below into **Endpoint URL**:\n\n```text\n{{webhookUrl}}\n```\n\n4. In **Events**, select **Signer Declined (signature.signer.declined)**.\n5. Save the webhook. The trigger will fire on every matching event.\n",
+ "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Make up a long random secret (at least 16 letters and digits) and enter it in **Webhook Secret** below.\n4. Paste the URL below into **Endpoint URL** and replace `YOUR_SECRET` with that secret:\n\n```text\n{{webhookUrl}}?ap_secret=YOUR_SECRET\n```\n\n5. In **Events**, select **Task Failed (task.failed)**.\n6. Save the webhook. Deliveries without the right secret are ignored, ": "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Make up a long random secret (at least 16 letters and digits) and enter it in **Webhook Secret** below.\n4. Paste the URL below into **Endpoint URL** and replace `YOUR_SECRET` with that secret:\n\n```text\n{{webhookUrl}}?ap_secret=YOUR_SECRET\n```\n\n5. In **Events**, select **Task Failed (task.failed)**.\n6. Save the webhook. Deliveries without the right secret are ignored, and a repeated delivery of the same event fires the flow only once.\n",
+ "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Make up a long random secret (at least 16 letters and digits) and enter it in **Webhook Secret** below.\n4. Paste the URL below into **Endpoint URL** and replace `YOUR_SECRET` with that secret:\n\n```text\n{{webhookUrl}}?ap_secret=YOUR_SECRET\n```\n\n5. In **Events**, select **Signature Created (signature.created)**.\n6. Save the webhook. Deliveries without the right secret a": "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Make up a long random secret (at least 16 letters and digits) and enter it in **Webhook Secret** below.\n4. Paste the URL below into **Endpoint URL** and replace `YOUR_SECRET` with that secret:\n\n```text\n{{webhookUrl}}?ap_secret=YOUR_SECRET\n```\n\n5. In **Events**, select **Signature Created (signature.created)**.\n6. Save the webhook. Deliveries without the right secret are ignored, and a repeated delivery of the same event fires the flow only once.\n",
+ "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Make up a long random secret (at least 16 letters and digits) and enter it in **Webhook Secret** below.\n4. Paste the URL below into **Endpoint URL** and replace `YOUR_SECRET` with that secret:\n\n```text\n{{webhookUrl}}?ap_secret=YOUR_SECRET\n```\n\n5. In **Events**, select **Signature Sent (signature.sent)**.\n6. Save the webhook. Deliveries without the right secret are ign": "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Make up a long random secret (at least 16 letters and digits) and enter it in **Webhook Secret** below.\n4. Paste the URL below into **Endpoint URL** and replace `YOUR_SECRET` with that secret:\n\n```text\n{{webhookUrl}}?ap_secret=YOUR_SECRET\n```\n\n5. In **Events**, select **Signature Sent (signature.sent)**.\n6. Save the webhook. Deliveries without the right secret are ignored, and a repeated delivery of the same event fires the flow only once.\n",
+ "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Make up a long random secret (at least 16 letters and digits) and enter it in **Webhook Secret** below.\n4. Paste the URL below into **Endpoint URL** and replace `YOUR_SECRET` with that secret:\n\n```text\n{{webhookUrl}}?ap_secret=YOUR_SECRET\n```\n\n5. In **Events**, select **Signature Completed (signature.completed)**.\n6. Save the webhook. Deliveries without the right secr": "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Make up a long random secret (at least 16 letters and digits) and enter it in **Webhook Secret** below.\n4. Paste the URL below into **Endpoint URL** and replace `YOUR_SECRET` with that secret:\n\n```text\n{{webhookUrl}}?ap_secret=YOUR_SECRET\n```\n\n5. In **Events**, select **Signature Completed (signature.completed)**.\n6. Save the webhook. Deliveries without the right secret are ignored, and a repeated delivery of the same event fires the flow only once.\n",
+ "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Make up a long random secret (at least 16 letters and digits) and enter it in **Webhook Secret** below.\n4. Paste the URL below into **Endpoint URL** and replace `YOUR_SECRET` with that secret:\n\n```text\n{{webhookUrl}}?ap_secret=YOUR_SECRET\n```\n\n5. In **Events**, select **Signature Declined (signature.declined)**.\n6. Save the webhook. Deliveries without the right secret": "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Make up a long random secret (at least 16 letters and digits) and enter it in **Webhook Secret** below.\n4. Paste the URL below into **Endpoint URL** and replace `YOUR_SECRET` with that secret:\n\n```text\n{{webhookUrl}}?ap_secret=YOUR_SECRET\n```\n\n5. In **Events**, select **Signature Declined (signature.declined)**.\n6. Save the webhook. Deliveries without the right secret are ignored, and a repeated delivery of the same event fires the flow only once.\n",
+ "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Make up a long random secret (at least 16 letters and digits) and enter it in **Webhook Secret** below.\n4. Paste the URL below into **Endpoint URL** and replace `YOUR_SECRET` with that secret:\n\n```text\n{{webhookUrl}}?ap_secret=YOUR_SECRET\n```\n\n5. In **Events**, select **Signature Expired (signature.expired)**.\n6. Save the webhook. Deliveries without the right secret a": "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Make up a long random secret (at least 16 letters and digits) and enter it in **Webhook Secret** below.\n4. Paste the URL below into **Endpoint URL** and replace `YOUR_SECRET` with that secret:\n\n```text\n{{webhookUrl}}?ap_secret=YOUR_SECRET\n```\n\n5. In **Events**, select **Signature Expired (signature.expired)**.\n6. Save the webhook. Deliveries without the right secret are ignored, and a repeated delivery of the same event fires the flow only once.\n",
+ "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Make up a long random secret (at least 16 letters and digits) and enter it in **Webhook Secret** below.\n4. Paste the URL below into **Endpoint URL** and replace `YOUR_SECRET` with that secret:\n\n```text\n{{webhookUrl}}?ap_secret=YOUR_SECRET\n```\n\n5. In **Events**, select **Signature Voided (signature.voided)**.\n6. Save the webhook. Deliveries without the right secret are": "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Make up a long random secret (at least 16 letters and digits) and enter it in **Webhook Secret** below.\n4. Paste the URL below into **Endpoint URL** and replace `YOUR_SECRET` with that secret:\n\n```text\n{{webhookUrl}}?ap_secret=YOUR_SECRET\n```\n\n5. In **Events**, select **Signature Voided (signature.voided)**.\n6. Save the webhook. Deliveries without the right secret are ignored, and a repeated delivery of the same event fires the flow only once.\n",
+ "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Make up a long random secret (at least 16 letters and digits) and enter it in **Webhook Secret** below.\n4. Paste the URL below into **Endpoint URL** and replace `YOUR_SECRET` with that secret:\n\n```text\n{{webhookUrl}}?ap_secret=YOUR_SECRET\n```\n\n5. In **Events**, select **Signer Viewed Document (signature.signer.viewed)**.\n6. Save the webhook. Deliveries without the rig": "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Make up a long random secret (at least 16 letters and digits) and enter it in **Webhook Secret** below.\n4. Paste the URL below into **Endpoint URL** and replace `YOUR_SECRET` with that secret:\n\n```text\n{{webhookUrl}}?ap_secret=YOUR_SECRET\n```\n\n5. In **Events**, select **Signer Viewed Document (signature.signer.viewed)**.\n6. Save the webhook. Deliveries without the right secret are ignored, and a repeated delivery of the same event fires the flow only once.\n",
+ "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Make up a long random secret (at least 16 letters and digits) and enter it in **Webhook Secret** below.\n4. Paste the URL below into **Endpoint URL** and replace `YOUR_SECRET` with that secret:\n\n```text\n{{webhookUrl}}?ap_secret=YOUR_SECRET\n```\n\n5. In **Events**, select **Signer Signed (signature.signer.completed)**.\n6. Save the webhook. Deliveries without the right sec": "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Make up a long random secret (at least 16 letters and digits) and enter it in **Webhook Secret** below.\n4. Paste the URL below into **Endpoint URL** and replace `YOUR_SECRET` with that secret:\n\n```text\n{{webhookUrl}}?ap_secret=YOUR_SECRET\n```\n\n5. In **Events**, select **Signer Signed (signature.signer.completed)**.\n6. Save the webhook. Deliveries without the right secret are ignored, and a repeated delivery of the same event fires the flow only once.\n",
+ "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Make up a long random secret (at least 16 letters and digits) and enter it in **Webhook Secret** below.\n4. Paste the URL below into **Endpoint URL** and replace `YOUR_SECRET` with that secret:\n\n```text\n{{webhookUrl}}?ap_secret=YOUR_SECRET\n```\n\n5. In **Events**, select **Signer Declined (signature.signer.declined)**.\n6. Save the webhook. Deliveries without the right se": "\n**How to connect**\n\n1. Sign in to https://developer.ilovepdf.com/ and open your project.\n2. Go to **Webhooks** and click **Add Webhook**.\n3. Make up a long random secret (at least 16 letters and digits) and enter it in **Webhook Secret** below.\n4. Paste the URL below into **Endpoint URL** and replace `YOUR_SECRET` with that secret:\n\n```text\n{{webhookUrl}}?ap_secret=YOUR_SECRET\n```\n\n5. In **Events**, select **Signer Declined (signature.signer.declined)**.\n6. Save the webhook. Deliveries without the right secret are ignored, and a repeated delivery of the same event fires the flow only once.\n",
"JPG/Image to PDF": "JPG/Image to PDF",
"Page Numbers": "Page Numbers",
"Extract Text": "Extract Text",
"PDF/A": "PDF/A",
- "Validate PDF/A": "Validate PDF/A",
"Edit PDF": "Edit PDF",
"Sign PDF": "Sign PDF"
}
\ No newline at end of file
diff --git a/packages/pieces/community/iloveapi/src/index.ts b/packages/pieces/community/iloveapi/src/index.ts
index d06b5132015..20b88b1ad4c 100644
--- a/packages/pieces/community/iloveapi/src/index.ts
+++ b/packages/pieces/community/iloveapi/src/index.ts
@@ -1,5 +1,6 @@
-import { createPiece } from '@activepieces/pieces-framework';
-import { PieceCategory } from '@activepieces/pieces-framework';
+import { createCustomApiCallAction } from '@activepieces/pieces-common';
+import { PieceCategory, createPiece } from '@activepieces/pieces-framework';
+import { iLoveApi } from './lib/common/client';
import { iloveapiAuth } from './lib/common/auth';
import { compressPdfAction } from './lib/actions/compress-pdf';
import { mergePdfAction } from './lib/actions/merge-pdf';
@@ -23,6 +24,19 @@ import { voidSignatureAction } from './lib/actions/void-signature';
import { increaseExpirationDaysAction } from './lib/actions/increase-expiration-days';
import { downloadSignedFilesAction } from './lib/actions/download-signed-files';
import { downloadAuditTrailAction } from './lib/actions/download-audit-trail';
+import { compressImageAction } from './lib/actions/compress-image';
+import { resizeImageAction } from './lib/actions/resize-image';
+import { cropImageAction } from './lib/actions/crop-image';
+import { convertImageAction } from './lib/actions/convert-image';
+import { upscaleImageAction } from './lib/actions/upscale-image';
+import { removeBackgroundImageAction } from './lib/actions/remove-background-image';
+import { rotateImageAction } from './lib/actions/rotate-image';
+import { convertPdfaAction } from './lib/actions/convert-pdf-to-pdfa';
+import { validatePdfaAction } from './lib/actions/validate-pdfa';
+import { createSignatureRequestAiAction } from './lib/actions/create-signature-request-ai';
+import { listSignatureRequestsAction } from './lib/actions/list-signature-requests';
+import { getSignerInfoAction } from './lib/actions/get-signer-info';
+import { watermarkImageAction } from './lib/actions/watermark-image';
import { taskCompletedTrigger } from './lib/triggers/task-completed';
import { taskFailedTrigger } from './lib/triggers/task-failed';
import {
@@ -37,14 +51,16 @@ import {
signerViewedTrigger,
} from './lib/triggers/signature-events';
+const CUSTOM_API_BASE = 'https://api.ilovepdf.com/v1';
+
export const iloveapi = createPiece({
displayName: 'iLoveAPI',
description:
'Compress, merge, split, convert, OCR, watermark, protect and sign PDFs and images using iLovePDF / iLoveIMG / iLoveSign.',
auth: iloveapiAuth,
- minimumSupportedRelease: '0.36.1',
+ minimumSupportedRelease: '0.86.4',
logoUrl: 'https://cdn.activepieces.com/pieces/iloveapi.png',
- authors: ['sanket-a11y'],
+ authors: ['sanket-a11y', 'OdaiAhmed99'],
categories: [PieceCategory.CONTENT_AND_FILES],
actions: [
compressPdfAction,
@@ -62,13 +78,35 @@ export const iloveapi = createPiece({
rotatePdfAction,
extractTextPdfAction,
repairPdfAction,
+ convertPdfaAction,
+ validatePdfaAction,
+ compressImageAction,
+ resizeImageAction,
+ cropImageAction,
+ convertImageAction,
+ upscaleImageAction,
+ removeBackgroundImageAction,
+ watermarkImageAction,
+ rotateImageAction,
createSignatureRequestAction,
+ createSignatureRequestAiAction,
+ listSignatureRequestsAction,
getSignatureStatusAction,
+ getSignerInfoAction,
sendSignerReminderAction,
voidSignatureAction,
increaseExpirationDaysAction,
downloadSignedFilesAction,
downloadAuditTrailAction,
+ createCustomApiCallAction({
+ auth: iloveapiAuth,
+ baseUrl: () => CUSTOM_API_BASE,
+ authMapping: async (auth, propsValue) => {
+ assertCustomApiUrl(propsValue['url']);
+ const token = await iLoveApi.authenticate({ publicKey: auth.secret_text });
+ return { Authorization: `Bearer ${token}` };
+ },
+ }),
],
triggers: [
taskCompletedTrigger,
@@ -84,3 +122,33 @@ export const iloveapi = createPiece({
signerDeclinedTrigger,
],
});
+
+function assertCustomApiUrl(urlProp: unknown): void {
+ const raw = urlProp !== null && typeof urlProp === 'object' ? Reflect.get(urlProp, 'url') : undefined;
+ const value = typeof raw === 'string' ? raw.trim() : '';
+ if (value === '') {
+ throw new Error('URL is required.');
+ }
+ const isAbsolute = /^[a-z][a-z0-9+.-]*:/i.test(value) || value.startsWith('//');
+ const target = isAbsolute ? value : `${CUSTOM_API_BASE}/${value.replace(/^\/+/, '')}`;
+ let parsed: URL;
+ try {
+ parsed = new URL(target);
+ } catch {
+ throw new Error('URL is not valid.');
+ }
+ const base = new URL(CUSTOM_API_BASE);
+ const segments = parsed.pathname.split('/');
+ if (
+ parsed.origin !== base.origin ||
+ parsed.username !== '' ||
+ parsed.password !== '' ||
+ !parsed.pathname.startsWith(`${base.pathname}/`) ||
+ segments.includes('..') ||
+ segments.includes('.') ||
+ /%2e|%2f|%5c|\\/i.test(value)
+ ) {
+ throw new Error(`Custom API Call only sends your iLoveAPI credentials to ${CUSTOM_API_BASE}/...`);
+ }
+}
+
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/compress-image.ts b/packages/pieces/community/iloveapi/src/lib/actions/compress-image.ts
new file mode 100644
index 00000000000..0ae3ddc4a5f
--- /dev/null
+++ b/packages/pieces/community/iloveapi/src/lib/actions/compress-image.ts
@@ -0,0 +1,55 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { iloveapiAuth } from '../common/auth';
+import { fileToUploadInput, regionOf, sharedProps, webhookOf } from '../common/props';
+import { runAndStoreResult } from '../common/runner';
+import { iloveSchemas } from '../common/schemas';
+
+export const compressImageAction = createAction({
+ auth: iloveapiAuth,
+ name: 'compress_image',
+ classification: 'READ',
+ displayName: 'Compress Image',
+ description: 'Reduce the file size of a JPG, PNG, SVG or GIF image.',
+ audience: 'both',
+ outputSchema: iloveSchemas.toolResult,
+ aiMetadata: {
+ description:
+ 'Shrink an image file (JPG, PNG, SVG, GIF) with iLoveIMG and store the smaller copy as a new file. Spends iLoveAPI credits on every run and returns a new file each time.',
+ idempotent: false,
+ },
+ props: {
+ file: Property.File({
+ displayName: 'Image',
+ required: true,
+ }),
+ compression_level: Property.StaticDropdown({
+ displayName: 'Compression Level',
+ required: false,
+ defaultValue: 'recommended',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Extreme (smallest, lower quality)', value: 'extreme' },
+ { label: 'Recommended (balanced)', value: 'recommended' },
+ { label: 'Low (largest, best quality)', value: 'low' },
+ ],
+ },
+ }),
+ ...sharedProps,
+ },
+ async run(context) {
+ const { file, output_filename, packaged_filename } = context.propsValue;
+ const options = { compression_level: context.propsValue.compression_level ?? 'recommended' };
+ return await runAndStoreResult({
+ auth: context.auth.secret_text,
+ region: regionOf(context.propsValue.region),
+ webhook: webhookOf(context.propsValue.webhook_url),
+ files: context.files,
+ tool: 'compressimage',
+ uploads: [fileToUploadInput({ file: file, label: 'Image' })],
+ options,
+ output_filename,
+ packaged_filename,
+ });
+ },
+});
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/compress-pdf.ts b/packages/pieces/community/iloveapi/src/lib/actions/compress-pdf.ts
index a325d5a22dd..bdb68444ee2 100644
--- a/packages/pieces/community/iloveapi/src/lib/actions/compress-pdf.ts
+++ b/packages/pieces/community/iloveapi/src/lib/actions/compress-pdf.ts
@@ -1,6 +1,7 @@
import { Property, createAction } from '@activepieces/pieces-framework';
import { iloveapiAuth } from '../common/auth';
-import { fileToUploadInput, sharedProps } from '../common/props';
+import { iloveSchemas } from '../common/schemas';
+import { fileToUploadInput, regionOf, sharedProps, webhookOf } from '../common/props';
import { runAndStoreResult } from '../common/runner';
export const compressPdfAction = createAction({
@@ -10,6 +11,7 @@ export const compressPdfAction = createAction({
displayName: 'Compress PDF',
description: 'Reduce the size of a PDF file using iLoveAPI.',
audience: 'both',
+ outputSchema: iloveSchemas.toolResult,
aiMetadata: {
description:
'Shrink a PDF file size, choosing a compression level: "extreme" for the smallest file at lower quality, "recommended" for a balanced result (default), or "low" for the largest file at best quality. Each run produces a new compressed file.',
@@ -42,9 +44,11 @@ export const compressPdfAction = createAction({
return await runAndStoreResult({
auth: context.auth.secret_text,
+ region: regionOf(context.propsValue.region),
+ webhook: webhookOf(context.propsValue.webhook_url),
files: context.files,
tool: 'compress',
- uploads: [fileToUploadInput(file)],
+ uploads: [fileToUploadInput({ file: file })],
options: {
compression_level: compression_level ?? 'recommended',
},
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/convert-image.ts b/packages/pieces/community/iloveapi/src/lib/actions/convert-image.ts
new file mode 100644
index 00000000000..5f482eed5c9
--- /dev/null
+++ b/packages/pieces/community/iloveapi/src/lib/actions/convert-image.ts
@@ -0,0 +1,62 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { iloveapiAuth } from '../common/auth';
+import { fileToUploadInput, regionOf, sharedProps, webhookOf } from '../common/props';
+import { runAndStoreResult } from '../common/runner';
+import { iloveSchemas } from '../common/schemas';
+
+export const convertImageAction = createAction({
+ auth: iloveapiAuth,
+ name: 'convert_image',
+ classification: 'READ',
+ displayName: 'Convert Image',
+ description: 'Convert an image to JPG, PNG, GIF, animated GIF or HEIC.',
+ audience: 'both',
+ outputSchema: iloveSchemas.toolResult,
+ aiMetadata: {
+ description:
+ 'Convert an image to another format with iLoveIMG: jpg, png, gif, gif_animation or heic. Each run creates a new file and spends credits.',
+ idempotent: false,
+ },
+ props: {
+ file: Property.File({
+ displayName: 'Image',
+ required: true,
+ }),
+ to: Property.StaticDropdown({
+ displayName: 'Target Format',
+ required: true,
+ defaultValue: 'jpg',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'JPG', value: 'jpg' },
+ { label: 'PNG', value: 'png' },
+ { label: 'GIF', value: 'gif' },
+ { label: 'Animated GIF', value: 'gif_animation' },
+ { label: 'HEIC', value: 'heic' },
+ ],
+ },
+ }),
+ ...sharedProps,
+ },
+ async run(context) {
+ const { file, to, output_filename, packaged_filename } = context.propsValue;
+ if (!FORMATS.includes(String(to))) {
+ throw new Error(`Target Format must be one of: ${FORMATS.join(', ')}.`);
+ }
+
+ return await runAndStoreResult({
+ auth: context.auth.secret_text,
+ region: regionOf(context.propsValue.region),
+ webhook: webhookOf(context.propsValue.webhook_url),
+ files: context.files,
+ tool: 'convertimage',
+ uploads: [fileToUploadInput({ file: file, label: 'Image' })],
+ options: { to },
+ output_filename,
+ packaged_filename,
+ });
+ },
+});
+
+const FORMATS = ['jpg', 'png', 'gif', 'gif_animation', 'heic'];
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/convert-pdf-to-pdfa.ts b/packages/pieces/community/iloveapi/src/lib/actions/convert-pdf-to-pdfa.ts
new file mode 100644
index 00000000000..0b31e0e50c6
--- /dev/null
+++ b/packages/pieces/community/iloveapi/src/lib/actions/convert-pdf-to-pdfa.ts
@@ -0,0 +1,60 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { iloveapiAuth } from '../common/auth';
+import { CONFORMANCE_OPTIONS, fileToUploadInput, regionOf, sharedProps, webhookOf } from '../common/props';
+import { runAndStoreResult } from '../common/runner';
+import { iloveSchemas } from '../common/schemas';
+
+export const convertPdfaAction = createAction({
+ auth: iloveapiAuth,
+ name: 'convert_pdf_to_pdfa',
+ classification: 'READ',
+ displayName: 'Convert PDF to PDF/A',
+ description: 'Convert a PDF into an archival PDF/A document.',
+ audience: 'both',
+ outputSchema: iloveSchemas.toolResult,
+ aiMetadata: {
+ description:
+ 'Convert a PDF into PDF/A (ISO archival format) at the chosen conformance level and store the result as a new file. Use Validate PDF/A to check an existing file instead. Spends credits on every run.',
+ idempotent: false,
+ },
+ props: {
+ file: Property.File({
+ displayName: 'PDF File',
+ required: true,
+ }),
+ conformance: Property.StaticDropdown({
+ displayName: 'Conformance Level',
+ required: false,
+ defaultValue: 'pdfa-2b',
+ options: {
+ disabled: false,
+ options: CONFORMANCE_OPTIONS,
+ },
+ }),
+ allow_downgrade: Property.Checkbox({
+ displayName: 'Allow Downgrade',
+ description: 'Allow a lower conformance level when the file cannot reach the chosen one.',
+ required: false,
+ defaultValue: true,
+ }),
+ ...sharedProps,
+ },
+ async run(context) {
+ const { file, output_filename, packaged_filename } = context.propsValue;
+ const options = {
+ conformance: context.propsValue.conformance ?? 'pdfa-2b',
+ allow_downgrade: context.propsValue.allow_downgrade ?? true,
+ };
+ return await runAndStoreResult({
+ auth: context.auth.secret_text,
+ region: regionOf(context.propsValue.region),
+ webhook: webhookOf(context.propsValue.webhook_url),
+ files: context.files,
+ tool: 'pdfa',
+ uploads: [fileToUploadInput({ file: file, label: 'PDF File' })],
+ options,
+ output_filename,
+ packaged_filename,
+ });
+ },
+});
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/create-signature-request-ai.ts b/packages/pieces/community/iloveapi/src/lib/actions/create-signature-request-ai.ts
new file mode 100644
index 00000000000..5afb0d69bf9
--- /dev/null
+++ b/packages/pieces/community/iloveapi/src/lib/actions/create-signature-request-ai.ts
@@ -0,0 +1,90 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { iloveapiAuth } from '../common/auth';
+import { UploadInput, iLoveApi } from '../common/client';
+import { regionOf, regionProp } from '../common/props';
+import { iloveSchemas } from '../common/schemas';
+import { signatureBodyOf } from '../common/signature';
+
+export const createSignatureRequestAiAction = createAction({
+ auth: iloveapiAuth,
+ name: 'create_signature_request_ai',
+ classification: 'WRITE',
+ displayName: 'Send PDF for Signature',
+ description: 'Send PDFs (by public URL) to signers by name and email. Signers place their own fields.',
+ audience: 'ai',
+ outputSchema: iloveSchemas.signature,
+ aiMetadata: {
+ description:
+ 'Create an iLoveSign signature request from 1 to 5 public https PDF URLs and up to 50 signers (name, email, role signer/validator/viewer). Signers place their own signature fields. Each call creates a new request, emails every signer and spends signature credits, so never call it twice for the same document. Returns the requester token for status, reminder, void and download actions.',
+ idempotent: false,
+ },
+ props: {
+ file_urls: Property.Array({
+ displayName: 'PDF URLs',
+ description: 'Public https URLs of the PDFs to sign (1 to 5).',
+ required: true,
+ }),
+ signers: Property.Array({
+ displayName: 'Signers',
+ required: true,
+ properties: {
+ name: Property.ShortText({ displayName: 'Name', required: true }),
+ email: Property.ShortText({ displayName: 'Email', required: true }),
+ type: Property.ShortText({
+ displayName: 'Role',
+ description: 'signer (default), validator or viewer.',
+ required: false,
+ }),
+ },
+ }),
+ subject_signer: Property.ShortText({
+ displayName: 'Email Subject',
+ required: false,
+ }),
+ message_signer: Property.LongText({
+ displayName: 'Email Message',
+ required: false,
+ }),
+ expiration_days: Property.Number({
+ displayName: 'Expiration (days)',
+ description: '1 to 130. Default 120.',
+ required: false,
+ }),
+ region: regionProp,
+ },
+ async run(context) {
+ const { file_urls, signers, subject_signer, message_signer, expiration_days } = context.propsValue;
+ const uploads = urlUploads(file_urls);
+ const draft = signatureBodyOf({
+ signers,
+ elements: [],
+ options: { subject_signer, message_signer, expiration_days },
+ });
+ return iLoveApi.createSignatureRequest({
+ publicKey: context.auth.secret_text,
+ region: regionOf(context.propsValue.region),
+ uploads,
+ draft,
+ });
+ },
+});
+
+function urlUploads(value: unknown): UploadInput[] {
+ const list = Array.isArray(value) ? value : [];
+ const urls = list.map((item) => (typeof item === 'string' ? item.trim() : '')).filter((item) => item !== '');
+ if (urls.length === 0) {
+ throw new Error('At least one PDF URL is required.');
+ }
+ return urls.map((url, index) => {
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ throw new Error(`PDF URL ${index + 1} is not a valid URL.`);
+ }
+ if (parsed.protocol !== 'https:') {
+ throw new Error(`PDF URL ${index + 1} must use https.`);
+ }
+ return { kind: 'url', url: parsed.toString() };
+ });
+}
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/create-signature-request.ts b/packages/pieces/community/iloveapi/src/lib/actions/create-signature-request.ts
index ac98617768d..6a2932dfb7c 100644
--- a/packages/pieces/community/iloveapi/src/lib/actions/create-signature-request.ts
+++ b/packages/pieces/community/iloveapi/src/lib/actions/create-signature-request.ts
@@ -1,30 +1,9 @@
import { Property, createAction } from '@activepieces/pieces-framework';
import { iloveapiAuth } from '../common/auth';
import { iLoveApi } from '../common/client';
-import {
- CreateSignatureRequest,
- SignatureElement,
- SignatureSigner,
-} from '../common/types';
-
-type SignerRow = {
- name?: string;
- email?: string;
- phone?: string;
- type?: 'signer' | 'validator' | 'viewer';
- force_signature_type?: 'all' | 'text' | 'sign' | 'image';
- access_code?: string;
-};
-
-type ElementRow = {
- signer_email?: string;
- type?: 'signature' | 'initials' | 'date' | 'text' | 'input';
- position?: string;
- pages?: string;
- size?: number;
- content?: string;
- color?: string;
-};
+import { regionOf, regionProp, rowFiles } from '../common/props';
+import { iloveSchemas } from '../common/schemas';
+import { signatureBodyOf } from '../common/signature';
export const createSignatureRequestAction = createAction({
auth: iloveapiAuth,
@@ -33,7 +12,8 @@ export const createSignatureRequestAction = createAction({
displayName: 'Create Signature Request',
description:
'Send one or more PDF documents for electronic signature, with custom signers and signature placeholders.',
- audience: 'both',
+ audience: 'human',
+ outputSchema: iloveSchemas.signature,
aiMetadata: {
description:
'Start an electronic signature request: upload one or more PDFs and define the signers (by name and email, each as signer, validator, or viewer) plus optional field placeholders matched to signers by email. Returns a requester token used by the status, reminder, void, expiration, and download actions. Each call creates a brand-new request and dispatches invitation emails, so it is not idempotent.',
@@ -218,6 +198,7 @@ export const createSignatureRequestAction = createAction({
description: 'Days between auto-reminders. Default 1.',
required: false,
}),
+ region: regionProp,
certified: Property.Checkbox({
displayName: 'Certified Signature',
description: 'Apply a certified-signature seal to the final PDF.',
@@ -241,109 +222,28 @@ export const createSignatureRequestAction = createAction({
certified,
} = context.propsValue;
- if (!Array.isArray(files) || files.length === 0) {
- throw new Error('At least one PDF file is required.');
- }
- if (!Array.isArray(signers) || signers.length === 0) {
- throw new Error('At least one signer is required.');
- }
-
- const token = await iLoveApi.authenticate({
- publicKey: context.auth.secret_text,
- });
- const startResp = await iLoveApi.startTask({ token, tool: 'sign' });
-
- const uploadedFiles: Array<{ server_filename: string; filename: string }> = [];
- for (const entry of files as Array<{
- file: { base64: string; filename: string };
- }>) {
- if (!entry.file?.base64) {
- throw new Error('Each PDF row must include a file.');
- }
- const buffer = Buffer.from(entry.file.base64, 'base64');
- const serverFilename = await iLoveApi.uploadBuffer({
- token,
- server: startResp.server,
- task: startResp.task,
- buffer,
- filename: entry.file.filename,
- });
- uploadedFiles.push({
- server_filename: serverFilename,
- filename: entry.file.filename,
- });
- }
-
- const signerRows = signers as SignerRow[];
- const elementRows = (elements ?? []) as ElementRow[];
-
- const elementsByEmail = new Map<string, SignatureElement[]>();
- for (const row of elementRows) {
- if (!row.signer_email || !row.type || !row.position || !row.pages) continue;
- const element: SignatureElement = {
- type: row.type,
- position: row.position,
- pages: row.pages,
- ...(row.size !== undefined && row.size !== null ? { size: row.size } : {}),
- ...(row.content ? { content: row.content } : {}),
- ...(row.color ? { color: row.color } : {}),
- };
- const list = elementsByEmail.get(row.signer_email) ?? [];
- list.push(element);
- elementsByEmail.set(row.signer_email, list);
- }
-
- const signatureSigners: SignatureSigner[] = signerRows.map((row) => {
- if (!row.name || !row.email) {
- throw new Error('Each signer needs both name and email.');
- }
- const elementsForSigner = elementsByEmail.get(row.email);
- const signerFiles = uploadedFiles.map((file) => ({
- server_filename: file.server_filename,
- ...(elementsForSigner && elementsForSigner.length > 0
- ? { elements: elementsForSigner }
- : {}),
- }));
- return {
- name: row.name,
- email: row.email,
- type: row.type ?? 'signer',
- force_signature_type: row.force_signature_type ?? 'all',
- files: signerFiles,
- ...(row.phone ? { phone: row.phone } : {}),
- ...(row.access_code ? { access_code: row.access_code } : {}),
- };
+ const uploads = rowFiles({ rows: files, label: 'PDF Files' });
+ const draft = signatureBodyOf({
+ signers,
+ elements,
+ options: {
+ brand_name,
+ language,
+ subject_signer,
+ message_signer,
+ expiration_days,
+ lock_order,
+ signer_reminders,
+ signer_reminder_days_cycle,
+ certified,
+ },
});
- const body: CreateSignatureRequest = {
- task: startResp.task,
- files: uploadedFiles,
- signers: signatureSigners,
- ...(brand_name ? { brand_name } : {}),
- ...(language ? { language } : {}),
- ...(subject_signer ? { subject_signer } : {}),
- ...(message_signer ? { message_signer } : {}),
- ...(expiration_days !== undefined && expiration_days !== null
- ? { expiration_days }
- : {}),
- ...(lock_order !== undefined ? { lock_order } : {}),
- ...(signer_reminders !== undefined ? { signer_reminders } : {}),
- ...(signer_reminder_days_cycle !== undefined &&
- signer_reminder_days_cycle !== null
- ? { signer_reminder_days_cycle }
- : {}),
- ...(certified !== undefined ? { certified } : {}),
- };
-
- const response = await iLoveApi.createSignature({
- token,
- server: startResp.server,
- body,
+ return iLoveApi.createSignatureRequest({
+ publicKey: context.auth.secret_text,
+ region: regionOf(context.propsValue.region),
+ uploads,
+ draft,
});
-
- return {
- ...response,
- server: startResp.server,
- };
},
});
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/crop-image.ts b/packages/pieces/community/iloveapi/src/lib/actions/crop-image.ts
new file mode 100644
index 00000000000..825af861cd8
--- /dev/null
+++ b/packages/pieces/community/iloveapi/src/lib/actions/crop-image.ts
@@ -0,0 +1,77 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { iloveapiAuth } from '../common/auth';
+import { fileToUploadInput, regionOf, sharedProps, webhookOf } from '../common/props';
+import { runAndStoreResult } from '../common/runner';
+import { iloveSchemas } from '../common/schemas';
+
+export const cropImageAction = createAction({
+ auth: iloveapiAuth,
+ name: 'crop_image',
+ classification: 'READ',
+ displayName: 'Crop Image',
+ description: 'Crop an image to a rectangle given in pixels.',
+ audience: 'both',
+ outputSchema: iloveSchemas.toolResult,
+ aiMetadata: {
+ description:
+ 'Crop an image with iLoveIMG to a rectangle of the given width and height in pixels, starting at the X/Y offset from the top-left corner (default 0,0). Each run creates a new file and spends credits.',
+ idempotent: false,
+ },
+ props: {
+ file: Property.File({
+ displayName: 'Image',
+ required: true,
+ }),
+ width: Property.Number({
+ displayName: 'Width (px)',
+ required: true,
+ }),
+ height: Property.Number({
+ displayName: 'Height (px)',
+ required: true,
+ }),
+ x: Property.Number({
+ displayName: 'X Offset (px)',
+ description: 'Distance from the left edge. Default 0.',
+ required: false,
+ }),
+ y: Property.Number({
+ displayName: 'Y Offset (px)',
+ description: 'Distance from the top edge. Default 0.',
+ required: false,
+ }),
+ ...sharedProps,
+ },
+ async run(context) {
+ const { file, width, height, x, y, output_filename, packaged_filename } = context.propsValue;
+ const options = {
+ width: wholeNumber({ value: width, label: 'Width (px)', min: 1 }) ?? 0,
+ height: wholeNumber({ value: height, label: 'Height (px)', min: 1 }) ?? 0,
+ x: wholeNumber({ value: x, label: 'X Offset (px)', min: 0 }) ?? 0,
+ y: wholeNumber({ value: y, label: 'Y Offset (px)', min: 0 }) ?? 0,
+ };
+ if (options.width < 1 || options.height < 1) {
+ throw new Error('Width and Height are required.');
+ }
+
+ return await runAndStoreResult({
+ auth: context.auth.secret_text,
+ region: regionOf(context.propsValue.region),
+ webhook: webhookOf(context.propsValue.webhook_url),
+ files: context.files,
+ tool: 'cropimage',
+ uploads: [fileToUploadInput({ file: file, label: 'Image' })],
+ options,
+ output_filename,
+ packaged_filename,
+ });
+ },
+});
+
+function wholeNumber({ value, label, min }: { value: number | undefined | null; label: string; min: number }): number | undefined {
+ if (value === undefined || value === null) return undefined;
+ if (!Number.isInteger(value) || value < min) {
+ throw new Error(`"${label}" must be a whole number, ${min} or more.`);
+ }
+ return value;
+}
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/download-audit-trail.ts b/packages/pieces/community/iloveapi/src/lib/actions/download-audit-trail.ts
index 6c6ff0f6ad9..5e20277bd34 100644
--- a/packages/pieces/community/iloveapi/src/lib/actions/download-audit-trail.ts
+++ b/packages/pieces/community/iloveapi/src/lib/actions/download-audit-trail.ts
@@ -1,6 +1,7 @@
import { Property, createAction } from '@activepieces/pieces-framework';
import { iloveapiAuth } from '../common/auth';
import { iLoveApi } from '../common/client';
+import { iloveSchemas } from '../common/schemas';
export const downloadAuditTrailAction = createAction({
auth: iloveapiAuth,
@@ -10,6 +11,7 @@ export const downloadAuditTrailAction = createAction({
description:
'Download the audit-trail PDF for a completed signature request. Useful for compliance and dispute resolution.',
audience: 'both',
+ outputSchema: iloveSchemas.signatureDownload,
aiMetadata: {
description:
'Fetch the audit-trail PDF (the legal evidence/event log) for a completed signature request, identified by its requester token, for compliance and dispute resolution. Read-only retrieval, safe to repeat; to get the actual signed documents use Download Signed Files instead.',
@@ -21,6 +23,12 @@ export const downloadAuditTrailAction = createAction({
description: 'The "token_requester" of the completed signature request.',
required: true,
}),
+ server: Property.ShortText({
+ displayName: 'Server',
+ description:
+ 'Optional. The "server" value returned by Create Signature Request. When empty, the server is looked up from the signature request.',
+ required: false,
+ }),
file_name: Property.ShortText({
displayName: 'Output File Name',
description: 'Name to store the audit PDF under. Defaults to "audit-{token}.pdf".',
@@ -28,29 +36,34 @@ export const downloadAuditTrailAction = createAction({
}),
},
async run(context) {
- const { token_requester, file_name } = context.propsValue;
- if (!token_requester) {
+ const tokenRequester = (context.propsValue.token_requester ?? '').trim();
+ if (!tokenRequester) {
throw new Error('Requester Token is required.');
}
const token = await iLoveApi.authenticate({
publicKey: context.auth.secret_text,
});
- const buffer = await iLoveApi.downloadAuditTrail({
+ const { data, contentType } = await iLoveApi.downloadSignatureFile({
token,
- tokenRequester: token_requester,
+ tokenRequester,
+ server: context.propsValue.server ?? undefined,
+ kind: 'audit',
});
- const finalName = file_name ?? `audit-${token_requester}.pdf`;
+ const extension = contentType?.includes('zip') ? 'zip' : 'pdf';
+ const finalName = context.propsValue.file_name?.trim() || `audit-${tokenRequester}.${extension}`;
const storedFile = await context.files.write({
fileName: finalName,
- data: buffer,
+ data,
});
return {
output_file: storedFile,
file_name: finalName,
- size: buffer.length,
+ size: data.length,
+ content_type: contentType,
+ token_requester: tokenRequester,
};
},
});
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/download-signed-files.ts b/packages/pieces/community/iloveapi/src/lib/actions/download-signed-files.ts
index 1a16900810b..f61ce6ffeec 100644
--- a/packages/pieces/community/iloveapi/src/lib/actions/download-signed-files.ts
+++ b/packages/pieces/community/iloveapi/src/lib/actions/download-signed-files.ts
@@ -1,6 +1,7 @@
import { Property, createAction } from '@activepieces/pieces-framework';
import { iloveapiAuth } from '../common/auth';
import { iLoveApi } from '../common/client';
+import { iloveSchemas } from '../common/schemas';
export const downloadSignedFilesAction = createAction({
auth: iloveapiAuth,
@@ -10,6 +11,7 @@ export const downloadSignedFilesAction = createAction({
description:
'Download the signed PDF (or ZIP if multiple files). The signature must be in "completed" status.',
audience: 'both',
+ outputSchema: iloveSchemas.signatureDownload,
aiMetadata: {
description:
'Retrieve the finished signed document for a signature request by its requester token, returning a single PDF or a ZIP when several files were signed. The request must already be in "completed" status (check first with Get Signature Status); for the evidence log use Download Audit Trail. Read-only retrieval, safe to repeat.',
@@ -21,36 +23,47 @@ export const downloadSignedFilesAction = createAction({
description: 'The "token_requester" of the completed signature request.',
required: true,
}),
+ server: Property.ShortText({
+ displayName: 'Server',
+ description:
+ 'Optional. The "server" value returned by Create Signature Request. When empty, the server is looked up from the signature request.',
+ required: false,
+ }),
file_name: Property.ShortText({
displayName: 'Output File Name',
- description: 'Name to store the downloaded file under. Defaults to "signed-{token}.pdf".',
+ description: 'Name to store the downloaded file under. Defaults to "signed-{token}.pdf" (".zip" when several files were signed).',
required: false,
}),
},
async run(context) {
- const { token_requester, file_name } = context.propsValue;
- if (!token_requester) {
+ const tokenRequester = (context.propsValue.token_requester ?? '').trim();
+ if (!tokenRequester) {
throw new Error('Requester Token is required.');
}
const token = await iLoveApi.authenticate({
publicKey: context.auth.secret_text,
});
- const buffer = await iLoveApi.downloadSignedFiles({
+ const { data, contentType } = await iLoveApi.downloadSignatureFile({
token,
- tokenRequester: token_requester,
+ tokenRequester,
+ server: context.propsValue.server ?? undefined,
+ kind: 'signed',
});
- const finalName = file_name ?? `signed-${token_requester}.pdf`;
+ const extension = contentType?.includes('zip') ? 'zip' : 'pdf';
+ const finalName = context.propsValue.file_name?.trim() || `signed-${tokenRequester}.${extension}`;
const storedFile = await context.files.write({
fileName: finalName,
- data: buffer,
+ data,
});
return {
output_file: storedFile,
file_name: finalName,
- size: buffer.length,
+ size: data.length,
+ content_type: contentType,
+ token_requester: tokenRequester,
};
},
});
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/extract-text.ts b/packages/pieces/community/iloveapi/src/lib/actions/extract-text.ts
index 631fb2ca0de..ca56b2da12d 100644
--- a/packages/pieces/community/iloveapi/src/lib/actions/extract-text.ts
+++ b/packages/pieces/community/iloveapi/src/lib/actions/extract-text.ts
@@ -1,7 +1,8 @@
import { Property, createAction } from '@activepieces/pieces-framework';
import { iloveapiAuth } from '../common/auth';
-import { fileToUploadInput, sharedProps } from '../common/props';
-import { iLoveApi } from '../common/client';
+import { iloveSchemas } from '../common/schemas';
+import { fileToUploadInput, regionOf, sharedProps, webhookOf } from '../common/props';
+import { runAndStoreWithBuffer } from '../common/runner';
export const extractTextPdfAction = createAction({
auth: iloveapiAuth,
@@ -11,9 +12,10 @@ export const extractTextPdfAction = createAction({
description:
'Extract plain or detailed text (with positions and font metadata) from a PDF.',
audience: 'both',
+ outputSchema: iloveSchemas.extractText,
aiMetadata: {
description:
- 'Extract the text content of a PDF via the iLoveAPI service. Pick this to pull readable text out of a PDF (e.g. for parsing or downstream analysis); enable detailed mode when you need per-block positional and font metadata for layout-aware parsing rather than plain text. Each call re-runs extraction and writes a fresh output file, so repeated runs are not idempotent.',
+ 'Extract the text content of a PDF via the iLoveAPI service. Pick this to pull readable text out of a PDF (e.g. for parsing or downstream analysis); enable detailed mode when you need per-block positional and font metadata for layout-aware parsing rather than plain text. Each call re-runs extraction (spending credits) and writes a fresh output file; inline text is capped at 200,000 characters, the full text stays in the output file.',
idempotent: false,
},
props: {
@@ -33,48 +35,88 @@ export const extractTextPdfAction = createAction({
async run(context) {
const { file, detailed, output_filename, packaged_filename } =
context.propsValue;
+ const wantDetailed = detailed === true;
- const result = await iLoveApi.runTask({
- publicKey: context.auth.secret_text,
+ const { output: stored, buffer } = await runAndStoreWithBuffer({
+ auth: context.auth.secret_text,
+ region: regionOf(context.propsValue.region),
+ webhook: webhookOf(context.propsValue.webhook_url),
+ files: context.files,
tool: 'extract',
- uploads: [fileToUploadInput(file)],
- options: { detailed: detailed ?? false },
+ uploads: [fileToUploadInput({ file: file, label: 'PDF File' })],
+ options: { detailed: wantDetailed },
output_filename,
packaged_filename,
});
- const storedFile = await context.files.write({
- fileName: result.downloadFilename,
- data: result.buffer,
- });
-
- const text = result.buffer.toString('utf-8');
- const detailedJson = parseDetailedJson({ detailed: detailed ?? false, text });
-
+ const fullText = decodeText(buffer);
+ const text = fullText.length > MAX_INLINE_TEXT ? fullText.slice(0, MAX_INLINE_TEXT) : fullText;
+ const parsed = wantDetailed ? parseDetailed(fullText) : undefined;
return {
- output_file: storedFile,
- download_filename: result.downloadFilename,
- output_filenumber: result.process.output_filenumber,
- output_filesize: result.process.output_filesize,
- output_extensions: result.process.output_extensions,
- status: result.process.status,
+ ...stored,
text,
- detailed: detailedJson,
+ text_length: fullText.length,
+ text_truncated: fullText.length > MAX_INLINE_TEXT,
+ ...(parsed ? parsed : {}),
};
},
});
-function parseDetailedJson({
- detailed,
- text,
-}: {
- detailed: boolean;
- text: string;
-}): unknown {
- if (!detailed) return undefined;
- try {
- return JSON.parse(text);
- } catch {
- return undefined;
+function decodeText(buffer: Buffer): string {
+ if (buffer.length >= 2 && buffer[0] === 0xff && buffer[1] === 0xfe) {
+ return buffer.subarray(2).toString('utf16le');
+ }
+ if (buffer.length >= 2 && buffer[0] === 0xfe && buffer[1] === 0xff) {
+ const swapped = Buffer.from(buffer.subarray(2));
+ swapped.swap16();
+ return swapped.toString('utf16le');
+ }
+ if (buffer.length >= 3 && buffer[0] === 0xef && buffer[1] === 0xbb && buffer[2] === 0xbf) {
+ return buffer.subarray(3).toString('utf-8');
+ }
+ return buffer.toString('utf-8');
+}
+
+function parseDetailed(text: string): { detailed: Array<Record<string, string | number>>; detailed_total_rows?: number; detailed_truncated?: boolean } | { detailed: null; detailed_parse_error: string } {
+ const trimmed = text.trim();
+ if (trimmed.startsWith('[') || trimmed.startsWith('{')) {
+ try {
+ const json: unknown = JSON.parse(trimmed);
+ if (Array.isArray(json)) {
+ return { detailed: json.filter((row): row is Record<string, string | number> => row !== null && typeof row === 'object') };
+ }
+ } catch (error) {
+ return { detailed: null, detailed_parse_error: `Detailed output is not valid JSON: ${error instanceof Error ? error.message : String(error)}` };
+ }
+ }
+ const lines = text.split(/\r?\n/).filter((line) => line.trim() !== '');
+ if (lines.length === 0) {
+ return { detailed: [] };
}
+ const header = lines[0].split(',').map((cell) => cell.trim().replace(/^"|"$/g, ''));
+ const wordIndex = header.length - 1;
+ if (header.length < 2 || !['Text', 'Word'].includes(header[wordIndex]) || header[0] !== 'PageNo') {
+ return {
+ detailed: null,
+ detailed_parse_error: `Detailed output has an unexpected header: ${lines[0].slice(0, 200)}. The full result is in the output file.`,
+ };
+ }
+ const rows = lines.slice(1, MAX_DETAILED_ROWS + 1).map((line) => line.replace(/\r$/, '')).map((line) => {
+ const cells = line.split(',');
+ const fixed = cells.slice(0, wordIndex);
+ const word = cells.slice(wordIndex).join(',').trim().replace(/^"|"$/g, '');
+ const row: Record<string, string | number> = {};
+ header.slice(0, wordIndex).forEach((name, index) => {
+ const raw = (fixed[index] ?? '').trim().replace(/^"|"$/g, '');
+ const numeric = Number(raw);
+ row[name] = raw !== '' && Number.isFinite(numeric) ? numeric : raw;
+ });
+ row[header[wordIndex]] = word;
+ return row;
+ });
+ const totalRows = lines.length - 1;
+ return { detailed: rows, detailed_total_rows: totalRows, detailed_truncated: totalRows > rows.length };
}
+
+const MAX_INLINE_TEXT = 200_000;
+const MAX_DETAILED_ROWS = 5_000;
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/get-signature-status.ts b/packages/pieces/community/iloveapi/src/lib/actions/get-signature-status.ts
index 87b5eb2d31e..d502cc0452a 100644
--- a/packages/pieces/community/iloveapi/src/lib/actions/get-signature-status.ts
+++ b/packages/pieces/community/iloveapi/src/lib/actions/get-signature-status.ts
@@ -1,6 +1,7 @@
import { Property, createAction } from '@activepieces/pieces-framework';
import { iloveapiAuth } from '../common/auth';
import { iLoveApi } from '../common/client';
+import { iloveSchemas } from '../common/schemas';
export const getSignatureStatusAction = createAction({
auth: iloveapiAuth,
@@ -10,6 +11,7 @@ export const getSignatureStatusAction = createAction({
description:
'Look up the current status of a signature request, including each signer.',
audience: 'both',
+ outputSchema: iloveSchemas.signature,
aiMetadata: {
description:
'Look up the current status of a signature request by its requester token, including the per-signer state. Read-only and safe to poll repeatedly; use this to check whether a request is completed before downloading signed files or the audit trail.',
@@ -24,17 +26,15 @@ export const getSignatureStatusAction = createAction({
}),
},
async run(context) {
- const { token_requester } = context.propsValue;
- if (!token_requester) {
+ const tokenRequester = (context.propsValue.token_requester ?? '').trim();
+ if (!tokenRequester) {
throw new Error('Requester Token is required.');
}
const token = await iLoveApi.authenticate({
publicKey: context.auth.secret_text,
});
- return await iLoveApi.getSignatureStatus({
- token,
- tokenRequester: token_requester,
- });
+ const view = await iLoveApi.getSignatureStatus({ token, tokenRequester });
+ return { ...view, token_requester: view['token_requester'] ?? tokenRequester };
},
});
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/get-signer-info.ts b/packages/pieces/community/iloveapi/src/lib/actions/get-signer-info.ts
new file mode 100644
index 00000000000..44139bad6cb
--- /dev/null
+++ b/packages/pieces/community/iloveapi/src/lib/actions/get-signer-info.ts
@@ -0,0 +1,39 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { iloveapiAuth } from '../common/auth';
+import { iLoveApi } from '../common/client';
+import { iloveSchemas } from '../common/schemas';
+
+export const getSignerInfoAction = createAction({
+ auth: iloveapiAuth,
+ name: 'get_signer_info',
+ classification: 'READ',
+ displayName: 'Get Signer Info',
+ description: 'Look up one signer of a signature request by the signer token.',
+ audience: 'both',
+ outputSchema: iloveSchemas.signerInfo,
+ aiMetadata: {
+ description:
+ 'Look up a single signer (receiver) of a signature request by its signer token, found in the "signers" list of Get Signature Status or Create Signature Request. Returns the signer\'s name, email, role and status. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ token_signer: Property.ShortText({
+ displayName: 'Signer Token',
+ description: 'The signer\'s "token_signer" (or receiver token) from Get Signature Status.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const tokenSigner = (context.propsValue.token_signer ?? '').trim();
+ if (!tokenSigner) {
+ throw new Error('Signer Token is required.');
+ }
+ const token = await iLoveApi.authenticate({ publicKey: context.auth.secret_text });
+ const info = await iLoveApi.getSignerInfo({ token, tokenSigner });
+ const accessCode = info['access_code'];
+ return {
+ ...info,
+ access_code: accessCode === undefined || accessCode === null || accessCode === '' ? false : true,
+ };
+ },
+});
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/html-to-pdf.ts b/packages/pieces/community/iloveapi/src/lib/actions/html-to-pdf.ts
index 0eba450c8fb..2c1ca5a88ce 100644
--- a/packages/pieces/community/iloveapi/src/lib/actions/html-to-pdf.ts
+++ b/packages/pieces/community/iloveapi/src/lib/actions/html-to-pdf.ts
@@ -1,6 +1,7 @@
import { Property, createAction } from '@activepieces/pieces-framework';
import { iloveapiAuth } from '../common/auth';
-import { sharedProps } from '../common/props';
+import { iloveSchemas } from '../common/schemas';
+import { regionOf, sharedProps, webhookOf } from '../common/props';
import { runAndStoreResult } from '../common/runner';
export const htmlToPdfAction = createAction({
@@ -10,6 +11,7 @@ export const htmlToPdfAction = createAction({
displayName: 'HTML to PDF',
description: 'Convert a publicly accessible web page URL into a PDF.',
audience: 'both',
+ outputSchema: iloveSchemas.toolResult,
aiMetadata: {
description:
'Render a publicly reachable web page, given its http(s) URL, into a PDF. The URL must be publicly accessible (no auth-gated or private pages). Use Office to PDF or JPG to PDF instead when the source is a local file rather than a live web page. Each run produces a new output.',
@@ -31,7 +33,9 @@ export const htmlToPdfAction = createAction({
}
return await runAndStoreResult({
- auth:context.auth.secret_text,
+ auth: context.auth.secret_text,
+ region: regionOf(context.propsValue.region),
+ webhook: webhookOf(context.propsValue.webhook_url),
files: context.files,
tool: 'htmlpdf',
uploads: [{ kind: 'url', url }],
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/increase-expiration-days.ts b/packages/pieces/community/iloveapi/src/lib/actions/increase-expiration-days.ts
index 61934a9d763..72c742d1d48 100644
--- a/packages/pieces/community/iloveapi/src/lib/actions/increase-expiration-days.ts
+++ b/packages/pieces/community/iloveapi/src/lib/actions/increase-expiration-days.ts
@@ -1,6 +1,7 @@
import { Property, createAction } from '@activepieces/pieces-framework';
import { iloveapiAuth } from '../common/auth';
import { iLoveApi } from '../common/client';
+import { iloveSchemas } from '../common/schemas';
export const increaseExpirationDaysAction = createAction({
auth: iloveapiAuth,
@@ -10,6 +11,7 @@ export const increaseExpirationDaysAction = createAction({
description:
'Extend the expiration of a signature request by a number of days. Total cannot exceed 130 days from now.',
audience: 'both',
+ outputSchema: iloveSchemas.signatureAck,
aiMetadata: {
description:
'Push back the expiration date of an existing signature request (by requester token) by a given number of days, where the added amount must be 1 to 130 and the resulting total cannot exceed 130 days from now. Not idempotent: each call adds days on top of the current expiration rather than setting it to an absolute date.',
@@ -28,21 +30,23 @@ export const increaseExpirationDaysAction = createAction({
}),
},
async run(context) {
- const { token_requester, days } = context.propsValue;
- if (!token_requester) {
+ const tokenRequester = (context.propsValue.token_requester ?? '').trim();
+ if (!tokenRequester) {
throw new Error('Requester Token is required.');
}
- if (days === undefined || days === null || days < 1 || days > 130) {
- throw new Error('Additional Days must be between 1 and 130.');
+ const days = Number(context.propsValue.days);
+ if (!Number.isInteger(days) || days < 1 || days > 130) {
+ throw new Error('Additional Days must be a whole number between 1 and 130.');
}
-
const token = await iLoveApi.authenticate({
publicKey: context.auth.secret_text,
});
- return await iLoveApi.increaseExpirationDays({
- token,
- tokenRequester: token_requester,
+ const response = await iLoveApi.increaseExpirationDays({ token, tokenRequester, days });
+ return {
+ ...response,
+ success: true,
+ token_requester: tokenRequester,
days,
- });
+ };
},
});
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/jpg-to-pdf.ts b/packages/pieces/community/iloveapi/src/lib/actions/jpg-to-pdf.ts
index dce89b18890..255526a82b5 100644
--- a/packages/pieces/community/iloveapi/src/lib/actions/jpg-to-pdf.ts
+++ b/packages/pieces/community/iloveapi/src/lib/actions/jpg-to-pdf.ts
@@ -1,8 +1,8 @@
import { Property, createAction } from '@activepieces/pieces-framework';
import { iloveapiAuth } from '../common/auth';
-import { sharedProps } from '../common/props';
+import { iloveSchemas } from '../common/schemas';
+import { regionOf, rowFiles, sharedProps, webhookOf } from '../common/props';
import { runAndStoreResult } from '../common/runner';
-import { UploadInput } from '../common/client';
export const jpgToPdfAction = createAction({
auth: iloveapiAuth,
@@ -11,6 +11,7 @@ export const jpgToPdfAction = createAction({
displayName: 'JPG to PDF',
description: 'Convert one or more images (JPG/PNG) into a PDF document.',
audience: 'both',
+ outputSchema: iloveSchemas.toolResult,
aiMetadata: {
description:
'Convert one or more JPG/PNG images into PDF, with control over orientation, page size, and margin. By default all images are merged into a single PDF; disable "Merge into single PDF" to instead get one PDF per image. Each run produces new output rather than reusing a prior result.',
@@ -82,16 +83,10 @@ export const jpgToPdfAction = createAction({
throw new Error('At least one image is required.');
}
- const uploads: UploadInput[] = images.map((entry) => {
- const file = (entry as { file: { base64: string; filename: string } }).file;
- if (!file?.base64) {
- throw new Error('Each row must include an image file.');
- }
- return {
- kind: 'file',
- file: { base64: file.base64, filename: file.filename },
- };
- });
+ const uploads = rowFiles({ rows: images, label: 'Images' });
+ if (margin !== undefined && margin !== null && (!Number.isFinite(margin) || margin < 0)) {
+ throw new Error('Margin must be a number of pixels, 0 or more.');
+ }
const options: Record<string, unknown> = {
orientation: orientation ?? 'portrait',
@@ -104,6 +99,8 @@ export const jpgToPdfAction = createAction({
return await runAndStoreResult({
auth: context.auth.secret_text,
+ region: regionOf(context.propsValue.region),
+ webhook: webhookOf(context.propsValue.webhook_url),
files: context.files,
tool: 'imagepdf',
uploads,
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/list-signature-requests.ts b/packages/pieces/community/iloveapi/src/lib/actions/list-signature-requests.ts
new file mode 100644
index 00000000000..48f265f9e8f
--- /dev/null
+++ b/packages/pieces/community/iloveapi/src/lib/actions/list-signature-requests.ts
@@ -0,0 +1,64 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { iloveapiAuth } from '../common/auth';
+import { iLoveApi } from '../common/client';
+import { iloveSchemas } from '../common/schemas';
+
+export const listSignatureRequestsAction = createAction({
+ auth: iloveapiAuth,
+ name: 'list_signature_requests',
+ classification: 'SEARCH',
+ displayName: 'List Signature Requests',
+ description: 'List the signature requests of this project, one page at a time.',
+ audience: 'both',
+ outputSchema: iloveSchemas.signatureList,
+ aiMetadata: {
+ description:
+ 'List the project\'s signature requests one page at a time (newest first), returning each request\'s requester token, status and signers. Use the returned requester token with Get Signature Status, reminders, void or downloads. When "has_more" is true, call again with "next_page". Read-only.',
+ idempotent: true,
+ },
+ props: {
+ page: Property.Number({
+ displayName: 'Page',
+ description: 'Page number, starting at 1.',
+ required: false,
+ defaultValue: 1,
+ }),
+ per_page: Property.Number({
+ displayName: 'Per Page',
+ description: '1 to 100. Default 20.',
+ required: false,
+ defaultValue: 20,
+ }),
+ },
+ async run(context) {
+ const page = Number(context.propsValue.page ?? 1);
+ const perPage = Number(context.propsValue.per_page ?? 20);
+ if (!Number.isInteger(page) || page < 1) {
+ throw new Error('Page must be a whole number, 1 or more.');
+ }
+ if (!Number.isInteger(perPage) || perPage < 1 || perPage > 100) {
+ throw new Error('Per Page must be a whole number between 1 and 100.');
+ }
+
+ const token = await iLoveApi.authenticate({ publicKey: context.auth.secret_text });
+ const response = await iLoveApi.listSignatures({ token, page, perPage });
+ const list = Array.isArray(response)
+ ? response
+ : iLoveApi.isRecord(response) && Array.isArray(response['items'])
+ ? response['items']
+ : null;
+ if (list === null) {
+ throw new Error('iLoveAPI returned an unexpected signature list.');
+ }
+ const items = list.filter((item): item is Record<string, unknown> => iLoveApi.isRecord(item));
+ const hasMore = items.length === perPage;
+ return {
+ items,
+ count: items.length,
+ page,
+ per_page: perPage,
+ next_page: hasMore ? page + 1 : null,
+ has_more: hasMore,
+ };
+ },
+});
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/merge-pdf.ts b/packages/pieces/community/iloveapi/src/lib/actions/merge-pdf.ts
index 64832faaeb7..da3b8dce870 100644
--- a/packages/pieces/community/iloveapi/src/lib/actions/merge-pdf.ts
+++ b/packages/pieces/community/iloveapi/src/lib/actions/merge-pdf.ts
@@ -1,8 +1,8 @@
import { Property, createAction } from '@activepieces/pieces-framework';
import { iloveapiAuth } from '../common/auth';
-import { sharedProps } from '../common/props';
+import { iloveSchemas } from '../common/schemas';
+import { regionOf, rowFiles, sharedProps, webhookOf } from '../common/props';
import { runAndStoreResult } from '../common/runner';
-import { UploadInput } from '../common/client';
export const mergePdfAction = createAction({
auth: iloveapiAuth,
@@ -12,6 +12,7 @@ export const mergePdfAction = createAction({
description:
'Combine multiple PDF files into a single document, in the order provided.',
audience: 'both',
+ outputSchema: iloveSchemas.toolResult,
aiMetadata: {
description:
'Concatenate two or more PDF files into one document, preserving the order in which they are listed. Requires at least two input files. Each run generates a new merged file, so re-running does not deduplicate against earlier outputs.',
@@ -39,19 +40,12 @@ export const mergePdfAction = createAction({
throw new Error('At least two PDF files are required for merging.');
}
- const uploads: UploadInput[] = files.map((entry) => {
- const file = (entry as { file: { base64: string; filename: string } }).file;
- if (!file?.base64) {
- throw new Error('Each row must include a file.');
- }
- return {
- kind: 'file',
- file: { base64: file.base64, filename: file.filename },
- };
- });
+ const uploads = rowFiles({ rows: files, label: 'PDF Files' });
return await runAndStoreResult({
auth: context.auth.secret_text,
+ region: regionOf(context.propsValue.region),
+ webhook: webhookOf(context.propsValue.webhook_url),
files: context.files,
tool: 'merge',
uploads,
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/ocr-pdf.ts b/packages/pieces/community/iloveapi/src/lib/actions/ocr-pdf.ts
index 14918c47bf0..07cccf1dab5 100644
--- a/packages/pieces/community/iloveapi/src/lib/actions/ocr-pdf.ts
+++ b/packages/pieces/community/iloveapi/src/lib/actions/ocr-pdf.ts
@@ -1,6 +1,7 @@
import { Property, createAction } from '@activepieces/pieces-framework';
import { iloveapiAuth } from '../common/auth';
-import { fileToUploadInput, sharedProps } from '../common/props';
+import { iloveSchemas } from '../common/schemas';
+import { fileToUploadInput, regionOf, sharedProps, webhookOf } from '../common/props';
import { runAndStoreResult } from '../common/runner';
export const ocrPdfAction = createAction({
@@ -11,6 +12,7 @@ export const ocrPdfAction = createAction({
description:
'Run OCR on a PDF to make scanned documents searchable. Supports 100+ languages.',
audience: 'both',
+ outputSchema: iloveSchemas.toolResult,
aiMetadata: {
description:
'Add a searchable, selectable text layer to a scanned or image-only PDF via OCR, defaulting to English when no language is given (accepts one or more ISO 639-2 codes such as eng, fra, deu, chi_sim). Use this before extracting or searching text in scanned documents. Each run produces a new output file.',
@@ -34,19 +36,42 @@ export const ocrPdfAction = createAction({
const { file, ocr_languages, output_filename, packaged_filename } =
context.propsValue;
- const languages =
- Array.isArray(ocr_languages) && ocr_languages.length > 0
- ? ocr_languages.map((lang) => String(lang)).filter((l) => l.length > 0)
- : ['eng'];
+ const given = Array.isArray(ocr_languages)
+ ? ocr_languages.map((lang) => languageOf(lang)).filter((l) => l.length > 0)
+ : [];
+ const invalid = given.filter((lang) => !/^[a-z]{3}(_[a-z]+)?$/.test(lang));
+ if (invalid.length > 0) {
+ throw new Error(`OCR languages must be ISO 639-2 codes like "eng" or "chi_sim". Invalid: ${invalid.join(', ')}`);
+ }
+ const languages = given.length > 0 ? given : ['eng'];
return await runAndStoreResult({
auth: context.auth.secret_text,
+ region: regionOf(context.propsValue.region),
+ webhook: webhookOf(context.propsValue.webhook_url),
files: context.files,
tool: 'pdfocr',
- uploads: [fileToUploadInput(file)],
+ uploads: [fileToUploadInput({ file: file })],
options: { ocr_languages: languages },
output_filename,
packaged_filename,
});
},
});
+
+function languageOf(value: unknown): string {
+ if (typeof value === 'string') return value.trim();
+ if (value !== null && typeof value === 'object') {
+ const entries = Object.entries(value);
+ if (entries.length > 0 && entries.every(([key, item]) => /^\d+$/.test(key) && typeof item === 'string')) {
+ return entries
+ .sort(([a], [b]) => Number(a) - Number(b))
+ .map(([, item]) => item)
+ .join('')
+ .trim();
+ }
+ const first = Object.values(value).find((item) => typeof item === 'string');
+ return typeof first === 'string' ? first.trim() : '';
+ }
+ return String(value ?? '').trim();
+}
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/office-to-pdf.ts b/packages/pieces/community/iloveapi/src/lib/actions/office-to-pdf.ts
index adf64cd59bb..1c022227bea 100644
--- a/packages/pieces/community/iloveapi/src/lib/actions/office-to-pdf.ts
+++ b/packages/pieces/community/iloveapi/src/lib/actions/office-to-pdf.ts
@@ -1,6 +1,7 @@
import { Property, createAction } from '@activepieces/pieces-framework';
import { iloveapiAuth } from '../common/auth';
-import { fileToUploadInput, sharedProps } from '../common/props';
+import { iloveSchemas } from '../common/schemas';
+import { fileToUploadInput, regionOf, sharedProps, webhookOf } from '../common/props';
import { runAndStoreResult } from '../common/runner';
export const officeToPdfAction = createAction({
@@ -11,6 +12,7 @@ export const officeToPdfAction = createAction({
description:
'Convert Office documents (DOCX, XLSX, PPTX, ODT, etc.) to PDF.',
audience: 'both',
+ outputSchema: iloveSchemas.toolResult,
aiMetadata: {
description:
'Convert a single Office document (DOCX, XLSX, PPTX, ODT, ODS, ODP, RTF, or TXT) into a PDF. Use this when the source is an Office/text file; for images use JPG to PDF and for web pages use HTML to PDF. Each run produces a new converted file.',
@@ -29,9 +31,11 @@ export const officeToPdfAction = createAction({
return await runAndStoreResult({
auth: context.auth.secret_text,
+ region: regionOf(context.propsValue.region),
+ webhook: webhookOf(context.propsValue.webhook_url),
files: context.files,
tool: 'officepdf',
- uploads: [fileToUploadInput(file)],
+ uploads: [fileToUploadInput({ file: file })],
output_filename,
packaged_filename,
});
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/page-numbers.ts b/packages/pieces/community/iloveapi/src/lib/actions/page-numbers.ts
index 9ccd7599166..a03b8c92d06 100644
--- a/packages/pieces/community/iloveapi/src/lib/actions/page-numbers.ts
+++ b/packages/pieces/community/iloveapi/src/lib/actions/page-numbers.ts
@@ -1,6 +1,7 @@
import { Property, createAction } from '@activepieces/pieces-framework';
import { iloveapiAuth } from '../common/auth';
-import { fileToUploadInput, sharedProps } from '../common/props';
+import { iloveSchemas } from '../common/schemas';
+import { fileToUploadInput, regionOf, sharedProps, webhookOf } from '../common/props';
import { runAndStoreResult } from '../common/runner';
export const pageNumbersPdfAction = createAction({
@@ -10,6 +11,7 @@ export const pageNumbersPdfAction = createAction({
displayName: 'Add Page Numbers to PDF',
description: 'Stamp page numbers onto a PDF, with control over position and styling.',
audience: 'both',
+ outputSchema: iloveSchemas.toolResult,
aiMetadata: {
description:
'Print page numbers onto a PDF, with control over which pages, the starting number, the {n}/{p} number format, facing-page (book) layout, cover-skip, and font styling. Each run produces a new numbered file, so re-running re-stamps rather than reusing an earlier output.',
@@ -136,10 +138,12 @@ export const pageNumbersPdfAction = createAction({
};
return await runAndStoreResult({
- auth:context.auth.secret_text,
+ auth: context.auth.secret_text,
+ region: regionOf(context.propsValue.region),
+ webhook: webhookOf(context.propsValue.webhook_url),
files: context.files,
tool: 'pagenumber',
- uploads: [fileToUploadInput(file)],
+ uploads: [fileToUploadInput({ file: file })],
options,
output_filename,
packaged_filename,
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/pdf-to-jpg.ts b/packages/pieces/community/iloveapi/src/lib/actions/pdf-to-jpg.ts
index f90118ff526..b90fe92ddee 100644
--- a/packages/pieces/community/iloveapi/src/lib/actions/pdf-to-jpg.ts
+++ b/packages/pieces/community/iloveapi/src/lib/actions/pdf-to-jpg.ts
@@ -1,6 +1,7 @@
import { Property, createAction } from '@activepieces/pieces-framework';
import { iloveapiAuth } from '../common/auth';
-import { fileToUploadInput, sharedProps } from '../common/props';
+import { iloveSchemas } from '../common/schemas';
+import { fileToUploadInput, regionOf, sharedProps, webhookOf } from '../common/props';
import { runAndStoreResult } from '../common/runner';
export const pdfToJpgAction = createAction({
@@ -11,6 +12,7 @@ export const pdfToJpgAction = createAction({
description:
'Convert PDF pages to JPG images, or extract images embedded in the PDF.',
audience: 'both',
+ outputSchema: iloveSchemas.toolResult,
aiMetadata: {
description:
'Turn a PDF into JPG images. Choose the "pages" mode to render each page as a full JPG, or the "extract" mode to pull out only the raster images already embedded inside the PDF. Each run produces a new converted output, so re-running creates a fresh result rather than reusing a prior one.',
@@ -40,10 +42,12 @@ export const pdfToJpgAction = createAction({
context.propsValue;
return await runAndStoreResult({
- auth:context.auth.secret_text,
+ auth: context.auth.secret_text,
+ region: regionOf(context.propsValue.region),
+ webhook: webhookOf(context.propsValue.webhook_url),
files: context.files,
tool: 'pdfjpg',
- uploads: [fileToUploadInput(file)],
+ uploads: [fileToUploadInput({ file: file })],
options: {
pdfjpg_mode: pdfjpg_mode ?? 'pages',
},
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/protect-pdf.ts b/packages/pieces/community/iloveapi/src/lib/actions/protect-pdf.ts
index 51320109600..cc0e11bb486 100644
--- a/packages/pieces/community/iloveapi/src/lib/actions/protect-pdf.ts
+++ b/packages/pieces/community/iloveapi/src/lib/actions/protect-pdf.ts
@@ -1,6 +1,7 @@
import { Property, createAction } from '@activepieces/pieces-framework';
import { iloveapiAuth } from '../common/auth';
-import { fileToUploadInput, sharedProps } from '../common/props';
+import { iloveSchemas } from '../common/schemas';
+import { fileToUploadInput, regionOf, sharedProps, webhookOf } from '../common/props';
import { runAndStoreResult } from '../common/runner';
export const protectPdfAction = createAction({
@@ -10,6 +11,7 @@ export const protectPdfAction = createAction({
displayName: 'Protect PDF',
description: 'Add a password to a PDF document.',
audience: 'both',
+ outputSchema: iloveSchemas.toolResult,
aiMetadata: {
description:
'Encrypt a PDF with a password so it cannot be opened without that password. Use Unlock PDF for the reverse operation of removing a known password. Each run produces a new protected file.',
@@ -37,9 +39,11 @@ export const protectPdfAction = createAction({
return await runAndStoreResult({
auth: context.auth.secret_text,
+ region: regionOf(context.propsValue.region),
+ webhook: webhookOf(context.propsValue.webhook_url),
files: context.files,
tool: 'protect',
- uploads: [fileToUploadInput(file)],
+ uploads: [fileToUploadInput({ file: file })],
options: { password },
output_filename,
packaged_filename,
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/remove-background-image.ts b/packages/pieces/community/iloveapi/src/lib/actions/remove-background-image.ts
new file mode 100644
index 00000000000..9820a668d84
--- /dev/null
+++ b/packages/pieces/community/iloveapi/src/lib/actions/remove-background-image.ts
@@ -0,0 +1,42 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { iloveapiAuth } from '../common/auth';
+import { fileToUploadInput, regionOf, sharedProps, webhookOf } from '../common/props';
+import { runAndStoreResult } from '../common/runner';
+import { iloveSchemas } from '../common/schemas';
+
+export const removeBackgroundImageAction = createAction({
+ auth: iloveapiAuth,
+ name: 'remove_background_image',
+ classification: 'READ',
+ displayName: 'Remove Image Background',
+ description: 'Remove the background from a photo and return a PNG with transparency.',
+ audience: 'both',
+ outputSchema: iloveSchemas.toolResult,
+ aiMetadata: {
+ description:
+ 'Cut the subject out of a photo with iLoveIMG background removal and store the result as a new transparent PNG. Costs more credits than other image tools; each run creates a new file.',
+ idempotent: false,
+ },
+ props: {
+ file: Property.File({
+ displayName: 'Image',
+ required: true,
+ }),
+ ...sharedProps,
+ },
+ async run(context) {
+ const { file, output_filename, packaged_filename } = context.propsValue;
+ const options = {};
+ return await runAndStoreResult({
+ auth: context.auth.secret_text,
+ region: regionOf(context.propsValue.region),
+ webhook: webhookOf(context.propsValue.webhook_url),
+ files: context.files,
+ tool: 'removebackgroundimage',
+ uploads: [fileToUploadInput({ file: file, label: 'Image' })],
+ options,
+ output_filename,
+ packaged_filename,
+ });
+ },
+});
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/repair-pdf.ts b/packages/pieces/community/iloveapi/src/lib/actions/repair-pdf.ts
index 6495a5b9894..34a669ae13d 100644
--- a/packages/pieces/community/iloveapi/src/lib/actions/repair-pdf.ts
+++ b/packages/pieces/community/iloveapi/src/lib/actions/repair-pdf.ts
@@ -1,6 +1,7 @@
import { Property, createAction } from '@activepieces/pieces-framework';
import { iloveapiAuth } from '../common/auth';
-import { fileToUploadInput, sharedProps } from '../common/props';
+import { iloveSchemas } from '../common/schemas';
+import { fileToUploadInput, regionOf, sharedProps, webhookOf } from '../common/props';
import { runAndStoreResult } from '../common/runner';
export const repairPdfAction = createAction({
@@ -10,6 +11,7 @@ export const repairPdfAction = createAction({
displayName: 'Repair PDF',
description: 'Attempt to fix a damaged or corrupted PDF file.',
audience: 'both',
+ outputSchema: iloveSchemas.toolResult,
aiMetadata: {
description:
'Attempt to recover a damaged or corrupted PDF into a readable file. Best-effort: success depends on the extent of corruption and is not guaranteed. Each run produces a new output file.',
@@ -27,9 +29,11 @@ export const repairPdfAction = createAction({
return await runAndStoreResult({
auth: context.auth.secret_text,
+ region: regionOf(context.propsValue.region),
+ webhook: webhookOf(context.propsValue.webhook_url),
files: context.files,
tool: 'repair',
- uploads: [fileToUploadInput(file)],
+ uploads: [fileToUploadInput({ file: file })],
output_filename,
packaged_filename,
});
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/resize-image.ts b/packages/pieces/community/iloveapi/src/lib/actions/resize-image.ts
new file mode 100644
index 00000000000..52778749df8
--- /dev/null
+++ b/packages/pieces/community/iloveapi/src/lib/actions/resize-image.ts
@@ -0,0 +1,120 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { iloveapiAuth } from '../common/auth';
+import { fileToUploadInput, regionOf, sharedProps, webhookOf } from '../common/props';
+import { runAndStoreResult } from '../common/runner';
+import { iloveSchemas } from '../common/schemas';
+
+export const resizeImageAction = createAction({
+ auth: iloveapiAuth,
+ name: 'resize_image',
+ classification: 'READ',
+ displayName: 'Resize Image',
+ description: 'Resize an image by exact pixels or by percentage.',
+ audience: 'both',
+ outputSchema: iloveSchemas.toolResult,
+ aiMetadata: {
+ description:
+ 'Resize an image with iLoveIMG, either to a width/height in pixels (optionally keeping the aspect ratio) or by a percentage of the original size. Pixel mode needs at least a width or a height; percentage mode needs the percentage. Each run creates a new file and spends credits.',
+ idempotent: false,
+ },
+ props: {
+ file: Property.File({
+ displayName: 'Image',
+ required: true,
+ }),
+ resize_mode: Property.StaticDropdown({
+ displayName: 'Resize Mode',
+ required: true,
+ defaultValue: 'pixels',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'By pixels', value: 'pixels' },
+ { label: 'By percentage', value: 'percentage' },
+ ],
+ },
+ }),
+ pixels_width: Property.Number({
+ displayName: 'Width (px)',
+ description: 'Used with "By pixels".',
+ required: false,
+ }),
+ pixels_height: Property.Number({
+ displayName: 'Height (px)',
+ description: 'Used with "By pixels".',
+ required: false,
+ }),
+ maintain_ratio: Property.Checkbox({
+ displayName: 'Keep Aspect Ratio',
+ description: 'Used with "By pixels".',
+ required: false,
+ defaultValue: true,
+ }),
+ percentage: Property.Number({
+ displayName: 'Percentage',
+ description: 'Used with "By percentage". 1 to 1000.',
+ required: false,
+ }),
+ no_enlarge_if_smaller: Property.Checkbox({
+ displayName: 'Do Not Enlarge Smaller Images',
+ required: false,
+ defaultValue: true,
+ }),
+ ...sharedProps,
+ },
+ async run(context) {
+ const {
+ file,
+ resize_mode,
+ pixels_width,
+ pixels_height,
+ maintain_ratio,
+ percentage,
+ no_enlarge_if_smaller,
+ output_filename,
+ packaged_filename,
+ } = context.propsValue;
+
+ const options: Record<string, unknown> = {
+ resize_mode,
+ no_enlarge_if_smaller: no_enlarge_if_smaller ?? true,
+ };
+ if (resize_mode === 'percentage') {
+ if (percentage === undefined || percentage === null || !Number.isInteger(percentage) || percentage < 1 || percentage > 1000) {
+ throw new Error('"Percentage" must be a whole number between 1 and 1000 in percentage mode.');
+ }
+ options['percentage'] = percentage;
+ } else if (resize_mode === 'pixels') {
+ const width = positiveInt({ value: pixels_width, label: 'Width (px)' });
+ const height = positiveInt({ value: pixels_height, label: 'Height (px)' });
+ if (width === undefined && height === undefined) {
+ throw new Error('Give a width, a height or both in pixel mode.');
+ }
+ options['maintain_ratio'] = maintain_ratio ?? true;
+ if (width !== undefined) options['pixels_width'] = width;
+ if (height !== undefined) options['pixels_height'] = height;
+ } else {
+ throw new Error('Resize Mode must be "pixels" or "percentage".');
+ }
+
+ return await runAndStoreResult({
+ auth: context.auth.secret_text,
+ region: regionOf(context.propsValue.region),
+ webhook: webhookOf(context.propsValue.webhook_url),
+ files: context.files,
+ tool: 'resizeimage',
+ uploads: [fileToUploadInput({ file: file, label: 'Image' })],
+ options,
+ output_filename,
+ packaged_filename,
+ });
+ },
+});
+
+function positiveInt({ value, label }: { value: number | undefined | null; label: string }): number | undefined {
+ if (value === undefined || value === null) return undefined;
+ if (!Number.isInteger(value) || value < 1) {
+ throw new Error(`"${label}" must be a whole number, 1 or more.`);
+ }
+ return value;
+}
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/rotate-image.ts b/packages/pieces/community/iloveapi/src/lib/actions/rotate-image.ts
new file mode 100644
index 00000000000..9d8a1b9b885
--- /dev/null
+++ b/packages/pieces/community/iloveapi/src/lib/actions/rotate-image.ts
@@ -0,0 +1,61 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { iloveapiAuth } from '../common/auth';
+import { fileToUploadInput, regionOf, sharedProps, webhookOf } from '../common/props';
+import { runAndStoreResult } from '../common/runner';
+import { iloveSchemas } from '../common/schemas';
+
+export const rotateImageAction = createAction({
+ auth: iloveapiAuth,
+ name: 'rotate_image',
+ classification: 'READ',
+ displayName: 'Rotate Image',
+ description: 'Rotate an image by 90, 180 or 270 degrees.',
+ audience: 'both',
+ outputSchema: iloveSchemas.toolResult,
+ aiMetadata: {
+ description:
+ 'Rotate an image clockwise by 90, 180 or 270 degrees with iLoveIMG and store the result as a new file. Each run spends credits.',
+ idempotent: false,
+ },
+ props: {
+ file: Property.File({
+ displayName: 'Image',
+ required: true,
+ }),
+ rotation: Property.StaticDropdown({
+ displayName: 'Rotation',
+ required: true,
+ defaultValue: 90,
+ options: {
+ disabled: false,
+ options: [
+ { label: '90° clockwise', value: 90 },
+ { label: '180°', value: 180 },
+ { label: '270° (90° counter-clockwise)', value: 270 },
+ ],
+ },
+ }),
+ ...sharedProps,
+ },
+ async run(context) {
+ const { file, rotation, output_filename, packaged_filename } = context.propsValue;
+ const rotate = ROTATIONS.find((value) => value === Number(rotation));
+ if (rotate === undefined) {
+ throw new Error('Rotation must be 90, 180 or 270.');
+ }
+
+ return await runAndStoreResult({
+ auth: context.auth.secret_text,
+ region: regionOf(context.propsValue.region),
+ webhook: webhookOf(context.propsValue.webhook_url),
+ files: context.files,
+ tool: 'rotateimage',
+ uploads: [fileToUploadInput({ file: file, label: 'Image' })],
+ perFileOverrides: [{ rotate }],
+ output_filename,
+ packaged_filename,
+ });
+ },
+});
+
+const ROTATIONS = [90, 180, 270] as const;
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/rotate-pdf.ts b/packages/pieces/community/iloveapi/src/lib/actions/rotate-pdf.ts
index ee4a28bc6f6..f17338fe2b0 100644
--- a/packages/pieces/community/iloveapi/src/lib/actions/rotate-pdf.ts
+++ b/packages/pieces/community/iloveapi/src/lib/actions/rotate-pdf.ts
@@ -1,6 +1,7 @@
import { Property, createAction } from '@activepieces/pieces-framework';
import { iloveapiAuth } from '../common/auth';
-import { fileToUploadInput, sharedProps } from '../common/props';
+import { iloveSchemas } from '../common/schemas';
+import { fileToUploadInput, regionOf, sharedProps, webhookOf } from '../common/props';
import { runAndStoreResult } from '../common/runner';
export const rotatePdfAction = createAction({
@@ -10,6 +11,7 @@ export const rotatePdfAction = createAction({
displayName: 'Rotate PDF',
description: 'Rotate every page of a PDF by 90, 180, or 270 degrees.',
audience: 'both',
+ outputSchema: iloveSchemas.toolResult,
aiMetadata: {
description:
'Rotate all pages of a PDF by a fixed 90, 180, or 270 degrees. The rotation is relative to the current orientation, so it is not idempotent: applying it repeatedly keeps turning the pages rather than settling on an absolute angle.',
@@ -43,9 +45,11 @@ export const rotatePdfAction = createAction({
return await runAndStoreResult({
auth: context.auth.secret_text,
+ region: regionOf(context.propsValue.region),
+ webhook: webhookOf(context.propsValue.webhook_url),
files: context.files,
tool: 'rotate',
- uploads: [fileToUploadInput(file)],
+ uploads: [fileToUploadInput({ file: file })],
perFileOverrides: [{ rotate: rotateValue }],
output_filename,
packaged_filename,
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/send-signer-reminder.ts b/packages/pieces/community/iloveapi/src/lib/actions/send-signer-reminder.ts
index 9a00fced457..810de3a0b5e 100644
--- a/packages/pieces/community/iloveapi/src/lib/actions/send-signer-reminder.ts
+++ b/packages/pieces/community/iloveapi/src/lib/actions/send-signer-reminder.ts
@@ -1,6 +1,7 @@
import { Property, createAction } from '@activepieces/pieces-framework';
import { iloveapiAuth } from '../common/auth';
import { iLoveApi } from '../common/client';
+import { iloveSchemas } from '../common/schemas';
export const sendSignerReminderAction = createAction({
auth: iloveapiAuth,
@@ -10,6 +11,7 @@ export const sendSignerReminderAction = createAction({
description:
'Email a reminder to signers who have not yet completed the signature. Limited to 2 calls per day.',
audience: 'both',
+ outputSchema: iloveSchemas.signatureAck,
aiMetadata: {
description:
'Send a manual nudge email to outstanding signers of an existing signature request, identified by its requester token. Each call sends a fresh reminder (not idempotent) and the provider caps this at 2 calls per day per request; for scheduled automatic reminders configure them on the request itself at creation time instead.',
@@ -23,17 +25,19 @@ export const sendSignerReminderAction = createAction({
}),
},
async run(context) {
- const { token_requester } = context.propsValue;
- if (!token_requester) {
+ const tokenRequester = (context.propsValue.token_requester ?? '').trim();
+ if (!tokenRequester) {
throw new Error('Requester Token is required.');
}
const token = await iLoveApi.authenticate({
publicKey: context.auth.secret_text,
});
- return await iLoveApi.sendSignerReminder({
- token,
- tokenRequester: token_requester,
- });
+ const response = await iLoveApi.sendSignerReminder({ token, tokenRequester });
+ return {
+ ...response,
+ success: true,
+ token_requester: tokenRequester,
+ };
},
});
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/split-pdf.ts b/packages/pieces/community/iloveapi/src/lib/actions/split-pdf.ts
index f1798f0fa77..5266049786b 100644
--- a/packages/pieces/community/iloveapi/src/lib/actions/split-pdf.ts
+++ b/packages/pieces/community/iloveapi/src/lib/actions/split-pdf.ts
@@ -1,6 +1,7 @@
import { Property, createAction } from '@activepieces/pieces-framework';
import { iloveapiAuth } from '../common/auth';
-import { fileToUploadInput, sharedProps } from '../common/props';
+import { iloveSchemas } from '../common/schemas';
+import { fileToUploadInput, regionOf, sharedProps, webhookOf } from '../common/props';
import { runAndStoreResult } from '../common/runner';
export const splitPdfAction = createAction({
@@ -11,6 +12,7 @@ export const splitPdfAction = createAction({
description:
'Split a PDF by page ranges, fixed page batches, removed pages, or target file size.',
audience: 'both',
+ outputSchema: iloveSchemas.toolResult,
aiMetadata: {
description:
'Split one PDF into multiple PDFs via the iLoveAPI service. Pick this to break a document apart by explicit page ranges, fixed batches of N pages, by removing specific pages, or by a maximum output file size (MB) — the split mode determines which range/size input is required. Optionally merge the pieces back into a single PDF. Each call produces new output files, so repeated runs are not idempotent.',
@@ -89,13 +91,19 @@ export const splitPdfAction = createAction({
if (!ranges) {
throw new Error('"Ranges" is required when split mode is "Page Ranges".');
}
- options['ranges'] = ranges;
+ if (!PAGE_LIST.test(ranges.replace(/\s/g, ''))) {
+ throw new Error('"Ranges" must look like "1-5,7,10-13".');
+ }
+ options['ranges'] = ranges.replace(/\s/g, '');
} else if (split_mode === 'fixed_range') {
if (fixed_range === undefined || fixed_range === null) {
throw new Error(
'"Fixed Range Size" is required when split mode is "Fixed Range".'
);
}
+ if (!Number.isInteger(fixed_range) || fixed_range < 1) {
+ throw new Error('"Fixed Range Size" must be a whole number of pages, 1 or more.');
+ }
options['fixed_range'] = fixed_range;
} else if (split_mode === 'remove_pages') {
if (!remove_pages) {
@@ -103,24 +111,34 @@ export const splitPdfAction = createAction({
'"Remove Pages" is required when split mode is "Remove Pages".'
);
}
- options['remove_pages'] = remove_pages;
+ if (!PAGE_LIST.test(remove_pages.replace(/\s/g, ''))) {
+ throw new Error('"Remove Pages" must look like "2,4-6".');
+ }
+ options['remove_pages'] = remove_pages.replace(/\s/g, '');
} else if (split_mode === 'filesize') {
if (filesize === undefined || filesize === null) {
throw new Error(
'"File Size (MB)" is required when split mode is "By File Size".'
);
}
- options['filesize'] = filesize;
+ if (!(filesize > 0)) {
+ throw new Error('"File Size (MB)" must be greater than 0.');
+ }
+ options['filesize'] = Math.round(filesize * 1024 * 1024);
}
return await runAndStoreResult({
auth: context.auth.secret_text,
+ region: regionOf(context.propsValue.region),
+ webhook: webhookOf(context.propsValue.webhook_url),
files: context.files,
tool: 'split',
- uploads: [fileToUploadInput(file)],
+ uploads: [fileToUploadInput({ file: file })],
options,
output_filename,
packaged_filename,
});
},
});
+
+const PAGE_LIST = /^\d+(-\d+)?(,\d+(-\d+)?)*$/;
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/unlock-pdf.ts b/packages/pieces/community/iloveapi/src/lib/actions/unlock-pdf.ts
index cd3b16e5875..8b2a6c8dc72 100644
--- a/packages/pieces/community/iloveapi/src/lib/actions/unlock-pdf.ts
+++ b/packages/pieces/community/iloveapi/src/lib/actions/unlock-pdf.ts
@@ -1,6 +1,7 @@
import { Property, createAction } from '@activepieces/pieces-framework';
import { iloveapiAuth } from '../common/auth';
-import { sharedProps } from '../common/props';
+import { iloveSchemas } from '../common/schemas';
+import { fileToUploadInput, regionOf, sharedProps, webhookOf } from '../common/props';
import { runAndStoreResult } from '../common/runner';
export const unlockPdfAction = createAction({
@@ -10,6 +11,7 @@ export const unlockPdfAction = createAction({
displayName: 'Unlock PDF',
description: 'Remove the password from a PDF (you must know the current password).',
audience: 'both',
+ outputSchema: iloveSchemas.toolResult,
aiMetadata: {
description:
'Strip password protection from a PDF, producing an unencrypted copy. You must supply the current password that protects the file. Use the Protect PDF action for the reverse operation of adding a password. Each run produces a new output file.',
@@ -37,14 +39,11 @@ export const unlockPdfAction = createAction({
return await runAndStoreResult({
auth: context.auth.secret_text,
+ region: regionOf(context.propsValue.region),
+ webhook: webhookOf(context.propsValue.webhook_url),
files: context.files,
tool: 'unlock',
- uploads: [
- {
- kind: 'file',
- file: { base64: file.base64, filename: file.filename },
- },
- ],
+ uploads: [fileToUploadInput({ file: file, label: 'PDF File' })],
perFileOverrides: [{ password }],
output_filename,
packaged_filename,
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/upscale-image.ts b/packages/pieces/community/iloveapi/src/lib/actions/upscale-image.ts
new file mode 100644
index 00000000000..34783f6b550
--- /dev/null
+++ b/packages/pieces/community/iloveapi/src/lib/actions/upscale-image.ts
@@ -0,0 +1,58 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { iloveapiAuth } from '../common/auth';
+import { fileToUploadInput, regionOf, sharedProps, webhookOf } from '../common/props';
+import { runAndStoreResult } from '../common/runner';
+import { iloveSchemas } from '../common/schemas';
+
+export const upscaleImageAction = createAction({
+ auth: iloveapiAuth,
+ name: 'upscale_image',
+ classification: 'READ',
+ displayName: 'Upscale Image',
+ description: 'Enlarge an image 2x or 4x with AI upscaling.',
+ audience: 'both',
+ outputSchema: iloveSchemas.toolResult,
+ aiMetadata: {
+ description:
+ 'Increase the resolution of an image by 2x or 4x with iLoveIMG upscaling and store the enlarged copy as a new file. Costs more credits than other image tools; each run creates a new file.',
+ idempotent: false,
+ },
+ props: {
+ file: Property.File({
+ displayName: 'Image',
+ required: true,
+ }),
+ multiplier: Property.StaticDropdown({
+ displayName: 'Scale',
+ required: true,
+ defaultValue: 2,
+ options: {
+ disabled: false,
+ options: [
+ { label: '2x', value: 2 },
+ { label: '4x', value: 4 },
+ ],
+ },
+ }),
+ ...sharedProps,
+ },
+ async run(context) {
+ const { file, output_filename, packaged_filename } = context.propsValue;
+ const multiplier = Number(context.propsValue.multiplier ?? 2);
+ if (multiplier !== 2 && multiplier !== 4) {
+ throw new Error('Scale must be 2 or 4.');
+ }
+ const options = { multiplier };
+ return await runAndStoreResult({
+ auth: context.auth.secret_text,
+ region: regionOf(context.propsValue.region),
+ webhook: webhookOf(context.propsValue.webhook_url),
+ files: context.files,
+ tool: 'upscaleimage',
+ uploads: [fileToUploadInput({ file: file, label: 'Image' })],
+ options,
+ output_filename,
+ packaged_filename,
+ });
+ },
+});
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/validate-pdfa.ts b/packages/pieces/community/iloveapi/src/lib/actions/validate-pdfa.ts
new file mode 100644
index 00000000000..a826346e672
--- /dev/null
+++ b/packages/pieces/community/iloveapi/src/lib/actions/validate-pdfa.ts
@@ -0,0 +1,62 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { iloveapiAuth } from '../common/auth';
+import { iLoveApi } from '../common/client';
+import { CONFORMANCE_OPTIONS, fileToUploadInput, regionOf, regionProp, webhookOf, webhookUrlProp } from '../common/props';
+import { iloveSchemas } from '../common/schemas';
+
+export const validatePdfaAction = createAction({
+ auth: iloveapiAuth,
+ name: 'validate_pdfa',
+ classification: 'READ',
+ displayName: 'Validate PDF/A',
+ description: 'Check whether a PDF conforms to a PDF/A level.',
+ audience: 'both',
+ outputSchema: iloveSchemas.validatePdfa,
+ aiMetadata: {
+ description:
+ 'Check whether a PDF meets a PDF/A conformance level, returning a per-file validation result and an overall "conformant" flag. Does not change the file and creates no output file, but each run spends iLoveAPI credits. Use Convert PDF to PDF/A to fix a non-conformant file.',
+ idempotent: true,
+ },
+ props: {
+ file: Property.File({
+ displayName: 'PDF File',
+ required: true,
+ }),
+ conformance: Property.StaticDropdown({
+ displayName: 'Conformance Level',
+ required: false,
+ defaultValue: 'pdfa-2b',
+ options: {
+ disabled: false,
+ options: CONFORMANCE_OPTIONS,
+ },
+ }),
+ region: regionProp,
+ webhook_url: webhookUrlProp,
+ },
+ async run(context) {
+ const result = await iLoveApi.runTask({
+ publicKey: context.auth.secret_text,
+ region: regionOf(context.propsValue.region),
+ webhook: webhookOf(context.propsValue.webhook_url),
+ tool: 'validatepdfa',
+ uploads: [fileToUploadInput({ file: context.propsValue.file, label: 'PDF File' })],
+ options: { conformance: context.propsValue.conformance ?? 'pdfa-2b' },
+ skipDownload: true,
+ });
+ const raw = result.process['validations'];
+ const validations = Array.isArray(raw)
+ ? raw.filter((item): item is Record<string, unknown> => iLoveApi.isRecord(item))
+ : [];
+ return {
+ conformant:
+ validations.length > 0 &&
+ validations.every((item) => String(item['status']).toLowerCase() === 'conformant'),
+ validations,
+ status: result.process.status,
+ timer: result.process.timer,
+ task: result.task,
+ remaining_credits: result.remainingCredits,
+ };
+ },
+});
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/void-signature.ts b/packages/pieces/community/iloveapi/src/lib/actions/void-signature.ts
index 27ba2e3c729..c5b85ac393c 100644
--- a/packages/pieces/community/iloveapi/src/lib/actions/void-signature.ts
+++ b/packages/pieces/community/iloveapi/src/lib/actions/void-signature.ts
@@ -1,6 +1,7 @@
import { Property, createAction } from '@activepieces/pieces-framework';
import { iloveapiAuth } from '../common/auth';
import { iLoveApi } from '../common/client';
+import { iloveSchemas } from '../common/schemas';
export const voidSignatureAction = createAction({
auth: iloveapiAuth,
@@ -10,6 +11,7 @@ export const voidSignatureAction = createAction({
description:
'Cancel an in-progress signature request. The document becomes inaccessible to all signers.',
audience: 'both',
+ outputSchema: iloveSchemas.signatureAck,
aiMetadata: {
description:
'Permanently cancel an in-progress signature request by its requester token, after which the document can no longer be signed and becomes inaccessible to every signer. This is a destructive, irreversible state change; calling it again on an already-voided request has no further effect.',
@@ -23,17 +25,19 @@ export const voidSignatureAction = createAction({
}),
},
async run(context) {
- const { token_requester } = context.propsValue;
- if (!token_requester) {
+ const tokenRequester = (context.propsValue.token_requester ?? '').trim();
+ if (!tokenRequester) {
throw new Error('Requester Token is required.');
}
const token = await iLoveApi.authenticate({
publicKey: context.auth.secret_text,
});
- return await iLoveApi.voidSignature({
- token,
- tokenRequester: token_requester,
- });
+ const response = await iLoveApi.voidSignature({ token, tokenRequester });
+ return {
+ ...response,
+ success: true,
+ token_requester: tokenRequester,
+ };
},
});
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/watermark-image.ts b/packages/pieces/community/iloveapi/src/lib/actions/watermark-image.ts
new file mode 100644
index 00000000000..27f0583e907
--- /dev/null
+++ b/packages/pieces/community/iloveapi/src/lib/actions/watermark-image.ts
@@ -0,0 +1,142 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { iloveapiAuth } from '../common/auth';
+import { fileToUploadInput, regionOf, sharedProps, webhookOf } from '../common/props';
+import { runAndStoreResult } from '../common/runner';
+import { iloveSchemas } from '../common/schemas';
+
+const GRAVITIES = [
+ 'North',
+ 'NorthEast',
+ 'NorthWest',
+ 'Center',
+ 'CenterEast',
+ 'CenterWest',
+ 'East',
+ 'West',
+ 'South',
+ 'SouthEast',
+ 'SouthWest',
+];
+
+export const watermarkImageAction = createAction({
+ auth: iloveapiAuth,
+ name: 'watermark_image',
+ classification: 'READ',
+ displayName: 'Watermark Image',
+ description: 'Stamp a logo or picture as a watermark on an image.',
+ audience: 'both',
+ outputSchema: iloveSchemas.toolResult,
+ aiMetadata: {
+ description:
+ 'Stamp a watermark picture (for example a logo, JPG or PNG) on an image with iLoveIMG. Position is a gravity such as Center or SouthEast; size is a percent of the base image. Text watermarks are not supported on images; use Watermark PDF for text. Each run creates a new file and spends credits.',
+ idempotent: false,
+ },
+ props: {
+ file: Property.File({
+ displayName: 'Image',
+ required: true,
+ }),
+ image: Property.File({
+ displayName: 'Watermark Image',
+ description: 'JPG or PNG to stamp on the image, for example a logo.',
+ required: true,
+ }),
+ gravity: Property.StaticDropdown({
+ displayName: 'Position',
+ required: false,
+ defaultValue: 'Center',
+ options: {
+ disabled: false,
+ options: GRAVITIES.map((value) => ({ label: value, value })),
+ },
+ }),
+ width_percent: Property.Number({
+ displayName: 'Width (% of image width)',
+ description: '1 to 100. Default 30.',
+ required: false,
+ }),
+ height_percent: Property.Number({
+ displayName: 'Height (% of image height)',
+ description: '1 to 100. Default 30.',
+ required: false,
+ }),
+ rotation: Property.Number({
+ displayName: 'Rotation (degrees)',
+ description: '0 to 360.',
+ required: false,
+ }),
+ transparency: Property.Number({
+ displayName: 'Opacity (%)',
+ description: '1 (almost invisible) to 100 (solid). Default 100.',
+ required: false,
+ }),
+ mosaic: Property.Checkbox({
+ displayName: 'Mosaic',
+ description: 'Repeat the watermark across the whole image.',
+ required: false,
+ defaultValue: false,
+ }),
+ ...sharedProps,
+ },
+ async run(context) {
+ const {
+ file,
+ image,
+ gravity,
+ width_percent,
+ height_percent,
+ rotation,
+ transparency,
+ mosaic,
+ output_filename,
+ packaged_filename,
+ } = context.propsValue;
+
+ if (gravity && !GRAVITIES.includes(gravity)) {
+ throw new Error(`Position must be one of: ${GRAVITIES.join(', ')}.`);
+ }
+ const width = percent({ value: width_percent, label: 'Width', min: 1 }) ?? 30;
+ const height = percent({ value: height_percent, label: 'Height', min: 1 }) ?? 30;
+ const opacity = percent({ value: transparency, label: 'Opacity', min: 1 }) ?? 100;
+ if (rotation !== undefined && rotation !== null && (rotation < 0 || rotation > 360)) {
+ throw new Error('Rotation must be between 0 and 360 degrees.');
+ }
+ const stamp = fileToUploadInput({ file: image, label: 'Watermark Image' });
+
+ return await runAndStoreResult({
+ auth: context.auth.secret_text,
+ region: regionOf(context.propsValue.region),
+ webhook: webhookOf(context.propsValue.webhook_url),
+ files: context.files,
+ tool: 'watermarkimage',
+ uploads: [fileToUploadInput({ file: file, label: 'Image' })],
+ extraUploads: [stamp],
+ options: (extras) => ({
+ elements: [
+ {
+ type: 'image',
+ server_filename: extras[0],
+ gravity: gravity ?? 'Center',
+ width_percent: width,
+ height_percent: height,
+ x_pos_percent: 0,
+ y_pos_percent: 0,
+ rotation: rotation ?? 0,
+ transparency: opacity,
+ mosaic: mosaic ?? false,
+ },
+ ],
+ }),
+ output_filename,
+ packaged_filename,
+ });
+ },
+});
+
+function percent({ value, label, min }: { value: number | undefined | null; label: string; min: number }): number | undefined {
+ if (value === undefined || value === null) return undefined;
+ if (!Number.isFinite(value) || value < min || value > 100) {
+ throw new Error(`${label} must be between ${min} and 100 percent.`);
+ }
+ return value;
+}
diff --git a/packages/pieces/community/iloveapi/src/lib/actions/watermark-pdf.ts b/packages/pieces/community/iloveapi/src/lib/actions/watermark-pdf.ts
index 47130542bda..141a1352abd 100644
--- a/packages/pieces/community/iloveapi/src/lib/actions/watermark-pdf.ts
+++ b/packages/pieces/community/iloveapi/src/lib/actions/watermark-pdf.ts
@@ -1,6 +1,7 @@
import { Property, createAction } from '@activepieces/pieces-framework';
import { iloveapiAuth } from '../common/auth';
-import { fileToUploadInput, sharedProps } from '../common/props';
+import { iloveSchemas } from '../common/schemas';
+import { fileToUploadInput, regionOf, sharedProps, webhookOf } from '../common/props';
import { runAndStoreResult } from '../common/runner';
import { UploadInput } from '../common/client';
@@ -11,6 +12,7 @@ export const watermarkPdfAction = createAction({
displayName: 'Watermark PDF',
description: 'Stamp a text or image watermark across pages of a PDF.',
audience: 'both',
+ outputSchema: iloveSchemas.toolResult,
aiMetadata: {
description:
'Overlay a watermark onto chosen pages of a PDF. Pick "text" mode to stamp a string (with font, color, rotation, transparency, mosaic, and layer controls) or "image" mode to stamp a supplied JPG/PNG; the matching text or image input is required for the selected mode. Each run writes a new watermarked file rather than reusing a previous result.',
@@ -176,11 +178,17 @@ export const watermarkPdfAction = createAction({
if (mode === 'text' && !text) {
throw new Error('"Text" is required when watermark mode is "Text".');
}
- if (mode === 'image' && !image?.base64) {
+ if (mode === 'image' && !image) {
throw new Error(
'A watermark image is required when watermark mode is "Image".'
);
}
+ if (rotation !== undefined && rotation !== null && (rotation < 0 || rotation > 360)) {
+ throw new Error('Rotation must be between 0 and 360 degrees.');
+ }
+ if (transparency !== undefined && transparency !== null && (transparency < 0 || transparency > 100)) {
+ throw new Error('Transparency must be between 0 and 100.');
+ }
const baseOptions: Record<string, unknown> = {
mode,
@@ -202,20 +210,15 @@ export const watermarkPdfAction = createAction({
}
const extraUploads: UploadInput[] | undefined =
- mode === 'image' && image?.base64
- ? [
- {
- kind: 'file',
- file: { base64: image.base64, filename: image.filename },
- },
- ]
- : undefined;
+ mode === 'image' ? [fileToUploadInput({ file: image, label: 'Watermark Image' })] : undefined;
return await runAndStoreResult({
auth: context.auth.secret_text,
+ region: regionOf(context.propsValue.region),
+ webhook: webhookOf(context.propsValue.webhook_url),
files: context.files,
tool: 'watermark',
- uploads: [fileToUploadInput(file)],
+ uploads: [fileToUploadInput({ file: file })],
extraUploads,
options: (extras) => {
if (mode === 'image') {
diff --git a/packages/pieces/community/iloveapi/src/lib/common/auth.ts b/packages/pieces/community/iloveapi/src/lib/common/auth.ts
index 1f965bc79a4..9615b8d7a9e 100644
--- a/packages/pieces/community/iloveapi/src/lib/common/auth.ts
+++ b/packages/pieces/community/iloveapi/src/lib/common/auth.ts
@@ -1,5 +1,5 @@
import { PieceAuth } from '@activepieces/pieces-framework';
-import { iLoveApi } from './client';
+import { ILoveApiError, iLoveApi } from './client';
export const iloveapiAuth = PieceAuth.SecretText({
displayName: 'Project Public Key',
@@ -18,10 +18,15 @@ Only the public key is required. Tokens are issued automatically per request.
try {
await iLoveApi.authenticate({ publicKey: auth });
return { valid: true };
- } catch {
+ } catch (error) {
+ const status = error instanceof ILoveApiError ? error.status : undefined;
+ if (status === 401 || status === 403) {
+ return { valid: false, error: 'Invalid iLoveAPI project public key.' };
+ }
+ const reason = error instanceof Error ? error.message : String(error);
return {
valid: false,
- error: 'Invalid iLoveAPI project public key.',
+ error: `Could not verify the key with iLoveAPI right now: ${reason}`,
};
}
},
diff --git a/packages/pieces/community/iloveapi/src/lib/common/client.ts b/packages/pieces/community/iloveapi/src/lib/common/client.ts
index e013fdc12ce..54af67822ab 100644
--- a/packages/pieces/community/iloveapi/src/lib/common/client.ts
+++ b/packages/pieces/community/iloveapi/src/lib/common/client.ts
@@ -1,14 +1,13 @@
-import {
- AuthenticationType,
- HttpMethod,
- HttpRequest,
- httpClient,
-} from '@activepieces/pieces-common';
-import FormData from 'form-data';
+import { Readable } from 'stream';
+import { HttpMethod, httpClient } from '@activepieces/pieces-common';
+import type FormData from 'form-data';
+import { iloveHost } from './host';
+import { SignatureDraft, buildSignatureRequest } from './signature';
import {
AuthResponse,
CreateSignatureRequest,
CreateSignatureResponse,
+ ILoveApiRegion,
ILoveApiTool,
ProcessFile,
ProcessRequest,
@@ -17,30 +16,233 @@ import {
UploadResponse,
} from './types';
-const ROOT_API = 'https://api.ilovepdf.com';
+const PDF_API = 'https://api.ilovepdf.com';
+const IMG_API = 'https://api.iloveimg.com';
+const REQUEST_TIMEOUT_MS = 60_000;
+const UPLOAD_TIMEOUT_MS = 120_000;
+const PROCESS_TIMEOUT_MS = 240_000;
+const DOWNLOAD_TIMEOUT_MS = 120_000;
+const MAX_DOWNLOAD_BYTES = 100 * 1024 * 1024;
+const MAX_ATTEMPTS = 4;
+const TASK_BUDGET_MS = 520_000;
+const TASK_TIMEOUT_MESSAGE = 'iLoveAPI did not finish within the step time limit. Try a smaller file or fewer files.';
+const MAX_SIGNATURE_FILES = 5;
+const BASE_BACKOFF_MS = 2_000;
+const MAX_BACKOFF_MS = 20_000;
+
+let verifiedTlsAgent: Promise<unknown> | undefined;
+
+export class ILoveApiError extends Error {
+ constructor(
+ message: string,
+ public readonly status: number,
+ public readonly responseBody: unknown
+ ) {
+ super(message);
+ this.name = 'ILoveApiError';
+ }
+}
+
+function verifiedTls(): Promise<unknown> {
+ verifiedTlsAgent ??= import('undici').then(
+ ({ Agent }) => new Agent({ connect: { rejectUnauthorized: true } })
+ );
+ return verifiedTlsAgent;
+}
+
+function isFormData(value: RequestBody | undefined): value is FormData {
+ return value !== undefined && typeof Reflect.get(value, 'getHeaders') === 'function';
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+function failureOf(error: unknown): { status: number; body: unknown } | null {
+ if (error === null || typeof error !== 'object') return null;
+ const response = Reflect.get(error, 'response');
+ if (!isRecord(response)) return null;
+ const status = response['status'];
+ return typeof status === 'number' ? { status, body: response['body'] } : null;
+}
+
+function vendorMessage(body: unknown): string {
+ if (isRecord(body)) {
+ const nested = body['error'];
+ if (isRecord(nested)) {
+ const parts = [nested['type'], nested['message']]
+ .filter((part) => typeof part === 'string' && part.trim() !== '')
+ .map(String);
+ const param = nested['param'];
+ if (isRecord(param) || Array.isArray(param)) {
+ parts.push(JSON.stringify(param).slice(0, 300));
+ }
+ if (parts.length > 0) return parts.join(': ');
+ }
+ const parts = [body['name'], body['message']]
+ .filter((part) => typeof part === 'string' && part.trim() !== '')
+ .map(String);
+ if (parts.length > 0) return parts.join(': ');
+ }
+ if (typeof body === 'string' && body.trim()) return body.trim().slice(0, 300);
+ return 'request failed';
+}
+
+function hintFor({ status, message }: { status: number; message: string }): string {
+ if (/WrongPassword/i.test(message)) {
+ return ' The PDF password is wrong. Check the password and try again.';
+ }
+ if (status === 401) return ' Check the project public key or reconnect your iLoveAPI account.';
+ if (status === 403) return ' This project has no access to this resource.';
+ if (status === 404) return ' The task, file or signature was not found. Tasks are deleted 2 hours after processing.';
+ if (status === 429) return ' iLoveAPI rate limit reached; try again later.';
+ return '';
+}
+
+function toApiError({ status, body }: { status: number; body: unknown }): ILoveApiError {
+ const message = vendorMessage(body).replace(/\.$/, '');
+ return new ILoveApiError(
+ `iLoveAPI error (${status}): ${message}.${hintFor({ status, message })}`,
+ status,
+ body
+ );
+}
+
+function backoffFor(attempt: number): number {
+ return Math.min(BASE_BACKOFF_MS * 2 ** attempt, MAX_BACKOFF_MS);
+}
+
+type RequestBody = Record<string, unknown> | FormData;
+
+async function request<T>({
+ method,
+ url,
+ token,
+ body,
+ query,
+ timeout,
+ deadline,
+}: {
+ method: HttpMethod;
+ url: string;
+ token?: string;
+ body?: () => RequestBody;
+ query?: Record<string, string>;
+ timeout?: number;
+ deadline?: number;
+}): Promise<T> {
+ if (!iloveHost.isAllowedUrl(url)) {
+ throw new Error('Refusing to send iLoveAPI credentials to a URL outside the iLoveAPI hosts.');
+ }
+ const dispatcher = await verifiedTls();
+ for (let attempt = 0; ; attempt++) {
+ const requestTimeout = boundedTimeout({ timeout: timeout ?? REQUEST_TIMEOUT_MS, deadline });
+ const payload = body?.();
+ const headers: Record<string, string> = { Accept: 'application/json' };
+ if (token) headers['Authorization'] = `Bearer ${token}`;
+ if (isFormData(payload)) {
+ Object.assign(headers, payload.getHeaders());
+ } else if (payload !== undefined) {
+ headers['Content-Type'] = 'application/json';
+ }
+ try {
+ const response = await httpClient.sendRequest<T>(
+ {
+ method,
+ url,
+ headers,
+ queryParams: query,
+ body: payload,
+ timeout: requestTimeout,
+ followRedirects: false,
+ redactBodyInErrors: true,
+ },
+ { dispatcher }
+ );
+ if (response.status >= 300) {
+ throw new ILoveApiError(
+ `iLoveAPI error (${response.status}): unexpected redirect.`,
+ response.status,
+ undefined
+ );
+ }
+ return response.body;
+ } catch (error) {
+ const failure = failureOf(error);
+ if (failure?.status === 429 && attempt + 1 < MAX_ATTEMPTS) {
+ const wait = backoffFor(attempt);
+ if (deadline !== undefined && Date.now() + wait >= deadline) {
+ throw new Error(TASK_TIMEOUT_MESSAGE);
+ }
+ await sleep(wait);
+ continue;
+ }
+ if (failure) throw toApiError(failure);
+ if (error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError')) {
+ if (deadline !== undefined && Date.now() >= deadline) {
+ throw new Error(TASK_TIMEOUT_MESSAGE);
+ }
+ throw new Error(
+ `iLoveAPI did not answer within ${Math.round((timeout ?? REQUEST_TIMEOUT_MS) / 1000)} seconds.`
+ );
+ }
+ throw error;
+ }
+ }
+}
+
+function boundedTimeout({ timeout, deadline }: { timeout: number; deadline: number | undefined }): number {
+ if (deadline === undefined) return timeout;
+ const remaining = deadline - Date.now();
+ if (remaining <= 0) {
+ throw new Error(TASK_TIMEOUT_MESSAGE);
+ }
+ return Math.min(timeout, remaining);
+}
-async function authenticate({ publicKey }: { publicKey: string }): Promise<string> {
- const response = await httpClient.sendRequest<AuthResponse>({
+async function authenticate({ publicKey, deadline }: { publicKey: string; deadline?: number }): Promise<string> {
+ const key = typeof publicKey === 'string' ? publicKey.trim() : '';
+ if (!key) {
+ throw new Error('The iLoveAPI connection has no project public key. Reconnect your account.');
+ }
+ const response = await request<AuthResponse>({
method: HttpMethod.POST,
- url: `${ROOT_API}/v1/auth`,
- body: { public_key: publicKey },
+ url: `${PDF_API}/v1/auth`,
+ body: () => ({ public_key: key }),
+ deadline,
});
- return response.body.token;
+ if (!isRecord(response) || typeof response.token !== 'string' || response.token === '') {
+ throw new Error('iLoveAPI did not return an access token.');
+ }
+ return response.token;
+}
+
+function isImageTool(tool: ILoveApiTool): boolean {
+ return tool.endsWith('image');
}
async function startTask({
token,
tool,
+ region,
+ deadline,
}: {
token: string;
tool: ILoveApiTool;
+ region?: ILoveApiRegion;
+ deadline?: number;
}): Promise<StartTaskResponse> {
- const response = await httpClient.sendRequest<StartTaskResponse>({
- method: HttpMethod.GET,
- url: `${ROOT_API}/v1/start/${tool}`,
- authentication: { type: AuthenticationType.BEARER_TOKEN, token },
- });
- return response.body;
+ const base = isImageTool(tool) ? IMG_API : PDF_API;
+ const url = region ? `${base}/v1/start/${tool}/${region}` : `${base}/v1/start/${tool}`;
+ const response = await request<StartTaskResponse>({ method: HttpMethod.GET, url, token, deadline });
+ if (!isRecord(response) || typeof response.task !== 'string' || response.task === '') {
+ throw new Error('iLoveAPI did not return a task ID when starting the task.');
+ }
+ return { ...response, server: iloveHost.assertServerHost(response.server) };
}
async function uploadBuffer({
@@ -49,28 +251,31 @@ async function uploadBuffer({
task,
buffer,
filename,
+ deadline,
}: {
token: string;
server: string;
task: string;
buffer: Buffer;
filename: string;
+ deadline?: number;
}): Promise<string> {
- const formData = new FormData();
- formData.append('task', task);
- formData.append('file', buffer, filename);
-
- const request: HttpRequest = {
+ const host = iloveHost.assertServerHost(server);
+ const { default: FormDataCtor } = await import('form-data');
+ const response = await request<UploadResponse>({
method: HttpMethod.POST,
- url: `https://${server}/v1/upload`,
- headers: {
- ...formData.getHeaders(),
- Authorization: `Bearer ${token}`,
+ url: `https://${host}/v1/upload`,
+ token,
+ timeout: UPLOAD_TIMEOUT_MS,
+ deadline,
+ body: () => {
+ const form = new FormDataCtor();
+ form.append('task', task);
+ form.append('file', buffer, filename);
+ return form;
},
- body: formData,
- };
- const response = await httpClient.sendRequest<UploadResponse>(request);
- return response.body.server_filename;
+ });
+ return serverFilenameOf(response);
}
async function uploadCloudUrl({
@@ -78,58 +283,159 @@ async function uploadCloudUrl({
server,
task,
url,
+ deadline,
}: {
token: string;
server: string;
task: string;
url: string;
+ deadline?: number;
}): Promise<string> {
- const response = await httpClient.sendRequest<UploadResponse>({
+ const host = iloveHost.assertServerHost(server);
+ const response = await request<UploadResponse>({
method: HttpMethod.POST,
- url: `https://${server}/v1/upload`,
- authentication: { type: AuthenticationType.BEARER_TOKEN, token },
- body: { task, cloud_file: url },
+ url: `https://${host}/v1/upload`,
+ token,
+ timeout: UPLOAD_TIMEOUT_MS,
+ deadline,
+ body: () => ({ task, cloud_file: url }),
});
- return response.body.server_filename;
+ return serverFilenameOf(response);
+}
+
+function serverFilenameOf(response: UploadResponse): string {
+ if (!isRecord(response) || typeof response.server_filename !== 'string' || response.server_filename === '') {
+ throw new Error('iLoveAPI accepted the upload but returned no server file name.');
+ }
+ return response.server_filename;
}
async function processTask({
token,
server,
body,
+ deadline,
}: {
token: string;
server: string;
body: ProcessRequest;
+ deadline?: number;
}): Promise<ProcessResponse> {
- const response = await httpClient.sendRequest<ProcessResponse>({
+ const host = iloveHost.assertServerHost(server);
+ return request<ProcessResponse>({
method: HttpMethod.POST,
- url: `https://${server}/v1/process`,
- authentication: { type: AuthenticationType.BEARER_TOKEN, token },
- body,
+ url: `https://${host}/v1/process`,
+ token,
+ timeout: PROCESS_TIMEOUT_MS,
+ deadline,
+ body: () => body,
});
- return response.body;
+}
+
+async function download({
+ token,
+ url,
+ deadline: taskDeadline,
+}: {
+ token: string;
+ url: string;
+ deadline?: number;
+}): Promise<{ data: Buffer; contentType: string | undefined }> {
+ if (!iloveHost.isAllowedUrl(url)) {
+ throw new Error('Refusing to send iLoveAPI credentials to a URL outside the iLoveAPI hosts.');
+ }
+ const dispatcher = await verifiedTls();
+ const downloadTimeout = boundedTimeout({ timeout: DOWNLOAD_TIMEOUT_MS, deadline: taskDeadline });
+ const deadline = Date.now() + downloadTimeout;
+ let response;
+ try {
+ response = await httpClient.sendRequest<unknown>(
+ {
+ method: HttpMethod.GET,
+ url,
+ headers: {
+ Authorization: `Bearer ${token}`,
+ Accept: 'application/pdf, application/zip, image/*, text/plain, */*',
+ },
+ responseType: 'stream',
+ timeout: downloadTimeout,
+ followRedirects: false,
+ },
+ { dispatcher }
+ );
+ } catch (error) {
+ const failure = failureOf(error);
+ if (failure) throw toApiError(failure);
+ throw error;
+ }
+ if (response.status >= 300) {
+ throw new ILoveApiError(
+ `iLoveAPI download failed with status ${response.status}.`,
+ response.status,
+ undefined
+ );
+ }
+ const data = await readCapped({ body: response.body, deadline });
+ const header = response.headers?.['content-type'];
+ return { data, contentType: Array.isArray(header) ? header[0] : header };
+}
+
+async function readCapped({ body, deadline }: { body: unknown; deadline: number }): Promise<Buffer> {
+ if (!(body instanceof Readable)) {
+ throw new Error('iLoveAPI returned an empty file.');
+ }
+ const remaining = Math.max(deadline - Date.now(), 1);
+ const timer = setTimeout(
+ () =>
+ body.destroy(
+ new Error(`The download did not finish within ${DOWNLOAD_TIMEOUT_MS / 1000} seconds.`)
+ ),
+ remaining
+ );
+ try {
+ const chunks: Buffer[] = [];
+ let total = 0;
+ for await (const chunk of body) {
+ const part = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
+ total += part.length;
+ if (total > MAX_DOWNLOAD_BYTES) {
+ body.destroy();
+ throw new Error('The result is larger than 100 MB and cannot be stored in a flow step.');
+ }
+ chunks.push(part);
+ }
+ return Buffer.concat(chunks);
+ } finally {
+ clearTimeout(timer);
+ }
}
async function downloadResult({
token,
server,
task,
+ deadline,
}: {
token: string;
server: string;
task: string;
+ deadline?: number;
}): Promise<Buffer> {
- const response = await httpClient.sendRequest<ArrayBuffer | string>({
- method: HttpMethod.GET,
- url: `https://${server}/v1/download/${task}`,
- authentication: { type: AuthenticationType.BEARER_TOKEN, token },
- responseType: 'arraybuffer',
+ const host = iloveHost.assertServerHost(server);
+ const { data } = await download({
+ token,
+ url: `https://${host}/v1/download/${encodeURIComponent(task)}`,
+ deadline,
});
- if (typeof response.body === 'string') {
- return Buffer.from(response.body, 'binary');
+ return data;
+}
+
+function tokenSegment({ value, label }: { value: unknown; label: string }): string {
+ const text = typeof value === 'string' ? value.trim() : '';
+ if (text === '' || text === '.' || text === '..') {
+ throw new Error(`${label} is required.`);
}
- return Buffer.from(response.body as ArrayBuffer);
+ return encodeURIComponent(text);
}
async function createSignature({
@@ -141,58 +447,86 @@ async function createSignature({
server: string;
body: CreateSignatureRequest;
}): Promise<CreateSignatureResponse> {
- const response = await httpClient.sendRequest<CreateSignatureResponse>({
+ const host = iloveHost.assertServerHost(server);
+ return request<CreateSignatureResponse>({
method: HttpMethod.POST,
- url: `https://${server}/v1/signature`,
- authentication: { type: AuthenticationType.BEARER_TOKEN, token },
- body,
+ url: `https://${host}/v1/signature`,
+ token,
+ timeout: PROCESS_TIMEOUT_MS,
+ body: () => body,
});
- return response.body;
}
-async function getSignatureStatus({
+async function signatureCall({
token,
- tokenRequester,
+ method,
+ path,
+ body,
+ query,
}: {
token: string;
- tokenRequester: string;
+ method: HttpMethod;
+ path: string;
+ body?: Record<string, unknown>;
+ query?: Record<string, string>;
}): Promise<Record<string, unknown>> {
- const response = await httpClient.sendRequest<Record<string, unknown>>({
+ const response = await request<unknown>({
+ method,
+ url: `${PDF_API}/v1/signature/${path}`,
+ token,
+ query,
+ body: body ? () => body : undefined,
+ });
+ return isRecord(response) ? response : { result: response };
+}
+
+async function getSignatureStatus({ token, tokenRequester }: { token: string; tokenRequester: string }) {
+ return signatureCall({
+ token,
+ method: HttpMethod.GET,
+ path: `requesterview/${tokenSegment({ value: tokenRequester, label: 'Requester Token' })}`,
+ });
+}
+
+async function getSignerInfo({ token, tokenSigner }: { token: string; tokenSigner: string }) {
+ return signatureCall({
+ token,
method: HttpMethod.GET,
- url: `${ROOT_API}/v1/signature/requesterview/${tokenRequester}`,
- authentication: { type: AuthenticationType.BEARER_TOKEN, token },
+ path: `receiver/info/${tokenSegment({ value: tokenSigner, label: 'Signer Token' })}`,
});
- return response.body;
}
-async function sendSignerReminder({
+async function listSignatures({
token,
- tokenRequester,
+ page,
+ perPage,
}: {
token: string;
- tokenRequester: string;
-}): Promise<Record<string, unknown>> {
- const response = await httpClient.sendRequest<Record<string, unknown>>({
+ page: number;
+ perPage: number;
+}): Promise<unknown> {
+ return request<unknown>({
+ method: HttpMethod.GET,
+ url: `${PDF_API}/v1/signature/list`,
+ token,
+ query: { page: String(page), 'per-page': String(perPage) },
+ });
+}
+
+async function sendSignerReminder({ token, tokenRequester }: { token: string; tokenRequester: string }) {
+ return signatureCall({
+ token,
method: HttpMethod.POST,
- url: `${ROOT_API}/v1/signature/sendReminder/${tokenRequester}`,
- authentication: { type: AuthenticationType.BEARER_TOKEN, token },
+ path: `sendReminder/${tokenSegment({ value: tokenRequester, label: 'Requester Token' })}`,
});
- return response.body;
}
-async function voidSignature({
- token,
- tokenRequester,
-}: {
- token: string;
- tokenRequester: string;
-}): Promise<Record<string, unknown>> {
- const response = await httpClient.sendRequest<Record<string, unknown>>({
+async function voidSignature({ token, tokenRequester }: { token: string; tokenRequester: string }) {
+ return signatureCall({
+ token,
method: HttpMethod.POST,
- url: `${ROOT_API}/v1/signature/void/${tokenRequester}`,
- authentication: { type: AuthenticationType.BEARER_TOKEN, token },
+ path: `void/${tokenSegment({ value: tokenRequester, label: 'Requester Token' })}`,
});
- return response.body;
}
async function increaseExpirationDays({
@@ -203,208 +537,289 @@ async function increaseExpirationDays({
token: string;
tokenRequester: string;
days: number;
-}): Promise<Record<string, unknown>> {
- const response = await httpClient.sendRequest<Record<string, unknown>>({
+}) {
+ return signatureCall({
+ token,
method: HttpMethod.POST,
- url: `${ROOT_API}/v1/signature/increase-expiration-days/${tokenRequester}`,
- authentication: { type: AuthenticationType.BEARER_TOKEN, token },
+ path: `increase-expiration-days/${tokenSegment({ value: tokenRequester, label: 'Requester Token' })}`,
body: { days },
});
- return response.body;
}
-async function downloadSignedFiles({
+async function resolveSignatureServer({
token,
tokenRequester,
+ server,
}: {
token: string;
tokenRequester: string;
-}): Promise<Buffer> {
- const response = await httpClient.sendRequest<ArrayBuffer | string>({
- method: HttpMethod.GET,
- url: `${ROOT_API}/v1/signature/${tokenRequester}/download-signed`,
- authentication: { type: AuthenticationType.BEARER_TOKEN, token },
- responseType: 'arraybuffer',
- });
- if (typeof response.body === 'string') {
- return Buffer.from(response.body, 'binary');
+ server?: string;
+}): Promise<string> {
+ if (server && server.trim() !== '') {
+ return iloveHost.assertServerHost(server);
+ }
+ const view = await getSignatureStatus({ token, tokenRequester });
+ const fromView = view['server'];
+ if (typeof fromView === 'string' && fromView.trim() !== '') {
+ return iloveHost.assertServerHost(fromView);
}
- return Buffer.from(response.body as ArrayBuffer);
+ return new URL(PDF_API).hostname;
}
-async function downloadAuditTrail({
+async function downloadSignatureFile({
token,
tokenRequester,
+ server,
+ kind,
}: {
token: string;
tokenRequester: string;
-}): Promise<Buffer> {
- const response = await httpClient.sendRequest<ArrayBuffer | string>({
- method: HttpMethod.GET,
- url: `${ROOT_API}/v1/signature/${tokenRequester}/download-audit`,
- authentication: { type: AuthenticationType.BEARER_TOKEN, token },
- responseType: 'arraybuffer',
+ server?: string;
+ kind: 'signed' | 'audit' | 'original';
+}): Promise<{ data: Buffer; contentType: string | undefined; server: string }> {
+ const host = await resolveSignatureServer({ token, tokenRequester, server });
+ const segment = tokenSegment({ value: tokenRequester, label: 'Requester Token' });
+ const result = await download({
+ token,
+ url: `https://${host}/v1/signature/${segment}/download-${kind}`,
});
- if (typeof response.body === 'string') {
- return Buffer.from(response.body, 'binary');
- }
- return Buffer.from(response.body as ArrayBuffer);
+ return { ...result, server: host };
}
-export const iLoveApiClient = {
- authenticate,
- startTask,
- uploadBuffer,
- uploadCloudUrl,
- processTask,
- downloadResult,
- createSignature,
- getSignatureStatus,
- sendSignerReminder,
- voidSignature,
- increaseExpirationDays,
- downloadSignedFiles,
- downloadAuditTrail,
-};
-
-export type UploadInput =
- | { kind: 'file'; file: { base64: string; filename: string } }
- | { kind: 'url'; url: string; filename?: string };
-
-export type RunTaskInput = {
- publicKey: string;
- tool: ILoveApiTool;
- uploads: UploadInput[];
- options?:
- | Record<string, unknown>
- | ((extraServerFilenames: string[]) => Record<string, unknown>);
- output_filename?: string;
- packaged_filename?: string;
- perFileOverrides?: Array<Partial<Pick<ProcessFile, 'rotate' | 'password'>>>;
- extraUploads?: UploadInput[];
-};
-
-export type RunTaskResult = {
- buffer: Buffer;
- downloadFilename: string;
- process: ProcessResponse;
- uploadedExtraFilenames: string[];
-};
+async function uploadOne({
+ token,
+ server,
+ task,
+ upload,
+ deadline,
+}: {
+ token: string;
+ server: string;
+ task: string;
+ upload: UploadInput;
+ deadline?: number;
+}): Promise<{ serverFilename: string; filename: string }> {
+ if (upload.kind === 'file') {
+ const serverFilename = await uploadBuffer({
+ token,
+ server,
+ task,
+ buffer: upload.file.data,
+ filename: upload.file.filename,
+ deadline,
+ });
+ return { serverFilename, filename: upload.file.filename };
+ }
+ const serverFilename = await uploadCloudUrl({ token, server, task, url: upload.url, deadline });
+ return { serverFilename, filename: upload.filename ?? deriveFilenameFromUrl(upload.url) };
+}
async function runTask({
publicKey,
tool,
+ region,
uploads,
options,
output_filename,
packaged_filename,
perFileOverrides,
extraUploads,
+ skipDownload,
+ webhook,
}: RunTaskInput): Promise<RunTaskResult> {
+ const deadline = Date.now() + TASK_BUDGET_MS;
+ let timer: NodeJS.Timeout | undefined;
+ const budget = new Promise<never>((_, reject) => {
+ timer = setTimeout(
+ () => reject(new Error(TASK_TIMEOUT_MESSAGE)),
+ TASK_BUDGET_MS
+ );
+ });
+ try {
+ return await Promise.race([
+ runTaskSteps({ publicKey, tool, region, uploads, options, output_filename, packaged_filename, perFileOverrides, extraUploads, skipDownload, webhook, deadline }),
+ budget,
+ ]);
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+function assertWithinBudget(deadline: number): void {
+ if (Date.now() >= deadline) {
+ throw new Error(TASK_TIMEOUT_MESSAGE);
+ }
+}
+
+async function runTaskSteps({
+ publicKey,
+ tool,
+ region,
+ uploads,
+ options,
+ output_filename,
+ packaged_filename,
+ perFileOverrides,
+ extraUploads,
+ skipDownload,
+ webhook,
+ deadline,
+}: RunTaskInput & { deadline: number }): Promise<RunTaskResult> {
if (!uploads || uploads.length === 0) {
throw new Error('At least one input file or URL is required');
}
- const token = await iLoveApiClient.authenticate({ publicKey });
- const { server, task } = await iLoveApiClient.startTask({ token, tool });
+ const token = await authenticate({ publicKey, deadline });
+ const started = await startTask({ token, tool, region, deadline });
+ const { server, task } = started;
const files: ProcessFile[] = [];
for (let i = 0; i < uploads.length; i++) {
- const upload = uploads[i];
- if (upload.kind === 'file') {
- const buffer = Buffer.from(upload.file.base64, 'base64');
- const serverFilename = await iLoveApiClient.uploadBuffer({
- token,
- server,
- task,
- buffer,
- filename: upload.file.filename,
- });
- files.push({
- server_filename: serverFilename,
- filename: upload.file.filename,
- ...perFileOverrides?.[i],
- });
- } else {
- const serverFilename = await iLoveApiClient.uploadCloudUrl({
- token,
- server,
- task,
- url: upload.url,
- });
- files.push({
- server_filename: serverFilename,
- filename: upload.filename ?? deriveFilenameFromUrl(upload.url),
- ...perFileOverrides?.[i],
- });
- }
+ assertWithinBudget(deadline);
+ const uploaded = await uploadOne({ token, server, task, upload: uploads[i], deadline });
+ files.push({
+ server_filename: uploaded.serverFilename,
+ filename: uploaded.filename,
+ ...perFileOverrides?.[i],
+ });
}
const uploadedExtraFilenames: string[] = [];
- if (extraUploads && extraUploads.length > 0) {
- for (const extra of extraUploads) {
- if (extra.kind === 'file') {
- const buffer = Buffer.from(extra.file.base64, 'base64');
- const serverFilename = await iLoveApiClient.uploadBuffer({
- token,
- server,
- task,
- buffer,
- filename: extra.file.filename,
- });
- uploadedExtraFilenames.push(serverFilename);
- } else {
- const serverFilename = await iLoveApiClient.uploadCloudUrl({
- token,
- server,
- task,
- url: extra.url,
- });
- uploadedExtraFilenames.push(serverFilename);
- }
- }
+ for (const extra of extraUploads ?? []) {
+ assertWithinBudget(deadline);
+ const uploaded = await uploadOne({ token, server, task, upload: extra, deadline });
+ uploadedExtraFilenames.push(uploaded.serverFilename);
}
const resolvedOptions =
typeof options === 'function' ? options(uploadedExtraFilenames) : options ?? {};
const processBody: ProcessRequest = {
+ ...resolvedOptions,
task,
tool,
files,
...(output_filename ? { output_filename } : {}),
...(packaged_filename ? { packaged_filename } : {}),
- ...resolvedOptions,
+ ...(webhook ? { webhook } : {}),
};
- const processResponse = await iLoveApiClient.processTask({
- token,
- server,
- body: processBody,
- });
+ assertWithinBudget(deadline);
+ const processResponse = await processTask({ token, server, body: processBody, deadline });
+ if (!isRecord(processResponse)) {
+ throw new Error('iLoveAPI returned an empty process response.');
+ }
- const buffer = await iLoveApiClient.downloadResult({ token, server, task });
+ assertWithinBudget(deadline);
+ const buffer = skipDownload ? undefined : await downloadResult({ token, server, task, deadline });
return {
buffer,
downloadFilename: processResponse.download_filename,
process: processResponse,
+ task,
+ server,
+ remainingCredits: remainingCreditsOf(started),
uploadedExtraFilenames,
};
}
+async function createSignatureRequest({
+ publicKey,
+ region,
+ uploads,
+ draft,
+}: {
+ publicKey: string;
+ region?: ILoveApiRegion;
+ uploads: UploadInput[];
+ draft: SignatureDraft;
+}): Promise<CreateSignatureResponse & { server: string }> {
+ if (uploads.length === 0) {
+ throw new Error('At least one PDF file is required.');
+ }
+ if (uploads.length > MAX_SIGNATURE_FILES) {
+ throw new Error(`iLoveSign accepts at most ${MAX_SIGNATURE_FILES} files per signature request.`);
+ }
+ const token = await authenticate({ publicKey });
+ const { server, task } = await startTask({ token, tool: 'sign', region });
+ const files: Array<{ server_filename: string; filename: string }> = [];
+ for (const upload of uploads) {
+ const uploaded = await uploadOne({ token, server, task, upload });
+ files.push({ server_filename: uploaded.serverFilename, filename: uploaded.filename });
+ }
+ const response = await createSignature({
+ token,
+ server,
+ body: buildSignatureRequest({ draft, task, files }),
+ });
+ return { ...response, server };
+}
+
+function remainingCreditsOf(started: StartTaskResponse): number | undefined {
+ const value = started.remaining_credits ?? started.remaining_files;
+ return typeof value === 'number' ? value : undefined;
+}
+
function deriveFilenameFromUrl(url: string): string {
try {
const parsed = new URL(url);
const last = parsed.pathname.split('/').filter(Boolean).pop();
- if (last && last.length > 0) return last;
+ if (last && last.length > 0) return decodeURIComponent(last);
} catch {
- // fall through
+ return 'remote-file';
}
return 'remote-file';
}
export const iLoveApi = {
- ...iLoveApiClient,
+ PDF_API,
+ isRecord,
+ authenticate,
+ startTask,
+ uploadBuffer,
+ uploadCloudUrl,
+ processTask,
+ downloadResult,
+ createSignature,
+ createSignatureRequest,
+ getSignatureStatus,
+ getSignerInfo,
+ listSignatures,
+ sendSignerReminder,
+ voidSignature,
+ increaseExpirationDays,
+ downloadSignatureFile,
runTask,
+ failureOf,
+};
+
+export type UploadInput =
+ | { kind: 'file'; file: { data: Buffer; filename: string } }
+ | { kind: 'url'; url: string; filename?: string };
+
+export type RunTaskInput = {
+ publicKey: string;
+ tool: ILoveApiTool;
+ region?: ILoveApiRegion;
+ uploads: UploadInput[];
+ options?:
+ | Record<string, unknown>
+ | ((extraServerFilenames: string[]) => Record<string, unknown>);
+ output_filename?: string;
+ packaged_filename?: string;
+ perFileOverrides?: Array<Partial<Pick<ProcessFile, 'rotate' | 'password'>>>;
+ extraUploads?: UploadInput[];
+ skipDownload?: boolean;
+ webhook?: string;
+};
+
+export type RunTaskResult = {
+ buffer: Buffer | undefined;
+ downloadFilename: string;
+ process: ProcessResponse;
+ task: string;
+ server: string;
+ remainingCredits: number | undefined;
+ uploadedExtraFilenames: string[];
};
diff --git a/packages/pieces/community/iloveapi/src/lib/common/host.ts b/packages/pieces/community/iloveapi/src/lib/common/host.ts
new file mode 100644
index 00000000000..15cc4d94ebd
--- /dev/null
+++ b/packages/pieces/community/iloveapi/src/lib/common/host.ts
@@ -0,0 +1,29 @@
+const ALLOWED_HOST = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.(ilovepdf|iloveimg|iloveapi)\.com$/;
+
+function assertServerHost(server: unknown): string {
+ const host = typeof server === 'string' ? server.trim().toLowerCase() : '';
+ if (!ALLOWED_HOST.test(host)) {
+ throw new Error(
+ `iLoveAPI returned an unexpected server "${String(server).slice(0, 100)}". The request was stopped so your credentials are not sent to another host.`
+ );
+ }
+ return host;
+}
+
+function isAllowedUrl(url: string): boolean {
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ return false;
+ }
+ return (
+ parsed.protocol === 'https:' &&
+ parsed.username === '' &&
+ parsed.password === '' &&
+ parsed.port === '' &&
+ ALLOWED_HOST.test(parsed.hostname)
+ );
+}
+
+export const iloveHost = { assertServerHost, isAllowedUrl };
diff --git a/packages/pieces/community/iloveapi/src/lib/common/props.ts b/packages/pieces/community/iloveapi/src/lib/common/props.ts
index 4358ec8858b..66285535021 100644
--- a/packages/pieces/community/iloveapi/src/lib/common/props.ts
+++ b/packages/pieces/community/iloveapi/src/lib/common/props.ts
@@ -1,5 +1,34 @@
import { Property } from '@activepieces/pieces-framework';
import { UploadInput } from './client';
+import { ILoveApiRegion } from './types';
+
+const REGIONS: ILoveApiRegion[] = ['eu', 'us', 'fr', 'de', 'pl', 'in', 'sg'];
+
+const regionProp = Property.StaticDropdown({
+ displayName: 'Processing Region',
+ description:
+ 'Optional. Server region where iLoveAPI processes the files. Leave empty to let iLoveAPI choose (previous behaviour).',
+ required: false,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Europe', value: 'eu' },
+ { label: 'United States', value: 'us' },
+ { label: 'France', value: 'fr' },
+ { label: 'Germany', value: 'de' },
+ { label: 'Poland', value: 'pl' },
+ { label: 'India', value: 'in' },
+ { label: 'Singapore', value: 'sg' },
+ ],
+ },
+});
+
+const webhookUrlProp = Property.ShortText({
+ displayName: 'Webhook URL',
+ description:
+ 'Optional. Paste the URL of an iLoveAPI "Task Completed" or "Task Failed" trigger (including ?ap_secret=...) to notify that flow when this task finishes. The URL must also be registered under Webhooks in the iLoveAPI dashboard.',
+ required: false,
+});
export const sharedProps = {
output_filename: Property.ShortText({
@@ -14,10 +43,78 @@ export const sharedProps = {
'Name of the ZIP archive when the result contains multiple files. No extension.',
required: false,
}),
+ region: regionProp,
+ webhook_url: webhookUrlProp,
};
-type ApFile = { base64: string; filename: string };
+export function regionOf(value: unknown): ILoveApiRegion | undefined {
+ if (value === undefined || value === null || value === '') return undefined;
+ const region = REGIONS.find((candidate) => candidate === value);
+ if (!region) {
+ throw new Error(`Processing Region must be one of: ${REGIONS.join(', ')}.`);
+ }
+ return region;
+}
+
+export function webhookOf(value: unknown): string | undefined {
+ const text = typeof value === 'string' ? value.trim() : '';
+ if (text === '') return undefined;
+ let parsed: URL;
+ try {
+ parsed = new URL(text);
+ } catch {
+ throw new Error('Webhook URL is not a valid URL.');
+ }
+ if (parsed.protocol !== 'https:') {
+ throw new Error('Webhook URL must use https.');
+ }
+ return parsed.toString();
+}
+
+export function fileToUploadInput({ file, label = 'File' }: { file: unknown; label?: string }): UploadInput {
+ if (file === null || typeof file !== 'object') {
+ throw new Error(`${label} is required.`);
+ }
+ const data = readFileData(file);
+ const filename: unknown = Reflect.get(file, 'filename');
+ if (data === null || data.length === 0) {
+ throw new Error(`${label} is empty or could not be read.`);
+ }
+ return {
+ kind: 'file',
+ file: {
+ data,
+ filename: typeof filename === 'string' && filename !== '' ? filename : 'file',
+ },
+ };
+}
+
+function readFileData(file: object): Buffer | null {
+ const data: unknown = Reflect.get(file, 'data');
+ if (Buffer.isBuffer(data)) return data;
+ if (data instanceof Uint8Array) return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
+ const base64: unknown = Reflect.get(file, 'base64');
+ if (typeof base64 === 'string' && base64 !== '') return Buffer.from(base64, 'base64');
+ return null;
+}
-export function fileToUploadInput(file: ApFile): UploadInput {
- return { kind: 'file', file: { base64: file.base64, filename: file.filename } };
+export function rowFiles({ rows, label }: { rows: unknown; label: string }): UploadInput[] {
+ if (!Array.isArray(rows)) return [];
+ return rows.map((row: unknown, index) => {
+ const file = row !== null && typeof row === 'object' ? Reflect.get(row, 'file') : undefined;
+ return fileToUploadInput({ file: file, label: `${label} row ${index + 1}` });
+ });
}
+
+const CONFORMANCE_OPTIONS = [
+ { label: 'PDF/A-1b', value: 'pdfa-1b' },
+ { label: 'PDF/A-1a', value: 'pdfa-1a' },
+ { label: 'PDF/A-2b (recommended)', value: 'pdfa-2b' },
+ { label: 'PDF/A-2u', value: 'pdfa-2u' },
+ { label: 'PDF/A-2a', value: 'pdfa-2a' },
+ { label: 'PDF/A-3b', value: 'pdfa-3b' },
+ { label: 'PDF/A-3u', value: 'pdfa-3u' },
+ { label: 'PDF/A-3a', value: 'pdfa-3a' },
+];
+
+export { CONFORMANCE_OPTIONS, regionProp, webhookUrlProp };
diff --git a/packages/pieces/community/iloveapi/src/lib/common/runner.ts b/packages/pieces/community/iloveapi/src/lib/common/runner.ts
index 1080630ea15..344e69322cc 100644
--- a/packages/pieces/community/iloveapi/src/lib/common/runner.ts
+++ b/packages/pieces/community/iloveapi/src/lib/common/runner.ts
@@ -2,6 +2,39 @@ import { FilesService } from '@activepieces/pieces-framework';
import { ILoveApiTool, ProcessResponse } from './types';
import { RunTaskInput, UploadInput, iLoveApi } from './client';
+export async function runAndStoreResult(input: RunAndStoreInput): Promise<RunAndStoreResult> {
+ const { output } = await runAndStoreWithBuffer(input);
+ return output;
+}
+
+export async function runAndStoreWithBuffer({
+ auth,
+ files,
+ ...input
+}: RunAndStoreInput): Promise<{ output: RunAndStoreResult; buffer: Buffer }> {
+ const result = await iLoveApi.runTask({ ...input, publicKey: auth });
+ if (!result.buffer) {
+ throw new Error('iLoveAPI returned no output file.');
+ }
+ const fileName = result.downloadFilename || `${input.tool}-${result.task}`;
+ const storedFile = await files.write({ fileName, data: result.buffer });
+
+ const output: RunAndStoreResult = {
+ output_file: storedFile,
+ download_filename: fileName,
+ output_filenumber: result.process.output_filenumber,
+ output_filesize: result.process.output_filesize ?? result.buffer.length,
+ filesize: result.process.filesize,
+ output_extensions: result.process.output_extensions,
+ status: result.process.status,
+ timer: result.process.timer,
+ task: result.task,
+ remaining_credits: result.remainingCredits,
+ process: result.process,
+ };
+ return { output, buffer: result.buffer };
+}
+
export type RunAndStoreInput = Omit<RunTaskInput, 'publicKey'> & {
auth: string;
files: FilesService;
@@ -12,48 +45,14 @@ export type RunAndStoreResult = {
download_filename: string;
output_filenumber?: number;
output_filesize?: number;
+ filesize?: number;
output_extensions?: string[];
status?: string;
+ timer?: string;
+ task: string;
+ remaining_credits?: number;
process: ProcessResponse;
};
-export async function runAndStoreResult({
- auth,
- files,
- tool,
- uploads,
- options,
- output_filename,
- packaged_filename,
- perFileOverrides,
- extraUploads,
-}: RunAndStoreInput): Promise<RunAndStoreResult> {
- const result = await iLoveApi.runTask({
- publicKey: auth,
- tool,
- uploads,
- options,
- output_filename,
- packaged_filename,
- perFileOverrides,
- extraUploads,
- });
-
- const storedFile = await files.write({
- fileName: result.downloadFilename,
- data: result.buffer,
- });
-
- return {
- output_file: storedFile,
- download_filename: result.downloadFilename,
- output_filenumber: result.process.output_filenumber,
- output_filesize: result.process.output_filesize,
- output_extensions: result.process.output_extensions,
- status: result.process.status,
- process: result.process,
- };
-}
-
export type ToolUploadInput = UploadInput;
export type ToolName = ILoveApiTool;
diff --git a/packages/pieces/community/iloveapi/src/lib/common/schemas.ts b/packages/pieces/community/iloveapi/src/lib/common/schemas.ts
new file mode 100644
index 00000000000..fc3d98d92dc
--- /dev/null
+++ b/packages/pieces/community/iloveapi/src/lib/common/schemas.ts
@@ -0,0 +1,183 @@
+import { OutputSchema, OutputSchemaField } from '@activepieces/pieces-framework';
+
+const toolResultFields: OutputSchemaField[] = [
+ { key: 'output_file', label: 'Output File', format: 'url' },
+ { key: 'download_filename', label: 'File Name' },
+ { key: 'output_filesize', label: 'Output Size', format: 'filesize' },
+ { key: 'filesize', label: 'Input Size', format: 'filesize' },
+ { key: 'output_filenumber', label: 'Number of Output Files', format: 'number' },
+ { key: 'output_extensions', label: 'Output Extensions' },
+ { key: 'status', label: 'Status' },
+ { key: 'timer', label: 'Processing Time (s)' },
+ { key: 'task', label: 'Task ID' },
+ { key: 'remaining_credits', label: 'Remaining Credits', format: 'number' },
+];
+
+const signerFields: OutputSchemaField[] = [
+ { key: 'uuid', label: 'Signer ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'type', label: 'Role' },
+ { key: 'status', label: 'Status' },
+ { key: 'token_signer', label: 'Signer Token' },
+];
+
+const signatureFields: OutputSchemaField[] = [
+ { key: 'token_requester', label: 'Requester Token' },
+ { key: 'uuid', label: 'Signature ID' },
+ { key: 'status', label: 'Status' },
+ { key: 'subject_signer', label: 'Email Subject' },
+ { key: 'created', label: 'Created', format: 'datetime' },
+ { key: 'expires', label: 'Expires', format: 'datetime' },
+ { key: 'certified', label: 'Certified', format: 'boolean' },
+ { key: 'server', label: 'Server' },
+ { key: 'signers', label: 'Signers', labelKey: 'email', listItems: signerFields },
+ {
+ key: 'files',
+ label: 'Files',
+ labelKey: 'filename',
+ listItems: [
+ { key: 'filename', label: 'File Name' },
+ { key: 'pages', label: 'Pages', format: 'number' },
+ ],
+ },
+];
+
+const toolResult: OutputSchema = { fields: toolResultFields };
+
+const extractText: OutputSchema = {
+ fields: [
+ ...toolResultFields,
+ { key: 'text', label: 'Text' },
+ { key: 'text_length', label: 'Text Length', format: 'number' },
+ { key: 'text_truncated', label: 'Text Truncated', format: 'boolean' },
+ { key: 'detailed_total_rows', label: 'Detailed Total Rows', format: 'number' },
+ { key: 'detailed_truncated', label: 'Detailed Truncated', format: 'boolean' },
+ {
+ key: 'detailed',
+ label: 'Detailed Words',
+ listItems: [
+ { key: 'PageNo', label: 'Page', format: 'number' },
+ { key: 'XPos', label: 'X Position', format: 'number' },
+ { key: 'YPos', label: 'Y Position', format: 'number' },
+ { key: 'XWidth', label: 'Width', format: 'number' },
+ { key: 'YWidth', label: 'Height', format: 'number' },
+ { key: 'FontName', label: 'Font' },
+ { key: 'FontSize', label: 'Font Size', format: 'number' },
+ { key: 'Length', label: 'Length', format: 'number' },
+ { key: 'Text', label: 'Text' },
+ ],
+ },
+ { key: 'detailed_parse_error', label: 'Detailed Parse Error' },
+ ],
+};
+
+const validatePdfa: OutputSchema = {
+ fields: [
+ { key: 'conformant', label: 'All Files Conformant', format: 'boolean' },
+ {
+ key: 'validations',
+ label: 'Validations',
+ labelKey: 'server_filename',
+ listItems: [
+ { key: 'server_filename', label: 'Server File Name' },
+ { key: 'status', label: 'Result' },
+ { key: 'reason', label: 'Reasons' },
+ ],
+ },
+ { key: 'status', label: 'Status' },
+ { key: 'timer', label: 'Processing Time (s)' },
+ { key: 'task', label: 'Task ID' },
+ { key: 'remaining_credits', label: 'Remaining Credits', format: 'number' },
+ ],
+};
+
+const signature: OutputSchema = { fields: signatureFields };
+
+const signatureAck: OutputSchema = {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'token_requester', label: 'Requester Token' },
+ { key: 'days', label: 'Days Added', format: 'number' },
+ ],
+};
+
+const signatureDownload: OutputSchema = {
+ fields: [
+ { key: 'output_file', label: 'File', format: 'url' },
+ { key: 'file_name', label: 'File Name' },
+ { key: 'size', label: 'Size', format: 'filesize' },
+ { key: 'content_type', label: 'Content Type' },
+ { key: 'token_requester', label: 'Requester Token' },
+ ],
+};
+
+const signatureList: OutputSchema = {
+ fields: [
+ { key: 'items', label: 'Signature Requests', labelKey: 'token_requester', listItems: signatureFields },
+ { key: 'count', label: 'Count on This Page', format: 'number' },
+ { key: 'page', label: 'Page', format: 'number' },
+ { key: 'per_page', label: 'Per Page', format: 'number' },
+ { key: 'next_page', label: 'Next Page', format: 'number' },
+ { key: 'has_more', label: 'May Have More', format: 'boolean' },
+ ],
+};
+
+const signerInfo: OutputSchema = {
+ fields: [
+ ...signerFields,
+ { key: 'phone', label: 'Phone' },
+ { key: 'access_code', label: 'Has Access Code' },
+ { key: 'signed', label: 'Signed At', format: 'datetime' },
+ ],
+};
+
+const taskEvent: OutputSchema = {
+ fields: [
+ { key: 'event', label: 'Event' },
+ {
+ key: 'task',
+ label: 'Task',
+ value: 'data.task',
+ children: [
+ { key: 'task', label: 'Task ID' },
+ { key: 'tool', label: 'Tool' },
+ { key: 'status', label: 'Status' },
+ { key: 'status_message', label: 'Status Message' },
+ { key: 'message', label: 'Message' },
+ { key: 'server', label: 'Server' },
+ { key: 'download_filename', label: 'File Name' },
+ { key: 'filesize', label: 'Input Size', format: 'filesize' },
+ { key: 'output_filesize', label: 'Output Size', format: 'filesize' },
+ { key: 'output_filenumber', label: 'Number of Output Files', format: 'number' },
+ { key: 'output_extensions', label: 'Output Extensions' },
+ { key: 'file_number', label: 'Number of Input Files', format: 'number' },
+ { key: 'process_start', label: 'Process Start' },
+ { key: 'timer', label: 'Processing Time (s)' },
+ { key: 'custom_int', label: 'Custom Integer', format: 'number' },
+ { key: 'custom_string', label: 'Custom String' },
+ ],
+ },
+ ],
+};
+
+const signatureEvent: OutputSchema = {
+ fields: [
+ { key: 'event', label: 'Event' },
+ { key: 'signature', label: 'Signature', value: 'data.signature', children: signatureFields },
+ { key: 'signer', label: 'Signer', value: 'data.signer', children: signerFields },
+ ],
+};
+
+export const iloveSchemas = {
+ toolResult,
+ extractText,
+ validatePdfa,
+ signature,
+ signatureAck,
+ signatureDownload,
+ signatureList,
+ signerInfo,
+ taskEvent,
+ signatureEvent,
+};
diff --git a/packages/pieces/community/iloveapi/src/lib/common/signature.ts b/packages/pieces/community/iloveapi/src/lib/common/signature.ts
new file mode 100644
index 00000000000..825b9e10ff8
--- /dev/null
+++ b/packages/pieces/community/iloveapi/src/lib/common/signature.ts
@@ -0,0 +1,235 @@
+import { CreateSignatureRequest, SignatureElement, SignatureSigner } from './types';
+
+const SIGNER_TYPES = ['signer', 'validator', 'viewer'] as const;
+const FORCE_TYPES = ['all', 'text', 'sign', 'image'] as const;
+const ELEMENT_TYPES = ['signature', 'initials', 'date', 'text', 'input'] as const;
+const MAX_SIGNERS = 50;
+const MAX_ELEMENTS = 1000;
+const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+
+export function signatureBodyOf({
+ signers,
+ elements,
+ options,
+}: {
+ signers: unknown;
+ elements: unknown;
+ options: SignatureOptionsInput;
+}): SignatureDraft {
+ const signerRows = Array.isArray(signers) ? signers : [];
+ if (signerRows.length === 0) {
+ throw new Error('At least one signer is required.');
+ }
+ if (signerRows.length > MAX_SIGNERS) {
+ throw new Error(`iLoveSign accepts at most ${MAX_SIGNERS} signers per request.`);
+ }
+ const parsedSigners = signerRows.map((row: unknown, index) => signerOf({ row, index }));
+ const emails = parsedSigners.map((signer) => signer.email.toLowerCase());
+ const duplicate = emails.find((email, index) => emails.indexOf(email) !== index);
+ if (duplicate) {
+ throw new Error(`Signer email ${duplicate} is listed more than once.`);
+ }
+
+ const elementRows = Array.isArray(elements) ? elements : [];
+ if (elementRows.length > MAX_ELEMENTS) {
+ throw new Error(`iLoveSign accepts at most ${MAX_ELEMENTS} signature elements per request.`);
+ }
+ const parsedElements = elementRows.map((row: unknown, index) => elementOf({ row, index, emails }));
+
+ const withElements = parsedSigners.map((signer) => {
+ const own = parsedElements
+ .filter((entry) => entry.email === signer.email.toLowerCase())
+ .map((entry) => entry.element);
+ return own.length > 0 ? { ...signer, elements: own } : signer;
+ });
+
+ return { signers: withElements, options: optionsOf(options) };
+}
+
+export function buildSignatureRequest({
+ draft,
+ task,
+ files,
+}: {
+ draft: SignatureDraft;
+ task: string;
+ files: Array<{ server_filename: string; filename: string }>;
+}): CreateSignatureRequest {
+ return {
+ ...draft.options,
+ task,
+ files,
+ signers: draft.signers.map(({ elements, ...signer }) => ({
+ ...signer,
+ files: files.map((file) => ({
+ server_filename: file.server_filename,
+ ...(elements && elements.length > 0 ? { elements } : {}),
+ })),
+ })),
+ };
+}
+
+function text(value: unknown): string | undefined {
+ if (typeof value === 'string') {
+ const trimmed = value.trim();
+ return trimmed === '' ? undefined : trimmed;
+ }
+ if (typeof value === 'number' && Number.isFinite(value)) return String(value);
+ return undefined;
+}
+
+function pick<T extends string>({
+ value,
+ allowed,
+ fallback,
+ label,
+}: {
+ value: unknown;
+ allowed: readonly T[];
+ fallback: T;
+ label: string;
+}): T {
+ const given = text(value);
+ if (given === undefined) return fallback;
+ const match = allowed.find((candidate) => candidate === given);
+ if (!match) {
+ throw new Error(`${label} must be one of: ${allowed.join(', ')}.`);
+ }
+ return match;
+}
+
+function field({ row, key }: { row: unknown; key: string }): unknown {
+ return row !== null && typeof row === 'object' ? Reflect.get(row, key) : undefined;
+}
+
+function signerOf({ row, index }: { row: unknown; index: number }): SignerDraft {
+ const label = `Signer ${index + 1}`;
+ const name = text(field({ row, key: 'name' }));
+ const email = text(field({ row, key: 'email' }));
+ if (!name || !email) {
+ throw new Error(`${label} needs both a name and an email.`);
+ }
+ if (!EMAIL.test(email)) {
+ throw new Error(`${label} has an invalid email: ${email}`);
+ }
+ const phone = text(field({ row, key: 'phone' }));
+ const accessCode = text(field({ row, key: 'access_code' }));
+ const notes = text(field({ row, key: 'notes' }));
+ return {
+ name,
+ email,
+ type: pick<(typeof SIGNER_TYPES)[number]>({ value: field({ row, key: 'type' }), allowed: SIGNER_TYPES, fallback: 'signer', label: `${label} role` }),
+ force_signature_type: pick<(typeof FORCE_TYPES)[number]>({
+ value: field({ row, key: 'force_signature_type' }),
+ allowed: FORCE_TYPES,
+ fallback: 'all',
+ label: `${label} signature type`,
+ }),
+ ...(phone ? { phone } : {}),
+ ...(accessCode ? { access_code: accessCode } : {}),
+ ...(notes ? { notes } : {}),
+ };
+}
+
+function elementOf({
+ row,
+ index,
+ emails,
+}: {
+ row: unknown;
+ index: number;
+ emails: string[];
+}): { email: string; element: SignatureElement } {
+ const label = `Signature element ${index + 1}`;
+ const email = text(field({ row, key: 'signer_email' }))?.toLowerCase();
+ const position = text(field({ row, key: 'position' }));
+ const pages = text(field({ row, key: 'pages' }));
+ if (!email || !position || !pages) {
+ throw new Error(`${label} needs a signer email, a position and pages.`);
+ }
+ if (!emails.includes(email)) {
+ throw new Error(`${label} uses ${email}, which matches no signer.`);
+ }
+ const type = pick<(typeof ELEMENT_TYPES)[number]>({ value: field({ row, key: 'type' }), allowed: ELEMENT_TYPES, fallback: 'signature', label: `${label} type` });
+ const sizeRaw = field({ row, key: 'size' });
+ const size = sizeRaw === undefined || sizeRaw === null || sizeRaw === '' ? undefined : Number(sizeRaw);
+ if (size !== undefined && !(Number.isFinite(size) && size > 0)) {
+ throw new Error(`${label} size must be a positive number.`);
+ }
+ const content = text(field({ row, key: 'content' }));
+ const color = text(field({ row, key: 'color' }));
+ return {
+ email,
+ element: {
+ type,
+ position,
+ pages,
+ ...(size !== undefined ? { size } : {}),
+ ...(content ? { content } : {}),
+ ...(color ? { color } : {}),
+ },
+ };
+}
+
+function optionalNumber({
+ value,
+ label,
+ min,
+ max,
+}: {
+ value: unknown;
+ label: string;
+ min: number;
+ max: number;
+}): number | undefined {
+ if (value === undefined || value === null || value === '') return undefined;
+ const parsed = Number(value);
+ if (!Number.isInteger(parsed) || parsed < min || parsed > max) {
+ throw new Error(`${label} must be a whole number between ${min} and ${max}.`);
+ }
+ return parsed;
+}
+
+function optionsOf(options: SignatureOptionsInput): Partial<CreateSignatureRequest> {
+ const expiration = optionalNumber({ value: options.expiration_days, label: 'Expiration (days)', min: 1, max: 130 });
+ const cycle = optionalNumber({
+ value: options.signer_reminder_days_cycle,
+ label: 'Reminder Frequency (days)',
+ min: 1,
+ max: 130,
+ });
+ const brand = text(options.brand_name);
+ const language = text(options.language);
+ const subject = text(options.subject_signer);
+ const message = text(options.message_signer);
+ return {
+ ...(brand ? { brand_name: brand } : {}),
+ ...(language ? { language } : {}),
+ ...(subject ? { subject_signer: subject } : {}),
+ ...(message ? { message_signer: message } : {}),
+ ...(expiration !== undefined ? { expiration_days: expiration } : {}),
+ ...(typeof options.lock_order === 'boolean' ? { lock_order: options.lock_order } : {}),
+ ...(typeof options.signer_reminders === 'boolean' ? { signer_reminders: options.signer_reminders } : {}),
+ ...(cycle !== undefined ? { signer_reminder_days_cycle: cycle } : {}),
+ ...(typeof options.certified === 'boolean' ? { certified: options.certified } : {}),
+ };
+}
+
+type SignerDraft = Omit<SignatureSigner, 'files'> & { elements?: SignatureElement[] };
+
+export type SignatureDraft = {
+ signers: SignerDraft[];
+ options: Partial<CreateSignatureRequest>;
+};
+
+export type SignatureOptionsInput = {
+ brand_name?: unknown;
+ language?: unknown;
+ subject_signer?: unknown;
+ message_signer?: unknown;
+ expiration_days?: unknown;
+ lock_order?: unknown;
+ signer_reminders?: unknown;
+ signer_reminder_days_cycle?: unknown;
+ certified?: unknown;
+};
diff --git a/packages/pieces/community/iloveapi/src/lib/common/types.ts b/packages/pieces/community/iloveapi/src/lib/common/types.ts
index 63f92ee8556..f52102c7f71 100644
--- a/packages/pieces/community/iloveapi/src/lib/common/types.ts
+++ b/packages/pieces/community/iloveapi/src/lib/common/types.ts
@@ -14,8 +14,20 @@ export type ILoveApiTool =
| 'rotate'
| 'extract'
| 'repair'
+ | 'pdfa'
+ | 'validatepdfa'
+ | 'compressimage'
+ | 'resizeimage'
+ | 'cropimage'
+ | 'convertimage'
+ | 'upscaleimage'
+ | 'removebackgroundimage'
+ | 'watermarkimage'
+ | 'rotateimage'
| 'sign';
+export type ILoveApiRegion = 'eu' | 'us' | 'fr' | 'de' | 'pl' | 'in' | 'sg';
+
export type SignatureSigner = {
name: string;
email: string;
@@ -82,6 +94,7 @@ export type CreateSignatureResponse = {
export type StartTaskResponse = {
server: string;
task: string;
+ remaining_credits?: number;
remaining_files?: number;
};
diff --git a/packages/pieces/community/iloveapi/src/lib/triggers/common.ts b/packages/pieces/community/iloveapi/src/lib/triggers/common.ts
index f2c96584646..65eecac268e 100644
--- a/packages/pieces/community/iloveapi/src/lib/triggers/common.ts
+++ b/packages/pieces/community/iloveapi/src/lib/triggers/common.ts
@@ -1,18 +1,20 @@
-import { Property } from '@activepieces/pieces-framework';
+import { createHash, randomUUID, timingSafeEqual } from 'node:crypto';
+import { DEDUPE_KEY_PROPERTY, Property, Store } from '@activepieces/pieces-framework';
export const webhookInstructions = (eventLabel: string): string => `
**How to connect**
1. Sign in to https://developer.ilovepdf.com/ and open your project.
2. Go to **Webhooks** and click **Add Webhook**.
-3. Paste the URL below into **Endpoint URL**:
+3. Make up a long random secret (at least 16 letters and digits) and enter it in **Webhook Secret** below.
+4. Paste the URL below into **Endpoint URL** and replace \`YOUR_SECRET\` with that secret:
\`\`\`text
-{{webhookUrl}}
+{{webhookUrl}}?ap_secret=YOUR_SECRET
\`\`\`
-4. In **Events**, select **${eventLabel}**.
-5. Save the webhook. The trigger will fire on every matching event.
+5. In **Events**, select **${eventLabel}**.
+6. Save the webhook. Deliveries without the right secret are ignored, and a repeated delivery of the same event fires the flow only once.
`;
export const toolFilterProperty = Property.StaticMultiSelectDropdown({
@@ -41,11 +43,97 @@ export const toolFilterProperty = Property.StaticMultiSelectDropdown({
{ label: 'PDF/A', value: 'pdfa' },
{ label: 'Validate PDF/A', value: 'validatepdfa' },
{ label: 'Edit PDF', value: 'editpdf' },
+ { label: 'Compress Image', value: 'compressimage' },
+ { label: 'Resize Image', value: 'resizeimage' },
+ { label: 'Crop Image', value: 'cropimage' },
+ { label: 'Convert Image', value: 'convertimage' },
+ { label: 'Upscale Image', value: 'upscaleimage' },
+ { label: 'Remove Image Background', value: 'removebackgroundimage' },
+ { label: 'Watermark Image', value: 'watermarkimage' },
+ { label: 'Rotate Image', value: 'rotateimage' },
{ label: 'Sign PDF', value: 'sign' },
],
},
});
+export const webhookSecretProperty = Property.ShortText({
+ displayName: 'Webhook Secret',
+ description:
+ 'A random secret of at least 16 characters. Add it to the endpoint URL as ?ap_secret=... (see the steps above).',
+ required: true,
+});
+
+export function hasValidSecret({
+ queryParams,
+ secret,
+}: {
+ queryParams: Record<string, string> | undefined;
+ secret: unknown;
+}): boolean {
+ const expected = typeof secret === 'string' ? secret.trim() : '';
+ if (expected.length < MIN_SECRET_LENGTH) {
+ throw new Error(`Webhook Secret must be at least ${MIN_SECRET_LENGTH} characters long.`);
+ }
+ const given = queryParams?.[SECRET_PARAM];
+ if (typeof given !== 'string' || given === '') return false;
+ return timingSafeEqual(digest(expected), digest(given));
+}
+
+export function dedupeKeyOf(envelope: WebhookEnvelope): string {
+ const task = envelope.data?.task;
+ const signature = envelope.data?.signature;
+ const signer = envelope.data?.signer;
+ const parts = [
+ envelope.event,
+ task?.['task'],
+ signature?.['uuid'] ?? signature?.['token_requester'],
+ signer?.['uuid'] ?? signer?.['token_signer'],
+ ].filter((part) => typeof part === 'string' && part !== '');
+ if (parts.length > 1) return parts.join(':');
+ return createHash('sha256').update(JSON.stringify(envelope)).digest('hex');
+}
+
+export async function claimDelivery({ store, key }: { store: Store; key: string }): Promise<boolean> {
+ const now = Date.now();
+ const seen = ((await store.get<SeenDelivery[]>(SEEN_STORE_KEY)) ?? []).filter(
+ (entry) => now - entry.at < SEEN_TTL_MS
+ );
+ if (seen.some((entry) => entry.key === key)) return false;
+ const claim = randomUUID();
+ await store.put<SeenDelivery[]>(SEEN_STORE_KEY, [...seen, { key, at: now, claim }].slice(-MAX_SEEN));
+ const stored = (await store.get<SeenDelivery[]>(SEEN_STORE_KEY)) ?? [];
+ return stored.some((entry) => entry.key === key && entry.claim === claim);
+}
+
+export async function acceptDelivery({
+ envelope,
+ store,
+ queryParams,
+ secret,
+}: {
+ envelope: WebhookEnvelope;
+ store: Store;
+ queryParams: Record<string, string> | undefined;
+ secret: unknown;
+}): Promise<unknown[]> {
+ if (!hasValidSecret({ queryParams, secret })) return [];
+ const key = dedupeKeyOf(envelope);
+ if (!(await claimDelivery({ store, key }))) return [];
+ return [{ ...envelope, [DEDUPE_KEY_PROPERTY]: `iloveapi:${key}` }];
+}
+
+function digest(value: string): Buffer {
+ return createHash('sha256').update(value).digest();
+}
+
+const SECRET_PARAM = 'ap_secret';
+const MIN_SECRET_LENGTH = 16;
+const SEEN_STORE_KEY = 'iloveapi_seen_deliveries';
+const SEEN_TTL_MS = 24 * 60 * 60 * 1000;
+const MAX_SEEN = 500;
+
+type SeenDelivery = { key: string; at: number; claim?: string };
+
type WebhookEnvelope = {
event?: string;
data?: {
diff --git a/packages/pieces/community/iloveapi/src/lib/triggers/sample-payloads.ts b/packages/pieces/community/iloveapi/src/lib/triggers/sample-payloads.ts
index 63a7e547532..87b96d709ea 100644
--- a/packages/pieces/community/iloveapi/src/lib/triggers/sample-payloads.ts
+++ b/packages/pieces/community/iloveapi/src/lib/triggers/sample-payloads.ts
@@ -5,12 +5,15 @@ export const taskCompletedSample = {
task: 'b3fd95c0c3b8c6f3a7e7b5b7a09a6d2a',
tool: 'compress',
status: 'TaskSuccess',
+ status_message: 'This task has been processed successfully.',
process_start: '2026-05-07 10:00:00',
timer: '1.32',
filesize: 1048576,
output_filesize: 524288,
output_filenumber: 1,
output_extensions: ['pdf'],
+ file_number: 1,
+ download_filename: 'contract.pdf',
server: 'api1g.ilovepdf.com',
custom_int: null,
custom_string: null,
diff --git a/packages/pieces/community/iloveapi/src/lib/triggers/signature-builder.ts b/packages/pieces/community/iloveapi/src/lib/triggers/signature-builder.ts
index 1a0231aff87..2edb9f74f67 100644
--- a/packages/pieces/community/iloveapi/src/lib/triggers/signature-builder.ts
+++ b/packages/pieces/community/iloveapi/src/lib/triggers/signature-builder.ts
@@ -1,15 +1,12 @@
import { Property, TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { iloveapiAuth } from '../common/auth';
-import { matchesEvent, webhookInstructions } from './common';
-
-export type SignatureTriggerSpec = {
- name: string;
- displayName: string;
- description: string;
- aiMetadata?: { description: string };
- event: string;
- sampleData: unknown;
-};
+import { iloveSchemas } from '../common/schemas';
+import {
+ acceptDelivery,
+ matchesEvent,
+ webhookInstructions,
+ webhookSecretProperty,
+} from './common';
export function buildSignatureTrigger(spec: SignatureTriggerSpec) {
return createTrigger({
@@ -24,7 +21,9 @@ export function buildSignatureTrigger(spec: SignatureTriggerSpec) {
instructions: Property.MarkDown({
value: webhookInstructions(`${spec.displayName} (${spec.event})`),
}),
+ webhook_secret: webhookSecretProperty,
},
+ outputSchema: iloveSchemas.signatureEvent,
sampleData: spec.sampleData,
async onEnable() {
return;
@@ -38,7 +37,21 @@ export function buildSignatureTrigger(spec: SignatureTriggerSpec) {
expectedEvent: spec.event,
});
if (!envelope) return [];
- return [envelope];
+ return acceptDelivery({
+ envelope,
+ store: context.store,
+ queryParams: context.payload.queryParams,
+ secret: context.propsValue.webhook_secret,
+ });
},
});
}
+
+export type SignatureTriggerSpec = {
+ name: string;
+ displayName: string;
+ description: string;
+ aiMetadata: { description: string };
+ event: string;
+ sampleData: unknown;
+};
diff --git a/packages/pieces/community/iloveapi/src/lib/triggers/signature-events.ts b/packages/pieces/community/iloveapi/src/lib/triggers/signature-events.ts
index 75fdd3286a5..d1a3423cb5d 100644
--- a/packages/pieces/community/iloveapi/src/lib/triggers/signature-events.ts
+++ b/packages/pieces/community/iloveapi/src/lib/triggers/signature-events.ts
@@ -15,6 +15,10 @@ export const signatureCreatedTrigger = buildSignatureTrigger({
name: 'signature_created',
displayName: 'Signature Created',
description: 'Fires when a new signature request is created.',
+ aiMetadata: {
+ description:
+ 'Fires when a new signature request is created. Delivered by an iLoveSign webhook registered manually in the iLoveAPI dashboard; the payload holds the signature request and, for signer events, the signer.',
+ },
event: 'signature.created',
sampleData: signatureCreatedSample,
});
@@ -23,6 +27,10 @@ export const signatureSentTrigger = buildSignatureTrigger({
name: 'signature_sent',
displayName: 'Signature Sent',
description: 'Fires when a signature request is sent to all receivers.',
+ aiMetadata: {
+ description:
+ 'Fires when a signature request is sent to all receivers. Delivered by an iLoveSign webhook registered manually in the iLoveAPI dashboard; the payload holds the signature request and, for signer events, the signer.',
+ },
event: 'signature.sent',
sampleData: signatureSentSample,
});
@@ -32,6 +40,10 @@ export const signatureCompletedTrigger = buildSignatureTrigger({
displayName: 'Signature Completed',
description:
'Fires when every signer has finished. Use this to drive contract-completion automations.',
+ aiMetadata: {
+ description:
+ 'Fires when every signer has finished. Use this to drive contract-completion automations. Delivered by an iLoveSign webhook registered manually in the iLoveAPI dashboard; the payload holds the signature request and, for signer events, the signer.',
+ },
event: 'signature.completed',
sampleData: signatureCompletedSample,
});
@@ -41,6 +53,10 @@ export const signatureDeclinedTrigger = buildSignatureTrigger({
displayName: 'Signature Declined',
description:
'Fires when a signer or validator declines the signature request.',
+ aiMetadata: {
+ description:
+ 'Fires when a signer or validator declines the signature request. Delivered by an iLoveSign webhook registered manually in the iLoveAPI dashboard; the payload holds the signature request and, for signer events, the signer.',
+ },
event: 'signature.declined',
sampleData: signatureDeclinedSample,
});
@@ -49,6 +65,10 @@ export const signatureExpiredTrigger = buildSignatureTrigger({
name: 'signature_expired',
displayName: 'Signature Expired',
description: 'Fires when a signature request reaches its expiration date.',
+ aiMetadata: {
+ description:
+ 'Fires when a signature request reaches its expiration date. Delivered by an iLoveSign webhook registered manually in the iLoveAPI dashboard; the payload holds the signature request and, for signer events, the signer.',
+ },
event: 'signature.expired',
sampleData: signatureExpiredSample,
});
@@ -57,6 +77,10 @@ export const signatureVoidedTrigger = buildSignatureTrigger({
name: 'signature_voided',
displayName: 'Signature Voided',
description: 'Fires when the requester cancels an in-progress signature.',
+ aiMetadata: {
+ description:
+ 'Fires when the requester cancels an in-progress signature. Delivered by an iLoveSign webhook registered manually in the iLoveAPI dashboard; the payload holds the signature request and, for signer events, the signer.',
+ },
event: 'signature.voided',
sampleData: signatureVoidedSample,
});
@@ -65,6 +89,10 @@ export const signerViewedTrigger = buildSignatureTrigger({
name: 'signer_viewed',
displayName: 'Signer Viewed Document',
description: 'Fires when an individual receiver opens the document.',
+ aiMetadata: {
+ description:
+ 'Fires when an individual receiver opens the document. Delivered by an iLoveSign webhook registered manually in the iLoveAPI dashboard; the payload holds the signature request and, for signer events, the signer.',
+ },
event: 'signature.signer.viewed',
sampleData: signerViewedSample,
});
@@ -73,6 +101,10 @@ export const signerSignedTrigger = buildSignatureTrigger({
name: 'signer_signed',
displayName: 'Signer Signed',
description: 'Fires when an individual signer completes their signature.',
+ aiMetadata: {
+ description:
+ 'Fires when an individual signer completes their signature. Delivered by an iLoveSign webhook registered manually in the iLoveAPI dashboard; the payload holds the signature request and, for signer events, the signer.',
+ },
event: 'signature.signer.completed',
sampleData: signerSignedSample,
});
@@ -81,6 +113,10 @@ export const signerDeclinedTrigger = buildSignatureTrigger({
name: 'signer_declined',
displayName: 'Signer Declined',
description: 'Fires when an individual signer declines to sign.',
+ aiMetadata: {
+ description:
+ 'Fires when an individual signer declines to sign. Delivered by an iLoveSign webhook registered manually in the iLoveAPI dashboard; the payload holds the signature request and, for signer events, the signer.',
+ },
event: 'signature.signer.declined',
sampleData: signerDeclinedSample,
});
diff --git a/packages/pieces/community/iloveapi/src/lib/triggers/task-completed.ts b/packages/pieces/community/iloveapi/src/lib/triggers/task-completed.ts
index c193e25dd76..08ca1571248 100644
--- a/packages/pieces/community/iloveapi/src/lib/triggers/task-completed.ts
+++ b/packages/pieces/community/iloveapi/src/lib/triggers/task-completed.ts
@@ -1,10 +1,13 @@
import { Property, TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { iloveapiAuth } from '../common/auth';
+import { iloveSchemas } from '../common/schemas';
import {
+ acceptDelivery,
matchesEvent,
matchesToolFilter,
toolFilterProperty,
webhookInstructions,
+ webhookSecretProperty,
} from './common';
import { taskCompletedSample } from './sample-payloads';
@@ -24,8 +27,10 @@ export const taskCompletedTrigger = createTrigger({
instructions: Property.MarkDown({
value: webhookInstructions('Task Completed (task.completed)'),
}),
+ webhook_secret: webhookSecretProperty,
tools: toolFilterProperty,
},
+ outputSchema: iloveSchemas.taskEvent,
sampleData: taskCompletedSample,
async onEnable() {
return;
@@ -43,6 +48,11 @@ export const taskCompletedTrigger = createTrigger({
const tools = (context.propsValue.tools ?? []) as string[] | undefined;
if (!matchesToolFilter({ envelope, tools })) return [];
- return [envelope];
+ return acceptDelivery({
+ envelope,
+ store: context.store,
+ queryParams: context.payload.queryParams,
+ secret: context.propsValue.webhook_secret,
+ });
},
});
diff --git a/packages/pieces/community/iloveapi/src/lib/triggers/task-failed.ts b/packages/pieces/community/iloveapi/src/lib/triggers/task-failed.ts
index 5463375dbfa..21381aca959 100644
--- a/packages/pieces/community/iloveapi/src/lib/triggers/task-failed.ts
+++ b/packages/pieces/community/iloveapi/src/lib/triggers/task-failed.ts
@@ -1,10 +1,13 @@
import { Property, TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { iloveapiAuth } from '../common/auth';
+import { iloveSchemas } from '../common/schemas';
import {
+ acceptDelivery,
matchesEvent,
matchesToolFilter,
toolFilterProperty,
webhookInstructions,
+ webhookSecretProperty,
} from './common';
import { taskFailedSample } from './sample-payloads';
@@ -24,8 +27,10 @@ export const taskFailedTrigger = createTrigger({
instructions: Property.MarkDown({
value: webhookInstructions('Task Failed (task.failed)'),
}),
+ webhook_secret: webhookSecretProperty,
tools: toolFilterProperty,
},
+ outputSchema: iloveSchemas.taskEvent,
sampleData: taskFailedSample,
async onEnable() {
return;
@@ -43,6 +48,11 @@ export const taskFailedTrigger = createTrigger({
const tools = (context.propsValue.tools ?? []) as string[] | undefined;
if (!matchesToolFilter({ envelope, tools })) return [];
- return [envelope];
+ return acceptDelivery({
+ envelope,
+ store: context.store,
+ queryParams: context.payload.queryParams,
+ secret: context.propsValue.webhook_secret,
+ });
},
});
diff --git a/packages/pieces/community/iloveapi/test/helpers.ts b/packages/pieces/community/iloveapi/test/helpers.ts
new file mode 100644
index 00000000000..78c147e0713
--- /dev/null
+++ b/packages/pieces/community/iloveapi/test/helpers.ts
@@ -0,0 +1,150 @@
+import { Readable } from 'stream';
+import { HttpError, httpClient } from '@activepieces/pieces-common';
+import { vi } from 'vitest';
+
+export type Call = {
+ method: string;
+ url: string;
+ body: unknown;
+ headers: Record<string, string>;
+ query: unknown;
+ redact: boolean | undefined;
+ responseType: string | undefined;
+ followRedirects: boolean | undefined;
+ hasDispatcher: boolean;
+};
+
+export type Route = {
+ method: string;
+ match: (url: string) => boolean;
+ status?: number;
+ body?: unknown;
+ reply?: (call: Call) => { status?: number; body?: unknown; headers?: Record<string, string> };
+};
+
+export const SERVER = 'api11.ilovepdf.com';
+
+export function defaultRoutes(overrides: Route[] = []): Route[] {
+ return [
+ ...overrides,
+ { method: 'POST', match: (u) => u === 'https://api.ilovepdf.com/v1/auth', body: { token: 'jwt-1' } },
+ {
+ method: 'GET',
+ match: (u) => /\/v1\/start\//.test(u),
+ body: { server: SERVER, task: 'TASK1', remaining_credits: 2400 },
+ },
+ {
+ method: 'POST',
+ match: (u) => u === `https://${SERVER}/v1/upload`,
+ reply: (call) => ({ body: { server_filename: `sf-${uploadIndex(call)}` } }),
+ },
+ {
+ method: 'POST',
+ match: (u) => u === `https://${SERVER}/v1/process`,
+ body: {
+ download_filename: 'out.pdf',
+ filesize: 2000,
+ output_filesize: 1000,
+ output_filenumber: 1,
+ output_extensions: '["pdf"]',
+ timer: '0.5',
+ status: 'TaskSuccess',
+ },
+ },
+ {
+ method: 'GET',
+ match: (u) => u.startsWith(`https://${SERVER}/v1/download/`),
+ reply: () => ({ body: Readable.from([Buffer.from('RESULT')]), headers: { 'content-type': 'application/pdf' } }),
+ },
+ ];
+}
+
+let uploads = 0;
+function uploadIndex(_call: Call): number {
+ uploads += 1;
+ return uploads;
+}
+
+export function mockHttp(routes: Route[]): Call[] {
+ uploads = 0;
+ const calls: Call[] = [];
+ vi.spyOn(httpClient, 'sendRequest').mockImplementation(async (request, options) => {
+ const call: Call = {
+ method: request.method,
+ url: request.url,
+ body: request.body,
+ headers: stringRecord(request.headers),
+ query: request.queryParams,
+ redact: request.redactBodyInErrors,
+ responseType: request.responseType,
+ followRedirects: request.followRedirects,
+ hasDispatcher: Boolean(options && 'dispatcher' in options && options.dispatcher),
+ };
+ calls.push(call);
+ const route = routes.find((r) => r.method === request.method && r.match(request.url));
+ if (!route) throw new Error(`unexpected ${request.method} ${request.url}`);
+ const result = route.reply ? route.reply(call) : { status: route.status, body: route.body };
+ const status = result.status ?? 200;
+ if (status >= 400) {
+ throw new HttpError('[redacted]', { status, responseBody: result.body });
+ }
+ return loose({ status, headers: result.headers ?? {}, body: result.body });
+ });
+ return calls;
+}
+
+export function fakeContext(propsValue: Record<string, unknown>) {
+ const written: Array<{ fileName: string; data: Buffer }> = [];
+ const store = new Map<string, unknown>();
+ return {
+ written,
+ store,
+ context: {
+ auth: { type: 'SECRET_TEXT', secret_text: ' project_public_abc ' },
+ propsValue,
+ files: {
+ write: vi.fn(async ({ fileName, data }: { fileName: string; data: Buffer }) => {
+ written.push({ fileName, data });
+ return `https://files.example/${fileName}`;
+ }),
+ },
+ store: {
+ get: vi.fn(async (key: string) => store.get(key) ?? null),
+ put: vi.fn(async (key: string, value: unknown) => {
+ store.set(key, value);
+ return value;
+ }),
+ delete: vi.fn(async (key: string) => {
+ store.delete(key);
+ }),
+ },
+ },
+ };
+}
+
+export const pdf = { base64: Buffer.from('%PDF-1.4').toString('base64'), filename: 'in.pdf', extension: 'pdf' };
+export const png = { base64: Buffer.from('PNG').toString('base64'), filename: 'in.png', extension: 'png' };
+
+export function processBody(calls: Call[]): Record<string, unknown> {
+ const call = calls.find((c) => c.url.endsWith('/v1/process'));
+ if (!call) throw new Error('no process call');
+ return record(call.body);
+}
+
+export function run(action: { run: (ctx: never) => Promise<unknown> }) {
+ return async (context: unknown): Promise<Record<string, unknown>> => record(await action.run(loose(context)));
+}
+
+export function loose(value: unknown): never {
+ return Reflect.get({ value }, 'value');
+}
+
+export function record(value: unknown): Record<string, unknown> {
+ if (value === null || typeof value !== 'object') throw new Error('expected an object');
+ return Object.fromEntries(Object.entries(value));
+}
+
+function stringRecord(value: unknown): Record<string, string> {
+ if (value === null || typeof value !== 'object') return {};
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, String(v)]));
+}
diff --git a/packages/pieces/community/iloveapi/test/platform.test.ts b/packages/pieces/community/iloveapi/test/platform.test.ts
new file mode 100644
index 00000000000..5a9e67f12bc
--- /dev/null
+++ b/packages/pieces/community/iloveapi/test/platform.test.ts
@@ -0,0 +1,130 @@
+import { Readable } from 'stream';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { iLoveApi } from '../src/lib/common/client';
+import { iloveHost } from '../src/lib/common/host';
+import { iloveapiAuth } from '../src/lib/common/auth';
+import { iloveapi } from '../src/index';
+import { defaultRoutes, loose, mockHttp, record } from './helpers';
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+});
+
+describe('host allow-list', () => {
+ it.each(['api11.ilovepdf.com', 'api8g.iloveimg.com', 'api.iloveapi.com'])('accepts %s', (host) => {
+ expect(iloveHost.assertServerHost(host)).toBe(host);
+ });
+ it.each(['api.ilovepdf.com.evil.io', '[email protected]', '//api.ilovepdf.com', 'evil.com/x.ilovepdf.com', 'api.ilovepdf.com:444', '', undefined])(
+ 'refuses %s',
+ (host) => {
+ expect(() => iloveHost.assertServerHost(host)).toThrow(/unexpected server/);
+ }
+ );
+ it('refuses URLs with credentials, ports or http', () => {
+ expect(iloveHost.isAllowedUrl('https://u:[email protected]/v1')).toBe(false);
+ expect(iloveHost.isAllowedUrl('http://api.ilovepdf.com/v1')).toBe(false);
+ expect(iloveHost.isAllowedUrl('https://api.ilovepdf.com:8443/v1')).toBe(false);
+ expect(iloveHost.isAllowedUrl('https://api.ilovepdf.com/v1')).toBe(true);
+ });
+});
+
+describe('request helper', () => {
+ it('trims the key, redacts the auth body and verifies TLS', async () => {
+ const calls = mockHttp(defaultRoutes());
+ await iLoveApi.authenticate({ publicKey: ' key ' });
+ expect(calls[0]).toMatchObject({ body: { public_key: 'key' }, redact: true, hasDispatcher: true, followRedirects: false });
+ });
+
+ it('retries a 429 with backoff and then succeeds', async () => {
+ vi.useFakeTimers();
+ let count = 0;
+ mockHttp([
+ {
+ method: 'POST',
+ match: () => true,
+ reply: () => {
+ count += 1;
+ return count < 3 ? { status: 429, body: { error: { message: 'slow down' } } } : { body: { token: 't' } };
+ },
+ },
+ ]);
+ const promise = iLoveApi.authenticate({ publicKey: 'k' });
+ await vi.advanceTimersByTimeAsync(10_000);
+ await expect(promise).resolves.toBe('t');
+ expect(count).toBe(3);
+ });
+
+ it('gives up after repeated 429s with a rate limit message', async () => {
+ vi.useFakeTimers();
+ mockHttp([{ method: 'POST', match: () => true, status: 429, body: {} }]);
+ const promise = iLoveApi.authenticate({ publicKey: 'k' }).catch((e: Error) => e);
+ await vi.advanceTimersByTimeAsync(60_000);
+ const error = await promise;
+ expect(String(error)).toMatch(/rate limit/);
+ expect(error).toHaveProperty('status', 429);
+ });
+
+ it('caps download size', async () => {
+ const big = Buffer.alloc(1024 * 1024);
+ mockHttp([
+ {
+ method: 'GET',
+ match: () => true,
+ reply: () => ({ body: Readable.from(Array.from({ length: 101 }, () => big)) }),
+ },
+ ]);
+ await expect(iLoveApi.downloadResult({ token: 't', server: 'api1.ilovepdf.com', task: 'T' })).rejects.toThrow(/100 MB/);
+ });
+
+ it('enforces its own download deadline', async () => {
+ vi.useFakeTimers();
+ mockHttp([{ method: 'GET', match: () => true, reply: () => ({ body: new Readable({ read() { return; } }) }) }]);
+ const promise = iLoveApi.downloadResult({ token: 't', server: 'api1.ilovepdf.com', task: 'T' }).catch((e: Error) => e);
+ await vi.advanceTimersByTimeAsync(121_000);
+ expect(String(await promise)).toMatch(/did not finish/);
+ });
+});
+
+describe('auth validate', () => {
+ it('reports invalid only on 401/403', async () => {
+ mockHttp([{ method: 'POST', match: () => true, status: 401, body: { name: 'Unauthorized' } }]);
+ await expect(iloveapiAuth.validate?.(loose({ auth: 'k' }))).resolves.toEqual({ valid: false, error: 'Invalid iLoveAPI project public key.' });
+ vi.restoreAllMocks();
+ mockHttp([{ method: 'POST', match: () => true, status: 500, body: { name: 'ServerError' } }]);
+ const result = await iloveapiAuth.validate?.(loose({ auth: 'k' }));
+ expect(result).toMatchObject({ valid: false });
+ expect(record(result)['error']).toMatch(/Could not verify/);
+ });
+ it('accepts a working key', async () => {
+ mockHttp(defaultRoutes());
+ await expect(iloveapiAuth.validate?.(loose({ auth: 'k' }))).resolves.toEqual({ valid: true });
+ });
+});
+
+describe('custom api call', () => {
+ const action = iloveapi.actions()['custom_api_call'];
+ async function headersFor(url: string): Promise<unknown> {
+ mockHttp([...defaultRoutes(), { method: 'GET', match: () => true, body: {} }]);
+ const props = record(action.props);
+ expect(props).toBeDefined();
+ return action.run(loose({
+ auth: { type: 'SECRET_TEXT', secret_text: 'k' },
+ propsValue: { url: { url }, method: 'GET', headers: {}, queryParams: {}, failsafe: false },
+ }));
+ }
+ it.each([
+ 'https://api.ilovepdf.com.evil.io/v1/x',
+ 'https://evil.io/v1/x',
+ '//evil.io/v1',
+ 'https://api.ilovepdf.com/v2/x',
+ 'https://[email protected]/v1/x',
+ '../../x',
+ '%2e%2e/x',
+ ])('refuses %s', async (url) => {
+ await expect(headersFor(url)).rejects.toThrow(/only sends your iLoveAPI credentials|not valid/);
+ });
+ it('allows a relative path on the base', async () => {
+ await expect(headersFor('signature/list')).resolves.toBeDefined();
+ });
+});
diff --git a/packages/pieces/community/iloveapi/test/signatures.test.ts b/packages/pieces/community/iloveapi/test/signatures.test.ts
new file mode 100644
index 00000000000..64c9097910e
--- /dev/null
+++ b/packages/pieces/community/iloveapi/test/signatures.test.ts
@@ -0,0 +1,118 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createSignatureRequestAction } from '../src/lib/actions/create-signature-request';
+import { createSignatureRequestAiAction } from '../src/lib/actions/create-signature-request-ai';
+import { getSignatureStatusAction } from '../src/lib/actions/get-signature-status';
+import { getSignerInfoAction } from '../src/lib/actions/get-signer-info';
+import { listSignatureRequestsAction } from '../src/lib/actions/list-signature-requests';
+import { sendSignerReminderAction } from '../src/lib/actions/send-signer-reminder';
+import { voidSignatureAction } from '../src/lib/actions/void-signature';
+import { increaseExpirationDaysAction } from '../src/lib/actions/increase-expiration-days';
+import { downloadSignedFilesAction } from '../src/lib/actions/download-signed-files';
+import { downloadAuditTrailAction } from '../src/lib/actions/download-audit-trail';
+import { Readable } from 'stream';
+import { SERVER, defaultRoutes, fakeContext, mockHttp, pdf, record, run } from './helpers';
+
+afterEach(() => vi.restoreAllMocks());
+
+const created = { uuid: 'u1', token_requester: 'TR1', status: 'sent', signers: [] };
+const sigRoutes = defaultRoutes([
+ { method: 'POST', match: (u) => u === `https://${SERVER}/v1/signature`, body: created },
+ { method: 'GET', match: (u) => u.includes('/v1/signature/requesterview/'), body: { token_requester: 'TR1', status: 'completed', server: SERVER } },
+ { method: 'GET', match: (u) => u.includes('/v1/signature/receiver/info/'), body: { uuid: 's1', email: '[email protected]', access_code: 'secret' } },
+ { method: 'GET', match: (u) => u.startsWith('https://api.ilovepdf.com/v1/signature/list'), body: [{ token_requester: 'A' }, { token_requester: 'B' }] },
+ { method: 'POST', match: (u) => /\/v1\/signature\/(sendReminder|void|increase-expiration-days)\//.test(u), body: {} },
+ { method: 'GET', match: (u) => u.includes('/download-'), reply: () => ({ body: Readable.from([Buffer.from('ZIP')]), headers: { 'content-type': 'application/zip' } }) },
+]);
+
+const signers = [
+ { name: 'Ann', email: '[email protected]', access_code: '1234' },
+ { name: 'Bob', email: '[email protected]', type: 'viewer' },
+];
+
+describe('create signature request', () => {
+ it('is human-only and builds the exact body', async () => {
+ const calls = mockHttp(sigRoutes);
+ const out = await run(createSignatureRequestAction)(fakeContext({
+ files: [{ file: pdf }],
+ signers,
+ elements: [{ signer_email: '[email protected]', type: 'signature', position: 'bottom right', pages: '1' }],
+ expiration_days: 30,
+ }).context
+ );
+ expect(createSignatureRequestAction.audience).toBe('human');
+ const body = record(calls.find((c) => c.url.endsWith('/v1/signature'))?.body);
+ expect(body).toMatchObject({ task: 'TASK1', expiration_days: 30, files: [{ server_filename: 'sf-1', filename: 'in.pdf' }] });
+ expect(body['signers']).toEqual([
+ {
+ name: 'Ann',
+ email: '[email protected]',
+ type: 'signer',
+ force_signature_type: 'all',
+ access_code: '1234',
+ files: [{ server_filename: 'sf-1', elements: [{ type: 'signature', position: 'bottom right', pages: '1' }] }],
+ },
+ { name: 'Bob', email: '[email protected]', type: 'viewer', force_signature_type: 'all', files: [{ server_filename: 'sf-1' }] },
+ ]);
+ expect(calls.find((c) => c.url.endsWith('/v1/signature'))?.redact).toBe(true);
+ expect(out).toMatchObject({ token_requester: 'TR1', server: SERVER });
+ });
+
+ it.each([
+ [{ elements: [{ signer_email: '[email protected]', type: 'signature', position: 'a', pages: '1' }] }, /matches no signer/],
+ [{ elements: [{ signer_email: '[email protected]', type: 'signature', pages: '1' }] }, /element 1 needs/],
+ [{ expiration_days: 200 }, /between 1 and 130/],
+ [{ signers: [{ name: 'A', email: 'bad' }] }, /invalid email/],
+ [{ signers: [signers[0], signers[0]] }, /more than once/],
+ [{ files: [] }, /At least one PDF/],
+ ])('rejects %o before any request', async (override, message) => {
+ const calls = mockHttp(sigRoutes);
+ await expect(run(createSignatureRequestAction)(fakeContext({ files: [{ file: pdf }], signers, ...override }).context)).rejects.toThrow(message);
+ expect(calls.filter((c) => c.url.includes('/v1/start/'))).toHaveLength(0);
+ });
+
+ it('ai twin uploads URLs and refuses http', async () => {
+ const calls = mockHttp(sigRoutes);
+ await run(createSignatureRequestAiAction)(fakeContext({ file_urls: ['https://x.co/a.pdf'], signers: [signers[0]] }).context);
+ expect(createSignatureRequestAiAction.audience).toBe('ai');
+ expect(calls.find((c) => c.url.endsWith('/v1/upload'))?.body).toEqual({ task: 'TASK1', cloud_file: 'https://x.co/a.pdf' });
+ await expect(run(createSignatureRequestAiAction)(fakeContext({ file_urls: ['http://x.co/a.pdf'], signers }).context)).rejects.toThrow(/https/);
+ });
+});
+
+describe('signature follow-ups', () => {
+ it('status, signer info and list', async () => {
+ const calls = mockHttp(sigRoutes);
+ expect(await run(getSignatureStatusAction)(fakeContext({ token_requester: ' TR1 ' }).context)).toMatchObject({ status: 'completed' });
+ expect(calls.at(-1)?.url).toBe('https://api.ilovepdf.com/v1/signature/requesterview/TR1');
+ expect(await run(getSignerInfoAction)(fakeContext({ token_signer: 'S/1' }).context)).toMatchObject({ access_code: true });
+ expect(calls.at(-1)?.url).toBe('https://api.ilovepdf.com/v1/signature/receiver/info/S%2F1');
+ const list = await run(listSignatureRequestsAction)(fakeContext({ page: 1, per_page: 2 }).context);
+ expect(list).toMatchObject({ count: 2, has_more: true, next_page: 2 });
+ expect(calls.at(-1)?.query).toEqual({ page: '1', 'per-page': '2' });
+ await expect(run(listSignatureRequestsAction)(fakeContext({ per_page: 101 }).context)).rejects.toThrow(/between 1 and 100/);
+ });
+
+ it('reminder, void, increase expiration', async () => {
+ const calls = mockHttp(sigRoutes);
+ expect(await run(sendSignerReminderAction)(fakeContext({ token_requester: 'TR1' }).context)).toMatchObject({ success: true, token_requester: 'TR1' });
+ expect(calls.at(-1)?.url).toBe('https://api.ilovepdf.com/v1/signature/sendReminder/TR1');
+ await run(voidSignatureAction)(fakeContext({ token_requester: 'TR1' }).context);
+ expect(calls.at(-1)?.url).toBe('https://api.ilovepdf.com/v1/signature/void/TR1');
+ expect(await run(increaseExpirationDaysAction)(fakeContext({ token_requester: 'TR1', days: 5 }).context)).toMatchObject({ days: 5 });
+ expect(calls.at(-1)?.body).toEqual({ days: 5 });
+ await expect(run(increaseExpirationDaysAction)(fakeContext({ token_requester: 'TR1', days: 131 }).context)).rejects.toThrow(/between 1 and 130/);
+ await expect(run(voidSignatureAction)(fakeContext({ token_requester: '..' }).context)).rejects.toThrow(/required/);
+ });
+
+ it('downloads go to the server host as a stream', async () => {
+ const calls = mockHttp(sigRoutes);
+ const out = await run(downloadSignedFilesAction)(fakeContext({ token_requester: 'TR1' }).context);
+ const dl = calls.find((c) => c.url.includes('download-signed'));
+ expect(dl?.url).toBe(`https://${SERVER}/v1/signature/TR1/download-signed`);
+ expect(dl?.responseType).toBe('stream');
+ expect(out).toMatchObject({ file_name: 'signed-TR1.zip', size: 3, content_type: 'application/zip' });
+ await run(downloadAuditTrailAction)(fakeContext({ token_requester: 'TR1', server: 'api3.ilovepdf.com' }).context);
+ expect(calls.at(-1)?.url).toBe('https://api3.ilovepdf.com/v1/signature/TR1/download-audit');
+ await expect(run(downloadAuditTrailAction)(fakeContext({ token_requester: 'TR1', server: 'evil.io' }).context)).rejects.toThrow(/unexpected server/);
+ });
+});
diff --git a/packages/pieces/community/iloveapi/test/tools.test.ts b/packages/pieces/community/iloveapi/test/tools.test.ts
new file mode 100644
index 00000000000..c6837c4aab4
--- /dev/null
+++ b/packages/pieces/community/iloveapi/test/tools.test.ts
@@ -0,0 +1,311 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { fileToUploadInput } from '../src/lib/common/props';
+import { compressPdfAction } from '../src/lib/actions/compress-pdf';
+import { mergePdfAction } from '../src/lib/actions/merge-pdf';
+import { splitPdfAction } from '../src/lib/actions/split-pdf';
+import { pdfToJpgAction } from '../src/lib/actions/pdf-to-jpg';
+import { jpgToPdfAction } from '../src/lib/actions/jpg-to-pdf';
+import { officeToPdfAction } from '../src/lib/actions/office-to-pdf';
+import { htmlToPdfAction } from '../src/lib/actions/html-to-pdf';
+import { ocrPdfAction } from '../src/lib/actions/ocr-pdf';
+import { watermarkPdfAction } from '../src/lib/actions/watermark-pdf';
+import { protectPdfAction } from '../src/lib/actions/protect-pdf';
+import { unlockPdfAction } from '../src/lib/actions/unlock-pdf';
+import { pageNumbersPdfAction } from '../src/lib/actions/page-numbers';
+import { rotatePdfAction } from '../src/lib/actions/rotate-pdf';
+import { extractTextPdfAction } from '../src/lib/actions/extract-text';
+import { repairPdfAction } from '../src/lib/actions/repair-pdf';
+import { convertPdfaAction } from '../src/lib/actions/convert-pdf-to-pdfa';
+import { validatePdfaAction } from '../src/lib/actions/validate-pdfa';
+import { compressImageAction } from '../src/lib/actions/compress-image';
+import { resizeImageAction } from '../src/lib/actions/resize-image';
+import { cropImageAction } from '../src/lib/actions/crop-image';
+import { convertImageAction } from '../src/lib/actions/convert-image';
+import { upscaleImageAction } from '../src/lib/actions/upscale-image';
+import { removeBackgroundImageAction } from '../src/lib/actions/remove-background-image';
+import { watermarkImageAction } from '../src/lib/actions/watermark-image';
+import { rotateImageAction } from '../src/lib/actions/rotate-image';
+import { Readable } from 'stream';
+import { httpClient } from '@activepieces/pieces-common';
+import { SERVER, defaultRoutes, fakeContext, mockHttp, pdf, png, processBody, record, run, loose } from './helpers';
+
+afterEach(() => vi.restoreAllMocks());
+
+type Case = {
+ name: string;
+ action: { run: (ctx: never) => Promise<unknown>; classification?: string; outputSchema?: unknown };
+ props: Record<string, unknown>;
+ tool: string;
+ expect: Record<string, unknown>;
+ host?: string;
+};
+
+const cases: Case[] = [
+ { name: 'compress', action: compressPdfAction, props: { file: pdf, compression_level: 'extreme' }, tool: 'compress', expect: { compression_level: 'extreme' } },
+ { name: 'merge', action: mergePdfAction, props: { files: [{ file: pdf }, { file: pdf }] }, tool: 'merge', expect: {} },
+ { name: 'split', action: splitPdfAction, props: { file: pdf, split_mode: 'ranges', ranges: '1-2, 4' }, tool: 'split', expect: { split_mode: 'ranges', ranges: '1-2,4', merge_after: false } },
+ { name: 'pdfjpg', action: pdfToJpgAction, props: { file: pdf }, tool: 'pdfjpg', expect: { pdfjpg_mode: 'pages' } },
+ { name: 'imagepdf', action: jpgToPdfAction, props: { images: [{ file: png }] }, tool: 'imagepdf', expect: { orientation: 'portrait', pagesize: 'fit', merge_after: true } },
+ { name: 'officepdf', action: officeToPdfAction, props: { file: { ...pdf, filename: 'a.docx' } }, tool: 'officepdf', expect: {} },
+ { name: 'ocr', action: ocrPdfAction, props: { file: pdf, ocr_languages: ['eng', { 0: 'f', 1: 'r', 2: 'a' }] }, tool: 'pdfocr', expect: { ocr_languages: ['eng', 'fra'] } },
+ { name: 'watermark', action: watermarkPdfAction, props: { file: pdf, mode: 'text', text: 'DRAFT' }, tool: 'watermark', expect: { mode: 'text', text: 'DRAFT', pages: 'all' } },
+ { name: 'protect', action: protectPdfAction, props: { file: pdf, password: 's3cret' }, tool: 'protect', expect: { password: 's3cret' } },
+ { name: 'pagenumber', action: pageNumbersPdfAction, props: { file: pdf }, tool: 'pagenumber', expect: { pages: 'all', starting_number: 1 } },
+ { name: 'repair', action: repairPdfAction, props: { file: pdf }, tool: 'repair', expect: {} },
+ { name: 'pdfa', action: convertPdfaAction, props: { file: pdf, conformance: 'pdfa-1b' }, tool: 'pdfa', expect: { conformance: 'pdfa-1b', allow_downgrade: true } },
+ { name: 'compressimage', action: compressImageAction, props: { file: png }, tool: 'compressimage', expect: { compression_level: 'recommended' }, host: 'api.iloveimg.com' },
+ { name: 'resizeimage', action: resizeImageAction, props: { file: png, resize_mode: 'percentage', percentage: 50 }, tool: 'resizeimage', expect: { resize_mode: 'percentage', percentage: 50 }, host: 'api.iloveimg.com' },
+ { name: 'cropimage', action: cropImageAction, props: { file: png, width: 10, height: 20 }, tool: 'cropimage', expect: { width: 10, height: 20, x: 0, y: 0 }, host: 'api.iloveimg.com' },
+ { name: 'convertimage', action: convertImageAction, props: { file: png, to: 'heic' }, tool: 'convertimage', expect: { to: 'heic' }, host: 'api.iloveimg.com' },
+ { name: 'upscaleimage', action: upscaleImageAction, props: { file: png, multiplier: 4 }, tool: 'upscaleimage', expect: { multiplier: 4 }, host: 'api.iloveimg.com' },
+ { name: 'removebg', action: removeBackgroundImageAction, props: { file: png }, tool: 'removebackgroundimage', expect: {}, host: 'api.iloveimg.com' },
+];
+
+describe('tool actions', () => {
+ it.each(cases)('$name sends the exact process body and stores the result', async (c) => {
+ const calls = mockHttp(defaultRoutes());
+ const { context, written } = fakeContext({ ...c.props, region: 'eu', webhook_url: ' https://hooks.example.com/api/v1/webhooks/F1?ap_secret=abc ' });
+ const out = await run(c.action)(context);
+ expect(c.action.classification).toBe('READ');
+ expect(c.action.outputSchema).toBeDefined();
+ const start = calls.find((x) => x.url.includes('/v1/start/'));
+ expect(start?.url).toBe(`https://${c.host ?? 'api.ilovepdf.com'}/v1/start/${c.tool}/eu`);
+ expect(start?.headers['Authorization']).toBe('Bearer jwt-1');
+ const body = processBody(calls);
+ expect(body).toMatchObject({ task: 'TASK1', tool: c.tool, webhook: 'https://hooks.example.com/api/v1/webhooks/F1?ap_secret=abc', ...c.expect });
+ expect(calls.every((x) => x.redact === true || x.responseType === 'stream')).toBe(true);
+ expect(calls.every((x) => x.hasDispatcher && x.followRedirects === false)).toBe(true);
+ const download = calls.find((x) => x.url.includes('/v1/download/'));
+ expect(download?.responseType).toBe('stream');
+ expect(written[0].data.toString()).toBe('RESULT');
+ expect(out).toMatchObject({ output_file: 'https://files.example/out.pdf', task: 'TASK1', remaining_credits: 2400, status: 'TaskSuccess' });
+ });
+
+ it('html to pdf uploads a cloud URL', async () => {
+ const calls = mockHttp(defaultRoutes());
+ const { context } = fakeContext({ url: 'https://example.com/page' });
+ await run(htmlToPdfAction)(context);
+ expect(calls.find((x) => x.url.endsWith('/v1/upload'))?.body).toEqual({ task: 'TASK1', cloud_file: 'https://example.com/page' });
+ expect(calls.find((x) => x.url.includes('/v1/start/'))?.url).toBe('https://api.ilovepdf.com/v1/start/htmlpdf');
+ });
+
+ it('unlock and rotate put per-file overrides on the file', async () => {
+ let calls = mockHttp(defaultRoutes());
+ await run(unlockPdfAction)(fakeContext({ file: pdf, password: 'pw' }).context);
+ expect(processBody(calls)['files']).toEqual([{ server_filename: 'sf-1', filename: 'in.pdf', password: 'pw' }]);
+ vi.restoreAllMocks();
+ calls = mockHttp(defaultRoutes());
+ await run(rotatePdfAction)(fakeContext({ file: pdf, rotation: 180 }).context);
+ expect(processBody(calls)['files']).toEqual([{ server_filename: 'sf-1', filename: 'in.pdf', rotate: 180 }]);
+ vi.restoreAllMocks();
+ calls = mockHttp(defaultRoutes());
+ await run(rotateImageAction)(fakeContext({ file: png, rotation: 90 }).context);
+ expect(processBody(calls)['files']).toEqual([{ server_filename: 'sf-1', filename: 'in.png', rotate: 90 }]);
+ });
+
+ it('watermark image sends one image element referencing the uploaded stamp', async () => {
+ const calls = mockHttp(defaultRoutes());
+ await run(watermarkImageAction)(fakeContext({ file: png, image: png, gravity: 'SouthEast' }).context);
+ expect(calls.find((x) => x.url.includes('/v1/start/'))?.url).toBe('https://api.iloveimg.com/v1/start/watermarkimage');
+ expect(processBody(calls)['elements']).toEqual([
+ { type: 'image', server_filename: 'sf-2', gravity: 'SouthEast', width_percent: 30, height_percent: 30, x_pos_percent: 0, y_pos_percent: 0, rotation: 0, transparency: 100, mosaic: false },
+ ]);
+ expect(processBody(calls)['files']).toEqual([{ server_filename: 'sf-1', filename: 'in.png' }]);
+ });
+
+ it('no webhook key is sent when the prop is empty', async () => {
+ const calls = mockHttp(defaultRoutes());
+ await run(compressPdfAction)(fakeContext({ file: pdf, webhook_url: '' }).context);
+ expect(processBody(calls)).not.toHaveProperty('webhook');
+ });
+
+ it('watermark pdf image mode references the uploaded stamp', async () => {
+ const calls = mockHttp(defaultRoutes());
+ await run(watermarkPdfAction)(fakeContext({ file: pdf, mode: 'image', image: png }).context);
+ expect(processBody(calls)).toMatchObject({ mode: 'image', image: 'sf-2' });
+ });
+
+ it('wrong password 400 gives a clear error with responseBody and no body field', async () => {
+ mockHttp(
+ defaultRoutes([
+ {
+ method: 'POST',
+ match: (u) => u.endsWith('/v1/process'),
+ status: 400,
+ body: { error: { type: 'ProcessingError', message: 'WrongPassword', code: '400' } },
+ },
+ ])
+ );
+ const error = await run(unlockPdfAction)(fakeContext({ file: pdf, password: 'bad' }).context).catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(Error);
+ expect(String(Reflect.get(Object(error), 'message'))).toMatch(/password is wrong/);
+ expect(error).toHaveProperty('responseBody');
+ expect(error).not.toHaveProperty('body');
+ });
+
+ it('validate pdfa reads validations and skips the download', async () => {
+ const calls = mockHttp(
+ defaultRoutes([
+ {
+ method: 'POST',
+ match: (u) => u.endsWith('/v1/process'),
+ body: { status: 'TaskSuccess', validations: [{ server_filename: 'sf-1', status: 'Conformant' }] },
+ },
+ ])
+ );
+ const out = await run(validatePdfaAction)(fakeContext({ file: pdf }).context);
+ expect(validatePdfaAction.classification).toBe('READ');
+ expect(out).toMatchObject({ conformant: true, task: 'TASK1' });
+ expect(calls.some((x) => x.url.includes('/download/'))).toBe(false);
+ });
+
+ it('extract text returns text and parses detailed rows', async () => {
+ const csv = Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from('PageNo,XPos,YPos,XWidth,YWidth,FontName,FontSize,Length,Text\r\n1,56.8,1,2,3,"Arial",12,12,Hello, world\r\n', 'utf16le')]);
+ mockHttp(
+ defaultRoutes([
+ { method: 'GET', match: (u) => u.includes('/v1/download/'), reply: () => ({ body: Readable.from([csv]) }) },
+ ])
+ );
+ const out = await run(extractTextPdfAction)(fakeContext({ file: pdf, detailed: true }).context);
+ expect(out['text_truncated']).toBe(false);
+ expect(out['text']).toMatch(/^PageNo,XPos/);
+ expect(out['detailed']).toEqual([{ PageNo: 1, XPos: 56.8, YPos: 1, XWidth: 2, YWidth: 3, FontName: 'Arial', FontSize: 12, Length: 12, Text: 'Hello, world' }]);
+ });
+
+ it('extract text flags detailed rows past the row limit', async () => {
+ const lines = Array.from({ length: 5002 }, (_, i) => `1,${i},1,2,3,"Arial",12,1,w${i}`);
+ const csv = Buffer.from(['PageNo,XPos,YPos,XWidth,YWidth,FontName,FontSize,Length,Text', ...lines].join('\n'));
+ mockHttp(defaultRoutes([{ method: 'GET', match: (u) => u.includes('/v1/download/'), reply: () => ({ body: Readable.from([csv]) }) }]));
+ const out = await run(extractTextPdfAction)(fakeContext({ file: pdf, detailed: true }).context);
+ expect(out['detailed']).toHaveLength(5000);
+ expect(out['detailed_total_rows']).toBe(5002);
+ expect(out['detailed_truncated']).toBe(true);
+ });
+
+ it('extract text surfaces an unparseable detailed result', async () => {
+ mockHttp(defaultRoutes([{ method: 'GET', match: (u) => u.includes('/v1/download/'), reply: () => ({ body: Readable.from([Buffer.from('garbage line')]) }) }]));
+ const out = await run(extractTextPdfAction)(fakeContext({ file: pdf, detailed: true }).context);
+ expect(out['detailed']).toBeNull();
+ expect(out['detailed_parse_error']).toMatch(/unexpected header/);
+ });
+
+ it.each([
+ ['merge with one file', mergePdfAction, { files: [{ file: pdf }] }, /At least two/],
+ ['split bad ranges', splitPdfAction, { file: pdf, split_mode: 'ranges', ranges: '1-a' }, /must look like/],
+ ['split fixed range zero', splitPdfAction, { file: pdf, split_mode: 'fixed_range', fixed_range: 0 }, /whole number/],
+ ['ocr bad language', ocrPdfAction, { file: pdf, ocr_languages: ['english'] }, /ISO 639-2/],
+ ['resize without size', resizeImageAction, { file: png, resize_mode: 'pixels' }, /width, a height/],
+ ['upscale 3x', upscaleImageAction, { file: png, multiplier: 3 }, /2 or 4/],
+ ['empty file', compressPdfAction, { file: { base64: '', filename: 'x.pdf' } }, /empty/],
+ ['bad region', compressPdfAction, { file: pdf, region: 'mars' }, /Processing Region/],
+ ['html not http', htmlToPdfAction, { url: 'ftp://x' }, /http/],
+ ['webhook not https', compressPdfAction, { file: pdf, webhook_url: 'http://x.co/h' }, /Webhook URL must use https/],
+ ['watermark image size', watermarkImageAction, { file: png, image: png, width_percent: 0 }, /between 1 and 100/],
+ ])('%s fails before any request', async (_name, action, props, message) => {
+ const calls = mockHttp(defaultRoutes());
+ await expect(run(loose(action))(fakeContext(props).context)).rejects.toThrow(message);
+ expect(calls).toHaveLength(0);
+ });
+
+ it('watermark text mode ignores a leftover image', async () => {
+ const calls = mockHttp(defaultRoutes());
+ await run(loose(watermarkPdfAction))(fakeContext({ file: pdf, mode: 'text', text: 'x', image: png }).context);
+ expect(processBody(calls)['text']).toBe('x');
+ expect(processBody(calls)['image']).toBeUndefined();
+ expect(calls.filter((x) => x.url.includes('/upload'))).toHaveLength(1);
+ });
+
+ it('split ignores leftover inputs from other modes', async () => {
+ const calls = mockHttp(defaultRoutes());
+ await run(loose(splitPdfAction))(fakeContext({ file: pdf, split_mode: 'ranges', ranges: '1-2', fixed_range: 0, filesize: 0, remove_pages: 'x' }).context);
+ expect(processBody(calls)['ranges']).toBe('1-2');
+ expect(processBody(calls)['fixed_range']).toBeUndefined();
+ });
+
+ it('split by file size sends bytes', async () => {
+ const calls = mockHttp(defaultRoutes());
+ await run(splitPdfAction)(fakeContext({ file: pdf, split_mode: 'filesize', filesize: 2 }).context);
+ expect(processBody(calls)['filesize']).toBe(2 * 1024 * 1024);
+ });
+
+ it('refuses a start response that points to a foreign server', async () => {
+ const calls = mockHttp(
+ defaultRoutes([{ method: 'GET', match: (u) => u.includes('/v1/start/'), body: { server: `${SERVER}.evil.io`, task: 'T' } }])
+ );
+ await expect(run(compressPdfAction)(fakeContext({ file: pdf }).context)).rejects.toThrow(/unexpected server/);
+ expect(calls.some((x) => x.url.includes('evil'))).toBe(false);
+ });
+});
+
+describe('step time budget', () => {
+ it('fails a task that does not finish before the step limit', async () => {
+ vi.useFakeTimers();
+ try {
+ mockHttp(defaultRoutes());
+ const mocked = httpClient.sendRequest;
+ vi.spyOn(httpClient, 'sendRequest').mockImplementation((request, options) =>
+ request.url.endsWith('/v1/process') ? new Promise(() => undefined) : mocked(request, options)
+ );
+ const pending = run(compressPdfAction)(fakeContext({ file: pdf }).context);
+ const assertion = expect(pending).rejects.toThrow(/step time limit/);
+ await vi.advanceTimersByTimeAsync(520_000);
+ await assertion;
+ } finally {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ }
+ });
+
+ it('sends no further request after the step limit is hit', async () => {
+ mockHttp(defaultRoutes());
+ await run(mergePdfAction)(fakeContext({ files: [{ file: pdf }, { file: pdf }] }).context);
+ vi.restoreAllMocks();
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });
+ try {
+ const urls: string[] = [];
+ const reply = (body: unknown) => ({ status: 200, headers: {}, body });
+ vi.spyOn(httpClient, 'sendRequest').mockImplementation(async (request) => {
+ urls.push(request.url);
+ if (request.url.endsWith('/v1/auth')) return reply({ token: 'jwt-1' });
+ if (request.url.includes('/v1/start/')) return reply({ server: SERVER, task: 'TASK1' });
+ if (request.url.endsWith('/v1/upload')) {
+ await new Promise((resolve) => setTimeout(resolve, 530_000));
+ return reply({ server_filename: 'sf-1' });
+ }
+ return reply({});
+ });
+ const pending = run(mergePdfAction)(fakeContext({ files: [{ file: pdf }, { file: pdf }] }).context);
+ const assertion = expect(pending).rejects.toThrow(/step time limit/);
+ for (let i = 0; i < 1000 && !urls.some((url) => url.endsWith('/v1/upload')); i++) {
+ await new Promise((resolve) => setImmediate(resolve));
+ }
+ await vi.advanceTimersByTimeAsync(600_000);
+ await assertion;
+ for (let i = 0; i < 200; i++) {
+ await new Promise((resolve) => setImmediate(resolve));
+ await vi.advanceTimersByTimeAsync(1_000);
+ }
+ expect(urls.filter((url) => url.endsWith('/v1/upload'))).toHaveLength(1);
+ expect(urls.some((url) => url.endsWith('/v1/process') || url.includes('/v1/download/'))).toBe(false);
+ } finally {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ }
+ });
+});
+
+describe('fileToUploadInput', () => {
+ it('passes the file Buffer through without a base64 round trip', () => {
+ const data = Buffer.from('%PDF-1.7');
+ const out = fileToUploadInput({ file: { data, base64: 'ignored', filename: 'a.pdf' } });
+ expect(out).toEqual({ kind: 'file', file: { data, filename: 'a.pdf' } });
+ expect(out.kind === 'file' && out.file.data).toBe(data);
+ });
+ it('falls back to base64 when the file has no data', () => {
+ const out = fileToUploadInput({ file: { base64: Buffer.from('x').toString('base64') } });
+ expect(out).toEqual({ kind: 'file', file: { data: Buffer.from('x'), filename: 'file' } });
+ });
+ it('rejects an empty Buffer', () => {
+ expect(() => fileToUploadInput({ file: { data: Buffer.alloc(0), filename: 'a.pdf' }, label: 'PDF' })).toThrow(/PDF is empty/);
+ });
+});
diff --git a/packages/pieces/community/iloveapi/test/triggers.test.ts b/packages/pieces/community/iloveapi/test/triggers.test.ts
new file mode 100644
index 00000000000..72c4abcb998
--- /dev/null
+++ b/packages/pieces/community/iloveapi/test/triggers.test.ts
@@ -0,0 +1,93 @@
+import { describe, expect, it } from 'vitest';
+import { taskCompletedTrigger } from '../src/lib/triggers/task-completed';
+import { taskFailedTrigger } from '../src/lib/triggers/task-failed';
+import * as signatureTriggers from '../src/lib/triggers/signature-events';
+import * as samples from '../src/lib/triggers/sample-payloads';
+import { fakeContext, loose, record } from './helpers';
+import { claimDelivery } from '../src/lib/triggers/common';
+
+const SECRET = 'abcdefghijklmnop1234';
+
+function ctx({ body, secret = SECRET, given = SECRET, tools }: { body: unknown; secret?: string; given?: string; tools?: string[] }) {
+ const fake = fakeContext({ webhook_secret: secret, tools });
+ return { ...fake, context: { ...fake.context, payload: { body, headers: {}, queryParams: given === '' ? {} : { ap_secret: given } } } };
+}
+
+const triggers: Array<[string, { run: (c: never) => Promise<unknown[]>; outputSchema?: unknown; aiMetadata?: unknown }, unknown]> = [
+ ['task_completed', taskCompletedTrigger, samples.taskCompletedSample],
+ ['task_failed', taskFailedTrigger, samples.taskFailedSample],
+ ['signature_created', signatureTriggers.signatureCreatedTrigger, samples.signatureCreatedSample],
+ ['signature_sent', signatureTriggers.signatureSentTrigger, samples.signatureSentSample],
+ ['signature_completed', signatureTriggers.signatureCompletedTrigger, samples.signatureCompletedSample],
+ ['signature_declined', signatureTriggers.signatureDeclinedTrigger, samples.signatureDeclinedSample],
+ ['signature_expired', signatureTriggers.signatureExpiredTrigger, samples.signatureExpiredSample],
+ ['signature_voided', signatureTriggers.signatureVoidedTrigger, samples.signatureVoidedSample],
+ ['signer_viewed', signatureTriggers.signerViewedTrigger, samples.signerViewedSample],
+ ['signer_signed', signatureTriggers.signerSignedTrigger, samples.signerSignedSample],
+ ['signer_declined', signatureTriggers.signerDeclinedTrigger, samples.signerDeclinedSample],
+];
+
+describe.each(triggers)('%s', (_name, trigger, sample) => {
+ it('has outputSchema and aiMetadata', () => {
+ expect(trigger.outputSchema).toBeDefined();
+ expect(trigger.aiMetadata).toBeDefined();
+ });
+ it('fires once with the right secret and dedupes a retry', async () => {
+ const { context } = ctx({ body: sample });
+ const first = await trigger.run(loose(context));
+ expect(first).toHaveLength(1);
+ expect(first[0]).toMatchObject({ event: record(sample)['event'], _dedupe_key: expect.stringMatching(/^iloveapi:/) });
+ expect(await trigger.run(loose(context))).toHaveLength(0);
+ });
+ it('ignores a missing or wrong secret', async () => {
+ expect(await trigger.run(loose(ctx({ body: sample, given: '' }).context))).toHaveLength(0);
+ expect(await trigger.run(loose(ctx({ body: sample, given: 'wrong-secret-0000000' }).context))).toHaveLength(0);
+ });
+ it('ignores another event', async () => {
+ expect(await trigger.run(loose(ctx({ body: { event: 'other.event', data: {} } }).context))).toHaveLength(0);
+ });
+});
+
+describe('task triggers', () => {
+ it('apply the tool filter', async () => {
+ expect(await taskCompletedTrigger.run(loose(ctx({ body: samples.taskCompletedSample, tools: ['merge'] }).context))).toHaveLength(0);
+ expect(await taskCompletedTrigger.run(loose(ctx({ body: samples.taskCompletedSample, tools: ['compress'] }).context))).toHaveLength(1);
+ });
+ it('refuse a short secret', async () => {
+ await expect(taskCompletedTrigger.run(loose(ctx({ body: samples.taskCompletedSample, secret: 'short' }).context))).rejects.toThrow(/at least 16/);
+ });
+ it('keep dedupe state on disable so a retry after republish is still dropped', async () => {
+ const { context, store } = ctx({ body: samples.taskCompletedSample });
+ await taskCompletedTrigger.run(loose(context));
+ expect(store.size).toBe(1);
+ await taskCompletedTrigger.onDisable(loose(context));
+ expect(store.size).toBe(1);
+ expect(await taskCompletedTrigger.run(loose(context))).toHaveLength(0);
+ });
+});
+
+describe('claimDelivery', () => {
+ it('lets only the write that survived claim a delivery when two arrive together', async () => {
+ const data = new Map<string, unknown>();
+ let pending: Array<() => void> = [];
+ const store = {
+ get: async (key: string) => data.get(key) ?? null,
+ put: async (key: string, value: unknown) => {
+ await new Promise<void>((resolve) => pending.push(resolve));
+ data.set(key, value);
+ return value;
+ },
+ delete: async (key: string) => {
+ data.delete(key);
+ },
+ };
+ const first = claimDelivery({ store: loose(store), key: 'a' });
+ const second = claimDelivery({ store: loose(store), key: 'b' });
+ await new Promise((resolve) => setImmediate(resolve));
+ const release = pending;
+ pending = [];
+ release.forEach((resolve) => resolve());
+ const results = await Promise.all([first, second]);
+ expect(results.filter(Boolean)).toHaveLength(1);
+ });
+});
diff --git a/packages/pieces/community/iloveapi/vitest.config.ts b/packages/pieces/community/iloveapi/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/iloveapi/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'),
+ },
+ },
+})