AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(mindee): run Mindee v2 extraction, OCR, classify, crop and split from flows and AI agents (#16690)
Odai Ahmadc61b40f0113f
diff --git a/bun.lock b/bun.lockindex 55fc25e048e..3a6163eeba9 100644--- a/bun.lock+++ b/bun.lock@@ -6166,16 +6166,17 @@},"packages/pieces/community/mindee": {"name": "@activepieces/piece-mindee",- "version": "0.3.1",+ "version": "0.4.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*","@activepieces/pieces-common": "workspace:*","@activepieces/pieces-framework": "workspace:*",- "form-data": "4.0.6",+ "undici": "7.29.1",},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/missive": {diff --git a/docs/install/reference/breaking-changes-unreleased.mdx b/docs/install/reference/breaking-changes-unreleased.mdxindex 0ad8e0bb202..ed95cb64d3d 100644--- a/docs/install/reference/breaking-changes-unreleased.mdx+++ b/docs/install/reference/breaking-changes-unreleased.mdx@@ -8,6 +8,20 @@ Entries here move to [Breaking Changes](/install/reference/breaking-changes) aut## What has changed?+#### Mindee 0.4.0: the piece moves to the Mindee v2 API, and Predict Document is builder-only++Mindee 0.4.0 adds actions for the Mindee v2 API (app.mindee.com). The old action is renamed **Predict Document (Legacy v1)** and keeps calling the v1 API, but it is no longer offered as a tool to AI agents. Steps keep running on the version they were built with until you upgrade them.++The legacy action no longer reads a local file path from the server's disk. Pass a file, a public URL or a Base64 string instead. A URL in **File URL or Base64** is now sent to Mindee, which downloads it itself, instead of Activepieces downloading it first. A URL Mindee cannot reach, such as a file URL from a self-hosted instance on a private network, stops working after the upgrade; map the file into the **File** field instead.++New connections must use a v2 API key. A legacy v1 key from platform.mindee.com is rejected when you create or re-test a connection. Existing connections keep working with Predict Document (Legacy v1).++**Custom API Call** now uses `https://api-v2.mindee.net/v2` as its base URL. A step that used a relative v1 path now calls the v2 API. It only calls `https://api-v2.mindee.net` and `https://api.mindee.net` and refuses any other host, and every Mindee request now verifies the TLS certificate.++#### What you need to do++Agents that used Predict Document switch to Extract Document (AI) with a v2 API key and a model ID from app.mindee.com. If a legacy step passed a local file path, or a URL Mindee cannot reach from the internet, pass the file itself in the **File** field. If a Custom API Call step used a v1 path, enter the full `https://api.mindee.net/v1/...` URL or move it to the matching v2 endpoint.+#### Alai 0.3.0: three actions are no longer AI agent tools, and Custom API Call only calls the Alai API**Generate Presentation**, **Add Slide** and **Export Presentation** are no longer offered to AI agents as tools; flow steps that use them keep working unchanged. Agents get **Generate Presentation (Agent)**, **Add Slide (Agent)** and **Export Presentation (Agent)** instead: they take plain IDs and return a `generation_id` at once, which the agent polls with **Get Generation**. **Custom API Call** now sends the API key only to `https://slides-api.getalai.com/api` and refuses any other host or a path that escapes it.diff --git a/packages/pieces/community/mindee/package.json b/packages/pieces/community/mindee/package.jsonindex 9ecb2b36a90..cd55f8b9d42 100644--- a/packages/pieces/community/mindee/package.json+++ b/packages/pieces/community/mindee/package.json@@ -1,21 +1,23 @@{"name": "@activepieces/piece-mindee",- "version": "0.3.1",+ "version": "0.4.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"},"dependencies": {"@activepieces/pieces-common": "workspace:*","@activepieces/pieces-framework": "workspace:*",- "form-data": "4.0.6","@activepieces/core-piece-types": "workspace:*",- "@activepieces/core-utils": "workspace:*"+ "@activepieces/core-utils": "workspace:*",+ "undici": "7.29.1"},"devDependencies": {- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"}}diff --git a/packages/pieces/community/mindee/src/i18n/translation.json b/packages/pieces/community/mindee/src/i18n/translation.jsonindex ab6ba40f454..60f6ba6e0e4 100644--- a/packages/pieces/community/mindee/src/i18n/translation.json+++ b/packages/pieces/community/mindee/src/i18n/translation.json@@ -1,12 +1,65 @@{"Document automation API": "Document automation API",- "\n #### To obtain access your Api Key\n 1. Sign up and log in to Mindee\n 2. Go to [API Key page](https://platform.mindee.com/api-keys)\n 3. Copy the Key and paste below.\n ": "\n #### To obtain access your Api Key\n 1. Sign up and log in to Mindee\n 2. Go to [API Key page](https://platform.mindee.com/api-keys)\n 3. Copy the Key and paste below.\n ",+ "To get your API key:\n1. Sign in to the Mindee platform at [app.mindee.com](https://app.mindee.com).\n2. Open **API Keys** and create a key.\n3. Copy the key and paste it here.\n\nKeys from the legacy platform (platform.mindee.com) only work with the **Predict Document (Legacy v1)** action.": "To get your API key:\n1. Sign in to the Mindee platform at [app.mindee.com](https://app.mindee.com).\n2. Open **API Keys** and create a key.\n3. Copy the key and paste it here.\n\nKeys from the legacy platform (platform.mindee.com) only work with the **Predict Document (Legacy v1)** action.","Extract Document": "Extract Document",+ "Classify Document": "Classify Document",+ "Crop Document": "Crop Document",+ "Read Document Text (OCR)": "Read Document Text (OCR)",+ "Split Document": "Split Document",+ "Get Job Status": "Get Job Status",+ "Get Result": "Get Result",+ "List Models": "List Models",+ "Upload RAG Document": "Upload RAG Document",+ "Get RAG Document": "Get RAG Document",+ "Update RAG Document": "Update RAG Document",+ "Delete RAG Document": "Delete RAG Document",+ "Search RAG Documents": "Search RAG Documents",+ "Predict Document (Legacy v1)": "Predict Document (Legacy v1)",+ "Extract Document (AI)": "Extract Document (AI)",+ "Classify Document (AI)": "Classify Document (AI)",+ "Crop Document (AI)": "Crop Document (AI)",+ "Read Document Text (OCR) (AI)": "Read Document Text (OCR) (AI)",+ "Split Document (AI)": "Split Document (AI)",+ "Upload RAG Document (AI)": "Upload RAG Document (AI)","Custom API Call": "Custom API Call",- "Parse details of a document using OCR.": "Parse details of a document using OCR.",+ "Extracts structured fields from a document with one of your Mindee extraction models.": "Extracts structured fields from a document with one of your Mindee extraction models.",+ "Detects the type of a document with one of your Mindee classification models.": "Detects the type of a document with one of your Mindee classification models.",+ "Finds each separate object (for example several receipts on one scan) with one of your Mindee crop models.": "Finds each separate object (for example several receipts on one scan) with one of your Mindee crop models.",+ "Reads all the text in a document with one of your Mindee OCR models.": "Reads all the text in a document with one of your Mindee OCR models.",+ "Finds where each document starts and ends in a multi-document file with one of your Mindee split models.": "Finds where each document starts and ends in a multi-document file with one of your Mindee split models.",+ "Checks whether a Mindee job has finished and returns its inference ID.": "Checks whether a Mindee job has finished and returns its inference ID.",+ "Gets the result of a finished Mindee inference.": "Gets the result of a finished Mindee inference.",+ "Lists the models in your Mindee organization.": "Lists the models in your Mindee organization.",+ "Adds a reference document to an extraction model so it can learn from it (RAG).": "Adds a reference document to an extraction model so it can learn from it (RAG).",+ "Gets a RAG document of an extraction model.": "Gets a RAG document of an extraction model.",+ "Activates or deactivates a RAG document, or replaces its field annotation.": "Activates or deactivates a RAG document, or replaces its field annotation.",+ "Permanently deletes a RAG document from an extraction model.": "Permanently deletes a RAG document from an extraction model.",+ "Lists the RAG documents of an extraction model, optionally by file name.": "Lists the RAG documents of an extraction model, optionally by file name.",+ "Legacy: parses a document with an off-the-shelf Mindee v1 API. Needs a v1 API key from platform.mindee.com; use Extract Document for v2 keys.": "Legacy: parses a document with an off-the-shelf Mindee v1 API. Needs a v1 API key from platform.mindee.com; use Extract Document for v2 keys.",+ "Adds a reference document from a URL to an extraction model so it can learn from it (RAG).": "Adds a reference document from a URL to an extraction model so it can learn from it (RAG).","Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",+ "Model": "Model",+ "File": "File",+ "Alias": "Alias",+ "Use RAG": "Use RAG",+ "Include Raw Text": "Include Raw Text",+ "Include Confidence": "Include Confidence",+ "Text Context": "Text Context",+ "Job ID": "Job ID",+ "Product": "Product",+ "Inference ID": "Inference ID",+ "Model Type": "Model Type",+ "Name Contains": "Name Contains",+ "Page": "Page",+ "Per Page": "Per Page",+ "RAG Document ID": "RAG Document ID",+ "Status": "Status",+ "Annotation": "Annotation",+ "File Name Contains": "File Name Contains","Account Name": "Account Name","API Name": "API Name",+ "File URL or Base64": "File URL or Base64",+ "Model ID": "Model ID","File URL": "File URL","Method": "Method","Headers": "Headers",@@ -17,21 +70,57 @@"Return Error as Output": "Return Error as Output","Timeout": "Timeout","Follow redirects": "Follow redirects",- "Refers to your username or organization name with which you signed up with.": "Refers to your username or organization name with which you signed up with.",- "Refers to the name of the API your are using.": "Refers to the name of the API your are using.",- "Remote file URL or Base64 string. We currently support .pdf (slower), .jpg, .png, .webp, .tiff and .heic formats": "Remote file URL or Base64 string. We currently support .pdf (slower), .jpg, .png, .webp, .tiff and .heic formats",+ "Your Mindee Extraction model. Models are created at app.mindee.com.": "Your Mindee Extraction model. Models are created at app.mindee.com.",+ "The document to process (PDF, JPEG, PNG, WEBP, TIFF or HEIC).": "The document to process (PDF, JPEG, PNG, WEBP, TIFF or HEIC).",+ "Optional tag of your own (for example an internal document ID). Mindee returns it with the job and result.": "Optional tag of your own (for example an internal document ID). Mindee returns it with the job and result.",+ "Use the RAG documents uploaded for this model to improve accuracy.": "Use the RAG documents uploaded for this model to improve accuracy.",+ "Also return the full text of the document.": "Also return the full text of the document.",+ "Return a confidence level (Certain, High or Medium) for each top-level field.": "Return a confidence level (Certain, High or Medium) for each top-level field.",+ "Optional hint for the model for this document, for example \"This is a grocery receipt.\"": "Optional hint for the model for this document, for example \"This is a grocery receipt.\"",+ "Your Mindee Classification model. Models are created at app.mindee.com.": "Your Mindee Classification model. Models are created at app.mindee.com.",+ "Your Mindee Crop model. Models are created at app.mindee.com.": "Your Mindee Crop model. Models are created at app.mindee.com.",+ "Your Mindee OCR model. Models are created at app.mindee.com.": "Your Mindee OCR model. Models are created at app.mindee.com.",+ "Your Mindee Split model. Models are created at app.mindee.com.": "Your Mindee Split model. Models are created at app.mindee.com.",+ "The Mindee product that ran the inference.": "The Mindee product that ran the inference.",+ "Page number, starting at 1.": "Page number, starting at 1.",+ "Between 1 and 100.": "Between 1 and 100.",+ "The extraction model the RAG documents belong to.": "The extraction model the RAG documents belong to.",+ "The reference document (PDF or image).": "The reference document (PDF or image).",+ "Active documents are used for matching; Draft documents are ignored.": "Active documents are used for matching; Draft documents are ignored.",+ "Optional. Replaces the field annotation of the document.": "Optional. Replaces the field annotation of the document.",+ "Keep \"mindee\" for the off-the-shelf APIs.": "Keep \"mindee\" for the off-the-shelf APIs.",+ "The Mindee v1 API to use.": "The Mindee v1 API to use.",+ "The document to parse. Leave empty to use File URL or Base64 instead.": "The document to parse. Leave empty to use File URL or Base64 instead.",+ "An http(s) URL or Base64 string, used when File is empty.": "An http(s) URL or Base64 string, used when File is empty.",+ "UUID of a Mindee Extraction model, from List Models.": "UUID of a Mindee Extraction model, from List Models.",+ "Public https:// URL of the document. Mindee downloads it directly.": "Public https:// URL of the document. Mindee downloads it directly.",+ "UUID of a Mindee Classification model, from List Models.": "UUID of a Mindee Classification model, from List Models.",+ "UUID of a Mindee Crop model, from List Models.": "UUID of a Mindee Crop model, from List Models.",+ "UUID of a Mindee OCR model, from List Models.": "UUID of a Mindee OCR model, from List Models.",+ "UUID of a Mindee Split model, from List Models.": "UUID of a Mindee Split model, from List Models.",+ "UUID of a Mindee extraction model.": "UUID of a Mindee extraction model.",+ "Public https:// URL of the reference document.": "Public https:// URL of the reference document.","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.",- "Bank Account Details OCR": "Bank Account Details OCR",- "Receipt OCR": "Receipt OCR",+ "Extraction": "Extraction",+ "Classification": "Classification",+ "Crop": "Crop",+ "OCR": "OCR",+ "Split": "Split",+ "Active": "Active",+ "Draft": "Draft",+ "Invoice OCR (v4)": "Invoice OCR (v4)",+ "Receipt OCR (v5)": "Receipt OCR (v5)",+ "Financial Documents OCR": "Financial Documents OCR","Passport OCR": "Passport OCR",- "Invoice OCR": "Invoice OCR",+ "Bank Account Details OCR": "Bank Account Details OCR","Proof of Address OCR": "Proof of Address OCR",- "Financial Documents OCR": "Financial Documents OCR",+ "Invoice OCR (v3, older)": "Invoice OCR (v3, older)",+ "Receipt OCR (v4, older)": "Receipt OCR (v4, older)","GET": "GET","POST": "POST","PATCH": "PATCH",diff --git a/packages/pieces/community/mindee/src/index.ts b/packages/pieces/community/mindee/src/index.tsindex 344336a06a6..8e31acf310b 100644--- a/packages/pieces/community/mindee/src/index.ts+++ b/packages/pieces/community/mindee/src/index.ts@@ -1,37 +1,55 @@-import { createCustomApiCallAction } from '@activepieces/pieces-common';-import { PieceAuth, createPiece } from '@activepieces/pieces-framework';-import { PieceCategory } from '@activepieces/pieces-framework';+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';+import { mindeeAuth } from './lib/auth';+import { mindeeCustomApiCall } from './lib/actions/custom-api-call';+import { getJobStatusAction, getResultAction } from './lib/actions/jobs';+import { listModelsAction } from './lib/actions/list-models';import { mindeePredictDocumentAction } from './lib/actions/predict-document';--export const mindeeAuth = PieceAuth.SecretText({- displayName: 'Api Key',- description: `- #### To obtain access your Api Key- 1. Sign up and log in to Mindee- 2. Go to [API Key page](https://platform.mindee.com/api-keys)- 3. Copy the Key and paste below.- `,- required: true,-});+import { classifyDocumentAction, classifyDocumentAiAction } from './lib/actions/classify-document';+import { cropDocumentAction, cropDocumentAiAction } from './lib/actions/crop-document';+import { extractDocumentAction, extractDocumentAiAction } from './lib/actions/extract-document';+import { ocrDocumentAction, ocrDocumentAiAction } from './lib/actions/ocr-document';+import { splitDocumentAction, splitDocumentAiAction } from './lib/actions/split-document';+import {+ deleteRagDocumentAction,+ getRagDocumentAction,+ searchRagDocumentsAction,+ updateRagDocumentAction,+ uploadRagDocumentAction,+ uploadRagDocumentAiAction,+} from './lib/actions/rag-documents';export const mindee = createPiece({displayName: 'Mindee',description: 'Document automation API',-- minimumSupportedRelease: '0.30.0',+ minimumSupportedRelease: '0.88.2',logoUrl: 'https://cdn.activepieces.com/pieces/mindee.png',- categories: [PieceCategory.COMMUNICATION],- authors: ["kanarelo","kishanprmr","MoShizzle","khaledmashaly","abuaboud"],+ categories: [PieceCategory.ARTIFICIAL_INTELLIGENCE, PieceCategory.PRODUCTIVITY],+ authors: ['kanarelo', 'kishanprmr', 'MoShizzle', 'khaledmashaly', 'abuaboud', 'OdaiAhmed99'],auth: mindeeAuth,actions: [+ extractDocumentAction,+ classifyDocumentAction,+ cropDocumentAction,+ ocrDocumentAction,+ splitDocumentAction,+ getJobStatusAction,+ getResultAction,+ listModelsAction,+ uploadRagDocumentAction,+ getRagDocumentAction,+ updateRagDocumentAction,+ deleteRagDocumentAction,+ searchRagDocumentsAction,mindeePredictDocumentAction,- createCustomApiCallAction({- baseUrl: () => 'https://api.mindee.net/v1',- auth: mindeeAuth,- authMapping: async (auth) => ({- Authorization: `Token ${auth.secret_text}`,- }),- }),+ extractDocumentAiAction,+ classifyDocumentAiAction,+ cropDocumentAiAction,+ ocrDocumentAiAction,+ splitDocumentAiAction,+ uploadRagDocumentAiAction,+ mindeeCustomApiCall,],triggers: [],});++export { mindeeAuth };diff --git a/packages/pieces/community/mindee/src/lib/actions/classify-document.ts b/packages/pieces/community/mindee/src/lib/actions/classify-document.tsnew file mode 100644index 00000000000..f6a433b9b8a--- /dev/null+++ b/packages/pieces/community/mindee/src/lib/actions/classify-document.ts@@ -0,0 +1,46 @@+import { createAction } from '@activepieces/pieces-framework';+import { mindeeAuth } from '../auth';+import { mindeeSchemas } from '../output-schemas';+import { productActionHelpers } from './product-action-helpers';++export const classifyDocumentAction = createAction({+ auth: mindeeAuth,+ name: 'classify_document',+ displayName: 'Classify Document',+ description: 'Detects the type of a document with one of your Mindee classification models.',+ classification: 'READ',+ audience: 'human',+ aiMetadata: {+ description:+ 'Identify which document type (from the classes configured in a Mindee classification model) a file is. Returns document_type. Waits up to 4 minutes; if Mindee is still processing, the step fails with the job ID so you can collect it later with Get Job Status and Get Result. Each run spends Mindee page credits.',+ idempotent: true,+ },+ props: {+ ...productActionHelpers.builderProps('classification'),+ },+ outputSchema: mindeeSchemas.inferenceSchema('classification'),+ async run({ auth, propsValue }) {+ return productActionHelpers.runWithFile({ apiKey: auth.secret_text, product: 'classification', props: propsValue });+ },+});++export const classifyDocumentAiAction = createAction({+ auth: mindeeAuth,+ name: 'classify_document_ai',+ displayName: 'Classify Document (AI)',+ description: 'Detects the type of a document with one of your Mindee classification models.',+ classification: 'READ',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Identify which document type (from the classes configured in a Mindee classification model) a file is. Returns document_type. Waits up to 4 minutes; if Mindee is still processing it returns completed=false and a job_id for Get Job Status and Get Result. Each run spends Mindee page credits. Get the model ID from List Models (model_type classification).',+ idempotent: true,+ },+ props: {+ ...productActionHelpers.aiProps('classification'),+ },+ outputSchema: mindeeSchemas.inferenceSchema('classification'),+ async run({ auth, propsValue }) {+ return productActionHelpers.runWithUrl({ apiKey: auth.secret_text, product: 'classification', props: propsValue });+ },+});diff --git a/packages/pieces/community/mindee/src/lib/actions/crop-document.ts b/packages/pieces/community/mindee/src/lib/actions/crop-document.tsnew file mode 100644index 00000000000..a7f027185cb--- /dev/null+++ b/packages/pieces/community/mindee/src/lib/actions/crop-document.ts@@ -0,0 +1,46 @@+import { createAction } from '@activepieces/pieces-framework';+import { mindeeAuth } from '../auth';+import { mindeeSchemas } from '../output-schemas';+import { productActionHelpers } from './product-action-helpers';++export const cropDocumentAction = createAction({+ auth: mindeeAuth,+ name: 'crop_document',+ displayName: 'Crop Document',+ description: 'Finds each separate object (for example several receipts on one scan) with one of your Mindee crop models.',+ classification: 'READ',+ audience: 'human',+ aiMetadata: {+ description:+ 'Detect the separate objects in one image or page (for example several receipts or cards scanned together) with a Mindee crop model. Returns each object type, page and polygon. Waits up to 4 minutes; if Mindee is still processing, the step fails with the job ID so you can collect it later with Get Job Status and Get Result. Each run spends Mindee page credits.',+ idempotent: true,+ },+ props: {+ ...productActionHelpers.builderProps('crop'),+ },+ outputSchema: mindeeSchemas.inferenceSchema('crop'),+ async run({ auth, propsValue }) {+ return productActionHelpers.runWithFile({ apiKey: auth.secret_text, product: 'crop', props: propsValue });+ },+});++export const cropDocumentAiAction = createAction({+ auth: mindeeAuth,+ name: 'crop_document_ai',+ displayName: 'Crop Document (AI)',+ description: 'Finds each separate object (for example several receipts on one scan) with one of your Mindee crop models.',+ classification: 'READ',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Detect the separate objects in one image or page (for example several receipts or cards scanned together) with a Mindee crop model. Returns each object type, page and polygon. Waits up to 4 minutes; if Mindee is still processing it returns completed=false and a job_id for Get Job Status and Get Result. Each run spends Mindee page credits. Get the model ID from List Models (model_type crop).',+ idempotent: true,+ },+ props: {+ ...productActionHelpers.aiProps('crop'),+ },+ outputSchema: mindeeSchemas.inferenceSchema('crop'),+ async run({ auth, propsValue }) {+ return productActionHelpers.runWithUrl({ apiKey: auth.secret_text, product: 'crop', props: propsValue });+ },+});diff --git a/packages/pieces/community/mindee/src/lib/actions/custom-api-call.ts b/packages/pieces/community/mindee/src/lib/actions/custom-api-call.tsnew file mode 100644index 00000000000..f3da45143c0--- /dev/null+++ b/packages/pieces/community/mindee/src/lib/actions/custom-api-call.ts@@ -0,0 +1,135 @@+import { createCustomApiCallAction, HttpMethod, HttpRequest, httpClient, toFailsafeOutput } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { mindeeAuth } from '../auth';+import { MINDEE_V2_BASE_URL, isRecord, normalizeApiKey, verifiedTls } from '../common/client';++const base = createCustomApiCallAction({+ auth: mindeeAuth,+ baseUrl: () => `${MINDEE_V2_BASE_URL}/v2`,+ authMapping: async () => ({}),+});++export const mindeeCustomApiCall = createAction({+ auth: mindeeAuth,+ name: 'custom_api_call',+ displayName: base.displayName,+ description: base.description,+ props: base.props,+ propertyGroups: base.propertyGroups,+ classification: 'WRITE',+ audience: 'human',+ aiMetadata: {+ description:+ 'Send any request to the Mindee API with the connection key, for endpoints the other actions do not cover. Only https://api-v2.mindee.net (v2, relative paths) and https://api.mindee.net (v1) are allowed. Returns status, headers and body. Can spend credits or change data depending on the endpoint.',+ idempotent: false,+ },+ async run({ auth, propsValue, files }) {+ const method = methodOf(propsValue['method']);+ let target = resolveMindeeUrl(urlOf(propsValue['url']));+ const timeout = propsValue['timeout'];+ const followRedirects = propsValue['followRedirects'] === true;+ const binary = propsValue['response_is_binary'] === true;+ const key = normalizeApiKey(auth.secret_text);+ const body = bodyOf({ body: propsValue['body'], bodyType: propsValue['body_type'] });+ try {+ for (let hop = 0; ; hop++) {+ const request: HttpRequest = {+ method,+ url: target.toString(),+ headers: { ...stringMap(propsValue['headers']), Authorization: target.host === V1_HOST ? `Token ${key}` : key },+ queryParams: stringMap(propsValue['queryParams']),+ timeout: typeof timeout === 'number' && timeout > 0 ? timeout * 1000 : 0,+ followRedirects: false,+ redactBodyInErrors: true,+ body,+ };+ if (binary) request.responseType = 'arraybuffer';+ const response = await httpClient.sendRequest(request, { dispatcher: await verifiedTls() });+ const location = headerValue(response.headers?.['location']);+ if (followRedirects && response.status >= 300 && response.status < 400 && location !== undefined && hop < MAX_REDIRECTS) {+ target = resolveMindeeUrl(new URL(location, target).toString());+ continue;+ }+ const data: unknown = response.body;+ if (binary && (data instanceof ArrayBuffer || Buffer.isBuffer(data))) {+ const buffer = Buffer.isBuffer(data) ? data : Buffer.from(new Uint8Array(data));+ return { status: response.status, headers: response.headers, body: await files.write({ fileName: 'output.bin', data: buffer }) };+ }+ return { status: response.status, headers: response.headers, body: data };+ }+ } catch (error) {+ if (propsValue['failsafe'] === true) return toFailsafeOutput({ error, requestBody: '[redacted]' });+ throw error;+ }+ },+});++function resolveMindeeUrl(raw: string): URL {+ if (raw === '') throw new Error('URL is required.');+ if (raw.split(/[/?#]/).some((part) => part === '..' || part.toLowerCase() === '%2e%2e')) {+ throw new Error('The URL must not contain ".." segments.');+ }+ const isAbsolute = /^[a-z][a-z0-9+.-]*:/i.test(raw) || raw.startsWith('//');+ let url: URL;+ try {+ url = isAbsolute ? new URL(raw) : new URL(`${MINDEE_V2_BASE_URL}/v2/${raw.replace(/^\/+/, '')}`);+ } catch {+ throw new Error('The URL is not valid.');+ }+ if (url.protocol !== 'https:' || !ALLOWED_HOSTS.includes(url.host) || url.username !== '' || url.password !== '') {+ throw new Error(`The URL must be on https://${ALLOWED_HOSTS.join(' or https://')}; the Mindee API key is only sent there.`);+ }+ return url;+}++function urlOf(value: unknown): string {+ const raw = isRecord(value) ? value['url'] : value;+ return typeof raw === 'string' ? raw.trim() : '';+}++function methodOf(value: unknown): HttpMethod {+ const method = Object.values(HttpMethod).find((m) => m === value);+ if (!method) throw new Error('Method is required.');+ return method;+}++function headerValue(raw: unknown): string | undefined {+ const value = Array.isArray(raw) ? raw[0] : raw;+ return typeof value === 'string' && value.length > 0 ? value : undefined;+}++function stringMap(value: unknown): Record<string, string> {+ if (!isRecord(value)) return {};+ const entries: [string, string][] = [];+ for (const [key, item] of Object.entries(value)) {+ if (key.toLowerCase() === 'authorization') continue;+ if (typeof item === 'string') entries.push([key, item]);+ else if (typeof item === 'number' || typeof item === 'boolean' || typeof item === 'bigint') entries.push([key, String(item)]);+ }+ return Object.fromEntries(entries);+}++function bodyOf({ body, bodyType }: { body: unknown; bodyType: unknown }): HttpRequest['body'] {+ if (body === undefined || body === null) return undefined;+ if (!bodyType) return isRecord(body) || Array.isArray(body) || typeof body === 'string' ? body : undefined;+ if (bodyType === 'none' || !isRecord(body)) return undefined;+ const data = body['data'];+ if (bodyType !== 'form_data') return isRecord(data) || Array.isArray(data) || typeof data === 'string' ? data : undefined;+ const form = new FormData();+ for (const field of Array.isArray(data) ? data : []) {+ if (!isRecord(field) || typeof field['fieldName'] !== 'string') continue;+ const text = field['textFieldValue'];+ const file = isRecord(field['fileFieldValue']) ? field['fileFieldValue'] : {};+ if (field['fieldType'] === 'text' && typeof text === 'string' && text !== '') form.append(field['fieldName'], text);+ else if (field['fieldType'] === 'file' && Buffer.isBuffer(file['data'])) {+ form.append(field['fieldName'], new Blob([new Uint8Array(file['data'])]), typeof file['filename'] === 'string' ? file['filename'] : undefined);+ }+ }+ return form;+}++const V1_HOST = 'api.mindee.net';+const ALLOWED_HOSTS = ['api-v2.mindee.net', V1_HOST];+const MAX_REDIRECTS = 3;++export const mindeeCustomCall = { resolveMindeeUrl };diff --git a/packages/pieces/community/mindee/src/lib/actions/extract-document.ts b/packages/pieces/community/mindee/src/lib/actions/extract-document.tsnew file mode 100644index 00000000000..ca2ac49cbfb--- /dev/null+++ b/packages/pieces/community/mindee/src/lib/actions/extract-document.ts@@ -0,0 +1,49 @@+import { createAction } from '@activepieces/pieces-framework';+import { mindeeAuth } from '../auth';+import { mindeeProps } from '../common/props';+import { mindeeSchemas } from '../output-schemas';+import { productActionHelpers } from './product-action-helpers';++export const extractDocumentAction = createAction({+ auth: mindeeAuth,+ name: 'extract_document',+ displayName: 'Extract Document',+ description: 'Extracts structured fields from a document with one of your Mindee extraction models.',+ classification: 'READ',+ audience: 'human',+ aiMetadata: {+ description:+ 'Extract structured data (for example invoice totals, receipt line items, ID details) from a document with a Mindee extraction model. Returns the fields defined in the model data schema as name to value pairs. Waits up to 4 minutes; if Mindee is still processing, the step fails with the job ID so you can collect it later with Get Job Status and Get Result. Each run spends Mindee page credits.',+ idempotent: true,+ },+ props: {+ ...productActionHelpers.builderProps('extraction'),+ ...mindeeProps.extractionOptionProps(),+ },+ outputSchema: mindeeSchemas.inferenceSchema('extraction'),+ async run({ auth, propsValue }) {+ return productActionHelpers.runWithFile({ apiKey: auth.secret_text, product: 'extraction', props: propsValue });+ },+});++export const extractDocumentAiAction = createAction({+ auth: mindeeAuth,+ name: 'extract_document_ai',+ displayName: 'Extract Document (AI)',+ description: 'Extracts structured fields from a document with one of your Mindee extraction models.',+ classification: 'READ',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Extract structured data (for example invoice totals, receipt line items, ID details) from a document with a Mindee extraction model. Returns the fields defined in the model data schema as name to value pairs. Waits up to 4 minutes; if Mindee is still processing it returns completed=false and a job_id for Get Job Status and Get Result. Each run spends Mindee page credits. Get the model ID from List Models (model_type extraction).',+ idempotent: true,+ },+ props: {+ ...productActionHelpers.aiProps('extraction'),+ ...mindeeProps.extractionOptionProps(),+ },+ outputSchema: mindeeSchemas.inferenceSchema('extraction'),+ async run({ auth, propsValue }) {+ return productActionHelpers.runWithUrl({ apiKey: auth.secret_text, product: 'extraction', props: propsValue });+ },+});diff --git a/packages/pieces/community/mindee/src/lib/actions/jobs.ts b/packages/pieces/community/mindee/src/lib/actions/jobs.tsnew file mode 100644index 00000000000..123a4eba458--- /dev/null+++ b/packages/pieces/community/mindee/src/lib/actions/jobs.ts@@ -0,0 +1,49 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { mindeeAuth } from '../auth';+import { mindeeInference } from '../common/inference';+import { mindeeProps } from '../common/props';+import { mindeeSchemas } from '../output-schemas';++export const getJobStatusAction = createAction({+ auth: mindeeAuth,+ name: 'get_job_status',+ displayName: 'Get Job Status',+ description: 'Checks whether a Mindee job has finished and returns its inference ID.',+ classification: 'READ',+ audience: 'both',+ aiMetadata: {+ description:+ 'Check a Mindee processing job by job_id (returned when an extract/classify/crop/OCR/split run hit its wait limit). When status is Processed it returns product and inference_id for Get Result. Read-only, free, safe to retry.',+ idempotent: true,+ },+ props: {+ job_id: Property.ShortText({ displayName: 'Job ID', required: true }),+ },+ outputSchema: mindeeSchemas.jobStatus,+ async run({ auth, propsValue }) {+ const job = await mindeeInference.getJob({ apiKey: auth.secret_text, jobId: propsValue.job_id });+ return mindeeInference.jobSummary(job);+ },+});++export const getResultAction = createAction({+ auth: mindeeAuth,+ name: 'get_result',+ displayName: 'Get Result',+ description: 'Gets the result of a finished Mindee inference.',+ classification: 'READ',+ audience: 'both',+ aiMetadata: {+ description:+ 'Get the result of a finished Mindee inference by product (extraction, classification, crop, ocr, split) and inference_id (from Get Job Status). Returns the same shape as the run actions. Only for runs that returned completed=false: once a result has been fetched, Mindee may delete the job and inference (depending on the account data retention setting) and this returns not found. Read-only, free.',+ idempotent: true,+ },+ props: {+ product: mindeeProps.productProp(),+ inference_id: Property.ShortText({ displayName: 'Inference ID', required: true }),+ },+ outputSchema: mindeeSchemas.anyResult,+ async run({ auth, propsValue }) {+ return mindeeInference.getResult({ apiKey: auth.secret_text, product: propsValue.product, inferenceId: propsValue.inference_id });+ },+});diff --git a/packages/pieces/community/mindee/src/lib/actions/list-models.ts b/packages/pieces/community/mindee/src/lib/actions/list-models.tsnew file mode 100644index 00000000000..2d10502d297--- /dev/null+++ b/packages/pieces/community/mindee/src/lib/actions/list-models.ts@@ -0,0 +1,42 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { mindeeAuth } from '../auth';+import { mindeeApi } from '../common/api';+import { mindeeInputs } from '../common/inputs';+import { MindeeProduct } from '../common/inference';+import { mindeeProps } from '../common/props';+import { mindeeSchemas } from '../output-schemas';++export const listModelsAction = createAction({+ auth: mindeeAuth,+ name: 'list_models',+ displayName: 'List Models',+ description: 'Lists the models in your Mindee organization.',+ classification: 'SEARCH',+ audience: 'both',+ aiMetadata: {+ description:+ 'List the Mindee models available to this API key, optionally filtered by name or model_type (extraction, classification, crop, ocr, split). Use it to find the model_id the run actions need. Read-only, free, safe to retry.',+ idempotent: true,+ },+ props: {+ model_type: Property.StaticDropdown<MindeeProduct, false>({+ displayName: 'Model Type',+ required: false,+ options: { disabled: false, options: mindeeProps.PRODUCT_OPTIONS },+ }),+ name: Property.ShortText({ displayName: 'Name Contains', required: false }),+ page: Property.Number({ displayName: 'Page', description: 'Page number, starting at 1.', required: false, defaultValue: 1 }),+ per_page: Property.Number({ displayName: 'Per Page', description: 'Between 1 and 100.', required: false, defaultValue: 50 }),+ },+ outputSchema: mindeeSchemas.models,+ async run({ auth, propsValue }) {+ return mindeeApi.listModels({+ apiKey: auth.secret_text,+ name: propsValue.name,+ modelType: propsValue.model_type,+ page: mindeeInputs.positiveInt({ value: propsValue.page, fallback: 1, max: 10_000 }),+ perPage: mindeeInputs.positiveInt({ value: propsValue.per_page, fallback: 50, max: 100 }),+ });+ },+});+diff --git a/packages/pieces/community/mindee/src/lib/actions/ocr-document.ts b/packages/pieces/community/mindee/src/lib/actions/ocr-document.tsnew file mode 100644index 00000000000..c7094cd9d76--- /dev/null+++ b/packages/pieces/community/mindee/src/lib/actions/ocr-document.ts@@ -0,0 +1,46 @@+import { createAction } from '@activepieces/pieces-framework';+import { mindeeAuth } from '../auth';+import { mindeeSchemas } from '../output-schemas';+import { productActionHelpers } from './product-action-helpers';++export const ocrDocumentAction = createAction({+ auth: mindeeAuth,+ name: 'ocr_document',+ displayName: 'Read Document Text (OCR)',+ description: 'Reads all the text in a document with one of your Mindee OCR models.',+ classification: 'READ',+ audience: 'human',+ aiMetadata: {+ description:+ 'Read the full text of a document page by page with a Mindee OCR model. Returns the text and per-page content. Waits up to 4 minutes; if Mindee is still processing, the step fails with the job ID so you can collect it later with Get Job Status and Get Result. Each run spends Mindee page credits.',+ idempotent: true,+ },+ props: {+ ...productActionHelpers.builderProps('ocr'),+ },+ outputSchema: mindeeSchemas.inferenceSchema('ocr'),+ async run({ auth, propsValue }) {+ return productActionHelpers.runWithFile({ apiKey: auth.secret_text, product: 'ocr', props: propsValue });+ },+});++export const ocrDocumentAiAction = createAction({+ auth: mindeeAuth,+ name: 'ocr_document_ai',+ displayName: 'Read Document Text (OCR) (AI)',+ description: 'Reads all the text in a document with one of your Mindee OCR models.',+ classification: 'READ',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Read the full text of a document page by page with a Mindee OCR model. Returns the text and per-page content. Waits up to 4 minutes; if Mindee is still processing it returns completed=false and a job_id for Get Job Status and Get Result. Each run spends Mindee page credits. Get the model ID from List Models (model_type ocr).',+ idempotent: true,+ },+ props: {+ ...productActionHelpers.aiProps('ocr'),+ },+ outputSchema: mindeeSchemas.inferenceSchema('ocr'),+ async run({ auth, propsValue }) {+ return productActionHelpers.runWithUrl({ apiKey: auth.secret_text, product: 'ocr', props: propsValue });+ },+});diff --git a/packages/pieces/community/mindee/src/lib/actions/predict-document.ts b/packages/pieces/community/mindee/src/lib/actions/predict-document.tsindex 1ae9dc572e3..dd5b7e52d80 100644--- a/packages/pieces/community/mindee/src/lib/actions/predict-document.ts+++ b/packages/pieces/community/mindee/src/lib/actions/predict-document.ts@@ -1,85 +1,123 @@import { createAction, Property } from '@activepieces/pieces-framework';import { httpClient, HttpMethod } from '@activepieces/pieces-common';-import { createReadStream } from 'fs';-import FormData from 'form-data';-import { mindeeAuth } from '../..';+import { mindeeAuth } from '../auth';+import { MINDEE_V1_BASE_URL, normalizeApiKey, toMindeeError, verifiedTls } from '../common/client';+import { mindeeFiles, MindeeUpload } from '../common/file';+import { mindeeSchemas } from '../output-schemas';export const mindeePredictDocumentAction = createAction({auth: mindeeAuth,name: 'mindee_predict_document',classification: 'READ',- displayName: 'Extract Document',- description: 'Parse details of a document using OCR.',- audience: 'both',- aiMetadata: { description: 'Runs OCR extraction on a document via Mindee, returning structured fields parsed from it. Choose the document-type model through the API Name option (receipt, invoice, passport, bank account details, proof of address, or financial document), since each extracts a different field set. The document is supplied as a remote URL, local file path, or Base64 string. Read-only analysis with no stored result, so re-running on the same document is idempotent.', idempotent: true },+ displayName: 'Predict Document (Legacy v1)',+ description: 'Legacy: parses a document with an off-the-shelf Mindee v1 API. Needs a v1 API key from platform.mindee.com; use Extract Document for v2 keys.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Legacy Mindee v1 prediction for existing flows: parses a receipt, invoice, passport, bank account details, proof of address or financial document with a v1 API key. Read-only analysis, idempotent.',+ idempotent: true,+ },props: {account_name: Property.ShortText({displayName: 'Account Name',- description:- 'Refers to your username or organization name with which you signed up with.',+ description: 'Keep "mindee" for the off-the-shelf APIs.',required: true,defaultValue: 'mindee',}),api_name: Property.StaticDropdown({displayName: 'API Name',- description: 'Refers to the name of the API your are using.',+ description: 'The Mindee v1 API to use.',required: true,- defaultValue: 'full',+ defaultValue: 'invoices/v4',options: {disabled: false,options: [- {- value: 'bank_account_details/v1',- label: 'Bank Account Details OCR',- },- { value: 'expense_reports/v4', label: 'Receipt OCR' },+ { value: 'invoices/v4', label: 'Invoice OCR (v4)' },+ { value: 'expense_reports/v5', label: 'Receipt OCR (v5)' },+ { value: 'financial_document/v1', label: 'Financial Documents OCR' },{ value: 'passport/v1', label: 'Passport OCR' },- { value: 'invoices/v3', label: 'Invoice OCR' },+ { value: 'bank_account_details/v1', label: 'Bank Account Details OCR' },{ value: 'proof_of_address/v1', label: 'Proof of Address OCR' },- { value: 'financial_document/v1', label: 'Financial Documents OCR' },+ { value: 'invoices/v3', label: 'Invoice OCR (v3, older)' },+ { value: 'expense_reports/v4', label: 'Receipt OCR (v4, older)' },],},}),+ upload: Property.File({+ displayName: 'File',+ description: 'The document to parse. Leave empty to use File URL or Base64 instead.',+ required: false,+ }),file: Property.LongText({- displayName: 'File URL',- description:- 'Remote file URL or Base64 string. We currently support .pdf (slower), .jpg, .png, .webp, .tiff and .heic formats',- required: true,+ displayName: 'File URL or Base64',+ description: 'An http(s) URL or Base64 string, used when File is empty.',+ required: false,}),},- run: async ({ auth, propsValue: { api_name, account_name, file } }) => {- let headers,- body = {};-+ outputSchema: mindeeSchemas.legacyPrediction,+ run: async ({ auth, propsValue }) => {+ const accountName = pathSegment({ value: propsValue.account_name, label: 'Account Name' });+ const apiName = (propsValue.api_name ?? '').trim();+ if (!/^[a-z0-9_-]+\/v\d+$/i.test(apiName)) {+ throw new Error('Pick an API Name such as invoices/v4.');+ }+ const body = await requestBody({ upload: propsValue.upload, file: propsValue.file });try {- const form = new FormData();-- if (['https:', 'http:'].includes(new URL(file).protocol))- form.append('document', await getRemoteFile(file));- else form.append('document', createReadStream(file));-- body = form;- headers = { ...form.getHeaders() };- } catch (_) {- body = { document: file };- headers = { 'Content-Type': 'application/json' };+ const response = await httpClient.sendRequest<unknown>(+ {+ method: HttpMethod.POST,+ url: `${MINDEE_V1_BASE_URL}/products/${accountName}/${apiName}/predict`,+ headers: {+ Authorization: `Token ${normalizeApiKey(auth.secret_text)}`,+ Accept: 'application/json',+ ...(body instanceof FormData ? {} : { 'Content-Type': 'application/json' }),+ },+ body,+ followRedirects: false,+ redactBodyInErrors: true,+ timeout: 120_000,+ },+ { dispatcher: await verifiedTls() },+ );+ return response.body;+ } catch (error) {+ const mapped = toMindeeError({ error, api: 'v1' });+ if (mapped !== undefined) {+ throw mapped;+ }+ throw error;}-- const response = await httpClient.sendRequest({- method: HttpMethod.POST,- url: `https://api.mindee.net/v1/products/${account_name}/${api_name}/predict`,- headers: {- Authorization: `Token ${auth.secret_text}`,- ...headers,- },- body: body,- });-- return response.body;},});-async function getRemoteFile(url: string): Promise<ArrayBuffer> {- const response = await fetch(url);- return await response.arrayBuffer();+async function requestBody({ upload, file }: { upload: unknown; file: string | undefined }): Promise<FormData | { document: string }> {+ if (upload !== undefined && upload !== null && upload !== '') {+ return multipart(mindeeFiles.readFileProp({ value: upload, label: 'File' }));+ }+ const value = (file ?? '').trim();+ if (value.length === 0) {+ throw new Error('Provide a File, or a File URL or Base64 string.');+ }+ if (/^https?:\/\//i.test(value)) {+ return { document: mindeeFiles.parseHttpsUrl({ value, label: 'File URL', allowHttp: true }).toString() };+ }+ const base64 = value.replace(/^data:[^;,]*;base64,/i, '').replace(/\s+/g, '');+ if (base64.length < 16 || !/^[A-Za-z0-9+/]+={0,2}$/.test(base64)) {+ throw new Error('File URL or Base64 must be an http(s) URL or a Base64 string. Local file paths are not supported.');+ }+ return { document: base64 };+}++function multipart(upload: MindeeUpload): FormData {+ const form = new FormData();+ form.append('document', mindeeFiles.toBlob(upload), upload.filename);+ return form;+}++function pathSegment({ value, label }: { value: string | undefined; label: string }): string {+ const trimmed = (value ?? '').trim();+ if (!/^[A-Za-z0-9_.-]+$/.test(trimmed)) {+ throw new Error(`${label} may only contain letters, numbers, dots, dashes and underscores.`);+ }+ return trimmed;}diff --git a/packages/pieces/community/mindee/src/lib/actions/product-action-helpers.ts b/packages/pieces/community/mindee/src/lib/actions/product-action-helpers.tsnew file mode 100644index 00000000000..ff90e46f006--- /dev/null+++ b/packages/pieces/community/mindee/src/lib/actions/product-action-helpers.ts@@ -0,0 +1,68 @@+import { Property } from '@activepieces/pieces-framework';+import { mindeeFiles } from '../common/file';+import { InferenceOptions, mindeeInference, MindeeProduct } from '../common/inference';+import { mindeeProps } from '../common/props';++function builderProps(product: MindeeProduct) {+ return {+ model_id: mindeeProps.modelDropdown({ product }),+ file: Property.File({+ displayName: 'File',+ description: 'The document to process (PDF, JPEG, PNG, WEBP, TIFF or HEIC).',+ required: true,+ }),+ alias: mindeeProps.aliasProp(),+ };+}++function aiProps(product: MindeeProduct) {+ return {+ model_id: Property.ShortText({+ displayName: 'Model ID',+ description: `UUID of a Mindee ${mindeeProps.PRODUCT_LABELS[product]} model, from List Models.`,+ required: true,+ }),+ file_url: Property.ShortText({+ displayName: 'File URL',+ description: 'Public https:// URL of the document. Mindee downloads it directly.',+ required: true,+ }),+ alias: mindeeProps.aliasProp(),+ };+}++async function runWithFile({ apiKey, product, props }: { apiKey: string; product: MindeeProduct; props: Record<string, unknown> }) {+ const output = await mindeeInference.runInference({+ apiKey,+ product,+ modelId: typeof props['model_id'] === 'string' ? props['model_id'] : undefined,+ source: { type: 'upload', upload: mindeeFiles.readFileProp({ value: props['file'], label: 'File' }) },+ options: readOptions(props),+ });+ if (!output.completed) {+ throw new Error(output.message ?? `Mindee is still processing job ${output.job_id}. Use Get Job Status, then Get Result, to collect it later.`);+ }+ return output;+}++function runWithUrl({ apiKey, product, props }: { apiKey: string; product: MindeeProduct; props: Record<string, unknown> }) {+ return mindeeInference.runInference({+ apiKey,+ product,+ modelId: typeof props['model_id'] === 'string' ? props['model_id'] : undefined,+ source: { type: 'url', url: typeof props['file_url'] === 'string' ? props['file_url'] : undefined },+ options: readOptions(props),+ });+}++function readOptions(props: Record<string, unknown>): InferenceOptions {+ return {+ alias: typeof props['alias'] === 'string' ? props['alias'] : undefined,+ rag: props['rag'] === true,+ rawText: props['raw_text'] === true,+ confidence: props['confidence'] === true,+ textContext: typeof props['text_context'] === 'string' ? props['text_context'] : undefined,+ };+}++export const productActionHelpers = { builderProps, aiProps, runWithFile, runWithUrl };diff --git a/packages/pieces/community/mindee/src/lib/actions/rag-documents.ts b/packages/pieces/community/mindee/src/lib/actions/rag-documents.tsnew file mode 100644index 00000000000..bdfe03b8a59--- /dev/null+++ b/packages/pieces/community/mindee/src/lib/actions/rag-documents.ts@@ -0,0 +1,191 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { mindeeAuth } from '../auth';+import { mindeeApi } from '../common/api';+import { mindeeFiles } from '../common/file';+import { mindeeInputs } from '../common/inputs';+import { mindeeProps } from '../common/props';+import { mindeeSchemas } from '../output-schemas';++export const uploadRagDocumentAction = createAction({+ auth: mindeeAuth,+ name: 'upload_rag_document',+ displayName: 'Upload RAG Document',+ description: 'Adds a reference document to an extraction model so it can learn from it (RAG).',+ classification: 'WRITE',+ audience: 'human',+ aiMetadata: {+ description: 'Upload a reference document to a Mindee extraction model for retrieval-augmented extraction. Creates a new RAG document on every run.',+ idempotent: false,+ },+ props: {+ model_id: ragModelDropdown(),+ file: Property.File({ displayName: 'File', description: 'The reference document (PDF or image).', required: true }),+ },+ outputSchema: mindeeSchemas.ragDocument,+ async run({ auth, propsValue }) {+ return mindeeApi.uploadRagDocument({+ apiKey: auth.secret_text,+ modelId: propsValue.model_id,+ upload: mindeeFiles.readFileProp({ value: propsValue.file, label: 'File' }),+ });+ },+});++export const uploadRagDocumentAiAction = createAction({+ auth: mindeeAuth,+ name: 'upload_rag_document_ai',+ displayName: 'Upload RAG Document (AI)',+ description: 'Adds a reference document from a URL to an extraction model so it can learn from it (RAG).',+ classification: 'WRITE',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Upload a reference document (downloaded from a public https:// URL, max 50 MB; private or local addresses are refused) to a Mindee extraction model so runs with rag=true can match it. Needs the extraction model_id from List Models. Not idempotent: each call creates another RAG document; delete extras with Delete RAG Document.',+ idempotent: false,+ },+ props: {+ model_id: Property.ShortText({ displayName: 'Model ID', description: 'UUID of a Mindee extraction model.', required: true }),+ file_url: Property.ShortText({ displayName: 'File URL', description: 'Public https:// URL of the reference document.', required: true }),+ },+ outputSchema: mindeeSchemas.ragDocument,+ async run({ auth, propsValue }) {+ const url = mindeeFiles.parseHttpsUrl({ value: propsValue.file_url, label: 'File URL' });+ const upload = await mindeeFiles.downloadFile({ url, label: 'File URL' });+ return mindeeApi.uploadRagDocument({ apiKey: auth.secret_text, modelId: propsValue.model_id, upload });+ },+});++export const getRagDocumentAction = createAction({+ auth: mindeeAuth,+ name: 'get_rag_document',+ displayName: 'Get RAG Document',+ description: 'Gets a RAG document of an extraction model.',+ classification: 'READ',+ audience: 'both',+ aiMetadata: {+ description: 'Get one Mindee RAG document by ID with its status (Processing, Failed, Draft, Active), match count and field annotation. Read-only, safe to retry.',+ idempotent: true,+ },+ props: {+ document_id: Property.ShortText({ displayName: 'RAG Document ID', required: true }),+ },+ outputSchema: mindeeSchemas.ragDocument,+ async run({ auth, propsValue }) {+ return mindeeApi.getRagDocument({ apiKey: auth.secret_text, documentId: propsValue.document_id });+ },+});++export const updateRagDocumentAction = createAction({+ auth: mindeeAuth,+ name: 'update_rag_document',+ displayName: 'Update RAG Document',+ description: 'Activates or deactivates a RAG document, or replaces its field annotation.',+ classification: 'WRITE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Update a Mindee RAG document: set status to Active (used in matching; Mindee requires at least one annotation field with "selected": true) or Draft (ignored), and/or replace its annotation ({"fields": {"<field>": {"value": ..., "selected": true}}}). Setting the same values again has the same effect, so it is safe to retry.',+ idempotent: true,+ },+ props: {+ document_id: Property.ShortText({ displayName: 'RAG Document ID', required: true }),+ status: Property.StaticDropdown<string, false>({+ displayName: 'Status',+ description: 'Active documents are used for matching; Draft documents are ignored.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Active', value: 'Active' },+ { label: 'Draft', value: 'Draft' },+ ],+ },+ }),+ annotation: Property.Json({+ displayName: 'Annotation',+ description: 'Optional. Replaces the field annotation of the document.',+ required: false,+ }),+ },+ outputSchema: mindeeSchemas.ragDocument,+ async run({ auth, propsValue }) {+ return mindeeApi.updateRagDocument({+ apiKey: auth.secret_text,+ documentId: propsValue.document_id,+ status: propsValue.status === undefined || propsValue.status === null || propsValue.status === '' ? undefined : propsValue.status,+ annotation: readAnnotation(propsValue.annotation),+ });+ },+});++export const deleteRagDocumentAction = createAction({+ auth: mindeeAuth,+ name: 'delete_rag_document',+ displayName: 'Delete RAG Document',+ description: 'Permanently deletes a RAG document from an extraction model.',+ classification: 'DESTRUCTIVE',+ audience: 'both',+ aiMetadata: {+ description: 'Permanently delete a Mindee RAG document by ID. It can not be restored; a second call fails with not found.',+ idempotent: false,+ },+ props: {+ document_id: Property.ShortText({ displayName: 'RAG Document ID', required: true }),+ },+ outputSchema: mindeeSchemas.ragDeleted,+ async run({ auth, propsValue }) {+ return mindeeApi.deleteRagDocument({ apiKey: auth.secret_text, documentId: propsValue.document_id });+ },+});++export const searchRagDocumentsAction = createAction({+ auth: mindeeAuth,+ name: 'search_rag_documents',+ displayName: 'Search RAG Documents',+ description: 'Lists the RAG documents of an extraction model, optionally by file name.',+ classification: 'SEARCH',+ audience: 'both',+ aiMetadata: {+ description: 'List the RAG documents of one Mindee extraction model (model_id required), optionally filtered by file name, with paging. Read-only, safe to retry.',+ idempotent: true,+ },+ props: {+ model_id: ragModelDropdown(),+ filename: Property.ShortText({ displayName: 'File Name Contains', required: false }),+ page: Property.Number({ displayName: 'Page', description: 'Page number, starting at 1.', required: false, defaultValue: 1 }),+ per_page: Property.Number({ displayName: 'Per Page', description: 'Between 1 and 100.', required: false, defaultValue: 50 }),+ },+ outputSchema: mindeeSchemas.ragSearch,+ async run({ auth, propsValue }) {+ return mindeeApi.searchRagDocuments({+ apiKey: auth.secret_text,+ modelId: propsValue.model_id,+ filename: propsValue.filename,+ page: mindeeInputs.positiveInt({ value: propsValue.page, fallback: 1, max: 10_000 }),+ perPage: mindeeInputs.positiveInt({ value: propsValue.per_page, fallback: 50, max: 100 }),+ });+ },+});++function ragModelDropdown() {+ return mindeeProps.modelDropdown({ product: 'extraction', description: 'The extraction model the RAG documents belong to.' });+}++function readAnnotation(value: unknown): Record<string, unknown> | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ const parsed: unknown = typeof value === 'string' ? parseJson(value) : value;+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {+ throw new Error('Annotation must be a JSON object such as {"fields": {...}}.');+ }+ return Object.fromEntries(Object.entries(parsed));+}++function parseJson(value: string): unknown {+ try {+ return JSON.parse(value);+ } catch {+ throw new Error('Annotation is not valid JSON.');+ }+}diff --git a/packages/pieces/community/mindee/src/lib/actions/split-document.ts b/packages/pieces/community/mindee/src/lib/actions/split-document.tsnew file mode 100644index 00000000000..5d51bdf8fbd--- /dev/null+++ b/packages/pieces/community/mindee/src/lib/actions/split-document.ts@@ -0,0 +1,46 @@+import { createAction } from '@activepieces/pieces-framework';+import { mindeeAuth } from '../auth';+import { mindeeSchemas } from '../output-schemas';+import { productActionHelpers } from './product-action-helpers';++export const splitDocumentAction = createAction({+ auth: mindeeAuth,+ name: 'split_document',+ displayName: 'Split Document',+ description: 'Finds where each document starts and ends in a multi-document file with one of your Mindee split models.',+ classification: 'READ',+ audience: 'human',+ aiMetadata: {+ description:+ 'Find the separate documents inside one multi-page file with a Mindee split model. Returns each document type with its 0-based start and end page. Waits up to 4 minutes; if Mindee is still processing, the step fails with the job ID so you can collect it later with Get Job Status and Get Result. Each run spends Mindee page credits.',+ idempotent: true,+ },+ props: {+ ...productActionHelpers.builderProps('split'),+ },+ outputSchema: mindeeSchemas.inferenceSchema('split'),+ async run({ auth, propsValue }) {+ return productActionHelpers.runWithFile({ apiKey: auth.secret_text, product: 'split', props: propsValue });+ },+});++export const splitDocumentAiAction = createAction({+ auth: mindeeAuth,+ name: 'split_document_ai',+ displayName: 'Split Document (AI)',+ description: 'Finds where each document starts and ends in a multi-document file with one of your Mindee split models.',+ classification: 'READ',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Find the separate documents inside one multi-page file with a Mindee split model. Returns each document type with its 0-based start and end page. Waits up to 4 minutes; if Mindee is still processing it returns completed=false and a job_id for Get Job Status and Get Result. Each run spends Mindee page credits. Get the model ID from List Models (model_type split).',+ idempotent: true,+ },+ props: {+ ...productActionHelpers.aiProps('split'),+ },+ outputSchema: mindeeSchemas.inferenceSchema('split'),+ async run({ auth, propsValue }) {+ return productActionHelpers.runWithUrl({ apiKey: auth.secret_text, product: 'split', props: propsValue });+ },+});diff --git a/packages/pieces/community/mindee/src/lib/auth.ts b/packages/pieces/community/mindee/src/lib/auth.tsnew file mode 100644index 00000000000..f6705f18e09--- /dev/null+++ b/packages/pieces/community/mindee/src/lib/auth.ts@@ -0,0 +1,33 @@+import { PieceAuth } from '@activepieces/pieces-framework';+import { detectKeyType, vendorDetail, toMindeeError } from './common/client';++export const mindeeAuth = PieceAuth.SecretText({+ displayName: 'API Key',+ description: `To get your API key:+1. Sign in to the Mindee platform at [app.mindee.com](https://app.mindee.com).+2. Open **API Keys** and create a key.+3. Copy the key and paste it here.++Keys from the legacy platform (platform.mindee.com) only work with the **Predict Document (Legacy v1)** action.`,+ required: true,+ validate: async ({ auth }) => {+ try {+ const keyType = await detectKeyType(auth);+ if (keyType === 'v2') {+ return { valid: true };+ }+ if (keyType === 'v1') {+ return {+ valid: false,+ error:+ 'This is a legacy Mindee v1 API key (platform.mindee.com). The Mindee actions use the v2 API: create an API key at app.mindee.com and paste it here.',+ };+ }+ return { valid: false, error: 'Mindee rejected this API key. Copy it again from app.mindee.com > API Keys.' };+ } catch (error) {+ const mapped = toMindeeError({ error, api: 'v2' });+ const detail = mapped === undefined ? (error instanceof Error ? error.message : String(error)) : vendorDetail(mapped.responseBody) ?? mapped.message;+ return { valid: false, error: `Could not check the API key with Mindee: ${detail}` };+ }+ },+});diff --git a/packages/pieces/community/mindee/src/lib/common/api.ts b/packages/pieces/community/mindee/src/lib/common/api.tsnew file mode 100644index 00000000000..85f8a9b9f86--- /dev/null+++ b/packages/pieces/community/mindee/src/lib/common/api.ts@@ -0,0 +1,195 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { encodeId, isRecord, mindeeV2Request } from './client';+import { mindeeFiles, MindeeUpload } from './file';+import { mindeeInference, MindeeProduct } from './inference';++async function listModels({+ apiKey,+ name,+ modelType,+ page,+ perPage,+}: {+ apiKey: string;+ name?: string;+ modelType?: MindeeProduct;+ page?: number;+ perPage?: number;+}): Promise<ModelsPage> {+ const response = await mindeeV2Request<unknown>({+ apiKey,+ method: HttpMethod.GET,+ path: '/v2/search/models',+ query: { name: name?.trim(), model_type: modelType, page, per_page: perPage },+ });+ const body = isRecord(response.body) ? response.body : {};+ const models = (Array.isArray(body['models']) ? body['models'] : []).filter(isRecord).map((model) => ({+ id: str(model['id']),+ name: str(model['name']),+ model_type: str(model['model_type']),+ webhooks: (Array.isArray(model['webhooks']) ? model['webhooks'] : []).filter(isRecord).map((webhook) => ({+ id: str(webhook['id']),+ name: str(webhook['name']),+ url: str(webhook['url']),+ })),+ }));+ return { models, ...pagination(body['pagination']) };+}++async function listAllModels({ apiKey, modelType }: { apiKey: string; modelType?: MindeeProduct }): Promise<ModelSummary[]> {+ const pages: ModelSummary[][] = [];+ for (let page = 1; page <= MAX_DROPDOWN_PAGES; page++) {+ const result = await listModels({ apiKey, modelType, page, perPage: DROPDOWN_PAGE_SIZE });+ pages.push(result.models);+ if (result.total_pages === null || page >= result.total_pages || result.models.length === 0) {+ break;+ }+ }+ return pages.flat();+}++async function uploadRagDocument({ apiKey, modelId, upload }: { apiKey: string; modelId: string | undefined; upload: MindeeUpload }): Promise<RagDocument> {+ const form = new FormData();+ form.append('model_id', mindeeInference.requireUuid({ value: modelId, label: 'Model' }));+ form.append('file', mindeeFiles.toBlob(upload), upload.filename);+ const response = await mindeeV2Request<unknown>({+ apiKey,+ method: HttpMethod.POST,+ path: '/v2/products/extraction/rag-documents',+ body: form,+ timeoutMs: 120_000,+ });+ return ragDocument(response.body);+}++async function getRagDocument({ apiKey, documentId }: { apiKey: string; documentId: string | undefined }): Promise<RagDocument> {+ const response = await mindeeV2Request<unknown>({+ apiKey,+ method: HttpMethod.GET,+ path: `/v2/products/extraction/rag-documents/${encodeId({ id: documentId, label: 'RAG Document ID' })}`,+ });+ return ragDocument(response.body);+}++async function updateRagDocument({+ apiKey,+ documentId,+ status,+ annotation,+}: {+ apiKey: string;+ documentId: string | undefined;+ status?: string;+ annotation?: Record<string, unknown>;+}): Promise<RagDocument> {+ if (status !== undefined && status !== 'Draft' && status !== 'Active') {+ throw new Error('Status must be Draft or Active.');+ }+ if (status === undefined && annotation === undefined) {+ throw new Error('Set a new status or an annotation to update the RAG document.');+ }+ const response = await mindeeV2Request<unknown>({+ apiKey,+ method: HttpMethod.PATCH,+ path: `/v2/products/extraction/rag-documents/${encodeId({ id: documentId, label: 'RAG Document ID' })}`,+ body: { ...(status === undefined ? {} : { status }), ...(annotation === undefined ? {} : { annotation }) },+ });+ return ragDocument(response.body);+}++async function deleteRagDocument({ apiKey, documentId }: { apiKey: string; documentId: string | undefined }): Promise<{ deleted: boolean; id: string }> {+ const id = encodeId({ id: documentId, label: 'RAG Document ID' });+ await mindeeV2Request<unknown>({ apiKey, method: HttpMethod.DELETE, path: `/v2/products/extraction/rag-documents/${id}` });+ return { deleted: true, id: decodeURIComponent(id) };+}++async function searchRagDocuments({+ apiKey,+ modelId,+ filename,+ page,+ perPage,+}: {+ apiKey: string;+ modelId: string | undefined;+ filename?: string;+ page?: number;+ perPage?: number;+}): Promise<RagSearchPage> {+ const response = await mindeeV2Request<unknown>({+ apiKey,+ method: HttpMethod.GET,+ path: '/v2/search/rag-documents',+ query: { model_id: mindeeInference.requireUuid({ value: modelId, label: 'Model' }), filename: filename?.trim(), page, per_page: perPage },+ });+ const body = isRecord(response.body) ? response.body : {};+ const documents = (Array.isArray(body['rag_documents']) ? body['rag_documents'] : []).filter(isRecord).map(ragSummary);+ return { rag_documents: documents, ...pagination(body['pagination']) };+}++function ragDocument(body: unknown): RagDocument {+ if (!isRecord(body) || typeof body['id'] !== 'string') {+ throw new Error('Mindee returned an unexpected RAG document response.');+ }+ return { ...ragSummary(body), annotation: isRecord(body['annotation']) ? body['annotation'] : null };+}++function ragSummary(body: Record<string, unknown>): RagSummary {+ return {+ id: str(body['id']),+ model_id: str(body['model_id']),+ filename: str(body['filename']),+ status: str(body['status']),+ created_at: str(body['created_at']),+ total_matches: typeof body['total_matches'] === 'number' ? body['total_matches'] : null,+ last_match_at: str(body['last_match_at']),+ };+}++function pagination(value: unknown): Pagination {+ const meta = isRecord(value) ? value : {};+ return {+ page: num(meta['page']),+ per_page: num(meta['per_page']),+ total_items: num(meta['total_items']),+ total_pages: num(meta['total_pages']),+ };+}++function str(value: unknown): string | null {+ return typeof value === 'string' ? value : null;+}++function num(value: unknown): number | null {+ return typeof value === 'number' ? value : null;+}++const DROPDOWN_PAGE_SIZE = 100;+const MAX_DROPDOWN_PAGES = 5;++export const mindeeApi = { listModels, listAllModels, uploadRagDocument, getRagDocument, updateRagDocument, deleteRagDocument, searchRagDocuments };++export type ModelSummary = {+ id: string | null;+ name: string | null;+ model_type: string | null;+ webhooks: { id: string | null; name: string | null; url: string | null }[];+};++type Pagination = { page: number | null; per_page: number | null; total_items: number | null; total_pages: number | null };++export type ModelsPage = { models: ModelSummary[] } & Pagination;++export type RagSummary = {+ id: string | null;+ model_id: string | null;+ filename: string | null;+ status: string | null;+ created_at: string | null;+ total_matches: number | null;+ last_match_at: string | null;+};++export type RagDocument = RagSummary & { annotation: Record<string, unknown> | null };++export type RagSearchPage = { rag_documents: RagSummary[] } & Pagination;diff --git a/packages/pieces/community/mindee/src/lib/common/client.ts b/packages/pieces/community/mindee/src/lib/common/client.tsnew file mode 100644index 00000000000..b7069acf661--- /dev/null+++ b/packages/pieces/community/mindee/src/lib/common/client.ts@@ -0,0 +1,243 @@+import { httpClient, HttpMethod, HttpRequest } from '@activepieces/pieces-common';++export const MINDEE_V2_BASE_URL = 'https://api-v2.mindee.net';+export const MINDEE_V1_BASE_URL = 'https://api.mindee.net/v1';++const V2_HOST = 'api-v2.mindee.net';+const DEFAULT_TIMEOUT_MS = 60_000;+const MAX_DETAIL = 500;++export type MindeeQuery = Record<string, string | number | boolean | undefined | null>;++export class MindeeApiError extends Error {+ readonly status: number;+ readonly responseBody: unknown;++ constructor({ message, status, responseBody }: { message: string; status: number; responseBody: unknown }) {+ super(message);+ this.name = 'MindeeApiError';+ this.status = status;+ this.responseBody = responseBody;+ }+}++export function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}++export function normalizeApiKey(raw: string | undefined): string {+ const trimmed = (raw ?? '').trim().replace(/^(token|bearer)\s+/i, '').trim();+ if (trimmed.length === 0) {+ throw new Error('Enter your Mindee API key.');+ }+ return trimmed;+}++export function encodeId({ id, label }: { id: string | undefined; label: string }): string {+ const trimmed = (id ?? '').trim();+ if (trimmed.length === 0) {+ throw new Error(`${label} is required.`);+ }+ return encodeURIComponent(trimmed);+}++let verifiedTlsAgent: Promise<unknown> | undefined;++export function verifiedTls(): Promise<unknown> {+ verifiedTlsAgent ??= import('undici').then(({ Agent }) => new Agent({ connect: { rejectUnauthorized: true } }));+ return verifiedTlsAgent;+}++export function buildV2Url({ path, query }: { path: string; query?: MindeeQuery }): string {+ if (+ !path.startsWith('/v2/') ||+ path.includes('?') ||+ path.includes('#') ||+ path.split('/').some((segment) => segment === '..' || segment === '.')+ ) {+ throw new Error(`Refusing to call Mindee with an unexpected path: ${path}`);+ }+ const url = new URL(MINDEE_V2_BASE_URL + path);+ for (const [key, value] of Object.entries(query ?? {})) {+ if (value === undefined || value === null || value === '') {+ continue;+ }+ url.searchParams.set(key, String(value));+ }+ return url.toString();+}++export function v2PathFromUrl(raw: string): string {+ let url: URL;+ try {+ url = new URL(raw);+ } catch {+ throw new Error(`Mindee returned an invalid URL: ${raw.slice(0, 200)}`);+ }+ if (url.protocol !== 'https:' || url.host !== V2_HOST || !url.pathname.startsWith('/v2/')) {+ throw new Error(`Mindee returned a URL outside ${V2_HOST}; refusing to send the API key there.`);+ }+ return url.pathname;+}++export async function mindeeV2Request<T>({+ apiKey,+ method,+ path,+ query,+ body,+ timeoutMs = DEFAULT_TIMEOUT_MS,+}: {+ apiKey: string;+ method: HttpMethod;+ path: string;+ query?: MindeeQuery;+ body?: unknown;+ timeoutMs?: number;+}): Promise<{ status: number; body: T }> {+ const request: HttpRequest = {+ method,+ url: buildV2Url({ path, query }),+ headers: {+ Authorization: normalizeApiKey(apiKey),+ Accept: 'application/json',+ },+ body,+ followRedirects: false,+ redactBodyInErrors: true,+ timeout: timeoutMs,+ };+ try {+ const response = await httpClient.sendRequest<T>(request, { dispatcher: await verifiedTls() });+ if (response.status >= 300) {+ throw buildMindeeError({ status: response.status, responseBody: response.body, api: 'v2' });+ }+ return { status: response.status, body: response.body };+ } catch (error) {+ const mapped = toMindeeError({ error, api: 'v2' });+ if (mapped !== undefined) {+ throw mapped;+ }+ if (error instanceof Error) {+ throw new Error(`Could not reach Mindee: ${error.message}`);+ }+ throw error;+ }+}++export function toMindeeError({ error, api }: { error: unknown; api: 'v1' | 'v2' }): MindeeApiError | undefined {+ if (error instanceof MindeeApiError) {+ return error;+ }+ if (!isRecord(error) && !(error instanceof Error)) {+ return undefined;+ }+ const response: unknown = Reflect.get(error, 'response');+ if (!isRecord(response) || typeof response['status'] !== 'number') {+ return undefined;+ }+ return buildMindeeError({ status: response['status'], responseBody: response['body'], api });+}++export function buildMindeeError({ status, responseBody, api }: { status: number; responseBody: unknown; api: 'v1' | 'v2' }): MindeeApiError {+ const detail = vendorDetail(responseBody);+ const suffix = detail === undefined ? '' : ` Mindee said: ${detail}`;+ return new MindeeApiError({ message: `${statusMessage({ status, api })}${suffix}`, status, responseBody });+}++function statusMessage({ status, api }: { status: number; api: 'v1' | 'v2' }): string {+ if (status === 401 || status === 403) {+ return api === 'v2'+ ? 'Mindee rejected the API key for the v2 API. If this is a legacy v1 key from platform.mindee.com, create a new API key at app.mindee.com, or use the "Predict Document (Legacy v1)" action.'+ : 'Mindee rejected the API key for the legacy v1 API. Keys created at app.mindee.com only work with the v2 actions.';+ }+ if (status === 404) {+ return 'Mindee could not find that resource. Check the ID.';+ }+ if (status === 402) {+ return 'Mindee refused the request because of your plan (subscription inactive or no page credits left). Check billing at app.mindee.com.';+ }+ if (status === 422 || status === 400) {+ return 'Mindee rejected the request.';+ }+ if (status === 429) {+ return 'Mindee rate limit or page quota reached. Wait and try again, or check your plan usage.';+ }+ if (status >= 500) {+ return `Mindee had a server error (HTTP ${status}). Try again later.`;+ }+ return `Mindee request failed with HTTP ${status}.`;+}++export function vendorDetail(responseBody: unknown): string | undefined {+ let parsed = responseBody;+ if (typeof parsed === 'string') {+ const trimmed = parsed.trim();+ if (trimmed.length === 0) {+ return undefined;+ }+ try {+ parsed = JSON.parse(trimmed);+ } catch {+ return trimmed.startsWith('<') ? undefined : trimmed.slice(0, MAX_DETAIL);+ }+ }+ if (!isRecord(parsed)) {+ return undefined;+ }+ const apiRequest = parsed['api_request'];+ if (isRecord(apiRequest) && isRecord(apiRequest['error'])) {+ const v1Error = apiRequest['error'];+ const parts = [v1Error['message'], v1Error['details']].filter((part): part is string => typeof part === 'string');+ return parts.length > 0 ? parts.join(': ').slice(0, MAX_DETAIL) : undefined;+ }+ const parts: string[] = [];+ if (typeof parsed['detail'] === 'string') {+ parts.push(parsed['detail']);+ } else if (typeof parsed['title'] === 'string') {+ parts.push(parsed['title']);+ }+ const errors = parsed['errors'];+ if (Array.isArray(errors)) {+ for (const item of errors.filter(isRecord)) {+ const pointer = typeof item['pointer'] === 'string' ? `${item['pointer']}: ` : '';+ if (typeof item['detail'] === 'string') {+ parts.push(`${pointer}${item['detail']}`);+ }+ }+ }+ return parts.length > 0 ? parts.join(' ').slice(0, MAX_DETAIL) : undefined;+}++export async function detectKeyType(apiKey: string): Promise<'v2' | 'v1' | 'invalid'> {+ try {+ await mindeeV2Request({ apiKey, method: HttpMethod.GET, path: '/v2/search/models', query: { per_page: 1 } });+ return 'v2';+ } catch (error) {+ const mapped = toMindeeError({ error, api: 'v2' });+ if (mapped === undefined || (mapped.status !== 401 && mapped.status !== 403)) {+ throw error;+ }+ }+ return (await isV1Key(apiKey)) ? 'v1' : 'invalid';+}++async function isV1Key(apiKey: string): Promise<boolean> {+ try {+ await httpClient.sendRequest(+ {+ method: HttpMethod.GET,+ url: `${MINDEE_V1_BASE_URL}/products/mindee/invoices/v4/documents/queue/00000000-0000-0000-0000-000000000000`,+ headers: { Authorization: `Token ${normalizeApiKey(apiKey)}`, Accept: 'application/json' },+ followRedirects: false,+ redactBodyInErrors: true,+ timeout: 20_000,+ },+ { dispatcher: await verifiedTls() },+ );+ return true;+ } catch (error) {+ const mapped = toMindeeError({ error, api: 'v1' });+ return mapped !== undefined && mapped.status !== 401 && mapped.status !== 403;+ }+}diff --git a/packages/pieces/community/mindee/src/lib/common/file.ts b/packages/pieces/community/mindee/src/lib/common/file.tsnew file mode 100644index 00000000000..89dc4b4967f--- /dev/null+++ b/packages/pieces/community/mindee/src/lib/common/file.ts@@ -0,0 +1,200 @@+import { Readable } from 'node:stream';+import { httpClient, HttpMethod } from '@activepieces/pieces-common';+import { isRecord } from './client';+import { mindeeNetwork } from './network-guard';++function readFileProp({ value, label }: { value: unknown; label: string }): MindeeUpload {+ if (!isRecord(value)) {+ throw new Error(`${label} is required. Pick a file or map one from an earlier step.`);+ }+ const data = value['data'];+ const filename = typeof value['filename'] === 'string' && value['filename'].trim().length > 0 ? value['filename'].trim() : 'document';+ if (Buffer.isBuffer(data)) {+ return checkSize({ data, filename, label });+ }+ const base64 = Reflect.get(value, 'base64');+ if (typeof base64 === 'string' && base64.length > 0) {+ return checkSize({ data: Buffer.from(base64, 'base64'), filename, label });+ }+ throw new Error(`${label} could not be read. Pick a file or map one from an earlier step.`);+}++function parseHttpsUrl({ value, label, allowHttp = false }: { value: string | undefined; label: string; allowHttp?: boolean }): URL {+ const trimmed = (value ?? '').trim();+ if (trimmed.length === 0) {+ throw new Error(`${label} is required.`);+ }+ let url: URL;+ try {+ url = new URL(trimmed);+ } catch {+ throw new Error(`${label} must be a full URL starting with https://.`);+ }+ if (url.protocol !== 'https:' && !(allowHttp && url.protocol === 'http:')) {+ throw new Error(`${label} must start with https://${allowHttp ? ' or http://' : ''}.`);+ }+ if (url.username !== '' || url.password !== '') {+ throw new Error(`${label} must not contain a user name or password.`);+ }+ return url;+}++async function downloadFile({ url, label, timeoutMs = DOWNLOAD_TIMEOUT_MS }: { url: URL; label: string; timeoutMs?: number }): Promise<MindeeUpload> {+ const { response, finalUrl } = await followSafely({ url, label, timeoutMs });+ const declared = Number(response.headers?.['content-length'] ?? '');+ if (Number.isFinite(declared) && declared > MAX_FILE_BYTES) {+ response.body.destroy();+ throw new Error(`${label} is larger than ${MAX_FILE_MB} MB, which Mindee does not accept.`);+ }+ const data = await readCapped({ stream: response.body, label, timeoutMs });+ if (data.length === 0) {+ throw new Error(`${label} returned an empty file.`);+ }+ return { data, filename: filenameFromUrl(finalUrl) };+}++async function followSafely({ url, label, timeoutMs }: { url: URL; label: string; timeoutMs: number }) {+ let current = url;+ for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {+ await assertSafeTarget({ url: current, label });+ const response = await requestDownload({ url: current, label, timeoutMs });+ if (response.status < 300 || response.status >= 400) {+ return { response, finalUrl: current };+ }+ response.body?.destroy();+ const location = headerValue(response.headers?.['location']);+ if (location === undefined) {+ throw new Error(`Could not download ${label}: the server answered HTTP ${response.status} without a redirect location.`);+ }+ try {+ current = new URL(location, current);+ } catch {+ throw new Error(`Could not download ${label}: the server redirected to an invalid URL.`);+ }+ }+ throw new Error(`Could not download ${label}: more than ${MAX_REDIRECTS} redirects.`);+}++async function assertSafeTarget({ url, label }: { url: URL; label: string }): Promise<void> {+ if (url.protocol !== 'https:') {+ throw new Error(`${label} must use https:// (redirects to other schemes are not followed).`);+ }+ if (url.username !== '' || url.password !== '') {+ throw new Error(`${label} must not contain a user name or password.`);+ }+ try {+ await mindeeNetwork.assertPublicHost(url.hostname);+ } catch (error) {+ throw new Error(`Could not download ${label}: ${error instanceof Error ? error.message : String(error)}`);+ }+}++function headerValue(raw: unknown): string | undefined {+ const value = Array.isArray(raw) ? raw[0] : raw;+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;+}++function toBlob(upload: MindeeUpload): Blob {+ return new Blob([new Uint8Array(upload.data)]);+}++async function requestDownload({ url, label, timeoutMs }: { url: URL; label: string; timeoutMs: number }) {+ const dispatcher = await mindeeNetwork.getGuardedDispatcher({ maxResponseBytes: MAX_FILE_BYTES + 1, bodyTimeoutMs: timeoutMs });+ const request = httpClient.sendRequest<Readable>(+ {+ method: HttpMethod.GET,+ url: url.toString(),+ headers: { Accept: '*/*' },+ responseType: 'stream',+ redactBodyInErrors: true,+ followRedirects: false,+ timeout: timeoutMs,+ },+ { dispatcher },+ );+ try {+ return await withDeadline({ promise: request, label, timeoutMs });+ } catch (error) {+ const response: unknown = isRecord(error) || error instanceof Error ? Reflect.get(error, 'response') : undefined;+ if (isRecord(response) && typeof response['status'] === 'number') {+ throw new Error(`Could not download ${label}: the server answered HTTP ${response['status']}.`);+ }+ throw new Error(`Could not download ${label}: ${error instanceof Error ? error.message : String(error)}`);+ }+}++function withDeadline<T>({ promise, label, timeoutMs }: { promise: Promise<T>; label: string; timeoutMs: number }): Promise<T> {+ return new Promise<T>((resolve, reject) => {+ const timer = setTimeout(() => {+ reject(new Error(`Downloading ${label} took longer than ${Math.round(timeoutMs / 1000)} seconds.`));+ }, timeoutMs);+ promise.then(+ (value) => {+ clearTimeout(timer);+ resolve(value);+ },+ (error: unknown) => {+ clearTimeout(timer);+ reject(error);+ },+ );+ });+}++function readCapped({ stream, label, timeoutMs }: { stream: Readable; label: string; timeoutMs: number }): Promise<Buffer> {+ return new Promise((resolve, reject) => {+ const chunks: Buffer[] = [];+ let total = 0;+ const timer = setTimeout(() => {+ stream.destroy(new Error(`Downloading ${label} took longer than ${Math.round(timeoutMs / 1000)} seconds.`));+ }, timeoutMs);+ stream.on('data', (chunk: unknown) => {+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));+ total += buffer.length;+ if (total > MAX_FILE_BYTES) {+ stream.destroy(new Error(`${label} is larger than ${MAX_FILE_MB} MB, which Mindee does not accept.`));+ return;+ }+ chunks.push(buffer);+ });+ stream.on('error', (error) => {+ clearTimeout(timer);+ reject(error);+ });+ stream.on('end', () => {+ clearTimeout(timer);+ resolve(Buffer.concat(chunks));+ });+ });+}++function checkSize({ data, filename, label }: { data: Buffer; filename: string; label: string }): MindeeUpload {+ if (data.length === 0) {+ throw new Error(`${label} is empty.`);+ }+ if (data.length > MAX_FILE_BYTES) {+ throw new Error(`${label} is larger than ${MAX_FILE_MB} MB, which Mindee does not accept.`);+ }+ return { data, filename };+}++function filenameFromUrl(url: URL): string {+ const last = url.pathname.split('/').filter((segment) => segment.length > 0).pop();+ if (last === undefined) {+ return 'document';+ }+ try {+ return decodeURIComponent(last).slice(0, 200);+ } catch {+ return last.slice(0, 200);+ }+}++const MAX_FILE_MB = 50;+const MAX_FILE_BYTES = MAX_FILE_MB * 1024 * 1024;+const DOWNLOAD_TIMEOUT_MS = 60_000;+const MAX_REDIRECTS = 3;++export const mindeeFiles = { readFileProp, parseHttpsUrl, downloadFile, toBlob, MAX_FILE_MB };++export type MindeeUpload = { data: Buffer; filename: string };diff --git a/packages/pieces/community/mindee/src/lib/common/inference.ts b/packages/pieces/community/mindee/src/lib/common/inference.tsnew file mode 100644index 00000000000..a92aeabe0a2--- /dev/null+++ b/packages/pieces/community/mindee/src/lib/common/inference.ts@@ -0,0 +1,432 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { encodeId, isRecord, MindeeApiError, mindeeV2Request, v2PathFromUrl, vendorDetail } from './client';+import { mindeeFiles, MindeeUpload } from './file';++async function runInference({+ apiKey,+ product,+ modelId,+ source,+ options,+ maxWaitMs = MAX_WAIT_MS,+}: {+ apiKey: string;+ product: MindeeProduct;+ modelId: string | undefined;+ source: InferenceSource;+ options: InferenceOptions;+ maxWaitMs?: number;+}): Promise<InferenceOutput> {+ const startedAt = Date.now();+ const job = await enqueue({ apiKey, product, modelId, source, options });+ const finalJob = await waitForJob({ apiKey, job, deadline: startedAt + maxWaitMs });+ if (finalJob.status !== 'Processed') {+ return pendingOutput({ product, job: finalJob, waitedSeconds: Math.round((Date.now() - startedAt) / 1000) });+ }+ return fetchResultForJob({ apiKey, product, job: finalJob });+}++async function enqueue({+ apiKey,+ product,+ modelId,+ source,+ options,+}: {+ apiKey: string;+ product: MindeeProduct;+ modelId: string | undefined;+ source: InferenceSource;+ options: InferenceOptions;+}): Promise<MindeeJob> {+ const form = new FormData();+ form.append('model_id', requireUuid({ value: modelId, label: 'Model' }));+ if (source.type === 'url') {+ form.append('url', mindeeFiles.parseHttpsUrl({ value: source.url, label: 'File URL' }).toString());+ } else {+ form.append('file', mindeeFiles.toBlob(source.upload), source.upload.filename);+ }+ const fields = enqueueFields({ product, options });+ for (const [key, value] of fields) {+ form.append(key, value);+ }+ const response = await mindeeV2Request<unknown>({+ apiKey,+ method: HttpMethod.POST,+ path: `/v2/products/${product}/enqueue`,+ body: form,+ timeoutMs: ENQUEUE_TIMEOUT_MS,+ });+ return parseJob(response.body);+}++async function getJob({ apiKey, jobId }: { apiKey: string; jobId: string | undefined }): Promise<MindeeJob> {+ const response = await mindeeV2Request<unknown>({+ apiKey,+ method: HttpMethod.GET,+ path: `/v2/jobs/${encodeId({ id: jobId, label: 'Job ID' })}`,+ query: { redirect: false },+ });+ return parseJob(response.body);+}++async function getResult({+ apiKey,+ product,+ inferenceId,+}: {+ apiKey: string;+ product: MindeeProduct;+ inferenceId: string | undefined;+}): Promise<InferenceOutput> {+ const response = await mindeeV2Request<unknown>({+ apiKey,+ method: HttpMethod.GET,+ path: `/v2/products/${product}/results/${encodeId({ id: inferenceId, label: 'Inference ID' })}`,+ });+ return normalizeInference({ product, body: response.body, job: null });+}++async function waitForJob({ apiKey, job, deadline }: { apiKey: string; job: MindeeJob; deadline: number }): Promise<MindeeJob> {+ let current = job;+ let attempt = 0;+ while (current.status === 'Processing') {+ const delay = pollDelay(attempt);+ if (Date.now() + delay > deadline) {+ return current;+ }+ await sleep(delay);+ attempt += 1;+ try {+ current = await getJob({ apiKey, jobId: current.id });+ } catch (error) {+ if (error instanceof MindeeApiError && error.status === 429) {+ continue;+ }+ throw error;+ }+ }+ if (current.status === 'Failed') {+ const detail = vendorDetail(current.error) ?? 'no reason given';+ throw new Error(`Mindee could not process the document (job ${current.id}): ${detail}`);+ }+ return current;+}++async function fetchResultForJob({ apiKey, product, job }: { apiKey: string; product: MindeeProduct; job: MindeeJob }): Promise<InferenceOutput> {+ const path = job.result_url !== null ? v2PathFromUrl(job.result_url) : null;+ if (path === null) {+ throw new Error(`Mindee marked job ${job.id} as processed but did not return a result URL. Use Get Job Status to check it again.`);+ }+ const response = await mindeeV2Request<unknown>({ apiKey, method: HttpMethod.GET, path });+ return normalizeInference({ product, body: response.body, job });+}++function enqueueFields({ product, options }: { product: MindeeProduct; options: InferenceOptions }): Array<[string, string]> {+ const fields: Array<[string, string]> = [];+ const alias = options.alias?.trim();+ if (alias !== undefined && alias.length > 0) {+ fields.push(['alias', alias]);+ }+ if (product !== 'extraction') {+ return fields;+ }+ if (options.rag === true) {+ fields.push(['rag', 'true']);+ }+ if (options.rawText === true) {+ fields.push(['raw_text', 'true']);+ }+ if (options.confidence === true) {+ fields.push(['confidence', 'true']);+ }+ const context = options.textContext?.trim();+ if (context !== undefined && context.length > 0) {+ fields.push(['text_context', context]);+ }+ return fields;+}++function parseJob(body: unknown): MindeeJob {+ const job = isRecord(body) && isRecord(body['job']) ? body['job'] : undefined;+ if (job === undefined || typeof job['id'] !== 'string') {+ throw new Error('Mindee returned an unexpected job response.');+ }+ const status = job['status'];+ return {+ id: job['id'],+ status: status === 'Processed' || status === 'Failed' ? status : 'Processing',+ model_id: str(job['model_id']),+ filename: str(job['filename']),+ alias: str(job['alias']),+ created_at: str(job['created_at']),+ completed_at: str(job['completed_at']),+ polling_url: str(job['polling_url']),+ result_url: str(job['result_url']),+ error: isRecord(job['error']) ? job['error'] : null,+ };+}++function jobSummary(job: MindeeJob): JobSummary {+ const resultPath = job.result_url === null ? null : safeResultPath(job.result_url);+ const match = resultPath === null ? null : RESULT_PATH.exec(resultPath);+ return {+ job_id: job.id,+ status: job.status,+ completed: job.status !== 'Processing',+ model_id: job.model_id,+ filename: job.filename,+ alias: job.alias,+ created_at: job.created_at,+ completed_at: job.completed_at,+ product: match === null ? null : match[1],+ inference_id: match === null ? null : decodeURIComponent(match[2]),+ error: job.error === null ? null : vendorDetail(job.error) ?? 'Processing failed.',+ };+}++function safeResultPath(url: string): string | null {+ try {+ return v2PathFromUrl(url);+ } catch {+ return null;+ }+}++function pendingOutput({ product, job, waitedSeconds }: { product: MindeeProduct; job: MindeeJob; waitedSeconds: number }): InferenceOutput {+ return {+ completed: false,+ status: job.status,+ message: `Mindee is still processing the document after ${waitedSeconds} seconds. Use Get Job Status with job ID ${job.id}, then Get Result, to collect it later.`,+ product,+ job_id: job.id,+ inference_id: null,+ model_id: job.model_id,+ alias: job.alias,+ file: { name: job.filename, page_count: null, mime_type: null },+ ...emptyProductFields(product),+ };+}++function normalizeInference({ product, body, job }: { product: MindeeProduct; body: unknown; job: MindeeJob | null }): InferenceOutput {+ const inference = isRecord(body) && isRecord(body['inference']) ? body['inference'] : undefined;+ if (inference === undefined) {+ throw new Error('Mindee returned an unexpected result response.');+ }+ const file = isRecord(inference['file']) ? inference['file'] : {};+ const model = isRecord(inference['model']) ? inference['model'] : {};+ const inferenceJob = isRecord(inference['job']) ? inference['job'] : {};+ const result = isRecord(inference['result']) ? inference['result'] : {};+ return {+ completed: true,+ status: 'Processed',+ message: null,+ product,+ job_id: job?.id ?? str(inferenceJob['id']),+ inference_id: str(inference['id']),+ model_id: str(model['id']) ?? job?.model_id ?? null,+ alias: str(file['alias']) ?? job?.alias ?? null,+ file: {+ name: str(file['name']) ?? job?.filename ?? null,+ page_count: typeof file['page_count'] === 'number' ? file['page_count'] : null,+ mime_type: str(file['mime_type']),+ },+ ...productFields({ product, result }),+ };+}++function productFields({ product, result }: { product: MindeeProduct; result: Record<string, unknown> }): ProductFields {+ switch (product) {+ case 'extraction':+ return extractionFields(result);+ case 'classification': {+ const classification = isRecord(result['classification']) ? result['classification'] : {};+ return { document_type: str(classification['document_type']), fields: nestedExtraction(classification['extraction_response']) };+ }+ case 'crop':+ return {+ crops: arrayOfRecords(result['crops']).map((crop) => {+ const location = isRecord(crop['location']) ? crop['location'] : {};+ return {+ object_type: str(crop['object_type']),+ page: typeof location['page'] === 'number' ? location['page'] : null,+ polygon: Array.isArray(location['polygon']) ? location['polygon'] : [],+ fields: nestedExtraction(crop['extraction_response']),+ };+ }),+ };+ case 'ocr': {+ const pages = arrayOfRecords(result['pages']).map((page, index) => ({+ page: index,+ content: str(page['content']) ?? '',+ word_count: Array.isArray(page['words']) ? page['words'].length : 0,+ }));+ return { text: pages.map((page) => page.content).join('\n\n'), pages };+ }+ case 'split':+ return {+ splits: arrayOfRecords(result['splits']).map((split) => {+ const range = Array.isArray(split['page_range']) ? split['page_range'] : [];+ const start = typeof range[0] === 'number' ? range[0] : null;+ const end = typeof range[1] === 'number' ? range[1] : null;+ return {+ document_type: str(split['document_type']),+ start_page: start,+ end_page: end,+ page_count: start !== null && end !== null ? end - start + 1 : null,+ fields: nestedExtraction(split['extraction_response']),+ };+ }),+ };+ }+}++function extractionFields(result: Record<string, unknown>): ProductFields {+ const rawFields = isRecord(result['fields']) ? result['fields'] : {};+ const rawText = isRecord(result['raw_text']) ? arrayOfRecords(result['raw_text']['pages']) : null;+ const rag = isRecord(result['rag']) ? result['rag'] : null;+ return {+ fields: simplifyFields(rawFields),+ field_confidence: confidenceMap(rawFields),+ raw_text: rawText === null ? null : rawText.map((page) => str(page['content']) ?? '').join('\n\n'),+ rag_document_id: rag === null ? null : str(rag['retrieved_document_id']),+ };+}++function nestedExtraction(value: unknown): Record<string, unknown> {+ if (!isRecord(value) || !isRecord(value['inference'])) {+ return {};+ }+ const result = value['inference']['result'];+ return isRecord(result) && isRecord(result['fields']) ? simplifyFields(result['fields']) : {};+}++function simplifyFields(fields: Record<string, unknown>): Record<string, unknown> {+ return Object.fromEntries(Object.entries(fields).map(([name, field]) => [name, simplifyField(field)]));+}++function simplifyField(field: unknown): unknown {+ if (!isRecord(field)) {+ return field ?? null;+ }+ if ('value' in field) {+ return field['value'] ?? null;+ }+ if (isRecord(field['fields'])) {+ return simplifyFields(field['fields']);+ }+ if (Array.isArray(field['items'])) {+ return field['items'].map(simplifyField);+ }+ return null;+}++function confidenceMap(fields: Record<string, unknown>): Record<string, string | null> {+ return Object.fromEntries(+ Object.entries(fields).map(([name, field]) => [name, isRecord(field) && typeof field['confidence'] === 'string' ? field['confidence'] : null]),+ );+}++function emptyProductFields(product: MindeeProduct): ProductFields {+ switch (product) {+ case 'extraction':+ return { fields: {}, field_confidence: {}, raw_text: null, rag_document_id: null };+ case 'classification':+ return { document_type: null, fields: {} };+ case 'crop':+ return { crops: [] };+ case 'ocr':+ return { text: null, pages: [] };+ case 'split':+ return { splits: [] };+ }+}++function requireUuid({ value, label }: { value: string | undefined; label: string }): string {+ const trimmed = (value ?? '').trim();+ if (!UUID.test(trimmed)) {+ throw new Error(`${label} must be a Mindee model ID (a UUID such as 4f3d1c2e-...). Use List Models to find it.`);+ }+ return trimmed;+}++function arrayOfRecords(value: unknown): Record<string, unknown>[] {+ return Array.isArray(value) ? value.filter(isRecord) : [];+}++function str(value: unknown): string | null {+ return typeof value === 'string' ? value : null;+}++function pollDelay(attempt: number): number {+ return attempt === 0 ? FIRST_POLL_MS : Math.min(Math.round(POLL_MS * 1.25 ** attempt), MAX_POLL_MS);+}++function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+const RESULT_PATH = /^\/v2\/products\/(extraction|classification|crop|ocr|split)\/results\/([^/]+)$/;+const MAX_WAIT_MS = 240_000;+const ENQUEUE_TIMEOUT_MS = 120_000;+const FIRST_POLL_MS = 2_000;+const POLL_MS = 1_500;+const MAX_POLL_MS = 6_000;++export const MINDEE_PRODUCTS: MindeeProduct[] = ['extraction', 'classification', 'crop', 'ocr', 'split'];++export const mindeeInference = { runInference, getJob, getResult, jobSummary, normalizeInference, simplifyFields, requireUuid, pollDelay };++export type MindeeProduct = 'extraction' | 'classification' | 'crop' | 'ocr' | 'split';++export type InferenceSource = { type: 'url'; url: string | undefined } | { type: 'upload'; upload: MindeeUpload };++export type InferenceOptions = {+ alias?: string;+ rag?: boolean;+ rawText?: boolean;+ confidence?: boolean;+ textContext?: string;+};++export type MindeeJob = {+ id: string;+ status: 'Processing' | 'Processed' | 'Failed';+ model_id: string | null;+ filename: string | null;+ alias: string | null;+ created_at: string | null;+ completed_at: string | null;+ polling_url: string | null;+ result_url: string | null;+ error: Record<string, unknown> | null;+};++export type JobSummary = {+ job_id: string;+ status: MindeeJob['status'];+ completed: boolean;+ model_id: string | null;+ filename: string | null;+ alias: string | null;+ created_at: string | null;+ completed_at: string | null;+ product: string | null;+ inference_id: string | null;+ error: string | null;+};++type ProductFields = Record<string, unknown>;++export type InferenceOutput = {+ completed: boolean;+ status: MindeeJob['status'];+ message: string | null;+ product: MindeeProduct;+ job_id: string | null;+ inference_id: string | null;+ model_id: string | null;+ alias: string | null;+ file: { name: string | null; page_count: number | null; mime_type: string | null };+} & ProductFields;diff --git a/packages/pieces/community/mindee/src/lib/common/inputs.ts b/packages/pieces/community/mindee/src/lib/common/inputs.tsnew file mode 100644index 00000000000..f6e1b266085--- /dev/null+++ b/packages/pieces/community/mindee/src/lib/common/inputs.ts@@ -0,0 +1,8 @@+function positiveInt({ value, fallback, max }: { value: number | undefined | null; fallback: number; max: number }): number {+ if (value === undefined || value === null || !Number.isFinite(value)) {+ return fallback;+ }+ return Math.min(Math.max(Math.trunc(value), 1), max);+}++export const mindeeInputs = { positiveInt };diff --git a/packages/pieces/community/mindee/src/lib/common/network-guard.ts b/packages/pieces/community/mindee/src/lib/common/network-guard.tsnew file mode 100644index 00000000000..e4e39db56c7--- /dev/null+++ b/packages/pieces/community/mindee/src/lib/common/network-guard.ts@@ -0,0 +1,172 @@+import { isIP } from 'node:net';+import { lookup as dnsLookup, LookupAddress, LookupOptions } from 'node:dns';++function parseIpv4(ip: string): number[] | undefined {+ const match = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(ip);+ if (match === null) {+ return undefined;+ }+ const octets = match.slice(1).map(Number);+ return octets.every((octet) => octet <= 255) ? octets : undefined;+}++function isBlockedIpv4(octets: number[]): boolean {+ const [a, b, c] = octets;+ return (+ a === 0 ||+ a === 10 ||+ a === 127 ||+ (a === 100 && b >= 64 && b <= 127) ||+ (a === 169 && b === 254) ||+ (a === 172 && b >= 16 && b <= 31) ||+ (a === 192 && b === 0 && (c === 0 || c === 2)) ||+ (a === 192 && b === 168) ||+ (a === 198 && (b === 18 || b === 19)) ||+ (a === 198 && b === 51 && c === 100) ||+ (a === 203 && b === 0 && c === 113) ||+ a >= 224+ );+}++function expandIpv6(ip: string): number[] | undefined {+ let text = ip.toLowerCase().split('%')[0];+ const tailV4 = /(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec(text);+ if (tailV4 !== null) {+ const octets = parseIpv4(tailV4[1]);+ if (octets === undefined) {+ return undefined;+ }+ const high = ((octets[0] << 8) | octets[1]).toString(16);+ const low = ((octets[2] << 8) | octets[3]).toString(16);+ text = `${text.slice(0, -tailV4[1].length)}${high}:${low}`;+ }+ const halves = text.split('::');+ if (halves.length > 2) {+ return undefined;+ }+ const head = halves[0] === '' ? [] : halves[0].split(':');+ const tail = halves.length === 2 && halves[1] !== '' ? halves[1].split(':') : [];+ const missing = 8 - head.length - tail.length;+ if ((halves.length === 1 && missing !== 0) || missing < 0) {+ return undefined;+ }+ const groups = [...head, ...Array<string>(halves.length === 2 ? missing : 0).fill('0'), ...tail];+ if (groups.length !== 8 || groups.some((group) => !/^[0-9a-f]{1,4}$/.test(group))) {+ return undefined;+ }+ return groups.map((group) => parseInt(group, 16));+}++function embeddedIpv4(groups: number[]): number[] {+ return [groups[6] >> 8, groups[6] & 0xff, groups[7] >> 8, groups[7] & 0xff];+}++function isBlockedIpv6(groups: number[]): boolean {+ const firstSixZero = groups.slice(0, 6).every((group) => group === 0);+ if (firstSixZero) {+ return true;+ }+ const mapped = groups.slice(0, 5).every((group) => group === 0) && groups[5] === 0xffff;+ if (mapped) {+ return isBlockedIpv4(embeddedIpv4(groups));+ }+ if (groups[0] === 0x64 && groups[1] === 0xff9b) {+ return true;+ }+ if (groups[0] === 0x2002) {+ return isBlockedIpv4([groups[1] >> 8, groups[1] & 0xff, groups[2] >> 8, groups[2] & 0xff]);+ }+ return (+ (groups[0] & 0xfe00) === 0xfc00 ||+ (groups[0] & 0xffc0) === 0xfe80 ||+ (groups[0] & 0xffc0) === 0xfec0 ||+ (groups[0] & 0xff00) === 0xff00 ||+ (groups[0] === 0x2001 && groups[1] === 0x0db8) ||+ (groups[0] === 0x2001 && groups[1] === 0)+ );+}++function isBlockedIp(ip: string): boolean {+ const version = isIP(ip.split('%')[0]);+ if (version === 4) {+ const octets = parseIpv4(ip);+ return octets === undefined || isBlockedIpv4(octets);+ }+ if (version === 6) {+ const groups = expandIpv6(ip);+ return groups === undefined || isBlockedIpv6(groups);+ }+ return true;+}++export class BlockedAddressError extends Error {+ constructor(hostname: string) {+ super(`The URL host "${hostname}" is a local or private network address, which is not allowed.`);+ this.name = 'BlockedAddressError';+ }+}++type LookupCallback = (error: NodeJS.ErrnoException | null, address: string | LookupAddress[], family?: number) => void;+type LookupArgs = [hostname: string, options: LookupOptions, callback: LookupCallback];++function guardedLookup(...args: LookupArgs): void {+ const [hostname, options, callback] = args;+ dnsLookup(hostname, { ...options, all: true }, (error, addresses) => {+ if (error) {+ callback(error, []);+ return;+ }+ const list: LookupAddress[] = Array.isArray(addresses) ? addresses : [];+ if (list.length === 0 || list.some((entry) => isBlockedIp(entry.address))) {+ callback(Object.assign(new BlockedAddressError(hostname), { code: 'EBLOCKEDADDRESS' }), []);+ return;+ }+ if (options.all === true) {+ callback(null, list);+ return;+ }+ callback(null, list[0].address, list[0].family);+ });+}++function isBlockedHostname(hostname: string): boolean {+ const host = hostname.toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, '');+ if (isIP(host) !== 0) {+ return isBlockedIp(host);+ }+ return (+ host === '' ||+ host === 'localhost' ||+ host.endsWith('.localhost') ||+ host.endsWith('.internal') ||+ host.endsWith('.local') ||+ !host.includes('.')+ );+}++async function assertPublicHost(hostname: string): Promise<void> {+ if (isBlockedHostname(hostname)) {+ throw new BlockedAddressError(hostname);+ }+ const host = hostname.replace(/^\[|\]$/g, '');+ if (isIP(host) !== 0) {+ return;+ }+ await new Promise<void>((resolve, reject) => {+ guardedLookup(host, { all: true }, (error) => (error ? reject(error) : resolve()));+ });+}++let guardedDispatcher: Promise<unknown> | undefined;++function getGuardedDispatcher({ maxResponseBytes, bodyTimeoutMs }: { maxResponseBytes: number; bodyTimeoutMs: number }): Promise<unknown> {+ guardedDispatcher ??= import('undici').then(({ Agent }) => new Agent({+ connect: { rejectUnauthorized: true, lookup: guardedLookup },+ maxResponseSize: maxResponseBytes,+ bodyTimeout: bodyTimeoutMs,+ headersTimeout: bodyTimeoutMs,+ }));+ return guardedDispatcher;+}++export const mindeeNetwork = { isBlockedIp, isBlockedHostname, guardedLookup, assertPublicHost, getGuardedDispatcher };diff --git a/packages/pieces/community/mindee/src/lib/common/props.ts b/packages/pieces/community/mindee/src/lib/common/props.tsnew file mode 100644index 00000000000..b4bf526cd7b--- /dev/null+++ b/packages/pieces/community/mindee/src/lib/common/props.ts@@ -0,0 +1,106 @@+import { Property } from '@activepieces/pieces-framework';+import { mindeeAuth } from '../auth';+import { mindeeApi } from './api';+import { MindeeProduct } from './inference';++function modelDropdown({ product, displayName, description }: { product: MindeeProduct; displayName?: string; description?: string }) {+ return Property.Dropdown({+ auth: mindeeAuth,+ displayName: displayName ?? 'Model',+ description: description ?? `Your Mindee ${PRODUCT_LABELS[product]} model. Models are created at app.mindee.com.`,+ required: true,+ refreshers: [],+ options: async ({ auth }) => {+ if (!auth) {+ return { disabled: true, options: [], placeholder: 'Connect your Mindee account first.' };+ }+ try {+ const models = await mindeeApi.listAllModels({ apiKey: auth.secret_text, modelType: product });+ if (models.length === 0) {+ return {+ disabled: true,+ options: [],+ placeholder: `No ${PRODUCT_LABELS[product]} models found. Create one at app.mindee.com first.`,+ };+ }+ return {+ disabled: false,+ options: models.flatMap((model) => (model.id === null ? [] : [{ label: model.name ?? model.id, value: model.id }])),+ };+ } catch (error) {+ return {+ disabled: true,+ options: [],+ placeholder: error instanceof Error ? error.message.slice(0, 200) : 'Could not load models from Mindee.',+ };+ }+ },+ });+}++function aliasProp() {+ return Property.ShortText({+ displayName: 'Alias',+ description: 'Optional tag of your own (for example an internal document ID). Mindee returns it with the job and result.',+ required: false,+ });+}++function extractionOptionProps() {+ return {+ rag: Property.Checkbox({+ displayName: 'Use RAG',+ description: 'Use the RAG documents uploaded for this model to improve accuracy.',+ required: false,+ defaultValue: false,+ }),+ raw_text: Property.Checkbox({+ displayName: 'Include Raw Text',+ description: 'Also return the full text of the document.',+ required: false,+ defaultValue: false,+ }),+ confidence: Property.Checkbox({+ displayName: 'Include Confidence',+ description: 'Return a confidence level (Certain, High or Medium) for each top-level field.',+ required: false,+ defaultValue: false,+ }),+ text_context: Property.LongText({+ displayName: 'Text Context',+ description: 'Optional hint for the model for this document, for example "This is a grocery receipt."',+ required: false,+ }),+ };+}++function productProp() {+ return Property.StaticDropdown<MindeeProduct, true>({+ displayName: 'Product',+ description: 'The Mindee product that ran the inference.',+ required: true,+ defaultValue: 'extraction',+ options: {+ disabled: false,+ options: PRODUCT_OPTIONS,+ },+ });+}++const PRODUCT_LABELS: Record<MindeeProduct, string> = {+ extraction: 'Extraction',+ classification: 'Classification',+ crop: 'Crop',+ ocr: 'OCR',+ split: 'Split',+};++const PRODUCT_OPTIONS: { label: string; value: MindeeProduct }[] = [+ { label: 'Extraction', value: 'extraction' },+ { label: 'Classification', value: 'classification' },+ { label: 'Crop', value: 'crop' },+ { label: 'OCR', value: 'ocr' },+ { label: 'Split', value: 'split' },+];++export const mindeeProps = { modelDropdown, aliasProp, extractionOptionProps, productProp, PRODUCT_LABELS, PRODUCT_OPTIONS };diff --git a/packages/pieces/community/mindee/src/lib/output-schemas.ts b/packages/pieces/community/mindee/src/lib/output-schemas.tsnew file mode 100644index 00000000000..015d339bee8--- /dev/null+++ b/packages/pieces/community/mindee/src/lib/output-schemas.ts@@ -0,0 +1,206 @@+import { OutputSchema, OutputSchemaField } from '@activepieces/pieces-framework';+import { MindeeProduct } from './common/inference';++const envelopeFields: OutputSchemaField[] = [+ { key: 'completed', label: 'Completed', format: 'boolean', description: 'False when Mindee was still processing at the wait limit; use the job ID to collect it later.' },+ { key: 'status', label: 'Status', description: 'Processed, Processing or Failed.' },+ { key: 'message', label: 'Message' },+ { key: 'product', label: 'Product' },+ { key: 'job_id', label: 'Job ID' },+ { key: 'inference_id', label: 'Inference ID' },+ { key: 'model_id', label: 'Model ID' },+ { key: 'alias', label: 'Alias' },+ {+ key: 'file',+ label: 'File',+ children: [+ { key: 'name', label: 'File Name' },+ { key: 'page_count', label: 'Page Count', format: 'number' },+ { key: 'mime_type', label: 'MIME Type' },+ ],+ },+];++const extractedFields: OutputSchemaField = {+ key: 'fields',+ label: 'Extracted Fields',+ dynamicKey: true,+ description: 'Values keyed by the field names in your model data schema.',+};++const productSchemaFields: Record<MindeeProduct, OutputSchemaField[]> = {+ extraction: [+ extractedFields,+ { key: 'field_confidence', label: 'Field Confidence', dynamicKey: true, description: 'Confidence per top-level field when Include Confidence is on.' },+ { key: 'raw_text', label: 'Raw Text' },+ { key: 'rag_document_id', label: 'Matched RAG Document ID' },+ ],+ classification: [{ key: 'document_type', label: 'Document Type' }, extractedFields],+ crop: [+ {+ key: 'crops',+ label: 'Crops',+ labelKey: 'object_type',+ listItems: [+ { key: 'object_type', label: 'Object Type' },+ { key: 'page', label: 'Page Index', format: 'number' },+ { key: 'polygon', label: 'Polygon' },+ extractedFields,+ ],+ },+ ],+ ocr: [+ { key: 'text', label: 'Full Text' },+ {+ key: 'pages',+ label: 'Pages',+ listItems: [+ { key: 'page', label: 'Page Index', format: 'number' },+ { key: 'content', label: 'Content' },+ { key: 'word_count', label: 'Word Count', format: 'number' },+ ],+ },+ ],+ split: [+ {+ key: 'splits',+ label: 'Documents',+ labelKey: 'document_type',+ listItems: [+ { key: 'document_type', label: 'Document Type' },+ { key: 'start_page', label: 'Start Page Index', format: 'number' },+ { key: 'end_page', label: 'End Page Index', format: 'number' },+ { key: 'page_count', label: 'Page Count', format: 'number' },+ extractedFields,+ ],+ },+ ],+};++function inferenceSchema(product: MindeeProduct): OutputSchema {+ return { fields: [...envelopeFields, ...productSchemaFields[product]] };+}++const anyResult: OutputSchema = {+ fields: [+ ...envelopeFields,+ extractedFields,+ { key: 'field_confidence', label: 'Field Confidence', dynamicKey: true },+ { key: 'raw_text', label: 'Raw Text (Extraction)' },+ { key: 'rag_document_id', label: 'Matched RAG Document ID (Extraction)' },+ { key: 'document_type', label: 'Document Type (Classification)' },+ ...productSchemaFields.crop,+ ...productSchemaFields.ocr,+ ...productSchemaFields.split,+ ],+};++const jobStatus: OutputSchema = {+ fields: [+ { key: 'job_id', label: 'Job ID' },+ { key: 'status', label: 'Status', description: 'Processing, Processed or Failed.' },+ { key: 'completed', label: 'Completed', format: 'boolean' },+ { key: 'product', label: 'Product' },+ { key: 'inference_id', label: 'Inference ID', description: 'Set once processed; use it with Get Result.' },+ { key: 'model_id', label: 'Model ID' },+ { key: 'filename', label: 'File Name' },+ { key: 'alias', label: 'Alias' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'completed_at', label: 'Completed At', format: 'datetime' },+ { key: 'error', label: 'Error' },+ ],+};++const paginationFields: OutputSchemaField[] = [+ { key: 'page', label: 'Page', format: 'number' },+ { key: 'per_page', label: 'Per Page', format: 'number' },+ { key: 'total_items', label: 'Total Items', format: 'number' },+ { key: 'total_pages', label: 'Total Pages', format: 'number' },+];++const models: OutputSchema = {+ fields: [+ {+ key: 'models',+ label: 'Models',+ labelKey: 'name',+ listItems: [+ { key: 'id', label: 'Model ID' },+ { key: 'name', label: 'Name' },+ { key: 'model_type', label: 'Model Type' },+ {+ key: 'webhooks',+ label: 'Webhooks',+ labelKey: 'name',+ listItems: [+ { key: 'id', label: 'Webhook ID' },+ { key: 'name', label: 'Name' },+ { key: 'url', label: 'URL', format: 'url' },+ ],+ },+ ],+ },+ ...paginationFields,+ ],+};++const ragSummaryFields: OutputSchemaField[] = [+ { key: 'id', label: 'RAG Document ID' },+ { key: 'model_id', label: 'Model ID' },+ { key: 'filename', label: 'File Name' },+ { key: 'status', label: 'Status', description: 'Processing, Failed, Draft or Active.' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'total_matches', label: 'Times Matched', format: 'number' },+ { key: 'last_match_at', label: 'Last Matched At', format: 'datetime' },+];++const ragDocument: OutputSchema = {+ fields: [+ ...ragSummaryFields,+ {+ key: 'annotation',+ label: 'Annotation',+ children: [{ key: 'fields', label: 'Annotated Fields', dynamicKey: true }],+ },+ ],+};++const ragSearch: OutputSchema = {+ fields: [{ key: 'rag_documents', label: 'RAG Documents', labelKey: 'filename', listItems: ragSummaryFields }, ...paginationFields],+};++const ragDeleted: OutputSchema = {+ fields: [+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ { key: 'id', label: 'RAG Document ID' },+ ],+};++const legacyPrediction: OutputSchema = {+ fields: [+ { key: 'document_id', label: 'Document ID', value: 'document.id' },+ { key: 'document_name', label: 'File Name', value: 'document.name' },+ { key: 'n_pages', label: 'Page Count', value: 'document.n_pages', format: 'number' },+ { key: 'product_name', label: 'Product', value: 'document.inference.product.name' },+ { key: 'product_version', label: 'Product Version', value: 'document.inference.product.version' },+ {+ key: 'prediction',+ label: 'Prediction',+ value: 'document.inference.prediction',+ dynamicKey: true,+ description: 'Document-level fields; each holds value, confidence and more, depending on the API.',+ },+ {+ key: 'pages',+ label: 'Page Predictions',+ value: 'document.inference.pages',+ listItems: [+ { key: 'id', label: 'Page Index', format: 'number' },+ { key: 'prediction', label: 'Prediction', dynamicKey: true },+ ],+ },+ { key: 'request_status', label: 'Request Status', value: 'api_request.status' },+ ],+};++export const mindeeSchemas = { inferenceSchema, anyResult, jobStatus, models, ragDocument, ragSearch, ragDeleted, legacyPrediction };diff --git a/packages/pieces/community/mindee/test/mindee.test.ts b/packages/pieces/community/mindee/test/mindee.test.tsnew file mode 100644index 00000000000..c424a4753e8--- /dev/null+++ b/packages/pieces/community/mindee/test/mindee.test.ts@@ -0,0 +1,493 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { buildMindeeError, detectKeyType, normalizeApiKey, v2PathFromUrl, vendorDetail } from '../src/lib/common/client';+import { mindeeFiles } from '../src/lib/common/file';+import { mindeeInference } from '../src/lib/common/inference';+import { mindeeApi } from '../src/lib/common/api';+import { productActionHelpers } from '../src/lib/actions/product-action-helpers';++const dnsAnswers = vi.hoisted(() => new Map<string, { address: string; family: number }[]>([['example.com', [{ address: '93.184.215.14', family: 4 }]]]));++vi.mock('node:dns', async (importOriginal) => {+ const actual = await importOriginal<typeof import('node:dns')>();+ const lookup = (...args: [hostname: string, options: unknown, callback: (error: NodeJS.ErrnoException | null, addresses: { address: string; family: number }[]) => void]) => {+ const [hostname, , callback] = args;+ const answer = dnsAnswers.get(hostname);+ if (answer === undefined) {+ throw new Error(`Unexpected DNS lookup in tests: ${hostname}`);+ }+ process.nextTick(() => callback(null, answer));+ };+ return { ...actual, lookup, default: { ...actual, lookup } };+});++const MODEL = '21b8675e-4c68-4d8d-abb6-ef34c453b0de';+const JOB = '11111111-2222-4333-8444-555555555555';+const INF = '99999999-2222-4333-8444-555555555555';++function json({ status, body }: { status: number; body: unknown }): Response {+ return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });+}++function job({ status, extra = {} }: { status: string; extra?: Record<string, unknown> }) {+ return {+ job: {+ id: JOB,+ model_id: MODEL,+ filename: 'invoice.jpg',+ alias: 'a1',+ created_at: '2026-10-20T10:00:00Z',+ completed_at: null,+ status,+ polling_url: `https://api-v2.mindee.net/v2/jobs/${JOB}`,+ result_url: status === 'Processed' ? `https://api-v2.mindee.net/v2/products/extraction/results/${INF}` : null,+ webhooks: [],+ ...extra,+ },+ };+}++const extractionResult = {+ inference: {+ id: INF,+ job: { id: JOB },+ model: { id: MODEL },+ file: { name: 'invoice.jpg', alias: 'a1', page_count: 1, mime_type: 'image/jpeg' },+ active_options: { raw_text: true, polygon: false, confidence: true, rag: false, text_context: false, data_schema: { replace: false } },+ result: {+ fields: {+ total_amount: { value: 42.5, confidence: 'High', locations: [] },+ supplier: { fields: { name: { value: 'ACME' } } },+ line_items: { items: [{ fields: { description: { value: 'Pen' }, quantity: { value: 2 } } }] },+ },+ raw_text: { pages: [{ content: 'line 1' }, { content: 'line 2' }] },+ rag: null,+ },+ },+};++afterEach(() => {+ vi.unstubAllGlobals();+ vi.useRealTimers();+});++describe('client helpers', () => {+ it('strips Token/Bearer prefixes from the key', () => {+ expect(normalizeApiKey(' Token md_abc ')).toBe('md_abc');+ expect(normalizeApiKey('Bearer md_abc')).toBe('md_abc');+ expect(() => normalizeApiKey(' ')).toThrow('Enter your Mindee API key.');+ });++ it('only accepts result URLs on the v2 host', () => {+ expect(v2PathFromUrl(`https://api-v2.mindee.net/v2/products/ocr/results/${INF}`)).toBe(`/v2/products/ocr/results/${INF}`);+ expect(() => v2PathFromUrl('https://evil.example.com/v2/jobs/1')).toThrow('refusing');+ expect(() => v2PathFromUrl('http://api-v2.mindee.net/v2/jobs/1')).toThrow('refusing');+ });++ it('reads v1 and v2 error bodies', () => {+ expect(vendorDetail({ status: 422, detail: 'Invalid fields', title: 'x', code: '422-001', errors: [{ pointer: '#/model_id', detail: 'bad uuid' }] })).toBe(+ 'Invalid fields #/model_id: bad uuid',+ );+ expect(vendorDetail({ api_request: { error: { message: 'Authorization required', details: 'Invalid token provided' } } })).toBe(+ 'Authorization required: Invalid token provided',+ );+ expect(vendorDetail('<html>')).toBeUndefined();+ });++ it('builds errors without a body field and points v1 keys to the legacy action', () => {+ const error = buildMindeeError({ status: 401, responseBody: { detail: 'The provided API key is invalid.' }, api: 'v2' });+ expect(error.message).toContain('Legacy v1');+ expect(error.status).toBe(401);+ expect(Reflect.has(error, 'body')).toBe(false);+ expect(error.responseBody).toEqual({ detail: 'The provided API key is invalid.' });+ });+});++describe('detectKeyType', () => {+ it('returns v2 when search/models works', async () => {+ const fetchMock = vi.fn(async () => json({ status: 200, body: { models: [], pagination: { page: 1, per_page: 1, total_items: 0, total_pages: 0 } } }));+ vi.stubGlobal('fetch', fetchMock);+ await expect(detectKeyType('md_key')).resolves.toBe('v2');+ const [url, init] = fetchMock.mock.calls[0] ?? [];+ expect(String(url)).toContain('https://api-v2.mindee.net/v2/search/models');+ expect(init?.headers).toMatchObject({ Authorization: 'md_key' });+ });++ it('returns v1 when v2 rejects the key but v1 accepts it', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (url: string) => (String(url).includes('api-v2') ? json({ status: 401, body: { detail: 'invalid' } }) : json({ status: 404, body: { api_request: { error: { message: 'Not found' } } } }))),+ );+ await expect(detectKeyType('old')).resolves.toBe('v1');+ });++ it('returns invalid when both reject the key', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => json({ status: 401, body: { detail: 'invalid' } })));+ await expect(detectKeyType('bad')).resolves.toBe('invalid');+ });+});++describe('runInference', () => {+ it('enqueues, polls and normalizes an extraction result', async () => {+ const calls: string[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (url: string, init: RequestInit) => {+ calls.push(`${init.method} ${url}`);+ if (String(url).endsWith('/v2/products/extraction/enqueue')) {+ const form = init.body;+ expect(form).toBeInstanceOf(FormData);+ if (form instanceof FormData) {+ expect(form.get('model_id')).toBe(MODEL);+ expect(form.get('url')).toBe('https://example.com/a.pdf');+ expect(form.get('confidence')).toBe('true');+ expect(form.get('rag')).toBeNull();+ }+ return json({ status: 202, body: job({ status: 'Processing' }) });+ }+ if (String(url).includes('/v2/jobs/')) {+ return json({ status: 200, body: job({ status: calls.length > 2 ? 'Processed' : 'Processing' }) });+ }+ return json({ status: 200, body: extractionResult });+ }),+ );+ vi.useFakeTimers();+ const promise = mindeeInference.runInference({+ apiKey: 'k',+ product: 'extraction',+ modelId: MODEL,+ source: { type: 'url', url: 'https://example.com/a.pdf' },+ options: { confidence: true },+ });+ await vi.runAllTimersAsync();+ const output = await promise;+ expect(calls[1]).toContain(`/v2/jobs/${JOB}?redirect=false`);+ expect(output).toMatchObject({+ completed: true,+ status: 'Processed',+ job_id: JOB,+ inference_id: INF,+ model_id: MODEL,+ file: { name: 'invoice.jpg', page_count: 1, mime_type: 'image/jpeg' },+ fields: { total_amount: 42.5, supplier: { name: 'ACME' }, line_items: [{ description: 'Pen', quantity: 2 }] },+ field_confidence: { total_amount: 'High', supplier: null, line_items: null },+ raw_text: 'line 1\n\nline 2',+ rag_document_id: null,+ });+ });++ it('fails a builder action with the job id when the wait limit is hit', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => json({ status: 202, body: job({ status: 'Processing' }) })));+ vi.useFakeTimers();+ const promise = productActionHelpers.runWithFile({+ apiKey: 'k',+ product: 'ocr',+ props: { model_id: MODEL, file: { filename: 'a.pdf', extension: 'pdf', data: Buffer.from('%PDF-1.4') } },+ });+ const assertion = expect(promise).rejects.toThrow(JOB);+ await vi.runAllTimersAsync();+ await assertion;+ });++ it('returns the job id instead of failing when the wait limit is hit', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => json({ status: 202, body: job({ status: 'Processing' }) })));+ vi.useFakeTimers();+ const promise = mindeeInference.runInference({+ apiKey: 'k',+ product: 'ocr',+ modelId: MODEL,+ source: { type: 'url', url: 'https://example.com/a.pdf' },+ options: {},+ maxWaitMs: 10_000,+ });+ await vi.runAllTimersAsync();+ const output = await promise;+ expect(output).toMatchObject({ completed: false, status: 'Processing', job_id: JOB, inference_id: null, text: null, pages: [] });+ expect(output.message).toContain(JOB);+ });++ it('throws the vendor reason when the job fails', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => json({ status: 200, body: job({ status: 'Failed', extra: { error: { status: 422, detail: 'File is corrupted', title: 'x', code: '422-002' } } }) })),+ );+ vi.useFakeTimers();+ const promise = mindeeInference.runInference({+ apiKey: 'k',+ product: 'split',+ modelId: MODEL,+ source: { type: 'url', url: 'https://example.com/a.pdf' },+ options: {},+ });+ const assertion = expect(promise).rejects.toThrow('File is corrupted');+ await vi.runAllTimersAsync();+ await assertion;+ });++ it('rejects a model id that is not a UUID before calling Mindee', async () => {+ const fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);+ await expect(+ mindeeInference.runInference({ apiKey: 'k', product: 'crop', modelId: 'invoice', source: { type: 'url', url: 'https://x.com/a' }, options: {} }),+ ).rejects.toThrow('List Models');+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('refuses a public-looking name that resolves to a private address', async () => {+ dnsAnswers.set('internal.example.org', [{ address: '10.0.0.7', family: 4 }]);+ const fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);+ await expect(mindeeFiles.downloadFile({ url: new URL('https://internal.example.org/a.pdf'), label: 'File URL' })).rejects.toThrow(/private network/);+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('allows a name that resolves to a public address', async () => {+ dnsAnswers.set('files.example.org', [{ address: '93.184.215.14', family: 4 }]);+ vi.stubGlobal('fetch', vi.fn(async () => new Response('ok', { status: 200 })));+ await expect(mindeeFiles.downloadFile({ url: new URL('https://files.example.org/a.pdf'), label: 'File URL' })).resolves.toMatchObject({ filename: 'a.pdf' });+ });++ it('rejects non-https file URLs', async () => {+ vi.stubGlobal('fetch', vi.fn());+ await expect(+ mindeeInference.runInference({ apiKey: 'k', product: 'ocr', modelId: MODEL, source: { type: 'url', url: 'file:///etc/passwd' }, options: {} }),+ ).rejects.toThrow('https://');+ });+});++describe('normalizeInference', () => {+ it('flattens classification, crop, ocr and split results', () => {+ const base = { id: INF, job: { id: JOB }, model: { id: MODEL }, file: { name: 'f.pdf', page_count: 3, mime_type: 'application/pdf' } };+ expect(+ mindeeInference.normalizeInference({ product: 'classification', job: null, body: { inference: { ...base, result: { classification: { document_type: 'invoice' } } } } }),+ ).toMatchObject({ document_type: 'invoice', fields: {} });+ expect(+ mindeeInference.normalizeInference({+ product: 'crop',+ job: null,+ body: { inference: { ...base, result: { crops: [{ object_type: 'receipt', location: { page: 0, polygon: [[0, 0], [1, 0], [1, 1]] } }] } } },+ }),+ ).toMatchObject({ crops: [{ object_type: 'receipt', page: 0, fields: {} }] });+ expect(+ mindeeInference.normalizeInference({+ product: 'ocr',+ job: null,+ body: { inference: { ...base, result: { pages: [{ content: 'a b', words: [{}, {}] }, { content: 'c', words: [{}] }] } } },+ }),+ ).toMatchObject({ text: 'a b\n\nc', pages: [{ page: 0, content: 'a b', word_count: 2 }, { page: 1, content: 'c', word_count: 1 }] });+ expect(+ mindeeInference.normalizeInference({+ product: 'split',+ job: null,+ body: { inference: { ...base, result: { splits: [{ page_range: [0, 1], document_type: 'invoice' }, { page_range: [2, 2], document_type: 'receipt' }] } } },+ }),+ ).toMatchObject({ splits: [{ start_page: 0, end_page: 1, page_count: 2 }, { start_page: 2, end_page: 2, page_count: 1 }] });+ });+});++describe('jobSummary', () => {+ it('derives product and inference id from the result URL', () => {+ const summary = mindeeInference.jobSummary({+ id: JOB,+ status: 'Processed',+ model_id: MODEL,+ filename: 'f',+ alias: null,+ created_at: null,+ completed_at: null,+ polling_url: null,+ result_url: `https://api-v2.mindee.net/v2/products/split/results/${INF}`,+ error: null,+ });+ expect(summary).toMatchObject({ completed: true, product: 'split', inference_id: INF, error: null });+ });+});++describe('poll delay', () => {+ it('stays bounded', () => {+ expect(mindeeInference.pollDelay(0)).toBe(2000);+ expect(mindeeInference.pollDelay(50)).toBe(6000);+ });+});++describe('files', () => {+ it('duck-types file props without instanceof', () => {+ const upload = mindeeFiles.readFileProp({ value: { filename: 'a.png', data: Buffer.from('abc') }, label: 'File' });+ expect(upload).toEqual({ filename: 'a.png', data: Buffer.from('abc') });+ expect(() => mindeeFiles.readFileProp({ value: '/etc/passwd', label: 'File' })).toThrow('File is required');+ });++ it('downloads with a status check', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => new Response('nope', { status: 404 })));+ await expect(mindeeFiles.downloadFile({ url: new URL('https://example.com/a.pdf'), label: 'File URL' })).rejects.toThrow('HTTP 404');+ });++ it('stops at the deadline when an error body never finishes', async () => {+ const neverEnding = new ReadableStream<Uint8Array>({ start: (controller) => controller.enqueue(new TextEncoder().encode('partial')) });+ vi.stubGlobal('fetch', vi.fn(async () => new Response(neverEnding, { status: 500 })));+ await expect(mindeeFiles.downloadFile({ url: new URL('https://example.com/a.pdf'), label: 'File URL', timeoutMs: 50 })).rejects.toThrow('took longer than');+ });++ it('refuses downloads larger than the cap', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => new Response('x', { status: 200, headers: { 'content-length': String(60 * 1024 * 1024) } })));+ await expect(mindeeFiles.downloadFile({ url: new URL('https://example.com/a.pdf'), label: 'File URL' })).rejects.toThrow('50 MB');+ });++ it('returns the downloaded bytes and file name', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => new Response('pdfdata', { status: 200 })));+ await expect(mindeeFiles.downloadFile({ url: new URL('https://example.com/docs/My%20File.pdf'), label: 'File URL' })).resolves.toEqual({+ data: Buffer.from('pdfdata'),+ filename: 'My File.pdf',+ });+ });+});++describe('rag documents', () => {+ it('requires a status or annotation to update', async () => {+ vi.stubGlobal('fetch', vi.fn());+ await expect(mindeeApi.updateRagDocument({ apiKey: 'k', documentId: INF })).rejects.toThrow('Set a new status');+ await expect(mindeeApi.updateRagDocument({ apiKey: 'k', documentId: INF, status: 'Deleted' })).rejects.toThrow('Draft or Active');+ });++ it('sends PATCH with JSON and maps the document', async () => {+ const fetchMock = vi.fn(async () =>+ json({ status: 200, body: { id: INF, model_id: MODEL, filename: 'r.pdf', created_at: 'x', total_matches: 0, last_match_at: null, status: 'Active', annotation: null } }),+ );+ vi.stubGlobal('fetch', fetchMock);+ const result = await mindeeApi.updateRagDocument({ apiKey: 'k', documentId: INF, status: 'Active' });+ expect(result).toMatchObject({ id: INF, status: 'Active', annotation: null });+ const [url, init] = fetchMock.mock.calls[0] ?? [];+ expect(String(url)).toBe(`https://api-v2.mindee.net/v2/products/extraction/rag-documents/${INF}`);+ expect(init?.method).toBe('PATCH');+ expect(init?.body).toBe(JSON.stringify({ status: 'Active' }));+ });+});++describe('download SSRF guard', () => {+ it('blocks private, loopback, link-local and metadata addresses and local names', async () => {+ const { mindeeNetwork } = await import('../src/lib/common/network-guard');+ for (const host of ['127.0.0.1', '10.1.2.3', '192.168.0.1', '172.16.0.5', '169.254.169.254', '[::1]', '[fe80::1]', '[::ffff:127.0.0.1]', 'localhost', 'metadata.google.internal', 'db']) {+ expect(mindeeNetwork.isBlockedHostname(host)).toBe(true);+ }+ expect(mindeeNetwork.isBlockedHostname('93.184.215.14')).toBe(false);+ expect(mindeeNetwork.isBlockedHostname('example.com')).toBe(false);+ });++ it('refuses a blocked host before any request', async () => {+ const fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);+ await expect(mindeeFiles.downloadFile({ url: new URL('https://169.254.169.254/latest'), label: 'File URL' })).rejects.toThrow(/private network/);+ await expect(mindeeFiles.downloadFile({ url: new URL('https://localhost/x.pdf'), label: 'File URL' })).rejects.toThrow(/private network/);+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('does not auto-follow redirects and re-validates every hop', async () => {+ const fetchMock = vi.fn(async (_url: string, init: RequestInit) => {+ expect(init.redirect).toBe('manual');+ return new Response(null, { status: 302, headers: { location: 'https://10.0.0.5/secret' } });+ });+ vi.stubGlobal('fetch', fetchMock);+ await expect(mindeeFiles.downloadFile({ url: new URL('https://93.184.215.14/a.pdf'), label: 'File URL' })).rejects.toThrow(/private network/);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it('refuses a redirect to http', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => new Response(null, { status: 301, headers: { location: 'http://93.184.215.14/a.pdf' } })));+ await expect(mindeeFiles.downloadFile({ url: new URL('https://93.184.215.14/a.pdf'), label: 'File URL' })).rejects.toThrow(/https/);+ });++ it('follows a safe redirect and stops after 3 hops', async () => {+ let calls = 0;+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => {+ calls++;+ return calls === 2 ? new Response('PDFDATA', { status: 200 }) : new Response(null, { status: 302, headers: { location: '/doc.pdf' } });+ }),+ );+ const upload = await mindeeFiles.downloadFile({ url: new URL('https://93.184.215.14/a.pdf'), label: 'File URL' });+ expect(upload.data.toString()).toBe('PDFDATA');+ expect(upload.filename).toBe('doc.pdf');+ calls = -10;+ await expect(mindeeFiles.downloadFile({ url: new URL('https://93.184.215.14/a.pdf'), label: 'File URL' })).rejects.toThrow(/more than 3 redirects/);+ });+});++describe('custom API call', () => {+ async function runCustom(props: Record<string, unknown>) {+ const { mindeeCustomApiCall } = await import('../src/lib/actions/custom-api-call');+ return Reflect.apply(mindeeCustomApiCall.run, mindeeCustomApiCall, [{ auth: { secret_text: 'md_key' }, propsValue: props, files: { write: vi.fn() } }]);+ }++ it('sends the bare key to v2 and Token to v1, with redirects off', async () => {+ const fetchMock = vi.fn(async (_url: string, _init: RequestInit) => json({ status: 200, body: { ok: true } }));+ vi.stubGlobal('fetch', fetchMock);+ await runCustom({ method: 'GET', url: { url: '/search/models' } });+ await runCustom({ method: 'GET', url: { url: 'https://api.mindee.net/v1/products' } });+ const first = fetchMock.mock.calls[0];+ const second = fetchMock.mock.calls[1];+ expect(String(first[0])).toBe('https://api-v2.mindee.net/v2/search/models');+ expect(new Headers(first[1].headers).get('authorization')).toBe('md_key');+ expect(new Headers(second[1].headers).get('authorization')).toBe('Token md_key');+ expect(first[1].redirect).toBe('manual');+ });++ it('refuses non-Mindee hosts and http', async () => {+ const fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);+ await expect(runCustom({ method: 'GET', url: { url: 'https://evil.example.com/v2/x' } })).rejects.toThrow(/api-v2.mindee.net/);+ await expect(runCustom({ method: 'GET', url: { url: 'http://api-v2.mindee.net/v2/x' } })).rejects.toThrow(/api-v2.mindee.net/);+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('does not follow a redirect off Mindee hosts', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => new Response(null, { status: 302, headers: { location: 'https://evil.example.com/' } })));+ await expect(runCustom({ method: 'GET', url: { url: '/jobs/1' }, followRedirects: true })).rejects.toThrow(/api-v2.mindee.net/);+ });++ it('redacts the request body in errors', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => json({ status: 400, body: { detail: 'bad' } })));+ const error = await runCustom({ method: 'POST', url: { url: '/x' }, body: { secret: 'doc-bytes' } }).catch((e: unknown) => e);+ expect(JSON.stringify(error instanceof Error ? error.message : error)).not.toContain('doc-bytes');+ });+});++describe('Predict Document (Legacy v1)', () => {+ async function runLegacy(props: Record<string, unknown>) {+ const { mindeePredictDocumentAction } = await import('../src/lib/actions/predict-document');+ return Reflect.apply(mindeePredictDocumentAction.run, mindeePredictDocumentAction, [{ auth: { secret_text: 'v1_key' }, propsValue: { account_name: 'mindee', api_name: 'invoices/v4', ...props } }]);+ }++ it('posts an uploaded file as multipart to the v1 predict endpoint with a Token header', async () => {+ const fetchMock = vi.fn(async (_url: string, _init: RequestInit) => json({ status: 201, body: { document: { id: 'd1' } } }));+ vi.stubGlobal('fetch', fetchMock);+ const output = await runLegacy({ upload: { filename: 'a.pdf', extension: 'pdf', data: Buffer.from('%PDF-1.4') } });+ const [url, init] = fetchMock.mock.calls[0];+ expect(String(url)).toBe('https://api.mindee.net/v1/products/mindee/invoices/v4/predict');+ expect(new Headers(init.headers).get('authorization')).toBe('Token v1_key');+ expect(init.body).toBeInstanceOf(FormData);+ expect(init.redirect).toBe('manual');+ expect(output).toEqual({ document: { id: 'd1' } });+ });++ it('sends a URL and a Base64 string as JSON documents', async () => {+ const fetchMock = vi.fn(async (_url: string, _init: RequestInit) => json({ status: 201, body: {} }));+ vi.stubGlobal('fetch', fetchMock);+ await runLegacy({ file: 'https://example.com/a.pdf' });+ await runLegacy({ file: 'data:application/pdf;base64,JVBERi0xLjQKJcfsj6IKNSAwIG9iago=' });+ expect(JSON.parse(String(fetchMock.mock.calls[0][1].body))).toEqual({ document: 'https://example.com/a.pdf' });+ expect(JSON.parse(String(fetchMock.mock.calls[1][1].body))).toEqual({ document: 'JVBERi0xLjQKJcfsj6IKNSAwIG9iago=' });+ });++ it('rejects a local file path and an empty input before any request', async () => {+ const fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);+ await expect(runLegacy({ file: '/etc/passwd' })).rejects.toThrow('Local file paths are not supported');+ await expect(runLegacy({})).rejects.toThrow('Provide a File');+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('explains a v2 key used against the legacy API', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => json({ status: 401, body: { api_request: { error: { code: 'Unauthorized', details: 'The token provided is for the v2 API.', message: 'Authorization required' } } } })));+ await expect(runLegacy({ file: 'https://example.com/a.pdf' })).rejects.toThrow(/legacy v1 API/);+ });+});diff --git a/packages/pieces/community/mindee/vitest.config.ts b/packages/pieces/community/mindee/vitest.config.tsnew file mode 100644index 00000000000..ba8ade4a178--- /dev/null+++ b/packages/pieces/community/mindee/vitest.config.ts@@ -0,0 +1,17 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ test: {+ globals: true,+ environment: 'node',+ },+ 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'),+ },+ },+})