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
fix(pieces-common): load form-data only when a Custom API Call sends a form body (#16135)
Odai Ahmad465810204b55
diff --git a/bun.lock b/bun.lockindex 0f23a6ffe42..497326d3fdb 100644--- a/bun.lock+++ b/bun.lock@@ -216,7 +216,7 @@},"packages/pieces/common": {"name": "@activepieces/pieces-common",- "version": "0.14.0",+ "version": "0.14.1","dependencies": {"@activepieces/core-utils": "workspace:*","@activepieces/pieces-framework": "workspace:*",diff --git a/packages/pieces/common/package.json b/packages/pieces/common/package.jsonindex f52dd9315ff..6a5be024f8d 100644--- a/packages/pieces/common/package.json+++ b/packages/pieces/common/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/pieces-common",- "version": "0.14.0",+ "version": "0.14.1","type": "commonjs","sideEffects": false,"main": "./dist/src/index.js",diff --git a/packages/pieces/common/src/lib/helpers/index.ts b/packages/pieces/common/src/lib/helpers/index.tsindex cf1617aa116..1685b7e4a0a 100644--- a/packages/pieces/common/src/lib/helpers/index.ts+++ b/packages/pieces/common/src/lib/helpers/index.ts@@ -82,7 +82,6 @@ function contentTypeToExtension(contentType: string): string {const type = contentType.split(';')[0].trim().toLowerCase();return CONTENT_TYPE_EXTENSIONS[type] ?? '';}-import FormData from 'form-data';export const getAccessTokenOrThrow = (auth: OAuth2PropertyValue | undefined@@ -420,6 +419,7 @@ export function createCustomApiCallAction<fileFieldValue?: ApFile;}>;+ const { default: FormData } = await import('form-data');const formData = new FormData();for (const {diff --git a/packages/pieces/common/test/custom-api-call-form-data.test.ts b/packages/pieces/common/test/custom-api-call-form-data.test.tsnew file mode 100644index 00000000000..701d8f21412--- /dev/null+++ b/packages/pieces/common/test/custom-api-call-form-data.test.ts@@ -0,0 +1,96 @@+/// <reference types="vitest/globals" />++import { createRequire } from 'node:module';+import { ApFile } from '@activepieces/pieces-framework';+import { createCustomApiCallAction, httpClient, HttpMethod, HttpRequest } from '../src';++const nodeRequire = createRequire(__filename);++function isFormDataLoaded(): boolean {+ return Object.keys(nodeRequire.cache).some((path) => path.includes('/form-data/'));+}++function buildAction() {+ return createCustomApiCallAction({+ baseUrl: () => 'https://api.example.com/v1',+ authMapping: async () => ({ 'x-api-key': 'secret' }),+ });+}++async function runAction({ propsValue }: { propsValue: Record<string, unknown> }) {+ const action = buildAction();+ return action.run({+ auth: undefined,+ propsValue,+ files: { write: vi.fn() },+ } as never);+}++async function readBody(body: unknown): Promise<string> {+ const stream = body as NodeJS.ReadableStream;+ const chunks: Buffer[] = [];+ return new Promise((resolve, reject) => {+ stream.on('data', (chunk: Buffer | string) => chunks.push(Buffer.from(chunk)));+ stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8')));+ stream.on('error', reject);+ stream.resume();+ });+}++describe('createCustomApiCallAction form data body', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ test('does not load form-data when the piece is loaded or a JSON body is sent', async () => {+ const sendRequest = vi.spyOn(httpClient, 'sendRequest').mockResolvedValue({ status: 200, headers: {}, body: { ok: true } });+ expect(isFormDataLoaded()).toBe(false);++ const result = await runAction({+ propsValue: {+ method: HttpMethod.POST,+ url: { url: '/items' },+ body_type: 'json',+ body: { data: { name: 'a' } },+ },+ });++ expect(result).toEqual({ status: 200, headers: {}, body: { ok: true } });+ expect(sendRequest.mock.calls[0][0].body).toEqual({ name: 'a' });+ expect(isFormDataLoaded()).toBe(false);+ });++ test('sends text and file fields as multipart with the boundary header and the auth header', async () => {+ const sendRequest = vi.spyOn(httpClient, 'sendRequest').mockResolvedValue({ status: 201, headers: {}, body: { id: 1 } });++ await runAction({+ propsValue: {+ method: HttpMethod.POST,+ url: { url: '/upload' },+ body_type: 'form_data',+ body: {+ data: [+ { fieldName: 'title', fieldType: 'text', textFieldValue: 'Report' },+ { fieldName: 'file', fieldType: 'file', fileFieldValue: new ApFile('report.pdf', Buffer.from('%PDF-1.4 body'), 'pdf') },+ { fieldName: 'empty', fieldType: 'text', textFieldValue: '' },+ ],+ },+ },+ });++ const request = sendRequest.mock.calls[0][0] as HttpRequest;+ expect(request.url).toBe('https://api.example.com/v1/upload');+ expect(request.headers?.['x-api-key']).toBe('secret');+ const contentType = String(request.headers?.['content-type']);+ expect(contentType).toMatch(/^multipart\/form-data; boundary=/);++ const raw = await readBody(request.body);+ const boundary = contentType.split('boundary=')[1];+ expect(raw).toContain(`--${boundary}`);+ expect(raw).toContain('name="title"\r\n\r\nReport');+ expect(raw).toContain('name="file"; filename="report.pdf"');+ expect(raw).toContain('%PDF-1.4 body');+ expect(raw).not.toContain('name="empty"');+ expect(isFormDataLoaded()).toBe(true);+ });+});