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(ninjapipe): let AI agents work with NinjaPipe contacts, deals and tasks, with typed outputs on every step (#16860)
Odai Ahmad71dd26c74761
diff --git a/bun.lock b/bun.lockindex 9fa81bc8e2e..833727c9b90 100644--- a/bun.lock+++ b/bun.lock@@ -6517,7 +6517,7 @@},"packages/pieces/community/ninjapipe": {"name": "@activepieces/piece-ninjapipe",- "version": "0.1.1",+ "version": "0.2.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -6526,6 +6526,7 @@},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/ninox": {diff --git a/docs/install/reference/breaking-changes-unreleased.mdx b/docs/install/reference/breaking-changes-unreleased.mdxindex ba0a139be92..ef0c750a0eb 100644--- a/docs/install/reference/breaking-changes-unreleased.mdx+++ b/docs/install/reference/breaking-changes-unreleased.mdx@@ -8,6 +8,39 @@ Entries here move to [Breaking Changes](/install/reference/breaking-changes) aut## What has changed?+#### NinjaPipe 0.2.0: 17 actions are builder-only, outputs change shape, and fields the API rejected or ignored are removed++NinjaPipe 0.2.0 changes what existing steps take and return once they are upgraded to that version. Steps keep running on the version they were built with until you upgrade them, but AI agents lose the old tools as soon as 0.2.0 is published.++**Actions no longer offered to AI agents.** Create Contact, Get Contact, List Contacts, Update Contact, Create Company, Get Company, List Companies, Update Company, Create Deal, Get Deal, List Deals, Update Deal, Create Task, List Tasks, Update Task, List Projects and List Pipelines keep working in flows but are no longer agent tools. Agents get new AI versions instead: Create Contact (`ai_create_contact`), Get Contact (`ai_get_contact`), Search Contacts (`ai_search_contacts`), Update Contact (`ai_update_contact`), Create Company (`ai_create_company`), Get Company (`ai_get_company`), Search Companies (`ai_search_companies`), Update Company (`ai_update_company`), Create Deal (`ai_create_deal`), Get Deal (`ai_get_deal`), Search Deals (`ai_search_deals`), Update Deal (`ai_update_deal`), Create Task (`ai_create_task`), List Tasks (`ai_list_tasks`), Update Task (`ai_update_task`), List Projects (`ai_list_projects`) and List Pipelines (`ai_list_pipelines`).++**Removed fields** (the API rejected or silently ignored them):+- Create Contact, Update Contact and Upsert Contact: Address, City, ZIP, Country, State, Notes and the Company text field. A Company dropdown replaces the text field.+- Create and Update Company: Address, City, ZIP, Country, State and Notes.+- Create and Update Deal: Title, Currency, Pipeline and Notes.+- Create and Update Project: Contact and Settings JSON.+- Create and Update Order, Create and Update Task: Settings JSON.+- Create and Update Product: Custom Fields.+- List Pipelines: Search. List Projects: Owner filter.++**Changed inputs.** Owner and Assignee are now a dropdown of workspace members instead of a text field.++**Changed outputs.**+- The List steps (Contacts, Companies, Deals, Products, Orders, Budgets, Projects, Pipelines) return `{ items, count, total, hasMore, nextPage }` instead of a plain array. List Tasks returns `{ items, count }`.+- Get, Create and Update steps return the record's own fields (`id`, `name`, …) instead of `data_id`, `data_name`, …. Create Contact in Skip mode (the email already exists) returns `{ action: "skipped", ...existing contact fields }` instead of `{ skipped, reason, email, existing_id }`.+- Delete steps return `{ deleted, id, name, message }` instead of `{ success, deleted_id }`.+- Send to Databin returns `{ status, response }` instead of the raw response body.+- The triggers emit the nested record as NinjaPipe returns it instead of flattened `fields_*` keys.++**Changed behaviour.**+- Custom API Call only calls the connected NinjaPipe host and refuses any other host.+- Update steps with nothing to change fail with "Nothing to update" instead of sending an empty update.+- Return All stops at 5,000 items.++#### What you need to do++After upgrading a NinjaPipe step, remap later steps that used the List output (map `items` instead of the array), a `data_*` field (map the plain field name), the Delete or Send to Databin output, or a trigger's `fields_*` key (map the nested field). Re-select the company in contact steps that used the old Company text field, and re-select Owner and Assignee from the dropdown. Custom API Call steps that called another host should use an HTTP step instead. Agents that used the old actions as tools: add the AI versions listed above to the agent.+#### Campaign Monitor 0.2.0: Add Subscriber and Update Subscriber are builder-onlyAdd Subscriber and Update Subscriber are no longer offered to AI agents. They keep working in flows, but an agent that used them as tools loses them after the upgrade.diff --git a/packages/pieces/community/ninjapipe/package.json b/packages/pieces/community/ninjapipe/package.jsonindex 70daf155cdf..4962e0fdc4b 100644--- a/packages/pieces/community/ninjapipe/package.json+++ b/packages/pieces/community/ninjapipe/package.json@@ -1,12 +1,13 @@{"name": "@activepieces/piece-ninjapipe",- "version": "0.1.1",+ "version": "0.2.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"},"dependencies": {"@activepieces/pieces-common": "workspace:*",@@ -15,6 +16,7 @@"@activepieces/core-utils": "workspace:*"},"devDependencies": {- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"}}diff --git a/packages/pieces/community/ninjapipe/src/i18n/translation.json b/packages/pieces/community/ninjapipe/src/i18n/translation.jsonindex 6f6d220eec7..5fabffaf194 100644--- a/packages/pieces/community/ninjapipe/src/i18n/translation.json+++ b/packages/pieces/community/ninjapipe/src/i18n/translation.json@@ -1,171 +1,169 @@{- "NinjaPipe CRM integration with contacts, companies, deals, tasks (under projects), pipelines, products, budgets, projects, orders, lists, and Databin webhook delivery.": "NinjaPipe CRM integration with contacts, companies, deals, tasks (under projects), pipelines, products, budgets, projects, orders, lists, and Databin webhook delivery.",+ "NinjaPipe CRM integration with contacts, companies, deals, tasks (under projects), pipelines and pipeline items, products, budgets, projects, orders, lists, and Databin webhook delivery.": "NinjaPipe CRM integration with contacts, companies, deals, tasks (under projects), pipelines and pipeline items, products, budgets, projects, orders, lists, and Databin webhook delivery.","API Base URL": "API Base URL","API Key": "API Key","Your workspace API base URL (e.g. https://www.ninjapipe.app/api).": "Your workspace API base URL (e.g. https://www.ninjapipe.app/api).","Your workspace API key from NinjaPipe Settings > API.": "Your workspace API key from NinjaPipe Settings > API.",- "Connect to your NinjaPipe workspace.\n\n1. Log in to NinjaPipe and open **Workspace Settings > NinjaPipe API**.\n2. Copy your **API key** (starts with `np_`).\n3. Enter your workspace **API Base URL**. The default is `https://www.ninjapipe.app/api`.": "Connect to your NinjaPipe workspace.\n\n1. Log in to NinjaPipe and open **Workspace Settings > NinjaPipe API**.\n2. Copy your **API key** (starts with `np_`).\n3. Enter your workspace **API Base URL**. The default is `https://www.ninjapipe.app/api`.",- "Create Contact": "Create Contact",- "Update Contact": "Update Contact",- "Get Contact": "Get Contact",- "List Contacts": "List Contacts",- "Delete Contact": "Delete Contact",- "Upsert Contact": "Upsert Contact",- "Toggle Client Portal": "Toggle Client Portal",+ "Connect to your NinjaPipe workspace.\n\n1. Log in to NinjaPipe and open **Workspace Settings > NinjaPipe API**.\n2. Create an **API key** (starts with `np_`). Pick **write** permission if your flows create, update or delete records.\n3. Enter your workspace **API Base URL**. The default is `https://www.ninjapipe.app/api`.": "Connect to your NinjaPipe workspace.\n\n1. Log in to NinjaPipe and open **Workspace Settings > NinjaPipe API**.\n2. Create an **API key** (starts with `np_`). Pick **write** permission if your flows create, update or delete records.\n3. Enter your workspace **API Base URL**. The default is `https://www.ninjapipe.app/api`.",+ "Add Note to Contact": "Add Note to Contact",+ "Add to List": "Add to List",+ "Create Budget Expense": "Create Budget Expense",+ "Create Budget": "Create Budget","Create Company": "Create Company",- "Update Company": "Update Company",- "Get Company": "Get Company",- "List Companies": "List Companies",- "Delete Company": "Delete Company",+ "Create Contact": "Create Contact","Create Deal": "Create Deal",- "Update Deal": "Update Deal",- "Get Deal": "Get Deal",- "List Deals": "List Deals",- "Delete Deal": "Delete Deal",+ "Create Order": "Create Order",+ "Create Pipeline Item": "Create Pipeline Item",+ "Create Pipeline": "Create Pipeline","Create Product": "Create Product",- "Update Product": "Update Product",- "Get Product": "Get Product",- "List Products": "List Products",- "Delete Product": "Delete Product",- "Create Budget": "Create Budget",- "Update Budget": "Update Budget",- "Get Budget": "Get Budget",- "List Budgets": "List Budgets",- "Delete Budget": "Delete Budget",- "Create Budget Expense": "Create Budget Expense","Create Project": "Create Project",- "Update Project": "Update Project",- "Get Project": "Get Project",- "List Projects": "List Projects",- "Delete Project": "Delete Project","Create Task": "Create Task",- "Update Task": "Update Task",- "Get Task": "Get Task",- "List Tasks": "List Tasks",- "Delete Task": "Delete Task",- "Create Pipeline": "Create Pipeline",- "Update Pipeline": "Update Pipeline",- "Get Pipeline": "Get Pipeline",- "List Pipelines": "List Pipelines",+ "Delete Budget": "Delete Budget",+ "Delete Company": "Delete Company",+ "Delete Contact": "Delete Contact",+ "Delete Deal": "Delete Deal",+ "Delete Order": "Delete Order","Delete Pipeline": "Delete Pipeline",- "Create Order": "Create Order",- "Update Order": "Update Order",+ "Delete Product": "Delete Product",+ "Delete Project": "Delete Project",+ "Delete Task": "Delete Task",+ "Get Budget": "Get Budget",+ "Get Company": "Get Company",+ "Get Contact": "Get Contact",+ "Get Deal": "Get Deal","Get Order": "Get Order",+ "Get Pipeline": "Get Pipeline",+ "Get Product": "Get Product",+ "Get Project": "Get Project",+ "Get Task": "Get Task",+ "List Budgets": "List Budgets",+ "List Companies": "List Companies",+ "List Contacts": "List Contacts",+ "List Deals": "List Deals","List Orders": "List Orders",- "Delete Order": "Delete Order",+ "List Pipelines": "List Pipelines",+ "List Products": "List Products",+ "List Projects": "List Projects",+ "List Tasks": "List Tasks","Send to Databin": "Send to Databin",- "Add to List": "Add to List",+ "Toggle Client Portal": "Toggle Client Portal",+ "Update Budget": "Update Budget",+ "Update Company": "Update Company",+ "Update Contact": "Update Contact",+ "Update Deal": "Update Deal",+ "Update Order": "Update Order",+ "Update Pipeline Item": "Update Pipeline Item",+ "Update Pipeline": "Update Pipeline",+ "Update Product": "Update Product",+ "Update Project": "Update Project",+ "Update Task": "Update Task",+ "Create or Update Contact": "Create or Update Contact",+ "List Contact Activities": "List Contact Activities",+ "List Pipeline Items": "List Pipeline Items",+ "List Workspace Members": "List Workspace Members",+ "Search Companies": "Search Companies",+ "Search Contacts": "Search Contacts",+ "Search Deals": "Search Deals","Custom API Call": "Custom API Call",- "Creates a new contact. Choose what happens if a contact with the same email already exists.": "Creates a new contact. Choose what happens if a contact with the same email already exists.",- "Updates an existing contact by ID.": "Updates an existing contact by ID.",- "Retrieves a contact by ID.": "Retrieves a contact by ID.",- "Retrieves a list of contacts.": "Retrieves a list of contacts.",- "Deletes a contact by ID.": "Deletes a contact by ID.",- "Creates a contact or updates an existing one by email.": "Creates a contact or updates an existing one by email.",- "Enable or disable client portal access for a contact. When enabling, NinjaPipe auto-generates a secure password and returns it in the response.": "Enable or disable client portal access for a contact. When enabling, NinjaPipe auto-generates a secure password and returns it in the response.",- "Creates a new company.": "Creates a new company.",- "Updates a company by ID.": "Updates a company by ID.",- "Retrieves a company by ID.": "Retrieves a company by ID.",- "Retrieves a list of companies.": "Retrieves a list of companies.",- "Deletes a company by ID.": "Deletes a company by ID.",- "Creates a new deal.": "Creates a new deal.",- "Updates a deal by ID.": "Updates a deal by ID.",- "Retrieves a deal by ID.": "Retrieves a deal by ID.",- "Retrieves a list of deals.": "Retrieves a list of deals.",- "Deletes a deal by ID.": "Deletes a deal by ID.",- "Creates a new product.": "Creates a new product.",- "Updates a product by ID.": "Updates a product by ID.",- "Retrieves a product by ID.": "Retrieves a product by ID.",- "Retrieves a list of products.": "Retrieves a list of products.",- "Deletes a product by ID.": "Deletes a product by ID.",- "Creates a new budget.": "Creates a new budget.",- "Updates a budget by ID.": "Updates a budget by ID.",- "Retrieves a budget by ID.": "Retrieves a budget by ID.",- "Retrieves a list of budgets.": "Retrieves a list of budgets.",- "Deletes a budget by ID.": "Deletes a budget by ID.",- "Adds an expense to a budget. The expense amount is added to the budget's spent amount.": "Adds an expense to a budget. The expense amount is added to the budget's spent amount.",- "Creates a new project.": "Creates a new project.",- "Updates a project by ID.": "Updates a project by ID.",- "Retrieves a project by ID.": "Retrieves a project by ID.",- "Retrieves a list of projects.": "Retrieves a list of projects.",- "Deletes a project by ID.": "Deletes a project by ID.",- "Creates a task or subtask in a project.": "Creates a task or subtask in a project.",- "Updates a task within a project.": "Updates a task within a project.",- "Retrieves a single task within a project.": "Retrieves a single task within a project.",- "Retrieves the tasks of a project as a flat list. Use parent_id on each item to build a tree.": "Retrieves the tasks of a project as a flat list. Use parent_id on each item to build a tree.",- "Deletes a task within a project. Subtasks may cascade.": "Deletes a task within a project. Subtasks may cascade.",- "Creates a new pipeline.": "Creates a new pipeline.",- "Updates a pipeline by ID.": "Updates a pipeline by ID.",- "Retrieves a pipeline by ID.": "Retrieves a pipeline by ID.",- "Retrieves a list of pipelines.": "Retrieves a list of pipelines.",- "Deletes a pipeline by ID.": "Deletes a pipeline by ID.",- "Creates a new order. Line items, currency, and custom fields go in Settings JSON.": "Creates a new order. Line items, currency, and custom fields go in Settings JSON.",- "Updates an order by ID.": "Updates an order by ID.",- "Retrieves an order by ID.": "Retrieves an order by ID.",- "Retrieves a list of orders.": "Retrieves a list of orders.",- "Deletes an order by ID.": "Deletes an order by ID.",- "Sends a JSON payload to a Databin webhook URL on your connected NinjaPipe workspace.": "Sends a JSON payload to a Databin webhook URL on your connected NinjaPipe workspace.",- "Adds a contact OR a company to a CRM list. The list type must match (Contact lists accept contacts, Company lists accept companies). Idempotent — returns already_in_list:true if already present.": "Adds a contact OR a company to a CRM list. The list type must match (Contact lists accept contacts, Company lists accept companies). Idempotent — returns already_in_list:true if already present.",- "Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",- "First Name": "First Name",- "Last Name": "Last Name",- "Email": "Email",- "Phone": "Phone",- "Company": "Company",- "Status": "Status",- "Owner": "Owner",- "Address": "Address",- "City": "City",- "ZIP Code": "ZIP Code",- "Country": "Country",- "State": "State",- "Notes": "Notes",- "Custom Fields": "Custom Fields",- "If Contact Exists": "If Contact Exists",+ "Adds a note to a contact's activity timeline.": "Adds a note to a contact's activity timeline.",+ "Adds a contact or a company to a CRM list. Contact lists take contacts, company lists take companies.": "Adds a contact or a company to a CRM list. Contact lists take contacts, company lists take companies.",+ "Records an expense against a budget.": "Records an expense against a budget.",+ "Creates a budget.": "Creates a budget.",+ "Creates a company.": "Creates a company.",+ "Creates a contact. Choose what happens when a contact with the same email already exists.": "Creates a contact. Choose what happens when a contact with the same email already exists.",+ "Creates a deal.": "Creates a deal.",+ "Creates a order.": "Creates a order.",+ "Adds an item (card) to a stage of a pipeline.": "Adds an item (card) to a stage of a pipeline.",+ "Creates a pipeline (board) with its stages.": "Creates a pipeline (board) with its stages.",+ "Creates a product.": "Creates a product.",+ "Creates a project.": "Creates a project.",+ "Creates a task in a project.": "Creates a task in a project.",+ "Permanently deletes a budget.": "Permanently deletes a budget.",+ "Permanently deletes a company.": "Permanently deletes a company.",+ "Permanently deletes a contact.": "Permanently deletes a contact.",+ "Permanently deletes a deal.": "Permanently deletes a deal.",+ "Permanently deletes a order.": "Permanently deletes a order.",+ "Permanently deletes a pipeline. Its items are removed with it.": "Permanently deletes a pipeline. Its items are removed with it.",+ "Permanently deletes a product.": "Permanently deletes a product.",+ "Permanently deletes a project. Its tasks are removed with it.": "Permanently deletes a project. Its tasks are removed with it.",+ "Permanently deletes a task from a project.": "Permanently deletes a task from a project.",+ "Gets one budget by ID.": "Gets one budget by ID.",+ "Gets one company by ID.": "Gets one company by ID.",+ "Gets one contact by ID.": "Gets one contact by ID.",+ "Gets one deal by ID.": "Gets one deal by ID.",+ "Gets one order by ID.": "Gets one order by ID.",+ "Gets one pipeline by ID.": "Gets one pipeline by ID.",+ "Gets one product by ID.": "Gets one product by ID.",+ "Gets one project by ID.": "Gets one project by ID.",+ "Gets one task of a project.": "Gets one task of a project.",+ "Lists budgets one page at a time, or all pages with Return All.": "Lists budgets one page at a time, or all pages with Return All.",+ "Lists companies one page at a time, or all pages with Return All.": "Lists companies one page at a time, or all pages with Return All.",+ "Lists contacts, with optional search, status, owner and assignee filters.": "Lists contacts, with optional search, status, owner and assignee filters.",+ "Lists deals one page at a time, or all pages with Return All.": "Lists deals one page at a time, or all pages with Return All.",+ "Lists orders one page at a time, or all pages with Return All.": "Lists orders one page at a time, or all pages with Return All.",+ "Lists pipelines one page at a time, or all pages with Return All.": "Lists pipelines one page at a time, or all pages with Return All.",+ "Lists products one page at a time, or all pages with Return All.": "Lists products one page at a time, or all pages with Return All.",+ "Lists projects one page at a time, or all pages with Return All.": "Lists projects one page at a time, or all pages with Return All.",+ "Lists every task of a project as a flat list. Use parent_id on each task to build a tree.": "Lists every task of a project as a flat list. Use parent_id on each task to build a tree.",+ "Sends a JSON payload to a Databin webhook URL of your connected NinjaPipe workspace.": "Sends a JSON payload to a Databin webhook URL of your connected NinjaPipe workspace.",+ "Enables or disables client portal access for a contact. Enabling generates a new portal password and returns it in the step output, where anyone who can see the run can read it.": "Enables or disables client portal access for a contact. Enabling generates a new portal password and returns it in the step output, where anyone who can see the run can read it.",+ "Updates a budget. Fields left blank keep their value; use Clear Fields to empty them.": "Updates a budget. Fields left blank keep their value; use Clear Fields to empty them.",+ "Updates a company. Fields left blank keep their value; use Clear Fields to empty them.": "Updates a company. Fields left blank keep their value; use Clear Fields to empty them.",+ "Updates a contact. Fields left blank keep their value; use Clear Fields to empty them.": "Updates a contact. Fields left blank keep their value; use Clear Fields to empty them.",+ "Updates a deal. Fields left blank keep their value; use Clear Fields to empty them.": "Updates a deal. Fields left blank keep their value; use Clear Fields to empty them.",+ "Updates a order. Fields left blank keep their value; use Clear Fields to empty them.": "Updates a order. Fields left blank keep their value; use Clear Fields to empty them.",+ "Updates an item (card) of a pipeline or moves it to another stage. Fields left blank keep their value.": "Updates an item (card) of a pipeline or moves it to another stage. Fields left blank keep their value.",+ "Renames a pipeline or changes its type, description or status. Stages are not changed.": "Renames a pipeline or changes its type, description or status. Stages are not changed.",+ "Updates a product. Fields left blank keep their value; use Clear Fields to empty them.": "Updates a product. Fields left blank keep their value; use Clear Fields to empty them.",+ "Updates a project. Fields left blank keep their value; use Clear Fields to empty them.": "Updates a project. Fields left blank keep their value; use Clear Fields to empty them.",+ "Updates a task. Fields left blank keep their value; use Clear Fields to empty them.": "Updates a task. Fields left blank keep their value; use Clear Fields to empty them.",+ "Finds a contact by exact email. Updates it when found, creates it when not.": "Finds a contact by exact email. Updates it when found, creates it when not.",+ "Adds a note to a contact's timeline.": "Adds a note to a contact's timeline.",+ "Creates a contact.": "Creates a contact.",+ "Adds an item (card) to a pipeline stage.": "Adds an item (card) to a pipeline stage.",+ "Lists a contact's activity timeline.": "Lists a contact's activity timeline.",+ "Lists the items (cards) of a pipeline.": "Lists the items (cards) of a pipeline.",+ "Lists pipelines with their stages.": "Lists pipelines with their stages.",+ "Lists projects page by page.": "Lists projects page by page.",+ "Lists the tasks of a project.": "Lists the tasks of a project.",+ "Lists the members of the NinjaPipe workspace.": "Lists the members of the NinjaPipe workspace.",+ "Searches companies page by page.": "Searches companies page by page.",+ "Searches contacts page by page.": "Searches contacts page by page.",+ "Searches deals page by page.": "Searches deals page by page.",+ "Updates a company.": "Updates a company.",+ "Updates a contact.": "Updates a contact.",+ "Updates a deal.": "Updates a deal.",+ "Updates or moves an item (card) of a pipeline.": "Updates or moves an item (card) of a pipeline.",+ "Updates a task in a project.": "Updates a task in a project.",+ "Sends an authenticated request to the NinjaPipe API of the connected workspace. The URL must be a path or a URL on the connected API Base URL.": "Sends an authenticated request to the NinjaPipe API of the connected workspace. The URL must be a path or a URL on the connected API Base URL.","Contact": "Contact",- "Limit": "Limit",- "Search": "Search",- "Status Filter": "Status Filter",- "Owner Filter": "Owner Filter",- "Return All": "Return All",- "Page": "Page",- "Enable Client Portal": "Enable Client Portal",- "Portal Email": "Portal Email",- "Name": "Name",- "Industry": "Industry",- "Website": "Website","Title": "Title",- "Value": "Value",- "Currency": "Currency",- "Pipeline": "Pipeline",- "Deal": "Deal",- "SKU": "SKU",- "Price": "Price",+ "Content": "Content",+ "Date": "Date",+ "List ID": "List ID",+ "Company": "Company",+ "Budget": "Budget","Description": "Description",- "Product": "Product",- "Allocated Amount": "Allocated Amount",+ "Amount": "Amount","Category": "Category",+ "Name": "Name",+ "Allocated Amount": "Allocated Amount","Period": "Period",+ "Currency": "Currency",+ "Status": "Status","Start Date": "Start Date","End Date": "End Date",- "Budget": "Budget",- "Amount": "Amount",- "Date": "Date",- "Priority": "Priority",- "Due Date": "Due Date",- "Team": "Team",- "Tags": "Tags",- "Extra Settings": "Extra Settings",- "Project": "Project",- "Assignee ID": "Assignee ID",- "Parent Task ID": "Parent Task ID",- "Task": "Task",- "Priority Filter": "Priority Filter",- "Parent Task Filter": "Parent Task Filter",- "Sort By": "Sort By",- "Sort Order": "Sort Order",- "Pipeline Type": "Pipeline Type",- "Stages": "Stages",+ "Email": "Email",+ "Phone": "Phone",+ "Website": "Website",+ "Industry": "Industry",+ "Owner": "Owner",+ "Custom Fields": "Custom Fields",+ "First Name": "First Name",+ "Last Name": "Last Name",+ "Assigned To": "Assigned To",+ "If Contact Exists": "If Contact Exists",+ "Value": "Value","Customer Name": "Customer Name","Customer Email": "Customer Email","Customer Company": "Customer Company",@@ -174,12 +172,50 @@"Payment Status": "Payment Status","Order Date": "Order Date","Delivery Date": "Delivery Date",+ "Priority": "Priority","Tracking Number": "Tracking Number",- "Settings JSON": "Settings JSON",+ "Notes": "Notes",+ "Pipeline": "Pipeline",+ "Stage": "Stage",+ "Due Date": "Due Date",+ "Tags": "Tags",+ "Pipeline Type": "Pipeline Type",+ "Stages": "Stages",+ "SKU": "SKU",+ "Price": "Price",+ "Cost": "Cost",+ "Team Member IDs": "Team Member IDs",+ "Project": "Project",+ "Assignee": "Assignee",+ "Parent Task ID": "Parent Task ID",+ "Estimated Hours": "Estimated Hours",+ "Deal": "Deal","Order": "Order",+ "Product": "Product",+ "Task": "Task",+ "Search": "Search",+ "Sort By": "Sort By",+ "Sort Order": "Sort Order",+ "Limit": "Limit",+ "Page": "Page",+ "Return All": "Return All","Databin Webhook URL": "Databin Webhook URL","Payload": "Payload",- "List ID": "List ID",+ "Enable Client Portal": "Enable Client Portal",+ "Portal Email": "Portal Email",+ "Clear Fields": "Clear Fields",+ "Pipeline Item": "Pipeline Item",+ "Contact ID": "Contact ID",+ "Owner ID": "Owner ID",+ "Company ID": "Company ID",+ "Pipeline ID": "Pipeline ID",+ "Stage ID": "Stage ID",+ "Project ID": "Project ID",+ "Assignee ID": "Assignee ID",+ "Deal ID": "Deal ID",+ "Type": "Type",+ "Item ID": "Item ID",+ "Task ID": "Task ID","Method": "Method","Headers": "Headers","Query Parameters": "Query Parameters",@@ -189,98 +225,165 @@"Return Error as Output": "Return Error as Output","Timeout": "Timeout","Follow redirects": "Follow redirects",- "The email address of the contact.": "The email address of the contact.",- "Company name or ID.": "Company name or ID.",- "Select a country.": "Select a country.",- "Key-value pairs sent as custom_fields.": "Key-value pairs sent as custom_fields.",+ "Select a contact, or type to search.": "Select a contact, or type to search.",+ "When the note happened. Defaults to now.": "When the note happened. Defaults to now.",+ "The list UUID (open the list in NinjaPipe and copy it from the URL).": "The list UUID (open the list in NinjaPipe and copy it from the URL).",+ "Select a company, or type to search.": "Select a company, or type to search.",+ "Select a budget.": "Select a budget.",+ "Date (YYYY-MM-DD). Defaults to today.": "Date (YYYY-MM-DD). Defaults to today.",+ "Category.": "Category.",+ "Budget cycle. NinjaPipe derives the end date from the start date and period.": "Budget cycle. NinjaPipe derives the end date from the start date and period.",+ "Status.": "Status.",+ "Date (YYYY-MM-DD).": "Date (YYYY-MM-DD).",+ "Workspace member who owns the company (owner_id).": "Workspace member who owns the company (owner_id).",+ "Custom field values by field key (the key shown in NinjaPipe settings).": "Custom field values by field key (the key shown in NinjaPipe settings).",+ "Email address of the contact. NinjaPipe allows one contact per email.": "Email address of the contact. NinjaPipe allows one contact per email.",+ "Contact status, e.g. Active or Lead.": "Contact status, e.g. Active or Lead.",+ "Workspace member who owns the contact (owner_id). Defaults to the API key owner.": "Workspace member who owns the contact (owner_id). Defaults to the API key owner.",+ "Workspace member shown as \"Assign to\" in NinjaPipe (assigned_to).": "Workspace member shown as \"Assign to\" in NinjaPipe (assigned_to).","What to do when a contact with this email already exists.": "What to do when a contact with this email already exists.",- "Select a contact.": "Select a contact.",- "Maximum number of records to return (1-100).": "Maximum number of records to return (1-100).",- "Search query string.": "Search query string.",- "Filter records by status.": "Filter records by status.",- "Filter by owner identifier.": "Filter by owner identifier.",- "Retrieve all contacts using pagination.": "Retrieve all contacts using pagination.",- "Page number when not using Return All.": "Page number when not using Return All.",- "Used as the unique key to decide create or update.": "Used as the unique key to decide create or update.",- "Turn ON to enable, OFF to disable.": "Turn ON to enable, OFF to disable.",- "Optional. Used only when enabling. Defaults to the contact's email.": "Optional. Used only when enabling. Defaults to the contact's email.",- "Select a company.": "Select a company.",- "Retrieve all companies using pagination.": "Retrieve all companies using pagination.",- "e.g. EUR, USD": "e.g. EUR, USD",+ "Deal value as a number.": "Deal value as a number.",+ "Workspace member who owns the deal (owner_id).": "Workspace member who owns the deal (owner_id).",+ "Payment Status.": "Payment Status.",+ "Priority.": "Priority.","Select a pipeline.": "Select a pipeline.",- "Select a deal.": "Select a deal.",- "Retrieve all deals using pagination.": "Retrieve all deals using pagination.",- "Product name.": "Product name.",- "Product SKU. Must be unique within your workspace.": "Product SKU. Must be unique within your workspace.",- "Product price.": "Product price.",- "Select a product.": "Select a product.",- "Retrieve all products using pagination.": "Retrieve all products using pagination.",- "Budget name.": "Budget name.",- "Total allocated budget amount. Must be greater than 0.": "Total allocated budget amount. Must be greater than 0.",- "Budget category.": "Budget category.",- "Budget period.": "Budget period.",- "Currency code, e.g. USD, EUR. Defaults to USD.": "Currency code, e.g. USD, EUR. Defaults to USD.",- "Budget status.": "Budget status.",- "Select a budget.": "Select a budget.",- "Total allocated budget amount. Must be greater than 0 if set.": "Total allocated budget amount. Must be greater than 0 if set.",- "Retrieve all budgets using pagination.": "Retrieve all budgets using pagination.",- "Description of the expense.": "Description of the expense.",- "Expense amount (positive number).": "Expense amount (positive number).",- "Expense category (e.g. Marketing, Travel).": "Expense category (e.g. Marketing, Travel).",- "Expense date.": "Expense date.",- "Project status.": "Project status.",- "Priority level.": "Priority level.",- "Optional list of team members (account IDs).": "Optional list of team members (account IDs).",- "Optional metadata (e.g. linked contact, custom fields).": "Optional metadata (e.g. linked contact, custom fields).",- "Select the project this task belongs to.": "Select the project this task belongs to.",- "Retrieve all projects using pagination.": "Retrieve all projects using pagination.",- "Task title.": "Task title.",+ "Stage (column) of the selected pipeline.": "Stage (column) of the selected pipeline.",+ "Item priority.": "Item priority.",+ "Workspace member responsible for the item.": "Workspace member responsible for the item.",+ "Company name shown on the card.": "Company name shown on the card.",+ "What this pipeline tracks.": "What this pipeline tracks.",+ "Stages in board order. Add at least one.": "Stages in board order. Add at least one.",+ "e.g. Active.": "e.g. Active.",+ "ISO currency code, e.g. EUR.": "ISO currency code, e.g. EUR.",+ "Select a project.": "Select a project.","Task status.": "Task status.",- "Account ID of the user to assign this task to.": "Account ID of the user to assign this task to.",- "Set to make this a subtask of another task in the same project.": "Set to make this a subtask of another task in the same project.",- "Additional task settings as a JSON object.": "Additional task settings as a JSON object.",- "Select a task. Pick the project first.": "Select a task. Pick the project first.",- "Move under another task in the same project.": "Move under another task in the same project.",- "Pass a parent task ID to fetch its subtasks. Empty string to fetch only root tasks.": "Pass a parent task ID to fetch its subtasks. Empty string to fetch only root tasks.",- "Required by NinjaPipe — what this pipeline tracks.": "Required by NinjaPipe — what this pipeline tracks.",- "Pipeline stages. Add at least one. Color must be a hex like #3b82f6.": "Pipeline stages. Add at least one. Color must be a hex like #3b82f6.",- "Retrieve all pipelines using pagination.": "Retrieve all pipelines using pagination.",- "Customer display name.": "Customer display name.",- "Defaults to ORD-<timestamp> if omitted.": "Defaults to ORD-<timestamp> if omitted.",- "Order status.": "Order status.",- "Payment status.": "Payment status.",- "Line items, currency, and custom fields. Example: {\"currency\":\"USD\",\"items\":[{\"name\":\"…\",\"price\":10}],\"custom_fields\":[]}.": "Line items, currency, and custom fields. Example: {\"currency\":\"USD\",\"items\":[{\"name\":\"…\",\"price\":10}],\"custom_fields\":[]}.",+ "Task priority.": "Task priority.",+ "Workspace member the task is assigned to.": "Workspace member the task is assigned to.",+ "Make this a subtask of another task in the same project.": "Make this a subtask of another task in the same project.",+ "Select a deal, or type to search.": "Select a deal, or type to search.","Select an order.": "Select an order.",- "Line items, currency, and custom fields.": "Line items, currency, and custom fields.",- "Retrieve all orders using pagination.": "Retrieve all orders using pagination.",+ "Select a product.": "Select a product.",+ "Select a task. Pick the project first.": "Select a task. Pick the project first.",+ "Text to search for.": "Text to search for.",+ "Only budgets with this status.": "Only budgets with this status.",+ "Field to sort by. Default: created_at.": "Field to sort by. Default: created_at.",+ "Default: desc.": "Default: desc.",+ "Records per page (1-100). Ignored when Return All is on.": "Records per page (1-100). Ignored when Return All is on.",+ "Page number to fetch (starts at 1). Ignored when Return All is on.": "Page number to fetch (starts at 1). Ignored when Return All is on.",+ "Follow every page (up to 5,000 records). Has More is true when the cap cut the list short.": "Follow every page (up to 5,000 records). Has More is true when the cap cut the list short.",+ "Only companies with this status.": "Only companies with this status.",+ "Only companies owned by this member (owner_id).": "Only companies owned by this member (owner_id).",+ "Only contacts with this status.": "Only contacts with this status.",+ "Only contacts owned by this member (owner_id).": "Only contacts owned by this member (owner_id).",+ "Only contacts assigned to this member (assigned_to).": "Only contacts assigned to this member (assigned_to).",+ "Only deals with this status.": "Only deals with this status.",+ "Only deals owned by this member (owner_id).": "Only deals owned by this member (owner_id).",+ "Only orders with this status.": "Only orders with this status.",+ "Only products with this status.": "Only products with this status.",+ "Only projects with this status, e.g. Planning or In Progress.": "Only projects with this status, e.g. Planning or In Progress.",+ "Only tasks with this status.": "Only tasks with this status.",+ "Only tasks with this priority.": "Only tasks with this priority.",+ "Only subtasks of this task.": "Only subtasks of this task.",+ "Default: created_at.": "Default: created_at.","The full HTTPS webhook URL from your Databin. Must point to your connected NinjaPipe host and contain /api/webhooks/.": "The full HTTPS webhook URL from your Databin. Must point to your connected NinjaPipe host and contain /api/webhooks/.","JSON object to send.": "JSON object to send.",- "The list UUID (must belong to your workspace).": "The list UUID (must belong to your workspace).",+ "On to enable, off to disable.": "On to enable, off to disable.",+ "Used only when enabling. Defaults to the contact's email.": "Used only when enabling. Defaults to the contact's email.",+ "Fields to empty on the record. A field you clear here must be left blank above.": "Fields to empty on the record. A field you clear here must be left blank above.",+ "Custom field values by field key. Keys you leave out keep their current value; set a key to an empty value to clear it.": "Custom field values by field key. Keys you leave out keep their current value; set a key to an empty value to clear it.",+ "Select the item (card) to update. Pick the pipeline first.": "Select the item (card) to update. Pick the pipeline first.",+ "Move the item to this stage. Leave empty to keep its stage.": "Move the item to this stage. Leave empty to keep its stage.",+ "Contact UUID from ai_search_contacts.": "Contact UUID from ai_search_contacts.",+ "Short note title.": "Short note title.",+ "Note text.": "Note text.",+ "Company name.": "Company name.",+ "Website URL.": "Website URL.",+ "Company email.": "Company email.",+ "Company phone.": "Company phone.",+ "Industry.": "Industry.",+ "Company status.": "Company status.",+ "Owner account_id from ai_list_workspace_members.": "Owner account_id from ai_list_workspace_members.",+ "Object of custom field keys to values, e.g. {\"industry_segment\": \"SMB\"}.": "Object of custom field keys to values, e.g. {\"industry_segment\": \"SMB\"}.",+ "First name.": "First name.",+ "Last name.": "Last name.",+ "Email address, unique per workspace.": "Email address, unique per workspace.",+ "Phone number.": "Phone number.",+ "Contact status, e.g. Active or Lead. Defaults to Active.": "Contact status, e.g. Active or Lead. Defaults to Active.",+ "Company UUID from ai_search_companies.": "Company UUID from ai_search_companies.",+ "Owner account_id from ai_list_workspace_members. Defaults to the API key owner.": "Owner account_id from ai_list_workspace_members. Defaults to the API key owner.",+ "Assignee account_id from ai_list_workspace_members.": "Assignee account_id from ai_list_workspace_members.",+ "Deal name.": "Deal name.",+ "Deal value as a plain number, e.g. 1500.": "Deal value as a plain number, e.g. 1500.",+ "Deal status. Default Open.": "Deal status. Default Open.",+ "Pipeline UUID from ai_list_pipelines.": "Pipeline UUID from ai_list_pipelines.",+ "Stage id of that pipeline, from ai_list_pipelines.": "Stage id of that pipeline, from ai_list_pipelines.",+ "Card title.": "Card title.",+ "Card details.": "Card details.",+ "Value as a plain number.": "Value as a plain number.",+ "Default medium.": "Default medium.",+ "account_id from ai_list_workspace_members.": "account_id from ai_list_workspace_members.",+ "YYYY-MM-DD.": "YYYY-MM-DD.",+ "Email shown on the card.": "Email shown on the card.",+ "Phone shown on the card.": "Phone shown on the card.",+ "Project UUID from ai_list_projects.": "Project UUID from ai_list_projects.",+ "Task title.": "Task title.",+ "Task details.": "Task details.",+ "Default To Do.": "Default To Do.",+ "Task UUID in the same project, to create a subtask.": "Task UUID in the same project, to create a subtask.",+ "NinjaPipe company UUID, from ai_search_companies.": "NinjaPipe company UUID, from ai_search_companies.",+ "NinjaPipe contact UUID, from ai_search_contacts or ai_search_companies.": "NinjaPipe contact UUID, from ai_search_contacts or ai_search_companies.",+ "NinjaPipe deal UUID, from ai_search_deals or ai_search_companies.": "NinjaPipe deal UUID, from ai_search_deals or ai_search_companies.",+ "Only this activity type, e.g. note or task.": "Only this activity type, e.g. note or task.",+ "Page number, starting at 1. Use nextPage from the previous result to continue.": "Page number, starting at 1. Use nextPage from the previous result to continue.",+ "Records per page, 1-100. Default 20.": "Records per page, 1-100. Default 20.",+ "Only items in this stage (stage id from ai_list_pipelines).": "Only items in this stage (stage id from ai_list_pipelines).",+ "Free text matched against project names.": "Free text matched against project names.",+ "Only projects with this status.": "Only projects with this status.",+ "Free text matched against the company name and other text fields.": "Free text matched against the company name and other text fields.",+ "Only companies owned by a workspace member account_id from ai_list_workspace_members.": "Only companies owned by a workspace member account_id from ai_list_workspace_members.",+ "Sort field. Default created_at. One of: created_at, updated_at, name.": "Sort field. Default created_at. One of: created_at, updated_at, name.",+ "asc or desc. Default desc.": "asc or desc. Default desc.",+ "Free text matched against name, email and phone. Not an exact match: check the email of each result.": "Free text matched against name, email and phone. Not an exact match: check the email of each result.",+ "Only contacts with this status, e.g. Active or Lead.": "Only contacts with this status, e.g. Active or Lead.",+ "Only contacts owned by a workspace member account_id from ai_list_workspace_members.": "Only contacts owned by a workspace member account_id from ai_list_workspace_members.",+ "Only contacts assigned to a workspace member account_id from ai_list_workspace_members.": "Only contacts assigned to a workspace member account_id from ai_list_workspace_members.",+ "Sort field. Default created_at. One of: created_at, updated_at, first_name, last_name, email.": "Sort field. Default created_at. One of: created_at, updated_at, first_name, last_name, email.",+ "Free text matched against the deal name.": "Free text matched against the deal name.",+ "Only deals owned by a workspace member account_id from ai_list_workspace_members.": "Only deals owned by a workspace member account_id from ai_list_workspace_members.",+ "Sort field. Default created_at. One of: created_at, updated_at, name, value, status.": "Sort field. Default created_at. One of: created_at, updated_at, name, value, status.",+ "New name.": "New name.",+ "New website URL.": "New website URL.",+ "New email.": "New email.",+ "New phone.": "New phone.",+ "New industry.": "New industry.",+ "New status.": "New status.",+ "Object of custom field keys to values, e.g. {\"industry_segment\": \"SMB\"}. Merged into the existing custom fields; a key set to \"\" or null is removed.": "Object of custom field keys to values, e.g. {\"industry_segment\": \"SMB\"}. Merged into the existing custom fields; a key set to \"\" or null is removed.",+ "Field names to set to empty. Allowed: website, email, phone, industry. Do not also give a value for a cleared field.": "Field names to set to empty. Allowed: website, email, phone, industry. Do not also give a value for a cleared field.",+ "New first name.": "New first name.",+ "New last name.": "New last name.",+ "New email, unique per workspace.": "New email, unique per workspace.",+ "New phone number.": "New phone number.",+ "New status, e.g. Active or Lead.": "New status, e.g. Active or Lead.",+ "Field names to set to empty. Allowed: first_name, last_name, phone, company_id, assigned_to. Do not also give a value for a cleared field.": "Field names to set to empty. Allowed: first_name, last_name, phone, company_id, assigned_to. Do not also give a value for a cleared field.",+ "Deal UUID from ai_search_deals.": "Deal UUID from ai_search_deals.",+ "New deal name.": "New deal name.",+ "New value as a plain number.": "New value as a plain number.",+ "Field names to set to empty. Allowed: contact_id, company_id. Do not also give a value for a cleared field.": "Field names to set to empty. Allowed: contact_id, company_id. Do not also give a value for a cleared field.",+ "Item UUID from ai_list_pipeline_items.": "Item UUID from ai_list_pipeline_items.",+ "Move the item to this stage id.": "Move the item to this stage id.",+ "New title.": "New title.",+ "New details.": "New details.",+ "New value.": "New value.",+ "New priority.": "New priority.",+ "Field names to set to empty. Allowed: description, assigned_to, due_date, email, phone, company. Do not also give a value for a cleared field.": "Field names to set to empty. Allowed: description, assigned_to, due_date, email, phone, company. Do not also give a value for a cleared field.",+ "Task UUID from ai_list_tasks.": "Task UUID from ai_list_tasks.",+ "Field names to set to empty. Allowed: description, assignee_id, due_date, parent_id. Do not also give a value for a cleared field.": "Field names to set to empty. Allowed: description, assignee_id, due_date, parent_id. Do not also give a value for a cleared field.","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.",- "Germany": "Germany",- "Austria": "Austria",- "Switzerland": "Switzerland",- "Belgium": "Belgium",- "Netherlands": "Netherlands",- "Luxembourg": "Luxembourg",- "France": "France",- "Italy": "Italy",- "Spain": "Spain",- "Portugal": "Portugal",- "Poland": "Poland",- "Hungary": "Hungary",- "United Kingdom": "United Kingdom",- "United States": "United States",- "Canada": "Canada",- "Throw Error": "Throw Error",- "Skip": "Skip",- "Get Existing": "Get Existing",- "Update Existing": "Update Existing","Marketing": "Marketing","Sales": "Sales","Operations": "Operations",@@ -290,30 +393,66 @@"Active": "Active","Inactive": "Inactive","Completed": "Completed",- "Planning": "Planning",+ "Fail the step": "Fail the step",+ "Skip": "Skip",+ "Return the existing contact": "Return the existing contact",+ "Update the existing contact": "Update the existing contact",+ "Open": "Open","In Progress": "In Progress",- "On Hold": "On Hold",- "Cancelled": "Cancelled",- "High": "High",- "Medium": "Medium",- "Low": "Low",- "To Do": "To Do",- "Done": "Done",- "Order Index": "Order Index",- "Created At": "Created At",- "Updated At": "Updated At",- "Ascending": "Ascending",- "Descending": "Descending",- "Contacts": "Contacts",- "Deals": "Deals",- "General": "General",+ "Won": "Won",+ "Lost": "Lost","Processing": "Processing","Shipped": "Shipped","Delivered": "Delivered",+ "Cancelled": "Cancelled","Pending": "Pending","Paid": "Paid","Refunded": "Refunded","Failed": "Failed",+ "High": "High",+ "Medium": "Medium",+ "Low": "Low",+ "low": "low",+ "medium": "medium",+ "high": "high",+ "Contacts": "Contacts",+ "Deals": "Deals",+ "General": "General",+ "Planning": "Planning",+ "On Hold": "On Hold",+ "To Do": "To Do",+ "Done": "Done",+ "created_at": "created_at",+ "updated_at": "updated_at",+ "name": "name",+ "desc": "desc",+ "asc": "asc",+ "first_name": "first_name",+ "last_name": "last_name",+ "email": "email",+ "status": "status",+ "value": "value",+ "order_date": "order_date",+ "total_amount": "total_amount",+ "price": "price",+ "due_date": "due_date",+ "title": "title",+ "priority": "priority",+ "order_index": "order_index",+ "contacts": "contacts",+ "deals": "deals",+ "general": "general",+ "Parent Task": "Parent Task",+ "website": "website",+ "phone": "phone",+ "industry": "industry",+ "company_id": "company_id",+ "assigned_to": "assigned_to",+ "contact_id": "contact_id",+ "description": "description",+ "company": "company",+ "assignee_id": "assignee_id",+ "parent_id": "parent_id","GET": "GET","POST": "POST","PATCH": "PATCH",@@ -322,20 +461,20 @@"HEAD": "HEAD","Request": "Request","Data to send": "Data to send",- "New Contact": "New Contact","New Company": "New Company",+ "New Contact": "New Contact","New Deal": "New Deal",- "New Task": "New Task",- "New or Updated Contact": "New or Updated Contact","New or Updated Company": "New or Updated Company",+ "New or Updated Contact": "New or Updated Contact","New or Updated Deal": "New or Updated Deal","New or Updated Task": "New or Updated Task",- "Triggers when a new contact is created.": "Triggers when a new contact is created.",- "Triggers when a new company is created.": "Triggers when a new company is created.",- "Triggers when a new deal is created.": "Triggers when a new deal is created.",- "Triggers when a new task is created in the selected project.": "Triggers when a new task is created in the selected project.",- "Triggers when a contact is created or updated.": "Triggers when a contact is created or updated.",+ "New Task": "New Task",+ "Triggers when a company is created.": "Triggers when a company is created.",+ "Triggers when a contact is created.": "Triggers when a contact is created.",+ "Triggers when a deal is created.": "Triggers when a deal is created.","Triggers when a company is created or updated.": "Triggers when a company is created or updated.",+ "Triggers when a contact is created or updated.": "Triggers when a contact is created or updated.","Triggers when a deal is created or updated.": "Triggers when a deal is created or updated.",- "Triggers when a task in the selected project is created or updated.": "Triggers when a task in the selected project is created or updated."+ "Triggers when a task in the selected project is created or updated.": "Triggers when a task in the selected project is created or updated.",+ "Triggers when a task is created in the selected project.": "Triggers when a task is created in the selected project."}\ No newline at end of filediff --git a/packages/pieces/community/ninjapipe/src/index.ts b/packages/pieces/community/ninjapipe/src/index.tsindex 83f428ef64d..00a43621ed7 100644--- a/packages/pieces/community/ninjapipe/src/index.ts+++ b/packages/pieces/community/ninjapipe/src/index.ts@@ -1,218 +1,188 @@-import { createPiece, PieceAuth, Property } from '@activepieces/pieces-framework';-import { createCustomApiCallAction } from '@activepieces/pieces-common';-import { PieceCategory } from '@activepieces/pieces-framework';-import { httpClient, HttpMethod, AuthenticationType } from '@activepieces/pieces-common';--// Actions-import { createContact } from './lib/actions/create-contact';-import { updateContact } from './lib/actions/update-contact';-import { getContact } from './lib/actions/get-contact';-import { listContacts } from './lib/actions/list-contacts';-import { deleteContact } from './lib/actions/delete-contact';-import { upsertContact } from './lib/actions/upsert-contact';-import { toggleClientPortal } from './lib/actions/toggle-client-portal';+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from './lib/auth';+import { addContactNote } from './lib/actions/add-contact-note';+import { addToList } from './lib/actions/add-to-list';+import { createBudgetExpense } from './lib/actions/create-budget-expense';+import { createBudget } from './lib/actions/create-budget';import { createCompany } from './lib/actions/create-company';-import { updateCompany } from './lib/actions/update-company';-import { getCompany } from './lib/actions/get-company';-import { listCompanies } from './lib/actions/list-companies';-import { deleteCompany } from './lib/actions/delete-company';+import { createContact } from './lib/actions/create-contact';+import { ninjapipeCustomApiCall } from './lib/actions/custom-api-call';import { createDeal } from './lib/actions/create-deal';-import { updateDeal } from './lib/actions/update-deal';-import { getDeal } from './lib/actions/get-deal';-import { listDeals } from './lib/actions/list-deals';-import { deleteDeal } from './lib/actions/delete-deal';+import { createOrder } from './lib/actions/create-order';+import { createPipelineItem } from './lib/actions/create-pipeline-item';+import { createPipeline } from './lib/actions/create-pipeline';import { createProduct } from './lib/actions/create-product';-import { updateProduct } from './lib/actions/update-product';-import { getProduct } from './lib/actions/get-product';-import { listProducts } from './lib/actions/list-products';-import { deleteProduct } from './lib/actions/delete-product';-import { createBudget } from './lib/actions/create-budget';-import { updateBudget } from './lib/actions/update-budget';-import { getBudget } from './lib/actions/get-budget';-import { listBudgets } from './lib/actions/list-budgets';-import { deleteBudget } from './lib/actions/delete-budget';-import { createBudgetExpense } from './lib/actions/create-budget-expense';import { createProject } from './lib/actions/create-project';-import { updateProject } from './lib/actions/update-project';-import { getProject } from './lib/actions/get-project';-import { listProjects } from './lib/actions/list-projects';-import { deleteProject } from './lib/actions/delete-project';import { createTask } from './lib/actions/create-task';-import { updateTask } from './lib/actions/update-task';-import { getTask } from './lib/actions/get-task';-import { listTasks } from './lib/actions/list-tasks';-import { deleteTask } from './lib/actions/delete-task';-import { createPipeline } from './lib/actions/create-pipeline';-import { updatePipeline } from './lib/actions/update-pipeline';-import { getPipeline } from './lib/actions/get-pipeline';-import { listPipelines } from './lib/actions/list-pipelines';+import { deleteBudget } from './lib/actions/delete-budget';+import { deleteCompany } from './lib/actions/delete-company';+import { deleteContact } from './lib/actions/delete-contact';+import { deleteDeal } from './lib/actions/delete-deal';+import { deleteOrder } from './lib/actions/delete-order';import { deletePipeline } from './lib/actions/delete-pipeline';-import { createOrder } from './lib/actions/create-order';-import { updateOrder } from './lib/actions/update-order';+import { deleteProduct } from './lib/actions/delete-product';+import { deleteProject } from './lib/actions/delete-project';+import { deleteTask } from './lib/actions/delete-task';+import { getBudget } from './lib/actions/get-budget';+import { getCompany } from './lib/actions/get-company';+import { getContact } from './lib/actions/get-contact';+import { getDeal } from './lib/actions/get-deal';import { getOrder } from './lib/actions/get-order';+import { getPipeline } from './lib/actions/get-pipeline';+import { getProduct } from './lib/actions/get-product';+import { getProject } from './lib/actions/get-project';+import { getTask } from './lib/actions/get-task';+import { listBudgets } from './lib/actions/list-budgets';+import { listCompanies } from './lib/actions/list-companies';+import { listContacts } from './lib/actions/list-contacts';+import { listDeals } from './lib/actions/list-deals';import { listOrders } from './lib/actions/list-orders';-import { deleteOrder } from './lib/actions/delete-order';+import { listPipelines } from './lib/actions/list-pipelines';+import { listProducts } from './lib/actions/list-products';+import { listProjects } from './lib/actions/list-projects';+import { listTasks } from './lib/actions/list-tasks';import { sendToDatabin } from './lib/actions/send-to-databin';-import { addToList } from './lib/actions/add-to-list';--// Triggers-import { newContact } from './lib/triggers/new-contact';+import { toggleClientPortal } from './lib/actions/toggle-client-portal';+import { updateBudget } from './lib/actions/update-budget';+import { updateCompany } from './lib/actions/update-company';+import { updateContact } from './lib/actions/update-contact';+import { updateDeal } from './lib/actions/update-deal';+import { updateOrder } from './lib/actions/update-order';+import { updatePipelineItem } from './lib/actions/update-pipeline-item';+import { updatePipeline } from './lib/actions/update-pipeline';+import { updateProduct } from './lib/actions/update-product';+import { updateProject } from './lib/actions/update-project';+import { updateTask } from './lib/actions/update-task';+import { upsertContact } from './lib/actions/upsert-contact';+import { aiAddContactNote } from './lib/actions/ai/add-contact-note';+import { aiCreateCompany } from './lib/actions/ai/create-company';+import { aiCreateContact } from './lib/actions/ai/create-contact';+import { aiCreateDeal } from './lib/actions/ai/create-deal';+import { aiCreatePipelineItem } from './lib/actions/ai/create-pipeline-item';+import { aiCreateTask } from './lib/actions/ai/create-task';+import { aiGetCompany } from './lib/actions/ai/get-company';+import { aiGetContact } from './lib/actions/ai/get-contact';+import { aiGetDeal } from './lib/actions/ai/get-deal';+import { aiListContactActivities } from './lib/actions/ai/list-contact-activities';+import { aiListPipelineItems } from './lib/actions/ai/list-pipeline-items';+import { aiListPipelines } from './lib/actions/ai/list-pipelines';+import { aiListProjects } from './lib/actions/ai/list-projects';+import { aiListTasks } from './lib/actions/ai/list-tasks';+import { aiListWorkspaceMembers } from './lib/actions/ai/list-workspace-members';+import { aiSearchCompanies } from './lib/actions/ai/search-companies';+import { aiSearchContacts } from './lib/actions/ai/search-contacts';+import { aiSearchDeals } from './lib/actions/ai/search-deals';+import { aiUpdateCompany } from './lib/actions/ai/update-company';+import { aiUpdateContact } from './lib/actions/ai/update-contact';+import { aiUpdateDeal } from './lib/actions/ai/update-deal';+import { aiUpdatePipelineItem } from './lib/actions/ai/update-pipeline-item';+import { aiUpdateTask } from './lib/actions/ai/update-task';import { newCompany } from './lib/triggers/new-company';+import { newContact } from './lib/triggers/new-contact';import { newDeal } from './lib/triggers/new-deal';-import { newTask } from './lib/triggers/new-task';-import { newOrUpdatedContact } from './lib/triggers/new-or-updated-contact';import { newOrUpdatedCompany } from './lib/triggers/new-or-updated-company';+import { newOrUpdatedContact } from './lib/triggers/new-or-updated-contact';import { newOrUpdatedDeal } from './lib/triggers/new-or-updated-deal';import { newOrUpdatedTask } from './lib/triggers/new-or-updated-task';--export const ninjapipeAuth = PieceAuth.CustomAuth({- displayName: 'NinjaPipe API Connection',- required: true,- description: `Connect to your NinjaPipe workspace.--1. Log in to NinjaPipe and open **Workspace Settings > NinjaPipe API**.-2. Copy your **API key** (starts with \`np_\`).-3. Enter your workspace **API Base URL**. The default is \`https://www.ninjapipe.app/api\`.`,- props: {- base_url: Property.ShortText({- displayName: 'API Base URL',- description: 'Your workspace API base URL (e.g. https://www.ninjapipe.app/api).',- required: true,- defaultValue: 'https://www.ninjapipe.app/api',- }),- api_key: PieceAuth.SecretText({- displayName: 'API Key',- description: 'Your workspace API key from NinjaPipe Settings > API.',- required: true,- }),- },- validate: async ({ auth }) => {- let parsed: URL;- try {- parsed = new URL(auth.base_url);- } catch {- return { valid: false, error: 'Base URL is not a valid URL.' };- }- if (parsed.protocol !== 'https:') {- return { valid: false, error: 'Base URL must use https://.' };- }- const host = parsed.hostname.toLowerCase();- if (- host === 'localhost' ||- host === '0.0.0.0' ||- host.endsWith('.localhost') ||- /^127\./.test(host) ||- /^10\./.test(host) ||- /^192\.168\./.test(host) ||- /^172\.(1[6-9]|2\d|3[01])\./.test(host) ||- host === '169.254.169.254' ||- /^169\.254\./.test(host) ||- /^fc00:/i.test(host) ||- /^fe80:/i.test(host) ||- host === '::1'- ) {- return { valid: false, error: `Base URL host "${host}" is not allowed (loopback, private, or metadata IP).` };- }- try {- await httpClient.sendRequest({- method: HttpMethod.GET,- url: `${auth.base_url.replace(/\/+$/, '')}/contacts`,- authentication: {- type: AuthenticationType.BEARER_TOKEN,- token: auth.api_key,- },- queryParams: { limit: '1' },- });- return { valid: true };- } catch (e) {- const err = e as { response?: { status?: number }; status?: number; message?: string };- const status = err.response?.status ?? err.status;- if (status === 401 || status === 403) {- return { valid: false, error: 'API key was rejected. Check the key in NinjaPipe Settings > API.' };- }- if (status === 404) {- return { valid: false, error: 'Base URL is reachable but /contacts returned 404. Check the Base URL path.' };- }- return { valid: false, error: `Could not connect to NinjaPipe (${status ?? err.message ?? 'unknown error'}). Check the Base URL and API Key.` };- }- },-});+import { newTask } from './lib/triggers/new-task';export const ninjapipe = createPiece({displayName: 'NinjaPipe',- description: 'NinjaPipe CRM integration with contacts, companies, deals, tasks (under projects), pipelines, products, budgets, projects, orders, lists, and Databin webhook delivery.',- minimumSupportedRelease: '0.36.1',+ description: 'NinjaPipe CRM integration with contacts, companies, deals, tasks (under projects), pipelines and pipeline items, products, budgets, projects, orders, lists, and Databin webhook delivery.',+ minimumSupportedRelease: '0.88.2',logoUrl: 'https://cdn.activepieces.com/pieces/ninjapipe.png',categories: [PieceCategory.SALES_AND_CRM],auth: ninjapipeAuth,- authors: ['hemmilicious'],+ authors: ['hemmilicious', 'OdaiAhmed99'],actions: [- createContact,- updateContact,- getContact,- listContacts,- deleteContact,- upsertContact,- toggleClientPortal,+ addContactNote,+ addToList,+ createBudgetExpense,+ createBudget,createCompany,- updateCompany,- getCompany,- listCompanies,- deleteCompany,+ createContact,createDeal,- updateDeal,- getDeal,- listDeals,- deleteDeal,+ createOrder,+ createPipelineItem,+ createPipeline,createProduct,- updateProduct,- getProduct,- listProducts,- deleteProduct,- createBudget,- updateBudget,- getBudget,- listBudgets,- deleteBudget,- createBudgetExpense,createProject,- updateProject,- getProject,- listProjects,- deleteProject,createTask,- updateTask,- getTask,- listTasks,- deleteTask,- createPipeline,- updatePipeline,- getPipeline,- listPipelines,+ deleteBudget,+ deleteCompany,+ deleteContact,+ deleteDeal,+ deleteOrder,deletePipeline,- createOrder,- updateOrder,+ deleteProduct,+ deleteProject,+ deleteTask,+ getBudget,+ getCompany,+ getContact,+ getDeal,getOrder,+ getPipeline,+ getProduct,+ getProject,+ getTask,+ listBudgets,+ listCompanies,+ listContacts,+ listDeals,listOrders,- deleteOrder,+ listPipelines,+ listProducts,+ listProjects,+ listTasks,sendToDatabin,- addToList,- createCustomApiCallAction({- baseUrl: (auth) => (auth?.props?.base_url as string) ?? '',- auth: ninjapipeAuth,- authMapping: async (auth) => ({- Authorization: `Bearer ${auth?.props?.api_key as string}`,- }),- }),+ toggleClientPortal,+ updateBudget,+ updateCompany,+ updateContact,+ updateDeal,+ updateOrder,+ updatePipelineItem,+ updatePipeline,+ updateProduct,+ updateProject,+ updateTask,+ upsertContact,+ aiAddContactNote,+ aiCreateCompany,+ aiCreateContact,+ aiCreateDeal,+ aiCreatePipelineItem,+ aiCreateTask,+ aiGetCompany,+ aiGetContact,+ aiGetDeal,+ aiListContactActivities,+ aiListPipelineItems,+ aiListPipelines,+ aiListProjects,+ aiListTasks,+ aiListWorkspaceMembers,+ aiSearchCompanies,+ aiSearchContacts,+ aiSearchDeals,+ aiUpdateCompany,+ aiUpdateContact,+ aiUpdateDeal,+ aiUpdatePipelineItem,+ aiUpdateTask,+ ninjapipeCustomApiCall,],triggers: [- newContact,newCompany,+ newContact,newDeal,- newTask,- newOrUpdatedContact,newOrUpdatedCompany,+ newOrUpdatedContact,newOrUpdatedDeal,newOrUpdatedTask,+ newTask,],});++export { ninjapipeAuth };diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/add-contact-note.ts b/packages/pieces/community/ninjapipe/src/lib/actions/add-contact-note.tsnew file mode 100644index 00000000000..989e194a25d--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/actions/add-contact-note.ts@@ -0,0 +1,34 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeFields } from '../common/fields';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';++export const addContactNote = createAction({+ auth: ninjapipeAuth,+ name: 'add_contact_note',+ classification: 'WRITE',+ displayName: 'Add Note to Contact',+ description: "Adds a note to a contact's activity timeline.",+ audience: 'human',+ aiMetadata: { description: "Add a note to a NinjaPipe contact's activity timeline. Not idempotent: each call adds another note.", idempotent: false },+ outputSchema: ninjapipeSchemas.activity,+ props: {+ contactId: ninjapipeProps.contactRequired(),+ title: Property.ShortText({ displayName: 'Title', required: true }),+ content: Property.LongText({ displayName: 'Content', required: false }),+ date: Property.DateTime({ displayName: 'Date', description: 'When the note happened. Defaults to now.', required: false }),+ },+ async run(context) {+ const p = context.propsValue;+ return ninjapipeClient.sendRecord({+ auth: ninjapipeClient.readAuth(context.auth),+ method: HttpMethod.POST,+ path: `/contacts/${ninjapipeClient.pathId({ value: p.contactId, field: 'Contact' })}/activities`,+ body: ninjapipeFields.compact({ type: 'note', title: p.title, content: p.content, date: p.date }),+ operation: 'add contact note',+ });+ },+});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/add-to-list.ts b/packages/pieces/community/ninjapipe/src/lib/actions/add-to-list.tsindex 9410a5f5557..f40ac7bc7dd 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/add-to-list.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/add-to-list.ts@@ -1,43 +1,40 @@-import { createAction, Property } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, flattenCustomFields, getAuth, ninjapipeCommon } from '../common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const addToList = createAction({auth: ninjapipeAuth,name: 'add_to_list',classification: 'WRITE',displayName: 'Add to List',- description: 'Adds a contact OR a company to a CRM list. The list type must match (Contact lists accept contacts, Company lists accept companies). Idempotent — returns already_in_list:true if already present.',+ description: 'Adds a contact or a company to a CRM list. Contact lists take contacts, company lists take companies.',audience: 'both',- aiMetadata: { description: 'Add a single member to a CRM list by list ID — provide exactly one of a contact ID or a company ID (not both, not neither), and the member type must match the list type. Idempotent — adding a member already on the list is a no-op rather than an error.', idempotent: true },+ aiMetadata: {+ description: 'Add one member to a NinjaPipe CRM list by list ID: give exactly one of contactId or companyId, matching the list type. Safe to retry: adding a member already on the list returns already_in_list: true.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.listMember,props: {- listId: Property.ShortText({- displayName: 'List ID',- description: 'The list UUID (must belong to your workspace).',- required: true,- }),- contactId: ninjapipeCommon.contactDropdown,- companyId: ninjapipeCommon.companyDropdown,+ listId: Property.ShortText({ displayName: 'List ID', description: 'The list UUID (open the list in NinjaPipe and copy it from the URL).', required: true }),+ contactId: ninjapipeProps.contactOptional(),+ companyId: ninjapipeProps.companyOptional(),},async run(context) {- const auth = getAuth(context);- const { listId, contactId, companyId } = context.propsValue;- if (!contactId && !companyId) {- throw new Error('Provide either Contact or Company.');- }- if (contactId && companyId) {- throw new Error('Provide only one: Contact or Company. Lists are typed.');+ const p = context.propsValue;+ const contactId = typeof p.contactId === 'string' ? p.contactId.trim() : '';+ const companyId = typeof p.companyId === 'string' ? p.companyId.trim() : '';+ if ((contactId === '') === (companyId === '')) {+ throw new Error('Choose exactly one of Contact or Company.');}- const body: Record<string, unknown> = {};- if (contactId) body['contact_id'] = contactId;- if (companyId) body['company_id'] = companyId;- const response = await ninjapipeApiCall<Record<string, unknown>>({- auth,+ return ninjapipeClient.sendRecord({+ auth: ninjapipeClient.readAuth(context.auth),method: HttpMethod.POST,- path: `/lists/${encodeURIComponent(String(listId))}/members`,- body,+ path: `/lists/${ninjapipeClient.pathId({ value: p.listId, field: 'List ID' })}/members`,+ body: contactId !== '' ? { contact_id: contactId } : { company_id: companyId },+ operation: 'add to list',});- return flattenCustomFields(response.body);},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/ai/add-contact-note.ts b/packages/pieces/community/ninjapipe/src/lib/actions/ai/add-contact-note.tsnew file mode 100644index 00000000000..f2030e45677--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/actions/ai/add-contact-note.ts@@ -0,0 +1,37 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../../auth';+import { ninjapipeAiProps } from '../../common/ai-props';+import { ninjapipeClient } from '../../common/client';+import { ninjapipeSchemas } from '../../output-schemas';+import { ninjapipeFields } from '../../common/fields';++export const aiAddContactNote = createAction({+ auth: ninjapipeAuth,+ name: 'ai_add_contact_note',+ classification: 'WRITE',+ displayName: 'Add Note to Contact',+ description: "Adds a note to a contact's timeline.",+ audience: 'ai',+ aiMetadata: {+ description:+ "Add a note (title plus optional content text) to a NinjaPipe contact's activity timeline by contact_id. Not idempotent: each call adds another note.",+ idempotent: false,+ },+ outputSchema: ninjapipeSchemas.activity,+ props: {+ contact_id: ninjapipeAiProps.id({ displayName: 'Contact ID', description: 'Contact UUID from ai_search_contacts.' }),+ title: ninjapipeAiProps.text({ displayName: 'Title', description: 'Short note title.', required: true }),+ content: ninjapipeAiProps.text({ displayName: 'Content', description: 'Note text.' }),+ },+ async run(context) {+ const p = context.propsValue;+ return ninjapipeClient.sendRecord({+ auth: ninjapipeClient.readAuth(context.auth),+ method: HttpMethod.POST,+ path: `/contacts/${ninjapipeClient.pathId({ value: p.contact_id, field: 'Contact ID' })}/activities`,+ body: ninjapipeFields.compact({ type: 'note', title: p.title, content: p.content }),+ operation: 'add contact note',+ });+ },+});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/ai/create-company.ts b/packages/pieces/community/ninjapipe/src/lib/actions/ai/create-company.tsnew file mode 100644index 00000000000..c1254f5e19a--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/actions/ai/create-company.ts@@ -0,0 +1,46 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../../auth';+import { ninjapipeAiProps } from '../../common/ai-props';+import { ninjapipeClient } from '../../common/client';+import { ninjapipeFields } from '../../common/fields';+import { ninjapipeSchemas } from '../../output-schemas';++export const aiCreateCompany = createAction({+ auth: ninjapipeAuth,+ name: 'ai_create_company',+ classification: 'WRITE',+ displayName: 'Create Company',+ description: 'Creates a company.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Create a NinjaPipe company (organisation). Only name is required. NinjaPipe does not block duplicate names, so search with ai_search_companies first when the company may exist. Not idempotent.',+ idempotent: false,+ },+ outputSchema: ninjapipeSchemas.company,+ props: {+ name: ninjapipeAiProps.text({ displayName: 'Name', description: 'Company name.', required: true }),+ website: ninjapipeAiProps.text({ displayName: 'Website', description: 'Website URL.' }),+ email: ninjapipeAiProps.text({ displayName: 'Email', description: 'Company email.' }),+ phone: ninjapipeAiProps.text({ displayName: 'Phone', description: 'Company phone.' }),+ industry: ninjapipeAiProps.text({ displayName: 'Industry', description: 'Industry.' }),+ status: ninjapipeAiProps.text({ displayName: 'Status', description: 'Company status.' }),+ owner_id: ninjapipeAiProps.optionalId({ displayName: 'Owner ID', description: 'Owner account_id from ai_list_workspace_members.' }),+ fields: ninjapipeAiProps.customFields({ update: false }),+ },+ async run(context) {+ const p = context.propsValue;+ const body = ninjapipeFields.compact({+ name: p.name,+ website: p.website,+ email: p.email,+ phone: p.phone,+ industry: p.industry,+ status: p.status,+ owner_id: p.owner_id,+ fields: ninjapipeFields.readCustomFields(p.fields),+ });+ return ninjapipeClient.sendRecord({ auth: ninjapipeClient.readAuth(context.auth), method: HttpMethod.POST, path: '/companies', body, operation: 'create company' });+ },+});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/ai/create-contact.ts b/packages/pieces/community/ninjapipe/src/lib/actions/ai/create-contact.tsnew file mode 100644index 00000000000..08d317df928--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/actions/ai/create-contact.ts@@ -0,0 +1,63 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../../auth';+import { ninjapipeAiProps } from '../../common/ai-props';+import { NinjaPipeApiError, ninjapipeClient } from '../../common/client';+import { ninjapipeFields } from '../../common/fields';+import { ninjapipeRecords } from '../../common/records';+import { ninjapipeSchemas } from '../../output-schemas';++export const aiCreateContact = createAction({+ auth: ninjapipeAuth,+ name: 'ai_create_contact',+ classification: 'WRITE',+ displayName: 'Create Contact',+ description: 'Creates a contact.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Create a new NinjaPipe contact. NinjaPipe allows one contact per email: if the email already exists the step fails and the error names the existing contact_id, so update that contact instead. Use upsert_contact when you want create-or-update in one call. Not idempotent.',+ idempotent: false,+ },+ outputSchema: ninjapipeSchemas.contact,+ props: {+ first_name: ninjapipeAiProps.text({ displayName: 'First Name', description: 'First name.' }),+ last_name: ninjapipeAiProps.text({ displayName: 'Last Name', description: 'Last name.' }),+ email: ninjapipeAiProps.text({ displayName: 'Email', description: 'Email address, unique per workspace.' }),+ phone: ninjapipeAiProps.text({ displayName: 'Phone', description: 'Phone number.' }),+ status: ninjapipeAiProps.text({ displayName: 'Status', description: 'Contact status, e.g. Active or Lead. Defaults to Active.' }),+ company_id: ninjapipeAiProps.optionalId({ displayName: 'Company ID', description: 'Company UUID from ai_search_companies.' }),+ owner_id: ninjapipeAiProps.optionalId({ displayName: 'Owner ID', description: 'Owner account_id from ai_list_workspace_members. Defaults to the API key owner.' }),+ assigned_to: ninjapipeAiProps.optionalId({ displayName: 'Assigned To', description: 'Assignee account_id from ai_list_workspace_members.' }),+ fields: ninjapipeAiProps.customFields({ update: false }),+ },+ async run(context) {+ const auth = ninjapipeClient.readAuth(context.auth);+ const p = context.propsValue;+ const body = ninjapipeFields.compact({+ first_name: p.first_name,+ last_name: p.last_name,+ email: p.email,+ phone: p.phone,+ status: p.status,+ company_id: p.company_id,+ owner_id: p.owner_id,+ assigned_to: p.assigned_to,+ fields: ninjapipeFields.readCustomFields(p.fields),+ });+ if (Object.keys(body).length === 0) throw new Error('Give at least a name or an email for the contact.');+ try {+ return await ninjapipeClient.sendRecord({ auth, method: HttpMethod.POST, path: '/contacts', body, operation: 'create contact' });+ } catch (error) {+ if (!(error instanceof NinjaPipeApiError) || error.status !== 409 || typeof p.email !== 'string') throw error;+ const existing = await ninjapipeRecords.findContactByEmail({ auth, email: p.email });+ if (!existing) throw error;+ throw new NinjaPipeApiError({+ message: `A contact with email ${p.email} already exists (contact_id ${String(existing['id'])}). Update that contact instead of creating a new one.`,+ status: 409,+ code: error.code,+ responseBody: error.responseBody,+ });+ }+ },+});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/ai/create-deal.ts b/packages/pieces/community/ninjapipe/src/lib/actions/ai/create-deal.tsnew file mode 100644index 00000000000..e060dcc2add--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/actions/ai/create-deal.ts@@ -0,0 +1,44 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../../auth';+import { ninjapipeAiProps } from '../../common/ai-props';+import { ninjapipeClient } from '../../common/client';+import { ninjapipeFields } from '../../common/fields';+import { ninjapipeSchemas } from '../../output-schemas';++export const aiCreateDeal = createAction({+ auth: ninjapipeAuth,+ name: 'ai_create_deal',+ classification: 'WRITE',+ displayName: 'Create Deal',+ description: 'Creates a deal.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Create a NinjaPipe deal with a name and optional value, status (Open, In Progress, Won, Lost), owner_id, contact_id and company_id. Not idempotent: each call creates another deal.',+ idempotent: false,+ },+ outputSchema: ninjapipeSchemas.deal,+ props: {+ name: ninjapipeAiProps.text({ displayName: 'Name', description: 'Deal name.', required: true }),+ value: ninjapipeAiProps.number({ displayName: 'Value', description: 'Deal value as a plain number, e.g. 1500.' }),+ status: ninjapipeAiProps.choice({ displayName: 'Status', description: 'Deal status. Default Open.', values: ['Open', 'In Progress', 'Won', 'Lost'] }),+ owner_id: ninjapipeAiProps.optionalId({ displayName: 'Owner ID', description: 'Owner account_id from ai_list_workspace_members.' }),+ contact_id: ninjapipeAiProps.optionalId({ displayName: 'Contact ID', description: 'Contact UUID from ai_search_contacts.' }),+ company_id: ninjapipeAiProps.optionalId({ displayName: 'Company ID', description: 'Company UUID from ai_search_companies.' }),+ fields: ninjapipeAiProps.customFields({ update: false }),+ },+ async run(context) {+ const p = context.propsValue;+ const body = ninjapipeFields.compact({+ name: p.name,+ value: ninjapipeFields.toNumber({ value: p.value, field: 'Value' }),+ status: p.status,+ owner_id: p.owner_id,+ contact_id: p.contact_id,+ company_id: p.company_id,+ fields: ninjapipeFields.readCustomFields(p.fields),+ });+ return ninjapipeClient.sendRecord({ auth: ninjapipeClient.readAuth(context.auth), method: HttpMethod.POST, path: '/deals', body, operation: 'create deal' });+ },+});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/ai/create-pipeline-item.ts b/packages/pieces/community/ninjapipe/src/lib/actions/ai/create-pipeline-item.tsnew file mode 100644index 00000000000..8663e9d6bc2--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/actions/ai/create-pipeline-item.ts@@ -0,0 +1,58 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../../auth';+import { ninjapipeAiProps } from '../../common/ai-props';+import { ninjapipeClient } from '../../common/client';+import { ninjapipeSchemas } from '../../output-schemas';+import { ninjapipeFields } from '../../common/fields';+import { ninjapipeItems } from '../../common/pipeline-item-props';++export const aiCreatePipelineItem = createAction({+ auth: ninjapipeAuth,+ name: 'ai_create_pipeline_item',+ classification: 'WRITE',+ displayName: 'Create Pipeline Item',+ description: 'Adds an item (card) to a pipeline stage.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Add an item (card) to a NinjaPipe pipeline: pipeline_id and stage_id come from ai_list_pipelines. Optional value, priority (low, medium, high), assigned_to (account_id), due_date (YYYY-MM-DD), email, phone and company name. Not idempotent: each call adds another card.',+ idempotent: false,+ },+ outputSchema: ninjapipeSchemas.pipelineItem,+ props: {+ pipeline_id: ninjapipeAiProps.id({ displayName: 'Pipeline ID', description: 'Pipeline UUID from ai_list_pipelines.' }),+ stage_id: ninjapipeAiProps.id({ displayName: 'Stage ID', description: 'Stage id of that pipeline, from ai_list_pipelines.' }),+ title: ninjapipeAiProps.text({ displayName: 'Title', description: 'Card title.', required: true }),+ description: ninjapipeAiProps.text({ displayName: 'Description', description: 'Card details.' }),+ value: ninjapipeAiProps.number({ displayName: 'Value', description: 'Value as a plain number.' }),+ priority: ninjapipeAiProps.choice({ displayName: 'Priority', description: 'Default medium.', values: ninjapipeItems.ITEM_PRIORITIES }),+ assigned_to: ninjapipeAiProps.optionalId({ displayName: 'Assigned To', description: 'account_id from ai_list_workspace_members.' }),+ due_date: ninjapipeAiProps.text({ displayName: 'Due Date', description: 'YYYY-MM-DD.' }),+ email: ninjapipeAiProps.text({ displayName: 'Email', description: 'Email shown on the card.' }),+ phone: ninjapipeAiProps.text({ displayName: 'Phone', description: 'Phone shown on the card.' }),+ company: ninjapipeAiProps.text({ displayName: 'Company', description: 'Company name shown on the card.' }),+ },+ async run(context) {+ const p = context.propsValue;+ const body = ninjapipeItems.itemBody({+ title: p.title,+ stageId: p.stage_id,+ description: p.description,+ value: p.value,+ priority: p.priority,+ assignedTo: p.assigned_to,+ dueDate: p.due_date,+ email: p.email,+ phone: p.phone,+ company: p.company,+ });+ return ninjapipeClient.sendRecord({+ auth: ninjapipeClient.readAuth(context.auth),+ method: HttpMethod.POST,+ path: `/pipelines/${ninjapipeClient.pathId({ value: p.pipeline_id, field: 'Pipeline ID' })}/items`,+ body: ninjapipeFields.requireChanges({ body, what: 'pipeline item' }),+ operation: 'create pipeline item',+ });+ },+});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/ai/create-task.ts b/packages/pieces/community/ninjapipe/src/lib/actions/ai/create-task.tsnew file mode 100644index 00000000000..fc11dcc94c1--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/actions/ai/create-task.ts@@ -0,0 +1,51 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../../auth';+import { ninjapipeAiProps } from '../../common/ai-props';+import { ninjapipeClient } from '../../common/client';+import { ninjapipeSchemas } from '../../output-schemas';+import { ninjapipeFields } from '../../common/fields';+import { ninjapipeTasks } from '../../common/task-props';++export const aiCreateTask = createAction({+ auth: ninjapipeAuth,+ name: 'ai_create_task',+ classification: 'WRITE',+ displayName: 'Create Task',+ description: 'Creates a task in a project.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Create a task in a NinjaPipe project (project_id from ai_list_projects) with a title and optional description, status, priority, assignee_id (account_id from ai_list_workspace_members), due_date (YYYY-MM-DD) and parent_id for a subtask. Not idempotent: each call creates another task.',+ idempotent: false,+ },+ outputSchema: ninjapipeSchemas.task,+ props: {+ project_id: ninjapipeAiProps.id({ displayName: 'Project ID', description: 'Project UUID from ai_list_projects.' }),+ title: ninjapipeAiProps.text({ displayName: 'Title', description: 'Task title.', required: true }),+ description: ninjapipeAiProps.text({ displayName: 'Description', description: 'Task details.' }),+ status: ninjapipeAiProps.choice({ displayName: 'Status', description: 'Default To Do.', values: ninjapipeTasks.TASK_STATUSES }),+ priority: ninjapipeAiProps.choice({ displayName: 'Priority', description: 'Task priority.', values: ninjapipeTasks.TASK_PRIORITIES }),+ assignee_id: ninjapipeAiProps.optionalId({ displayName: 'Assignee ID', description: 'account_id from ai_list_workspace_members.' }),+ due_date: ninjapipeAiProps.text({ displayName: 'Due Date', description: 'YYYY-MM-DD.' }),+ parent_id: ninjapipeAiProps.optionalId({ displayName: 'Parent Task ID', description: 'Task UUID in the same project, to create a subtask.' }),+ },+ async run(context) {+ const p = context.propsValue;+ return ninjapipeClient.sendRecord({+ auth: ninjapipeClient.readAuth(context.auth),+ method: HttpMethod.POST,+ path: `/projects/${ninjapipeClient.pathId({ value: p.project_id, field: 'Project ID' })}/tasks`,+ body: ninjapipeFields.compact({+ title: p.title,+ description: p.description,+ status: p.status,+ priority: p.priority,+ assignee_id: p.assignee_id,+ due_date: ninjapipeFields.toDateOnly({ value: p.due_date, field: 'Due Date' }),+ parent_id: p.parent_id,+ }),+ operation: 'create task',+ });+ },+});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/ai/get-company.ts b/packages/pieces/community/ninjapipe/src/lib/actions/ai/get-company.tsnew file mode 100644index 00000000000..a211c92a3d4--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/actions/ai/get-company.ts@@ -0,0 +1,30 @@+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../../auth';+import { ninjapipeAiProps } from '../../common/ai-props';+import { ninjapipeClient } from '../../common/client';+import { ninjapipeSchemas } from '../../output-schemas';++export const aiGetCompany = createAction({+ auth: ninjapipeAuth,+ name: 'ai_get_company',+ classification: 'READ',+ displayName: 'Get Company',+ description: 'Gets one company by ID.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Fetch one NinjaPipe company by company_id, with its custom fields. Read-only.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.company,+ props: {+ company_id: ninjapipeAiProps.id({ displayName: 'Company ID', description: 'NinjaPipe company UUID, from ai_search_companies.' }),+ },+ async run(context) {+ return ninjapipeClient.getRecord({+ auth: ninjapipeClient.readAuth(context.auth),+ path: `/companies/${ninjapipeClient.pathId({ value: context.propsValue.company_id, field: 'Company ID' })}`,+ operation: 'get company',+ });+ },+});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/ai/get-contact.ts b/packages/pieces/community/ninjapipe/src/lib/actions/ai/get-contact.tsnew file mode 100644index 00000000000..0955e269444--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/actions/ai/get-contact.ts@@ -0,0 +1,30 @@+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../../auth';+import { ninjapipeAiProps } from '../../common/ai-props';+import { ninjapipeClient } from '../../common/client';+import { ninjapipeSchemas } from '../../output-schemas';++export const aiGetContact = createAction({+ auth: ninjapipeAuth,+ name: 'ai_get_contact',+ classification: 'READ',+ displayName: 'Get Contact',+ description: 'Gets one contact by ID.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Fetch one NinjaPipe contact by contact_id, with its custom fields (fields object), owner_id and assigned_to. Read-only.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.contact,+ props: {+ contact_id: ninjapipeAiProps.id({ displayName: 'Contact ID', description: 'NinjaPipe contact UUID, from ai_search_contacts or ai_search_companies.' }),+ },+ async run(context) {+ return ninjapipeClient.getRecord({+ auth: ninjapipeClient.readAuth(context.auth),+ path: `/contacts/${ninjapipeClient.pathId({ value: context.propsValue.contact_id, field: 'Contact ID' })}`,+ operation: 'get contact',+ });+ },+});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/ai/get-deal.ts b/packages/pieces/community/ninjapipe/src/lib/actions/ai/get-deal.tsnew file mode 100644index 00000000000..7d9deb82ede--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/actions/ai/get-deal.ts@@ -0,0 +1,30 @@+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../../auth';+import { ninjapipeAiProps } from '../../common/ai-props';+import { ninjapipeClient } from '../../common/client';+import { ninjapipeSchemas } from '../../output-schemas';++export const aiGetDeal = createAction({+ auth: ninjapipeAuth,+ name: 'ai_get_deal',+ classification: 'READ',+ displayName: 'Get Deal',+ description: 'Gets one deal by ID.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Fetch one NinjaPipe deal by deal_id: name, value, status, owner, linked contact and company, custom fields. Read-only.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.deal,+ props: {+ deal_id: ninjapipeAiProps.id({ displayName: 'Deal ID', description: 'NinjaPipe deal UUID, from ai_search_deals or ai_search_companies.' }),+ },+ async run(context) {+ return ninjapipeClient.getRecord({+ auth: ninjapipeClient.readAuth(context.auth),+ path: `/deals/${ninjapipeClient.pathId({ value: context.propsValue.deal_id, field: 'Deal ID' })}`,+ operation: 'get deal',+ });+ },+});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/ai/list-contact-activities.ts b/packages/pieces/community/ninjapipe/src/lib/actions/ai/list-contact-activities.tsnew file mode 100644index 00000000000..d7f0aefc7d6--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/actions/ai/list-contact-activities.ts@@ -0,0 +1,37 @@+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../../auth';+import { ninjapipeAiProps } from '../../common/ai-props';+import { ninjapipeClient } from '../../common/client';+import { ninjapipeSchemas } from '../../output-schemas';++export const aiListContactActivities = createAction({+ auth: ninjapipeAuth,+ name: 'ai_list_contact_activities',+ classification: 'SEARCH',+ displayName: 'List Contact Activities',+ description: "Lists a contact's activity timeline.",+ audience: 'ai',+ aiMetadata: {+ description:+ "List a NinjaPipe contact's timeline (notes, tasks, list changes and other events) by contact_id, newest first, optionally only one type such as note or task. Returns one page with items, total, hasMore and nextPage. Read-only.",+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.activityList,+ props: {+ contact_id: ninjapipeAiProps.id({ displayName: 'Contact ID', description: 'Contact UUID from ai_search_contacts.' }),+ type: ninjapipeAiProps.text({ displayName: 'Type', description: 'Only this activity type, e.g. note or task.' }),+ page: ninjapipeAiProps.page(),+ limit: ninjapipeAiProps.limit(),+ },+ async run(context) {+ const p = context.propsValue;+ return ninjapipeClient.listPage({+ auth: ninjapipeClient.readAuth(context.auth),+ path: `/contacts/${ninjapipeClient.pathId({ value: p.contact_id, field: 'Contact ID' })}/activities`,+ query: { type: p.type },+ page: ninjapipeClient.readPage(p.page),+ limit: ninjapipeClient.clampLimit({ value: p.limit }),+ operation: 'list contact activities',+ });+ },+});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/ai/list-pipeline-items.ts b/packages/pieces/community/ninjapipe/src/lib/actions/ai/list-pipeline-items.tsnew file mode 100644index 00000000000..26083fccb19--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/actions/ai/list-pipeline-items.ts@@ -0,0 +1,37 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../../auth';+import { ninjapipeAiProps } from '../../common/ai-props';+import { ninjapipeClient } from '../../common/client';+import { ninjapipeSchemas } from '../../output-schemas';++export const aiListPipelineItems = createAction({+ auth: ninjapipeAuth,+ name: 'ai_list_pipeline_items',+ classification: 'SEARCH',+ displayName: 'List Pipeline Items',+ description: 'Lists the items (cards) of a pipeline.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'List all items (cards) of one NinjaPipe pipeline (pipeline_id from ai_list_pipelines), optionally only those in stage_id. Returns every matching item in one call. Read-only.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.pipelineItemList,+ props: {+ pipeline_id: ninjapipeAiProps.id({ displayName: 'Pipeline ID', description: 'Pipeline UUID from ai_list_pipelines.' }),+ stage_id: ninjapipeAiProps.optionalId({ displayName: 'Stage ID', description: 'Only items in this stage (stage id from ai_list_pipelines).' }),+ },+ async run(context) {+ const p = context.propsValue;+ const body = await ninjapipeClient.ninjapipeRequest({+ auth: ninjapipeClient.readAuth(context.auth),+ method: HttpMethod.GET,+ path: `/pipelines/${ninjapipeClient.pathId({ value: p.pipeline_id, field: 'Pipeline ID' })}/items`,+ operation: 'list pipeline items',+ });+ const stageId = typeof p.stage_id === 'string' ? p.stage_id.trim() : '';+ const items = ninjapipeClient.readItems(body).filter((item) => stageId === '' || item['stage_id'] === stageId);+ return { items, count: items.length };+ },+});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/ai/list-pipelines.ts b/packages/pieces/community/ninjapipe/src/lib/actions/ai/list-pipelines.tsnew file mode 100644index 00000000000..d55a5590c24--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/actions/ai/list-pipelines.ts@@ -0,0 +1,34 @@+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../../auth';+import { ninjapipeAiProps } from '../../common/ai-props';+import { ninjapipeClient } from '../../common/client';+import { ninjapipeSchemas } from '../../output-schemas';++export const aiListPipelines = createAction({+ auth: ninjapipeAuth,+ name: 'ai_list_pipelines',+ classification: 'SEARCH',+ displayName: 'List Pipelines',+ description: 'Lists pipelines with their stages.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'List NinjaPipe pipelines (boards) with their stages; each stage has the id that pipeline items use as stage_id. Each item has pipeline_type (deals, contacts, general). Returns one page with items, total, hasMore and nextPage. Read-only.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.pipelineList,+ props: {+ page: ninjapipeAiProps.page(),+ limit: ninjapipeAiProps.limit(),+ },+ async run(context) {+ const p = context.propsValue;+ return ninjapipeClient.listPage({+ auth: ninjapipeClient.readAuth(context.auth),+ path: '/pipelines',+ page: ninjapipeClient.readPage(p.page),+ limit: ninjapipeClient.clampLimit({ value: p.limit }),+ operation: 'list pipelines',+ });+ },+});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/ai/list-projects.ts b/packages/pieces/community/ninjapipe/src/lib/actions/ai/list-projects.tsnew file mode 100644index 00000000000..b3e8bbe0191--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/actions/ai/list-projects.ts@@ -0,0 +1,37 @@+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../../auth';+import { ninjapipeAiProps } from '../../common/ai-props';+import { ninjapipeClient } from '../../common/client';+import { ninjapipeSchemas } from '../../output-schemas';++export const aiListProjects = createAction({+ auth: ninjapipeAuth,+ name: 'ai_list_projects',+ classification: 'SEARCH',+ displayName: 'List Projects',+ description: 'Lists projects page by page.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'List NinjaPipe projects, optionally filtered by free text or status (Planning, In Progress, Completed, On Hold, Cancelled). Returns one page with items, total, hasMore and nextPage. Use it to find the project_id that tasks belong to. Read-only.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.projectList,+ props: {+ search: ninjapipeAiProps.text({ displayName: 'Search', description: 'Free text matched against project names.' }),+ status: ninjapipeAiProps.choice({ displayName: 'Status', description: 'Only projects with this status.', values: ['Planning', 'In Progress', 'Completed', 'On Hold', 'Cancelled'] }),+ page: ninjapipeAiProps.page(),+ limit: ninjapipeAiProps.limit(),+ },+ async run(context) {+ const p = context.propsValue;+ return ninjapipeClient.listPage({+ auth: ninjapipeClient.readAuth(context.auth),+ path: '/projects',+ query: { search: p.search, status: p.status },+ page: ninjapipeClient.readPage(p.page),+ limit: ninjapipeClient.clampLimit({ value: p.limit }),+ operation: 'list projects',+ });+ },+});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/ai/list-tasks.ts b/packages/pieces/community/ninjapipe/src/lib/actions/ai/list-tasks.tsnew file mode 100644index 00000000000..7b8ddab81e1--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/actions/ai/list-tasks.ts@@ -0,0 +1,38 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../../auth';+import { ninjapipeAiProps } from '../../common/ai-props';+import { ninjapipeClient } from '../../common/client';+import { ninjapipeSchemas } from '../../output-schemas';+import { ninjapipeRecords } from '../../common/records';+import { ninjapipeTasks } from '../../common/task-props';++export const aiListTasks = createAction({+ auth: ninjapipeAuth,+ name: 'ai_list_tasks',+ classification: 'SEARCH',+ displayName: 'List Tasks',+ description: 'Lists the tasks of a project.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'List every task of one NinjaPipe project (project_id from ai_list_projects), optionally only a status (To Do, In Progress, Done, Cancelled), a priority (High, Medium, Low) the subtasks of parent_id, or only top-level tasks with root_only. Returns all matching tasks in one call. Read-only.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.taskList,+ props: {+ project_id: ninjapipeAiProps.id({ displayName: 'Project ID', description: 'Project UUID from ai_list_projects.' }),+ status: ninjapipeAiProps.choice({ displayName: 'Status', description: 'Only tasks with this status.', values: ninjapipeTasks.TASK_STATUSES }),+ priority: ninjapipeAiProps.choice({ displayName: 'Priority', description: 'Only tasks with this priority.', values: ninjapipeTasks.TASK_PRIORITIES }),+ parent_id: ninjapipeAiProps.optionalId({ displayName: 'Parent Task ID', description: 'Only subtasks of this task.' }),+ root_only: Property.Checkbox({ displayName: 'Root Tasks Only', description: 'true returns only top-level tasks (no subtasks). Ignored when parent_id is set.', required: false }),+ },+ async run(context) {+ const p = context.propsValue;+ return ninjapipeRecords.listUnpaged({+ auth: ninjapipeClient.readAuth(context.auth),+ path: `/projects/${ninjapipeClient.pathId({ value: p.project_id, field: 'Project ID' })}/tasks`,+ query: { status: p.status, priority: p.priority, parent_id: ninjapipeTasks.parentFilter({ parentId: p.parent_id, rootOnly: p.root_only }) },+ operation: 'list tasks',+ });+ },+});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/ai/list-workspace-members.ts b/packages/pieces/community/ninjapipe/src/lib/actions/ai/list-workspace-members.tsnew file mode 100644index 00000000000..471c26f99ad--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/actions/ai/list-workspace-members.ts@@ -0,0 +1,24 @@+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../../auth';+import { ninjapipeClient } from '../../common/client';+import { ninjapipeRecords } from '../../common/records';+import { ninjapipeSchemas } from '../../output-schemas';++export const aiListWorkspaceMembers = createAction({+ auth: ninjapipeAuth,+ name: 'ai_list_workspace_members',+ classification: 'SEARCH',+ displayName: 'List Workspace Members',+ description: 'Lists the members of the NinjaPipe workspace.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'List the people in the NinjaPipe workspace with account_id, email, full name and role. Use account_id as owner_id, assigned_to or assignee_id in other steps. Read-only.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.memberList,+ props: {},+ async run(context) {+ return ninjapipeRecords.listWorkspaceMembers({ auth: ninjapipeClient.readAuth(context.auth) });+ },+});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/ai/search-companies.ts b/packages/pieces/community/ninjapipe/src/lib/actions/ai/search-companies.tsnew file mode 100644index 00000000000..a13692aa759--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/actions/ai/search-companies.ts@@ -0,0 +1,40 @@+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../../auth';+import { ninjapipeAiProps } from '../../common/ai-props';+import { ninjapipeClient } from '../../common/client';+import { ninjapipeSchemas } from '../../output-schemas';++export const aiSearchCompanies = createAction({+ auth: ninjapipeAuth,+ name: 'ai_search_companies',+ classification: 'SEARCH',+ displayName: 'Search Companies',+ description: 'Searches companies page by page.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Search NinjaPipe companies by free text and filter by status or owner_id. Returns one page: items, total, hasMore and nextPage. Use it to find a company_id for contacts, deals or lists. Read-only.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.companyList,+ props: {+ search: ninjapipeAiProps.text({ displayName: 'Search', description: 'Free text matched against the company name and other text fields.' }),+ status: ninjapipeAiProps.text({ displayName: 'Status', description: 'Only companies with this status.' }),+ owner_id: ninjapipeAiProps.optionalId({ displayName: 'Owner ID', description: 'Only companies owned by a workspace member account_id from ai_list_workspace_members.' }),+ sort_by: ninjapipeAiProps.sortBy({ values: ['created_at', 'updated_at', 'name'] }),+ sort_order: ninjapipeAiProps.sortOrder(),+ page: ninjapipeAiProps.page(),+ limit: ninjapipeAiProps.limit(),+ },+ async run(context) {+ const p = context.propsValue;+ return ninjapipeClient.listPage({+ auth: ninjapipeClient.readAuth(context.auth),+ path: '/companies',+ query: { search: p.search, status: p.status, owner_id: p.owner_id, sort_by: p.sort_by, sort_order: p.sort_order },+ page: ninjapipeClient.readPage(p.page),+ limit: ninjapipeClient.clampLimit({ value: p.limit }),+ operation: 'search companies',+ });+ },+});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/ai/search-contacts.ts b/packages/pieces/community/ninjapipe/src/lib/actions/ai/search-contacts.tsnew file mode 100644index 00000000000..07ba54e221d--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/actions/ai/search-contacts.ts@@ -0,0 +1,41 @@+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../../auth';+import { ninjapipeAiProps } from '../../common/ai-props';+import { ninjapipeClient } from '../../common/client';+import { ninjapipeSchemas } from '../../output-schemas';++export const aiSearchContacts = createAction({+ auth: ninjapipeAuth,+ name: 'ai_search_contacts',+ classification: 'SEARCH',+ displayName: 'Search Contacts',+ description: 'Searches contacts page by page.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Search NinjaPipe contacts by free text (name, email, phone) and filter by status, owner_id or assigned_to. Returns one page: items, total, hasMore and nextPage (pass it as page to continue). Use it to find a contact_id before get, update, note or delete steps. Read-only.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.contactList,+ props: {+ search: ninjapipeAiProps.text({ displayName: 'Search', description: 'Free text matched against name, email and phone. Not an exact match: check the email of each result.' }),+ status: ninjapipeAiProps.text({ displayName: 'Status', description: 'Only contacts with this status, e.g. Active or Lead.' }),+ owner_id: ninjapipeAiProps.optionalId({ displayName: 'Owner ID', description: 'Only contacts owned by a workspace member account_id from ai_list_workspace_members.' }),+ assigned_to: ninjapipeAiProps.optionalId({ displayName: 'Assigned To', description: 'Only contacts assigned to a workspace member account_id from ai_list_workspace_members.' }),+ sort_by: ninjapipeAiProps.sortBy({ values: ['created_at', 'updated_at', 'first_name', 'last_name', 'email'] }),+ sort_order: ninjapipeAiProps.sortOrder(),+ page: ninjapipeAiProps.page(),+ limit: ninjapipeAiProps.limit(),+ },+ async run(context) {+ const p = context.propsValue;+ return ninjapipeClient.listPage({+ auth: ninjapipeClient.readAuth(context.auth),+ path: '/contacts',+ query: { search: p.search, status: p.status, owner_id: p.owner_id, assigned_to: p.assigned_to, sort_by: p.sort_by, sort_order: p.sort_order },+ page: ninjapipeClient.readPage(p.page),+ limit: ninjapipeClient.clampLimit({ value: p.limit }),+ operation: 'search contacts',+ });+ },+});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/ai/search-deals.ts b/packages/pieces/community/ninjapipe/src/lib/actions/ai/search-deals.tsnew file mode 100644index 00000000000..b6cdfccbb9e--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/actions/ai/search-deals.ts@@ -0,0 +1,40 @@+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../../auth';+import { ninjapipeAiProps } from '../../common/ai-props';+import { ninjapipeClient } from '../../common/client';+import { ninjapipeSchemas } from '../../output-schemas';++export const aiSearchDeals = createAction({+ auth: ninjapipeAuth,+ name: 'ai_search_deals',+ classification: 'SEARCH',+ displayName: 'Search Deals',+ description: 'Searches deals page by page.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Search NinjaPipe deals by name and filter by status (Open, In Progress, Won, Lost) or owner_id; sort by value to find the biggest. Returns one page: items, total, hasMore and nextPage. Read-only.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.dealList,+ props: {+ search: ninjapipeAiProps.text({ displayName: 'Search', description: 'Free text matched against the deal name.' }),+ status: ninjapipeAiProps.choice({ displayName: 'Status', description: 'Only deals with this status.', values: ['Open', 'In Progress', 'Won', 'Lost'] }),+ owner_id: ninjapipeAiProps.optionalId({ displayName: 'Owner ID', description: 'Only deals owned by a workspace member account_id from ai_list_workspace_members.' }),+ sort_by: ninjapipeAiProps.sortBy({ values: ['created_at', 'updated_at', 'name', 'value', 'status'] }),+ sort_order: ninjapipeAiProps.sortOrder(),+ page: ninjapipeAiProps.page(),+ limit: ninjapipeAiProps.limit(),+ },+ async run(context) {+ const p = context.propsValue;+ return ninjapipeClient.listPage({+ auth: ninjapipeClient.readAuth(context.auth),+ path: '/deals',+ query: { search: p.search, status: p.status, owner_id: p.owner_id, sort_by: p.sort_by, sort_order: p.sort_order },+ page: ninjapipeClient.readPage(p.page),+ limit: ninjapipeClient.clampLimit({ value: p.limit }),+ operation: 'search deals',+ });+ },+});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/ai/update-company.ts b/packages/pieces/community/ninjapipe/src/lib/actions/ai/update-company.tsnew file mode 100644index 00000000000..336ec3f1d5f--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/actions/ai/update-company.ts@@ -0,0 +1,52 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../../auth';+import { ninjapipeAiProps } from '../../common/ai-props';+import { ninjapipeClient } from '../../common/client';+import { ninjapipeFields } from '../../common/fields';+import { ninjapipeSchemas } from '../../output-schemas';++export const aiUpdateCompany = createAction({+ auth: ninjapipeAuth,+ name: 'ai_update_company',+ classification: 'WRITE',+ displayName: 'Update Company',+ description: 'Updates a company.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Change fields of an existing NinjaPipe company by company_id. Only the fields you give change; list field names in clear_fields to empty them. Custom fields are merged into the existing ones. Repeating the same call gives the same result.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.company,+ props: {+ company_id: ninjapipeAiProps.id({ displayName: 'Company ID', description: 'Company UUID from ai_search_companies.' }),+ name: ninjapipeAiProps.text({ displayName: 'Name', description: 'New name.' }),+ website: ninjapipeAiProps.text({ displayName: 'Website', description: 'New website URL.' }),+ email: ninjapipeAiProps.text({ displayName: 'Email', description: 'New email.' }),+ phone: ninjapipeAiProps.text({ displayName: 'Phone', description: 'New phone.' }),+ industry: ninjapipeAiProps.text({ displayName: 'Industry', description: 'New industry.' }),+ status: ninjapipeAiProps.text({ displayName: 'Status', description: 'New status.' }),+ owner_id: ninjapipeAiProps.optionalId({ displayName: 'Owner ID', description: 'Owner account_id from ai_list_workspace_members.' }),+ fields: ninjapipeAiProps.customFields({ update: true }),+ clear_fields: ninjapipeAiProps.clearFields({ fields: ['website', 'email', 'phone', 'industry'] }),+ },+ async run(context) {+ const auth = ninjapipeClient.readAuth(context.auth);+ const p = context.propsValue;+ const path = `/companies/${ninjapipeClient.pathId({ value: p.company_id, field: 'Company ID' })}`;+ const fields = await ninjapipeFields.mergeCustomFields({ auth, path, fields: p.fields, operation: 'read company' });+ const changes = ninjapipeFields.compact({+ name: p.name,+ website: p.website,+ email: p.email,+ phone: p.phone,+ industry: p.industry,+ status: p.status,+ owner_id: p.owner_id,+ fields,+ });+ const body = ninjapipeFields.requireChanges({ body: ninjapipeFields.withClears({ body: changes, clear: p.clear_fields }), what: 'company' });+ return ninjapipeClient.sendRecord({ auth, method: HttpMethod.PUT, path, body, operation: 'update company' });+ },+});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/ai/update-contact.ts b/packages/pieces/community/ninjapipe/src/lib/actions/ai/update-contact.tsnew file mode 100644index 00000000000..23a46363cd2--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/actions/ai/update-contact.ts@@ -0,0 +1,54 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../../auth';+import { ninjapipeAiProps } from '../../common/ai-props';+import { ninjapipeClient } from '../../common/client';+import { ninjapipeFields } from '../../common/fields';+import { ninjapipeSchemas } from '../../output-schemas';++export const aiUpdateContact = createAction({+ auth: ninjapipeAuth,+ name: 'ai_update_contact',+ classification: 'WRITE',+ displayName: 'Update Contact',+ description: 'Updates a contact.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Change fields of an existing NinjaPipe contact by contact_id. Only the fields you give change; list field names in clear_fields to empty them (e.g. assigned_to to unassign). Custom fields are merged into the existing ones. Repeating the same call gives the same result.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.contact,+ props: {+ contact_id: ninjapipeAiProps.id({ displayName: 'Contact ID', description: 'Contact UUID from ai_search_contacts.' }),+ first_name: ninjapipeAiProps.text({ displayName: 'First Name', description: 'New first name.' }),+ last_name: ninjapipeAiProps.text({ displayName: 'Last Name', description: 'New last name.' }),+ email: ninjapipeAiProps.text({ displayName: 'Email', description: 'New email, unique per workspace.' }),+ phone: ninjapipeAiProps.text({ displayName: 'Phone', description: 'New phone number.' }),+ status: ninjapipeAiProps.text({ displayName: 'Status', description: 'New status, e.g. Active or Lead.' }),+ company_id: ninjapipeAiProps.optionalId({ displayName: 'Company ID', description: 'Company UUID from ai_search_companies.' }),+ owner_id: ninjapipeAiProps.optionalId({ displayName: 'Owner ID', description: 'Owner account_id from ai_list_workspace_members.' }),+ assigned_to: ninjapipeAiProps.optionalId({ displayName: 'Assigned To', description: 'Assignee account_id from ai_list_workspace_members.' }),+ fields: ninjapipeAiProps.customFields({ update: true }),+ clear_fields: ninjapipeAiProps.clearFields({ fields: ['first_name', 'last_name', 'phone', 'company_id', 'assigned_to'] }),+ },+ async run(context) {+ const auth = ninjapipeClient.readAuth(context.auth);+ const p = context.propsValue;+ const path = `/contacts/${ninjapipeClient.pathId({ value: p.contact_id, field: 'Contact ID' })}`;+ const fields = await ninjapipeFields.mergeCustomFields({ auth, path, fields: p.fields, operation: 'read contact' });+ const changes = ninjapipeFields.compact({+ first_name: p.first_name,+ last_name: p.last_name,+ email: p.email,+ phone: p.phone,+ status: p.status,+ company_id: p.company_id,+ owner_id: p.owner_id,+ assigned_to: p.assigned_to,+ fields,+ });+ const body = ninjapipeFields.requireChanges({ body: ninjapipeFields.withClears({ body: changes, clear: p.clear_fields }), what: 'contact' });+ return ninjapipeClient.sendRecord({ auth, method: HttpMethod.PUT, path, body, operation: 'update contact' });+ },+});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/ai/update-deal.ts b/packages/pieces/community/ninjapipe/src/lib/actions/ai/update-deal.tsnew file mode 100644index 00000000000..700f9143a98--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/actions/ai/update-deal.ts@@ -0,0 +1,50 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../../auth';+import { ninjapipeAiProps } from '../../common/ai-props';+import { ninjapipeClient } from '../../common/client';+import { ninjapipeFields } from '../../common/fields';+import { ninjapipeSchemas } from '../../output-schemas';++export const aiUpdateDeal = createAction({+ auth: ninjapipeAuth,+ name: 'ai_update_deal',+ classification: 'WRITE',+ displayName: 'Update Deal',+ description: 'Updates a deal.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Change an existing NinjaPipe deal by deal_id: name, value, status (e.g. mark Won or Lost), owner, contact or company. Only the fields you give change; clear_fields unlinks contact_id or company_id. Custom fields are merged. Repeating the same call gives the same result.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.deal,+ props: {+ deal_id: ninjapipeAiProps.id({ displayName: 'Deal ID', description: 'Deal UUID from ai_search_deals.' }),+ name: ninjapipeAiProps.text({ displayName: 'Name', description: 'New deal name.' }),+ value: ninjapipeAiProps.number({ displayName: 'Value', description: 'New value as a plain number.' }),+ status: ninjapipeAiProps.choice({ displayName: 'Status', description: 'New status.', values: ['Open', 'In Progress', 'Won', 'Lost'] }),+ owner_id: ninjapipeAiProps.optionalId({ displayName: 'Owner ID', description: 'Owner account_id from ai_list_workspace_members.' }),+ contact_id: ninjapipeAiProps.optionalId({ displayName: 'Contact ID', description: 'Contact UUID from ai_search_contacts.' }),+ company_id: ninjapipeAiProps.optionalId({ displayName: 'Company ID', description: 'Company UUID from ai_search_companies.' }),+ fields: ninjapipeAiProps.customFields({ update: true }),+ clear_fields: ninjapipeAiProps.clearFields({ fields: ['contact_id', 'company_id'] }),+ },+ async run(context) {+ const auth = ninjapipeClient.readAuth(context.auth);+ const p = context.propsValue;+ const path = `/deals/${ninjapipeClient.pathId({ value: p.deal_id, field: 'Deal ID' })}`;+ const fields = await ninjapipeFields.mergeCustomFields({ auth, path, fields: p.fields, operation: 'read deal' });+ const changes = ninjapipeFields.compact({+ name: p.name,+ value: ninjapipeFields.toNumber({ value: p.value, field: 'Value' }),+ status: p.status,+ owner_id: p.owner_id,+ contact_id: p.contact_id,+ company_id: p.company_id,+ fields,+ });+ const body = ninjapipeFields.requireChanges({ body: ninjapipeFields.withClears({ body: changes, clear: p.clear_fields }), what: 'deal' });+ return ninjapipeClient.sendRecord({ auth, method: HttpMethod.PUT, path, body, operation: 'update deal' });+ },+});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/ai/update-pipeline-item.ts b/packages/pieces/community/ninjapipe/src/lib/actions/ai/update-pipeline-item.tsnew file mode 100644index 00000000000..1b985ee5477--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/actions/ai/update-pipeline-item.ts@@ -0,0 +1,50 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../../auth';+import { ninjapipeAiProps } from '../../common/ai-props';+import { ninjapipeClient } from '../../common/client';+import { ninjapipeSchemas } from '../../output-schemas';+import { ninjapipeFields } from '../../common/fields';+import { ninjapipeItems } from '../../common/pipeline-item-props';++export const aiUpdatePipelineItem = createAction({+ auth: ninjapipeAuth,+ name: 'ai_update_pipeline_item',+ classification: 'WRITE',+ displayName: 'Update Pipeline Item',+ description: 'Updates or moves an item (card) of a pipeline.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Change an item of a NinjaPipe pipeline by pipeline_id and item_id (from ai_list_pipeline_items); set stage_id to move it to another stage. Only the fields you give change; clear_fields empties them. Repeating the same call gives the same result.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.pipelineItem,+ props: {+ pipeline_id: ninjapipeAiProps.id({ displayName: 'Pipeline ID', description: 'Pipeline UUID from ai_list_pipelines.' }),+ item_id: ninjapipeAiProps.id({ displayName: 'Item ID', description: 'Item UUID from ai_list_pipeline_items.' }),+ stage_id: ninjapipeAiProps.optionalId({ displayName: 'Stage ID', description: 'Move the item to this stage id.' }),+ title: ninjapipeAiProps.text({ displayName: 'Title', description: 'New title.' }),+ description: ninjapipeAiProps.text({ displayName: 'Description', description: 'New details.' }),+ value: ninjapipeAiProps.number({ displayName: 'Value', description: 'New value.' }),+ priority: ninjapipeAiProps.choice({ displayName: 'Priority', description: 'New priority.', values: ninjapipeItems.ITEM_PRIORITIES }),+ assigned_to: ninjapipeAiProps.optionalId({ displayName: 'Assigned To', description: 'account_id from ai_list_workspace_members.' }),+ due_date: ninjapipeAiProps.text({ displayName: 'Due Date', description: 'YYYY-MM-DD.' }),+ clear_fields: ninjapipeAiProps.clearFields({ fields: Object.keys(ninjapipeItems.ITEM_CLEARABLE) }),+ },+ async run(context) {+ const p = context.propsValue;+ const path = `/pipelines/${ninjapipeClient.pathId({ value: p.pipeline_id, field: 'Pipeline ID' })}/items/${ninjapipeClient.pathId({ value: p.item_id, field: 'Item ID' })}`;+ const changes = ninjapipeItems.itemBody({+ title: p.title,+ stageId: p.stage_id,+ description: p.description,+ value: p.value,+ priority: p.priority,+ assignedTo: p.assigned_to,+ dueDate: p.due_date,+ });+ const body = ninjapipeFields.requireChanges({ body: ninjapipeFields.withClears({ body: changes, clear: p.clear_fields }), what: 'pipeline item' });+ return ninjapipeClient.sendRecord({ auth: ninjapipeClient.readAuth(context.auth), method: HttpMethod.PUT, path, body, operation: 'update pipeline item' });+ },+});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/ai/update-task.ts b/packages/pieces/community/ninjapipe/src/lib/actions/ai/update-task.tsnew file mode 100644index 00000000000..6945452bbca--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/actions/ai/update-task.ts@@ -0,0 +1,48 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../../auth';+import { ninjapipeAiProps } from '../../common/ai-props';+import { ninjapipeClient } from '../../common/client';+import { ninjapipeSchemas } from '../../output-schemas';+import { ninjapipeFields } from '../../common/fields';+import { ninjapipeTasks } from '../../common/task-props';++export const aiUpdateTask = createAction({+ auth: ninjapipeAuth,+ name: 'ai_update_task',+ classification: 'WRITE',+ displayName: 'Update Task',+ description: 'Updates a task in a project.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Change a task by project_id and task_id (from ai_list_tasks): title, description, status (e.g. Done to complete it), priority, assignee_id or due_date. Only the fields you give change; clear_fields empties them. Repeating the same call gives the same result.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.task,+ props: {+ project_id: ninjapipeAiProps.id({ displayName: 'Project ID', description: 'Project UUID from ai_list_projects.' }),+ task_id: ninjapipeAiProps.id({ displayName: 'Task ID', description: 'Task UUID from ai_list_tasks.' }),+ title: ninjapipeAiProps.text({ displayName: 'Title', description: 'New title.' }),+ description: ninjapipeAiProps.text({ displayName: 'Description', description: 'New details.' }),+ status: ninjapipeAiProps.choice({ displayName: 'Status', description: 'New status.', values: ninjapipeTasks.TASK_STATUSES }),+ priority: ninjapipeAiProps.choice({ displayName: 'Priority', description: 'New priority.', values: ninjapipeTasks.TASK_PRIORITIES }),+ assignee_id: ninjapipeAiProps.optionalId({ displayName: 'Assignee ID', description: 'account_id from ai_list_workspace_members.' }),+ due_date: ninjapipeAiProps.text({ displayName: 'Due Date', description: 'YYYY-MM-DD.' }),+ clear_fields: ninjapipeAiProps.clearFields({ fields: ['description', 'assignee_id', 'due_date', 'parent_id'] }),+ },+ async run(context) {+ const p = context.propsValue;+ const path = `/projects/${ninjapipeClient.pathId({ value: p.project_id, field: 'Project ID' })}/tasks/${ninjapipeClient.pathId({ value: p.task_id, field: 'Task ID' })}`;+ const changes = ninjapipeFields.compact({+ title: p.title,+ description: p.description,+ status: p.status,+ priority: p.priority,+ assignee_id: p.assignee_id,+ due_date: ninjapipeFields.toDateOnly({ value: p.due_date, field: 'Due Date' }),+ });+ const body = ninjapipeFields.requireChanges({ body: ninjapipeFields.withClears({ body: changes, clear: p.clear_fields }), what: 'task' });+ return ninjapipeClient.sendRecord({ auth: ninjapipeClient.readAuth(context.auth), method: HttpMethod.PUT, path, body, operation: 'update task' });+ },+});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/create-budget-expense.ts b/packages/pieces/community/ninjapipe/src/lib/actions/create-budget-expense.tsindex 08f95634ab1..ff006f700a3 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/create-budget-expense.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/create-budget-expense.ts@@ -1,56 +1,46 @@-import { createAction, Property } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, flattenCustomFields, getAuth, toDateOnly, ninjapipeCommon } from '../common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeFields } from '../common/fields';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const createBudgetExpense = createAction({auth: ninjapipeAuth,name: 'create_budget_expense',classification: 'WRITE',displayName: 'Create Budget Expense',- description: 'Adds an expense to a budget. The expense amount is added to the budget\'s spent amount.',+ description: 'Records an expense against a budget.',audience: 'both',- aiMetadata: { description: 'Records an expense against a specific budget, increasing that budget\'s spent total by the amount given. Requires budget ID, description, amount, category, and date. Not idempotent: each call adds another expense and further increases the spent amount, so avoid duplicate retries.', idempotent: false },+ aiMetadata: {+ description: 'Record one expense (description, amount, optional category and date) against a NinjaPipe budget by budget ID; the budget spent and remaining amounts update. Not idempotent: each call adds another expense.',+ idempotent: false,+ },+ outputSchema: ninjapipeSchemas.budgetExpense,props: {- budgetId: ninjapipeCommon.budgetDropdownRequired,- description: Property.ShortText({- displayName: 'Description',- description: 'Description of the expense.',- required: true,- }),- amount: Property.Number({- displayName: 'Amount',- description: 'Expense amount (positive number).',- required: true,- }),- category: Property.ShortText({- displayName: 'Category',- description: 'Expense category (e.g. Marketing, Travel).',- required: true,- }),- date: Property.DateTime({- displayName: 'Date',- description: 'Expense date.',- required: true,- }),+ budgetId: ninjapipeProps.budgetRequired(),+ description: Property.ShortText({ displayName: 'Description', required: true }),+ amount: Property.Number({ displayName: 'Amount', required: true }),+ category: Property.ShortText({ displayName: 'Category', required: false }),+ date: Property.DateTime({ displayName: 'Date', description: 'Date (YYYY-MM-DD). Defaults to today.', required: false }),},async run(context) {- const auth = getAuth(context);const p = context.propsValue;- const date = toDateOnly(p.date);- if (!date) throw new Error('Date is required.');- const body: Record<string, unknown> = {- description: p.description,- amount: p.amount,- category: p.category,- date,- };- const response = await ninjapipeApiCall<Record<string, unknown>>({- auth,+ const amount = ninjapipeFields.toNumber({ value: p.amount, field: 'Amount' });+ if (amount === undefined) throw new Error('Amount is required.');+ const result = await ninjapipeClient.sendRecord({+ auth: ninjapipeClient.readAuth(context.auth),method: HttpMethod.POST,- path: `/budgets/${encodeURIComponent(String(p.budgetId))}/expenses`,- body,+ path: `/budgets/${ninjapipeClient.pathId({ value: p.budgetId, field: 'Budget' })}/expenses`,+ body: ninjapipeFields.compact({+ description: p.description,+ amount,+ category: p.category,+ date: ninjapipeFields.toDateOnly({ value: p.date, field: 'Date' }),+ }),+ operation: 'create budget expense',});- return flattenCustomFields(response.body);+ return result;},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/create-budget.ts b/packages/pieces/community/ninjapipe/src/lib/actions/create-budget.tsindex 133a5b6cfa3..08d214c2817 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/create-budget.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/create-budget.ts@@ -1,67 +1,56 @@-import { createAction, Property } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, flattenCustomFields, getAuth, ninjapipeCommon, toDateOnly } from '../common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeFields } from '../common/fields';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const createBudget = createAction({auth: ninjapipeAuth,name: 'create_budget',classification: 'WRITE',displayName: 'Create Budget',- description: 'Creates a new budget.',+ description: 'Creates a budget.',audience: 'both',- aiMetadata: { description: 'Create a new budget in NinjaPipe with a name and an allocated amount (which must be greater than 0); optionally set category, period, currency (defaults to USD), status, and start/end dates. Not idempotent — each call creates a separate budget, so calling repeatedly produces duplicates.', idempotent: false },+ aiMetadata: {+ description: 'Create a NinjaPipe budget. Required: name, allocated, category, period, and a start_date (end date derived from the period) or an end_date. Not idempotent: each call creates another budget.',+ idempotent: false,+ },+ outputSchema: ninjapipeSchemas.budget,props: {- name: Property.ShortText({ displayName: 'Name', description: 'Budget name.', required: true }),- allocated: Property.Number({- displayName: 'Allocated Amount',- description: 'Total allocated budget amount. Must be greater than 0.',- required: true,- }),+ name: Property.ShortText({ displayName: 'Name', required: true }),+ allocated: Property.Number({ displayName: 'Allocated Amount', required: true }),description: Property.LongText({ displayName: 'Description', required: false }),- category: ninjapipeCommon.budgetCategoryDropdown,- period: ninjapipeCommon.budgetPeriodDropdown,- currency: Property.ShortText({- displayName: 'Currency',- description: 'Currency code, e.g. USD, EUR. Defaults to USD.',- required: false,- }),- status: ninjapipeCommon.budgetStatusDropdown,- startDate: Property.DateTime({- displayName: 'Start Date',- required: false,- }),- endDate: Property.DateTime({- displayName: 'End Date',- required: false,- }),+ category: Property.StaticDropdown({ displayName: 'Category', description: 'Category.', required: true, options: { options: [{ label: 'Marketing', value: 'Marketing' }, { label: 'Sales', value: 'Sales' }, { label: 'Product', value: 'Product' }, { label: 'Operations', value: 'Operations' }] } }),+ period: Property.StaticDropdown({ displayName: 'Period', description: 'Budget cycle. NinjaPipe derives the end date from the start date and period.', required: true, options: { options: [{ label: 'Monthly', value: 'Monthly' }, { label: 'Quarterly', value: 'Quarterly' }, { label: 'Yearly', value: 'Yearly' }] } }),+ currency: Property.ShortText({ displayName: 'Currency', required: false }),+ status: ninjapipeProps.staticDropdown({ displayName: 'Status', description: 'Status.', values: ['Active', 'Inactive', 'Completed'] }),+ startDate: Property.DateTime({ displayName: 'Start Date', description: 'Date (YYYY-MM-DD).', required: false }),+ endDate: Property.DateTime({ displayName: 'End Date', description: 'Date (YYYY-MM-DD).', required: false }),},async run(context) {- const auth = getAuth(context);const p = context.propsValue;- const body: Record<string, unknown> = {- name: p.name,- allocated: p.allocated,- };- if (p.description) body['description'] = p.description;- if (p.category) body['category'] = p.category;- if (p.period) body['period'] = p.period;- if (p.currency) body['currency'] = p.currency;- if (p.status) body['status'] = p.status;- {- const v = toDateOnly(p.startDate);- if (v) body['start_date'] = v;+ if (ninjapipeFields.isBlank(p.startDate) && ninjapipeFields.isBlank(p.endDate)) {+ throw new Error('Give a Start Date (the end date is derived from the period) or an End Date.');}- {- const v = toDateOnly(p.endDate);- if (v) body['end_date'] = v;- }- const response = await ninjapipeApiCall<Record<string, unknown>>({- auth,+ const body = ninjapipeFields.compact({+ name: p.name,+ allocated: ninjapipeFields.toNumber({ value: p.allocated, field: 'Allocated Amount' }),+ description: p.description,+ category: p.category,+ period: p.period,+ currency: p.currency,+ status: p.status,+ start_date: ninjapipeFields.toDateOnly({ value: p.startDate, field: 'Start Date' }),+ end_date: ninjapipeFields.toDateOnly({ value: p.endDate, field: 'End Date' }),+ });+ return ninjapipeClient.sendRecord({+ auth: ninjapipeClient.readAuth(context.auth),method: HttpMethod.POST,path: '/budgets',body,+ operation: 'create budget',});- return flattenCustomFields(response.body);},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/create-company.ts b/packages/pieces/community/ninjapipe/src/lib/actions/create-company.tsindex 78772cc25ed..08a25d1f1a2 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/create-company.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/create-company.ts@@ -1,51 +1,51 @@-import { createAction, Property } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, flattenCustomFields, getAuth, ninjapipeCommon } from '../common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeFields } from '../common/fields';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const createCompany = createAction({auth: ninjapipeAuth,name: 'create_company',classification: 'WRITE',displayName: 'Create Company',- description: 'Creates a new company.',- audience: 'both',- aiMetadata: { description: 'Creates a new company (CRM account) in NinjaPipe with optional industry, contact details, address, status, owner, notes, and custom fields. Only Name is required. Not idempotent: each call adds another company, so check List Companies first to avoid duplicates.', idempotent: false },+ description: 'Creates a company.',+ audience: 'human',+ aiMetadata: {+ description: 'Create a NinjaPipe company. Required: name. Not idempotent: each call creates another company.',+ idempotent: false,+ },+ outputSchema: ninjapipeSchemas.company,props: {name: Property.ShortText({ displayName: 'Name', required: true }),- industry: Property.ShortText({ displayName: 'Industry', required: false }),- website: Property.ShortText({ displayName: 'Website', required: false }),email: Property.ShortText({ displayName: 'Email', required: false }),phone: Property.ShortText({ displayName: 'Phone', required: false }),- address: Property.LongText({ displayName: 'Address', required: false }),- city: Property.ShortText({ displayName: 'City', required: false }),- zip: Property.ShortText({ displayName: 'ZIP Code', required: false }),- country: ninjapipeCommon.countryDropdown,- state: Property.ShortText({ displayName: 'State', required: false }),+ website: Property.ShortText({ displayName: 'Website', required: false }),+ industry: Property.ShortText({ displayName: 'Industry', required: false }),status: Property.ShortText({ displayName: 'Status', required: false }),- owner: Property.ShortText({ displayName: 'Owner', required: false }),- notes: Property.LongText({ displayName: 'Notes', required: false }),- customFields: Property.Object({ displayName: 'Custom Fields', required: false }),+ owner: ninjapipeProps.member({ displayName: 'Owner', description: 'Workspace member who owns the company (owner_id).' }),+ customFields: ninjapipeProps.customFields({ update: false }),},async run(context) {- const auth = getAuth(context);const p = context.propsValue;- const body: Record<string, unknown> = {};- if (p.name) body['name'] = p.name;- if (p.industry) body['industry'] = p.industry;- if (p.website) body['website'] = p.website;- if (p.email) body['email'] = p.email;- if (p.phone) body['phone'] = p.phone;- if (p.address) body['address'] = p.address;- if (p.city) body['city'] = p.city;- if (p.zip) body['zip'] = p.zip;- if (p.country) body['country'] = p.country;- if (p.state) body['state'] = p.state;- if (p.status) body['status'] = p.status;- if (p.owner) body['owner'] = p.owner;- if (p.notes) body['notes'] = p.notes;- if (p.customFields && typeof p.customFields === 'object') body['custom_fields'] = p.customFields;- const response = await ninjapipeApiCall<Record<string, unknown>>({ auth, method: HttpMethod.POST, path: '/companies', body });- return flattenCustomFields(response.body);+ const body = ninjapipeFields.compact({+ name: p.name,+ email: p.email,+ phone: p.phone,+ website: p.website,+ industry: p.industry,+ status: p.status,+ owner_id: p.owner,+ fields: ninjapipeFields.readCustomFields(p.customFields),+ });+ return ninjapipeClient.sendRecord({+ auth: ninjapipeClient.readAuth(context.auth),+ method: HttpMethod.POST,+ path: '/companies',+ body,+ operation: 'create company',+ });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/create-contact.ts b/packages/pieces/community/ninjapipe/src/lib/actions/create-contact.tsindex 3f054a3748e..4b953e83a97 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/create-contact.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/create-contact.ts@@ -1,31 +1,25 @@-import { createAction, Property } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, extractItems, flattenCustomFields, getAuth, ninjapipeCommon } from '../common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { NinjaPipeApiError, ninjapipeClient } from '../common/client';+import { ninjapipeContacts } from '../common/contact-props';+import { ninjapipeRecords } from '../common/records';+import { ninjapipeSchemas } from '../output-schemas';export const createContact = createAction({auth: ninjapipeAuth,name: 'create_contact',classification: 'WRITE',displayName: 'Create Contact',- description: 'Creates a new contact. Choose what happens if a contact with the same email already exists.',- audience: 'both',- aiMetadata: { description: 'Create a NinjaPipe contact. Email is the only required field; the "If Contact Exists" mode controls duplicate handling (error, skip, get existing, or update existing) when the email already exists. Default mode (error) is non-idempotent and will fail on re-run; pick "update existing" or "upsert-contact" for safe retries.', idempotent: false },+ description: 'Creates a contact. Choose what happens when a contact with the same email already exists.',+ audience: 'human',+ aiMetadata: {+ description: 'Create a NinjaPipe contact. When the email already exists, the If Contact Exists mode decides: fail, skip, return the existing contact, or update it. The default (fail) is not safe to retry.',+ idempotent: false,+ },+ outputSchema: ninjapipeSchemas.contactWithAction,props: {- firstName: Property.ShortText({ displayName: 'First Name', required: false }),- lastName: Property.ShortText({ displayName: 'Last Name', required: false }),- email: Property.ShortText({ displayName: 'Email', description: 'The email address of the contact.', required: true }),- phone: Property.ShortText({ displayName: 'Phone', required: false }),- company: Property.ShortText({ displayName: 'Company', description: 'Company name or ID.', required: false }),- status: Property.ShortText({ displayName: 'Status', required: false }),- owner: Property.ShortText({ displayName: 'Owner', required: false }),- address: Property.LongText({ displayName: 'Address', required: false }),- city: Property.ShortText({ displayName: 'City', required: false }),- zip: Property.ShortText({ displayName: 'ZIP Code', required: false }),- country: ninjapipeCommon.countryDropdown,- state: Property.ShortText({ displayName: 'State', required: false }),- notes: Property.LongText({ displayName: 'Notes', required: false }),- customFields: Property.Object({ displayName: 'Custom Fields', description: 'Key-value pairs sent as custom_fields.', required: false }),+ ...ninjapipeContacts.contactProps({ emailRequired: true }),ifContactExists: Property.StaticDropdown({displayName: 'If Contact Exists',description: 'What to do when a contact with this email already exists.',@@ -33,80 +27,32 @@ export const createContact = createAction({defaultValue: 'error',options: {options: [- { label: 'Throw Error', value: 'error' },+ { label: 'Fail the step', value: 'error' },{ label: 'Skip', value: 'skip' },- { label: 'Get Existing', value: 'getExisting' },- { label: 'Update Existing', value: 'updateExisting' },+ { label: 'Return the existing contact', value: 'getExisting' },+ { label: 'Update the existing contact', value: 'updateExisting' },],},}),},async run(context) {- const auth = getAuth(context);+ const auth = ninjapipeClient.readAuth(context.auth);const p = context.propsValue;- const body: Record<string, unknown> = {};- if (p.firstName) body['first_name'] = p.firstName;- if (p.lastName) body['last_name'] = p.lastName;- if (p.email) body['email'] = p.email;- if (p.phone) body['phone'] = p.phone;- if (p.company) body['company'] = p.company;- if (p.status) body['status'] = p.status;- if (p.owner) body['owner'] = p.owner;- if (p.address) body['address'] = p.address;- if (p.city) body['city'] = p.city;- if (p.zip) body['zip'] = p.zip;- if (p.country) body['country'] = p.country;- if (p.state) body['state'] = p.state;- if (p.notes) body['notes'] = p.notes;- if (p.customFields && typeof p.customFields === 'object') {- body['custom_fields'] = p.customFields;- }-+ const body = ninjapipeContacts.contactBody(p);try {- const response = await ninjapipeApiCall<Record<string, unknown>>({- auth,- method: HttpMethod.POST,- path: '/contacts',- body,- });- return flattenCustomFields(response.body);+ const created = await ninjapipeClient.sendRecord({ auth, method: HttpMethod.POST, path: '/contacts', body, operation: 'create contact' });+ return { action: 'created', ...created };} catch (error) {- const err = error as { response?: { status?: number }; status?: number; message?: string };- const status = err.response?.status ?? err.status ?? 0;- if (status === 409 && p.ifContactExists && p.ifContactExists !== 'error') {- const search = await ninjapipeApiCall<Record<string, unknown>>({- auth,- method: HttpMethod.GET,- path: '/contacts',- queryParams: { search: p.email, limit: '5' },- });- const items = extractItems(search.body) as ContactRecord[];- const existing = items.find(- (c) => c.email?.toLowerCase() === p.email.toLowerCase(),- );- if (!existing) {- throw new Error('Duplicate detected but could not locate existing contact by email.');- }-- if (p.ifContactExists === 'skip') {- return { skipped: true, reason: 'contact_exists', email: p.email, existing_id: existing.id };- }- if (p.ifContactExists === 'getExisting') {- return flattenCustomFields(existing as unknown as Record<string, unknown>);- }- if (p.ifContactExists === 'updateExisting') {- const update = await ninjapipeApiCall<Record<string, unknown>>({- auth,- method: HttpMethod.PUT,- path: `/contacts/${encodeURIComponent(String(existing.id))}`,- body,- });- return flattenCustomFields(update.body);- }- }- throw new Error(`Failed to create contact: ${err.message ?? String(error)}`);+ const mode = p.ifContactExists ?? 'error';+ if (!(error instanceof NinjaPipeApiError) || error.status !== 409 || mode === 'error') throw error;+ const existing = await ninjapipeRecords.findContactByEmail({ auth, email: String(p.email) });+ if (!existing) throw error;+ if (mode === 'skip') return { action: 'skipped', ...existing };+ if (mode === 'getExisting') return { action: 'existing', ...existing };+ const contactPath = `/contacts/${ninjapipeClient.pathId({ value: existing['id'], field: 'Contact ID' })}`;+ const updateBody = await ninjapipeContacts.contactUpdateBody({ auth, contactPath, p, clear: undefined });+ const updated = await ninjapipeClient.sendRecord({ auth, method: HttpMethod.PUT, path: contactPath, body: updateBody, operation: 'update contact' });+ return { action: 'updated', ...updated };}},});--type ContactRecord = { id?: string | number; email?: string };diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/create-deal.ts b/packages/pieces/community/ninjapipe/src/lib/actions/create-deal.tsindex 56f1168e483..1609c6485b4 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/create-deal.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/create-deal.ts@@ -1,45 +1,49 @@-import { createAction, Property } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, flattenCustomFields, getAuth, ninjapipeCommon } from '../common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeFields } from '../common/fields';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const createDeal = createAction({auth: ninjapipeAuth,name: 'create_deal',classification: 'WRITE',displayName: 'Create Deal',- description: 'Creates a new deal.',- audience: 'both',- aiMetadata: { description: 'Creates a new deal (sales opportunity) in NinjaPipe, optionally tied to a pipeline, company, and contact, with value/currency, status, owner, and custom fields. Only Name is required. Not idempotent: each call adds another deal, so guard against duplicates.', idempotent: false },+ description: 'Creates a deal.',+ audience: 'human',+ aiMetadata: {+ description: 'Create a NinjaPipe deal. Required: name. Not idempotent: each call creates another deal.',+ idempotent: false,+ },+ outputSchema: ninjapipeSchemas.deal,props: {name: Property.ShortText({ displayName: 'Name', required: true }),- title: Property.ShortText({ displayName: 'Title', required: false }),- status: Property.ShortText({ displayName: 'Status', required: false }),- value: Property.Number({ displayName: 'Value', required: false }),- currency: Property.ShortText({ displayName: 'Currency', description: 'e.g. EUR, USD', required: false }),- owner: Property.ShortText({ displayName: 'Owner', required: false }),- pipelineId: ninjapipeCommon.pipelineDropdown,- companyId: ninjapipeCommon.companyDropdown,- contactId: ninjapipeCommon.contactDropdown,- notes: Property.LongText({ displayName: 'Notes', required: false }),- customFields: Property.Object({ displayName: 'Custom Fields', required: false }),+ value: Property.Number({ displayName: 'Value', description: 'Deal value as a number.', required: false }),+ status: ninjapipeProps.staticDropdown({ displayName: 'Status', description: 'Status.', values: ['Open', 'In Progress', 'Won', 'Lost'] }),+ owner: ninjapipeProps.member({ displayName: 'Owner', description: 'Workspace member who owns the deal (owner_id).' }),+ contactId: ninjapipeProps.contactOptional(),+ companyId: ninjapipeProps.companyOptional(),+ customFields: ninjapipeProps.customFields({ update: false }),},async run(context) {- const auth = getAuth(context);const p = context.propsValue;- const body: Record<string, unknown> = {};- if (p.name) body['name'] = p.name;- if (p.title) body['title'] = p.title;- if (p.status) body['status'] = p.status;- if (p.value !== undefined) body['value'] = p.value;- if (p.currency) body['currency'] = p.currency;- if (p.owner) body['owner'] = p.owner;- if (p.pipelineId) body['pipeline_id'] = p.pipelineId;- if (p.companyId) body['company_id'] = p.companyId;- if (p.contactId) body['contact_id'] = p.contactId;- if (p.notes) body['notes'] = p.notes;- if (p.customFields && typeof p.customFields === 'object') body['custom_fields'] = p.customFields;- const response = await ninjapipeApiCall<Record<string, unknown>>({ auth, method: HttpMethod.POST, path: '/deals', body });- return flattenCustomFields(response.body);+ const body = ninjapipeFields.compact({+ name: p.name,+ value: ninjapipeFields.toNumber({ value: p.value, field: 'Value' }),+ status: p.status,+ owner_id: p.owner,+ contact_id: p.contactId,+ company_id: p.companyId,+ fields: ninjapipeFields.readCustomFields(p.customFields),+ });+ return ninjapipeClient.sendRecord({+ auth: ninjapipeClient.readAuth(context.auth),+ method: HttpMethod.POST,+ path: '/deals',+ body,+ operation: 'create deal',+ });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/create-order.ts b/packages/pieces/community/ninjapipe/src/lib/actions/create-order.tsindex 8d65a7a2d6c..690d348e6cf 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/create-order.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/create-order.ts@@ -1,81 +1,61 @@-import { createAction, Property } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, flattenCustomFields, getAuth, ninjapipeCommon, toDateOnly } from '../common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeFields } from '../common/fields';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const createOrder = createAction({auth: ninjapipeAuth,name: 'create_order',classification: 'WRITE',displayName: 'Create Order',- description: 'Creates a new order. Line items, currency, and custom fields go in Settings JSON.',+ description: 'Creates an order.',audience: 'both',- aiMetadata: { description: 'Creates a new order with customer details, amounts, status, payment status, dates, priority, and tracking; line items, currency, and custom fields go in Settings JSON. Only Customer Name is required, and Order Number defaults to ORD-<timestamp> if omitted. Not idempotent: each call creates another order.', idempotent: false },+ aiMetadata: {+ description: 'Create a NinjaPipe order. Required: customer_name. Not idempotent: each call creates another order.',+ idempotent: false,+ },+ outputSchema: ninjapipeSchemas.order,props: {- customerName: Property.ShortText({- displayName: 'Customer Name',- description: 'Customer display name.',- required: true,- }),+ customerName: Property.ShortText({ displayName: 'Customer Name', required: true }),customerEmail: Property.ShortText({ displayName: 'Customer Email', required: false }),customerCompany: Property.ShortText({ displayName: 'Customer Company', required: false }),- contactId: ninjapipeCommon.contactDropdown,- orderNumber: Property.ShortText({- displayName: 'Order Number',- description: 'Defaults to ORD-<timestamp> if omitted.',- required: false,- }),+ contactId: ninjapipeProps.contactOptional(),+ orderNumber: Property.ShortText({ displayName: 'Order Number', required: false }),totalAmount: Property.Number({ displayName: 'Total Amount', required: false }),- status: ninjapipeCommon.orderStatusDropdown,- paymentStatus: ninjapipeCommon.paymentStatusDropdown,- orderDate: Property.DateTime({- displayName: 'Order Date',- required: false,- }),- deliveryDate: Property.DateTime({- displayName: 'Delivery Date',- required: false,- }),- priority: ninjapipeCommon.priorityDropdown,+ status: ninjapipeProps.staticDropdown({ displayName: 'Status', description: 'Status.', values: ['Processing', 'Shipped', 'Delivered', 'Cancelled'] }),+ paymentStatus: ninjapipeProps.staticDropdown({ displayName: 'Payment Status', description: 'Payment Status.', values: ['Pending', 'Paid', 'Refunded', 'Failed'] }),+ orderDate: Property.DateTime({ displayName: 'Order Date', description: 'Date (YYYY-MM-DD).', required: false }),+ deliveryDate: Property.DateTime({ displayName: 'Delivery Date', description: 'Date (YYYY-MM-DD).', required: false }),+ priority: ninjapipeProps.staticDropdown({ displayName: 'Priority', description: 'Priority.', values: ['High', 'Medium', 'Low'] }),trackingNumber: Property.ShortText({ displayName: 'Tracking Number', required: false }),notes: Property.LongText({ displayName: 'Notes', required: false }),- settingsJson: Property.Object({- displayName: 'Settings JSON',- description: 'Line items, currency, and custom fields. Example: {"currency":"USD","items":[{"name":"…","price":10}],"custom_fields":[]}.',- required: false,- }),},async run(context) {- const auth = getAuth(context);const p = context.propsValue;- const body: Record<string, unknown> = { customer_name: p.customerName };- if (p.customerEmail) body['customer_email'] = p.customerEmail;- if (p.customerCompany) body['customer_company'] = p.customerCompany;- if (p.contactId) body['contact_id'] = p.contactId;- if (p.orderNumber) body['order_number'] = p.orderNumber;- if (p.totalAmount !== undefined && p.totalAmount !== null) body['total_amount'] = p.totalAmount;- if (p.status) body['status'] = p.status;- if (p.paymentStatus) body['payment_status'] = p.paymentStatus;- {- const v = toDateOnly(p.orderDate);- if (v) body['order_date'] = v;- }- {- const v = toDateOnly(p.deliveryDate);- if (v) body['delivery_date'] = v;- }- if (p.priority) body['priority'] = p.priority;- if (p.trackingNumber) body['tracking_number'] = p.trackingNumber;- if (p.notes) body['notes'] = p.notes;- if (p.settingsJson && typeof p.settingsJson === 'object' && Object.keys(p.settingsJson).length > 0) {- body['settings_json'] = p.settingsJson;- }- const response = await ninjapipeApiCall<Record<string, unknown>>({- auth,+ const body = ninjapipeFields.compact({+ customer_name: p.customerName,+ customer_email: p.customerEmail,+ customer_company: p.customerCompany,+ contact_id: p.contactId,+ order_number: p.orderNumber,+ total_amount: ninjapipeFields.toNumber({ value: p.totalAmount, field: 'Total Amount' }),+ status: p.status,+ payment_status: p.paymentStatus,+ order_date: ninjapipeFields.toDateOnly({ value: p.orderDate, field: 'Order Date' }),+ delivery_date: ninjapipeFields.toDateOnly({ value: p.deliveryDate, field: 'Delivery Date' }),+ priority: p.priority,+ tracking_number: p.trackingNumber,+ notes: p.notes,+ });+ return ninjapipeClient.sendRecord({+ auth: ninjapipeClient.readAuth(context.auth),method: HttpMethod.POST,path: '/orders',body,+ operation: 'create order',});- return flattenCustomFields(response.body);},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/create-pipeline-item.ts b/packages/pieces/community/ninjapipe/src/lib/actions/create-pipeline-item.tsnew file mode 100644index 00000000000..a47a91f134f--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/actions/create-pipeline-item.ts@@ -0,0 +1,34 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeItems } from '../common/pipeline-item-props';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';++export const createPipelineItem = createAction({+ auth: ninjapipeAuth,+ name: 'create_pipeline_item',+ classification: 'WRITE',+ displayName: 'Create Pipeline Item',+ description: 'Adds an item (card) to a stage of a pipeline.',+ audience: 'human',+ aiMetadata: { description: 'Create an item (card) in a NinjaPipe pipeline stage. Not idempotent: each call adds another card.', idempotent: false },+ outputSchema: ninjapipeSchemas.pipelineItem,+ props: {+ pipelineId: ninjapipeProps.pipelineRequired(),+ stageId: ninjapipeProps.stageRequired(),+ title: Property.ShortText({ displayName: 'Title', required: true }),+ ...ninjapipeItems.itemProps(),+ },+ async run(context) {+ const p = context.propsValue;+ return ninjapipeClient.sendRecord({+ auth: ninjapipeClient.readAuth(context.auth),+ method: HttpMethod.POST,+ path: `/pipelines/${ninjapipeClient.pathId({ value: p.pipelineId, field: 'Pipeline' })}/items`,+ body: ninjapipeItems.itemBody(p),+ operation: 'create pipeline item',+ });+ },+});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/create-pipeline.ts b/packages/pieces/community/ninjapipe/src/lib/actions/create-pipeline.tsindex 811c8a2f074..2fc72c1fc22 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/create-pipeline.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/create-pipeline.ts@@ -1,21 +1,28 @@-import { createAction, Property } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, flattenCustomFields, getAuth } from '../common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeFields } from '../common/fields';+import { ninjapipePipelines } from '../common/pipelines';+import { ninjapipeSchemas } from '../output-schemas';export const createPipeline = createAction({auth: ninjapipeAuth,name: 'create_pipeline',classification: 'WRITE',displayName: 'Create Pipeline',- description: 'Creates a new pipeline.',+ description: 'Creates a pipeline (board) with its stages.',audience: 'both',- aiMetadata: { description: 'Creates a new pipeline of a given type (contacts, deals, or general) with at least one stage, each stage needing an id, name, and hex color. Requires name, pipeline type, and a non-empty stages array. Not idempotent: each call creates another pipeline.', idempotent: false },+ aiMetadata: {+ description: 'Create a NinjaPipe pipeline of type deals, contacts or general with an ordered list of stages (each needs a name; id and hex color are optional and generated when missing). Not idempotent: each call creates another pipeline.',+ idempotent: false,+ },+ outputSchema: ninjapipeSchemas.pipeline,props: {name: Property.ShortText({ displayName: 'Name', required: true }),pipelineType: Property.StaticDropdown({displayName: 'Pipeline Type',- description: 'Required by NinjaPipe — what this pipeline tracks.',+ description: 'What this pipeline tracks.',required: true,defaultValue: 'general',options: {@@ -28,54 +35,26 @@ export const createPipeline = createAction({}),stages: Property.Array({displayName: 'Stages',- description: 'Pipeline stages. Add at least one. Color must be a hex like #3b82f6.',+ description: 'Stages in board order. Add at least one.',required: true,properties: {- id: Property.ShortText({- displayName: 'ID',- description: 'Stable slug, e.g. "new", "won".',- required: true,- }),- name: Property.ShortText({- displayName: 'Name',- description: 'Display name shown on the board.',- required: true,- }),- color: Property.ShortText({- displayName: 'Color',- description: 'Hex color, e.g. #3b82f6.',- required: true,- }),+ name: Property.ShortText({ displayName: 'Name', description: 'Name shown on the board.', required: true }),+ id: Property.ShortText({ displayName: 'ID', description: 'Optional stable ID, e.g. "won". Generated from the name when empty.', required: false }),+ color: Property.ShortText({ displayName: 'Color', description: 'Optional hex color, e.g. #3b82f6.', required: false }),},}),description: Property.LongText({ displayName: 'Description', required: false }),- status: Property.ShortText({ displayName: 'Status', required: false }),+ status: Property.ShortText({ displayName: 'Status', description: 'e.g. Active.', required: false }),},async run(context) {- const auth = getAuth(context);const p = context.propsValue;- if (!Array.isArray(p.stages) || p.stages.length === 0) {- throw new Error('Stages must contain at least one entry with id, name, and color.');- }- const stages = (p.stages as Array<{ id?: unknown; name?: unknown; color?: unknown }>).map((stage) => {- if (!stage?.id || !stage.name || !stage.color) {- throw new Error('Each stage requires id, name, and color.');- }- return { id: String(stage.id), name: String(stage.name), color: String(stage.color) };- });- const body: Record<string, unknown> = {+ const body = ninjapipeFields.compact({name: p.name,pipeline_type: p.pipelineType,- stages,- };- if (p.description) body['description'] = p.description;- if (p.status) body['status'] = p.status;- const response = await ninjapipeApiCall<Record<string, unknown>>({- auth,- method: HttpMethod.POST,- path: '/pipelines',- body,+ stages: ninjapipePipelines.toStages(p.stages),+ description: p.description,+ status: p.status,});- return flattenCustomFields(response.body);+ return ninjapipeClient.sendRecord({ auth: ninjapipeClient.readAuth(context.auth), method: HttpMethod.POST, path: '/pipelines', body, operation: 'create pipeline' });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/create-product.ts b/packages/pieces/community/ninjapipe/src/lib/actions/create-product.tsindex a2ae51aeacf..c508db1fba5 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/create-product.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/create-product.ts@@ -1,45 +1,50 @@-import { createAction, Property } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, flattenCustomFields, getAuth } from '../common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeFields } from '../common/fields';+import { ninjapipeSchemas } from '../output-schemas';export const createProduct = createAction({auth: ninjapipeAuth,name: 'create_product',classification: 'WRITE',displayName: 'Create Product',- description: 'Creates a new product.',+ description: 'Creates a product.',audience: 'both',- aiMetadata: { description: 'Create a new product with a required name, SKU, and price; optionally set description, currency, status, and custom fields. The SKU must be unique within the workspace, so a duplicate SKU is rejected. Not idempotent — each successful call creates a distinct product.', idempotent: false },+ aiMetadata: {+ description: 'Create a NinjaPipe product. Required: name. Not idempotent: each call creates another product.',+ idempotent: false,+ },+ outputSchema: ninjapipeSchemas.product,props: {- name: Property.ShortText({ displayName: 'Name', description: 'Product name.', required: true }),- sku: Property.ShortText({- displayName: 'SKU',- description: 'Product SKU. Must be unique within your workspace.',- required: true,- }),- price: Property.Number({- displayName: 'Price',- description: 'Product price.',- required: true,- }),+ name: Property.ShortText({ displayName: 'Name', required: true }),+ sku: Property.ShortText({ displayName: 'SKU', required: false }),+ price: Property.Number({ displayName: 'Price', required: false }),+ cost: Property.Number({ displayName: 'Cost', required: false }),description: Property.LongText({ displayName: 'Description', required: false }),- currency: Property.ShortText({ displayName: 'Currency', required: false }),+ currency: Property.ShortText({ displayName: 'Currency', description: 'ISO currency code, e.g. EUR.', required: false }),status: Property.ShortText({ displayName: 'Status', required: false }),- customFields: Property.Object({ displayName: 'Custom Fields', required: false }),+ category: Property.ShortText({ displayName: 'Category', required: false }),},async run(context) {- const auth = getAuth(context);const p = context.propsValue;- const body: Record<string, unknown> = {};- if (p.name) body['name'] = p.name;- if (p.sku) body['sku'] = p.sku;- if (p.description) body['description'] = p.description;- if (p.price !== undefined) body['price'] = p.price;- if (p.currency) body['currency'] = p.currency;- if (p.status) body['status'] = p.status;- if (p.customFields && typeof p.customFields === 'object') body['custom_fields'] = p.customFields;- const response = await ninjapipeApiCall<Record<string, unknown>>({ auth, method: HttpMethod.POST, path: '/products', body });- return flattenCustomFields(response.body);+ const body = ninjapipeFields.compact({+ name: p.name,+ sku: p.sku,+ price: ninjapipeFields.toNumber({ value: p.price, field: 'Price' }),+ cost: ninjapipeFields.toNumber({ value: p.cost, field: 'Cost' }),+ description: p.description,+ currency: p.currency,+ status: p.status,+ category: p.category,+ });+ return ninjapipeClient.sendRecord({+ auth: ninjapipeClient.readAuth(context.auth),+ method: HttpMethod.POST,+ path: '/products',+ body,+ operation: 'create product',+ });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/create-project.ts b/packages/pieces/community/ninjapipe/src/lib/actions/create-project.tsindex d388494dc11..fda83e18d30 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/create-project.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/create-project.ts@@ -1,63 +1,49 @@-import { createAction, Property } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, flattenCustomFields, getAuth, ninjapipeCommon, toDateOnly } from '../common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeFields } from '../common/fields';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const createProject = createAction({auth: ninjapipeAuth,name: 'create_project',classification: 'WRITE',displayName: 'Create Project',- description: 'Creates a new project.',+ description: 'Creates a project.',audience: 'both',- aiMetadata: { description: 'Creates a new project in NinjaPipe with optional description, status, priority, due date, linked contact, team members, tags, and extra settings. Only Name is required. Not idempotent: each call creates another project, so avoid retries that would duplicate it.', idempotent: false },+ aiMetadata: {+ description: 'Create a NinjaPipe project. Required: name. Not idempotent: each call creates another project.',+ idempotent: false,+ },+ outputSchema: ninjapipeSchemas.project,props: {name: Property.ShortText({ displayName: 'Name', required: true }),description: Property.LongText({ displayName: 'Description', required: false }),- status: ninjapipeCommon.projectStatusDropdown,- priority: ninjapipeCommon.priorityDropdown,- dueDate: Property.DateTime({- displayName: 'Due Date',- required: false,- }),- contactId: ninjapipeCommon.contactDropdown,- team: Property.Array({- displayName: 'Team',- description: 'Optional list of team members (account IDs).',- required: false,- }),+ status: ninjapipeProps.staticDropdown({ displayName: 'Status', description: 'Status.', values: ['Planning', 'In Progress', 'Completed', 'On Hold', 'Cancelled'] }),+ priority: ninjapipeProps.staticDropdown({ displayName: 'Priority', description: 'Priority.', values: ['High', 'Medium', 'Low'] }),+ dueDate: Property.DateTime({ displayName: 'Due Date', description: 'Date (YYYY-MM-DD).', required: false }),+ team: Property.Array({ displayName: 'Team Member IDs', required: false }),tags: Property.Array({ displayName: 'Tags', required: false }),- settingsJson: Property.Object({- displayName: 'Extra Settings',- description: 'Optional metadata (e.g. linked contact, custom fields).',- required: false,- }),},async run(context) {- const auth = getAuth(context);const p = context.propsValue;- const body: Record<string, unknown> = { name: p.name };- if (p.description) body['description'] = p.description;- if (p.status) body['status'] = p.status;- if (p.priority) body['priority'] = p.priority;- {- const v = toDateOnly(p.dueDate);- if (v) body['due_date'] = v;- }- if (p.team && Array.isArray(p.team) && p.team.length > 0) body['team'] = p.team;- if (p.tags && Array.isArray(p.tags) && p.tags.length > 0) body['tags'] = p.tags;- const settings: Record<string, unknown> =- p.settingsJson && typeof p.settingsJson === 'object'- ? { ...(p.settingsJson as Record<string, unknown>) }- : {};- if (p.contactId) settings['contact_id'] = p.contactId;- if (Object.keys(settings).length > 0) body['settings_json'] = settings;- const response = await ninjapipeApiCall<Record<string, unknown>>({- auth,+ const body = ninjapipeFields.compact({+ name: p.name,+ description: p.description,+ status: p.status,+ priority: p.priority,+ due_date: ninjapipeFields.toDateOnly({ value: p.dueDate, field: 'Due Date' }),+ team: ninjapipeFields.toStringList(p.team),+ tags: ninjapipeFields.toStringList(p.tags),+ });+ return ninjapipeClient.sendRecord({+ auth: ninjapipeClient.readAuth(context.auth),method: HttpMethod.POST,path: '/projects',body,+ operation: 'create project',});- return flattenCustomFields(response.body);},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/create-task.ts b/packages/pieces/community/ninjapipe/src/lib/actions/create-task.tsindex d9f7edbe919..2b8a0599239 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/create-task.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/create-task.ts@@ -1,66 +1,32 @@-import { createAction, Property } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, flattenCustomFields, getAuth, ninjapipeCommon, toDateOnly } from '../common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeProps } from '../common/props';+import { ninjapipeTasks } from '../common/task-props';+import { ninjapipeSchemas } from '../output-schemas';export const createTask = createAction({auth: ninjapipeAuth,name: 'create_task',classification: 'WRITE',displayName: 'Create Task',- description: 'Creates a task or subtask in a project.',- audience: 'both',- aiMetadata: { description: 'Creates a task inside a given project, with optional description, status, priority, assignee, due date, tags, and settings. Set Parent Task ID to instead create a subtask under an existing task in the same project. Requires a project ID and title; not idempotent, so each call adds another task.', idempotent: false },+ description: 'Creates a task in a project.',+ audience: 'human',+ aiMetadata: { description: 'Create a task in a NinjaPipe project. Not idempotent: each call creates another task.', idempotent: false },+ outputSchema: ninjapipeSchemas.task,props: {- projectId: ninjapipeCommon.projectDropdownRequired,- title: Property.ShortText({ displayName: 'Title', description: 'Task title.', required: true }),- description: Property.LongText({ displayName: 'Description', required: false }),- status: ninjapipeCommon.taskStatusDropdown,- priority: ninjapipeCommon.priorityDropdown,- assigneeId: Property.ShortText({- displayName: 'Assignee ID',- description: 'Account ID of the user to assign this task to.',- required: false,- }),- dueDate: Property.DateTime({- displayName: 'Due Date',- required: false,- }),- parentId: Property.ShortText({- displayName: 'Parent Task ID',- description: 'Set to make this a subtask of another task in the same project.',- required: false,- }),- tags: Property.Array({ displayName: 'Tags', required: false }),- settingsJson: Property.Object({- displayName: 'Extra Settings',- description: 'Additional task settings as a JSON object.',- required: false,- }),+ projectId: ninjapipeProps.projectRequired(),+ ...ninjapipeTasks.taskProps({ titleRequired: true }),},async run(context) {- const auth = getAuth(context);const p = context.propsValue;- const body: Record<string, unknown> = { title: p.title };- if (p.description) body['description'] = p.description;- if (p.status) body['status'] = p.status;- if (p.priority) body['priority'] = p.priority;- if (p.assigneeId) body['assignee_id'] = p.assigneeId;- {- const v = toDateOnly(p.dueDate);- if (v) body['due_date'] = v;- }- if (p.parentId) body['parent_id'] = p.parentId;- if (p.tags && Array.isArray(p.tags) && p.tags.length > 0) body['tags'] = p.tags;- if (p.settingsJson && typeof p.settingsJson === 'object' && Object.keys(p.settingsJson).length > 0) {- body['settings_json'] = p.settingsJson;- }- const response = await ninjapipeApiCall<Record<string, unknown>>({- auth,+ return ninjapipeClient.sendRecord({+ auth: ninjapipeClient.readAuth(context.auth),method: HttpMethod.POST,- path: `/projects/${encodeURIComponent(String(p.projectId))}/tasks`,- body,+ path: `/projects/${ninjapipeClient.pathId({ value: p.projectId, field: 'Project' })}/tasks`,+ body: ninjapipeTasks.taskBody(p),+ operation: 'create task',});- return flattenCustomFields(response.body);},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/custom-api-call.ts b/packages/pieces/community/ninjapipe/src/lib/actions/custom-api-call.tsnew file mode 100644index 00000000000..9472a7bd64a--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/actions/custom-api-call.ts@@ -0,0 +1,52 @@+import { createCustomApiCallAction } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';++const baseAction = createCustomApiCallAction({+ baseUrl: (auth) => (auth ? ninjapipeClient.readAuth(auth).baseUrl : ''),+ auth: ninjapipeAuth,+ authMapping: async (auth) => ({+ Authorization: `Bearer ${ninjapipeClient.readAuth(auth).apiKey}`,+ }),+});++export const ninjapipeCustomApiCall = createAction({+ auth: ninjapipeAuth,+ name: 'custom_api_call',+ displayName: baseAction.displayName,+ description: 'Sends an authenticated request to the NinjaPipe API of the connected workspace. The URL must be a path or a URL on the connected API Base URL.',+ props: baseAction.props,+ propertyGroups: baseAction.propertyGroups,+ errorHandlingOptions: baseAction.errorHandlingOptions,+ classification: 'WRITE',+ audience: 'human',+ aiMetadata: {+ description: 'Send a raw authenticated request to the NinjaPipe REST API of the connected workspace, for endpoints no other step covers. The URL must stay on the connection API Base URL.',+ idempotent: false,+ },+ async run(context) {+ const { baseUrl } = ninjapipeClient.readAuth(context.auth);+ const url = ninjapipeClient.isRecord(context.propsValue.url) ? context.propsValue.url['url'] : undefined;+ assertSameApi({ url, baseUrl });+ return baseAction.run(context);+ },+});++function assertSameApi({ url, baseUrl }: { url: unknown; baseUrl: string }): void {+ if (typeof url !== 'string') throw new Error('URL is required.');+ const value = url.trim();+ if (!/^https?:\/\//i.test(value)) {+ if (value.startsWith('//') || value.includes('..') || value.includes('\\')) {+ throw new Error('URL must be a path under the connected NinjaPipe API Base URL.');+ }+ return;+ }+ const target = new URL(value);+ const base = new URL(baseUrl);+ const basePath = base.pathname.replace(/\/+$/, '');+ const pathOk = target.pathname === basePath || target.pathname.startsWith(`${basePath}/`);+ if (target.origin !== base.origin || target.username || target.password || !pathOk || target.pathname.includes('..')) {+ throw new Error(`URL must be on the connected NinjaPipe API (${base.origin}${basePath}). Requests to other hosts are refused because they would carry your API key.`);+ }+}diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/delete-budget.ts b/packages/pieces/community/ninjapipe/src/lib/actions/delete-budget.tsindex 25d8a6c167e..5fc8aa98862 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/delete-budget.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/delete-budget.ts@@ -1,22 +1,31 @@-import { createAction } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, getAuth, ninjapipeCommon } from '../common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const deleteBudget = createAction({auth: ninjapipeAuth,name: 'delete_budget',classification: 'DESTRUCTIVE',displayName: 'Delete Budget',- description: 'Deletes a budget by ID.',+ description: 'Permanently deletes a budget.',audience: 'both',- aiMetadata: { description: 'Permanently deletes a budget identified by Budget ID. Pick this to remove a budget and its tracking; the change is destructive and cannot be undone. Re-running after deletion typically fails since the ID no longer exists.', idempotent: false },+ aiMetadata: {+ description: 'Permanently delete one NinjaPipe budget by ID (budgetId; get it from a list or search step). Cannot be undone. A second call fails with 404 because the budget is gone.',+ idempotent: false,+ },+ outputSchema: ninjapipeSchemas.deleted,props: {- budgetId: ninjapipeCommon.budgetDropdownRequired,+ budgetId: ninjapipeProps.budgetRequired(),},async run(context) {- const auth = getAuth(context);- await ninjapipeApiCall<Record<string, unknown>>({ auth, method: HttpMethod.DELETE, path: `/budgets/${encodeURIComponent(String(context.propsValue.budgetId))}` });- return { success: true, deleted_id: context.propsValue.budgetId };+ const id = ninjapipeClient.pathId({ value: context.propsValue.budgetId, field: 'Budget' });+ return ninjapipeClient.deleteRecord({+ auth: ninjapipeClient.readAuth(context.auth),+ path: `/budgets/${id}`,+ id: decodeURIComponent(id),+ operation: 'delete budget',+ });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/delete-company.ts b/packages/pieces/community/ninjapipe/src/lib/actions/delete-company.tsindex 21fbca07149..ff7e4188b1c 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/delete-company.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/delete-company.ts@@ -1,22 +1,31 @@-import { createAction } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, getAuth, ninjapipeCommon } from '../common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const deleteCompany = createAction({auth: ninjapipeAuth,name: 'delete_company',classification: 'DESTRUCTIVE',displayName: 'Delete Company',- description: 'Deletes a company by ID.',+ description: 'Permanently deletes a company.',audience: 'both',- aiMetadata: { description: 'Permanently delete a company identified by its ID. Destructive and not reversible; re-running after the company is gone will fail since the ID no longer exists.', idempotent: false },+ aiMetadata: {+ description: 'Permanently delete one NinjaPipe company by ID (companyId; get it from a list or search step). Cannot be undone. A second call fails with 404 because the company is gone.',+ idempotent: false,+ },+ outputSchema: ninjapipeSchemas.deleted,props: {- companyId: ninjapipeCommon.companyDropdownRequired,+ companyId: ninjapipeProps.companyRequired(),},async run(context) {- const auth = getAuth(context);- await ninjapipeApiCall<Record<string, unknown>>({ auth, method: HttpMethod.DELETE, path: `/companies/${encodeURIComponent(String(context.propsValue.companyId))}` });- return { success: true, deleted_id: context.propsValue.companyId };+ const id = ninjapipeClient.pathId({ value: context.propsValue.companyId, field: 'Company' });+ return ninjapipeClient.deleteRecord({+ auth: ninjapipeClient.readAuth(context.auth),+ path: `/companies/${id}`,+ id: decodeURIComponent(id),+ operation: 'delete company',+ });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/delete-contact.ts b/packages/pieces/community/ninjapipe/src/lib/actions/delete-contact.tsindex b07fcc1b7c7..b36e5bc96ef 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/delete-contact.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/delete-contact.ts@@ -1,26 +1,31 @@-import { createAction } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, getAuth, ninjapipeCommon } from '../common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const deleteContact = createAction({auth: ninjapipeAuth,name: 'delete_contact',classification: 'DESTRUCTIVE',displayName: 'Delete Contact',- description: 'Deletes a contact by ID.',+ description: 'Permanently deletes a contact.',audience: 'both',- aiMetadata: { description: 'Permanently delete a contact identified by its ID. Destructive and not reversible; re-running after the contact is gone will fail since the ID no longer exists.', idempotent: false },+ aiMetadata: {+ description: 'Permanently delete one NinjaPipe contact by ID (contactId; get it from a list or search step). Cannot be undone. A second call fails with 404 because the contact is gone.',+ idempotent: false,+ },+ outputSchema: ninjapipeSchemas.deleted,props: {- contactId: ninjapipeCommon.contactDropdownRequired,+ contactId: ninjapipeProps.contactRequired(),},async run(context) {- const auth = getAuth(context);- await ninjapipeApiCall<Record<string, unknown>>({- auth,- method: HttpMethod.DELETE,- path: `/contacts/${encodeURIComponent(String(context.propsValue.contactId))}`,+ const id = ninjapipeClient.pathId({ value: context.propsValue.contactId, field: 'Contact' });+ return ninjapipeClient.deleteRecord({+ auth: ninjapipeClient.readAuth(context.auth),+ path: `/contacts/${id}`,+ id: decodeURIComponent(id),+ operation: 'delete contact',});- return { success: true, deleted_id: context.propsValue.contactId };},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/delete-deal.ts b/packages/pieces/community/ninjapipe/src/lib/actions/delete-deal.tsindex 540c93003ee..c8c47400ce6 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/delete-deal.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/delete-deal.ts@@ -1,22 +1,31 @@-import { createAction } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, getAuth, ninjapipeCommon } from '../common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const deleteDeal = createAction({auth: ninjapipeAuth,name: 'delete_deal',classification: 'DESTRUCTIVE',displayName: 'Delete Deal',- description: 'Deletes a deal by ID.',+ description: 'Permanently deletes a deal.',audience: 'both',- aiMetadata: { description: 'Permanently delete a deal identified by its ID. Destructive and not reversible; re-running after the deal is gone will fail since the ID no longer exists.', idempotent: false },+ aiMetadata: {+ description: 'Permanently delete one NinjaPipe deal by ID (dealId; get it from a list or search step). Cannot be undone. A second call fails with 404 because the deal is gone.',+ idempotent: false,+ },+ outputSchema: ninjapipeSchemas.deleted,props: {- dealId: ninjapipeCommon.dealDropdownRequired,+ dealId: ninjapipeProps.dealRequired(),},async run(context) {- const auth = getAuth(context);- await ninjapipeApiCall<Record<string, unknown>>({ auth, method: HttpMethod.DELETE, path: `/deals/${encodeURIComponent(String(context.propsValue.dealId))}` });- return { success: true, deleted_id: context.propsValue.dealId };+ const id = ninjapipeClient.pathId({ value: context.propsValue.dealId, field: 'Deal' });+ return ninjapipeClient.deleteRecord({+ auth: ninjapipeClient.readAuth(context.auth),+ path: `/deals/${id}`,+ id: decodeURIComponent(id),+ operation: 'delete deal',+ });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/delete-order.ts b/packages/pieces/community/ninjapipe/src/lib/actions/delete-order.tsindex 573f252c460..cea9dc68702 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/delete-order.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/delete-order.ts@@ -1,22 +1,31 @@-import { createAction } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, getAuth, ninjapipeCommon } from '../common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const deleteOrder = createAction({auth: ninjapipeAuth,name: 'delete_order',classification: 'DESTRUCTIVE',displayName: 'Delete Order',- description: 'Deletes an order by ID.',+ description: 'Permanently deletes a order.',audience: 'both',- aiMetadata: { description: 'Permanently delete an order identified by its ID. Destructive and not reversible; re-running after the order is gone will fail since the ID no longer exists.', idempotent: false },+ aiMetadata: {+ description: 'Permanently delete one NinjaPipe order by ID (orderId; get it from a list or search step). Cannot be undone. A second call fails with 404 because the order is gone.',+ idempotent: false,+ },+ outputSchema: ninjapipeSchemas.deleted,props: {- orderId: ninjapipeCommon.orderDropdownRequired,+ orderId: ninjapipeProps.orderRequired(),},async run(context) {- const auth = getAuth(context);- await ninjapipeApiCall<Record<string, unknown>>({ auth, method: HttpMethod.DELETE, path: `/orders/${encodeURIComponent(String(context.propsValue.orderId))}` });- return { success: true, deleted_id: context.propsValue.orderId };+ const id = ninjapipeClient.pathId({ value: context.propsValue.orderId, field: 'Order' });+ return ninjapipeClient.deleteRecord({+ auth: ninjapipeClient.readAuth(context.auth),+ path: `/orders/${id}`,+ id: decodeURIComponent(id),+ operation: 'delete order',+ });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/delete-pipeline.ts b/packages/pieces/community/ninjapipe/src/lib/actions/delete-pipeline.tsindex d9e96e0d64f..d82c48b8069 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/delete-pipeline.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/delete-pipeline.ts@@ -1,22 +1,31 @@-import { createAction } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, getAuth, ninjapipeCommon } from '../common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const deletePipeline = createAction({auth: ninjapipeAuth,name: 'delete_pipeline',classification: 'DESTRUCTIVE',displayName: 'Delete Pipeline',- description: 'Deletes a pipeline by ID.',+ description: 'Permanently deletes a pipeline. Its items are removed with it.',audience: 'both',- aiMetadata: { description: 'Permanently delete a NinjaPipe pipeline by its ID. Pick this only when the pipeline should be removed entirely; deletion is irreversible and cascades to the pipeline\'s stages. Safe to retry — deleting an already-deleted pipeline settles to the same removed state.', idempotent: true },+ aiMetadata: {+ description: 'Permanently delete one NinjaPipe pipeline by ID (pipelineId; get it from a list or search step). Cannot be undone. A second call fails with 404 because the pipeline is gone.',+ idempotent: false,+ },+ outputSchema: ninjapipeSchemas.deleted,props: {- pipelineId: ninjapipeCommon.pipelineDropdownRequired,+ pipelineId: ninjapipeProps.pipelineRequired(),},async run(context) {- const auth = getAuth(context);- await ninjapipeApiCall<Record<string, unknown>>({ auth, method: HttpMethod.DELETE, path: `/pipelines/${encodeURIComponent(String(context.propsValue.pipelineId))}` });- return { success: true, deleted_id: context.propsValue.pipelineId };+ const id = ninjapipeClient.pathId({ value: context.propsValue.pipelineId, field: 'Pipeline' });+ return ninjapipeClient.deleteRecord({+ auth: ninjapipeClient.readAuth(context.auth),+ path: `/pipelines/${id}`,+ id: decodeURIComponent(id),+ operation: 'delete pipeline',+ });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/delete-product.ts b/packages/pieces/community/ninjapipe/src/lib/actions/delete-product.tsindex a0231c7efc0..eba3de1e479 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/delete-product.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/delete-product.ts@@ -1,22 +1,31 @@-import { createAction } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, getAuth, ninjapipeCommon } from '../common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const deleteProduct = createAction({auth: ninjapipeAuth,name: 'delete_product',classification: 'DESTRUCTIVE',displayName: 'Delete Product',- description: 'Deletes a product by ID.',+ description: 'Permanently deletes a product.',audience: 'both',- aiMetadata: { description: 'Permanently deletes a product identified by Product ID. Pick this to remove a product from the catalog; the change is destructive and cannot be undone. Re-running after deletion typically fails since the ID no longer exists.', idempotent: false },+ aiMetadata: {+ description: 'Permanently delete one NinjaPipe product by ID (productId; get it from a list or search step). Cannot be undone. A second call fails with 404 because the product is gone.',+ idempotent: false,+ },+ outputSchema: ninjapipeSchemas.deleted,props: {- productId: ninjapipeCommon.productDropdownRequired,+ productId: ninjapipeProps.productRequired(),},async run(context) {- const auth = getAuth(context);- await ninjapipeApiCall<Record<string, unknown>>({ auth, method: HttpMethod.DELETE, path: `/products/${encodeURIComponent(String(context.propsValue.productId))}` });- return { success: true, deleted_id: context.propsValue.productId };+ const id = ninjapipeClient.pathId({ value: context.propsValue.productId, field: 'Product' });+ return ninjapipeClient.deleteRecord({+ auth: ninjapipeClient.readAuth(context.auth),+ path: `/products/${id}`,+ id: decodeURIComponent(id),+ operation: 'delete product',+ });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/delete-project.ts b/packages/pieces/community/ninjapipe/src/lib/actions/delete-project.tsindex b42040fa2d9..62423ef9f80 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/delete-project.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/delete-project.ts@@ -1,22 +1,31 @@-import { createAction } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, getAuth, ninjapipeCommon } from '../common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const deleteProject = createAction({auth: ninjapipeAuth,name: 'delete_project',classification: 'DESTRUCTIVE',displayName: 'Delete Project',- description: 'Deletes a project by ID.',+ description: 'Permanently deletes a project. Its tasks are removed with it.',audience: 'both',- aiMetadata: { description: 'Permanently deletes a project identified by Project ID, including its tasks. Pick this to remove a project entirely; the change is destructive and cannot be undone. Re-running after deletion typically fails since the ID no longer exists.', idempotent: false },+ aiMetadata: {+ description: 'Permanently delete one NinjaPipe project by ID (projectId; get it from a list or search step). Cannot be undone. A second call fails with 404 because the project is gone.',+ idempotent: false,+ },+ outputSchema: ninjapipeSchemas.deleted,props: {- projectId: ninjapipeCommon.projectDropdownRequired,+ projectId: ninjapipeProps.projectRequired(),},async run(context) {- const auth = getAuth(context);- await ninjapipeApiCall<Record<string, unknown>>({ auth, method: HttpMethod.DELETE, path: `/projects/${encodeURIComponent(String(context.propsValue.projectId))}` });- return { success: true, deleted_id: context.propsValue.projectId };+ const id = ninjapipeClient.pathId({ value: context.propsValue.projectId, field: 'Project' });+ return ninjapipeClient.deleteRecord({+ auth: ninjapipeClient.readAuth(context.auth),+ path: `/projects/${id}`,+ id: decodeURIComponent(id),+ operation: 'delete project',+ });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/delete-task.ts b/packages/pieces/community/ninjapipe/src/lib/actions/delete-task.tsindex 533bb2fd952..480f3a42f4e 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/delete-task.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/delete-task.ts@@ -1,28 +1,33 @@import { createAction } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, getAuth, ninjapipeCommon } from '../common';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const deleteTask = createAction({auth: ninjapipeAuth,name: 'delete_task',classification: 'DESTRUCTIVE',displayName: 'Delete Task',- description: 'Deletes a task within a project. Subtasks may cascade.',+ description: 'Permanently deletes a task from a project.',audience: 'both',- aiMetadata: { description: 'Permanently delete a task by ID within a given project; any subtasks may be cascade-deleted along with it. Requires both the project ID and the task ID. Use only when the task should be removed outright; the operation is irreversible and safe to retry since re-deleting settles to the same removed state.', idempotent: true },+ aiMetadata: {+ description: 'Permanently delete one task by project ID and task ID. Cannot be undone. A second call fails with 404 because the task is gone.',+ idempotent: false,+ },+ outputSchema: ninjapipeSchemas.deleted,props: {- projectId: ninjapipeCommon.projectDropdownRequired,- taskId: ninjapipeCommon.taskDropdown,+ projectId: ninjapipeProps.projectRequired(),+ taskId: ninjapipeProps.task(),},async run(context) {- const auth = getAuth(context);- const { projectId, taskId } = context.propsValue;- await ninjapipeApiCall<Record<string, unknown>>({- auth,- method: HttpMethod.DELETE,- path: `/projects/${encodeURIComponent(String(projectId))}/tasks/${encodeURIComponent(String(taskId))}`,+ const p = context.propsValue;+ const taskId = ninjapipeClient.pathId({ value: p.taskId, field: 'Task' });+ return ninjapipeClient.deleteRecord({+ auth: ninjapipeClient.readAuth(context.auth),+ path: `/projects/${ninjapipeClient.pathId({ value: p.projectId, field: 'Project' })}/tasks/${taskId}`,+ id: decodeURIComponent(taskId),+ operation: 'delete task',});- return { success: true, deleted_id: taskId, project_id: projectId };},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/get-budget.ts b/packages/pieces/community/ninjapipe/src/lib/actions/get-budget.tsindex 9b186527fbf..c85e8016970 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/get-budget.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/get-budget.ts@@ -1,22 +1,23 @@-import { createAction } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, flattenCustomFields, getAuth, ninjapipeCommon } from '../common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const getBudget = createAction({auth: ninjapipeAuth,name: 'get_budget',classification: 'READ',displayName: 'Get Budget',- description: 'Retrieves a budget by ID.',+ description: 'Gets one budget by ID.',audience: 'both',- aiMetadata: { description: 'Fetch a single budget by its ID. Read-only lookup for inspecting one budget; to enumerate or search budgets use a list action instead.', idempotent: true },+ aiMetadata: { description: 'Fetch a single NinjaPipe budget by ID. Read-only.', idempotent: true },+ outputSchema: ninjapipeSchemas.budget,props: {- budgetId: ninjapipeCommon.budgetDropdownRequired,+ budgetId: ninjapipeProps.budgetRequired(),},async run(context) {- const auth = getAuth(context);- const response = await ninjapipeApiCall<Record<string, unknown>>({ auth, method: HttpMethod.GET, path: `/budgets/${encodeURIComponent(String(context.propsValue.budgetId))}` });- return flattenCustomFields(response.body);+ const id = ninjapipeClient.pathId({ value: context.propsValue.budgetId, field: 'Budget' });+ return ninjapipeClient.getRecord({ auth: ninjapipeClient.readAuth(context.auth), path: `/budgets/${id}`, operation: 'get budget' });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/get-company.ts b/packages/pieces/community/ninjapipe/src/lib/actions/get-company.tsindex 99d76b641d9..3c29c60afb2 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/get-company.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/get-company.ts@@ -1,22 +1,23 @@-import { createAction } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, flattenCustomFields, getAuth, ninjapipeCommon } from '../common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const getCompany = createAction({auth: ninjapipeAuth,name: 'get_company',classification: 'READ',displayName: 'Get Company',- description: 'Retrieves a company by ID.',- audience: 'both',- aiMetadata: { description: 'Fetch a single company record by its ID. Read-only lookup for inspecting one company; to enumerate or search companies use a list action instead.', idempotent: true },+ description: 'Gets one company by ID.',+ audience: 'human',+ aiMetadata: { description: 'Fetch a single NinjaPipe company by ID. Read-only.', idempotent: true },+ outputSchema: ninjapipeSchemas.company,props: {- companyId: ninjapipeCommon.companyDropdownRequired,+ companyId: ninjapipeProps.companyRequired(),},async run(context) {- const auth = getAuth(context);- const response = await ninjapipeApiCall<Record<string, unknown>>({ auth, method: HttpMethod.GET, path: `/companies/${encodeURIComponent(String(context.propsValue.companyId))}` });- return flattenCustomFields(response.body);+ const id = ninjapipeClient.pathId({ value: context.propsValue.companyId, field: 'Company' });+ return ninjapipeClient.getRecord({ auth: ninjapipeClient.readAuth(context.auth), path: `/companies/${id}`, operation: 'get company' });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/get-contact.ts b/packages/pieces/community/ninjapipe/src/lib/actions/get-contact.tsindex 68d927df64e..6f6120afa12 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/get-contact.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/get-contact.ts@@ -1,26 +1,26 @@-import { createAction } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, flattenCustomFields, getAuth, ninjapipeCommon } from '../common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const getContact = createAction({auth: ninjapipeAuth,name: 'get_contact',classification: 'READ',displayName: 'Get Contact',- description: 'Retrieves a contact by ID.',- audience: 'both',- aiMetadata: { description: 'Fetch a single contact by its ID. Read-only lookup for inspecting one known contact; to search or enumerate contacts (e.g. find one by email) use the list-contacts action instead.', idempotent: true },+ description: 'Gets one contact by ID.',+ audience: 'human',+ aiMetadata: { description: 'Fetch a single NinjaPipe contact by ID, including its custom fields. Read-only.', idempotent: true },+ outputSchema: ninjapipeSchemas.contact,props: {- contactId: ninjapipeCommon.contactDropdownRequired,+ contactId: ninjapipeProps.contactRequired(),},async run(context) {- const auth = getAuth(context);- const response = await ninjapipeApiCall<Record<string, unknown>>({- auth,- method: HttpMethod.GET,- path: `/contacts/${encodeURIComponent(String(context.propsValue.contactId))}`,+ return ninjapipeClient.getRecord({+ auth: ninjapipeClient.readAuth(context.auth),+ path: `/contacts/${ninjapipeClient.pathId({ value: context.propsValue.contactId, field: 'Contact' })}`,+ operation: 'get contact',});- return flattenCustomFields(response.body);},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/get-deal.ts b/packages/pieces/community/ninjapipe/src/lib/actions/get-deal.tsindex 39c068020f6..2c889fd03ff 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/get-deal.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/get-deal.ts@@ -1,22 +1,23 @@-import { createAction } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, flattenCustomFields, getAuth, ninjapipeCommon } from '../common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const getDeal = createAction({auth: ninjapipeAuth,name: 'get_deal',classification: 'READ',displayName: 'Get Deal',- description: 'Retrieves a deal by ID.',- audience: 'both',- aiMetadata: { description: 'Fetches a single deal by its ID, returning its full record. Pick this when you already have a deal ID and need its details; use List Deals instead to search or browse. Read-only and safe to repeat.', idempotent: true },+ description: 'Gets one deal by ID.',+ audience: 'human',+ aiMetadata: { description: 'Fetch a single NinjaPipe deal by ID. Read-only.', idempotent: true },+ outputSchema: ninjapipeSchemas.deal,props: {- dealId: ninjapipeCommon.dealDropdownRequired,+ dealId: ninjapipeProps.dealRequired(),},async run(context) {- const auth = getAuth(context);- const response = await ninjapipeApiCall<Record<string, unknown>>({ auth, method: HttpMethod.GET, path: `/deals/${encodeURIComponent(String(context.propsValue.dealId))}` });- return flattenCustomFields(response.body);+ const id = ninjapipeClient.pathId({ value: context.propsValue.dealId, field: 'Deal' });+ return ninjapipeClient.getRecord({ auth: ninjapipeClient.readAuth(context.auth), path: `/deals/${id}`, operation: 'get deal' });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/get-order.ts b/packages/pieces/community/ninjapipe/src/lib/actions/get-order.tsindex 666d70afd5d..7ecbf8c0049 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/get-order.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/get-order.ts@@ -1,22 +1,23 @@-import { createAction } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, flattenCustomFields, getAuth, ninjapipeCommon } from '../common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const getOrder = createAction({auth: ninjapipeAuth,name: 'get_order',classification: 'READ',displayName: 'Get Order',- description: 'Retrieves an order by ID.',+ description: 'Gets one order by ID.',audience: 'both',- aiMetadata: { description: 'Fetches a single order by its ID, returning its full record. Pick this when you already have an order ID and need its details rather than searching a list. Read-only and safe to repeat.', idempotent: true },+ aiMetadata: { description: 'Fetch a single NinjaPipe order by ID. Read-only.', idempotent: true },+ outputSchema: ninjapipeSchemas.order,props: {- orderId: ninjapipeCommon.orderDropdownRequired,+ orderId: ninjapipeProps.orderRequired(),},async run(context) {- const auth = getAuth(context);- const response = await ninjapipeApiCall<Record<string, unknown>>({ auth, method: HttpMethod.GET, path: `/orders/${encodeURIComponent(String(context.propsValue.orderId))}` });- return flattenCustomFields(response.body);+ const id = ninjapipeClient.pathId({ value: context.propsValue.orderId, field: 'Order' });+ return ninjapipeClient.getRecord({ auth: ninjapipeClient.readAuth(context.auth), path: `/orders/${id}`, operation: 'get order' });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/get-pipeline.ts b/packages/pieces/community/ninjapipe/src/lib/actions/get-pipeline.tsindex 5b9ef46daab..74f67ec12bf 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/get-pipeline.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/get-pipeline.ts@@ -1,22 +1,23 @@-import { createAction } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, flattenCustomFields, getAuth, ninjapipeCommon } from '../common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const getPipeline = createAction({auth: ninjapipeAuth,name: 'get_pipeline',classification: 'READ',displayName: 'Get Pipeline',- description: 'Retrieves a pipeline by ID.',+ description: 'Gets one pipeline by ID.',audience: 'both',- aiMetadata: { description: 'Fetch a single NinjaPipe sales pipeline by its ID. Read-only lookup for inspecting one pipeline; to enumerate available pipelines use a list action instead.', idempotent: true },+ aiMetadata: { description: 'Fetch a single NinjaPipe pipeline by ID including its stages (stage IDs are used by pipeline items). Read-only.', idempotent: true },+ outputSchema: ninjapipeSchemas.pipeline,props: {- pipelineId: ninjapipeCommon.pipelineDropdownRequired,+ pipelineId: ninjapipeProps.pipelineRequired(),},async run(context) {- const auth = getAuth(context);- const response = await ninjapipeApiCall<Record<string, unknown>>({ auth, method: HttpMethod.GET, path: `/pipelines/${encodeURIComponent(String(context.propsValue.pipelineId))}` });- return flattenCustomFields(response.body);+ const id = ninjapipeClient.pathId({ value: context.propsValue.pipelineId, field: 'Pipeline' });+ return ninjapipeClient.getRecord({ auth: ninjapipeClient.readAuth(context.auth), path: `/pipelines/${id}`, operation: 'get pipeline' });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/get-product.ts b/packages/pieces/community/ninjapipe/src/lib/actions/get-product.tsindex 3a98557f4b3..cd2b1f6c531 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/get-product.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/get-product.ts@@ -1,22 +1,23 @@-import { createAction } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, flattenCustomFields, getAuth, ninjapipeCommon } from '../common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const getProduct = createAction({auth: ninjapipeAuth,name: 'get_product',classification: 'READ',displayName: 'Get Product',- description: 'Retrieves a product by ID.',+ description: 'Gets one product by ID.',audience: 'both',- aiMetadata: { description: 'Fetch a single product by its ID to read its current details. Use when you already have the product ID; to find a product by name or SKU, list/search products first. Read-only and idempotent.', idempotent: true },+ aiMetadata: { description: 'Fetch a single NinjaPipe product by ID. Read-only.', idempotent: true },+ outputSchema: ninjapipeSchemas.product,props: {- productId: ninjapipeCommon.productDropdownRequired,+ productId: ninjapipeProps.productRequired(),},async run(context) {- const auth = getAuth(context);- const response = await ninjapipeApiCall<Record<string, unknown>>({ auth, method: HttpMethod.GET, path: `/products/${encodeURIComponent(String(context.propsValue.productId))}` });- return flattenCustomFields(response.body);+ const id = ninjapipeClient.pathId({ value: context.propsValue.productId, field: 'Product' });+ return ninjapipeClient.getRecord({ auth: ninjapipeClient.readAuth(context.auth), path: `/products/${id}`, operation: 'get product' });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/get-project.ts b/packages/pieces/community/ninjapipe/src/lib/actions/get-project.tsindex c305f726fe4..f59c19e1000 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/get-project.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/get-project.ts@@ -1,22 +1,23 @@-import { createAction } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, flattenCustomFields, getAuth, ninjapipeCommon } from '../common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const getProject = createAction({auth: ninjapipeAuth,name: 'get_project',classification: 'READ',displayName: 'Get Project',- description: 'Retrieves a project by ID.',+ description: 'Gets one project by ID.',audience: 'both',- aiMetadata: { description: 'Fetch a single project by its ID. Read-only lookup for inspecting one project; to enumerate or search projects use the list-projects action instead.', idempotent: true },+ aiMetadata: { description: 'Fetch a single NinjaPipe project by ID. Read-only.', idempotent: true },+ outputSchema: ninjapipeSchemas.project,props: {- projectId: ninjapipeCommon.projectDropdownRequired,+ projectId: ninjapipeProps.projectRequired(),},async run(context) {- const auth = getAuth(context);- const response = await ninjapipeApiCall<Record<string, unknown>>({ auth, method: HttpMethod.GET, path: `/projects/${encodeURIComponent(String(context.propsValue.projectId))}` });- return flattenCustomFields(response.body);+ const id = ninjapipeClient.pathId({ value: context.propsValue.projectId, field: 'Project' });+ return ninjapipeClient.getRecord({ auth: ninjapipeClient.readAuth(context.auth), path: `/projects/${id}`, operation: 'get project' });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/get-task.ts b/packages/pieces/community/ninjapipe/src/lib/actions/get-task.tsindex 39aa6c1bb07..910e8a1383b 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/get-task.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/get-task.ts@@ -1,28 +1,28 @@import { createAction } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, flattenCustomFields, getAuth, ninjapipeCommon } from '../common';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const getTask = createAction({auth: ninjapipeAuth,name: 'get_task',classification: 'READ',displayName: 'Get Task',- description: 'Retrieves a single task within a project.',+ description: 'Gets one task of a project.',audience: 'both',- aiMetadata: { description: 'Fetch a single task by its ID within a specific project to read its current details; requires both the project ID and the task ID. Use when you already have both IDs. Read-only and idempotent.', idempotent: true },+ aiMetadata: { description: 'Fetch a single task by project ID and task ID. Read-only.', idempotent: true },+ outputSchema: ninjapipeSchemas.task,props: {- projectId: ninjapipeCommon.projectDropdownRequired,- taskId: ninjapipeCommon.taskDropdown,+ projectId: ninjapipeProps.projectRequired(),+ taskId: ninjapipeProps.task(),},async run(context) {- const auth = getAuth(context);- const { projectId, taskId } = context.propsValue;- const response = await ninjapipeApiCall<Record<string, unknown>>({- auth,- method: HttpMethod.GET,- path: `/projects/${encodeURIComponent(String(projectId))}/tasks/${encodeURIComponent(String(taskId))}`,+ const p = context.propsValue;+ return ninjapipeClient.getRecord({+ auth: ninjapipeClient.readAuth(context.auth),+ path: `/projects/${ninjapipeClient.pathId({ value: p.projectId, field: 'Project' })}/tasks/${ninjapipeClient.pathId({ value: p.taskId, field: 'Task' })}`,+ operation: 'get task',});- return flattenCustomFields(response.body);},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/list-budgets.ts b/packages/pieces/community/ninjapipe/src/lib/actions/list-budgets.tsindex 584346ab001..440d87efc37 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/list-budgets.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/list-budgets.ts@@ -1,42 +1,40 @@-import { createAction, Property } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, extractItems, flattenArray, getAuth, ninjapipeCommon } from '../common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const listBudgets = createAction({auth: ninjapipeAuth,name: 'list_budgets',classification: 'SEARCH',displayName: 'List Budgets',- description: 'Retrieves a list of budgets.',+ description: 'Lists budgets one page at a time, or all pages with Return All.',audience: 'both',- aiMetadata: { description: 'Read-only listing of budgets in NinjaPipe, with optional search text and pagination. Pick this to browse or find budgets; enable Return All to page through every match instead of a single page. Safe to repeat.', idempotent: true },+ aiMetadata: {+ description: 'List NinjaPipe budgets with allocated, spent and remaining amounts, filtered by search text or status. Returns one page (limit 1-100, use nextPage to continue) or every page with Return All (capped at 5,000; hasMore tells when the cap cut it short). Read-only.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.budgetList,props: {- limit: ninjapipeCommon.limitProperty,- search: ninjapipeCommon.searchProperty,- returnAll: Property.Checkbox({ displayName: 'Return All', description: 'Retrieve all budgets using pagination.', required: false, defaultValue: false }),- page: Property.Number({ displayName: 'Page', description: 'Page number when not using Return All.', required: false, defaultValue: 1 }),+ search: ninjapipeProps.search(),+ statusFilter: Property.ShortText({ displayName: 'Status', description: 'Only budgets with this status.', required: false }),+ sortBy: ninjapipeProps.staticDropdown({ displayName: 'Sort By', description: 'Field to sort by. Default: created_at.', values: ['created_at', 'updated_at', 'name'] }),+ sortOrder: ninjapipeProps.staticDropdown({ displayName: 'Sort Order', description: 'Default: desc.', values: ['desc', 'asc'] }),+ limit: ninjapipeProps.limit(),+ page: ninjapipeProps.page(),+ returnAll: ninjapipeProps.returnAll(),},async run(context) {- const auth = getAuth(context);- const qs: Record<string, string> = { limit: String(context.propsValue.limit ?? 20), page: String(context.propsValue.page ?? 1) };- if (context.propsValue.search) qs['search'] = context.propsValue.search;- if (context.propsValue.returnAll) {- const results: unknown[] = [];- let page = 1;- const limit = 100;- let hasMore = true;- while (hasMore) {- const response = await ninjapipeApiCall<{ data?: unknown[] }>({ auth, method: HttpMethod.GET, path: '/budgets', queryParams: { ...qs, limit: String(limit), page: String(page) } });- const items = extractItems(response.body);- results.push(...items);- hasMore = items.length === limit && page < 1000;- page++;- }- return flattenArray(results);- }- const response = await ninjapipeApiCall<{ data?: unknown[] }>({ auth, method: HttpMethod.GET, path: '/budgets', queryParams: qs });- const items = extractItems(response.body);- return flattenArray(items);+ const p = context.propsValue;+ return ninjapipeClient.runList({+ auth: ninjapipeClient.readAuth(context.auth),+ path: '/budgets',+ query: { search: p.search, status: p.statusFilter, sort_by: p.sortBy, sort_order: p.sortOrder },+ operation: 'list budgets',+ returnAll: p.returnAll,+ page: p.page,+ limit: p.limit,+ });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/list-companies.ts b/packages/pieces/community/ninjapipe/src/lib/actions/list-companies.tsindex 705d9f769d7..640568a406f 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/list-companies.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/list-companies.ts@@ -1,46 +1,41 @@-import { createAction, Property } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, extractItems, flattenArray, getAuth, ninjapipeCommon } from '../common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const listCompanies = createAction({auth: ninjapipeAuth,name: 'list_companies',classification: 'SEARCH',displayName: 'List Companies',- description: 'Retrieves a list of companies.',- audience: 'both',- aiMetadata: { description: 'Read-only listing of companies (CRM accounts) in NinjaPipe, with optional search text, status/owner filters, and pagination. Pick this to browse or find companies; enable Return All to page through every match instead of a single page. Safe to repeat.', idempotent: true },+ description: 'Lists companies one page at a time, or all pages with Return All.',+ audience: 'human',+ aiMetadata: {+ description: 'List NinjaPipe companies, filtered by search text, status or owner. Returns one page (limit 1-100, use nextPage to continue) or every page with Return All (capped at 5,000; hasMore tells when the cap cut it short). Read-only.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.companyList,props: {- limit: ninjapipeCommon.limitProperty,- search: ninjapipeCommon.searchProperty,- statusFilter: ninjapipeCommon.statusFilterProperty,- ownerFilter: ninjapipeCommon.ownerFilterProperty,- returnAll: Property.Checkbox({ displayName: 'Return All', description: 'Retrieve all companies using pagination.', required: false, defaultValue: false }),- page: Property.Number({ displayName: 'Page', description: 'Page number when not using Return All.', required: false, defaultValue: 1 }),+ search: ninjapipeProps.search(),+ statusFilter: Property.ShortText({ displayName: 'Status', description: 'Only companies with this status.', required: false }),+ ownerFilter: ninjapipeProps.member({ displayName: 'Owner', description: 'Only companies owned by this member (owner_id).' }),+ sortBy: ninjapipeProps.staticDropdown({ displayName: 'Sort By', description: 'Field to sort by. Default: created_at.', values: ['created_at', 'updated_at', 'name'] }),+ sortOrder: ninjapipeProps.staticDropdown({ displayName: 'Sort Order', description: 'Default: desc.', values: ['desc', 'asc'] }),+ limit: ninjapipeProps.limit(),+ page: ninjapipeProps.page(),+ returnAll: ninjapipeProps.returnAll(),},async run(context) {- const auth = getAuth(context);- const qs: Record<string, string> = { limit: String(context.propsValue.limit ?? 20), page: String(context.propsValue.page ?? 1) };- if (context.propsValue.search) qs['search'] = context.propsValue.search;- if (context.propsValue.statusFilter) qs['status'] = context.propsValue.statusFilter;- if (context.propsValue.ownerFilter) qs['owner'] = context.propsValue.ownerFilter;- if (context.propsValue.returnAll) {- const results: unknown[] = [];- let page = 1;- const limit = 100;- let hasMore = true;- while (hasMore) {- const response = await ninjapipeApiCall<{ data?: unknown[] }>({ auth, method: HttpMethod.GET, path: '/companies', queryParams: { ...qs, limit: String(limit), page: String(page) } });- const items = extractItems(response.body);- results.push(...items);- hasMore = items.length === limit && page < 1000;- page++;- }- return flattenArray(results);- }- const response = await ninjapipeApiCall<{ data?: unknown[] }>({ auth, method: HttpMethod.GET, path: '/companies', queryParams: qs });- const items = extractItems(response.body);- return flattenArray(items);+ const p = context.propsValue;+ return ninjapipeClient.runList({+ auth: ninjapipeClient.readAuth(context.auth),+ path: '/companies',+ query: { search: p.search, status: p.statusFilter, owner_id: p.ownerFilter, sort_by: p.sortBy, sort_order: p.sortOrder },+ operation: 'list companies',+ returnAll: p.returnAll,+ page: p.page,+ limit: p.limit,+ });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/list-contacts.ts b/packages/pieces/community/ninjapipe/src/lib/actions/list-contacts.tsindex a70a83d5fa5..3275d308ca5 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/list-contacts.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/list-contacts.ts@@ -1,71 +1,42 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, extractItems, flattenArray, getAuth, ninjapipeCommon } from '../common';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const listContacts = createAction({auth: ninjapipeAuth,name: 'list_contacts',classification: 'SEARCH',displayName: 'List Contacts',- description: 'Retrieves a list of contacts.',- audience: 'both',- aiMetadata: { description: 'List contacts with optional search text and status/owner filters. Read-only; supports single-page paging or "Return All" to follow pagination across every page. Use to discover contact IDs or find a contact by name/email before acting on it.', idempotent: true },+ description: 'Lists contacts, with optional search, status, owner and assignee filters.',+ audience: 'human',+ aiMetadata: {+ description: 'List NinjaPipe contacts one page at a time, or every page with Return All (capped at 5,000), filtered by search text, status, owner or assignee. Read-only.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.contactList,props: {- limit: ninjapipeCommon.limitProperty,- search: ninjapipeCommon.searchProperty,- statusFilter: ninjapipeCommon.statusFilterProperty,- ownerFilter: ninjapipeCommon.ownerFilterProperty,- returnAll: Property.Checkbox({- displayName: 'Return All',- description: 'Retrieve all contacts using pagination.',- required: false,- defaultValue: false,- }),- page: Property.Number({- displayName: 'Page',- description: 'Page number when not using Return All.',- required: false,- defaultValue: 1,- }),+ search: ninjapipeProps.search(),+ statusFilter: Property.ShortText({ displayName: 'Status', description: 'Only contacts with this status.', required: false }),+ ownerFilter: ninjapipeProps.member({ displayName: 'Owner', description: 'Only contacts owned by this member (owner_id).' }),+ assignedTo: ninjapipeProps.member({ displayName: 'Assigned To', description: 'Only contacts assigned to this member (assigned_to).' }),+ sortBy: ninjapipeProps.staticDropdown({ displayName: 'Sort By', description: 'Field to sort by. Default: created_at.', values: ['created_at', 'updated_at', 'first_name', 'last_name', 'email', 'status'] }),+ sortOrder: ninjapipeProps.staticDropdown({ displayName: 'Sort Order', description: 'Default: desc.', values: ['desc', 'asc'] }),+ limit: ninjapipeProps.limit(),+ page: ninjapipeProps.page(),+ returnAll: ninjapipeProps.returnAll(),},async run(context) {- const auth = getAuth(context);- const qs: Record<string, string> = {- limit: String(context.propsValue.limit ?? 20),- page: String(context.propsValue.page ?? 1),- };- if (context.propsValue.search) qs['search'] = context.propsValue.search;- if (context.propsValue.statusFilter) qs['status'] = context.propsValue.statusFilter;- if (context.propsValue.ownerFilter) qs['owner'] = context.propsValue.ownerFilter;-- if (context.propsValue.returnAll) {- const results: unknown[] = [];- let page = 1;- const limit = 100;- let hasMore = true;- while (hasMore) {- const response = await ninjapipeApiCall<{ data?: unknown[] }>({- auth,- method: HttpMethod.GET,- path: '/contacts',- queryParams: { ...qs, limit: String(limit), page: String(page) },- });- const items = extractItems(response.body);- results.push(...items);- hasMore = items.length === limit && page < 1000;- page++;- }- return flattenArray(results);- }-- const response = await ninjapipeApiCall<{ data?: unknown[] }>({- auth,- method: HttpMethod.GET,+ const p = context.propsValue;+ return ninjapipeClient.runList({+ auth: ninjapipeClient.readAuth(context.auth),path: '/contacts',- queryParams: qs,+ query: { search: p.search, status: p.statusFilter, owner_id: p.ownerFilter, assigned_to: p.assignedTo, sort_by: p.sortBy, sort_order: p.sortOrder },+ operation: 'list contacts',+ returnAll: p.returnAll,+ page: p.page,+ limit: p.limit,});- const items = extractItems(response.body);- return flattenArray(items);},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/list-deals.ts b/packages/pieces/community/ninjapipe/src/lib/actions/list-deals.tsindex fa76f5a0a46..9ad48dcdf88 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/list-deals.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/list-deals.ts@@ -1,46 +1,41 @@-import { createAction, Property } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, extractItems, flattenArray, getAuth, ninjapipeCommon } from '../common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const listDeals = createAction({auth: ninjapipeAuth,name: 'list_deals',classification: 'SEARCH',displayName: 'List Deals',- description: 'Retrieves a list of deals.',- audience: 'both',- aiMetadata: { description: 'Read-only listing of deals (sales opportunities) in NinjaPipe, with optional search text, status/owner filters, and pagination. Pick this to browse or find deals; enable Return All to page through every match instead of a single page. Safe to repeat.', idempotent: true },+ description: 'Lists deals one page at a time, or all pages with Return All.',+ audience: 'human',+ aiMetadata: {+ description: 'List NinjaPipe deals, filtered by search text, status or owner. Returns one page (limit 1-100, use nextPage to continue) or every page with Return All (capped at 5,000; hasMore tells when the cap cut it short). Read-only.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.dealList,props: {- limit: ninjapipeCommon.limitProperty,- search: ninjapipeCommon.searchProperty,- statusFilter: ninjapipeCommon.statusFilterProperty,- ownerFilter: ninjapipeCommon.ownerFilterProperty,- returnAll: Property.Checkbox({ displayName: 'Return All', description: 'Retrieve all deals using pagination.', required: false, defaultValue: false }),- page: Property.Number({ displayName: 'Page', description: 'Page number when not using Return All.', required: false, defaultValue: 1 }),+ search: ninjapipeProps.search(),+ statusFilter: ninjapipeProps.staticDropdown({ displayName: 'Status', description: 'Only deals with this status.', values: ['Open', 'In Progress', 'Won', 'Lost'] }),+ ownerFilter: ninjapipeProps.member({ displayName: 'Owner', description: 'Only deals owned by this member (owner_id).' }),+ sortBy: ninjapipeProps.staticDropdown({ displayName: 'Sort By', description: 'Field to sort by. Default: created_at.', values: ['created_at', 'updated_at', 'name', 'value', 'status'] }),+ sortOrder: ninjapipeProps.staticDropdown({ displayName: 'Sort Order', description: 'Default: desc.', values: ['desc', 'asc'] }),+ limit: ninjapipeProps.limit(),+ page: ninjapipeProps.page(),+ returnAll: ninjapipeProps.returnAll(),},async run(context) {- const auth = getAuth(context);- const qs: Record<string, string> = { limit: String(context.propsValue.limit ?? 20), page: String(context.propsValue.page ?? 1) };- if (context.propsValue.search) qs['search'] = context.propsValue.search;- if (context.propsValue.statusFilter) qs['status'] = context.propsValue.statusFilter;- if (context.propsValue.ownerFilter) qs['owner'] = context.propsValue.ownerFilter;- if (context.propsValue.returnAll) {- const results: unknown[] = [];- let page = 1;- const limit = 100;- let hasMore = true;- while (hasMore) {- const response = await ninjapipeApiCall<{ data?: unknown[] }>({ auth, method: HttpMethod.GET, path: '/deals', queryParams: { ...qs, limit: String(limit), page: String(page) } });- const items = extractItems(response.body);- results.push(...items);- hasMore = items.length === limit && page < 1000;- page++;- }- return flattenArray(results);- }- const response = await ninjapipeApiCall<{ data?: unknown[] }>({ auth, method: HttpMethod.GET, path: '/deals', queryParams: qs });- const items = extractItems(response.body);- return flattenArray(items);+ const p = context.propsValue;+ return ninjapipeClient.runList({+ auth: ninjapipeClient.readAuth(context.auth),+ path: '/deals',+ query: { search: p.search, status: p.statusFilter, owner_id: p.ownerFilter, sort_by: p.sortBy, sort_order: p.sortOrder },+ operation: 'list deals',+ returnAll: p.returnAll,+ page: p.page,+ limit: p.limit,+ });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/list-orders.ts b/packages/pieces/community/ninjapipe/src/lib/actions/list-orders.tsindex 3c828911358..2de4dd11588 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/list-orders.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/list-orders.ts@@ -1,44 +1,40 @@-import { createAction, Property } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, extractItems, flattenArray, getAuth, ninjapipeCommon } from '../common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const listOrders = createAction({auth: ninjapipeAuth,name: 'list_orders',classification: 'SEARCH',displayName: 'List Orders',- description: 'Retrieves a list of orders.',+ description: 'Lists orders one page at a time, or all pages with Return All.',audience: 'both',- aiMetadata: { description: 'List orders with optional search text and status filter. Read-only; supports single-page paging or "Return All" to follow pagination across every page. Use to discover order IDs before fetching or deleting an order.', idempotent: true },+ aiMetadata: {+ description: 'List NinjaPipe orders, filtered by search text or status. Returns one page (limit 1-100, use nextPage to continue) or every page with Return All (capped at 5,000; hasMore tells when the cap cut it short). Read-only.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.orderList,props: {- limit: ninjapipeCommon.limitProperty,- search: ninjapipeCommon.searchProperty,- statusFilter: ninjapipeCommon.statusFilterProperty,- returnAll: Property.Checkbox({ displayName: 'Return All', description: 'Retrieve all orders using pagination.', required: false, defaultValue: false }),- page: Property.Number({ displayName: 'Page', description: 'Page number when not using Return All.', required: false, defaultValue: 1 }),+ search: ninjapipeProps.search(),+ statusFilter: ninjapipeProps.staticDropdown({ displayName: 'Status', description: 'Only orders with this status.', values: ['Processing', 'Shipped', 'Delivered', 'Cancelled'] }),+ sortBy: ninjapipeProps.staticDropdown({ displayName: 'Sort By', description: 'Field to sort by. Default: created_at.', values: ['created_at', 'updated_at', 'order_date', 'total_amount'] }),+ sortOrder: ninjapipeProps.staticDropdown({ displayName: 'Sort Order', description: 'Default: desc.', values: ['desc', 'asc'] }),+ limit: ninjapipeProps.limit(),+ page: ninjapipeProps.page(),+ returnAll: ninjapipeProps.returnAll(),},async run(context) {- const auth = getAuth(context);- const qs: Record<string, string> = { limit: String(context.propsValue.limit ?? 20), page: String(context.propsValue.page ?? 1) };- if (context.propsValue.search) qs['search'] = context.propsValue.search;- if (context.propsValue.statusFilter) qs['status'] = context.propsValue.statusFilter;- if (context.propsValue.returnAll) {- const results: unknown[] = [];- let page = 1;- const limit = 100;- let hasMore = true;- while (hasMore) {- const response = await ninjapipeApiCall<{ data?: unknown[] }>({ auth, method: HttpMethod.GET, path: '/orders', queryParams: { ...qs, limit: String(limit), page: String(page) } });- const items = extractItems(response.body);- results.push(...items);- hasMore = items.length === limit && page < 1000;- page++;- }- return flattenArray(results);- }- const response = await ninjapipeApiCall<{ data?: unknown[] }>({ auth, method: HttpMethod.GET, path: '/orders', queryParams: qs });- const items = extractItems(response.body);- return flattenArray(items);+ const p = context.propsValue;+ return ninjapipeClient.runList({+ auth: ninjapipeClient.readAuth(context.auth),+ path: '/orders',+ query: { search: p.search, status: p.statusFilter, sort_by: p.sortBy, sort_order: p.sortOrder },+ operation: 'list orders',+ returnAll: p.returnAll,+ page: p.page,+ limit: p.limit,+ });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/list-pipelines.ts b/packages/pieces/community/ninjapipe/src/lib/actions/list-pipelines.tsindex c48a7fb9b6b..0594417d353 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/list-pipelines.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/list-pipelines.ts@@ -1,42 +1,38 @@-import { createAction, Property } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, extractItems, flattenArray, getAuth, ninjapipeCommon } from '../common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const listPipelines = createAction({auth: ninjapipeAuth,name: 'list_pipelines',classification: 'SEARCH',displayName: 'List Pipelines',- description: 'Retrieves a list of pipelines.',- audience: 'both',- aiMetadata: { description: 'List pipelines in the workspace, optionally filtered by a search term, with paging via limit and page. Set Return All to fetch every matching pipeline across pages; otherwise a single page is returned. Use to discover pipelines or resolve a pipeline ID by name. Read-only and idempotent.', idempotent: true },+ description: 'Lists pipelines one page at a time, or all pages with Return All.',+ audience: 'human',+ aiMetadata: {+ description: 'List NinjaPipe pipelines with their stages. Returns one page (limit 1-100, use nextPage to continue) or every page with Return All (capped at 5,000; hasMore tells when the cap cut it short). Read-only.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.pipelineList,props: {- limit: ninjapipeCommon.limitProperty,- search: ninjapipeCommon.searchProperty,- returnAll: Property.Checkbox({ displayName: 'Return All', description: 'Retrieve all pipelines using pagination.', required: false, defaultValue: false }),- page: Property.Number({ displayName: 'Page', description: 'Page number when not using Return All.', required: false, defaultValue: 1 }),+ sortBy: ninjapipeProps.staticDropdown({ displayName: 'Sort By', description: 'Field to sort by. Default: created_at.', values: ['created_at', 'updated_at', 'name'] }),+ sortOrder: ninjapipeProps.staticDropdown({ displayName: 'Sort Order', description: 'Default: desc.', values: ['desc', 'asc'] }),+ limit: ninjapipeProps.limit(),+ page: ninjapipeProps.page(),+ returnAll: ninjapipeProps.returnAll(),},async run(context) {- const auth = getAuth(context);- const qs: Record<string, string> = { limit: String(context.propsValue.limit ?? 20), page: String(context.propsValue.page ?? 1) };- if (context.propsValue.search) qs['search'] = context.propsValue.search;- if (context.propsValue.returnAll) {- const results: unknown[] = [];- let page = 1;- const limit = 100;- let hasMore = true;- while (hasMore) {- const response = await ninjapipeApiCall<{ data?: unknown[] }>({ auth, method: HttpMethod.GET, path: '/pipelines', queryParams: { ...qs, limit: String(limit), page: String(page) } });- const items = extractItems(response.body);- results.push(...items);- hasMore = items.length === limit && page < 1000;- page++;- }- return flattenArray(results);- }- const response = await ninjapipeApiCall<{ data?: unknown[] }>({ auth, method: HttpMethod.GET, path: '/pipelines', queryParams: qs });- const items = extractItems(response.body);- return flattenArray(items);+ const p = context.propsValue;+ return ninjapipeClient.runList({+ auth: ninjapipeClient.readAuth(context.auth),+ path: '/pipelines',+ query: { sort_by: p.sortBy, sort_order: p.sortOrder },+ operation: 'list pipelines',+ returnAll: p.returnAll,+ page: p.page,+ limit: p.limit,+ });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/list-products.ts b/packages/pieces/community/ninjapipe/src/lib/actions/list-products.tsindex 844e484b0e4..77c7be1af03 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/list-products.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/list-products.ts@@ -1,42 +1,40 @@-import { createAction, Property } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, extractItems, flattenArray, getAuth, ninjapipeCommon } from '../common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const listProducts = createAction({auth: ninjapipeAuth,name: 'list_products',classification: 'SEARCH',displayName: 'List Products',- description: 'Retrieves a list of products.',+ description: 'Lists products one page at a time, or all pages with Return All.',audience: 'both',- aiMetadata: { description: 'List products with optional search text. Read-only; supports single-page paging or "Return All" to follow pagination across every page. Use to discover product IDs or look up a product by name.', idempotent: true },+ aiMetadata: {+ description: 'List NinjaPipe products (catalog items with SKU and price), filtered by search text or status. Returns one page (limit 1-100, use nextPage to continue) or every page with Return All (capped at 5,000; hasMore tells when the cap cut it short). Read-only.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.productList,props: {- limit: ninjapipeCommon.limitProperty,- search: ninjapipeCommon.searchProperty,- returnAll: Property.Checkbox({ displayName: 'Return All', description: 'Retrieve all products using pagination.', required: false, defaultValue: false }),- page: Property.Number({ displayName: 'Page', description: 'Page number when not using Return All.', required: false, defaultValue: 1 }),+ search: ninjapipeProps.search(),+ statusFilter: Property.ShortText({ displayName: 'Status', description: 'Only products with this status.', required: false }),+ sortBy: ninjapipeProps.staticDropdown({ displayName: 'Sort By', description: 'Field to sort by. Default: created_at.', values: ['created_at', 'updated_at', 'name', 'price'] }),+ sortOrder: ninjapipeProps.staticDropdown({ displayName: 'Sort Order', description: 'Default: desc.', values: ['desc', 'asc'] }),+ limit: ninjapipeProps.limit(),+ page: ninjapipeProps.page(),+ returnAll: ninjapipeProps.returnAll(),},async run(context) {- const auth = getAuth(context);- const qs: Record<string, string> = { limit: String(context.propsValue.limit ?? 20), page: String(context.propsValue.page ?? 1) };- if (context.propsValue.search) qs['search'] = context.propsValue.search;- if (context.propsValue.returnAll) {- const results: unknown[] = [];- let page = 1;- const limit = 100;- let hasMore = true;- while (hasMore) {- const response = await ninjapipeApiCall<{ data?: unknown[] }>({ auth, method: HttpMethod.GET, path: '/products', queryParams: { ...qs, limit: String(limit), page: String(page) } });- const items = extractItems(response.body);- results.push(...items);- hasMore = items.length === limit && page < 1000;- page++;- }- return flattenArray(results);- }- const response = await ninjapipeApiCall<{ data?: unknown[] }>({ auth, method: HttpMethod.GET, path: '/products', queryParams: qs });- const items = extractItems(response.body);- return flattenArray(items);+ const p = context.propsValue;+ return ninjapipeClient.runList({+ auth: ninjapipeClient.readAuth(context.auth),+ path: '/products',+ query: { search: p.search, status: p.statusFilter, sort_by: p.sortBy, sort_order: p.sortOrder },+ operation: 'list products',+ returnAll: p.returnAll,+ page: p.page,+ limit: p.limit,+ });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/list-projects.ts b/packages/pieces/community/ninjapipe/src/lib/actions/list-projects.tsindex 7b6259d8474..0e93bf99590 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/list-projects.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/list-projects.ts@@ -1,46 +1,40 @@-import { createAction, Property } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, extractItems, flattenArray, getAuth, ninjapipeCommon } from '../common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const listProjects = createAction({auth: ninjapipeAuth,name: 'list_projects',classification: 'SEARCH',displayName: 'List Projects',- description: 'Retrieves a list of projects.',- audience: 'both',- aiMetadata: { description: 'List projects with optional search text and status/owner filters. Read-only; supports single-page paging or "Return All" to follow pagination across every page. Use to discover project IDs before fetching or operating on a project.', idempotent: true },+ description: 'Lists projects one page at a time, or all pages with Return All.',+ audience: 'human',+ aiMetadata: {+ description: 'List NinjaPipe projects, filtered by search text or status. Returns one page (limit 1-100, use nextPage to continue) or every page with Return All (capped at 5,000; hasMore tells when the cap cut it short). Read-only.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.projectList,props: {- limit: ninjapipeCommon.limitProperty,- search: ninjapipeCommon.searchProperty,- statusFilter: ninjapipeCommon.statusFilterProperty,- ownerFilter: ninjapipeCommon.ownerFilterProperty,- returnAll: Property.Checkbox({ displayName: 'Return All', description: 'Retrieve all projects using pagination.', required: false, defaultValue: false }),- page: Property.Number({ displayName: 'Page', description: 'Page number when not using Return All.', required: false, defaultValue: 1 }),+ search: ninjapipeProps.search(),+ statusFilter: Property.ShortText({ displayName: 'Status', description: 'Only projects with this status, e.g. Planning or In Progress.', required: false }),+ sortBy: ninjapipeProps.staticDropdown({ displayName: 'Sort By', description: 'Field to sort by. Default: created_at.', values: ['created_at', 'updated_at', 'name', 'due_date'] }),+ sortOrder: ninjapipeProps.staticDropdown({ displayName: 'Sort Order', description: 'Default: desc.', values: ['desc', 'asc'] }),+ limit: ninjapipeProps.limit(),+ page: ninjapipeProps.page(),+ returnAll: ninjapipeProps.returnAll(),},async run(context) {- const auth = getAuth(context);- const qs: Record<string, string> = { limit: String(context.propsValue.limit ?? 20), page: String(context.propsValue.page ?? 1) };- if (context.propsValue.search) qs['search'] = context.propsValue.search;- if (context.propsValue.statusFilter) qs['status'] = context.propsValue.statusFilter;- if (context.propsValue.ownerFilter) qs['owner'] = context.propsValue.ownerFilter;- if (context.propsValue.returnAll) {- const results: unknown[] = [];- let page = 1;- const limit = 100;- let hasMore = true;- while (hasMore) {- const response = await ninjapipeApiCall<{ data?: unknown[] }>({ auth, method: HttpMethod.GET, path: '/projects', queryParams: { ...qs, limit: String(limit), page: String(page) } });- const items = extractItems(response.body);- results.push(...items);- hasMore = items.length === limit && page < 1000;- page++;- }- return flattenArray(results);- }- const response = await ninjapipeApiCall<{ data?: unknown[] }>({ auth, method: HttpMethod.GET, path: '/projects', queryParams: qs });- const items = extractItems(response.body);- return flattenArray(items);+ const p = context.propsValue;+ return ninjapipeClient.runList({+ auth: ninjapipeClient.readAuth(context.auth),+ path: '/projects',+ query: { search: p.search, status: p.statusFilter, sort_by: p.sortBy, sort_order: p.sortOrder },+ operation: 'list projects',+ returnAll: p.returnAll,+ page: p.page,+ limit: p.limit,+ });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/list-tasks.ts b/packages/pieces/community/ninjapipe/src/lib/actions/list-tasks.tsindex 00df9967e27..5174d40bd3b 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/list-tasks.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/list-tasks.ts@@ -1,88 +1,36 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, extractItems, flattenArray, getAuth, ninjapipeCommon } from '../common';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeProps } from '../common/props';+import { ninjapipeRecords } from '../common/records';+import { ninjapipeTasks } from '../common/task-props';+import { ninjapipeSchemas } from '../output-schemas';export const listTasks = createAction({auth: ninjapipeAuth,name: 'list_tasks',classification: 'SEARCH',displayName: 'List Tasks',- description: 'Retrieves the tasks of a project as a flat list. Use parent_id on each item to build a tree.',- audience: 'both',- aiMetadata: { description: 'List the tasks of a given project as a flat array, with optional status, priority, and parent-task filters plus sorting. Read-only; pass a parent task ID to fetch its subtasks, or an empty string to fetch only root tasks. Use to discover task IDs before updating a task.', idempotent: true },+ description: 'Lists every task of a project as a flat list. Use parent_id on each task to build a tree.',+ audience: 'human',+ aiMetadata: { description: 'List all tasks of a NinjaPipe project, with optional status, priority, parent and root-only filters. Read-only.', idempotent: true },+ outputSchema: ninjapipeSchemas.taskList,props: {- projectId: ninjapipeCommon.projectDropdownRequired,- statusFilter: Property.StaticDropdown({- displayName: 'Status Filter',- required: false,- options: {- options: [- { label: 'To Do', value: 'To Do' },- { label: 'In Progress', value: 'In Progress' },- { label: 'Done', value: 'Done' },- { label: 'Cancelled', value: 'Cancelled' },- ],- },- }),- priorityFilter: Property.StaticDropdown({- displayName: 'Priority Filter',- required: false,- options: {- options: [- { label: 'High', value: 'High' },- { label: 'Medium', value: 'Medium' },- { label: 'Low', value: 'Low' },- ],- },- }),- parentId: Property.ShortText({- displayName: 'Parent Task Filter',- description: 'Pass a parent task ID to fetch its subtasks. Empty string to fetch only root tasks.',- required: false,- }),- sortBy: Property.StaticDropdown({- displayName: 'Sort By',- required: false,- defaultValue: 'order_index',- options: {- options: [- { label: 'Order Index', value: 'order_index' },- { label: 'Created At', value: 'created_at' },- { label: 'Updated At', value: 'updated_at' },- { label: 'Title', value: 'title' },- { label: 'Due Date', value: 'due_date' },- ],- },- }),- sortOrder: Property.StaticDropdown({- displayName: 'Sort Order',- required: false,- defaultValue: 'asc',- options: {- options: [- { label: 'Ascending', value: 'asc' },- { label: 'Descending', value: 'desc' },- ],- },- }),+ projectId: ninjapipeProps.projectRequired(),+ statusFilter: ninjapipeProps.staticDropdown({ displayName: 'Status', description: 'Only tasks with this status.', values: ninjapipeTasks.TASK_STATUSES }),+ priorityFilter: ninjapipeProps.staticDropdown({ displayName: 'Priority', description: 'Only tasks with this priority.', values: ninjapipeTasks.TASK_PRIORITIES }),+ parentId: Property.ShortText({ displayName: 'Parent Task ID', description: 'Only subtasks of this task.', required: false }),+ rootOnly: Property.Checkbox({ displayName: 'Root Tasks Only', description: 'Only top-level tasks (no subtasks). Ignored when Parent Task ID is set.', required: false, defaultValue: false }),+ sortBy: ninjapipeProps.staticDropdown({ displayName: 'Sort By', description: 'Default: created_at.', values: ['created_at', 'updated_at', 'due_date', 'title', 'priority', 'order_index'] }),+ sortOrder: ninjapipeProps.staticDropdown({ displayName: 'Sort Order', description: 'Default: desc.', values: ['desc', 'asc'] }),},async run(context) {- const auth = getAuth(context);const p = context.propsValue;- const qs: Record<string, string> = {};- if (p.statusFilter) qs['status'] = p.statusFilter;- if (p.priorityFilter) qs['priority'] = p.priorityFilter;- if (p.parentId !== undefined && p.parentId !== null) qs['parent_id'] = p.parentId;- if (p.sortBy) qs['sort_by'] = p.sortBy;- if (p.sortOrder) qs['sort_order'] = p.sortOrder;- const response = await ninjapipeApiCall<{ data?: unknown[] }>({- auth,- method: HttpMethod.GET,- path: `/projects/${encodeURIComponent(String(p.projectId))}/tasks`,- queryParams: qs,+ return ninjapipeRecords.listUnpaged({+ auth: ninjapipeClient.readAuth(context.auth),+ path: `/projects/${ninjapipeClient.pathId({ value: p.projectId, field: 'Project' })}/tasks`,+ query: { status: p.statusFilter, priority: p.priorityFilter, parent_id: ninjapipeTasks.parentFilter({ parentId: p.parentId, rootOnly: p.rootOnly }), sort_by: p.sortBy, sort_order: p.sortOrder },+ operation: 'list tasks',});- const items = extractItems(response.body);- return flattenArray(items);},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/send-to-databin.ts b/packages/pieces/community/ninjapipe/src/lib/actions/send-to-databin.tsindex b0975a23dbd..ac9d95c98e0 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/send-to-databin.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/send-to-databin.ts@@ -1,75 +1,77 @@+import { HttpMethod, httpClient } from '@activepieces/pieces-common';import { createAction, Property } from '@activepieces/pieces-framework';-import { httpClient, HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { getAuth } from '../common';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeSchemas } from '../output-schemas';export const sendToDatabin = createAction({auth: ninjapipeAuth,name: 'send_to_databin',classification: 'WRITE',displayName: 'Send to Databin',- description: 'Sends a JSON payload to a Databin webhook URL on your connected NinjaPipe workspace.',+ description: 'Sends a JSON payload to a Databin webhook URL of your connected NinjaPipe workspace.',audience: 'both',- aiMetadata: { description: 'Post an arbitrary JSON payload to a NinjaPipe Databin webhook. The webhook URL must be HTTPS, contain /api/webhooks/, and resolve to the same host as the connected workspace, or the call is rejected. Each send is a fresh delivery, so repeated calls are not idempotent.', idempotent: false },+ aiMetadata: {+ description:+ 'Post a JSON object to a NinjaPipe Databin webhook URL. The URL must be https, contain /api/webhooks/, and use the same host as the connection (a www. prefix may differ); anything else is refused. Each call is a new delivery, so it is not idempotent.',+ idempotent: false,+ },+ outputSchema: ninjapipeSchemas.databin,props: {webhookUrl: Property.ShortText({displayName: 'Databin Webhook URL',description: 'The full HTTPS webhook URL from your Databin. Must point to your connected NinjaPipe host and contain /api/webhooks/.',required: true,}),- payload: Property.Json({- displayName: 'Payload',- description: 'JSON object to send.',- required: true,- }),+ payload: Property.Json({ displayName: 'Payload', description: 'JSON object to send.', required: true }),},async run(context) {- const auth = getAuth(context);- const rawUrl = String(context.propsValue.webhookUrl ?? '').trim();- let parsed: URL;+ const auth = ninjapipeClient.readAuth(context.auth);+ const url = checkWebhookUrl({ rawUrl: String(context.propsValue.webhookUrl ?? '').trim(), baseUrl: auth.baseUrl });+ const payload = parsePayload(context.propsValue.payload);try {- parsed = new URL(rawUrl);- } catch {- throw new Error('Invalid webhook URL: not a valid URL.');- }- if (parsed.protocol !== 'https:') {- throw new Error('Invalid webhook URL: must use https://.');- }- if (!parsed.pathname.includes('/api/webhooks/')) {- throw new Error('Invalid webhook URL: path must contain /api/webhooks/.');+ const response = await httpClient.sendRequest({+ method: HttpMethod.POST,+ url,+ headers: { 'Content-Type': 'application/json', Accept: 'application/json' },+ body: payload,+ });+ return { status: response.status, response: response.body ?? null };+ } catch (error) {+ const failure = ninjapipeClient.isRecord(error) && ninjapipeClient.isRecord(error['response']) ? error['response'] : undefined;+ if (!failure) throw error;+ throw ninjapipeClient.toNinjaPipeError({ status: Number(failure['status']), body: failure['body'], operation: 'send to Databin' });}- const expectedHost = (() => {- try {- return new URL(auth.base_url).host.toLowerCase();- } catch {- return '';- }- })();- const actualHost = parsed.host.toLowerCase();- const isHostAllowed =- expectedHost === actualHost ||- (expectedHost && actualHost.endsWith('.' + expectedHost.replace(/^www\./, ''))) ||- (expectedHost && expectedHost.endsWith('.' + actualHost.replace(/^www\./, ''))) ||- actualHost === expectedHost.replace(/^www\./, '') ||- actualHost.replace(/^www\./, '') === expectedHost.replace(/^www\./, '');- if (!isHostAllowed) {- throw new Error(- `Webhook host "${actualHost}" does not match your connected NinjaPipe host "${expectedHost}". Update the connection or use a Databin URL from your workspace.`,- );- }- const body =- typeof context.propsValue.payload === 'string'- ? JSON.parse(context.propsValue.payload)- : context.propsValue.payload;- const response = await httpClient.sendRequest<Record<string, unknown>>({- method: HttpMethod.POST,- url: rawUrl,- headers: {- 'Content-Type': 'application/json',- Accept: 'application/json',- },- body,- });- return response.body;},});++function checkWebhookUrl({ rawUrl, baseUrl }: { rawUrl: string; baseUrl: string }): string {+ let parsed: URL;+ try {+ parsed = new URL(rawUrl);+ } catch {+ throw new Error('Invalid webhook URL: not a valid URL.');+ }+ if (parsed.protocol !== 'https:') throw new Error('Invalid webhook URL: must use https://.');+ if (parsed.username || parsed.password) throw new Error('Invalid webhook URL: must not contain a user name or password.');+ if (!parsed.pathname.includes('/api/webhooks/')) throw new Error('Invalid webhook URL: path must contain /api/webhooks/.');+ const expected = stripWww(new URL(baseUrl).host.toLowerCase());+ const actual = stripWww(parsed.host.toLowerCase());+ if (expected !== actual && !actual.endsWith(`.${expected}`)) {+ throw new Error(`Webhook host "${parsed.host}" does not match your connected NinjaPipe host "${new URL(baseUrl).host}". Use a Databin URL from your workspace.`);+ }+ return parsed.toString();+}++function stripWww(host: string): string {+ return host.startsWith('www.') ? host.slice(4) : host;+}++function parsePayload(value: unknown): unknown {+ if (typeof value !== 'string') return value;+ try {+ return JSON.parse(value);+ } catch {+ throw new Error('Payload must be valid JSON.');+ }+}diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/toggle-client-portal.ts b/packages/pieces/community/ninjapipe/src/lib/actions/toggle-client-portal.tsindex 6a9fb8919f7..50946aec349 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/toggle-client-portal.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/toggle-client-portal.ts@@ -1,45 +1,47 @@-import { createAction, Property } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, flattenCustomFields, getAuth, ninjapipeCommon } from '../common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeFields } from '../common/fields';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const toggleClientPortal = createAction({auth: ninjapipeAuth,name: 'toggle_client_portal',classification: 'DESTRUCTIVE',displayName: 'Toggle Client Portal',- description: 'Enable or disable client portal access for a contact. When enabling, NinjaPipe auto-generates a secure password and returns it in the response.',+ description:+ 'Enables or disables client portal access for a contact. Enabling generates a new portal password and returns it in the step output, where anyone who can see the run can read it.',audience: 'both',- aiMetadata: { description: 'Turns client portal access on or off for a given contact via the Enable toggle; the Enable mode optionally sets a portal email and provisions a fresh auto-generated password. Pick this to grant or revoke a customer-facing login. Re-running with the same toggle leaves access in the same on/off state, though enabling again may rotate the password.', idempotent: true },+ aiMetadata: {+ description:+ 'Turn client portal access on (enable: true) or off (enable: false) for a NinjaPipe contact by contact ID. Disabling revokes the login. Enabling sets a fresh auto-generated password every time and returns it as generated_password, so a repeated enable rotates the password. Not idempotent.',+ idempotent: false,+ },+ outputSchema: ninjapipeSchemas.clientPortal,props: {- contactId: ninjapipeCommon.contactDropdownRequired,- enable: Property.Checkbox({- displayName: 'Enable Client Portal',- description: 'Turn ON to enable, OFF to disable.',- required: true,- defaultValue: true,- }),- email: Property.ShortText({- displayName: 'Portal Email',- description: 'Optional. Used only when enabling. Defaults to the contact\'s email.',- required: false,- }),+ contactId: ninjapipeProps.contactRequired(),+ enable: Property.Checkbox({ displayName: 'Enable Client Portal', description: 'On to enable, off to disable.', required: true, defaultValue: true }),+ email: Property.ShortText({ displayName: 'Portal Email', description: "Used only when enabling. Defaults to the contact's email.", required: false }),},async run(context) {- const auth = getAuth(context);- const { contactId, enable, email } = context.propsValue;- const action = enable ? 'enable' : 'disable';- const body: Record<string, unknown> = {};- if (enable) {- if (email) body['email'] = email;- body['auto_generate_password'] = true;- }- const response = await ninjapipeApiCall<Record<string, unknown>>({- auth,+ const p = context.propsValue;+ const enable = p.enable === true;+ const body = await ninjapipeClient.ninjapipeRequest({+ auth: ninjapipeClient.readAuth(context.auth),method: HttpMethod.PUT,- path: `/client-portal-accounts/${encodeURIComponent(String(contactId))}/${encodeURIComponent(String(action))}`,- body: enable ? body : undefined,+ path: `/client-portal-accounts/${ninjapipeClient.pathId({ value: p.contactId, field: 'Contact' })}/${enable ? 'enable' : 'disable'}`,+ body: enable ? ninjapipeFields.compact({ email: p.email, auto_generate_password: true }) : {},+ operation: enable ? 'enable client portal' : 'disable client portal',});- return flattenCustomFields(response.body);+ const record = ninjapipeClient.unwrapRecord(body);+ const envelope = ninjapipeClient.isRecord(body) ? body : {};+ return {+ enabled: enable,+ ...record,+ generated_password: typeof envelope['generated_password'] === 'string' ? envelope['generated_password'] : null,+ message: typeof envelope['message'] === 'string' ? envelope['message'] : null,+ };},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/update-budget.ts b/packages/pieces/community/ninjapipe/src/lib/actions/update-budget.tsindex 172f7c483a8..226fde72e96 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/update-budget.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/update-budget.ts@@ -1,57 +1,52 @@-import { createAction, Property } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, flattenCustomFields, getAuth, ninjapipeCommon, toDateOnly } from '../common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeFields } from '../common/fields';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const updateBudget = createAction({auth: ninjapipeAuth,name: 'update_budget',classification: 'WRITE',displayName: 'Update Budget',- description: 'Updates a budget by ID.',+ description: 'Updates a budget. Fields left blank keep their value; use Clear Fields to empty them.',audience: 'both',- aiMetadata: { description: 'Update an existing budget identified by its ID. Only supplied fields change (name, allocated amount, category, period, currency, status, start/end dates); allocated must be greater than 0 if set. Repeating the same update is idempotent.', idempotent: true },+ aiMetadata: {+ description: 'Update a NinjaPipe budget by ID. Only filled fields change and Clear Fields empties fields. Re-running with the same input gives the same result.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.budget,props: {- budgetId: ninjapipeCommon.budgetDropdownRequired,+ budgetId: ninjapipeProps.budgetRequired(),name: Property.ShortText({ displayName: 'Name', required: false }),- allocated: Property.Number({- displayName: 'Allocated Amount',- description: 'Total allocated budget amount. Must be greater than 0 if set.',- required: false,- }),+ allocated: Property.Number({ displayName: 'Allocated Amount', required: false }),description: Property.LongText({ displayName: 'Description', required: false }),- category: ninjapipeCommon.budgetCategoryDropdown,- period: ninjapipeCommon.budgetPeriodDropdown,+ category: ninjapipeProps.staticDropdown({ displayName: 'Category', description: 'Category.', values: ['Marketing', 'Sales', 'Product', 'Operations'] }),+ period: ninjapipeProps.staticDropdown({ displayName: 'Period', description: 'Budget cycle. NinjaPipe derives the end date from the start date and period.', values: ['Monthly', 'Quarterly', 'Yearly'] }),currency: Property.ShortText({ displayName: 'Currency', required: false }),- status: ninjapipeCommon.budgetStatusDropdown,- startDate: Property.DateTime({ displayName: 'Start Date', required: false }),- endDate: Property.DateTime({ displayName: 'End Date', required: false }),+ status: ninjapipeProps.staticDropdown({ displayName: 'Status', description: 'Status.', values: ['Active', 'Inactive', 'Completed'] }),+ startDate: Property.DateTime({ displayName: 'Start Date', description: 'Date (YYYY-MM-DD).', required: false }),+ endDate: Property.DateTime({ displayName: 'End Date', description: 'Date (YYYY-MM-DD).', required: false }),+ clearFields: ninjapipeProps.clearFields({ fields: { description: 'Description', currency: 'Currency', start_date: 'Start Date', end_date: 'End Date' } }),},async run(context) {- const auth = getAuth(context);+ const auth = ninjapipeClient.readAuth(context.auth);const p = context.propsValue;- const body: Record<string, unknown> = {};- if (p.name) body['name'] = p.name;- if (p.allocated !== undefined && p.allocated !== null) body['allocated'] = p.allocated;- if (p.description !== undefined) body['description'] = p.description;- if (p.category) body['category'] = p.category;- if (p.period) body['period'] = p.period;- if (p.currency) body['currency'] = p.currency;- if (p.status) body['status'] = p.status;- {- const v = toDateOnly(p.startDate);- if (v) body['start_date'] = v;- }- {- const v = toDateOnly(p.endDate);- if (v) body['end_date'] = v;- }- const response = await ninjapipeApiCall<Record<string, unknown>>({- auth,- method: HttpMethod.PUT,- path: `/budgets/${encodeURIComponent(String(p.budgetId))}`,- body,+ const path = `/budgets/${ninjapipeClient.pathId({ value: p.budgetId, field: 'Budget' })}`;+ const changes = ninjapipeFields.compact({+ name: p.name,+ allocated: ninjapipeFields.toNumber({ value: p.allocated, field: 'Allocated Amount' }),+ description: p.description,+ category: p.category,+ period: p.period,+ currency: p.currency,+ status: p.status,+ start_date: ninjapipeFields.toDateOnly({ value: p.startDate, field: 'Start Date' }),+ end_date: ninjapipeFields.toDateOnly({ value: p.endDate, field: 'End Date' }),});- return flattenCustomFields(response.body);+ const body = ninjapipeFields.requireChanges({ body: ninjapipeFields.withClears({ body: changes, clear: p.clearFields }), what: 'budget' });+ return ninjapipeClient.sendRecord({ auth, method: HttpMethod.PUT, path, body, operation: 'update budget' });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/update-company.ts b/packages/pieces/community/ninjapipe/src/lib/actions/update-company.tsindex 44026f17f33..7e3f4518fef 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/update-company.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/update-company.ts@@ -1,52 +1,51 @@-import { createAction, Property } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, flattenCustomFields, getAuth, ninjapipeCommon } from '../common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeFields } from '../common/fields';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const updateCompany = createAction({auth: ninjapipeAuth,name: 'update_company',classification: 'WRITE',displayName: 'Update Company',- description: 'Updates a company by ID.',- audience: 'both',- aiMetadata: { description: 'Updates an existing company (CRM account) identified by Company ID, applying only the fields you supply (name, contact details, address, status, owner, notes, custom fields); omitted fields are left unchanged. Requires a valid company ID; repeating with the same values is safe.', idempotent: true },+ description: 'Updates a company. Fields left blank keep their value; use Clear Fields to empty them.',+ audience: 'human',+ aiMetadata: {+ description: 'Update a NinjaPipe company by ID. Only filled fields change and Clear Fields empties fields; custom fields are merged with the existing ones. Re-running with the same input gives the same result.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.company,props: {- companyId: ninjapipeCommon.companyDropdownRequired,+ companyId: ninjapipeProps.companyRequired(),name: Property.ShortText({ displayName: 'Name', required: false }),- industry: Property.ShortText({ displayName: 'Industry', required: false }),- website: Property.ShortText({ displayName: 'Website', required: false }),email: Property.ShortText({ displayName: 'Email', required: false }),phone: Property.ShortText({ displayName: 'Phone', required: false }),- address: Property.LongText({ displayName: 'Address', required: false }),- city: Property.ShortText({ displayName: 'City', required: false }),- zip: Property.ShortText({ displayName: 'ZIP Code', required: false }),- country: ninjapipeCommon.countryDropdown,- state: Property.ShortText({ displayName: 'State', required: false }),+ website: Property.ShortText({ displayName: 'Website', required: false }),+ industry: Property.ShortText({ displayName: 'Industry', required: false }),status: Property.ShortText({ displayName: 'Status', required: false }),- owner: Property.ShortText({ displayName: 'Owner', required: false }),- notes: Property.LongText({ displayName: 'Notes', required: false }),- customFields: Property.Object({ displayName: 'Custom Fields', required: false }),+ owner: ninjapipeProps.member({ displayName: 'Owner', description: 'Workspace member who owns the company (owner_id).' }),+ customFields: ninjapipeProps.customFields({ update: true }),+ clearFields: ninjapipeProps.clearFields({ fields: { email: 'Email', phone: 'Phone', website: 'Website', industry: 'Industry', status: 'Status' } }),},async run(context) {- const auth = getAuth(context);+ const auth = ninjapipeClient.readAuth(context.auth);const p = context.propsValue;- const body: Record<string, unknown> = {};- if (p.name) body['name'] = p.name;- if (p.industry) body['industry'] = p.industry;- if (p.website) body['website'] = p.website;- if (p.email) body['email'] = p.email;- if (p.phone) body['phone'] = p.phone;- if (p.address) body['address'] = p.address;- if (p.city) body['city'] = p.city;- if (p.zip) body['zip'] = p.zip;- if (p.country) body['country'] = p.country;- if (p.state) body['state'] = p.state;- if (p.status) body['status'] = p.status;- if (p.owner) body['owner'] = p.owner;- if (p.notes) body['notes'] = p.notes;- if (p.customFields && typeof p.customFields === 'object') body['custom_fields'] = p.customFields;- const response = await ninjapipeApiCall<Record<string, unknown>>({ auth, method: HttpMethod.PUT, path: `/companies/${encodeURIComponent(String(p.companyId))}`, body });- return flattenCustomFields(response.body);+ const path = `/companies/${ninjapipeClient.pathId({ value: p.companyId, field: 'Company' })}`;+ const fields = await ninjapipeFields.mergeCustomFields({ auth, path, fields: p.customFields, operation: 'read company' });+ const changes = ninjapipeFields.compact({+ name: p.name,+ email: p.email,+ phone: p.phone,+ website: p.website,+ industry: p.industry,+ status: p.status,+ owner_id: p.owner,+ fields,+ });+ const body = ninjapipeFields.requireChanges({ body: ninjapipeFields.withClears({ body: changes, clear: p.clearFields }), what: 'company' });+ return ninjapipeClient.sendRecord({ auth, method: HttpMethod.PUT, path, body, operation: 'update company' });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/update-contact.ts b/packages/pieces/community/ninjapipe/src/lib/actions/update-contact.tsindex 9322dfe3748..0fa91e6b4d3 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/update-contact.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/update-contact.ts@@ -1,60 +1,34 @@-import { createAction, Property } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, flattenCustomFields, getAuth, ninjapipeCommon } from '../common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeContacts } from '../common/contact-props';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const updateContact = createAction({auth: ninjapipeAuth,name: 'update_contact',classification: 'WRITE',displayName: 'Update Contact',- description: 'Updates an existing contact by ID.',- audience: 'both',- aiMetadata: { description: 'Update an existing contact identified by ID, setting only the fields you provide (name, email, phone, company, status, owner, address fields, notes, or custom fields); omitted fields are left unchanged. Use to edit a known contact, not to create one. Idempotent — re-sending the same values yields the same result.', idempotent: true },+ description: 'Updates a contact. Fields left blank keep their value; use Clear Fields to empty them.',+ audience: 'human',+ aiMetadata: {+ description: 'Update a NinjaPipe contact by ID. Only filled fields change; Clear Fields empties fields; custom fields are merged with the existing ones. Re-running with the same input gives the same result.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.contact,props: {- contactId: ninjapipeCommon.contactDropdownRequired,- firstName: Property.ShortText({ displayName: 'First Name', required: false }),- lastName: Property.ShortText({ displayName: 'Last Name', required: false }),- email: Property.ShortText({ displayName: 'Email', required: false }),- phone: Property.ShortText({ displayName: 'Phone', required: false }),- company: Property.ShortText({ displayName: 'Company', required: false }),- status: Property.ShortText({ displayName: 'Status', required: false }),- owner: Property.ShortText({ displayName: 'Owner', required: false }),- address: Property.LongText({ displayName: 'Address', required: false }),- city: Property.ShortText({ displayName: 'City', required: false }),- zip: Property.ShortText({ displayName: 'ZIP Code', required: false }),- country: ninjapipeCommon.countryDropdown,- state: Property.ShortText({ displayName: 'State', required: false }),- notes: Property.LongText({ displayName: 'Notes', required: false }),- customFields: Property.Object({ displayName: 'Custom Fields', required: false }),+ contactId: ninjapipeProps.contactRequired(),+ ...ninjapipeContacts.contactProps({ emailRequired: false }),+ customFields: ninjapipeProps.customFields({ update: true }),+ clearFields: ninjapipeProps.clearFields({ fields: ninjapipeContacts.CONTACT_CLEARABLE }),},async run(context) {- const auth = getAuth(context);+ const auth = ninjapipeClient.readAuth(context.auth);const p = context.propsValue;- const body: Record<string, unknown> = {};- if (p.firstName) body['first_name'] = p.firstName;- if (p.lastName) body['last_name'] = p.lastName;- if (p.email) body['email'] = p.email;- if (p.phone) body['phone'] = p.phone;- if (p.company) body['company'] = p.company;- if (p.status) body['status'] = p.status;- if (p.owner) body['owner'] = p.owner;- if (p.address) body['address'] = p.address;- if (p.city) body['city'] = p.city;- if (p.zip) body['zip'] = p.zip;- if (p.country) body['country'] = p.country;- if (p.state) body['state'] = p.state;- if (p.notes) body['notes'] = p.notes;- if (p.customFields && typeof p.customFields === 'object') {- body['custom_fields'] = p.customFields;- }-- const response = await ninjapipeApiCall<Record<string, unknown>>({- auth,- method: HttpMethod.PUT,- path: `/contacts/${encodeURIComponent(String(p.contactId))}`,- body,- });- return flattenCustomFields(response.body);+ const contactPath = `/contacts/${ninjapipeClient.pathId({ value: p.contactId, field: 'Contact' })}`;+ const body = await ninjapipeContacts.contactUpdateBody({ auth, contactPath, p, clear: p.clearFields });+ return ninjapipeClient.sendRecord({ auth, method: HttpMethod.PUT, path: contactPath, body, operation: 'update contact' });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/update-deal.ts b/packages/pieces/community/ninjapipe/src/lib/actions/update-deal.tsindex 2d92378bd39..62a1491854c 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/update-deal.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/update-deal.ts@@ -1,46 +1,49 @@-import { createAction, Property } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, flattenCustomFields, getAuth, ninjapipeCommon } from '../common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeFields } from '../common/fields';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const updateDeal = createAction({auth: ninjapipeAuth,name: 'update_deal',classification: 'WRITE',displayName: 'Update Deal',- description: 'Updates a deal by ID.',- audience: 'both',- aiMetadata: { description: 'Update an existing deal identified by its ID. Only supplied fields are changed (name, status, value, currency, owner, or associated pipeline/company/contact). Repeating the same update is idempotent.', idempotent: true },+ description: 'Updates a deal. Fields left blank keep their value; use Clear Fields to empty them.',+ audience: 'human',+ aiMetadata: {+ description: 'Update a NinjaPipe deal by ID. Only filled fields change and Clear Fields empties fields; custom fields are merged with the existing ones. Re-running with the same input gives the same result.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.deal,props: {- dealId: ninjapipeCommon.dealDropdownRequired,+ dealId: ninjapipeProps.dealRequired(),name: Property.ShortText({ displayName: 'Name', required: false }),- title: Property.ShortText({ displayName: 'Title', required: false }),- status: Property.ShortText({ displayName: 'Status', required: false }),- value: Property.Number({ displayName: 'Value', required: false }),- currency: Property.ShortText({ displayName: 'Currency', required: false }),- owner: Property.ShortText({ displayName: 'Owner', required: false }),- pipelineId: ninjapipeCommon.pipelineDropdown,- companyId: ninjapipeCommon.companyDropdown,- contactId: ninjapipeCommon.contactDropdown,- notes: Property.LongText({ displayName: 'Notes', required: false }),- customFields: Property.Object({ displayName: 'Custom Fields', required: false }),+ value: Property.Number({ displayName: 'Value', description: 'Deal value as a number.', required: false }),+ status: ninjapipeProps.staticDropdown({ displayName: 'Status', description: 'Status.', values: ['Open', 'In Progress', 'Won', 'Lost'] }),+ owner: ninjapipeProps.member({ displayName: 'Owner', description: 'Workspace member who owns the deal (owner_id).' }),+ contactId: ninjapipeProps.contactOptional(),+ companyId: ninjapipeProps.companyOptional(),+ customFields: ninjapipeProps.customFields({ update: true }),+ clearFields: ninjapipeProps.clearFields({ fields: { contact_id: 'Contact', company_id: 'Company' } }),},async run(context) {- const auth = getAuth(context);+ const auth = ninjapipeClient.readAuth(context.auth);const p = context.propsValue;- const body: Record<string, unknown> = {};- if (p.name) body['name'] = p.name;- if (p.title) body['title'] = p.title;- if (p.status) body['status'] = p.status;- if (p.value !== undefined) body['value'] = p.value;- if (p.currency) body['currency'] = p.currency;- if (p.owner) body['owner'] = p.owner;- if (p.pipelineId) body['pipeline_id'] = p.pipelineId;- if (p.companyId) body['company_id'] = p.companyId;- if (p.contactId) body['contact_id'] = p.contactId;- if (p.notes) body['notes'] = p.notes;- if (p.customFields && typeof p.customFields === 'object') body['custom_fields'] = p.customFields;- const response = await ninjapipeApiCall<Record<string, unknown>>({ auth, method: HttpMethod.PUT, path: `/deals/${encodeURIComponent(String(p.dealId))}`, body });- return flattenCustomFields(response.body);+ const path = `/deals/${ninjapipeClient.pathId({ value: p.dealId, field: 'Deal' })}`;+ const fields = await ninjapipeFields.mergeCustomFields({ auth, path, fields: p.customFields, operation: 'read deal' });+ const changes = ninjapipeFields.compact({+ name: p.name,+ value: ninjapipeFields.toNumber({ value: p.value, field: 'Value' }),+ status: p.status,+ owner_id: p.owner,+ contact_id: p.contactId,+ company_id: p.companyId,+ fields,+ });+ const body = ninjapipeFields.requireChanges({ body: ninjapipeFields.withClears({ body: changes, clear: p.clearFields }), what: 'deal' });+ return ninjapipeClient.sendRecord({ auth, method: HttpMethod.PUT, path, body, operation: 'update deal' });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/update-order.ts b/packages/pieces/community/ninjapipe/src/lib/actions/update-order.tsindex dc9c0ad9196..0dbf6cf6126 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/update-order.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/update-order.ts@@ -1,69 +1,60 @@-import { createAction, Property } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, flattenCustomFields, getAuth, ninjapipeCommon, toDateOnly } from '../common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeFields } from '../common/fields';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const updateOrder = createAction({auth: ninjapipeAuth,name: 'update_order',classification: 'WRITE',displayName: 'Update Order',- description: 'Updates an order by ID.',+ description: 'Updates a order. Fields left blank keep their value; use Clear Fields to empty them.',audience: 'both',- aiMetadata: { description: 'Updates an existing order identified by Order ID, applying only the fields you supply (customer details, amounts, status, payment status, dates, priority, tracking, notes); line items, currency, and custom fields go in Settings JSON. Requires a valid order ID; repeating with the same values is safe.', idempotent: true },+ aiMetadata: {+ description: 'Update a NinjaPipe order by ID. Only filled fields change and Clear Fields empties fields. Re-running with the same input gives the same result.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.order,props: {- orderId: ninjapipeCommon.orderDropdownRequired,+ orderId: ninjapipeProps.orderRequired(),customerName: Property.ShortText({ displayName: 'Customer Name', required: false }),customerEmail: Property.ShortText({ displayName: 'Customer Email', required: false }),customerCompany: Property.ShortText({ displayName: 'Customer Company', required: false }),- contactId: ninjapipeCommon.contactDropdown,+ contactId: ninjapipeProps.contactOptional(),orderNumber: Property.ShortText({ displayName: 'Order Number', required: false }),totalAmount: Property.Number({ displayName: 'Total Amount', required: false }),- status: ninjapipeCommon.orderStatusDropdown,- paymentStatus: ninjapipeCommon.paymentStatusDropdown,- orderDate: Property.DateTime({ displayName: 'Order Date', required: false }),- deliveryDate: Property.DateTime({ displayName: 'Delivery Date', required: false }),- priority: ninjapipeCommon.priorityDropdown,+ status: ninjapipeProps.staticDropdown({ displayName: 'Status', description: 'Status.', values: ['Processing', 'Shipped', 'Delivered', 'Cancelled'] }),+ paymentStatus: ninjapipeProps.staticDropdown({ displayName: 'Payment Status', description: 'Payment Status.', values: ['Pending', 'Paid', 'Refunded', 'Failed'] }),+ orderDate: Property.DateTime({ displayName: 'Order Date', description: 'Date (YYYY-MM-DD).', required: false }),+ deliveryDate: Property.DateTime({ displayName: 'Delivery Date', description: 'Date (YYYY-MM-DD).', required: false }),+ priority: ninjapipeProps.staticDropdown({ displayName: 'Priority', description: 'Priority.', values: ['High', 'Medium', 'Low'] }),trackingNumber: Property.ShortText({ displayName: 'Tracking Number', required: false }),notes: Property.LongText({ displayName: 'Notes', required: false }),- settingsJson: Property.Object({- displayName: 'Settings JSON',- description: 'Line items, currency, and custom fields.',- required: false,- }),+ clearFields: ninjapipeProps.clearFields({ fields: { customer_email: 'Customer Email', customer_company: 'Customer Company', contact_id: 'Contact', order_number: 'Order Number', order_date: 'Order Date', delivery_date: 'Delivery Date', tracking_number: 'Tracking Number', notes: 'Notes' } }),},async run(context) {- const auth = getAuth(context);+ const auth = ninjapipeClient.readAuth(context.auth);const p = context.propsValue;- const body: Record<string, unknown> = {};- if (p.customerName) body['customer_name'] = p.customerName;- if (p.customerEmail) body['customer_email'] = p.customerEmail;- if (p.customerCompany) body['customer_company'] = p.customerCompany;- if (p.contactId) body['contact_id'] = p.contactId;- if (p.orderNumber) body['order_number'] = p.orderNumber;- if (p.totalAmount !== undefined && p.totalAmount !== null) body['total_amount'] = p.totalAmount;- if (p.status) body['status'] = p.status;- if (p.paymentStatus) body['payment_status'] = p.paymentStatus;- {- const v = toDateOnly(p.orderDate);- if (v) body['order_date'] = v;- }- {- const v = toDateOnly(p.deliveryDate);- if (v) body['delivery_date'] = v;- }- if (p.priority) body['priority'] = p.priority;- if (p.trackingNumber) body['tracking_number'] = p.trackingNumber;- if (p.notes !== undefined) body['notes'] = p.notes;- if (p.settingsJson && typeof p.settingsJson === 'object' && Object.keys(p.settingsJson).length > 0) {- body['settings_json'] = p.settingsJson;- }- const response = await ninjapipeApiCall<Record<string, unknown>>({- auth,- method: HttpMethod.PUT,- path: `/orders/${encodeURIComponent(String(p.orderId))}`,- body,+ const path = `/orders/${ninjapipeClient.pathId({ value: p.orderId, field: 'Order' })}`;+ const changes = ninjapipeFields.compact({+ customer_name: p.customerName,+ customer_email: p.customerEmail,+ customer_company: p.customerCompany,+ contact_id: p.contactId,+ order_number: p.orderNumber,+ total_amount: ninjapipeFields.toNumber({ value: p.totalAmount, field: 'Total Amount' }),+ status: p.status,+ payment_status: p.paymentStatus,+ order_date: ninjapipeFields.toDateOnly({ value: p.orderDate, field: 'Order Date' }),+ delivery_date: ninjapipeFields.toDateOnly({ value: p.deliveryDate, field: 'Delivery Date' }),+ priority: p.priority,+ tracking_number: p.trackingNumber,+ notes: p.notes,});- return flattenCustomFields(response.body);+ const body = ninjapipeFields.requireChanges({ body: ninjapipeFields.withClears({ body: changes, clear: p.clearFields }), what: 'order' });+ return ninjapipeClient.sendRecord({ auth, method: HttpMethod.PUT, path, body, operation: 'update order' });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/update-pipeline-item.ts b/packages/pieces/community/ninjapipe/src/lib/actions/update-pipeline-item.tsnew file mode 100644index 00000000000..15456f8d872--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/actions/update-pipeline-item.ts@@ -0,0 +1,33 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeFields } from '../common/fields';+import { ninjapipeItems } from '../common/pipeline-item-props';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';++export const updatePipelineItem = createAction({+ auth: ninjapipeAuth,+ name: 'update_pipeline_item',+ classification: 'WRITE',+ displayName: 'Update Pipeline Item',+ description: 'Updates an item (card) of a pipeline or moves it to another stage. Fields left blank keep their value.',+ audience: 'human',+ aiMetadata: { description: 'Update or move a NinjaPipe pipeline item. Only filled fields change. Re-running with the same input gives the same result.', idempotent: true },+ outputSchema: ninjapipeSchemas.pipelineItem,+ props: {+ pipelineId: ninjapipeProps.pipelineRequired(),+ itemId: ninjapipeProps.pipelineItem(),+ stageId: ninjapipeProps.stageOptional(),+ title: Property.ShortText({ displayName: 'Title', required: false }),+ ...ninjapipeItems.itemProps(),+ clearFields: ninjapipeProps.clearFields({ fields: ninjapipeItems.ITEM_CLEARABLE }),+ },+ async run(context) {+ const p = context.propsValue;+ const path = `/pipelines/${ninjapipeClient.pathId({ value: p.pipelineId, field: 'Pipeline' })}/items/${ninjapipeClient.pathId({ value: p.itemId, field: 'Pipeline Item' })}`;+ const body = ninjapipeFields.requireChanges({ body: ninjapipeFields.withClears({ body: ninjapipeItems.itemBody(p), clear: p.clearFields }), what: 'pipeline item' });+ return ninjapipeClient.sendRecord({ auth: ninjapipeClient.readAuth(context.auth), method: HttpMethod.PUT, path, body, operation: 'update pipeline item' });+ },+});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/update-pipeline.ts b/packages/pieces/community/ninjapipe/src/lib/actions/update-pipeline.tsindex 4c815888613..05c8af81f68 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/update-pipeline.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/update-pipeline.ts@@ -1,47 +1,36 @@-import { createAction, Property } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, flattenCustomFields, getAuth, ninjapipeCommon } from '../common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeFields } from '../common/fields';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const updatePipeline = createAction({auth: ninjapipeAuth,name: 'update_pipeline',classification: 'WRITE',displayName: 'Update Pipeline',- description: 'Updates a pipeline by ID.',+ description: 'Renames a pipeline or changes its type, description or status. Stages are not changed.',audience: 'both',- aiMetadata: { description: 'Update an existing pipeline identified by ID, changing only the fields you supply (name, pipeline type, description, or status); omitted fields are left unchanged. Use to edit a known pipeline rather than create one. Idempotent — applying the same field values repeatedly yields the same result.', idempotent: true },+ aiMetadata: {+ description: 'Update a NinjaPipe pipeline by ID: name, type, description or status. Only filled fields change; stages stay as they are. Re-running with the same input gives the same result.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.pipeline,props: {- pipelineId: ninjapipeCommon.pipelineDropdownRequired,+ pipelineId: ninjapipeProps.pipelineRequired(),name: Property.ShortText({ displayName: 'Name', required: false }),- pipelineType: Property.StaticDropdown({- displayName: 'Pipeline Type',- required: false,- options: {- options: [- { label: 'Contacts', value: 'contacts' },- { label: 'Deals', value: 'deals' },- { label: 'General', value: 'general' },- ],- },- }),+ pipelineType: ninjapipeProps.staticDropdown({ displayName: 'Pipeline Type', description: 'What this pipeline tracks.', values: ['contacts', 'deals', 'general'] }),description: Property.LongText({ displayName: 'Description', required: false }),status: Property.ShortText({ displayName: 'Status', required: false }),+ clearFields: ninjapipeProps.clearFields({ fields: { description: 'Description' } }),},async run(context) {- const auth = getAuth(context);const p = context.propsValue;- const body: Record<string, unknown> = {};- if (p.name) body['name'] = p.name;- if (p.pipelineType) body['pipeline_type'] = p.pipelineType;- if (p.description !== undefined) body['description'] = p.description;- if (p.status) body['status'] = p.status;- const response = await ninjapipeApiCall<Record<string, unknown>>({- auth,- method: HttpMethod.PUT,- path: `/pipelines/${encodeURIComponent(String(p.pipelineId))}`,- body,- });- return flattenCustomFields(response.body);+ const path = `/pipelines/${ninjapipeClient.pathId({ value: p.pipelineId, field: 'Pipeline' })}`;+ const changes = ninjapipeFields.compact({ name: p.name, pipeline_type: p.pipelineType, description: p.description, status: p.status });+ const body = ninjapipeFields.requireChanges({ body: ninjapipeFields.withClears({ body: changes, clear: p.clearFields }), what: 'pipeline' });+ return ninjapipeClient.sendRecord({ auth: ninjapipeClient.readAuth(context.auth), method: HttpMethod.PUT, path, body, operation: 'update pipeline' });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/update-product.ts b/packages/pieces/community/ninjapipe/src/lib/actions/update-product.tsindex 4edd6bc6d97..949c91997c2 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/update-product.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/update-product.ts@@ -1,38 +1,50 @@-import { createAction, Property } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, flattenCustomFields, getAuth, ninjapipeCommon } from '../common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeFields } from '../common/fields';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const updateProduct = createAction({auth: ninjapipeAuth,name: 'update_product',classification: 'WRITE',displayName: 'Update Product',- description: 'Updates a product by ID.',+ description: 'Updates a product. Fields left blank keep their value; use Clear Fields to empty them.',audience: 'both',- aiMetadata: { description: 'Updates an existing product identified by Product ID, applying only the fields you supply (name, SKU, description, price, currency, status, custom fields); omitted fields are left unchanged. Requires a valid product ID; repeating with the same values is safe.', idempotent: true },+ aiMetadata: {+ description: 'Update a NinjaPipe product by ID. Only filled fields change and Clear Fields empties fields. Re-running with the same input gives the same result.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.product,props: {- productId: ninjapipeCommon.productDropdownRequired,+ productId: ninjapipeProps.productRequired(),name: Property.ShortText({ displayName: 'Name', required: false }),sku: Property.ShortText({ displayName: 'SKU', required: false }),- description: Property.LongText({ displayName: 'Description', required: false }),price: Property.Number({ displayName: 'Price', required: false }),- currency: Property.ShortText({ displayName: 'Currency', required: false }),+ cost: Property.Number({ displayName: 'Cost', required: false }),+ description: Property.LongText({ displayName: 'Description', required: false }),+ currency: Property.ShortText({ displayName: 'Currency', description: 'ISO currency code, e.g. EUR.', required: false }),status: Property.ShortText({ displayName: 'Status', required: false }),- customFields: Property.Object({ displayName: 'Custom Fields', required: false }),+ category: Property.ShortText({ displayName: 'Category', required: false }),+ clearFields: ninjapipeProps.clearFields({ fields: { sku: 'SKU', description: 'Description', currency: 'Currency', status: 'Status', category: 'Category' } }),},async run(context) {- const auth = getAuth(context);+ const auth = ninjapipeClient.readAuth(context.auth);const p = context.propsValue;- const body: Record<string, unknown> = {};- if (p.name) body['name'] = p.name;- if (p.sku) body['sku'] = p.sku;- if (p.description) body['description'] = p.description;- if (p.price !== undefined) body['price'] = p.price;- if (p.currency) body['currency'] = p.currency;- if (p.status) body['status'] = p.status;- if (p.customFields && typeof p.customFields === 'object') body['custom_fields'] = p.customFields;- const response = await ninjapipeApiCall<Record<string, unknown>>({ auth, method: HttpMethod.PUT, path: `/products/${encodeURIComponent(String(p.productId))}`, body });- return flattenCustomFields(response.body);+ const path = `/products/${ninjapipeClient.pathId({ value: p.productId, field: 'Product' })}`;+ const changes = ninjapipeFields.compact({+ name: p.name,+ sku: p.sku,+ price: ninjapipeFields.toNumber({ value: p.price, field: 'Price' }),+ cost: ninjapipeFields.toNumber({ value: p.cost, field: 'Cost' }),+ description: p.description,+ currency: p.currency,+ status: p.status,+ category: p.category,+ });+ const body = ninjapipeFields.requireChanges({ body: ninjapipeFields.withClears({ body: changes, clear: p.clearFields }), what: 'product' });+ return ninjapipeClient.sendRecord({ auth, method: HttpMethod.PUT, path, body, operation: 'update product' });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/update-project.ts b/packages/pieces/community/ninjapipe/src/lib/actions/update-project.tsindex b021b615b7d..0e50db2b538 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/update-project.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/update-project.ts@@ -1,50 +1,48 @@-import { createAction, Property } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, flattenCustomFields, getAuth, ninjapipeCommon, toDateOnly } from '../common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeFields } from '../common/fields';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';export const updateProject = createAction({auth: ninjapipeAuth,name: 'update_project',classification: 'WRITE',displayName: 'Update Project',- description: 'Updates a project by ID.',+ description: 'Updates a project. Fields left blank keep their value; use Clear Fields to empty them.',audience: 'both',- aiMetadata: { description: 'Updates an existing project identified by Project ID, applying only the fields you supply (name, description, status, priority, due date, team, tags, extra settings); omitted fields are left unchanged. Requires a valid project ID; repeating with the same values is safe.', idempotent: true },+ aiMetadata: {+ description: 'Update a NinjaPipe project by ID. Only filled fields change and Clear Fields empties fields. Re-running with the same input gives the same result.',+ idempotent: true,+ },+ outputSchema: ninjapipeSchemas.project,props: {- projectId: ninjapipeCommon.projectDropdownRequired,+ projectId: ninjapipeProps.projectRequired(),name: Property.ShortText({ displayName: 'Name', required: false }),description: Property.LongText({ displayName: 'Description', required: false }),- status: ninjapipeCommon.projectStatusDropdown,- priority: ninjapipeCommon.priorityDropdown,- dueDate: Property.DateTime({ displayName: 'Due Date', required: false }),- team: Property.Array({ displayName: 'Team', required: false }),+ status: ninjapipeProps.staticDropdown({ displayName: 'Status', description: 'Status.', values: ['Planning', 'In Progress', 'Completed', 'On Hold', 'Cancelled'] }),+ priority: ninjapipeProps.staticDropdown({ displayName: 'Priority', description: 'Priority.', values: ['High', 'Medium', 'Low'] }),+ dueDate: Property.DateTime({ displayName: 'Due Date', description: 'Date (YYYY-MM-DD).', required: false }),+ team: Property.Array({ displayName: 'Team Member IDs', required: false }),tags: Property.Array({ displayName: 'Tags', required: false }),- settingsJson: Property.Object({ displayName: 'Extra Settings', required: false }),+ clearFields: ninjapipeProps.clearFields({ fields: { description: 'Description', due_date: 'Due Date' } }),},async run(context) {- const auth = getAuth(context);+ const auth = ninjapipeClient.readAuth(context.auth);const p = context.propsValue;- const body: Record<string, unknown> = {};- if (p.name) body['name'] = p.name;- if (p.description !== undefined) body['description'] = p.description;- if (p.status) body['status'] = p.status;- if (p.priority) body['priority'] = p.priority;- {- const v = toDateOnly(p.dueDate);- if (v) body['due_date'] = v;- }- if (p.team && Array.isArray(p.team) && p.team.length > 0) body['team'] = p.team;- if (p.tags && Array.isArray(p.tags) && p.tags.length > 0) body['tags'] = p.tags;- if (p.settingsJson && typeof p.settingsJson === 'object' && Object.keys(p.settingsJson).length > 0) {- body['settings_json'] = p.settingsJson;- }- const response = await ninjapipeApiCall<Record<string, unknown>>({- auth,- method: HttpMethod.PUT,- path: `/projects/${encodeURIComponent(String(p.projectId))}`,- body,+ const path = `/projects/${ninjapipeClient.pathId({ value: p.projectId, field: 'Project' })}`;+ const changes = ninjapipeFields.compact({+ name: p.name,+ description: p.description,+ status: p.status,+ priority: p.priority,+ due_date: ninjapipeFields.toDateOnly({ value: p.dueDate, field: 'Due Date' }),+ team: ninjapipeFields.toStringList(p.team),+ tags: ninjapipeFields.toStringList(p.tags),});- return flattenCustomFields(response.body);+ const body = ninjapipeFields.requireChanges({ body: ninjapipeFields.withClears({ body: changes, clear: p.clearFields }), what: 'project' });+ return ninjapipeClient.sendRecord({ auth, method: HttpMethod.PUT, path, body, operation: 'update project' });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/update-task.ts b/packages/pieces/community/ninjapipe/src/lib/actions/update-task.tsindex 53682c302d4..662e08a5ac7 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/update-task.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/update-task.ts@@ -1,64 +1,31 @@-import { createAction, Property } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, flattenCustomFields, getAuth, ninjapipeCommon, toDateOnly } from '../common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeFields } from '../common/fields';+import { ninjapipeProps } from '../common/props';+import { ninjapipeTasks } from '../common/task-props';+import { ninjapipeSchemas } from '../output-schemas';export const updateTask = createAction({auth: ninjapipeAuth,name: 'update_task',classification: 'WRITE',displayName: 'Update Task',- description: 'Updates a task within a project.',- audience: 'both',- aiMetadata: { description: 'Update fields on an existing task, identified by its project ID and task ID. Only provided fields are changed; use this to set status, priority, assignee, due date, or to re-parent a subtask within the same project. Repeating the same update is idempotent.', idempotent: true },+ description: 'Updates a task. Fields left blank keep their value; use Clear Fields to empty them.',+ audience: 'human',+ aiMetadata: { description: 'Update a task in a NinjaPipe project. Only filled fields change. Re-running with the same input gives the same result.', idempotent: true },+ outputSchema: ninjapipeSchemas.task,props: {- projectId: ninjapipeCommon.projectDropdownRequired,- taskId: ninjapipeCommon.taskDropdown,- title: Property.ShortText({ displayName: 'Title', required: false }),- description: Property.LongText({ displayName: 'Description', required: false }),- status: ninjapipeCommon.taskStatusDropdown,- priority: ninjapipeCommon.priorityDropdown,- assigneeId: Property.ShortText({- displayName: 'Assignee ID',- description: 'Account ID of the user to assign this task to.',- required: false,- }),- dueDate: Property.DateTime({- displayName: 'Due Date',- required: false,- }),- parentId: Property.ShortText({- displayName: 'Parent Task ID',- description: 'Move under another task in the same project.',- required: false,- }),- tags: Property.Array({ displayName: 'Tags', required: false }),- settingsJson: Property.Object({ displayName: 'Extra Settings', required: false }),+ projectId: ninjapipeProps.projectRequired(),+ taskId: ninjapipeProps.task(),+ ...ninjapipeTasks.taskProps({ titleRequired: false }),+ clearFields: ninjapipeProps.clearFields({ fields: ninjapipeTasks.TASK_CLEARABLE }),},async run(context) {- const auth = getAuth(context);const p = context.propsValue;- const body: Record<string, unknown> = {};- if (p.title) body['title'] = p.title;- if (p.description !== undefined) body['description'] = p.description;- if (p.status) body['status'] = p.status;- if (p.priority) body['priority'] = p.priority;- if (p.assigneeId) body['assignee_id'] = p.assigneeId;- {- const v = toDateOnly(p.dueDate);- if (v) body['due_date'] = v;- }- if (p.parentId) body['parent_id'] = p.parentId;- if (p.tags && Array.isArray(p.tags) && p.tags.length > 0) body['tags'] = p.tags;- if (p.settingsJson && typeof p.settingsJson === 'object' && Object.keys(p.settingsJson).length > 0) {- body['settings_json'] = p.settingsJson;- }- const response = await ninjapipeApiCall<Record<string, unknown>>({- auth,- method: HttpMethod.PUT,- path: `/projects/${encodeURIComponent(String(p.projectId))}/tasks/${encodeURIComponent(String(p.taskId))}`,- body,- });- return flattenCustomFields(response.body);+ const path = `/projects/${ninjapipeClient.pathId({ value: p.projectId, field: 'Project' })}/tasks/${ninjapipeClient.pathId({ value: p.taskId, field: 'Task' })}`;+ const body = ninjapipeFields.requireChanges({ body: ninjapipeFields.withClears({ body: ninjapipeTasks.taskBody(p), clear: p.clearFields }), what: 'task' });+ return ninjapipeClient.sendRecord({ auth: ninjapipeClient.readAuth(context.auth), method: HttpMethod.PUT, path, body, operation: 'update task' });},});diff --git a/packages/pieces/community/ninjapipe/src/lib/actions/upsert-contact.ts b/packages/pieces/community/ninjapipe/src/lib/actions/upsert-contact.tsindex c059d5a4366..76006b41c96 100644--- a/packages/pieces/community/ninjapipe/src/lib/actions/upsert-contact.ts+++ b/packages/pieces/community/ninjapipe/src/lib/actions/upsert-contact.ts@@ -1,82 +1,41 @@-import { createAction, Property } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, extractItems, flattenCustomFields, getAuth, ninjapipeCommon } from '../common';+import { createAction } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { ninjapipeClient } from '../common/client';+import { ninjapipeContacts } from '../common/contact-props';+import { ninjapipeRecords } from '../common/records';+import { ninjapipeSchemas } from '../output-schemas';export const upsertContact = createAction({auth: ninjapipeAuth,name: 'upsert_contact',classification: 'WRITE',- displayName: 'Upsert Contact',- description: 'Creates a contact or updates an existing one by email.',+ displayName: 'Create or Update Contact',+ description: 'Finds a contact by exact email. Updates it when found, creates it when not.',audience: 'both',- aiMetadata: { description: 'Create-or-update a contact keyed on email: if a contact with the given email exists it is updated, otherwise a new one is created. Email is required and serves as the stable match key, making this safe to re-run (idempotent) unlike plain create-contact.', idempotent: true },- props: {- firstName: Property.ShortText({ displayName: 'First Name', required: false }),- lastName: Property.ShortText({ displayName: 'Last Name', required: false }),- email: Property.ShortText({ displayName: 'Email', description: 'Used as the unique key to decide create or update.', required: true }),- phone: Property.ShortText({ displayName: 'Phone', required: false }),- company: Property.ShortText({ displayName: 'Company', required: false }),- status: Property.ShortText({ displayName: 'Status', required: false }),- owner: Property.ShortText({ displayName: 'Owner', required: false }),- address: Property.LongText({ displayName: 'Address', required: false }),- city: Property.ShortText({ displayName: 'City', required: false }),- zip: Property.ShortText({ displayName: 'ZIP Code', required: false }),- country: ninjapipeCommon.countryDropdown,- state: Property.ShortText({ displayName: 'State', required: false }),- notes: Property.LongText({ displayName: 'Notes', required: false }),- customFields: Property.Object({ displayName: 'Custom Fields', required: false }),+ aiMetadata: {+ description: 'Create-or-update a NinjaPipe contact keyed on an exact, case-insensitive email match. Use it when an email may already exist (sync, form submissions); safe to retry because a second call updates the same contact. Custom fields are merged. Output action is "created" or "updated".',+ idempotent: true,},+ outputSchema: ninjapipeSchemas.contactWithAction,+ props: ninjapipeContacts.contactProps({ emailRequired: true }),async run(context) {- const auth = getAuth(context);+ const auth = ninjapipeClient.readAuth(context.auth);const p = context.propsValue;- const body: Record<string, unknown> = {};- if (p.firstName) body['first_name'] = p.firstName;- if (p.lastName) body['last_name'] = p.lastName;- if (p.email) body['email'] = p.email;- if (p.phone) body['phone'] = p.phone;- if (p.company) body['company'] = p.company;- if (p.status) body['status'] = p.status;- if (p.owner) body['owner'] = p.owner;- if (p.address) body['address'] = p.address;- if (p.city) body['city'] = p.city;- if (p.zip) body['zip'] = p.zip;- if (p.country) body['country'] = p.country;- if (p.state) body['state'] = p.state;- if (p.notes) body['notes'] = p.notes;- if (p.customFields && typeof p.customFields === 'object') {- body['custom_fields'] = p.customFields;- }-- const search = await ninjapipeApiCall<Record<string, unknown>>({- auth,- method: HttpMethod.GET,- path: '/contacts',- queryParams: { search: p.email, limit: '5' },- });- const items = extractItems(search.body) as ContactRecord[];- const existing = items.find(- (c) => c.email?.toLowerCase() === p.email.toLowerCase(),- );-+ const existing = await ninjapipeRecords.findContactByEmail({ auth, email: String(p.email) });if (existing) {- const response = await ninjapipeApiCall<Record<string, unknown>>({- auth,- method: HttpMethod.PUT,- path: `/contacts/${encodeURIComponent(String(existing.id))}`,- body,- });- return { ...flattenCustomFields(response.body), _upsert_action: 'updated' };+ const contactPath = `/contacts/${ninjapipeClient.pathId({ value: existing['id'], field: 'Contact ID' })}`;+ const body = await ninjapipeContacts.contactUpdateBody({ auth, contactPath, p, clear: undefined });+ const updated = await ninjapipeClient.sendRecord({ auth, method: HttpMethod.PUT, path: contactPath, body, operation: 'update contact' });+ return { action: 'updated', ...updated };}-- const response = await ninjapipeApiCall<Record<string, unknown>>({+ const created = await ninjapipeClient.sendRecord({auth,method: HttpMethod.POST,path: '/contacts',- body,+ body: ninjapipeContacts.contactBody(p),+ operation: 'create contact',});- return { ...flattenCustomFields(response.body), _upsert_action: 'created' };+ return { action: 'created', ...created };},});--type ContactRecord = { id?: string | number; email?: string };diff --git a/packages/pieces/community/ninjapipe/src/lib/auth.ts b/packages/pieces/community/ninjapipe/src/lib/auth.tsnew file mode 100644index 00000000000..bdfc39ff9c3--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/auth.ts@@ -0,0 +1,84 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { PieceAuth, Property } from '@activepieces/pieces-framework';+import { ninjapipeClient } from './common/client';++export const ninjapipeAuth = PieceAuth.CustomAuth({+ displayName: 'NinjaPipe API Connection',+ required: true,+ description: `Connect to your NinjaPipe workspace.++1. Log in to NinjaPipe and open **Workspace Settings > NinjaPipe API**.+2. Create an **API key** (starts with \`np_\`). Pick **write** permission if your flows create, update or delete records.+3. Enter your workspace **API Base URL**. The default is \`https://www.ninjapipe.app/api\`.`,+ props: {+ base_url: Property.ShortText({+ displayName: 'API Base URL',+ description: 'Your workspace API base URL (e.g. https://www.ninjapipe.app/api).',+ required: true,+ defaultValue: 'https://www.ninjapipe.app/api',+ }),+ api_key: PieceAuth.SecretText({+ displayName: 'API Key',+ description: 'Your workspace API key from NinjaPipe Settings > API.',+ required: true,+ }),+ },+ validate: async ({ auth }) => {+ const baseUrl = String(auth.base_url ?? '').trim();+ let parsed: URL;+ try {+ parsed = new URL(baseUrl);+ } catch {+ return { valid: false, error: 'Base URL is not a valid URL.' };+ }+ if (parsed.protocol !== 'https:') {+ return { valid: false, error: 'Base URL must use https://.' };+ }+ if (parsed.username || parsed.password) {+ return { valid: false, error: 'Base URL must not contain a user name or password.' };+ }+ const host = parsed.hostname.toLowerCase();+ if (isBlockedHost(host)) {+ return { valid: false, error: `Base URL host "${host}" is not allowed (loopback, private, or metadata IP).` };+ }+ try {+ await ninjapipeClient.ninjapipeRequest({+ auth: ninjapipeClient.readAuth(auth),+ method: HttpMethod.GET,+ path: '/contacts',+ query: { limit: 1 },+ operation: 'connection check',+ });+ return { valid: true };+ } catch (e) {+ const status = e instanceof Error && 'status' in e ? Number(e.status) : undefined;+ if (status === 401 || status === 403) {+ return { valid: false, error: 'API key was rejected. Check the key in NinjaPipe Settings > API.' };+ }+ if (status === 404) {+ return { valid: false, error: 'Base URL is reachable but /contacts returned 404. Check the Base URL path.' };+ }+ return {+ valid: false,+ error: `Could not connect to NinjaPipe (${status ?? (e instanceof Error ? e.message : 'unknown error')}). Check the Base URL and API Key.`,+ };+ }+ },+});++function isBlockedHost(host: string): boolean {+ return (+ host === 'localhost' ||+ host === '0.0.0.0' ||+ host.endsWith('.localhost') ||+ /^127\./.test(host) ||+ /^10\./.test(host) ||+ /^192\.168\./.test(host) ||+ /^172\.(1[6-9]|2\d|3[01])\./.test(host) ||+ /^169\.254\./.test(host) ||+ /^\[?(fc|fd)[0-9a-f]{2}:/i.test(host) ||+ /^\[?fe80:/i.test(host) ||+ host === '[::1]' ||+ host === '::1'+ );+}diff --git a/packages/pieces/community/ninjapipe/src/lib/common/ai-props.ts b/packages/pieces/community/ninjapipe/src/lib/common/ai-props.tsnew file mode 100644index 00000000000..48da9e85c73--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/common/ai-props.ts@@ -0,0 +1,63 @@+import { Property } from '@activepieces/pieces-framework';++function id({ displayName, description }: { displayName: string; description: string }) {+ return Property.ShortText({ displayName, description, required: true });+}++function optionalId({ displayName, description }: { displayName: string; description: string }) {+ return Property.ShortText({ displayName, description, required: false });+}++function text({ displayName, description, required = false }: { displayName: string; description: string; required?: boolean }) {+ return required ? Property.ShortText({ displayName, description, required: true }) : Property.ShortText({ displayName, description, required: false });+}++function number({ displayName, description }: { displayName: string; description: string }) {+ return Property.Number({ displayName, description, required: false });+}++function choice({ displayName, description, values }: { displayName: string; description: string; values: string[] }) {+ return Property.StaticDropdown({+ displayName,+ description,+ required: false,+ options: { options: values.map((value) => ({ label: value, value })) },+ });+}++function customFields({ update }: { update: boolean }) {+ return Property.Json({+ displayName: 'Custom Fields',+ description: update+ ? 'Object of custom field keys to values, e.g. {"industry_segment": "SMB"}. Merged into the existing custom fields; a key set to "" or null is removed.'+ : 'Object of custom field keys to values, e.g. {"industry_segment": "SMB"}.',+ required: false,+ });+}++function clearFields({ fields }: { fields: string[] }) {+ return Property.StaticMultiSelectDropdown({+ displayName: 'Clear Fields',+ description: `Field names to set to empty. Allowed: ${fields.join(', ')}. Do not also give a value for a cleared field.`,+ required: false,+ options: { options: fields.map((value) => ({ label: value, value })) },+ });+}++function page() {+ return Property.Number({ displayName: 'Page', description: 'Page number, starting at 1. Use nextPage from the previous result to continue.', required: false });+}++function limit() {+ return Property.Number({ displayName: 'Limit', description: 'Records per page, 1-100. Default 20.', required: false });+}++function sortBy({ values }: { values: string[] }) {+ return choice({ displayName: 'Sort By', description: `Sort field. Default created_at. One of: ${values.join(', ')}.`, values });+}++function sortOrder() {+ return choice({ displayName: 'Sort Order', description: 'asc or desc. Default desc.', values: ['desc', 'asc'] });+}++export const ninjapipeAiProps = { id, optionalId, text, number, choice, customFields, clearFields, page, limit, sortBy, sortOrder };diff --git a/packages/pieces/community/ninjapipe/src/lib/common/client.ts b/packages/pieces/community/ninjapipe/src/lib/common/client.tsnew file mode 100644index 00000000000..953c8d9ae9d--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/common/client.ts@@ -0,0 +1,343 @@+import { AuthenticationType, HttpMethod, HttpRequest, httpClient } from '@activepieces/pieces-common';++const MAX_PAGE_SIZE = 100;+const RETURN_ALL_MAX_ITEMS = 5000;+const MAX_RATE_LIMIT_RETRIES = 2;+const MAX_RETRY_WAIT_SECONDS = 60;+const DEFAULT_RETRY_WAIT_SECONDS = 10;+const MAX_ERROR_BODY_CHARS = 2000;+const KEEP_EMPTY_QUERY_KEYS = ['parent_id'];+++export class NinjaPipeApiError extends Error {+ readonly status: number;+ readonly code: string | undefined;+ readonly responseBody: unknown;++ constructor({ message, status, code, responseBody }: { message: string; status: number; code?: string; responseBody: unknown }) {+ super(message);+ this.name = 'NinjaPipeApiError';+ this.status = status;+ this.code = code;+ this.responseBody = responseBody;+ }+}++function isRecord(value: unknown): value is NinjaPipeRecord {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function readString(value: unknown): string | undefined {+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;+}++function readNumber(value: unknown): number | undefined {+ if (typeof value === 'number' && Number.isFinite(value)) return value;+ if (typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value))) return Number(value);+ return undefined;+}++function readAuth(auth: unknown): NinjaPipeAuth {+ const source = isRecord(auth) && isRecord(auth['props']) ? auth['props'] : auth;+ const baseUrl = isRecord(source) ? readString(source['base_url']) : undefined;+ const apiKey = isRecord(source) ? readString(source['api_key']) : undefined;+ if (!baseUrl || !apiKey) {+ throw new Error('The NinjaPipe connection is missing the API Base URL or API Key. Reconnect the account.');+ }+ return { baseUrl: baseUrl.replace(/\/+$/, ''), apiKey };+}++function pathId({ value, field }: { value: unknown; field: string }): string {+ const text = typeof value === 'number' ? String(value) : typeof value === 'string' ? value.trim() : '';+ if (text.length === 0) throw new Error(`${field} is required.`);+ return encodeURIComponent(text);+}++function clampLimit({ value, fallback = 20 }: { value: unknown; fallback?: number }): number {+ const parsed = readNumber(value);+ if (parsed === undefined) return fallback;+ return Math.min(MAX_PAGE_SIZE, Math.max(1, Math.floor(parsed)));+}++function readPage(value: unknown): number {+ const parsed = readNumber(value);+ if (parsed === undefined) return 1;+ return Math.max(1, Math.floor(parsed));+}++function boundedBody(body: unknown): unknown {+ const serialized = typeof body === 'string' ? body : JSON.stringify(body ?? null);+ return serialized.length > MAX_ERROR_BODY_CHARS ? `${serialized.slice(0, MAX_ERROR_BODY_CHARS)}…` : body;+}++function describeBody(body: unknown): { message: string | undefined; code: string | undefined } {+ if (isRecord(body)) {+ const details = isRecord(body['details']) ? body['details'] : undefined;+ const fields = details && Array.isArray(details['fields']) ? details['fields'].map(String) : [];+ const base = readString(body['message']) ?? readString(body['error']);+ const message = base && fields.length > 0 && !base.includes(fields[0]) ? `${base} (${fields.join(', ')})` : base;+ return { message, code: readString(body['code']) };+ }+ if (typeof body === 'string' && /<html/i.test(body)) {+ return { message: 'endpoint not found on this NinjaPipe API', code: undefined };+ }+ return { message: readString(body), code: undefined };+}++function hint(status: number): string {+ if (status === 401) return ' The API key was rejected; check it in NinjaPipe Workspace Settings > NinjaPipe API.';+ if (status === 403) return ' The API key is not allowed to do this; create and update steps need a key with write permission.';+ if (status === 404) return ' Check that the ID exists in this workspace.';+ if (status === 429) return ' NinjaPipe allows 100 requests per minute per API key; space out the steps.';+ return '';+}++function toNinjaPipeError({ status, body, operation }: { status: number; body: unknown; operation: string }): NinjaPipeApiError {+ const { message, code } = describeBody(body);+ return new NinjaPipeApiError({+ message: `NinjaPipe ${operation} failed (HTTP ${status})${message ? `: ${message.replace(/\.+$/, '')}` : ''}.${hint(status)}`,+ status,+ code,+ responseBody: boundedBody(body),+ });+}++function readHttpFailure(error: unknown): { status: number; body: unknown; headers: Record<string, unknown> } | undefined {+ if (!isRecord(error) || !isRecord(error['response'])) return undefined;+ const response = error['response'];+ const status = readNumber(response['status']);+ if (status === undefined) return undefined;+ return { status, body: response['body'], headers: isRecord(response['headers']) ? response['headers'] : {} };+}++function retryAfterSeconds({ body, headers }: { body: unknown; headers: Record<string, unknown> }): number {+ const fromBody = isRecord(body) ? readNumber(body['retryAfter']) : undefined;+ const fromHeader = readNumber(headers['retry-after']);+ const seconds = fromBody ?? fromHeader ?? DEFAULT_RETRY_WAIT_SECONDS;+ return Math.min(MAX_RETRY_WAIT_SECONDS, Math.max(1, seconds));+}+++function cleanQuery(query: Record<string, unknown> | undefined): Record<string, string> | undefined {+ if (!query) return undefined;+ const result: Record<string, string> = {};+ for (const [key, value] of Object.entries(query)) {+ if (value === undefined || value === null || (value === '' && !KEEP_EMPTY_QUERY_KEYS.includes(key))) continue;+ result[key] = String(value);+ }+ return result;+}++async function ninjapipeRequest<T = unknown>({+ auth,+ method,+ path,+ body,+ query,+ operation,+}: {+ auth: NinjaPipeAuth;+ method: HttpMethod;+ path: string;+ body?: unknown;+ query?: Record<string, unknown>;+ operation: string;+}): Promise<T> {+ if (!path.startsWith('/') || path.startsWith('//')) {+ throw new Error(`Invalid NinjaPipe API path "${path}".`);+ }+ const request: HttpRequest = {+ method,+ url: `${auth.baseUrl}${path}`,+ authentication: { type: AuthenticationType.BEARER_TOKEN, token: auth.apiKey },+ headers: body === undefined ? { Accept: 'application/json' } : { Accept: 'application/json', 'Content-Type': 'application/json' },+ body,+ queryParams: cleanQuery(query),+ };+ for (let attempt = 0; ; attempt++) {+ try {+ const response = await httpClient.sendRequest<T>(request);+ return response.body;+ } catch (error) {+ const failure = readHttpFailure(error);+ if (!failure) throw error;+ if (failure.status === 429 && attempt < MAX_RATE_LIMIT_RETRIES) {+ await ninjapipeClock.wait(retryAfterSeconds(failure) * 1000);+ continue;+ }+ throw toNinjaPipeError({ status: failure.status, body: failure.body, operation });+ }+ }+}++function unwrapRecord(body: unknown): NinjaPipeRecord {+ if (isRecord(body) && isRecord(body['data'])) return body['data'];+ if (isRecord(body)) return body;+ return {};+}++async function getRecord({ auth, path, operation }: { auth: NinjaPipeAuth; path: string; operation: string }): Promise<NinjaPipeRecord> {+ return unwrapRecord(await ninjapipeRequest({ auth, method: HttpMethod.GET, path, operation }));+}++async function sendRecord({+ auth,+ method,+ path,+ body,+ operation,+}: {+ auth: NinjaPipeAuth;+ method: HttpMethod;+ path: string;+ body: NinjaPipeRecord;+ operation: string;+}): Promise<NinjaPipeRecord> {+ return unwrapRecord(await ninjapipeRequest({ auth, method, path, body, operation }));+}++async function deleteRecord({+ auth,+ path,+ id,+ operation,+}: {+ auth: NinjaPipeAuth;+ path: string;+ id: string;+ operation: string;+}): Promise<{ deleted: boolean; id: string; name: string | null; message: string | null }> {+ const body = await ninjapipeRequest({ auth, method: HttpMethod.DELETE, path, operation });+ const data = isRecord(body) && isRecord(body['data']) ? body['data'] : {};+ const name = readString(data['name']) ?? readString(data['title']) ?? null;+ return {+ deleted: true,+ id: readString(data['id']) ?? id,+ name,+ message: isRecord(body) ? readString(body['message']) ?? null : null,+ };+}++function readItems(body: unknown): NinjaPipeRecord[] {+ const data = Array.isArray(body) ? body : isRecord(body) && Array.isArray(body['data']) ? body['data'] : [];+ return data.filter(isRecord);+}++function readPagination({ body, page, limit, itemCount }: { body: unknown; page: number; limit: number; itemCount: number }): { total: number | null; hasMore: boolean } {+ const pagination = isRecord(body) && isRecord(body['pagination']) ? body['pagination'] : undefined;+ const total = pagination ? readNumber(pagination['total']) ?? null : null;+ const pages = pagination ? readNumber(pagination['pages']) ?? readNumber(pagination['totalPages']) : undefined;+ if (pages !== undefined && pages > 0) return { total, hasMore: page < pages };+ if (total !== null && total > 0) return { total, hasMore: page * limit < total };+ return { total, hasMore: itemCount === limit };+}++async function listPage({+ auth,+ path,+ query,+ page,+ limit,+ operation,+}: {+ auth: NinjaPipeAuth;+ path: string;+ query?: Record<string, unknown>;+ page: number;+ limit: number;+ operation: string;+}): Promise<NinjaPipePage> {+ const body = await ninjapipeRequest({ auth, method: HttpMethod.GET, path, query: { ...query, page, limit }, operation });+ const items = readItems(body);+ const pagination = readPagination({ body, page, limit, itemCount: items.length });+ const hasMore = pagination.hasMore;+ const total = page === 1 && !hasMore ? items.length : pagination.total;+ return { items, count: items.length, total, hasMore, nextPage: hasMore ? page + 1 : null };+}++async function listAll({+ auth,+ path,+ query,+ operation,+ maxItems = RETURN_ALL_MAX_ITEMS,+}: {+ auth: NinjaPipeAuth;+ path: string;+ query?: Record<string, unknown>;+ operation: string;+ maxItems?: number;+}): Promise<NinjaPipePage> {+ const items: NinjaPipeRecord[] = [];+ let page = 1;+ let total: number | null = null;+ let hasMore = true;+ while (hasMore && items.length < maxItems) {+ const result = await listPage({ auth, path, query, page, limit: MAX_PAGE_SIZE, operation });+ total = result.total;+ items.push(...result.items.slice(0, maxItems - items.length));+ hasMore = result.hasMore && result.items.length > 0;+ page += 1;+ }+ const truncated = hasMore;+ return { items, count: items.length, total, hasMore: truncated, nextPage: truncated ? page : null };+}++async function runList({+ auth,+ path,+ query,+ operation,+ returnAll,+ page,+ limit,+}: {+ auth: NinjaPipeAuth;+ path: string;+ query?: Record<string, unknown>;+ operation: string;+ returnAll: unknown;+ page: unknown;+ limit: unknown;+}): Promise<NinjaPipePage> {+ if (returnAll === true) return listAll({ auth, path, query, operation });+ return listPage({ auth, path, query, page: readPage(page), limit: clampLimit({ value: limit }), operation });+}++export const ninjapipeClock = {+ wait: (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)),+};++export const ninjapipeClient = {+ isRecord,+ readAuth,+ pathId,+ clampLimit,+ readPage,+ toNinjaPipeError,+ retryAfterSeconds,+ ninjapipeRequest,+ unwrapRecord,+ getRecord,+ sendRecord,+ deleteRecord,+ readItems,+ readPagination,+ listPage,+ listAll,+ runList,+ MAX_PAGE_SIZE,+ RETURN_ALL_MAX_ITEMS,+};++export type NinjaPipeAuth = { baseUrl: string; apiKey: string };++export type NinjaPipeRecord = Record<string, unknown>;++export type NinjaPipePage = {+ items: NinjaPipeRecord[];+ count: number;+ total: number | null;+ hasMore: boolean;+ nextPage: number | null;+};diff --git a/packages/pieces/community/ninjapipe/src/lib/common/contact-props.ts b/packages/pieces/community/ninjapipe/src/lib/common/contact-props.tsnew file mode 100644index 00000000000..b67025a56dd--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/common/contact-props.ts@@ -0,0 +1,72 @@+import { Property } from '@activepieces/pieces-framework';+import { NinjaPipeAuth, NinjaPipeRecord } from './client';+import { ninjapipeFields } from './fields';+import { ninjapipeProps } from './props';++function contactProps({ emailRequired }: { emailRequired: boolean }) {+ return {+ firstName: Property.ShortText({ displayName: 'First Name', required: false }),+ lastName: Property.ShortText({ displayName: 'Last Name', required: false }),+ email: emailRequired+ ? Property.ShortText({ displayName: 'Email', description: 'Email address of the contact. NinjaPipe allows one contact per email.', required: true })+ : Property.ShortText({ displayName: 'Email', description: 'Email address of the contact. NinjaPipe allows one contact per email.', required: false }),+ phone: Property.ShortText({ displayName: 'Phone', required: false }),+ status: Property.ShortText({ displayName: 'Status', description: 'Contact status, e.g. Active or Lead.', required: false }),+ companyId: ninjapipeProps.companyOptional(),+ owner: ninjapipeProps.member({ displayName: 'Owner', description: 'Workspace member who owns the contact (owner_id). Defaults to the API key owner.' }),+ assignedTo: ninjapipeProps.member({ displayName: 'Assigned To', description: 'Workspace member shown as "Assign to" in NinjaPipe (assigned_to).' }),+ customFields: ninjapipeProps.customFields({ update: false }),+ };+}++function contactBody(p: ContactInput): NinjaPipeRecord {+ return ninjapipeFields.compact({+ first_name: p.firstName,+ last_name: p.lastName,+ email: p.email,+ phone: p.phone,+ status: p.status,+ company_id: p.companyId,+ owner_id: p.owner,+ assigned_to: p.assignedTo,+ fields: ninjapipeFields.readCustomFields(p.customFields),+ });+}++async function contactUpdateBody({+ auth,+ contactPath,+ p,+ clear,+}: {+ auth: NinjaPipeAuth;+ contactPath: string;+ p: ContactInput;+ clear: unknown;+}): Promise<NinjaPipeRecord> {+ const fields = await ninjapipeFields.mergeCustomFields({ auth, path: contactPath, fields: p.customFields, operation: 'read contact' });+ const body = ninjapipeFields.compact({ ...contactBody({ ...p, customFields: undefined }), fields });+ return ninjapipeFields.requireChanges({ body: ninjapipeFields.withClears({ body, clear }), what: 'contact' });+}++const CONTACT_CLEARABLE: Record<string, string> = {+ first_name: 'First Name',+ last_name: 'Last Name',+ phone: 'Phone',+ company_id: 'Company',+ assigned_to: 'Assigned To',+};++export const ninjapipeContacts = { contactProps, contactBody, contactUpdateBody, CONTACT_CLEARABLE };++export type ContactInput = {+ firstName?: unknown;+ lastName?: unknown;+ email?: unknown;+ phone?: unknown;+ status?: unknown;+ companyId?: unknown;+ owner?: unknown;+ assignedTo?: unknown;+ customFields?: unknown;+};diff --git a/packages/pieces/community/ninjapipe/src/lib/common/fields.ts b/packages/pieces/community/ninjapipe/src/lib/common/fields.tsnew file mode 100644index 00000000000..2d1da6f2b8d--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/common/fields.ts@@ -0,0 +1,102 @@+import { NinjaPipeAuth, NinjaPipeRecord, ninjapipeClient } from './client';++function isBlank(value: unknown): boolean {+ return value === undefined || value === null || (typeof value === 'string' && value.trim() === '');+}++function compact(input: Record<string, unknown>): NinjaPipeRecord {+ return Object.fromEntries(+ Object.entries(input)+ .filter(([, value]) => !isBlank(value))+ .map(([key, value]) => [key, typeof value === 'string' ? value.trim() : value]),+ );+}++function withClears({ body, clear }: { body: NinjaPipeRecord; clear: unknown }): NinjaPipeRecord {+ const keys = Array.isArray(clear) ? clear.filter((key): key is string => typeof key === 'string') : [];+ const conflicts = keys.filter((key) => key in body);+ if (conflicts.length > 0) {+ throw new Error(`Fields cannot be set and cleared in the same step: ${conflicts.join(', ')}.`);+ }+ return { ...body, ...Object.fromEntries(keys.map((key) => [key, null])) };+}++function toNumber({ value, field }: { value: unknown; field: string }): number | undefined {+ if (isBlank(value)) return undefined;+ const parsed = typeof value === 'number' ? value : Number(String(value).trim());+ if (!Number.isFinite(parsed)) throw new Error(`${field} must be a number.`);+ return parsed;+}++function toDateOnly({ value, field }: { value: unknown; field: string }): string | undefined {+ if (isBlank(value)) return undefined;+ const text = String(value).trim();+ const isoDate = /^(\d{4}-\d{2}-\d{2})/.exec(text);+ if (isoDate) return isoDate[1];+ const parsed = new Date(text);+ if (Number.isNaN(parsed.getTime())) throw new Error(`${field} must be a date (YYYY-MM-DD).`);+ return parsed.toISOString().slice(0, 10);+}++function toStringList(value: unknown): string[] | undefined {+ if (value === undefined || value === null) return undefined;+ const list = Array.isArray(value) ? value : [value];+ const cleaned = list+ .map((item) => (ninjapipeClient.isRecord(item) ? Object.values(item)[0] : item))+ .filter((item) => !isBlank(item))+ .map((item) => String(item).trim());+ return cleaned.length > 0 ? cleaned : undefined;+}++function readCustomFields(value: unknown): NinjaPipeRecord | undefined {+ if (value === undefined || value === null || value === '') return undefined;+ const parsed = typeof value === 'string' ? parseJsonObject(value) : value;+ if (!ninjapipeClient.isRecord(parsed)) throw new Error('Custom Fields must be an object of field keys and values.');+ return Object.keys(parsed).length > 0 ? parsed : undefined;+}++function parseJsonObject(text: string): unknown {+ try {+ return JSON.parse(text);+ } catch {+ throw new Error('Custom Fields must be valid JSON.');+ }+}++async function mergeCustomFields({+ auth,+ path,+ fields,+ operation,+}: {+ auth: NinjaPipeAuth;+ path: string;+ fields: unknown;+ operation: string;+}): Promise<NinjaPipeRecord | undefined> {+ const incoming = readCustomFields(fields);+ if (!incoming) return undefined;+ const current = await ninjapipeClient.getRecord({ auth, path, operation });+ const existing = ninjapipeClient.isRecord(current['fields']) ? current['fields'] : {};+ const merged = { ...existing, ...incoming };+ return Object.fromEntries(Object.entries(merged).filter(([, value]) => !isBlank(value)));+}++function requireChanges({ body, what }: { body: NinjaPipeRecord; what: string }): NinjaPipeRecord {+ if (Object.keys(body).length === 0) {+ throw new Error(`Nothing to update: set or clear at least one ${what} field.`);+ }+ return body;+}++export const ninjapipeFields = {+ isBlank,+ compact,+ withClears,+ toNumber,+ toDateOnly,+ toStringList,+ readCustomFields,+ mergeCustomFields,+ requireChanges,+};diff --git a/packages/pieces/community/ninjapipe/src/lib/common/index.ts b/packages/pieces/community/ninjapipe/src/lib/common/index.tsdeleted file mode 100644index 18bbd50550b..00000000000--- a/packages/pieces/community/ninjapipe/src/lib/common/index.ts+++ /dev/null@@ -1,675 +0,0 @@-import { httpClient, HttpMethod, AuthenticationType, HttpMessageBody, HttpResponse } from '@activepieces/pieces-common';-import { PiecePropValueSchema, Property } from '@activepieces/pieces-framework';-import { ninjapipeAuth } from '../../';--export type NinjaPipeAuth = { base_url: string; api_key: string };--export function getAuth(context: { auth: unknown }): NinjaPipeAuth {- const raw = context.auth as- | (PiecePropValueSchema<typeof ninjapipeAuth> & { props?: { base_url?: string; api_key?: string } })- | null- | undefined;- const base_url = raw?.props?.base_url ?? raw?.base_url;- const api_key = raw?.props?.api_key ?? raw?.api_key;- if (!base_url || !api_key) {- throw new Error('NinjaPipe connection is missing Base URL or API Key. Reconnect the account.');- }- return { base_url, api_key };-}--export async function ninjapipeApiCall<T extends HttpMessageBody>({- auth,- method,- path,- body,- queryParams,-}: {- auth: NinjaPipeAuth;- method: HttpMethod;- path: string;- body?: unknown;- queryParams?: Record<string, string | number | boolean | undefined>;-}): Promise<HttpResponse<T>> {- const sanitizedPath = path.startsWith('/') ? path : `/${path}`;- const url = `${auth.base_url.replace(/\/+$/, '')}${sanitizedPath}`;-- const cleanQuery = queryParams- ? Object.fromEntries(- Object.entries(queryParams)- .filter(([, v]) => v !== undefined && v !== null)- .map(([k, v]) => [k, String(v)]),- )- : undefined;-- return await httpClient.sendRequest<T>({- method,- url,- authentication: {- type: AuthenticationType.BEARER_TOKEN,- token: auth.api_key,- },- headers: {- Accept: 'application/json',- 'Content-Type': 'application/json',- },- body,- queryParams: cleanQuery,- });-}--const RESOURCE_KEYS = [- 'contacts', 'companies', 'deals', 'products', 'budgets', 'lists',- 'pipelines', 'pipeline_items', 'pipelineItems', 'invoices', 'orders', 'projects', 'tasks', 'databins', 'responses',-];--export function extractItems(response: unknown): unknown[] {- if (!response) return [];- if (Array.isArray(response)) return response;- const r = response as Record<string, unknown>;- if (Array.isArray(r['data'])) return r['data'] as unknown[];- if (Array.isArray(r['items'])) return r['items'] as unknown[];- if (Array.isArray(r['results'])) return r['results'] as unknown[];- for (const key of RESOURCE_KEYS) {- if (Array.isArray(r[key])) return r[key] as unknown[];- }- return [];-}--export function flattenObject(- obj: Record<string, unknown>,- prefix = '',-): Record<string, unknown> {- const result: Record<string, unknown> = {};- for (const [key, value] of Object.entries(obj)) {- const flatKey = prefix ? `${prefix}_${key}` : key;- if (value === null || value === undefined) {- result[flatKey] = null;- } else if (Array.isArray(value)) {- result[flatKey] = value- .map((v) => (typeof v === 'object' ? JSON.stringify(v) : String(v)))- .join(', ');- } else if (typeof value === 'object') {- Object.assign(result, flattenObject(value as Record<string, unknown>, flatKey));- } else {- result[flatKey] = value;- }- }- return result;-}--export function flattenCustomFields(record: Record<string, unknown>): Record<string, unknown> {- const flat: Record<string, unknown> = { ...record };- const cf = flat['custom_fields'] as Record<string, unknown> | undefined;- if (cf && typeof cf === 'object' && !Array.isArray(cf)) {- for (const [key, value] of Object.entries(cf)) {- if (!(key in flat)) flat[key] = value;- flat[`cf_${key}`] = value;- }- }- delete flat['custom_fields'];- return flattenObject(flat);-}--export function flattenArray(items: unknown[]): Record<string, unknown>[] {- return items.map((item) => {- if (typeof item === 'object' && item !== null) {- return flattenCustomFields(item as Record<string, unknown>);- }- return { raw_value: item };- });-}--export function toDateOnly(value: unknown): string | undefined {- if (value === null || value === undefined || value === '') return undefined;- const str = String(value);- const isoMatch = str.match(/^(\d{4}-\d{2}-\d{2})/);- if (isoMatch) return isoMatch[1];- const d = new Date(str);- if (isNaN(d.getTime())) return undefined;- return d.toISOString().slice(0, 10);-}--export function safeParseJson(value: unknown, fieldName: string): unknown {- if (value === null || value === undefined) return undefined;- if (typeof value === 'object') return value;- if (typeof value !== 'string') return value;- try {- return JSON.parse(value);- } catch {- throw new Error(`Invalid JSON in field "${fieldName}".`);- }-}--type DropdownItem = {- id?: string | number;- name?: string;- title?: string;- first_name?: string;- last_name?: string;- email?: string;-};--const buildDropdownOption = (item: DropdownItem) => ({- label: item.name ?? item.title ?? String(item.id ?? ''),- value: String(item.id ?? ''),-});--export const ninjapipeCommon = {- countryDropdown: Property.StaticDropdown({- displayName: 'Country',- description: 'Select a country.',- required: false,- options: {- options: [- { label: 'Germany', value: 'DE' },- { label: 'Austria', value: 'AT' },- { label: 'Switzerland', value: 'CH' },- { label: 'Belgium', value: 'BE' },- { label: 'Netherlands', value: 'NL' },- { label: 'Luxembourg', value: 'LU' },- { label: 'France', value: 'FR' },- { label: 'Italy', value: 'IT' },- { label: 'Spain', value: 'ES' },- { label: 'Portugal', value: 'PT' },- { label: 'Poland', value: 'PL' },- { label: 'Hungary', value: 'HU' },- { label: 'United Kingdom', value: 'GB' },- { label: 'United States', value: 'US' },- { label: 'Canada', value: 'CA' },- ],- },- }),-- pipelineDropdown: Property.Dropdown({- auth: ninjapipeAuth,- displayName: 'Pipeline',- description: 'Select a pipeline.',- refreshers: [],- required: false,- options: async ({ auth }) => {- if (!auth) return { disabled: true, options: [], placeholder: 'Please connect your account first' };- try {- const a = getAuth({ auth });- const response = await ninjapipeApiCall<{ data?: unknown[]; pipelines?: unknown[] }>({- auth: a,- method: HttpMethod.GET,- path: '/pipelines',- queryParams: { limit: '100' },- });- const items = extractItems(response.body) as DropdownItem[];- return {- disabled: false,- options: items.map(buildDropdownOption),- };- } catch {- return { disabled: true, options: [], placeholder: 'Failed to load pipelines. Check connection.' };- }- },- }),-- contactDropdown: Property.Dropdown({- auth: ninjapipeAuth,- displayName: 'Contact',- description: 'Select a contact.',- refreshers: [],- required: false,- options: async ({ auth }) => {- if (!auth) return { disabled: true, options: [], placeholder: 'Please connect your account first' };- try {- const a = getAuth({ auth });- const response = await ninjapipeApiCall<{ data?: unknown[]; contacts?: unknown[] }>({- auth: a,- method: HttpMethod.GET,- path: '/contacts',- queryParams: { limit: '100' },- });- const items = extractItems(response.body) as DropdownItem[];- return {- disabled: false,- options: items.map((c) => ({- label:- `${c.first_name ?? ''} ${c.last_name ?? ''} <${c.email ?? 'no-email'}>`.trim() ||- c.email ||- String(c.id ?? ''),- value: String(c.id ?? ''),- })),- };- } catch {- return { disabled: true, options: [], placeholder: 'Failed to load contacts. Check connection.' };- }- },- }),-- companyDropdown: Property.Dropdown({- auth: ninjapipeAuth,- displayName: 'Company',- description: 'Select a company.',- refreshers: [],- required: false,- options: async ({ auth }) => {- if (!auth) return { disabled: true, options: [], placeholder: 'Please connect your account first' };- try {- const a = getAuth({ auth });- const response = await ninjapipeApiCall<{ data?: unknown[]; companies?: unknown[] }>({- auth: a,- method: HttpMethod.GET,- path: '/companies',- queryParams: { limit: '100' },- });- const items = extractItems(response.body) as DropdownItem[];- return {- disabled: false,- options: items.map(buildDropdownOption),- };- } catch {- return { disabled: true, options: [], placeholder: 'Failed to load companies. Check connection.' };- }- },- }),-- projectDropdown: Property.Dropdown({- auth: ninjapipeAuth,- displayName: 'Project',- description: 'Select a project.',- refreshers: [],- required: false,- options: async ({ auth }) => {- if (!auth) return { disabled: true, options: [], placeholder: 'Please connect your account first' };- try {- const a = getAuth({ auth });- const response = await ninjapipeApiCall<{ data?: unknown[]; projects?: unknown[] }>({- auth: a,- method: HttpMethod.GET,- path: '/projects',- queryParams: { limit: '100' },- });- const items = extractItems(response.body) as DropdownItem[];- return {- disabled: false,- options: items.map(buildDropdownOption),- };- } catch {- return { disabled: true, options: [], placeholder: 'Failed to load projects. Check connection.' };- }- },- }),-- projectDropdownRequired: Property.Dropdown({- auth: ninjapipeAuth,- displayName: 'Project',- description: 'Select the project this task belongs to.',- refreshers: [],- required: true,- options: async ({ auth }) => {- if (!auth) return { disabled: true, options: [], placeholder: 'Please connect your account first' };- try {- const a = getAuth({ auth });- const response = await ninjapipeApiCall<{ data?: unknown[]; projects?: unknown[] }>({- auth: a,- method: HttpMethod.GET,- path: '/projects',- queryParams: { limit: '100' },- });- const items = extractItems(response.body) as DropdownItem[];- return {- disabled: false,- options: items.map(buildDropdownOption),- };- } catch {- return { disabled: true, options: [], placeholder: 'Failed to load projects. Check connection.' };- }- },- }),-- taskDropdown: Property.Dropdown({- auth: ninjapipeAuth,- displayName: 'Task',- description: 'Select a task. Pick the project first.',- refreshers: ['projectId'],- required: true,- options: async ({ auth, projectId }) => {- if (!auth) return { disabled: true, options: [], placeholder: 'Please connect your account first' };- if (!projectId) return { disabled: true, options: [], placeholder: 'Select a project first' };- try {- const a = getAuth({ auth });- const response = await ninjapipeApiCall<{ data?: unknown[] }>({- auth: a,- method: HttpMethod.GET,- path: `/projects/${projectId}/tasks`,- queryParams: { sort_by: 'created_at', sort_order: 'desc' },- });- const items = extractItems(response.body) as DropdownItem[];- return {- disabled: false,- options: items.map(buildDropdownOption),- };- } catch {- return { disabled: true, options: [], placeholder: 'Failed to load tasks.' };- }- },- }),-- taskStatusDropdown: Property.StaticDropdown({- displayName: 'Status',- description: 'Task status.',- required: false,- defaultValue: 'To Do',- options: {- options: [- { label: 'To Do', value: 'To Do' },- { label: 'In Progress', value: 'In Progress' },- { label: 'Done', value: 'Done' },- { label: 'Cancelled', value: 'Cancelled' },- ],- },- }),-- priorityDropdown: Property.StaticDropdown({- displayName: 'Priority',- description: 'Priority level.',- required: false,- defaultValue: 'Medium',- options: {- options: [- { label: 'High', value: 'High' },- { label: 'Medium', value: 'Medium' },- { label: 'Low', value: 'Low' },- ],- },- }),-- projectStatusDropdown: Property.StaticDropdown({- displayName: 'Status',- description: 'Project status.',- required: false,- defaultValue: 'Planning',- options: {- options: [- { label: 'Planning', value: 'Planning' },- { label: 'In Progress', value: 'In Progress' },- { label: 'Completed', value: 'Completed' },- { label: 'On Hold', value: 'On Hold' },- { label: 'Cancelled', value: 'Cancelled' },- ],- },- }),-- budgetCategoryDropdown: Property.StaticDropdown({- displayName: 'Category',- description: 'Budget category.',- required: false,- options: {- options: [- { label: 'Marketing', value: 'Marketing' },- { label: 'Sales', value: 'Sales' },- { label: 'Product', value: 'Product' },- { label: 'Operations', value: 'Operations' },- ],- },- }),-- budgetPeriodDropdown: Property.StaticDropdown({- displayName: 'Period',- description: 'Budget period.',- required: false,- options: {- options: [- { label: 'Monthly', value: 'Monthly' },- { label: 'Quarterly', value: 'Quarterly' },- { label: 'Yearly', value: 'Yearly' },- ],- },- }),-- budgetStatusDropdown: Property.StaticDropdown({- displayName: 'Status',- description: 'Budget status.',- required: false,- defaultValue: 'Active',- options: {- options: [- { label: 'Active', value: 'Active' },- { label: 'Inactive', value: 'Inactive' },- { label: 'Completed', value: 'Completed' },- ],- },- }),-- orderStatusDropdown: Property.StaticDropdown({- displayName: 'Status',- description: 'Order status.',- required: false,- defaultValue: 'Processing',- options: {- options: [- { label: 'Processing', value: 'Processing' },- { label: 'Shipped', value: 'Shipped' },- { label: 'Delivered', value: 'Delivered' },- { label: 'Cancelled', value: 'Cancelled' },- ],- },- }),-- paymentStatusDropdown: Property.StaticDropdown({- displayName: 'Payment Status',- description: 'Payment status.',- required: false,- defaultValue: 'Pending',- options: {- options: [- { label: 'Pending', value: 'Pending' },- { label: 'Paid', value: 'Paid' },- { label: 'Refunded', value: 'Refunded' },- { label: 'Failed', value: 'Failed' },- ],- },- }),-- pipelineDropdownRequired: Property.Dropdown({- auth: ninjapipeAuth,- displayName: 'Pipeline',- description: 'Select a pipeline.',- refreshers: [],- required: true,- options: async ({ auth }) => {- if (!auth) return { disabled: true, options: [], placeholder: 'Please connect your account first' };- try {- const a = getAuth({ auth });- const response = await ninjapipeApiCall<Record<string, unknown>>({- auth: a,- method: HttpMethod.GET,- path: '/pipelines',- queryParams: { limit: '100' },- });- const items = extractItems(response.body) as DropdownItem[];- return { disabled: false, options: items.map(buildDropdownOption) };- } catch {- return { disabled: true, options: [], placeholder: 'Failed to load pipelines.' };- }- },- }),-- contactDropdownRequired: Property.Dropdown({- auth: ninjapipeAuth,- displayName: 'Contact',- description: 'Select a contact.',- refreshers: [],- required: true,- options: async ({ auth }) => {- if (!auth) return { disabled: true, options: [], placeholder: 'Please connect your account first' };- try {- const a = getAuth({ auth });- const response = await ninjapipeApiCall<Record<string, unknown>>({- auth: a,- method: HttpMethod.GET,- path: '/contacts',- queryParams: { limit: '100' },- });- const items = extractItems(response.body) as DropdownItem[];- return {- disabled: false,- options: items.map((c) => ({- label:- `${c.first_name ?? ''} ${c.last_name ?? ''} <${c.email ?? 'no-email'}>`.trim() ||- c.email ||- String(c.id ?? ''),- value: String(c.id ?? ''),- })),- };- } catch {- return { disabled: true, options: [], placeholder: 'Failed to load contacts.' };- }- },- }),-- companyDropdownRequired: Property.Dropdown({- auth: ninjapipeAuth,- displayName: 'Company',- description: 'Select a company.',- refreshers: [],- required: true,- options: async ({ auth }) => {- if (!auth) return { disabled: true, options: [], placeholder: 'Please connect your account first' };- try {- const a = getAuth({ auth });- const response = await ninjapipeApiCall<Record<string, unknown>>({- auth: a,- method: HttpMethod.GET,- path: '/companies',- queryParams: { limit: '100' },- });- const items = extractItems(response.body) as DropdownItem[];- return { disabled: false, options: items.map(buildDropdownOption) };- } catch {- return { disabled: true, options: [], placeholder: 'Failed to load companies.' };- }- },- }),-- dealDropdownRequired: Property.Dropdown({- auth: ninjapipeAuth,- displayName: 'Deal',- description: 'Select a deal.',- refreshers: [],- required: true,- options: async ({ auth }) => {- if (!auth) return { disabled: true, options: [], placeholder: 'Please connect your account first' };- try {- const a = getAuth({ auth });- const response = await ninjapipeApiCall<Record<string, unknown>>({- auth: a,- method: HttpMethod.GET,- path: '/deals',- queryParams: { limit: '100' },- });- const items = extractItems(response.body) as DropdownItem[];- return { disabled: false, options: items.map(buildDropdownOption) };- } catch {- return { disabled: true, options: [], placeholder: 'Failed to load deals.' };- }- },- }),-- productDropdownRequired: Property.Dropdown({- auth: ninjapipeAuth,- displayName: 'Product',- description: 'Select a product.',- refreshers: [],- required: true,- options: async ({ auth }) => {- if (!auth) return { disabled: true, options: [], placeholder: 'Please connect your account first' };- try {- const a = getAuth({ auth });- const response = await ninjapipeApiCall<Record<string, unknown>>({- auth: a,- method: HttpMethod.GET,- path: '/products',- queryParams: { limit: '100' },- });- const items = extractItems(response.body) as DropdownItem[];- return { disabled: false, options: items.map(buildDropdownOption) };- } catch {- return { disabled: true, options: [], placeholder: 'Failed to load products.' };- }- },- }),-- budgetDropdownRequired: Property.Dropdown({- auth: ninjapipeAuth,- displayName: 'Budget',- description: 'Select a budget.',- refreshers: [],- required: true,- options: async ({ auth }) => {- if (!auth) return { disabled: true, options: [], placeholder: 'Please connect your account first' };- try {- const a = getAuth({ auth });- const response = await ninjapipeApiCall<Record<string, unknown>>({- auth: a,- method: HttpMethod.GET,- path: '/budgets',- queryParams: { limit: '100' },- });- const items = extractItems(response.body) as DropdownItem[];- return { disabled: false, options: items.map(buildDropdownOption) };- } catch {- return { disabled: true, options: [], placeholder: 'Failed to load budgets.' };- }- },- }),-- orderDropdownRequired: Property.Dropdown({- auth: ninjapipeAuth,- displayName: 'Order',- description: 'Select an order.',- refreshers: [],- required: true,- options: async ({ auth }) => {- if (!auth) return { disabled: true, options: [], placeholder: 'Please connect your account first' };- try {- const a = getAuth({ auth });- const response = await ninjapipeApiCall<Record<string, unknown>>({- auth: a,- method: HttpMethod.GET,- path: '/orders',- queryParams: { limit: '100' },- });- const items = extractItems(response.body) as Array<{ id?: string | number; order_number?: string; customer_name?: string }>;- return {- disabled: false,- options: items.map((o) => ({- label: `${o.order_number ?? ''} — ${o.customer_name ?? ''}`.trim().replace(/^—\s*/, '') || String(o.id ?? ''),- value: String(o.id ?? ''),- })),- };- } catch {- return { disabled: true, options: [], placeholder: 'Failed to load orders.' };- }- },- }),-- limitProperty: Property.Number({- displayName: 'Limit',- description: 'Maximum number of records to return (1-100).',- required: false,- defaultValue: 20,- }),-- statusFilterProperty: Property.ShortText({- displayName: 'Status Filter',- description: 'Filter records by status.',- required: false,- }),-- searchProperty: Property.ShortText({- displayName: 'Search',- description: 'Search query string.',- required: false,- }),-- ownerFilterProperty: Property.ShortText({- displayName: 'Owner Filter',- description: 'Filter by owner identifier.',- required: false,- }),-};diff --git a/packages/pieces/community/ninjapipe/src/lib/common/pipeline-item-props.ts b/packages/pieces/community/ninjapipe/src/lib/common/pipeline-item-props.tsnew file mode 100644index 00000000000..834ab2a2307--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/common/pipeline-item-props.ts@@ -0,0 +1,60 @@+import { Property } from '@activepieces/pieces-framework';+import { NinjaPipeRecord } from './client';+import { ninjapipeFields } from './fields';+import { ninjapipeProps } from './props';++function itemProps() {+ return {+ description: Property.LongText({ displayName: 'Description', required: false }),+ value: Property.Number({ displayName: 'Value', required: false }),+ priority: ninjapipeProps.staticDropdown({ displayName: 'Priority', description: 'Item priority.', values: ITEM_PRIORITIES }),+ assignedTo: ninjapipeProps.member({ displayName: 'Assigned To', description: 'Workspace member responsible for the item.' }),+ dueDate: Property.DateTime({ displayName: 'Due Date', description: 'Date (YYYY-MM-DD).', required: false }),+ email: Property.ShortText({ displayName: 'Email', required: false }),+ phone: Property.ShortText({ displayName: 'Phone', required: false }),+ company: Property.ShortText({ displayName: 'Company', description: 'Company name shown on the card.', required: false }),+ tags: Property.Array({ displayName: 'Tags', required: false }),+ };+}++function itemBody(p: ItemInput): NinjaPipeRecord {+ return ninjapipeFields.compact({+ title: p.title,+ stage_id: p.stageId,+ description: p.description,+ value: ninjapipeFields.toNumber({ value: p.value, field: 'Value' }),+ priority: p.priority,+ assigned_to: p.assignedTo,+ due_date: ninjapipeFields.toDateOnly({ value: p.dueDate, field: 'Due Date' }),+ email: p.email,+ phone: p.phone,+ company: p.company,+ tags: ninjapipeFields.toStringList(p.tags),+ });+}++const ITEM_PRIORITIES = ['low', 'medium', 'high'];+const ITEM_CLEARABLE: Record<string, string> = {+ description: 'Description',+ assigned_to: 'Assigned To',+ due_date: 'Due Date',+ email: 'Email',+ phone: 'Phone',+ company: 'Company',+};++export const ninjapipeItems = { itemProps, itemBody, ITEM_PRIORITIES, ITEM_CLEARABLE };++export type ItemInput = {+ title?: unknown;+ stageId?: unknown;+ description?: unknown;+ value?: unknown;+ priority?: unknown;+ assignedTo?: unknown;+ dueDate?: unknown;+ email?: unknown;+ phone?: unknown;+ company?: unknown;+ tags?: unknown;+};diff --git a/packages/pieces/community/ninjapipe/src/lib/common/pipelines.ts b/packages/pieces/community/ninjapipe/src/lib/common/pipelines.tsnew file mode 100644index 00000000000..5739941767c--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/common/pipelines.ts@@ -0,0 +1,27 @@+import { NinjaPipeRecord } from './client';++function toStages(value: unknown): NinjaPipeRecord[] {+ const list = Array.isArray(value) ? value : [];+ const stages = list.map((stage, index) => {+ const record = typeof stage === 'object' && stage !== null ? Object.fromEntries(Object.entries(stage)) : {};+ const name = typeof record['name'] === 'string' ? record['name'].trim() : '';+ if (name === '') throw new Error(`Stage ${index + 1} needs a name.`);+ const id = typeof record['id'] === 'string' && record['id'].trim() !== '' ? record['id'].trim() : slug({ name, index });+ const color = typeof record['color'] === 'string' && record['color'].trim() !== '' ? record['color'].trim() : DEFAULT_COLORS[index % DEFAULT_COLORS.length];+ if (!/^#[0-9a-fA-F]{6}$/.test(color)) throw new Error(`Stage "${name}" color must be a hex value like #3b82f6.`);+ return { id, name, color };+ });+ if (stages.length === 0) throw new Error('Add at least one stage.');+ const ids = stages.map((stage) => stage.id);+ if (new Set(ids).size !== ids.length) throw new Error('Stage IDs must be unique.');+ return stages;+}++function slug({ name, index }: { name: string; index: number }): string {+ const base = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');+ return base === '' ? `stage-${index + 1}` : base;+}++const DEFAULT_COLORS = ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#059669'];++export const ninjapipePipelines = { toStages };diff --git a/packages/pieces/community/ninjapipe/src/lib/common/props.ts b/packages/pieces/community/ninjapipe/src/lib/common/props.tsnew file mode 100644index 00000000000..2ddba3d45d8--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/common/props.ts@@ -0,0 +1,313 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property } from '@activepieces/pieces-framework';+import { ninjapipeAuth } from '../auth';+import { NinjaPipeAuth, NinjaPipeRecord, ninjapipeClient } from './client';++function contactLabel(item: NinjaPipeRecord): string {+ const name = [item['first_name'], item['last_name']].filter((part) => typeof part === 'string' && part.trim() !== '').join(' ');+ const email = typeof item['email'] === 'string' && item['email'] !== '' ? `<${item['email']}>` : '';+ return [name, email].filter((part) => part !== '').join(' ') || String(item['id'] ?? '');+}++function nameLabel(item: NinjaPipeRecord): string {+ const name = item['name'] ?? item['title'] ?? item['order_number'];+ return typeof name === 'string' && name.trim() !== '' ? name : String(item['id'] ?? '');+}++function orderLabel(item: NinjaPipeRecord): string {+ const parts = [item['order_number'], item['customer_name']].filter((part) => typeof part === 'string' && part.trim() !== '');+ return parts.length > 0 ? parts.join(' — ') : String(item['id'] ?? '');+}++function errorText(error: unknown): string {+ return error instanceof Error ? error.message : String(error);+}++async function collectOptions({+ auth,+ path,+ label,+ search,+ paged,+}: {+ auth: NinjaPipeAuth;+ path: string;+ label: (item: NinjaPipeRecord) => string;+ search?: string;+ paged: boolean;+}): Promise<{ label: string; value: string }[]> {+ const query = search && search.trim() !== '' ? { search: search.trim() } : undefined;+ const items: NinjaPipeRecord[] = [];+ if (!paged) {+ const body = await ninjapipeClient.ninjapipeRequest({ auth, method: HttpMethod.GET, path, query, operation: 'load options' });+ items.push(...ninjapipeClient.readItems(body));+ } else {+ for (let page = 1; page <= DROPDOWN_MAX_PAGES; page++) {+ const result = await ninjapipeClient.listPage({ auth, path, query, page, limit: 100, operation: 'load options' });+ items.push(...result.items);+ if (!result.hasMore || result.items.length === 0) break;+ }+ }+ return items+ .filter((item) => item['id'] !== undefined && item['id'] !== null)+ .map((item) => ({ label: label(item), value: String(item['id']) }));+}++async function loadOptions({+ auth,+ path,+ noun,+ label,+ search,+ paged = true,+}: {+ auth: unknown;+ path: string;+ noun: string;+ label: (item: NinjaPipeRecord) => string;+ search?: string;+ paged?: boolean;+}) {+ if (!auth) return { disabled: true, options: [], placeholder: 'Connect your NinjaPipe account first.' };+ try {+ const options = await collectOptions({ auth: ninjapipeClient.readAuth(auth), path, label, search, paged });+ return {+ disabled: false,+ options,+ placeholder: options.length === 0 ? `No ${noun} found in this workspace.` : undefined,+ };+ } catch (error) {+ return { disabled: true, options: [], placeholder: `Could not load ${noun}: ${errorText(error)}` };+ }+}++function recordDropdown<R extends boolean>({+ displayName,+ description,+ required,+ path,+ noun,+ label = nameLabel,+ searchable = false,+}: {+ displayName: string;+ description: string;+ required: R;+ path: string;+ noun: string;+ label?: (item: NinjaPipeRecord) => string;+ searchable?: boolean;+}) {+ return Property.Dropdown({+ auth: ninjapipeAuth,+ displayName,+ description,+ required,+ refreshers: [],+ refreshOnSearch: searchable,+ options: async ({ auth }, ctx) => loadOptions({ auth, path, noun, label, search: searchable ? ctx.searchValue : undefined }),+ });+}++async function loadMembers({ auth }: { auth: unknown }) {+ if (!auth) return { disabled: true, options: [], placeholder: 'Connect your NinjaPipe account first.' };+ try {+ const body = await ninjapipeClient.ninjapipeRequest({+ auth: ninjapipeClient.readAuth(auth),+ method: HttpMethod.GET,+ path: '/workspace/members',+ operation: 'load workspace members',+ });+ const options = ninjapipeClient+ .readItems(body)+ .filter((member) => typeof member['account_id'] === 'string')+ .map((member) => {+ const name = typeof member['full_name'] === 'string' && member['full_name'] !== '' ? member['full_name'] : String(member['email'] ?? '');+ const email = typeof member['email'] === 'string' ? ` <${member['email']}>` : '';+ return { label: `${name}${email}`, value: String(member['account_id']) };+ });+ return { disabled: false, options };+ } catch (error) {+ return { disabled: true, options: [], placeholder: `Could not load workspace members: ${errorText(error)}` };+ }+}++function ownerDropdown<R extends boolean>({ displayName, description, required }: { displayName: string; description: string; required: R }) {+ return Property.Dropdown({+ auth: ninjapipeAuth,+ displayName,+ description,+ required,+ refreshers: [],+ options: async ({ auth }) => loadMembers({ auth }),+ });+}++function taskDropdown() {+ return Property.Dropdown({+ auth: ninjapipeAuth,+ displayName: 'Task',+ description: 'Select a task. Pick the project first.',+ required: true,+ refreshers: ['projectId'],+ options: async ({ auth, projectId }) => {+ if (!projectId) return { disabled: true, options: [], placeholder: 'Select a project first.' };+ return loadOptions({+ auth,+ path: `/projects/${encodeURIComponent(String(projectId))}/tasks`,+ noun: 'tasks',+ paged: false,+ label: nameLabel,+ });+ },+ });+}++function stageDropdown<R extends boolean>({ required, description }: { required: R; description: string }) {+ return Property.Dropdown({+ auth: ninjapipeAuth,+ displayName: 'Stage',+ description,+ required,+ refreshers: ['pipelineId'],+ options: async ({ auth, pipelineId }) => {+ if (!auth) return { disabled: true, options: [], placeholder: 'Connect your NinjaPipe account first.' };+ if (!pipelineId) return { disabled: true, options: [], placeholder: 'Select a pipeline first.' };+ try {+ const pipeline = await ninjapipeClient.getRecord({+ auth: ninjapipeClient.readAuth(auth),+ path: `/pipelines/${encodeURIComponent(String(pipelineId))}`,+ operation: 'load stages',+ });+ const stages = Array.isArray(pipeline['stages']) ? pipeline['stages'] : [];+ const options = stages+ .filter(ninjapipeClient.isRecord)+ .filter((stage) => stage['id'] !== undefined)+ .map((stage) => ({ label: String(stage['name'] ?? stage['id']), value: String(stage['id']) }));+ return { disabled: false, options };+ } catch (error) {+ return { disabled: true, options: [], placeholder: `Could not load stages: ${errorText(error)}` };+ }+ },+ });+}++function pipelineItemDropdown() {+ return Property.Dropdown({+ auth: ninjapipeAuth,+ displayName: 'Pipeline Item',+ description: 'Select the item (card) to update. Pick the pipeline first.',+ required: true,+ refreshers: ['pipelineId'],+ options: async ({ auth, pipelineId }) => {+ if (!pipelineId) return { disabled: true, options: [], placeholder: 'Select a pipeline first.' };+ return loadOptions({+ auth,+ path: `/pipelines/${encodeURIComponent(String(pipelineId))}/items`,+ noun: 'pipeline items',+ paged: false,+ label: nameLabel,+ });+ },+ });+}++function staticDropdown({+ displayName,+ description,+ values,+}: {+ displayName: string;+ description: string;+ values: string[];+}) {+ return Property.StaticDropdown({+ displayName,+ description,+ required: false,+ options: { options: values.map((value) => ({ label: value, value })) },+ });+}++function clearFields({ fields }: { fields: Record<string, string> }) {+ return Property.StaticMultiSelectDropdown({+ displayName: 'Clear Fields',+ description: 'Fields to empty on the record. A field you clear here must be left blank above.',+ required: false,+ options: { options: Object.entries(fields).map(([value, label]) => ({ label, value })) },+ });+}++function customFields({ update }: { update: boolean }) {+ return Property.Object({+ displayName: 'Custom Fields',+ description: update+ ? 'Custom field values by field key. Keys you leave out keep their current value; set a key to an empty value to clear it.'+ : 'Custom field values by field key (the key shown in NinjaPipe settings).',+ required: false,+ });+}++function limit() {+ return Property.Number({+ displayName: 'Limit',+ description: 'Records per page (1-100). Ignored when Return All is on.',+ required: false,+ defaultValue: 20,+ });+}++function page() {+ return Property.Number({+ displayName: 'Page',+ description: 'Page number to fetch (starts at 1). Ignored when Return All is on.',+ required: false,+ defaultValue: 1,+ });+}++function returnAll() {+ return Property.Checkbox({+ displayName: 'Return All',+ description: `Follow every page (up to ${RETURN_ALL_LABEL} records). Has More is true when the cap cut the list short.`,+ required: false,+ defaultValue: false,+ });+}++function search() {+ return Property.ShortText({ displayName: 'Search', description: 'Text to search for.', required: false });+}++const DROPDOWN_MAX_PAGES = 10;+const RETURN_ALL_LABEL = '5,000';++export const ninjapipeProps = {+ contactRequired: () =>+ recordDropdown({ displayName: 'Contact', description: 'Select a contact, or type to search.', required: true, path: '/contacts', noun: 'contacts', label: contactLabel, searchable: true }),+ contactOptional: () =>+ recordDropdown({ displayName: 'Contact', description: 'Select a contact, or type to search.', required: false, path: '/contacts', noun: 'contacts', label: contactLabel, searchable: true }),+ companyRequired: () =>+ recordDropdown({ displayName: 'Company', description: 'Select a company, or type to search.', required: true, path: '/companies', noun: 'companies', searchable: true }),+ companyOptional: () =>+ recordDropdown({ displayName: 'Company', description: 'Select a company, or type to search.', required: false, path: '/companies', noun: 'companies', searchable: true }),+ dealRequired: () =>+ recordDropdown({ displayName: 'Deal', description: 'Select a deal, or type to search.', required: true, path: '/deals', noun: 'deals', searchable: true }),+ productRequired: () => recordDropdown({ displayName: 'Product', description: 'Select a product.', required: true, path: '/products', noun: 'products' }),+ budgetRequired: () => recordDropdown({ displayName: 'Budget', description: 'Select a budget.', required: true, path: '/budgets', noun: 'budgets' }),+ orderRequired: () => recordDropdown({ displayName: 'Order', description: 'Select an order.', required: true, path: '/orders', noun: 'orders', label: orderLabel }),+ projectRequired: () => recordDropdown({ displayName: 'Project', description: 'Select a project.', required: true, path: '/projects', noun: 'projects' }),+ pipelineRequired: () => recordDropdown({ displayName: 'Pipeline', description: 'Select a pipeline.', required: true, path: '/pipelines', noun: 'pipelines' }),+ task: taskDropdown,+ stageRequired: () => stageDropdown({ required: true, description: 'Stage (column) of the selected pipeline.' }),+ stageOptional: () => stageDropdown({ required: false, description: 'Move the item to this stage. Leave empty to keep its stage.' }),+ pipelineItem: pipelineItemDropdown,+ member: ({ displayName, description }: { displayName: string; description: string }) => ownerDropdown({ displayName, description, required: false }),+ staticDropdown,+ clearFields,+ customFields,+ limit,+ page,+ returnAll,+ search,+};diff --git a/packages/pieces/community/ninjapipe/src/lib/common/records.ts b/packages/pieces/community/ninjapipe/src/lib/common/records.tsnew file mode 100644index 00000000000..b3807103534--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/common/records.ts@@ -0,0 +1,77 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { NinjaPipeAuth, NinjaPipeRecord, ninjapipeClient } from './client';++async function findContactByEmail({ auth, email }: { auth: NinjaPipeAuth; email: string }): Promise<NinjaPipeRecord | undefined> {+ const wanted = email.trim().toLowerCase();+ for (let page = 1; page <= EMAIL_LOOKUP_MAX_PAGES; page++) {+ const result = await ninjapipeClient.listPage({+ auth,+ path: '/contacts',+ query: { search: email.trim() },+ page,+ limit: 100,+ operation: 'contact lookup by email',+ });+ const match = result.items.find((item) => typeof item['email'] === 'string' && item['email'].trim().toLowerCase() === wanted);+ if (match) return match;+ if (!result.hasMore) return undefined;+ }+ return undefined;+}++async function findCompanyByField({+ auth,+ field,+ value,+}: {+ auth: NinjaPipeAuth;+ field: string;+ value: string;+}): Promise<NinjaPipeRecord | undefined> {+ const wanted = value.trim().toLowerCase();+ for (let page = 1; page <= EMAIL_LOOKUP_MAX_PAGES; page++) {+ const result = await ninjapipeClient.listPage({+ auth,+ path: '/companies',+ query: { search: value.trim() },+ page,+ limit: 100,+ operation: 'company lookup',+ });+ const match = result.items.find((item) => typeof item[field] === 'string' && item[field].trim().toLowerCase() === wanted);+ if (match) return match;+ if (!result.hasMore) return undefined;+ }+ return undefined;+}++async function listWorkspaceMembers({ auth }: { auth: NinjaPipeAuth }): Promise<{ items: NinjaPipeRecord[]; count: number }> {+ const body = await ninjapipeClient.ninjapipeRequest({+ auth,+ method: HttpMethod.GET,+ path: '/workspace/members',+ operation: 'list workspace members',+ });+ const items = ninjapipeClient.readItems(body);+ return { items, count: items.length };+}++async function listUnpaged({+ auth,+ path,+ query,+ operation,+}: {+ auth: NinjaPipeAuth;+ path: string;+ query?: Record<string, unknown>;+ operation: string;+}): Promise<{ items: NinjaPipeRecord[]; count: number }> {+ const body = await ninjapipeClient.ninjapipeRequest({ auth, method: HttpMethod.GET, path, query, operation });+ const items = ninjapipeClient.readItems(body);+ return { items, count: items.length };+}++const EMAIL_LOOKUP_MAX_PAGES = 10;++export const ninjapipeRecords = { findContactByEmail, findCompanyByField, listWorkspaceMembers, listUnpaged };diff --git a/packages/pieces/community/ninjapipe/src/lib/common/task-props.ts b/packages/pieces/community/ninjapipe/src/lib/common/task-props.tsnew file mode 100644index 00000000000..9f0cd08eeab--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/common/task-props.ts@@ -0,0 +1,65 @@+import { Property } from '@activepieces/pieces-framework';+import { NinjaPipeRecord } from './client';+import { ninjapipeFields } from './fields';+import { ninjapipeProps } from './props';++function taskProps({ titleRequired }: { titleRequired: boolean }) {+ return {+ title: titleRequired+ ? Property.ShortText({ displayName: 'Title', required: true })+ : Property.ShortText({ displayName: 'Title', required: false }),+ description: Property.LongText({ displayName: 'Description', required: false }),+ status: ninjapipeProps.staticDropdown({ displayName: 'Status', description: 'Task status.', values: TASK_STATUSES }),+ priority: ninjapipeProps.staticDropdown({ displayName: 'Priority', description: 'Task priority.', values: TASK_PRIORITIES }),+ assigneeId: ninjapipeProps.member({ displayName: 'Assignee', description: 'Workspace member the task is assigned to.' }),+ dueDate: Property.DateTime({ displayName: 'Due Date', description: 'Date (YYYY-MM-DD).', required: false }),+ parentId: Property.ShortText({ displayName: 'Parent Task ID', description: 'Make this a subtask of another task in the same project.', required: false }),+ estimatedHours: Property.Number({ displayName: 'Estimated Hours', required: false }),+ tags: Property.Array({ displayName: 'Tags', required: false }),+ };+}++function parentFilter({ parentId, rootOnly }: { parentId: string | undefined; rootOnly: boolean | undefined }): string | undefined {+ const id = parentId?.trim();+ if (id) return id;+ if (rootOnly === true) return '';+ return undefined;+}++function taskBody(p: TaskInput): NinjaPipeRecord {+ return ninjapipeFields.compact({+ title: p.title,+ description: p.description,+ status: p.status,+ priority: p.priority,+ assignee_id: p.assigneeId,+ due_date: ninjapipeFields.toDateOnly({ value: p.dueDate, field: 'Due Date' }),+ parent_id: p.parentId,+ estimated_hours: ninjapipeFields.toNumber({ value: p.estimatedHours, field: 'Estimated Hours' }),+ tags: ninjapipeFields.toStringList(p.tags),+ });+}++const TASK_STATUSES = ['To Do', 'In Progress', 'Done', 'Cancelled'];+const TASK_PRIORITIES = ['High', 'Medium', 'Low'];+const TASK_CLEARABLE: Record<string, string> = {+ description: 'Description',+ assignee_id: 'Assignee',+ due_date: 'Due Date',+ parent_id: 'Parent Task',+ estimated_hours: 'Estimated Hours',+};++export const ninjapipeTasks = { taskProps, taskBody, parentFilter, TASK_STATUSES, TASK_PRIORITIES, TASK_CLEARABLE };++export type TaskInput = {+ title?: unknown;+ description?: unknown;+ status?: unknown;+ priority?: unknown;+ assigneeId?: unknown;+ dueDate?: unknown;+ parentId?: unknown;+ estimatedHours?: unknown;+ tags?: unknown;+};diff --git a/packages/pieces/community/ninjapipe/src/lib/output-schemas.ts b/packages/pieces/community/ninjapipe/src/lib/output-schemas.tsnew file mode 100644index 00000000000..97b236b3ace--- /dev/null+++ b/packages/pieces/community/ninjapipe/src/lib/output-schemas.ts@@ -0,0 +1,284 @@+import { OutputSchema, OutputSchemaField } from '@activepieces/pieces-framework';++const timestamps: OutputSchemaField[] = [+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },+];++const customFields: OutputSchemaField = { key: 'fields', label: 'Custom Fields', dynamicKey: true };++const contactFields: OutputSchemaField[] = [+ { key: 'id', label: 'Contact ID' },+ { key: 'first_name', label: 'First Name' },+ { key: 'last_name', label: 'Last Name' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'phone', label: 'Phone' },+ { key: 'status', label: 'Status' },+ { key: 'owner_id', label: 'Owner ID' },+ { key: 'assigned_to', label: 'Assigned To (Member ID)' },+ { key: 'company_id', label: 'Company ID' },+ { key: 'slug', label: 'Slug' },+ customFields,+ ...timestamps,+];++const companyFields: OutputSchemaField[] = [+ { key: 'id', label: 'Company ID' },+ { key: 'name', label: 'Name' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'phone', label: 'Phone' },+ { key: 'website', label: 'Website' },+ { key: 'industry', label: 'Industry' },+ { key: 'status', label: 'Status' },+ { key: 'owner_id', label: 'Owner ID' },+ { key: 'is_archived', label: 'Archived', format: 'boolean' },+ { key: 'slug', label: 'Slug' },+ customFields,+ ...timestamps,+];++const dealFields: OutputSchemaField[] = [+ { key: 'id', label: 'Deal ID' },+ { key: 'name', label: 'Name' },+ { key: 'value', label: 'Value', format: 'number' },+ { key: 'status', label: 'Status' },+ { key: 'owner_id', label: 'Owner ID' },+ { key: 'contact_id', label: 'Contact ID' },+ { key: 'company_id', label: 'Company ID' },+ customFields,+ ...timestamps,+];++const productFields: OutputSchemaField[] = [+ { key: 'id', label: 'Product ID' },+ { key: 'name', label: 'Name' },+ { key: 'description', label: 'Description' },+ { key: 'sku', label: 'SKU' },+ { key: 'price', label: 'Price', format: 'number' },+ { key: 'cost', label: 'Cost', format: 'number' },+ { key: 'currency', label: 'Currency' },+ { key: 'status', label: 'Status' },+ { key: 'category', label: 'Category' },+ { key: 'product_type', label: 'Product Type' },+ { key: 'image_url', label: 'Image URL', format: 'url' },+ ...timestamps,+];++const budgetFields: OutputSchemaField[] = [+ { key: 'id', label: 'Budget ID' },+ { key: 'name', label: 'Name' },+ { key: 'description', label: 'Description' },+ { key: 'category', label: 'Category' },+ { key: 'period', label: 'Period' },+ { key: 'allocated_amount', label: 'Allocated Amount', format: 'number' },+ { key: 'spent_amount', label: 'Spent Amount', format: 'number' },+ { key: 'remaining_amount', label: 'Remaining Amount', format: 'number' },+ { key: 'currency', label: 'Currency' },+ { key: 'status', label: 'Status' },+ { key: 'start_date', label: 'Start Date', format: 'date' },+ { key: 'end_date', label: 'End Date', format: 'date' },+ ...timestamps,+];++const budgetExpenseFields: OutputSchemaField[] = [+ { key: 'id', label: 'Expense ID' },+ { key: 'budget_id', label: 'Budget ID' },+ { key: 'description', label: 'Description' },+ { key: 'amount', label: 'Amount', format: 'number' },+ { key: 'category', label: 'Category' },+ { key: 'date', label: 'Date', format: 'date' },+ ...timestamps,+];++const projectFields: OutputSchemaField[] = [+ { key: 'id', label: 'Project ID' },+ { key: 'name', label: 'Name' },+ { key: 'description', label: 'Description' },+ { key: 'status', label: 'Status' },+ { key: 'priority', label: 'Priority' },+ { key: 'progress', label: 'Progress', format: 'number' },+ { key: 'total_tasks', label: 'Total Tasks', format: 'number' },+ { key: 'completed_tasks', label: 'Completed Tasks', format: 'number' },+ { key: 'due_date', label: 'Due Date', format: 'date' },+ { key: 'team', label: 'Team' },+ { key: 'tags', label: 'Tags' },+ ...timestamps,+];++const taskFields: OutputSchemaField[] = [+ { key: 'id', label: 'Task ID' },+ { key: 'project_id', label: 'Project ID' },+ { key: 'title', label: 'Title' },+ { key: 'description', label: 'Description' },+ { key: 'status', label: 'Status' },+ { key: 'priority', label: 'Priority' },+ { key: 'assignee_id', label: 'Assignee ID' },+ { key: 'due_date', label: 'Due Date', format: 'date' },+ { key: 'parent_id', label: 'Parent Task ID' },+ { key: 'estimated_hours', label: 'Estimated Hours', format: 'number' },+ { key: 'level', label: 'Level', format: 'number' },+ { key: 'has_children', label: 'Has Subtasks', format: 'boolean' },+ { key: 'tags', label: 'Tags' },+ ...timestamps,+];++const stageFields: OutputSchemaField[] = [+ { key: 'id', label: 'Stage ID' },+ { key: 'name', label: 'Name' },+ { key: 'color', label: 'Color' },+];++const pipelineFields: OutputSchemaField[] = [+ { key: 'id', label: 'Pipeline ID' },+ { key: 'name', label: 'Name' },+ { key: 'description', label: 'Description' },+ { key: 'pipeline_type', label: 'Pipeline Type' },+ { key: 'stages', label: 'Stages', labelKey: 'name', listItems: stageFields },+ { key: 'slug', label: 'Slug' },+ { key: 'archived', label: 'Archived', format: 'boolean' },+ ...timestamps,+];++const pipelineItemFields: OutputSchemaField[] = [+ { key: 'id', label: 'Item ID' },+ { key: 'title', label: 'Title' },+ { key: 'subtitle', label: 'Subtitle' },+ { key: 'description', label: 'Description' },+ { key: 'stage_id', label: 'Stage ID' },+ { key: 'item_type', label: 'Item Type' },+ { key: 'priority', label: 'Priority' },+ { key: 'value', label: 'Value', format: 'number' },+ { key: 'assigned_to', label: 'Assigned To (Member ID)' },+ { key: 'due_date', label: 'Due Date', format: 'date' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'phone', label: 'Phone' },+ { key: 'company', label: 'Company' },+ { key: 'tags', label: 'Tags' },+ ...timestamps,+];++const orderFields: OutputSchemaField[] = [+ { key: 'id', label: 'Order ID' },+ { key: 'order_number', label: 'Order Number' },+ { key: 'customer_name', label: 'Customer Name' },+ { key: 'customer_email', label: 'Customer Email', format: 'email' },+ { key: 'customer_company', label: 'Customer Company' },+ { key: 'contact_id', label: 'Contact ID' },+ { key: 'total_amount', label: 'Total Amount', format: 'number' },+ { key: 'status', label: 'Status' },+ { key: 'payment_status', label: 'Payment Status' },+ { key: 'order_date', label: 'Order Date', format: 'date' },+ { key: 'delivery_date', label: 'Delivery Date', format: 'date' },+ { key: 'priority', label: 'Priority' },+ { key: 'tracking_number', label: 'Tracking Number' },+ { key: 'notes', label: 'Notes' },+ ...timestamps,+];++const activityFields: OutputSchemaField[] = [+ { key: 'id', label: 'Activity ID' },+ { key: 'contact_id', label: 'Contact ID' },+ { key: 'type', label: 'Type' },+ { key: 'title', label: 'Title' },+ { key: 'date', label: 'Date', format: 'datetime' },+ { key: 'data', label: 'Details', dynamicKey: true },+ ...timestamps,+];++const memberFields: OutputSchemaField[] = [+ { key: 'account_id', label: 'Member ID' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'full_name', label: 'Full Name' },+ { key: 'first_name', label: 'First Name' },+ { key: 'last_name', label: 'Last Name' },+ { key: 'role', label: 'Role' },+ { key: 'joined_at', label: 'Joined At', format: 'datetime' },+];++function listSchema({ itemFields, labelKey }: { itemFields: OutputSchemaField[]; labelKey: string }): OutputSchema {+ return {+ fields: [+ { key: 'items', label: 'Items', labelKey, listItems: itemFields },+ { key: 'count', label: 'Returned', format: 'number' },+ { key: 'total', label: 'Total Matching', format: 'number' },+ { key: 'hasMore', label: 'Has More', format: 'boolean' },+ { key: 'nextPage', label: 'Next Page', format: 'number' },+ ],+ };+}++function recordSchema(fields: OutputSchemaField[]): OutputSchema {+ return { fields };+}++const deleteSchema: OutputSchema = {+ fields: [+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ { key: 'id', label: 'Deleted ID' },+ { key: 'name', label: 'Name' },+ { key: 'message', label: 'Message' },+ ],+};++export const ninjapipeSchemas = {+ contact: recordSchema(contactFields),+ contactList: listSchema({ itemFields: contactFields, labelKey: 'email' }),+ contactWithAction: recordSchema([+ { key: 'action', label: 'Action (created, updated, existing or skipped)' },+ ...contactFields,+ ]),+ company: recordSchema(companyFields),+ companyList: listSchema({ itemFields: companyFields, labelKey: 'name' }),+ deal: recordSchema(dealFields),+ dealList: listSchema({ itemFields: dealFields, labelKey: 'name' }),+ product: recordSchema(productFields),+ productList: listSchema({ itemFields: productFields, labelKey: 'name' }),+ budget: recordSchema(budgetFields),+ budgetList: listSchema({ itemFields: budgetFields, labelKey: 'name' }),+ budgetExpense: recordSchema(budgetExpenseFields),+ project: recordSchema(projectFields),+ projectList: listSchema({ itemFields: projectFields, labelKey: 'name' }),+ task: recordSchema(taskFields),+ taskList: recordSchema([+ { key: 'items', label: 'Tasks', labelKey: 'title', listItems: taskFields },+ { key: 'count', label: 'Returned', format: 'number' },+ ]),+ pipeline: recordSchema(pipelineFields),+ pipelineList: listSchema({ itemFields: pipelineFields, labelKey: 'name' }),+ pipelineItem: recordSchema(pipelineItemFields),+ pipelineItemList: recordSchema([+ { key: 'items', label: 'Items', labelKey: 'title', listItems: pipelineItemFields },+ { key: 'count', label: 'Returned', format: 'number' },+ ]),+ order: recordSchema(orderFields),+ orderList: listSchema({ itemFields: orderFields, labelKey: 'order_number' }),+ activity: recordSchema(activityFields),+ activityList: listSchema({ itemFields: activityFields, labelKey: 'title' }),+ memberList: recordSchema([+ { key: 'items', label: 'Members', labelKey: 'email', listItems: memberFields },+ { key: 'count', label: 'Returned', format: 'number' },+ ]),+ listMember: recordSchema([+ { key: 'list_id', label: 'List ID' },+ { key: 'list_member_id', label: 'List Member ID' },+ { key: 'member_type', label: 'Member Type' },+ { key: 'member_id', label: 'Member ID' },+ { key: 'added_at', label: 'Added At', format: 'datetime' },+ { key: 'already_in_list', label: 'Already In List', format: 'boolean' },+ ]),+ clientPortal: recordSchema([+ { key: 'enabled', label: 'Portal Enabled', format: 'boolean' },+ { key: 'is_enabled', label: 'Enabled In NinjaPipe', format: 'boolean' },+ { key: 'id', label: 'Portal Account ID' },+ { key: 'contact_id', label: 'Contact ID' },+ { key: 'email', label: 'Portal Email', format: 'email' },+ { key: 'generated_password', label: 'Generated Password' },+ { key: 'message', label: 'Message' },+ ...timestamps,+ ]),+ databin: recordSchema([+ { key: 'status', label: 'HTTP Status', format: 'number' },+ { key: 'response', label: 'Response' },+ ]),+ deleted: deleteSchema,+};diff --git a/packages/pieces/community/ninjapipe/src/lib/triggers/common.ts b/packages/pieces/community/ninjapipe/src/lib/triggers/common.tsindex 0827f827218..9a1ea2f1577 100644--- a/packages/pieces/community/ninjapipe/src/lib/triggers/common.ts+++ b/packages/pieces/community/ninjapipe/src/lib/triggers/common.ts@@ -1,65 +1,123 @@-import { AppConnectionValueForAuthProperty } from '@activepieces/pieces-framework';+import { AppConnectionValueForAuthProperty, Store } from '@activepieces/pieces-framework';import { DedupeStrategy, HttpMethod, Polling } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeApiCall, extractItems, flattenCustomFields, getAuth } from '../common';+import { ninjapipeAuth } from '../auth';+import { NinjaPipeRecord, ninjapipeClient } from '../common/client';-export function buildPolling(- path: string,- timestampField: string,-): Polling<AppConnectionValueForAuthProperty<typeof ninjapipeAuth>, Record<string, never>> {+function readTimestamp({ record, field }: { record: NinjaPipeRecord; field: TimestampField }): number | undefined {+ const value = record[field];+ if (typeof value !== 'string' && typeof value !== 'number') return undefined;+ const ms = new Date(value).getTime();+ return Number.isFinite(ms) ? ms : undefined;+}++async function toPollItems({+ records,+ field,+ store,+ lastFetchEpochMS,+}: {+ records: NinjaPipeRecord[];+ field: TimestampField;+ store: Store;+ lastFetchEpochMS: number;+}): Promise<{ epochMilliSeconds: number; data: unknown }[]> {+ const timed = records.flatMap((record) => {+ const ms = readTimestamp({ record, field });+ return ms === undefined ? [] : [{ epochMilliSeconds: ms, data: record }];+ });+ const untimed = records.filter((record) => readTimestamp({ record, field }) === undefined && record['id'] !== undefined);+ if (untimed.length === 0) return timed;+ const emitAt = Math.max(lastFetchEpochMS + 1, 1);+ // Test mode (lastFetchEpochMS 0) only samples: never read or write the remembered IDs.+ if (lastFetchEpochMS === 0) {+ return [...timed, ...untimed.map((record) => ({ epochMilliSeconds: emitAt, data: record }))];+ }+ const seen = new Set((await store.get<string[]>(UNTIMED_STORE_KEY)) ?? []);+ const fetchedIds = untimed.map((record) => String(record['id']));+ const fresh = untimed.filter((record) => !seen.has(String(record['id'])));+ if (fresh.length === 0) return timed;+ // Remember every untimed ID instead of a sliding window, so records still returned by+ // the API are never forgotten and emitted again. Only when the list is full are IDs the+ // API no longer returns dropped; if the returned ones alone exceed the bound, stop with+ // an error instead of forgetting records.+ if (fetchedIds.length > UNTIMED_MAX_IDS) {+ throw new Error(`NinjaPipe returned more than ${UNTIMED_MAX_IDS} records without a timestamp, so new ones cannot be told apart from old ones safely.`);+ }+ const fetched = new Set(fetchedIds);+ const kept = [...seen].filter((id) => !fetched.has(id));+ const room = UNTIMED_MAX_IDS - fetchedIds.length;+ await store.put(UNTIMED_STORE_KEY, [...kept.slice(Math.max(kept.length - room, 0)), ...fetchedIds]);+ return [...timed, ...fresh.map((record) => ({ epochMilliSeconds: emitAt, data: record }))];+}++async function fetchSince({+ auth,+ path,+ field,+ lastFetchEpochMS,+}: {+ auth: AppConnectionValueForAuthProperty<typeof ninjapipeAuth>;+ path: string;+ field: TimestampField;+ lastFetchEpochMS: number;+}): Promise<NinjaPipeRecord[]> {+ const client = ninjapipeClient.readAuth(auth);+ const isTest = lastFetchEpochMS === 0;+ const records: NinjaPipeRecord[] = [];+ for (let page = 1; ; page++) {+ if (page > MAX_POLL_PAGES) {+ throw new Error(`NinjaPipe polling stopped after ${MAX_POLL_PAGES} pages without reaching the last checkpoint. The API may be ignoring the page or sort parameters.`);+ }+ const result = await ninjapipeClient.listPage({+ auth: client,+ path,+ query: { sort_by: field, sort_order: 'desc' },+ page,+ limit: isTest ? TEST_PAGE_SIZE : 100,+ operation: 'poll for changes',+ });+ records.push(...result.items);+ const timestamps = result.items.map((record) => readTimestamp({ record, field })).filter((ms): ms is number => ms !== undefined);+ const reachedCheckpoint = timestamps.length > 0 && timestamps.reduce((min, ms) => (ms < min ? ms : min)) <= lastFetchEpochMS;+ if (isTest || !result.hasMore || reachedCheckpoint || result.items.length === 0) break;+ }+ return records;+}++function buildPolling({ path, field }: { path: string; field: TimestampField }): Polling<AppConnectionValueForAuthProperty<typeof ninjapipeAuth>, Record<string, never>> {return {strategy: DedupeStrategy.TIMEBASED,- items: async ({ auth }) => {- const a = getAuth({ auth });- const response = await ninjapipeApiCall<{ data?: unknown[] }>({- auth: a,- method: HttpMethod.GET,- path,- queryParams: { limit: '100', sort: timestampField, order: 'desc' },- });- const items = extractItems(response.body);- return items.map((item) => {- const record = item as Record<string, unknown>;- const ts = (record[timestampField] ?? record['created_at'] ?? record['updated_at']) as- | string- | number- | undefined;- return {- epochMilliSeconds: ts ? new Date(ts).getTime() : Date.now(),- data: flattenCustomFields(record),- };- });+ items: async ({ auth, store, lastFetchEpochMS }) => {+ const records = await fetchSince({ auth, path, field, lastFetchEpochMS });+ return toPollItems({ records, field, store, lastFetchEpochMS });},};}-export function buildProjectTasksPolling(- timestampField: 'created_at' | 'updated_at',-): Polling<AppConnectionValueForAuthProperty<typeof ninjapipeAuth>, { projectId: string }> {+function buildProjectTasksPolling({ field }: { field: TimestampField }): Polling<AppConnectionValueForAuthProperty<typeof ninjapipeAuth>, { projectId: string }> {return {strategy: DedupeStrategy.TIMEBASED,- items: async ({ auth, propsValue }) => {- const projectId = propsValue.projectId;- if (!projectId) return [];- const a = getAuth({ auth });- const response = await ninjapipeApiCall<{ data?: unknown[] }>({- auth: a,+ items: async ({ auth, store, propsValue, lastFetchEpochMS }) => {+ const body = await ninjapipeClient.ninjapipeRequest({+ auth: ninjapipeClient.readAuth(auth),method: HttpMethod.GET,- path: `/projects/${projectId}/tasks`,- queryParams: { sort_by: timestampField, sort_order: 'desc' },- });- const items = extractItems(response.body);- return items.map((item) => {- const record = item as Record<string, unknown>;- const ts = (record[timestampField] ?? record['created_at'] ?? record['updated_at']) as- | string- | number- | undefined;- return {- epochMilliSeconds: ts ? new Date(ts).getTime() : Date.now(),- data: flattenCustomFields(record),- };+ path: `/projects/${ninjapipeClient.pathId({ value: propsValue.projectId, field: 'Project' })}/tasks`,+ query: { sort_by: field, sort_order: 'desc' },+ operation: 'poll for task changes',});+ const records = ninjapipeClient.readItems(body);+ const sorted = [...records].sort((a, b) => (readTimestamp({ record: b, field }) ?? 0) - (readTimestamp({ record: a, field }) ?? 0));+ const items = await toPollItems({ records: lastFetchEpochMS === 0 ? sorted.slice(0, TEST_PAGE_SIZE) : sorted, field, store, lastFetchEpochMS });+ return items;},};}++const TEST_PAGE_SIZE = 5;+const MAX_POLL_PAGES = 100;+const UNTIMED_STORE_KEY = 'ninjapipe_untimed_seen_ids';+const UNTIMED_MAX_IDS = 5000;++export const ninjapipePolling = { buildPolling, buildProjectTasksPolling, toPollItems };++type TimestampField = 'created_at' | 'updated_at';diff --git a/packages/pieces/community/ninjapipe/src/lib/triggers/new-company.ts b/packages/pieces/community/ninjapipe/src/lib/triggers/new-company.tsindex 9f64357bca7..dd0cc8caba0 100644--- a/packages/pieces/community/ninjapipe/src/lib/triggers/new-company.ts+++ b/packages/pieces/community/ninjapipe/src/lib/triggers/new-company.ts@@ -1,30 +1,50 @@import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';import { pollingHelper } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { buildPolling } from './common';+import { ninjapipeAuth } from '../auth';+import { ninjapipeSchemas } from '../output-schemas';+import { ninjapipePolling } from './common';++const polling = ninjapipePolling.buildPolling({ path: '/companies', field: 'created_at' });export const newCompany = createTrigger({auth: ninjapipeAuth,name: 'new_company',classification: 'READ',displayName: 'New Company',- description: 'Triggers when a new company is created.',+ description: 'Triggers when a company is created.',aiMetadata: {- description: 'Fires once for each company newly created in NinjaPipe, detected by polling on the company creation timestamp. The event payload is the created company, including its id, name, and created_at. Use it to react to brand-new companies; it does not fire when an existing company is later updated.',+ description:+ 'Fires once for each newly created NinjaPipe company, found by polling companies sorted by created_at. The payload is the company record: id, name, domain, email, phone, website, industry, status, owner_id, fields and timestamps.',},type: TriggerStrategy.POLLING,- sampleData: { id: '1', name: 'Acme Inc', created_at: '2024-01-01T00:00:00Z' },+ outputSchema: ninjapipeSchemas.company,+ sampleData: {+ id: '43e794a1-fbc0-4167-b881-c2c568d30a51',+ name: 'Acme GmbH',+ domain: 'acme.example',+ email: '[email protected]',+ phone: '+4930123456',+ website: 'https://acme.example',+ industry: 'Software',+ status: 'Active',+ owner_id: '01a55c1c-96af-4a4f-879b-e317def0769a',+ is_archived: false,+ slug: 'acme-gmbh',+ fields: {},+ created_at: '2026-10-25T15:33:57.944899+00:00',+ updated_at: '2026-10-25T15:33:57.944899+00:00',+ },props: {},async test(context) {- return await pollingHelper.test(buildPolling('/companies', 'created_at'), context);+ return pollingHelper.test(polling, context);},async onEnable(context) {- await pollingHelper.onEnable(buildPolling('/companies', 'created_at'), context);+ await pollingHelper.onEnable(polling, context);},async onDisable(context) {- await pollingHelper.onDisable(buildPolling('/companies', 'created_at'), context);+ await pollingHelper.onDisable(polling, context);},async run(context) {- return await pollingHelper.poll(buildPolling('/companies', 'created_at'), context);+ return pollingHelper.poll(polling, context);},});diff --git a/packages/pieces/community/ninjapipe/src/lib/triggers/new-contact.ts b/packages/pieces/community/ninjapipe/src/lib/triggers/new-contact.tsindex 47a1bab2b43..e2e46d35767 100644--- a/packages/pieces/community/ninjapipe/src/lib/triggers/new-contact.ts+++ b/packages/pieces/community/ninjapipe/src/lib/triggers/new-contact.ts@@ -1,30 +1,49 @@import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';import { pollingHelper } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { buildPolling } from './common';+import { ninjapipeAuth } from '../auth';+import { ninjapipeSchemas } from '../output-schemas';+import { ninjapipePolling } from './common';++const polling = ninjapipePolling.buildPolling({ path: '/contacts', field: 'created_at' });export const newContact = createTrigger({auth: ninjapipeAuth,name: 'new_contact',classification: 'READ',displayName: 'New Contact',- description: 'Triggers when a new contact is created.',+ description: 'Triggers when a contact is created.',aiMetadata: {- description: 'Fires once for each contact newly created in NinjaPipe, detected by polling on the contact creation timestamp. The event payload is the created contact, including its id, email, first_name, last_name, and created_at. Use it to react to brand-new contacts; it does not fire when an existing contact is later updated.',+ description:+ 'Fires once for each newly created NinjaPipe contact, found by polling contacts sorted by created_at. The payload is the contact record: id, first_name, last_name, email, phone, status, owner_id, assigned_to, company_id, fields and timestamps. It does not fire on later updates.',},type: TriggerStrategy.POLLING,- sampleData: { id: '1', email: '[email protected]', first_name: 'Jane', last_name: 'Doe', created_at: '2024-01-01T00:00:00Z' },+ outputSchema: ninjapipeSchemas.contact,+ sampleData: {+ id: '8bd9d1d9-4e0e-4606-aad9-bcb198b17d26',+ first_name: 'Jane',+ last_name: 'Doe',+ email: '[email protected]',+ phone: '+15550001',+ status: 'Active',+ owner_id: '01a55c1c-96af-4a4f-879b-e317def0769a',+ assigned_to: null,+ company_id: null,+ slug: 'jane-doe',+ fields: {},+ created_at: '2026-10-25T15:33:09.636647+00:00',+ updated_at: '2026-10-25T15:36:51.542+00:00',+ },props: {},async test(context) {- return await pollingHelper.test(buildPolling('/contacts', 'created_at'), context);+ return pollingHelper.test(polling, context);},async onEnable(context) {- await pollingHelper.onEnable(buildPolling('/contacts', 'created_at'), context);+ await pollingHelper.onEnable(polling, context);},async onDisable(context) {- await pollingHelper.onDisable(buildPolling('/contacts', 'created_at'), context);+ await pollingHelper.onDisable(polling, context);},async run(context) {- return await pollingHelper.poll(buildPolling('/contacts', 'created_at'), context);+ return pollingHelper.poll(polling, context);},});diff --git a/packages/pieces/community/ninjapipe/src/lib/triggers/new-deal.ts b/packages/pieces/community/ninjapipe/src/lib/triggers/new-deal.tsindex f3e73a81bb8..1a7f64f3cf0 100644--- a/packages/pieces/community/ninjapipe/src/lib/triggers/new-deal.ts+++ b/packages/pieces/community/ninjapipe/src/lib/triggers/new-deal.ts@@ -1,30 +1,46 @@import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';import { pollingHelper } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { buildPolling } from './common';+import { ninjapipeAuth } from '../auth';+import { ninjapipeSchemas } from '../output-schemas';+import { ninjapipePolling } from './common';++const polling = ninjapipePolling.buildPolling({ path: '/deals', field: 'created_at' });export const newDeal = createTrigger({auth: ninjapipeAuth,name: 'new_deal',classification: 'READ',displayName: 'New Deal',- description: 'Triggers when a new deal is created.',+ description: 'Triggers when a deal is created.',aiMetadata: {- description: 'Fires once for each deal newly created in NinjaPipe, detected by polling on the deal creation timestamp. The event payload is the created deal, including its id, name, value, and created_at. Use it to react to brand-new deals entering the pipeline; it does not fire when an existing deal is later updated.',+ description:+ 'Fires once for each newly created NinjaPipe deal, found by polling deals sorted by created_at. The payload is the deal record: id, name, value, status, owner_id, contact_id, company_id, fields and timestamps.',},type: TriggerStrategy.POLLING,- sampleData: { id: '1', name: 'Enterprise Plan', value: 5000, created_at: '2024-01-01T00:00:00Z' },+ outputSchema: ninjapipeSchemas.deal,+ sampleData: {+ id: 'c5971a27-7db7-4379-afa0-2177e4006c2a',+ name: 'Enterprise plan',+ value: 5000,+ status: 'Open',+ owner_id: '01a55c1c-96af-4a4f-879b-e317def0769a',+ contact_id: null,+ company_id: null,+ fields: {},+ created_at: '2026-10-25T15:34:04.263228+00:00',+ updated_at: '2026-10-25T15:36:24.547+00:00',+ },props: {},async test(context) {- return await pollingHelper.test(buildPolling('/deals', 'created_at'), context);+ return pollingHelper.test(polling, context);},async onEnable(context) {- await pollingHelper.onEnable(buildPolling('/deals', 'created_at'), context);+ await pollingHelper.onEnable(polling, context);},async onDisable(context) {- await pollingHelper.onDisable(buildPolling('/deals', 'created_at'), context);+ await pollingHelper.onDisable(polling, context);},async run(context) {- return await pollingHelper.poll(buildPolling('/deals', 'created_at'), context);+ return pollingHelper.poll(polling, context);},});diff --git a/packages/pieces/community/ninjapipe/src/lib/triggers/new-or-updated-company.ts b/packages/pieces/community/ninjapipe/src/lib/triggers/new-or-updated-company.tsindex d18d2e31266..82681a7cf31 100644--- a/packages/pieces/community/ninjapipe/src/lib/triggers/new-or-updated-company.ts+++ b/packages/pieces/community/ninjapipe/src/lib/triggers/new-or-updated-company.ts@@ -1,7 +1,10 @@import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';import { pollingHelper } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { buildPolling } from './common';+import { ninjapipeAuth } from '../auth';+import { ninjapipeSchemas } from '../output-schemas';+import { ninjapipePolling } from './common';++const polling = ninjapipePolling.buildPolling({ path: '/companies', field: 'updated_at' });export const newOrUpdatedCompany = createTrigger({auth: ninjapipeAuth,@@ -10,21 +13,38 @@ export const newOrUpdatedCompany = createTrigger({displayName: 'New or Updated Company',description: 'Triggers when a company is created or updated.',aiMetadata: {- description: 'Fires whenever a company in NinjaPipe is created or has any field changed, detected by polling on the company last-updated timestamp. The event payload is the current state of the affected company, including its id, name, and updated_at. A given company can fire this multiple times as it is edited; the payload does not distinguish a first creation from a later update.',+ description:+ 'Fires whenever a NinjaPipe company is created or changed, found by polling companies sorted by updated_at. The payload is the current company record. One company can fire many times.',},type: TriggerStrategy.POLLING,- sampleData: { id: '1', name: 'Acme Inc', updated_at: '2024-01-01T00:00:00Z' },+ outputSchema: ninjapipeSchemas.company,+ sampleData: {+ id: '43e794a1-fbc0-4167-b881-c2c568d30a51',+ name: 'Acme GmbH',+ domain: 'acme.example',+ email: '[email protected]',+ phone: '+4930123456',+ website: 'https://acme.example',+ industry: 'Software',+ status: 'Active',+ owner_id: '01a55c1c-96af-4a4f-879b-e317def0769a',+ is_archived: false,+ slug: 'acme-gmbh',+ fields: {},+ created_at: '2026-10-25T15:33:57.944899+00:00',+ updated_at: '2026-10-25T15:33:57.944899+00:00',+ },props: {},async test(context) {- return await pollingHelper.test(buildPolling('/companies', 'updated_at'), context);+ return pollingHelper.test(polling, context);},async onEnable(context) {- await pollingHelper.onEnable(buildPolling('/companies', 'updated_at'), context);+ await pollingHelper.onEnable(polling, context);},async onDisable(context) {- await pollingHelper.onDisable(buildPolling('/companies', 'updated_at'), context);+ await pollingHelper.onDisable(polling, context);},async run(context) {- return await pollingHelper.poll(buildPolling('/companies', 'updated_at'), context);+ return pollingHelper.poll(polling, context);},});diff --git a/packages/pieces/community/ninjapipe/src/lib/triggers/new-or-updated-contact.ts b/packages/pieces/community/ninjapipe/src/lib/triggers/new-or-updated-contact.tsindex 237a087b0c8..a0ed0dc84d4 100644--- a/packages/pieces/community/ninjapipe/src/lib/triggers/new-or-updated-contact.ts+++ b/packages/pieces/community/ninjapipe/src/lib/triggers/new-or-updated-contact.ts@@ -1,7 +1,10 @@import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';import { pollingHelper } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { buildPolling } from './common';+import { ninjapipeAuth } from '../auth';+import { ninjapipeSchemas } from '../output-schemas';+import { ninjapipePolling } from './common';++const polling = ninjapipePolling.buildPolling({ path: '/contacts', field: 'updated_at' });export const newOrUpdatedContact = createTrigger({auth: ninjapipeAuth,@@ -10,21 +13,37 @@ export const newOrUpdatedContact = createTrigger({displayName: 'New or Updated Contact',description: 'Triggers when a contact is created or updated.',aiMetadata: {- description: 'Fires whenever a contact in NinjaPipe is created or has any field changed, detected by polling on the contact last-updated timestamp. The event payload is the current state of the affected contact, including its id, email, first_name, last_name, and updated_at. A given contact can fire this multiple times as it is edited; the payload does not distinguish a first creation from a later update.',+ description:+ 'Fires whenever a NinjaPipe contact is created or changed, found by polling contacts sorted by updated_at. The payload is the current contact record. One contact can fire many times; the payload does not say whether it was a create or an update.',},type: TriggerStrategy.POLLING,- sampleData: { id: '1', email: '[email protected]', first_name: 'Jane', last_name: 'Doe', updated_at: '2024-01-01T00:00:00Z' },+ outputSchema: ninjapipeSchemas.contact,+ sampleData: {+ id: '8bd9d1d9-4e0e-4606-aad9-bcb198b17d26',+ first_name: 'Jane',+ last_name: 'Doe',+ email: '[email protected]',+ phone: '+15550001',+ status: 'Active',+ owner_id: '01a55c1c-96af-4a4f-879b-e317def0769a',+ assigned_to: null,+ company_id: null,+ slug: 'jane-doe',+ fields: {},+ created_at: '2026-10-25T15:33:09.636647+00:00',+ updated_at: '2026-10-25T15:36:51.542+00:00',+ },props: {},async test(context) {- return await pollingHelper.test(buildPolling('/contacts', 'updated_at'), context);+ return pollingHelper.test(polling, context);},async onEnable(context) {- await pollingHelper.onEnable(buildPolling('/contacts', 'updated_at'), context);+ await pollingHelper.onEnable(polling, context);},async onDisable(context) {- await pollingHelper.onDisable(buildPolling('/contacts', 'updated_at'), context);+ await pollingHelper.onDisable(polling, context);},async run(context) {- return await pollingHelper.poll(buildPolling('/contacts', 'updated_at'), context);+ return pollingHelper.poll(polling, context);},});diff --git a/packages/pieces/community/ninjapipe/src/lib/triggers/new-or-updated-deal.ts b/packages/pieces/community/ninjapipe/src/lib/triggers/new-or-updated-deal.tsindex 7ef5a0f732e..e5fbc9acd57 100644--- a/packages/pieces/community/ninjapipe/src/lib/triggers/new-or-updated-deal.ts+++ b/packages/pieces/community/ninjapipe/src/lib/triggers/new-or-updated-deal.ts@@ -1,7 +1,10 @@import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';import { pollingHelper } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { buildPolling } from './common';+import { ninjapipeAuth } from '../auth';+import { ninjapipeSchemas } from '../output-schemas';+import { ninjapipePolling } from './common';++const polling = ninjapipePolling.buildPolling({ path: '/deals', field: 'updated_at' });export const newOrUpdatedDeal = createTrigger({auth: ninjapipeAuth,@@ -10,21 +13,34 @@ export const newOrUpdatedDeal = createTrigger({displayName: 'New or Updated Deal',description: 'Triggers when a deal is created or updated.',aiMetadata: {- description: 'Fires whenever a deal in NinjaPipe is created or has any field changed, detected by polling on the deal last-updated timestamp. The event payload is the current state of the affected deal, including its id, name, value, and updated_at. A given deal can fire this multiple times as it moves through the pipeline; the payload does not distinguish a first creation from a later update.',+ description:+ 'Fires whenever a NinjaPipe deal is created or changed (value, status, links), found by polling deals sorted by updated_at. The payload is the current deal record. One deal can fire many times as it progresses.',},type: TriggerStrategy.POLLING,- sampleData: { id: '1', name: 'Enterprise Plan', value: 5000, updated_at: '2024-01-01T00:00:00Z' },+ outputSchema: ninjapipeSchemas.deal,+ sampleData: {+ id: 'c5971a27-7db7-4379-afa0-2177e4006c2a',+ name: 'Enterprise plan',+ value: 5000,+ status: 'Open',+ owner_id: '01a55c1c-96af-4a4f-879b-e317def0769a',+ contact_id: null,+ company_id: null,+ fields: {},+ created_at: '2026-10-25T15:34:04.263228+00:00',+ updated_at: '2026-10-25T15:36:24.547+00:00',+ },props: {},async test(context) {- return await pollingHelper.test(buildPolling('/deals', 'updated_at'), context);+ return pollingHelper.test(polling, context);},async onEnable(context) {- await pollingHelper.onEnable(buildPolling('/deals', 'updated_at'), context);+ await pollingHelper.onEnable(polling, context);},async onDisable(context) {- await pollingHelper.onDisable(buildPolling('/deals', 'updated_at'), context);+ await pollingHelper.onDisable(polling, context);},async run(context) {- return await pollingHelper.poll(buildPolling('/deals', 'updated_at'), context);+ return pollingHelper.poll(polling, context);},});diff --git a/packages/pieces/community/ninjapipe/src/lib/triggers/new-or-updated-task.ts b/packages/pieces/community/ninjapipe/src/lib/triggers/new-or-updated-task.tsindex 704204ac6b2..75becf9dedc 100644--- a/packages/pieces/community/ninjapipe/src/lib/triggers/new-or-updated-task.ts+++ b/packages/pieces/community/ninjapipe/src/lib/triggers/new-or-updated-task.ts@@ -1,10 +1,11 @@import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';import { pollingHelper } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeCommon } from '../common';-import { buildProjectTasksPolling } from './common';+import { ninjapipeAuth } from '../auth';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';+import { ninjapipePolling } from './common';-const polling = buildProjectTasksPolling('updated_at');+const polling = ninjapipePolling.buildProjectTasksPolling({ field: 'updated_at' });export const newOrUpdatedTask = createTrigger({auth: ninjapipeAuth,@@ -13,26 +14,29 @@ export const newOrUpdatedTask = createTrigger({displayName: 'New or Updated Task',description: 'Triggers when a task in the selected project is created or updated.',aiMetadata: {- description: 'Fires whenever a task in the selected NinjaPipe project is created or has any field changed, detected by polling on the task last-updated timestamp. The event payload is the current state of the affected task, including its id, project_id, title, description, status, priority, assignee_id, due_date, parent_id, tags, and timestamps. A given task can fire this multiple times as it progresses (e.g. status moving to In Progress); the payload does not distinguish a first creation from a later update.',+ description:+ 'Fires whenever a task in the selected NinjaPipe project is created or changed (for example its status moves to Done), found by polling by updated_at. The payload is the current task. One task can fire many times.',},type: TriggerStrategy.POLLING,+ outputSchema: ninjapipeSchemas.task,sampleData: {- id: 'a97381c8-75d3-4773-92d7-80ad97cf06f9',- project_id: 'dbe92bb3-3239-4710-8216-dccc9ffceaa5',+ id: 'f6bc8683-31a9-46f2-9f3d-58a0a66f5e27',+ project_id: 'd9e0d794-e966-473e-bc7f-89d90e40d1aa',title: 'Ship release notes',description: null,- status: 'In Progress',- priority: 'Medium',+ status: 'To Do',+ priority: 'High',assignee_id: null,- due_date: null,+ due_date: '2026-12-01',parent_id: null,- order_index: 0,+ level: 0,+ has_children: false,tags: [],- created_at: '2026-04-28T13:00:00Z',- updated_at: '2026-04-28T13:30:00Z',+ created_at: '2026-10-25T15:34:47.050306+00:00',+ updated_at: '2026-10-25T15:34:47.050306+00:00',},props: {- projectId: ninjapipeCommon.projectDropdownRequired,+ projectId: ninjapipeProps.projectRequired(),},async test(context) {return pollingHelper.test(polling, context);diff --git a/packages/pieces/community/ninjapipe/src/lib/triggers/new-task.ts b/packages/pieces/community/ninjapipe/src/lib/triggers/new-task.tsindex 6c55c8b7c58..1c9de5abd63 100644--- a/packages/pieces/community/ninjapipe/src/lib/triggers/new-task.ts+++ b/packages/pieces/community/ninjapipe/src/lib/triggers/new-task.ts@@ -1,38 +1,42 @@import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';import { pollingHelper } from '@activepieces/pieces-common';-import { ninjapipeAuth } from '../../';-import { ninjapipeCommon } from '../common';-import { buildProjectTasksPolling } from './common';+import { ninjapipeAuth } from '../auth';+import { ninjapipeProps } from '../common/props';+import { ninjapipeSchemas } from '../output-schemas';+import { ninjapipePolling } from './common';-const polling = buildProjectTasksPolling('created_at');+const polling = ninjapipePolling.buildProjectTasksPolling({ field: 'created_at' });export const newTask = createTrigger({auth: ninjapipeAuth,name: 'new_task',classification: 'READ',displayName: 'New Task',- description: 'Triggers when a new task is created in the selected project.',+ description: 'Triggers when a task is created in the selected project.',aiMetadata: {- description: 'Fires once for each task newly created in the selected NinjaPipe project, detected by polling on the task creation timestamp. The event payload is the created task, including its id, project_id, title, description, status, priority, assignee_id, due_date, parent_id, tags, and timestamps. Use it to react to brand-new work items; it does not fire for subsequent edits to an existing task.',+ description:+ 'Fires once for each task newly created in the selected NinjaPipe project, found by polling the project tasks by created_at. The payload is the task: id, project_id, title, description, status, priority, assignee_id, due_date, parent_id, tags and timestamps.',},type: TriggerStrategy.POLLING,+ outputSchema: ninjapipeSchemas.task,sampleData: {- id: 'a97381c8-75d3-4773-92d7-80ad97cf06f9',- project_id: 'dbe92bb3-3239-4710-8216-dccc9ffceaa5',+ id: 'f6bc8683-31a9-46f2-9f3d-58a0a66f5e27',+ project_id: 'd9e0d794-e966-473e-bc7f-89d90e40d1aa',title: 'Ship release notes',description: null,status: 'To Do',- priority: 'Medium',+ priority: 'High',assignee_id: null,- due_date: null,+ due_date: '2026-12-01',parent_id: null,- order_index: 0,+ level: 0,+ has_children: false,tags: [],- created_at: '2026-04-28T13:00:00Z',- updated_at: '2026-04-28T13:00:00Z',+ created_at: '2026-10-25T15:34:47.050306+00:00',+ updated_at: '2026-10-25T15:34:47.050306+00:00',},props: {- projectId: ninjapipeCommon.projectDropdownRequired,+ projectId: ninjapipeProps.projectRequired(),},async test(context) {return pollingHelper.test(polling, context);diff --git a/packages/pieces/community/ninjapipe/test/actions.test.ts b/packages/pieces/community/ninjapipe/test/actions.test.tsnew file mode 100644index 00000000000..2b96fa3d5c8--- /dev/null+++ b/packages/pieces/community/ninjapipe/test/actions.test.ts@@ -0,0 +1,159 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { ninjapipe } from '../src';+import { request, runAction, stubFetch, page } from './helpers';++const ID = '11111111-2222-3333-4444-555555555555';+const MEMBER = '01a55c1c-96af-4a4f-879b-e317def0769a';+const record = { id: ID, name: 'AP test', title: 'AP test', fields: { keep: 'yes' }, created_at: '2026-10-25T10:00:00Z', updated_at: '2026-10-25T10:00:00Z' };+const wrapped = { data: record, message: 'ok' };+const deleted = { message: 'deleted', data: { id: ID, name: 'AP test' } };++type Case = {+ action: string;+ props: Record<string, unknown>;+ responses?: { status: number; body: unknown }[];+ method: string;+ path: string;+ call?: number;+ query?: Record<string, string>;+ body?: Record<string, unknown>;+};++const cases: Case[] = [+ { action: 'list_contacts', props: { search: 'jane', statusFilter: 'Lead', ownerFilter: MEMBER, assignedTo: MEMBER, sortBy: 'updated_at', sortOrder: 'asc', limit: 500, page: 2 }, responses: [{ status: 200, body: page({ data: [record] }) }], method: 'GET', path: '/contacts', query: { search: 'jane', status: 'Lead', owner_id: MEMBER, assigned_to: MEMBER, sort_by: 'updated_at', sort_order: 'asc', page: '2', limit: '100' } },+ { action: 'get_contact', props: { contactId: 'a/b' }, responses: [{ status: 200, body: wrapped }], method: 'GET', path: '/contacts/a%2Fb' },+ { action: 'create_contact', props: { firstName: 'Jane', email: ' [email protected] ', owner: MEMBER, assignedTo: MEMBER, companyId: ID, customFields: { tier: 'gold' } }, responses: [{ status: 201, body: wrapped }], method: 'POST', path: '/contacts', body: { first_name: 'Jane', email: '[email protected]', owner_id: MEMBER, assigned_to: MEMBER, company_id: ID, fields: { tier: 'gold' } } },+ { action: 'update_contact', props: { contactId: ID, lastName: 'Doe', clearFields: ['phone', 'assigned_to'] }, responses: [{ status: 200, body: wrapped }], method: 'PUT', path: `/contacts/${ID}`, body: { last_name: 'Doe', phone: null, assigned_to: null } },+ { action: 'delete_contact', props: { contactId: ID }, responses: [{ status: 200, body: deleted }], method: 'DELETE', path: `/contacts/${ID}` },+ { action: 'upsert_contact', props: { email: '[email protected]', firstName: 'Jane' }, responses: [{ status: 200, body: page({ data: [] }) }, { status: 201, body: wrapped }], method: 'POST', path: '/contacts', call: 1, body: { email: '[email protected]', first_name: 'Jane' } },+ { action: 'toggle_client_portal', props: { contactId: ID, enable: false }, responses: [{ status: 200, body: wrapped }], method: 'PUT', path: `/client-portal-accounts/${ID}/disable`, body: {} },+ { action: 'list_companies', props: { search: 'acme', ownerFilter: MEMBER, limit: 0 }, responses: [{ status: 200, body: page({ data: [record] }) }], method: 'GET', path: '/companies', query: { search: 'acme', owner_id: MEMBER, page: '1', limit: '1' } },+ { action: 'get_company', props: { companyId: ID }, responses: [{ status: 200, body: wrapped }], method: 'GET', path: `/companies/${ID}` },+ { action: 'create_company', props: { name: 'Acme', industry: 'SaaS', owner: MEMBER, customFields: { size: 10 } }, responses: [{ status: 201, body: wrapped }], method: 'POST', path: '/companies', body: { name: 'Acme', industry: 'SaaS', owner_id: MEMBER, fields: { size: 10 } } },+ { action: 'update_company', props: { companyId: ID, website: 'https://acme.example', clearFields: ['phone'] }, responses: [{ status: 200, body: wrapped }], method: 'PUT', path: `/companies/${ID}`, body: { website: 'https://acme.example', phone: null } },+ { action: 'delete_company', props: { companyId: ID }, responses: [{ status: 200, body: deleted }], method: 'DELETE', path: `/companies/${ID}` },+ { action: 'list_deals', props: { statusFilter: 'Won', sortBy: 'value' }, responses: [{ status: 200, body: page({ data: [record] }) }], method: 'GET', path: '/deals', query: { status: 'Won', sort_by: 'value', page: '1', limit: '20' } },+ { action: 'get_deal', props: { dealId: ID }, responses: [{ status: 200, body: wrapped }], method: 'GET', path: `/deals/${ID}` },+ { action: 'create_deal', props: { name: 'Big', value: 0, status: 'Open', contactId: ID }, responses: [{ status: 201, body: wrapped }], method: 'POST', path: '/deals', body: { name: 'Big', value: 0, status: 'Open', contact_id: ID } },+ { action: 'update_deal', props: { dealId: ID, value: '1500', clearFields: ['company_id'] }, responses: [{ status: 200, body: wrapped }], method: 'PUT', path: `/deals/${ID}`, body: { value: 1500, company_id: null } },+ { action: 'delete_deal', props: { dealId: ID }, responses: [{ status: 200, body: deleted }], method: 'DELETE', path: `/deals/${ID}` },+ { action: 'list_products', props: { search: 'sku' }, responses: [{ status: 200, body: page({ data: [record] }) }], method: 'GET', path: '/products', query: { search: 'sku', page: '1', limit: '20' } },+ { action: 'get_product', props: { productId: ID }, responses: [{ status: 200, body: wrapped }], method: 'GET', path: `/products/${ID}` },+ { action: 'create_product', props: { name: 'P', price: 9.5, sku: 'S1' }, responses: [{ status: 201, body: wrapped }], method: 'POST', path: '/products', body: { name: 'P', price: 9.5, sku: 'S1' } },+ { action: 'update_product', props: { productId: ID, price: 0 }, responses: [{ status: 200, body: wrapped }], method: 'PUT', path: `/products/${ID}`, body: { price: 0 } },+ { action: 'delete_product', props: { productId: ID }, responses: [{ status: 200, body: deleted }], method: 'DELETE', path: `/products/${ID}` },+ { action: 'list_budgets', props: {}, responses: [{ status: 200, body: page({ data: [record] }) }], method: 'GET', path: '/budgets', query: { page: '1', limit: '20' } },+ { action: 'get_budget', props: { budgetId: ID }, responses: [{ status: 200, body: wrapped }], method: 'GET', path: `/budgets/${ID}` },+ { action: 'create_budget', props: { name: 'B', allocated: 100, category: 'Marketing', period: 'Monthly', startDate: '2026-10-01T09:00:00.000Z' }, responses: [{ status: 201, body: wrapped }], method: 'POST', path: '/budgets', body: { name: 'B', allocated: 100, category: 'Marketing', period: 'Monthly', start_date: '2026-10-01' } },+ { action: 'update_budget', props: { budgetId: ID, allocated: 200 }, responses: [{ status: 200, body: wrapped }], method: 'PUT', path: `/budgets/${ID}`, body: { allocated: 200 } },+ { action: 'delete_budget', props: { budgetId: ID }, responses: [{ status: 200, body: deleted }], method: 'DELETE', path: `/budgets/${ID}` },+ { action: 'create_budget_expense', props: { budgetId: ID, description: 'Ads', amount: '12.5', date: '2026-10-20' }, responses: [{ status: 201, body: wrapped }], method: 'POST', path: `/budgets/${ID}/expenses`, body: { description: 'Ads', amount: 12.5, date: '2026-10-20' } },+ { action: 'list_projects', props: { statusFilter: 'Planning' }, responses: [{ status: 200, body: page({ data: [record] }) }], method: 'GET', path: '/projects', query: { status: 'Planning', page: '1', limit: '20' } },+ { action: 'get_project', props: { projectId: ID }, responses: [{ status: 200, body: wrapped }], method: 'GET', path: `/projects/${ID}` },+ { action: 'create_project', props: { name: 'P', tags: ['a', ''], team: [] }, responses: [{ status: 201, body: wrapped }], method: 'POST', path: '/projects', body: { name: 'P', tags: ['a'] } },+ { action: 'update_project', props: { projectId: ID, status: 'Completed', clearFields: ['due_date'] }, responses: [{ status: 200, body: wrapped }], method: 'PUT', path: `/projects/${ID}`, body: { status: 'Completed', due_date: null } },+ { action: 'delete_project', props: { projectId: ID }, responses: [{ status: 200, body: deleted }], method: 'DELETE', path: `/projects/${ID}` },+ { action: 'list_tasks', props: { projectId: ID, statusFilter: 'Done', priorityFilter: 'High' }, responses: [{ status: 200, body: { data: [record] } }], method: 'GET', path: `/projects/${ID}/tasks`, query: { status: 'Done', priority: 'High' } },+ { action: 'get_task', props: { projectId: ID, taskId: 't 1' }, responses: [{ status: 200, body: wrapped }], method: 'GET', path: `/projects/${ID}/tasks/t%201` },+ { action: 'create_task', props: { projectId: ID, title: 'T', assigneeId: MEMBER, estimatedHours: 0 }, responses: [{ status: 201, body: wrapped }], method: 'POST', path: `/projects/${ID}/tasks`, body: { title: 'T', assignee_id: MEMBER, estimated_hours: 0 } },+ { action: 'update_task', props: { projectId: ID, taskId: ID, status: 'Done', clearFields: ['assignee_id'] }, responses: [{ status: 200, body: wrapped }], method: 'PUT', path: `/projects/${ID}/tasks/${ID}`, body: { status: 'Done', assignee_id: null } },+ { action: 'delete_task', props: { projectId: ID, taskId: ID }, responses: [{ status: 200, body: deleted }], method: 'DELETE', path: `/projects/${ID}/tasks/${ID}` },+ { action: 'list_pipelines', props: { sortBy: 'name' }, responses: [{ status: 200, body: page({ data: [record] }) }], method: 'GET', path: '/pipelines', query: { sort_by: 'name', page: '1', limit: '20' } },+ { action: 'get_pipeline', props: { pipelineId: ID }, responses: [{ status: 200, body: wrapped }], method: 'GET', path: `/pipelines/${ID}` },+ { action: 'create_pipeline', props: { name: 'P', pipelineType: 'deals', stages: [{ name: 'New Lead' }, { name: 'Won', id: 'won', color: '#059669' }] }, responses: [{ status: 201, body: wrapped }], method: 'POST', path: '/pipelines', body: { name: 'P', pipeline_type: 'deals', stages: [{ id: 'new-lead', name: 'New Lead', color: '#3b82f6' }, { id: 'won', name: 'Won', color: '#059669' }] } },+ { action: 'update_pipeline', props: { pipelineId: ID, name: 'R' }, responses: [{ status: 200, body: wrapped }], method: 'PUT', path: `/pipelines/${ID}`, body: { name: 'R' } },+ { action: 'delete_pipeline', props: { pipelineId: ID }, responses: [{ status: 200, body: deleted }], method: 'DELETE', path: `/pipelines/${ID}` },+ { action: 'list_orders', props: { statusFilter: 'Shipped' }, responses: [{ status: 200, body: page({ data: [record] }) }], method: 'GET', path: '/orders', query: { status: 'Shipped', page: '1', limit: '20' } },+ { action: 'get_order', props: { orderId: ID }, responses: [{ status: 200, body: wrapped }], method: 'GET', path: `/orders/${ID}` },+ { action: 'create_order', props: { customerName: 'C', totalAmount: 10, orderDate: '2026-10-25' }, responses: [{ status: 201, body: wrapped }], method: 'POST', path: '/orders', body: { customer_name: 'C', total_amount: 10, order_date: '2026-10-25' } },+ { action: 'update_order', props: { orderId: ID, status: 'Shipped', clearFields: ['notes'] }, responses: [{ status: 200, body: wrapped }], method: 'PUT', path: `/orders/${ID}`, body: { status: 'Shipped', notes: null } },+ { action: 'delete_order', props: { orderId: ID }, responses: [{ status: 200, body: deleted }], method: 'DELETE', path: `/orders/${ID}` },+ { action: 'add_to_list', props: { listId: ID, companyId: ID }, responses: [{ status: 201, body: { data: { list_id: ID, already_in_list: false } } }], method: 'POST', path: `/lists/${ID}/members`, body: { company_id: ID } },+ { action: 'create_pipeline_item', props: { pipelineId: ID, stageId: 's1', title: 'Card', value: 5, assignedTo: MEMBER }, responses: [{ status: 201, body: wrapped }], method: 'POST', path: `/pipelines/${ID}/items`, body: { title: 'Card', stage_id: 's1', value: 5, assigned_to: MEMBER } },+ { action: 'update_pipeline_item', props: { pipelineId: ID, itemId: ID, stageId: 'won', clearFields: ['due_date'] }, responses: [{ status: 200, body: wrapped }], method: 'PUT', path: `/pipelines/${ID}/items/${ID}`, body: { stage_id: 'won', due_date: null } },+ { action: 'add_contact_note', props: { contactId: ID, title: 'Call', content: 'Went well' }, responses: [{ status: 201, body: wrapped }], method: 'POST', path: `/contacts/${ID}/activities`, body: { type: 'note', title: 'Call', content: 'Went well' } },+ { action: 'ai_search_contacts', props: { search: 'jane', assigned_to: MEMBER, limit: 5 }, responses: [{ status: 200, body: page({ data: [record], pages: 3 }) }], method: 'GET', path: '/contacts', query: { search: 'jane', assigned_to: MEMBER, page: '1', limit: '5' } },+ { action: 'ai_get_contact', props: { contact_id: ID }, responses: [{ status: 200, body: wrapped }], method: 'GET', path: `/contacts/${ID}` },+ { action: 'ai_create_contact', props: { first_name: 'Jane', email: '[email protected]', fields: { a: 1 } }, responses: [{ status: 201, body: wrapped }], method: 'POST', path: '/contacts', body: { first_name: 'Jane', email: '[email protected]', fields: { a: 1 } } },+ { action: 'ai_update_contact', props: { contact_id: ID, status: 'Lead', clear_fields: ['assigned_to'] }, responses: [{ status: 200, body: wrapped }], method: 'PUT', path: `/contacts/${ID}`, body: { status: 'Lead', assigned_to: null } },+ { action: 'ai_search_companies', props: { search: 'acme' }, responses: [{ status: 200, body: page({ data: [record] }) }], method: 'GET', path: '/companies', query: { search: 'acme', page: '1', limit: '20' } },+ { action: 'ai_get_company', props: { company_id: ID }, responses: [{ status: 200, body: wrapped }], method: 'GET', path: `/companies/${ID}` },+ { action: 'ai_create_company', props: { name: 'Acme', industry: 'SaaS' }, responses: [{ status: 201, body: wrapped }], method: 'POST', path: '/companies', body: { name: 'Acme', industry: 'SaaS' } },+ { action: 'ai_update_company', props: { company_id: ID, industry: 'Retail' }, responses: [{ status: 200, body: wrapped }], method: 'PUT', path: `/companies/${ID}`, body: { industry: 'Retail' } },+ { action: 'ai_search_deals', props: { status: 'Open', sort_by: 'value', sort_order: 'desc' }, responses: [{ status: 200, body: page({ data: [record] }) }], method: 'GET', path: '/deals', query: { status: 'Open', sort_by: 'value', sort_order: 'desc', page: '1', limit: '20' } },+ { action: 'ai_get_deal', props: { deal_id: ID }, responses: [{ status: 200, body: wrapped }], method: 'GET', path: `/deals/${ID}` },+ { action: 'ai_create_deal', props: { name: 'D', value: 10, status: 'Open' }, responses: [{ status: 201, body: wrapped }], method: 'POST', path: '/deals', body: { name: 'D', value: 10, status: 'Open' } },+ { action: 'ai_update_deal', props: { deal_id: ID, status: 'Won' }, responses: [{ status: 200, body: wrapped }], method: 'PUT', path: `/deals/${ID}`, body: { status: 'Won' } },+ { action: 'ai_list_projects', props: { status: 'Planning', page: 2 }, responses: [{ status: 200, body: page({ data: [record], page: 2, pages: 2 }) }], method: 'GET', path: '/projects', query: { status: 'Planning', page: '2', limit: '20' } },+ { action: 'list_tasks', props: { projectId: ID, rootOnly: true }, responses: [{ status: 200, body: { data: [record] } }], method: 'GET', path: `/projects/${ID}/tasks`, query: { parent_id: '' } },+ { action: 'list_tasks', props: { projectId: ID, parentId: '' }, responses: [{ status: 200, body: { data: [record] } }], method: 'GET', path: `/projects/${ID}/tasks`, query: {} },+ { action: 'ai_list_tasks', props: { project_id: ID, parent_id: '' }, responses: [{ status: 200, body: { data: [record] } }], method: 'GET', path: `/projects/${ID}/tasks`, query: {} },+ { action: 'list_tasks', props: { projectId: ID, parentId: ' t1 ', rootOnly: true }, responses: [{ status: 200, body: { data: [record] } }], method: 'GET', path: `/projects/${ID}/tasks`, query: { parent_id: 't1' } },+ { action: 'ai_list_tasks', props: { project_id: ID, root_only: true }, responses: [{ status: 200, body: { data: [record] } }], method: 'GET', path: `/projects/${ID}/tasks`, query: { parent_id: '' } },+ { action: 'ai_list_tasks', props: { project_id: ID, status: 'Done' }, responses: [{ status: 200, body: { data: [record] } }], method: 'GET', path: `/projects/${ID}/tasks`, query: { status: 'Done' } },+ { action: 'ai_create_task', props: { project_id: ID, title: 'T', due_date: '2026-12-01' }, responses: [{ status: 201, body: wrapped }], method: 'POST', path: `/projects/${ID}/tasks`, body: { title: 'T', due_date: '2026-12-01' } },+ { action: 'ai_update_task', props: { project_id: ID, task_id: ID, status: 'Done' }, responses: [{ status: 200, body: wrapped }], method: 'PUT', path: `/projects/${ID}/tasks/${ID}`, body: { status: 'Done' } },+ { action: 'ai_list_pipelines', props: {}, responses: [{ status: 200, body: page({ data: [record] }) }], method: 'GET', path: '/pipelines', query: { page: '1', limit: '20' } },+ { action: 'ai_list_pipeline_items', props: { pipeline_id: ID }, responses: [{ status: 200, body: { data: [record] } }], method: 'GET', path: `/pipelines/${ID}/items` },+ { action: 'ai_create_pipeline_item', props: { pipeline_id: ID, stage_id: 's1', title: 'Card' }, responses: [{ status: 201, body: wrapped }], method: 'POST', path: `/pipelines/${ID}/items`, body: { title: 'Card', stage_id: 's1' } },+ { action: 'ai_update_pipeline_item', props: { pipeline_id: ID, item_id: ID, stage_id: 'won' }, responses: [{ status: 200, body: wrapped }], method: 'PUT', path: `/pipelines/${ID}/items/${ID}`, body: { stage_id: 'won' } },+ { action: 'ai_list_workspace_members', props: {}, responses: [{ status: 200, body: { data: [{ account_id: MEMBER }] } }], method: 'GET', path: '/workspace/members' },+ { action: 'ai_add_contact_note', props: { contact_id: ID, title: 'Note' }, responses: [{ status: 201, body: wrapped }], method: 'POST', path: `/contacts/${ID}/activities`, body: { type: 'note', title: 'Note' } },+ { action: 'ai_list_contact_activities', props: { contact_id: ID, type: 'note' }, responses: [{ status: 200, body: page({ data: [record] }) }], method: 'GET', path: `/contacts/${ID}/activities`, query: { type: 'note', page: '1', limit: '20' } },+];++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('every action sends the documented request', () => {+ it.each(cases)('$action', async ({ action, props, responses, method, path, call = 0, query, body }) => {+ const fetchMock = stubFetch({ responses: responses ?? [{ status: 200, body: wrapped }] });+ const output = await runAction({ name: action, propsValue: props });+ const sent = request({ fetchMock, call });+ expect(sent.method).toBe(method);+ expect(sent.url.origin + sent.url.pathname).toBe(`https://www.ninjapipe.app/api${path}`);+ expect(sent.headers.get('authorization')).toBe('Bearer np_test');+ if (query) expect(sent.query).toEqual(query);+ if (body) expect(sent.body).toEqual(body);+ expect(output).toBeTruthy();+ });++ it('covers every action except Custom API Call and Send to Databin', () => {+ const covered = new Set(cases.map((item) => item.action));+ const missing = Object.keys(ninjapipe.actions()).filter((name) => !covered.has(name));+ expect(missing.sort()).toEqual(['custom_api_call', 'send_to_databin']);+ });+});++describe('output shape', () => {+ it('get actions return the unwrapped record, not data_* keys', async () => {+ stubFetch({ responses: [{ status: 200, body: wrapped }] });+ const output = await runAction({ name: 'get_contact', propsValue: { contactId: ID } });+ expect(output).toEqual(record);+ });++ it('list actions return items, total, hasMore and nextPage', async () => {+ stubFetch({ responses: [{ status: 200, body: page({ data: [record], page: 1, pages: 3, total: 41 }) }] });+ const output = await runAction({ name: 'list_deals', propsValue: { limit: 20 } });+ expect(output).toEqual({ items: [record], count: 1, total: 41, hasMore: true, nextPage: 2 });+ });++ it('companies pagination without pages falls back to a full page meaning more', async () => {+ stubFetch({ responses: [{ status: 200, body: { data: [record], pagination: { page: 1, limit: 1, total: null, totalPages: 0 } } }] });+ const output = await runAction({ name: 'list_companies', propsValue: { limit: 1 } });+ expect(output).toMatchObject({ hasMore: true, nextPage: 2 });+ });++ it('delete returns deleted, id and name', async () => {+ stubFetch({ responses: [{ status: 200, body: deleted }] });+ const output = await runAction({ name: 'delete_deal', propsValue: { dealId: ID } });+ expect(output).toEqual({ deleted: true, id: ID, name: 'AP test', message: 'deleted' });+ });++ it('portal enable returns the generated password next to the record', async () => {+ stubFetch({ responses: [{ status: 200, body: { data: { id: 'p1', contact_id: ID }, message: 'enabled', generated_password: 'pw' } }] });+ const output = await runAction({ name: 'toggle_client_portal', propsValue: { contactId: ID, enable: true, email: '[email protected]' } });+ expect(output).toEqual({ enabled: true, id: 'p1', contact_id: ID, generated_password: 'pw', message: 'enabled' });+ });+});diff --git a/packages/pieces/community/ninjapipe/test/client.test.ts b/packages/pieces/community/ninjapipe/test/client.test.tsnew file mode 100644index 00000000000..0b12be6288a--- /dev/null+++ b/packages/pieces/community/ninjapipe/test/client.test.ts@@ -0,0 +1,278 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { ninjapipe } from '../src';+import { HttpMethod } from '@activepieces/pieces-common';+import { NinjaPipeApiError, ninjapipeClient, ninjapipeClock } from '../src/lib/common/client';+import { page, request, runAction, stubFetch } from './helpers';++const ID = '11111111-2222-3333-4444-555555555555';+const auth = { baseUrl: 'https://www.ninjapipe.app/api', apiKey: 'np_test' };++afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++describe('client', () => {+ it('trims the key and base URL from the connection', () => {+ expect(ninjapipeClient.readAuth({ props: { base_url: ' https://x.example/api/ ', api_key: ' np_1 ' } })).toEqual({ baseUrl: 'https://x.example/api', apiKey: 'np_1' });+ });++ it('retries a 429 after retryAfter seconds (clamped to 60) and then succeeds', async () => {+ const wait = vi.spyOn(ninjapipeClock, 'wait').mockResolvedValue(undefined);+ const fetchMock = stubFetch({+ responses: [+ { status: 429, body: { error: 'Too Many Requests', code: 'RATE_LIMIT_EXCEEDED', retryAfter: 600 } },+ { status: 200, body: { data: { id: ID } } },+ ],+ });+ const result = await ninjapipeClient.getRecord({ auth, path: `/contacts/${ID}`, operation: 'get contact' });+ expect(result).toEqual({ id: ID });+ expect(wait).toHaveBeenCalledWith(60000);+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ it('gives up after two 429 retries with a readable error', async () => {+ vi.spyOn(ninjapipeClock, 'wait').mockResolvedValue(undefined);+ stubFetch({ responses: [{ status: 429, body: { error: 'Too Many Requests', retryAfter: 1 } }] });+ await expect(ninjapipeClient.getRecord({ auth, path: '/contacts/x', operation: 'get contact' })).rejects.toThrow(/HTTP 429.*100 requests per minute/);+ });++ it('throws NinjaPipeApiError with responseBody and no body field', async () => {+ stubFetch({ responses: [{ status: 400, body: { error: 'Validation Error', message: 'Unrecognized field(s): city', code: 'UNKNOWN_FIELDS', details: { fields: ['city'] } } }] });+ const error = await ninjapipeClient.getRecord({ auth, path: '/contacts/x', operation: 'get contact' }).catch((e: unknown) => e);+ if (!(error instanceof NinjaPipeApiError)) throw new Error('expected NinjaPipeApiError');+ const apiError = error;+ expect(apiError.status).toBe(400);+ expect(apiError.code).toBe('UNKNOWN_FIELDS');+ expect(apiError.message).toContain('Unrecognized field(s): city');+ expect(apiError.responseBody).toMatchObject({ code: 'UNKNOWN_FIELDS' });+ expect('body' in apiError).toBe(false);+ });++ it('explains a 403 as a missing write permission', async () => {+ stubFetch({ responses: [{ status: 403, body: { error: 'Forbidden' } }] });+ await expect(ninjapipeClient.getRecord({ auth, path: '/x', operation: 'create contact' })).rejects.toThrow(/write permission/);+ });++ it('turns an HTML 404 into a short message', async () => {+ stubFetch({ responses: [{ status: 404, body: '<!DOCTYPE html><html><pre>Cannot GET /api/x</pre></html>' }] });+ await expect(ninjapipeClient.getRecord({ auth, path: '/x', operation: 'get x' })).rejects.toThrow('NinjaPipe get x failed (HTTP 404): endpoint not found on this NinjaPipe API.');+ });++ it('refuses paths that would leave the base URL', async () => {+ await expect(ninjapipeClient.ninjapipeRequest({ auth, method: HttpMethod.GET, path: '//evil.example/x', operation: 'x' })).rejects.toThrow(/Invalid NinjaPipe API path/);+ });++ it('clamps limits to 1-100', () => {+ expect(ninjapipeClient.clampLimit({ value: 0 })).toBe(1);+ expect(ninjapipeClient.clampLimit({ value: '500' })).toBe(100);+ expect(ninjapipeClient.clampLimit({ value: undefined })).toBe(20);+ });++ it('Return All stops at the last page', async () => {+ const fetchMock = stubFetch({+ responses: [+ { status: 200, body: page({ data: [{ id: '1' }], page: 1, pages: 2, total: 2 }) },+ { status: 200, body: page({ data: [{ id: '2' }], page: 2, pages: 2, total: 2 }) },+ ],+ });+ const output = await runAction({ name: 'list_contacts', propsValue: { returnAll: true } });+ expect(output).toEqual({ items: [{ id: '1' }, { id: '2' }], count: 2, total: 2, hasMore: false, nextPage: null });+ expect(request({ fetchMock, call: 1 }).query).toMatchObject({ page: '2', limit: '100' });+ });++ it('Return All is capped and reports hasMore', async () => {+ const items = Array.from({ length: 100 }, (_, index) => ({ id: String(index) }));+ stubFetch({ responses: [{ status: 200, body: page({ data: items, pages: 999, total: 99900 }) }] });+ const result = await ninjapipeClient.listAll({ auth, path: '/contacts', operation: 'list', maxItems: 250 });+ expect(result.count).toBe(250);+ expect(result.hasMore).toBe(true);+ expect(result.nextPage).toBe(4);+ });+});++describe('three-state updates and custom fields', () => {+ it('leaves blank fields out, sends null for cleared ones and merges custom fields', async () => {+ const fetchMock = stubFetch({+ responses: [+ { status: 200, body: { data: { id: ID, fields: { keep: 'yes', drop: 'old' } } } },+ { status: 200, body: { data: { id: ID } } },+ ],+ });+ await runAction({+ name: 'update_contact',+ propsValue: { contactId: ID, firstName: '', phone: undefined, customFields: { drop: '', added: 'new' }, clearFields: ['last_name'] },+ });+ expect(request({ fetchMock, call: 0 }).method).toBe('GET');+ expect(request({ fetchMock, call: 1 }).body).toEqual({ fields: { keep: 'yes', added: 'new' }, last_name: null });+ });++ it('refuses to set and clear the same field', async () => {+ stubFetch({ responses: [{ status: 200, body: {} }] });+ await expect(runAction({ name: 'update_deal', propsValue: { dealId: ID, contactId: ID, clearFields: ['contact_id'] } })).rejects.toThrow(/set and cleared/);+ });++ it('refuses an update with nothing to change', async () => {+ const fetchMock = stubFetch({ responses: [{ status: 200, body: {} }] });+ await expect(runAction({ name: 'update_order', propsValue: { orderId: ID } })).rejects.toThrow(/Nothing to update/);+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('sends 0 and false-like values instead of dropping them', async () => {+ const fetchMock = stubFetch({ responses: [{ status: 200, body: { data: { id: ID } } }] });+ await runAction({ name: 'update_product', propsValue: { productId: ID, price: 0, cost: 0 } });+ expect(request({ fetchMock }).body).toEqual({ price: 0, cost: 0 });+ });++ it('rejects non-numeric numbers before any request', async () => {+ const fetchMock = stubFetch({ responses: [{ status: 200, body: {} }] });+ await expect(runAction({ name: 'ai_create_deal', propsValue: { name: 'D', value: 'abc' } })).rejects.toThrow(/Value must be a number/);+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('create budget needs a start or end date', async () => {+ const fetchMock = stubFetch({ responses: [{ status: 200, body: {} }] });+ await expect(runAction({ name: 'create_budget', propsValue: { name: 'B', allocated: 1, category: 'Sales', period: 'Monthly' } })).rejects.toThrow(/Start Date/);+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('create pipeline rejects bad stage colors and duplicate ids', async () => {+ stubFetch({ responses: [{ status: 200, body: {} }] });+ await expect(runAction({ name: 'create_pipeline', propsValue: { name: 'P', pipelineType: 'deals', stages: [{ name: 'A', color: 'red' }] } })).rejects.toThrow(/hex/);+ await expect(runAction({ name: 'create_pipeline', propsValue: { name: 'P', pipelineType: 'deals', stages: [{ name: 'A' }, { name: 'a' }] } })).rejects.toThrow(/unique/);+ });+});++describe('contact matching', () => {+ it('upsert matches the exact email, not the first fuzzy hit, and follows pages', async () => {+ const fetchMock = stubFetch({+ responses: [+ { status: 200, body: page({ data: [{ id: 'fuzzy', email: '[email protected]' }], page: 1, pages: 2 }) },+ { status: 200, body: page({ data: [{ id: 'exact', email: '[email protected]' }], page: 2, pages: 2 }) },+ { status: 200, body: { data: { id: 'exact' } } },+ ],+ });+ const output = await runAction({ name: 'upsert_contact', propsValue: { email: '[email protected]', lastName: 'Doe' } });+ expect(output).toEqual({ action: 'updated', id: 'exact' });+ expect(request({ fetchMock, call: 0 }).query).toMatchObject({ search: '[email protected]', limit: '100', page: '1' });+ expect(request({ fetchMock, call: 2 })).toMatchObject({ method: 'PUT', path: '/contacts/exact' });+ });++ it('create contact in update-existing mode updates the 409 match', async () => {+ const fetchMock = stubFetch({+ responses: [+ { status: 409, body: { error: 'Conflict', code: 'DUPLICATE_EMAIL' } },+ { status: 200, body: page({ data: [{ id: 'c1', email: '[email protected]' }] }) },+ { status: 200, body: { data: { id: 'c1', last_name: 'Doe' } } },+ ],+ });+ const output = await runAction({ name: 'create_contact', propsValue: { email: '[email protected]', lastName: 'Doe', ifContactExists: 'updateExisting' } });+ expect(output).toEqual({ action: 'updated', id: 'c1', last_name: 'Doe' });+ expect(request({ fetchMock, call: 2 }).body).toEqual({ email: '[email protected]', last_name: 'Doe' });+ });++ it('create contact fails on a duplicate by default', async () => {+ stubFetch({ responses: [{ status: 409, body: { error: 'Conflict', message: 'Contact with this email already exists' } }] });+ await expect(runAction({ name: 'create_contact', propsValue: { email: '[email protected]' } })).rejects.toThrow(/HTTP 409/);+ });++ it('AI create contact names the existing contact on a duplicate email', async () => {+ stubFetch({+ responses: [+ { status: 409, body: { error: 'Conflict', code: 'DUPLICATE_EMAIL' } },+ { status: 200, body: page({ data: [{ id: 'c9', email: '[email protected]' }] }) },+ ],+ });+ await expect(runAction({ name: 'ai_create_contact', propsValue: { email: '[email protected]' } })).rejects.toThrow(/contact_id c9/);+ });++ it('add to list needs exactly one member', async () => {+ const fetchMock = stubFetch({ responses: [{ status: 200, body: {} }] });+ await expect(runAction({ name: 'add_to_list', propsValue: { listId: ID, contactId: 'a', companyId: 'b' } })).rejects.toThrow(/exactly one/);+ expect(fetchMock).not.toHaveBeenCalled();+ });+});++describe('send to databin', () => {+ const run = (webhookUrl: string) => runAction({ name: 'send_to_databin', propsValue: { webhookUrl, payload: { a: 1 } } });++ it.each([+ 'https://www.ninjapipe.app.evil.io/api/webhooks/x',+ 'https://evil.io/api/webhooks/x?h=www.ninjapipe.app',+ 'https://app/api/webhooks/x',+ 'http://www.ninjapipe.app/api/webhooks/x',+ 'https://user:[email protected]/api/webhooks/x',+ 'https://www.ninjapipe.app/other/x',+ ])('refuses %s', async (url) => {+ const fetchMock = stubFetch({ responses: [{ status: 200, body: {} }] });+ await expect(run(url)).rejects.toThrow(/Invalid webhook URL|does not match/);+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('posts to the exact host or its www twin without the API key', async () => {+ const fetchMock = stubFetch({ responses: [{ status: 200, body: { success: true } }] });+ const output = await run('https://ninjapipe.app/api/webhooks/abc');+ const sent = request({ fetchMock });+ expect(sent.url.toString()).toBe('https://ninjapipe.app/api/webhooks/abc');+ expect(sent.headers.get('authorization')).toBeNull();+ expect(sent.body).toEqual({ a: 1 });+ expect(output).toEqual({ status: 200, response: { success: true } });+ });++ it('accepts a subdomain of the connected host, like 0.1.1 did', async () => {+ const fetchMock = stubFetch({ responses: [{ status: 200, body: {} }] });+ await run('https://acme.ninjapipe.app/api/webhooks/abc');+ expect(request({ fetchMock }).url.toString()).toBe('https://acme.ninjapipe.app/api/webhooks/abc');+ });++ it('reports invalid JSON payloads clearly', async () => {+ stubFetch({ responses: [{ status: 200, body: {} }] });+ await expect(runAction({ name: 'send_to_databin', propsValue: { webhookUrl: 'https://www.ninjapipe.app/api/webhooks/a', payload: '{bad' } })).rejects.toThrow('Payload must be valid JSON.');+ });+});++describe('custom api call', () => {+ it.each(['https://evil.example/api/contacts', 'https://www.ninjapipe.app/other', '//evil.example/x', '/contacts/../../x'])('refuses %s', async (url) => {+ const fetchMock = stubFetch({ responses: [{ status: 200, body: {} }] });+ await expect(runAction({ name: 'custom_api_call', propsValue: { url: { url }, method: 'GET', headers: {}, queryParams: {} } })).rejects.toThrow(/URL must/);+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('is human-only with aiMetadata', () => {+ const action = ninjapipe.getAction('custom_api_call');+ expect(action?.audience).toBe('human');+ expect(action?.aiMetadata?.description).toBeTruthy();+ });+});++describe('metadata', () => {+ it('every action and trigger has an outputSchema except Custom API Call', () => {+ const missing = Object.entries(ninjapipe.actions())+ .filter(([, action]) => !action.outputSchema)+ .map(([name]) => name);+ expect(missing).toEqual(['custom_api_call']);+ expect(Object.values(ninjapipe.triggers()).every((trigger) => trigger.outputSchema)).toBe(true);+ });++ it('audience counts match the plan', () => {+ const counts: Record<string, number> = {};+ Object.values(ninjapipe.actions()).forEach((action) => {+ counts[String(action.audience)] = (counts[String(action.audience)] ?? 0) + 1;+ });+ expect(counts).toEqual({ human: 21, both: 33, ai: 23 });+ });++ it('toggle client portal stays DESTRUCTIVE and not idempotent', () => {+ const action = ninjapipe.getAction('toggle_client_portal');+ expect(action?.classification).toBe('DESTRUCTIVE');+ expect(action?.aiMetadata?.idempotent).toBe(false);+ });++ it('ai actions take IDs as text, not dropdowns', () => {+ Object.values(ninjapipe.actions())+ .filter((action) => action.audience === 'ai')+ .forEach((action) => {+ Object.values(action.props).forEach((prop) => expect(prop.type).not.toBe('DROPDOWN'));+ });+ });+});diff --git a/packages/pieces/community/ninjapipe/test/helpers.ts b/packages/pieces/community/ninjapipe/test/helpers.tsnew file mode 100644index 00000000000..e83ef065341--- /dev/null+++ b/packages/pieces/community/ninjapipe/test/helpers.ts@@ -0,0 +1,91 @@+import { vi } from 'vitest';+import { createMockActionContext } from '../../../framework/src/lib/test';+import { ninjapipe } from '../src';++export const BASE = 'https://www.ninjapipe.app/api';++export function auth() {+ return { type: 'CUSTOM_AUTH', props: { base_url: `${BASE}/`, api_key: ' np_test ' } };+}++export function jsonResponse({ status, body }: { status: number; body: unknown }) {+ return new Response(typeof body === 'string' ? body : JSON.stringify(body), {+ status,+ headers: { 'Content-Type': typeof body === 'string' ? 'text/html' : 'application/json' },+ });+}++export function stubFetch({ responses }: { responses: { status: number; body: unknown }[] }) {+ let call = 0;+ const fetchMock = vi.fn(async () => {+ const response = responses[Math.min(call, responses.length - 1)];+ call += 1;+ return jsonResponse(response);+ });+ vi.stubGlobal('fetch', fetchMock);+ return fetchMock;+}++export function request({ fetchMock, call = 0 }: { fetchMock: ReturnType<typeof vi.fn>; call?: number }) {+ const [input, init] = fetchMock.mock.calls[call] ?? [];+ const url = new URL(typeof input === 'string' ? input : String(input));+ const raw = init?.body;+ return {+ url,+ path: url.pathname.replace('/api', ''),+ query: Object.fromEntries(url.searchParams.entries()),+ method: init?.method,+ headers: new Headers(init?.headers),+ body: typeof raw === 'string' && raw.length > 0 ? JSON.parse(raw) : raw,+ };+}++export function runAction({ name, propsValue }: { name: string; propsValue: Record<string, unknown> }): Promise<unknown> {+ const action = ninjapipe.getAction(name);+ if (!action) throw new Error(`Unknown action ${name}`);+ const context = { ...createMockActionContext({ propsValue: {} }), propsValue, auth: auth() };+ return Reflect.apply(action.run, action, [context]);+}++export async function loadOptions({ action, prop, propsValue = {}, ctx = {} }: { action: string; prop: string; propsValue?: Record<string, unknown>; ctx?: Record<string, unknown> }): Promise<Record<string, unknown>> {+ const property: unknown = ninjapipe.getAction(action)?.props[prop];+ const options: unknown = typeof property === 'object' && property !== null ? Reflect.get(property, 'options') : undefined;+ if (typeof options !== 'function') throw new Error(`${action}.${prop} has no options`);+ const state: unknown = await Reflect.apply(options, property, [{ auth: auth(), ...propsValue }, ctx]);+ if (typeof state !== 'object' || state === null) throw new Error('options returned nothing');+ return Object.fromEntries(Object.entries(state));+}++export function ids(value: unknown): string[] {+ if (!Array.isArray(value)) throw new Error('expected an array');+ return value.map((item: unknown) => String(typeof item === 'object' && item !== null ? Reflect.get(item, 'id') : item));+}++export function memoryStore({ initial = {} }: { initial?: Record<string, unknown> } = {}) {+ const data = new Map<string, unknown>(Object.entries(initial));+ return {+ data,+ store: {+ put: async (key: string, value: unknown) => {+ data.set(key, value);+ return value;+ },+ get: async (key: string): Promise<unknown> => (data.has(key) ? data.get(key) : null),+ delete: async (key: string) => {+ data.delete(key);+ },+ },+ };+}++export function runHook({ name, hook, context }: { name: string; hook: 'run' | 'test' | 'onEnable'; context: Record<string, unknown> }): Promise<unknown> {+ const trigger = ninjapipe.getTrigger(name);+ if (!trigger) throw new Error(`Unknown trigger ${name}`);+ const fn: unknown = Reflect.get(trigger, hook);+ if (typeof fn !== 'function') throw new Error(`Trigger has no ${hook}`);+ return Reflect.apply(fn, trigger, [{ auth: auth(), files: { write: async () => 'file-url' }, ...context }]);+}++export function page({ data, page = 1, pages = 1, total }: { data: unknown[]; page?: number; pages?: number; total?: number }) {+ return { data, pagination: { page, limit: 100, total: total ?? data.length, pages } };+}diff --git a/packages/pieces/community/ninjapipe/test/triggers.test.ts b/packages/pieces/community/ninjapipe/test/triggers.test.tsnew file mode 100644index 00000000000..708a3432a38--- /dev/null+++ b/packages/pieces/community/ninjapipe/test/triggers.test.ts@@ -0,0 +1,172 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { ids, loadOptions, memoryStore, page, request, runHook, stubFetch } from './helpers';++const PROJECT = 'proj 1';+const T0 = Date.parse('2026-10-25T10:00:00Z');++function rec({ id, minutes, field = 'updated_at' }: { id: string; minutes: number; field?: string }) {+ return { id, name: id, title: id, created_at: new Date(T0 + minutes * 60000).toISOString(), [field]: new Date(T0 + minutes * 60000).toISOString() };+}++afterEach(() => {+ vi.unstubAllGlobals();+});++const recordTriggers = [+ { name: 'new_contact', path: '/contacts', field: 'created_at' },+ { name: 'new_company', path: '/companies', field: 'created_at' },+ { name: 'new_deal', path: '/deals', field: 'created_at' },+ { name: 'new_or_updated_contact', path: '/contacts', field: 'updated_at' },+ { name: 'new_or_updated_company', path: '/companies', field: 'updated_at' },+ { name: 'new_or_updated_deal', path: '/deals', field: 'updated_at' },+];++describe('record polling triggers', () => {+ it.each(recordTriggers)('$name sorts by $field and pages back to the checkpoint', async ({ name, path, field }) => {+ const trigger = name;+ const fetchMock = stubFetch({+ responses: [+ { status: 200, body: page({ data: [rec({ id: 'c', minutes: 30, field }), rec({ id: 'b', minutes: 20, field })], page: 1, pages: 3 }) },+ { status: 200, body: page({ data: [rec({ id: 'a', minutes: 15, field }), rec({ id: 'old', minutes: 5, field })], page: 2, pages: 3 }) },+ ],+ });+ const { store } = memoryStore({ initial: { lastPoll: T0 + 10 * 60000 } });+ const result = ids(await runHook({ name: trigger, hook: 'run', context: { store, propsValue: {} } }));+ expect(result).toEqual(['c', 'b', 'a']);+ expect(fetchMock).toHaveBeenCalledTimes(2);+ const first = request({ fetchMock, call: 0 });+ expect(first.path).toBe(path);+ expect(first.query).toMatchObject({ sort_by: field, sort_order: 'desc', limit: '100', page: '1' });+ expect(request({ fetchMock, call: 1 }).query).toMatchObject({ page: '2' });+ expect(await store.get('lastPoll')).toBe(T0 + 30 * 60000);+ });++ it('a burst larger than ten pages is read back to the checkpoint', async () => {+ const trigger = 'new_or_updated_deal';+ const pages = 12;+ const responses = Array.from({ length: pages }, (_, index) => ({+ status: 200,+ body: page({ data: [rec({ id: `p${index}`, minutes: 1000 - index })], page: index + 1, pages: pages + 1 }),+ }));+ responses.push({ status: 200, body: page({ data: [rec({ id: 'old', minutes: 5 })], page: pages + 1, pages: pages + 1 }) });+ const fetchMock = stubFetch({ responses });+ const { store } = memoryStore({ initial: { lastPoll: T0 + 10 * 60000 } });+ const result = ids(await runHook({ name: trigger, hook: 'run', context: { store, propsValue: {} } }));+ expect(result).toHaveLength(pages);+ expect(result.at(-1)).toBe(`p${pages - 1}`);+ expect(fetchMock).toHaveBeenCalledTimes(pages + 1);+ });++ it('stops with an error when paging never reaches the checkpoint', async () => {+ const fetchMock = stubFetch({ responses: [{ status: 200, body: page({ data: [rec({ id: 'loop', minutes: 1000 })], page: 1, pages: 9999 }) }] });+ const { store } = memoryStore({ initial: { lastPoll: T0 + 10 * 60000 } });+ await expect(runHook({ name: 'new_or_updated_deal', hook: 'run', context: { store, propsValue: {} } })).rejects.toThrow(/stopped after 100 pages/);+ expect(fetchMock).toHaveBeenCalledTimes(100);+ });++ it('a second poll with no changes emits nothing', async () => {+ const trigger = 'new_or_updated_deal';+ stubFetch({ responses: [{ status: 200, body: page({ data: [rec({ id: 'c', minutes: 30 })] }) }] });+ const { store } = memoryStore({ initial: { lastPoll: T0 + 30 * 60000 } });+ expect(await runHook({ name: trigger, hook: 'run', context: { store, propsValue: {} } })).toEqual([]);+ });++ it('items without a timestamp fire once, with bounded dedupe', async () => {+ const trigger = 'new_or_updated_contact';+ const untimed = { id: 'no-ts', name: 'x' };+ stubFetch({ responses: [{ status: 200, body: page({ data: [untimed] }) }] });+ const { store, data } = memoryStore({ initial: { lastPoll: T0, ninjapipe_untimed_seen_ids: Array.from({ length: 500 }, (_, index) => `old-${index}`) } });+ const first = await runHook({ name: trigger, hook: 'run', context: { store, propsValue: {} } });+ const second = await runHook({ name: trigger, hook: 'run', context: { store, propsValue: {} } });+ expect(first).toEqual([untimed]);+ expect(second).toEqual([]);+ const seen = ids(data.get('ninjapipe_untimed_seen_ids'));+ expect(seen).toHaveLength(501);+ expect(seen.at(-1)).toBe('no-ts');+ });++ it('more than 500 untimed items never fire twice', async () => {+ const trigger = 'new_or_updated_contact';+ const records = Array.from({ length: 501 }, (_, index) => ({ id: `t-${index}`, name: 'x' }));+ stubFetch({ responses: [{ status: 200, body: page({ data: records }) }] });+ const { store } = memoryStore({ initial: { lastPoll: T0 } });+ const first = await runHook({ name: trigger, hook: 'run', context: { store, propsValue: {} } });+ const second = await runHook({ name: trigger, hook: 'run', context: { store, propsValue: {} } });+ const third = await runHook({ name: trigger, hook: 'run', context: { store, propsValue: {} } });+ expect(first).toHaveLength(501);+ expect(second).toEqual([]);+ expect(third).toEqual([]);+ });++ it('test() returns untimed samples every time and leaves the remembered IDs alone', async () => {+ const trigger = 'new_or_updated_contact';+ const untimed = { id: 'no-ts', name: 'x' };+ stubFetch({ responses: [{ status: 200, body: page({ data: [untimed] }) }] });+ const { store, data } = memoryStore();+ expect(await runHook({ name: trigger, hook: 'test', context: { store, propsValue: {} } })).toEqual([untimed]);+ expect(await runHook({ name: trigger, hook: 'test', context: { store, propsValue: {} } })).toEqual([untimed]);+ expect(data.get('ninjapipe_untimed_seen_ids')).toBeUndefined();+ });++ it('test() reads one small page', async () => {+ const trigger = 'new_contact';+ const fetchMock = stubFetch({ responses: [{ status: 200, body: page({ data: [rec({ id: 'a', minutes: 1 })], pages: 9 }) }] });+ const { store } = memoryStore();+ const result = await runHook({ name: trigger, hook: 'test', context: { store, propsValue: {} } });+ expect(result).toHaveLength(1);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(request({ fetchMock }).query).toMatchObject({ limit: '5' });+ });++ it('polling errors fail instead of returning an empty list', async () => {+ const trigger = 'new_deal';+ stubFetch({ responses: [{ status: 401, body: { error: 'Unauthorized', code: 'INVALID_API_KEY' } }] });+ const { store } = memoryStore({ initial: { lastPoll: T0 } });+ await expect(runHook({ name: trigger, hook: 'run', context: { store, propsValue: {} } })).rejects.toThrow(/HTTP 401/);+ });+});++describe('task polling triggers', () => {+ it.each([+ { name: 'new_task', field: 'created_at' },+ { name: 'new_or_updated_task', field: 'updated_at' },+ ])('$name encodes the project id and emits only newer tasks', async ({ name, field }) => {+ const trigger = name;+ const fetchMock = stubFetch({ responses: [{ status: 200, body: { data: [rec({ id: 'old', minutes: 1, field }), rec({ id: 'new', minutes: 20, field })] } }] });+ const { store } = memoryStore({ initial: { lastPoll: T0 + 10 * 60000 } });+ const result = ids(await runHook({ name: trigger, hook: 'run', context: { store, propsValue: { projectId: PROJECT } } }));+ expect(result).toEqual(['new']);+ expect(request({ fetchMock }).url.pathname).toBe('/api/projects/proj%201/tasks');+ expect(request({ fetchMock }).query).toMatchObject({ sort_by: field, sort_order: 'desc' });+ });+});++describe('dropdowns', () => {+ it('show the API error instead of hiding it', async () => {+ stubFetch({ responses: [{ status: 403, body: { error: 'Forbidden', message: 'Key revoked' } }] });+ const state = await loadOptions({ action: 'get_contact', prop: 'contactId', ctx: { searchValue: undefined } });+ expect(state.disabled).toBe(true);+ expect(state.placeholder).toMatch(/Could not load contacts: .*Key revoked/);+ });++ it('follow pages and pass the search text', async () => {+ const fetchMock = stubFetch({+ responses: [+ { status: 200, body: page({ data: [{ id: '1', first_name: 'A', email: '[email protected]' }], page: 1, pages: 2 }) },+ { status: 200, body: page({ data: [{ id: '2', first_name: 'B' }], page: 2, pages: 2 }) },+ ],+ });+ const state = await loadOptions({ action: 'get_contact', prop: 'contactId', ctx: { searchValue: 'a' } });+ expect(state.options).toEqual([+ { label: 'A <[email protected]>', value: '1' },+ { label: 'B', value: '2' },+ ]);+ expect(request({ fetchMock, call: 0 }).query).toMatchObject({ search: 'a', limit: '100' });+ });++ it('stage dropdown reads the selected pipeline', async () => {+ stubFetch({ responses: [{ status: 200, body: { data: { id: 'p', stages: [{ id: 's1', name: 'Lead' }] } } }] });+ const state = await loadOptions({ action: 'create_pipeline_item', prop: 'stageId', propsValue: { pipelineId: 'p' } });+ expect(state.options).toEqual([{ label: 'Lead', value: 's1' }]);+ });+});diff --git a/packages/pieces/community/ninjapipe/vitest.config.ts b/packages/pieces/community/ninjapipe/vitest.config.tsnew file mode 100644index 00000000000..79c97261904--- /dev/null+++ b/packages/pieces/community/ninjapipe/vitest.config.ts@@ -0,0 +1,19 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ root: __dirname,+ test: {+ globals: true,+ environment: 'node',+ include: ['test/**/*.test.ts'],+ },+ resolve: {+ alias: {+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),+ },+ },+})