Skip to content

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

feat(coda): manage docs, pages, rows and sharing from flows and AI agents (#16160)

Odai Ahmad69c041a9139b
diff --git a/bun.lock b/bun.lock
index 6b77f877e17..15136e436f0 100644
--- a/bun.lock
+++ b/bun.lock
@@ -2076,7 +2076,7 @@
},
"packages/pieces/community/coda": {
"name": "@activepieces/piece-coda",
- "version": "0.2.0",
+ "version": "0.3.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -2086,6 +2086,7 @@
},
"devDependencies": {
"tslib": "2.6.2",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/cody": {
diff --git a/packages/pieces/community/coda/package.json b/packages/pieces/community/coda/package.json
index 6fa411d318d..667ca92365c 100644
--- a/packages/pieces/community/coda/package.json
+++ b/packages/pieces/community/coda/package.json
@@ -1,12 +1,13 @@
{
"name": "@activepieces/piece-coda",
- "version": "0.2.0",
+ "version": "0.3.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:*",
@@ -16,6 +17,7 @@
"@activepieces/core-utils": "workspace:*"
},
"devDependencies": {
- "tslib": "2.6.2"
+ "tslib": "2.6.2",
+ "vitest": "3.2.6"
}
}
diff --git a/packages/pieces/community/coda/src/i18n/translation.json b/packages/pieces/community/coda/src/i18n/translation.json
index 3cd78c65d48..24a3de4b82b 100644
--- a/packages/pieces/community/coda/src/i18n/translation.json
+++ b/packages/pieces/community/coda/src/i18n/translation.json
@@ -1,5 +1,5 @@
{
- "Create an API key in the [Coda Account dashboard](https://coda.io/account).": "Create an API key in the [Coda Account dashboard](https://coda.io/account).",
+ "Create an API token in Coda (now Superhuman Docs): open [Account settings](https://coda.io/account), scroll to **API settings**, click **Generate API token**, and paste it here.": "Create an API token in Coda (now Superhuman Docs): open [Account settings](https://coda.io/account), scroll to **API settings**, click **Generate API token**, and paste it here.",
"Create Row": "Create Row",
"Update Row": "Update Row",
"Upsert Row": "Upsert Row",
@@ -7,6 +7,39 @@
"Get Row": "Get Row",
"List Table(s)": "List Table(s)",
"Get Table": "Get Table",
+ "Get Current User": "Get Current User",
+ "List Docs": "List Docs",
+ "Get Doc": "Get Doc",
+ "Create Doc": "Create Doc",
+ "Rename Doc": "Rename Doc",
+ "Delete Doc": "Delete Doc",
+ "List Folders": "List Folders",
+ "List Pages": "List Pages",
+ "Get Page": "Get Page",
+ "Get Page Content": "Get Page Content",
+ "Create Page": "Create Page",
+ "Update Page": "Update Page",
+ "Delete Page": "Delete Page",
+ "List Tables (by Doc ID)": "List Tables (by Doc ID)",
+ "Get Table (by ID)": "Get Table (by ID)",
+ "List Columns": "List Columns",
+ "List Rows": "List Rows",
+ "Get Row (by ID)": "Get Row (by ID)",
+ "Add Rows": "Add Rows",
+ "Upsert Rows": "Upsert Rows",
+ "Update Row (by ID)": "Update Row (by ID)",
+ "Delete Rows": "Delete Rows",
+ "Push Button": "Push Button",
+ "List Named Formulas": "List Named Formulas",
+ "Get Named Formula": "Get Named Formula",
+ "List Controls": "List Controls",
+ "Get Control": "Get Control",
+ "Get Mutation Status": "Get Mutation Status",
+ "Resolve Coda Link": "Resolve Coda Link",
+ "List Doc Sharing": "List Doc Sharing",
+ "Share Doc": "Share Doc",
+ "Remove Doc Sharing": "Remove Doc Sharing",
+ "Trigger Automation": "Trigger Automation",
"Custom API Call": "Custom API Call",
"Creates a new row in the selected table.": "Creates a new row in the selected table.",
"Updates an existing row in the selected table.": "Updates an existing row in the selected table.",
@@ -14,7 +47,40 @@
"Find specific rows in the selected table using a column match search.": "Find specific rows in the selected table using a column match search.",
"Retrieves a single row by specified ID.": "Retrieves a single row by specified ID.",
"List tables in a selected document.": "List tables in a selected document.",
- "Get structure and details of a specific table (e.g., columns, schema).": "Get structure and details of a specific table (e.g., columns, schema).",
+ "Get the details of a specific table: name, type, row count, display column and layout.": "Get the details of a specific table: name, type, row count, display column and layout.",
+ "Returns the Coda account and workspace that the connected API token belongs to.": "Returns the Coda account and workspace that the connected API token belongs to.",
+ "Lists the docs the connected account can open, one page at a time, with optional search and filters.": "Lists the docs the connected account can open, one page at a time, with optional search and filters.",
+ "Gets the details of a doc: name, owner, links, folder, workspace and size.": "Gets the details of a doc: name, owner, links, folder, workspace and size.",
+ "Creates a new doc, either blank (optionally with a first page) or as a copy of an existing doc.": "Creates a new doc, either blank (optionally with a first page) or as a copy of an existing doc.",
+ "Changes a doc's title and/or icon.": "Changes a doc's title and/or icon.",
+ "Permanently deletes a doc. This cannot be undone through the API.": "Permanently deletes a doc. This cannot be undone through the API.",
+ "Lists the folders the connected account can see, one page at a time.": "Lists the folders the connected account can see, one page at a time.",
+ "Lists the pages of a doc, one page of results at a time.": "Lists the pages of a doc, one page of results at a time.",
+ "Gets a page's details: name, subtitle, parent, subpages, visibility and links.": "Gets a page's details: name, subtitle, parent, subpages, visibility and links.",
+ "Exports a page's content as Markdown or HTML text.": "Exports a page's content as Markdown or HTML text.",
+ "Adds a new page to a doc, optionally under a parent page and with Markdown or HTML content.": "Adds a new page to a doc, optionally under a parent page and with Markdown or HTML content.",
+ "Renames, hides or shows a page, and can append, prepend or replace its content.": "Renames, hides or shows a page, and can append, prepend or replace its content.",
+ "Deletes a page and everything on it, including its tables.": "Deletes a page and everything on it, including its tables.",
+ "Lists the tables and views in a doc, one page at a time.": "Lists the tables and views in a doc, one page at a time.",
+ "Gets a table's details by doc ID and table ID or name.": "Gets a table's details by doc ID and table ID or name.",
+ "Lists a table's columns with their IDs, names and types, one page at a time.": "Lists a table's columns with their IDs, names and types, one page at a time.",
+ "Lists rows of a table one page at a time, optionally only rows where a column equals a value.": "Lists rows of a table one page at a time, optionally only rows where a column equals a value.",
+ "Gets one row by doc ID, table ID and row ID.": "Gets one row by doc ID, table ID and row ID.",
+ "Adds one or more rows to a table, each given as column → value.": "Adds one or more rows to a table, each given as column → value.",
+ "Updates rows whose key columns match, and adds the rest as new rows.": "Updates rows whose key columns match, and adds the rest as new rows.",
+ "Changes cells of one row by row ID.": "Changes cells of one row by row ID.",
+ "Permanently deletes rows from a table by row ID.": "Permanently deletes rows from a table by row ID.",
+ "Presses a button in a table row, running whatever action the button is set up to do. If the button is disabled for that row, Coda accepts the press but nothing happens.": "Presses a button in a table row, running whatever action the button is set up to do. If the button is disabled for that row, Coda accepts the press but nothing happens.",
+ "Lists the named formulas in a doc, one page at a time.": "Lists the named formulas in a doc, one page at a time.",
+ "Gets the current value of a named formula.": "Gets the current value of a named formula.",
+ "Lists the controls (sliders, pickers, buttons…) in a doc, one page at a time.": "Lists the controls (sliders, pickers, buttons…) in a doc, one page at a time.",
+ "Gets the type and current value of a control.": "Gets the type and current value of a control.",
+ "Checks whether an earlier change (by its Request ID) has been applied by Coda.": "Checks whether an earlier change (by its Request ID) has been applied by Coda.",
+ "Finds the doc, page, table or row a Coda link points to and returns its IDs.": "Finds the doc, page, table or row a Coda link points to and returns its IDs.",
+ "Lists who a doc is shared with and their access level, one page at a time.": "Lists who a doc is shared with and their access level, one page at a time.",
+ "Shares a doc with a person (by email) or with everyone at an email domain.": "Shares a doc with a person (by email) or with everyone at an email domain.",
+ "Stops sharing a doc with a person or domain, by permission ID.": "Stops sharing a doc with a person or domain, by permission ID.",
+ "Runs a doc automation whose trigger is \"Webhook invoked\", optionally passing a JSON payload.": "Runs a doc automation whose trigger is \"Webhook invoked\", optionally passing a JSON payload.",
"Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",
"Document": "Document",
"Table": "Table",
@@ -23,30 +89,149 @@
"Matching Columns": "Matching Columns",
"Search Column": "Search Column",
"Search Value": "Search Value",
+ "Max Rows": "Max Rows",
"Max Tables": "Max Tables",
+ "Search": "Search",
+ "Only Docs I Own": "Only Docs I Own",
+ "Only Starred Docs": "Only Starred Docs",
+ "Folder ID": "Folder ID",
+ "Workspace ID": "Workspace ID",
+ "Limit": "Limit",
+ "Page Token": "Page Token",
+ "Doc ID or Link": "Doc ID or Link",
+ "Title": "Title",
+ "Copy From Doc (ID or Link)": "Copy From Doc (ID or Link)",
+ "Time Zone": "Time Zone",
+ "First Page Name": "First Page Name",
+ "First Page Content": "First Page Content",
+ "Content Format": "Content Format",
+ "Wait for Coda to Apply": "Wait for Coda to Apply",
+ "Icon Name": "Icon Name",
+ "Only Starred Folders": "Only Starred Folders",
+ "Page ID or Name": "Page ID or Name",
+ "Format": "Format",
+ "Export ID": "Export ID",
+ "Page Name": "Page Name",
+ "Subtitle": "Subtitle",
+ "Parent Page ID": "Parent Page ID",
+ "Content": "Content",
+ "New Page Name": "New Page Name",
+ "New Subtitle": "New Subtitle",
+ "New Icon Name": "New Icon Name",
+ "Visibility": "Visibility",
+ "Content Placement": "Content Placement",
+ "Include": "Include",
+ "Table ID or Name": "Table ID or Name",
+ "Visible Columns Only": "Visible Columns Only",
+ "Filter Column": "Filter Column",
+ "Filter Value": "Filter Value",
+ "Sort By": "Sort By",
+ "Key Values by Column Name": "Key Values by Column Name",
+ "Value Format": "Value Format",
+ "Row ID": "Row ID",
+ "Rows": "Rows",
+ "Store Values Exactly as Given": "Store Values Exactly as Given",
+ "Key Columns": "Key Columns",
+ "Cells": "Cells",
+ "Row IDs": "Row IDs",
+ "Button Column ID or Name": "Button Column ID or Name",
+ "Formula ID or Name": "Formula ID or Name",
+ "Control ID or Name": "Control ID or Name",
+ "Request ID": "Request ID",
+ "Link": "Link",
+ "Share With": "Share With",
+ "Email or Domain": "Email or Domain",
+ "Access": "Access",
+ "Do Not Send Notification Email": "Do Not Send Notification Email",
+ "Permission ID": "Permission ID",
+ "Automation Rule ID": "Automation Rule ID",
+ "Payload": "Payload",
"Method": "Method",
"Headers": "Headers",
"Query Parameters": "Query Parameters",
"Body Type": "Body Type",
"Body": "Body",
- "Response is Binary ?": "Response is Binary ?",
- "No Error on Failure": "No Error on Failure",
- "Timeout (in seconds)": "Timeout (in seconds)",
+ "Response is Binary": "Response is Binary",
+ "Return Error as Output": "Return Error as Output",
+ "Timeout": "Timeout",
"Follow redirects": "Follow redirects",
"Define the data for the new row based on table columns.": "Define the data for the new row based on table columns.",
+ "Rows whose column equals this value are returned.": "Rows whose column equals this value are returned.",
+ "Stop after this many matching rows. Leave empty to return every match.": "Stop after this many matching rows. Leave empty to return every match.",
"Maximum number of results to return.": "Maximum number of results to return.",
+ "Only docs whose name contains this text.": "Only docs whose name contains this text.",
+ "Only docs in this folder (starts with \"fl-\"). Use List Folders to find it.": "Only docs in this folder (starts with \"fl-\"). Use List Folders to find it.",
+ "Only docs in this workspace (starts with \"ws-\").": "Only docs in this workspace (starts with \"ws-\").",
+ "How many items to return in this page (1-100).": "How many items to return in this page (1-100).",
+ "Leave empty for the first page. To get the next page, pass the Next Page Token from the previous result.": "Leave empty for the first page. To get the next page, pass the Next Page Token from the previous result.",
+ "The doc ID (for example AbC123xyZ) or the doc's browser link. Use List Docs to find it.": "The doc ID (for example AbC123xyZ) or the doc's browser link. Use List Docs to find it.",
+ "Optional. The doc to copy. Leave empty to create a blank doc.": "Optional. The doc to copy. Leave empty to create a blank doc.",
+ "Optional folder for the new doc (starts with \"fl-\"). Defaults to your \"My docs\" folder. Use List Folders to find it.": "Optional folder for the new doc (starts with \"fl-\"). Defaults to your \"My docs\" folder. Use List Folders to find it.",
+ "Optional, for example America/New_York.": "Optional, for example America/New_York.",
+ "Optional. Only used for a blank doc.": "Optional. Only used for a blank doc.",
+ "Coda applies changes in the background. When on, the step waits up to 30 seconds until the change is applied; if it takes longer, the step still succeeds with Completed = false and you can check later with Get Mutation Status.": "Coda applies changes in the background. When on, the step waits up to 30 seconds until the change is applied; if it takes longer, the step still succeeds with Completed = false and you can check later with Get Mutation Status.",
+ "A Coda icon name, for example \"rocket\".": "A Coda icon name, for example \"rocket\".",
+ "Only folders in this workspace (starts with \"ws-\").": "Only folders in this workspace (starts with \"ws-\").",
+ "The page ID (starts with \"canvas-\") or its exact name. Use List Pages to find it.": "The page ID (starts with \"canvas-\") or its exact name. Use List Pages to find it.",
+ "Leave empty. Only fill it to resume an export that returned Completed = false earlier.": "Leave empty. Only fill it to resume an export that returned Completed = false earlier.",
+ "Optional. Creates the page as a subpage of this page.": "Optional. Creates the page as a subpage of this page.",
+ "Hiding pages needs a paid Coda plan.": "Hiding pages needs a paid Coda plan.",
+ "Optional content to add to the page.": "Optional content to add to the page.",
+ "Where the content goes. Replace overwrites everything on the page.": "Where the content goes. Replace overwrites everything on the page.",
+ "The table ID (starts with \"grid-\" or \"table-\") or its exact name. IDs are safer: names can change or repeat. Use List Tables to find it.": "The table ID (starts with \"grid-\" or \"table-\") or its exact name. IDs are safer: names can change or repeat. Use List Tables to find it.",
+ "Optional column ID or name. Only rows where this column equals Filter Value are returned.": "Optional column ID or name. Only rows where this column equals Filter Value are returned.",
+ "The value the Filter Column must equal. Required when Filter Column is set.": "The value the Filter Column must equal. Required when Filter Column is set.",
+ "When off, values are keyed by column ID, which does not change if a column is renamed.": "When off, values are keyed by column ID, which does not change if a column is renamed.",
+ "How many items to return in this page (1-500).": "How many items to return in this page (1-500).",
+ "The row ID (starts with \"i-\"), for example from List Rows. A display-column value also works, but if several rows share it Coda picks one at random.": "The row ID (starts with \"i-\"), for example from List Rows. A display-column value also works, but if several rows share it Coda picks one at random.",
+ "A list of rows, each an object of column name or ID → value. Example: [{\"Name\": \"Ada\", \"Amount\": 5, \"Done\": false}]": "A list of rows, each an object of column name or ID → value. Example: [{\"Name\": \"Ada\", \"Amount\": 5, \"Done\": false}]",
+ "When on, Coda does not convert text like \"5\" or \"2026-01-31\" into numbers or dates.": "When on, Coda does not convert text like \"5\" or \"2026-01-31\" into numbers or dates.",
+ "Column names or IDs that identify a row, for example Email.": "Column names or IDs that identify a row, for example Email.",
+ "A list of rows, each an object of column name or ID → value, including every key column. Example: [{\"Email\": \"[email protected]\", \"Amount\": 5}]": "A list of rows, each an object of column name or ID → value, including every key column. Example: [{\"Email\": \"[email protected]\", \"Amount\": 5}]",
+ "Object of column name or ID → new value. Use null or \"\" to clear a cell. Example: {\"Status\": \"Closed\", \"Notes\": null}": "Object of column name or ID → new value. Use null or \"\" to clear a cell. Example: {\"Status\": \"Closed\", \"Notes\": null}",
+ "IDs of the rows to delete (they start with \"i-\").": "IDs of the rows to delete (they start with \"i-\").",
+ "The button column (List Columns shows it with type \"button\").": "The button column (List Columns shows it with type \"button\").",
+ "The formula ID (starts with \"f-\") or its exact name.": "The formula ID (starts with \"f-\") or its exact name.",
+ "The control ID (starts with \"ctrl-\") or its exact name.": "The control ID (starts with \"ctrl-\") or its exact name.",
+ "The Request ID returned by a previous Coda step.": "The Request ID returned by a previous Coda step.",
+ "A coda.io or docs.superhuman.com link copied from the browser.": "A coda.io or docs.superhuman.com link copied from the browser.",
+ "For a person: their email, for example [email protected]. For a domain: example.com.": "For a person: their email, for example [email protected]. For a domain: example.com.",
+ "From List Doc Sharing or Share Doc.": "From List Doc Sharing or Share Doc.",
+ "In the doc, open Automations, pick the rule with the \"Webhook invoked\" trigger, and copy its rule ID (it looks like grid-auto-xxxx).": "In the doc, open Automations, pick the rule with the \"Webhook invoked\" trigger, and copy its rule ID (it looks like grid-auto-xxxx).",
+ "Optional JSON object the automation can read as its webhook payload.": "Optional JSON object the automation can read as its webhook payload.",
"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.",
+ "Markdown": "Markdown",
+ "HTML": "HTML",
+ "Hide page": "Hide page",
+ "Show page": "Show page",
+ "Append to the end": "Append to the end",
+ "Prepend to the start": "Prepend to the start",
+ "Replace the whole page": "Replace the whole page",
+ "Tables only": "Tables only",
+ "Views only": "Views only",
+ "Tables and views": "Tables and views",
+ "Table order": "Table order",
+ "Created time (oldest first)": "Created time (oldest first)",
+ "Updated time (oldest first)": "Updated time (oldest first)",
+ "Simple (lists as arrays)": "Simple (lists as arrays)",
+ "Simple (lists as text)": "Simple (lists as text)",
+ "Rich (links, people, currency as objects)": "Rich (links, people, currency as objects)",
+ "A person (email)": "A person (email)",
+ "Everyone at a domain": "Everyone at a domain",
+ "Can view": "Can view",
+ "Can comment": "Can comment",
+ "Can edit": "Can edit",
"GET": "GET",
"POST": "POST",
"PATCH": "PATCH",
"PUT": "PUT",
"DELETE": "DELETE",
"HEAD": "HEAD",
- "None": "None",
- "JSON": "JSON",
- "Form Data": "Form Data",
- "Raw": "Raw",
"New Row Created": "New Row Created",
"Triggers when a new row is added to the selected table.": "Triggers when a new row is added to the selected table."
}
\ No newline at end of file
diff --git a/packages/pieces/community/coda/src/index.ts b/packages/pieces/community/coda/src/index.ts
index 344b0d725ed..ef60c27a97c 100644
--- a/packages/pieces/community/coda/src/index.ts
+++ b/packages/pieces/community/coda/src/index.ts
@@ -1,23 +1,56 @@
-import { PieceAuth, createPiece } from '@activepieces/pieces-framework';
+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';
+import { createCustomApiCallAction } from '@activepieces/pieces-common';
+import { codaAuth } from './lib/auth';
+import { CODA_BASE_URL, codaApi } from './lib/common/client';
import { findRowAction } from './lib/actions/find-row';
import { createRowAction } from './lib/actions/create-row';
import { upsertRowAction } from './lib/actions/upsert-row';
import { updateRowAction } from './lib/actions/update-row';
-import { newRowCreatedTrigger } from './lib/triggers/new-row-created';
-import { PieceCategory } from '@activepieces/pieces-framework';
import { getRowAction } from './lib/actions/get-row';
import { listTablesAction } from './lib/actions/list-tables';
import { getTableAction } from './lib/actions/get-table';
-import { createCustomApiCallAction } from '@activepieces/pieces-common';
-import { CODA_BASE_URL } from './lib/common/types';
-import { codaAuth } from './lib/auth';
+import { getCurrentUserAction } from './lib/actions/get-current-user';
+import { listDocsAction } from './lib/actions/list-docs';
+import { getDocAction } from './lib/actions/get-doc';
+import { createDocAction } from './lib/actions/create-doc';
+import { deleteDocAction } from './lib/actions/delete-doc';
+import { listFoldersAction } from './lib/actions/list-folders';
+import { listPagesAction } from './lib/actions/list-pages';
+import { getPageAction } from './lib/actions/get-page';
+import { createPageAction } from './lib/actions/create-page';
+import { updatePageAction } from './lib/actions/update-page';
+import { deletePageAction } from './lib/actions/delete-page';
+import { getPageContentAction } from './lib/actions/get-page-content';
+import { listColumnsAction } from './lib/actions/list-columns';
+import { listRowsAction } from './lib/actions/list-rows';
+import { createRowsAction } from './lib/actions/create-rows';
+import { upsertRowsAction } from './lib/actions/upsert-rows';
+import { deleteRowsAction } from './lib/actions/delete-rows';
+import { pushButtonAction } from './lib/actions/push-button';
+import { listFormulasAction } from './lib/actions/list-formulas';
+import { getFormulaAction } from './lib/actions/get-formula';
+import { listControlsAction } from './lib/actions/list-controls';
+import { getControlAction } from './lib/actions/get-control';
+import { getMutationStatusAction } from './lib/actions/get-mutation-status';
+import { listPermissionsAction } from './lib/actions/list-permissions';
+import { addPermissionAction } from './lib/actions/add-permission';
+import { removePermissionAction } from './lib/actions/remove-permission';
+import { triggerAutomationAction } from './lib/actions/trigger-automation';
+import { updateDocAction } from './lib/actions/ai/update-doc';
+import { listDocTablesAction } from './lib/actions/ai/list-doc-tables';
+import { getTableByIdAction } from './lib/actions/ai/get-table-by-id';
+import { getRowByIdAction } from './lib/actions/ai/get-row-by-id';
+import { updateRowByIdAction } from './lib/actions/ai/update-row-by-id';
+import { resolveBrowserLinkAction } from './lib/actions/ai/resolve-browser-link';
+import { newRowCreatedTrigger } from './lib/triggers/new-row-created';
export const coda = createPiece({
displayName: 'Coda',
logoUrl: 'https://cdn.activepieces.com/pieces/coda.png',
categories: [PieceCategory.PRODUCTIVITY],
+ minimumSupportedRelease: '0.88.2',
auth: codaAuth,
- authors: ['onyedikachi-david', 'kishanprmr','rimjhimyadav'],
+ authors: ['onyedikachi-david', 'kishanprmr', 'rimjhimyadav'],
actions: [
createRowAction,
updateRowAction,
@@ -26,14 +59,44 @@ export const coda = createPiece({
getRowAction,
listTablesAction,
getTableAction,
+ getCurrentUserAction,
+ listDocsAction,
+ getDocAction,
+ createDocAction,
+ updateDocAction,
+ deleteDocAction,
+ listFoldersAction,
+ listPagesAction,
+ getPageAction,
+ getPageContentAction,
+ createPageAction,
+ updatePageAction,
+ deletePageAction,
+ listDocTablesAction,
+ getTableByIdAction,
+ listColumnsAction,
+ listRowsAction,
+ getRowByIdAction,
+ createRowsAction,
+ upsertRowsAction,
+ updateRowByIdAction,
+ deleteRowsAction,
+ pushButtonAction,
+ listFormulasAction,
+ getFormulaAction,
+ listControlsAction,
+ getControlAction,
+ getMutationStatusAction,
+ resolveBrowserLinkAction,
+ listPermissionsAction,
+ addPermissionAction,
+ removePermissionAction,
+ triggerAutomationAction,
createCustomApiCallAction({
- auth:codaAuth,
- baseUrl:()=>CODA_BASE_URL,
- authMapping: async (auth) => ({
- Authorization: `Bearer ${auth.secret_text}`,
- }),
-
- })
+ auth: codaAuth,
+ baseUrl: () => CODA_BASE_URL,
+ authMapping: async (auth) => codaApi.authHeaders(auth.secret_text),
+ }),
],
triggers: [newRowCreatedTrigger],
});
diff --git a/packages/pieces/community/coda/src/lib/actions/add-permission.ts b/packages/pieces/community/coda/src/lib/actions/add-permission.ts
new file mode 100644
index 00000000000..356756f0b0f
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/add-permission.ts
@@ -0,0 +1,103 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../auth';
+import { codaApi } from '../common/client';
+import { codaProps } from '../common/ai-props';
+import { SharePrincipal, codaPermissions } from '../common/permissions';
+import { addPermissionActionOutputSchema } from '../output-schemas';
+
+const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+const DOMAIN_PATTERN = /^(?=.{1,253}$)([a-z0-9-]+\.)+[a-z]{2,}$/i;
+
+export const addPermissionAction = createAction({
+ auth: codaAuth,
+ name: 'add_permission',
+ classification: 'WRITE',
+ displayName: 'Share Doc',
+ description: 'Shares a doc with a person (by email) or with everyone at an email domain.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Shares a Coda doc with one email address or one email domain at readonly, comment or write access, optionally without the notification email. Use only when the user asks to share the doc with that person or domain; public or workspace-wide sharing is not offered. Sharing again with the same person updates the same entry, so it is idempotent.',
+ idempotent: true,
+ },
+ props: {
+ docId: codaProps.docId(),
+ principalType: Property.StaticDropdown({
+ displayName: 'Share With',
+ required: true,
+ defaultValue: 'email',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'A person (email)', value: 'email' },
+ { label: 'Everyone at a domain', value: 'domain' },
+ ],
+ },
+ }),
+ principal: Property.ShortText({
+ displayName: 'Email or Domain',
+ description: 'For a person: their email, for example [email protected]. For a domain: example.com.',
+ required: true,
+ }),
+ access: Property.StaticDropdown({
+ displayName: 'Access',
+ required: true,
+ defaultValue: 'readonly',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Can view', value: 'readonly' },
+ { label: 'Can comment', value: 'comment' },
+ { label: 'Can edit', value: 'write' },
+ ],
+ },
+ }),
+ suppressEmail: Property.Checkbox({
+ displayName: 'Do Not Send Notification Email',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ outputSchema: addPermissionActionOutputSchema,
+ async run(context) {
+ const { docId, principalType, principal, access, suppressEmail } = context.propsValue;
+ const value = principal.trim();
+ const target = toPrincipal({ type: principalType, value });
+ if (!['readonly', 'comment', 'write'].includes(access)) {
+ throw new Error('Access must be readonly, comment or write.');
+ }
+ const token = context.auth.secret_text;
+ const id = codaApi.parseDocId(docId);
+ await codaApi.request({
+ token,
+ method: HttpMethod.POST,
+ path: `${codaApi.docPath(id)}/acl/permissions`,
+ operation: 'share doc',
+ body: { access, principal: target, suppressEmail: suppressEmail === true },
+ });
+ const permission = await codaPermissions.findPermission({ token, docId: id, principal: target });
+ return {
+ docId: id,
+ permissionId: permission?.id ?? null,
+ principalType: target.type,
+ principal: value,
+ access: permission?.access ?? access,
+ };
+ },
+});
+
+function toPrincipal({ type, value }: { type: string; value: string }): SharePrincipal {
+ if (type === 'email') {
+ if (!EMAIL_PATTERN.test(value)) {
+ throw new Error(`"${value}" is not a valid email address.`);
+ }
+ return { type: 'email', email: value };
+ }
+ if (type === 'domain') {
+ if (!DOMAIN_PATTERN.test(value)) {
+ throw new Error(`"${value}" is not a valid domain, for example example.com.`);
+ }
+ return { type: 'domain', domain: value };
+ }
+ throw new Error('Share With must be "email" or "domain".');
+}
diff --git a/packages/pieces/community/coda/src/lib/actions/ai/get-row-by-id.ts b/packages/pieces/community/coda/src/lib/actions/ai/get-row-by-id.ts
new file mode 100644
index 00000000000..75666c57044
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/ai/get-row-by-id.ts
@@ -0,0 +1,48 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../../auth';
+import { codaApi } from '../../common/client';
+import { codaProps } from '../../common/ai-props';
+import { getRowActionOutputSchema } from '../../output-schemas';
+
+export const getRowByIdAction = createAction({
+ auth: codaAuth,
+ name: 'get_row_by_id',
+ classification: 'READ',
+ displayName: 'Get Row (by ID)',
+ description: 'Gets one row by doc ID, table ID and row ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Returns one Coda row with its values keyed by column name, given the doc, table and row ID. Use when you already have the row ID (from List Rows or a write); use List Rows to search by value. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ docId: codaProps.docId(),
+ tableIdOrName: codaProps.tableIdOrName(),
+ rowIdOrName: codaProps.rowIdOrName(),
+ valueFormat: Property.StaticDropdown({
+ displayName: 'Value Format',
+ required: false,
+ defaultValue: 'simpleWithArrays',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Simple (lists as arrays)', value: 'simpleWithArrays' },
+ { label: 'Simple (lists as text)', value: 'simple' },
+ { label: 'Rich (links, people, currency as objects)', value: 'rich' },
+ ],
+ },
+ }),
+ },
+ outputSchema: getRowActionOutputSchema,
+ async run(context) {
+ const { docId, tableIdOrName, rowIdOrName, valueFormat } = context.propsValue;
+ return codaApi.request({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: `${codaApi.tablePath({ docId, tableIdOrName })}/rows/${codaApi.pathSegment({ value: rowIdOrName, label: 'Row ID' })}`,
+ operation: 'get row',
+ query: { useColumnNames: true, valueFormat: valueFormat ?? 'simpleWithArrays' },
+ });
+ },
+});
diff --git a/packages/pieces/community/coda/src/lib/actions/ai/get-table-by-id.ts b/packages/pieces/community/coda/src/lib/actions/ai/get-table-by-id.ts
new file mode 100644
index 00000000000..302b1d58cc1
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/ai/get-table-by-id.ts
@@ -0,0 +1,33 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../../auth';
+import { codaApi } from '../../common/client';
+import { codaProps } from '../../common/ai-props';
+import { getTableActionOutputSchema } from '../../output-schemas';
+
+export const getTableByIdAction = createAction({
+ auth: codaAuth,
+ name: 'get_table_by_id',
+ classification: 'READ',
+ displayName: 'Get Table (by ID)',
+ description: 'Gets a table\'s details by doc ID and table ID or name.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Returns one Coda table\'s metadata (name, type, row count, display column, page, link) by doc ID and table ID or name. It does not return columns; use List Columns for those. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ docId: codaProps.docId(),
+ tableIdOrName: codaProps.tableIdOrName(),
+ },
+ outputSchema: getTableActionOutputSchema,
+ async run(context) {
+ const { docId, tableIdOrName } = context.propsValue;
+ return codaApi.request({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: codaApi.tablePath({ docId, tableIdOrName }),
+ operation: 'get table',
+ });
+ },
+});
diff --git a/packages/pieces/community/coda/src/lib/actions/ai/list-doc-tables.ts b/packages/pieces/community/coda/src/lib/actions/ai/list-doc-tables.ts
new file mode 100644
index 00000000000..bd11fefb763
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/ai/list-doc-tables.ts
@@ -0,0 +1,53 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../../auth';
+import { CodaPage, codaApi } from '../../common/client';
+import { codaProps } from '../../common/ai-props';
+import { listDocTablesActionOutputSchema } from '../../output-schemas';
+
+export const listDocTablesAction = createAction({
+ auth: codaAuth,
+ name: 'list_doc_tables',
+ classification: 'SEARCH',
+ displayName: 'List Tables (by Doc ID)',
+ description: 'Lists the tables and views in a doc, one page at a time.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Lists the tables (and optionally views) in a Coda doc given its ID or link, with each table ID, name, type and page, one page at a time. Use to find a table ID before List Columns or List Rows; pass Next Page Token to continue. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ docId: codaProps.docId(),
+ tableTypes: Property.StaticDropdown({
+ displayName: 'Include',
+ required: false,
+ defaultValue: 'table',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Tables only', value: 'table' },
+ { label: 'Views only', value: 'view' },
+ { label: 'Tables and views', value: 'table,view' },
+ ],
+ },
+ }),
+ limit: codaProps.limit({ max: 100, defaultValue: 25 }),
+ pageToken: codaProps.pageToken(),
+ },
+ outputSchema: listDocTablesActionOutputSchema,
+ async run(context) {
+ const { docId, tableTypes, limit, pageToken } = context.propsValue;
+ const page = await codaApi.request<CodaPage<unknown>>({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: `${codaApi.docPath(docId)}/tables`,
+ operation: 'list tables',
+ query: {
+ tableTypes: tableTypes ?? 'table',
+ limit: codaApi.validateLimit({ limit, max: 100 }),
+ pageToken: pageToken?.trim(),
+ },
+ });
+ return codaApi.toPageOutput(page);
+ },
+});
diff --git a/packages/pieces/community/coda/src/lib/actions/ai/resolve-browser-link.ts b/packages/pieces/community/coda/src/lib/actions/ai/resolve-browser-link.ts
new file mode 100644
index 00000000000..de394150221
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/ai/resolve-browser-link.ts
@@ -0,0 +1,67 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../../auth';
+import { codaApi } from '../../common/client';
+import { resolveBrowserLinkActionOutputSchema } from '../../output-schemas';
+
+export const resolveBrowserLinkAction = createAction({
+ auth: codaAuth,
+ name: 'resolve_browser_link',
+ classification: 'READ',
+ displayName: 'Resolve Coda Link',
+ description: 'Finds the doc, page, table or row a Coda link points to and returns its IDs.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Turns a Coda / Superhuman Docs URL into the object it points to (doc, page, table, row, column…) with its ID and the doc and table IDs. Use first whenever the user gives a link instead of IDs. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ url: Property.ShortText({
+ displayName: 'Link',
+ description: 'A coda.io or docs.superhuman.com link copied from the browser.',
+ required: true,
+ }),
+ },
+ outputSchema: resolveBrowserLinkActionOutputSchema,
+ async run(context) {
+ const url = context.propsValue.url.trim();
+ if (!/^https:\/\/([a-z0-9-]+\.)*(coda\.io|docs\.superhuman\.com)\//i.test(url)) {
+ throw new Error('Link must be a https://coda.io or https://docs.superhuman.com URL.');
+ }
+ const response = await codaApi.request<ResolvedLink>({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: '/resolveBrowserLink',
+ operation: 'resolve link',
+ query: { url, degradeGracefully: true },
+ });
+ const resource = response.resource ?? {};
+ const ids = idsFromApiHref(resource.href);
+ return {
+ resourceType: resource.type ?? null,
+ id: resource.id ?? null,
+ name: resource.name ?? null,
+ docId: ids.docId,
+ tableId: ids.tableId,
+ browserLink: response.browserLink ?? url,
+ };
+ },
+});
+
+function idsFromApiHref(href: string | undefined): { docId: string | null; tableId: string | null } {
+ const match = href ? /\/docs\/([^/?#]+)(?:\/tables\/([^/?#]+))?/.exec(href) : null;
+ return {
+ docId: match?.[1] ? decodeURIComponent(match[1]) : null,
+ tableId: match?.[2] ? decodeURIComponent(match[2]) : null,
+ };
+}
+
+type ResolvedLink = {
+ browserLink?: string;
+ resource?: {
+ type?: string;
+ id?: string;
+ name?: string;
+ href?: string;
+ };
+};
diff --git a/packages/pieces/community/coda/src/lib/actions/ai/update-doc.ts b/packages/pieces/community/coda/src/lib/actions/ai/update-doc.ts
new file mode 100644
index 00000000000..d5f766f229a
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/ai/update-doc.ts
@@ -0,0 +1,52 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../../auth';
+import { codaApi } from '../../common/client';
+import { codaProps } from '../../common/ai-props';
+import { updateDocActionOutputSchema } from '../../output-schemas';
+
+export const updateDocAction = createAction({
+ auth: codaAuth,
+ name: 'update_doc',
+ classification: 'WRITE',
+ displayName: 'Rename Doc',
+ description: 'Changes a doc\'s title and/or icon.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Renames a Coda doc and/or changes its icon, by doc ID or link. Give at least one of Title or Icon Name. Requires the Doc Maker role. Setting the same values again changes nothing, so it is idempotent.',
+ idempotent: true,
+ },
+ props: {
+ docId: codaProps.docId(),
+ title: Property.ShortText({
+ displayName: 'Title',
+ required: false,
+ }),
+ iconName: Property.ShortText({
+ displayName: 'Icon Name',
+ description: 'A Coda icon name, for example "rocket".',
+ required: false,
+ }),
+ },
+ outputSchema: updateDocActionOutputSchema,
+ async run(context) {
+ const { docId, title, iconName } = context.propsValue;
+ const newTitle = title?.trim();
+ const newIcon = iconName?.trim();
+ if (!newTitle && !newIcon) {
+ throw new Error('Provide a Title or an Icon Name to change.');
+ }
+ const id = codaApi.parseDocId(docId);
+ await codaApi.request({
+ token: context.auth.secret_text,
+ method: HttpMethod.PATCH,
+ path: codaApi.docPath(id),
+ operation: 'update doc',
+ body: {
+ ...(newTitle ? { title: newTitle } : {}),
+ ...(newIcon ? { iconName: newIcon } : {}),
+ },
+ });
+ return { id, title: newTitle ?? null, iconName: newIcon ?? null };
+ },
+});
diff --git a/packages/pieces/community/coda/src/lib/actions/ai/update-row-by-id.ts b/packages/pieces/community/coda/src/lib/actions/ai/update-row-by-id.ts
new file mode 100644
index 00000000000..9fbe9d5e9b5
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/ai/update-row-by-id.ts
@@ -0,0 +1,53 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../../auth';
+import { codaApi } from '../../common/client';
+import { codaProps } from '../../common/ai-props';
+import { rowInput } from '../../common/row-input';
+import { updateRowByIdActionOutputSchema } from '../../output-schemas';
+
+export const updateRowByIdAction = createAction({
+ auth: codaAuth,
+ name: 'update_row_by_id',
+ classification: 'WRITE',
+ displayName: 'Update Row (by ID)',
+ description: 'Changes cells of one row by row ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Changes cells of one Coda row by row ID; columns you leave out stay as they are, and null or "" clears a cell. Use after List Rows or Get Row; calculated columns cannot be written. Setting the same values again changes nothing, so it is idempotent.',
+ idempotent: true,
+ },
+ props: {
+ docId: codaProps.docId(),
+ tableIdOrName: codaProps.tableIdOrName(),
+ rowIdOrName: codaProps.rowIdOrName(),
+ cells: Property.Json({
+ displayName: 'Cells',
+ description: 'Object of column name or ID → new value. Use null or "" to clear a cell. Example: {"Status": "Closed", "Notes": null}',
+ required: true,
+ defaultValue: { Name: 'New value' },
+ }),
+ disableParsing: Property.Checkbox({
+ displayName: 'Store Values Exactly as Given',
+ required: false,
+ defaultValue: false,
+ }),
+ waitForCompletion: codaProps.waitForCompletion(),
+ },
+ outputSchema: updateRowByIdActionOutputSchema,
+ async run(context) {
+ const { docId, tableIdOrName, rowIdOrName, cells, disableParsing, waitForCompletion } = context.propsValue;
+ const edits = rowInput.updateCells(rowInput.toRecord({ value: cells, label: 'Cells' }));
+ const token = context.auth.secret_text;
+ const response = await codaApi.request<{ requestId?: string; id?: string }>({
+ token,
+ method: HttpMethod.PUT,
+ path: `${codaApi.tablePath({ docId, tableIdOrName })}/rows/${codaApi.pathSegment({ value: rowIdOrName, label: 'Row ID' })}`,
+ operation: 'update row',
+ query: { disableParsing: disableParsing === true ? true : undefined },
+ body: { row: { cells: edits } },
+ });
+ const mutation = await codaApi.settleMutation({ token, requestId: response.requestId, waitForCompletion });
+ return { id: response.id ?? rowIdOrName, ...mutation };
+ },
+});
diff --git a/packages/pieces/community/coda/src/lib/actions/create-doc.ts b/packages/pieces/community/coda/src/lib/actions/create-doc.ts
new file mode 100644
index 00000000000..b62415b8cfd
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/create-doc.ts
@@ -0,0 +1,96 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../auth';
+import { codaApi } from '../common/client';
+import { codaProps } from '../common/ai-props';
+import { createDocActionOutputSchema } from '../output-schemas';
+
+export const createDocAction = createAction({
+ auth: codaAuth,
+ name: 'create_doc',
+ classification: 'WRITE',
+ displayName: 'Create Doc',
+ description: 'Creates a new doc, either blank (optionally with a first page) or as a copy of an existing doc.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Creates a new Coda doc, blank with an optional first page of Markdown/HTML, or as a full copy of a source doc (tables, formulas and buttons included). Use a copy when a template doc already has the tables you need, since tables cannot be created through the API. Requires the Doc Maker role. Not idempotent: each call creates another doc.',
+ idempotent: false,
+ },
+ props: {
+ title: Property.ShortText({
+ displayName: 'Title',
+ required: true,
+ }),
+ sourceDoc: Property.ShortText({
+ displayName: 'Copy From Doc (ID or Link)',
+ description: 'Optional. The doc to copy. Leave empty to create a blank doc.',
+ required: false,
+ }),
+ folderId: Property.ShortText({
+ displayName: 'Folder ID',
+ description: 'Optional folder for the new doc (starts with "fl-"). Defaults to your "My docs" folder. Use List Folders to find it.',
+ required: false,
+ }),
+ timezone: Property.ShortText({
+ displayName: 'Time Zone',
+ description: 'Optional, for example America/New_York.',
+ required: false,
+ }),
+ pageName: Property.ShortText({
+ displayName: 'First Page Name',
+ description: 'Optional. Only used for a blank doc.',
+ required: false,
+ }),
+ pageContent: Property.LongText({
+ displayName: 'First Page Content',
+ description: 'Optional. Only used for a blank doc.',
+ required: false,
+ }),
+ contentFormat: codaProps.contentFormat(),
+ waitForCompletion: codaProps.waitForCompletion(),
+ },
+ outputSchema: createDocActionOutputSchema,
+ async run(context) {
+ const { title, sourceDoc, folderId, timezone, pageName, pageContent, contentFormat, waitForCompletion } = context.propsValue;
+ if (!title || title.trim().length === 0) {
+ throw new Error('Title is required.');
+ }
+ const copyFrom = sourceDoc && sourceDoc.trim().length > 0 ? codaApi.parseDocId(sourceDoc) : undefined;
+ if (copyFrom && (pageName?.trim() || pageContent?.trim())) {
+ throw new Error('First Page Name and First Page Content only apply to a blank doc. Leave them empty when copying a doc.');
+ }
+ const initialPage =
+ !copyFrom && (pageName?.trim() || pageContent?.trim())
+ ? {
+ name: pageName?.trim() || title.trim(),
+ ...(pageContent?.trim()
+ ? { pageContent: { type: 'canvas', canvasContent: { format: contentFormat ?? 'markdown', content: pageContent } } }
+ : {}),
+ }
+ : undefined;
+ const token = context.auth.secret_text;
+ const doc = await codaApi.request<CreatedDoc>({
+ token,
+ method: HttpMethod.POST,
+ path: '/docs',
+ operation: 'create doc',
+ body: {
+ title: title.trim(),
+ ...(copyFrom ? { sourceDoc: copyFrom } : {}),
+ ...(folderId?.trim() ? { folderId: folderId.trim() } : {}),
+ ...(timezone?.trim() ? { timezone: timezone.trim() } : {}),
+ ...(initialPage ? { initialPage } : {}),
+ },
+ });
+ const mutation = doc.requestId
+ ? await codaApi.settleMutation({ token, requestId: doc.requestId, waitForCompletion })
+ : { requestId: null, completed: true, warning: null };
+ return { ...doc, ...mutation };
+ },
+});
+
+type CreatedDoc = {
+ id: string;
+ requestId?: string;
+ [key: string]: unknown;
+};
diff --git a/packages/pieces/community/coda/src/lib/actions/create-page.ts b/packages/pieces/community/coda/src/lib/actions/create-page.ts
new file mode 100644
index 00000000000..8c59edbe6b5
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/create-page.ts
@@ -0,0 +1,76 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../auth';
+import { codaApi } from '../common/client';
+import { codaProps } from '../common/ai-props';
+import { pageMutationActionOutputSchema } from '../output-schemas';
+
+export const createPageAction = createAction({
+ auth: codaAuth,
+ name: 'create_page',
+ classification: 'WRITE',
+ displayName: 'Create Page',
+ description: 'Adds a new page to a doc, optionally under a parent page and with Markdown or HTML content.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Adds a new page (or subpage, with Parent Page ID) to a Coda doc, optionally filled with Markdown or HTML, and by default waits until Coda has created it. Use Update Page to change an existing page. Requires the Doc Maker role. Not idempotent: each call adds another page.',
+ idempotent: false,
+ },
+ props: {
+ docId: codaProps.docId(),
+ name: Property.ShortText({
+ displayName: 'Page Name',
+ required: true,
+ }),
+ subtitle: Property.ShortText({
+ displayName: 'Subtitle',
+ required: false,
+ }),
+ iconName: Property.ShortText({
+ displayName: 'Icon Name',
+ description: 'A Coda icon name, for example "rocket".',
+ required: false,
+ }),
+ parentPageId: Property.ShortText({
+ displayName: 'Parent Page ID',
+ description: 'Optional. Creates the page as a subpage of this page.',
+ required: false,
+ }),
+ content: Property.LongText({
+ displayName: 'Content',
+ required: false,
+ }),
+ contentFormat: codaProps.contentFormat(),
+ waitForCompletion: codaProps.waitForCompletion(),
+ },
+ outputSchema: pageMutationActionOutputSchema,
+ async run(context) {
+ const { docId, name, subtitle, iconName, parentPageId, content, contentFormat, waitForCompletion } = context.propsValue;
+ if (!name || name.trim().length === 0) {
+ throw new Error('Page Name is required.');
+ }
+ const token = context.auth.secret_text;
+ const response = await codaApi.request<PageMutationResponse>({
+ token,
+ method: HttpMethod.POST,
+ path: `${codaApi.docPath(docId)}/pages`,
+ operation: 'create page',
+ body: {
+ name: name.trim(),
+ ...(subtitle?.trim() ? { subtitle: subtitle.trim() } : {}),
+ ...(iconName?.trim() ? { iconName: iconName.trim() } : {}),
+ ...(parentPageId?.trim() ? { parentPageId: parentPageId.trim() } : {}),
+ ...(content && content.trim().length > 0
+ ? { pageContent: { type: 'canvas', canvasContent: { format: contentFormat ?? 'markdown', content } } }
+ : {}),
+ },
+ });
+ const mutation = await codaApi.settleMutation({ token, requestId: response.requestId, waitForCompletion });
+ return { id: response.id, ...mutation };
+ },
+});
+
+type PageMutationResponse = {
+ id: string;
+ requestId?: string;
+};
diff --git a/packages/pieces/community/coda/src/lib/actions/create-row.ts b/packages/pieces/community/coda/src/lib/actions/create-row.ts
index 2be3886962b..bc70ab129a0 100644
--- a/packages/pieces/community/coda/src/lib/actions/create-row.ts
+++ b/packages/pieces/community/coda/src/lib/actions/create-row.ts
@@ -11,7 +11,7 @@ export const createRowAction = createAction({
classification: 'WRITE',
displayName: 'Create Row',
description: 'Creates a new row in the selected table.',
- audience: 'both',
+ audience: 'human',
aiMetadata: { description: 'Append a new row to a table in a Coda doc, with cell values keyed by column. Use to add data to a Coda table; choose Upsert Row instead if you want to match-and-update existing rows on key columns. Requires the doc, table, and at least one non-empty cell value. Not idempotent — each call inserts a separate row.', idempotent: false },
props: {
docId: docIdDropdown,
@@ -23,7 +23,7 @@ export const createRowAction = createAction({
const { docId, tableId, rowData } = context.propsValue;
const client = codaClient(context.auth);
- const cells = Object.entries(rowData as Record<string, any>)
+ const cells = Object.entries(rowData ?? {})
.filter(([, value]) => value !== undefined && value !== null && value !== '')
.map(([columnId, value]) => ({
column: columnId,
@@ -52,6 +52,6 @@ export const createRowAction = createAction({
throw new Error(`Unexpected error occured : ${JSON.stringify(response)}`);
}
- return { rowId };
+ return { rowId, requestId: response.requestId };
},
});
diff --git a/packages/pieces/community/coda/src/lib/actions/create-rows.ts b/packages/pieces/community/coda/src/lib/actions/create-rows.ts
new file mode 100644
index 00000000000..b40a97b78a8
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/create-rows.ts
@@ -0,0 +1,54 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../auth';
+import { codaApi } from '../common/client';
+import { codaProps } from '../common/ai-props';
+import { rowInput } from '../common/row-input';
+import { createRowsActionOutputSchema } from '../output-schemas';
+
+export const createRowsAction = createAction({
+ auth: codaAuth,
+ name: 'create_rows',
+ classification: 'WRITE',
+ displayName: 'Add Rows',
+ description: 'Adds one or more rows to a table, each given as column → value.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Adds 1-500 new rows to a Coda base table (not a view), each given as an object of column name or ID → value, and by default waits until Coda has applied them. Use Upsert Rows instead when rows may already exist. Not idempotent: each call inserts new rows.',
+ idempotent: false,
+ },
+ props: {
+ docId: codaProps.docId(),
+ tableIdOrName: codaProps.tableIdOrName(),
+ rows: Property.Json({
+ displayName: 'Rows',
+ description: 'A list of rows, each an object of column name or ID → value. Example: [{"Name": "Ada", "Amount": 5, "Done": false}]',
+ required: true,
+ defaultValue: [{ Name: 'Example' }],
+ }),
+ disableParsing: Property.Checkbox({
+ displayName: 'Store Values Exactly as Given',
+ description: 'When on, Coda does not convert text like "5" or "2026-01-31" into numbers or dates.',
+ required: false,
+ defaultValue: false,
+ }),
+ waitForCompletion: codaProps.waitForCompletion(),
+ },
+ outputSchema: createRowsActionOutputSchema,
+ async run(context) {
+ const { docId, tableIdOrName, rows, disableParsing, waitForCompletion } = context.propsValue;
+ const rowList = rowInput.toRows({ value: rows, label: 'Rows' });
+ const payload = { rows: rowList.map((row, index) => ({ cells: rowInput.insertCells({ row, rowNumber: index + 1 }) })) };
+ const token = context.auth.secret_text;
+ const response = await codaApi.request<{ requestId?: string; addedRowIds?: string[] }>({
+ token,
+ method: HttpMethod.POST,
+ path: `${codaApi.tablePath({ docId, tableIdOrName })}/rows`,
+ operation: 'add rows',
+ query: { disableParsing: disableParsing === true ? true : undefined },
+ body: payload,
+ });
+ const mutation = await codaApi.settleMutation({ token, requestId: response.requestId, waitForCompletion });
+ return { addedRowIds: response.addedRowIds ?? [], ...mutation };
+ },
+});
diff --git a/packages/pieces/community/coda/src/lib/actions/delete-doc.ts b/packages/pieces/community/coda/src/lib/actions/delete-doc.ts
new file mode 100644
index 00000000000..2879c9a9560
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/delete-doc.ts
@@ -0,0 +1,40 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../auth';
+import { codaApi } from '../common/client';
+import { codaProps } from '../common/ai-props';
+import { deleteDocActionOutputSchema } from '../output-schemas';
+
+export const deleteDocAction = createAction({
+ auth: codaAuth,
+ name: 'delete_doc',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Doc',
+ description: 'Permanently deletes a doc. This cannot be undone through the API.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Permanently deletes a whole Coda doc with all its pages and tables. Use only when the user explicitly asks to delete the doc. A repeat call finds it gone and reports Already Deleted instead of failing, so it is idempotent.',
+ idempotent: true,
+ },
+ props: {
+ docId: codaProps.docId(),
+ },
+ outputSchema: deleteDocActionOutputSchema,
+ async run(context) {
+ const id = codaApi.parseDocId(context.propsValue.docId);
+ try {
+ await codaApi.request({
+ token: context.auth.secret_text,
+ method: HttpMethod.DELETE,
+ path: codaApi.docPath(id),
+ operation: 'delete doc',
+ });
+ return { id, deleted: true, alreadyDeleted: false };
+ } catch (error) {
+ if (codaApi.statusOf(error) === 404) {
+ return { id, deleted: true, alreadyDeleted: true };
+ }
+ throw error;
+ }
+ },
+});
diff --git a/packages/pieces/community/coda/src/lib/actions/delete-page.ts b/packages/pieces/community/coda/src/lib/actions/delete-page.ts
new file mode 100644
index 00000000000..06122e204c4
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/delete-page.ts
@@ -0,0 +1,50 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../auth';
+import { codaApi } from '../common/client';
+import { codaProps } from '../common/ai-props';
+import { deletePageActionOutputSchema } from '../output-schemas';
+
+export const deletePageAction = createAction({
+ auth: codaAuth,
+ name: 'delete_page',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Page',
+ description: 'Deletes a page and everything on it, including its tables.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Deletes a Coda page with its content and any tables on it. Use only when the user asks to remove the page. A repeat call finds it gone and reports Already Deleted instead of failing, so it is idempotent.',
+ idempotent: true,
+ },
+ props: {
+ docId: codaProps.docId(),
+ pageIdOrName: codaProps.pageIdOrName(),
+ waitForCompletion: codaProps.waitForCompletion(),
+ },
+ outputSchema: deletePageActionOutputSchema,
+ async run(context) {
+ const { docId, pageIdOrName, waitForCompletion } = context.propsValue;
+ const token = context.auth.secret_text;
+ try {
+ const response = await codaApi.request<PageMutationResponse>({
+ token,
+ method: HttpMethod.DELETE,
+ path: `${codaApi.docPath(docId)}/pages/${codaApi.pathSegment({ value: pageIdOrName, label: 'Page ID or name' })}`,
+ operation: 'delete page',
+ });
+ const mutation = await codaApi.settleMutation({ token, requestId: response.requestId, waitForCompletion });
+ return { id: response.id ?? pageIdOrName, alreadyDeleted: false, ...mutation };
+ } catch (error) {
+ const status = codaApi.statusOf(error);
+ if (status === 404 || status === 410) {
+ return { id: pageIdOrName, alreadyDeleted: true, requestId: null, completed: true, warning: null };
+ }
+ throw error;
+ }
+ },
+});
+
+type PageMutationResponse = {
+ id?: string;
+ requestId?: string;
+};
diff --git a/packages/pieces/community/coda/src/lib/actions/delete-rows.ts b/packages/pieces/community/coda/src/lib/actions/delete-rows.ts
new file mode 100644
index 00000000000..364aa5549c5
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/delete-rows.ts
@@ -0,0 +1,51 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../auth';
+import { codaApi } from '../common/client';
+import { codaProps } from '../common/ai-props';
+import { rowInput } from '../common/row-input';
+import { deleteRowsActionOutputSchema } from '../output-schemas';
+
+export const deleteRowsAction = createAction({
+ auth: codaAuth,
+ name: 'delete_rows',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Rows',
+ description: 'Permanently deletes rows from a table by row ID.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Permanently deletes 1-500 rows (by row ID) from a Coda table or view. Use only when the user asks to remove rows; get the IDs from List Rows first. Row IDs that no longer exist are ignored, so a repeat call leaves the same end state and it is idempotent.',
+ idempotent: true,
+ },
+ props: {
+ docId: codaProps.docId(),
+ tableIdOrName: codaProps.tableIdOrName(),
+ rowIds: Property.Array({
+ displayName: 'Row IDs',
+ description: 'IDs of the rows to delete (they start with "i-").',
+ required: true,
+ }),
+ waitForCompletion: codaProps.waitForCompletion(),
+ },
+ outputSchema: deleteRowsActionOutputSchema,
+ async run(context) {
+ const { docId, tableIdOrName, rowIds, waitForCompletion } = context.propsValue;
+ const ids = rowInput.toStringList({ value: rowIds, label: 'Row IDs' });
+ if (ids.length === 0) {
+ throw new Error('Give at least one row ID to delete.');
+ }
+ if (ids.length > rowInput.MAX_ROWS_PER_REQUEST) {
+ throw new Error(`At most ${rowInput.MAX_ROWS_PER_REQUEST} rows can be deleted per call.`);
+ }
+ const token = context.auth.secret_text;
+ const response = await codaApi.request<{ requestId?: string; rowIds?: string[] }>({
+ token,
+ method: HttpMethod.DELETE,
+ path: `${codaApi.tablePath({ docId, tableIdOrName })}/rows`,
+ operation: 'delete rows',
+ body: { rowIds: ids },
+ });
+ const mutation = await codaApi.settleMutation({ token, requestId: response.requestId, waitForCompletion });
+ return { rowIds: response.rowIds ?? ids, ...mutation };
+ },
+});
diff --git a/packages/pieces/community/coda/src/lib/actions/find-row.ts b/packages/pieces/community/coda/src/lib/actions/find-row.ts
index 705d2e570bb..1cd7dd8bcfc 100644
--- a/packages/pieces/community/coda/src/lib/actions/find-row.ts
+++ b/packages/pieces/community/coda/src/lib/actions/find-row.ts
@@ -2,15 +2,18 @@ import { Property, createAction } from '@activepieces/pieces-framework';
import { codaAuth } from '../auth';
import { CodaRow, codaClient } from '../common/types';
import { columnIdsDropdown, docIdDropdown, tableIdDropdown } from '../common/props';
+import { codaApi } from '../common/client';
import { findRowActionOutputSchema } from '../output-schemas';
+const PAGE_SIZE = 500;
+
export const findRowAction = createAction({
auth: codaAuth,
name: 'find-row',
classification: 'SEARCH',
displayName: 'Find Row(s)',
description: 'Find specific rows in the selected table using a column match search.',
- audience: 'both',
+ audience: 'human',
aiMetadata: { description: 'Search a Coda table for rows where a chosen column equals a given value, paging through all matches. Use to look up rows by a field value before reading or updating them; pair with Update Row using a returned row ID. Read-only and idempotent.', idempotent: true },
props: {
docId: docIdDropdown,
@@ -18,25 +21,35 @@ export const findRowAction = createAction({
searchColumn: columnIdsDropdown('Search Column', true),
searchValue: Property.ShortText({
displayName: 'Search Value',
+ description: 'Rows whose column equals this value are returned.',
required: true,
}),
+ maxRows: Property.Number({
+ displayName: 'Max Rows',
+ description: 'Stop after this many matching rows. Leave empty to return every match.',
+ required: false,
+ }),
},
outputSchema: findRowActionOutputSchema,
async run(context) {
- const { docId, tableId, searchColumn, searchValue } = context.propsValue;
+ const { docId, tableId, searchColumn, searchValue, maxRows } = context.propsValue;
+ if (maxRows !== undefined && maxRows !== null && (!Number.isInteger(maxRows) || maxRows < 1)) {
+ throw new Error('Max Rows must be a whole number of 1 or more, or empty for all rows.');
+ }
const client = codaClient(context.auth);
+ const query = codaApi.buildRowQuery({ column: String(searchColumn), value: searchValue });
const matchedRows: CodaRow[] = [];
let nextPageToken: string | undefined = undefined;
do {
const response = await client.listRows(docId, tableId, {
- query: `${searchColumn}:${JSON.stringify(searchValue)}`,
+ query,
sortBy: 'natural',
useColumnNames: true,
valueFormat: 'simpleWithArrays',
visibleOnly: true,
- limit: 100,
+ limit: PAGE_SIZE,
pageToken: nextPageToken,
});
@@ -44,11 +57,13 @@ export const findRowAction = createAction({
matchedRows.push(...response.items);
}
nextPageToken = response.nextPageToken;
- } while (nextPageToken);
+ } while (nextPageToken && (maxRows === undefined || maxRows === null || matchedRows.length < maxRows));
+
+ const result = maxRows ? matchedRows.slice(0, maxRows) : matchedRows;
return {
- found: matchedRows.length > 0,
- result: matchedRows,
+ found: result.length > 0,
+ result,
};
},
});
diff --git a/packages/pieces/community/coda/src/lib/actions/get-control.ts b/packages/pieces/community/coda/src/lib/actions/get-control.ts
new file mode 100644
index 00000000000..d9c7b660f98
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/get-control.ts
@@ -0,0 +1,37 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../auth';
+import { codaApi } from '../common/client';
+import { codaProps } from '../common/ai-props';
+import { getControlActionOutputSchema } from '../output-schemas';
+
+export const getControlAction = createAction({
+ auth: codaAuth,
+ name: 'get_control',
+ classification: 'READ',
+ displayName: 'Get Control',
+ description: 'Gets the type and current value of a control.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Returns a Coda control\'s type and current value (for example a slider position or a selected option), by control ID or name. Use List Controls to find it. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ docId: codaProps.docId(),
+ controlIdOrName: Property.ShortText({
+ displayName: 'Control ID or Name',
+ description: 'The control ID (starts with "ctrl-") or its exact name.',
+ required: true,
+ }),
+ },
+ outputSchema: getControlActionOutputSchema,
+ async run(context) {
+ const { docId, controlIdOrName } = context.propsValue;
+ return codaApi.request({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: `${codaApi.docPath(docId)}/controls/${codaApi.pathSegment({ value: controlIdOrName, label: 'Control ID or Name' })}`,
+ operation: 'get control',
+ });
+ },
+});
diff --git a/packages/pieces/community/coda/src/lib/actions/get-current-user.ts b/packages/pieces/community/coda/src/lib/actions/get-current-user.ts
new file mode 100644
index 00000000000..bd9b819d9aa
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/get-current-user.ts
@@ -0,0 +1,28 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../auth';
+import { codaApi } from '../common/client';
+import { getCurrentUserActionOutputSchema } from '../output-schemas';
+
+export const getCurrentUserAction = createAction({
+ auth: codaAuth,
+ name: 'get_current_user',
+ classification: 'READ',
+ displayName: 'Get Current User',
+ description: 'Returns the Coda account and workspace that the connected API token belongs to.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Returns the name, login email and workspace of the Coda account behind this connection, and whether the token is limited to some docs. Use to confirm which account you are acting as. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {},
+ outputSchema: getCurrentUserActionOutputSchema,
+ async run(context) {
+ return codaApi.request({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: '/whoami',
+ operation: 'get current user',
+ });
+ },
+});
diff --git a/packages/pieces/community/coda/src/lib/actions/get-doc.ts b/packages/pieces/community/coda/src/lib/actions/get-doc.ts
new file mode 100644
index 00000000000..9dcb0bc29cc
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/get-doc.ts
@@ -0,0 +1,31 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../auth';
+import { codaApi } from '../common/client';
+import { codaProps } from '../common/ai-props';
+import { getDocActionOutputSchema } from '../output-schemas';
+
+export const getDocAction = createAction({
+ auth: codaAuth,
+ name: 'get_doc',
+ classification: 'READ',
+ displayName: 'Get Doc',
+ description: 'Gets the details of a doc: name, owner, links, folder, workspace and size.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Returns one Coda doc\'s metadata (name, owner, browser link, folder, workspace, page/table/row counts) by doc ID or link. Use to check a doc exists or to get its link; it does not return page text (use Get Page Content). Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ docId: codaProps.docId(),
+ },
+ outputSchema: getDocActionOutputSchema,
+ async run(context) {
+ return codaApi.request({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: codaApi.docPath(context.propsValue.docId),
+ operation: 'get doc',
+ });
+ },
+});
diff --git a/packages/pieces/community/coda/src/lib/actions/get-formula.ts b/packages/pieces/community/coda/src/lib/actions/get-formula.ts
new file mode 100644
index 00000000000..d8ad97f8fef
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/get-formula.ts
@@ -0,0 +1,37 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../auth';
+import { codaApi } from '../common/client';
+import { codaProps } from '../common/ai-props';
+import { getFormulaActionOutputSchema } from '../output-schemas';
+
+export const getFormulaAction = createAction({
+ auth: codaAuth,
+ name: 'get_formula',
+ classification: 'READ',
+ displayName: 'Get Named Formula',
+ description: 'Gets the current value of a named formula.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Returns the current computed value of a named formula in a Coda doc (for example a total), by formula ID or name. Use List Named Formulas to find it. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ docId: codaProps.docId(),
+ formulaIdOrName: Property.ShortText({
+ displayName: 'Formula ID or Name',
+ description: 'The formula ID (starts with "f-") or its exact name.',
+ required: true,
+ }),
+ },
+ outputSchema: getFormulaActionOutputSchema,
+ async run(context) {
+ const { docId, formulaIdOrName } = context.propsValue;
+ return codaApi.request({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: `${codaApi.docPath(docId)}/formulas/${codaApi.pathSegment({ value: formulaIdOrName, label: 'Formula ID or Name' })}`,
+ operation: 'get formula',
+ });
+ },
+});
diff --git a/packages/pieces/community/coda/src/lib/actions/get-mutation-status.ts b/packages/pieces/community/coda/src/lib/actions/get-mutation-status.ts
new file mode 100644
index 00000000000..5e3065a0108
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/get-mutation-status.ts
@@ -0,0 +1,30 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { codaAuth } from '../auth';
+import { codaApi } from '../common/client';
+import { getMutationStatusActionOutputSchema } from '../output-schemas';
+
+export const getMutationStatusAction = createAction({
+ auth: codaAuth,
+ name: 'get_mutation_status',
+ classification: 'READ',
+ displayName: 'Get Mutation Status',
+ description: 'Checks whether an earlier change (by its Request ID) has been applied by Coda.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Checks whether an earlier Coda write, identified by the Request ID it returned, has been applied, and returns any warning. Use when a write returned Completed = false. Coda keeps statuses for about a day. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ requestId: Property.ShortText({
+ displayName: 'Request ID',
+ description: 'The Request ID returned by a previous Coda step.',
+ required: true,
+ }),
+ },
+ outputSchema: getMutationStatusActionOutputSchema,
+ async run(context) {
+ const requestId = context.propsValue.requestId.trim();
+ const status = await codaApi.getMutationStatus({ token: context.auth.secret_text, requestId });
+ return { requestId, completed: status.completed, warning: status.warning ?? null };
+ },
+});
diff --git a/packages/pieces/community/coda/src/lib/actions/get-page-content.ts b/packages/pieces/community/coda/src/lib/actions/get-page-content.ts
new file mode 100644
index 00000000000..46a07e8be5e
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/get-page-content.ts
@@ -0,0 +1,57 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../auth';
+import { codaApi } from '../common/client';
+import { codaProps } from '../common/ai-props';
+import { pageExport } from '../common/page-export';
+import { getPageContentActionOutputSchema } from '../output-schemas';
+
+export const getPageContentAction = createAction({
+ auth: codaAuth,
+ name: 'get_page_content',
+ classification: 'READ',
+ displayName: 'Get Page Content',
+ description: 'Exports a page\'s content as Markdown or HTML text.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Returns the text of a Coda page as Markdown (or HTML), capped at 5 MB. Use to read or summarise a page; use Get Page for its metadata only. If Coda needs more than a minute, it returns Completed = false and an Export ID to pass back in a second call. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ docId: codaProps.docId(),
+ pageIdOrName: codaProps.pageIdOrName(),
+ outputFormat: Property.StaticDropdown({
+ displayName: 'Format',
+ required: true,
+ defaultValue: 'markdown',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Markdown', value: 'markdown' },
+ { label: 'HTML', value: 'html' },
+ ],
+ },
+ }),
+ exportId: Property.ShortText({
+ displayName: 'Export ID',
+ description: 'Leave empty. Only fill it to resume an export that returned Completed = false earlier.',
+ required: false,
+ }),
+ },
+ outputSchema: getPageContentActionOutputSchema,
+ async run(context) {
+ const { docId, pageIdOrName, outputFormat, exportId } = context.propsValue;
+ const format = outputFormat === 'html' ? 'html' : 'markdown';
+ const token = context.auth.secret_text;
+ const pagePath = `${codaApi.docPath(docId)}/pages/${codaApi.pathSegment({ value: pageIdOrName, label: 'Page ID or name' })}`;
+ const id = exportId?.trim() || (await pageExport.startExport({ token, pagePath, format })).id;
+ const status = await pageExport.waitForExport({ token, pagePath, exportId: id });
+ if (!status) {
+ return { pageId: pageIdOrName, format, completed: false, exportId: id, content: null, truncated: false };
+ }
+ if (!status.downloadLink) {
+ throw new Error('Coda finished the export but returned no download link.');
+ }
+ const { content, truncated } = await pageExport.downloadText({ url: status.downloadLink, format });
+ return { pageId: pageIdOrName, format, completed: true, exportId: id, content, truncated };
+ },
+});
diff --git a/packages/pieces/community/coda/src/lib/actions/get-page.ts b/packages/pieces/community/coda/src/lib/actions/get-page.ts
new file mode 100644
index 00000000000..02137f271fd
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/get-page.ts
@@ -0,0 +1,33 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../auth';
+import { codaApi } from '../common/client';
+import { codaProps } from '../common/ai-props';
+import { getPageActionOutputSchema } from '../output-schemas';
+
+export const getPageAction = createAction({
+ auth: codaAuth,
+ name: 'get_page',
+ classification: 'READ',
+ displayName: 'Get Page',
+ description: 'Gets a page\'s details: name, subtitle, parent, subpages, visibility and links.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Returns one Coda page\'s metadata (name, subtitle, parent, subpages, hidden state, authors, link) by page ID or name. It does not return the page text; use Get Page Content for that. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ docId: codaProps.docId(),
+ pageIdOrName: codaProps.pageIdOrName(),
+ },
+ outputSchema: getPageActionOutputSchema,
+ async run(context) {
+ const { docId, pageIdOrName } = context.propsValue;
+ return codaApi.request({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: `${codaApi.docPath(docId)}/pages/${codaApi.pathSegment({ value: pageIdOrName, label: 'Page ID or name' })}`,
+ operation: 'get page',
+ });
+ },
+});
diff --git a/packages/pieces/community/coda/src/lib/actions/get-row.ts b/packages/pieces/community/coda/src/lib/actions/get-row.ts
index 87aca3291f5..7e7c0505e74 100644
--- a/packages/pieces/community/coda/src/lib/actions/get-row.ts
+++ b/packages/pieces/community/coda/src/lib/actions/get-row.ts
@@ -10,7 +10,7 @@ export const getRowAction = createAction({
classification: 'READ',
displayName: 'Get Row',
description: 'Retrieves a single row by specified ID.',
- audience: 'both',
+ audience: 'human',
aiMetadata: { description: 'Fetch one row from a Coda table by its row ID or unique row name, returning its cell values. Use when you already have a specific row identifier; use Find Row(s) instead to search by a column value. Read-only and idempotent.', idempotent: true },
props: {
docId: docIdDropdown,
diff --git a/packages/pieces/community/coda/src/lib/actions/get-table.ts b/packages/pieces/community/coda/src/lib/actions/get-table.ts
index 01edc752466..fc1770572b3 100644
--- a/packages/pieces/community/coda/src/lib/actions/get-table.ts
+++ b/packages/pieces/community/coda/src/lib/actions/get-table.ts
@@ -9,9 +9,9 @@ export const getTableAction = createAction({
name: 'get-table',
classification: 'READ',
displayName: 'Get Table',
- description: 'Get structure and details of a specific table (e.g., columns, schema).',
- audience: 'both',
- aiMetadata: { description: 'Retrieve the metadata of a single Coda table, including its columns and schema. Use to inspect a table structure before building row payloads or mapping fields. Requires the doc and table; read-only and idempotent.', idempotent: true },
+ description: 'Get the details of a specific table: name, type, row count, display column and layout.',
+ audience: 'human',
+ aiMetadata: { description: 'Retrieve the metadata of a single Coda table: name, type, row count, display column and layout. It does not return the columns; use List Columns for those. Read-only and idempotent.', idempotent: true },
props: {
docId: docIdDropdown,
tableId: tableIdDropdown,
diff --git a/packages/pieces/community/coda/src/lib/actions/list-columns.ts b/packages/pieces/community/coda/src/lib/actions/list-columns.ts
new file mode 100644
index 00000000000..24227482d07
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/list-columns.ts
@@ -0,0 +1,46 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../auth';
+import { CodaPage, codaApi } from '../common/client';
+import { codaProps } from '../common/ai-props';
+import { listColumnsActionOutputSchema } from '../output-schemas';
+
+export const listColumnsAction = createAction({
+ auth: codaAuth,
+ name: 'list_columns',
+ classification: 'SEARCH',
+ displayName: 'List Columns',
+ description: 'Lists a table\'s columns with their IDs, names and types, one page at a time.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Lists the columns of a Coda table with ID, name, type (text, number, date, checkbox, select, button…), whether it is calculated (read-only) and whether it is the display column. Use before writing rows to learn the column names and which ones accept values. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ docId: codaProps.docId(),
+ tableIdOrName: codaProps.tableIdOrName(),
+ visibleOnly: Property.Checkbox({
+ displayName: 'Visible Columns Only',
+ required: false,
+ defaultValue: false,
+ }),
+ limit: codaProps.limit({ max: 100, defaultValue: 100 }),
+ pageToken: codaProps.pageToken(),
+ },
+ outputSchema: listColumnsActionOutputSchema,
+ async run(context) {
+ const { docId, tableIdOrName, visibleOnly, limit, pageToken } = context.propsValue;
+ const page = await codaApi.request<CodaPage<unknown>>({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: `${codaApi.tablePath({ docId, tableIdOrName })}/columns`,
+ operation: 'list columns',
+ query: {
+ visibleOnly: visibleOnly === true ? true : undefined,
+ limit: codaApi.validateLimit({ limit, max: 100 }),
+ pageToken: pageToken?.trim(),
+ },
+ });
+ return codaApi.toPageOutput(page);
+ },
+});
diff --git a/packages/pieces/community/coda/src/lib/actions/list-controls.ts b/packages/pieces/community/coda/src/lib/actions/list-controls.ts
new file mode 100644
index 00000000000..f6184c5c5d6
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/list-controls.ts
@@ -0,0 +1,39 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../auth';
+import { CodaPage, codaApi } from '../common/client';
+import { codaProps } from '../common/ai-props';
+import { listControlsActionOutputSchema } from '../output-schemas';
+
+export const listControlsAction = createAction({
+ auth: codaAuth,
+ name: 'list_controls',
+ classification: 'SEARCH',
+ displayName: 'List Controls',
+ description: 'Lists the controls (sliders, pickers, buttons…) in a doc, one page at a time.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Lists the controls of a Coda doc (sliders, select lists, date pickers, buttons…) with ID, name and page, one page at a time. Use to find a control before Get Control reads its value. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ docId: codaProps.docId(),
+ limit: codaProps.limit({ max: 100, defaultValue: 25 }),
+ pageToken: codaProps.pageToken(),
+ },
+ outputSchema: listControlsActionOutputSchema,
+ async run(context) {
+ const { docId, limit, pageToken } = context.propsValue;
+ const page = await codaApi.request<CodaPage<unknown>>({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: `${codaApi.docPath(docId)}/controls`,
+ operation: 'list controls',
+ query: {
+ limit: codaApi.validateLimit({ limit, max: 100 }),
+ pageToken: pageToken?.trim(),
+ },
+ });
+ return codaApi.toPageOutput(page);
+ },
+});
diff --git a/packages/pieces/community/coda/src/lib/actions/list-docs.ts b/packages/pieces/community/coda/src/lib/actions/list-docs.ts
new file mode 100644
index 00000000000..3b5b7d9499d
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/list-docs.ts
@@ -0,0 +1,68 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../auth';
+import { CodaPage, codaApi } from '../common/client';
+import { codaProps } from '../common/ai-props';
+import { listDocsActionOutputSchema } from '../output-schemas';
+
+export const listDocsAction = createAction({
+ auth: codaAuth,
+ name: 'list_docs',
+ classification: 'SEARCH',
+ displayName: 'List Docs',
+ description: 'Lists the docs the connected account can open, one page at a time, with optional search and filters.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Lists Coda docs the account can access, optionally filtered by a name search, owner, starred state, folder or workspace, one page at a time. Use to find a doc ID before working inside a doc; pass Next Page Token to continue. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ query: Property.ShortText({
+ displayName: 'Search',
+ description: 'Only docs whose name contains this text.',
+ required: false,
+ }),
+ isOwner: Property.Checkbox({
+ displayName: 'Only Docs I Own',
+ required: false,
+ defaultValue: false,
+ }),
+ isStarred: Property.Checkbox({
+ displayName: 'Only Starred Docs',
+ required: false,
+ defaultValue: false,
+ }),
+ folderId: Property.ShortText({
+ displayName: 'Folder ID',
+ description: 'Only docs in this folder (starts with "fl-"). Use List Folders to find it.',
+ required: false,
+ }),
+ workspaceId: Property.ShortText({
+ displayName: 'Workspace ID',
+ description: 'Only docs in this workspace (starts with "ws-").',
+ required: false,
+ }),
+ limit: codaProps.limit({ max: 100, defaultValue: 25 }),
+ pageToken: codaProps.pageToken(),
+ },
+ outputSchema: listDocsActionOutputSchema,
+ async run(context) {
+ const { query, isOwner, isStarred, folderId, workspaceId, limit, pageToken } = context.propsValue;
+ const page = await codaApi.request<CodaPage<unknown>>({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: '/docs',
+ operation: 'list docs',
+ query: {
+ query: query?.trim(),
+ isOwner: isOwner === true ? true : undefined,
+ isStarred: isStarred === true ? true : undefined,
+ folderId: folderId?.trim(),
+ workspaceId: workspaceId?.trim(),
+ limit: codaApi.validateLimit({ limit, max: 100 }),
+ pageToken: pageToken?.trim(),
+ },
+ });
+ return codaApi.toPageOutput(page);
+ },
+});
diff --git a/packages/pieces/community/coda/src/lib/actions/list-folders.ts b/packages/pieces/community/coda/src/lib/actions/list-folders.ts
new file mode 100644
index 00000000000..8a03aafd686
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/list-folders.ts
@@ -0,0 +1,50 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../auth';
+import { CodaPage, codaApi } from '../common/client';
+import { codaProps } from '../common/ai-props';
+import { listFoldersActionOutputSchema } from '../output-schemas';
+
+export const listFoldersAction = createAction({
+ auth: codaAuth,
+ name: 'list_folders',
+ classification: 'SEARCH',
+ displayName: 'List Folders',
+ description: 'Lists the folders the connected account can see, one page at a time.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Lists Coda folders (ID, name, workspace) the account can see, one page at a time. Use to find a folder ID for Create Doc or List Docs. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ workspaceId: Property.ShortText({
+ displayName: 'Workspace ID',
+ description: 'Only folders in this workspace (starts with "ws-").',
+ required: false,
+ }),
+ isStarred: Property.Checkbox({
+ displayName: 'Only Starred Folders',
+ required: false,
+ defaultValue: false,
+ }),
+ limit: codaProps.limit({ max: 100, defaultValue: 25 }),
+ pageToken: codaProps.pageToken(),
+ },
+ outputSchema: listFoldersActionOutputSchema,
+ async run(context) {
+ const { workspaceId, isStarred, limit, pageToken } = context.propsValue;
+ const page = await codaApi.request<CodaPage<unknown>>({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: '/folders',
+ operation: 'list folders',
+ query: {
+ workspaceId: workspaceId?.trim(),
+ isStarred: isStarred === true ? true : undefined,
+ limit: codaApi.validateLimit({ limit, max: 100 }),
+ pageToken: pageToken?.trim(),
+ },
+ });
+ return codaApi.toPageOutput(page);
+ },
+});
diff --git a/packages/pieces/community/coda/src/lib/actions/list-formulas.ts b/packages/pieces/community/coda/src/lib/actions/list-formulas.ts
new file mode 100644
index 00000000000..e191990d7de
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/list-formulas.ts
@@ -0,0 +1,39 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../auth';
+import { CodaPage, codaApi } from '../common/client';
+import { codaProps } from '../common/ai-props';
+import { listFormulasActionOutputSchema } from '../output-schemas';
+
+export const listFormulasAction = createAction({
+ auth: codaAuth,
+ name: 'list_formulas',
+ classification: 'SEARCH',
+ displayName: 'List Named Formulas',
+ description: 'Lists the named formulas in a doc, one page at a time.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Lists the named formulas of a Coda doc (ID, name, page) one page at a time. Use to find a formula before Get Named Formula reads its current value. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ docId: codaProps.docId(),
+ limit: codaProps.limit({ max: 100, defaultValue: 25 }),
+ pageToken: codaProps.pageToken(),
+ },
+ outputSchema: listFormulasActionOutputSchema,
+ async run(context) {
+ const { docId, limit, pageToken } = context.propsValue;
+ const page = await codaApi.request<CodaPage<unknown>>({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: `${codaApi.docPath(docId)}/formulas`,
+ operation: 'list formulas',
+ query: {
+ limit: codaApi.validateLimit({ limit, max: 100 }),
+ pageToken: pageToken?.trim(),
+ },
+ });
+ return codaApi.toPageOutput(page);
+ },
+});
diff --git a/packages/pieces/community/coda/src/lib/actions/list-pages.ts b/packages/pieces/community/coda/src/lib/actions/list-pages.ts
new file mode 100644
index 00000000000..0d00cd3b4f7
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/list-pages.ts
@@ -0,0 +1,39 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../auth';
+import { CodaPage, codaApi } from '../common/client';
+import { codaProps } from '../common/ai-props';
+import { listPagesActionOutputSchema } from '../output-schemas';
+
+export const listPagesAction = createAction({
+ auth: codaAuth,
+ name: 'list_pages',
+ classification: 'SEARCH',
+ displayName: 'List Pages',
+ description: 'Lists the pages of a doc, one page of results at a time.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Lists the pages (and subpages) of a Coda doc with their IDs, names, parent and visibility, one page of results at a time. Use to find a page ID before Get Page Content, Update Page or Delete Page; pass Next Page Token to continue. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ docId: codaProps.docId(),
+ limit: codaProps.limit({ max: 100, defaultValue: 25 }),
+ pageToken: codaProps.pageToken(),
+ },
+ outputSchema: listPagesActionOutputSchema,
+ async run(context) {
+ const { docId, limit, pageToken } = context.propsValue;
+ const page = await codaApi.request<CodaPage<unknown>>({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: `${codaApi.docPath(docId)}/pages`,
+ operation: 'list pages',
+ query: {
+ limit: codaApi.validateLimit({ limit, max: 100 }),
+ pageToken: pageToken?.trim(),
+ },
+ });
+ return codaApi.toPageOutput(page);
+ },
+});
diff --git a/packages/pieces/community/coda/src/lib/actions/list-permissions.ts b/packages/pieces/community/coda/src/lib/actions/list-permissions.ts
new file mode 100644
index 00000000000..c067669ce00
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/list-permissions.ts
@@ -0,0 +1,35 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../auth';
+import { codaApi } from '../common/client';
+import { codaProps } from '../common/ai-props';
+import { codaPermissions } from '../common/permissions';
+import { listPermissionsActionOutputSchema } from '../output-schemas';
+
+export const listPermissionsAction = createAction({
+ auth: codaAuth,
+ name: 'list_permissions',
+ classification: 'SEARCH',
+ displayName: 'List Doc Sharing',
+ description: 'Lists who a doc is shared with and their access level, one page at a time.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Lists the people, domains or link-sharing entries a Coda doc is shared with, each with a permission ID and access level (readonly, comment, write), one page at a time. Use to find the permission ID before Remove Doc Sharing. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ docId: codaProps.docId(),
+ limit: codaProps.limit({ max: 100, defaultValue: 25 }),
+ pageToken: codaProps.pageToken(),
+ },
+ outputSchema: listPermissionsActionOutputSchema,
+ async run(context) {
+ const { docId, limit, pageToken } = context.propsValue;
+ const page = await codaPermissions.listPermissions({
+ token: context.auth.secret_text,
+ docId,
+ limit: codaApi.validateLimit({ limit, max: 100 }),
+ pageToken: pageToken?.trim() || undefined,
+ });
+ return codaApi.toPageOutput(page);
+ },
+});
diff --git a/packages/pieces/community/coda/src/lib/actions/list-rows.ts b/packages/pieces/community/coda/src/lib/actions/list-rows.ts
new file mode 100644
index 00000000000..06a00a27865
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/list-rows.ts
@@ -0,0 +1,100 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../auth';
+import { CodaPage, codaApi } from '../common/client';
+import { codaProps } from '../common/ai-props';
+import { listRowsActionOutputSchema } from '../output-schemas';
+
+export const listRowsAction = createAction({
+ auth: codaAuth,
+ name: 'list_rows',
+ classification: 'SEARCH',
+ displayName: 'List Rows',
+ description: 'Lists rows of a table one page at a time, optionally only rows where a column equals a value.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Lists rows of a Coda table one page at a time, optionally only those whose column equals a value, with values keyed by column name. Use to find row IDs before Get Row, Update Row or Delete Rows; pass Next Page Token to continue. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ docId: codaProps.docId(),
+ tableIdOrName: codaProps.tableIdOrName(),
+ filterColumn: Property.ShortText({
+ displayName: 'Filter Column',
+ description: 'Optional column ID or name. Only rows where this column equals Filter Value are returned.',
+ required: false,
+ }),
+ filterValue: Property.ShortText({
+ displayName: 'Filter Value',
+ description: 'The value the Filter Column must equal. Required when Filter Column is set.',
+ required: false,
+ }),
+ sortBy: Property.StaticDropdown({
+ displayName: 'Sort By',
+ required: false,
+ defaultValue: 'natural',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Table order', value: 'natural' },
+ { label: 'Created time (oldest first)', value: 'createdAt' },
+ { label: 'Updated time (oldest first)', value: 'updatedAt' },
+ ],
+ },
+ }),
+ useColumnNames: Property.Checkbox({
+ displayName: 'Key Values by Column Name',
+ description: 'When off, values are keyed by column ID, which does not change if a column is renamed.',
+ required: false,
+ defaultValue: true,
+ }),
+ valueFormat: Property.StaticDropdown({
+ displayName: 'Value Format',
+ required: false,
+ defaultValue: 'simpleWithArrays',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Simple (lists as arrays)', value: 'simpleWithArrays' },
+ { label: 'Simple (lists as text)', value: 'simple' },
+ { label: 'Rich (links, people, currency as objects)', value: 'rich' },
+ ],
+ },
+ }),
+ visibleOnly: Property.Checkbox({
+ displayName: 'Visible Columns Only',
+ required: false,
+ defaultValue: false,
+ }),
+ limit: codaProps.limit({ max: 500, defaultValue: 100 }),
+ pageToken: codaProps.pageToken(),
+ },
+ outputSchema: listRowsActionOutputSchema,
+ async run(context) {
+ const { docId, tableIdOrName, filterColumn, filterValue, sortBy, useColumnNames, valueFormat, visibleOnly, limit, pageToken } =
+ context.propsValue;
+ const column = filterColumn?.trim();
+ if (column && (filterValue === undefined || filterValue === null)) {
+ throw new Error('Filter Value is required when Filter Column is set.');
+ }
+ if (!column && filterValue !== undefined && filterValue !== null && filterValue !== '') {
+ throw new Error('Filter Column is required when Filter Value is set.');
+ }
+ const page = await codaApi.request<CodaPage<unknown>>({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: `${codaApi.tablePath({ docId, tableIdOrName })}/rows`,
+ operation: 'list rows',
+ query: {
+ query: column ? codaApi.buildRowQuery({ column, value: filterValue }) : undefined,
+ sortBy: sortBy ?? 'natural',
+ useColumnNames: useColumnNames !== false,
+ valueFormat: valueFormat ?? 'simpleWithArrays',
+ visibleOnly: visibleOnly === true ? true : undefined,
+ limit: codaApi.validateLimit({ limit, max: 500 }),
+ pageToken: pageToken?.trim(),
+ },
+ });
+ return codaApi.toPageOutput(page);
+ },
+});
diff --git a/packages/pieces/community/coda/src/lib/actions/list-tables.ts b/packages/pieces/community/coda/src/lib/actions/list-tables.ts
index 2ab6b61cfe2..c2640c1a864 100644
--- a/packages/pieces/community/coda/src/lib/actions/list-tables.ts
+++ b/packages/pieces/community/coda/src/lib/actions/list-tables.ts
@@ -10,7 +10,7 @@ export const listTablesAction = createAction({
classification: 'SEARCH',
displayName: 'List Table(s)',
description: 'List tables in a selected document.',
- audience: 'both',
+ audience: 'human',
aiMetadata: { description: 'List the tables in a Coda doc, up to a caller-specified maximum, returning each table reference. Use to discover available tables and their IDs before reading or writing rows. Read-only and idempotent.', idempotent: true },
props: {
docId: docIdDropdown,
@@ -23,13 +23,16 @@ export const listTablesAction = createAction({
outputSchema: listTablesActionOutputSchema,
async run(context) {
const { docId, max } = context.propsValue;
+ if (!Number.isInteger(max) || max < 1) {
+ throw new Error('Max Tables must be a whole number of 1 or more.');
+ }
const client = codaClient(context.auth);
const allTables: CodaTableReference[] = [];
let nextPageToken: string | undefined = undefined;
do {
- const response = await client.listTables(docId as string, {
+ const response = await client.listTables(docId, {
limit: 100,
sortBy: 'name',
tableTypes: 'table',
diff --git a/packages/pieces/community/coda/src/lib/actions/push-button.ts b/packages/pieces/community/coda/src/lib/actions/push-button.ts
new file mode 100644
index 00000000000..d66c6bfdfa2
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/push-button.ts
@@ -0,0 +1,43 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../auth';
+import { codaApi } from '../common/client';
+import { codaProps } from '../common/ai-props';
+import { pushButtonActionOutputSchema } from '../output-schemas';
+
+export const pushButtonAction = createAction({
+ auth: codaAuth,
+ name: 'push_button',
+ classification: 'WRITE',
+ displayName: 'Push Button',
+ description: 'Presses a button in a table row, running whatever action the button is set up to do. If the button is disabled for that row, Coda accepts the press but nothing happens.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Presses the button in one row\'s button column, which runs the action the doc owner configured (it can edit rows, send notifications or call Packs). Use only when the user asks to press that button. A button disabled for that row is accepted but does nothing; check the row afterwards if the outcome matters. Not idempotent: each press runs the action again.',
+ idempotent: false,
+ },
+ props: {
+ docId: codaProps.docId(),
+ tableIdOrName: codaProps.tableIdOrName(),
+ rowIdOrName: codaProps.rowIdOrName(),
+ columnIdOrName: Property.ShortText({
+ displayName: 'Button Column ID or Name',
+ description: 'The button column (List Columns shows it with type "button").',
+ required: true,
+ }),
+ waitForCompletion: codaProps.waitForCompletion(),
+ },
+ outputSchema: pushButtonActionOutputSchema,
+ async run(context) {
+ const { docId, tableIdOrName, rowIdOrName, columnIdOrName, waitForCompletion } = context.propsValue;
+ const token = context.auth.secret_text;
+ const response = await codaApi.request<{ requestId?: string; rowId?: string; columnId?: string }>({
+ token,
+ method: HttpMethod.POST,
+ path: `${codaApi.tablePath({ docId, tableIdOrName })}/rows/${codaApi.pathSegment({ value: rowIdOrName, label: 'Row ID' })}/buttons/${codaApi.pathSegment({ value: columnIdOrName, label: 'Button column' })}`,
+ operation: 'push button',
+ });
+ const mutation = await codaApi.settleMutation({ token, requestId: response.requestId, waitForCompletion });
+ return { rowId: response.rowId ?? rowIdOrName, columnId: response.columnId ?? columnIdOrName, ...mutation };
+ },
+});
diff --git a/packages/pieces/community/coda/src/lib/actions/remove-permission.ts b/packages/pieces/community/coda/src/lib/actions/remove-permission.ts
new file mode 100644
index 00000000000..7fa8e5b1972
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/remove-permission.ts
@@ -0,0 +1,47 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../auth';
+import { codaApi } from '../common/client';
+import { codaProps } from '../common/ai-props';
+import { removePermissionActionOutputSchema } from '../output-schemas';
+
+export const removePermissionAction = createAction({
+ auth: codaAuth,
+ name: 'remove_permission',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Remove Doc Sharing',
+ description: 'Stops sharing a doc with a person or domain, by permission ID.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Removes one sharing entry from a Coda doc by permission ID, so that person or domain loses access. Get the ID from List Doc Sharing. Removing an entry that is already gone succeeds without error, so it is idempotent.',
+ idempotent: true,
+ },
+ props: {
+ docId: codaProps.docId(),
+ permissionId: Property.ShortText({
+ displayName: 'Permission ID',
+ description: 'From List Doc Sharing or Share Doc.',
+ required: true,
+ }),
+ },
+ outputSchema: removePermissionActionOutputSchema,
+ async run(context) {
+ const { docId, permissionId } = context.propsValue;
+ const id = codaApi.parseDocId(docId);
+ const permission = permissionId.trim();
+ try {
+ await codaApi.request({
+ token: context.auth.secret_text,
+ method: HttpMethod.DELETE,
+ path: `${codaApi.docPath(id)}/acl/permissions/${codaApi.pathSegment({ value: permission, label: 'Permission ID' })}`,
+ operation: 'remove sharing',
+ });
+ return { docId: id, permissionId: permission, removed: true, alreadyRemoved: false };
+ } catch (error) {
+ if (codaApi.statusOf(error) === 404) {
+ return { docId: id, permissionId: permission, removed: true, alreadyRemoved: true };
+ }
+ throw error;
+ }
+ },
+});
diff --git a/packages/pieces/community/coda/src/lib/actions/trigger-automation.ts b/packages/pieces/community/coda/src/lib/actions/trigger-automation.ts
new file mode 100644
index 00000000000..e11aaa2a79e
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/trigger-automation.ts
@@ -0,0 +1,45 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../auth';
+import { codaApi } from '../common/client';
+import { codaProps } from '../common/ai-props';
+import { triggerAutomationActionOutputSchema } from '../output-schemas';
+
+export const triggerAutomationAction = createAction({
+ auth: codaAuth,
+ name: 'trigger_automation',
+ classification: 'WRITE',
+ displayName: 'Trigger Automation',
+ description: 'Runs a doc automation whose trigger is "Webhook invoked", optionally passing a JSON payload.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Runs a Coda automation rule set to "Webhook invoked", passing an optional JSON payload the rule can read. The rule does whatever the doc owner configured (edit rows, notify people). Use only for that rule ID. Not idempotent: each call runs the rule again.',
+ idempotent: false,
+ },
+ props: {
+ docId: codaProps.docId(),
+ ruleId: Property.ShortText({
+ displayName: 'Automation Rule ID',
+ description: 'In the doc, open Automations, pick the rule with the "Webhook invoked" trigger, and copy its rule ID (it looks like grid-auto-xxxx).',
+ required: true,
+ }),
+ payload: Property.Json({
+ displayName: 'Payload',
+ description: 'Optional JSON object the automation can read as its webhook payload.',
+ required: false,
+ }),
+ },
+ outputSchema: triggerAutomationActionOutputSchema,
+ async run(context) {
+ const { docId, ruleId, payload } = context.propsValue;
+ const body = codaApi.parseJsonInput({ value: payload, label: 'Payload' });
+ const response = await codaApi.request<{ requestId?: string }>({
+ token: context.auth.secret_text,
+ method: HttpMethod.POST,
+ path: `${codaApi.docPath(docId)}/hooks/automation/${codaApi.pathSegment({ value: ruleId, label: 'Automation Rule ID' })}`,
+ operation: 'trigger automation',
+ body: body ?? {},
+ });
+ return { ruleId: ruleId.trim(), requestId: response.requestId ?? null };
+ },
+});
diff --git a/packages/pieces/community/coda/src/lib/actions/update-page.ts b/packages/pieces/community/coda/src/lib/actions/update-page.ts
new file mode 100644
index 00000000000..6d80000d49e
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/update-page.ts
@@ -0,0 +1,106 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../auth';
+import { codaApi } from '../common/client';
+import { codaProps } from '../common/ai-props';
+import { pageMutationActionOutputSchema } from '../output-schemas';
+
+export const updatePageAction = createAction({
+ auth: codaAuth,
+ name: 'update_page',
+ classification: 'WRITE',
+ displayName: 'Update Page',
+ description: 'Renames, hides or shows a page, and can append, prepend or replace its content.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Changes a Coda page\'s name, subtitle, icon or hidden state, and can append, prepend or replace its content with Markdown or HTML. Use Replace only when the user wants the page overwritten. Append and Prepend are not idempotent: each call adds the content again.',
+ idempotent: false,
+ },
+ props: {
+ docId: codaProps.docId(),
+ pageIdOrName: codaProps.pageIdOrName(),
+ name: Property.ShortText({
+ displayName: 'New Page Name',
+ required: false,
+ }),
+ subtitle: Property.ShortText({
+ displayName: 'New Subtitle',
+ required: false,
+ }),
+ iconName: Property.ShortText({
+ displayName: 'New Icon Name',
+ required: false,
+ }),
+ visibility: Property.StaticDropdown({
+ displayName: 'Visibility',
+ description: 'Hiding pages needs a paid Coda plan.',
+ required: false,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Hide page', value: 'hidden' },
+ { label: 'Show page', value: 'visible' },
+ ],
+ },
+ }),
+ content: Property.LongText({
+ displayName: 'Content',
+ description: 'Optional content to add to the page.',
+ required: false,
+ }),
+ insertionMode: Property.StaticDropdown({
+ displayName: 'Content Placement',
+ description: 'Where the content goes. Replace overwrites everything on the page.',
+ required: false,
+ defaultValue: 'append',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Append to the end', value: 'append' },
+ { label: 'Prepend to the start', value: 'prepend' },
+ { label: 'Replace the whole page', value: 'replace' },
+ ],
+ },
+ }),
+ contentFormat: codaProps.contentFormat(),
+ waitForCompletion: codaProps.waitForCompletion(),
+ },
+ outputSchema: pageMutationActionOutputSchema,
+ async run(context) {
+ const { docId, pageIdOrName, name, subtitle, iconName, visibility, content, insertionMode, contentFormat, waitForCompletion } =
+ context.propsValue;
+ const hasContent = content !== undefined && content !== null && content.trim().length > 0;
+ const body = {
+ ...(name?.trim() ? { name: name.trim() } : {}),
+ ...(subtitle?.trim() ? { subtitle: subtitle.trim() } : {}),
+ ...(iconName?.trim() ? { iconName: iconName.trim() } : {}),
+ ...(visibility ? { isHidden: visibility === 'hidden' } : {}),
+ ...(hasContent
+ ? {
+ contentUpdate: {
+ insertionMode: insertionMode ?? 'append',
+ canvasContent: { format: contentFormat ?? 'markdown', content },
+ },
+ }
+ : {}),
+ };
+ if (Object.keys(body).length === 0) {
+ throw new Error('Nothing to update: give a new name, subtitle, icon, visibility or some content.');
+ }
+ const token = context.auth.secret_text;
+ const response = await codaApi.request<PageMutationResponse>({
+ token,
+ method: HttpMethod.PUT,
+ path: `${codaApi.docPath(docId)}/pages/${codaApi.pathSegment({ value: pageIdOrName, label: 'Page ID or name' })}`,
+ operation: 'update page',
+ body,
+ });
+ const mutation = await codaApi.settleMutation({ token, requestId: response.requestId, waitForCompletion });
+ return { id: response.id, ...mutation };
+ },
+});
+
+type PageMutationResponse = {
+ id: string;
+ requestId?: string;
+};
diff --git a/packages/pieces/community/coda/src/lib/actions/update-row.ts b/packages/pieces/community/coda/src/lib/actions/update-row.ts
index 70c43c0e3b5..bb343081cdb 100644
--- a/packages/pieces/community/coda/src/lib/actions/update-row.ts
+++ b/packages/pieces/community/coda/src/lib/actions/update-row.ts
@@ -11,7 +11,7 @@ export const updateRowAction = createAction({
classification: 'WRITE',
displayName: 'Update Row',
description: 'Updates an existing row in the selected table.',
- audience: 'both',
+ audience: 'human',
aiMetadata: { description: 'Overwrite cell values on an existing Coda table row, identified by its row ID or a unique row name. Use when you already know which row to change; use Upsert Row instead when the row may not yet exist. Idempotent — repeating with the same values leaves the row in the same state.', idempotent: true },
props: {
docId: docIdDropdown,
@@ -27,13 +27,17 @@ export const updateRowAction = createAction({
const { docId, tableId, rowIdOrName, rowData } = context.propsValue;
const client = codaClient(context.auth);
- const cells = Object.entries(rowData as Record<string, any>)
+ const cells = Object.entries(rowData ?? {})
.filter(([, value]) => value !== undefined && value !== null && value !== '')
.map(([columnId, value]) => ({
column: columnId,
value: value,
}));
+ if (cells.length === 0) {
+ throw new Error('Provide at least one column value to update the row.');
+ }
+
const payload = {
row: {
cells: cells,
@@ -50,6 +54,6 @@ export const updateRowAction = createAction({
throw new Error(`Unexpected error occured : ${JSON.stringify(response)}`);
}
- return { rowId };
+ return { rowId, requestId: response.requestId };
},
});
diff --git a/packages/pieces/community/coda/src/lib/actions/upsert-row.ts b/packages/pieces/community/coda/src/lib/actions/upsert-row.ts
index 0c8acbd66c3..51e10fc92d5 100644
--- a/packages/pieces/community/coda/src/lib/actions/upsert-row.ts
+++ b/packages/pieces/community/coda/src/lib/actions/upsert-row.ts
@@ -7,6 +7,7 @@ import {
tableIdDropdown,
tableRowsDynamicProps,
} from '../common/props';
+import { upsertRowActionOutputSchema } from '../output-schemas';
export const upsertRowAction = createAction({
auth: codaAuth,
@@ -14,7 +15,7 @@ export const upsertRowAction = createAction({
classification: 'WRITE',
displayName: 'Upsert Row',
description: 'Creates a new row or updates an existing one if it matches key columns.',
- audience: 'both',
+ audience: 'human',
aiMetadata: { description: 'Insert a row into a Coda table, or update an existing row when its values match the chosen key columns. Use when you want create-or-update semantics keyed on stable columns rather than a known row ID. Idempotent when key columns uniquely identify a row — repeating the same input converges to one matching row; with no matching columns it behaves like an insert.', idempotent: true },
props: {
docId: docIdDropdown,
@@ -22,24 +23,37 @@ export const upsertRowAction = createAction({
keyColumns: columnIdsDropdown('Matching Columns', false),
rowData: tableRowsDynamicProps,
},
+ outputSchema: upsertRowActionOutputSchema,
async run(context) {
const { docId, tableId, rowData, keyColumns } = context.propsValue;
const client = codaClient(context.auth);
- const cells = Object.entries(rowData as Record<string, any>)
+ const cells = Object.entries(rowData ?? {})
.filter(([, value]) => value !== undefined && value !== null && value !== '')
.map(([columnId, value]) => ({
column: columnId,
value: value,
}));
+ if (cells.length === 0) {
+ throw new Error('Provide at least one column value to upsert the row.');
+ }
+ const matchingColumns = Array.isArray(keyColumns) ? keyColumns : keyColumns ? [keyColumns] : [];
+ const filledColumns = new Set(cells.map((cell) => cell.column));
+ const missingKeys = matchingColumns.filter((column) => !filledColumns.has(column));
+ if (missingKeys.length > 0) {
+ throw new Error(
+ `Every matching column needs a value in Row Data, otherwise Coda cannot find the existing row. Missing values for: ${missingKeys.join(', ')}.`,
+ );
+ }
+
const payload = {
rows: [
{
cells: cells,
},
],
- keyColumns: keyColumns as string[],
+ keyColumns: matchingColumns,
};
const response = await client.mutateRows(docId, tableId, payload, {
@@ -50,6 +64,6 @@ export const upsertRowAction = createAction({
throw new Error(`Unexpected error occured : ${JSON.stringify(response)}`);
}
- return { success: true };
+ return { success: true, requestId: response.requestId };
},
});
diff --git a/packages/pieces/community/coda/src/lib/actions/upsert-rows.ts b/packages/pieces/community/coda/src/lib/actions/upsert-rows.ts
new file mode 100644
index 00000000000..919d7ffcd35
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/actions/upsert-rows.ts
@@ -0,0 +1,71 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { codaAuth } from '../auth';
+import { codaApi } from '../common/client';
+import { codaProps } from '../common/ai-props';
+import { rowInput } from '../common/row-input';
+import { upsertRowsActionOutputSchema } from '../output-schemas';
+
+export const upsertRowsAction = createAction({
+ auth: codaAuth,
+ name: 'upsert_rows',
+ classification: 'WRITE',
+ displayName: 'Upsert Rows',
+ description: 'Updates rows whose key columns match, and adds the rest as new rows.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Inserts rows or updates existing ones whose key-column values match; every matching row is updated, so pick key columns that are unique. Each row must include all key columns. Use for create-or-update sync on stable keys. Repeating the same input converges to the same rows, so it is idempotent.',
+ idempotent: true,
+ },
+ props: {
+ docId: codaProps.docId(),
+ tableIdOrName: codaProps.tableIdOrName(),
+ keyColumns: Property.Array({
+ displayName: 'Key Columns',
+ description: 'Column names or IDs that identify a row, for example Email.',
+ required: true,
+ }),
+ rows: Property.Json({
+ displayName: 'Rows',
+ description: 'A list of rows, each an object of column name or ID → value, including every key column. Example: [{"Email": "[email protected]", "Amount": 5}]',
+ required: true,
+ defaultValue: [{ Name: 'Example' }],
+ }),
+ disableParsing: Property.Checkbox({
+ displayName: 'Store Values Exactly as Given',
+ description: 'When on, Coda does not convert text like "5" or "2026-01-31" into numbers or dates.',
+ required: false,
+ defaultValue: false,
+ }),
+ waitForCompletion: codaProps.waitForCompletion(),
+ },
+ outputSchema: upsertRowsActionOutputSchema,
+ async run(context) {
+ const { docId, tableIdOrName, keyColumns, rows, disableParsing, waitForCompletion } = context.propsValue;
+ const keys = rowInput.toStringList({ value: keyColumns, label: 'Key Columns' });
+ if (keys.length === 0) {
+ throw new Error('Give at least one key column. Use Add Rows if you only want to insert.');
+ }
+ const rowList = rowInput.toRows({ value: rows, label: 'Rows' });
+ rowList.forEach((row, index) => {
+ const missing = keys.filter((key) => !rowInput.hasValue(row[key]));
+ if (missing.length > 0) {
+ throw new Error(`Row ${index + 1} has no value for key column(s) ${missing.join(', ')}. Use the same column names or IDs in Rows as in Key Columns.`);
+ }
+ });
+ const token = context.auth.secret_text;
+ const response = await codaApi.request<{ requestId?: string }>({
+ token,
+ method: HttpMethod.POST,
+ path: `${codaApi.tablePath({ docId, tableIdOrName })}/rows`,
+ operation: 'upsert rows',
+ query: { disableParsing: disableParsing === true ? true : undefined },
+ body: {
+ rows: rowList.map((row, index) => ({ cells: rowInput.insertCells({ row, rowNumber: index + 1 }) })),
+ keyColumns: keys,
+ },
+ });
+ const mutation = await codaApi.settleMutation({ token, requestId: response.requestId, waitForCompletion });
+ return { rowCount: rowList.length, ...mutation };
+ },
+});
diff --git a/packages/pieces/community/coda/src/lib/auth.ts b/packages/pieces/community/coda/src/lib/auth.ts
index fa6c76fa513..8c01ab83d5a 100644
--- a/packages/pieces/community/coda/src/lib/auth.ts
+++ b/packages/pieces/community/coda/src/lib/auth.ts
@@ -1,7 +1,26 @@
+import { HttpMethod } from '@activepieces/pieces-common';
import { PieceAuth } from '@activepieces/pieces-framework';
+import { codaApi } from './common/client';
export const codaAuth = PieceAuth.SecretText({
displayName: 'Coda API Key',
- description: `Create an API key in the [Coda Account dashboard](https://coda.io/account).`,
+ description: `Create an API token in Coda (now Superhuman Docs): open [Account settings](https://coda.io/account), scroll to **API settings**, click **Generate API token**, and paste it here.`,
required: true,
+ validate: async ({ auth }) => {
+ try {
+ await codaApi.request({
+ token: auth,
+ method: HttpMethod.GET,
+ path: '/whoami',
+ operation: 'check API token',
+ });
+ return { valid: true };
+ } catch (error) {
+ const status = codaApi.statusOf(error);
+ if (status === 401 || status === 403) {
+ return { valid: false, error: 'Invalid API token. Generate a new token in Coda account settings and try again.' };
+ }
+ return { valid: false, error: error instanceof Error ? error.message : 'Could not reach Coda to check the API token.' };
+ }
+ },
});
diff --git a/packages/pieces/community/coda/src/lib/common/ai-props.ts b/packages/pieces/community/coda/src/lib/common/ai-props.ts
new file mode 100644
index 00000000000..c9931c91945
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/common/ai-props.ts
@@ -0,0 +1,85 @@
+import { Property } from '@activepieces/pieces-framework';
+
+function docId() {
+ return Property.ShortText({
+ displayName: 'Doc ID or Link',
+ description: 'The doc ID (for example AbC123xyZ) or the doc\'s browser link. Use List Docs to find it.',
+ required: true,
+ });
+}
+
+function tableIdOrName() {
+ return Property.ShortText({
+ displayName: 'Table ID or Name',
+ description: 'The table ID (starts with "grid-" or "table-") or its exact name. IDs are safer: names can change or repeat. Use List Tables to find it.',
+ required: true,
+ });
+}
+
+function rowIdOrName() {
+ return Property.ShortText({
+ displayName: 'Row ID',
+ description: 'The row ID (starts with "i-"), for example from List Rows. A display-column value also works, but if several rows share it Coda picks one at random.',
+ required: true,
+ });
+}
+
+function pageIdOrName() {
+ return Property.ShortText({
+ displayName: 'Page ID or Name',
+ description: 'The page ID (starts with "canvas-") or its exact name. Use List Pages to find it.',
+ required: true,
+ });
+}
+
+function limit({ max, defaultValue }: { max: number; defaultValue: number }) {
+ return Property.Number({
+ displayName: 'Limit',
+ description: `How many items to return in this page (1-${max}).`,
+ required: false,
+ defaultValue,
+ });
+}
+
+function pageToken() {
+ return Property.ShortText({
+ displayName: 'Page Token',
+ description: 'Leave empty for the first page. To get the next page, pass the Next Page Token from the previous result.',
+ required: false,
+ });
+}
+
+function waitForCompletion() {
+ return Property.Checkbox({
+ displayName: 'Wait for Coda to Apply',
+ description: 'Coda applies changes in the background. When on, the step waits up to 30 seconds until the change is applied; if it takes longer, the step still succeeds with Completed = false and you can check later with Get Mutation Status.',
+ required: false,
+ defaultValue: true,
+ });
+}
+
+function contentFormat() {
+ return Property.StaticDropdown({
+ displayName: 'Content Format',
+ required: false,
+ defaultValue: 'markdown',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Markdown', value: 'markdown' },
+ { label: 'HTML', value: 'html' },
+ ],
+ },
+ });
+}
+
+export const codaProps = {
+ docId,
+ tableIdOrName,
+ rowIdOrName,
+ pageIdOrName,
+ limit,
+ pageToken,
+ waitForCompletion,
+ contentFormat,
+};
diff --git a/packages/pieces/community/coda/src/lib/common/client.ts b/packages/pieces/community/coda/src/lib/common/client.ts
new file mode 100644
index 00000000000..bf032bf130b
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/common/client.ts
@@ -0,0 +1,407 @@
+import {
+ AuthenticationType,
+ HttpMethod,
+ HttpRequest,
+ httpClient,
+} from '@activepieces/pieces-common';
+
+const REQUEST_TIMEOUT_MS = 30_000;
+const RATE_LIMIT_RETRY_DELAYS_MS = [3_000, 6_000];
+const MUTATION_POLL_DELAYS_MS = [1_000, 2_000, 3_000];
+const MUTATION_POLL_STEP_MS = 3_000;
+const DEFAULT_MUTATION_WAIT_MS = 30_000;
+const MIN_POLL_REQUEST_MS = 1_000;
+const MAX_ERROR_TEXT = 500;
+const DOC_LINK_HOSTS = ['coda.io', 'docs.superhuman.com'];
+const DOC_ID_PATTERN = /^[A-Za-z0-9_-]+$/;
+const COLUMN_ID_PATTERN = /^c-[A-Za-z0-9_-]+$/;
+
+export class CodaApiError extends Error {
+ readonly status: number;
+ readonly responseBody: unknown;
+
+ constructor({ operation, status, responseBody }: { operation: string; status: number; responseBody: unknown }) {
+ super(`Coda ${operation} failed (${status}): ${describeStatus({ status, responseBody })}`);
+ this.name = 'CodaApiError';
+ this.status = status;
+ this.responseBody = responseBody;
+ }
+}
+
+function vendorMessage(responseBody: unknown): string {
+ if (typeof responseBody === 'string') {
+ return responseBody.slice(0, MAX_ERROR_TEXT);
+ }
+ if (isRecord(responseBody)) {
+ const message = responseBody['message'] ?? responseBody['statusMessage'];
+ if (typeof message === 'string' && message.length > 0) {
+ return message.slice(0, MAX_ERROR_TEXT);
+ }
+ return JSON.stringify(responseBody).slice(0, MAX_ERROR_TEXT);
+ }
+ return 'no details returned';
+}
+
+function describeStatus({ status, responseBody }: { status: number; responseBody: unknown }): string {
+ const detail = vendorMessage(responseBody);
+ switch (status) {
+ case 401:
+ return `the API token is invalid or was revoked. ${detail}`;
+ case 403:
+ return `Coda refused the request (no access to this doc, or not allowed on this workspace plan). ${detail}`;
+ case 404:
+ return `not found. Check the IDs or names you passed. ${detail}`;
+ case 409:
+ return `the doc is not available to the API yet (for example just created or copied); try again in a moment. ${detail}`;
+ case 410:
+ return `the object was deleted. ${detail}`;
+ case 429:
+ return `Coda rate limit reached, try again in a few seconds. ${detail}`;
+ default:
+ return detail;
+ }
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+function statusOf(error: unknown): number | undefined {
+ if (error instanceof CodaApiError) {
+ return error.status;
+ }
+ if (!isRecord(error) && !(error instanceof Error)) {
+ return undefined;
+ }
+ const response: unknown = Reflect.get(error, 'response');
+ if (isRecord(response) && typeof response['status'] === 'number') {
+ return response['status'];
+ }
+ return undefined;
+}
+
+function responseBodyOf(error: unknown): unknown {
+ if (!isRecord(error) && !(error instanceof Error)) {
+ return undefined;
+ }
+ const response: unknown = Reflect.get(error, 'response');
+ return isRecord(response) ? response['body'] : undefined;
+}
+
+function pathSegment({ value, label }: { value: unknown; label: string }): string {
+ if (value === undefined || value === null) {
+ throw new Error(`${label} is required.`);
+ }
+ const text = String(value).trim();
+ if (text.length === 0) {
+ throw new Error(`${label} is required.`);
+ }
+ if (text === '.' || text === '..') {
+ throw new Error(`${label} "${text}" is not a valid Coda ID or name.`);
+ }
+ return encodeURIComponent(text);
+}
+
+function parseDocId(input: unknown): string {
+ if (input === undefined || input === null || String(input).trim() === '') {
+ throw new Error('Doc ID is required.');
+ }
+ const text = String(input).trim();
+ if (!/^https?:\/\//i.test(text)) {
+ if (!DOC_ID_PATTERN.test(text)) {
+ throw new Error(`"${text}" is not a valid Coda doc ID. Pass the ID (for example AbC123xyZ) or the doc's browser link.`);
+ }
+ return text;
+ }
+ const url = safeUrl(text);
+ const host = url?.hostname.toLowerCase().replace(/^www\./, '');
+ if (!url || !host || !DOC_LINK_HOSTS.includes(host)) {
+ throw new Error(`"${text}" is not a Coda doc link (expected coda.io or docs.superhuman.com).`);
+ }
+ const parts = url.pathname.split('/').filter((part) => part.length > 0);
+ const slug = parts[0] === 'd' ? parts[1] : undefined;
+ const marker = slug ? slug.lastIndexOf('_d') : -1;
+ const id = slug && marker >= 0 ? slug.slice(marker + 2) : undefined;
+ if (!id || !DOC_ID_PATTERN.test(id)) {
+ throw new Error(`Could not find a doc ID in "${text}". Paste a link like https://coda.io/d/My-Doc_dAbC123 or the doc ID itself.`);
+ }
+ return id;
+}
+
+function safeUrl(text: string): URL | undefined {
+ try {
+ return new URL(text);
+ } catch {
+ return undefined;
+ }
+}
+
+function docPath(docId: unknown): string {
+ return `/docs/${pathSegment({ value: parseDocId(docId), label: 'Doc ID' })}`;
+}
+
+function tablePath({ docId, tableIdOrName }: { docId: unknown; tableIdOrName: unknown }): string {
+ return `${docPath(docId)}/tables/${pathSegment({ value: tableIdOrName, label: 'Table ID or name' })}`;
+}
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+function toQueryParams(query: Record<string, CodaQueryValue> | undefined): Record<string, string> {
+ if (!query) {
+ return {};
+ }
+ return Object.fromEntries(
+ Object.entries(query)
+ .filter(([, value]) => value !== undefined && value !== null && value !== '')
+ .map(([key, value]) => [key, String(value)]),
+ );
+}
+
+function authHeaders(token: string): Record<string, string> {
+ return { Authorization: `Bearer ${token.trim()}` };
+}
+
+async function request<T>({ token, method, path, operation, query, body, wait = sleep, timeoutMs = REQUEST_TIMEOUT_MS, retryRateLimits = true }: CodaRequest): Promise<T> {
+ const httpRequest: HttpRequest = {
+ method,
+ url: `${CODA_BASE_URL}${path}`,
+ authentication: { type: AuthenticationType.BEARER_TOKEN, token: token.trim() },
+ queryParams: toQueryParams(query),
+ timeout: timeoutMs,
+ followRedirects: false,
+ };
+ if (body !== undefined) {
+ httpRequest.body = body;
+ httpRequest.headers = { 'Content-Type': 'application/json' };
+ }
+ for (let attempt = 0; ; attempt++) {
+ try {
+ const response = await httpClient.sendRequest<T>(httpRequest);
+ if (response.status >= 300) {
+ throw new CodaApiError({ operation, status: response.status, responseBody: response.body });
+ }
+ return response.body;
+ } catch (error) {
+ if (error instanceof CodaApiError) {
+ throw error;
+ }
+ const status = statusOf(error);
+ if (status === undefined) {
+ throw error;
+ }
+ if (retryRateLimits && (status === 429 || status === 409) && attempt < RATE_LIMIT_RETRY_DELAYS_MS.length) {
+ await wait(RATE_LIMIT_RETRY_DELAYS_MS[attempt]);
+ continue;
+ }
+ throw new CodaApiError({ operation, status, responseBody: responseBodyOf(error) });
+ }
+ }
+}
+
+async function getMutationStatus({ token, requestId, timeoutMs }: { token: string; requestId: string; timeoutMs?: number }): Promise<MutationStatus> {
+ return request<MutationStatus>({
+ token,
+ method: HttpMethod.GET,
+ path: `/mutationStatus/${pathSegment({ value: requestId, label: 'Request ID' })}`,
+ operation: 'get mutation status',
+ timeoutMs,
+ retryRateLimits: timeoutMs === undefined,
+ });
+}
+
+function isTransientPollError(error: unknown): boolean {
+ const status = statusOf(error);
+ return status === undefined || status === 404 || status === 408 || status === 409 || status === 429 || status >= 500;
+}
+
+function pollRequestBudget({ deadline, now }: { deadline: number; now: () => number }): number | undefined {
+ const remaining = deadline - now();
+ return remaining < MIN_POLL_REQUEST_MS ? undefined : Math.min(REQUEST_TIMEOUT_MS, remaining);
+}
+
+async function withinBudget<T>({ task, ms }: { task: Promise<T>; ms: number }): Promise<{ done: true; value: T } | { done: false }> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const expired = new Promise<{ done: false }>((resolve) => {
+ timer = setTimeout(() => resolve({ done: false }), ms);
+ });
+ task.catch(() => undefined);
+ try {
+ return await Promise.race([task.then((value) => ({ done: true as const, value })), expired]);
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+async function waitForMutation({
+ token,
+ requestId,
+ timeoutMs = DEFAULT_MUTATION_WAIT_MS,
+ now = Date.now,
+ wait = sleep,
+}: {
+ token: string;
+ requestId: string;
+ timeoutMs?: number;
+ now?: () => number;
+ wait?: (ms: number) => Promise<void>;
+}): Promise<MutationWaitResult> {
+ pathSegment({ value: requestId, label: 'Request ID' });
+ const deadline = now() + timeoutMs;
+ for (let attempt = 0; ; attempt++) {
+ const remaining = deadline - now();
+ if (remaining <= 0) {
+ return { requestId, completed: false, warning: null };
+ }
+ await wait(Math.min(MUTATION_POLL_DELAYS_MS[attempt] ?? MUTATION_POLL_STEP_MS, remaining));
+ const budget = pollRequestBudget({ deadline, now });
+ if (budget === undefined) {
+ return { requestId, completed: false, warning: null };
+ }
+ try {
+ const poll = await withinBudget({ task: getMutationStatus({ token, requestId, timeoutMs: budget }), ms: budget });
+ if (poll.done && poll.value.completed) {
+ return { requestId, completed: true, warning: poll.value.warning ?? null };
+ }
+ } catch (error) {
+ if (!isTransientPollError(error)) {
+ return {
+ requestId,
+ completed: false,
+ warning: `Coda accepted the change, but checking its status failed, so do not repeat it. Check it later with Get Mutation Status. ${error instanceof Error ? error.message : String(error)}`,
+ };
+ }
+ }
+ }
+}
+
+async function settleMutation({
+ token,
+ requestId,
+ waitForCompletion,
+ wait,
+ now,
+}: {
+ token: string;
+ requestId: string | undefined;
+ waitForCompletion: boolean | undefined;
+ wait?: (ms: number) => Promise<void>;
+ now?: () => number;
+}): Promise<MutationWaitResult> {
+ if (!requestId) {
+ throw new Error('Coda accepted the request but returned no request ID, so its outcome cannot be checked.');
+ }
+ if (waitForCompletion === false) {
+ return { requestId, completed: false, warning: null };
+ }
+ return waitForMutation({ token, requestId, wait, now });
+}
+
+function toPageOutput<T>(page: CodaPage<T>): PageOutput<T> {
+ const nextPageToken = page.nextPageToken ?? null;
+ return { items: page.items ?? [], nextPageToken, hasMore: nextPageToken !== null };
+}
+
+function validateLimit({ limit, max }: { limit: unknown; max: number }): number | undefined {
+ if (limit === undefined || limit === null || limit === '') {
+ return undefined;
+ }
+ const value = Number(limit);
+ if (!Number.isInteger(value) || value < 1 || value > max) {
+ throw new Error(`Limit must be a whole number between 1 and ${max}.`);
+ }
+ return value;
+}
+
+function formatQueryValue(value: unknown): string {
+ if ((typeof value === 'number' && Number.isFinite(value)) || typeof value === 'boolean') {
+ return String(value);
+ }
+ return JSON.stringify(String(value ?? ''));
+}
+
+function formatQueryColumn(columnIdOrName: string): string {
+ const text = columnIdOrName.trim();
+ return COLUMN_ID_PATTERN.test(text) ? text : JSON.stringify(text);
+}
+
+function buildRowQuery({ column, value }: { column: string; value: unknown }): string {
+ return `${formatQueryColumn(column)}:${formatQueryValue(value)}`;
+}
+
+function parseJsonInput({ value, label }: { value: unknown; label: string }): unknown {
+ if (typeof value !== 'string') {
+ return value;
+ }
+ const text = value.trim();
+ if (text.length === 0) {
+ return undefined;
+ }
+ try {
+ return JSON.parse(text);
+ } catch {
+ throw new Error(`${label} must be valid JSON.`);
+ }
+}
+
+export const CODA_BASE_URL = 'https://coda.io/apis/v1';
+
+export const codaApi = {
+ request,
+ authHeaders,
+ pathSegment,
+ parseDocId,
+ docPath,
+ tablePath,
+ getMutationStatus,
+ waitForMutation,
+ settleMutation,
+ toPageOutput,
+ validateLimit,
+ isTransientPollError,
+ pollRequestBudget,
+ withinBudget,
+ buildRowQuery,
+ statusOf,
+ isRecord,
+ parseJsonInput,
+ sleep,
+};
+
+export type CodaQueryValue = string | number | boolean | undefined | null;
+
+export type CodaRequest = {
+ token: string;
+ method: HttpMethod;
+ path: string;
+ operation: string;
+ query?: Record<string, CodaQueryValue>;
+ body?: unknown;
+ wait?: (ms: number) => Promise<void>;
+ timeoutMs?: number;
+ retryRateLimits?: boolean;
+};
+
+export type MutationStatus = {
+ completed: boolean;
+ warning?: string;
+};
+
+export type MutationWaitResult = {
+ requestId: string;
+ completed: boolean;
+ warning: string | null;
+};
+
+export type CodaPage<T> = {
+ items: T[];
+ nextPageToken?: string;
+ nextSyncToken?: string;
+};
+
+export type PageOutput<T> = {
+ items: T[];
+ nextPageToken: string | null;
+ hasMore: boolean;
+};
diff --git a/packages/pieces/community/coda/src/lib/common/page-export.ts b/packages/pieces/community/coda/src/lib/common/page-export.ts
new file mode 100644
index 00000000000..4bc074f76fa
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/common/page-export.ts
@@ -0,0 +1,159 @@
+import { HttpMethod, httpClient } from '@activepieces/pieces-common';
+import { Readable } from 'node:stream';
+import { codaApi } from './client';
+
+const EXPORT_WAIT_MS = 60_000;
+const EXPORT_POLL_DELAYS_MS = [1_000, 2_000, 3_000];
+const EXPORT_POLL_STEP_MS = 3_000;
+const DOWNLOAD_TIMEOUT_MS = 30_000;
+const MAX_CONTENT_BYTES = 5 * 1024 * 1024;
+
+async function startExport({ token, pagePath, format }: { token: string; pagePath: string; format: ExportFormat }): Promise<ExportStatus> {
+ return codaApi.request<ExportStatus>({
+ token,
+ method: HttpMethod.POST,
+ path: `${pagePath}/export`,
+ operation: 'start page export',
+ body: { outputFormat: format },
+ });
+}
+
+async function getExportStatus({
+ token,
+ pagePath,
+ exportId,
+ timeoutMs,
+}: {
+ token: string;
+ pagePath: string;
+ exportId: string;
+ timeoutMs?: number;
+}): Promise<ExportStatus> {
+ return codaApi.request<ExportStatus>({
+ token,
+ method: HttpMethod.GET,
+ path: `${pagePath}/export/${codaApi.pathSegment({ value: exportId, label: 'Export ID' })}`,
+ operation: 'check page export',
+ timeoutMs,
+ retryRateLimits: timeoutMs === undefined,
+ });
+}
+
+async function waitForExport({
+ token,
+ pagePath,
+ exportId,
+ wait = codaApi.sleep,
+ now = Date.now,
+}: {
+ token: string;
+ pagePath: string;
+ exportId: string;
+ wait?: (ms: number) => Promise<void>;
+ now?: () => number;
+}): Promise<ExportStatus | undefined> {
+ codaApi.pathSegment({ value: exportId, label: 'Export ID' });
+ const deadline = now() + EXPORT_WAIT_MS;
+ for (let attempt = 0; ; attempt++) {
+ const budget = codaApi.pollRequestBudget({ deadline, now });
+ if (budget === undefined) {
+ return undefined;
+ }
+ const status = await pollExport({ token, pagePath, exportId, timeoutMs: budget });
+ if (status?.status === 'complete') {
+ return status;
+ }
+ if (status?.status === 'failed') {
+ throw new Error(`Coda could not export the page: ${status.error ?? 'no reason given'}`);
+ }
+ const remaining = deadline - now();
+ if (remaining <= 0) {
+ return undefined;
+ }
+ await wait(Math.min(EXPORT_POLL_DELAYS_MS[attempt] ?? EXPORT_POLL_STEP_MS, remaining));
+ }
+}
+
+async function pollExport(params: { token: string; pagePath: string; exportId: string; timeoutMs: number }): Promise<ExportStatus | undefined> {
+ try {
+ const poll = await codaApi.withinBudget({ task: getExportStatus(params), ms: params.timeoutMs });
+ return poll.done ? poll.value : undefined;
+ } catch (error) {
+ if (codaApi.statusOf(error) !== 404 && codaApi.isTransientPollError(error)) {
+ return undefined;
+ }
+ throw error;
+ }
+}
+
+async function downloadText({ url, format }: { url: string; format: ExportFormat }): Promise<{ content: string; truncated: boolean }> {
+ if (!url.startsWith('https://')) {
+ throw new Error('Coda returned an export link that is not HTTPS, so it was not downloaded.');
+ }
+ const response = await httpClient.sendRequest<Readable>({
+ method: HttpMethod.GET,
+ url,
+ responseType: 'stream',
+ timeout: DOWNLOAD_TIMEOUT_MS,
+ headers: { Accept: format === 'html' ? 'text/html, text/plain, */*' : 'text/markdown, text/plain, */*' },
+ });
+ return readCapped({ stream: response.body, maxBytes: MAX_CONTENT_BYTES, timeoutMs: DOWNLOAD_TIMEOUT_MS });
+}
+
+function readCapped({ stream, maxBytes, timeoutMs }: { stream: Readable; maxBytes: number; timeoutMs: number }): Promise<{ content: string; truncated: boolean }> {
+ return new Promise((resolve, reject) => {
+ const chunks: Buffer[] = [];
+ let size = 0;
+ let settled = false;
+ const finish = (result: { content: string; truncated: boolean } | Error) => {
+ if (settled) {
+ return;
+ }
+ settled = true;
+ clearTimeout(timer);
+ if (result instanceof Error) {
+ reject(result);
+ } else {
+ resolve(result);
+ }
+ };
+ const timer = setTimeout(() => {
+ stream.destroy();
+ finish(new Error('Downloading the page export took longer than 30 seconds.'));
+ }, timeoutMs);
+ stream.on('data', (chunk: Buffer | string) => {
+ const buffer = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
+ const room = maxBytes - size;
+ if (buffer.length > room) {
+ chunks.push(buffer.subarray(0, room));
+ size += room;
+ stream.destroy();
+ finish({ content: Buffer.concat(chunks).toString('utf8'), truncated: true });
+ return;
+ }
+ chunks.push(buffer);
+ size += buffer.length;
+ });
+ stream.on('end', () => finish({ content: Buffer.concat(chunks).toString('utf8'), truncated: false }));
+ stream.on('error', (error) => finish(error));
+ });
+}
+
+export const pageExport = {
+ startExport,
+ getExportStatus,
+ waitForExport,
+ downloadText,
+ readCapped,
+ MAX_CONTENT_BYTES,
+};
+
+export type ExportFormat = 'markdown' | 'html';
+
+export type ExportStatus = {
+ id: string;
+ status: 'inProgress' | 'failed' | 'complete' | string;
+ href?: string;
+ downloadLink?: string;
+ error?: string;
+};
diff --git a/packages/pieces/community/coda/src/lib/common/permissions.ts b/packages/pieces/community/coda/src/lib/common/permissions.ts
new file mode 100644
index 00000000000..9a1b3e121d1
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/common/permissions.ts
@@ -0,0 +1,77 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { CodaPage, codaApi } from './client';
+
+const PERMISSION_PAGE_SIZE = 100;
+const MAX_LOOKUP_PAGES = 10;
+
+async function listPermissions({
+ token,
+ docId,
+ limit,
+ pageToken,
+}: {
+ token: string;
+ docId: string;
+ limit?: number;
+ pageToken?: string;
+}): Promise<CodaPage<CodaPermission>> {
+ return codaApi.request<CodaPage<CodaPermission>>({
+ token,
+ method: HttpMethod.GET,
+ path: `${codaApi.docPath(docId)}/acl/permissions`,
+ operation: 'list sharing',
+ query: { limit, pageToken },
+ });
+}
+
+async function findPermission({
+ token,
+ docId,
+ principal,
+}: {
+ token: string;
+ docId: string;
+ principal: SharePrincipal;
+}): Promise<CodaPermission | undefined> {
+ let pageToken: string | undefined = undefined;
+ for (let page = 0; page < MAX_LOOKUP_PAGES; page++) {
+ const response: CodaPage<CodaPermission> = await listPermissions({ token, docId, limit: PERMISSION_PAGE_SIZE, pageToken });
+ const match = (response.items ?? []).find((permission) => samePrincipal({ permission, principal }));
+ if (match) {
+ return match;
+ }
+ pageToken = response.nextPageToken;
+ if (!pageToken) {
+ return undefined;
+ }
+ }
+ return undefined;
+}
+
+function samePrincipal({ permission, principal }: { permission: CodaPermission; principal: SharePrincipal }): boolean {
+ const actual = permission.principal;
+ if (!actual || actual.type !== principal.type) {
+ return false;
+ }
+ if (principal.type === 'email') {
+ return (actual.email ?? '').toLowerCase() === principal.email.toLowerCase();
+ }
+ return (actual.domain ?? '').toLowerCase() === principal.domain.toLowerCase();
+}
+
+export const codaPermissions = {
+ listPermissions,
+ findPermission,
+};
+
+export type SharePrincipal = { type: 'email'; email: string } | { type: 'domain'; domain: string };
+
+export type CodaPermission = {
+ id: string;
+ access?: string;
+ principal?: {
+ type?: string;
+ email?: string;
+ domain?: string;
+ };
+};
diff --git a/packages/pieces/community/coda/src/lib/common/props.ts b/packages/pieces/community/coda/src/lib/common/props.ts
index 663d8bd2b04..599f7de2a66 100644
--- a/packages/pieces/community/coda/src/lib/common/props.ts
+++ b/packages/pieces/community/coda/src/lib/common/props.ts
@@ -1,5 +1,6 @@
import { DropdownOption, DynamicPropsValue, Property } from '@activepieces/pieces-framework';
import { codaClient, CodaTableColumn } from './types';
+import { codaApi } from './client';
import { codaAuth } from '../auth';
export const docIdDropdown = Property.Dropdown({
@@ -43,7 +44,7 @@ export const docIdDropdown = Property.Dropdown({
return {
disabled: true,
options: [],
- placeholder: 'Error listing docs, please check connection or API key permissions.',
+ placeholder: dropdownErrorPlaceholder({ error, what: 'docs' }),
};
}
},
@@ -92,7 +93,7 @@ export const tableIdDropdown = Property.Dropdown({
return {
disabled: true,
options: [],
- placeholder: 'Error listing tables. Check document ID or permissions.',
+ placeholder: dropdownErrorPlaceholder({ error, what: 'tables' }),
};
}
},
@@ -130,60 +131,10 @@ export const tableRowsDynamicProps = Property.DynamicProperties({
nextPageToken = columnsResponse.nextPageToken;
} while (nextPageToken);
- if (columns.length > 0) {
- for (const column of columns) {
- if (column.calculated) {
- continue;
- }
-
- switch (column.format.type.toLowerCase()) {
- case 'text':
- case 'link':
- case 'email':
- fields[column.id] = Property.ShortText({
- displayName: column.name,
- required: false,
- });
- break;
- case 'select':
- case 'lookup':
- fields[column.id] = Property.ShortText({
- displayName: column.name,
- required: false,
- description: column.format.isArray
- ? 'Provide options as comma seprated values.'
- : '',
- });
- break;
-
- case 'number':
- case 'currency':
- case 'percent':
- case 'slider':
- case 'scale':
- case 'duration':
- fields[column.id] = Property.Number({
- displayName: column.name,
- required: false,
- });
- break;
- case 'date':
- case 'dateTime':
- case 'time':
- fields[column.id] = Property.DateTime({
- displayName: column.name,
- required: false,
- });
- break;
- case 'checkbox':
- fields[column.id] = Property.Checkbox({
- displayName: column.name,
- required: false,
- });
- break;
- default:
- break;
- }
+ for (const column of columns) {
+ const field = columnToProperty(column);
+ if (field) {
+ fields[column.id] = field;
}
}
return fields;
@@ -205,7 +156,7 @@ export const columnIdsDropdown = (displayName: string, singleSelect = true) => {
if (!auth || !docId || !tableId) {
return {
disabled: true,
- placeholder: 'Connect your Coda account first.',
+ placeholder: !auth ? 'Connect your Coda account first.' : 'Select a document and table first.',
options: [],
};
}
@@ -241,9 +192,57 @@ export const columnIdsDropdown = (displayName: string, singleSelect = true) => {
return {
disabled: true,
options: [],
- placeholder: 'Error listing docs, please check connection or API key permissions.',
+ placeholder: dropdownErrorPlaceholder({ error, what: 'columns' }),
};
}
},
});
};
+
+function dropdownErrorPlaceholder({ error, what }: { error: unknown; what: string }): string {
+ const status = codaApi.statusOf(error);
+ if (status === 401 || status === 403) {
+ return `Could not list ${what}: the Coda API token is invalid or has no access. Reconnect your account.`;
+ }
+ if (status === 404) {
+ return `Could not list ${what}: the selected doc or table was not found.`;
+ }
+ if (status === 429) {
+ return `Could not list ${what}: Coda rate limit reached. Wait a few seconds and refresh.`;
+ }
+ return `Could not list ${what}: ${error instanceof Error ? error.message : 'unknown error'}`;
+}
+
+export function columnToProperty(column: CodaTableColumn) {
+ if (column.calculated) {
+ return undefined;
+ }
+ switch (column.format.type) {
+ case 'text':
+ case 'link':
+ case 'email':
+ return Property.ShortText({ displayName: column.name, required: false });
+ case 'select':
+ case 'lookup':
+ return Property.ShortText({
+ displayName: column.name,
+ required: false,
+ description: column.format.isArray ? 'Provide options as comma-separated values.' : '',
+ });
+ case 'number':
+ case 'currency':
+ case 'percent':
+ case 'slider':
+ case 'scale':
+ case 'duration':
+ return Property.Number({ displayName: column.name, required: false });
+ case 'date':
+ case 'dateTime':
+ case 'time':
+ return Property.DateTime({ displayName: column.name, required: false });
+ case 'checkbox':
+ return Property.Checkbox({ displayName: column.name, required: false });
+ default:
+ return undefined;
+ }
+}
diff --git a/packages/pieces/community/coda/src/lib/common/row-input.ts b/packages/pieces/community/coda/src/lib/common/row-input.ts
new file mode 100644
index 00000000000..6c7fd8aae94
--- /dev/null
+++ b/packages/pieces/community/coda/src/lib/common/row-input.ts
@@ -0,0 +1,84 @@
+import { codaApi } from './client';
+
+const MAX_ROWS_PER_REQUEST = 500;
+
+function toRecord({ value, label }: { value: unknown; label: string }): Record<string, unknown> {
+ const parsed = codaApi.parseJsonInput({ value, label });
+ if (!codaApi.isRecord(parsed)) {
+ throw new Error(`${label} must be an object of column → value, for example {"Name": "Ada", "Amount": 5}.`);
+ }
+ return parsed;
+}
+
+function toRows({ value, label }: { value: unknown; label: string }): Record<string, unknown>[] {
+ const parsed = codaApi.parseJsonInput({ value, label });
+ const list = Array.isArray(parsed) ? parsed : codaApi.isRecord(parsed) ? [parsed] : undefined;
+ if (!list || list.length === 0) {
+ throw new Error(`${label} must be a non-empty list of objects, for example [{"Name": "Ada", "Amount": 5}].`);
+ }
+ if (list.length > MAX_ROWS_PER_REQUEST) {
+ throw new Error(`${label} can hold at most ${MAX_ROWS_PER_REQUEST} rows per call; split the list into smaller batches.`);
+ }
+ return list.map((row, index) => {
+ if (!codaApi.isRecord(row)) {
+ throw new Error(`${label}: item ${index + 1} must be an object of column → value.`);
+ }
+ return row;
+ });
+}
+
+function insertCells({ row, rowNumber }: { row: Record<string, unknown>; rowNumber: number }): CodaCell[] {
+ const cells = Object.entries(row)
+ .filter(([column, value]) => column.trim().length > 0 && value !== undefined && value !== null)
+ .map(([column, value]) => ({ column: column.trim(), value }));
+ if (cells.length === 0) {
+ throw new Error(`Row ${rowNumber} has no column values.`);
+ }
+ return cells;
+}
+
+function updateCells(cells: Record<string, unknown>): CodaCell[] {
+ const edits = Object.entries(cells)
+ .filter(([column, value]) => column.trim().length > 0 && value !== undefined)
+ .map(([column, value]) => ({ column: column.trim(), value: value === null ? '' : value }));
+ if (edits.length === 0) {
+ throw new Error('Provide at least one column to change.');
+ }
+ return edits;
+}
+
+function toStringList({ value, label }: { value: unknown; label: string }): string[] {
+ const list = Array.isArray(value) ? value : typeof value === 'string' ? splitText({ text: value, label }) : [];
+ const items = list
+ .filter((item) => item !== undefined && item !== null)
+ .map((item) => String(item).trim())
+ .filter((item) => item.length > 0);
+ return [...new Set(items)];
+}
+
+function splitText({ text, label }: { text: string; label: string }): unknown[] {
+ if (text.trim().startsWith('[')) {
+ const parsed = codaApi.parseJsonInput({ value: text, label });
+ return Array.isArray(parsed) ? parsed : [];
+ }
+ return text.split(',');
+}
+
+function hasValue(value: unknown): boolean {
+ return value !== undefined && value !== null && !(typeof value === 'string' && value.trim().length === 0);
+}
+
+export const rowInput = {
+ toRecord,
+ toRows,
+ insertCells,
+ updateCells,
+ toStringList,
+ hasValue,
+ MAX_ROWS_PER_REQUEST,
+};
+
+export type CodaCell = {
+ column: string;
+ value: unknown;
+};
diff --git a/packages/pieces/community/coda/src/lib/common/types.ts b/packages/pieces/community/coda/src/lib/common/types.ts
index 617622af60c..358a4855283 100644
--- a/packages/pieces/community/coda/src/lib/common/types.ts
+++ b/packages/pieces/community/coda/src/lib/common/types.ts
@@ -1,31 +1,28 @@
-import { HttpMethod, httpClient, HttpRequest, AuthenticationType } from "@activepieces/pieces-common";
+import { HttpMethod } from "@activepieces/pieces-common";
import { AppConnectionValueForAuthProperty } from "@activepieces/pieces-framework";
import { codaAuth } from '../auth';
+import { CODA_BASE_URL, CodaQueryValue, codaApi } from './client';
-export const CODA_BASE_URL = "https://coda.io/apis/v1";
+export { CODA_BASE_URL };
-// --- Common Reference Types ---
export interface CodaObjectReference {
id: string;
type: string;
href: string;
- name?: string; // Common but not always present in all reference types
+ name?: string;
}
export interface CodaPageReference extends CodaObjectReference {
- type: 'page'; // More specific type if known
- // Add other page-specific reference fields if needed
+ type: 'page';
}
export interface CodaColumnReference extends CodaObjectReference {
- type: 'column'; // More specific type if known
- // Add other column-specific reference fields if needed
+ type: 'column';
}
-// --- Table Related Interfaces ---
export interface CodaTableReference extends CodaObjectReference {
- type: 'table' | 'view'; // More specific, can be table or view reference
- name: string; // Name is required for table reference as per GetTable response
+ type: 'table' | 'view';
+ name: string;
}
export interface CodaListTablesResponse {
@@ -36,33 +33,25 @@ export interface CodaListTablesResponse {
}
export interface CodaSort {
- column: CodaColumnReference | string; // API might return ID or full reference
+ column: CodaColumnReference | string;
direction: 'ascending' | 'descending';
}
-// Interface for the format of a column
export interface CodaColumnFormat {
- type: string; // e.g., "text", "number", "date", "person", "lookup", "checkbox", "currency", "percent", "slider", "scale", "selectList", "multiSelectList", "button"
- // Other format-specific properties can be added here if needed for dynamic prop generation
- // For example, for selectList:
- // options?: { name: string, id?: string }[];
- // For lookup:
- // table?: CodaTableReference;
+ type: string;
isArray?:boolean
}
-// Interface for a single column in the getTableDetails response
export interface CodaTableColumn {
- id: string; // Column ID, e.g., "c-123abcDEF"
+ id: string;
type: "column";
href: string;
- name: string; // User-visible name of the column
+ name: string;
format: CodaColumnFormat;
- display?: boolean; // As per docs, optional
- calculated?: boolean; // Whether this is a calculated column
- formula?: string; // The formula if it's a calculated column
- defaultValue?: string; // As per docs, it's a formula string
- // Add other relevant column properties if necessary
+ display?: boolean;
+ calculated?: boolean;
+ formula?: string;
+ defaultValue?: string;
}
export interface CodaListColumnsResponse {
@@ -74,24 +63,22 @@ export interface CodaListColumnsResponse {
export interface CodaGetTableDetailsResponse {
id: string;
- type: "table"; // This specific endpoint returns "table"
+ type: "table";
tableType: "table" | "view";
href: string;
name: string;
parent: CodaPageReference;
browserLink: string;
- displayColumn: CodaColumnReference; // This is a reference, not the full column object
+ displayColumn: CodaColumnReference;
rowCount: number;
sorts: CodaSort[];
- layout: string; // Enum of layout types, string for simplicity
- createdAt: string; // date-time
- updatedAt: string; // date-time
- parentTable?: CodaTableReference; // Optional, for views
- filter?: any; // object, structure can be complex
+ layout: string;
+ createdAt: string;
+ updatedAt: string;
+ parentTable?: CodaTableReference;
+ filter?: unknown;
}
-
-// --- Row Related Interfaces ---
export interface CodaRow {
id: string;
type: "row";
@@ -101,7 +88,7 @@ export interface CodaRow {
browserLink: string;
createdAt: string;
updatedAt: string;
- values: Record<string, any>;
+ values: Record<string, unknown>;
parentTable?: CodaTableReference;
}
@@ -117,10 +104,9 @@ export interface CodaListRowsResponse {
nextSyncToken?: string;
}
-// For creating/updating rows
export interface CodaCellEdit {
- column: string; // Column ID or Name
- value: any;
+ column: string;
+ value: unknown;
}
export interface CodaRowEdit {
cells: CodaCellEdit[];
@@ -128,25 +114,23 @@ export interface CodaRowEdit {
export interface CodaMutateRowsPayload {
rows: CodaRowEdit[];
- keyColumns?: string[]; // Column IDs or Names for upsert
+ keyColumns?: string[];
}
export interface CodaMutateRowsResponse {
requestId: string;
addedRowIds?: string[];
- updatedRowIds?: string[]; // API docs for POST say addedRowIds, but PUT might have updatedRowIds. Let's be broad.
}
-export interface CodaUpdateRowPayload { // Used for PUT (update single row)
+export interface CodaUpdateRowPayload {
row: CodaRowEdit;
}
export interface CodaUpdateRowResponse {
requestId: string;
- id: string; // ID of the updated row
+ id: string;
}
-// --- Document Related Interfaces ---
export interface CodaDocIcon {
name: string;
type: string;
@@ -172,7 +156,7 @@ export interface CodaDocPublished {
discoverable: boolean;
earnCredit: boolean;
mode: "view" | "play" | "edit";
- categories: { name: string }[]; // Simplified, assuming only name is needed for now
+ categories: { name: string }[];
description?: string;
imageLink?: string;
}
@@ -182,14 +166,14 @@ export interface CodaDoc {
href: string;
browserLink: string;
name: string;
- owner: string; // email
+ owner: string;
ownerName: string;
- createdAt: string; // date-time
- updatedAt: string; // date-time
- workspaceId: string; // Deprecated but present
- folderId: string; // Deprecated but present
- workspace: CodaObjectReference; // WorkspaceReference
- folder: CodaObjectReference; // FolderReference
+ createdAt: string;
+ updatedAt: string;
+ workspaceId: string;
+ folderId: string;
+ workspace: CodaObjectReference;
+ folder: CodaObjectReference;
icon?: CodaDocIcon;
docSize?: CodaDocSize;
sourceDoc?: CodaDocSourceDocReference;
@@ -203,7 +187,6 @@ export interface CodaListDocsResponse {
nextPageLink?: string;
}
-// --- API Client ---
export interface CodaAPIClient {
listTables: (docId: string, params?: { limit?: number; sortBy?: string; tableTypes?: string, pageToken?: string }) => Promise<CodaListTablesResponse>;
getTableDetails: (docId: string, tableIdOrName: string, params?: { useUpdatedTableLayouts?: boolean }) => Promise<CodaGetTableDetailsResponse>;
@@ -235,132 +218,68 @@ export interface CodaAPIClient {
}) => Promise<CodaListDocsResponse>;
}
-export const codaClient = ({secret_text}: AppConnectionValueForAuthProperty<typeof codaAuth>): CodaAPIClient => {
- const makeRequest = async <T>(request: Omit<HttpRequest, 'authentication'> & { body?: any }): Promise<T> => {
- const response = await httpClient.sendRequest<T>({
- ...request,
- authentication: {
- type: AuthenticationType.BEARER_TOKEN,
- token: secret_text,
- }
- });
- return response.body;
- }
+export const codaClient = ({ secret_text }: AppConnectionValueForAuthProperty<typeof codaAuth>): CodaAPIClient => {
+ const call = <T>({ method, path, operation, query, body }: { method: HttpMethod; path: string; operation: string; query?: Record<string, CodaQueryValue>; body?: unknown }): Promise<T> =>
+ codaApi.request<T>({ token: secret_text, method, path, operation, query, body });
return {
- listTables: async (docId, params) => {
- const queryParams: Record<string, string | number | boolean> = {};
- if (params?.limit) queryParams['limit'] = params.limit.toString();
- if (params?.sortBy) queryParams['sortBy'] = params.sortBy;
- if (params?.tableTypes) queryParams['tableTypes'] = params.tableTypes;
- if (params?.pageToken) queryParams['pageToken'] = params.pageToken;
-
- return makeRequest<CodaListTablesResponse>({
+ listTables: (docId, params) =>
+ call<CodaListTablesResponse>({
method: HttpMethod.GET,
- url: `${CODA_BASE_URL}/docs/${docId}/tables`,
- queryParams: Object.fromEntries(Object.entries(queryParams).map(([k, v]) => [k, String(v)])),
- });
- },
- getTableDetails: async (docId, tableIdOrName, params) => {
- const queryParams: Record<string, string | boolean> = {};
- if (params?.useUpdatedTableLayouts !== undefined) queryParams['useUpdatedTableLayouts'] = params.useUpdatedTableLayouts;
-
- return makeRequest<CodaGetTableDetailsResponse>({
+ path: `${codaApi.docPath(docId)}/tables`,
+ operation: 'list tables',
+ query: { ...params },
+ }),
+ getTableDetails: (docId, tableIdOrName, params) =>
+ call<CodaGetTableDetailsResponse>({
method: HttpMethod.GET,
- url: `${CODA_BASE_URL}/docs/${docId}/tables/${encodeURIComponent(tableIdOrName)}`,
- queryParams: Object.fromEntries(Object.entries(queryParams).map(([k, v]) => [k, String(v)])),
- });
- },
- listColumns: async (docId, tableIdOrName, params) => {
- const queryParams: Record<string, string | number | boolean> = {};
- if (params?.limit) queryParams['limit'] = params.limit;
- if (params?.pageToken) queryParams['pageToken'] = params.pageToken;
- if (params?.visibleOnly !== undefined) queryParams['visibleOnly'] = params.visibleOnly;
-
- return makeRequest<CodaListColumnsResponse>({
+ path: codaApi.tablePath({ docId, tableIdOrName }),
+ operation: 'get table',
+ query: { ...params },
+ }),
+ listColumns: (docId, tableIdOrName, params) =>
+ call<CodaListColumnsResponse>({
method: HttpMethod.GET,
- url: `${CODA_BASE_URL}/docs/${docId}/tables/${encodeURIComponent(tableIdOrName)}/columns`,
- queryParams: Object.fromEntries(Object.entries(queryParams).map(([k,v])=>[k,String(v)])),
- });
- },
- getRow: async (docId, tableIdOrName, rowIdOrName, params) => {
- const queryParams: Record<string, string | boolean> = {};
- if (params?.useColumnNames !== undefined) queryParams['useColumnNames'] = params.useColumnNames;
- if (params?.valueFormat) queryParams['valueFormat'] = params.valueFormat;
-
- return makeRequest<CodaGetRowResponse>({
+ path: `${codaApi.tablePath({ docId, tableIdOrName })}/columns`,
+ operation: 'list columns',
+ query: { ...params },
+ }),
+ getRow: (docId, tableIdOrName, rowIdOrName, params) =>
+ call<CodaGetRowResponse>({
method: HttpMethod.GET,
- url: `${CODA_BASE_URL}/docs/${docId}/tables/${encodeURIComponent(tableIdOrName)}/rows/${encodeURIComponent(rowIdOrName)}`,
- queryParams: Object.fromEntries(Object.entries(queryParams).map(([k, v]) => [k, String(v)])),
- });
- },
- listRows: async (docId, tableIdOrName, params) => {
- const queryParams: Record<string, string | number | boolean> = {};
- if (params?.query) queryParams['query'] = params.query;
- if (params?.sortBy) queryParams['sortBy'] = params.sortBy;
- if (params?.useColumnNames !== undefined) queryParams['useColumnNames'] = params.useColumnNames;
- if (params?.valueFormat) queryParams['valueFormat'] = params.valueFormat;
- if (params?.visibleOnly !== undefined) queryParams['visibleOnly'] = params.visibleOnly;
- if (params?.limit) queryParams['limit'] = params.limit;
- if (params?.pageToken) queryParams['pageToken'] = params.pageToken;
- if (params?.syncToken) queryParams['syncToken'] = params.syncToken;
-
- return makeRequest<CodaListRowsResponse>({
+ path: `${codaApi.tablePath({ docId, tableIdOrName })}/rows/${codaApi.pathSegment({ value: rowIdOrName, label: 'Row ID or name' })}`,
+ operation: 'get row',
+ query: { ...params },
+ }),
+ listRows: (docId, tableIdOrName, params) =>
+ call<CodaListRowsResponse>({
method: HttpMethod.GET,
- url: `${CODA_BASE_URL}/docs/${docId}/tables/${encodeURIComponent(tableIdOrName)}/rows`,
- queryParams: Object.fromEntries(
- Object.entries(queryParams).map(([key, value]) => [key, String(value)])
- ),
- });
- },
- mutateRows: async (docId, tableIdOrName, payload, params) => {
- const queryParams: Record<string, string | boolean> = {};
- if (params?.disableParsing !== undefined) queryParams['disableParsing'] = params.disableParsing;
-
- return makeRequest<CodaMutateRowsResponse>({
+ path: `${codaApi.tablePath({ docId, tableIdOrName })}/rows`,
+ operation: 'list rows',
+ query: { ...params },
+ }),
+ mutateRows: (docId, tableIdOrName, payload, params) =>
+ call<CodaMutateRowsResponse>({
method: HttpMethod.POST,
- url: `${CODA_BASE_URL}/docs/${docId}/tables/${encodeURIComponent(tableIdOrName)}/rows`,
+ path: `${codaApi.tablePath({ docId, tableIdOrName })}/rows`,
+ operation: 'add or update rows',
+ query: { ...params },
body: payload,
- queryParams: Object.fromEntries(Object.entries(queryParams).map(([k, v]) => [k, String(v)])),
- headers: {
- 'Content-Type': 'application/json'
- }
- });
- },
- updateRow: async (docId, tableIdOrName, rowIdOrName, payload, params) => {
- const queryParams: Record<string, string | boolean> = {};
- if (params?.disableParsing !== undefined) queryParams['disableParsing'] = params.disableParsing;
-
- return makeRequest<CodaUpdateRowResponse>({
+ }),
+ updateRow: (docId, tableIdOrName, rowIdOrName, payload, params) =>
+ call<CodaUpdateRowResponse>({
method: HttpMethod.PUT,
- url: `${CODA_BASE_URL}/docs/${docId}/tables/${encodeURIComponent(tableIdOrName)}/rows/${encodeURIComponent(rowIdOrName)}`,
+ path: `${codaApi.tablePath({ docId, tableIdOrName })}/rows/${codaApi.pathSegment({ value: rowIdOrName, label: 'Row ID or name' })}`,
+ operation: 'update row',
+ query: { ...params },
body: payload,
- queryParams: Object.fromEntries(Object.entries(queryParams).map(([k, v]) => [k, String(v)])),
- headers: {
- 'Content-Type': 'application/json'
- }
- });
- },
- listDocs: async (params) => {
- const queryParams: Record<string, string | number | boolean> = {};
- if (params?.isOwner !== undefined) queryParams['isOwner'] = params.isOwner;
- if (params?.isPublished !== undefined) queryParams['isPublished'] = params.isPublished;
- if (params?.query) queryParams['query'] = params.query;
- if (params?.sourceDoc) queryParams['sourceDoc'] = params.sourceDoc;
- if (params?.isStarred !== undefined) queryParams['isStarred'] = params.isStarred;
- if (params?.inGallery !== undefined) queryParams['inGallery'] = params.inGallery;
- if (params?.workspaceId) queryParams['workspaceId'] = params.workspaceId;
- if (params?.folderId) queryParams['folderId'] = params.folderId;
- if (params?.limit) queryParams['limit'] = params.limit;
- if (params?.pageToken) queryParams['pageToken'] = params.pageToken;
-
- return makeRequest<CodaListDocsResponse>({
+ }),
+ listDocs: (params) =>
+ call<CodaListDocsResponse>({
method: HttpMethod.GET,
- url: `${CODA_BASE_URL}/docs`,
- queryParams: Object.fromEntries(
- Object.entries(queryParams).map(([key, value]) => [key, String(value)])
- ),
- });
- }
+ path: '/docs',
+ operation: 'list docs',
+ query: { ...params },
+ }),
};
};
diff --git a/packages/pieces/community/coda/src/lib/output-schemas.ts b/packages/pieces/community/coda/src/lib/output-schemas.ts
index 4938beea8e3..625c086afce 100644
--- a/packages/pieces/community/coda/src/lib/output-schemas.ts
+++ b/packages/pieces/community/coda/src/lib/output-schemas.ts
@@ -43,6 +43,151 @@ const rowFields: OutputSchema['fields'] = [
},
];
+
+const requestIdField: OutputSchema['fields'][number] = {
+ key: 'requestId',
+ label: 'Request ID',
+ description: 'Coda applies the change in the background. Pass this to Get Mutation Status to check it was applied.',
+};
+
+const mutationFields: OutputSchema['fields'] = [
+ requestIdField,
+ {
+ key: 'completed',
+ label: 'Completed',
+ format: 'boolean',
+ description: 'True once Coda has applied the change. False when waiting was off or took longer than 30 seconds; check later with Get Mutation Status.',
+ },
+ {
+ key: 'warning',
+ label: 'Warning',
+ description: 'A warning from Coda about the applied change, or why its status could not be checked.',
+ },
+];
+
+const refFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'ID' },
+ { key: 'name', label: 'Name' },
+];
+
+const docFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Doc ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'browserLink', label: 'Browser Link', format: 'url' },
+ { key: 'owner', label: 'Owner Email', format: 'email' },
+ { key: 'ownerName', label: 'Owner Name' },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+ { key: 'updatedAt', label: 'Updated At', format: 'datetime' },
+ { key: 'workspace', label: 'Workspace', children: refFields },
+ { key: 'folder', label: 'Folder', children: refFields },
+];
+
+const docSizeField: OutputSchema['fields'][number] = {
+ key: 'docSize',
+ label: 'Doc Size',
+ children: [
+ { key: 'totalRowCount', label: 'Total Rows', format: 'number' },
+ { key: 'tableAndViewCount', label: 'Tables and Views', format: 'number' },
+ { key: 'pageCount', label: 'Pages', format: 'number' },
+ {
+ key: 'overApiSizeLimit',
+ label: 'Over API Size Limit',
+ format: 'boolean',
+ description: 'When true the doc is too large for the API to read.',
+ },
+ ],
+};
+
+const personFields: OutputSchema['fields'] = [
+ { key: 'name', label: 'Name' },
+ { key: 'email', label: 'Email', format: 'email' },
+];
+
+const pageFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Page ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'subtitle', label: 'Subtitle' },
+ { key: 'browserLink', label: 'Browser Link', format: 'url' },
+ { key: 'contentType', label: 'Content Type', description: '"canvas" for a normal page, "embed" or "syncPage" for special pages.' },
+ { key: 'isHidden', label: 'Hidden', format: 'boolean' },
+ { key: 'parent', label: 'Parent Page', children: refFields },
+ { key: 'children', label: 'Subpages', labelKey: 'name', listItems: refFields },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+ { key: 'updatedAt', label: 'Updated At', format: 'datetime' },
+ { key: 'createdBy', label: 'Created By', children: personFields },
+ { key: 'updatedBy', label: 'Updated By', children: personFields },
+];
+
+const columnFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Column ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'display', label: 'Display Column', format: 'boolean', description: 'True for the column whose value names each row.' },
+ { key: 'calculated', label: 'Calculated', format: 'boolean', description: 'True for formula or button columns, which cannot be written.' },
+ { key: 'formula', label: 'Formula' },
+ {
+ key: 'format',
+ label: 'Format',
+ children: [
+ { key: 'type', label: 'Type', description: 'For example text, number, date, dateTime, checkbox, select, email, person, button.' },
+ { key: 'isArray', label: 'Holds a List', format: 'boolean' },
+ ],
+ },
+];
+
+const pageRefFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Page ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'browserLink', label: 'Browser Link', format: 'url' },
+];
+
+const formulaRefFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Formula ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'parent', label: 'Page', children: pageRefFields },
+];
+
+const controlRefFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Control ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'parent', label: 'Page', children: pageRefFields },
+];
+
+const folderFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Folder ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'browserLink', label: 'Browser Link', format: 'url' },
+ { key: 'canEdit', label: 'Can Edit', format: 'boolean' },
+ { key: 'workspace', label: 'Workspace', children: refFields },
+];
+
+const permissionFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Permission ID' },
+ { key: 'access', label: 'Access', description: 'readonly, comment, write or none.' },
+ {
+ key: 'principal',
+ label: 'Shared With',
+ children: [
+ { key: 'type', label: 'Type', description: 'email, domain, workspace or anyone.' },
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'domain', label: 'Domain' },
+ ],
+ },
+];
+
+function pagedSchema({ label, labelKey, itemFields }: { label: string; labelKey: string; itemFields: OutputSchema['fields'] }): OutputSchema {
+ return {
+ fields: [
+ { key: 'items', label, labelKey, listItems: itemFields },
+ {
+ key: 'nextPageToken',
+ label: 'Next Page Token',
+ description: 'Pass this as Page Token to get the next page. Empty on the last page.',
+ },
+ { key: 'hasMore', label: 'Has More', format: 'boolean', description: 'True when another page of results exists.' },
+ ],
+ };
+}
+
const tableFields: OutputSchema['fields'] = [
{ key: 'id', label: 'Table ID' },
{ key: 'name', label: 'Name' },
@@ -77,6 +222,7 @@ export const createRowActionOutputSchema: OutputSchema = {
description:
'Coda applies row writes asynchronously, so the new row may not be readable for a few seconds. Add a short delay before passing this to Get Row.',
},
+ requestIdField,
],
};
@@ -87,6 +233,7 @@ export const updateRowActionOutputSchema: OutputSchema = {
label: 'Row ID',
description: 'The row that was updated.',
},
+ requestIdField,
],
};
@@ -166,3 +313,177 @@ export const getTableActionOutputSchema: OutputSchema = {
};
export const newRowCreatedTriggerOutputSchema: OutputSchema = { fields: rowFields };
+
+export const upsertRowActionOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ {
+ ...requestIdField,
+ description: 'Coda applies upserts asynchronously. Pass this to Get Mutation Status to check it was applied.',
+ },
+ ],
+};
+
+export const getCurrentUserActionOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'name', label: 'Name' },
+ { key: 'loginId', label: 'Login Email', format: 'email' },
+ { key: 'tokenName', label: 'Token Name' },
+ { key: 'scoped', label: 'Token Is Restricted', format: 'boolean', description: 'True when the API token only works for some docs.' },
+ { key: 'pictureLink', label: 'Picture', format: 'image' },
+ { key: 'workspace', label: 'Workspace', children: refFields },
+ ],
+};
+
+export const listDocsActionOutputSchema = pagedSchema({ label: 'Docs', labelKey: 'name', itemFields: docFields });
+
+export const getDocActionOutputSchema: OutputSchema = { fields: [...docFields, docSizeField] };
+
+export const createDocActionOutputSchema: OutputSchema = {
+ fields: [
+ ...docFields,
+ { key: 'sourceDoc', label: 'Copied From', children: [{ key: 'id', label: 'Doc ID' }] },
+ ...mutationFields,
+ ],
+};
+
+export const updateDocActionOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'id', label: 'Doc ID' },
+ { key: 'title', label: 'New Title' },
+ { key: 'iconName', label: 'New Icon Name' },
+ ],
+};
+
+export const deleteDocActionOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'id', label: 'Doc ID' },
+ { key: 'deleted', label: 'Deleted', format: 'boolean' },
+ { key: 'alreadyDeleted', label: 'Already Deleted', format: 'boolean', description: 'True when the doc was not found, usually because it was deleted before.' },
+ ],
+};
+
+export const listFoldersActionOutputSchema = pagedSchema({ label: 'Folders', labelKey: 'name', itemFields: folderFields });
+
+export const listPagesActionOutputSchema = pagedSchema({ label: 'Pages', labelKey: 'name', itemFields: pageFields });
+
+export const getPageActionOutputSchema: OutputSchema = { fields: pageFields };
+
+export const pageMutationActionOutputSchema: OutputSchema = {
+ fields: [{ key: 'id', label: 'Page ID' }, ...mutationFields],
+};
+
+export const deletePageActionOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'id', label: 'Page ID' },
+ { key: 'alreadyDeleted', label: 'Already Deleted', format: 'boolean', description: 'True when the page was not found, usually because it was deleted before.' },
+ ...mutationFields,
+ ],
+};
+
+export const getPageContentActionOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'content', label: 'Content', description: 'The page as Markdown or HTML. Empty when Completed is false.' },
+ { key: 'format', label: 'Format' },
+ { key: 'completed', label: 'Completed', format: 'boolean', description: 'False when Coda needed more than a minute; run again with the Export ID.' },
+ { key: 'exportId', label: 'Export ID' },
+ { key: 'truncated', label: 'Truncated', format: 'boolean', description: 'True when the page was larger than 5 MB and was cut off.' },
+ { key: 'pageId', label: 'Page' },
+ ],
+};
+
+export const listDocTablesActionOutputSchema = pagedSchema({ label: 'Tables', labelKey: 'name', itemFields: tableFields });
+
+export const listColumnsActionOutputSchema = pagedSchema({ label: 'Columns', labelKey: 'name', itemFields: columnFields });
+
+export const listRowsActionOutputSchema = pagedSchema({ label: 'Rows', labelKey: 'name', itemFields: rowFields });
+
+export const createRowsActionOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'addedRowIds', label: 'Added Row IDs', description: 'IDs of the new rows, in the order given.' },
+ ...mutationFields,
+ ],
+};
+
+export const upsertRowsActionOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'rowCount', label: 'Rows Sent', format: 'number' },
+ ...mutationFields,
+ ],
+};
+
+export const updateRowByIdActionOutputSchema: OutputSchema = {
+ fields: [{ key: 'id', label: 'Row ID' }, ...mutationFields],
+};
+
+export const deleteRowsActionOutputSchema: OutputSchema = {
+ fields: [{ key: 'rowIds', label: 'Deleted Row IDs' }, ...mutationFields],
+};
+
+export const pushButtonActionOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'rowId', label: 'Row ID' },
+ { key: 'columnId', label: 'Button Column ID' },
+ ...mutationFields,
+ ],
+};
+
+export const listFormulasActionOutputSchema = pagedSchema({ label: 'Formulas', labelKey: 'name', itemFields: formulaRefFields });
+
+export const getFormulaActionOutputSchema: OutputSchema = {
+ fields: [
+ ...formulaRefFields,
+ { key: 'value', label: 'Value', description: 'The formula result: text, number, boolean, date or a list.' },
+ ],
+};
+
+export const listControlsActionOutputSchema = pagedSchema({ label: 'Controls', labelKey: 'name', itemFields: controlRefFields });
+
+export const getControlActionOutputSchema: OutputSchema = {
+ fields: [
+ ...controlRefFields,
+ { key: 'controlType', label: 'Control Type', description: 'For example slider, select, datePicker, checkbox, button.' },
+ { key: 'value', label: 'Value' },
+ ],
+};
+
+export const getMutationStatusActionOutputSchema: OutputSchema = { fields: mutationFields };
+
+export const resolveBrowserLinkActionOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'resourceType', label: 'Object Type', description: 'doc, page, table, row, column, formula or control.' },
+ { key: 'id', label: 'Object ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'docId', label: 'Doc ID' },
+ { key: 'tableId', label: 'Table ID', description: 'Set when the link points to a table, row or column.' },
+ { key: 'browserLink', label: 'Browser Link', format: 'url' },
+ ],
+};
+
+export const listPermissionsActionOutputSchema = pagedSchema({ label: 'Sharing', labelKey: 'id', itemFields: permissionFields });
+
+export const addPermissionActionOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'docId', label: 'Doc ID' },
+ { key: 'permissionId', label: 'Permission ID', description: 'Pass this to Remove Doc Sharing to undo the share.' },
+ { key: 'principalType', label: 'Shared With Type' },
+ { key: 'principal', label: 'Shared With' },
+ { key: 'access', label: 'Access' },
+ ],
+};
+
+export const removePermissionActionOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'docId', label: 'Doc ID' },
+ { key: 'permissionId', label: 'Permission ID' },
+ { key: 'removed', label: 'Removed', format: 'boolean' },
+ { key: 'alreadyRemoved', label: 'Already Removed', format: 'boolean', description: 'True when the entry was not found, usually because it was removed before.' },
+ ],
+};
+
+export const triggerAutomationActionOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'ruleId', label: 'Rule ID' },
+ { key: 'requestId', label: 'Request ID' },
+ ],
+};
diff --git a/packages/pieces/community/coda/src/lib/triggers/new-row-created.ts b/packages/pieces/community/coda/src/lib/triggers/new-row-created.ts
index e095e12d117..cb8dabbe21f 100644
--- a/packages/pieces/community/coda/src/lib/triggers/new-row-created.ts
+++ b/packages/pieces/community/coda/src/lib/triggers/new-row-created.ts
@@ -10,6 +10,9 @@ import dayjs from 'dayjs';
import { docIdDropdown, tableIdDropdown } from '../common/props';
import { newRowCreatedTriggerOutputSchema } from '../output-schemas';
+const PAGE_SIZE = 500;
+const TEST_SAMPLE_SIZE = 5;
+
type Props = {
tableId: string;
docId: string;
@@ -22,28 +25,32 @@ const polling: Polling<AppConnectionValueForAuthProperty<typeof codaAuth>, Props
const isTest = lastFetchEpochMS === 0;
const client = codaClient(auth);
- const rows: CodaRow[] = [];
+ let rows: CodaRow[] = [];
let nextPageToken: string | undefined = undefined;
- // We will sort by createdAt to process in order. The API default is ascending.
do {
const response = await client.listRows(docId, tableId, {
- sortBy: 'createdAt', // Default is ascending
+ sortBy: 'createdAt',
valueFormat: 'simpleWithArrays',
useColumnNames: true,
- limit: isTest ? 5 : 100,
+ limit: PAGE_SIZE,
pageToken: nextPageToken,
});
-
- if (response.items) {
- for (const row of response.items) {
- rows.push(row);
- }
+ const fresh = (response.items ?? []).filter((row) => dayjs(row.createdAt).valueOf() > lastFetchEpochMS);
+ if (isTest) {
+ rows = [...rows, ...fresh].slice(-TEST_SAMPLE_SIZE);
+ } else {
+ rows.push(...fresh);
}
- if (isTest) break;
nextPageToken = response.nextPageToken;
} while (nextPageToken);
+ if (isTest) {
+ return [...rows]
+ .reverse()
+ .map((row) => ({ epochMilliSeconds: dayjs(row.createdAt).valueOf(), data: row }));
+ }
+
return rows.map((row) => {
return {
epochMilliSeconds: dayjs(row.createdAt).valueOf(),
@@ -69,18 +76,10 @@ export const newRowCreatedTrigger = createTrigger({
outputSchema: newRowCreatedTriggerOutputSchema,
type: TriggerStrategy.POLLING,
async onEnable(context) {
- await pollingHelper.onEnable(polling, {
- auth: context.auth,
- store: context.store,
- propsValue: context.propsValue,
- });
+ await pollingHelper.onEnable(polling, context);
},
async onDisable(context) {
- await pollingHelper.onDisable(polling, {
- auth: context.auth,
- store: context.store,
- propsValue: context.propsValue,
- });
+ await pollingHelper.onDisable(polling, context);
},
async test(context) {
return await pollingHelper.test(polling, context);
diff --git a/packages/pieces/community/coda/test/auth.test.ts b/packages/pieces/community/coda/test/auth.test.ts
new file mode 100644
index 00000000000..88ca7947f9e
--- /dev/null
+++ b/packages/pieces/community/coda/test/auth.test.ts
@@ -0,0 +1,39 @@
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { codaAuth } from '../src/lib/auth';
+import { runStep, stubFetch } from './helpers';
+
+const server = { apiUrl: 'http://localhost:3000/api/', publicUrl: 'http://localhost:4200/', mintOidcToken: async () => 'oidc-token' };
+
+function validate(auth: string) {
+ const check = codaAuth.validate;
+ if (!check) {
+ throw new Error('codaAuth has no validate');
+ }
+ return runStep(check({ auth, server }));
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+describe('codaAuth.validate', () => {
+ test('valid token calls /whoami with the trimmed bearer token', async () => {
+ const seen = stubFetch(() => ({ body: { name: 'A' } }));
+ await expect(validate(' tok ')).resolves.toEqual({ valid: true });
+ expect(seen[0].path).toBe('/whoami');
+ expect(seen[0].auth).toBe('Bearer tok');
+ });
+ test.each([401, 403])('%s → invalid token', async (status) => {
+ stubFetch(() => ({ status, body: { message: 'Unauthorized' } }));
+ await expect(validate('bad')).resolves.toEqual({ valid: false, error: expect.stringMatching(/Invalid API token/) });
+ });
+ test('other errors keep their message', async () => {
+ stubFetch(() => ({ status: 500, body: { message: 'Coda is down' } }));
+ await expect(validate('tok')).resolves.toEqual({ valid: false, error: expect.stringMatching(/Coda is down/) });
+ });
+});
diff --git a/packages/pieces/community/coda/test/client.test.ts b/packages/pieces/community/coda/test/client.test.ts
new file mode 100644
index 00000000000..6c8c1c71783
--- /dev/null
+++ b/packages/pieces/community/coda/test/client.test.ts
@@ -0,0 +1,215 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { CodaApiError, codaApi } from '../src/lib/common/client';
+import { replies, runStep, stubFetch, TOKEN } from './helpers';
+
+beforeEach(() => {
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+describe('pathSegment', () => {
+ test('encodes names with spaces and slashes', () => {
+ expect(codaApi.pathSegment({ value: ' My Table/2 ', label: 'Table' })).toBe('My%20Table%2F2');
+ });
+ test.each(['', ' ', '.', '..', undefined, null])('rejects %p', (value) => {
+ expect(() => codaApi.pathSegment({ value, label: 'Table' })).toThrow();
+ });
+});
+
+describe('parseDocId', () => {
+ test.each([
+ ['AbC123xyZ', 'AbC123xyZ'],
+ ['https://coda.io/d/My-Doc_dAbC123xyZ', 'AbC123xyZ'],
+ ['https://coda.io/d/My-Doc_dAbC123xyZ/Page_suXYZ#_tugrid-1', 'AbC123xyZ'],
+ ['https://docs.superhuman.com/d/_dMG3aOhChDA', 'MG3aOhChDA'],
+ ['https://www.coda.io/d/_dMG3aOhChDA/_suBzIp5A', 'MG3aOhChDA'],
+ ['https://coda.io/d/My_draft_dAbC123', 'AbC123'],
+ ['https://coda.io/d/Q3_data_dump_dXy-9_Z/Page_su1', 'Xy-9_Z'],
+ ])('%s → %s', (input, expected) => {
+ expect(codaApi.parseDocId(input)).toBe(expected);
+ });
+ test.each([
+ 'https://coda.io.evil.io/d/_dMG3aOhChDA',
+ 'https://evil.example.com/d/_dMG3aOhChDA',
+ 'https://coda.io/docs',
+ '../etc',
+ 'abc/def',
+ '',
+ ])('rejects %s', (input) => {
+ expect(() => codaApi.parseDocId(input)).toThrow();
+ });
+ test('docPath always encodes the parsed id', () => {
+ expect(codaApi.docPath('https://coda.io/d/X_dAbc-1_2')).toBe('/docs/Abc-1_2');
+ });
+});
+
+describe('buildRowQuery', () => {
+ test('keeps column ids bare and quotes text values', () => {
+ expect(codaApi.buildRowQuery({ column: 'c-abc', value: 'Ada "A"' })).toBe('c-abc:"Ada \\"A\\""');
+ });
+ test('quotes column names', () => {
+ expect(codaApi.buildRowQuery({ column: 'Due Time', value: 'x' })).toBe('"Due Time":"x"');
+ });
+ test('numbers and booleans stay unquoted', () => {
+ expect(codaApi.buildRowQuery({ column: 'c-a', value: 5 })).toBe('c-a:5');
+ expect(codaApi.buildRowQuery({ column: 'c-a', value: true })).toBe('c-a:true');
+ });
+});
+
+describe('validateLimit and toPageOutput', () => {
+ test('limit bounds', () => {
+ expect(codaApi.validateLimit({ limit: undefined, max: 100 })).toBeUndefined();
+ expect(codaApi.validateLimit({ limit: 100, max: 100 })).toBe(100);
+ expect(() => codaApi.validateLimit({ limit: 0, max: 100 })).toThrow();
+ expect(() => codaApi.validateLimit({ limit: 101, max: 100 })).toThrow();
+ expect(() => codaApi.validateLimit({ limit: 2.5, max: 100 })).toThrow();
+ });
+ test('page output never follows nextPageLink', () => {
+ expect(codaApi.toPageOutput({ items: [1], nextPageToken: 'n' })).toEqual({ items: [1], nextPageToken: 'n', hasMore: true });
+ expect(codaApi.toPageOutput({ items: [] })).toEqual({ items: [], nextPageToken: null, hasMore: false });
+ });
+});
+
+describe('request', () => {
+ test('sends bearer token to coda.io with query params and JSON body', async () => {
+ const seen = stubFetch(() => ({ body: { ok: 1 } }));
+ const result = await runStep(
+ codaApi.request({
+ token: ` ${TOKEN} `,
+ method: HttpMethod.POST,
+ path: '/docs/abc/tables/t/rows',
+ operation: 'add rows',
+ query: { disableParsing: true, skip: undefined, empty: '' },
+ body: { rows: [] },
+ }),
+ );
+ expect(result).toEqual({ ok: 1 });
+ expect(seen[0].url.startsWith('https://coda.io/apis/v1/docs/abc/tables/t/rows')).toBe(true);
+ expect(seen[0].auth).toBe(`Bearer ${TOKEN}`);
+ expect(seen[0].query.get('disableParsing')).toBe('true');
+ expect(seen[0].query.has('skip')).toBe(false);
+ expect(seen[0].query.has('empty')).toBe(false);
+ expect(seen[0].body).toEqual({ rows: [] });
+ });
+
+ test('retries 429 twice then succeeds', async () => {
+ const seen = stubFetch(replies([{ status: 429, body: { message: 'slow down' } }, { status: 429 }, { body: { done: true } }]));
+ const result = await runStep(codaApi.request({ token: TOKEN, method: HttpMethod.GET, path: '/whoami', operation: 'x' }));
+ expect(result).toEqual({ done: true });
+ expect(seen).toHaveLength(3);
+ });
+
+ test('gives up after the retries with a rate-limit message', async () => {
+ const seen = stubFetch(() => ({ status: 429, body: { message: 'slow down' } }));
+ await expect(runStep(codaApi.request({ token: TOKEN, method: HttpMethod.GET, path: '/whoami', operation: 'get user' }))).rejects.toThrow(
+ /Coda get user failed \(429\): Coda rate limit reached/,
+ );
+ expect(seen).toHaveLength(3);
+ });
+
+ test('retries 409 doc-not-ready', async () => {
+ stubFetch(replies([{ status: 409, body: { message: 'not accessible yet' } }, { body: { items: [] } }]));
+ await expect(runStep(codaApi.request({ token: TOKEN, method: HttpMethod.GET, path: '/docs/a/pages', operation: 'x' }))).resolves.toEqual({ items: [] });
+ });
+
+ test('errors carry status and responseBody, never body, and keep the vendor message', async () => {
+ stubFetch(() => ({ status: 404, body: { statusCode: 404, message: 'Could not find a row with the specified ID.' } }));
+ const error = await runStep(codaApi.request({ token: TOKEN, method: HttpMethod.GET, path: '/docs/a', operation: 'get row' })).catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(CodaApiError);
+ expect(error).toMatchObject({ status: 404, responseBody: { message: 'Could not find a row with the specified ID.' } });
+ expect(error).not.toHaveProperty('body');
+ expect(error instanceof Error ? error.message : '').toContain('Could not find a row with the specified ID.');
+ });
+
+ test('401 names the token', async () => {
+ stubFetch(() => ({ status: 401, body: { message: 'Unauthorized' } }));
+ await expect(runStep(codaApi.request({ token: TOKEN, method: HttpMethod.GET, path: '/whoami', operation: 'x' }))).rejects.toThrow(/invalid or was revoked/);
+ });
+});
+
+describe('waitForMutation', () => {
+ test('treats 404 as not registered yet and keeps polling', async () => {
+ const seen = stubFetch(replies([{ status: 404 }, { body: { completed: false } }, { body: { completed: true, warning: 'w' } }]));
+ const result = await runStep(codaApi.waitForMutation({ token: TOKEN, requestId: 'mutate:1' }));
+ expect(result).toEqual({ requestId: 'mutate:1', completed: true, warning: 'w' });
+ expect(seen.map((r) => r.path)).toEqual(['/mutationStatus/mutate%3A1', '/mutationStatus/mutate%3A1', '/mutationStatus/mutate%3A1']);
+ });
+
+ test('returns completed false after the wait budget instead of failing', async () => {
+ const seen = stubFetch(() => ({ body: { completed: false } }));
+ const result = await runStep(codaApi.waitForMutation({ token: TOKEN, requestId: 'r', timeoutMs: 10_000 }));
+ expect(result).toEqual({ requestId: 'r', completed: false, warning: null });
+ expect(seen.length).toBeGreaterThan(1);
+ expect(seen.length).toBeLessThanOrEqual(6);
+ });
+
+ test('a non-transient status-check error still returns the accepted write as pending', async () => {
+ stubFetch(() => ({ status: 401, body: { message: 'boom' } }));
+ const result = await runStep(codaApi.waitForMutation({ token: TOKEN, requestId: 'r-9' }));
+ expect(result).toMatchObject({ requestId: 'r-9', completed: false });
+ expect(result.warning).toMatch(/do not repeat.*boom/s);
+ });
+
+ test('a status check whose body never finishes is cut at the budget', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => new Response(new ReadableStream({ start: () => undefined }), { status: 200, headers: { 'content-type': 'application/json' } })),
+ );
+ const start = Date.now();
+ const result = await runStep(codaApi.waitForMutation({ token: TOKEN, requestId: 'r', timeoutMs: 10_000 }));
+ expect(result).toEqual({ requestId: 'r', completed: false, warning: null });
+ expect(Date.now() - start).toBeLessThanOrEqual(10_000);
+ });
+
+ test('server errors and rate limits keep polling, then return pending', async () => {
+ const seen = stubFetch(replies([{ status: 500, body: { message: 'boom' } }, { status: 429 }, { body: { completed: true } }]));
+ await expect(runStep(codaApi.waitForMutation({ token: TOKEN, requestId: 'r' }))).resolves.toEqual({ requestId: 'r', completed: true, warning: null });
+ expect(seen).toHaveLength(3);
+ stubFetch(() => ({ status: 503 }));
+ await expect(runStep(codaApi.waitForMutation({ token: TOKEN, requestId: 'r', timeoutMs: 5_000 }))).resolves.toEqual({
+ requestId: 'r',
+ completed: false,
+ warning: null,
+ });
+ });
+
+ test('a hanging status check is cut at the wait budget and returns pending', async () => {
+ let calls = 0;
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn((_input: unknown, init?: RequestInit) => {
+ calls++;
+ return new Promise<Response>((_resolve, reject) => {
+ init?.signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')));
+ });
+ }),
+ );
+ const start = Date.now();
+ const result = await runStep(codaApi.waitForMutation({ token: TOKEN, requestId: 'r', timeoutMs: 10_000 }));
+ expect(result).toEqual({ requestId: 'r', completed: false, warning: null });
+ expect(Date.now() - start).toBeLessThanOrEqual(10_000);
+ expect(calls).toBeGreaterThanOrEqual(1);
+ });
+
+ test('pollRequestBudget never exceeds the remaining time', () => {
+ expect(codaApi.pollRequestBudget({ deadline: 5_000, now: () => 0 })).toBe(5_000);
+ expect(codaApi.pollRequestBudget({ deadline: 100_000, now: () => 0 })).toBe(30_000);
+ expect(codaApi.pollRequestBudget({ deadline: 500, now: () => 0 })).toBeUndefined();
+ });
+
+ test('settleMutation skips waiting when turned off and refuses a missing request id', async () => {
+ const seen = stubFetch(() => ({ body: {} }));
+ await expect(codaApi.settleMutation({ token: TOKEN, requestId: 'r', waitForCompletion: false })).resolves.toEqual({
+ requestId: 'r',
+ completed: false,
+ warning: null,
+ });
+ expect(seen).toHaveLength(0);
+ await expect(codaApi.settleMutation({ token: TOKEN, requestId: undefined, waitForCompletion: true })).rejects.toThrow(/no request ID/);
+ });
+});
diff --git a/packages/pieces/community/coda/test/docs.test.ts b/packages/pieces/community/coda/test/docs.test.ts
new file mode 100644
index 00000000000..05ac5d2c1d2
--- /dev/null
+++ b/packages/pieces/community/coda/test/docs.test.ts
@@ -0,0 +1,127 @@
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { getCurrentUserAction } from '../src/lib/actions/get-current-user';
+import { listDocsAction } from '../src/lib/actions/list-docs';
+import { getDocAction } from '../src/lib/actions/get-doc';
+import { createDocAction } from '../src/lib/actions/create-doc';
+import { updateDocAction } from '../src/lib/actions/ai/update-doc';
+import { deleteDocAction } from '../src/lib/actions/delete-doc';
+import { listFoldersAction } from '../src/lib/actions/list-folders';
+import { replies, run, stubFetch } from './helpers';
+
+beforeEach(() => {
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+describe('get_current_user', () => {
+ test('GET /whoami', async () => {
+ const seen = stubFetch(() => ({ body: { name: 'A', loginId: '[email protected]' } }));
+ await expect(run(getCurrentUserAction)({})).resolves.toEqual({ name: 'A', loginId: '[email protected]' });
+ expect(seen[0].path).toBe('/whoami');
+ });
+});
+
+describe('list_docs', () => {
+ test('sends only set filters and returns one page', async () => {
+ const seen = stubFetch(() => ({ body: { items: [{ id: 'd1' }], nextPageToken: 'n', nextPageLink: 'https://evil.io/x' } }));
+ const result = await run(listDocsAction)({ query: ' plan ', isOwner: true, isStarred: false, limit: 10, pageToken: 'p' });
+ expect(result).toEqual({ items: [{ id: 'd1' }], nextPageToken: 'n', hasMore: true });
+ expect(Object.fromEntries(seen[0].query)).toEqual({ query: 'plan', isOwner: 'true', limit: '10', pageToken: 'p' });
+ expect(seen).toHaveLength(1);
+ });
+ test('rejects limit above 100', async () => {
+ await expect(run(listDocsAction)({ limit: 101 })).rejects.toThrow(/between 1 and 100/);
+ });
+});
+
+describe('get_doc', () => {
+ test('accepts a browser link', async () => {
+ const seen = stubFetch(() => ({ body: { id: 'MG3' } }));
+ await run(getDocAction)({ docId: 'https://docs.superhuman.com/d/AP-TEST_dMG3' });
+ expect(seen[0].path).toBe('/docs/MG3');
+ });
+ test('refuses a lookalike host before any request', async () => {
+ const seen = stubFetch(() => ({ body: {} }));
+ await expect(run(getDocAction)({ docId: 'https://coda.io.evil.io/d/_dMG3' })).rejects.toThrow(/not a Coda doc link/);
+ expect(seen).toHaveLength(0);
+ });
+});
+
+describe('create_doc', () => {
+ test('copies a doc and waits for the copy', async () => {
+ const seen = stubFetch(
+ replies([
+ { status: 201, body: { id: 'new1', name: 'T', requestId: 'copy_doc:src:new1' } },
+ { body: { completed: true } },
+ ]),
+ );
+ const result = await run(createDocAction)({ title: ' T ', sourceDoc: 'https://coda.io/d/X_dsrc', folderId: 'fl-1' });
+ expect(seen[0].body).toEqual({ title: 'T', sourceDoc: 'src', folderId: 'fl-1' });
+ expect(seen[1].path).toBe('/mutationStatus/copy_doc%3Asrc%3Anew1');
+ expect(result).toMatchObject({ id: 'new1', requestId: 'copy_doc:src:new1', completed: true, warning: null });
+ });
+ test('blank doc with a first page', async () => {
+ const seen = stubFetch(replies([{ status: 201, body: { id: 'n', requestId: 'create_doc:n' } }, { body: { completed: true } }]));
+ await run(createDocAction)({ title: 'T', pageName: 'Intro', pageContent: '# Hi', contentFormat: 'markdown' });
+ expect(seen[0].body).toEqual({
+ title: 'T',
+ initialPage: { name: 'Intro', pageContent: { type: 'canvas', canvasContent: { format: 'markdown', content: '# Hi' } } },
+ });
+ });
+ test('refuses page content together with a copy', async () => {
+ const seen = stubFetch(() => ({ body: {} }));
+ await expect(run(createDocAction)({ title: 'T', sourceDoc: 'src', pageContent: 'x' })).rejects.toThrow(/blank doc/);
+ expect(seen).toHaveLength(0);
+ });
+ test('no wait when turned off', async () => {
+ const seen = stubFetch(() => ({ status: 201, body: { id: 'n', requestId: 'create_doc:n' } }));
+ const result = await run(createDocAction)({ title: 'T', waitForCompletion: false });
+ expect(seen).toHaveLength(1);
+ expect(result).toMatchObject({ completed: false, requestId: 'create_doc:n' });
+ });
+});
+
+describe('update_doc', () => {
+ test('is ai-only and PATCHes only given fields', async () => {
+ expect(updateDocAction.audience).toBe('ai');
+ const seen = stubFetch(() => ({ body: {} }));
+ const result = await run(updateDocAction)({ docId: 'd1', title: ' New ' });
+ expect(seen[0].method).toBe('PATCH');
+ expect(seen[0].body).toEqual({ title: 'New' });
+ expect(result).toEqual({ id: 'd1', title: 'New', iconName: null });
+ });
+ test('refuses an empty update', async () => {
+ const seen = stubFetch(() => ({ body: {} }));
+ await expect(run(updateDocAction)({ docId: 'd1', title: ' ' })).rejects.toThrow(/Title or an Icon Name/);
+ expect(seen).toHaveLength(0);
+ });
+});
+
+describe('delete_doc', () => {
+ test('DELETE and report', async () => {
+ const seen = stubFetch(() => ({ status: 202, body: {} }));
+ await expect(run(deleteDocAction)({ docId: 'd1' })).resolves.toEqual({ id: 'd1', deleted: true, alreadyDeleted: false });
+ expect(seen[0].method).toBe('DELETE');
+ });
+ test('404 means already deleted', async () => {
+ stubFetch(() => ({ status: 404, body: { message: 'gone' } }));
+ await expect(run(deleteDocAction)({ docId: 'd1' })).resolves.toEqual({ id: 'd1', deleted: true, alreadyDeleted: true });
+ });
+ test('other failures fail', async () => {
+ stubFetch(() => ({ status: 403, body: { message: 'nope' } }));
+ await expect(run(deleteDocAction)({ docId: 'd1' })).rejects.toThrow(/403/);
+ });
+});
+
+describe('list_folders', () => {
+ test('filters by workspace', async () => {
+ const seen = stubFetch(() => ({ body: { items: [] } }));
+ await expect(run(listFoldersAction)({ workspaceId: 'ws-1' })).resolves.toEqual({ items: [], nextPageToken: null, hasMore: false });
+ expect(seen[0].path).toBe('/folders');
+ expect(seen[0].query.get('workspaceId')).toBe('ws-1');
+ });
+});
diff --git a/packages/pieces/community/coda/test/existing-actions.test.ts b/packages/pieces/community/coda/test/existing-actions.test.ts
new file mode 100644
index 00000000000..57edb50446d
--- /dev/null
+++ b/packages/pieces/community/coda/test/existing-actions.test.ts
@@ -0,0 +1,144 @@
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { createRowAction } from '../src/lib/actions/create-row';
+import { updateRowAction } from '../src/lib/actions/update-row';
+import { upsertRowAction } from '../src/lib/actions/upsert-row';
+import { findRowAction } from '../src/lib/actions/find-row';
+import { getRowAction } from '../src/lib/actions/get-row';
+import { getTableAction } from '../src/lib/actions/get-table';
+import { listTablesAction } from '../src/lib/actions/list-tables';
+import { replies, run, stubFetch } from './helpers';
+
+beforeEach(() => {
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+describe('existing actions keep their names and become human-only', () => {
+ test.each([
+ [createRowAction, 'create-row'],
+ [updateRowAction, 'update-row'],
+ [upsertRowAction, 'upsert-row'],
+ [findRowAction, 'find-row'],
+ [getRowAction, 'get-row'],
+ [getTableAction, 'get-table'],
+ [listTablesAction, 'list-tables'],
+ ])('%#', (action, name) => {
+ expect(action.name).toBe(name);
+ expect(action.audience).toBe('human');
+ expect(action.outputSchema).toBeDefined();
+ });
+});
+
+describe('create-row', () => {
+ test('posts non-empty cells and returns rowId plus requestId without waiting', async () => {
+ const seen = stubFetch(() => ({ status: 202, body: { requestId: 'mutate:1', addedRowIds: ['i-1'] } }));
+ const result = await run(createRowAction)({
+ docId: 'doc1',
+ tableId: 'grid-1',
+ rowData: { 'c-a': 'x', 'c-b': '', 'c-c': null, 'c-d': 0, 'c-e': false },
+ });
+ expect(result).toEqual({ rowId: 'i-1', requestId: 'mutate:1' });
+ expect(seen).toHaveLength(1);
+ expect(seen[0].method).toBe('POST');
+ expect(seen[0].path).toBe('/docs/doc1/tables/grid-1/rows');
+ expect(seen[0].body).toEqual({
+ rows: [{ cells: [{ column: 'c-a', value: 'x' }, { column: 'c-d', value: 0 }, { column: 'c-e', value: false }] }],
+ });
+ });
+ test('refuses an empty row', async () => {
+ const seen = stubFetch(() => ({ body: {} }));
+ await expect(run(createRowAction)({ docId: 'd', tableId: 't', rowData: {} })).rejects.toThrow(/column values/);
+ expect(seen).toHaveLength(0);
+ });
+});
+
+describe('update-row', () => {
+ test('refuses empty cells before any request', async () => {
+ const seen = stubFetch(() => ({ body: {} }));
+ await expect(run(updateRowAction)({ docId: 'd', tableId: 't', rowIdOrName: 'i-1', rowData: { 'c-a': '' } })).rejects.toThrow(
+ /at least one column value/,
+ );
+ expect(seen).toHaveLength(0);
+ });
+ test('PUTs the row with an encoded row name', async () => {
+ const seen = stubFetch(() => ({ status: 202, body: { requestId: 'mutate:2', id: 'i-9' } }));
+ const result = await run(updateRowAction)({ docId: 'd', tableId: 't', rowIdOrName: 'Row/1', rowData: { 'c-a': 'v' } });
+ expect(result).toEqual({ rowId: 'i-9', requestId: 'mutate:2' });
+ expect(seen[0].method).toBe('PUT');
+ expect(seen[0].url).toContain('/docs/d/tables/t/rows/Row%2F1');
+ expect(seen[0].body).toEqual({ row: { cells: [{ column: 'c-a', value: 'v' }] } });
+ });
+});
+
+describe('upsert-row', () => {
+ test('refuses when a key column has no value', async () => {
+ const seen = stubFetch(() => ({ body: {} }));
+ await expect(
+ run(upsertRowAction)({ docId: 'd', tableId: 't', keyColumns: ['c-key'], rowData: { 'c-other': 'v' } }),
+ ).rejects.toThrow(/Missing values for: c-key/);
+ expect(seen).toHaveLength(0);
+ });
+ test('sends keyColumns and returns requestId', async () => {
+ const seen = stubFetch(() => ({ status: 202, body: { requestId: 'mutate:3' } }));
+ const result = await run(upsertRowAction)({ docId: 'd', tableId: 't', keyColumns: ['c-key'], rowData: { 'c-key': 'k', 'c-v': 1 } });
+ expect(result).toEqual({ success: true, requestId: 'mutate:3' });
+ expect(seen[0].body).toEqual({ rows: [{ cells: [{ column: 'c-key', value: 'k' }, { column: 'c-v', value: 1 }] }], keyColumns: ['c-key'] });
+ });
+ test('has an output schema with the request id', () => {
+ expect(upsertRowAction.outputSchema?.fields.map((field) => field.key)).toEqual(['success', 'requestId']);
+ });
+});
+
+describe('find-row', () => {
+ test('queries by column id with a quoted value, page size 500, all pages', async () => {
+ const seen = stubFetch(
+ replies([
+ { body: { items: [{ id: 'i-1' }], nextPageToken: 'p2' } },
+ { body: { items: [{ id: 'i-2' }] } },
+ ]),
+ );
+ const result = await run(findRowAction)({ docId: 'd', tableId: 't', searchColumn: 'c-amount', searchValue: '10' });
+ expect(result).toEqual({ found: true, result: [{ id: 'i-1' }, { id: 'i-2' }] });
+ expect(seen[0].query.get('query')).toBe('c-amount:"10"');
+ expect(seen[0].query.get('limit')).toBe('500');
+ expect(seen[1].query.get('pageToken')).toBe('p2');
+ });
+ test('stops at Max Rows', async () => {
+ const seen = stubFetch(() => ({ body: { items: [{ id: 'a' }, { id: 'b' }], nextPageToken: 'more' } }));
+ const result = await run(findRowAction)({ docId: 'd', tableId: 't', searchColumn: 'c-a', searchValue: 'x', maxRows: 1 });
+ expect(result).toEqual({ found: true, result: [{ id: 'a' }] });
+ expect(seen).toHaveLength(1);
+ });
+ test('rejects a bad Max Rows', async () => {
+ await expect(run(findRowAction)({ docId: 'd', tableId: 't', searchColumn: 'c-a', searchValue: 'x', maxRows: 0 })).rejects.toThrow();
+ });
+});
+
+describe('get-row / get-table / list-tables', () => {
+ test('get-row asks for column names and simpleWithArrays', async () => {
+ const seen = stubFetch(() => ({ body: { id: 'i-1' } }));
+ await run(getRowAction)({ docId: 'd', tableId: 't', rowIdOrName: 'i-1' });
+ expect(seen[0].path).toBe('/docs/d/tables/t/rows/i-1');
+ expect(seen[0].query.get('useColumnNames')).toBe('true');
+ expect(seen[0].query.get('valueFormat')).toBe('simpleWithArrays');
+ });
+ test('get-table description no longer promises columns', async () => {
+ expect(getTableAction.description).not.toMatch(/columns, schema/);
+ const seen = stubFetch(() => ({ body: { id: 't' } }));
+ await run(getTableAction)({ docId: 'd', tableId: 't' });
+ expect(seen[0].path).toBe('/docs/d/tables/t');
+ });
+ test('list-tables refuses max below 1', async () => {
+ const seen = stubFetch(() => ({ body: { items: [] } }));
+ await expect(run(listTablesAction)({ docId: 'd', max: 0 })).rejects.toThrow(/Max Tables/);
+ expect(seen).toHaveLength(0);
+ });
+ test('list-tables trims to max', async () => {
+ stubFetch(() => ({ body: { items: [{ id: 'a' }, { id: 'b' }, { id: 'c' }], nextPageToken: 'n' } }));
+ await expect(run(listTablesAction)({ docId: 'd', max: 2 })).resolves.toEqual({ found: true, result: [{ id: 'a' }, { id: 'b' }] });
+ });
+});
diff --git a/packages/pieces/community/coda/test/helpers.ts b/packages/pieces/community/coda/test/helpers.ts
new file mode 100644
index 00000000000..e58745a428a
--- /dev/null
+++ b/packages/pieces/community/coda/test/helpers.ts
@@ -0,0 +1,118 @@
+import { AppConnectionType, Store } from '@activepieces/pieces-framework';
+import { vi } from 'vitest';
+
+export type SeenRequest = {
+ url: string;
+ method: string;
+ path: string;
+ query: URLSearchParams;
+ auth: string | null;
+ accept: string | null;
+ body: unknown;
+};
+
+export type FakeReply = {
+ status?: number;
+ body?: unknown;
+ text?: string;
+ headers?: Record<string, string>;
+};
+
+export function stubFetch(respond: (request: SeenRequest, index: number) => FakeReply): SeenRequest[] {
+ const seen: SeenRequest[] = [];
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
+ const url = input instanceof Request ? input.url : String(input);
+ const headers = new Headers(init?.headers);
+ const parsed = new URL(url);
+ const rawBody = typeof init?.body === 'string' ? init.body : null;
+ const request: SeenRequest = {
+ url,
+ method: (init?.method ?? 'GET').toUpperCase(),
+ path: parsed.pathname.replace('/apis/v1', ''),
+ query: parsed.searchParams,
+ auth: headers.get('authorization'),
+ accept: headers.get('accept'),
+ body: rawBody ? JSON.parse(rawBody) : null,
+ };
+ seen.push(request);
+ const reply = respond(request, seen.length - 1);
+ const payload = reply.text ?? JSON.stringify(reply.body ?? {});
+ return new Response(payload, {
+ status: reply.status ?? 200,
+ headers: { 'content-type': reply.text !== undefined ? 'text/plain' : 'application/json', ...(reply.headers ?? {}) },
+ });
+ }),
+ );
+ return seen;
+}
+
+export function replies(list: FakeReply[]): (request: SeenRequest, index: number) => FakeReply {
+ return (_request, index) => list[Math.min(index, list.length - 1)];
+}
+
+export const TOKEN = 'test-token';
+
+export const SERVER = { apiUrl: 'http://localhost:3000/api/', publicUrl: 'http://localhost:4200/', token: 'x' };
+
+export function codaConnection() {
+ return { type: AppConnectionType.SECRET_TEXT as const, secret_text: TOKEN };
+}
+
+export function actionContext(propsValue: Record<string, unknown>): TestActionContext {
+ return { auth: codaConnection(), propsValue, store: memoryStore(), server: SERVER };
+}
+
+export function memoryStore(initial: Record<string, unknown> = {}): MemoryStore {
+ const data = new Map<string, string>(Object.entries(initial).map(([key, value]) => [key, JSON.stringify(value)]));
+ return {
+ read: (key: string): unknown => {
+ const raw = data.get(key);
+ return raw === undefined ? undefined : JSON.parse(raw);
+ },
+ put: async <T>(key: string, value: T): Promise<T> => {
+ data.set(key, JSON.stringify(value));
+ return value;
+ },
+ get: async <T>(key: string): Promise<T | null> => {
+ const raw = data.get(key);
+ return raw === undefined ? null : JSON.parse(raw);
+ },
+ delete: async (key: string): Promise<void> => {
+ data.delete(key);
+ },
+ };
+}
+
+export async function runStep<T>(promise: Promise<T>): Promise<T> {
+ const settled = promise.then(
+ (value) => ({ ok: true as const, value }),
+ (error: unknown) => ({ ok: false as const, error }),
+ );
+ await vi.runAllTimersAsync();
+ const result = await settled;
+ if (!result.ok) {
+ throw result.error;
+ }
+ return result.value;
+}
+
+export function run(action: Runnable) {
+ return (propsValue: Record<string, unknown>): Promise<unknown> => runStep(action.run(actionContext(propsValue)));
+}
+
+export function idsOf(items: unknown): unknown[] {
+ return Array.isArray(items) ? items.map((item: unknown) => (item !== null && typeof item === 'object' ? Reflect.get(item, 'id') : undefined)) : [];
+}
+
+export type MemoryStore = Store & { read: (key: string) => unknown };
+
+type TestActionContext = {
+ auth: { type: AppConnectionType.SECRET_TEXT; secret_text: string };
+ propsValue: Record<string, unknown>;
+ store: Store;
+ server: typeof SERVER;
+};
+
+type Runnable = { run(context: TestActionContext): Promise<unknown> };
diff --git a/packages/pieces/community/coda/test/misc.test.ts b/packages/pieces/community/coda/test/misc.test.ts
new file mode 100644
index 00000000000..48fb52d1280
--- /dev/null
+++ b/packages/pieces/community/coda/test/misc.test.ts
@@ -0,0 +1,143 @@
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { listFormulasAction } from '../src/lib/actions/list-formulas';
+import { getFormulaAction } from '../src/lib/actions/get-formula';
+import { listControlsAction } from '../src/lib/actions/list-controls';
+import { getControlAction } from '../src/lib/actions/get-control';
+import { getMutationStatusAction } from '../src/lib/actions/get-mutation-status';
+import { resolveBrowserLinkAction } from '../src/lib/actions/ai/resolve-browser-link';
+import { listPermissionsAction } from '../src/lib/actions/list-permissions';
+import { addPermissionAction } from '../src/lib/actions/add-permission';
+import { removePermissionAction } from '../src/lib/actions/remove-permission';
+import { triggerAutomationAction } from '../src/lib/actions/trigger-automation';
+import { coda } from '../src';
+import { run, stubFetch } from './helpers';
+
+beforeEach(() => {
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+describe('formulas and controls', () => {
+ test.each([
+ [listFormulasAction, '/docs/d/formulas'],
+ [listControlsAction, '/docs/d/controls'],
+ ])('%# list path', async (action, path) => {
+ const seen = stubFetch(() => ({ body: { items: [] } }));
+ await run(action)({ docId: 'd' });
+ expect(seen[0].path).toBe(path);
+ });
+ test('get formula by name', async () => {
+ const seen = stubFetch(() => ({ body: { id: 'f-1', value: 35.5 } }));
+ await expect(run(getFormulaAction)({ docId: 'd', formulaIdOrName: 'Total Amount' })).resolves.toEqual({ id: 'f-1', value: 35.5 });
+ expect(seen[0].url).toContain('/docs/d/formulas/Total%20Amount');
+ });
+ test('get control', async () => {
+ const seen = stubFetch(() => ({ body: { id: 'ctrl-1', value: 0 } }));
+ await run(getControlAction)({ docId: 'd', controlIdOrName: 'ctrl-1' });
+ expect(seen[0].path).toBe('/docs/d/controls/ctrl-1');
+ });
+});
+
+describe('get_mutation_status', () => {
+ test('returns completed and warning', async () => {
+ const seen = stubFetch(() => ({ body: { completed: true } }));
+ await expect(run(getMutationStatusAction)({ requestId: ' mutate:1 ' })).resolves.toEqual({ requestId: 'mutate:1', completed: true, warning: null });
+ expect(seen[0].path).toBe('/mutationStatus/mutate%3A1');
+ });
+});
+
+describe('resolve_browser_link', () => {
+ test('derives doc and table ids', async () => {
+ const seen = stubFetch(() => ({
+ body: {
+ browserLink: 'https://docs.superhuman.com/d/_dD1#_tugrid-1/_rui-1',
+ resource: { type: 'row', id: 'i-1', href: 'https://coda.io/apis/v1/docs/D1/tables/grid-1/rows/i-1' },
+ },
+ }));
+ const result = await run(resolveBrowserLinkAction)({ url: 'https://docs.superhuman.com/d/_dD1#_tugrid-1/_rui-1' });
+ expect(result).toEqual({
+ resourceType: 'row',
+ id: 'i-1',
+ name: null,
+ docId: 'D1',
+ tableId: 'grid-1',
+ browserLink: 'https://docs.superhuman.com/d/_dD1#_tugrid-1/_rui-1',
+ });
+ expect(seen[0].path).toBe('/resolveBrowserLink');
+ expect(seen[0].query.get('degradeGracefully')).toBe('true');
+ });
+ test('refuses non-Coda links', async () => {
+ const seen = stubFetch(() => ({ body: {} }));
+ await expect(run(resolveBrowserLinkAction)({ url: 'https://coda.io.evil.io/d/x' })).rejects.toThrow();
+ await expect(run(resolveBrowserLinkAction)({ url: 'http://coda.io/d/x' })).rejects.toThrow();
+ expect(seen).toHaveLength(0);
+ });
+});
+
+describe('sharing', () => {
+ test('list', async () => {
+ const seen = stubFetch(() => ({ body: { items: [{ id: 'p1' }] } }));
+ await expect(run(listPermissionsAction)({ docId: 'd' })).resolves.toEqual({ items: [{ id: 'p1' }], nextPageToken: null, hasMore: false });
+ expect(seen[0].path).toBe('/docs/d/acl/permissions');
+ });
+ test('share with an email then look up the permission id', async () => {
+ const seen = stubFetch((request) =>
+ request.method === 'POST'
+ ? { body: {} }
+ : { body: { items: [{ id: 'p-other', principal: { type: 'email', email: '[email protected]' } }, { id: 'p-1', access: 'readonly', principal: { type: 'email', email: '[email protected]' } }] } },
+ );
+ const result = await run(addPermissionAction)({ docId: 'd', principalType: 'email', principal: '[email protected]', access: 'readonly', suppressEmail: true });
+ expect(seen[0].body).toEqual({ access: 'readonly', principal: { type: 'email', email: '[email protected]' }, suppressEmail: true });
+ expect(result).toEqual({ docId: 'd', permissionId: 'p-1', principalType: 'email', principal: '[email protected]', access: 'readonly' });
+ });
+ test.each([
+ ['email', 'not-an-email'],
+ ['domain', 'nodot'],
+ ['anyone', 'x'],
+ ])('refuses %s %s', async (principalType, principal) => {
+ const seen = stubFetch(() => ({ body: {} }));
+ await expect(run(addPermissionAction)({ docId: 'd', principalType, principal, access: 'readonly' })).rejects.toThrow();
+ expect(seen).toHaveLength(0);
+ });
+ test('remove; 404 means already removed', async () => {
+ const seen = stubFetch(() => ({ status: 404, body: { message: 'gone' } }));
+ await expect(run(removePermissionAction)({ docId: 'd', permissionId: 'p-1' })).resolves.toEqual({
+ docId: 'd',
+ permissionId: 'p-1',
+ removed: true,
+ alreadyRemoved: true,
+ });
+ expect(seen[0].method).toBe('DELETE');
+ expect(seen[0].path).toBe('/docs/d/acl/permissions/p-1');
+ });
+});
+
+describe('trigger_automation', () => {
+ test('posts the payload', async () => {
+ const seen = stubFetch(() => ({ status: 202, body: { requestId: 'r' } }));
+ await expect(run(triggerAutomationAction)({ docId: 'd', ruleId: 'grid-auto-1', payload: { a: 1 } })).resolves.toEqual({ ruleId: 'grid-auto-1', requestId: 'r' });
+ expect(seen[0].path).toBe('/docs/d/hooks/automation/grid-auto-1');
+ expect(seen[0].body).toEqual({ a: 1 });
+ });
+});
+
+describe('piece metadata', () => {
+ test('every action is tagged and new names are unique', () => {
+ const actions = Object.values(coda.actions());
+ expect(actions).toHaveLength(41);
+ for (const action of actions) {
+ expect(action.audience, action.name).toBeDefined();
+ expect(action.classification, action.name).toBeDefined();
+ if (action.name !== 'custom_api_call') {
+ expect(action.aiMetadata?.description, action.name).toBeTruthy();
+ expect(action.outputSchema, action.name).toBeDefined();
+ }
+ }
+ const byAudience = actions.reduce<Record<string, number>>((acc, action) => ({ ...acc, [String(action.audience)]: (acc[String(action.audience)] ?? 0) + 1 }), {});
+ expect(byAudience).toEqual({ human: 8, both: 27, ai: 6 });
+ });
+});
diff --git a/packages/pieces/community/coda/test/pages.test.ts b/packages/pieces/community/coda/test/pages.test.ts
new file mode 100644
index 00000000000..cf9673437a6
--- /dev/null
+++ b/packages/pieces/community/coda/test/pages.test.ts
@@ -0,0 +1,158 @@
+import { Readable } from 'node:stream';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { listPagesAction } from '../src/lib/actions/list-pages';
+import { getPageAction } from '../src/lib/actions/get-page';
+import { createPageAction } from '../src/lib/actions/create-page';
+import { updatePageAction } from '../src/lib/actions/update-page';
+import { deletePageAction } from '../src/lib/actions/delete-page';
+import { getPageContentAction } from '../src/lib/actions/get-page-content';
+import { pageExport } from '../src/lib/common/page-export';
+import { run, stubFetch, TOKEN } from './helpers';
+
+const S3 = 'https://bucket.s3.amazonaws.com/export/1?sig=abc';
+
+beforeEach(() => {
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+describe('list_pages / get_page', () => {
+ test('list pages with paging', async () => {
+ const seen = stubFetch(() => ({ body: { items: [{ id: 'canvas-1' }] } }));
+ await expect(run(listPagesAction)({ docId: 'd', limit: 5 })).resolves.toEqual({ items: [{ id: 'canvas-1' }], nextPageToken: null, hasMore: false });
+ expect(seen[0].path).toBe('/docs/d/pages');
+ expect(seen[0].query.get('limit')).toBe('5');
+ });
+ test('get page by name is encoded', async () => {
+ const seen = stubFetch(() => ({ body: { id: 'canvas-1' } }));
+ await run(getPageAction)({ docId: 'd', pageIdOrName: 'My Page' });
+ expect(seen[0].url).toContain('/docs/d/pages/My%20Page');
+ });
+});
+
+describe('create_page', () => {
+ test('posts canvas content and waits', async () => {
+ const seen = stubFetch((request) =>
+ request.path.startsWith('/mutationStatus') ? { body: { completed: true } } : { status: 202, body: { id: 'canvas-9', requestId: 'mutate:p' } },
+ );
+ const result = await run(createPageAction)({ docId: 'd', name: 'P', parentPageId: 'canvas-1', content: '# x', contentFormat: 'markdown' });
+ expect(seen[0].body).toEqual({
+ name: 'P',
+ parentPageId: 'canvas-1',
+ pageContent: { type: 'canvas', canvasContent: { format: 'markdown', content: '# x' } },
+ });
+ expect(result).toEqual({ id: 'canvas-9', requestId: 'mutate:p', completed: true, warning: null });
+ });
+});
+
+describe('update_page', () => {
+ test('replace content and hide', async () => {
+ const seen = stubFetch((request) =>
+ request.path.startsWith('/mutationStatus') ? { body: { completed: true } } : { status: 202, body: { id: 'canvas-1', requestId: 'mutate:u' } },
+ );
+ await run(updatePageAction)({ docId: 'd', pageIdOrName: 'canvas-1', content: 'new', insertionMode: 'replace', visibility: 'hidden' });
+ expect(seen[0].method).toBe('PUT');
+ expect(seen[0].body).toEqual({
+ isHidden: true,
+ contentUpdate: { insertionMode: 'replace', canvasContent: { format: 'markdown', content: 'new' } },
+ });
+ });
+ test('defaults to append', async () => {
+ const seen = stubFetch(() => ({ status: 202, body: { id: 'canvas-1', requestId: 'mutate:u' } }));
+ await run(updatePageAction)({ docId: 'd', pageIdOrName: 'canvas-1', content: 'more', waitForCompletion: false });
+ expect(seen[0].body).toMatchObject({ contentUpdate: { insertionMode: 'append' } });
+ });
+ test('refuses an empty update', async () => {
+ const seen = stubFetch(() => ({ body: {} }));
+ await expect(run(updatePageAction)({ docId: 'd', pageIdOrName: 'canvas-1', content: ' ' })).rejects.toThrow(/Nothing to update/);
+ expect(seen).toHaveLength(0);
+ });
+});
+
+describe('delete_page', () => {
+ test.each([404, 410])('%s means already deleted', async (status) => {
+ stubFetch(() => ({ status, body: { message: 'gone' } }));
+ await expect(run(deletePageAction)({ docId: 'd', pageIdOrName: 'canvas-1' })).resolves.toMatchObject({ alreadyDeleted: true, completed: true });
+ });
+ test('deletes and waits', async () => {
+ const seen = stubFetch((request) =>
+ request.path.startsWith('/mutationStatus') ? { body: { completed: true } } : { status: 202, body: { id: 'canvas-1', requestId: 'mutate:d' } },
+ );
+ await expect(run(deletePageAction)({ docId: 'd', pageIdOrName: 'canvas-1' })).resolves.toMatchObject({ id: 'canvas-1', alreadyDeleted: false, completed: true });
+ expect(seen[0].method).toBe('DELETE');
+ });
+});
+
+describe('get_page_content', () => {
+ test('exports, polls, then downloads without the Coda token', async () => {
+ const seen = stubFetch((request) => {
+ if (request.method === 'POST') {
+ return { status: 202, body: { id: 'exp1', status: 'inProgress' } };
+ }
+ if (request.url.startsWith(S3)) {
+ return { text: '# Hello' };
+ }
+ return { body: { id: 'exp1', status: seen.length < 4 ? 'inProgress' : 'complete', downloadLink: S3 } };
+ });
+ const result = await run(getPageContentAction)({ docId: 'd', pageIdOrName: 'canvas-1', outputFormat: 'markdown' });
+ expect(result).toEqual({ pageId: 'canvas-1', format: 'markdown', completed: true, exportId: 'exp1', content: '# Hello', truncated: false });
+ expect(seen[0].body).toEqual({ outputFormat: 'markdown' });
+ const download = seen.find((request) => request.url.startsWith(S3));
+ expect(download?.auth).toBeNull();
+ expect(download?.accept).toContain('text/markdown');
+ expect(seen.filter((request) => request.url.startsWith('https://coda.io')).every((request) => request.auth === `Bearer ${TOKEN}`)).toBe(true);
+ });
+ test('resumes with an export id and returns completed false when still running', async () => {
+ const seen = stubFetch(() => ({ body: { id: 'exp1', status: 'inProgress' } }));
+ const result = await run(getPageContentAction)({ docId: 'd', pageIdOrName: 'canvas-1', outputFormat: 'html', exportId: 'exp1' });
+ expect(result).toEqual({ pageId: 'canvas-1', format: 'html', completed: false, exportId: 'exp1', content: null, truncated: false });
+ expect(seen.every((request) => request.method === 'GET')).toBe(true);
+ });
+ test('a hanging or failing status check returns the export id to resume instead of failing', async () => {
+ stubFetch(() => ({ status: 503 }));
+ await expect(run(getPageContentAction)({ docId: 'd', pageIdOrName: 'p', outputFormat: 'markdown', exportId: 'exp1' })).resolves.toEqual({
+ pageId: 'p',
+ format: 'markdown',
+ completed: false,
+ exportId: 'exp1',
+ content: null,
+ truncated: false,
+ });
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(
+ (_input: unknown, init?: RequestInit) =>
+ new Promise<Response>((_resolve, reject) => {
+ init?.signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')));
+ }),
+ ),
+ );
+ const start = Date.now();
+ const result = await run(getPageContentAction)({ docId: 'd', pageIdOrName: 'p', outputFormat: 'markdown', exportId: 'exp1' });
+ expect(result).toMatchObject({ completed: false, exportId: 'exp1' });
+ expect(Date.now() - start).toBeLessThanOrEqual(60_000);
+ });
+ test('an unknown export id fails instead of waiting', async () => {
+ stubFetch(() => ({ status: 404, body: { message: 'no such export' } }));
+ await expect(run(getPageContentAction)({ docId: 'd', pageIdOrName: 'p', outputFormat: 'markdown', exportId: 'nope' })).rejects.toThrow(/no such export/);
+ });
+ test('failed export throws', async () => {
+ stubFetch((request) => (request.method === 'POST' ? { status: 202, body: { id: 'e' } } : { body: { id: 'e', status: 'failed', error: 'too big' } }));
+ await expect(run(getPageContentAction)({ docId: 'd', pageIdOrName: 'p', outputFormat: 'markdown' })).rejects.toThrow(/too big/);
+ });
+ test('refuses a non-https download link', async () => {
+ await expect(pageExport.downloadText({ url: 'http://bucket/x', format: 'markdown' })).rejects.toThrow(/not HTTPS/);
+ });
+ test('caps content at the byte limit', async () => {
+ const stream = Readable.from([Buffer.from('abcdef'), Buffer.from('ghij')]);
+ await expect(pageExport.readCapped({ stream, maxBytes: 8, timeoutMs: 1000 })).resolves.toEqual({ content: 'abcdefgh', truncated: true });
+ });
+ test('exact-size content is not truncated', async () => {
+ const stream = Readable.from([Buffer.from('abcd')]);
+ await expect(pageExport.readCapped({ stream, maxBytes: 4, timeoutMs: 1000 })).resolves.toEqual({ content: 'abcd', truncated: false });
+ });
+});
diff --git a/packages/pieces/community/coda/test/props.test.ts b/packages/pieces/community/coda/test/props.test.ts
new file mode 100644
index 00000000000..02897027114
--- /dev/null
+++ b/packages/pieces/community/coda/test/props.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, test } from 'vitest';
+import { columnToProperty } from '../src/lib/common/props';
+import { CodaTableColumn } from '../src/lib/common/types';
+
+function column({ type, extra = {} }: { type: string; extra?: Partial<CodaTableColumn> }): CodaTableColumn {
+ return { id: 'c-1', type: 'column', href: '', name: 'Col', format: { type }, ...extra };
+}
+
+describe('columnToProperty', () => {
+ test('dateTime columns get a date-time field', () => {
+ expect(columnToProperty(column({ type: 'dateTime' }))?.type).toBe('DATE_TIME');
+ });
+ test.each([
+ ['text', 'SHORT_TEXT'],
+ ['email', 'SHORT_TEXT'],
+ ['select', 'SHORT_TEXT'],
+ ['number', 'NUMBER'],
+ ['currency', 'NUMBER'],
+ ['date', 'DATE_TIME'],
+ ['time', 'DATE_TIME'],
+ ['checkbox', 'CHECKBOX'],
+ ])('%s → %s', (type, expected) => {
+ expect(columnToProperty(column({ type }))?.type).toBe(expected);
+ });
+ test('calculated and unsupported columns are skipped', () => {
+ expect(columnToProperty(column({ type: 'text', extra: { calculated: true } }))).toBeUndefined();
+ expect(columnToProperty(column({ type: 'button' }))).toBeUndefined();
+ expect(columnToProperty(column({ type: 'person' }))).toBeUndefined();
+ });
+ test('multi-select columns explain comma-separated input', () => {
+ expect(columnToProperty(column({ type: 'select', extra: { format: { type: 'select', isArray: true } } }))?.description).toBe(
+ 'Provide options as comma-separated values.',
+ );
+ });
+});
diff --git a/packages/pieces/community/coda/test/rows.test.ts b/packages/pieces/community/coda/test/rows.test.ts
new file mode 100644
index 00000000000..93df4abf2e4
--- /dev/null
+++ b/packages/pieces/community/coda/test/rows.test.ts
@@ -0,0 +1,179 @@
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { listDocTablesAction } from '../src/lib/actions/ai/list-doc-tables';
+import { getTableByIdAction } from '../src/lib/actions/ai/get-table-by-id';
+import { listColumnsAction } from '../src/lib/actions/list-columns';
+import { listRowsAction } from '../src/lib/actions/list-rows';
+import { getRowByIdAction } from '../src/lib/actions/ai/get-row-by-id';
+import { createRowsAction } from '../src/lib/actions/create-rows';
+import { upsertRowsAction } from '../src/lib/actions/upsert-rows';
+import { updateRowByIdAction } from '../src/lib/actions/ai/update-row-by-id';
+import { deleteRowsAction } from '../src/lib/actions/delete-rows';
+import { pushButtonAction } from '../src/lib/actions/push-button';
+import { run, SeenRequest, stubFetch } from './helpers';
+
+function mutationServer(write: { status?: number; body: unknown }) {
+ return (request: SeenRequest) => (request.path.startsWith('/mutationStatus') ? { body: { completed: true } } : { status: write.status ?? 202, body: write.body });
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+describe('table and column reads', () => {
+ test('list_doc_tables defaults to tables', async () => {
+ const seen = stubFetch(() => ({ body: { items: [] } }));
+ await run(listDocTablesAction)({ docId: 'd' });
+ expect(seen[0].path).toBe('/docs/d/tables');
+ expect(seen[0].query.get('tableTypes')).toBe('table');
+ });
+ test('get_table_by_id encodes a table name', async () => {
+ const seen = stubFetch(() => ({ body: { id: 'grid-1' } }));
+ await run(getTableByIdAction)({ docId: 'd', tableIdOrName: 'Tasks & Bugs' });
+ expect(seen[0].url).toContain('/docs/d/tables/Tasks%20%26%20Bugs');
+ });
+ test('list_columns visible only', async () => {
+ const seen = stubFetch(() => ({ body: { items: [{ id: 'c-1' }] } }));
+ await expect(run(listColumnsAction)({ docId: 'd', tableIdOrName: 't', visibleOnly: true })).resolves.toMatchObject({ items: [{ id: 'c-1' }] });
+ expect(seen[0].path).toBe('/docs/d/tables/t/columns');
+ expect(seen[0].query.get('visibleOnly')).toBe('true');
+ });
+});
+
+describe('list_rows', () => {
+ test('builds the filter query and defaults', async () => {
+ const seen = stubFetch(() => ({ body: { items: [{ id: 'i-1' }], nextPageToken: 'next' } }));
+ const result = await run(listRowsAction)({ docId: 'd', tableIdOrName: 't', filterColumn: 'Status', filterValue: 'Open', limit: 2 });
+ expect(result).toEqual({ items: [{ id: 'i-1' }], nextPageToken: 'next', hasMore: true });
+ expect(Object.fromEntries(seen[0].query)).toEqual({
+ query: '"Status":"Open"',
+ sortBy: 'natural',
+ useColumnNames: 'true',
+ valueFormat: 'simpleWithArrays',
+ limit: '2',
+ });
+ });
+ test('value without column, and column without value, are refused', async () => {
+ const seen = stubFetch(() => ({ body: { items: [] } }));
+ await expect(run(listRowsAction)({ docId: 'd', tableIdOrName: 't', filterValue: 'x' })).rejects.toThrow(/Filter Column/);
+ await expect(run(listRowsAction)({ docId: 'd', tableIdOrName: 't', filterColumn: 'c-1' })).rejects.toThrow(/Filter Value/);
+ expect(seen).toHaveLength(0);
+ });
+ test('limit capped at 500', async () => {
+ await expect(run(listRowsAction)({ docId: 'd', tableIdOrName: 't', limit: 501 })).rejects.toThrow(/between 1 and 500/);
+ });
+ test('column ids can be turned off', async () => {
+ const seen = stubFetch(() => ({ body: { items: [] } }));
+ await run(listRowsAction)({ docId: 'd', tableIdOrName: 't', useColumnNames: false, pageToken: 'tok' });
+ expect(seen[0].query.get('useColumnNames')).toBe('false');
+ expect(seen[0].query.get('pageToken')).toBe('tok');
+ });
+});
+
+describe('get_row_by_id', () => {
+ test('encodes and asks for names', async () => {
+ const seen = stubFetch(() => ({ body: { id: 'i-1' } }));
+ await run(getRowByIdAction)({ docId: 'd', tableIdOrName: 't', rowIdOrName: 'i-1' });
+ expect(seen[0].path).toBe('/docs/d/tables/t/rows/i-1');
+ expect(seen[0].query.get('useColumnNames')).toBe('true');
+ });
+ test('refuses a dot-dot row id', async () => {
+ await expect(run(getRowByIdAction)({ docId: 'd', tableIdOrName: 't', rowIdOrName: '..' })).rejects.toThrow(/not a valid/);
+ });
+});
+
+describe('create_rows', () => {
+ test('posts each row as cells, skipping null, and waits', async () => {
+ const seen = stubFetch(mutationServer({ body: { requestId: 'mutate:c', addedRowIds: ['i-1', 'i-2'] } }));
+ const result = await run(createRowsAction)({
+ docId: 'd',
+ tableIdOrName: 't',
+ rows: [{ Name: 'A', Amount: 5, Notes: null }, { Name: 'B', Done: false }],
+ disableParsing: true,
+ });
+ expect(seen[0].body).toEqual({
+ rows: [
+ { cells: [{ column: 'Name', value: 'A' }, { column: 'Amount', value: 5 }] },
+ { cells: [{ column: 'Name', value: 'B' }, { column: 'Done', value: false }] },
+ ],
+ });
+ expect(seen[0].query.get('disableParsing')).toBe('true');
+ expect(result).toEqual({ addedRowIds: ['i-1', 'i-2'], requestId: 'mutate:c', completed: true, warning: null });
+ });
+ test('accepts a JSON string and a single object', async () => {
+ const seen = stubFetch(mutationServer({ body: { requestId: 'r', addedRowIds: ['i-1'] } }));
+ await run(createRowsAction)({ docId: 'd', tableIdOrName: 't', rows: '{"Name":"A"}' });
+ expect(seen[0].body).toEqual({ rows: [{ cells: [{ column: 'Name', value: 'A' }] }] });
+ });
+ test.each([[[]], [[{}]], [['x']], ['not json'], [Array.from({ length: 501 }, () => ({ a: 1 }))]])('refuses %#', async (rows) => {
+ const seen = stubFetch(() => ({ body: {} }));
+ await expect(run(createRowsAction)({ docId: 'd', tableIdOrName: 't', rows })).rejects.toThrow();
+ expect(seen).toHaveLength(0);
+ });
+});
+
+describe('upsert_rows', () => {
+ test('requires every key column in every row', async () => {
+ const seen = stubFetch(() => ({ body: {} }));
+ await expect(
+ run(upsertRowsAction)({ docId: 'd', tableIdOrName: 't', keyColumns: ['Email'], rows: [{ Email: '[email protected]' }, { Name: 'x', Email: ' ' }] }),
+ ).rejects.toThrow(/Row 2 has no value for key column\(s\) Email/);
+ expect(seen).toHaveLength(0);
+ });
+ test('refuses no key columns', async () => {
+ await expect(run(upsertRowsAction)({ docId: 'd', tableIdOrName: 't', keyColumns: [], rows: [{ a: 1 }] })).rejects.toThrow(/key column/);
+ });
+ test('sends deduped key columns', async () => {
+ const seen = stubFetch(mutationServer({ body: { requestId: 'r' } }));
+ const result = await run(upsertRowsAction)({ docId: 'd', tableIdOrName: 't', keyColumns: ['Email', 'Email'], rows: [{ Email: '[email protected]', Amount: 1 }] });
+ expect(seen[0].body).toEqual({ rows: [{ cells: [{ column: 'Email', value: '[email protected]' }, { column: 'Amount', value: 1 }] }], keyColumns: ['Email'] });
+ expect(result).toEqual({ rowCount: 1, requestId: 'r', completed: true, warning: null });
+ });
+});
+
+describe('update_row_by_id', () => {
+ test('null clears, omitted stays untouched', async () => {
+ const seen = stubFetch(mutationServer({ body: { requestId: 'r', id: 'i-1' } }));
+ const result = await run(updateRowByIdAction)({ docId: 'd', tableIdOrName: 't', rowIdOrName: 'i-1', cells: { Notes: null, Status: 'Closed', Name: '' } });
+ expect(seen[0].method).toBe('PUT');
+ expect(seen[0].body).toEqual({
+ row: { cells: [{ column: 'Notes', value: '' }, { column: 'Status', value: 'Closed' }, { column: 'Name', value: '' }] },
+ });
+ expect(result).toEqual({ id: 'i-1', requestId: 'r', completed: true, warning: null });
+ });
+ test('refuses an empty object', async () => {
+ const seen = stubFetch(() => ({ body: {} }));
+ await expect(run(updateRowByIdAction)({ docId: 'd', tableIdOrName: 't', rowIdOrName: 'i-1', cells: {} })).rejects.toThrow(/at least one column/);
+ await expect(run(updateRowByIdAction)({ docId: 'd', tableIdOrName: 't', rowIdOrName: 'i-1', cells: [1] })).rejects.toThrow(/object/);
+ expect(seen).toHaveLength(0);
+ });
+});
+
+describe('delete_rows', () => {
+ test('dedupes ids and sends a DELETE body', async () => {
+ const seen = stubFetch(mutationServer({ body: { requestId: 'r', rowIds: ['i-1', 'i-2'] } }));
+ const result = await run(deleteRowsAction)({ docId: 'd', tableIdOrName: 't', rowIds: ['i-1', ' i-1 ', 'i-2', ''] });
+ expect(seen[0].method).toBe('DELETE');
+ expect(seen[0].body).toEqual({ rowIds: ['i-1', 'i-2'] });
+ expect(result).toEqual({ rowIds: ['i-1', 'i-2'], requestId: 'r', completed: true, warning: null });
+ });
+ test('refuses an empty list', async () => {
+ const seen = stubFetch(() => ({ body: {} }));
+ await expect(run(deleteRowsAction)({ docId: 'd', tableIdOrName: 't', rowIds: [] })).rejects.toThrow(/at least one row ID/);
+ expect(seen).toHaveLength(0);
+ });
+});
+
+describe('push_button', () => {
+ test('posts to the button path', async () => {
+ const seen = stubFetch(mutationServer({ body: { requestId: 'r', rowId: 'i-1', columnId: 'c-b' } }));
+ const result = await run(pushButtonAction)({ docId: 'd', tableIdOrName: 't', rowIdOrName: 'i-1', columnIdOrName: 'Mark Done' });
+ expect(seen[0].method).toBe('POST');
+ expect(seen[0].url).toContain('/docs/d/tables/t/rows/i-1/buttons/Mark%20Done');
+ expect(result).toEqual({ rowId: 'i-1', columnId: 'c-b', requestId: 'r', completed: true, warning: null });
+ });
+});
diff --git a/packages/pieces/community/coda/test/trigger.test.ts b/packages/pieces/community/coda/test/trigger.test.ts
new file mode 100644
index 00000000000..3d66abaeeee
--- /dev/null
+++ b/packages/pieces/community/coda/test/trigger.test.ts
@@ -0,0 +1,68 @@
+import { Store } from '@activepieces/pieces-framework';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { newRowCreatedTrigger } from '../src/lib/triggers/new-row-created';
+import { codaConnection, idsOf, memoryStore, MemoryStore, runStep, stubFetch } from './helpers';
+
+const trigger: PollingHooks = newRowCreatedTrigger;
+
+function row({ id, createdAt }: { id: string; createdAt: string }) {
+ return { id, createdAt, name: id, values: {} };
+}
+
+function context({ store = memoryStore(), isRepublish = false }: { store?: MemoryStore; isRepublish?: boolean } = {}): HookContext {
+ return { auth: codaConnection(), propsValue: { docId: 'd', tableId: 't' }, store, isRepublish };
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-10-06T12:00:00Z'));
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+describe('new-row-created', () => {
+ test('republish keeps the stored lastPoll', async () => {
+ const store = memoryStore({ lastPoll: 1234 });
+ await runStep(trigger.onEnable(context({ store, isRepublish: true })));
+ expect(store.read('lastPoll')).toBe(1234);
+ });
+ test('first enable sets lastPoll to now', async () => {
+ const store = memoryStore();
+ await runStep(trigger.onEnable(context({ store })));
+ expect(store.read('lastPoll')).toBe(Date.parse('2026-10-06T12:00:00Z'));
+ });
+ test('test returns the newest rows first across pages, 500 per page', async () => {
+ const seen = stubFetch((request) =>
+ request.query.get('pageToken')
+ ? { body: { items: [row({ id: 'r6', createdAt: '2026-01-06T00:00:00Z' }), row({ id: 'r7', createdAt: '2026-01-07T00:00:00Z' })] } }
+ : { body: { items: ['1', '2', '3', '4', '5'].map((n) => row({ id: `r${n}`, createdAt: `2026-01-0${n}T00:00:00Z` })), nextPageToken: 'p2' } },
+ );
+ const result = await runStep(trigger.test(context()));
+ expect(idsOf(result)).toEqual(['r7', 'r6', 'r5', 'r4', 'r3']);
+ expect(seen[0].query.get('limit')).toBe('500');
+ expect(seen[0].query.get('sortBy')).toBe('createdAt');
+ });
+ test('poll emits only rows created after lastPoll and advances it', async () => {
+ const store = memoryStore({ lastPoll: Date.parse('2026-01-03T00:00:00Z') });
+ stubFetch(() => ({ body: { items: [row({ id: 'old', createdAt: '2026-01-02T00:00:00Z' }), row({ id: 'same', createdAt: '2026-01-03T00:00:00Z' }), row({ id: 'new', createdAt: '2026-01-04T00:00:00Z' })] } }));
+ const result = await runStep(trigger.run(context({ store })));
+ expect(idsOf(result)).toEqual(['new']);
+ expect(store.read('lastPoll')).toBe(Date.parse('2026-01-04T00:00:00Z'));
+ });
+});
+
+type HookContext = {
+ auth: ReturnType<typeof codaConnection>;
+ propsValue: { docId: string; tableId: string };
+ store: Store;
+ isRepublish?: boolean;
+};
+
+type PollingHooks = {
+ onEnable(context: HookContext): Promise<unknown>;
+ test(context: HookContext): Promise<unknown>;
+ run(context: HookContext): Promise<unknown>;
+};
diff --git a/packages/pieces/community/coda/vitest.config.ts b/packages/pieces/community/coda/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/coda/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'),
+ },
+ },
+})