Skip to content

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

feat(convertapi): merge, split and convert files with ConvertAPI (#15855)

Odai Ahmadd1764cf6fd6c
diff --git a/bun.lock b/bun.lock
index ccf465fd93b..a4a63c6e52b 100644
--- a/bun.lock
+++ b/bun.lock
@@ -2224,6 +2224,18 @@
"tslib": "2.6.2",
},
},
+ "packages/pieces/community/convertapi": {
+ "name": "@activepieces/piece-convertapi",
+ "version": "0.0.1",
+ "dependencies": {
+ "@activepieces/pieces-common": "workspace:*",
+ "@activepieces/pieces-framework": "workspace:*",
+ },
+ "devDependencies": {
+ "tslib": "2.6.2",
+ "vitest": "3.2.6",
+ },
+ },
"packages/pieces/community/convertkit": {
"name": "@activepieces/piece-convertkit",
"version": "0.3.9",
@@ -11477,6 +11489,8 @@
"@activepieces/piece-contiguity": ["@activepieces/piece-contiguity@workspace:packages/pieces/community/contiguity"],
+ "@activepieces/piece-convertapi": ["@activepieces/piece-convertapi@workspace:packages/pieces/community/convertapi"],
+
"@activepieces/piece-convertkit": ["@activepieces/piece-convertkit@workspace:packages/pieces/community/convertkit"],
"@activepieces/piece-copper": ["@activepieces/piece-copper@workspace:packages/pieces/community/copper"],
diff --git a/packages/pieces/community/convertapi/.eslintrc.json b/packages/pieces/community/convertapi/.eslintrc.json
new file mode 100644
index 00000000000..9ee1a0770e8
--- /dev/null
+++ b/packages/pieces/community/convertapi/.eslintrc.json
@@ -0,0 +1,26 @@
+{
+ "extends": ["../../../../.eslintrc.json"],
+ "ignorePatterns": ["!**/*"],
+ "overrides": [
+ { "files": ["*.ts", "*.tsx", "*.js", "*.jsx"], "rules": {} },
+ {
+ "files": ["*.ts", "*.tsx"],
+ "rules": {
+ "no-restricted-imports": [
+ "error",
+ {
+ "patterns": [
+ "lodash",
+ "lodash/*",
+ "@activepieces/core-*",
+ "@activepieces/server*",
+ "@activepieces/engine",
+ "@activepieces/shared"
+ ]
+ }
+ ]
+ }
+ },
+ { "files": ["*.js", "*.jsx"], "rules": {} }
+ ]
+}
diff --git a/packages/pieces/community/convertapi/package.json b/packages/pieces/community/convertapi/package.json
new file mode 100644
index 00000000000..9a823efc6e3
--- /dev/null
+++ b/packages/pieces/community/convertapi/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "@activepieces/piece-convertapi",
+ "version": "0.0.1",
+ "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'",
+ "test": "vitest run"
+ },
+ "dependencies": {
+ "@activepieces/pieces-common": "workspace:*",
+ "@activepieces/pieces-framework": "workspace:*"
+ },
+ "devDependencies": {
+ "tslib": "2.6.2",
+ "vitest": "3.2.6"
+ }
+}
diff --git a/packages/pieces/community/convertapi/src/i18n/translation.json b/packages/pieces/community/convertapi/src/i18n/translation.json
new file mode 100644
index 00000000000..2a2b00cb1c0
--- /dev/null
+++ b/packages/pieces/community/convertapi/src/i18n/translation.json
@@ -0,0 +1,85 @@
+{
+ "Convert, merge and split documents, images and PDFs with 300+ file converters.": "Convert, merge and split documents, images and PDFs with 300+ file converters.",
+ "To get your API token:\n1. Sign in to [ConvertAPI](https://www.convertapi.com/a).\n2. Open **Authentication** (https://www.convertapi.com/a/authentication).\n3. Copy an existing **API Token**, or create a new one, and paste it here.": "To get your API token:\n1. Sign in to [ConvertAPI](https://www.convertapi.com/a).\n2. Open **Authentication** (https://www.convertapi.com/a/authentication).\n3. Copy an existing **API Token**, or create a new one, and paste it here.",
+ "Merge PDF Files": "Merge PDF Files",
+ "Split PDF File": "Split PDF File",
+ "Convert File": "Convert File",
+ "Custom API Call": "Custom API Call",
+ "Combine several PDF files into one PDF, in the order you list them.": "Combine several PDF files into one PDF, in the order you list them.",
+ "Split a PDF into several PDFs by page count, page ranges, single pages, matching text or bookmarks.": "Split a PDF into several PDFs by page count, page ranges, single pages, matching text or bookmarks.",
+ "Convert a file to another format with any of ConvertAPI's converters, such as Word to PDF or PDF to JPG. Extra file inputs (like a template or overlay file) are not supported here; use Custom API Call for those.": "Convert a file to another format with any of ConvertAPI's converters, such as Word to PDF or PDF to JPG. Extra file inputs (like a template or overlay file) are not supported here; use Custom API Call for those.",
+ "Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",
+ "PDF Files": "PDF Files",
+ "Output File Name": "Output File Name",
+ "Password": "Password",
+ "Bookmark Each File": "Bookmark Each File",
+ "Page Size": "Page Size",
+ "Page Orientation": "Page Orientation",
+ "PDF File": "PDF File",
+ "Split By": "Split By",
+ "Markdown": "Markdown",
+ "Split Value": "Split Value",
+ "Merge Parts Into One PDF": "Merge Parts Into One PDF",
+ "From Format": "From Format",
+ "To Format": "To Format",
+ "File": "File",
+ "Additional Files": "Additional Files",
+ "Conversion Options": "Conversion Options",
+ "Method": "Method",
+ "Headers": "Headers",
+ "Query Parameters": "Query Parameters",
+ "Body Type": "Body Type",
+ "Body": "Body",
+ "Response is Binary": "Response is Binary",
+ "Return Error as Output": "Return Error as Output",
+ "Timeout": "Timeout",
+ "Follow redirects": "Follow redirects",
+ "Add the PDFs in the order they should appear. At least two are needed.": "Add the PDFs in the order they should appear. At least two are needed.",
+ "Merged file name, without the extension. Leave empty for a default.": "Merged file name, without the extension. Leave empty for a default.",
+ "Only needed if the PDFs are password-protected. Used for every file.": "Only needed if the PDFs are password-protected. Used for every file.",
+ "Add a top-level bookmark for each merged file.": "Add a top-level bookmark for each merged file.",
+ "Scale every page to this size, or keep the original size.": "Scale every page to this size, or keep the original size.",
+ "Rotate every page to this orientation, or keep the original.": "Rotate every page to this orientation, or keep the original.",
+ "The PDF to split.": "The PDF to split.",
+ "How the PDF is cut into parts.": "How the PDF is cut into parts.",
+ "**Split Value** by mode:\n- **Page count**: pages per part, e.g. `5`, or a repeating pattern such as `3,2`. Leave empty for one file per page.\n- **Page ranges**: one part per range, e.g. `1-3,5,7-9` gives three files.\n- **Single pages**: each listed page becomes its own file, e.g. `1-2,5` gives pages 1, 2 and 5.\n- **Text match**: a regular expression; a new part starts at every page whose text matches, e.g. `Invoice\\s+#\\d+`.\n- **Bookmarks**: leave empty.": "**Split Value** by mode:\n- **Page count**: pages per part, e.g. `5`, or a repeating pattern such as `3,2`. Leave empty for one file per page.\n- **Page ranges**: one part per range, e.g. `1-3,5,7-9` gives three files.\n- **Single pages**: each listed page becomes its own file, e.g. `1-2,5` gives pages 1, 2 and 5.\n- **Text match**: a regular expression; a new part starts at every page whose text matches, e.g. `Invoice\\s+#\\d+`.\n- **Bookmarks**: leave empty.",
+ "What to split on. The format depends on the Split By mode.": "What to split on. The format depends on the Split By mode.",
+ "Join the parts back into one PDF, e.g. to extract selected pages.": "Join the parts back into one PDF, e.g. to extract selected pages.",
+ "Only needed if the PDF is password-protected.": "Only needed if the PDF is password-protected.",
+ "Base name for the parts, without extension. Each part gets a number.": "Base name for the parts, without extension. Each part gets a number.",
+ "The format of the file you are converting.": "The format of the file you are converting.",
+ "What to convert the file into.": "What to convert the file into.",
+ "The file to convert.": "The file to convert.",
+ "Files to add after the main one, for converters that combine files.": "Files to add after the main one, for converters that combine files.",
+ "Options of the chosen converter. Leave empty for the defaults.": "Options of the chosen converter. Leave empty for the defaults.",
+ "Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.",
+ "Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.",
+ "Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.",
+ "On a failed request, output the error instead of failing the step.": "On a failed request, output the error instead of failing the step.",
+ "Seconds to wait for a response. Empty: up to the flow limit (10 min).": "Seconds to wait for a response. Empty: up to the flow limit (10 min).",
+ "Follow 3xx redirects instead of returning them as the response.": "Follow 3xx redirects instead of returning them as the response.",
+ "No bookmarks": "No bookmarks",
+ "Use file names": "Use file names",
+ "Use PDF titles": "Use PDF titles",
+ "Original": "Original",
+ "A2": "A2",
+ "A3": "A3",
+ "A4": "A4",
+ "A5": "A5",
+ "A6": "A6",
+ "Letter": "Letter",
+ "Legal": "Legal",
+ "Portrait": "Portrait",
+ "Landscape": "Landscape",
+ "Page count (every N pages)": "Page count (every N pages)",
+ "Page ranges": "Page ranges",
+ "Single pages": "Single pages",
+ "Text match (regular expression)": "Text match (regular expression)",
+ "Bookmarks": "Bookmarks",
+ "GET": "GET",
+ "POST": "POST",
+ "PATCH": "PATCH",
+ "PUT": "PUT",
+ "DELETE": "DELETE",
+ "HEAD": "HEAD"
+}
\ No newline at end of file
diff --git a/packages/pieces/community/convertapi/src/index.ts b/packages/pieces/community/convertapi/src/index.ts
new file mode 100644
index 00000000000..ef1426fc455
--- /dev/null
+++ b/packages/pieces/community/convertapi/src/index.ts
@@ -0,0 +1,30 @@
+import { createCustomApiCallAction } from '@activepieces/pieces-common';
+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';
+import { convertFileAction } from './lib/actions/convert-file';
+import { mergePdfAction } from './lib/actions/merge-pdf';
+import { splitPdfAction } from './lib/actions/split-pdf';
+import { convertApiAuth } from './lib/auth';
+import { CONVERTAPI_BASE_URL } from './lib/common/client';
+
+export const convertapi = createPiece({
+ displayName: 'ConvertAPI',
+ description: 'Convert, merge and split documents, images and PDFs with 300+ file converters.',
+ minimumSupportedRelease: '0.82.0',
+ logoUrl: 'https://cdn.activepieces.com/pieces/convertapi.png',
+ categories: [PieceCategory.CONTENT_AND_FILES],
+ auth: convertApiAuth,
+ authors: ['OdaiAhmed99'],
+ actions: [
+ mergePdfAction,
+ splitPdfAction,
+ convertFileAction,
+ createCustomApiCallAction({
+ baseUrl: () => CONVERTAPI_BASE_URL,
+ auth: convertApiAuth,
+ authMapping: async (auth) => ({
+ Authorization: `Bearer ${auth.secret_text}`,
+ }),
+ }),
+ ],
+ triggers: [],
+});
diff --git a/packages/pieces/community/convertapi/src/lib/actions/convert-file.ts b/packages/pieces/community/convertapi/src/lib/actions/convert-file.ts
new file mode 100644
index 00000000000..fe20cb31be0
--- /dev/null
+++ b/packages/pieces/community/convertapi/src/lib/actions/convert-file.ts
@@ -0,0 +1,127 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { convertApiAuth } from '../auth';
+import { convertApi } from '../common/client';
+import { converterInfo } from '../common/converters';
+import { inputFiles } from '../common/input-files';
+import { convertFileOutputSchema } from '../output-schemas';
+
+export const convertFileAction = createAction({
+ auth: convertApiAuth,
+ name: 'convert_file',
+ classification: 'WRITE',
+ displayName: 'Convert File',
+ description: 'Convert a file to another format with any of ConvertAPI\'s converters, such as Word to PDF or PDF to JPG. Extra file inputs (like a template or overlay file) are not supported here; use Custom API Call for those.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Converts a file between formats with any ConvertAPI converter (Office, PDF, images, HTML, CAD, email and more) and returns a list with one stored file per output, since some conversions produce several files (for example one image per PDF page). Prefer Merge PDF Files or Split PDF File for those PDF jobs. Secondary file inputs such as TemplateFile or OverlayFile are not exposed; use Custom API Call for converters that need them. Each call uses ConvertAPI conversions and creates new output files.',
+ idempotent: false,
+ },
+ props: {
+ from: Property.Dropdown({
+ auth: convertApiAuth,
+ displayName: 'From Format',
+ description: 'The format of the file you are converting.',
+ required: true,
+ refreshers: [],
+ options: async () => {
+ const converters = await converterInfo.fetchConverters();
+ const options = converterInfo.sourceOptions(converters);
+ if (options.length === 0) {
+ return { disabled: true, options: [], placeholder: 'Could not load formats from ConvertAPI' };
+ }
+ return { disabled: false, options };
+ },
+ }),
+ to: Property.Dropdown({
+ auth: convertApiAuth,
+ displayName: 'To Format',
+ description: 'What to convert the file into.',
+ required: true,
+ refreshers: ['from'],
+ options: async ({ from }) => {
+ if (typeof from !== 'string' || from.length === 0) {
+ return { disabled: true, options: [], placeholder: 'Select a From Format first' };
+ }
+ const converters = await converterInfo.fetchConverters({ from });
+ const options = converterInfo.destinationOptions({ converters, from });
+ if (options.length === 0) {
+ return { disabled: true, options: [], placeholder: 'No conversions available for this format' };
+ }
+ return { disabled: false, options };
+ },
+ }),
+ file: Property.File({
+ displayName: 'File',
+ description: 'The file to convert.',
+ required: true,
+ }),
+ additionalFiles: Property.Array({
+ displayName: 'Additional Files',
+ description: 'Files to add after the main one, for converters that combine files.',
+ required: false,
+ properties: {
+ file: Property.File({
+ displayName: 'File',
+ required: true,
+ }),
+ },
+ }),
+ options: Property.DynamicProperties({
+ auth: convertApiAuth,
+ displayName: 'Conversion Options',
+ description: 'Options of the chosen converter. Leave empty for the defaults.',
+ required: false,
+ refreshers: ['from', 'to'],
+ props: async ({ from, to }) => {
+ if (typeof from !== 'string' || typeof to !== 'string' || from.length === 0 || to.length === 0) {
+ return {};
+ }
+ const converter = await converterInfo.fetchConverter({ from, to });
+ return converterInfo.optionProps(converter);
+ },
+ }),
+ },
+ outputSchema: convertFileOutputSchema,
+ async run({ auth, propsValue, files }) {
+ const converter = await converterInfo.fetchConverter({ from: propsValue.from, to: propsValue.to });
+ const mainInput = converterInfo.mainInputOf(converter);
+ if (mainInput === undefined) {
+ throw new Error(`The ${propsValue.from} to ${propsValue.to} converter does not take a file as input.`);
+ }
+ const additional = inputFiles.fromArrayItems({ items: propsValue.additionalFiles, key: 'file' });
+ if (!mainInput.multiple && additional.length > 0) {
+ throw new Error(`The ${propsValue.from} to ${propsValue.to} converter takes a single file. Remove the Additional Files.`);
+ }
+
+ const result = await convertApi.convertFiles({
+ apiKey: auth.secret_text,
+ from: propsValue.from,
+ to: propsValue.to,
+ fileInputs: [
+ { name: mainInput.name, files: [propsValue.file, ...additional], multiple: mainInput.multiple },
+ ],
+ parameters: convertApi.toValueParameters(
+ withDefaultFileName({ options: propsValue.options ?? {}, inputName: propsValue.file.filename }),
+ ),
+ files,
+ });
+
+ return result.files;
+ },
+});
+
+function withDefaultFileName({
+ options,
+ inputName,
+}: {
+ options: Record<string, unknown>;
+ inputName: string;
+}): Record<string, unknown> {
+ const current = options['FileName'];
+ const hasFileName = typeof current === 'string' && current.trim() !== '';
+ if (hasFileName || !inputName.startsWith('unknown.')) {
+ return options;
+ }
+ return { ...options, FileName: 'converted' };
+}
diff --git a/packages/pieces/community/convertapi/src/lib/actions/merge-pdf.ts b/packages/pieces/community/convertapi/src/lib/actions/merge-pdf.ts
new file mode 100644
index 00000000000..3da8a471399
--- /dev/null
+++ b/packages/pieces/community/convertapi/src/lib/actions/merge-pdf.ts
@@ -0,0 +1,114 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { convertApiAuth } from '../auth';
+import { convertApi } from '../common/client';
+import { inputFiles } from '../common/input-files';
+import { mergePdfOutputSchema } from '../output-schemas';
+
+export const mergePdfAction = createAction({
+ auth: convertApiAuth,
+ name: 'merge_pdf',
+ classification: 'WRITE',
+ displayName: 'Merge PDF Files',
+ description: 'Combine several PDF files into one PDF, in the order you list them.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Merges two or more PDF files into a single new PDF with ConvertAPI, keeping the listed order, and returns it as a stored file. Use Split PDF File to break a PDF apart, or Convert File to merge Word or PowerPoint documents. Each call uses ConvertAPI conversions and creates a new output file.',
+ idempotent: false,
+ },
+ props: {
+ files: Property.Array({
+ displayName: 'PDF Files',
+ description: 'Add the PDFs in the order they should appear. At least two are needed.',
+ required: true,
+ properties: {
+ file: Property.File({
+ displayName: 'PDF File',
+ required: true,
+ }),
+ },
+ }),
+ fileName: Property.ShortText({
+ displayName: 'Output File Name',
+ description: 'Merged file name, without the extension. Leave empty for a default.',
+ placeholder: 'e.g. combined',
+ required: false,
+ }),
+ password: Property.ShortText({
+ displayName: 'Password',
+ description: 'Only needed if the PDFs are password-protected. Used for every file.',
+ required: false,
+ }),
+ bookmarksTableOfContents: Property.StaticDropdown({
+ displayName: 'Bookmark Each File',
+ description: 'Add a top-level bookmark for each merged file.',
+ required: false,
+ defaultValue: 'disabled',
+ options: {
+ options: [
+ { label: 'No bookmarks', value: 'disabled' },
+ { label: 'Use file names', value: 'filename' },
+ { label: 'Use PDF titles', value: 'title' },
+ ],
+ },
+ }),
+ pageSize: Property.StaticDropdown({
+ displayName: 'Page Size',
+ description: 'Scale every page to this size, or keep the original size.',
+ required: false,
+ defaultValue: 'default',
+ options: {
+ options: [
+ { label: 'Original', value: 'default' },
+ { label: 'A2', value: 'a2' },
+ { label: 'A3', value: 'a3' },
+ { label: 'A4', value: 'a4' },
+ { label: 'A5', value: 'a5' },
+ { label: 'A6', value: 'a6' },
+ { label: 'Letter', value: 'letter' },
+ { label: 'Legal', value: 'legal' },
+ ],
+ },
+ }),
+ pageOrientation: Property.StaticDropdown({
+ displayName: 'Page Orientation',
+ description: 'Rotate every page to this orientation, or keep the original.',
+ required: false,
+ defaultValue: 'default',
+ options: {
+ options: [
+ { label: 'Original', value: 'default' },
+ { label: 'Portrait', value: 'portrait' },
+ { label: 'Landscape', value: 'landscape' },
+ ],
+ },
+ }),
+ },
+ outputSchema: mergePdfOutputSchema,
+ async run({ auth, propsValue, files }) {
+ const pdfFiles = inputFiles.fromArrayItems({ items: propsValue.files, key: 'file' });
+ if (pdfFiles.length < 2) {
+ throw new Error('Add at least two PDF files to merge.');
+ }
+
+ const result = await convertApi.convertFiles({
+ apiKey: auth.secret_text,
+ from: 'pdf',
+ to: 'merge',
+ fileInputs: [{ name: 'Files', files: pdfFiles, multiple: true }],
+ parameters: convertApi.toValueParameters({
+ FileName: propsValue.fileName,
+ Password: propsValue.password,
+ BookmarksTableOfContents: propsValue.bookmarksTableOfContents,
+ PageSize: propsValue.pageSize,
+ PageOrientation: propsValue.pageOrientation,
+ }),
+ files,
+ });
+
+ return {
+ ...result.files[0],
+ conversion_cost: result.conversion_cost,
+ };
+ },
+});
diff --git a/packages/pieces/community/convertapi/src/lib/actions/split-pdf.ts b/packages/pieces/community/convertapi/src/lib/actions/split-pdf.ts
new file mode 100644
index 00000000000..9fbc45f0851
--- /dev/null
+++ b/packages/pieces/community/convertapi/src/lib/actions/split-pdf.ts
@@ -0,0 +1,99 @@
+import { createAction, MarkdownVariant, Property } from '@activepieces/pieces-framework';
+import { convertApiAuth } from '../auth';
+import { convertApi } from '../common/client';
+import { splitPdfOutputSchema } from '../output-schemas';
+
+export const splitPdfAction = createAction({
+ auth: convertApiAuth,
+ name: 'split_pdf',
+ classification: 'WRITE',
+ displayName: 'Split PDF File',
+ description: 'Split a PDF into several PDFs by page count, page ranges, single pages, matching text or bookmarks.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Splits one PDF into multiple new PDFs with ConvertAPI and returns a list with one stored file per part. Pick the mode that matches the request: fixed page counts, explicit page ranges, individual pages, a regular expression that starts each new part, or the document bookmarks. Use Merge PDF Files for the opposite. Each call uses ConvertAPI conversions and creates new output files.',
+ idempotent: false,
+ },
+ props: {
+ file: Property.File({
+ displayName: 'PDF File',
+ description: 'The PDF to split.',
+ required: true,
+ }),
+ mode: Property.StaticDropdown({
+ displayName: 'Split By',
+ description: 'How the PDF is cut into parts.',
+ required: true,
+ defaultValue: 'pagecount',
+ options: {
+ options: [
+ { label: 'Page count (every N pages)', value: 'pagecount' },
+ { label: 'Page ranges', value: 'ranges' },
+ { label: 'Single pages', value: 'singlepages' },
+ { label: 'Text match (regular expression)', value: 'text' },
+ { label: 'Bookmarks', value: 'bookmark' },
+ ],
+ },
+ }),
+ valueHelp: Property.MarkDown({
+ variant: MarkdownVariant.INFO,
+ value: `**Split Value** by mode:
+- **Page count**: pages per part, e.g. \`5\`, or a repeating pattern such as \`3,2\`. Leave empty for one file per page.
+- **Page ranges**: one part per range, e.g. \`1-3,5,7-9\` gives three files.
+- **Single pages**: each listed page becomes its own file, e.g. \`1-2,5\` gives pages 1, 2 and 5.
+- **Text match**: a regular expression; a new part starts at every page whose text matches, e.g. \`Invoice\\s+#\\d+\`.
+- **Bookmarks**: leave empty.`,
+ }),
+ value: Property.ShortText({
+ displayName: 'Split Value',
+ description: 'What to split on. The format depends on the Split By mode.',
+ placeholder: 'e.g. 1-3,5,7-9',
+ required: false,
+ }),
+ mergeOutput: Property.Checkbox({
+ displayName: 'Merge Parts Into One PDF',
+ description: 'Join the parts back into one PDF, e.g. to extract selected pages.',
+ required: false,
+ defaultValue: false,
+ }),
+ password: Property.ShortText({
+ displayName: 'Password',
+ description: 'Only needed if the PDF is password-protected.',
+ required: false,
+ }),
+ fileName: Property.ShortText({
+ displayName: 'Output File Name',
+ description: 'Base name for the parts, without extension. Each part gets a number.',
+ placeholder: 'e.g. invoice',
+ required: false,
+ }),
+ },
+ outputSchema: splitPdfOutputSchema,
+ async run({ auth, propsValue, files }) {
+ const mode = propsValue.mode ?? 'pagecount';
+ const value = propsValue.value?.trim() ?? '';
+ if (MODES_REQUIRING_VALUE.includes(mode) && value.length === 0) {
+ throw new Error(`Enter a Split Value for the "${mode}" mode.`);
+ }
+
+ const result = await convertApi.convertFiles({
+ apiKey: auth.secret_text,
+ from: 'pdf',
+ to: 'split',
+ fileInputs: [{ name: 'File', files: [propsValue.file], multiple: false }],
+ parameters: convertApi.toValueParameters({
+ Mode: mode,
+ Value: mode === 'bookmark' ? undefined : value,
+ MergeOutput: propsValue.mergeOutput === true ? true : undefined,
+ Password: propsValue.password,
+ FileName: propsValue.fileName,
+ }),
+ files,
+ });
+
+ return result.files;
+ },
+});
+
+const MODES_REQUIRING_VALUE = ['ranges', 'singlepages', 'text'];
diff --git a/packages/pieces/community/convertapi/src/lib/auth.ts b/packages/pieces/community/convertapi/src/lib/auth.ts
new file mode 100644
index 00000000000..179311b874d
--- /dev/null
+++ b/packages/pieces/community/convertapi/src/lib/auth.ts
@@ -0,0 +1,12 @@
+import { PieceAuth } from '@activepieces/pieces-framework';
+import { convertApi } from './common/client';
+
+export const convertApiAuth = PieceAuth.SecretText({
+ displayName: 'API Token',
+ description: `To get your API token:
+1. Sign in to [ConvertAPI](https://www.convertapi.com/a).
+2. Open **Authentication** (https://www.convertapi.com/a/authentication).
+3. Copy an existing **API Token**, or create a new one, and paste it here.`,
+ required: true,
+ validate: async ({ auth }) => convertApi.checkToken({ apiKey: auth }),
+});
diff --git a/packages/pieces/community/convertapi/src/lib/common/client.ts b/packages/pieces/community/convertapi/src/lib/common/client.ts
new file mode 100644
index 00000000000..1b1ae06c4e3
--- /dev/null
+++ b/packages/pieces/community/convertapi/src/lib/common/client.ts
@@ -0,0 +1,347 @@
+import { httpClient, HttpError, HttpMethod, HttpRequest } from '@activepieces/pieces-common';
+import { FilesService } from '@activepieces/pieces-framework';
+import {
+ ConvertApiConversionResponse,
+ ConvertApiErrorBody,
+ ConvertApiParameter,
+ ConvertApiResultFile,
+ ConvertApiUploadResponse,
+ InputFile,
+ StoredFile,
+} from './types';
+
+export const convertApi = {
+ upload,
+ convert,
+ download,
+ deleteFiles,
+ convertFiles,
+ checkToken,
+ toValueParameters,
+ describeError,
+};
+
+export const CONVERTAPI_BASE_URL = 'https://v2.convertapi.com';
+export const MAX_TIMEOUT_SECONDS = 360;
+export const DOWNLOAD_TIMEOUT_MS = 60_000;
+export const DELETE_TIMEOUT_MS = 15_000;
+export const UPLOAD_TIMEOUT_MS = 120_000;
+export const STEP_BUDGET_MS = 540_000;
+
+async function upload({ apiKey, file, timeoutMs }: UploadParams): Promise<string> {
+ const response = await sendOrThrow<ConvertApiUploadResponse>({
+ method: HttpMethod.POST,
+ url: `${CONVERTAPI_BASE_URL}/upload`,
+ headers: {
+ Authorization: `Bearer ${apiKey}`,
+ 'Content-Type': 'application/octet-stream',
+ },
+ queryParams: { filename: file.filename },
+ body: file.data,
+ timeout: timeoutMs,
+ });
+ if (typeof response.FileId !== 'string' || response.FileId.length === 0) {
+ throw new Error(`ConvertAPI did not return a file ID after uploading "${file.filename}".`);
+ }
+ return response.FileId;
+}
+
+async function convert({ apiKey, from, to, parameters, timeoutMs }: ConvertParams): Promise<ConvertApiConversionResponse> {
+ return sendOrThrow<ConvertApiConversionResponse>({
+ method: HttpMethod.POST,
+ url: `${CONVERTAPI_BASE_URL}/convert/${encodeURIComponent(from)}/to/${encodeURIComponent(to)}`,
+ headers: {
+ Authorization: `Bearer ${apiKey}`,
+ },
+ body: { Parameters: withExecutionParameters(parameters) },
+ timeout: timeoutMs ?? (MAX_TIMEOUT_SECONDS + 30) * 1000,
+ });
+}
+
+async function download({ url, timeoutMs }: { url: string; timeoutMs?: number }): Promise<Buffer> {
+ if (!isConvertApiUrl(url)) {
+ throw new Error('ConvertAPI returned a download link outside convertapi.com, so it was not followed.');
+ }
+ const response = await sendOrThrow<unknown>({
+ method: HttpMethod.GET,
+ url,
+ responseType: 'arraybuffer',
+ followRedirects: false,
+ timeout: timeoutMs ?? DOWNLOAD_TIMEOUT_MS,
+ });
+ if (!Buffer.isBuffer(response)) {
+ throw new Error('ConvertAPI returned an unreadable file.');
+ }
+ return response;
+}
+
+async function deleteFiles({ fileIds }: { fileIds: string[] }): Promise<string[]> {
+ const results = await Promise.allSettled(
+ fileIds.map((fileId) =>
+ httpClient.sendRequest({
+ method: HttpMethod.DELETE,
+ url: `${CONVERTAPI_BASE_URL}/d/${encodeURIComponent(fileId)}`,
+ timeout: DELETE_TIMEOUT_MS,
+ }),
+ ),
+ );
+ return fileIds.filter((_, index) => results[index].status === 'rejected');
+}
+
+async function convertFiles({
+ apiKey,
+ from,
+ to,
+ fileInputs,
+ parameters,
+ files,
+}: ConvertFilesParams): Promise<ConversionOutput> {
+ const fileIdsToDelete: string[] = [];
+ const deadline = Date.now() + STEP_BUDGET_MS;
+ try {
+ const fileParameters: ConvertApiParameter[] = [];
+ for (const input of fileInputs) {
+ const ids: string[] = [];
+ for (const file of input.files) {
+ const id = await upload({ apiKey, file, timeoutMs: remainingMs({ deadline, cap: UPLOAD_TIMEOUT_MS }) });
+ fileIdsToDelete.push(id);
+ ids.push(id);
+ }
+ fileParameters.push(toFileParameter({ name: input.name, ids, multiple: input.multiple }));
+ }
+
+ const response = await convert({
+ apiKey,
+ from,
+ to,
+ parameters: [...fileParameters, ...parameters],
+ timeoutMs: remainingMs({ deadline, cap: (MAX_TIMEOUT_SECONDS + 30) * 1000 }),
+ });
+ const resultFiles = response.Files ?? [];
+ if (resultFiles.length === 0) {
+ throw new Error('ConvertAPI finished the conversion but returned no files.');
+ }
+ fileIdsToDelete.push(
+ ...resultFiles.flatMap((resultFile) => (resultFile.FileId ? [resultFile.FileId] : [])),
+ );
+
+ const downloadTimeoutMs = remainingMs({ deadline, cap: DOWNLOAD_TIMEOUT_MS });
+ const settled = await Promise.allSettled(
+ resultFiles.map((resultFile) => storeResultFile({ resultFile, files, timeoutMs: downloadTimeoutMs })),
+ );
+ const failure = settled.find((result) => result.status === 'rejected');
+ if (failure !== undefined && failure.status === 'rejected') {
+ throw failure.reason;
+ }
+ const stored = settled.flatMap((result) => (result.status === 'fulfilled' ? [result.value] : []));
+ return {
+ files: stored,
+ conversion_cost: typeof response.ConversionCost === 'number' ? response.ConversionCost : null,
+ };
+ } finally {
+ const notDeleted = await deleteFiles({ fileIds: fileIdsToDelete });
+ if (notDeleted.length > 0) {
+ console.warn(
+ `[convertapi] Could not delete ${notDeleted.length} file(s) from ConvertAPI after the step: ${notDeleted.join(', ')}. ConvertAPI removes stored files automatically after a few hours.`,
+ );
+ }
+ }
+}
+
+async function checkToken({ apiKey }: { apiKey: string }): Promise<TokenCheck> {
+ try {
+ await httpClient.sendRequest({
+ method: HttpMethod.POST,
+ url: `${CONVERTAPI_BASE_URL}/convert/pdf/to/merge`,
+ headers: {
+ Authorization: `Bearer ${apiKey}`,
+ },
+ body: { Parameters: [] },
+ });
+ return { valid: true };
+ } catch (error) {
+ const status = statusOf(error);
+ if (status === 401) {
+ return {
+ valid: false,
+ error: 'ConvertAPI rejected this API token. Copy an active token from https://www.convertapi.com/a/authentication and try again.',
+ };
+ }
+ if (status !== undefined && status >= 400 && status < 500) {
+ return { valid: true };
+ }
+ return {
+ valid: false,
+ error: `Could not reach ConvertAPI to check this token: ${describeError(error)}`,
+ };
+ }
+}
+
+function withExecutionParameters(parameters: ConvertApiParameter[]): ConvertApiParameter[] {
+ const reserved = new Set(RESERVED_PARAMETER_NAMES.map((name) => name.toLowerCase()));
+ return [
+ ...parameters.filter((parameter) => !reserved.has(parameter.Name.toLowerCase())),
+ { Name: 'StoreFile', Value: 'true' },
+ { Name: 'Timeout', Value: String(MAX_TIMEOUT_SECONDS) },
+ ];
+}
+
+function toFileParameter({ name, ids, multiple }: { name: string; ids: string[]; multiple: boolean }): ConvertApiParameter {
+ if (multiple) {
+ return { Name: name, FileValues: ids.map((id) => ({ Id: id })) };
+ }
+ return { Name: name, FileValue: { Id: ids[0] } };
+}
+
+function toValueParameters(values: Record<string, unknown>): ConvertApiParameter[] {
+ return Object.entries(values).flatMap(([name, value]) => {
+ if (value === undefined || value === null || value === '') {
+ return [];
+ }
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
+ return [{ Name: name, Value: String(value) }];
+ }
+ return [];
+ });
+}
+
+async function storeResultFile({
+ resultFile,
+ files,
+ timeoutMs,
+}: {
+ resultFile: ConvertApiResultFile;
+ files: FilesService;
+ timeoutMs: number;
+}): Promise<StoredFile> {
+ const url = resultFile.Url ?? resultFile.FileUrl;
+ if (url === undefined || url.length === 0) {
+ throw new Error(`ConvertAPI did not return a download link for "${resultFile.FileName}".`);
+ }
+ const data = await download({ url, timeoutMs });
+ const file = await files.write({ fileName: resultFile.FileName, data });
+ return {
+ file,
+ file_name: resultFile.FileName,
+ file_extension: resultFile.FileExt ?? null,
+ file_size: typeof resultFile.FileSize === 'number' ? resultFile.FileSize : data.length,
+ };
+}
+
+async function sendOrThrow<T>(request: HttpRequest): Promise<T> {
+ try {
+ const response = await httpClient.sendRequest<T>(request);
+ return response.body;
+ } catch (error) {
+ throw new Error(describeError(error));
+ }
+}
+
+function remainingMs({ deadline, cap }: { deadline: number; cap: number }): number {
+ const left = deadline - Date.now();
+ if (left <= 0) {
+ throw new Error('ConvertAPI took too long: there is not enough time left in this step to finish. Try smaller files or fewer pages.');
+ }
+ return Math.min(cap, left);
+}
+
+function isConvertApiUrl(url: string): boolean {
+ try {
+ const parsed = new URL(url);
+ const host = parsed.hostname.toLowerCase();
+ return parsed.protocol === 'https:' && (host === 'convertapi.com' || host.endsWith('.convertapi.com'));
+ } catch {
+ return false;
+ }
+}
+
+function statusOf(error: unknown): number | undefined {
+ if (error instanceof HttpError) {
+ return error.response.status;
+ }
+ return undefined;
+}
+
+function readErrorBody(error: HttpError): ConvertApiErrorBody {
+ const body = parseBody(error.response.body);
+ if (body === null || typeof body !== 'object' || Array.isArray(body)) {
+ return typeof body === 'string' && body.length > 0 ? { Message: body } : {};
+ }
+ const code = 'Code' in body ? body.Code : undefined;
+ const message = 'Message' in body ? body.Message : undefined;
+ return {
+ Code: typeof code === 'number' ? code : undefined,
+ Message: typeof message === 'string' ? message : undefined,
+ };
+}
+
+function parseBody(body: unknown): unknown {
+ if (typeof body !== 'string') {
+ return body;
+ }
+ try {
+ return JSON.parse(body);
+ } catch {
+ return body;
+ }
+}
+
+function describeError(error: unknown): string {
+ if (!(error instanceof HttpError)) {
+ return error instanceof Error ? error.message : String(error);
+ }
+ const status = error.response.status;
+ const { Code, Message } = readErrorBody(error);
+ const detail = [Message, Code === undefined ? undefined : `code ${Code}`]
+ .filter((part) => part !== undefined)
+ .join(', ');
+ const base = `ConvertAPI error (HTTP ${status})${detail.length > 0 ? `: ${detail}` : ''}`;
+ if (status === 401) {
+ return `${base}. Check that your API token is active.`;
+ }
+ if (status === 403) {
+ return `${base}. Your ConvertAPI account may be out of conversions.`;
+ }
+ if (status === 503) {
+ return `${base}. ConvertAPI limits how many conversions run at the same time on your plan (the Developer plan allows one). Wait for other conversions to finish, then run the step again.`;
+ }
+ return base;
+}
+
+const RESERVED_PARAMETER_NAMES = ['StoreFile', 'Timeout', 'Secret', 'Token'];
+
+type UploadParams = {
+ apiKey: string;
+ file: InputFile;
+ timeoutMs?: number;
+};
+
+type ConvertParams = {
+ apiKey: string;
+ from: string;
+ to: string;
+ parameters: ConvertApiParameter[];
+ timeoutMs?: number;
+};
+
+type TokenCheck = { valid: true } | { valid: false; error: string };
+
+export type FileInput = {
+ name: string;
+ files: InputFile[];
+ multiple: boolean;
+};
+
+export type ConvertFilesParams = {
+ apiKey: string;
+ from: string;
+ to: string;
+ fileInputs: FileInput[];
+ parameters: ConvertApiParameter[];
+ files: FilesService;
+};
+
+export type ConversionOutput = {
+ files: StoredFile[];
+ conversion_cost: number | null;
+};
diff --git a/packages/pieces/community/convertapi/src/lib/common/converters.ts b/packages/pieces/community/convertapi/src/lib/common/converters.ts
new file mode 100644
index 00000000000..508df662a33
--- /dev/null
+++ b/packages/pieces/community/convertapi/src/lib/common/converters.ts
@@ -0,0 +1,266 @@
+import { httpClient, HttpMethod } from '@activepieces/pieces-common';
+import { InputProperty, InputPropertyMap, Property } from '@activepieces/pieces-framework';
+import { CONVERTAPI_BASE_URL } from './client';
+import { ConverterInfo, ConverterParameter } from './types';
+
+export const converterInfo = {
+ fetchConverters,
+ fetchConverter,
+ parseConverters,
+ sourceOptions,
+ destinationOptions,
+ mainInputOf,
+ optionProps,
+};
+
+async function fetchConverters({ from, to }: { from?: string; to?: string } = {}): Promise<ConverterInfo[]> {
+ const url =
+ from === undefined
+ ? `${CONVERTAPI_BASE_URL}/info`
+ : `${CONVERTAPI_BASE_URL}/info/${encodeURIComponent(from)}/to/${to === undefined ? '*' : encodeURIComponent(to)}`;
+ const response = await httpClient.sendRequest<unknown>({
+ method: HttpMethod.GET,
+ url,
+ });
+ return parseConverters(response.body);
+}
+
+async function fetchConverter({ from, to }: { from: string; to: string }): Promise<ConverterInfo> {
+ const converters = await fetchConverters({ from, to });
+ const match = converters.find(
+ (converter) => sourceOf(converter) === from.toLowerCase() && destinationOf(converter) === to.toLowerCase(),
+ );
+ if (match === undefined) {
+ throw new Error(`ConvertAPI has no converter from "${from}" to "${to}".`);
+ }
+ return match;
+}
+
+function parseConverters(body: unknown): ConverterInfo[] {
+ if (!Array.isArray(body)) {
+ return [];
+ }
+ return body.flatMap((item) => {
+ const converter = toConverterInfo(item);
+ return converter === undefined ? [] : [converter];
+ });
+}
+
+function sourceOptions(converters: ConverterInfo[]): DropdownOption[] {
+ const extensionsBySource = new Map<string, Set<string>>();
+ for (const converter of converters) {
+ if (mainInputOf(converter) === undefined) {
+ continue;
+ }
+ const source = sourceOf(converter);
+ const extensions = extensionsBySource.get(source) ?? new Set<string>();
+ for (const extension of converter.SourceExtensions ?? []) {
+ extensions.add(extension.toLowerCase());
+ }
+ extensionsBySource.set(source, extensions);
+ }
+ return [...extensionsBySource.entries()]
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([source, extensions]) => ({
+ label: formatLabel({ format: source, extensions: [...extensions] }),
+ value: source,
+ }));
+}
+
+function destinationOptions({ converters, from }: { converters: ConverterInfo[]; from: string }): DropdownOption[] {
+ const seen = new Set<string>();
+ return converters
+ .filter((converter) => sourceOf(converter) === from.toLowerCase() && mainInputOf(converter) !== undefined)
+ .flatMap((converter) => {
+ const destination = destinationOf(converter);
+ if (seen.has(destination)) {
+ return [];
+ }
+ seen.add(destination);
+ return [{ label: titleOf(converter), value: destination }];
+ })
+ .sort((a, b) => a.label.localeCompare(b.label));
+}
+
+function mainInputOf(converter: ConverterInfo): MainInput | undefined {
+ const parameters = parametersOf(converter);
+ const single = parameters.find((parameter) => parameter.Name === 'File' && parameter.Type === 'File');
+ if (single !== undefined) {
+ return { name: 'File', multiple: single.Array === true };
+ }
+ const multiple = parameters.find((parameter) => parameter.Name === 'Files' && parameter.Type === 'File');
+ if (multiple !== undefined) {
+ return { name: 'Files', multiple: true };
+ }
+ return undefined;
+}
+
+function optionProps(converter: ConverterInfo): InputPropertyMap {
+ return Object.fromEntries(
+ parametersOf(converter).flatMap((parameter) => {
+ const property = toOptionProperty(parameter);
+ return property === undefined ? [] : [[parameter.Name, property]];
+ }),
+ );
+}
+
+function toOptionProperty(parameter: ConverterParameter): InputProperty | undefined {
+ if (EXCLUDED_PARAMETER_NAMES.has(parameter.Name) || parameter.Type === 'File' || parameter.Array === true) {
+ return undefined;
+ }
+ const shared = {
+ displayName: parameter.Label ?? parameter.Name,
+ description: describeParameter(parameter),
+ required: parameter.Required === true,
+ };
+ const defaultValue = parameter.Default;
+ switch (parameter.Type) {
+ case 'Collection': {
+ const values = parameter.Values ?? {};
+ return Property.StaticDropdown({
+ ...shared,
+ defaultValue: typeof defaultValue === 'string' ? defaultValue : undefined,
+ options: {
+ options: Object.entries(values).map(([value, label]) => ({ label, value })),
+ },
+ });
+ }
+ case 'Integer':
+ case 'Double':
+ return Property.Number({
+ ...shared,
+ defaultValue: typeof defaultValue === 'number' ? defaultValue : undefined,
+ });
+ case 'Bool':
+ return Property.Checkbox({
+ ...shared,
+ defaultValue: typeof defaultValue === 'boolean' ? defaultValue : undefined,
+ });
+ default:
+ return Property.ShortText({
+ ...shared,
+ defaultValue: typeof defaultValue === 'string' ? defaultValue : undefined,
+ });
+ }
+}
+
+function describeParameter(parameter: ConverterParameter): string | undefined {
+ const description = parameter.Description?.replace(/\s+/g, ' ').trim();
+ if (description === undefined || description.length === 0) {
+ return undefined;
+ }
+ return description;
+}
+
+function parametersOf(converter: ConverterInfo): ConverterParameter[] {
+ return (converter.ConverterParameterGroups ?? [])
+ .filter((group) => group.Name !== 'Authentication')
+ .flatMap((group) => group.ConverterParameters);
+}
+
+function sourceOf(converter: ConverterInfo): string {
+ return (converter.SourceFileFormats[0] ?? '').toLowerCase();
+}
+
+function destinationOf(converter: ConverterInfo): string {
+ return (converter.DestinationFileFormats[0] ?? '').toLowerCase();
+}
+
+function titleOf(converter: ConverterInfo): string {
+ const title = converter.Title?.replace(/\s+API$/i, '').trim();
+ if (title !== undefined && title.length > 0) {
+ return title;
+ }
+ return `${sourceOf(converter).toUpperCase()} to ${destinationOf(converter).toUpperCase()}`;
+}
+
+function formatLabel({ format, extensions }: { format: string; extensions: string[] }): string {
+ const others = extensions.filter((extension) => extension !== format).sort();
+ if (others.length === 0) {
+ return format.toUpperCase();
+ }
+ return `${format.toUpperCase()} (${[format, ...others].map((extension) => `.${extension}`).join(', ')})`;
+}
+
+function toConverterInfo(item: unknown): ConverterInfo | undefined {
+ if (!isRecord(item)) {
+ return undefined;
+ }
+ const sources = toStringArray(item['SourceFileFormats']);
+ const destinations = toStringArray(item['DestinationFileFormats']);
+ if (sources.length === 0 || destinations.length === 0) {
+ return undefined;
+ }
+ const groups = Array.isArray(item['ConverterParameterGroups']) ? item['ConverterParameterGroups'] : [];
+ return {
+ Name: typeof item['Name'] === 'string' ? item['Name'] : '',
+ Title: typeof item['Title'] === 'string' ? item['Title'] : undefined,
+ SourceFileFormats: sources,
+ SourceExtensions: toStringArray(item['SourceExtensions']),
+ DestinationFileFormats: destinations,
+ DestinationExtensions: toStringArray(item['DestinationExtensions']),
+ ConverterParameterGroups: groups.flatMap((group) => {
+ if (!isRecord(group) || typeof group['Name'] !== 'string') {
+ return [];
+ }
+ const parameters = Array.isArray(group['ConverterParameters']) ? group['ConverterParameters'] : [];
+ return [
+ {
+ Name: group['Name'],
+ ConverterParameters: parameters.flatMap((parameter) => {
+ const parsed = toConverterParameter(parameter);
+ return parsed === undefined ? [] : [parsed];
+ }),
+ },
+ ];
+ }),
+ };
+}
+
+function toConverterParameter(item: unknown): ConverterParameter | undefined {
+ if (!isRecord(item) || typeof item['Name'] !== 'string' || typeof item['Type'] !== 'string') {
+ return undefined;
+ }
+ const rawDefault = item['Default'];
+ const rawValues = item['Values'];
+ return {
+ Name: item['Name'],
+ Type: item['Type'],
+ Label: typeof item['Label'] === 'string' ? item['Label'] : undefined,
+ Description: typeof item['Description'] === 'string' ? item['Description'] : undefined,
+ Required: item['Required'] === true,
+ Array: item['Array'] === true,
+ Default:
+ typeof rawDefault === 'string' || typeof rawDefault === 'number' || typeof rawDefault === 'boolean'
+ ? rawDefault
+ : undefined,
+ Values: isRecord(rawValues)
+ ? Object.fromEntries(
+ Object.entries(rawValues).flatMap(([key, value]) => (typeof value === 'string' ? [[key, value]] : [])),
+ )
+ : undefined,
+ };
+}
+
+function toStringArray(value: unknown): string[] {
+ if (!Array.isArray(value)) {
+ return [];
+ }
+ return value.filter((entry): entry is string => typeof entry === 'string');
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+const EXCLUDED_PARAMETER_NAMES = new Set(['File', 'Files', 'StoreFile', 'Timeout', 'Secret', 'Token']);
+
+type DropdownOption = {
+ label: string;
+ value: string;
+};
+
+export type MainInput = {
+ name: 'File' | 'Files';
+ multiple: boolean;
+};
diff --git a/packages/pieces/community/convertapi/src/lib/common/input-files.ts b/packages/pieces/community/convertapi/src/lib/common/input-files.ts
new file mode 100644
index 00000000000..859abcbf6dd
--- /dev/null
+++ b/packages/pieces/community/convertapi/src/lib/common/input-files.ts
@@ -0,0 +1,39 @@
+import { InputFile } from './types';
+
+export const inputFiles = {
+ fromValue,
+ fromArrayItems,
+};
+
+function fromValue(value: unknown): InputFile | undefined {
+ if (!isRecord(value)) {
+ return undefined;
+ }
+ const filename = value['filename'];
+ const data = value['data'];
+ if (typeof filename !== 'string' || !Buffer.isBuffer(data)) {
+ return undefined;
+ }
+ return { filename, data };
+}
+
+function fromArrayItems({ items, key }: { items: unknown; key: string }): InputFile[] {
+ if (!Array.isArray(items)) {
+ return [];
+ }
+ return items.flatMap((item, index) => {
+ if (!isRecord(item) || item[key] === undefined || item[key] === null || item[key] === '') {
+ return [];
+ }
+ const file = fromValue(item[key]);
+ if (file === undefined) {
+ throw new Error(`File ${index + 1} could not be read. Pick a file from a previous step or upload one.`);
+ }
+ return [file];
+ });
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
diff --git a/packages/pieces/community/convertapi/src/lib/common/types.ts b/packages/pieces/community/convertapi/src/lib/common/types.ts
new file mode 100644
index 00000000000..71aec4e928c
--- /dev/null
+++ b/packages/pieces/community/convertapi/src/lib/common/types.ts
@@ -0,0 +1,76 @@
+export type ConvertApiFileRef = {
+ Id: string;
+};
+
+export type ConvertApiParameter = {
+ Name: string;
+ Value?: string;
+ FileValue?: ConvertApiFileRef;
+ FileValues?: ConvertApiFileRef[];
+};
+
+export type ConvertApiUploadResponse = {
+ FileId: string;
+ FileName?: string;
+ FileExt?: string;
+ FileSize?: number;
+ Url?: string;
+};
+
+export type ConvertApiResultFile = {
+ FileName: string;
+ FileExt?: string;
+ FileSize?: number;
+ FileId?: string;
+ Url?: string;
+ FileUrl?: string;
+};
+
+export type ConvertApiConversionResponse = {
+ ConversionCost?: number;
+ Files?: ConvertApiResultFile[];
+};
+
+export type ConvertApiErrorBody = {
+ Code?: number;
+ Message?: string;
+};
+
+export type ConverterParameter = {
+ Name: string;
+ Label?: string;
+ Description?: string;
+ Type: string;
+ Required?: boolean;
+ Array?: boolean;
+ Default?: string | number | boolean | null;
+ Values?: Record<string, string>;
+ GroupName?: string;
+};
+
+export type ConverterParameterGroup = {
+ Name: string;
+ ConverterParameters: ConverterParameter[];
+};
+
+export type ConverterInfo = {
+ Name: string;
+ Title?: string;
+ SourceFileFormats: string[];
+ SourceExtensions?: string[];
+ DestinationFileFormats: string[];
+ DestinationExtensions?: string[];
+ ConverterParameterGroups?: ConverterParameterGroup[];
+};
+
+export type InputFile = {
+ filename: string;
+ data: Buffer;
+};
+
+export type StoredFile = {
+ file: string;
+ file_name: string;
+ file_extension: string | null;
+ file_size: number | null;
+};
diff --git a/packages/pieces/community/convertapi/src/lib/output-schemas.ts b/packages/pieces/community/convertapi/src/lib/output-schemas.ts
new file mode 100644
index 00000000000..813329639b5
--- /dev/null
+++ b/packages/pieces/community/convertapi/src/lib/output-schemas.ts
@@ -0,0 +1,68 @@
+import { OutputSchema } from '@activepieces/pieces-framework';
+
+export const mergePdfOutputSchema: OutputSchema = {
+ fields: [
+ ...storedFileFields(),
+ {
+ key: 'conversion_cost',
+ label: 'Conversion Cost',
+ format: 'number',
+ description: 'How many ConvertAPI conversions this merge used. Empty when ConvertAPI does not report it.',
+ },
+ ],
+};
+
+export const splitPdfOutputSchema: OutputSchema = {
+ itemLabel: '{file_name}',
+ fields: [
+ {
+ key: 'parts',
+ label: 'PDF Parts',
+ value: '',
+ labelKey: 'file_name',
+ description: 'One stored PDF per part, in page order.',
+ listItems: storedFileFields(),
+ },
+ ],
+};
+
+export const convertFileOutputSchema: OutputSchema = {
+ itemLabel: '{file_name}',
+ fields: [
+ {
+ key: 'files',
+ label: 'Converted Files',
+ value: '',
+ labelKey: 'file_name',
+ description: 'One stored file per output. Most conversions produce a single file; some, like PDF to JPG, produce one per page.',
+ listItems: storedFileFields(),
+ },
+ ],
+};
+
+function storedFileFields(): OutputSchema['fields'] {
+ return [
+ {
+ key: 'file',
+ label: 'File',
+ format: 'url',
+ description: 'The converted file, stored in Activepieces. Pass this to any step that takes a file input.',
+ },
+ {
+ key: 'file_name',
+ label: 'File Name',
+ description: 'Name of the output file, including its extension.',
+ },
+ {
+ key: 'file_extension',
+ label: 'File Extension',
+ description: 'Extension of the output file without the dot, such as pdf or jpg. Empty when ConvertAPI does not report one.',
+ },
+ {
+ key: 'file_size',
+ label: 'File Size',
+ format: 'filesize',
+ description: 'Size of the output file in bytes.',
+ },
+ ];
+}
diff --git a/packages/pieces/community/convertapi/test/actions.test.ts b/packages/pieces/community/convertapi/test/actions.test.ts
new file mode 100644
index 00000000000..a798e39924f
--- /dev/null
+++ b/packages/pieces/community/convertapi/test/actions.test.ts
@@ -0,0 +1,875 @@
+import { HttpError } from '@activepieces/pieces-common';
+import {
+ ApFile,
+ AppConnectionType,
+ createMockActionContext,
+ InputPropertyMap,
+ PropertyContext,
+ StaticPropsValue,
+} from '@activepieces/pieces-framework';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { convertFileAction } from '../src/lib/actions/convert-file';
+import { mergePdfAction } from '../src/lib/actions/merge-pdf';
+import { splitPdfAction } from '../src/lib/actions/split-pdf';
+import { convertApiAuth } from '../src/lib/auth';
+
+const sendRequest = vi.fn();
+
+vi.mock('@activepieces/pieces-common', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();
+ return {
+ ...actual,
+ httpClient: {
+ sendRequest: (...args: unknown[]) => sendRequest(...args),
+ },
+ };
+});
+
+const AUTH = { type: AppConnectionType.SECRET_TEXT, secret_text: 'token_123' } satisfies AuthValue;
+const BASE = 'https://v2.convertapi.com';
+
+function pdf(name: string): ApFile {
+ return new ApFile(name, Buffer.from(`%PDF ${name}`));
+}
+
+function resultFile({ name, id }: { name: string; id: string }) {
+ return {
+ FileName: name,
+ FileExt: name.split('.').pop(),
+ FileSize: 1000,
+ FileId: id,
+ Url: `${BASE}/d/${id}/${name}`,
+ };
+}
+
+function mockApi({ conversion, info }: { conversion?: ConversionReply; info?: unknown } = {}) {
+ let uploads = 0;
+ sendRequest.mockImplementation(async (request: Request) => {
+ if (request.url === `${BASE}/upload`) {
+ uploads += 1;
+ return { status: 200, body: { FileId: `up${uploads}`, FileName: request.queryParams?.['filename'] } };
+ }
+ if (request.url.startsWith(`${BASE}/convert/`)) {
+ const reply = conversion ?? { body: { ConversionCost: 1, Files: [resultFile({ name: 'out.pdf', id: 'res1' })] } };
+ if (reply.status !== undefined && reply.status >= 400) {
+ throw new HttpError(request.body, { status: reply.status, responseBody: reply.body });
+ }
+ return { status: 200, body: reply.body };
+ }
+ if (request.url.startsWith(`${BASE}/info`)) {
+ return { status: 200, body: info ?? [] };
+ }
+ if (request.method === 'GET' && request.url.startsWith(`${BASE}/d/`)) {
+ return { status: 200, body: Buffer.from(`bytes of ${request.url}`) };
+ }
+ if (request.method === 'DELETE') {
+ return { status: 200, body: undefined };
+ }
+ throw new Error(`Unexpected request ${request.method} ${request.url}`);
+ });
+}
+
+function requests(): Request[] {
+ return sendRequest.mock.calls.map((call) => call[0]);
+}
+
+function conversionRequest(): Request {
+ const found = requests().find((request) => request.url.startsWith(`${BASE}/convert/`));
+ if (found === undefined) {
+ throw new Error('no conversion request');
+ }
+ return found;
+}
+
+function parametersOf(request: Request): Record<string, unknown>[] {
+ const body = request.body;
+ if (typeof body !== 'object' || body === null || !('Parameters' in body) || !Array.isArray(body.Parameters)) {
+ throw new Error('no Parameters');
+ }
+ return body.Parameters;
+}
+
+function param({ request, name }: { request: Request; name: string }) {
+ return parametersOf(request).find((parameter) => parameter['Name'] === name);
+}
+
+function makeFiles() {
+ return {
+ write: vi.fn(async ({ fileName }: { fileName: string; data: unknown }) => `https://ap.files/${fileName}`),
+ upload: vi.fn(async ({ fileName }: { fileName: string; data: unknown }) => ({ id: fileName, url: `https://ap.files/${fileName}` })),
+ };
+}
+
+function makeContext<Props extends InputPropertyMap>({
+ propsValue,
+ files,
+}: {
+ propsValue: StaticPropsValue<Props>;
+ files?: ReturnType<typeof makeFiles>;
+}) {
+ return { ...createMockActionContext<Props>({ propsValue }), auth: AUTH, files: files ?? makeFiles() };
+}
+
+function propertyContext(): PropertyContext {
+ const { server, project, flows, connections } = createMockActionContext({ propsValue: {} });
+ return { server, project, flows, connections };
+}
+
+async function runMerge({ propsValue, files }: RunInput<typeof mergePdfAction.props>) {
+ const output = await mergePdfAction.run(
+ makeContext<typeof mergePdfAction.props>({
+ propsValue: {
+ fileName: undefined,
+ password: undefined,
+ bookmarksTableOfContents: undefined,
+ pageSize: undefined,
+ pageOrientation: undefined,
+ ...propsValue,
+ },
+ files,
+ }),
+ );
+ return expectStoredOutput(output);
+}
+
+async function runSplit({ propsValue, files }: RunInput<typeof splitPdfAction.props>) {
+ const output = await splitPdfAction.run(
+ makeContext<typeof splitPdfAction.props>({
+ propsValue: {
+ valueHelp: undefined,
+ value: undefined,
+ mergeOutput: undefined,
+ password: undefined,
+ fileName: undefined,
+ ...propsValue,
+ },
+ files,
+ }),
+ );
+ return expectStoredOutputs(output);
+}
+
+async function runConvert({ propsValue, files }: RunInput<typeof convertFileAction.props>) {
+ const output = await convertFileAction.run(
+ makeContext<typeof convertFileAction.props>({ propsValue: { additionalFiles: undefined, options: undefined, ...propsValue }, files }),
+ );
+ return expectStoredOutputs(output);
+}
+
+function isStoredOutput(value: unknown): value is StoredOutput {
+ return (
+ typeof value === 'object' &&
+ value !== null &&
+ 'file' in value &&
+ typeof value.file === 'string' &&
+ 'file_name' in value &&
+ typeof value.file_name === 'string'
+ );
+}
+
+function expectStoredOutput(value: unknown): StoredOutput {
+ if (!isStoredOutput(value)) {
+ throw new Error('expected a stored file output');
+ }
+ return value;
+}
+
+function expectStoredOutputs(value: unknown): StoredOutput[] {
+ if (!Array.isArray(value) || !value.every(isStoredOutput)) {
+ throw new Error('expected a list of stored file outputs');
+ }
+ return value;
+}
+
+function validateToken({ auth }: { auth: string }) {
+ return convertApiAuth.validate?.({
+ auth,
+ server: { apiUrl: 'http://localhost:3000', publicUrl: 'http://localhost:4200', mintOidcToken: async () => 'oidc' },
+ });
+}
+
+const DOCX_TO_PDF = {
+ Name: 'Word',
+ Title: 'DOCX to PDF API',
+ SourceFileFormats: ['docx'],
+ SourceExtensions: ['doc', 'docx'],
+ DestinationFileFormats: ['pdf'],
+ DestinationExtensions: ['pdf'],
+ ConverterParameterGroups: [
+ {
+ Name: 'Authentication',
+ ConverterParameters: [{ Name: 'Token', Type: 'String', Required: false, Array: false }],
+ },
+ {
+ Name: 'Input',
+ ConverterParameters: [
+ { Name: 'File', Type: 'File', Required: true, Array: false },
+ { Name: 'PageRange', Label: 'Page range', Type: 'String', Required: false, Array: false, Default: '1-2000' },
+ ],
+ },
+ {
+ Name: 'Output',
+ ConverterParameters: [
+ { Name: 'FileName', Label: 'Output file name', Type: 'String', Required: false, Array: false },
+ { Name: 'StoreFile', Type: 'Bool', Required: false, Array: false, Default: false },
+ ],
+ },
+ {
+ Name: 'Execution',
+ ConverterParameters: [{ Name: 'Timeout', Type: 'Integer', Required: false, Array: false, Default: 900 }],
+ },
+ {
+ Name: 'PDF',
+ ConverterParameters: [
+ { Name: 'PdfVersion', Label: 'PDF version', Type: 'Collection', Required: false, Array: false, Default: '1.7', Values: { '1.4': 'PDF 1.4', '1.7': 'PDF 1.7' } },
+ { Name: 'ConvertMarkups', Label: 'Convert markups', Type: 'Bool', Required: false, Array: false, Default: false },
+ { Name: 'ImageQuality', Label: 'Image quality', Type: 'Integer', Required: false, Array: false, Default: 75 },
+ { Name: 'Scale', Label: 'Scale', Type: 'Double', Required: false, Array: false },
+ { Name: 'TemplateFile', Label: 'Template', Type: 'File', Required: false, Array: false },
+ ],
+ },
+ ],
+};
+
+const DOCX_MERGE = {
+ Name: 'Word',
+ Title: 'Merge DOCX API',
+ SourceFileFormats: ['docx'],
+ SourceExtensions: ['docx'],
+ DestinationFileFormats: ['merge'],
+ ConverterParameterGroups: [
+ { Name: 'Input', ConverterParameters: [{ Name: 'Files', Type: 'File', Required: true, Array: true }] },
+ ],
+};
+
+const PDF_TO_JPG = {
+ Name: 'Pdf',
+ Title: 'PDF to JPG API',
+ SourceFileFormats: ['pdf'],
+ SourceExtensions: ['pdf'],
+ DestinationFileFormats: ['jpg'],
+ ConverterParameterGroups: [
+ { Name: 'Input', ConverterParameters: [{ Name: 'File', Type: 'File', Required: true, Array: false }] },
+ ],
+};
+
+const DATA_TO_QR = {
+ Name: 'Barcode',
+ Title: 'Data to QR Code API',
+ SourceFileFormats: ['data'],
+ DestinationFileFormats: ['qrcode'],
+ ConverterParameterGroups: [
+ { Name: 'Input', ConverterParameters: [{ Name: 'Data', Type: 'String', Required: true, Array: false }] },
+ ],
+};
+
+beforeEach(() => {
+ sendRequest.mockReset();
+});
+
+describe('Merge PDF Files', () => {
+ it('uploads every file as raw bytes, then converts by file id', async () => {
+ mockApi();
+
+ await runMerge({ propsValue: { files: [{ file: pdf('a.pdf') }, { file: pdf('b.pdf') }] } });
+
+ const uploads = requests().filter((request) => request.url === `${BASE}/upload`);
+ expect(uploads).toHaveLength(2);
+ expect(uploads[0].method).toBe('POST');
+ expect(uploads[0].headers?.['Content-Type']).toBe('application/octet-stream');
+ expect(uploads[0].headers?.['Authorization']).toBe('Bearer token_123');
+ expect(uploads[0].queryParams).toEqual({ filename: 'a.pdf' });
+ expect(Buffer.isBuffer(uploads[0].body)).toBe(true);
+
+ const conversion = conversionRequest();
+ expect(conversion.url).toBe(`${BASE}/convert/pdf/to/merge`);
+ expect(conversion.headers?.['Authorization']).toBe('Bearer token_123');
+ expect(param({ request: conversion, name: 'Files' })).toEqual({ Name: 'Files', FileValues: [{ Id: 'up1' }, { Id: 'up2' }] });
+ });
+
+ it('always asks for stored files and a timeout under the step limit', async () => {
+ mockApi();
+
+ await runMerge({ propsValue: { files: [{ file: pdf('a.pdf') }, { file: pdf('b.pdf') }] } });
+
+ const conversion = conversionRequest();
+ expect(param({ request: conversion, name: 'StoreFile' })).toEqual({ Name: 'StoreFile', Value: 'true' });
+ expect(param({ request: conversion, name: 'Timeout' })).toEqual({ Name: 'Timeout', Value: '360' });
+ expect(Number(param({ request: conversion, name: 'Timeout' })?.['Value'])).toBeLessThanOrEqual(360);
+ });
+
+ it('sends the merge options as string values and skips empty ones', async () => {
+ mockApi();
+
+ await runMerge({
+ propsValue: {
+ files: [{ file: pdf('a.pdf') }, { file: pdf('b.pdf') }],
+ fileName: 'combined',
+ password: 'secret',
+ bookmarksTableOfContents: 'filename',
+ pageSize: 'a4',
+ pageOrientation: 'landscape',
+ },
+ });
+
+ const conversion = conversionRequest();
+ expect(param({ request: conversion, name: 'FileName' })).toEqual({ Name: 'FileName', Value: 'combined' });
+ expect(param({ request: conversion, name: 'Password' })).toEqual({ Name: 'Password', Value: 'secret' });
+ expect(param({ request: conversion, name: 'BookmarksTableOfContents' })).toEqual({ Name: 'BookmarksTableOfContents', Value: 'filename' });
+ expect(param({ request: conversion, name: 'PageSize' })).toEqual({ Name: 'PageSize', Value: 'a4' });
+ expect(param({ request: conversion, name: 'PageOrientation' })).toEqual({ Name: 'PageOrientation', Value: 'landscape' });
+
+ sendRequest.mockClear();
+ await runMerge({ propsValue: { files: [{ file: pdf('a.pdf') }, { file: pdf('b.pdf') }], fileName: '' } });
+ expect(param({ request: conversionRequest(), name: 'FileName' })).toBeUndefined();
+ expect(param({ request: conversionRequest(), name: 'Password' })).toBeUndefined();
+ });
+
+ it('downloads the result URL and writes it as an Activepieces file', async () => {
+ mockApi({ conversion: { body: { ConversionCost: 2, Files: [resultFile({ name: 'merged.pdf', id: 'res1' })] } } });
+ const files = makeFiles();
+
+ const result = await runMerge({ propsValue: { files: [{ file: pdf('a.pdf') }, { file: pdf('b.pdf') }] }, files });
+
+ const download = requests().find((request) => request.method === 'GET' && request.url.includes('/d/res1'));
+ expect(download?.url).toBe(`${BASE}/d/res1/merged.pdf`);
+ expect(download?.responseType).toBe('arraybuffer');
+ expect(download?.headers).toBeUndefined();
+ expect(files.write).toHaveBeenCalledTimes(1);
+ expect(files.write.mock.calls[0][0].fileName).toBe('merged.pdf');
+ expect(Buffer.isBuffer(files.write.mock.calls[0][0].data)).toBe(true);
+ expect(result).toEqual({
+ file: 'https://ap.files/merged.pdf',
+ file_name: 'merged.pdf',
+ file_extension: 'pdf',
+ file_size: 1000,
+ conversion_cost: 2,
+ });
+ expect(JSON.stringify(result)).not.toContain('FileData');
+ });
+
+ it('accepts the FileUrl field some responses use instead of Url', async () => {
+ mockApi({
+ conversion: { body: { Files: [{ FileName: 'merged.pdf', FileExt: 'pdf', FileUrl: `${BASE}/d/alt/merged.pdf` }] } },
+ });
+
+ const result = await runMerge({ propsValue: { files: [{ file: pdf('a.pdf') }, { file: pdf('b.pdf') }] } });
+
+ expect(result.file).toBe('https://ap.files/merged.pdf');
+ expect(result.conversion_cost).toBeNull();
+ });
+
+ it('fails clearly when ConvertAPI returns no download link instead of passing base64 through', async () => {
+ mockApi({ conversion: { body: { Files: [{ FileName: 'merged.pdf', FileData: 'JVBERi0x' }] } } });
+
+ await expect(runMerge({ propsValue: { files: [{ file: pdf('a.pdf') }, { file: pdf('b.pdf') }] } })).rejects.toThrow(
+ /did not return a download link/,
+ );
+ });
+
+ it('downloads results without following redirects and with a bounded timeout', async () => {
+ mockApi();
+
+ await runMerge({ propsValue: { files: [{ file: pdf('a.pdf') }, { file: pdf('b.pdf') }] } });
+
+ const download = requests().find((request) => request.method === 'GET' && request.url.includes('/d/res1'));
+ expect(download?.followRedirects).toBe(false);
+ expect(download?.timeout).toBe(60_000);
+ });
+
+ it('refuses to download a result link outside convertapi.com', async () => {
+ mockApi({ conversion: { body: { Files: [{ FileName: 'merged.pdf', FileExt: 'pdf', Url: 'http://169.254.169.254/latest/meta-data' }] } } });
+
+ await expect(runMerge({ propsValue: { files: [{ file: pdf('a.pdf') }, { file: pdf('b.pdf') }] } })).rejects.toThrow(
+ /outside convertapi\.com/,
+ );
+ expect(requests().some((request) => request.method === 'GET' && request.url.includes('169.254'))).toBe(false);
+ });
+
+ it('keeps the conversion inside the step time limit', async () => {
+ mockApi();
+
+ await runMerge({ propsValue: { files: [{ file: pdf('a.pdf') }, { file: pdf('b.pdf') }] } });
+
+ expect(conversionRequest().timeout).toBe(390_000);
+ });
+
+ it('downloads many result files in parallel, each bounded by the step budget', async () => {
+ const many = Array.from({ length: 5 }, (_, index) => resultFile({ name: `page-${index + 1}.jpg`, id: `r${index + 1}` }));
+ mockApi({ conversion: { body: { Files: many } } });
+
+ const result = await runSplit({ propsValue: { file: pdf('a.pdf'), mode: 'singlepages', value: '1,2,3,4,5' } });
+
+ expect(result).toHaveLength(5);
+ const downloads = requests().filter((request) => request.method === 'GET' && request.url.includes('/d/r'));
+ expect(downloads).toHaveLength(5);
+ for (const download of downloads) {
+ expect(download.timeout).toBeGreaterThan(0);
+ expect(download.timeout).toBeLessThanOrEqual(60_000);
+ }
+ });
+
+ it('waits for every result download to finish before cleaning up, even when one fails', async () => {
+ mockApi({
+ conversion: {
+ body: { Files: [resultFile({ name: 'part-1.pdf', id: 'r1' }), resultFile({ name: 'part-2.pdf', id: 'r2' })] },
+ },
+ });
+ const base = sendRequest.getMockImplementation();
+ const events: string[] = [];
+ sendRequest.mockImplementation(async (request: Request) => {
+ if (request.method === 'GET' && request.url.includes('/d/r1')) {
+ events.push('r1 download failed');
+ throw new HttpError(undefined, { status: 500, responseBody: { Message: 'broken' } });
+ }
+ if (request.method === 'GET' && request.url.includes('/d/r2')) {
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ events.push('r2 download finished');
+ }
+ if (request.method === 'DELETE') {
+ events.push(`delete ${request.url.split('/d/')[1]}`);
+ }
+ return base === undefined ? undefined : base(request);
+ });
+
+ await expect(runSplit({ propsValue: { file: pdf('a.pdf'), mode: 'singlepages', value: '1,2' } })).rejects.toThrow();
+
+ const finished = events.indexOf('r2 download finished');
+ const firstDelete = events.findIndex((event) => event.startsWith('delete'));
+ expect(finished).toBeGreaterThanOrEqual(0);
+ expect(firstDelete).toBeGreaterThan(finished);
+ });
+
+ it('stops with a clear error instead of overrunning the step when the budget is spent', async () => {
+ mockApi();
+ const start = Date.now();
+ let calls = 0;
+ const clock = vi.spyOn(Date, 'now').mockImplementation(() => {
+ calls += 1;
+ return calls <= 4 ? start : start + 600_000;
+ });
+
+ await expect(runMerge({ propsValue: { files: [{ file: pdf('a.pdf') }, { file: pdf('b.pdf') }] } })).rejects.toThrow(
+ /not enough time left/,
+ );
+ expect(requests().some((request) => request.method === 'GET' && request.url.includes('/d/res1'))).toBe(false);
+ clock.mockRestore();
+ });
+
+ it('still returns the files but warns when ConvertAPI cleanup fails', async () => {
+ mockApi();
+ const base = sendRequest.getMockImplementation();
+ sendRequest.mockImplementation(async (request: Request) => {
+ if (request.method === 'DELETE' && request.url === `${BASE}/d/up1`) {
+ throw new HttpError(undefined, { status: 500, responseBody: { Message: 'nope' } });
+ }
+ return base === undefined ? undefined : base(request);
+ });
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
+
+ const result = await runMerge({ propsValue: { files: [{ file: pdf('a.pdf') }, { file: pdf('b.pdf') }] } });
+
+ expect(result.file_name).toBe('out.pdf');
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(String(warn.mock.calls[0][0])).toContain('up1');
+ warn.mockRestore();
+ });
+
+ it('deletes the uploaded inputs and the stored result from ConvertAPI afterwards', async () => {
+ mockApi();
+
+ await runMerge({ propsValue: { files: [{ file: pdf('a.pdf') }, { file: pdf('b.pdf') }] } });
+
+ const deleted = requests()
+ .filter((request) => request.method === 'DELETE')
+ .map((request) => request.url);
+ expect(deleted.sort()).toEqual([`${BASE}/d/res1`, `${BASE}/d/up1`, `${BASE}/d/up2`]);
+ });
+
+ it('needs at least two files before calling ConvertAPI', async () => {
+ await expect(runMerge({ propsValue: { files: [{ file: pdf('a.pdf') }] } })).rejects.toThrow(/at least two/);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+});
+
+describe('Split PDF File', () => {
+ it.each([
+ { mode: 'pagecount', value: '5', expected: '5' },
+ { mode: 'pagecount', value: '3,2', expected: '3,2' },
+ { mode: 'ranges', value: '1-3,5,7-9', expected: '1-3,5,7-9' },
+ { mode: 'singlepages', value: '1-2,5', expected: '1-2,5' },
+ { mode: 'text', value: 'Invoice\\s+#\\d+', expected: 'Invoice\\s+#\\d+' },
+ ])('sends Mode=$mode with Value=$value', async ({ mode, value, expected }) => {
+ mockApi();
+
+ await runSplit({ propsValue: { file: pdf('doc.pdf'), mode, value } });
+
+ const conversion = conversionRequest();
+ expect(conversion.url).toBe(`${BASE}/convert/pdf/to/split`);
+ expect(param({ request: conversion, name: 'File' })).toEqual({ Name: 'File', FileValue: { Id: 'up1' } });
+ expect(param({ request: conversion, name: 'Mode' })).toEqual({ Name: 'Mode', Value: mode });
+ expect(param({ request: conversion, name: 'Value' })).toEqual({ Name: 'Value', Value: expected });
+ });
+
+ it('omits Value for page count when empty, giving one file per page', async () => {
+ mockApi();
+
+ await runSplit({ propsValue: { file: pdf('doc.pdf'), mode: 'pagecount', value: '' } });
+
+ expect(param({ request: conversionRequest(), name: 'Mode' })).toEqual({ Name: 'Mode', Value: 'pagecount' });
+ expect(param({ request: conversionRequest(), name: 'Value' })).toBeUndefined();
+ });
+
+ it('ignores Value for the bookmark mode', async () => {
+ mockApi();
+
+ await runSplit({ propsValue: { file: pdf('doc.pdf'), mode: 'bookmark', value: 'anything' } });
+
+ expect(param({ request: conversionRequest(), name: 'Mode' })).toEqual({ Name: 'Mode', Value: 'bookmark' });
+ expect(param({ request: conversionRequest(), name: 'Value' })).toBeUndefined();
+ });
+
+ it.each(['ranges', 'singlepages', 'text'])('requires a Value for the %s mode', async (mode) => {
+ await expect(runSplit({ propsValue: { file: pdf('doc.pdf'), mode, value: ' ' } })).rejects.toThrow(/Split Value/);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('sends MergeOutput and Password only when set', async () => {
+ mockApi();
+
+ await runSplit({ propsValue: { file: pdf('doc.pdf'), mode: 'ranges', value: '1,3', mergeOutput: true, password: 'pw' } });
+ expect(param({ request: conversionRequest(), name: 'MergeOutput' })).toEqual({ Name: 'MergeOutput', Value: 'true' });
+ expect(param({ request: conversionRequest(), name: 'Password' })).toEqual({ Name: 'Password', Value: 'pw' });
+
+ sendRequest.mockClear();
+ await runSplit({ propsValue: { file: pdf('doc.pdf'), mode: 'ranges', value: '1,3', mergeOutput: false } });
+ expect(param({ request: conversionRequest(), name: 'MergeOutput' })).toBeUndefined();
+ expect(param({ request: conversionRequest(), name: 'Password' })).toBeUndefined();
+ });
+
+ it('returns one stored file per part, as an array', async () => {
+ mockApi({
+ conversion: {
+ body: {
+ ConversionCost: 1,
+ Files: [resultFile({ name: 'doc_0.pdf', id: 'r0' }), resultFile({ name: 'doc_1.pdf', id: 'r1' }), resultFile({ name: 'doc_2.pdf', id: 'r2' })],
+ },
+ },
+ });
+ const files = makeFiles();
+
+ const result = await runSplit({ propsValue: { file: pdf('doc.pdf'), mode: 'pagecount', value: '1' }, files });
+
+ expect(Array.isArray(result)).toBe(true);
+ expect(result).toHaveLength(3);
+ expect(files.write).toHaveBeenCalledTimes(3);
+ expect(result.map((part) => part.file)).toEqual([
+ 'https://ap.files/doc_0.pdf',
+ 'https://ap.files/doc_1.pdf',
+ 'https://ap.files/doc_2.pdf',
+ ]);
+ expect(Object.keys(result[0]).sort()).toEqual(['file', 'file_extension', 'file_name', 'file_size']);
+ });
+});
+
+describe('error surfacing', () => {
+ it('shows ConvertAPI\'s message for a concurrency limit and does not retry', async () => {
+ mockApi({
+ conversion: { status: 503, body: { Code: 5030, Message: 'Too many parallel conversions.' } },
+ });
+
+ const error = await runSplit({ propsValue: { file: pdf('doc.pdf'), mode: 'pagecount' } }).catch((caught: unknown) => caught);
+
+ expect(error).toBeInstanceOf(Error);
+ const message = error instanceof Error ? error.message : '';
+ expect(message).toContain('Too many parallel conversions.');
+ expect(message).toContain('code 5030');
+ expect(message).toContain('HTTP 503');
+ expect(message).toMatch(/one/);
+ const conversions = requests().filter((request) => request.url.startsWith(`${BASE}/convert/`));
+ expect(conversions).toHaveLength(1);
+ expect(conversions[0].retries).toBeUndefined();
+ });
+
+ it('still cleans up uploaded files when the conversion fails', async () => {
+ mockApi({ conversion: { status: 500, body: { Code: 5002, Message: 'The file is damaged.' } } });
+
+ await expect(runSplit({ propsValue: { file: pdf('doc.pdf'), mode: 'pagecount' } })).rejects.toThrow(/The file is damaged/);
+
+ expect(requests().some((request) => request.method === 'DELETE' && request.url === `${BASE}/d/up1`)).toBe(true);
+ });
+
+ it('reads error bodies that arrive as JSON strings', async () => {
+ mockApi({ conversion: { status: 401, body: '{"Code":4011,"Message":"Unauthorized."}' } });
+
+ await expect(runSplit({ propsValue: { file: pdf('doc.pdf'), mode: 'pagecount' } })).rejects.toThrow(
+ /Unauthorized\., code 4011\. Check that your API token is active/,
+ );
+ });
+});
+
+describe('Convert File', () => {
+ it('looks up the converter, uploads the file and converts it', async () => {
+ mockApi({ info: [DOCX_TO_PDF] });
+
+ const result = await runConvert({ propsValue: { from: 'docx', to: 'pdf', file: pdf('letter.docx'), options: {} } });
+
+ expect(requests()[0].url).toBe(`${BASE}/info/docx/to/pdf`);
+ const conversion = conversionRequest();
+ expect(conversion.url).toBe(`${BASE}/convert/docx/to/pdf`);
+ expect(param({ request: conversion, name: 'File' })).toEqual({ Name: 'File', FileValue: { Id: 'up1' } });
+ expect(result).toEqual([
+ { file: 'https://ap.files/out.pdf', file_name: 'out.pdf', file_extension: 'pdf', file_size: 1000 },
+ ]);
+ });
+
+ it('passes the converter options but never lets them override StoreFile or Timeout', async () => {
+ mockApi({ info: [DOCX_TO_PDF] });
+
+ await runConvert({
+ propsValue: {
+ from: 'docx',
+ to: 'pdf',
+ file: pdf('letter.docx'),
+ options: { PageRange: '1-3', ConvertMarkups: true, ImageQuality: 80, Timeout: 900, StoreFile: false, Empty: '' },
+ },
+ });
+
+ const conversion = conversionRequest();
+ expect(param({ request: conversion, name: 'PageRange' })).toEqual({ Name: 'PageRange', Value: '1-3' });
+ expect(param({ request: conversion, name: 'ConvertMarkups' })).toEqual({ Name: 'ConvertMarkups', Value: 'true' });
+ expect(param({ request: conversion, name: 'ImageQuality' })).toEqual({ Name: 'ImageQuality', Value: '80' });
+ expect(param({ request: conversion, name: 'Empty' })).toBeUndefined();
+ const timeouts = parametersOf(conversion).filter((parameter) => parameter['Name'] === 'Timeout');
+ expect(timeouts).toEqual([{ Name: 'Timeout', Value: '360' }]);
+ const storeFiles = parametersOf(conversion).filter((parameter) => parameter['Name'] === 'StoreFile');
+ expect(storeFiles).toEqual([{ Name: 'StoreFile', Value: 'true' }]);
+ });
+
+ it('names the output "converted" when the input came from a URL with no file name', async () => {
+ mockApi({ info: [DOCX_TO_PDF] });
+
+ await runConvert({ propsValue: { from: 'docx', to: 'pdf', file: pdf('unknown.docx'), options: {} } });
+
+ expect(param({ request: conversionRequest(), name: 'FileName' })).toEqual({ Name: 'FileName', Value: 'converted' });
+ });
+
+ it('keeps the input name, or the FileName option, when there is one', async () => {
+ mockApi({ info: [DOCX_TO_PDF, DOCX_TO_PDF] });
+
+ await runConvert({ propsValue: { from: 'docx', to: 'pdf', file: pdf('letter.docx'), options: {} } });
+ expect(param({ request: conversionRequest(), name: 'FileName' })).toBeUndefined();
+
+ await runConvert({ propsValue: { from: 'docx', to: 'pdf', file: pdf('unknown.docx'), options: { FileName: 'invoice' } } });
+ const conversions = requests().filter((request) => request.url.includes('/convert/'));
+ expect(param({ request: conversions[conversions.length - 1], name: 'FileName' })).toEqual({ Name: 'FileName', Value: 'invoice' });
+ });
+
+ it('sends every file as Files for converters that combine files', async () => {
+ mockApi({ info: [DOCX_MERGE] });
+
+ await runConvert({
+ propsValue: {
+ from: 'docx',
+ to: 'merge',
+ file: pdf('one.docx'),
+ additionalFiles: [{ file: pdf('two.docx') }, { file: pdf('three.docx') }],
+ },
+ });
+
+ expect(param({ request: conversionRequest(), name: 'Files' })).toEqual({
+ Name: 'Files',
+ FileValues: [{ Id: 'up1' }, { Id: 'up2' }, { Id: 'up3' }],
+ });
+ });
+
+ it('rejects additional files for single-file converters before uploading', async () => {
+ mockApi({ info: [DOCX_TO_PDF] });
+
+ await expect(
+ runConvert({ propsValue: { from: 'docx', to: 'pdf', file: pdf('a.docx'), additionalFiles: [{ file: pdf('b.docx') }] } }),
+ ).rejects.toThrow(/takes a single file/);
+ expect(requests().some((request) => request.url === `${BASE}/upload`)).toBe(false);
+ });
+
+ it('returns every output file when a conversion produces several', async () => {
+ mockApi({
+ info: [PDF_TO_JPG],
+ conversion: { body: { Files: [resultFile({ name: 'p-1.jpg', id: 'j1' }), resultFile({ name: 'p-2.jpg', id: 'j2' })] } },
+ });
+
+ const result = await runConvert({ propsValue: { from: 'pdf', to: 'jpg', file: pdf('deck.pdf') } });
+
+ expect(result.map((item) => item.file_name)).toEqual(['p-1.jpg', 'p-2.jpg']);
+ });
+
+ it('reports a missing converter', async () => {
+ mockApi({ info: [] });
+
+ await expect(runConvert({ propsValue: { from: 'docx', to: 'xyz', file: pdf('a.docx') } })).rejects.toThrow(/no converter/);
+ });
+});
+
+describe('/info dropdowns', () => {
+ const fromProp = convertFileAction.props.from;
+ const toProp = convertFileAction.props.to;
+ const optionsProp = convertFileAction.props.options;
+
+ it('lists each source format once with its extensions, skipping converters without a file input', async () => {
+ mockApi({ info: [DOCX_TO_PDF, DOCX_MERGE, PDF_TO_JPG, DATA_TO_QR, { Name: 'broken' }] });
+
+ const result = await fromProp.options({ auth: AUTH }, propertyContext());
+
+ expect(requests()[0].url).toBe(`${BASE}/info`);
+ expect(result.options).toEqual([
+ { label: 'DOCX (.docx, .doc)', value: 'docx' },
+ { label: 'PDF', value: 'pdf' },
+ ]);
+ });
+
+ it('asks for a From Format before listing targets', async () => {
+ const result = await toProp.options({ auth: AUTH }, propertyContext());
+
+ expect(result.disabled).toBe(true);
+ expect(result.placeholder).toMatch(/From Format/);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('lists the targets for the chosen source using the converter titles', async () => {
+ mockApi({ info: [DOCX_TO_PDF, DOCX_MERGE] });
+
+ const result = await toProp.options({ auth: AUTH, from: 'docx' }, propertyContext());
+
+ expect(requests()[0].url).toBe(`${BASE}/info/docx/to/*`);
+ expect(result.options).toEqual([
+ { label: 'DOCX to PDF', value: 'pdf' },
+ { label: 'Merge DOCX', value: 'merge' },
+ ]);
+ });
+
+ it('builds option fields from the converter parameters', async () => {
+ mockApi({ info: [DOCX_TO_PDF] });
+
+ const props = await optionsProp.props({ auth: AUTH, from: 'docx', to: 'pdf' }, propertyContext());
+
+ expect(Object.keys(props).sort()).toEqual(['ConvertMarkups', 'FileName', 'ImageQuality', 'PageRange', 'PdfVersion', 'Scale']);
+ expect(props['PageRange']).toMatchObject({ type: 'SHORT_TEXT', displayName: 'Page range', defaultValue: '1-2000' });
+ expect(props['PdfVersion']).toMatchObject({
+ type: 'STATIC_DROPDOWN',
+ defaultValue: '1.7',
+ options: { options: [{ label: 'PDF 1.4', value: '1.4' }, { label: 'PDF 1.7', value: '1.7' }] },
+ });
+ expect(props['ConvertMarkups']).toMatchObject({ type: 'CHECKBOX', defaultValue: false });
+ expect(props['ImageQuality']).toMatchObject({ type: 'NUMBER', defaultValue: 75 });
+ expect(props['Scale']).toMatchObject({ type: 'NUMBER' });
+ });
+
+ it('returns no option fields until both formats are picked', async () => {
+ const props = await optionsProp.props({ auth: AUTH, from: 'docx' }, propertyContext());
+
+ expect(props).toEqual({});
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+});
+
+describe('auth validation', () => {
+
+ it('treats a 401 as an invalid token', async () => {
+ sendRequest.mockRejectedValueOnce(new HttpError({}, { status: 401, responseBody: { Code: 4011, Message: 'Unauthorized.' } }));
+
+ const result = await validateToken({ auth: 'bad' });
+
+ expect(result).toMatchObject({ valid: false });
+ expect(sendRequest.mock.calls[0][0].headers.Authorization).toBe('Bearer bad');
+ });
+
+ it('treats a parameter validation error as a working token, without running a conversion', async () => {
+ sendRequest.mockRejectedValueOnce(new HttpError({}, { status: 400, responseBody: { Code: 4000, Message: 'Parameter validation error.' } }));
+
+ const result = await validateToken({ auth: 'good' });
+
+ expect(result).toEqual({ valid: true });
+ expect(sendRequest.mock.calls[0][0].body).toEqual({ Parameters: [] });
+ });
+
+ it('reports network failures without calling the token invalid', async () => {
+ sendRequest.mockRejectedValueOnce(new HttpError({}, { status: 502, responseBody: 'Bad gateway' }));
+
+ const result = await validateToken({ auth: 'good' });
+
+ expect(result).toMatchObject({ valid: false, error: expect.stringMatching(/Could not reach ConvertAPI/) });
+ });
+});
+
+describe('output schemas', () => {
+ function fieldKeys(fields: { key: string }[] | undefined): string[] {
+ return (fields ?? []).map((field) => field.key).sort();
+ }
+
+ it('describes the flat merged file with the same keys run() returns', async () => {
+ mockApi({ conversion: { body: { ConversionCost: 2, Files: [resultFile({ name: 'merged.pdf', id: 'res1' })] } } });
+
+ const result = await runMerge({ propsValue: { files: [{ file: pdf('a.pdf') }, { file: pdf('b.pdf') }] } });
+
+ const schema = mergePdfAction.outputSchema;
+ expect(schema?.itemLabel).toBeUndefined();
+ expect(fieldKeys(schema?.fields)).toEqual(Object.keys(result).sort());
+ });
+
+ it('describes each split part with the same keys run() returns', async () => {
+ mockApi({ conversion: { body: { Files: [resultFile({ name: 'p-1.pdf', id: 'r1' }), resultFile({ name: 'p-2.pdf', id: 'r2' })] } } });
+
+ const result = await runSplit({ propsValue: { file: pdf('doc.pdf'), mode: 'pagecount', value: '1' } });
+
+ const schema = splitPdfAction.outputSchema;
+ expect(schema?.itemLabel).toBe('{file_name}');
+ expect(schema?.fields).toHaveLength(1);
+ expect(schema?.fields[0].value).toBe('');
+ expect(fieldKeys(schema?.fields[0].listItems)).toEqual(Object.keys(result[0]).sort());
+ });
+
+ it('describes each converted file with the same keys run() returns', async () => {
+ mockApi({ info: [DOCX_TO_PDF] });
+
+ const result = await runConvert({ propsValue: { from: 'docx', to: 'pdf', file: pdf('letter.docx'), options: {} } });
+
+ const schema = convertFileAction.outputSchema;
+ expect(schema?.itemLabel).toBe('{file_name}');
+ expect(schema?.fields).toHaveLength(1);
+ expect(schema?.fields[0].value).toBe('');
+ expect(fieldKeys(schema?.fields[0].listItems)).toEqual(Object.keys(result[0]).sort());
+ });
+});
+
+type Request = {
+ method: string;
+ url: string;
+ headers?: Record<string, string>;
+ queryParams?: Record<string, string>;
+ body?: unknown;
+ responseType?: string;
+ retries?: number;
+};
+
+type ConversionReply = { status?: number; body: unknown };
+
+type AuthValue = { type: AppConnectionType.SECRET_TEXT; secret_text: string };
+
+type OptionalKeys<Value> = {
+ [Key in keyof Value]-?: undefined extends Value[Key] ? Key : never;
+}[keyof Value];
+
+type LoosePropsValue<Value> = Omit<Value, OptionalKeys<Value>> & Partial<Pick<Value, OptionalKeys<Value>>>;
+
+type RunInput<Props extends InputPropertyMap> = {
+ propsValue: LoosePropsValue<StaticPropsValue<Props>>;
+ files?: ReturnType<typeof makeFiles>;
+};
+
+type StoredOutput = {
+ file: string;
+ file_name: string;
+ file_extension?: string | null;
+ file_size?: number | null;
+ conversion_cost?: number | null;
+};
diff --git a/packages/pieces/community/convertapi/tsconfig.json b/packages/pieces/community/convertapi/tsconfig.json
new file mode 100644
index 00000000000..71bc5814f5d
--- /dev/null
+++ b/packages/pieces/community/convertapi/tsconfig.json
@@ -0,0 +1,15 @@
+{
+ "extends": "../../../../tsconfig.base.json",
+ "compilerOptions": {
+ "module": "commonjs",
+ "forceConsistentCasingInFileNames": true,
+ "strict": true,
+ "noImplicitOverride": true,
+ "noPropertyAccessFromIndexSignature": true,
+ "noImplicitReturns": true,
+ "noFallthroughCasesInSwitch": true
+ },
+ "files": [],
+ "include": [],
+ "references": [{ "path": "./tsconfig.lib.json" }]
+}
diff --git a/packages/pieces/community/convertapi/tsconfig.lib.json b/packages/pieces/community/convertapi/tsconfig.lib.json
new file mode 100644
index 00000000000..a648eb45d7f
--- /dev/null
+++ b/packages/pieces/community/convertapi/tsconfig.lib.json
@@ -0,0 +1,13 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "rootDir": ".",
+ "baseUrl": ".",
+ "paths": {},
+ "outDir": "./dist",
+ "declaration": true,
+ "types": ["node"]
+ },
+ "include": ["src/**/*.ts"],
+ "exclude": ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"]
+}
diff --git a/packages/pieces/community/convertapi/vitest.config.ts b/packages/pieces/community/convertapi/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/convertapi/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'),
+ },
+ },
+})
diff --git a/tsconfig.base.json b/tsconfig.base.json
index 2f67ad50d1d..7cdc39fbcee 100644
--- a/tsconfig.base.json
+++ b/tsconfig.base.json
@@ -346,6 +346,9 @@
"@activepieces/piece-contiguity": [
"packages/pieces/community/contiguity/src/index.ts"
],
+ "@activepieces/piece-convertapi": [
+ "packages/pieces/community/convertapi/src/index.ts"
+ ],
"@activepieces/piece-convertkit": [
"packages/pieces/community/convertkit/src/index.ts"
],