AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(pdf-co): merge, split, compress, protect and convert PDFs, and save results as files (#16134)
Odai Ahmadbe1a0a7d6eb3
diff --git a/bun.lock b/bun.lockindex 497326d3fdb..04a04421b59 100644--- a/bun.lock+++ b/bun.lock@@ -6863,7 +6863,7 @@},"packages/pieces/community/pdf-co": {"name": "@activepieces/piece-pdf-co",- "version": "0.1.7",+ "version": "0.2.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -6872,6 +6872,7 @@},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/pdf4me": {diff --git a/packages/pieces/community/pdf-co/package.json b/packages/pieces/community/pdf-co/package.jsonindex 1afd9275015..691d45d65a3 100644--- a/packages/pieces/community/pdf-co/package.json+++ b/packages/pieces/community/pdf-co/package.json@@ -1,12 +1,13 @@{"name": "@activepieces/piece-pdf-co",- "version": "0.1.7",+ "version": "0.2.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"},"dependencies": {"@activepieces/pieces-common": "workspace:*",@@ -15,6 +16,7 @@"@activepieces/core-utils": "workspace:*"},"devDependencies": {- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"}}diff --git a/packages/pieces/community/pdf-co/src/i18n/translation.json b/packages/pieces/community/pdf-co/src/i18n/translation.jsonindex 3c295c2cbf7..8c59497f5bf 100644--- a/packages/pieces/community/pdf-co/src/i18n/translation.json+++ b/packages/pieces/community/pdf-co/src/i18n/translation.json@@ -1,22 +1,80 @@{"Automate PDF conversion, editing, extraction": "Automate PDF conversion, editing, extraction",- "To get your PDF.co API key please [click here to create your account](https://app.pdf.co/).": "To get your PDF.co API key please [click here to create your account](https://app.pdf.co/).",+ "To get your PDF.co API key:\n1. Sign in or create an account at [app.pdf.co](https://app.pdf.co/).\n2. Open **API** in the left menu.\n3. Copy the API key and paste it here.": "To get your PDF.co API key:\n1. Sign in or create an account at [app.pdf.co](https://app.pdf.co/).\n2. Open **API** in the left menu.\n3. Copy the API key and paste it here.","Add Barcode to PDF": "Add Barcode to PDF","Add Image to PDF": "Add Image to PDF","Add Text to PDF": "Add Text to PDF","Convert HTML to PDF": "Convert HTML to PDF",- "Convert PDF to JSON/CSV/XML": "Convert PDF to JSON/CSV/XML",+ "Convert PDF to JSON/CSV/XML/Excel/HTML": "Convert PDF to JSON/CSV/XML/Excel/HTML","Extract Tables from PDF (using Template)": "Extract Tables from PDF (using Template)","Extract Plain Text from PDF": "Extract Plain Text from PDF","Search and Replace Text in PDF": "Search and Replace Text in PDF",+ "Merge PDFs": "Merge PDFs",+ "Split PDF": "Split PDF",+ "Delete Pages from PDF": "Delete Pages from PDF",+ "Rotate PDF Pages": "Rotate PDF Pages",+ "Compress PDF": "Compress PDF",+ "Protect PDF with Password": "Protect PDF with Password",+ "Remove PDF Password": "Remove PDF Password",+ "Make PDF Searchable (OCR)": "Make PDF Searchable (OCR)",+ "Get PDF Info": "Get PDF Info",+ "Get PDF Form Fields": "Get PDF Form Fields",+ "Fill PDF Form": "Fill PDF Form",+ "Find Text in PDF": "Find Text in PDF",+ "Delete (Redact) Text in PDF": "Delete (Redact) Text in PDF",+ "Read Barcodes": "Read Barcodes",+ "Generate Barcode Image": "Generate Barcode Image",+ "Convert PDF to Images": "Convert PDF to Images",+ "Convert Web Page to PDF": "Convert Web Page to PDF",+ "Convert Document to PDF": "Convert Document to PDF",+ "Create PDF from HTML Template": "Create PDF from HTML Template",+ "List HTML Templates": "List HTML Templates",+ "Parse Document with Template": "Parse Document with Template",+ "List Document Parser Templates": "List Document Parser Templates",+ "Parse Invoice with AI": "Parse Invoice with AI",+ "Upload File to PDF.co": "Upload File to PDF.co",+ "Check Job Status": "Check Job Status",+ "Get Credit Balance": "Get Credit Balance",+ "Convert PDF (AI)": "Convert PDF (AI)",+ "Edit PDF (AI)": "Edit PDF (AI)",+ "Parse Document (AI)": "Parse Document (AI)","Generate a barcode image and add it to a specific location on a PDF.": "Generate a barcode image and add it to a specific location on a PDF.","Add image to a PDF document.": "Add image to a PDF document.","Adds text to PDF.": "Adds text to PDF.","Convert HTML code into a downloadable PDF document.": "Convert HTML code into a downloadable PDF document.",- "Convert PDF content into structured formats (JSON, CSV, or XML).": "Convert PDF content into structured formats (JSON, CSV, or XML).",+ "Convert PDF content into structured formats (JSON, CSV, XML, Excel or HTML).": "Convert PDF content into structured formats (JSON, CSV, XML, Excel or HTML).","Extracts table data from a PDF using a predefined PDF.co Document Parser template.": "Extracts table data from a PDF using a predefined PDF.co Document Parser template.","Extracts plain text content from a PDF document.": "Extracts plain text content from a PDF document.","Search for specific text or patterns in a PDF and replace it with new text.": "Search for specific text or patterns in a PDF and replace it with new text.",+ "Combine two or more PDFs into one PDF, in the order given.": "Combine two or more PDFs into one PDF, in the order given.",+ "Split a PDF into several PDFs by page ranges.": "Split a PDF into several PDFs by page ranges.",+ "Create a copy of a PDF without the pages you list.": "Create a copy of a PDF without the pages you list.",+ "Rotate all or some pages of a PDF by 90, 180 or 270 degrees.": "Rotate all or some pages of a PDF by 90, 180 or 270 degrees.",+ "Reduce the file size of a PDF.": "Reduce the file size of a PDF.",+ "Create a password-protected copy of a PDF and choose what readers may do.": "Create a password-protected copy of a PDF and choose what readers may do.",+ "Create an unprotected copy of a password-protected PDF.": "Create an unprotected copy of a password-protected PDF.",+ "Run OCR on a scanned PDF so its text can be selected and searched.": "Run OCR on a scanned PDF so its text can be selected and searched.",+ "Read a PDF's page count, metadata, page size and security settings.": "Read a PDF's page count, metadata, page size and security settings.",+ "List the fillable form fields of a PDF with their exact names.": "List the fillable form fields of a PDF with their exact names.",+ "Fill the form fields of a fillable PDF by field name.": "Fill the form fields of a fillable PDF by field name.",+ "Find every place a word, phrase or pattern appears in a PDF.": "Find every place a word, phrase or pattern appears in a PDF.",+ "Create a copy of a PDF with the given words or patterns removed.": "Create a copy of a PDF with the given words or patterns removed.",+ "Find and decode barcodes and QR codes in a PDF or image.": "Find and decode barcodes and QR codes in a PDF or image.",+ "Create a QR code or barcode image for a value.": "Create a QR code or barcode image for a value.",+ "Render PDF pages as JPG, PNG, WEBP or TIFF images.": "Render PDF pages as JPG, PNG, WEBP or TIFF images.",+ "Turn a public web page into a PDF.": "Turn a public web page into a PDF.",+ "Convert a Word document, spreadsheet or images to PDF.": "Convert a Word document, spreadsheet or images to PDF.",+ "Fill a saved PDF.co HTML template with your data and turn it into a PDF, e.g. an invoice.": "Fill a saved PDF.co HTML template with your data and turn it into a PDF, e.g. an invoice.",+ "List the HTML-to-PDF templates on your PDF.co account.": "List the HTML-to-PDF templates on your PDF.co account.",+ "Extract the fields and tables a Document Parser template defines from a PDF or scan.": "Extract the fields and tables a Document Parser template defines from a PDF or scan.",+ "List the Document Parser templates on your PDF.co account.": "List the Document Parser templates on your PDF.co account.",+ "Extract vendor, customer, totals, dates and line items from an invoice of any layout.": "Extract vendor, customer, totals, dates and line items from an invoice of any layout.",+ "Upload a file to PDF.co temporary storage and get a link other PDF.co actions can use.": "Upload a file to PDF.co temporary storage and get a link other PDF.co actions can use.",+ "Check a PDF.co background job and get its result link when it is done.": "Check a PDF.co background job and get its result link when it is done.",+ "Get the number of PDF.co credits left on the account.": "Get the number of PDF.co credits left on the account.",+ "Convert a PDF to text, CSV, JSON, XML or HTML and return the content directly.": "Convert a PDF to text, CSV, JSON, XML or HTML and return the content directly.",+ "Add texts, images and form-field values to a PDF in one call.": "Add texts, images and form-field values to a PDF in one call.",+ "Extract fields and tables from a PDF with a Document Parser template ID.": "Extract fields and tables from a PDF with a Document Parser template ID.","Source PDF URL": "Source PDF URL","Barcode Value": "Barcode Value","Barcode Type": "Barcode Type",@@ -30,6 +88,7 @@"Source PDF Password": "Source PDF Password","HTTP Username": "HTTP Username","HTTP Password": "HTTP Password",+ "Save Result as File": "Save Result as File","Image URL": "Image URL","Width": "Width","Height": "Height",@@ -56,14 +115,70 @@"Do not wait till full page load ?": "Do not wait till full page load ?","Output Link Expiration (minutes)": "Output Link Expiration (minutes)","Profiles": "Profiles",+ "Custom Paper Size": "Custom Paper Size","Output Format": "Output Format","OCR Language": "OCR Language","Template ID": "Template ID",+ "Use OCR (Scanned PDFs)": "Use OCR (Scanned PDFs)","PDF URL": "PDF URL","Text to Locate": "Text to Locate","Replacement Text": "Replacement Text","Case Sensitive": "Case Sensitive","Use Regular Expressions ?": "Use Regular Expressions ?",+ "Max Replacements per Text": "Max Replacements per Text",+ "PDF URLs": "PDF URLs",+ "PDF Files": "PDF Files",+ "Link Expiration (minutes)": "Link Expiration (minutes)",+ "Run in Background": "Run in Background",+ "Source File URL": "Source File URL",+ "Source File": "Source File",+ "Page Ranges": "Page Ranges",+ "Pages to Delete": "Pages to Delete",+ "Angle": "Angle",+ "Compression Level": "Compression Level",+ "Image Quality (1-100)": "Image Quality (1-100)",+ "Owner Password": "Owner Password",+ "Open Password": "Open Password",+ "Encryption": "Encryption",+ "Markdown": "Markdown",+ "Allow Printing": "Allow Printing",+ "Allow Copying Content": "Allow Copying Content",+ "Allow Editing": "Allow Editing",+ "Allow Filling Forms": "Allow Filling Forms",+ "Allow Annotations": "Allow Annotations",+ "Allow Assembling Pages": "Allow Assembling Pages",+ "Allow Accessibility Tools": "Allow Accessibility Tools",+ "PDF Password": "PDF Password",+ "Fields": "Fields",+ "Flatten Form": "Flatten Form",+ "Text to Find": "Text to Find",+ "Use Regular Expression": "Use Regular Expression",+ "Word Matching": "Word Matching",+ "Text to Remove": "Text to Remove",+ "Use Regular Expressions": "Use Regular Expressions",+ "Max Matches per Text": "Max Matches per Text",+ "Barcode Types": "Barcode Types",+ "Value": "Value",+ "Logo URL": "Logo URL",+ "Image Format": "Image Format",+ "Web Page URL": "Web Page URL",+ "Print Background": "Print Background",+ "Render Wait (ms)": "Render Wait (ms)",+ "Source Type": "Source Type",+ "More Image URLs": "More Image URLs",+ "Template": "Template",+ "Template Data": "Template Data",+ "Custom Fields": "Custom Fields",+ "Line Item Structure": "Line Item Structure",+ "Job ID": "Job ID",+ "File": "File",+ "Source URL": "Source URL",+ "Format": "Format",+ "Max Characters": "Max Characters",+ "Text Annotations": "Text Annotations",+ "Images": "Images",+ "Form Fields": "Form Fields",+ "Output Name": "Output Name","URL of the PDF file to add the barcode to.": "URL of the PDF file to add the barcode to.","The text or data to encode in the barcode.": "The text or data to encode in the barcode.","Select the type of barcode to generate.": "Select the type of barcode to generate.",@@ -71,21 +186,22 @@"Y coordinate (from top-left corner) to place the barcode.": "Y coordinate (from top-left corner) to place the barcode.","Optional width for the barcode image on the PDF (in points). Aspect ratio is kept by default.": "Optional width for the barcode image on the PDF (in points). Aspect ratio is kept by default.","Optional height for the barcode image on the PDF (in points). Aspect ratio is kept by default.": "Optional height for the barcode image on the PDF (in points). Aspect ratio is kept by default.",- "Comma-separated page numbers or ranges to add the barcode (e.g., \"0,2,5-10\"). Leave empty for all pages.": "Comma-separated page numbers or ranges to add the barcode (e.g., \"0,2,5-10\"). Leave empty for all pages.",+ "Comma-separated page indexes or ranges to add the barcode (first page is 0), e.g. \"0,2,5-10\". Leave empty for all pages.": "Comma-separated page indexes or ranges to add the barcode (first page is 0), e.g. \"0,2,5-10\". Leave empty for all pages.","Desired name for the output PDF file (e.g., \"result.pdf\").": "Desired name for the output PDF file (e.g., \"result.pdf\").","Set the expiration time for the output link in minutes (default is 60 i.e 60 minutes or 1 hour).": "Set the expiration time for the output link in minutes (default is 60 i.e 60 minutes or 1 hour).","Password if the source PDF is protected.": "Password if the source PDF is protected.","HTTP auth username if required to access source url.": "HTTP auth username if required to access source url.","HTTP auth password if required to access source url.": "HTTP auth password if required to access source url.",+ "Download the result and keep it as a file in this flow, so later steps can use it after the PDF.co link expires (links last 60 minutes by default). Files over 100 MB are not saved; the link is still returned.": "Download the result and keep it as a file in this flow, so later steps can use it after the PDF.co link expires (links last 60 minutes by default). Files over 100 MB are not saved; the link is still returned.","URL of the PDF file to modify.": "URL of the PDF file to modify.","X coordinate (from top-left corner) to place the image.": "X coordinate (from top-left corner) to place the image.","Y coordinate (from top-left corner) to place the image.": "Y coordinate (from top-left corner) to place the image.","Optional width for the image on the PDF (in points). Aspect ratio is kept by default.": "Optional width for the image on the PDF (in points). Aspect ratio is kept by default.","Optional height for the image on the PDF (in points). Aspect ratio is kept by default.": "Optional height for the image on the PDF (in points). Aspect ratio is kept by default.",- "Specify page indices as comma-separated values or ranges to process (e.g. \"0, 1, 2-\" or \"1, 2, 3-7\").": "Specify page indices as comma-separated values or ranges to process (e.g. \"0, 1, 2-\" or \"1, 2, 3-7\").",+ "Page indexes as comma-separated values or ranges (first page is 0), e.g. \"0, 1, 2-\" or \"1, 2, 3-7\".": "Page indexes as comma-separated values or ranges (first page is 0), e.g. \"0, 1, 2-\" or \"1, 2, 3-7\".","The HTML code to convert to PDF.": "The HTML code to convert to PDF.","CSS style margins (e.g., \"10px\", \"5mm 5mm 5mm 5mm\" for top, right, bottom, left).": "CSS style margins (e.g., \"10px\", \"5mm 5mm 5mm 5mm\" for top, right, bottom, left).",- "Select a paper size. For custom sizes, input the value directly (e.g., '200mm 300mm') if your desired size isn't listed. Refer to PDF.co docs.": "Select a paper size. For custom sizes, input the value directly (e.g., '200mm 300mm') if your desired size isn't listed. Refer to PDF.co docs.",+ "Select a standard paper size. For another size, fill Custom Paper Size below.": "Select a standard paper size. For another size, fill Custom Paper Size below.","Set page orientation.": "Set page orientation.","Set to true to print background graphics and colors (default is true).": "Set to true to print background graphics and colors (default is true).","CSS media type to emulate.": "CSS media type to emulate.",@@ -93,17 +209,84 @@"HTML content for the page footer.": "HTML content for the page footer.","Set the expiration time for the output link in minutes (default is 60).": "Set the expiration time for the output link in minutes (default is 60).","JSON object for additional configurations.": "JSON object for additional configurations.",+ "Width and height with units, e.g. \"200mm 300mm\" or \"8.5in 11in\". Overrides Paper Size when set.": "Width and height with units, e.g. \"200mm 300mm\" or \"8.5in 11in\". Overrides Paper Size when set.","URL of the PDF file to convert.": "URL of the PDF file to convert.","Select the desired structured output format.": "Select the desired structured output format.",- "Comma-separated page numbers or ranges (e.g., \"0,2,5-10\"). Leave empty for all pages.": "Comma-separated page numbers or ranges (e.g., \"0,2,5-10\"). Leave empty for all pages.",+ "Comma-separated page indexes or ranges (first page is 0), e.g. \"0,2,5-10\". Leave empty for all pages.": "Comma-separated page indexes or ranges (first page is 0), e.g. \"0,2,5-10\". Leave empty for all pages.","Language for OCR if processing scanned documents (e.g., \"eng\", \"deu\", \"eng+deu\"). See PDF.co docs for list.": "Language for OCR if processing scanned documents (e.g., \"eng\", \"deu\", \"eng+deu\"). See PDF.co docs for list.","URL of the PDF file to extract tables from.": "URL of the PDF file to extract tables from.","The ID of your Document Parser template (created in PDF.co dashboard) designed to extract the table(s).": "The ID of your Document Parser template (created in PDF.co dashboard) designed to extract the table(s).",- "Comma-separated page numbers or ranges (e.g., \"0,2,5-10\"). Overrides template settings if provided.": "Comma-separated page numbers or ranges (e.g., \"0,2,5-10\"). Overrides template settings if provided.",+ "Comma-separated page indexes or ranges (first page is 0), e.g. \"0,2,5-10\". Overrides template settings if provided.": "Comma-separated page indexes or ranges (first page is 0), e.g. \"0,2,5-10\". Overrides template settings if provided.","URL of the PDF file to extract text from.": "URL of the PDF file to extract text from.",+ "Read scanned pages and keep the layout. Costs 21 credits per page instead of 4.": "Read scanned pages and keep the layout. Costs 21 credits per page instead of 4.",+ "Only with OCR: language of the text, e.g. \"eng\", \"deu\", or \"eng+deu\". Default \"eng\".": "Only with OCR: language of the text, e.g. \"eng\", \"deu\", or \"eng+deu\". Default \"eng\".","URL to the source PDF file.": "URL to the source PDF file.",+ "Texts to find. Each one is replaced by the Replacement Text in the same position.": "Texts to find. Each one is replaced by the Replacement Text in the same position.",+ "One replacement per Text to Locate, in the same order.": "One replacement per Text to Locate, in the same order.","Set to true for case-sensitive search, false otherwise.": "Set to true for case-sensitive search, false otherwise.","Set to true to use regular expressions for search texts.": "Set to true to use regular expressions for search texts.",+ "Maximum replacements for each text. Leave empty or 0 to replace every match.": "Maximum replacements for each text. Leave empty or 0 to replace every match.",+ "Public links to the PDFs, in merge order. These come before any files below.": "Public links to the PDFs, in merge order. These come before any files below.",+ "PDFs from earlier steps, merged after the URLs. Each file is uploaded to PDF.co first (7 credits each).": "PDFs from earlier steps, merged after the URLs. Each file is uploaded to PDF.co first (7 credits each).",+ "Username if the source URL needs HTTP basic auth.": "Username if the source URL needs HTTP basic auth.",+ "Password if the source URL needs HTTP basic auth.": "Password if the source URL needs HTTP basic auth.",+ "Name for the result file, e.g. \"result.pdf\". Leave empty to let PDF.co pick one.": "Name for the result file, e.g. \"result.pdf\". Leave empty to let PDF.co pick one.",+ "How long the PDF.co result link stays valid. Default 60. The maximum depends on your PDF.co plan.": "How long the PDF.co result link stays valid. Default 60. The maximum depends on your PDF.co plan.",+ "For large files. PDF.co processes the job in the background and this step checks it for up to 4 minutes (each check costs 2 credits). If it is still running, the step returns the job ID; use Check Job Status later.": "For large files. PDF.co processes the job in the background and this step checks it for up to 4 minutes (each check costs 2 credits). If it is still running, the step returns the job ID; use Check Job Status later.",+ "Public link to the file (for example a PDF on Google Drive, Dropbox or S3). Fill this or pick a file below, not both.": "Public link to the file (for example a PDF on Google Drive, Dropbox or S3). Fill this or pick a file below, not both.",+ "A file from an earlier step. It is uploaded to PDF.co temporary storage first (7 extra credits). Fill this or the URL above, not both.": "A file from an earlier step. It is uploaded to PDF.co temporary storage first (7 extra credits). Fill this or the URL above, not both.",+ "Comma-separated ranges, one output file per range. The first page is 1 (not 0). Example: \"1-2,3-\" gives pages 1-2 and page 3 to the end. Use \"*\" for one file per page.": "Comma-separated ranges, one output file per range. The first page is 1 (not 0). Example: \"1-2,3-\" gives pages 1-2 and page 3 to the end. Use \"*\" for one file per page.",+ "Pages to remove, comma-separated. The first page is 1 (not 0). Example: \"1,3-4\" or \"5-\" for page 5 to the end.": "Pages to remove, comma-separated. The first page is 1 (not 0). Example: \"1,3-4\" or \"5-\" for page 5 to the end.",+ "How far to rotate the pages clockwise.": "How far to rotate the pages clockwise.",+ "Comma-separated pages or ranges, e.g. \"0,2,5-10\" or \"3-\" (first page is 0). Use \"!0\" for the last page. Leave empty for all pages.": "Comma-separated pages or ranges, e.g. \"0,2,5-10\" or \"3-\" (first page is 0). Use \"!0\" for the last page. Leave empty for all pages.",+ "Stronger levels make smaller files with lower image quality.": "Stronger levels make smaller files with lower image quality.",+ "JPEG quality for color and grayscale images. Lower is smaller. Leave empty for the preset default.": "JPEG quality for color and grayscale images. Lower is smaller. Leave empty for the preset default.",+ "Password to open the source PDF, if it is protected.": "Password to open the source PDF, if it is protected.",+ "Password that allows changing the security settings.": "Password that allows changing the security settings.",+ "Password readers need to open the PDF. Leave empty to let anyone open it with the permissions below.": "Password readers need to open the PDF. Leave empty to let anyone open it with the permissions below.",+ "Permissions are off by default, as in PDF.co. Turn on what readers of the protected PDF may do.": "Permissions are off by default, as in PDF.co. Turn on what readers of the protected PDF may do.",+ "The owner or open password of the PDF.": "The owner or open password of the PDF.",+ "Language of the text, e.g. \"eng\", \"deu\", or \"eng+deu\" for several. Default \"eng\".": "Language of the text, e.g. \"eng\", \"deu\", or \"eng+deu\" for several. Default \"eng\".",+ "One entry per form field. Use Get PDF Form Fields to see the exact names.": "One entry per form field. Use Get PDF Form Fields to see the exact names.",+ "Make the filled form read-only so values can no longer be changed.": "Make the filled form read-only so values can no longer be changed.",+ "The word or phrase to look for, or a regular expression when \"Use Regular Expression\" is on.": "The word or phrase to look for, or a regular expression when \"Use Regular Expression\" is on.",+ "Smart Match (default) matches whole words flexibly; Exact Match needs the exact word; None matches any part of the text.": "Smart Match (default) matches whole words flexibly; Exact Match needs the exact word; None matches any part of the text.",+ "Words, phrases or (with Regular Expressions on) patterns to delete.": "Words, phrases or (with Regular Expressions on) patterns to delete.",+ "Maximum matches to remove for each text. Leave empty or 0 to remove every match.": "Maximum matches to remove for each text. Leave empty or 0 to remove every match.",+ "Public link to the PDF or image. Fill this or pick a file below, not both.": "Public link to the PDF or image. Fill this or pick a file below, not both.",+ "Which barcode types to look for. Fewer types read faster.": "Which barcode types to look for. Fewer types read faster.",+ "The text, number or link to encode.": "The text, number or link to encode.",+ "QR codes only: public link to a small logo placed in the middle.": "QR codes only: public link to a small logo placed in the middle.",+ "The public page to convert, e.g. https://example.com/report.": "The public page to convert, e.g. https://example.com/report.",+ "Standard paper size. For a custom size use Custom Paper Size instead.": "Standard paper size. For a custom size use Custom Paper Size instead.",+ "CSS-style margins: one value for all sides or \"top right bottom left\", e.g. \"10mm\" or \"5mm 5mm 5mm 5mm\".": "CSS-style margins: one value for all sides or \"top right bottom left\", e.g. \"10mm\" or \"5mm 5mm 5mm 5mm\".",+ "Include background colors and images.": "Include background colors and images.",+ "HTML shown at the top of every page.": "HTML shown at the top of every page.",+ "HTML shown at the bottom of every page.": "HTML shown at the bottom of every page.",+ "Extra time to let heavy JavaScript pages finish rendering, in milliseconds.": "Extra time to let heavy JavaScript pages finish rendering, in milliseconds.",+ "Images only: more public image links, added as further pages after the first image.": "Images only: more public image links, added as further pages after the first image.",+ "An HTML template from PDF.co (app.pdf.co > HTML to PDF Templates). Loading this list costs 2 credits.": "An HTML template from PDF.co (app.pdf.co > HTML to PDF Templates). Loading this list costs 2 credits.",+ "JSON object with the values for the template macros, e.g. {\"invoice_id\":\"123\",\"paid\":true}.": "JSON object with the values for the template macros, e.g. {\"invoice_id\":\"123\",\"paid\":true}.",+ "A Document Parser template from PDF.co (app.pdf.co > Document Parser). Loading this list costs 2 credits.": "A Document Parser template from PDF.co (app.pdf.co > Document Parser). Loading this list costs 2 credits.",+ "Public link to the invoice PDF (one invoice per file). Fill this or pick a file below, not both.": "Public link to the invoice PDF (one invoice per file). Fill this or pick a file below, not both.",+ "Extra fields to extract, in camelCase, e.g. storeNumber, deliveryDate.": "Extra fields to extract, in camelCase, e.g. storeNumber, deliveryDate.",+ "Optional shape for each line item: field name to \"string\" or \"number\", e.g. {\"description\":\"string\",\"quantity\":\"number\"}.": "Optional shape for each line item: field name to \"string\" or \"number\", e.g. {\"description\":\"string\",\"quantity\":\"number\"}.",+ "To read an invoice job that returned status \"working\", paste its Job ID. The source and fields above are then not used and no new parse is started.": "To read an invoice job that returned status \"working\", paste its Job ID. The source and fields above are then not used and no new parse is started.",+ "The file to upload, for example a PDF from an earlier step.": "The file to upload, for example a PDF from an earlier step.",+ "The Job ID returned by an earlier PDF.co step that ran in the background.": "The Job ID returned by an earlier PDF.co step that ran in the background.",+ "Public http(s) URL of the PDF.": "Public http(s) URL of the PDF.",+ "One of: text, text_ocr, csv, json, xml, html. Default text.": "One of: text, text_ocr, csv, json, xml, html. Default text.",+ "Optional 0-based pages or ranges, e.g. \"0,2-4\". Empty = all pages.": "Optional 0-based pages or ranges, e.g. \"0,2-4\". Empty = all pages.",+ "Optional OCR language for text_ocr, csv, json, xml and html, e.g. \"eng\" or \"eng+deu\".": "Optional OCR language for text_ocr, csv, json, xml and html, e.g. \"eng\" or \"eng+deu\".",+ "Optional password if the PDF is protected.": "Optional password if the PDF is protected.",+ "Maximum characters of content to return (default 50000, max 200000).": "Maximum characters of content to return (default 50000, max 200000).",+ "Optional JSON array of {text, x, y, pages?, size?, fontName?, color?, fontBold?, alignment?, width?, height?}.": "Optional JSON array of {text, x, y, pages?, size?, fontName?, color?, fontBold?, alignment?, width?, height?}.",+ "Optional JSON array of {url, x, y, pages?, width?, height?, link?, keepAspectRatio?}; url must be a public image link.": "Optional JSON array of {url, x, y, pages?, width?, height?, link?, keepAspectRatio?}; url must be a public image link.",+ "Optional JSON array of {fieldName, text, pages?} to fill existing form fields by exact name.": "Optional JSON array of {fieldName, text, pages?} to fill existing form fields by exact name.",+ "Optional name for the result file.": "Optional name for the result file.",+ "Public http(s) URL of the PDF or image.": "Public http(s) URL of the PDF or image.",+ "Numeric Document Parser template ID, e.g. \"1\".": "Numeric Document Parser template ID, e.g. \"1\".",+ "Optional 0-based pages or ranges, e.g. \"0,2-4\".": "Optional 0-based pages or ranges, e.g. \"0,2-4\".","QR Code (Default)": "QR Code (Default)","DataMatrix": "DataMatrix","Code 128": "Code 128",@@ -132,5 +315,33 @@"none": "none","JSON": "JSON","CSV": "CSV",- "XML": "XML"+ "XML": "XML",+ "Excel (XLSX)": "Excel (XLSX)",+ "Excel 97-2003 (XLS)": "Excel 97-2003 (XLS)",+ "HTML": "HTML",+ "90 degrees": "90 degrees",+ "180 degrees": "180 degrees",+ "270 degrees": "270 degrees",+ "Low (best quality)": "Low (best quality)",+ "Medium (default)": "Medium (default)",+ "High": "High",+ "Aggressive (smallest file)": "Aggressive (smallest file)",+ "AES 128-bit (default)": "AES 128-bit (default)",+ "AES 256-bit": "AES 256-bit",+ "RC4 40-bit (legacy)": "RC4 40-bit (legacy)",+ "RC4 128-bit (legacy)": "RC4 128-bit (legacy)",+ "Smart Match (default)": "Smart Match (default)",+ "Exact Match": "Exact Match",+ "None (substring)": "None (substring)",+ "QR Code": "QR Code",+ "Interleaved 2 of 5": "Interleaved 2 of 5",+ "JPG": "JPG",+ "PNG": "PNG",+ "WEBP": "WEBP",+ "TIFF (one multi-page file)": "TIFF (one multi-page file)",+ "A4 (default)": "A4 (default)",+ "Portrait (default)": "Portrait (default)",+ "Document (DOC, DOCX, RTF, TXT, XPS)": "Document (DOC, DOCX, RTF, TXT, XPS)",+ "Spreadsheet (CSV, XLS, XLSX)": "Spreadsheet (CSV, XLS, XLSX)",+ "Images (JPG, PNG, TIFF...)": "Images (JPG, PNG, TIFF...)"}\ No newline at end of filediff --git a/packages/pieces/community/pdf-co/src/index.ts b/packages/pieces/community/pdf-co/src/index.tsindex e11a0ba6266..086c23baa42 100644--- a/packages/pieces/community/pdf-co/src/index.ts+++ b/packages/pieces/community/pdf-co/src/index.ts@@ -1,15 +1,43 @@-import { PieceAuth, createPiece } from '@activepieces/pieces-framework';+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';import {- searchAndReplaceText,- addTextToPdf,+ addBarcodeToPdf,addImageToPdf,+ addPasswordToPdf,+ addTextToPdf,+ checkJobStatus,+ compressPdf,+ convertDocumentToPdf,+ convertHtmlTemplateToPdf,convertHtmlToPdf,- extractTextFromPdf,+ convertPdfToImage,convertPdfToStructuredFormat,+ convertUrlToPdf,+ deletePdfPages,+ deleteTextFromPdf,extractTablesFromPdf,- addBarcodeToPdf,+ extractTextFromPdf,+ fillPdfForm,+ findTextInPdf,+ generateBarcode,+ getCreditBalance,+ getPdfFormFields,+ getPdfInfo,+ listDocumentParserTemplates,+ listHtmlTemplates,+ makePdfSearchable,+ mergePdfs,+ parseDocument,+ parseInvoiceWithAi,+ pdfCoConvertPdf,+ pdfCoEditPdf,+ pdfCoParseDocument,+ readBarcodes,+ removePasswordFromPdf,+ rotatePdfPages,+ searchAndReplaceText,+ splitPdf,+ uploadFile,} from './lib/actions';-import { PieceCategory } from '@activepieces/pieces-framework';import { pdfCoAuth } from './lib/auth';export const pdfCo = createPiece({@@ -18,6 +46,7 @@ export const pdfCo = createPiece({categories: [PieceCategory.PRODUCTIVITY, PieceCategory.CONTENT_AND_FILES],logoUrl: 'https://cdn.activepieces.com/pieces/pdf-co.png',auth: pdfCoAuth,+ minimumSupportedRelease: '0.88.2',authors: ['onyedikachi-david', 'kishanprmr'],actions: [addBarcodeToPdf,@@ -28,6 +57,35 @@ export const pdfCo = createPiece({extractTablesFromPdf,extractTextFromPdf,searchAndReplaceText,+ mergePdfs,+ splitPdf,+ deletePdfPages,+ rotatePdfPages,+ compressPdf,+ addPasswordToPdf,+ removePasswordFromPdf,+ makePdfSearchable,+ getPdfInfo,+ getPdfFormFields,+ fillPdfForm,+ findTextInPdf,+ deleteTextFromPdf,+ readBarcodes,+ generateBarcode,+ convertPdfToImage,+ convertUrlToPdf,+ convertDocumentToPdf,+ convertHtmlTemplateToPdf,+ listHtmlTemplates,+ parseDocument,+ listDocumentParserTemplates,+ parseInvoiceWithAi,+ uploadFile,+ checkJobStatus,+ getCreditBalance,+ pdfCoConvertPdf,+ pdfCoEditPdf,+ pdfCoParseDocument,],triggers: [],});diff --git a/packages/pieces/community/pdf-co/src/lib/actions/add-barcode-to-pdf.ts b/packages/pieces/community/pdf-co/src/lib/actions/add-barcode-to-pdf.tsindex 2be222e18a2..077f0c4298d 100644--- a/packages/pieces/community/pdf-co/src/lib/actions/add-barcode-to-pdf.ts+++ b/packages/pieces/community/pdf-co/src/lib/actions/add-barcode-to-pdf.ts@@ -1,46 +1,10 @@-import { Property, DropdownOption, createAction } from '@activepieces/pieces-framework';-import { httpClient, HttpMethod, HttpError } from '@activepieces/pieces-common';-import {- PdfCoSuccessResponse,- PdfCoErrorResponse,- PdfCoImageAnnotation,- PdfCoAddImagesRequestBody,-} from '../common/types';+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';import { pdfCoAuth } from '../auth';-import { BASE_URL, commonProps } from '../common/props';--// Interface for /barcode/generate request-interface BarcodeGenerateRequestBody {- value: string;- type?: string;- async: boolean;- inline: boolean; // Must be false to get URL- name?: string;- decorationImage?: string;- profiles?: Record<string, unknown>;-}--// Interface for /barcode/generate success response (when inline=false)-interface BarcodeGenerateSuccessResponse {- url: string; // URL to the generated barcode image- error: false;- status: number;- name: string;- duration: number;- remainingCredits: number;- credits: number;-}--// Supported Barcode Types-const barcodeTypes: DropdownOption<string>[] = [- { label: 'QR Code (Default)', value: 'QRCode' },- { label: 'DataMatrix', value: 'DataMatrix' },- { label: 'Code 128', value: 'Code128' },- { label: 'Code 39', value: 'Code39' },- { label: 'PDF417', value: 'PDF417' },- { label: 'EAN-13', value: 'EAN13' },- { label: 'UPC-A', value: 'UPCA' },-];+import { pdfCoClient } from '../common/client';+import { pdfCoJobs } from '../common/jobs';+import { BARCODE_TYPES, commonProps, PDF_CO_DEFAULTS, pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';export const addBarcodeToPdf = createAction({name: 'add_barcode_to_pdf',@@ -50,10 +14,11 @@ export const addBarcodeToPdf = createAction({audience: 'both',aiMetadata: {description:- 'Generates a barcode (QR, DataMatrix, Code 128/39, PDF417, EAN-13, or UPC-A) and stamps it onto a source PDF (referenced by URL) at the given x/y coordinates. Use when an agent needs to embed a scannable code into an existing document. Each call produces a new output PDF file and consumes credits, so it is not idempotent.',+ 'Generates a barcode (QR, DataMatrix, Code 128/39, PDF417, EAN-13, or UPC-A) and stamps it onto a source PDF (referenced by URL) at the given x/y coordinates (points from the top-left; page indexes start at 0). Use when an agent needs to embed a scannable code into an existing document. Each call produces a new output PDF file and consumes credits, so it is not idempotent.',idempotent: false,},auth: pdfCoAuth,+ outputSchema: pdfCoOutputSchemas.rawResult,props: {sourcePdfUrl: Property.ShortText({displayName: 'Source PDF URL',@@ -69,7 +34,7 @@ export const addBarcodeToPdf = createAction({displayName: 'Barcode Type',description: 'Select the type of barcode to generate.',required: true,- options: { disabled: false, options: barcodeTypes, placeholder: 'Select Barcode Type' },+ options: { disabled: false, options: BARCODE_TYPES, placeholder: 'Select Barcode Type' },}),x: Property.Number({displayName: 'X Coordinate',@@ -96,135 +61,59 @@ export const addBarcodeToPdf = createAction({pages: Property.ShortText({displayName: 'Pages',description:- 'Comma-separated page numbers or ranges to add the barcode (e.g., "0,2,5-10"). Leave empty for all pages.',+ 'Comma-separated page indexes or ranges to add the barcode (first page is 0), e.g. "0,2,5-10". Leave empty for all pages.',required: false,}),...commonProps,+ saveOutputFile: pdfCoProps.saveOutputFile({ defaultValue: PDF_CO_DEFAULTS.saveOutputFileOnExistingActions }),},- async run(context) {- const { auth, propsValue } = context;- const {- sourcePdfUrl,- barcodeValue,- barcodeType,- x,- y,- width,- height,- pages,- fileName,- pdfPassword,- httpPassword,- httpUsername,- expiration,- } = propsValue;-- let barcodeImageUrl = '';-- // --- Step 1: Generate Barcode ---- const generateBarcodeBody: BarcodeGenerateRequestBody = {- value: barcodeValue,- type: barcodeType,- async: false,- inline: false, // Need the URL- };-- try {- const generateResponse = await httpClient.sendRequest<- BarcodeGenerateSuccessResponse | PdfCoErrorResponse- >({+ async run({ auth, propsValue, files }) {+ const apiKey = pdfCoClient.apiKeyOf(auth);+ const generated = pdfCoClient.readRecord(+ await pdfCoClient.request<unknown>({+ apiKey,method: HttpMethod.POST,- url: `${BASE_URL}/barcode/generate`,- headers: {- 'x-api-key': auth.secret_text,- 'Content-Type': 'application/json',- },- body: generateBarcodeBody,- });-- if (generateResponse.body.error) {- const errorBody = generateResponse.body as PdfCoErrorResponse;- throw new Error(- `PDF.co Barcode Generation Error: Status ${errorBody.status}. ${- errorBody.message || 'Unknown error.'- }`,- );- }-- barcodeImageUrl = (generateResponse.body as BarcodeGenerateSuccessResponse).url;- if (!barcodeImageUrl) {- throw new Error('Failed to get barcode image URL from PDF.co response.');- }- } catch (error) {- if (error instanceof HttpError) {- const responseBody = error.response?.body as PdfCoErrorResponse | undefined;- throw new Error(- `HTTP Error generating barcode: ${error.message}. ${- responseBody?.message- ? 'Server message: ' + responseBody.message- : 'Raw response: ' + JSON.stringify(responseBody)- }`,- );- }- throw error; // Re-throw other errors+ path: '/v1/barcode/generate',+ body: { value: propsValue.barcodeValue, type: propsValue.barcodeType, async: false, inline: false },+ }),+ );+ const barcodeImageUrl = generated['url'];+ if (typeof barcodeImageUrl !== 'string' || barcodeImageUrl === '') {+ throw new Error('Failed to get barcode image URL from PDF.co response.');}-- // --- Step 2: Add Barcode Image to PDF ---- const imageAnnotation: PdfCoImageAnnotation = {- url: barcodeImageUrl,- x: x,- y: y,- width,- height,- pages,- };-- const addImageBody: PdfCoAddImagesRequestBody = {- url: sourcePdfUrl,- images: [imageAnnotation],- async: false,- inline: false, // Get final PDF URL- name: fileName,- expiration,- httppassword: httpPassword,- httpusername: httpUsername,- password: pdfPassword,- };-- try {- const addResponse = await httpClient.sendRequest<PdfCoSuccessResponse | PdfCoErrorResponse>({+ const result = pdfCoClient.readRecord(+ await pdfCoClient.request<unknown>({+ apiKey,method: HttpMethod.POST,- url: `${BASE_URL}/pdf/edit/add`,- headers: {- 'x-api-key': auth.secret_text,- 'Content-Type': 'application/json',+ path: '/v1/pdf/edit/add',+ body: {+ url: propsValue.sourcePdfUrl,+ images: [+ {+ url: barcodeImageUrl,+ x: propsValue.x,+ y: propsValue.y,+ width: propsValue.width,+ height: propsValue.height,+ pages: propsValue.pages,+ },+ ],+ async: false,+ inline: false,+ name: propsValue.fileName,+ expiration: propsValue.expiration,+ httppassword: propsValue.httpPassword,+ httpusername: propsValue.httpUsername,+ password: propsValue.pdfPassword,},- body: addImageBody,- });-- if (addResponse.body.error) {- const errorBody = addResponse.body as PdfCoErrorResponse;- throw new Error(- `PDF.co Add Image Error: Status ${errorBody.status}. ${- errorBody.message || 'Unknown error.'- }`,- );- }-- // Return the successful response containing the final PDF URL- return addResponse.body as PdfCoSuccessResponse;- } catch (error) {- if (error instanceof HttpError) {- const responseBody = error.response?.body as PdfCoErrorResponse | undefined;- throw new Error(- `HTTP Error adding barcode image to PDF: ${error.message}. ${- responseBody?.message- ? 'Server message: ' + responseBody.message- : 'Raw response: ' + JSON.stringify(responseBody)- }`,- );- }- throw error; // Re-throw other errors- }+ }),+ );+ const saved = await pdfCoJobs.optionalSave({+ files,+ url: result['url'],+ enabled: propsValue.saveOutputFile,+ fileName: propsValue.fileName,+ });+ return { ...result, ...saved };},});diff --git a/packages/pieces/community/pdf-co/src/lib/actions/add-image-to-pdf.ts b/packages/pieces/community/pdf-co/src/lib/actions/add-image-to-pdf.tsindex dd43acd82fa..e9d9f504e04 100644--- a/packages/pieces/community/pdf-co/src/lib/actions/add-image-to-pdf.ts+++ b/packages/pieces/community/pdf-co/src/lib/actions/add-image-to-pdf.ts@@ -1,26 +1,24 @@+import { HttpMethod } from '@activepieces/pieces-common';import { Property, createAction } from '@activepieces/pieces-framework';-import { httpClient, HttpMethod, HttpError } from '@activepieces/pieces-common';-import {- PdfCoSuccessResponse,- PdfCoErrorResponse,- PdfCoImageAnnotation,- PdfCoAddImagesRequestBody,-} from '../common/types';import { pdfCoAuth } from '../auth';-import { BASE_URL, commonProps } from '../common/props';+import { pdfCoClient } from '../common/client';+import { pdfCoJobs } from '../common/jobs';+import { commonProps, PDF_CO_DEFAULTS, pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';export const addImageToPdf = createAction({name: 'add_image_to_pdf',classification: 'WRITE',displayName: 'Add Image to PDF',description: 'Add image to a PDF document.',- audience: 'both',+ audience: 'human',aiMetadata: {description:- 'Overlays an image (referenced by URL) onto a source PDF (referenced by URL) at the given x/y coordinates, optionally on specific pages. Use when an agent needs to stamp a logo, signature, or other graphic onto an existing document. Each call produces a new output PDF file and consumes credits, so it is not idempotent.',+ 'Overlays an image (referenced by URL) onto a source PDF (referenced by URL) at the given x/y coordinates, optionally on specific pages (first page is 0). Agents should use Edit PDF (AI), which adds several images, texts and form values in one call. Each call produces a new output PDF file and consumes credits, so it is not idempotent.',idempotent: false,},auth: pdfCoAuth,+ outputSchema: pdfCoOutputSchemas.legacyEdit,props: {url: Property.ShortText({displayName: 'Source PDF URL',@@ -56,94 +54,40 @@ export const addImageToPdf = createAction({pages: Property.ShortText({displayName: 'Target Pages',description:- 'Specify page indices as comma-separated values or ranges to process (e.g. "0, 1, 2-" or "1, 2, 3-7").',+ 'Page indexes as comma-separated values or ranges (first page is 0), e.g. "0, 1, 2-" or "1, 2, 3-7".',required: false,}),...commonProps,+ saveOutputFile: pdfCoProps.saveOutputFile({ defaultValue: PDF_CO_DEFAULTS.saveOutputFileOnExistingActions }),},- async run(context) {- const { auth, propsValue } = context;- const {- url,- imageUrl,- fileName,- pdfPassword,- xCoordinate,- pages,- yCoordinate,- width,- height,- expiration,- httpPassword,- httpUsername,- } = propsValue;-- const imageAnnotationPayload: PdfCoImageAnnotation = {- url: imageUrl,- x: xCoordinate,- y: yCoordinate,- pages,- height,- width,- };-- const requestBody: PdfCoAddImagesRequestBody = {- url: url,- images: [imageAnnotationPayload],- async: false,- name: fileName,- expiration,- httppassword: httpPassword,- httpusername: httpUsername,- password: pdfPassword,- inline: false,- };-- try {- const response = await httpClient.sendRequest<PdfCoSuccessResponse | PdfCoErrorResponse>({+ async run({ auth, propsValue, files }) {+ const body = pdfCoClient.readRecord(+ await pdfCoClient.request<unknown>({+ apiKey: pdfCoClient.apiKeyOf(auth),method: HttpMethod.POST,- url: `${BASE_URL}/pdf/edit/add`,- headers: {- 'x-api-key': auth.secret_text,- 'Content-Type': 'application/json',+ path: '/v1/pdf/edit/add',+ body: {+ url: propsValue.url,+ images: [+ {+ url: propsValue.imageUrl,+ x: propsValue.xCoordinate,+ y: propsValue.yCoordinate,+ pages: propsValue.pages,+ height: propsValue.height,+ width: propsValue.width,+ },+ ],+ async: false,+ name: propsValue.fileName,+ expiration: propsValue.expiration,+ httppassword: propsValue.httpPassword,+ httpusername: propsValue.httpUsername,+ password: propsValue.pdfPassword,+ inline: false,},- body: requestBody,- });-- console.log(JSON.stringify(response, null, 2));-- if (response.body.error) {- const errorBody = response.body as PdfCoErrorResponse;- let errorMessage = `PDF.co API Error (Add Image): Status ${errorBody.status}.`;- if (errorBody.message) {- errorMessage += ` Message: ${errorBody.message}.`;- } else {- errorMessage += ` An unspecified error occurred.`;- }- errorMessage += ` Raw response: ${JSON.stringify(errorBody)}`;- throw new Error(errorMessage);- }-- const successBody = response.body as PdfCoSuccessResponse;- return {- outputUrl: successBody.url,- pageCount: successBody.pageCount,- outputName: successBody.name,- creditsUsed: successBody.credits,- remainingCredits: successBody.remainingCredits,- };- } catch (error) {- if (error instanceof HttpError) {- const responseBody = error.response?.body as PdfCoErrorResponse | undefined;- let detailedMessage = `HTTP Error calling PDF.co API (Add Image): ${error.message}.`;- if (responseBody && responseBody.message) {- detailedMessage += ` Server message: ${responseBody.message}.`;- } else if (responseBody) {- detailedMessage += ` Server response: ${JSON.stringify(responseBody)}.`;- }- throw new Error(detailedMessage);- }- throw error;- }+ }),+ );+ return pdfCoJobs.legacyEditOutput({ body, files, saveOutputFile: propsValue.saveOutputFile, fileName: propsValue.fileName });},});diff --git a/packages/pieces/community/pdf-co/src/lib/actions/add-password-to-pdf.ts b/packages/pieces/community/pdf-co/src/lib/actions/add-password-to-pdf.tsnew file mode 100644index 00000000000..e1a4211360b--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/actions/add-password-to-pdf.ts@@ -0,0 +1,93 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../auth';+import { pdfCoClient } from '../common/client';+import { pdfCoFiles } from '../common/files';+import { pdfCoJobs } from '../common/jobs';+import { pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';++const ALGORITHMS = ['AES_128bit', 'AES_256bit', 'RC4_40bit', 'RC4_128bit'];++export const addPasswordToPdf = createAction({+ auth: pdfCoAuth,+ name: 'add_password_to_pdf',+ displayName: 'Protect PDF with Password',+ description: 'Create a password-protected copy of a PDF and choose what readers may do.',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Creates a password-protected copy of a PDF (public URL or file) with an owner password, an optional password to open it, and permission flags (print, copy, edit, fill forms, annotate, assemble). Costs 3 credits per page. Not idempotent: each call runs a new job and creates a new output.',+ idempotent: false,+ },+ outputSchema: pdfCoOutputSchemas.fileResult,+ props: {+ sourceUrl: pdfCoProps.sourceUrl(),+ sourceFile: pdfCoProps.sourceFile(),+ ownerPassword: Property.ShortText({+ displayName: 'Owner Password',+ description: 'Password that allows changing the security settings.',+ required: true,+ }),+ userPassword: Property.ShortText({+ displayName: 'Open Password',+ description: 'Password readers need to open the PDF. Leave empty to let anyone open it with the permissions below.',+ required: false,+ }),+ encryptionAlgorithm: Property.StaticDropdown({+ displayName: 'Encryption',+ required: false,+ defaultValue: 'AES_128bit',+ options: {+ disabled: false,+ options: [+ { label: 'AES 128-bit (default)', value: 'AES_128bit' },+ { label: 'AES 256-bit', value: 'AES_256bit' },+ { label: 'RC4 40-bit (legacy)', value: 'RC4_40bit' },+ { label: 'RC4 128-bit (legacy)', value: 'RC4_128bit' },+ ],+ },+ }),+ permissionsInfo: Property.MarkDown({ value: 'Permissions are off by default, as in PDF.co. Turn on what readers of the protected PDF may do.' }),+ allowPrintDocument: Property.Checkbox({ displayName: 'Allow Printing', required: false, defaultValue: false }),+ allowContentExtraction: Property.Checkbox({ displayName: 'Allow Copying Content', required: false, defaultValue: false }),+ allowModifyDocument: Property.Checkbox({ displayName: 'Allow Editing', required: false, defaultValue: false }),+ allowFillForms: Property.Checkbox({ displayName: 'Allow Filling Forms', required: false, defaultValue: false }),+ allowModifyAnnotations: Property.Checkbox({ displayName: 'Allow Annotations', required: false, defaultValue: false }),+ allowAssemblyDocument: Property.Checkbox({ displayName: 'Allow Assembling Pages', required: false, defaultValue: false }),+ allowAccessibilitySupport: Property.Checkbox({ displayName: 'Allow Accessibility Tools', required: false, defaultValue: false }),+ ...pdfCoProps.output(),+ },+ async run({ auth, propsValue, files }) {+ const apiKey = pdfCoClient.apiKeyOf(auth);+ const ownerPassword = propsValue.ownerPassword;+ if (ownerPassword.trim() === '') {+ throw new Error('Owner Password is required.');+ }+ const algorithm = pdfCoFiles.nonEmptyString(propsValue.encryptionAlgorithm);+ if (algorithm !== undefined && !ALGORITHMS.includes(algorithm)) {+ throw new Error(`Encryption must be one of ${ALGORITHMS.join(', ')}.`);+ }+ const userPassword = pdfCoFiles.nonEmptyString(propsValue.userPassword);+ const url = await pdfCoFiles.resolveSource({ apiKey, url: propsValue.sourceUrl, file: propsValue.sourceFile });+ return pdfCoJobs.runFileAction({+ apiKey,+ files,+ path: '/v1/pdf/security/add',+ body: {+ url,+ ownerPassword,+ ...(userPassword === undefined ? {} : { userPassword }),+ ...(algorithm === undefined ? {} : { encryptionAlgorithm: algorithm }),+ allowPrintDocument: propsValue.allowPrintDocument === true,+ allowContentExtraction: propsValue.allowContentExtraction === true,+ allowModifyDocument: propsValue.allowModifyDocument === true,+ allowFillForms: propsValue.allowFillForms === true,+ allowModifyAnnotations: propsValue.allowModifyAnnotations === true,+ allowAssemblyDocument: propsValue.allowAssemblyDocument === true,+ allowAccessibilitySupport: propsValue.allowAccessibilitySupport === true,+ },+ common: propsValue,+ });+ },+});diff --git a/packages/pieces/community/pdf-co/src/lib/actions/add-text-to-pdf.ts b/packages/pieces/community/pdf-co/src/lib/actions/add-text-to-pdf.tsindex e2656a12097..c5738642e74 100644--- a/packages/pieces/community/pdf-co/src/lib/actions/add-text-to-pdf.ts+++ b/packages/pieces/community/pdf-co/src/lib/actions/add-text-to-pdf.ts@@ -1,57 +1,24 @@+import { HttpMethod } from '@activepieces/pieces-common';import { Property, createAction } from '@activepieces/pieces-framework';-import { httpClient, HttpMethod, HttpError } from '@activepieces/pieces-common';-import { PdfCoSuccessResponse, PdfCoErrorResponse } from '../common/types';import { pdfCoAuth } from '../auth';-import { BASE_URL, commonProps } from '../common/props';--// Interface for a single text annotation object based on PDF.co docs-interface PdfCoTextAnnotation {- text: string;- x: number;- y: number;- pages?: string;- size?: number;- fontName?: string;- color?: string;- link?: string;- width?: number;- height?: number;- fontBold?: boolean;- fontUnderline?: boolean;- fontStrikeout?: boolean;- alignment?: string;- type?: 'text' | 'textField' | 'TextFieldMultiline' | 'checkbox';- id?: string;- transparent?: boolean;- RotationAngle?: number;-}--// Interface for the main request body for /pdf/edit/add-interface PdfCoAddAnnotationsRequestBody {- url: string;- annotations: PdfCoTextAnnotation[];- async: boolean;- name?: string;- password?: string;- expiration?: number;- inline?: boolean;- profiles?: Record<string, unknown>; // JSON object for profiles- httpusername?: string;- httppassword?: string;-}+import { pdfCoClient } from '../common/client';+import { pdfCoJobs } from '../common/jobs';+import { commonProps, PDF_CO_DEFAULTS, pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';export const addTextToPdf = createAction({name: 'add_text_to_pdf',classification: 'WRITE',displayName: 'Add Text to PDF',description: 'Adds text to PDF.',- audience: 'both',+ audience: 'human',aiMetadata: {description:- 'Stamps a text annotation onto a source PDF (referenced by URL) at the given x/y coordinates, with optional font, size, color, and styling. Use when an agent needs to write text onto an existing document. Each call produces a new output PDF file and consumes credits, so it is not idempotent.',+ 'Stamps a text annotation onto a source PDF (referenced by URL) at the given x/y coordinates, with optional font, size, color, and styling. Page indexes start at 0. Agents should use Edit PDF (AI), which adds several texts, images and form values in one call. Each call produces a new output PDF file and consumes credits, so it is not idempotent.',idempotent: false,},auth: pdfCoAuth,+ outputSchema: pdfCoOutputSchemas.legacyEdit,props: {url: Property.ShortText({displayName: 'Source PDF URL',@@ -99,7 +66,7 @@ export const addTextToPdf = createAction({pages: Property.ShortText({displayName: 'Target Pages',description:- 'Specify page indices as comma-separated values or ranges to process (e.g. "0, 1, 2-" or "1, 2, 3-7").',+ 'Page indexes as comma-separated values or ranges (first page is 0), e.g. "0, 1, 2-" or "1, 2, 3-7".',required: false,}),textBoxHeight: Property.Number({@@ -124,102 +91,43 @@ export const addTextToPdf = createAction({},}),...commonProps,+ saveOutputFile: pdfCoProps.saveOutputFile({ defaultValue: PDF_CO_DEFAULTS.saveOutputFileOnExistingActions }),},- async run(context) {- const { auth, propsValue } = context;- const {- url,- xCoordinate,- yCoordinate,- fontSize,- fontName,- fontBold,- fontStrikeout,- fontUnderline,- color,- pages,- textBoxAlignment,- textBoxHeight,- textBoxWidth,- text,- fileName,- pdfPassword,- httpPassword,- httpUsername,- expiration,- } = propsValue;-- const textAnnotationPayload: PdfCoTextAnnotation = {- x: xCoordinate,- y: yCoordinate,- text,- type: 'text',- color,- pages,- width: textBoxWidth,- height: textBoxHeight,- alignment: textBoxAlignment,- size: fontSize,- fontName,- fontBold,- fontStrikeout,- fontUnderline,- };-- const requestBody: PdfCoAddAnnotationsRequestBody = {- url: url,- annotations: [textAnnotationPayload],- async: false,- name: fileName,- expiration,- httppassword: httpPassword,- httpusername: httpUsername,- password: pdfPassword,- };-- try {- const response = await httpClient.sendRequest<PdfCoSuccessResponse | PdfCoErrorResponse>({+ async run({ auth, propsValue, files }) {+ const body = pdfCoClient.readRecord(+ await pdfCoClient.request<unknown>({+ apiKey: pdfCoClient.apiKeyOf(auth),method: HttpMethod.POST,- url: `${BASE_URL}/pdf/edit/add`,- headers: {- 'x-api-key': auth.secret_text,- 'Content-Type': 'application/json',+ path: '/v1/pdf/edit/add',+ body: {+ url: propsValue.url,+ annotations: [+ {+ x: propsValue.xCoordinate,+ y: propsValue.yCoordinate,+ text: propsValue.text,+ type: 'text',+ color: propsValue.color,+ pages: propsValue.pages,+ width: propsValue.textBoxWidth,+ height: propsValue.textBoxHeight,+ alignment: propsValue.textBoxAlignment,+ size: propsValue.fontSize,+ fontName: propsValue.fontName,+ fontBold: propsValue.fontBold,+ fontStrikeout: propsValue.fontStrikeout,+ fontUnderline: propsValue.fontUnderline,+ },+ ],+ async: false,+ name: propsValue.fileName,+ expiration: propsValue.expiration,+ httppassword: propsValue.httpPassword,+ httpusername: propsValue.httpUsername,+ password: propsValue.pdfPassword,},- body: requestBody,- });-- if (response.body.error) {- const errorBody = response.body as PdfCoErrorResponse;- let errorMessage = `PDF.co API Error (Add Text): Status ${errorBody.status}.`;- if (errorBody.message) {- errorMessage += ` Message: ${errorBody.message}.`;- } else {- errorMessage += ` An unspecified error occurred.`;- }- errorMessage += ` Raw response: ${JSON.stringify(errorBody)}`;- throw new Error(errorMessage);- }-- const successBody = response.body as PdfCoSuccessResponse;- return {- outputUrl: successBody.url,- pageCount: successBody.pageCount,- outputName: successBody.name,- creditsUsed: successBody.credits,- remainingCredits: successBody.remainingCredits,- };- } catch (error) {- if (error instanceof HttpError) {- const responseBody = error.response?.body as PdfCoErrorResponse | undefined;- let detailedMessage = `HTTP Error calling PDF.co API (Add Text): ${error.message}.`;- if (responseBody && responseBody.message) {- detailedMessage += ` Server message: ${responseBody.message}.`;- } else if (responseBody) {- detailedMessage += ` Server response: ${JSON.stringify(responseBody)}.`;- }- throw new Error(detailedMessage);- }- throw error;- }+ }),+ );+ return pdfCoJobs.legacyEditOutput({ body, files, saveOutputFile: propsValue.saveOutputFile, fileName: propsValue.fileName });},});diff --git a/packages/pieces/community/pdf-co/src/lib/actions/ai/convert-pdf.ts b/packages/pieces/community/pdf-co/src/lib/actions/ai/convert-pdf.tsnew file mode 100644index 00000000000..5590526aec9--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/actions/ai/convert-pdf.ts@@ -0,0 +1,121 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../../auth';+import { pdfCoClient } from '../../common/client';+import { pdfCoFiles } from '../../common/files';+import { pdfCoOutputSchemas } from '../../output-schemas';++const ENDPOINTS: Record<string, string> = {+ text: '/v1/pdf/convert/to/text-simple',+ text_ocr: '/v1/pdf/convert/to/text',+ csv: '/v1/pdf/convert/to/csv',+ json: '/v1/pdf/convert/to/json2',+ xml: '/v1/pdf/convert/to/xml',+ html: '/v1/pdf/convert/to/html',+};+const DEFAULT_MAX_CHARS = 50_000;+const MAX_MAX_CHARS = 200_000;++export const pdfCoConvertPdf = createAction({+ auth: pdfCoAuth,+ name: 'pdf_co_convert_pdf',+ displayName: 'Convert PDF (AI)',+ description: 'Convert a PDF to text, CSV, JSON, XML or HTML and return the content directly.',+ audience: 'ai',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Converts a PDF at a public URL into plain text, OCR text (for scans), CSV, JSON, XML or HTML and returns the converted content directly, cut to max_chars with a truncated flag. Use when the agent needs to read a PDF\'s content; pages are 0-based. Credits per page: text 4, text_ocr 21, csv/json 28, xml 35, html 21. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: pdfCoOutputSchemas.aiConvert,+ props: {+ source_url: Property.ShortText({+ displayName: 'Source URL',+ description: 'Public http(s) URL of the PDF.',+ required: true,+ }),+ format: Property.ShortText({+ displayName: 'Format',+ description: 'One of: text, text_ocr, csv, json, xml, html. Default text.',+ required: false,+ }),+ pages: Property.ShortText({+ displayName: 'Pages',+ description: 'Optional 0-based pages or ranges, e.g. "0,2-4". Empty = all pages.',+ required: false,+ }),+ lang: Property.ShortText({+ displayName: 'OCR Language',+ description: 'Optional OCR language for text_ocr, csv, json, xml and html, e.g. "eng" or "eng+deu".',+ required: false,+ }),+ password: Property.ShortText({+ displayName: 'PDF Password',+ description: 'Optional password if the PDF is protected.',+ required: false,+ }),+ max_chars: Property.Number({+ displayName: 'Max Characters',+ description: `Maximum characters of content to return (default ${DEFAULT_MAX_CHARS}, max ${MAX_MAX_CHARS}).`,+ required: false,+ }),+ },+ async run({ auth, propsValue }) {+ const format = (pdfCoFiles.nonEmptyString(propsValue.format) ?? 'text').trim().toLowerCase();+ const path = ENDPOINTS[format];+ if (path === undefined) {+ throw new Error(`format must be one of: ${Object.keys(ENDPOINTS).join(', ')}.`);+ }+ const maxChars = propsValue.max_chars === undefined || propsValue.max_chars === null ? DEFAULT_MAX_CHARS : Number(propsValue.max_chars);+ if (!Number.isInteger(maxChars) || maxChars < 1 || maxChars > MAX_MAX_CHARS) {+ throw new Error(`max_chars must be a whole number from 1 to ${MAX_MAX_CHARS}.`);+ }+ const lang = pdfCoFiles.nonEmptyString(propsValue.lang);+ if (lang !== undefined && format === 'text') {+ throw new Error('lang does not apply to format "text"; use "text_ocr" for OCR.');+ }+ pdfCoFiles.validateSource({ url: propsValue.source_url, file: undefined, label: 'source_url' });+ const pages = pdfCoFiles.nonEmptyString(propsValue.pages);+ const password = pdfCoFiles.nonEmptyString(propsValue.password);+ const body = await convertInline({+ apiKey: pdfCoClient.apiKeyOf(auth),+ path,+ body: {+ url: propsValue.source_url.trim(),+ ...(pages === undefined ? {} : { pages: pages.trim() }),+ ...(lang === undefined ? {} : { lang: lang.trim() }),+ ...(password === undefined ? {} : { password }),+ },+ });+ const raw = body['body'];+ const content = typeof raw === 'string' ? raw : raw === undefined || raw === null ? '' : JSON.stringify(raw);+ return {+ format,+ content: content.slice(0, maxChars),+ truncated: content.length > maxChars,+ total_chars: content.length,+ page_count: body['pageCount'],+ credits_used: body['credits'],+ remaining_credits: body['remainingCredits'],+ };+ },+});++async function convertInline({+ apiKey,+ path,+ body,+}: {+ apiKey: string;+ path: string;+ body: Record<string, unknown>;+}): Promise<Record<string, unknown>> {+ const response = await pdfCoClient.request<unknown>({+ apiKey,+ method: HttpMethod.POST,+ path,+ body: { ...body, async: false, inline: true },+ });+ return pdfCoClient.readRecord(response);+}diff --git a/packages/pieces/community/pdf-co/src/lib/actions/ai/edit-pdf.ts b/packages/pieces/community/pdf-co/src/lib/actions/ai/edit-pdf.tsnew file mode 100644index 00000000000..89346608292--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/actions/ai/edit-pdf.ts@@ -0,0 +1,132 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../../auth';+import { pdfCoClient } from '../../common/client';+import { pdfCoFiles } from '../../common/files';+import { pdfCoJobs } from '../../common/jobs';+import { pdfCoOutputSchemas } from '../../output-schemas';+import { toFormFields } from '../fill-pdf-form';++const ANNOTATION_KEYS = ['text', 'x', 'y', 'pages', 'size', 'fontName', 'color', 'link', 'width', 'height', 'fontBold', 'fontItalic', 'fontUnderline', 'fontStrikeout', 'alignment', 'transparent', 'RotationAngle'];+const IMAGE_KEYS = ['url', 'x', 'y', 'pages', 'width', 'height', 'link', 'keepAspectRatio'];+const MAX_ITEMS = 100;++export const pdfCoEditPdf = createAction({+ auth: pdfCoAuth,+ name: 'pdf_co_edit_pdf',+ displayName: 'Edit PDF (AI)',+ description: 'Add texts, images and form-field values to a PDF in one call.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Adds any mix of text annotations, images and form-field values to a PDF at a public URL in one pass and returns a temporary link to the new PDF. Coordinates are points from the top-left corner; pages are 0-based. Costs 21 credits per page. Not idempotent: each call creates a new output and consumes credits.',+ idempotent: false,+ },+ outputSchema: pdfCoOutputSchemas.fileResult,+ props: {+ source_url: Property.ShortText({ displayName: 'Source URL', description: 'Public http(s) URL of the PDF.', required: true }),+ annotations: Property.Json({+ displayName: 'Text Annotations',+ description: 'Optional JSON array of {text, x, y, pages?, size?, fontName?, color?, fontBold?, alignment?, width?, height?}.',+ required: false,+ }),+ images: Property.Json({+ displayName: 'Images',+ description: 'Optional JSON array of {url, x, y, pages?, width?, height?, link?, keepAspectRatio?}; url must be a public image link.',+ required: false,+ }),+ fields: Property.Json({+ displayName: 'Form Fields',+ description: 'Optional JSON array of {fieldName, text, pages?} to fill existing form fields by exact name.',+ required: false,+ }),+ password: Property.ShortText({ displayName: 'PDF Password', description: 'Optional password if the PDF is protected.', required: false }),+ output_name: Property.ShortText({ displayName: 'Output Name', description: 'Optional name for the result file.', required: false }),+ },+ async run({ auth, propsValue, files }) {+ pdfCoFiles.validateSource({ url: propsValue.source_url, file: undefined, label: 'source_url' });+ const annotations = toItems({ value: propsValue.annotations, label: 'annotations', keys: ANNOTATION_KEYS, required: ['text', 'x', 'y'] });+ const images = toItems({ value: propsValue.images, label: 'images', keys: IMAGE_KEYS, required: ['url', 'x', 'y'] });+ images.forEach((image, index) =>+ pdfCoFiles.validateSource({ url: image['url'], file: undefined, label: `images[${index}].url` }),+ );+ const fields = isEmpty(propsValue.fields) ? [] : toFormFields(toArray({ value: propsValue.fields, label: 'fields' }));+ if (annotations.length + images.length + fields.length === 0) {+ throw new Error('Give at least one item in annotations, images or fields.');+ }+ return pdfCoJobs.runFileAction({+ apiKey: pdfCoClient.apiKeyOf(auth),+ files,+ path: '/v1/pdf/edit/add',+ body: {+ url: propsValue.source_url.trim(),+ inline: false,+ ...(annotations.length === 0 ? {} : { annotations }),+ ...(images.length === 0 ? {} : { images }),+ ...(fields.length === 0 ? {} : { fields }),+ },+ common: { pdfPassword: propsValue.password, outputName: propsValue.output_name, saveOutputFile: false, runInBackground: false },+ });+ },+});++function isEmpty(value: unknown): boolean {+ return value === undefined || value === null || value === '' || (Array.isArray(value) && value.length === 0);+}++function toArray({ value, label }: { value: unknown; label: string }): unknown[] {+ const parsed = typeof value === 'string' ? parseJson({ text: value, label }) : value;+ if (!Array.isArray(parsed)) {+ throw new Error(`${label} must be a JSON array.`);+ }+ if (parsed.length > MAX_ITEMS) {+ throw new Error(`${label} can have at most ${MAX_ITEMS} items.`);+ }+ return parsed;+}++function parseJson({ text, label }: { text: string; label: string }): unknown {+ try {+ return JSON.parse(text);+ } catch {+ throw new Error(`${label} is not valid JSON.`);+ }+}++function toItems({+ value,+ label,+ keys,+ required,+}: {+ value: unknown;+ label: string;+ keys: string[];+ required: string[];+}): Record<string, unknown>[] {+ if (isEmpty(value)) {+ return [];+ }+ const allowed = new Set(keys);+ return toArray({ value, label }).map((item, index) => {+ const record = pdfCoClient.readRecord(item);+ const unknownKeys = Object.keys(record).filter((key) => !allowed.has(key));+ if (unknownKeys.length > 0) {+ throw new Error(`${label}[${index}] has unknown keys: ${unknownKeys.join(', ')}.`);+ }+ const missing = required.filter((key) => record[key] === undefined || record[key] === null || record[key] === '');+ if (missing.length > 0) {+ throw new Error(`${label}[${index}] is missing: ${missing.join(', ')}.`);+ }+ ['x', 'y', 'width', 'height', 'size'].forEach((key) => {+ if (record[key] !== undefined && !Number.isFinite(Number(record[key]))) {+ throw new Error(`${label}[${index}].${key} must be a number.`);+ }+ });+ return Object.fromEntries(+ Object.entries(record).map(([key, entry]) =>+ ['x', 'y', 'width', 'height', 'size'].includes(key) ? [key, Number(entry)] : key === 'pages' ? [key, String(entry)] : [key, entry],+ ),+ );+ });+}diff --git a/packages/pieces/community/pdf-co/src/lib/actions/ai/parse-document.ts b/packages/pieces/community/pdf-co/src/lib/actions/ai/parse-document.tsnew file mode 100644index 00000000000..9e6f28015c1--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/actions/ai/parse-document.ts@@ -0,0 +1,46 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../../auth';+import { pdfCoClient } from '../../common/client';+import { pdfCoFiles } from '../../common/files';+import { pdfCoJobs } from '../../common/jobs';+import { pdfCoOutputSchemas } from '../../output-schemas';+import { flattenParserResult, parseTemplateId } from '../parse-document';++export const pdfCoParseDocument = createAction({+ auth: pdfCoAuth,+ name: 'pdf_co_parse_document',+ displayName: 'Parse Document (AI)',+ description: 'Extract fields and tables from a PDF with a Document Parser template ID.',+ audience: 'ai',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Extracts the fields (as name/value pairs) and tables defined by a PDF.co Document Parser template from a PDF or scan at a public URL; get template IDs from List Document Parser Templates (1 = built-in Invoice Parser). Costs 42 credits per page. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: pdfCoOutputSchemas.parseDocument,+ props: {+ source_url: Property.ShortText({ displayName: 'Source URL', description: 'Public http(s) URL of the PDF or image.', required: true }),+ template_id: Property.ShortText({ displayName: 'Template ID', description: 'Numeric Document Parser template ID, e.g. "1".', required: true }),+ pages: Property.ShortText({ displayName: 'Pages', description: 'Optional 0-based pages or ranges, e.g. "0,2-4".', required: false }),+ password: Property.ShortText({ displayName: 'PDF Password', description: 'Optional password if the PDF is protected.', required: false }),+ },+ async run({ auth, propsValue }) {+ const templateId = parseTemplateId(propsValue.template_id);+ pdfCoFiles.validateSource({ url: propsValue.source_url, file: undefined, label: 'source_url' });+ const pages = pdfCoFiles.nonEmptyString(propsValue.pages);+ const body = await pdfCoJobs.runInline({+ apiKey: pdfCoClient.apiKeyOf(auth),+ path: '/v1/pdf/documentparser',+ body: {+ url: propsValue.source_url.trim(),+ templateId,+ inline: true,+ outputFormat: 'JSON',+ ...(pages === undefined ? {} : { pages: pages.trim() }),+ },+ common: { pdfPassword: propsValue.password },+ });+ return flattenParserResult(body);+ },+});diff --git a/packages/pieces/community/pdf-co/src/lib/actions/check-job-status.ts b/packages/pieces/community/pdf-co/src/lib/actions/check-job-status.tsnew file mode 100644index 00000000000..b7b60bf0a82--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/actions/check-job-status.ts@@ -0,0 +1,65 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../auth';+import { pdfCoClient } from '../common/client';+import { pdfCoFiles } from '../common/files';+import { pdfCoJobs } from '../common/jobs';+import { pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';++export const checkJobStatus = createAction({+ auth: pdfCoAuth,+ name: 'check_job_status',+ displayName: 'Check Job Status',+ description: 'Check a PDF.co background job and get its result link when it is done.',+ audience: 'both',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Returns the status (working, success, failed or aborted) and result link of a background PDF.co job started with "Run in Background", optionally saving the finished result as a file. Use when an earlier PDF.co step returned status "working" and a job ID. Each check costs 2 credits; read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: pdfCoOutputSchemas.jobStatus,+ props: {+ jobId: Property.ShortText({+ displayName: 'Job ID',+ description: 'The Job ID returned by an earlier PDF.co step that ran in the background.',+ required: true,+ }),+ saveOutputFile: pdfCoProps.saveOutputFile({ defaultValue: false }),+ },+ async run({ auth, propsValue, files }) {+ const jobId = propsValue.jobId.trim();+ if (jobId === '') {+ throw new Error('Job ID is required.');+ }+ const check = await pdfCoJobs.checkJob({ apiKey: pdfCoClient.apiKeyOf(auth), jobId });+ const status = typeof check['status'] === 'string' ? check['status'] : 'unknown';+ const url = pdfCoFiles.nonEmptyString(check['url']);+ const urls = status === 'success' ? await partLinks({ check, jobId }) : undefined;+ const output = {+ job_id: jobId,+ status,+ message: pdfCoFiles.nonEmptyString(check['message']),+ url,+ urls,+ page_count: typeof check['pageCount'] === 'number' ? check['pageCount'] : undefined,+ link_valid_until: pdfCoFiles.nonEmptyString(check['outputLinkValidTill']),+ credits_used: typeof check['credits'] === 'number' ? check['credits'] : undefined,+ remaining_credits: typeof check['remainingCredits'] === 'number' ? check['remainingCredits'] : undefined,+ };+ if (propsValue.saveOutputFile !== true || status !== 'success' || url === undefined) {+ return output;+ }+ const saved = await pdfCoJobs.saveAll({ files, targets: urls ?? [url] });+ return { ...output, ...pdfCoJobs.savedFileFields({ ...saved, multiOutput: urls !== undefined }) };+ },+});++async function partLinks({ check, jobId }: { check: Record<string, unknown>; jobId: string }): Promise<string[] | undefined> {+ try {+ const links = await pdfCoJobs.resultUrls({ result: { body: check, status: 'success', jobId } });+ return links === undefined || links.length === 0 ? undefined : links;+ } catch {+ return undefined;+ }+}diff --git a/packages/pieces/community/pdf-co/src/lib/actions/compress-pdf.ts b/packages/pieces/community/pdf-co/src/lib/actions/compress-pdf.tsnew file mode 100644index 00000000000..1cd8ec59f1c--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/actions/compress-pdf.ts@@ -0,0 +1,68 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../auth';+import { pdfCoClient } from '../common/client';+import { pdfCoFiles } from '../common/files';+import { pdfCoJobs } from '../common/jobs';+import { pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';++export const compressPdf = createAction({+ auth: pdfCoAuth,+ name: 'compress_pdf',+ displayName: 'Compress PDF',+ description: 'Reduce the file size of a PDF.',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Reduces the file size of a PDF (public URL or file) using a compression preset (low, medium, high or aggressive) and an optional image quality, returning the smaller copy. Use before emailing or archiving large PDFs. Costs 35 credits per page. Not idempotent: each call runs a new job and creates a new output.',+ idempotent: false,+ },+ outputSchema: pdfCoOutputSchemas.fileResult,+ props: {+ sourceUrl: pdfCoProps.sourceUrl(),+ sourceFile: pdfCoProps.sourceFile(),+ compressionLevel: Property.StaticDropdown({+ displayName: 'Compression Level',+ description: 'Stronger levels make smaller files with lower image quality.',+ required: false,+ defaultValue: 'medium',+ options: {+ disabled: false,+ options: [+ { label: 'Low (best quality)', value: 'low' },+ { label: 'Medium (default)', value: 'medium' },+ { label: 'High', value: 'high' },+ { label: 'Aggressive (smallest file)', value: 'aggressive' },+ ],+ },+ }),+ colorQuality: Property.Number({+ displayName: 'Image Quality (1-100)',+ description: 'JPEG quality for color and grayscale images. Lower is smaller. Leave empty for the preset default.',+ required: false,+ }),+ ...pdfCoProps.password(),+ ...pdfCoProps.output(),+ },+ async run({ auth, propsValue, files }) {+ const apiKey = pdfCoClient.apiKeyOf(auth);+ const quality = propsValue.colorQuality;+ if (quality !== undefined && quality !== null && (!Number.isInteger(Number(quality)) || Number(quality) < 1 || Number(quality) > 100)) {+ throw new Error('Image Quality must be a whole number from 1 to 100.');+ }+ const level = pdfCoFiles.nonEmptyString(propsValue.compressionLevel);+ const url = await pdfCoFiles.resolveSource({ apiKey, url: propsValue.sourceUrl, file: propsValue.sourceFile });+ return pdfCoJobs.runFileAction({+ apiKey,+ files,+ path: '/v2/pdf/compress',+ body: {+ url,+ ...(level === undefined ? {} : { compressionLevel: level }),+ ...(quality === undefined || quality === null ? {} : { colorQuality: Number(quality) }),+ },+ common: propsValue,+ });+ },+});diff --git a/packages/pieces/community/pdf-co/src/lib/actions/convert-document-to-pdf.ts b/packages/pieces/community/pdf-co/src/lib/actions/convert-document-to-pdf.tsnew file mode 100644index 00000000000..a7a14a73b08--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/actions/convert-document-to-pdf.ts@@ -0,0 +1,74 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../auth';+import { pdfCoClient } from '../common/client';+import { pdfCoFiles } from '../common/files';+import { pdfCoJobs } from '../common/jobs';+import { pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';++const ENDPOINTS: Record<string, string> = {+ document: '/v1/pdf/convert/from/doc',+ spreadsheet: '/v1/pdf/convert/from/csv',+ image: '/v1/pdf/convert/from/image',+};++export const convertDocumentToPdf = createAction({+ auth: pdfCoAuth,+ name: 'convert_document_to_pdf',+ displayName: 'Convert Document to PDF',+ description: 'Convert a Word document, spreadsheet or images to PDF.',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Converts a Word/RTF/TXT/XPS document, a CSV/XLS/XLSX spreadsheet, or one or more images (combined into one PDF) to a PDF, given as public URLs or a file; choose the source type. Costs 21 credits per page for documents and spreadsheets, 9 for images. Not idempotent: each call runs a new job and creates a new output.',+ idempotent: false,+ },+ outputSchema: pdfCoOutputSchemas.fileResult,+ props: {+ sourceType: Property.StaticDropdown({+ displayName: 'Source Type',+ required: true,+ defaultValue: 'document',+ options: {+ disabled: false,+ options: [+ { label: 'Document (DOC, DOCX, RTF, TXT, XPS)', value: 'document' },+ { label: 'Spreadsheet (CSV, XLS, XLSX)', value: 'spreadsheet' },+ { label: 'Images (JPG, PNG, TIFF...)', value: 'image' },+ ],+ },+ }),+ sourceUrl: pdfCoProps.sourceUrl(),+ sourceFile: pdfCoProps.sourceFile(),+ extraImageUrls: Property.Array({+ displayName: 'More Image URLs',+ description: 'Images only: more public image links, added as further pages after the first image.',+ required: false,+ }),+ ...pdfCoProps.httpAuth(),+ ...pdfCoProps.output(),+ },+ async run({ auth, propsValue, files }) {+ const apiKey = pdfCoClient.apiKeyOf(auth);+ const path = ENDPOINTS[propsValue.sourceType];+ if (path === undefined) {+ throw new Error('Source Type must be document, spreadsheet or image.');+ }+ const extra = (Array.isArray(propsValue.extraImageUrls) ? propsValue.extraImageUrls : [])+ .map((item) => String(item ?? '').trim())+ .filter((item) => item !== '');+ if (extra.length > 0 && propsValue.sourceType !== 'image') {+ throw new Error('More Image URLs only works with Source Type "Images".');+ }+ extra.forEach((url, index) => pdfCoFiles.validateSource({ url, file: undefined, label: `Image URL #${index + 2}` }));+ const url = await pdfCoFiles.resolveSource({ apiKey, url: propsValue.sourceUrl, file: propsValue.sourceFile });+ return pdfCoJobs.runFileAction({+ apiKey,+ files,+ path,+ body: { url: [url, ...extra].join(',') },+ common: propsValue,+ });+ },+});diff --git a/packages/pieces/community/pdf-co/src/lib/actions/convert-html-template-to-pdf.ts b/packages/pieces/community/pdf-co/src/lib/actions/convert-html-template-to-pdf.tsnew file mode 100644index 00000000000..ac9f88958b8--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/actions/convert-html-template-to-pdf.ts@@ -0,0 +1,47 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../auth';+import { pdfCoClient } from '../common/client';+import { pdfCoJobs } from '../common/jobs';+import { pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';+import { parseTemplateId } from './parse-document';++export const convertHtmlTemplateToPdf = createAction({+ auth: pdfCoAuth,+ name: 'convert_html_template_to_pdf',+ displayName: 'Create PDF from HTML Template',+ description: 'Fill a saved PDF.co HTML template with your data and turn it into a PDF, e.g. an invoice.',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Fills a saved PDF.co HTML template (Mustache/Handlebars macros) with JSON data and renders it to a PDF, e.g. invoices or certificates; requires a template ID (see List HTML Templates). Costs 9 credits per page. Not idempotent: each call runs a new job and creates a new output.',+ idempotent: false,+ },+ outputSchema: pdfCoOutputSchemas.fileResult,+ props: {+ templateId: pdfCoProps.templateDropdown({ kind: 'html', required: true }),+ templateData: Property.Json({+ displayName: 'Template Data',+ description: 'JSON object with the values for the template macros, e.g. {"invoice_id":"123","paid":true}.',+ required: true,+ }),+ ...pdfCoProps.pageLayout(),+ ...pdfCoProps.output(),+ },+ async run({ auth, propsValue, files }) {+ const apiKey = pdfCoClient.apiKeyOf(auth);+ const templateId = parseTemplateId(propsValue.templateId);+ const data = propsValue.templateData;+ if (typeof data !== 'object' || data === null) {+ throw new Error('Template Data must be a JSON object.');+ }+ return pdfCoJobs.runFileAction({+ apiKey,+ files,+ path: '/v1/pdf/convert/from/html',+ body: { templateId, templateData: JSON.stringify(data), ...pdfCoProps.pageLayoutBody(propsValue) },+ common: propsValue,+ });+ },+});diff --git a/packages/pieces/community/pdf-co/src/lib/actions/convert-html-to-pdf.ts b/packages/pieces/community/pdf-co/src/lib/actions/convert-html-to-pdf.tsindex fb0f77d8a5d..f77b25cfb3e 100644--- a/packages/pieces/community/pdf-co/src/lib/actions/convert-html-to-pdf.ts+++ b/packages/pieces/community/pdf-co/src/lib/actions/convert-html-to-pdf.ts@@ -1,23 +1,10 @@-import { Property, createAction } from "@activepieces/pieces-framework";-import { httpClient, HttpMethod, HttpError } from "@activepieces/pieces-common";-import { PdfCoSuccessResponse, PdfCoErrorResponse } from "../common/types";+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';import { pdfCoAuth } from '../auth';-import { BASE_URL } from "../common/props";-interface PdfConvertFromHtmlRequestBody {- html: string;- async: boolean;- name?: string;- margins?: string; // e.g., "10px", "5mm 5mm 5mm 5mm"- paperSize?: string; // "A4", "Letter", "200mm 300mm", etc.- orientation?: 'Portrait' | 'Landscape';- printBackground?: boolean;- mediaType?: 'print' | 'screen' | 'none';- header?: string; // HTML content- footer?: string; // HTML content- expiration?: number;- profiles?: Record<string, unknown>;- DoNotWaitFullLoad?:boolean-}+import { pdfCoClient } from '../common/client';+import { pdfCoJobs } from '../common/jobs';+import { PDF_CO_DEFAULTS, pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';export const convertHtmlToPdf = createAction({name: 'convert_html_to_pdf',@@ -31,6 +18,7 @@ export const convertHtmlToPdf = createAction({idempotent: false,},auth: pdfCoAuth,+ outputSchema: pdfCoOutputSchemas.legacyEdit,props: {html: Property.LongText({displayName: 'HTML Content',@@ -49,11 +37,11 @@ export const convertHtmlToPdf = createAction({}),paperSize: Property.StaticDropdown({displayName: 'Paper Size',- description: 'Select a paper size. For custom sizes, input the value directly (e.g., \'200mm 300mm\') if your desired size isn\'t listed. Refer to PDF.co docs.',+ description: 'Select a standard paper size. For another size, fill Custom Paper Size below.',required: false,options: {disabled: false,- placeholder: 'Select paper size or input custom',+ placeholder: 'Select paper size',options: [{ label: "A4 (Default)", value: "A4" },{ label: "Letter", value: "Letter" },@@ -125,74 +113,47 @@ export const convertHtmlToPdf = createAction({displayName: 'Profiles',description: 'JSON object for additional configurations.',required: false,- })+ }),+ customPaperSize: Property.ShortText({+ displayName: 'Custom Paper Size',+ description: 'Width and height with units, e.g. "200mm 300mm" or "8.5in 11in". Overrides Paper Size when set.',+ required: false,+ }),+ saveOutputFile: pdfCoProps.saveOutputFile({ defaultValue: PDF_CO_DEFAULTS.saveOutputFileOnExistingActions }),},- async run(context) {- const { auth, propsValue } = context;-- const requestBody: PdfConvertFromHtmlRequestBody = {+ async run({ auth, propsValue, files }) {+ const text = (value: unknown): string | undefined => (typeof value === 'string' && value !== '' ? value : undefined);+ const customPaperSize = text(propsValue.customPaperSize)?.trim();+ const orientation = text(propsValue.orientation);+ const mediaType = text(propsValue.mediaType);+ const profiles = pdfCoClient.serializeProfiles(propsValue.profiles);+ const requestBody: Record<string, unknown> = {html: propsValue.html,async: false,- DoNotWaitFullLoad:propsValue.doNotWaitFullLoad+ DoNotWaitFullLoad: propsValue.doNotWaitFullLoad,+ ...(text(propsValue.name) === undefined ? {} : { name: propsValue.name }),+ ...(text(propsValue.margins) === undefined ? {} : { margins: propsValue.margins }),+ ...(customPaperSize !== undefined && customPaperSize !== ''+ ? { paperSize: customPaperSize }+ : propsValue.paperSize === undefined+ ? {}+ : { paperSize: propsValue.paperSize }),+ ...(orientation === undefined ? {} : { orientation }),+ ...(propsValue.printBackground === undefined ? {} : { printBackground: propsValue.printBackground }),+ ...(mediaType === undefined ? {} : { mediaType }),+ ...(text(propsValue.header) === undefined ? {} : { header: propsValue.header }),+ ...(text(propsValue.footer) === undefined ? {} : { footer: propsValue.footer }),+ ...(propsValue.expiration === undefined ? {} : { expiration: propsValue.expiration }),+ ...(profiles === undefined ? {} : { profiles }),};-- if (propsValue.name !== undefined && propsValue.name !== '') requestBody.name = propsValue.name;- if (propsValue.margins !== undefined && propsValue.margins !== '') requestBody.margins = propsValue.margins;- if (propsValue.paperSize !== undefined) requestBody.paperSize = propsValue.paperSize;- if (propsValue.orientation !== undefined) requestBody.orientation = propsValue.orientation as 'Portrait' | 'Landscape';- if (propsValue.printBackground !== undefined) requestBody.printBackground = propsValue.printBackground;- if (propsValue.mediaType !== undefined) requestBody.mediaType = propsValue.mediaType as 'print' | 'screen' | 'none';- if (propsValue.header !== undefined && propsValue.header !== '') requestBody.header = propsValue.header;- if (propsValue.footer !== undefined && propsValue.footer !== '') requestBody.footer = propsValue.footer;- if (propsValue.expiration !== undefined) requestBody.expiration = propsValue.expiration;- if (propsValue.profiles !== undefined && typeof propsValue.profiles === 'object' && propsValue.profiles !== null) {- requestBody.profiles = propsValue.profiles as Record<string, unknown>;- }-- try {- const response = await httpClient.sendRequest<PdfCoSuccessResponse | PdfCoErrorResponse>({+ const body = pdfCoClient.readRecord(+ await pdfCoClient.request<unknown>({+ apiKey: pdfCoClient.apiKeyOf(auth),method: HttpMethod.POST,- url: `${BASE_URL}/pdf/convert/from/html`,- headers: {- 'x-api-key': auth.secret_text,- 'Content-Type': 'application/json',- },+ path: '/v1/pdf/convert/from/html',body: requestBody,- });-- if (response.body.error) {- const errorBody = response.body as PdfCoErrorResponse;- let errorMessage = `PDF.co API Error (Convert HTML to PDF): Status ${errorBody.status}.`;- if (errorBody.message) {- errorMessage += ` Message: ${errorBody.message}.`;- } else {- errorMessage += ` An unspecified error occurred.`;- }- errorMessage += ` Raw response: ${JSON.stringify(errorBody)}`;- throw new Error(errorMessage);- }-- const successBody = response.body as PdfCoSuccessResponse;- return {- outputUrl: successBody.url,- pageCount: successBody.pageCount,- outputName: successBody.name,- creditsUsed: successBody.credits,- remainingCredits: successBody.remainingCredits,- };-- } catch (error) {- if (error instanceof HttpError) {- const responseBody = error.response?.body as (PdfCoErrorResponse | undefined);- let detailedMessage = `HTTP Error calling PDF.co API (Convert HTML to PDF): ${error.message}.`;- if (responseBody && responseBody.message) {- detailedMessage += ` Server message: ${responseBody.message}.`;- } else if (responseBody) {- detailedMessage += ` Server response: ${JSON.stringify(responseBody)}.`;- }- throw new Error(detailedMessage);- }- throw error;- }+ }),+ );+ return pdfCoJobs.legacyEditOutput({ body, files, saveOutputFile: propsValue.saveOutputFile, fileName: propsValue.name });},});diff --git a/packages/pieces/community/pdf-co/src/lib/actions/convert-pdf-to-image.ts b/packages/pieces/community/pdf-co/src/lib/actions/convert-pdf-to-image.tsnew file mode 100644index 00000000000..8b185162177--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/actions/convert-pdf-to-image.ts@@ -0,0 +1,63 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../auth';+import { pdfCoClient } from '../common/client';+import { pdfCoFiles } from '../common/files';+import { pdfCoJobs } from '../common/jobs';+import { pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';++const FORMATS = ['jpg', 'png', 'webp', 'tiff'];++export const convertPdfToImage = createAction({+ auth: pdfCoAuth,+ name: 'convert_pdf_to_image',+ displayName: 'Convert PDF to Images',+ description: 'Render PDF pages as JPG, PNG, WEBP or TIFF images.',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Renders the pages of a PDF (public URL or file) to JPG, PNG or WEBP images (one image per page) or one multi-page TIFF, returning a temporary link per image and optionally saving the files. Use for previews and thumbnails; pages start at 0. Costs 12 (JPG), 15 (PNG), 18 (WEBP) or 28 (TIFF) credits per page. Not idempotent: each call runs a new job and creates new outputs.',+ idempotent: false,+ },+ outputSchema: pdfCoOutputSchemas.multiFileResult,+ props: {+ sourceUrl: pdfCoProps.sourceUrl(),+ sourceFile: pdfCoProps.sourceFile(),+ format: Property.StaticDropdown({+ displayName: 'Image Format',+ required: true,+ defaultValue: 'png',+ options: {+ disabled: false,+ options: [+ { label: 'JPG', value: 'jpg' },+ { label: 'PNG', value: 'png' },+ { label: 'WEBP', value: 'webp' },+ { label: 'TIFF (one multi-page file)', value: 'tiff' },+ ],+ },+ }),+ pages: pdfCoProps.pages({ base: 0 }),+ ...pdfCoProps.password(),+ ...pdfCoProps.httpAuth(),+ ...pdfCoProps.output(),+ },+ async run({ auth, propsValue, files }) {+ const apiKey = pdfCoClient.apiKeyOf(auth);+ const format = propsValue.format;+ if (!FORMATS.includes(format)) {+ throw new Error(`Image Format must be one of ${FORMATS.join(', ')}.`);+ }+ const pages = pdfCoFiles.nonEmptyString(propsValue.pages);+ const url = await pdfCoFiles.resolveSource({ apiKey, url: propsValue.sourceUrl, file: propsValue.sourceFile });+ return pdfCoJobs.runFileAction({+ apiKey,+ files,+ path: `/v1/pdf/convert/to/${format}`,+ body: { url, ...(pages === undefined ? {} : { pages: pages.trim() }) },+ common: propsValue,+ multiOutput: true,+ });+ },+});diff --git a/packages/pieces/community/pdf-co/src/lib/actions/convert-pdf-to-structured-format.ts b/packages/pieces/community/pdf-co/src/lib/actions/convert-pdf-to-structured-format.tsindex 0bb4f502531..8b8afc4356e 100644--- a/packages/pieces/community/pdf-co/src/lib/actions/convert-pdf-to-structured-format.ts+++ b/packages/pieces/community/pdf-co/src/lib/actions/convert-pdf-to-structured-format.ts@@ -1,156 +1,102 @@-import { Property, DropdownOption, createAction } from "@activepieces/pieces-framework";-import { httpClient, HttpMethod, HttpError } from "@activepieces/pieces-common";-import { PdfCoSuccessResponse, PdfCoErrorResponse } from "../common/types";+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';import { pdfCoAuth } from '../auth';-import { BASE_URL, commonProps } from "../common/props";-// Interface for the request body (common params for CSV/JSON/XML conversion)-interface PdfConvertToStructuredFormatRequestBody {- url: string;- async: boolean;- inline: boolean; // Should typically be false to get output URL- name?: string;- pages?: string;- password?: string;- lang?: string;- expiration?: number;- profiles?: Record<string, unknown>;- httpusername?: string;- httppassword?: string;-}+import { pdfCoClient } from '../common/client';+import { pdfCoJobs } from '../common/jobs';+import { commonProps, PDF_CO_DEFAULTS, pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';-export const convertPdfToStructuredFormat = createAction({- name: 'convert_pdf_to_structured_format',- classification: 'READ',- displayName: 'Convert PDF to JSON/CSV/XML',- description: 'Convert PDF content into structured formats (JSON, CSV, or XML).',- audience: 'both',- aiMetadata: {- description:- 'Converts a source PDF (referenced by URL) into structured data, with the output format selectable between JSON, CSV, or XML. Optional OCR language handles scanned documents. Use when an agent needs machine-readable data extracted from a PDF. Each call generates a new output file and consumes credits, so it is not idempotent.',- idempotent: false,- },- auth: pdfCoAuth,- props: {- url: Property.ShortText({- displayName: 'Source PDF URL',- description: 'URL of the PDF file to convert.',- required: true,- }),- outputFormat: Property.StaticDropdown ({- displayName: 'Output Format',- description: 'Select the desired structured output format.',- required: true,- options: {- disabled:false,- options: [- { label: "JSON", value: "json" },- { label: "CSV", value: "csv" },- { label: "XML", value: "xml" },- ] as DropdownOption<'json' | 'csv' | 'xml'>[],-- }- }),- pages: Property.ShortText({- displayName: 'Pages',- description: 'Comma-separated page numbers or ranges (e.g., "0,2,5-10"). Leave empty for all pages.',- required: false,- }),- lang: Property.ShortText({- displayName: 'OCR Language',- description: 'Language for OCR if processing scanned documents (e.g., "eng", "deu", "eng+deu"). See PDF.co docs for list.',- required: false,- }),- profiles: Property.Json({- displayName: 'Profiles',- description: 'JSON object for additional configurations.',- required: false,- }),- ...commonProps- },- async run(context) {- const { auth, propsValue } = context;- const {- url,- outputFormat,- pages,- lang,- pdfPassword,- fileName,- httpPassword,- httpUsername,- expiration,- profiles- } = propsValue;-- let endpoint = '';- switch (outputFormat) {- case 'json':- endpoint = `${BASE_URL}/pdf/convert/to/json2`;- break;- case 'csv':- endpoint = `${BASE_URL}/pdf/convert/to/csv`;- break;- case 'xml':- endpoint = `${BASE_URL}/pdf/convert/to/xml`;- break;- default:- throw new Error(`Unsupported output format: ${outputFormat}`);- }-- const requestBody: PdfConvertToStructuredFormatRequestBody = {- url: url,- async: false,- httppassword:httpPassword,- httpusername:httpUsername,- inline: false, // Ensure we get the URL to the output file- };-- if (pages !== undefined && pages !== '') requestBody.pages = pages;- if (lang !== undefined && lang !== '') requestBody.lang = lang;- if (pdfPassword !== undefined && pdfPassword !== '') requestBody.password = pdfPassword;- if (fileName !== undefined && fileName !== '') requestBody.name = fileName;- if (expiration !== undefined) requestBody.expiration = expiration;- if (profiles !== undefined && typeof profiles === 'object' && profiles !== null) {- requestBody.profiles = profiles as Record<string, unknown>;- }+const ENDPOINTS: Record<string, string> = {+ json: '/v1/pdf/convert/to/json2',+ csv: '/v1/pdf/convert/to/csv',+ xml: '/v1/pdf/convert/to/xml',+ xlsx: '/v1/pdf/convert/to/xlsx',+ xls: '/v1/pdf/convert/to/xls',+ html: '/v1/pdf/convert/to/html',+};- try {- const response = await httpClient.sendRequest<PdfCoSuccessResponse | PdfCoErrorResponse>({- method: HttpMethod.POST,- url: endpoint,- headers: {- 'x-api-key': auth.secret_text,- 'Content-Type': 'application/json',- },- body: requestBody,- });-- if (response.body.error) {- const errorBody = response.body as PdfCoErrorResponse;- let errorMessage = `PDF.co API Error (Convert PDF to ${outputFormat.toUpperCase()}): Status ${errorBody.status}.`;- if (errorBody.message) {- errorMessage += ` Message: ${errorBody.message}.`;- } else {- errorMessage += ` An unspecified error occurred.`;- }- errorMessage += ` Raw response: ${JSON.stringify(errorBody)}`;- throw new Error(errorMessage);- }-- return response.body;-- } catch (error) {- if (error instanceof HttpError) {- const responseBody = error.response?.body as (PdfCoErrorResponse | undefined);- let detailedMessage = `HTTP Error calling PDF.co API (Convert PDF to ${outputFormat.toUpperCase()}): ${error.message}.`;- if (responseBody && responseBody.message) {- detailedMessage += ` Server message: ${responseBody.message}.`;- } else if (responseBody) {- detailedMessage += ` Server response: ${JSON.stringify(responseBody)}.`;- }- throw new Error(detailedMessage);- }- throw error;- }- },+export const convertPdfToStructuredFormat = createAction({+ name: 'convert_pdf_to_structured_format',+ classification: 'READ',+ displayName: 'Convert PDF to JSON/CSV/XML/Excel/HTML',+ description: 'Convert PDF content into structured formats (JSON, CSV, XML, Excel or HTML).',+ audience: 'human',+ aiMetadata: {+ description:+ 'Converts a source PDF (referenced by URL) to a JSON, CSV, XML, XLSX, XLS or HTML file and returns a temporary link to the result file; optional OCR language handles scanned documents and page indexes start at 0. Agents wanting the content inline should use Convert PDF (AI). Not idempotent: each call runs a new conversion job and consumes credits.',+ idempotent: false,+ },+ auth: pdfCoAuth,+ outputSchema: pdfCoOutputSchemas.rawResult,+ props: {+ url: Property.ShortText({+ displayName: 'Source PDF URL',+ description: 'URL of the PDF file to convert.',+ required: true,+ }),+ outputFormat: Property.StaticDropdown({+ displayName: 'Output Format',+ description: 'Select the desired structured output format.',+ required: true,+ options: {+ disabled: false,+ options: [+ { label: 'JSON', value: 'json' },+ { label: 'CSV', value: 'csv' },+ { label: 'XML', value: 'xml' },+ { label: 'Excel (XLSX)', value: 'xlsx' },+ { label: 'Excel 97-2003 (XLS)', value: 'xls' },+ { label: 'HTML', value: 'html' },+ ],+ },+ }),+ pages: Property.ShortText({+ displayName: 'Pages',+ description: 'Comma-separated page indexes or ranges (first page is 0), e.g. "0,2,5-10". Leave empty for all pages.',+ required: false,+ }),+ lang: Property.ShortText({+ displayName: 'OCR Language',+ description: 'Language for OCR if processing scanned documents (e.g., "eng", "deu", "eng+deu"). See PDF.co docs for list.',+ required: false,+ }),+ profiles: Property.Json({+ displayName: 'Profiles',+ description: 'JSON object for additional configurations.',+ required: false,+ }),+ ...commonProps,+ saveOutputFile: pdfCoProps.saveOutputFile({ defaultValue: PDF_CO_DEFAULTS.saveOutputFileOnExistingActions }),+ },+ async run({ auth, propsValue, files }) {+ const { url, outputFormat, pages, lang, pdfPassword, fileName, httpPassword, httpUsername, expiration, profiles } = propsValue;+ const path = ENDPOINTS[outputFormat];+ if (path === undefined) {+ throw new Error(`Unsupported output format: ${outputFormat}`);+ }+ const text = (value: unknown): value is string => typeof value === 'string' && value !== '';+ const serialized = pdfCoClient.serializeProfiles(profiles);+ const body = pdfCoClient.readRecord(+ await pdfCoClient.request<unknown>({+ apiKey: pdfCoClient.apiKeyOf(auth),+ method: HttpMethod.POST,+ path,+ body: {+ url,+ async: false,+ httppassword: httpPassword,+ httpusername: httpUsername,+ inline: false,+ ...(text(pages) ? { pages } : {}),+ ...(text(lang) ? { lang } : {}),+ ...(text(pdfPassword) ? { password: pdfPassword } : {}),+ ...(text(fileName) ? { name: fileName } : {}),+ ...(expiration === undefined ? {} : { expiration }),+ ...(serialized === undefined ? {} : { profiles: serialized }),+ },+ }),+ );+ const saved = await pdfCoJobs.optionalSave({ files, url: body['url'], enabled: propsValue.saveOutputFile, fileName });+ return { ...body, ...saved };+ },});diff --git a/packages/pieces/community/pdf-co/src/lib/actions/convert-url-to-pdf.ts b/packages/pieces/community/pdf-co/src/lib/actions/convert-url-to-pdf.tsnew file mode 100644index 00000000000..0e577bba662--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/actions/convert-url-to-pdf.ts@@ -0,0 +1,55 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../auth';+import { pdfCoClient } from '../common/client';+import { pdfCoFiles } from '../common/files';+import { pdfCoJobs } from '../common/jobs';+import { pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';++export const convertUrlToPdf = createAction({+ auth: pdfCoAuth,+ name: 'convert_url_to_pdf',+ displayName: 'Convert Web Page to PDF',+ description: 'Turn a public web page into a PDF.',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Renders a public web page URL into a PDF with optional paper size, orientation, margins, header and footer, returning a temporary link and optionally the file. The page must be reachable without login. Costs 9 credits per page. Not idempotent: each call runs a new job and creates a new output.',+ idempotent: false,+ },+ outputSchema: pdfCoOutputSchemas.fileResult,+ props: {+ pageUrl: Property.ShortText({+ displayName: 'Web Page URL',+ description: 'The public page to convert, e.g. https://example.com/report.',+ required: true,+ }),+ ...pdfCoProps.pageLayout(),+ renderTimeout: Property.Number({+ displayName: 'Render Wait (ms)',+ description: 'Extra time to let heavy JavaScript pages finish rendering, in milliseconds.',+ required: false,+ }),+ ...pdfCoProps.output(),+ },+ async run({ auth, propsValue, files }) {+ const apiKey = pdfCoClient.apiKeyOf(auth);+ pdfCoFiles.validateSource({ url: propsValue.pageUrl, file: undefined, label: 'Web Page' });+ const timeout = propsValue.renderTimeout;+ if (timeout !== undefined && timeout !== null && (!Number.isInteger(Number(timeout)) || Number(timeout) < 0)) {+ throw new Error('Render Wait must be a whole number of milliseconds.');+ }+ return pdfCoJobs.runFileAction({+ apiKey,+ files,+ path: '/v1/pdf/convert/from/url',+ body: {+ url: propsValue.pageUrl.trim(),+ ...pdfCoProps.pageLayoutBody(propsValue),+ ...(timeout === undefined || timeout === null ? {} : { renderTimeout: Number(timeout) }),+ },+ common: propsValue,+ });+ },+});diff --git a/packages/pieces/community/pdf-co/src/lib/actions/delete-pdf-pages.ts b/packages/pieces/community/pdf-co/src/lib/actions/delete-pdf-pages.tsnew file mode 100644index 00000000000..048af864817--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/actions/delete-pdf-pages.ts@@ -0,0 +1,48 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../auth';+import { pdfCoClient } from '../common/client';+import { pdfCoFiles } from '../common/files';+import { pdfCoJobs } from '../common/jobs';+import { pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';++export const deletePdfPages = createAction({+ auth: pdfCoAuth,+ name: 'delete_pdf_pages',+ displayName: 'Delete Pages from PDF',+ description: 'Create a copy of a PDF without the pages you list.',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Creates a new PDF from a source PDF (public URL or file) with the listed pages removed; the source file is not changed. Page numbers start at 1 here (e.g. "1,3-4"). Costs 5 credits per page. Not idempotent: each call runs a new job and creates a new output.',+ idempotent: false,+ },+ outputSchema: pdfCoOutputSchemas.fileResult,+ props: {+ sourceUrl: pdfCoProps.sourceUrl(),+ sourceFile: pdfCoProps.sourceFile(),+ pages: Property.ShortText({+ displayName: 'Pages to Delete',+ description: 'Pages to remove, comma-separated. The first page is 1 (not 0). Example: "1,3-4" or "5-" for page 5 to the end.',+ required: true,+ }),+ ...pdfCoProps.httpAuth(),+ ...pdfCoProps.output(),+ },+ async run({ auth, propsValue, files }) {+ const apiKey = pdfCoClient.apiKeyOf(auth);+ const pages = propsValue.pages.trim();+ if (pages === '') {+ throw new Error('Pages is required, e.g. "1,3-4".');+ }+ const url = await pdfCoFiles.resolveSource({ apiKey, url: propsValue.sourceUrl, file: propsValue.sourceFile });+ return pdfCoJobs.runFileAction({+ apiKey,+ files,+ path: '/v1/pdf/edit/delete-pages',+ body: { url, pages },+ common: propsValue,+ });+ },+});diff --git a/packages/pieces/community/pdf-co/src/lib/actions/delete-text-from-pdf.ts b/packages/pieces/community/pdf-co/src/lib/actions/delete-text-from-pdf.tsnew file mode 100644index 00000000000..ea0055de310--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/actions/delete-text-from-pdf.ts@@ -0,0 +1,71 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../auth';+import { pdfCoClient } from '../common/client';+import { pdfCoFiles } from '../common/files';+import { pdfCoJobs } from '../common/jobs';+import { pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';++export const deleteTextFromPdf = createAction({+ auth: pdfCoAuth,+ name: 'delete_text_from_pdf',+ displayName: 'Delete (Redact) Text in PDF',+ description: 'Create a copy of a PDF with the given words or patterns removed.',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Creates a copy of a PDF (public URL or file) with every match of the given texts or regular expressions removed, e.g. to redact names or numbers; the source file is not changed. Pages start at 0. Costs 21 credits per page. Not idempotent: each call runs a new job and creates a new output.',+ idempotent: false,+ },+ outputSchema: pdfCoOutputSchemas.fileResult,+ props: {+ sourceUrl: pdfCoProps.sourceUrl(),+ sourceFile: pdfCoProps.sourceFile(),+ searchStrings: Property.Array({+ displayName: 'Text to Remove',+ description: 'Words, phrases or (with Regular Expressions on) patterns to delete.',+ required: true,+ }),+ caseSensitive: Property.Checkbox({ displayName: 'Case Sensitive', required: false, defaultValue: true }),+ regex: Property.Checkbox({ displayName: 'Use Regular Expressions', required: false, defaultValue: false }),+ replacementLimit: Property.Number({+ displayName: 'Max Matches per Text',+ description: 'Maximum matches to remove for each text. Leave empty or 0 to remove every match.',+ required: false,+ }),+ pages: pdfCoProps.pages({ base: 0 }),+ ...pdfCoProps.password(),+ ...pdfCoProps.httpAuth(),+ ...pdfCoProps.output(),+ },+ async run({ auth, propsValue, files }) {+ const apiKey = pdfCoClient.apiKeyOf(auth);+ const searchStrings = (Array.isArray(propsValue.searchStrings) ? propsValue.searchStrings : [])+ .map((item) => String(item ?? ''))+ .filter((item) => item !== '');+ if (searchStrings.length === 0) {+ throw new Error('Add at least one text to remove.');+ }+ const limit = propsValue.replacementLimit;+ if (limit !== undefined && limit !== null && (!Number.isInteger(Number(limit)) || Number(limit) < 0)) {+ throw new Error('Max Matches per Text must be a whole number of 0 or more.');+ }+ const pages = pdfCoFiles.nonEmptyString(propsValue.pages);+ const url = await pdfCoFiles.resolveSource({ apiKey, url: propsValue.sourceUrl, file: propsValue.sourceFile });+ return pdfCoJobs.runFileAction({+ apiKey,+ files,+ path: '/v1/pdf/edit/delete-text',+ body: {+ url,+ searchStrings,+ caseSensitive: propsValue.caseSensitive !== false,+ regex: propsValue.regex === true,+ ...(limit === undefined || limit === null ? {} : { replacementLimit: Number(limit) }),+ ...(pages === undefined ? {} : { pages: pages.trim() }),+ },+ common: propsValue,+ });+ },+});diff --git a/packages/pieces/community/pdf-co/src/lib/actions/extract-tables-from-pdf.ts b/packages/pieces/community/pdf-co/src/lib/actions/extract-tables-from-pdf.tsindex 4428219262f..3f93b66c826 100644--- a/packages/pieces/community/pdf-co/src/lib/actions/extract-tables-from-pdf.ts+++ b/packages/pieces/community/pdf-co/src/lib/actions/extract-tables-from-pdf.ts@@ -1,164 +1,76 @@-import { Property, createAction } from "@activepieces/pieces-framework";-import { httpClient, HttpMethod, HttpError } from "@activepieces/pieces-common";-import { PdfCoErrorResponse } from "../common/types"; // Use common error response type+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';import { pdfCoAuth } from '../auth';-import { BASE_URL, commonProps } from "../common/props";-// Interface for the Document Parser API request body-interface PdfDocumentParserRequestBody {- url: string;- templateId: string; // Making this required for table extraction- async: boolean;- inline: boolean; // Set to true to get data in response- outputFormat?: 'JSON' | 'CSV' | 'XML'; // Keep JSON for this action- name?: string;- pages?: string;- password?: string;- expiration?: number;- profiles?: Record<string, unknown>;- httpusername?: string;- httppassword?: string;-}--// Interface for the structure within the successful response's 'body' field-interface PdfDocumentParserResult {- objects: Array<{- name: string;- objectType: 'field' | 'table' | string; // Can be field, table, etc.- value?: unknown; // For fields- rows?: unknown[][]; // For tables- pageIndex?: number;- rectangle?: number[];- [key: string]: unknown; // Allow other properties- }>;- templateName: string;- templateVersion: string;- timestamp: string;-}--// Interface for the overall successful response from the Document Parser endpoint-interface PdfDocumentParserSuccessResponse {- body: PdfDocumentParserResult;- pageCount: number;- error: false;- status: number;- name: string; // Name of the generated output (e.g., sample-invoice.json)- remainingCredits: number;- credits: number;- url?: string; // URL if inline=false-}+import { pdfCoClient } from '../common/client';+import { commonProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';export const extractTablesFromPdf = createAction({- name: 'extract_tables_from_pdf',- classification: 'READ',- displayName: 'Extract Tables from PDF (using Template)',- description: 'Extracts table data from a PDF using a predefined PDF.co Document Parser template.',- audience: 'both',- aiMetadata: {- description:- 'Extracts table data from a source PDF (referenced by URL) using a predefined PDF.co Document Parser template; requires a Template ID created beforehand in the PDF.co dashboard. Use when an agent needs structured tables from a document whose layout a template already describes. The call only reads the input and returns the parsed tables, so it is idempotent.',- idempotent: true,- },- auth: pdfCoAuth, // Inherits auth from the piece- props: {- url: Property.ShortText({- displayName: 'Source PDF URL',- description: 'URL of the PDF file to extract tables from.',- required: true,- }),- templateId: Property.ShortText({- displayName: 'Template ID',- description: 'The ID of your Document Parser template (created in PDF.co dashboard) designed to extract the table(s).',- required: true,- }),- pages: Property.ShortText({- displayName: 'Pages',- description: 'Comma-separated page numbers or ranges (e.g., "0,2,5-10"). Overrides template settings if provided.',- required: false,- }),- profiles: Property.Json({- displayName: 'Profiles',- description: 'JSON object for additional configurations.',- required: false,- }),- ...commonProps- },- async run(context) {- const { auth, propsValue } = context;- const {- url,- templateId,- pages,- pdfPassword,- fileName,- httpPassword,- httpUsername,- expiration,- profiles- } = propsValue;-- const requestBody: PdfDocumentParserRequestBody = {- url: url,- templateId: templateId,- httppassword:httpPassword,- httpusername:httpUsername,- async: false,- inline: true, // Get the parsed data directly- outputFormat: 'JSON', // We want JSON to process tables- };-- if (pages !== undefined && pages !== '') requestBody.pages = pages;- if (pdfPassword !== undefined && pdfPassword !== '') requestBody.password = pdfPassword;- if (fileName !== undefined && fileName !== '') requestBody.name = fileName;- if (expiration !== undefined) requestBody.expiration = expiration;- if (profiles !== undefined && typeof profiles === 'object' && profiles !== null) {- requestBody.profiles = profiles as Record<string, unknown>;- }-- try {- const response = await httpClient.sendRequest<PdfDocumentParserSuccessResponse | PdfCoErrorResponse>({- method: HttpMethod.POST,- url: `${BASE_URL}/pdf/documentparser`,- headers: {- 'x-api-key': auth.secret_text,- 'Content-Type': 'application/json',- },- body: requestBody,- });-- if (response.body.error) {- const errorBody = response.body as PdfCoErrorResponse;- let errorMessage = `PDF.co API Error (Extract Tables): Status ${errorBody.status}.`;- if (errorBody.message) {- errorMessage += ` Message: ${errorBody.message}.`;- } else {- errorMessage += ` An unspecified error occurred.`;- }- errorMessage += ` Raw response: ${JSON.stringify(errorBody)}`;- throw new Error(errorMessage);- }-- const successBody = response.body as PdfDocumentParserSuccessResponse;-- // Filter the results to return only table objects- const tables = successBody.body.objects.filter(obj => obj.objectType === 'table');-- return {- extractedTables: tables, // Array of table objects found by the template- templateNameUsed: successBody.body.templateName,- };-- } catch (error) {- if (error instanceof HttpError) {- const responseBody = error.response?.body as (PdfCoErrorResponse | undefined);- let detailedMessage = `HTTP Error calling PDF.co API (Extract Tables): ${error.message}.`;- if (responseBody && responseBody.message) {- detailedMessage += ` Server message: ${responseBody.message}.`;- } else if (responseBody) {- detailedMessage += ` Server response: ${JSON.stringify(responseBody)}.`;- }- throw new Error(detailedMessage);- }- throw error;- }- },+ name: 'extract_tables_from_pdf',+ classification: 'READ',+ displayName: 'Extract Tables from PDF (using Template)',+ description: 'Extracts table data from a PDF using a predefined PDF.co Document Parser template.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Extracts table data from a source PDF (referenced by URL) using a predefined PDF.co Document Parser template; requires a Template ID created beforehand in the PDF.co dashboard. Agents should use Parse Document (AI), which also returns the template fields. Read-only and idempotent (consumes credits).',+ idempotent: true,+ },+ auth: pdfCoAuth,+ outputSchema: pdfCoOutputSchemas.extractTables,+ props: {+ url: Property.ShortText({+ displayName: 'Source PDF URL',+ description: 'URL of the PDF file to extract tables from.',+ required: true,+ }),+ templateId: Property.ShortText({+ displayName: 'Template ID',+ description: 'The ID of your Document Parser template (created in PDF.co dashboard) designed to extract the table(s).',+ required: true,+ }),+ pages: Property.ShortText({+ displayName: 'Pages',+ description: 'Comma-separated page indexes or ranges (first page is 0), e.g. "0,2,5-10". Overrides template settings if provided.',+ required: false,+ }),+ profiles: Property.Json({+ displayName: 'Profiles',+ description: 'JSON object for additional configurations.',+ required: false,+ }),+ ...commonProps,+ },+ async run({ auth, propsValue }) {+ const { url, templateId, pages, pdfPassword, fileName, httpPassword, httpUsername, expiration, profiles } = propsValue;+ const text = (value: unknown): value is string => typeof value === 'string' && value !== '';+ const serialized = pdfCoClient.serializeProfiles(profiles);+ const response = pdfCoClient.readRecord(+ await pdfCoClient.request<unknown>({+ apiKey: pdfCoClient.apiKeyOf(auth),+ method: HttpMethod.POST,+ path: '/v1/pdf/documentparser',+ body: {+ url,+ templateId,+ httppassword: httpPassword,+ httpusername: httpUsername,+ async: false,+ inline: true,+ outputFormat: 'JSON',+ ...(text(pages) ? { pages } : {}),+ ...(text(pdfPassword) ? { password: pdfPassword } : {}),+ ...(text(fileName) ? { name: fileName } : {}),+ ...(expiration === undefined ? {} : { expiration }),+ ...(serialized === undefined ? {} : { profiles: serialized }),+ },+ }),+ );+ const parsed = pdfCoClient.readRecord(response['body']);+ const objects = Array.isArray(parsed['objects']) ? parsed['objects'] : [];+ return {+ extractedTables: objects.filter((item) => pdfCoClient.readRecord(item)['objectType'] === 'table'),+ templateNameUsed: parsed['templateName'],+ };+ },});diff --git a/packages/pieces/community/pdf-co/src/lib/actions/extract-text-from-pdf.ts b/packages/pieces/community/pdf-co/src/lib/actions/extract-text-from-pdf.tsindex 074b5ba0cd1..2267b601e20 100644--- a/packages/pieces/community/pdf-co/src/lib/actions/extract-text-from-pdf.ts+++ b/packages/pieces/community/pdf-co/src/lib/actions/extract-text-from-pdf.ts@@ -1,135 +1,80 @@-import { Property, createAction } from "@activepieces/pieces-framework";-import { httpClient, HttpMethod, HttpError } from "@activepieces/pieces-common";+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';import { pdfCoAuth } from '../auth';-import { BASE_URL, commonProps } from "../common/props";--interface PdfCoExtractTextSuccessResponse {- body: string; // The extracted text content- pageCount: number;- error: false;- status: number;- name: string; // Output file name (e.g., sample.txt)- remainingCredits: number;- credits: number;- url?: string; // URL to output file if inline=false-}--// Define a type for the expected error response body (can use common one if it matches)-interface PdfCoErrorResponse {- error: true;- status: number;- message?: string;- [key: string]: unknown;-}--// Interface for the request body-interface PdfConvertToTextSimpleRequestBody {- url: string;- async: boolean;- inline: boolean; // Keep true to get text directly in response body- name?: string;- pages?: string;- password?: string;- httpusername?: string;- httppassword?: string;-}+import { pdfCoClient } from '../common/client';+import { commonProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';export const extractTextFromPdf = createAction({- name: 'extract_text_from_pdf',- classification: 'READ',- displayName: 'Extract Plain Text from PDF',- description: 'Extracts plain text content from a PDF document.',- audience: 'both',- aiMetadata: {- description:- 'Extracts plain text content from a source PDF (referenced by URL), optionally limited to specific pages. Use when an agent needs the raw text of a document for reading or downstream processing. The call only reads the input and returns the text directly, so it is idempotent.',- idempotent: true,- },- auth: pdfCoAuth,- props: {- url: Property.ShortText({- displayName: 'Source PDF URL',- description: 'URL of the PDF file to extract text from.',- required: true,- }),- pages: Property.ShortText({- displayName: 'Pages',- description: 'Comma-separated page numbers or ranges (e.g., "0,2,5-10"). Leave empty for all pages.',- required: false,- }),- password: commonProps.pdfPassword,- outputName: commonProps.fileName,- httpUsername:commonProps.httpUsername,- httpPassword:commonProps.httpPassword- },- async run(context) {- const { auth, propsValue } = context;- const {- url,- pages,- password,- outputName,- httpPassword,- httpUsername- } = propsValue;-- const requestBody: PdfConvertToTextSimpleRequestBody = {- url: url,- async: false,- httpusername:httpUsername,- httppassword:httpPassword,- inline: true, // Get text directly in response.body.body- };-- if (pages !== undefined && pages !== '') requestBody.pages = pages;- if (password !== undefined && password !== '') requestBody.password = password;- if (outputName !== undefined && outputName !== '') requestBody.name = outputName;-- try {- const response = await httpClient.sendRequest<PdfCoExtractTextSuccessResponse | PdfCoErrorResponse>({- method: HttpMethod.POST,- url: `${BASE_URL}/pdf/convert/to/text-simple`,- headers: {- 'x-api-key': auth.secret_text,- 'Content-Type': 'application/json',- },- body: requestBody,- });-- if (response.body.error) {- const errorBody = response.body as PdfCoErrorResponse;- let errorMessage = `PDF.co API Error (Extract Text): Status ${errorBody.status}.`;- if (errorBody.message) {- errorMessage += ` Message: ${errorBody.message}.`;- } else {- errorMessage += ` An unspecified error occurred.`;- }- errorMessage += ` Raw response: ${JSON.stringify(errorBody)}`;- throw new Error(errorMessage);- }-- const successBody = response.body as PdfCoExtractTextSuccessResponse;-- return {- extractedText: successBody.body,- pageCount: successBody.pageCount,- outputName: successBody.name,- creditsUsed: successBody.credits,- remainingCredits: successBody.remainingCredits,- };-- } catch (error) {- if (error instanceof HttpError) {- const responseBody = error.response?.body as (PdfCoErrorResponse | undefined);- let detailedMessage = `HTTP Error calling PDF.co API (Extract Text): ${error.message}.`;- if (responseBody && responseBody.message) {- detailedMessage += ` Server message: ${responseBody.message}.`;- } else if (responseBody) {- detailedMessage += ` Server response: ${JSON.stringify(responseBody)}.`;- }- throw new Error(detailedMessage);- }- throw error;- }- },+ name: 'extract_text_from_pdf',+ classification: 'READ',+ displayName: 'Extract Plain Text from PDF',+ description: 'Extracts plain text content from a PDF document.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Extracts the text of a source PDF (referenced by URL), optionally limited to specific pages (first page is 0). By default it reads the embedded text (4 credits per page); turn on OCR for scanned documents or layout-preserving text (21 credits per page). Use when an agent needs the raw text of a document. Read-only and idempotent.',+ idempotent: true,+ },+ auth: pdfCoAuth,+ outputSchema: pdfCoOutputSchemas.extractText,+ props: {+ url: Property.ShortText({+ displayName: 'Source PDF URL',+ description: 'URL of the PDF file to extract text from.',+ required: true,+ }),+ pages: Property.ShortText({+ displayName: 'Pages',+ description: 'Comma-separated page indexes or ranges (first page is 0), e.g. "0,2,5-10". Leave empty for all pages.',+ required: false,+ }),+ password: commonProps.pdfPassword,+ outputName: commonProps.fileName,+ httpUsername: commonProps.httpUsername,+ httpPassword: commonProps.httpPassword,+ useOcr: Property.Checkbox({+ displayName: 'Use OCR (Scanned PDFs)',+ description: 'Read scanned pages and keep the layout. Costs 21 credits per page instead of 4.',+ required: false,+ defaultValue: false,+ }),+ lang: Property.ShortText({+ displayName: 'OCR Language',+ description: 'Only with OCR: language of the text, e.g. "eng", "deu", or "eng+deu". Default "eng".',+ required: false,+ }),+ },+ async run({ auth, propsValue }) {+ const { url, pages, password, outputName, httpPassword, httpUsername, useOcr, lang } = propsValue;+ const text = (value: unknown): value is string => typeof value === 'string' && value !== '';+ if (text(lang) && useOcr !== true) {+ throw new Error('OCR Language only applies when "Use OCR" is on.');+ }+ const body = pdfCoClient.readRecord(+ await pdfCoClient.request<unknown>({+ apiKey: pdfCoClient.apiKeyOf(auth),+ method: HttpMethod.POST,+ path: useOcr === true ? '/v1/pdf/convert/to/text' : '/v1/pdf/convert/to/text-simple',+ body: {+ url,+ async: false,+ httpusername: httpUsername,+ httppassword: httpPassword,+ inline: true,+ ...(text(pages) ? { pages } : {}),+ ...(text(password) ? { password } : {}),+ ...(text(outputName) ? { name: outputName } : {}),+ ...(useOcr === true && text(lang) ? { lang } : {}),+ },+ }),+ );+ return {+ extractedText: body['body'],+ pageCount: body['pageCount'],+ outputName: body['name'],+ creditsUsed: body['credits'],+ remainingCredits: body['remainingCredits'],+ };+ },});diff --git a/packages/pieces/community/pdf-co/src/lib/actions/fill-pdf-form.ts b/packages/pieces/community/pdf-co/src/lib/actions/fill-pdf-form.tsnew file mode 100644index 00000000000..d64c2fe578b--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/actions/fill-pdf-form.ts@@ -0,0 +1,85 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../auth';+import { pdfCoClient } from '../common/client';+import { pdfCoFiles } from '../common/files';+import { pdfCoJobs } from '../common/jobs';+import { pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';++export const fillPdfForm = createAction({+ auth: pdfCoAuth,+ name: 'fill_pdf_form',+ displayName: 'Fill PDF Form',+ description: 'Fill the form fields of a fillable PDF by field name.',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Fills existing form fields of a fillable PDF (public URL or file) by exact field name, optionally flattening the result so it can no longer be edited. Get the exact names from Get PDF Form Fields; checkboxes take "true". Costs 21 credits per page. Not idempotent: each call runs a new job and creates a new output.',+ idempotent: false,+ },+ outputSchema: pdfCoOutputSchemas.fileResult,+ props: {+ sourceUrl: pdfCoProps.sourceUrl(),+ sourceFile: pdfCoProps.sourceFile(),+ fields: Property.Array({+ displayName: 'Fields',+ description: 'One entry per form field. Use Get PDF Form Fields to see the exact names.',+ required: true,+ properties: {+ fieldName: Property.ShortText({ displayName: 'Field Name', description: 'Exact form field name.', required: true }),+ text: Property.ShortText({+ displayName: 'Value',+ description: 'Text to enter. For a checkbox use "true"; for a list or radio button use the option value.',+ required: true,+ }),+ pages: Property.ShortText({ displayName: 'Page', description: 'Page of the field (first page is 0). Optional.', required: false }),+ },+ }),+ flatten: Property.Checkbox({+ displayName: 'Flatten Form',+ description: 'Make the filled form read-only so values can no longer be changed.',+ required: false,+ defaultValue: false,+ }),+ ...pdfCoProps.password(),+ ...pdfCoProps.httpAuth(),+ ...pdfCoProps.output(),+ },+ async run({ auth, propsValue, files }) {+ const apiKey = pdfCoClient.apiKeyOf(auth);+ const fields = toFormFields(propsValue.fields);+ const url = await pdfCoFiles.resolveSource({ apiKey, url: propsValue.sourceUrl, file: propsValue.sourceFile });+ return pdfCoJobs.runFileAction({+ apiKey,+ files,+ path: '/v1/pdf/edit/add',+ body: {+ url,+ fields,+ ...(propsValue.flatten === true ? { profiles: JSON.stringify({ 'FlattenDocument()': [] }) } : {}),+ },+ common: propsValue,+ });+ },+});++export function toFormFields(value: unknown): FormField[] {+ const items = Array.isArray(value) ? value : [];+ if (items.length === 0) {+ throw new Error('Add at least one field to fill.');+ }+ return items.map((item, index) => {+ const record = pdfCoClient.readRecord(item);+ const fieldName = typeof record['fieldName'] === 'string' ? record['fieldName'].trim() : '';+ if (fieldName === '') {+ throw new Error(`Field #${index + 1} needs a field name.`);+ }+ const rawText = record['text'];+ const text = rawText === undefined || rawText === null ? '' : String(rawText);+ const pages = record['pages'] === undefined || record['pages'] === null ? '' : String(record['pages']).trim();+ return { fieldName, text, ...(pages === '' ? {} : { pages }) };+ });+}++export type FormField = { fieldName: string; text: string; pages?: string };diff --git a/packages/pieces/community/pdf-co/src/lib/actions/find-text-in-pdf.ts b/packages/pieces/community/pdf-co/src/lib/actions/find-text-in-pdf.tsnew file mode 100644index 00000000000..9837e1fc0ed--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/actions/find-text-in-pdf.ts@@ -0,0 +1,99 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../auth';+import { pdfCoClient } from '../common/client';+import { pdfCoFiles } from '../common/files';+import { pdfCoJobs } from '../common/jobs';+import { pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';++const MODES = ['SmartMatch', 'ExactMatch', 'None'];++export const findTextInPdf = createAction({+ auth: pdfCoAuth,+ name: 'find_text_in_pdf',+ displayName: 'Find Text in PDF',+ description: 'Find every place a word, phrase or pattern appears in a PDF.',+ audience: 'both',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Finds every occurrence of a text or regular expression in a PDF (public URL or file) and returns each match\'s text, page (0-based) and coordinates. Use to locate where to stamp text or images, or to check a document contains a phrase. Costs 35 credits per page. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: pdfCoOutputSchemas.findText,+ props: {+ sourceUrl: pdfCoProps.sourceUrl(),+ sourceFile: pdfCoProps.sourceFile(),+ searchString: Property.ShortText({+ displayName: 'Text to Find',+ description: 'The word or phrase to look for, or a regular expression when "Use Regular Expression" is on.',+ required: true,+ }),+ regexSearch: Property.Checkbox({+ displayName: 'Use Regular Expression',+ required: false,+ defaultValue: false,+ }),+ wordMatchingMode: Property.StaticDropdown({+ displayName: 'Word Matching',+ description: 'Smart Match (default) matches whole words flexibly; Exact Match needs the exact word; None matches any part of the text.',+ required: false,+ defaultValue: 'SmartMatch',+ options: {+ disabled: false,+ options: [+ { label: 'Smart Match (default)', value: 'SmartMatch' },+ { label: 'Exact Match', value: 'ExactMatch' },+ { label: 'None (substring)', value: 'None' },+ ],+ },+ }),+ pages: pdfCoProps.pages({ base: 0 }),+ ...pdfCoProps.inlineRead(),+ },+ async run({ auth, propsValue }) {+ const apiKey = pdfCoClient.apiKeyOf(auth);+ const searchString = propsValue.searchString;+ if (searchString.trim() === '') {+ throw new Error('Text to Find is required.');+ }+ const mode = pdfCoFiles.nonEmptyString(propsValue.wordMatchingMode);+ if (mode !== undefined && !MODES.includes(mode)) {+ throw new Error(`Word Matching must be one of ${MODES.join(', ')}.`);+ }+ const pages = pdfCoFiles.nonEmptyString(propsValue.pages);+ const url = await pdfCoFiles.resolveSource({ apiKey, url: propsValue.sourceUrl, file: propsValue.sourceFile });+ const body = await pdfCoJobs.runInline({+ apiKey,+ path: '/v1/pdf/find',+ body: {+ url,+ searchString,+ regexSearch: propsValue.regexSearch === true,+ inline: true,+ ...(mode === undefined ? {} : { wordMatchingMode: mode }),+ ...(pages === undefined ? {} : { pages: pages.trim() }),+ },+ common: propsValue,+ });+ const raw = body['body'];+ const matches = (Array.isArray(raw) ? raw : []).map((item) => {+ const match = pdfCoClient.readRecord(item);+ return {+ text: match['text'],+ page_index: match['pageIndex'],+ left: match['left'],+ top: match['top'],+ width: match['width'],+ height: match['height'],+ };+ });+ return {+ match_count: matches.length,+ matches,+ page_count: body['pageCount'],+ credits_used: body['credits'],+ remaining_credits: body['remainingCredits'],+ };+ },+});diff --git a/packages/pieces/community/pdf-co/src/lib/actions/generate-barcode.ts b/packages/pieces/community/pdf-co/src/lib/actions/generate-barcode.tsnew file mode 100644index 00000000000..29356f5b5d9--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/actions/generate-barcode.ts@@ -0,0 +1,66 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../auth';+import { pdfCoClient } from '../common/client';+import { pdfCoFiles } from '../common/files';+import { pdfCoJobs } from '../common/jobs';+import { BARCODE_TYPES, pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';++export const generateBarcode = createAction({+ auth: pdfCoAuth,+ name: 'generate_barcode',+ displayName: 'Generate Barcode Image',+ description: 'Create a QR code or barcode image for a value.',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Generates a QR code or barcode image (QR, DataMatrix, Code 128/39, PDF417, EAN-13, UPC-A) for a value and returns a temporary PNG link, optionally saving the file. Use Add Barcode to PDF to stamp one onto a document. Costs 7 credits per call. Not idempotent: each call creates a new image.',+ idempotent: false,+ },+ outputSchema: pdfCoOutputSchemas.fileResult,+ props: {+ value: Property.ShortText({+ displayName: 'Value',+ description: 'The text, number or link to encode.',+ required: true,+ }),+ type: Property.StaticDropdown({+ displayName: 'Barcode Type',+ required: true,+ defaultValue: 'QRCode',+ options: { disabled: false, options: BARCODE_TYPES },+ }),+ decorationImage: Property.ShortText({+ displayName: 'Logo URL',+ description: 'QR codes only: public link to a small logo placed in the middle.',+ required: false,+ }),+ ...pdfCoProps.output(),+ },+ async run({ auth, propsValue, files }) {+ const apiKey = pdfCoClient.apiKeyOf(auth);+ if (propsValue.value.trim() === '') {+ throw new Error('Value is required.');+ }+ if (!BARCODE_TYPES.some((option) => option.value === propsValue.type)) {+ throw new Error('Pick a barcode type from the list.');+ }+ const logo = pdfCoFiles.nonEmptyString(propsValue.decorationImage);+ if (logo !== undefined) {+ pdfCoFiles.validateSource({ url: logo, file: undefined, label: 'Logo' });+ }+ return pdfCoJobs.runFileAction({+ apiKey,+ files,+ path: '/v1/barcode/generate',+ body: {+ value: propsValue.value,+ type: propsValue.type,+ inline: false,+ ...(logo === undefined ? {} : { decorationImage: logo.trim() }),+ },+ common: propsValue,+ });+ },+});diff --git a/packages/pieces/community/pdf-co/src/lib/actions/get-credit-balance.ts b/packages/pieces/community/pdf-co/src/lib/actions/get-credit-balance.tsnew file mode 100644index 00000000000..c9e96a1d5e1--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/actions/get-credit-balance.ts@@ -0,0 +1,30 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../auth';+import { pdfCoClient } from '../common/client';+import { pdfCoOutputSchemas } from '../output-schemas';++export const getCreditBalance = createAction({+ auth: pdfCoAuth,+ name: 'get_credit_balance',+ displayName: 'Get Credit Balance',+ description: 'Get the number of PDF.co credits left on the account.',+ audience: 'both',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Returns the remaining PDF.co credits of the connected account. Use before a large batch to avoid "not enough credits" (402) failures. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: pdfCoOutputSchemas.creditBalance,+ props: {},+ async run({ auth }) {+ const body = await pdfCoClient.request<unknown>({+ apiKey: pdfCoClient.apiKeyOf(auth),+ method: HttpMethod.GET,+ path: '/v1/account/credit/balance',+ });+ const remaining = pdfCoClient.readRecord(body)['remainingCredits'];+ return { remaining_credits: typeof remaining === 'number' ? remaining : undefined };+ },+});diff --git a/packages/pieces/community/pdf-co/src/lib/actions/get-pdf-form-fields.ts b/packages/pieces/community/pdf-co/src/lib/actions/get-pdf-form-fields.tsnew file mode 100644index 00000000000..8db78b6378f--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/actions/get-pdf-form-fields.ts@@ -0,0 +1,54 @@+import { createAction } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../auth';+import { pdfCoClient } from '../common/client';+import { pdfCoFiles } from '../common/files';+import { pdfCoJobs } from '../common/jobs';+import { pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';++export const getPdfFormFields = createAction({+ auth: pdfCoAuth,+ name: 'get_pdf_form_fields',+ displayName: 'Get PDF Form Fields',+ description: 'List the fillable form fields of a PDF with their exact names.',+ audience: 'both',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Lists the fillable form fields of a PDF (public URL or file): exact field name, type, page (0-based), current value and position, so Fill PDF Form can target them by name. Costs 8 credits per call. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: pdfCoOutputSchemas.formFields,+ props: {+ sourceUrl: pdfCoProps.sourceUrl(),+ sourceFile: pdfCoProps.sourceFile(),+ ...pdfCoProps.inlineRead(),+ },+ async run({ auth, propsValue }) {+ const apiKey = pdfCoClient.apiKeyOf(auth);+ const url = await pdfCoFiles.resolveSource({ apiKey, url: propsValue.sourceUrl, file: propsValue.sourceFile });+ const body = await pdfCoJobs.runInline({ apiKey, path: '/v1/pdf/info/fields', body: { url }, common: propsValue });+ const info = pdfCoClient.readRecord(body['info']);+ const rawFields = pdfCoClient.readRecord(info['FieldsInfo'])['Fields'];+ const fields = (Array.isArray(rawFields) ? rawFields : []).map((raw) => {+ const field = pdfCoClient.readRecord(raw);+ return {+ field_name: field['FieldName'],+ type: field['Type'],+ value: field['Value'],+ page_index: field['PageIndex'],+ left: field['Left'],+ top: field['Top'],+ width: field['Width'],+ height: field['Height'],+ };+ });+ return {+ page_count: info['PageCount'],+ field_count: fields.length,+ fields,+ credits_used: body['credits'],+ remaining_credits: body['remainingCredits'],+ };+ },+});diff --git a/packages/pieces/community/pdf-co/src/lib/actions/get-pdf-info.ts b/packages/pieces/community/pdf-co/src/lib/actions/get-pdf-info.tsnew file mode 100644index 00000000000..df32f92a9c6--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/actions/get-pdf-info.ts@@ -0,0 +1,62 @@+import { createAction } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../auth';+import { pdfCoClient } from '../common/client';+import { pdfCoFiles } from '../common/files';+import { pdfCoJobs } from '../common/jobs';+import { pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';++export const getPdfInfo = createAction({+ auth: pdfCoAuth,+ name: 'get_pdf_info',+ displayName: 'Get PDF Info',+ description: 'Read a PDF\'s page count, metadata, page size and security settings.',+ audience: 'both',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Reads a PDF\'s metadata (public URL or file): page count, title, author, dates, page size, encryption and permission flags. Use to check the page count or protection before other steps. Costs 7 credits per page. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: pdfCoOutputSchemas.pdfInfo,+ props: {+ sourceUrl: pdfCoProps.sourceUrl(),+ sourceFile: pdfCoProps.sourceFile(),+ ...pdfCoProps.inlineRead(),+ },+ async run({ auth, propsValue }) {+ const apiKey = pdfCoClient.apiKeyOf(auth);+ const url = await pdfCoFiles.resolveSource({ apiKey, url: propsValue.sourceUrl, file: propsValue.sourceFile });+ const body = await pdfCoJobs.runInline({ apiKey, path: '/v1/pdf/info', body: { url }, common: propsValue });+ return flattenPdfInfo(body);+ },+});++export function flattenPdfInfo(body: Record<string, unknown>): Record<string, unknown> {+ const info = pdfCoClient.readRecord(body['info']);+ const rect = pdfCoClient.readRecord(info['PageRectangle']);+ return {+ page_count: info['PageCount'],+ title: info['Title'],+ author: info['Author'],+ subject: info['Subject'],+ keywords: info['Keywords'],+ creator: info['Creator'],+ producer: info['Producer'],+ creation_date: info['CreationDate'],+ modification_date: info['ModificationDate'],+ page_width: rect['Width'],+ page_height: rect['Height'],+ encrypted: info['Encrypted'],+ password_protected: info['PasswordProtected'],+ encryption_algorithm: info['EncryptionAlgorithm'],+ permission_printing: info['PermissionPrinting'],+ permission_modify_document: info['PermissionModifyDocument'],+ permission_content_extraction: info['PermissionContentExtraction'],+ permission_modify_annotations: info['PermissionModifyAnnotations'],+ permission_fill_forms: info['PermissionFillForms'],+ permission_assemble: info['PermissionAssemble'],+ credits_used: body['credits'],+ remaining_credits: body['remainingCredits'],+ };+}diff --git a/packages/pieces/community/pdf-co/src/lib/actions/index.ts b/packages/pieces/community/pdf-co/src/lib/actions/index.tsindex 50e8bcd9e54..7ad692b66a4 100644--- a/packages/pieces/community/pdf-co/src/lib/actions/index.ts+++ b/packages/pieces/community/pdf-co/src/lib/actions/index.ts@@ -6,3 +6,32 @@ export * from './extract-text-from-pdf';export * from './convert-pdf-to-structured-format';export * from './extract-tables-from-pdf';export * from './add-barcode-to-pdf';+export * from './get-credit-balance';+export * from './check-job-status';+export * from './upload-file';+export * from './merge-pdfs';+export * from './split-pdf';+export * from './delete-pdf-pages';+export * from './rotate-pdf-pages';+export * from './compress-pdf';+export * from './add-password-to-pdf';+export * from './remove-password-from-pdf';+export * from './make-pdf-searchable';+export * from './get-pdf-info';+export * from './get-pdf-form-fields';+export * from './find-text-in-pdf';+export * from './read-barcodes';+export * from './list-html-templates';+export * from './list-document-parser-templates';+export * from './parse-document';+export * from './parse-invoice-with-ai';+export * from './convert-pdf-to-image';+export * from './convert-url-to-pdf';+export * from './convert-document-to-pdf';+export * from './convert-html-template-to-pdf';+export * from './fill-pdf-form';+export * from './delete-text-from-pdf';+export * from './generate-barcode';+export * from './ai/convert-pdf';+export * from './ai/edit-pdf';+export * from './ai/parse-document';diff --git a/packages/pieces/community/pdf-co/src/lib/actions/list-document-parser-templates.ts b/packages/pieces/community/pdf-co/src/lib/actions/list-document-parser-templates.tsnew file mode 100644index 00000000000..a4d280808ec--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/actions/list-document-parser-templates.ts@@ -0,0 +1,30 @@+import { createAction } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../auth';+import { pdfCoClient } from '../common/client';+import { pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';++export const listDocumentParserTemplates = createAction({+ auth: pdfCoAuth,+ name: 'list_document_parser_templates',+ displayName: 'List Document Parser Templates',+ description: 'List the Document Parser templates on your PDF.co account.',+ audience: 'both',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Lists every Document Parser template (built-in system ones such as "Invoice Parser" and your own) with ID, title, type and description. Use to find the template ID for Parse Document with Template. Costs 2 credits per call. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: pdfCoOutputSchemas.templates,+ props: {},+ async run({ auth }) {+ const list = await pdfCoProps.listTemplates({ apiKey: pdfCoClient.apiKeyOf(auth), kind: 'documentParser' });+ return {+ template_count: list.templates.length,+ templates: list.templates.map(({ id, title, type, description }) => ({ id, title, type, description })),+ credits_used: list.credits_used,+ remaining_credits: list.remaining_credits,+ };+ },+});diff --git a/packages/pieces/community/pdf-co/src/lib/actions/list-html-templates.ts b/packages/pieces/community/pdf-co/src/lib/actions/list-html-templates.tsnew file mode 100644index 00000000000..3684e36579f--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/actions/list-html-templates.ts@@ -0,0 +1,25 @@+import { createAction } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../auth';+import { pdfCoClient } from '../common/client';+import { pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';++export const listHtmlTemplates = createAction({+ auth: pdfCoAuth,+ name: 'list_html_templates',+ displayName: 'List HTML Templates',+ description: 'List the HTML-to-PDF templates on your PDF.co account.',+ audience: 'both',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Lists every HTML-to-PDF template (built-in system ones and your own) with ID, title, type and sample JSON data. Use to find the template ID for Create PDF from HTML Template. Costs 2 credits per call. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: pdfCoOutputSchemas.htmlTemplates,+ props: {},+ async run({ auth }) {+ const list = await pdfCoProps.listTemplates({ apiKey: pdfCoClient.apiKeyOf(auth), kind: 'html' });+ return { template_count: list.templates.length, ...list };+ },+});diff --git a/packages/pieces/community/pdf-co/src/lib/actions/make-pdf-searchable.ts b/packages/pieces/community/pdf-co/src/lib/actions/make-pdf-searchable.tsnew file mode 100644index 00000000000..6c741d0d5e0--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/actions/make-pdf-searchable.ts@@ -0,0 +1,52 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../auth';+import { pdfCoClient } from '../common/client';+import { pdfCoFiles } from '../common/files';+import { pdfCoJobs } from '../common/jobs';+import { pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';++export const makePdfSearchable = createAction({+ auth: pdfCoAuth,+ name: 'make_pdf_searchable',+ displayName: 'Make PDF Searchable (OCR)',+ description: 'Run OCR on a scanned PDF so its text can be selected and searched.',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Runs OCR on a scanned PDF or image (public URL or file) and returns a copy with a selectable, searchable text layer. Use before text extraction on scans when Extract Text with OCR is not enough; pages start at 0. Costs 35 credits per page. Not idempotent: each call runs a new job and creates a new output.',+ idempotent: false,+ },+ outputSchema: pdfCoOutputSchemas.fileResult,+ props: {+ sourceUrl: pdfCoProps.sourceUrl(),+ sourceFile: pdfCoProps.sourceFile(),+ lang: Property.ShortText({+ displayName: 'OCR Language',+ description: 'Language of the text, e.g. "eng", "deu", or "eng+deu" for several. Default "eng".',+ required: false,+ }),+ pages: pdfCoProps.pages({ base: 0 }),+ ...pdfCoProps.password(),+ ...pdfCoProps.httpAuth(),+ ...pdfCoProps.output(),+ },+ async run({ auth, propsValue, files }) {+ const apiKey = pdfCoClient.apiKeyOf(auth);+ const lang = pdfCoFiles.nonEmptyString(propsValue.lang);+ const pages = pdfCoFiles.nonEmptyString(propsValue.pages);+ const url = await pdfCoFiles.resolveSource({ apiKey, url: propsValue.sourceUrl, file: propsValue.sourceFile });+ return pdfCoJobs.runFileAction({+ apiKey,+ files,+ path: '/v1/pdf/makesearchable',+ body: {+ url,+ ...(lang === undefined ? {} : { lang: lang.trim() }),+ ...(pages === undefined ? {} : { pages: pages.trim() }),+ },+ common: propsValue,+ });+ },+});diff --git a/packages/pieces/community/pdf-co/src/lib/actions/merge-pdfs.ts b/packages/pieces/community/pdf-co/src/lib/actions/merge-pdfs.tsnew file mode 100644index 00000000000..ece74941287--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/actions/merge-pdfs.ts@@ -0,0 +1,79 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../auth';+import { pdfCoClient } from '../common/client';+import { pdfCoFiles } from '../common/files';+import { pdfCoJobs } from '../common/jobs';+import { pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';++export const mergePdfs = createAction({+ auth: pdfCoAuth,+ name: 'merge_pdfs',+ displayName: 'Merge PDFs',+ description: 'Combine two or more PDFs into one PDF, in the order given.',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Merges two or more PDFs, given as public URLs and/or files, into one new PDF in the order listed (URLs first, then files) and returns a temporary link, optionally saving the file. Use to combine documents; convert Word, Excel or images to PDF first. Costs 2 credits per page. Not idempotent: each call runs a new job and creates a new output.',+ idempotent: false,+ },+ outputSchema: pdfCoOutputSchemas.fileResult,+ props: {+ sourceUrls: Property.Array({+ displayName: 'PDF URLs',+ description: 'Public links to the PDFs, in merge order. These come before any files below.',+ required: false,+ }),+ sourceFiles: Property.Array({+ displayName: 'PDF Files',+ description: 'PDFs from earlier steps, merged after the URLs. Each file is uploaded to PDF.co first (7 credits each).',+ required: false,+ properties: {+ file: Property.File({ displayName: 'PDF File', required: true }),+ },+ }),+ ...pdfCoProps.httpAuth(),+ ...pdfCoProps.output(),+ },+ async run({ auth, propsValue, files }) {+ const apiKey = pdfCoClient.apiKeyOf(auth);+ const urls = listOfUrls(propsValue.sourceUrls);+ const fileItems = listOfFiles(propsValue.sourceFiles);+ if (urls.length + fileItems.length < 2) {+ throw new Error('Give at least two PDFs to merge (URLs, files, or both).');+ }+ urls.forEach((url, index) => pdfCoFiles.validateSource({ url, file: undefined, label: `PDF URL #${index + 1}` }));+ const uploaded: string[] = [];+ for (const file of fileItems) {+ uploaded.push(await pdfCoFiles.uploadFile({ apiKey, file }));+ }+ return pdfCoJobs.runFileAction({+ apiKey,+ files,+ path: '/v1/pdf/merge',+ body: { url: [...urls.map((url) => url.trim()), ...uploaded].join(',') },+ common: propsValue,+ });+ },+});++function listOfUrls(value: unknown): string[] {+ if (!Array.isArray(value)) {+ return [];+ }+ return value.map((item) => (typeof item === 'string' ? item : String(item ?? ''))).filter((item) => item.trim() !== '');+}++function listOfFiles(value: unknown): unknown[] {+ if (!Array.isArray(value)) {+ return [];+ }+ return value.map((item, index) => {+ const file = pdfCoClient.readRecord(item)['file'];+ if (!pdfCoFiles.isFileLike(file)) {+ throw new Error(`PDF File #${index + 1} could not be read. Pick a file from an earlier step.`);+ }+ return file;+ });+}diff --git a/packages/pieces/community/pdf-co/src/lib/actions/parse-document.ts b/packages/pieces/community/pdf-co/src/lib/actions/parse-document.tsnew file mode 100644index 00000000000..5b1a6c14517--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/actions/parse-document.ts@@ -0,0 +1,90 @@+import { createAction } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../auth';+import { pdfCoClient } from '../common/client';+import { pdfCoFiles } from '../common/files';+import { pdfCoJobs } from '../common/jobs';+import { pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';++export const parseDocument = createAction({+ auth: pdfCoAuth,+ name: 'parse_document',+ displayName: 'Parse Document with Template',+ description: 'Extract the fields and tables a Document Parser template defines from a PDF or scan.',+ audience: 'both',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Extracts every field and table defined by a PDF.co Document Parser template from a PDF or scan (public URL or file), e.g. invoices, statements or orders, returning fields as name/value pairs plus tables. Requires a template; use Parse Invoice with AI for invoice layouts without one. Costs 42 credits per page. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: pdfCoOutputSchemas.parseDocument,+ props: {+ sourceUrl: pdfCoProps.sourceUrl(),+ sourceFile: pdfCoProps.sourceFile(),+ templateId: pdfCoProps.templateDropdown({ kind: 'documentParser', required: true }),+ pages: pdfCoProps.pages({ base: 0 }),+ ...pdfCoProps.inlineRead(),+ },+ async run({ auth, propsValue }) {+ const apiKey = pdfCoClient.apiKeyOf(auth);+ const templateId = parseTemplateId(propsValue.templateId);+ const pages = pdfCoFiles.nonEmptyString(propsValue.pages);+ const url = await pdfCoFiles.resolveSource({ apiKey, url: propsValue.sourceUrl, file: propsValue.sourceFile });+ const body = await pdfCoJobs.runInline({+ apiKey,+ path: '/v1/pdf/documentparser',+ body: { url, templateId, inline: true, outputFormat: 'JSON', ...(pages === undefined ? {} : { pages: pages.trim() }) },+ common: propsValue,+ });+ return flattenParserResult(body);+ },+});++export function parseTemplateId(value: unknown): number {+ const id = Number(typeof value === 'string' ? value.trim() : value);+ if (!Number.isInteger(id) || id <= 0) {+ throw new Error('Template ID must be a positive whole number, e.g. 1 for the built-in Invoice Parser.');+ }+ return id;+}++export function flattenParserResult(body: Record<string, unknown>): ParsedDocument {+ const result = pdfCoClient.readRecord(body['body']);+ const objects = Array.isArray(result['objects']) ? result['objects'] : [];+ const records = objects.map((item) => pdfCoClient.readRecord(item));+ const fields = Object.fromEntries(+ records+ .filter((object) => object['objectType'] === 'field' && typeof object['name'] === 'string')+ .map((object) => [String(object['name']), object['value']]),+ );+ const tables = records+ .filter((object) => object['objectType'] === 'table')+ .map((object) => ({ name: object['name'], page_index: object['pageIndex'] ?? firstCellPageIndex(object['rows']), rows: object['rows'] }));+ return {+ template_name: result['templateName'],+ fields,+ tables,+ page_count: body['pageCount'],+ credits_used: body['credits'],+ remaining_credits: body['remainingCredits'],+ };+}++function firstCellPageIndex(rows: unknown): unknown {+ if (!Array.isArray(rows) || rows.length === 0) {+ return undefined;+ }+ const cells = Object.values(pdfCoClient.readRecord(rows[0]));+ const pageIndex = cells.map((cell) => pdfCoClient.readRecord(cell)['pageIndex']).find((value) => typeof value === 'number');+ return pageIndex;+}++export type ParsedDocument = {+ template_name: unknown;+ fields: Record<string, unknown>;+ tables: { name: unknown; page_index: unknown; rows: unknown }[];+ page_count: unknown;+ credits_used: unknown;+ remaining_credits: unknown;+};diff --git a/packages/pieces/community/pdf-co/src/lib/actions/parse-invoice-with-ai.ts b/packages/pieces/community/pdf-co/src/lib/actions/parse-invoice-with-ai.tsnew file mode 100644index 00000000000..d0c313916d2--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/actions/parse-invoice-with-ai.ts@@ -0,0 +1,129 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../auth';+import { pdfCoClient } from '../common/client';+import { pdfCoFiles } from '../common/files';+import { JobResult, pdfCoJobs } from '../common/jobs';+import { pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';++export const parseInvoiceWithAi = createAction({+ auth: pdfCoAuth,+ name: 'parse_invoice_with_ai',+ displayName: 'Parse Invoice with AI',+ description: 'Extract vendor, customer, totals, dates and line items from an invoice of any layout.',+ audience: 'both',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Uses PDF.co\'s AI Invoice Parser to extract vendor, customer, invoice number, dates, totals, tax and line items from an invoice PDF of any layout (public URL or file), no template needed. The job runs in the background and is checked for up to 4 minutes; if still running, status "working" and the job ID are returned: call this action again with only that Job ID to get the fields without starting a new parse. Costs 100 credits per page. Not idempotent: AI output can differ between runs.',+ idempotent: false,+ },+ outputSchema: pdfCoOutputSchemas.invoice,+ props: {+ sourceUrl: pdfCoProps.sourceUrl({ description: 'Public link to the invoice PDF (one invoice per file). Fill this or pick a file below, not both.' }),+ sourceFile: pdfCoProps.sourceFile(),+ customFields: Property.Array({+ displayName: 'Custom Fields',+ description: 'Extra fields to extract, in camelCase, e.g. storeNumber, deliveryDate.',+ required: false,+ }),+ lineItemStructure: Property.Json({+ displayName: 'Line Item Structure',+ description: 'Optional shape for each line item: field name to "string" or "number", e.g. {"description":"string","quantity":"number"}.',+ required: false,+ }),+ jobId: Property.ShortText({+ displayName: 'Job ID',+ description: 'To read an invoice job that returned status "working", paste its Job ID. The source and fields above are then not used and no new parse is started.',+ required: false,+ }),+ },+ async run({ auth, propsValue }) {+ const apiKey = pdfCoClient.apiKeyOf(auth);+ const pendingJobId = pdfCoFiles.nonEmptyString(propsValue.jobId?.trim());+ if (pendingJobId !== undefined) {+ return invoiceOutput(await pdfCoJobs.waitForJob({ apiKey, jobId: pendingJobId, checkImmediately: true }));+ }+ const customFields = (Array.isArray(propsValue.customFields) ? propsValue.customFields : [])+ .map((field) => String(field ?? '').trim())+ .filter((field) => field !== '');+ const invalidField = customFields.find((field) => !/^[A-Za-z][A-Za-z0-9]*$/.test(field));+ if (invalidField !== undefined) {+ throw new Error(`Custom field "${invalidField}" must be one camelCase word, e.g. deliveryDate.`);+ }+ const structure = validateStructure(propsValue.lineItemStructure);+ const url = await pdfCoFiles.resolveSource({ apiKey, url: propsValue.sourceUrl, file: propsValue.sourceFile });+ const result = await pdfCoJobs.runJob({+ apiKey,+ path: '/v1/ai-invoice-parser',+ body: {+ url,+ ...(customFields.length === 0 ? {} : { customField: customFields.join(',') }),+ ...(structure === undefined ? {} : { lineItemStructure: structure }),+ },+ background: true,+ alwaysAsync: true,+ });+ return invoiceOutput(result);+ },+});++async function invoiceOutput(result: JobResult): Promise<Record<string, unknown>> {+ if (result.status === 'working') {+ return {+ status: 'working',+ job_id: result.jobId,+ credits_used: result.body['credits'],+ remaining_credits: result.body['remainingCredits'],+ };+ }+ const invoice = await invoiceBody(result.body);+ return { status: 'success', job_id: result.jobId, ...flattenInvoice(invoice), page_count: result.body['pageCount'], credits_used: result.body['credits'], remaining_credits: result.body['remainingCredits'] };+}++function validateStructure(value: unknown): Record<string, string> | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ const record = pdfCoClient.readRecord(value);+ const entries = Object.entries(record);+ if (entries.length === 0 || entries.some(([, type]) => type !== 'string' && type !== 'number')) {+ throw new Error('Line Item Structure must be a JSON object whose values are "string" or "number".');+ }+ return Object.fromEntries(entries.map(([key, type]) => [key, String(type)]));+}++async function invoiceBody(body: Record<string, unknown>): Promise<Record<string, unknown>> {+ const inline = body['body'];+ if (typeof inline === 'object' && inline !== null) {+ return pdfCoClient.readRecord(inline);+ }+ const url = pdfCoFiles.nonEmptyString(body['url']);+ if (url === undefined) {+ throw new Error('PDF.co finished the invoice job but returned no result.');+ }+ const parsed = pdfCoClient.readRecord(await pdfCoFiles.readStorageJson({ url }));+ return typeof parsed['body'] === 'object' && parsed['body'] !== null ? pdfCoClient.readRecord(parsed['body']) : parsed;+}++function flattenInvoice(invoice: Record<string, unknown>): Record<string, unknown> {+ const vendor = pdfCoClient.readRecord(invoice['vendor']);+ const billTo = pdfCoClient.readRecord(pdfCoClient.readRecord(invoice['customer'])['billTo']);+ const details = pdfCoClient.readRecord(invoice['invoice']);+ const payment = pdfCoClient.readRecord(invoice['paymentDetails']);+ const rawItems = invoice['lineItems'];+ const lineItems = Array.isArray(rawItems) ? rawItems.flatMap((item) => (Array.isArray(item) ? item : [item])) : [];+ return {+ vendor_name: vendor['name'],+ customer_name: billTo['name'],+ invoice_number: details['invoiceNo'],+ invoice_date: details['invoiceDate'],+ due_date: details['dueDate'] ?? payment['dueDate'],+ po_number: details['poNo'],+ total: payment['total'] ?? details['total'],+ subtotal: payment['subtotal'] ?? details['subtotal'],+ tax: payment['tax'] ?? details['tax'],+ line_items: lineItems,+ invoice,+ };+}diff --git a/packages/pieces/community/pdf-co/src/lib/actions/read-barcodes.ts b/packages/pieces/community/pdf-co/src/lib/actions/read-barcodes.tsnew file mode 100644index 00000000000..c6aab0128a9--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/actions/read-barcodes.ts@@ -0,0 +1,84 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../auth';+import { pdfCoClient } from '../common/client';+import { pdfCoFiles } from '../common/files';+import { pdfCoJobs } from '../common/jobs';+import { pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';++const BARCODE_TYPES = [+ { label: 'QR Code', value: 'QRCode' },+ { label: 'DataMatrix', value: 'DataMatrix' },+ { label: 'Code 128', value: 'Code128' },+ { label: 'Code 39', value: 'Code39' },+ { label: 'PDF417', value: 'PDF417' },+ { label: 'EAN-13', value: 'EAN13' },+ { label: 'UPC-A', value: 'UPCA' },+ { label: 'Interleaved 2 of 5', value: 'Interleaved2of5' },+];++export const readBarcodes = createAction({+ auth: pdfCoAuth,+ name: 'read_barcodes_from_file',+ displayName: 'Read Barcodes',+ description: 'Find and decode barcodes and QR codes in a PDF or image.',+ audience: 'both',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Detects and decodes barcodes and QR codes in a PDF or image (public URL or file), returning each value, type, page (0-based), position and confidence. Choose the barcode types to look for. Costs 35 credits per page. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: pdfCoOutputSchemas.readBarcodes,+ props: {+ sourceUrl: pdfCoProps.sourceUrl({ description: 'Public link to the PDF or image. Fill this or pick a file below, not both.' }),+ sourceFile: pdfCoProps.sourceFile(),+ types: Property.StaticMultiSelectDropdown({+ displayName: 'Barcode Types',+ description: 'Which barcode types to look for. Fewer types read faster.',+ required: true,+ defaultValue: ['QRCode', 'Code128', 'Code39', 'EAN13', 'DataMatrix'],+ options: { disabled: false, options: BARCODE_TYPES },+ }),+ pages: pdfCoProps.pages({ base: 0 }),+ ...pdfCoProps.httpAuth(),+ },+ async run({ auth, propsValue }) {+ const apiKey = pdfCoClient.apiKeyOf(auth);+ const allowed = new Set(BARCODE_TYPES.map((option) => option.value));+ const types = (Array.isArray(propsValue.types) ? propsValue.types : []).map((type) => String(type));+ if (types.length === 0) {+ throw new Error('Pick at least one barcode type.');+ }+ const unknown = types.filter((type) => !allowed.has(type));+ if (unknown.length > 0) {+ throw new Error(`Unknown barcode type: ${unknown.join(', ')}.`);+ }+ const pages = pdfCoFiles.nonEmptyString(propsValue.pages);+ const url = await pdfCoFiles.resolveSource({ apiKey, url: propsValue.sourceUrl, file: propsValue.sourceFile });+ const body = await pdfCoJobs.runInline({+ apiKey,+ path: '/v1/barcode/read/from/url',+ body: { url, types: types.join(','), ...(pages === undefined ? {} : { pages: pages.trim() }) },+ common: propsValue,+ });+ const raw = body['barcodes'];+ const barcodes = (Array.isArray(raw) ? raw : []).map((item) => {+ const barcode = pdfCoClient.readRecord(item);+ return {+ value: barcode['Value'],+ type: barcode['TypeName'],+ page: barcode['Page'],+ rect: barcode['Rect'],+ confidence: barcode['Confidence'],+ };+ });+ return {+ barcode_count: barcodes.length,+ barcodes,+ page_count: body['pageCount'],+ credits_used: body['credits'],+ remaining_credits: body['remainingCredits'],+ };+ },+});diff --git a/packages/pieces/community/pdf-co/src/lib/actions/remove-password-from-pdf.ts b/packages/pieces/community/pdf-co/src/lib/actions/remove-password-from-pdf.tsnew file mode 100644index 00000000000..93082e6b30e--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/actions/remove-password-from-pdf.ts@@ -0,0 +1,47 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../auth';+import { pdfCoClient } from '../common/client';+import { pdfCoFiles } from '../common/files';+import { pdfCoJobs } from '../common/jobs';+import { pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';++export const removePasswordFromPdf = createAction({+ auth: pdfCoAuth,+ name: 'remove_password_from_pdf',+ displayName: 'Remove PDF Password',+ description: 'Create an unprotected copy of a password-protected PDF.',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Creates an unprotected copy of a password-protected PDF (public URL or file) given its password; the source file is not changed. Costs 3 credits per page. Not idempotent: each call runs a new job and creates a new output.',+ idempotent: false,+ },+ outputSchema: pdfCoOutputSchemas.fileResult,+ props: {+ sourceUrl: pdfCoProps.sourceUrl(),+ sourceFile: pdfCoProps.sourceFile(),+ password: Property.ShortText({+ displayName: 'PDF Password',+ description: 'The owner or open password of the PDF.',+ required: true,+ }),+ ...pdfCoProps.output(),+ },+ async run({ auth, propsValue, files }) {+ const apiKey = pdfCoClient.apiKeyOf(auth);+ const password = propsValue.password;+ if (password.trim() === '') {+ throw new Error('PDF Password is required.');+ }+ const url = await pdfCoFiles.resolveSource({ apiKey, url: propsValue.sourceUrl, file: propsValue.sourceFile });+ return pdfCoJobs.runFileAction({+ apiKey,+ files,+ path: '/v1/pdf/security/remove',+ body: { url, password },+ common: propsValue,+ });+ },+});diff --git a/packages/pieces/community/pdf-co/src/lib/actions/rotate-pdf-pages.ts b/packages/pieces/community/pdf-co/src/lib/actions/rotate-pdf-pages.tsnew file mode 100644index 00000000000..83797c4eeec--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/actions/rotate-pdf-pages.ts@@ -0,0 +1,59 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../auth';+import { pdfCoClient } from '../common/client';+import { pdfCoFiles } from '../common/files';+import { pdfCoJobs } from '../common/jobs';+import { pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';++export const rotatePdfPages = createAction({+ auth: pdfCoAuth,+ name: 'rotate_pdf_pages',+ displayName: 'Rotate PDF Pages',+ description: 'Rotate all or some pages of a PDF by 90, 180 or 270 degrees.',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Rotates the selected pages of a PDF (public URL or file) clockwise by 90, 180 or 270 degrees into a new PDF; leave pages empty to rotate every page. Page numbers start at 0 here. Costs 7 credits per page. Not idempotent: each call runs a new job and creates a new output.',+ idempotent: false,+ },+ outputSchema: pdfCoOutputSchemas.fileResult,+ props: {+ sourceUrl: pdfCoProps.sourceUrl(),+ sourceFile: pdfCoProps.sourceFile(),+ angle: Property.StaticDropdown({+ displayName: 'Angle',+ description: 'How far to rotate the pages clockwise.',+ required: true,+ defaultValue: '90',+ options: {+ disabled: false,+ options: [+ { label: '90 degrees', value: '90' },+ { label: '180 degrees', value: '180' },+ { label: '270 degrees', value: '270' },+ ],+ },+ }),+ pages: pdfCoProps.pages({ base: 0 }),+ ...pdfCoProps.httpAuth(),+ ...pdfCoProps.output(),+ },+ async run({ auth, propsValue, files }) {+ const apiKey = pdfCoClient.apiKeyOf(auth);+ const angle = Number(propsValue.angle);+ if (![90, 180, 270].includes(angle)) {+ throw new Error('Angle must be 90, 180 or 270.');+ }+ const url = await pdfCoFiles.resolveSource({ apiKey, url: propsValue.sourceUrl, file: propsValue.sourceFile });+ const pages = pdfCoFiles.nonEmptyString(propsValue.pages);+ return pdfCoJobs.runFileAction({+ apiKey,+ files,+ path: '/v1/pdf/edit/rotate',+ body: { url, angle, ...(pages === undefined ? {} : { pages: pages.trim() }) },+ common: propsValue,+ });+ },+});diff --git a/packages/pieces/community/pdf-co/src/lib/actions/search-and-replace-text.ts b/packages/pieces/community/pdf-co/src/lib/actions/search-and-replace-text.tsindex b829da46fca..0bdc9dd0dc6 100644--- a/packages/pieces/community/pdf-co/src/lib/actions/search-and-replace-text.ts+++ b/packages/pieces/community/pdf-co/src/lib/actions/search-and-replace-text.ts@@ -1,23 +1,10 @@+import { HttpMethod } from '@activepieces/pieces-common';import { Property, createAction } from '@activepieces/pieces-framework';-import { httpClient, HttpMethod, HttpError } from '@activepieces/pieces-common';-import { PdfCoSuccessResponse, PdfCoErrorResponse } from '../common/types';import { pdfCoAuth } from '../auth';-import { BASE_URL, commonProps } from '../common/props';--interface PdfCoSearchAndReplaceRequestBody {- url: string;- searchStrings: string[];- replaceStrings: string[];- async: boolean;- caseSensitive?: boolean;- regex?: boolean;- pages?: string;- name?: string;- expiration?: number;- httpusername?: string;- httppassword?: string;- password?: string;-}+import { pdfCoClient } from '../common/client';+import { pdfCoJobs } from '../common/jobs';+import { commonProps, PDF_CO_DEFAULTS, pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';export const searchAndReplaceText = createAction({name: 'search_and_replace_text',@@ -27,10 +14,11 @@ export const searchAndReplaceText = createAction({audience: 'both',aiMetadata: {description:- 'Finds occurrences of given text in a source PDF (referenced by URL) and replaces them with new text, with optional case-sensitive matching or regular-expression patterns instead of literal search. Use when an agent needs to edit textual content in an existing document. Each call produces a new output PDF file and consumes credits, so it is not idempotent.',+ 'Finds occurrences of given texts in a source PDF (referenced by URL) and replaces each with the replacement at the same position in the list, with optional case-sensitive matching or regular-expression patterns; both lists must have the same length and page indexes start at 0. Use when an agent needs to edit textual content in an existing document. Each call produces a new output PDF file and consumes credits, so it is not idempotent.',idempotent: false,},auth: pdfCoAuth,+ outputSchema: pdfCoOutputSchemas.rawResult,props: {url: Property.ShortText({displayName: 'PDF URL',@@ -39,10 +27,12 @@ export const searchAndReplaceText = createAction({}),searchStrings: Property.Array({displayName: 'Text to Locate',+ description: 'Texts to find. Each one is replaced by the Replacement Text in the same position.',required: true,}),replaceStrings: Property.Array({displayName: 'Replacement Text',+ description: 'One replacement per Text to Locate, in the same order.',required: true,}),caseSensitive: Property.Checkbox({@@ -59,81 +49,65 @@ export const searchAndReplaceText = createAction({}),pages: Property.ShortText({displayName: 'Pages',- description:- 'Comma-separated page numbers or ranges (e.g., "0,2,5-10"). Leave empty for all pages.',+ description: 'Comma-separated page indexes or ranges (first page is 0), e.g. "0,2,5-10". Leave empty for all pages.',required: false,}),...commonProps,+ replacementLimit: Property.Number({+ displayName: 'Max Replacements per Text',+ description: 'Maximum replacements for each text. Leave empty or 0 to replace every match.',+ required: false,+ }),+ saveOutputFile: pdfCoProps.saveOutputFile({ defaultValue: PDF_CO_DEFAULTS.saveOutputFileOnExistingActions }),},- async run(context) {- const { auth, propsValue } = context;- const {- url,- searchStrings,- replaceStrings,- caseSensitive,- regex,- pages,- fileName,- httpPassword,- httpUsername,- pdfPassword,- expiration,- } = propsValue;-- const requestBody: PdfCoSearchAndReplaceRequestBody = {- url: url,- searchStrings: searchStrings as string[],- replaceStrings: replaceStrings as string[],- async: false,- caseSensitive: caseSensitive,- regex,- pages,- name: fileName,- expiration,- httppassword: httpPassword,- httpusername: httpUsername,- password: pdfPassword,- };-- try {- const response = await httpClient.sendRequest<PdfCoSuccessResponse | PdfCoErrorResponse>({+ async run({ auth, propsValue, files }) {+ const searchStrings = toStringList(propsValue.searchStrings);+ const replaceStrings = toStringList(propsValue.replaceStrings);+ if (searchStrings.length === 0) {+ throw new Error('Add at least one Text to Locate.');+ }+ if (searchStrings.some((item) => item === '')) {+ throw new Error('Text to Locate cannot contain empty entries.');+ }+ if (searchStrings.length !== replaceStrings.length) {+ throw new Error(+ `Text to Locate has ${searchStrings.length} entries but Replacement Text has ${replaceStrings.length}. Give one replacement per text, in the same order.`,+ );+ }+ const limit = propsValue.replacementLimit;+ if (limit !== undefined && limit !== null && (!Number.isInteger(Number(limit)) || Number(limit) < 0)) {+ throw new Error('Max Replacements per Text must be a whole number of 0 or more.');+ }+ const body = pdfCoClient.readRecord(+ await pdfCoClient.request<unknown>({+ apiKey: pdfCoClient.apiKeyOf(auth),method: HttpMethod.POST,- url: `${BASE_URL}/pdf/edit/replace-text`,- headers: {- 'x-api-key': auth.secret_text,- 'Content-Type': 'application/json',+ path: '/v1/pdf/edit/replace-text',+ body: {+ url: propsValue.url,+ searchStrings,+ replaceStrings,+ async: false,+ caseSensitive: propsValue.caseSensitive,+ regex: propsValue.regex,+ pages: propsValue.pages,+ name: propsValue.fileName,+ expiration: propsValue.expiration,+ httppassword: propsValue.httpPassword,+ httpusername: propsValue.httpUsername,+ password: propsValue.pdfPassword,+ ...(limit === undefined || limit === null ? {} : { replacementLimit: Number(limit) }),},- body: requestBody,- });-- if (response.body.error) {- const errorBody = response.body as PdfCoErrorResponse;- let errorMessage = `PDF.co API Error: Status ${errorBody.status}.`;- if (errorBody.message) {- errorMessage += ` Message: ${errorBody.message}.`;- } else {- errorMessage += ` An unspecified error occurred.`;- }- errorMessage += ` Check input parameters, API key, and PDF.co dashboard for more details. Raw response: ${JSON.stringify(- errorBody,- )}`;- throw new Error(errorMessage);- }-- return response.body;- } catch (error) {- if (error instanceof HttpError) {- const responseBody = error.response?.body as PdfCoErrorResponse | undefined;- let detailedMessage = `HTTP Error calling PDF.co API: ${error.message}.`;- if (responseBody && responseBody.message) {- detailedMessage += ` Server message: ${responseBody.message}.`;- } else if (responseBody) {- detailedMessage += ` Server response: ${JSON.stringify(responseBody)}.`;- }- throw new Error(detailedMessage);- }- throw error;- }+ }),+ );+ const saved = await pdfCoJobs.optionalSave({ files, url: body['url'], enabled: propsValue.saveOutputFile, fileName: propsValue.fileName });+ return { ...body, ...saved };},});++function toStringList(value: unknown): string[] {+ if (!Array.isArray(value)) {+ return [];+ }+ return value.map((item) => (item === undefined || item === null ? '' : String(item)));+}diff --git a/packages/pieces/community/pdf-co/src/lib/actions/split-pdf.ts b/packages/pieces/community/pdf-co/src/lib/actions/split-pdf.tsnew file mode 100644index 00000000000..ab4274b9844--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/actions/split-pdf.ts@@ -0,0 +1,51 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../auth';+import { pdfCoClient } from '../common/client';+import { pdfCoFiles } from '../common/files';+import { pdfCoJobs } from '../common/jobs';+import { pdfCoProps } from '../common/props';+import { pdfCoOutputSchemas } from '../output-schemas';++export const splitPdf = createAction({+ auth: pdfCoAuth,+ name: 'split_pdf',+ displayName: 'Split PDF',+ description: 'Split a PDF into several PDFs by page ranges.',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Splits a PDF (public URL or file) into several PDFs by page ranges and returns one temporary link per part, optionally saving each part as a file. Page numbers start at 1 here (e.g. "1-2,3-"); "*" makes one file per page. Costs 2 credits per page. Not idempotent: each call runs a new job and creates new outputs.',+ idempotent: false,+ },+ outputSchema: pdfCoOutputSchemas.multiFileResult,+ props: {+ sourceUrl: pdfCoProps.sourceUrl(),+ sourceFile: pdfCoProps.sourceFile(),+ pages: Property.ShortText({+ displayName: 'Page Ranges',+ description:+ 'Comma-separated ranges, one output file per range. The first page is 1 (not 0). Example: "1-2,3-" gives pages 1-2 and page 3 to the end. Use "*" for one file per page.',+ required: true,+ defaultValue: '*',+ }),+ ...pdfCoProps.httpAuth(),+ ...pdfCoProps.output(),+ },+ async run({ auth, propsValue, files }) {+ const apiKey = pdfCoClient.apiKeyOf(auth);+ const pages = propsValue.pages.trim();+ if (pages === '') {+ throw new Error('Page Ranges is required, e.g. "1-2,3-" or "*".');+ }+ const url = await pdfCoFiles.resolveSource({ apiKey, url: propsValue.sourceUrl, file: propsValue.sourceFile });+ return pdfCoJobs.runFileAction({+ apiKey,+ files,+ path: '/v1/pdf/split',+ body: { url, pages, inline: true },+ common: propsValue,+ multiOutput: true,+ });+ },+});diff --git a/packages/pieces/community/pdf-co/src/lib/actions/upload-file.ts b/packages/pieces/community/pdf-co/src/lib/actions/upload-file.tsnew file mode 100644index 00000000000..22a2e020d7a--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/actions/upload-file.ts@@ -0,0 +1,40 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../auth';+import { pdfCoClient } from '../common/client';+import { pdfCoFiles } from '../common/files';+import { pdfCoOutputSchemas } from '../output-schemas';++export const uploadFile = createAction({+ auth: pdfCoAuth,+ name: 'upload_file',+ displayName: 'Upload File to PDF.co',+ description: 'Upload a file to PDF.co temporary storage and get a link other PDF.co actions can use.',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Uploads a file to PDF.co temporary storage (kept for 1 hour) and returns a URL that any PDF.co action accepts as its source. Use when a PDF.co action only takes a URL and the file is not public. Costs 7 credits. Not idempotent: each call stores a new copy.',+ idempotent: false,+ },+ outputSchema: pdfCoOutputSchemas.upload,+ props: {+ file: Property.File({+ displayName: 'File',+ description: 'The file to upload, for example a PDF from an earlier step.',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const { url, fileName, presigned } = await pdfCoFiles.uploadToStorage({+ apiKey: pdfCoClient.apiKeyOf(auth),+ file: propsValue.file,+ });+ return {+ url,+ name: pdfCoFiles.nonEmptyString(presigned['name']) ?? fileName,+ link_valid_until: pdfCoFiles.nonEmptyString(presigned['outputLinkValidTill']),+ credits_used: typeof presigned['credits'] === 'number' ? presigned['credits'] : undefined,+ remaining_credits: typeof presigned['remainingCredits'] === 'number' ? presigned['remainingCredits'] : undefined,+ };+ },+});diff --git a/packages/pieces/community/pdf-co/src/lib/auth.ts b/packages/pieces/community/pdf-co/src/lib/auth.tsindex 6ecc6c0ae94..22836989176 100644--- a/packages/pieces/community/pdf-co/src/lib/auth.ts+++ b/packages/pieces/community/pdf-co/src/lib/auth.ts@@ -1,7 +1,28 @@+import { HttpMethod } from '@activepieces/pieces-common';import { PieceAuth } from '@activepieces/pieces-framework';+import { pdfCoClient } from './common/client';export const pdfCoAuth = PieceAuth.SecretText({displayName: 'API Key',- description: `To get your PDF.co API key please [click here to create your account](https://app.pdf.co/).`,+ description: `To get your PDF.co API key:+1. Sign in or create an account at [app.pdf.co](https://app.pdf.co/).+2. Open **API** in the left menu.+3. Copy the API key and paste it here.`,required: true,+ validate: async ({ auth }) => {+ const apiKey = auth.trim();+ if (apiKey === '') {+ return { valid: false, error: 'Enter your PDF.co API key.' };+ }+ try {+ await pdfCoClient.request({ apiKey, method: HttpMethod.GET, path: '/v1/account/credit/balance' });+ return { valid: true };+ } catch (error) {+ const status = pdfCoClient.statusOf(error);+ if (status === 401 || status === 403) {+ return { valid: false, error: 'PDF.co rejected this API key. Copy it again from app.pdf.co > API.' };+ }+ return { valid: true };+ }+ },});diff --git a/packages/pieces/community/pdf-co/src/lib/common/client.ts b/packages/pieces/community/pdf-co/src/lib/common/client.tsnew file mode 100644index 00000000000..47a7bab1cfd--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/common/client.ts@@ -0,0 +1,256 @@+import { httpClient, HttpMethod, QueryParams } from '@activepieces/pieces-common';++const REQUEST_TIMEOUT_MS = 60_000;+const RATE_LIMIT_BACKOFF_MS = [5_000, 15_000];+const MAX_VENDOR_MESSAGE_LENGTH = 300;++const ERROR_HINTS: Record<number, string> = {+ 400: 'Check the input values and that every source URL is publicly reachable.',+ 401: 'The API key was rejected. Copy a fresh key from app.pdf.co and reconnect.',+ 402: 'The PDF.co account is out of credits. Top up at app.pdf.co.',+ 403: 'PDF.co could not open the source URL (access forbidden). Make the file public or set the HTTP username and password.',+ 404: 'PDF.co could not find the requested resource or job.',+ 408: 'PDF.co timed out waiting for the request. Try again.',+ 429: 'PDF.co rate limit reached. Wait a minute and try again.',+ 441: 'The PDF password is wrong or missing.',+ 442: 'The input document is damaged or not the expected file type.',+ 443: 'The document security settings do not allow this operation.',+ 444: 'The profiles value could not be parsed.',+ 445: 'The job took longer than 30 seconds. Turn on "Run in Background" or limit the pages.',+ 446: 'Some files needed for the conversion are missing.',+ 447: 'The template is invalid.',+ 448: 'The URL or HTML is invalid or not reachable.',+ 449: 'A page index is out of range. Check whether this action counts pages from 0 or from 1.',+ 450: 'The page range is invalid. Check whether this action counts pages from 0 or from 1.',+ 452: 'The URL is invalid.',+ 454: 'One or more parameters are invalid.',+};++function readRecord(value: unknown): Record<string, unknown> {+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {+ return {};+ }+ return Object.fromEntries(Object.entries(value));+}++function numberOrUndefined(value: unknown): number | undefined {+ if (typeof value === 'number' && Number.isFinite(value)) {+ return value;+ }+ if (typeof value === 'string' && /^\d{3}$/.test(value)) {+ return Number(value);+ }+ return undefined;+}++function collectSecrets({ value, apiKey }: { value: unknown; apiKey: string }): string[] {+ const secrets = new Set<string>();+ if (apiKey.length > 0) {+ secrets.add(apiKey);+ }+ const visit = ({ node, key }: { node: unknown; key: string }): void => {+ if (typeof node === 'string') {+ if (/pass(word)?/i.test(key) && node.length > 0) {+ secrets.add(node);+ }+ return;+ }+ if (Array.isArray(node)) {+ node.forEach((item) => visit({ node: item, key }));+ return;+ }+ if (typeof node === 'object' && node !== null) {+ Object.entries(node).forEach(([childKey, child]) => visit({ node: child, key: childKey }));+ }+ };+ visit({ node: value, key: '' });+ return [...secrets].sort((a, b) => b.length - a.length);+}++function redact({ text, secrets }: { text: string; secrets: string[] }): string {+ return secrets.reduce((current, secret) => current.split(secret).join('***'), text);+}++function vendorMessage(body: unknown): string | undefined {+ const record = readRecord(body);+ const message = record['message'];+ if (typeof message === 'string' && message.trim() !== '') {+ return message.trim().slice(0, MAX_VENDOR_MESSAGE_LENGTH);+ }+ if (typeof body === 'string' && body.trim() !== '' && !body.trim().startsWith('<')) {+ return body.trim().slice(0, MAX_VENDOR_MESSAGE_LENGTH);+ }+ return undefined;+}++function buildPdfCoError({+ httpStatus,+ body,+ secrets,+}: {+ httpStatus: number;+ body: unknown;+ secrets: string[];+}): PdfCoError {+ const record = readRecord(body);+ const errorCode = numberOrUndefined(record['errorCode']) ?? numberOrUndefined(record['status']);+ const code = errorCode ?? httpStatus;+ const vendor = vendorMessage(body);+ const hint = ERROR_HINTS[code] ?? ERROR_HINTS[httpStatus];+ const parts = [`PDF.co request failed (${code})`];+ if (vendor !== undefined) {+ parts.push(`: ${vendor}`);+ }+ if (vendor === undefined || !/[.!?]$/.test(vendor)) {+ parts.push('.');+ }+ if (hint !== undefined) {+ parts.push(` ${hint}`);+ }+ const message = redact({ text: parts.join(''), secrets });+ const safeBody = vendor === undefined ? undefined : { errorCode: code, message: redact({ text: vendor, secrets }) };+ return new PdfCoError({ message, status: httpStatus, errorCode: code, responseBody: safeBody });+}++function httpErrorDetails(error: unknown): { status: number; body: unknown } | undefined {+ if (typeof error !== 'object' || error === null || !('response' in error)) {+ return undefined;+ }+ const response = readRecord(error.response);+ const status = response['status'];+ if (typeof status !== 'number') {+ return undefined;+ }+ return { status, body: response['body'] };+}++function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++function serializeProfiles(profiles: unknown): string | undefined {+ if (typeof profiles === 'string') {+ return profiles.trim() === '' ? undefined : profiles;+ }+ if (typeof profiles === 'object' && profiles !== null) {+ return Object.keys(profiles).length === 0 ? undefined : JSON.stringify(profiles);+ }+ return undefined;+}++function apiKeyOf(auth: { secret_text: string }): string {+ return auth.secret_text.trim();+}++function pdfCoHeaders(apiKey: string): Record<string, string> {+ return { 'x-api-key': apiKey };+}++function assertApiPath(path: string): void {+ if (!/^\/v[12]\/[A-Za-z0-9/_-]+$/.test(path)) {+ throw new Error(`Invalid PDF.co API path "${path}".`);+ }+}++function statusOf(error: unknown): number | undefined {+ if (error instanceof PdfCoError) {+ return error.status;+ }+ return httpErrorDetails(error)?.status;+}++async function pdfCoRequest<T>({+ apiKey,+ method,+ path,+ body,+ queryParams,+ timeoutMs = REQUEST_TIMEOUT_MS,+}: {+ apiKey: string;+ method: HttpMethod;+ path: string;+ body?: Record<string, unknown>;+ queryParams?: QueryParams;+ timeoutMs?: number;+}): Promise<T> {+ assertApiPath(path);+ const secrets = collectSecrets({ value: body, apiKey });+ const headers: Record<string, string> = { ...pdfCoHeaders(apiKey), Accept: 'application/json' };+ if (body !== undefined) {+ headers['Content-Type'] = 'application/json';+ }+ for (let attempt = 0; ; attempt++) {+ try {+ const response = await httpClient.sendRequest<T>({+ method,+ url: `${PDF_CO_ORIGIN}${path}`,+ headers,+ body,+ queryParams,+ timeout: timeoutMs,+ followRedirects: false,+ });+ const record = readRecord(response.body);+ if (response.status < 200 || response.status >= 300 || record['error'] === true) {+ throw buildPdfCoError({ httpStatus: response.status, body: response.body, secrets });+ }+ return response.body;+ } catch (error) {+ if (error instanceof PdfCoError) {+ throw error;+ }+ const details = httpErrorDetails(error);+ if (details === undefined) {+ const reason = error instanceof Error ? error.message : String(error);+ throw new Error(redact({ text: `Could not reach PDF.co: ${reason}`, secrets }));+ }+ const backoff = RATE_LIMIT_BACKOFF_MS[attempt];+ if (details.status === 429 && backoff !== undefined) {+ await sleep(backoff);+ continue;+ }+ throw buildPdfCoError({ httpStatus: details.status, body: details.body, secrets });+ }+ }+}++export const pdfCoClient = {+ request: pdfCoRequest,+ buildError: buildPdfCoError,+ httpErrorDetails,+ readRecord,+ redact,+ sleep,+ apiKeyOf,+ headers: pdfCoHeaders,+ statusOf,+ serializeProfiles,+};++export class PdfCoError extends Error {+ readonly status: number;+ readonly errorCode: number | undefined;+ readonly responseBody: unknown;++ constructor({+ message,+ status,+ errorCode,+ responseBody,+ }: {+ message: string;+ status: number;+ errorCode?: number;+ responseBody?: unknown;+ }) {+ super(message);+ this.name = 'PdfCoError';+ this.status = status;+ this.errorCode = errorCode;+ this.responseBody = responseBody;+ }+}++export const PDF_CO_ORIGIN = 'https://api.pdf.co';+export const PDF_CO_BASE_URL = `${PDF_CO_ORIGIN}/v1`;diff --git a/packages/pieces/community/pdf-co/src/lib/common/files.ts b/packages/pieces/community/pdf-co/src/lib/common/files.tsnew file mode 100644index 00000000000..15974500a35--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/common/files.ts@@ -0,0 +1,306 @@+import { Readable } from 'node:stream';+import { httpClient, HttpMethod } from '@activepieces/pieces-common';+import { pdfCoClient } from './client';++const UPLOAD_TIMEOUT_MS = 60_000;+const DOWNLOAD_TIMEOUT_MS = 60_000;+const MAX_DOWNLOAD_BYTES = 100 * 1024 * 1024;+const MAX_JSON_BYTES = 20 * 1024 * 1024;+const STORAGE_HOST = /^pdf-temp-files\.s3(\.[a-z0-9-]+)?\.amazonaws\.com$/;++const MIME_TYPES: Record<string, string> = {+ pdf: 'application/pdf',+ png: 'image/png',+ jpg: 'image/jpeg',+ jpeg: 'image/jpeg',+ gif: 'image/gif',+ bmp: 'image/bmp',+ tif: 'image/tiff',+ tiff: 'image/tiff',+ webp: 'image/webp',+ doc: 'application/msword',+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',+ ppt: 'application/vnd.ms-powerpoint',+ pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',+ rtf: 'application/rtf',+ txt: 'text/plain',+ csv: 'text/csv',+ xls: 'application/vnd.ms-excel',+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',+ json: 'application/json',+ xml: 'application/xml',+ html: 'text/html',+};++function isFileLike(value: unknown): value is FileLike {+ if (typeof value !== 'object' || value === null) {+ return false;+ }+ const record = pdfCoClient.readRecord(value);+ return Buffer.isBuffer(record['data']) && typeof record['filename'] === 'string';+}++function toFileLike(value: unknown): FileLike {+ if (isFileLike(value)) {+ return value;+ }+ throw new Error('The selected file could not be read. Pick a file from an earlier step.');+}++function extensionOf(fileName: string): string {+ const match = /\.([A-Za-z0-9]+)$/.exec(fileName);+ return match === null ? '' : match[1].toLowerCase();+}++function mimeTypeOf(fileName: string): string {+ return MIME_TYPES[extensionOf(fileName)] ?? 'application/octet-stream';+}++function isStorageUrl(url: string): boolean {+ let parsed: URL;+ try {+ parsed = new URL(url);+ } catch {+ return false;+ }+ return (+ parsed.protocol === 'https:' &&+ parsed.username === '' &&+ parsed.password === '' &&+ parsed.port === '' &&+ STORAGE_HOST.test(parsed.hostname)+ );+}++function assertSourceUrl({ url, label }: { url: string; label: string }): string {+ const trimmed = url.trim();+ const withoutCache = trimmed.startsWith('cache:') ? trimmed.slice('cache:'.length) : trimmed;+ let parsed: URL;+ try {+ parsed = new URL(withoutCache);+ } catch {+ throw new Error(`${label} "${trimmed}" is not a valid URL. Use a public http(s) link to the file.`);+ }+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {+ throw new Error(`${label} must start with http:// or https://.`);+ }+ return trimmed;+}++function nonEmptyString(value: unknown): string | undefined {+ return typeof value === 'string' && value.trim() !== '' ? value : undefined;+}++async function putToPresignedUrl({+ presigned,+ file,+ contentType,+}: {+ presigned: Record<string, unknown>;+ file: FileLike;+ contentType: string;+}): Promise<string> {+ const presignedUrl = nonEmptyString(presigned['presignedUrl']);+ const fileUrl = nonEmptyString(presigned['url']);+ if (presignedUrl === undefined || fileUrl === undefined) {+ throw new Error('PDF.co did not return an upload link for the file.');+ }+ if (!isStorageUrl(presignedUrl) || !isStorageUrl(fileUrl)) {+ throw new Error('PDF.co returned an upload link outside its file storage; the file was not sent.');+ }+ let status: number;+ try {+ const response = await httpClient.sendRequest({+ method: HttpMethod.PUT,+ url: presignedUrl,+ headers: { 'Content-Type': contentType },+ body: file.data,+ timeout: UPLOAD_TIMEOUT_MS,+ followRedirects: false,+ });+ status = response.status;+ } catch (error) {+ const details = pdfCoClient.httpErrorDetails(error);+ const reason = details === undefined ? (error instanceof Error ? error.message : String(error)) : `HTTP ${details.status}`;+ throw new Error(`Uploading "${file.filename}" to PDF.co storage failed: ${reason}.`);+ }+ if (!isSuccessStatus(status)) {+ throw new Error(`Uploading "${file.filename}" to PDF.co storage failed: HTTP ${status}.`);+ }+ return fileUrl;+}++async function uploadToStorage({ apiKey, file }: { apiKey: string; file: unknown }): Promise<UploadResult> {+ const resolved = toFileLike(file);+ const fileName = resolved.filename.trim() === '' ? 'file' : resolved.filename;+ const contentType = mimeTypeOf(fileName);+ const presigned = pdfCoClient.readRecord(+ await pdfCoClient.request<unknown>({+ apiKey,+ method: HttpMethod.GET,+ path: '/v1/file/upload/get-presigned-url',+ queryParams: { name: fileName, contenttype: contentType },+ }),+ );+ const url = await putToPresignedUrl({ presigned, file: resolved, contentType });+ return { url, fileName, presigned };+}++async function uploadFile({ apiKey, file }: { apiKey: string; file: unknown }): Promise<string> {+ const { url } = await uploadToStorage({ apiKey, file });+ return url;+}++function isSuccessStatus(status: number): boolean {+ return status >= 200 && status < 300;+}++async function resolveSource({+ apiKey,+ url,+ file,+ label = 'Source',+}: {+ apiKey: string;+ url: unknown;+ file: unknown;+ label?: string;+}): Promise<string> {+ const urlValue = nonEmptyString(url);+ const hasFile = file !== undefined && file !== null && file !== '';+ if (urlValue !== undefined && hasFile) {+ throw new Error(`${label}: give either a file URL or a file, not both.`);+ }+ if (urlValue !== undefined) {+ return assertSourceUrl({ url: urlValue, label: `${label} URL` });+ }+ if (hasFile) {+ return uploadFile({ apiKey, file });+ }+ throw new Error(`${label}: give a file URL or pick a file.`);+}++function validateSource({ url, file, label = 'Source' }: { url: unknown; file: unknown; label?: string }): void {+ const urlValue = nonEmptyString(url);+ const hasFile = file !== undefined && file !== null && file !== '';+ if (urlValue !== undefined && hasFile) {+ throw new Error(`${label}: give either a file URL or a file, not both.`);+ }+ if (urlValue === undefined && !hasFile) {+ throw new Error(`${label}: give a file URL or pick a file.`);+ }+ if (urlValue !== undefined) {+ assertSourceUrl({ url: urlValue, label: `${label} URL` });+ }+ if (hasFile) {+ toFileLike(file);+ }+}++async function readCapped({ stream, maxBytes, timeoutMs }: { stream: Readable; maxBytes: number; timeoutMs: number }): Promise<Buffer> {+ const chunks: Buffer[] = [];+ let total = 0;+ let tooLarge = false;+ const timer = setTimeout(() => {+ stream.destroy(new Error(`timed out after ${Math.round(timeoutMs / 1000)} s`));+ }, timeoutMs);+ try {+ for await (const chunk of stream) {+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);+ total += buffer.byteLength;+ if (total > maxBytes) {+ tooLarge = true;+ break;+ }+ chunks.push(buffer);+ }+ } finally {+ clearTimeout(timer);+ if (tooLarge) {+ stream.destroy();+ }+ }+ if (tooLarge) {+ throw new Error(`the file is larger than ${Math.round(maxBytes / 1024 / 1024)} MB`);+ }+ return Buffer.concat(chunks, total);+}++async function downloadStorageFile({ url, maxBytes = MAX_DOWNLOAD_BYTES }: { url: string; maxBytes?: number }): Promise<Buffer> {+ if (!isStorageUrl(url)) {+ throw new Error('the result link is not on PDF.co file storage, so it was not downloaded');+ }+ const deadline = Date.now() + DOWNLOAD_TIMEOUT_MS;+ const response = await httpClient.sendRequest<Readable>({+ method: HttpMethod.GET,+ url,+ headers: { Accept: '*/*' },+ responseType: 'stream',+ timeout: DOWNLOAD_TIMEOUT_MS,+ followRedirects: false,+ });+ if (!isSuccessStatus(response.status)) {+ response.body.destroy();+ throw new Error(`PDF.co file storage answered HTTP ${response.status} instead of the file, so nothing was downloaded`);+ }+ const declared = Number(response.headers?.['content-length'] ?? '');+ if (Number.isFinite(declared) && declared > maxBytes) {+ response.body.destroy();+ throw new Error(`the file is larger than ${Math.round(maxBytes / 1024 / 1024)} MB`);+ }+ return readCapped({ stream: response.body, maxBytes, timeoutMs: Math.max(1, deadline - Date.now()) });+}++function fileNameFromUrl({ url, fallback }: { url: string; fallback: string }): string {+ try {+ const last = new URL(url).pathname.split('/').pop() ?? '';+ const decoded = decodeURIComponent(last);+ return decoded.trim() === '' ? fallback : decoded;+ } catch {+ return fallback;+ }+}++async function saveToFlow({+ files,+ url,+ fileName,+}: {+ files: FlowFiles;+ url: string;+ fileName?: string;+}): Promise<string> {+ const data = await downloadStorageFile({ url });+ const name = nonEmptyString(fileName) ?? fileNameFromUrl({ url, fallback: 'result' });+ return files.write({ fileName: name, data });+}++async function readStorageJson({ url }: { url: string }): Promise<unknown> {+ const data = await downloadStorageFile({ url, maxBytes: MAX_JSON_BYTES });+ try {+ return JSON.parse(data.toString('utf8'));+ } catch {+ throw new Error('the PDF.co result file is not valid JSON');+ }+}++export const pdfCoFiles = {+ resolveSource,+ validateSource,+ uploadFile,+ uploadToStorage,+ isFileLike,+ isStorageUrl,+ downloadStorageFile,+ saveToFlow,+ readStorageJson,+ fileNameFromUrl,+ mimeTypeOf,+ nonEmptyString,+};++export type FileLike = { filename: string; data: Buffer; extension?: string };++type UploadResult = { url: string; fileName: string; presigned: Record<string, unknown> };++export type FlowFiles = { write: (params: { fileName: string; data: Buffer }) => Promise<string> };diff --git a/packages/pieces/community/pdf-co/src/lib/common/jobs.ts b/packages/pieces/community/pdf-co/src/lib/common/jobs.tsnew file mode 100644index 00000000000..b28d32e7c5d--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/common/jobs.ts@@ -0,0 +1,410 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { pdfCoClient } from './client';+import { FlowFiles, pdfCoFiles } from './files';++const POLL_DELAYS_MS = [3_000, 5_000, 10_000, 15_000, 20_000];+const MAX_POLL_DELAY_MS = 30_000;+const JOB_CHECK_TIMEOUT_MS = 20_000;++function pollDelay(attempt: number): number {+ return POLL_DELAYS_MS[attempt] ?? MAX_POLL_DELAY_MS;+}++function stringOrUndefined(value: unknown): string | undefined {+ return typeof value === 'string' && value !== '' ? value : undefined;+}++function numberOrUndefined(value: unknown): number | undefined {+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;+}++function stringList(value: unknown): string[] | undefined {+ if (!Array.isArray(value)) {+ return undefined;+ }+ return value.filter((item): item is string => typeof item === 'string' && item !== '');+}++async function checkJob({ apiKey, jobId }: { apiKey: string; jobId: string }): Promise<Record<string, unknown>> {+ const body = await pdfCoClient.request<unknown>({+ apiKey,+ method: HttpMethod.POST,+ path: '/v1/job/check',+ body: { jobid: jobId },+ timeoutMs: JOB_CHECK_TIMEOUT_MS,+ });+ return pdfCoClient.readRecord(body);+}++function assertNotFailed({ check, jobId }: { check: Record<string, unknown>; jobId: string }): void {+ const status = check['status'];+ if (status === 'failed' || status === 'aborted') {+ const message = stringOrUndefined(check['message']) ?? 'no reason given';+ throw new Error(`PDF.co background job ${jobId} ${status}: ${message}`);+ }+}++async function runJob({+ apiKey,+ path,+ body,+ background,+ pollCeilingMs = DEFAULT_POLL_CEILING_MS,+ alwaysAsync = false,+}: {+ apiKey: string;+ path: string;+ body: Record<string, unknown>;+ background: boolean;+ pollCeilingMs?: number;+ alwaysAsync?: boolean;+}): Promise<JobResult> {+ const useAsync = background || alwaysAsync;+ const initial = pdfCoClient.readRecord(+ await pdfCoClient.request<unknown>({+ apiKey,+ method: HttpMethod.POST,+ path,+ body: { ...body, async: useAsync },+ }),+ );+ if (!useAsync) {+ return { body: initial, status: 'success' };+ }+ const jobId = stringOrUndefined(initial['jobId']);+ if (jobId === undefined) {+ throw new Error('PDF.co did not return a job ID for the background job.');+ }+ return waitForJob({ apiKey, jobId, initial, pollCeilingMs, checkImmediately: false });+}++async function waitForJob({+ apiKey,+ jobId,+ initial = {},+ pollCeilingMs = DEFAULT_POLL_CEILING_MS,+ checkImmediately,+}: {+ apiKey: string;+ jobId: string;+ initial?: Record<string, unknown>;+ pollCeilingMs?: number;+ checkImmediately: boolean;+}): Promise<JobResult> {+ const deadline = Date.now() + pollCeilingMs;+ let credits = numberOrUndefined(initial['credits']);+ let remaining = numberOrUndefined(initial['remainingCredits']);+ for (let attempt = 0; ; attempt++) {+ const delay = checkImmediately && attempt === 0 ? 0 : pollDelay(checkImmediately ? attempt - 1 : attempt);+ if (Date.now() + delay > deadline) {+ break;+ }+ if (delay > 0) {+ await pdfCoClient.sleep(delay);+ }+ const check = await checkJob({ apiKey, jobId });+ assertNotFailed({ check, jobId });+ credits = addCredits({ total: credits, value: check['credits'] });+ remaining = numberOrUndefined(check['remainingCredits']) ?? remaining;+ if (check['status'] === 'success') {+ return { body: { ...initial, ...check, ...creditFields({ credits, remaining }) }, status: 'success', jobId };+ }+ }+ return { body: { ...initial, ...creditFields({ credits, remaining }) }, status: 'working', jobId };+}++function addCredits({ total, value }: { total: number | undefined; value: unknown }): number | undefined {+ const extra = numberOrUndefined(value);+ if (extra === undefined) {+ return total;+ }+ return (total ?? 0) + extra;+}++function creditFields({ credits, remaining }: { credits: number | undefined; remaining: number | undefined }): Record<string, number> {+ return {+ ...(credits === undefined ? {} : { credits }),+ ...(remaining === undefined ? {} : { remainingCredits: remaining }),+ };+}++async function resultUrls({ result }: { result: JobResult }): Promise<string[] | undefined> {+ const direct = stringList(result.body['urls']);+ if (direct !== undefined) {+ return direct;+ }+ const listed = result.jobId === undefined ? undefined : stringList(result.body['body']);+ if (listed !== undefined && listed.length > 0) {+ return listed;+ }+ const url = stringOrUndefined(result.body['url']);+ if (result.status !== 'success' || result.jobId === undefined || url === undefined || !/\.json(\?|$)/i.test(url)) {+ return undefined;+ }+ const parsed = await pdfCoFiles.readStorageJson({ url });+ return isLinkList(parsed) ? parsed : undefined;+}++function isLinkList(value: unknown): value is string[] {+ return Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === 'string' && item.startsWith('https://'));+}++async function saveAll({+ files,+ targets,+ fileName,+}: {+ files: FlowFiles;+ targets: string[];+ fileName?: string;+}): Promise<{ saved: (string | null)[]; error?: string }> {+ const results = await Promise.allSettled(+ targets.map((target) => pdfCoFiles.saveToFlow({ files, url: target, fileName: targets.length === 1 ? fileName : undefined })),+ );+ const saved = results.map((result) => (result.status === 'fulfilled' ? result.value : null));+ const failures = results.flatMap((result, index) => (result.status === 'rejected' ? [{ index, reason: result.reason }] : []));+ if (failures.length === 0) {+ return { saved };+ }+ const first = failures[0].reason instanceof Error ? failures[0].reason.message : String(failures[0].reason);+ if (targets.length === 1) {+ return { saved, error: `The result was created but could not be saved as a file: ${first}. Use the link instead.` };+ }+ const parts = failures.map((failure) => failure.index + 1).join(', ');+ return {+ saved,+ error: `${failures.length} of ${targets.length} results could not be saved as files (part ${parts}): ${first}. Use the links instead.`,+ };+}++async function buildFileOutput({+ result,+ files,+ saveOutputFile,+ multiOutput = false,+ fileName,+}: {+ result: JobResult;+ files: FlowFiles;+ saveOutputFile: boolean;+ multiOutput?: boolean;+ fileName?: string;+}): Promise<FileActionOutput> {+ const body = result.body;+ const url = stringOrUndefined(body['url']);+ const urls = multiOutput ? await resultUrls({ result }) : undefined;+ const base: FileActionOutput = {+ status: result.status,+ job_id: result.jobId,+ url: multiOutput && urls !== undefined ? urls[0] : url,+ urls,+ name: stringOrUndefined(body['name']),+ page_count: numberOrUndefined(body['pageCount']),+ file_size: numberOrUndefined(body['fileSize']),+ credits_used: numberOrUndefined(body['credits']),+ remaining_credits: numberOrUndefined(body['remainingCredits']),+ link_valid_until: stringOrUndefined(body['outputLinkValidTill']),+ duration_ms: numberOrUndefined(body['duration']),+ };+ if (!saveOutputFile || result.status !== 'success') {+ return base;+ }+ const single = url === undefined ? [] : [url];+ const targets = multiOutput ? urls ?? single : single;+ if (targets.length === 0) {+ return base;+ }+ const saved = await saveAll({ files, targets, fileName });+ return { ...base, ...savedFileFields({ ...saved, multiOutput }) };+}++function savedFileFields({+ saved,+ error,+ multiOutput,+}: {+ saved: (string | null)[];+ error?: string;+ multiOutput: boolean;+}): Pick<FileActionOutput, 'file' | 'files' | 'file_error'> {+ const first = saved[0];+ const anySaved = saved.some((entry) => entry !== null);+ return {+ ...(first === null || first === undefined ? {} : { file: first }),+ ...(multiOutput && anySaved ? { files: saved } : {}),+ ...(error === undefined ? {} : { file_error: error }),+ };+}++function optionalText(value: unknown): string | undefined {+ return typeof value === 'string' && value.trim() !== '' ? value : undefined;+}++function validateExpiration(expiration: unknown): number | undefined {+ if (expiration === undefined || expiration === null || expiration === '') {+ return undefined;+ }+ const value = Number(expiration);+ if (!Number.isInteger(value) || value <= 0) {+ throw new Error('Link Expiration must be a whole number of minutes greater than 0.');+ }+ return value;+}++function commonBody({+ outputName,+ expiration,+ pdfPassword,+ httpUsername,+ httpPassword,+}: CommonBodyInput): Record<string, unknown> {+ const minutes = validateExpiration(expiration);+ return {+ ...(optionalText(outputName) === undefined ? {} : { name: outputName }),+ ...(minutes === undefined ? {} : { expiration: minutes }),+ ...(optionalText(pdfPassword) === undefined ? {} : { password: pdfPassword }),+ ...(optionalText(httpUsername) === undefined ? {} : { httpusername: httpUsername }),+ ...(optionalText(httpPassword) === undefined ? {} : { httppassword: httpPassword }),+ };+}++async function runFileAction({+ apiKey,+ files,+ path,+ body,+ common,+ multiOutput = false,+}: {+ apiKey: string;+ files: FlowFiles;+ path: string;+ body: Record<string, unknown>;+ common: CommonBodyInput & { runInBackground?: unknown; saveOutputFile?: unknown };+ multiOutput?: boolean;+}): Promise<FileActionOutput> {+ const request = { ...commonBody(common), ...body };+ const result = await runJob({ apiKey, path, body: request, background: common.runInBackground === true });+ return buildFileOutput({+ result,+ files,+ saveOutputFile: common.saveOutputFile === true,+ multiOutput,+ fileName: optionalText(common.outputName),+ });+}++async function runInline({+ apiKey,+ path,+ body,+ common,+}: {+ apiKey: string;+ path: string;+ body: Record<string, unknown>;+ common: CommonBodyInput;+}): Promise<Record<string, unknown>> {+ const result = await runJob({+ apiKey,+ path,+ body: { ...commonBody({ pdfPassword: common.pdfPassword, httpUsername: common.httpUsername, httpPassword: common.httpPassword }), ...body },+ background: false,+ });+ return result.body;+}++async function optionalSave({+ files,+ url,+ enabled,+ fileName,+}: {+ files: FlowFiles;+ url: unknown;+ enabled: unknown;+ fileName?: unknown;+}): Promise<{ file?: string; file_error?: string }> {+ if (enabled !== true || typeof url !== 'string' || url === '') {+ return {};+ }+ try {+ return { file: await pdfCoFiles.saveToFlow({ files, url, fileName: optionalText(fileName) }) };+ } catch (error) {+ const reason = error instanceof Error ? error.message : String(error);+ return { file_error: `The result was created but could not be saved as a file: ${reason}. Use the link instead.` };+ }+}++async function legacyEditOutput({+ body,+ files,+ saveOutputFile,+ fileName,+}: {+ body: Record<string, unknown>;+ files: FlowFiles;+ saveOutputFile: unknown;+ fileName: unknown;+}): Promise<Record<string, unknown>> {+ const saved = await optionalSave({ files, url: body['url'], enabled: saveOutputFile, fileName });+ return {+ outputUrl: body['url'],+ pageCount: body['pageCount'],+ outputName: body['name'],+ creditsUsed: body['credits'],+ remainingCredits: body['remainingCredits'],+ ...saved,+ };+}++export const pdfCoJobs = {+ runJob,+ waitForJob,+ saveAll,+ savedFileFields,+ stringList,+ checkJob,+ assertNotFailed,+ buildFileOutput,+ resultUrls,+ commonBody,+ validateExpiration,+ runFileAction,+ runInline,+ optionalSave,+ legacyEditOutput,+};++export const DEFAULT_POLL_CEILING_MS = 240_000;++export type CommonBodyInput = {+ outputName?: unknown;+ expiration?: unknown;+ pdfPassword?: unknown;+ httpUsername?: unknown;+ httpPassword?: unknown;+};++export type JobResult = {+ body: Record<string, unknown>;+ status: 'success' | 'working';+ jobId?: string;+};++export type FileActionOutput = {+ status: 'success' | 'working';+ job_id?: string;+ url?: string;+ urls?: string[];+ name?: string;+ page_count?: number;+ file_size?: number;+ credits_used?: number;+ remaining_credits?: number;+ link_valid_until?: string;+ duration_ms?: number;+ file?: string;+ files?: (string | null)[];+ file_error?: string;+};diff --git a/packages/pieces/community/pdf-co/src/lib/common/props.ts b/packages/pieces/community/pdf-co/src/lib/common/props.tsindex a46ed63dd05..f2069d4d8e2 100644--- a/packages/pieces/community/pdf-co/src/lib/common/props.ts+++ b/packages/pieces/community/pdf-co/src/lib/common/props.ts@@ -1,6 +1,232 @@-import { Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { DropdownOption, Property } from '@activepieces/pieces-framework';+import { pdfCoAuth } from '../auth';+import { pdfCoClient, PDF_CO_BASE_URL } from './client';-export const BASE_URL = 'https://api.pdf.co/v1';+function saveOutputFileProp({ defaultValue }: { defaultValue: boolean }) {+ return Property.Checkbox({+ displayName: 'Save Result as File',+ description:+ 'Download the result and keep it as a file in this flow, so later steps can use it after the PDF.co link expires (links last 60 minutes by default). Files over 100 MB are not saved; the link is still returned.',+ required: false,+ defaultValue,+ });+}++function sourceUrlProp({ displayName = 'Source File URL', description }: { displayName?: string; description?: string } = {}) {+ return Property.ShortText({+ displayName,+ description:+ description ??+ 'Public link to the file (for example a PDF on Google Drive, Dropbox or S3). Fill this or pick a file below, not both.',+ required: false,+ });+}++function sourceFileProp({ displayName = 'Source File', description }: { displayName?: string; description?: string } = {}) {+ return Property.File({+ displayName,+ description:+ description ??+ 'A file from an earlier step. It is uploaded to PDF.co temporary storage first (7 extra credits). Fill this or the URL above, not both.',+ required: false,+ });+}++function pagesProp({ base, description }: { base: 0 | 1; description?: string }) {+ const example = base === 0 ? '"0,2,5-10" or "3-" (first page is 0)' : '"1,3,5-10" or "3-" (first page is 1)';+ return Property.ShortText({+ displayName: 'Pages',+ description:+ description ?? `Comma-separated pages or ranges, e.g. ${example}. Use "!0" for the last page. Leave empty for all pages.`,+ required: false,+ });+}++function outputProps({ background = true }: { background?: boolean } = {}) {+ return {+ outputName: Property.ShortText({+ displayName: 'Output File Name',+ description: 'Name for the result file, e.g. "result.pdf". Leave empty to let PDF.co pick one.',+ required: false,+ }),+ expiration: Property.Number({+ displayName: 'Link Expiration (minutes)',+ description: 'How long the PDF.co result link stays valid. Default 60. The maximum depends on your PDF.co plan.',+ required: false,+ }),+ ...(background ? { runInBackground: runInBackgroundProp() } : {}),+ saveOutputFile: saveOutputFileProp({ defaultValue: PDF_CO_DEFAULTS.saveOutputFileOnNewActions }),+ };+}++function runInBackgroundProp() {+ return Property.Checkbox({+ displayName: 'Run in Background',+ description:+ 'For large files. PDF.co processes the job in the background and this step checks it for up to 4 minutes (each check costs 2 credits). If it is still running, the step returns the job ID; use Check Job Status later.',+ required: false,+ defaultValue: false,+ });+}++function passwordProps() {+ return {+ pdfPassword: Property.ShortText({+ displayName: 'Source PDF Password',+ description: 'Password to open the source PDF, if it is protected.',+ required: false,+ }),+ };+}++function httpAuthProps() {+ return {+ httpUsername: Property.ShortText({+ displayName: 'HTTP Username',+ description: 'Username if the source URL needs HTTP basic auth.',+ required: false,+ }),+ httpPassword: Property.ShortText({+ displayName: 'HTTP Password',+ description: 'Password if the source URL needs HTTP basic auth.',+ required: false,+ }),+ };+}++function inlineReadProps() {+ return { ...passwordProps(), ...httpAuthProps() };+}++function templateDropdown({ kind, required }: { kind: 'html' | 'documentParser'; required: boolean }) {+ return Property.Dropdown({+ auth: pdfCoAuth,+ displayName: 'Template',+ description:+ kind === 'html'+ ? 'An HTML template from PDF.co (app.pdf.co > HTML to PDF Templates). Loading this list costs 2 credits.'+ : 'A Document Parser template from PDF.co (app.pdf.co > Document Parser). Loading this list costs 2 credits.',+ required,+ refreshers: [],+ options: async ({ auth }) => {+ if (auth === undefined) {+ return { disabled: true, options: [], placeholder: 'Connect your PDF.co account first.' };+ }+ try {+ const { templates } = await listTemplates({ apiKey: pdfCoClient.apiKeyOf(auth), kind });+ return {+ disabled: false,+ options: templates.map((template) => ({+ label: `${template.title} (${template.type}, #${template.id})`,+ value: String(template.id),+ })),+ };+ } catch (error) {+ return {+ disabled: true,+ options: [],+ placeholder: error instanceof Error ? error.message : 'Could not load templates.',+ };+ }+ },+ });+}++async function listTemplates({ apiKey, kind }: { apiKey: string; kind: 'html' | 'documentParser' }): Promise<TemplateList> {+ const body = await pdfCoClient.request<unknown>({+ apiKey,+ method: HttpMethod.GET,+ path: kind === 'html' ? '/v1/templates/html' : '/v1/pdf/documentparser/templates',+ });+ const record = pdfCoClient.readRecord(body);+ const raw = record['templates'];+ const templates = (Array.isArray(raw) ? raw : []).map((item) => {+ const template = pdfCoClient.readRecord(item);+ return {+ id: typeof template['id'] === 'number' || typeof template['id'] === 'string' ? template['id'] : '',+ title: typeof template['title'] === 'string' ? template['title'] : 'Untitled',+ type: typeof template['type'] === 'string' ? template['type'] : '',+ description: typeof template['description'] === 'string' ? template['description'] : '',+ sample_data: typeof template['test_json'] === 'string' ? template['test_json'] : undefined,+ updated_at: typeof template['updated_at'] === 'string' ? template['updated_at'] : undefined,+ };+ });+ return {+ templates,+ credits_used: typeof record['credits'] === 'number' ? record['credits'] : undefined,+ remaining_credits: typeof record['remainingCredits'] === 'number' ? record['remainingCredits'] : undefined,+ };+}++function pageLayoutProps() {+ return {+ paperSize: Property.StaticDropdown({+ displayName: 'Paper Size',+ description: 'Standard paper size. For a custom size use Custom Paper Size instead.',+ required: false,+ options: { disabled: false, options: PAPER_SIZES },+ }),+ customPaperSize: Property.ShortText({+ displayName: 'Custom Paper Size',+ description: 'Width and height with units, e.g. "200mm 300mm" or "8.5in 11in". Overrides Paper Size when set.',+ required: false,+ }),+ orientation: Property.StaticDropdown({+ displayName: 'Orientation',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Portrait (default)', value: 'Portrait' },+ { label: 'Landscape', value: 'Landscape' },+ ],+ },+ }),+ margins: Property.ShortText({+ displayName: 'Margins',+ description: 'CSS-style margins: one value for all sides or "top right bottom left", e.g. "10mm" or "5mm 5mm 5mm 5mm".',+ required: false,+ }),+ printBackground: Property.Checkbox({+ displayName: 'Print Background',+ description: 'Include background colors and images.',+ required: false,+ defaultValue: true,+ }),+ header: Property.LongText({+ displayName: 'Header HTML',+ description: 'HTML shown at the top of every page.',+ required: false,+ }),+ footer: Property.LongText({+ displayName: 'Footer HTML',+ description: 'HTML shown at the bottom of every page.',+ required: false,+ }),+ };+}++function pageLayoutBody(values: PageLayoutValues): Record<string, unknown> {+ const custom = typeof values.customPaperSize === 'string' ? values.customPaperSize.trim() : '';+ const paper = custom !== '' ? custom : typeof values.paperSize === 'string' ? values.paperSize : '';+ const orientation = typeof values.orientation === 'string' ? values.orientation : '';+ if (orientation !== '' && orientation !== 'Portrait' && orientation !== 'Landscape') {+ throw new Error('Orientation must be Portrait or Landscape.');+ }+ const text = (value: unknown): string | undefined => (typeof value === 'string' && value.trim() !== '' ? value : undefined);+ const margins = text(values.margins);+ const header = text(values.header);+ const footer = text(values.footer);+ return {+ ...(paper === '' ? {} : { paperSize: paper }),+ ...(orientation === '' ? {} : { orientation }),+ ...(margins === undefined ? {} : { margins: margins.trim() }),+ ...(typeof values.printBackground === 'boolean' ? { printBackground: values.printBackground } : {}),+ ...(header === undefined ? {} : { header }),+ ...(footer === undefined ? {} : { footer }),+ };+}export const commonProps = {fileName: Property.ShortText({@@ -30,3 +256,75 @@ export const commonProps = {required: false,}),};++export const pdfCoProps = {+ saveOutputFile: saveOutputFileProp,+ sourceUrl: sourceUrlProp,+ sourceFile: sourceFileProp,+ pages: pagesProp,+ output: outputProps,+ password: passwordProps,+ httpAuth: httpAuthProps,+ inlineRead: inlineReadProps,+ runInBackground: runInBackgroundProp,+ templateDropdown,+ listTemplates,+ pageLayout: pageLayoutProps,+ pageLayoutBody,+};++export const PAPER_SIZES = [+ { label: 'A4 (default)', value: 'A4' },+ { label: 'Letter', value: 'Letter' },+ { label: 'Legal', value: 'Legal' },+ { label: 'Tabloid', value: 'Tabloid' },+ { label: 'Ledger', value: 'Ledger' },+ { label: 'A0', value: 'A0' },+ { label: 'A1', value: 'A1' },+ { label: 'A2', value: 'A2' },+ { label: 'A3', value: 'A3' },+ { label: 'A5', value: 'A5' },+ { label: 'A6', value: 'A6' },+];++export const BARCODE_TYPES: DropdownOption<string>[] = [+ { label: 'QR Code (Default)', value: 'QRCode' },+ { label: 'DataMatrix', value: 'DataMatrix' },+ { label: 'Code 128', value: 'Code128' },+ { label: 'Code 39', value: 'Code39' },+ { label: 'PDF417', value: 'PDF417' },+ { label: 'EAN-13', value: 'EAN13' },+ { label: 'UPC-A', value: 'UPCA' },+];++export const PDF_CO_DEFAULTS = {+ saveOutputFileOnNewActions: true,+ saveOutputFileOnExistingActions: false,+};++export const BASE_URL = PDF_CO_BASE_URL;++export type TemplateSummary = {+ id: number | string;+ title: string;+ type: string;+ description: string;+ sample_data?: string;+ updated_at?: string;+};++export type TemplateList = {+ templates: TemplateSummary[];+ credits_used?: number;+ remaining_credits?: number;+};++export type PageLayoutValues = {+ paperSize?: unknown;+ customPaperSize?: unknown;+ orientation?: unknown;+ margins?: unknown;+ printBackground?: unknown;+ header?: unknown;+ footer?: unknown;+};diff --git a/packages/pieces/community/pdf-co/src/lib/common/types.ts b/packages/pieces/community/pdf-co/src/lib/common/types.tsdeleted file mode 100644index 86986fba1b1..00000000000--- a/packages/pieces/community/pdf-co/src/lib/common/types.ts+++ /dev/null@@ -1,45 +0,0 @@--// Define a type for the expected successful response body (shared structure)-export interface PdfCoSuccessResponse {- url: string;- pageCount: number;- error: false;- status: number;- name: string;- remainingCredits: number;- credits: number;-}--// Define a type for the expected error response body (shared structure)-export interface PdfCoErrorResponse {- error: true;- status: number;- message?: string;- [key: string]: unknown;-}-- // Interface for the image object needed by /pdf/edit/add-export interface PdfCoImageAnnotation {- url: string;- x: number;- y: number;- pages?: string;- width?: number;- height?: number;- link?: string;- keepAspectRatio?: boolean;-}--// Interface for the /pdf/edit/add request body (when adding images)-export interface PdfCoAddImagesRequestBody {- url: string; // Source PDF URL- images: PdfCoImageAnnotation[];- async: boolean;- inline: boolean; // Should be false to get final PDF url- name?: string;- password?: string;- expiration?: number;- profiles?: Record<string, unknown>;- httpusername?: string;- httppassword?: string;-}\ No newline at end of filediff --git a/packages/pieces/community/pdf-co/src/lib/output-schemas.ts b/packages/pieces/community/pdf-co/src/lib/output-schemas.tsnew file mode 100644index 00000000000..2c618bf1ff6--- /dev/null+++ b/packages/pieces/community/pdf-co/src/lib/output-schemas.ts@@ -0,0 +1,281 @@+import { OutputSchema, OutputSchemaField } from '@activepieces/pieces-framework';++const creditFields: OutputSchemaField[] = [+ { key: 'credits_used', label: 'Credits Used', format: 'number' },+ { key: 'remaining_credits', label: 'Remaining Credits', format: 'number' },+];++const fileResultFields: OutputSchemaField[] = [+ {+ key: 'status',+ label: 'Status',+ description: '"success" when the result is ready, "working" when a background job is still running (use Check Job Status with the job ID).',+ },+ { key: 'job_id', label: 'Job ID', description: 'Only set when Run in Background is on.' },+ { key: 'url', label: 'Result Link', format: 'url', description: 'Temporary PDF.co link; it expires at Link Valid Until.' },+ { key: 'name', label: 'File Name' },+ { key: 'page_count', label: 'Page Count', format: 'number' },+ { key: 'file_size', label: 'File Size', format: 'filesize', description: 'Only returned by some endpoints.' },+ {+ key: 'credits_used',+ label: 'Credits Used',+ format: 'number',+ description: 'For background jobs this includes the status checks (2 credits per check on most endpoints).',+ },+ { key: 'remaining_credits', label: 'Remaining Credits', format: 'number' },+ { key: 'link_valid_until', label: 'Link Valid Until', format: 'datetime' },+ { key: 'duration_ms', label: 'Duration (ms)', format: 'number' },+ { key: 'file', label: 'Saved File', description: 'Set when Save Result as File is on.' },+ { key: 'file_error', label: 'File Save Error', description: 'Why the result could not be saved as a file; the link is still valid.' },+];++const multiFileResultFields: OutputSchemaField[] = [+ ...fileResultFields,+ {+ key: 'urls',+ label: 'Result Links',+ description: 'One temporary link per output part or page. Not set when the result is a single file, e.g. a multi-page TIFF.',+ },+ { key: 'files', label: 'Saved Files', description: 'One file per output part, in the same order as Result Links, when Save Result as File is on. A part that could not be saved is null (see File Save Error).' },+];++const legacyEditFields: OutputSchemaField[] = [+ { key: 'outputUrl', label: 'Result Link', format: 'url' },+ { key: 'pageCount', label: 'Page Count', format: 'number' },+ { key: 'outputName', label: 'File Name' },+ { key: 'creditsUsed', label: 'Credits Used', format: 'number' },+ { key: 'remainingCredits', label: 'Remaining Credits', format: 'number' },+ { key: 'file', label: 'Saved File', description: 'Set when Save Result as File is on.' },+ { key: 'file_error', label: 'File Save Error' },+];++const rawResultFields: OutputSchemaField[] = [+ { key: 'url', label: 'Result Link', format: 'url' },+ { key: 'name', label: 'File Name' },+ { key: 'pageCount', label: 'Page Count', format: 'number' },+ { key: 'credits', label: 'Credits Used', format: 'number' },+ { key: 'remainingCredits', label: 'Remaining Credits', format: 'number' },+ { key: 'outputLinkValidTill', label: 'Link Valid Until', format: 'datetime' },+ { key: 'duration', label: 'Duration (ms)', format: 'number' },+ { key: 'file', label: 'Saved File', description: 'Set when Save Result as File is on.' },+ { key: 'file_error', label: 'File Save Error' },+];++const pdfInfoFields: OutputSchemaField[] = [+ { key: 'page_count', label: 'Page Count', format: 'number' },+ { key: 'title', label: 'Title' },+ { key: 'author', label: 'Author' },+ { key: 'subject', label: 'Subject' },+ { key: 'keywords', label: 'Keywords' },+ { key: 'creator', label: 'Creator' },+ { key: 'producer', label: 'Producer' },+ { key: 'creation_date', label: 'Created', description: 'As PDF.co reports it, e.g. "2001-08-15T14:50:36".' },+ { key: 'modification_date', label: 'Modified' },+ { key: 'page_width', label: 'Page Width (pt)', format: 'number' },+ { key: 'page_height', label: 'Page Height (pt)', format: 'number' },+ { key: 'encrypted', label: 'Encrypted', format: 'boolean' },+ { key: 'password_protected', label: 'Password Protected', format: 'boolean' },+ { key: 'encryption_algorithm', label: 'Encryption Algorithm' },+ { key: 'permission_printing', label: 'Can Print', format: 'boolean' },+ { key: 'permission_modify_document', label: 'Can Modify', format: 'boolean' },+ { key: 'permission_content_extraction', label: 'Can Copy Content', format: 'boolean' },+ { key: 'permission_modify_annotations', label: 'Can Annotate', format: 'boolean' },+ { key: 'permission_fill_forms', label: 'Can Fill Forms', format: 'boolean' },+ { key: 'permission_assemble', label: 'Can Assemble', format: 'boolean' },+ ...creditFields,+];++const templateFields: OutputSchemaField[] = [+ { key: 'id', label: 'Template ID' },+ { key: 'title', label: 'Title' },+ { key: 'description', label: 'Description' },+ { key: 'type', label: 'Type', description: '"system" (built in) or "user" (yours).' },+];++export const pdfCoOutputSchemas = {+ fileResult: { fields: fileResultFields } satisfies OutputSchema,+ multiFileResult: { fields: multiFileResultFields } satisfies OutputSchema,+ legacyEdit: { fields: legacyEditFields } satisfies OutputSchema,+ rawResult: { fields: rawResultFields } satisfies OutputSchema,+ extractText: {+ fields: [+ { key: 'extractedText', label: 'Extracted Text' },+ { key: 'pageCount', label: 'Page Count', format: 'number' },+ { key: 'outputName', label: 'File Name' },+ { key: 'creditsUsed', label: 'Credits Used', format: 'number' },+ { key: 'remainingCredits', label: 'Remaining Credits', format: 'number' },+ ],+ } satisfies OutputSchema,+ extractTables: {+ fields: [+ {+ key: 'extractedTables',+ label: 'Tables',+ labelKey: 'name',+ listItems: [+ { key: 'name', label: 'Table Name' },+ { key: 'objectType', label: 'Object Type' },+ { key: 'pageIndex', label: 'Page (0-based)', format: 'number', description: 'Often not set on the table; each cell in Rows carries its own pageIndex.' },+ { key: 'rows', label: 'Rows' },+ ],+ },+ { key: 'templateNameUsed', label: 'Template Name' },+ ],+ } satisfies OutputSchema,+ creditBalance: { fields: [{ key: 'remaining_credits', label: 'Remaining Credits', format: 'number' }] } satisfies OutputSchema,+ pdfInfo: { fields: pdfInfoFields } satisfies OutputSchema,+ formFields: {+ fields: [+ { key: 'page_count', label: 'Page Count', format: 'number' },+ { key: 'field_count', label: 'Field Count', format: 'number' },+ {+ key: 'fields',+ label: 'Form Fields',+ labelKey: 'field_name',+ listItems: [+ { key: 'field_name', label: 'Field Name', description: 'Use this exact name in Fill PDF Form.' },+ { key: 'type', label: 'Type' },+ { key: 'value', label: 'Current Value' },+ { key: 'page_index', label: 'Page (0-based)', format: 'number' },+ { key: 'left', label: 'Left', format: 'number' },+ { key: 'top', label: 'Top', format: 'number' },+ { key: 'width', label: 'Width', format: 'number' },+ { key: 'height', label: 'Height', format: 'number' },+ ],+ },+ ...creditFields,+ ],+ } satisfies OutputSchema,+ findText: {+ fields: [+ { key: 'match_count', label: 'Matches Found', format: 'number' },+ {+ key: 'matches',+ label: 'Matches',+ labelKey: 'text',+ listItems: [+ { key: 'text', label: 'Text' },+ { key: 'page_index', label: 'Page (0-based)', format: 'number' },+ { key: 'left', label: 'Left', format: 'number' },+ { key: 'top', label: 'Top', format: 'number' },+ { key: 'width', label: 'Width', format: 'number' },+ { key: 'height', label: 'Height', format: 'number' },+ ],+ },+ { key: 'page_count', label: 'Pages Searched', format: 'number' },+ ...creditFields,+ ],+ } satisfies OutputSchema,+ readBarcodes: {+ fields: [+ { key: 'barcode_count', label: 'Barcodes Found', format: 'number' },+ {+ key: 'barcodes',+ label: 'Barcodes',+ labelKey: 'value',+ listItems: [+ { key: 'value', label: 'Value' },+ { key: 'type', label: 'Type', description: 'PDF.co type name, e.g. "QRCode", "Code128", "EAN13"; Interleaved 2 of 5 comes back as "I2of5".' },+ { key: 'page', label: 'Page (0-based)', format: 'number' },+ { key: 'rect', label: 'Position', description: 'For example "{X=448,Y=23,Width=106,Height=112}".' },+ { key: 'confidence', label: 'Confidence', format: 'number' },+ ],+ },+ { key: 'page_count', label: 'Page Count', format: 'number' },+ ...creditFields,+ ],+ } satisfies OutputSchema,+ templates: {+ fields: [+ { key: 'template_count', label: 'Template Count', format: 'number' },+ { key: 'templates', label: 'Templates', labelKey: 'title', listItems: templateFields },+ ...creditFields,+ ],+ } satisfies OutputSchema,+ htmlTemplates: {+ fields: [+ { key: 'template_count', label: 'Template Count', format: 'number' },+ {+ key: 'templates',+ label: 'Templates',+ labelKey: 'title',+ listItems: [+ ...templateFields,+ { key: 'sample_data', label: 'Sample Data (JSON)' },+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },+ ],+ },+ ...creditFields,+ ],+ } satisfies OutputSchema,+ parseDocument: {+ fields: [+ { key: 'template_name', label: 'Template Name' },+ { key: 'fields', label: 'Fields', description: 'Each field name defined in the template mapped to its value.' },+ {+ key: 'tables',+ label: 'Tables',+ labelKey: 'name',+ listItems: [+ { key: 'name', label: 'Table Name' },+ { key: 'page_index', label: 'Page (0-based)', format: 'number', description: 'Page of the first table cell.' },+ { key: 'rows', label: 'Rows', description: 'Each row maps column1, column2… to { value, pageIndex }.' },+ ],+ },+ { key: 'page_count', label: 'Page Count', format: 'number' },+ ...creditFields,+ ],+ } satisfies OutputSchema,+ invoice: {+ fields: [+ { key: 'status', label: 'Status', description: '"success", or "working" if the job is still running (run this action again with the Job ID).' },+ { key: 'job_id', label: 'Job ID' },+ { key: 'vendor_name', label: 'Vendor Name' },+ { key: 'customer_name', label: 'Bill-To Name' },+ { key: 'invoice_number', label: 'Invoice Number' },+ { key: 'invoice_date', label: 'Invoice Date' },+ { key: 'due_date', label: 'Due Date' },+ { key: 'po_number', label: 'PO Number' },+ { key: 'total', label: 'Total' },+ { key: 'subtotal', label: 'Subtotal' },+ { key: 'tax', label: 'Tax' },+ { key: 'line_items', label: 'Line Items', description: 'Rows as PDF.co returns them; the keys vary by invoice unless Line Item Structure is set.' },+ { key: 'invoice', label: 'Full Invoice Data', description: 'The complete parsed invoice (vendor, customer, invoice, paymentDetails, lineItems).' },+ { key: 'page_count', label: 'Page Count', format: 'number' },+ ...creditFields,+ ],+ } satisfies OutputSchema,+ upload: {+ fields: [+ { key: 'url', label: 'File URL', format: 'url', description: 'Use this as the source URL in other PDF.co actions. Kept for 1 hour.' },+ { key: 'name', label: 'File Name' },+ { key: 'link_valid_until', label: 'Link Valid Until', format: 'datetime' },+ ...creditFields,+ ],+ } satisfies OutputSchema,+ jobStatus: {+ fields: [+ { key: 'job_id', label: 'Job ID' },+ { key: 'status', label: 'Status', description: 'working, success, failed or aborted.' },+ { key: 'message', label: 'Message' },+ { key: 'url', label: 'Result Link', format: 'url', description: 'For split jobs this is a JSON file listing the part links (see Result Links).' },+ { key: 'urls', label: 'Result Links', description: 'One link per part, for jobs with several outputs such as Split PDF.' },+ { key: 'page_count', label: 'Page Count', format: 'number' },+ { key: 'link_valid_until', label: 'Link Valid Until', format: 'datetime' },+ ...creditFields,+ { key: 'file', label: 'Saved File', description: 'The first part when the job has several outputs; not set if that part could not be saved.' },+ { key: 'files', label: 'Saved Files', description: 'One file per part, in the same order as Result Links, for jobs with several outputs. A part that could not be saved is null (see File Save Error).' },+ { key: 'file_error', label: 'File Save Error' },+ ],+ } satisfies OutputSchema,+ aiConvert: {+ fields: [+ { key: 'format', label: 'Format' },+ { key: 'content', label: 'Content', description: 'The converted content, cut to max_chars.' },+ { key: 'truncated', label: 'Truncated', format: 'boolean' },+ { key: 'total_chars', label: 'Total Characters', format: 'number' },+ { key: 'page_count', label: 'Page Count', format: 'number' },+ ...creditFields,+ ],+ } satisfies OutputSchema,+};diff --git a/packages/pieces/community/pdf-co/test/actions.test.ts b/packages/pieces/community/pdf-co/test/actions.test.tsnew file mode 100644index 00000000000..10f53562833--- /dev/null+++ b/packages/pieces/community/pdf-co/test/actions.test.ts@@ -0,0 +1,355 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ addBarcodeToPdf,+ addImageToPdf,+ addPasswordToPdf,+ convertDocumentToPdf,+ convertHtmlToPdf,+ convertPdfToImage,+ convertPdfToStructuredFormat,+ deletePdfPages,+ extractTablesFromPdf,+ extractTextFromPdf,+ fillPdfForm,+ findTextInPdf,+ getCreditBalance,+ getPdfFormFields,+ getPdfInfo,+ mergePdfs,+ parseInvoiceWithAi,+ readBarcodes,+ rotatePdfPages,+ searchAndReplaceText,+ splitPdf,+ uploadFile,+} from '../src/lib/actions';+import { pdfCo } from '../src';+import { binaryResponse, installFetch, jsonResponse, okFileResult, requestOf, runAction, STORAGE_URL } from './helpers';++let fetchMock: ReturnType<typeof installFetch>;++beforeEach(() => {+ fetchMock = installFetch();+});++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++describe('piece metadata', () => {+ it('every action has audience, classification, aiMetadata and outputSchema', () => {+ const actions = Object.values(pdfCo.actions());+ expect(actions.length).toBe(37);+ for (const action of actions) {+ expect(['both', 'human', 'ai']).toContain(action.audience);+ expect(action.classification).toBeDefined();+ expect(action.aiMetadata?.description.length).toBeGreaterThan(40);+ expect(action.outputSchema?.fields.length).toBeGreaterThan(0);+ }+ });++ it('keeps all 8 original action names', () => {+ const names = Object.keys(pdfCo.actions());+ for (const name of [+ 'add_barcode_to_pdf',+ 'add_image_to_pdf',+ 'add_text_to_pdf',+ 'convert_html_to_pdf',+ 'convert_pdf_to_structured_format',+ 'extract_tables_from_pdf',+ 'extract_text_from_pdf',+ 'search_and_replace_text',+ ]) {+ expect(names).toContain(name);+ }+ });+});++describe('existing actions keep their output', () => {+ it('Add Image keeps outputUrl/pageCount/outputName and does not download by default', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: okFileResult() }));+ const result = await runAction({+ action: addImageToPdf,+ propsValue: { url: 'https://a.example/a.pdf', imageUrl: 'https://a.example/logo.png', xCoordinate: 10, yCoordinate: 20 },+ });+ expect(result).toEqual({ outputUrl: STORAGE_URL, pageCount: 2, outputName: 'result.pdf', creditsUsed: 4, remainingCredits: 9000 });+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(requestOf({ fetchMock, call: 0 }).body).toMatchObject({+ url: 'https://a.example/a.pdf',+ images: [{ url: 'https://a.example/logo.png', x: 10, y: 20 }],+ async: false,+ inline: false,+ });+ });++ it('Add Barcode returns the raw body plus a saved file when asked', async () => {+ const written: { fileName: string; size: number }[] = [];+ fetchMock+ .mockResolvedValueOnce(jsonResponse({ body: { url: 'https://pdf-temp-files.s3.amazonaws.com/b/barcode.png', error: false } }))+ .mockResolvedValueOnce(jsonResponse({ body: okFileResult() }))+ .mockResolvedValueOnce(binaryResponse({ data: Buffer.from('pdf') }));+ const result = await runAction({+ action: addBarcodeToPdf,+ propsValue: { sourcePdfUrl: 'https://a.example/a.pdf', barcodeValue: 'X1', barcodeType: 'QRCode', x: 1, y: 2, saveOutputFile: true, fileName: 'b.pdf' },+ written,+ });+ expect(result).toMatchObject({ ...okFileResult(), file: 'https://files.example/b.pdf' });+ expect(requestOf({ fetchMock, call: 0 })).toMatchObject({ url: 'https://api.pdf.co/v1/barcode/generate', body: { value: 'X1', type: 'QRCode' } });+ expect(written).toEqual([{ fileName: 'b.pdf', size: 3 }]);+ });++ it('Convert HTML uses Custom Paper Size over the dropdown', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: okFileResult() }));+ await runAction({ action: convertHtmlToPdf, propsValue: { html: '<p>x</p>', paperSize: 'A4', customPaperSize: ' 200mm 300mm ' } });+ expect(requestOf({ fetchMock, call: 0 }).body).toMatchObject({ html: '<p>x</p>', paperSize: '200mm 300mm', async: false });+ });++ it('Convert PDF to structured format supports the new XLSX value', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: okFileResult({ name: 'sample.xlsx' }) }));+ const result = await runAction({ action: convertPdfToStructuredFormat, propsValue: { url: 'https://a.example/a.pdf', outputFormat: 'xlsx' } });+ expect(requestOf({ fetchMock, call: 0 }).url).toBe('https://api.pdf.co/v1/pdf/convert/to/xlsx');+ expect(result).toMatchObject({ name: 'sample.xlsx', url: STORAGE_URL });+ });++ it('Extract Tables returns an empty list instead of crashing when there are no objects (B9)', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: { error: false, status: 200, pageCount: 1 } }));+ const result = await runAction({ action: extractTablesFromPdf, propsValue: { url: 'https://a.example/a.pdf', templateId: '1' } });+ expect(result).toEqual({ extractedTables: [], templateNameUsed: undefined });+ });++ it('Extract Text keeps text-simple by default and switches to OCR text when asked', async () => {+ fetchMock+ .mockResolvedValueOnce(jsonResponse({ body: { body: 'hello', pageCount: 1, name: 'a.txt', credits: 4, remainingCredits: 1 } }))+ .mockResolvedValueOnce(jsonResponse({ body: { body: 'scan', pageCount: 1, name: 'a.txt', credits: 21, remainingCredits: 1 } }));+ const plain = await runAction({ action: extractTextFromPdf, propsValue: { url: 'https://a.example/a.pdf' } });+ expect(plain).toEqual({ extractedText: 'hello', pageCount: 1, outputName: 'a.txt', creditsUsed: 4, remainingCredits: 1 });+ expect(requestOf({ fetchMock, call: 0 }).url).toBe('https://api.pdf.co/v1/pdf/convert/to/text-simple');+ await runAction({ action: extractTextFromPdf, propsValue: { url: 'https://a.example/a.pdf', useOcr: true, lang: 'deu' } });+ expect(requestOf({ fetchMock, call: 1 })).toMatchObject({ url: 'https://api.pdf.co/v1/pdf/convert/to/text', body: { lang: 'deu', inline: true } });+ });++ it('Search and Replace rejects lists of different length before calling PDF.co (B6)', async () => {+ await expect(+ runAction({ action: searchAndReplaceText, propsValue: { url: 'https://a.example/a.pdf', searchStrings: ['a', 'b'], replaceStrings: ['x'] } }),+ ).rejects.toThrow('Text to Locate has 2 entries but Replacement Text has 1');+ await expect(+ runAction({ action: searchAndReplaceText, propsValue: { url: 'https://a.example/a.pdf', searchStrings: [], replaceStrings: [] } }),+ ).rejects.toThrow('at least one');+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('Search and Replace sends strings, not raw values', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: okFileResult() }));+ await runAction({ action: searchAndReplaceText, propsValue: { url: 'https://a.example/a.pdf', searchStrings: [2024], replaceStrings: [2025], replacementLimit: 1 } });+ expect(requestOf({ fetchMock, call: 0 }).body).toMatchObject({ searchStrings: ['2024'], replaceStrings: ['2025'], replacementLimit: 1 });+ });+});++describe('new file actions', () => {+ it('Merge PDFs joins URLs then uploaded files in order and saves the result by default', async () => {+ const written: { fileName: string; size: number }[] = [];+ fetchMock+ .mockResolvedValueOnce(+ jsonResponse({ body: { presignedUrl: 'https://pdf-temp-files.s3.amazonaws.com/up/c.pdf?sig', url: 'https://pdf-temp-files.s3.amazonaws.com/up/c.pdf' } }),+ )+ .mockResolvedValueOnce(new Response(null, { status: 200 }))+ .mockResolvedValueOnce(jsonResponse({ body: okFileResult() }))+ .mockResolvedValueOnce(binaryResponse({ data: Buffer.from('merged') }));+ const result = await runAction({+ action: mergePdfs,+ propsValue: {+ sourceUrls: ['https://a.example/a.pdf', 'https://a.example/b.pdf'],+ sourceFiles: [{ file: { filename: 'c.pdf', data: Buffer.from('%PDF') } }],+ saveOutputFile: true,+ },+ written,+ });+ expect(requestOf({ fetchMock, call: 2 })).toMatchObject({+ url: 'https://api.pdf.co/v1/pdf/merge',+ body: { url: 'https://a.example/a.pdf,https://a.example/b.pdf,https://pdf-temp-files.s3.amazonaws.com/up/c.pdf', async: false },+ });+ expect(result).toMatchObject({ status: 'success', url: STORAGE_URL, file: 'https://files.example/result.pdf' });+ });++ it('Merge PDFs needs at least two inputs', async () => {+ await expect(runAction({ action: mergePdfs, propsValue: { sourceUrls: ['https://a.example/a.pdf'] } })).rejects.toThrow('at least two');+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('Split PDF sends 1-based ranges and returns one link per part', async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ body: { urls: ['https://pdf-temp-files.s3.amazonaws.com/p1.pdf', 'https://pdf-temp-files.s3.amazonaws.com/p2.pdf'], pageCount: 4, error: false } }),+ );+ const result = await runAction({ action: splitPdf, propsValue: { sourceUrl: 'https://a.example/a.pdf', pages: '1-2,3-' } });+ expect(requestOf({ fetchMock, call: 0 }).body).toMatchObject({ url: 'https://a.example/a.pdf', pages: '1-2,3-' });+ expect(result).toMatchObject({ urls: ['https://pdf-temp-files.s3.amazonaws.com/p1.pdf', 'https://pdf-temp-files.s3.amazonaws.com/p2.pdf'], page_count: 4 });+ });++ it('Delete Pages and Rotate send the documented fields', async () => {+ fetchMock.mockImplementation(async () => jsonResponse({ body: okFileResult() }));+ await runAction({ action: deletePdfPages, propsValue: { sourceUrl: 'https://a.example/a.pdf', pages: '1,3' } });+ await runAction({ action: rotatePdfPages, propsValue: { sourceUrl: 'https://a.example/a.pdf', angle: '180', pages: '' } });+ expect(requestOf({ fetchMock, call: 0 })).toMatchObject({ url: 'https://api.pdf.co/v1/pdf/edit/delete-pages', body: { pages: '1,3' } });+ const rotate = requestOf({ fetchMock, call: 1 });+ expect(rotate).toMatchObject({ url: 'https://api.pdf.co/v1/pdf/edit/rotate', body: { angle: 180 } });+ expect(rotate.body).not.toHaveProperty('pages');+ });++ it('Rotate rejects an angle that is not 90/180/270', async () => {+ await expect(runAction({ action: rotatePdfPages, propsValue: { sourceUrl: 'https://a.example/a.pdf', angle: '45' } })).rejects.toThrow('90, 180 or 270');+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('Protect PDF sends permission flags explicitly (off by default, like PDF.co)', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: okFileResult() }));+ await runAction({ action: addPasswordToPdf, propsValue: { sourceUrl: 'https://a.example/a.pdf', ownerPassword: 'own', allowPrintDocument: true } });+ expect(requestOf({ fetchMock, call: 0 }).body).toMatchObject({ ownerPassword: 'own', allowPrintDocument: true, allowModifyDocument: false });+ });++ it('Convert PDF to Images hits the format endpoint', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: { urls: ['https://pdf-temp-files.s3.amazonaws.com/p0.png'], pageCount: 1 } }));+ await runAction({ action: convertPdfToImage, propsValue: { sourceUrl: 'https://a.example/a.pdf', format: 'webp' } });+ expect(requestOf({ fetchMock, call: 0 }).url).toBe('https://api.pdf.co/v1/pdf/convert/to/webp');+ });++ it('Convert Document rejects extra image URLs for non-image sources', async () => {+ await expect(+ runAction({ action: convertDocumentToPdf, propsValue: { sourceType: 'document', sourceUrl: 'https://a.example/a.docx', extraImageUrls: ['https://a.example/b.png'] } }),+ ).rejects.toThrow('only works with Source Type "Images"');+ });++ it('Fill PDF Form validates field names and can flatten', async () => {+ await expect(runAction({ action: fillPdfForm, propsValue: { sourceUrl: 'https://a.example/f.pdf', fields: [{ text: 'x' }] } })).rejects.toThrow(+ 'Field #1 needs a field name',+ );+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: okFileResult() }));+ await runAction({+ action: fillPdfForm,+ propsValue: { sourceUrl: 'https://a.example/f.pdf', fields: [{ fieldName: 'name', text: 'Jo', pages: 0 }], flatten: true, saveOutputFile: false },+ });+ expect(requestOf({ fetchMock, call: 0 }).body).toMatchObject({+ fields: [{ fieldName: 'name', text: 'Jo', pages: '0' }],+ profiles: JSON.stringify({ 'FlattenDocument()': [] }),+ });+ });+});++describe('new read actions', () => {+ it('Get Credit Balance flattens remainingCredits', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: { remainingCredits: 9428 } }));+ await expect(runAction({ action: getCreditBalance, propsValue: {} })).resolves.toEqual({ remaining_credits: 9428 });+ });++ it('Get PDF Info flattens the info object', async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ body: { info: { PageCount: 1, Title: 'T', Encrypted: false, PageRectangle: { Width: 612, Height: 792 } }, credits: 7, remainingCredits: 1 } }),+ );+ const result = await runAction({ action: getPdfInfo, propsValue: { sourceUrl: 'https://a.example/a.pdf' } });+ expect(result).toMatchObject({ page_count: 1, title: 'T', encrypted: false, page_width: 612, page_height: 792, credits_used: 7 });+ });++ it('Get PDF Form Fields lists fields with exact names', async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ body: { info: { PageCount: 3, FieldsInfo: { Fields: [{ FieldName: 'f1', Type: 'Text', Value: '', PageIndex: 0 }] } } } }),+ );+ const result = await runAction({ action: getPdfFormFields, propsValue: { sourceUrl: 'https://a.example/a.pdf' } });+ expect(result).toMatchObject({ field_count: 1, fields: [{ field_name: 'f1', type: 'Text', page_index: 0 }] });+ });++ it('Find Text returns flat matches', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: { body: [{ text: 'Invoice', pageIndex: 0, left: 1, top: 2, width: 3, height: 4 }], pageCount: 1 } }));+ const result = await runAction({ action: findTextInPdf, propsValue: { sourceUrl: 'https://a.example/a.pdf', searchString: 'Invoice' } });+ expect(result).toMatchObject({ match_count: 1, matches: [{ text: 'Invoice', page_index: 0 }] });+ expect(requestOf({ fetchMock, call: 0 }).body).toMatchObject({ searchString: 'Invoice', inline: true, async: false });+ });++ it('Read Barcodes sends the type list as a comma string', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: { barcodes: [{ Value: 'abc', TypeName: 'QRCode', Page: 0, Rect: '{X=1}', Confidence: 1 }] } }));+ const result = await runAction({ action: readBarcodes, propsValue: { sourceUrl: 'https://a.example/a.pdf', types: ['QRCode', 'Code128'] } });+ expect(requestOf({ fetchMock, call: 0 }).body).toMatchObject({ types: 'QRCode,Code128' });+ expect(result).toMatchObject({ barcode_count: 1, barcodes: [{ value: 'abc', type: 'QRCode' }] });+ });++ it('Parse Invoice with AI always runs async and returns working with the job ID at the ceiling', async () => {+ vi.useFakeTimers();+ fetchMock+ .mockResolvedValueOnce(jsonResponse({ body: { error: false, status: 'created', jobId: 'INV1', credits: 100 } }))+ .mockImplementation(async () => jsonResponse({ body: { status: 'working' } }));+ const pending = runAction({ action: parseInvoiceWithAi, propsValue: { sourceUrl: 'https://a.example/inv.pdf' } });+ await vi.advanceTimersByTimeAsync(241_000);+ await expect(pending).resolves.toMatchObject({ status: 'working', job_id: 'INV1' });+ expect(requestOf({ fetchMock, call: 0 })).toMatchObject({ url: 'https://api.pdf.co/v1/ai-invoice-parser', body: { async: true } });+ });++ it('Parse Invoice with AI flattens the finished invoice', async () => {+ vi.useFakeTimers();+ fetchMock+ .mockResolvedValueOnce(jsonResponse({ body: { error: false, status: 'created', jobId: 'INV2' } }))+ .mockResolvedValueOnce(+ jsonResponse({+ body: {+ status: 'success',+ body: {+ vendor: { name: 'ACME' },+ customer: { billTo: { name: 'Lanny' } },+ invoice: { invoiceNo: '67', invoiceDate: 'JAN 5' },+ paymentDetails: { total: '$1', tax: '$0' },+ lineItems: [[{ description: 'Item 1' }]],+ },+ credits: 100,+ },+ }),+ );+ const pending = runAction({ action: parseInvoiceWithAi, propsValue: { sourceUrl: 'https://a.example/inv.pdf', customFields: ['deliveryDate'] } });+ await vi.advanceTimersByTimeAsync(3_000);+ await expect(pending).resolves.toMatchObject({+ status: 'success',+ vendor_name: 'ACME',+ customer_name: 'Lanny',+ invoice_number: '67',+ total: '$1',+ line_items: [{ description: 'Item 1' }],+ });+ expect(requestOf({ fetchMock, call: 0 }).body).toMatchObject({ customField: 'deliveryDate' });+ });++ it('Parse Invoice rejects custom field names that are not camelCase words', async () => {+ await expect(runAction({ action: parseInvoiceWithAi, propsValue: { sourceUrl: 'https://a.example/inv.pdf', customFields: ['delivery date'] } })).rejects.toThrow(+ 'camelCase',+ );+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('Upload File returns the storage link, name and credits from the presigned step', async () => {+ fetchMock+ .mockResolvedValueOnce(+ jsonResponse({+ body: {+ presignedUrl: 'https://pdf-temp-files.s3.us-west-2.amazonaws.com/u/scan.png?X-Amz-SignedHeaders=host',+ url: STORAGE_URL,+ name: 'scan.png',+ outputLinkValidTill: '2026-10-05T20:00:00Z',+ credits: 7,+ remainingCredits: 9000,+ error: false,+ },+ }),+ )+ .mockResolvedValueOnce(new Response(null, { status: 200 }));+ await expect(runAction({ action: uploadFile, propsValue: { file: { filename: 'scan.png', data: Buffer.from('png') } } })).resolves.toEqual({+ url: STORAGE_URL,+ name: 'scan.png',+ link_valid_until: '2026-10-05T20:00:00Z',+ credits_used: 7,+ remaining_credits: 9000,+ });+ expect(requestOf({ fetchMock, call: 0 }).url).toContain('contenttype=image%2Fpng');+ expect(requestOf({ fetchMock, call: 1 }).headers['content-type']).toBe('image/png');+ });++ it('Upload File rejects a value that is not a file before any request', async () => {+ await expect(runAction({ action: uploadFile, propsValue: { file: 'not-a-file' } })).rejects.toThrow('could not be read');+ expect(fetchMock).not.toHaveBeenCalled();+ });+});diff --git a/packages/pieces/community/pdf-co/test/ai.test.ts b/packages/pieces/community/pdf-co/test/ai.test.tsnew file mode 100644index 00000000000..8d50d8e7e5e--- /dev/null+++ b/packages/pieces/community/pdf-co/test/ai.test.ts@@ -0,0 +1,86 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { pdfCoConvertPdf, pdfCoEditPdf, pdfCoParseDocument } from '../src/lib/actions';+import { installFetch, jsonResponse, okFileResult, requestOf, runAction } from './helpers';++let fetchMock: ReturnType<typeof installFetch>;++beforeEach(() => {+ fetchMock = installFetch();+});++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('Convert PDF (AI)', () => {+ it('returns inline content cut to max_chars with a truncated flag', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: { body: 'abcdefghij', pageCount: 1, credits: 4 } }));+ const result = await runAction({ action: pdfCoConvertPdf, propsValue: { source_url: 'https://a.example/a.pdf', max_chars: 4 } });+ expect(result).toMatchObject({ format: 'text', content: 'abcd', truncated: true, total_chars: 10 });+ expect(requestOf({ fetchMock, call: 0 })).toMatchObject({ url: 'https://api.pdf.co/v1/pdf/convert/to/text-simple', body: { inline: true } });+ });++ it('stringifies JSON content and rejects unknown formats', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: { body: { document: { page: [] } } } }));+ const result = await runAction({ action: pdfCoConvertPdf, propsValue: { source_url: 'https://a.example/a.pdf', format: 'JSON' } });+ expect(result).toMatchObject({ format: 'json', content: '{"document":{"page":[]}}', truncated: false });+ await expect(runAction({ action: pdfCoConvertPdf, propsValue: { source_url: 'https://a.example/a.pdf', format: 'docx' } })).rejects.toThrow('format must be one of');+ });+});++describe('Edit PDF (AI)', () => {+ it('sends annotations, images and fields in one request', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: okFileResult() }));+ await runAction({+ action: pdfCoEditPdf,+ propsValue: {+ source_url: 'https://a.example/a.pdf',+ annotations: [{ text: 'Hi', x: '10', y: 20, pages: 0 }],+ images: '[{"url":"https://a.example/logo.png","x":1,"y":2}]',+ fields: [{ fieldName: 'f', text: 'v' }],+ },+ });+ expect(requestOf({ fetchMock, call: 0 }).body).toMatchObject({+ annotations: [{ text: 'Hi', x: 10, y: 20, pages: '0' }],+ images: [{ url: 'https://a.example/logo.png', x: 1, y: 2 }],+ fields: [{ fieldName: 'f', text: 'v' }],+ async: false,+ });+ });++ it('rejects unknown keys, missing coordinates and empty edits before calling PDF.co', async () => {+ await expect(runAction({ action: pdfCoEditPdf, propsValue: { source_url: 'https://a.example/a.pdf', annotations: [{ text: 'a', x: 1, y: 2, bogus: 1 }] } })).rejects.toThrow(+ 'unknown keys: bogus',+ );+ await expect(runAction({ action: pdfCoEditPdf, propsValue: { source_url: 'https://a.example/a.pdf', images: [{ url: 'https://a.example/i.png', x: 1 }] } })).rejects.toThrow(+ 'missing: y',+ );+ await expect(runAction({ action: pdfCoEditPdf, propsValue: { source_url: 'https://a.example/a.pdf' } })).rejects.toThrow('at least one item');+ expect(fetchMock).not.toHaveBeenCalled();+ });+});++describe('Parse Document (AI)', () => {+ it('flattens fields and tables and validates the template ID', async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ body: {+ body: {+ templateName: 'Invoice Parser',+ objects: [+ { name: 'total', objectType: 'field', value: 6.58 },+ { name: 'items', objectType: 'table', pageIndex: 0, rows: [[{ cellType: 'field' }]] },+ ],+ },+ pageCount: 1,+ },+ }),+ );+ const result = await runAction({ action: pdfCoParseDocument, propsValue: { source_url: 'https://a.example/inv.pdf', template_id: '1' } });+ expect(result).toMatchObject({ template_name: 'Invoice Parser', fields: { total: 6.58 }, tables: [{ name: 'items', page_index: 0 }] });+ expect(requestOf({ fetchMock, call: 0 }).body).toMatchObject({ templateId: 1, inline: true });+ await expect(runAction({ action: pdfCoParseDocument, propsValue: { source_url: 'https://a.example/inv.pdf', template_id: 'abc' } })).rejects.toThrow(+ 'positive whole number',+ );+ });+});diff --git a/packages/pieces/community/pdf-co/test/client.test.ts b/packages/pieces/community/pdf-co/test/client.test.tsnew file mode 100644index 00000000000..971466c858c--- /dev/null+++ b/packages/pieces/community/pdf-co/test/client.test.ts@@ -0,0 +1,139 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { pdfCoClient, PdfCoError } from '../src/lib/common/client';+import { pdfCoAuth } from '../src/lib/auth';+import { API_KEY, installFetch, jsonResponse, requestOf } from './helpers';++let fetchMock: ReturnType<typeof installFetch>;++beforeEach(() => {+ fetchMock = installFetch();+});++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++describe('pdfCoRequest', () => {+ it('sends the API key only in the x-api-key header to api.pdf.co', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: { remainingCredits: 5 } }));+ await pdfCoClient.request({ apiKey: API_KEY, method: HttpMethod.GET, path: '/v1/account/credit/balance' });+ const request = requestOf({ fetchMock, call: 0 });+ expect(request.url).toBe('https://api.pdf.co/v1/account/credit/balance');+ expect(request.headers['x-api-key']).toBe(API_KEY);+ expect(request.url).not.toContain(API_KEY);+ expect(request.redirect).toBe('manual');+ });++ it('treats a redirect from api.pdf.co as a failure instead of following it', async () => {+ fetchMock.mockResolvedValueOnce(new Response(null, { status: 302, headers: { location: 'http://169.254.169.254/' } }));+ const error = await pdfCoClient.request({ apiKey: API_KEY, method: HttpMethod.GET, path: '/v1/account/credit/balance' }).catch((e: unknown) => e);+ expect(error).toBeInstanceOf(PdfCoError);+ expect(String(error)).toContain('(302)');+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it('B1: never puts the PDF password, HTTP password or API key into the error message', async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ status: 441, body: { status: 'error', errorCode: 441, error: true, message: `Invalid password s3cret-pdf for ${API_KEY}` } }),+ );+ const error = await pdfCoClient+ .request({+ apiKey: API_KEY,+ method: HttpMethod.POST,+ path: '/v1/pdf/info',+ body: { url: 'https://example.com/a.pdf', password: 's3cret-pdf', httppassword: 'http-s3cret', httpusername: 'bob' },+ })+ .catch((e: unknown) => e);+ expect(error).toBeInstanceOf(PdfCoError);+ const text = String(error) + JSON.stringify(error);+ expect(text).not.toContain('s3cret-pdf');+ expect(text).not.toContain('http-s3cret');+ expect(text).not.toContain(API_KEY);+ expect(String(error)).toContain('PDF.co request failed (441)');+ expect(String(error)).toContain('PDF password is wrong');+ });++ it('B1: a 400 error body does not echo the request body', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ status: 400, body: { error: true, errorCode: 400, message: 'Unable to download the file' } }));+ const error = await pdfCoClient+ .request({ apiKey: API_KEY, method: HttpMethod.POST, path: '/v1/pdf/info', body: { url: 'x', httppassword: 'top-secret-1' } })+ .catch((e: unknown) => e);+ expect(String(error)).not.toContain('top-secret-1');+ expect(JSON.stringify(error)).not.toContain('top-secret-1');+ });++ it('keeps status and responseBody but never a field named body on the error', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ status: 402, body: { error: true, errorCode: 402, message: 'Not enough credits' } }));+ const error = await pdfCoClient.request({ apiKey: API_KEY, method: HttpMethod.GET, path: '/v1/templates/html' }).catch((e: unknown) => e);+ expect(error).toBeInstanceOf(PdfCoError);+ expect(error).toMatchObject({ status: 402, errorCode: 402, responseBody: { errorCode: 402, message: 'Not enough credits' } });+ expect(Object.keys(pdfCoClient.readRecord(error))).not.toContain('body');+ expect(String(error)).toContain('out of credits');+ });++ it('throws when PDF.co answers HTTP 200 with error: true', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ status: 200, body: { error: true, status: 'error', errorCode: 445, message: 'Timeout' } }));+ await expect(+ pdfCoClient.request({ apiKey: API_KEY, method: HttpMethod.POST, path: '/v1/pdf/merge', body: { url: 'a,b' } }),+ ).rejects.toThrow('PDF.co request failed (445): Timeout. The job took longer than 30 seconds');+ });++ it('retries a 429 after a 5 s backoff and then succeeds', async () => {+ vi.useFakeTimers();+ fetchMock+ .mockResolvedValueOnce(jsonResponse({ status: 429, body: { message: 'Too many requests' } }))+ .mockResolvedValueOnce(jsonResponse({ body: { remainingCredits: 7 } }));+ const pending = pdfCoClient.request<{ remainingCredits: number }>({ apiKey: API_KEY, method: HttpMethod.GET, path: '/v1/account/credit/balance' });+ await vi.advanceTimersByTimeAsync(4_000);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(1_000);+ await expect(pending).resolves.toEqual({ remainingCredits: 7 });+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ it('gives up after two 429 retries (20 s of waiting in total)', async () => {+ vi.useFakeTimers();+ fetchMock.mockImplementation(async () => jsonResponse({ status: 429, body: { message: 'Too many requests' } }));+ const pending = pdfCoClient.request({ apiKey: API_KEY, method: HttpMethod.GET, path: '/v1/account/credit/balance' }).catch((e: unknown) => e);+ await vi.advanceTimersByTimeAsync(20_000);+ const error = await pending;+ expect(String(error)).toContain('PDF.co request failed (429)');+ expect(fetchMock).toHaveBeenCalledTimes(3);+ });++ it('refuses paths that would leave the PDF.co API', async () => {+ await expect(pdfCoClient.request({ apiKey: API_KEY, method: HttpMethod.GET, path: '//evil.io/v1/x' })).rejects.toThrow('Invalid PDF.co API path');+ await expect(pdfCoClient.request({ apiKey: API_KEY, method: HttpMethod.GET, path: '/v1/../x' })).rejects.toThrow('Invalid PDF.co API path');+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('redacts secrets from network errors', async () => {+ fetchMock.mockRejectedValueOnce(new Error(`socket hang up near ${API_KEY}`));+ await expect(pdfCoClient.request({ apiKey: API_KEY, method: HttpMethod.GET, path: '/v1/account/credit/balance' })).rejects.toThrow(+ 'Could not reach PDF.co: socket hang up near ***',+ );+ });+});++describe('auth validate', () => {+ const validate = pdfCoAuth.validate;++ it('is invalid only on 401 or 403', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ status: 401, body: { status: 'error', errorCode: 401, error: true, message: 'Unauthorized' } }));+ await expect(validate?.({ auth: ' bad ', server: { apiUrl: '', publicUrl: '', token: '' } })).resolves.toMatchObject({ valid: false });+ expect(requestOf({ fetchMock, call: 0 }).headers['x-api-key']).toBe('bad');+ });++ it('stays valid on a 500 so an outage does not block saving the connection', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ status: 500, body: { message: 'oops' } }));+ await expect(validate?.({ auth: 'good', server: { apiUrl: '', publicUrl: '', token: '' } })).resolves.toEqual({ valid: true });+ });++ it('is valid when the free balance call succeeds', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: { remainingCredits: 10 } }));+ await expect(validate?.({ auth: 'good', server: { apiUrl: '', publicUrl: '', token: '' } })).resolves.toEqual({ valid: true });+ expect(requestOf({ fetchMock, call: 0 }).url).toBe('https://api.pdf.co/v1/account/credit/balance');+ });+});diff --git a/packages/pieces/community/pdf-co/test/files.test.ts b/packages/pieces/community/pdf-co/test/files.test.tsnew file mode 100644index 00000000000..6baa5709fd1--- /dev/null+++ b/packages/pieces/community/pdf-co/test/files.test.ts@@ -0,0 +1,223 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { pdfCoFiles } from '../src/lib/common/files';+import { pdfCoJobs } from '../src/lib/common/jobs';+import { API_KEY, binaryResponse, installFetch, jsonResponse, okFileResult, requestOf, STORAGE_URL } from './helpers';++let fetchMock: ReturnType<typeof installFetch>;++beforeEach(() => {+ fetchMock = installFetch();+});++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++const memoryFiles = () => {+ const written: { fileName: string; size: number }[] = [];+ return {+ written,+ files: {+ write: async ({ fileName, data }: { fileName: string; data: Buffer }) => {+ written.push({ fileName, size: data.byteLength });+ return `https://files.example/${fileName}`;+ },+ },+ };+};++describe('storage host pinning', () => {+ it('accepts only PDF.co temporary storage over https', () => {+ expect(pdfCoFiles.isStorageUrl('https://pdf-temp-files.s3.amazonaws.com/a/b.pdf')).toBe(true);+ expect(pdfCoFiles.isStorageUrl('https://pdf-temp-files.s3.us-west-2.amazonaws.com/a/b.pdf')).toBe(true);+ expect(pdfCoFiles.isStorageUrl('https://pdf-temp-files.s3.amazonaws.com.evil.io/a.pdf')).toBe(false);+ expect(pdfCoFiles.isStorageUrl('http://pdf-temp-files.s3.amazonaws.com/a.pdf')).toBe(false);+ expect(pdfCoFiles.isStorageUrl('https://[email protected]/a.pdf')).toBe(false);+ expect(pdfCoFiles.isStorageUrl('https://pdf-temp-files.s3.amazonaws.com:8443/a.pdf')).toBe(false);+ expect(pdfCoFiles.isStorageUrl('https://evil-pdf-temp-files.s3.amazonaws.com/a.pdf')).toBe(false);+ });++ it('does not download a result link from another host', async () => {+ await expect(pdfCoFiles.downloadStorageFile({ url: 'https://pdf-temp-files.s3.amazonaws.com.evil.io/x.pdf' })).rejects.toThrow(+ 'not on PDF.co file storage',+ );+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('does not follow a redirect off the storage host and does not save the redirect body', async () => {+ fetchMock.mockResolvedValueOnce(new Response('moved', { status: 302, headers: { location: 'http://169.254.169.254/latest/meta-data/' } }));+ await expect(pdfCoFiles.downloadStorageFile({ url: STORAGE_URL })).rejects.toThrow('HTTP 302');+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(requestOf({ fetchMock, call: 0 }).redirect).toBe('manual');+ });++ it('fails the upload when the presigned PUT answers with a redirect', async () => {+ fetchMock+ .mockResolvedValueOnce(+ jsonResponse({+ body: {+ presignedUrl: 'https://pdf-temp-files.s3.us-west-2.amazonaws.com/u/doc.pdf?X-Amz-SignedHeaders=host',+ url: 'https://pdf-temp-files.s3.us-west-2.amazonaws.com/u/doc.pdf',+ },+ }),+ )+ .mockResolvedValueOnce(new Response(null, { status: 307, headers: { location: 'http://127.0.0.1/' } }));+ await expect(pdfCoFiles.uploadFile({ apiKey: API_KEY, file: { filename: 'doc.pdf', data: Buffer.from('x') } })).rejects.toThrow(+ 'HTTP 307',+ );+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });+});++describe('source resolution', () => {+ it('needs exactly one of URL or file, before any request', async () => {+ await expect(pdfCoFiles.resolveSource({ apiKey: API_KEY, url: '', file: undefined })).rejects.toThrow('give a file URL or pick a file');+ await expect(+ pdfCoFiles.resolveSource({ apiKey: API_KEY, url: 'https://a.example/x.pdf', file: { filename: 'a.pdf', data: Buffer.from('x') } }),+ ).rejects.toThrow('not both');+ await expect(pdfCoFiles.resolveSource({ apiKey: API_KEY, url: 'ftp://a.example/x.pdf', file: undefined })).rejects.toThrow('http://');+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('accepts a cache: prefixed URL as is', async () => {+ await expect(pdfCoFiles.resolveSource({ apiKey: API_KEY, url: ' cache:https://a.example/x.pdf ', file: undefined })).resolves.toBe(+ 'cache:https://a.example/x.pdf',+ );+ });++ it('uploads a file with a presigned PUT that carries the same content type and no API key', async () => {+ fetchMock+ .mockResolvedValueOnce(+ jsonResponse({+ body: {+ presignedUrl: 'https://pdf-temp-files.s3.us-west-2.amazonaws.com/u/doc.pdf?X-Amz-SignedHeaders=content-type;host',+ url: 'https://pdf-temp-files.s3.us-west-2.amazonaws.com/u/doc.pdf?X-Amz-Expires=3600',+ error: false,+ status: 200,+ },+ }),+ )+ .mockResolvedValueOnce(new Response(null, { status: 200 }));+ const url = await pdfCoFiles.resolveSource({ apiKey: API_KEY, url: undefined, file: { filename: 'doc.pdf', data: Buffer.from('%PDF-1.4') } });+ expect(url).toBe('https://pdf-temp-files.s3.us-west-2.amazonaws.com/u/doc.pdf?X-Amz-Expires=3600');+ const presign = requestOf({ fetchMock, call: 0 });+ expect(presign.url).toBe('https://api.pdf.co/v1/file/upload/get-presigned-url?name=doc.pdf&contenttype=application%2Fpdf');+ const put = requestOf({ fetchMock, call: 1 });+ expect(put.method).toBe('PUT');+ expect(put.headers['content-type']).toBe('application/pdf');+ expect(put.headers['x-api-key']).toBeUndefined();+ expect(put.redirect).toBe('manual');+ });++ it('refuses to PUT to a presigned URL outside PDF.co storage', async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ body: { presignedUrl: 'https://pdf-temp-files.s3.amazonaws.com.evil.io/u', url: 'https://pdf-temp-files.s3.amazonaws.com/u' } }),+ );+ await expect(pdfCoFiles.uploadFile({ apiKey: API_KEY, file: { filename: 'a.pdf', data: Buffer.from('x') } })).rejects.toThrow(+ 'outside its file storage',+ );+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it('duck-types files instead of instanceof', () => {+ expect(pdfCoFiles.isFileLike({ filename: 'a.pdf', data: Buffer.from('x'), extension: 'pdf' })).toBe(true);+ expect(pdfCoFiles.isFileLike({ filename: 'a.pdf', data: 'x' })).toBe(false);+ });+});++describe('save output to file', () => {+ it('downloads the result with Accept */* and no API key, then writes it to the flow', async () => {+ const { files, written } = memoryFiles();+ fetchMock.mockResolvedValueOnce(binaryResponse({ data: Buffer.from('%PDF-result') }));+ const output = await pdfCoJobs.buildFileOutput({ result: { body: okFileResult(), status: 'success' }, files, saveOutputFile: true, fileName: 'out.pdf' });+ expect(output).toMatchObject({ status: 'success', url: STORAGE_URL, file: 'https://files.example/out.pdf', page_count: 2, credits_used: 4 });+ expect(written).toEqual([{ fileName: 'out.pdf', size: 11 }]);+ const download = requestOf({ fetchMock, call: 0 });+ expect(download.headers['accept']).toBe('*/*');+ expect(download.headers['x-api-key']).toBeUndefined();+ });++ it('reports a failed download in file_error instead of failing the step', async () => {+ const { files } = memoryFiles();+ fetchMock.mockResolvedValueOnce(binaryResponse({ data: Buffer.from('x'), headers: { 'content-length': String(200 * 1024 * 1024) } }));+ const output = await pdfCoJobs.buildFileOutput({ result: { body: okFileResult(), status: 'success' }, files, saveOutputFile: true });+ expect(output.file).toBeUndefined();+ expect(output.file_error).toContain('larger than 100 MB');+ expect(output.url).toBe(STORAGE_URL);+ });++ it('does not download when saving is off', async () => {+ const { files } = memoryFiles();+ const output = await pdfCoJobs.buildFileOutput({ result: { body: okFileResult(), status: 'success' }, files, saveOutputFile: false });+ expect(output.file).toBeUndefined();+ expect(fetchMock).not.toHaveBeenCalled();+ });+});++describe('background jobs', () => {+ it('sends async true, polls job/check and returns the finished result', async () => {+ vi.useFakeTimers();+ fetchMock+ .mockResolvedValueOnce(jsonResponse({ body: { jobId: 'JOB1', url: STORAGE_URL, error: false, status: 200 } }))+ .mockResolvedValueOnce(jsonResponse({ body: { status: 'working', remainingCredits: 10 } }))+ .mockResolvedValueOnce(jsonResponse({ body: { status: 'success', url: STORAGE_URL, jobId: 'JOB1', credits: 2, pageCount: 3 } }));+ const pending = pdfCoJobs.runJob({ apiKey: API_KEY, path: '/v1/pdf/merge', body: { url: 'a,b' }, background: true });+ await vi.advanceTimersByTimeAsync(3_000 + 5_000);+ const result = await pending;+ expect(result).toMatchObject({ status: 'success', jobId: 'JOB1', body: { pageCount: 3 } });+ expect(requestOf({ fetchMock, call: 0 }).body).toMatchObject({ async: true, url: 'a,b' });+ expect(requestOf({ fetchMock, call: 1 })).toMatchObject({ url: 'https://api.pdf.co/v1/job/check', body: { jobid: 'JOB1' } });+ });++ it('returns the job ID with status working when the 240 s ceiling is reached', async () => {+ vi.useFakeTimers();+ fetchMock+ .mockResolvedValueOnce(jsonResponse({ body: { jobId: 'JOB2', url: STORAGE_URL, error: false } }))+ .mockImplementation(async () => jsonResponse({ body: { status: 'working' } }));+ const pending = pdfCoJobs.runJob({ apiKey: API_KEY, path: '/v1/pdf/split', body: { url: 'a' }, background: true });+ await vi.advanceTimersByTimeAsync(241_000);+ const result = await pending;+ expect(result).toMatchObject({ status: 'working', jobId: 'JOB2' });+ const checks = fetchMock.mock.calls.length - 1;+ expect(checks).toBeLessThanOrEqual(12);+ expect(checks).toBeGreaterThan(5);+ });++ it('throws with the vendor message when the job fails', async () => {+ vi.useFakeTimers();+ fetchMock+ .mockResolvedValueOnce(jsonResponse({ body: { jobId: 'JOB3' } }))+ .mockResolvedValueOnce(jsonResponse({ body: { status: 'failed', message: 'Damaged file' } }));+ const pending = pdfCoJobs.runJob({ apiKey: API_KEY, path: '/v1/pdf/merge', body: {}, background: true }).catch((e: unknown) => e);+ await vi.advanceTimersByTimeAsync(3_000);+ expect(String(await pending)).toContain('PDF.co background job JOB3 failed: Damaged file');+ });++ it('stops polling on a 404 job', async () => {+ vi.useFakeTimers();+ fetchMock+ .mockResolvedValueOnce(jsonResponse({ body: { jobId: 'JOB4' } }))+ .mockResolvedValueOnce(jsonResponse({ status: 404, body: { errorCode: 404, error: true, message: 'Job not found' } }));+ const pending = pdfCoJobs.runJob({ apiKey: API_KEY, path: '/v1/pdf/merge', body: {}, background: true }).catch((e: unknown) => e);+ await vi.advanceTimersByTimeAsync(3_000);+ expect(String(await pending)).toContain('PDF.co request failed (404): Job not found');+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ it('reads split part links from the JSON result file of a finished background job', async () => {+ const { files } = memoryFiles();+ const jsonUrl = 'https://pdf-temp-files.s3.us-west-2.amazonaws.com/j/result.json?X-Amz-Expires=3600';+ fetchMock.mockResolvedValueOnce(+ new Response(JSON.stringify(['https://pdf-temp-files.s3.amazonaws.com/p1.pdf', 'https://pdf-temp-files.s3.amazonaws.com/p2.pdf'])),+ );+ const output = await pdfCoJobs.buildFileOutput({+ result: { body: { url: jsonUrl, status: 'success' }, status: 'success', jobId: 'J' },+ files,+ saveOutputFile: false,+ multiOutput: true,+ });+ expect(output.urls).toEqual(['https://pdf-temp-files.s3.amazonaws.com/p1.pdf', 'https://pdf-temp-files.s3.amazonaws.com/p2.pdf']);+ expect(output.url).toBe('https://pdf-temp-files.s3.amazonaws.com/p1.pdf');+ });+});diff --git a/packages/pieces/community/pdf-co/test/helpers.ts b/packages/pieces/community/pdf-co/test/helpers.tsnew file mode 100644index 00000000000..5a9fbc10246--- /dev/null+++ b/packages/pieces/community/pdf-co/test/helpers.ts@@ -0,0 +1,84 @@+import { AppConnectionType } from '@activepieces/pieces-framework';+import { vi } from 'vitest';+import { createMockActionContext } from '../../../framework/src/lib/test';++export const API_KEY = 'key_test_123';++export function auth() {+ return { type: AppConnectionType.SECRET_TEXT, secret_text: ` ${API_KEY} ` };+}++export function runAction({+ action,+ propsValue,+ written = [],+}: {+ action: { run: (context: never) => Promise<unknown> };+ propsValue: Record<string, unknown>;+ written?: { fileName: string; size: number }[];+}): Promise<unknown> {+ const base = createMockActionContext({ propsValue: {} });+ const context = {+ ...base,+ propsValue,+ auth: auth(),+ files: {+ ...base.files,+ write: async ({ fileName, data }: { fileName: string; data: Buffer }) => {+ written.push({ fileName, size: data.byteLength });+ return `https://files.example/${fileName}`;+ },+ },+ };+ return Reflect.apply(action.run, action, [context]);+}++export function jsonResponse({ status = 200, body, headers = {} }: { status?: number; body: unknown; headers?: Record<string, string> }): Response {+ return new Response(body === undefined ? null : JSON.stringify(body), {+ status,+ headers: { 'content-type': 'application/json', ...headers },+ });+}++export function binaryResponse({ data, headers = {} }: { data: Buffer; headers?: Record<string, string> }): Response {+ return new Response(new Uint8Array(data), { status: 200, headers: { 'content-type': 'application/pdf', ...headers } });+}++export function installFetch() {+ const fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);+ return fetchMock;+}++export function requestOf({ fetchMock, call }: { fetchMock: ReturnType<typeof vi.fn>; call: number }) {+ const [input, init] = fetchMock.mock.calls[call];+ const headers = new Headers(init?.headers);+ const rawBody = init?.body;+ const body = typeof rawBody === 'string' ? safeJson(rawBody) : rawBody;+ return { url: String(input), method: String(init?.method ?? 'GET'), headers: Object.fromEntries(headers.entries()), body, redirect: init?.redirect };+}++export const STORAGE_URL = 'https://pdf-temp-files.s3.us-west-2.amazonaws.com/abc/result.pdf?X-Amz-Expires=3600';++export function okFileResult(overrides: Record<string, unknown> = {}) {+ return {+ url: STORAGE_URL,+ pageCount: 2,+ error: false,+ status: 200,+ name: 'result.pdf',+ credits: 4,+ remainingCredits: 9000,+ outputLinkValidTill: '2026-10-05T20:00:00Z',+ duration: 120,+ ...overrides,+ };+}++function safeJson(text: string): unknown {+ try {+ return JSON.parse(text);+ } catch {+ return text;+ }+}diff --git a/packages/pieces/community/pdf-co/test/live-fixes.test.ts b/packages/pieces/community/pdf-co/test/live-fixes.test.tsnew file mode 100644index 00000000000..aa5e4ebf029--- /dev/null+++ b/packages/pieces/community/pdf-co/test/live-fixes.test.ts@@ -0,0 +1,303 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ checkJobStatus,+ compressPdf,+ convertHtmlToPdf,+ convertPdfToStructuredFormat,+ extractTablesFromPdf,+ parseDocument,+ parseInvoiceWithAi,+} from '../src/lib/actions';+import { pdfCoClient } from '../src/lib/common/client';+import { pdfCoJobs } from '../src/lib/common/jobs';+import { API_KEY, binaryResponse, installFetch, jsonResponse, okFileResult, requestOf, runAction, STORAGE_URL } from './helpers';++let fetchMock: ReturnType<typeof installFetch>;++beforeEach(() => {+ fetchMock = installFetch();+});++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++const PART_1 = 'https://pdf-temp-files.s3.us-west-2.amazonaws.com/A/sample_page1-1.pdf?X-Amz-Expires=3600';+const PART_2 = 'https://pdf-temp-files.s3.us-west-2.amazonaws.com/B/sample_page2-2.pdf?X-Amz-Expires=3600';+const LISTING = 'https://pdf-temp-files.s3.us-west-2.amazonaws.com/C/sample.json?X-Amz-Expires=3600';++describe('B8: profiles are sent as a JSON string', () => {+ it('serializes objects, keeps strings and drops empty values', () => {+ expect(pdfCoClient.serializeProfiles({ OutputStructure: 'OnlyLinks' })).toBe('{"OutputStructure":"OnlyLinks"}');+ expect(pdfCoClient.serializeProfiles("{ 'TrimSpaces': true }")).toBe("{ 'TrimSpaces': true }");+ expect(pdfCoClient.serializeProfiles({})).toBeUndefined();+ expect(pdfCoClient.serializeProfiles(' ')).toBeUndefined();+ expect(pdfCoClient.serializeProfiles(undefined)).toBeUndefined();+ });++ it('Convert PDF to structured format sends profiles as a string (an object gets HTTP 400 live)', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: okFileResult() }));+ await runAction({+ action: convertPdfToStructuredFormat,+ propsValue: { url: 'https://a.example/a.pdf', outputFormat: 'json', profiles: { OutputStructure: 'OnlyLinks' } },+ });+ expect(requestOf({ fetchMock, call: 0 }).body).toMatchObject({ profiles: '{"OutputStructure":"OnlyLinks"}' });+ });++ it('Extract Tables sends profiles as a string', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: { body: { objects: [] } } }));+ await runAction({+ action: extractTablesFromPdf,+ propsValue: { url: 'https://a.example/a.pdf', templateId: '1', profiles: { DetectNewColumnBySpacesRatio: 1.5 } },+ });+ expect(requestOf({ fetchMock, call: 0 }).body).toMatchObject({ profiles: '{"DetectNewColumnBySpacesRatio":1.5}' });+ });++ it('Convert HTML sends profiles as a string and omits an empty object', async () => {+ fetchMock.mockImplementation(async () => jsonResponse({ body: okFileResult() }));+ await runAction({ action: convertHtmlToPdf, propsValue: { html: '<p>x</p>', profiles: { PreserveFormattingOnTextExtraction: true } } });+ expect(requestOf({ fetchMock, call: 0 }).body).toMatchObject({ profiles: '{"PreserveFormattingOnTextExtraction":true}' });+ await runAction({ action: convertHtmlToPdf, propsValue: { html: '<p>x</p>', profiles: {} } });+ expect(requestOf({ fetchMock, call: 1 }).body).not.toHaveProperty('profiles');+ });+});++describe('background jobs report the credits of the whole job', () => {+ it('adds the start call and every status check (live: compress 35 + 2 + 2 = 39)', async () => {+ vi.useFakeTimers();+ fetchMock+ .mockResolvedValueOnce(jsonResponse({ body: { jobId: 'J1', status: 'working', credits: 35, remainingCredits: 100 } }))+ .mockResolvedValueOnce(jsonResponse({ body: { status: 'working', credits: 2, remainingCredits: 98 } }))+ .mockResolvedValueOnce(jsonResponse({ body: { status: 'success', url: STORAGE_URL, pageCount: 1, credits: 2, remainingCredits: 96 } }));+ const pending = runAction({+ action: compressPdf,+ propsValue: { sourceUrl: 'https://a.example/a.pdf', runInBackground: true, saveOutputFile: false },+ });+ await vi.advanceTimersByTimeAsync(3_000 + 5_000);+ await expect(pending).resolves.toMatchObject({ status: 'success', job_id: 'J1', credits_used: 39, remaining_credits: 96 });+ });++ it('keeps the summed credits when the ceiling is reached', async () => {+ vi.useFakeTimers();+ fetchMock+ .mockResolvedValueOnce(jsonResponse({ body: { jobId: 'J2', credits: 8 } }))+ .mockImplementation(async () => jsonResponse({ body: { status: 'working', credits: 2, remainingCredits: 50 } }));+ const pending = pdfCoJobs.runJob({ apiKey: API_KEY, path: '/v1/pdf/split', body: {}, background: true, pollCeilingMs: 10_000 });+ await vi.advanceTimersByTimeAsync(10_000);+ const result = await pending;+ expect(result.status).toBe('working');+ expect(result.body).toMatchObject({ credits: 8 + 2 * (fetchMock.mock.calls.length - 1), remainingCredits: 50 });+ });++ it('Parse Invoice with AI reports the 100 credits of the start call, not the free check', async () => {+ vi.useFakeTimers();+ fetchMock+ .mockResolvedValueOnce(jsonResponse({ body: { jobId: 'INV', status: 'working', credits: 100, remainingCredits: 8489 } }))+ .mockResolvedValueOnce(+ jsonResponse({ body: { status: 'success', jobId: 'INV', pageCount: 1, body: { vendor: { name: 'ACME Inc.' } }, credits: 0, remainingCredits: 8489 } }),+ );+ const pending = runAction({ action: parseInvoiceWithAi, propsValue: { sourceUrl: 'https://a.example/inv.pdf' } });+ await vi.advanceTimersByTimeAsync(3_000);+ await expect(pending).resolves.toMatchObject({ status: 'success', vendor_name: 'ACME Inc.', credits_used: 100, remaining_credits: 8489 });+ });+});++describe('finished split jobs', () => {+ it('takes the part links from the job/check body without downloading the JSON listing', async () => {+ const output = await pdfCoJobs.buildFileOutput({+ result: { body: { status: 'success', url: LISTING, body: [PART_1, PART_2] }, status: 'success', jobId: 'S1' },+ files: { write: async () => 'unused' },+ saveOutputFile: false,+ multiOutput: true,+ });+ expect(output).toMatchObject({ url: PART_1, urls: [PART_1, PART_2] });+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('Check Job Status returns the part links and saves each part', async () => {+ const written: { fileName: string; size: number }[] = [];+ fetchMock+ .mockResolvedValueOnce(jsonResponse({ body: { status: 'success', message: 'Success', url: LISTING, body: [PART_1, PART_2], credits: 2, remainingCredits: 9311 } }))+ .mockResolvedValueOnce(binaryResponse({ data: Buffer.from('p1') }))+ .mockResolvedValueOnce(binaryResponse({ data: Buffer.from('p2!') }));+ const result = await runAction({ action: checkJobStatus, propsValue: { jobId: 'S1', saveOutputFile: true }, written });+ expect(result).toMatchObject({+ status: 'success',+ url: LISTING,+ urls: [PART_1, PART_2],+ file: 'https://files.example/sample_page1-1.pdf',+ files: ['https://files.example/sample_page1-1.pdf', 'https://files.example/sample_page2-2.pdf'],+ credits_used: 2,+ });+ expect(written).toEqual([+ { fileName: 'sample_page1-1.pdf', size: 2 },+ { fileName: 'sample_page2-2.pdf', size: 3 },+ ]);+ });++ it('Check Job Status leaves urls out for single-file jobs', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ body: { status: 'success', url: STORAGE_URL, credits: 2 } }));+ const result = await runAction({ action: checkJobStatus, propsValue: { jobId: 'C1' } });+ expect(result).toMatchObject({ status: 'success', url: STORAGE_URL });+ expect(result).not.toHaveProperty('urls', expect.anything());+ });+});++describe('Parse Document table page', () => {+ it('falls back to the first cell page when the table has no pageIndex (live shape)', async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ body: {+ body: {+ templateName: 'Generic Invoice [en]',+ objects: [+ { name: 'total', objectType: 'field', value: 1272.35 },+ { name: 'table', objectType: 'table', rows: [{ column1: { pageIndex: 0, value: '2' }, column2: { pageIndex: 0, value: 'Item 1' } }] },+ ],+ },+ pageCount: 1,+ credits: 42,+ },+ }),+ );+ const result = await runAction({ action: parseDocument, propsValue: { sourceUrl: 'https://a.example/inv.pdf', templateId: '1' } });+ expect(result).toMatchObject({ fields: { total: 1272.35 }, tables: [{ name: 'table', page_index: 0 }], credits_used: 42 });+ });+});++describe('error text', () => {+ it('does not double the full stop after a vendor message that ends with one', async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ status: 400, body: { errorCode: 400, error: true, message: 'Incorrect input parameters, please check and try again.' } }),+ );+ const error = await pdfCoClient.request({ apiKey: API_KEY, method: HttpMethod.POST, path: '/v1/pdf/convert/to/json2', body: {} }).catch((e: unknown) => e);+ expect(String(error)).toContain('(400): Incorrect input parameters, please check and try again. Check the input values');+ expect(String(error)).not.toContain('..');+ });+});++function urlOf(input: unknown): string {+ if (typeof input === 'string') {+ return input;+ }+ if (input instanceof URL) {+ return input.toString();+ }+ return input instanceof Request ? input.url : String(input);+}++describe('Greptile round 1: background results', () => {+ it('Check Job Status reads the part links from the JSON listing when job/check has no list, and saves the parts', async () => {+ const written: { fileName: string; size: number }[] = [];+ fetchMock.mockImplementation(async (input: unknown) => {+ const url = urlOf(input);+ if (url.includes('/v1/job/check')) {+ return jsonResponse({ body: { status: 'success', url: LISTING, credits: 2 } });+ }+ if (url === LISTING) {+ return jsonResponse({ body: [PART_1, PART_2] });+ }+ return binaryResponse({ data: Buffer.from(url === PART_1 ? 'p1' : 'p2!') });+ });+ const result = await runAction({ action: checkJobStatus, propsValue: { jobId: 'S2', saveOutputFile: true }, written });+ expect(result).toMatchObject({+ status: 'success',+ urls: [PART_1, PART_2],+ files: ['https://files.example/sample_page1-1.pdf', 'https://files.example/sample_page2-2.pdf'],+ });+ expect(written.map((entry) => entry.fileName).sort()).toEqual(['sample_page1-1.pdf', 'sample_page2-2.pdf']);+ });++ it('Check Job Status saves a JSON result as one file when it is not a list of links', async () => {+ const written: { fileName: string; size: number }[] = [];+ fetchMock.mockImplementation(async (input: unknown) => {+ if (urlOf(input).includes('/v1/job/check')) {+ return jsonResponse({ body: { status: 'success', url: LISTING } });+ }+ return jsonResponse({ body: [{ text: 'page 1' }] });+ });+ const result = await runAction({ action: checkJobStatus, propsValue: { jobId: 'J9', saveOutputFile: true }, written });+ expect(result).toMatchObject({ status: 'success', url: LISTING, file: 'https://files.example/sample.json' });+ expect(result).not.toHaveProperty('urls', expect.anything());+ expect(written).toHaveLength(1);+ });++ it('keeps the saved parts and names the failed one when a single part cannot be downloaded', async () => {+ const written: { fileName: string; size: number }[] = [];+ fetchMock.mockImplementation(async (input: unknown) =>+ urlOf(input) === PART_1+ ? binaryResponse({ data: Buffer.from('p1') })+ : binaryResponse({ data: Buffer.from('x'), headers: { 'content-length': String(200 * 1024 * 1024) } }),+ );+ const output = await pdfCoJobs.buildFileOutput({+ result: { body: { status: 'success', body: [PART_1, PART_2] }, status: 'success', jobId: 'S3' },+ files: {+ write: async ({ fileName, data }) => {+ written.push({ fileName, size: data.byteLength });+ return `https://files.example/${fileName}`;+ },+ },+ saveOutputFile: true,+ multiOutput: true,+ });+ expect(output.files).toEqual(['https://files.example/sample_page1-1.pdf', null]);+ expect(output.file).toBe('https://files.example/sample_page1-1.pdf');+ expect(output.file_error).toContain('1 of 2 results could not be saved as files (part 2)');+ expect(output.urls).toEqual([PART_1, PART_2]);+ });++ it('Parse Invoice with AI picks up a running job by Job ID without starting a new parse', async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ body: { status: 'success', pageCount: 1, body: { vendor: { name: 'ACME Inc.' }, paymentDetails: { total: '$5' } }, credits: 0 } }),+ );+ const result = await runAction({ action: parseInvoiceWithAi, propsValue: { jobId: ' INV9 ' } });+ expect(result).toMatchObject({ status: 'success', job_id: 'INV9', vendor_name: 'ACME Inc.', total: '$5' });+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(requestOf({ fetchMock, call: 0 })).toMatchObject({ url: 'https://api.pdf.co/v1/job/check', body: { jobid: 'INV9' } });+ });++ it('Parse Invoice with AI returns working again with the same Job ID when the job is still running', async () => {+ vi.useFakeTimers();+ fetchMock.mockImplementation(async () => jsonResponse({ body: { status: 'working' } }));+ const pending = runAction({ action: parseInvoiceWithAi, propsValue: { jobId: 'INV10' } });+ await vi.advanceTimersByTimeAsync(241_000);+ await expect(pending).resolves.toMatchObject({ status: 'working', job_id: 'INV10' });+ expect(requestOf({ fetchMock, call: 0 }).url).toBe('https://api.pdf.co/v1/job/check');+ });++ it('keeps each saved file at its part number when part 1 fails and part 2 saves', async () => {+ fetchMock.mockImplementation(async (input: unknown) =>+ urlOf(input) === PART_2+ ? binaryResponse({ data: Buffer.from('p2') })+ : binaryResponse({ data: Buffer.from('x'), headers: { 'content-length': String(200 * 1024 * 1024) } }),+ );+ const output = await pdfCoJobs.buildFileOutput({+ result: { body: { status: 'success', body: [PART_1, PART_2] }, status: 'success', jobId: 'S4' },+ files: { write: async ({ fileName }) => `https://files.example/${fileName}` },+ saveOutputFile: true,+ multiOutput: true,+ });+ expect(output.urls).toEqual([PART_1, PART_2]);+ expect(output.files).toEqual([null, 'https://files.example/sample_page2-2.pdf']);+ expect(output).not.toHaveProperty('file');+ expect(output.file_error).toContain('1 of 2 results could not be saved as files (part 1)');+ });++ it('Check Job Status keeps each saved file at its part number when part 1 fails', async () => {+ fetchMock.mockImplementation(async (input: unknown) => {+ const url = urlOf(input);+ if (url.includes('/v1/job/check')) {+ return jsonResponse({ body: { status: 'success', url: LISTING, body: [PART_1, PART_2], credits: 2 } });+ }+ return url === PART_2+ ? binaryResponse({ data: Buffer.from('p2') })+ : binaryResponse({ data: Buffer.from('x'), headers: { 'content-length': String(200 * 1024 * 1024) } });+ });+ const result = await runAction({ action: checkJobStatus, propsValue: { jobId: 'S5', saveOutputFile: true }, written: [] });+ expect(result).toMatchObject({ urls: [PART_1, PART_2], files: [null, 'https://files.example/sample_page2-2.pdf'] });+ expect(result).not.toHaveProperty('file');+ expect(result['file_error']).toContain('(part 1)');+ });+});diff --git a/packages/pieces/community/pdf-co/vitest.config.ts b/packages/pieces/community/pdf-co/vitest.config.tsnew file mode 100644index 00000000000..79c97261904--- /dev/null+++ b/packages/pieces/community/pdf-co/vitest.config.ts@@ -0,0 +1,19 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ root: __dirname,+ test: {+ globals: true,+ environment: 'node',+ include: ['test/**/*.test.ts'],+ },+ resolve: {+ alias: {+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),+ },+ },+})