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(teable): manage tables, fields and batch records, with AI agent actions and polling triggers (#16319)

Odai Ahmad945ac21284fa
diff --git a/bun.lock b/bun.lock
index 8f529922704..0095c0fcb79 100644
--- a/bun.lock
+++ b/bun.lock
@@ -9031,15 +9031,19 @@
},
"packages/pieces/community/teable": {
"name": "@activepieces/piece-teable",
- "version": "0.2.0",
+ "version": "0.3.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
+ "form-data": "4.0.6",
+ "mime-types": "2.1.35",
},
"devDependencies": {
+ "@types/mime-types": "2.1.1",
"tslib": "^2.3.0",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/teamhood": {
diff --git a/packages/pieces/community/teable/package.json b/packages/pieces/community/teable/package.json
index 36c20b723bc..e5f719ed150 100644
--- a/packages/pieces/community/teable/package.json
+++ b/packages/pieces/community/teable/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/piece-teable",
- "version": "0.2.0",
+ "version": "0.3.0",
"type": "commonjs",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
@@ -8,14 +8,19 @@
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
"@activepieces/core-piece-types": "workspace:*",
- "@activepieces/core-utils": "workspace:*"
+ "@activepieces/core-utils": "workspace:*",
+ "form-data": "4.0.6",
+ "mime-types": "2.1.35"
},
"devDependencies": {
- "tslib": "^2.3.0"
+ "@types/mime-types": "2.1.1",
+ "tslib": "^2.3.0",
+ "vitest": "3.2.6"
},
"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"
}
}
diff --git a/packages/pieces/community/teable/src/i18n/translation.json b/packages/pieces/community/teable/src/i18n/translation.json
index e3c657ded5e..202c5ecd475 100644
--- a/packages/pieces/community/teable/src/i18n/translation.json
+++ b/packages/pieces/community/teable/src/i18n/translation.json
@@ -1,60 +1,148 @@
{
"No-code database built on PostgreSQL": "No-code database built on PostgreSQL",
"Create Record": "Create Record",
+ "Create Records": "Create Records",
"List Records": "List Records",
"Get Record": "Get Record",
"Update Record": "Update Record",
+ "Update Records": "Update Records",
"Delete Record": "Delete Record",
+ "Delete Records": "Delete Records",
"Upload Attachment": "Upload Attachment",
+ "List Bases": "List Bases",
+ "List Tables": "List Tables",
+ "List Fields": "List Fields",
+ "List Views": "List Views",
+ "Create Table": "Create Table",
+ "Create Field": "Create Field",
+ "Add Comment": "Add Comment",
+ "Get Base Schema (Agent)": "Get Base Schema (Agent)",
+ "Create Record (Agent)": "Create Record (Agent)",
+ "Update Record (Agent)": "Update Record (Agent)",
+ "Upsert Record (Agent)": "Upsert Record (Agent)",
+ "Search Records (Agent)": "Search Records (Agent)",
"Custom API Call": "Custom API Call",
"Creates a new record in a Teable table.": "Creates a new record in a Teable table.",
- "Retrieves a list of records from a table with optional filtering, sorting, and pagination.": "Retrieves a list of records from a table with optional filtering, sorting, and pagination.",
+ "Creates multiple records in a Teable table in one call.": "Creates multiple records in a Teable table in one call.",
+ "Retrieves records from a table with optional filtering, search, and sorting, paging through results automatically.": "Retrieves records from a table with optional filtering, search, and sorting, paging through results automatically.",
"Retrieves a single record from a table by its ID.": "Retrieves a single record from a table by its ID.",
"Updates an existing record in a Teable table.": "Updates an existing record in a Teable table.",
+ "Updates multiple records in a Teable table in one call.": "Updates multiple records in a Teable table in one call.",
"Deletes a record from a Teable table by its ID.": "Deletes a record from a Teable table by its ID.",
+ "Permanently deletes multiple records from a Teable table by their IDs.": "Permanently deletes multiple records from a Teable table by their IDs.",
"Uploads a file as an attachment to a field in a Teable record.": "Uploads a file as an attachment to a field in a Teable record.",
+ "Lists all bases the connection has access to.": "Lists all bases the connection has access to.",
+ "Lists all tables in a base.": "Lists all tables in a base.",
+ "Lists all fields of a table.": "Lists all fields of a table.",
+ "Lists all views of a table.": "Lists all views of a table.",
+ "Creates a new table in a base.": "Creates a new table in a base.",
+ "Adds a new field (column) to a table.": "Adds a new field (column) to a table.",
+ "Adds a comment to a record.": "Adds a comment to a record.",
+ "Gets every table and field in a Teable base.": "Gets every table and field in a Teable base.",
+ "Adds a record to a Teable table using field names.": "Adds a record to a Teable table using field names.",
+ "Changes some fields of a Teable record using field names.": "Changes some fields of a Teable record using field names.",
+ "Updates the record whose key field matches, or creates it.": "Updates the record whose key field matches, or creates it.",
+ "Finds records in a Teable table by text or field values.": "Finds records in a Teable table by text or field values.",
"Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",
"Base": "Base",
"Table": "Table",
"Fields": "Fields",
+ "Records": "Records",
+ "View": "View",
"Filter": "Filter",
+ "Search": "Search",
+ "Order By": "Order By",
"Cell Format": "Cell Format",
- "Take": "Take",
+ "Max Records": "Max Records",
"Skip": "Skip",
"Selected Record IDs": "Selected Record IDs",
"Record": "Record",
+ "Fields to Clear": "Fields to Clear",
+ "Record IDs": "Record IDs",
"Attachment Field": "Attachment Field",
"File": "File",
+ "Name": "Name",
+ "Description": "Description",
+ "Type": "Type",
+ "Options": "Options",
+ "Comment": "Comment",
+ "Base ID": "Base ID",
+ "Table (name or ID)": "Table (name or ID)",
+ "Record ID": "Record ID",
+ "Key Field (name or ID)": "Key Field (name or ID)",
+ "Search Text": "Search Text",
+ "Field Filters": "Field Filters",
+ "Limit": "Limit",
"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",
"The table inside the selected base.": "The table inside the selected base.",
- "The fields to add to the record.": "The fields to add to the record.",
+ "The fields to set on the record.": "The fields to set on the record.",
+ "A JSON array of records, each an object keyed by field name.": "A JSON array of records, each an object keyed by field name.",
+ "Only return records visible in this view.": "Only return records visible in this view.",
"A filter expression for the records. Use the visual query builder at https://app.teable.ai/developer/tool/query-builder to build one.": "A filter expression for the records. Use the visual query builder at https://app.teable.ai/developer/tool/query-builder to build one.",
+ "Only return records containing this text in any field.": "Only return records containing this text in any field.",
+ "A JSON array of sort conditions.": "A JSON array of sort conditions.",
"The format of the cell values in the response.": "The format of the cell values in the response.",
- "The record count you want to take, maximum is 1000.": "The record count you want to take, maximum is 1000.",
- "The records count you want to skip.": "The records count you want to skip.",
- "Filter selected records by record ids.": "Filter selected records by record ids.",
- "The record to act on.": "The record to act on.",
+ "The maximum number of records to return (1-5000). The action pages through the table automatically.": "The maximum number of records to return (1-5000). The action pages through the table automatically.",
+ "The number of records to skip before collecting results.": "The number of records to skip before collecting results.",
+ "Only return the records with these IDs.": "Only return the records with these IDs.",
+ "The record to act on. Shows the first 1000 records; pass a record ID directly for larger tables.": "The record to act on. Shows the first 1000 records; pass a record ID directly for larger tables.",
+ "Fields whose value should be removed from the record.": "Fields whose value should be removed from the record.",
+ "A JSON array of updates with record IDs; a null field value clears it.": "A JSON array of updates with record IDs; a null field value clears it.",
+ "The IDs of the records to delete.": "The IDs of the records to delete.",
"The attachment field to upload the file to.": "The attachment field to upload the file to.",
"The file to upload. Accepts a URL or a binary file.": "The file to upload. Accepts a URL or a binary file.",
+ "The name of the new table.": "The name of the new table.",
+ "The name of the new field. Must be unique within the table.": "The name of the new field. Must be unique within the table.",
+ "Type-specific options as JSON. See the Teable field documentation.": "Type-specific options as JSON. See the Teable field documentation.",
+ "The text of the comment.": "The text of the comment.",
+ "The Teable base ID. Get it from List Bases.": "The Teable base ID. Get it from List Bases.",
+ "The table name or table ID. Get both from Get Base Schema (Agent).": "The table name or table ID. Get both from Get Base Schema (Agent).",
+ "A JSON object keyed by field name or field ID, e.g. {\"Name\": \"Jane\", \"Age\": 30, \"Status\": \"Open\"}. Select fields take the option name; link and user fields take names or IDs.": "A JSON object keyed by field name or field ID, e.g. {\"Name\": \"Jane\", \"Age\": 30, \"Status\": \"Open\"}. Select fields take the option name; link and user fields take names or IDs.",
+ "The ID of the record, e.g. from Search Records (Agent).": "The ID of the record, e.g. from Search Records (Agent).",
+ "The field that identifies the record, e.g. Email.": "The field that identifies the record, e.g. Email.",
+ "Exact matches keyed by field name or ID; all conditions must match.": "Exact matches keyed by field name or ID; all conditions must match.",
+ "The maximum number of records to return (1-1000).": "The maximum number of records to return (1-1000).",
"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.",
"JSON": "JSON",
"Text": "Text",
+ "singleLineText": "singleLineText",
+ "longText": "longText",
+ "user": "user",
+ "attachment": "attachment",
+ "checkbox": "checkbox",
+ "multipleSelect": "multipleSelect",
+ "singleSelect": "singleSelect",
+ "date": "date",
+ "number": "number",
+ "rating": "rating",
+ "formula": "formula",
+ "link": "link",
+ "createdTime": "createdTime",
+ "lastModifiedTime": "lastModifiedTime",
+ "createdBy": "createdBy",
+ "lastModifiedBy": "lastModifiedBy",
+ "autoNumber": "autoNumber",
"GET": "GET",
"POST": "POST",
"PATCH": "PATCH",
"PUT": "PUT",
"DELETE": "DELETE",
"HEAD": "HEAD",
- "None": "None",
- "Form Data": "Form Data",
- "Raw": "Raw"
+ "New Record": "New Record",
+ "Updated Record": "Updated Record",
+ "Triggers when a new record is created in a table.": "Triggers when a new record is created in a table.",
+ "Triggers when a record is created or modified. The table must have a \"Last modified time\" field that shows the time.": "Triggers when a record is created or modified. The table must have a \"Last modified time\" field that shows the time."
}
\ No newline at end of file
diff --git a/packages/pieces/community/teable/src/index.ts b/packages/pieces/community/teable/src/index.ts
index 79fce1522d3..179bede1d53 100644
--- a/packages/pieces/community/teable/src/index.ts
+++ b/packages/pieces/community/teable/src/index.ts
@@ -1,18 +1,30 @@
import { createCustomApiCallAction } from '@activepieces/pieces-common';
-import { createPiece } from '@activepieces/pieces-framework';
-import { PieceCategory } from '@activepieces/pieces-framework';
+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';
import { createRecordAction } from './lib/actions/create-record';
+import { createRecordsAction } from './lib/actions/create-records';
import { findRecordsAction } from './lib/actions/find-records';
import { findRecordAction } from './lib/actions/find-record';
import { deleteRecordAction } from './lib/actions/delete-record';
+import { deleteRecordsAction } from './lib/actions/delete-records';
import { updateRecordAction } from './lib/actions/update-record';
+import { updateRecordsAction } from './lib/actions/update-records';
import { uploadAttachmentAction } from './lib/actions/upload-attachment';
-import {
- TeableAuth,
- TeableAuthValue,
- getTeableToken,
- getTeableBaseUrl,
-} from './lib/auth';
+import { listBasesAction } from './lib/actions/list-bases';
+import { listTablesAction } from './lib/actions/list-tables';
+import { listFieldsAction } from './lib/actions/list-fields';
+import { listViewsAction } from './lib/actions/list-views';
+import { createTableAction } from './lib/actions/create-table';
+import { createFieldAction } from './lib/actions/create-field';
+import { addCommentAction } from './lib/actions/add-comment';
+import { getBaseSchemaAi } from './lib/actions/get-base-schema-ai';
+import { createRecordAi } from './lib/actions/create-record-ai';
+import { updateRecordAi } from './lib/actions/update-record-ai';
+import { upsertRecordAi } from './lib/actions/upsert-record-ai';
+import { searchRecordsAi } from './lib/actions/search-records-ai';
+import { newRecordTrigger } from './lib/triggers/new-record';
+import { updatedRecordTrigger } from './lib/triggers/updated-record';
+import { TeableAuth, teableAuthUtil } from './lib/auth';
+import { TEABLE_CLOUD_URL } from './lib/common/constants';
export const teable = createPiece({
displayName: 'Teable',
@@ -24,18 +36,36 @@ export const teable = createPiece({
authors: ['codegino', 'onyedikachi-david'],
actions: [
createRecordAction,
+ createRecordsAction,
findRecordsAction,
findRecordAction,
updateRecordAction,
+ updateRecordsAction,
deleteRecordAction,
+ deleteRecordsAction,
uploadAttachmentAction,
+ listBasesAction,
+ listTablesAction,
+ listFieldsAction,
+ listViewsAction,
+ createTableAction,
+ createFieldAction,
+ addCommentAction,
+ getBaseSchemaAi,
+ createRecordAi,
+ updateRecordAi,
+ upsertRecordAi,
+ searchRecordsAi,
createCustomApiCallAction({
auth: TeableAuth,
- baseUrl: (auth) => `${getTeableBaseUrl(auth as TeableAuthValue)}/api`,
+ baseUrl: (auth) =>
+ auth === undefined
+ ? `${TEABLE_CLOUD_URL}/api`
+ : `${teableAuthUtil.getBaseUrl(auth)}/api`,
authMapping: async (auth) => ({
- Authorization: `Bearer ${getTeableToken(auth as TeableAuthValue)}`,
+ Authorization: `Bearer ${teableAuthUtil.getToken(auth)}`,
}),
}),
],
- triggers: [],
+ triggers: [newRecordTrigger, updatedRecordTrigger],
});
diff --git a/packages/pieces/community/teable/src/lib/actions/add-comment.ts b/packages/pieces/community/teable/src/lib/actions/add-comment.ts
new file mode 100644
index 00000000000..6b526d63877
--- /dev/null
+++ b/packages/pieces/community/teable/src/lib/actions/add-comment.ts
@@ -0,0 +1,44 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { TeableAuth } from '../auth';
+import { TeableCommon } from '../common';
+import { teableClient } from '../common/client';
+import { teableOutputSchemas } from '../output-schemas';
+
+export const addCommentAction = createAction({
+ auth: TeableAuth,
+ name: 'teable_add_comment',
+ classification: 'WRITE',
+ displayName: 'Add Comment',
+ description: 'Adds a comment to a record.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Posts a plain-text comment on a Teable record, identified by its table and record ID. Each call adds another comment, so a retry duplicates it.',
+ idempotent: false,
+ },
+ props: {
+ base_id: TeableCommon.base_id,
+ table_id: TeableCommon.table_id,
+ record_id: TeableCommon.record_id,
+ comment: Property.LongText({
+ displayName: 'Comment',
+ description: 'The text of the comment.',
+ required: true,
+ }),
+ },
+ outputSchema: teableOutputSchemas.addComment,
+ async run(context) {
+ const { table_id, record_id, comment } = context.propsValue;
+ const text = comment.trim();
+ if (text.length === 0) {
+ throw new Error('Comment must not be empty.');
+ }
+ await teableClient.createComment({
+ auth: context.auth,
+ tableId: table_id,
+ recordId: record_id,
+ content: [{ type: 'p', children: [{ type: 'span', value: text }] }],
+ });
+ return { success: true, recordId: record_id, comment: text };
+ },
+});
diff --git a/packages/pieces/community/teable/src/lib/actions/create-field.ts b/packages/pieces/community/teable/src/lib/actions/create-field.ts
new file mode 100644
index 00000000000..84617c5406a
--- /dev/null
+++ b/packages/pieces/community/teable/src/lib/actions/create-field.ts
@@ -0,0 +1,66 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { TeableAuth } from '../auth';
+import { TeableCommon } from '../common';
+import { teableClient } from '../common/client';
+import { TeableCreatableFieldTypes } from '../common/constants';
+import { teableOutputSchemas } from '../output-schemas';
+
+export const createFieldAction = createAction({
+ auth: TeableAuth,
+ name: 'teable_create_field',
+ classification: 'WRITE',
+ displayName: 'Create Field',
+ description: 'Adds a new field (column) to a table.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Adds a new column to a Teable table with the given name and type, and optional type-specific options such as select choices. Each call adds another column; duplicate names fail.',
+ idempotent: false,
+ },
+ props: {
+ base_id: TeableCommon.base_id,
+ table_id: TeableCommon.table_id,
+ name: Property.ShortText({
+ displayName: 'Name',
+ description: 'The name of the new field. Must be unique within the table.',
+ required: true,
+ }),
+ type: Property.StaticDropdown({
+ displayName: 'Type',
+ required: true,
+ options: {
+ options: TeableCreatableFieldTypes.map((type) => ({ label: type, value: type })),
+ },
+ }),
+ description: Property.LongText({
+ displayName: 'Description',
+ required: false,
+ }),
+ options: Property.Json({
+ displayName: 'Options',
+ description:
+ 'Type-specific options as JSON. See the Teable field documentation.',
+ required: false,
+ }),
+ },
+ outputSchema: teableOutputSchemas.createField,
+ async run(context) {
+ const { table_id, name, type, description, options } = context.propsValue;
+ const trimmed = name.trim();
+ if (trimmed.length === 0) {
+ throw new Error('Name must not be empty.');
+ }
+ const hasOptions =
+ typeof options === 'object' && options !== null && Object.keys(options).length > 0;
+ return teableClient.createField({
+ auth: context.auth,
+ tableId: table_id,
+ body: {
+ name: trimmed,
+ type,
+ ...(description !== undefined && description !== '' ? { description } : {}),
+ ...(hasOptions ? { options } : {}),
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/teable/src/lib/actions/create-record-ai.ts b/packages/pieces/community/teable/src/lib/actions/create-record-ai.ts
new file mode 100644
index 00000000000..7ca1bdc69d1
--- /dev/null
+++ b/packages/pieces/community/teable/src/lib/actions/create-record-ai.ts
@@ -0,0 +1,42 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { TeableAuth } from '../auth';
+import { teableAgent } from '../common/agent';
+import { TeableAgentProps } from '../common';
+import { teableClient } from '../common/client';
+import { teableOutputSchemas } from '../output-schemas';
+
+export const createRecordAi = createAction({
+ auth: TeableAuth,
+ name: 'create_record_ai',
+ classification: 'WRITE',
+ displayName: 'Create Record (Agent)',
+ description: 'Adds a record to a Teable table using field names.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Adds one new record to a Teable table. Agents: use this instead of Create Record. Needs the base ID, the table name or ID, and a JSON object of values keyed by field name (case-insensitive) or field ID — see Get Base Schema (Agent). Values are typecast, so select options, links, and users accept names. Returns the new record with values keyed by field name. Each call adds a new record, so a retry makes a duplicate; use Upsert Record (Agent) to avoid that.',
+ idempotent: false,
+ },
+ props: {
+ baseId: TeableAgentProps.base_id,
+ table: TeableAgentProps.table,
+ fields: TeableAgentProps.fields,
+ },
+ outputSchema: teableOutputSchemas.recordCore,
+ async run({ auth, propsValue }) {
+ const baseId = teableAgent.requireText({ value: propsValue.baseId, label: 'Base ID' });
+ const reference = teableAgent.requireText({ value: propsValue.table, label: 'Table' });
+ const input = teableAgent.parseFieldsInput(propsValue.fields);
+ const table = await teableAgent.resolveTable({ auth, baseId, reference });
+ const fields = await teableClient.listFields({ auth, tableId: table.id });
+ const values = teableAgent.buildRecordFields({ fields, input, allowClear: false });
+ const created = await teableClient.createRecords({
+ auth,
+ tableId: table.id,
+ records: [{ fields: values }],
+ fieldKeyType: 'id',
+ typecast: true,
+ });
+ return teableAgent.mapFieldIdsToNames({ fields, record: created.records[0] });
+ },
+});
diff --git a/packages/pieces/community/teable/src/lib/actions/create-record.ts b/packages/pieces/community/teable/src/lib/actions/create-record.ts
index 53e395a9142..0e8dfc996c2 100644
--- a/packages/pieces/community/teable/src/lib/actions/create-record.ts
+++ b/packages/pieces/community/teable/src/lib/actions/create-record.ts
@@ -1,9 +1,8 @@
-import {
- DynamicPropsValue,
- createAction,
-} from '@activepieces/pieces-framework';
-import { TeableCommon, makeClient } from '../common';
-import { TeableAuth, TeableAuthValue } from '../auth';
+import { DynamicPropsValue, createAction } from '@activepieces/pieces-framework';
+import { TeableCommon } from '../common';
+import { teableClient } from '../common/client';
+import { TeableAuth } from '../auth';
+import { teableOutputSchemas } from '../output-schemas';
export const createRecordAction = createAction({
auth: TeableAuth,
@@ -11,9 +10,10 @@ export const createRecordAction = createAction({
classification: 'WRITE',
displayName: 'Create Record',
description: 'Creates a new record in a Teable table.',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
- description: 'Insert a new row into a specific Teable table within a base, populating its field values. Use when an agent needs to add data to a no-code database; requires the target table ID and a fields object keyed by field name. Not idempotent — each call appends another record even with identical input.',
+ description:
+ 'Adds one new row to a Teable table. Each call appends another record, so a retry makes a duplicate.',
idempotent: false,
},
props: {
@@ -21,21 +21,24 @@ export const createRecordAction = createAction({
table_id: TeableCommon.table_id,
fields: TeableCommon.fields,
},
+ outputSchema: teableOutputSchemas.createRecord,
async run(context) {
const { table_id } = context.propsValue;
const dynamicFields: DynamicPropsValue = context.propsValue.fields;
-
const fields: Record<string, unknown> = {};
for (const [key, value] of Object.entries(dynamicFields)) {
if (value !== undefined && value !== null && value !== '') {
fields[key] = value;
}
}
-
- const client = makeClient(context.auth as TeableAuthValue);
- return await client.createRecord(table_id, {
+ if (Object.keys(fields).length === 0) {
+ throw new Error('Fill in at least one field value.');
+ }
+ return teableClient.createRecords({
+ auth: context.auth,
+ tableId: table_id,
records: [{ fields }],
+ typecast: true,
});
},
});
-
diff --git a/packages/pieces/community/teable/src/lib/actions/create-records.ts b/packages/pieces/community/teable/src/lib/actions/create-records.ts
new file mode 100644
index 00000000000..6c2c03fcdf8
--- /dev/null
+++ b/packages/pieces/community/teable/src/lib/actions/create-records.ts
@@ -0,0 +1,66 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { TeableAuth } from '../auth';
+import { TeableCommon } from '../common';
+import { teableClient } from '../common/client';
+import { teableOutputSchemas } from '../output-schemas';
+
+const MAX_BATCH_SIZE = 1000;
+
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function parseRecordsInput(value: unknown): { fields: Record<string, unknown> }[] {
+ if (!Array.isArray(value) || value.length === 0) {
+ throw new Error(
+ 'Records must be a non-empty JSON array of objects keyed by field name, e.g. [{"Name": "Jane"}, {"Name": "Joe"}].'
+ );
+ }
+ if (value.length > MAX_BATCH_SIZE) {
+ throw new Error(`Records holds ${value.length} items; the maximum per call is ${MAX_BATCH_SIZE}.`);
+ }
+ return value.map((item, index) => {
+ if (!isPlainObject(item)) {
+ throw new Error(`Records item ${index + 1} must be an object keyed by field name.`);
+ }
+ const entries = Object.entries(item).filter(([, v]) => v !== undefined && v !== null && v !== '');
+ if (entries.length === 0) {
+ throw new Error(`Records item ${index + 1} has no field values.`);
+ }
+ return { fields: Object.fromEntries(entries) };
+ });
+}
+
+export const createRecordsAction = createAction({
+ auth: TeableAuth,
+ name: 'teable_create_records',
+ classification: 'WRITE',
+ displayName: 'Create Records',
+ description: 'Creates multiple records in a Teable table in one call.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Adds up to 1000 new rows to a Teable table in one call. Records is a JSON array of objects keyed by field name. Each call appends all records again, so a retry makes duplicates.',
+ idempotent: false,
+ },
+ props: {
+ base_id: TeableCommon.base_id,
+ table_id: TeableCommon.table_id,
+ records: Property.Json({
+ displayName: 'Records',
+ description:
+ 'A JSON array of records, each an object keyed by field name.',
+ required: true,
+ }),
+ },
+ outputSchema: teableOutputSchemas.createRecord,
+ async run(context) {
+ const records = parseRecordsInput(context.propsValue.records);
+ return teableClient.createRecords({
+ auth: context.auth,
+ tableId: context.propsValue.table_id,
+ records,
+ typecast: true,
+ });
+ },
+});
diff --git a/packages/pieces/community/teable/src/lib/actions/create-table.ts b/packages/pieces/community/teable/src/lib/actions/create-table.ts
new file mode 100644
index 00000000000..245b4b7ce1a
--- /dev/null
+++ b/packages/pieces/community/teable/src/lib/actions/create-table.ts
@@ -0,0 +1,47 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { TeableAuth } from '../auth';
+import { TeableCommon } from '../common';
+import { teableClient } from '../common/client';
+import { teableOutputSchemas } from '../output-schemas';
+
+export const createTableAction = createAction({
+ auth: TeableAuth,
+ name: 'teable_create_table',
+ classification: 'WRITE',
+ displayName: 'Create Table',
+ description: 'Creates a new table in a base.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Creates a new table in a Teable base with a default grid view and default fields, and returns the table with its field IDs. Each call creates another table, so a retry makes a duplicate.',
+ idempotent: false,
+ },
+ props: {
+ base_id: TeableCommon.base_id,
+ name: Property.ShortText({
+ displayName: 'Name',
+ description: 'The name of the new table.',
+ required: true,
+ }),
+ description: Property.LongText({
+ displayName: 'Description',
+ required: false,
+ }),
+ },
+ outputSchema: teableOutputSchemas.createTable,
+ async run(context) {
+ const { base_id, name, description } = context.propsValue;
+ const trimmed = name.trim();
+ if (trimmed.length === 0) {
+ throw new Error('Name must not be empty.');
+ }
+ return teableClient.createTable({
+ auth: context.auth,
+ baseId: base_id,
+ body: {
+ name: trimmed,
+ ...(description !== undefined && description !== '' ? { description } : {}),
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/teable/src/lib/actions/delete-record.ts b/packages/pieces/community/teable/src/lib/actions/delete-record.ts
index 651895e1936..3609d95f5cc 100644
--- a/packages/pieces/community/teable/src/lib/actions/delete-record.ts
+++ b/packages/pieces/community/teable/src/lib/actions/delete-record.ts
@@ -1,6 +1,8 @@
import { createAction } from '@activepieces/pieces-framework';
-import { TeableCommon, makeClient } from '../common';
-import { TeableAuth, TeableAuthValue } from '../auth';
+import { TeableCommon } from '../common';
+import { teableClient } from '../common/client';
+import { TeableAuth } from '../auth';
+import { teableOutputSchemas } from '../output-schemas';
export const deleteRecordAction = createAction({
auth: TeableAuth,
@@ -10,7 +12,8 @@ export const deleteRecordAction = createAction({
description: 'Deletes a record from a Teable table by its ID.',
audience: 'both',
aiMetadata: {
- description: 'Permanently removes a single record from a Teable table by its record ID. Use when the agent must delete a known row. Effectively idempotent on the end state (the record stays gone), though a repeat call on an already-deleted ID may error.',
+ description:
+ 'Permanently removes one record from a Teable table by its record ID. Deleting the same ID again still succeeds and the record stays gone, so a retry is safe.',
idempotent: true,
},
props: {
@@ -18,9 +21,14 @@ export const deleteRecordAction = createAction({
table_id: TeableCommon.table_id,
record_id: TeableCommon.record_id,
},
+ outputSchema: teableOutputSchemas.deleteRecord,
async run(context) {
const { table_id, record_id } = context.propsValue;
- const client = makeClient(context.auth as TeableAuthValue);
- return await client.deleteRecord(table_id, record_id);
+ await teableClient.deleteRecord({
+ auth: context.auth,
+ tableId: table_id,
+ recordId: record_id,
+ });
+ return { success: true, recordId: record_id };
},
});
diff --git a/packages/pieces/community/teable/src/lib/actions/delete-records.ts b/packages/pieces/community/teable/src/lib/actions/delete-records.ts
new file mode 100644
index 00000000000..03ee95222a9
--- /dev/null
+++ b/packages/pieces/community/teable/src/lib/actions/delete-records.ts
@@ -0,0 +1,50 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { TeableAuth } from '../auth';
+import { TeableCommon } from '../common';
+import { teableClient } from '../common/client';
+import { teableOutputSchemas } from '../output-schemas';
+
+const MAX_BATCH_SIZE = 1000;
+
+export const deleteRecordsAction = createAction({
+ auth: TeableAuth,
+ name: 'teable_delete_records',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Records',
+ description: 'Permanently deletes multiple records from a Teable table by their IDs.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Permanently removes up to 1000 records from a Teable table in one call, by their record IDs. Refuses an empty ID list. Deleting the same IDs again still succeeds, so a retry is safe.',
+ idempotent: true,
+ },
+ props: {
+ base_id: TeableCommon.base_id,
+ table_id: TeableCommon.table_id,
+ recordIds: Property.Array({
+ displayName: 'Record IDs',
+ description: 'The IDs of the records to delete.',
+ required: true,
+ }),
+ },
+ outputSchema: teableOutputSchemas.deleteRecords,
+ async run(context) {
+ const recordIds = (context.propsValue.recordIds ?? [])
+ .map((id) => String(id).trim())
+ .filter((id) => id.length > 0);
+ if (recordIds.length === 0) {
+ throw new Error('Record IDs must contain at least one record ID.');
+ }
+ if (recordIds.length > MAX_BATCH_SIZE) {
+ throw new Error(
+ `Record IDs holds ${recordIds.length} items; the maximum per call is ${MAX_BATCH_SIZE}.`
+ );
+ }
+ await teableClient.deleteRecords({
+ auth: context.auth,
+ tableId: context.propsValue.table_id,
+ recordIds,
+ });
+ return { success: true, deletedCount: recordIds.length, recordIds };
+ },
+});
diff --git a/packages/pieces/community/teable/src/lib/actions/find-record.ts b/packages/pieces/community/teable/src/lib/actions/find-record.ts
index 23af47a3faf..2b878bc3b0a 100644
--- a/packages/pieces/community/teable/src/lib/actions/find-record.ts
+++ b/packages/pieces/community/teable/src/lib/actions/find-record.ts
@@ -1,10 +1,8 @@
-import {
- Property,
- createAction,
-} from '@activepieces/pieces-framework';
-import { TeableCommon, makeClient } from '../common';
-import { TeableAuth, TeableAuthValue } from '../auth';
-import { prepareQuery } from '../common/client';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { TeableCommon } from '../common';
+import { teableClient } from '../common/client';
+import { TeableAuth } from '../auth';
+import { teableOutputSchemas } from '../output-schemas';
export const findRecordAction = createAction({
auth: TeableAuth,
@@ -14,7 +12,8 @@ export const findRecordAction = createAction({
description: 'Retrieves a single record from a table by its ID.',
audience: 'both',
aiMetadata: {
- description: 'Fetches one record from a Teable table by its exact record ID. Use when the agent already knows the record ID and needs its current field values; for lookups by field value use List Records with a filter instead. Read-only and idempotent.',
+ description:
+ 'Fetches one record by its exact record ID and returns its current field values. For lookups by value use Search Records (Agent). Read-only and safe to retry.',
idempotent: true,
},
props: {
@@ -34,9 +33,14 @@ export const findRecordAction = createAction({
},
}),
},
+ outputSchema: teableOutputSchemas.record,
async run(context) {
const { table_id, record_id, cellFormat } = context.propsValue;
- const client = makeClient(context.auth as TeableAuthValue);
- return await client.getRecord(table_id, record_id, prepareQuery({ cellFormat }));
+ return teableClient.getRecord({
+ auth: context.auth,
+ tableId: table_id,
+ recordId: record_id,
+ query: { cellFormat },
+ });
},
});
diff --git a/packages/pieces/community/teable/src/lib/actions/find-records.ts b/packages/pieces/community/teable/src/lib/actions/find-records.ts
index 9eb21485f4f..70ed769a931 100644
--- a/packages/pieces/community/teable/src/lib/actions/find-records.ts
+++ b/packages/pieces/community/teable/src/lib/actions/find-records.ts
@@ -1,31 +1,45 @@
-import {
- Property,
- createAction,
-} from '@activepieces/pieces-framework';
-import { TeableCommon, makeClient } from '../common';
-import { TeableAuth, TeableAuthValue } from '../auth';
-import { prepareQuery } from '../common/client';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { TeableCommon } from '../common';
+import { teableClient } from '../common/client';
+import { TeableAuth } from '../auth';
+import { teableOutputSchemas } from '../output-schemas';
+
+const MAX_TOTAL_RECORDS = 5000;
export const findRecordsAction = createAction({
auth: TeableAuth,
name: 'teable_list_records',
classification: 'SEARCH',
displayName: 'List Records',
- description: 'Retrieves a list of records from a table with optional filtering, sorting, and pagination.',
- audience: 'both',
+ description:
+ 'Retrieves records from a table with optional filtering, search, and sorting, paging through results automatically.',
+ audience: 'human',
aiMetadata: {
- description: 'Retrieves a list of records from a Teable table, returning all rows when no filter is supplied or only matching rows when a filter expression or specific record IDs are given. Supports pagination via take/skip. Use to query or scan a table; read-only and idempotent. Requires the table ID.',
+ description:
+ 'Lists records from a Teable table, optionally narrowed by a filter expression, a view, or a search term. Read-only and safe to retry.',
idempotent: true,
},
props: {
base_id: TeableCommon.base_id,
table_id: TeableCommon.table_id,
+ view_id: TeableCommon.view_id,
filter: Property.LongText({
displayName: 'Filter',
description:
'A filter expression for the records. Use the visual query builder at https://app.teable.ai/developer/tool/query-builder to build one.',
required: false,
}),
+ search: Property.ShortText({
+ displayName: 'Search',
+ description: 'Only return records containing this text in any field.',
+ required: false,
+ }),
+ orderBy: Property.LongText({
+ displayName: 'Order By',
+ description:
+ 'A JSON array of sort conditions.',
+ required: false,
+ }),
cellFormat: Property.StaticDropdown({
displayName: 'Cell Format',
description: 'The format of the cell values in the response.',
@@ -39,38 +53,59 @@ export const findRecordsAction = createAction({
},
}),
take: Property.Number({
- displayName: 'Take',
- description: 'The record count you want to take, maximum is 1000.',
+ displayName: 'Max Records',
+ description: `The maximum number of records to return (1-${MAX_TOTAL_RECORDS}). The action pages through the table automatically.`,
required: false,
defaultValue: 100,
}),
skip: Property.Number({
displayName: 'Skip',
- description: 'The records count you want to skip.',
+ description: 'The number of records to skip before collecting results.',
required: false,
defaultValue: 0,
}),
selectedRecordIds: Property.Array({
displayName: 'Selected Record IDs',
- description: 'Filter selected records by record ids.',
+ description: 'Only return the records with these IDs.',
required: false,
}),
},
+ outputSchema: teableOutputSchemas.listRecords,
async run(context) {
- const { table_id, filter, cellFormat, take, skip, selectedRecordIds } = context.propsValue;
-
- const client = makeClient(context.auth as TeableAuthValue);
-
- return await client.listRecords(
+ const {
table_id,
- prepareQuery({
+ view_id,
+ filter,
+ search,
+ orderBy,
+ cellFormat,
+ take,
+ skip,
+ selectedRecordIds,
+ } = context.propsValue;
+ const limit = Number(take ?? 100);
+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_TOTAL_RECORDS) {
+ throw new Error(`Max Records must be a whole number between 1 and ${MAX_TOTAL_RECORDS}.`);
+ }
+ const offset = Number(skip ?? 0);
+ if (!Number.isInteger(offset) || offset < 0) {
+ throw new Error('Skip must be a whole number of 0 or more.');
+ }
+ const recordIds = (selectedRecordIds ?? []).map((id) => String(id));
+ const { records, hasMore } = await teableClient.listRecordsPaged({
+ auth: context.auth,
+ tableId: table_id,
+ maxRecords: limit,
+ skip: offset,
+ query: {
+ viewId: view_id,
filter,
+ search: search !== undefined && search !== '' ? [search, '', 'true'] : undefined,
+ orderBy,
cellFormat,
- take,
- skip,
- selectedRecordIds,
- })
- );
+ selectedRecordIds: recordIds.length > 0 ? recordIds : undefined,
+ },
+ });
+ return { records, recordCount: records.length, hasMore };
},
});
-
diff --git a/packages/pieces/community/teable/src/lib/actions/get-base-schema-ai.ts b/packages/pieces/community/teable/src/lib/actions/get-base-schema-ai.ts
new file mode 100644
index 00000000000..e345ff9d84a
--- /dev/null
+++ b/packages/pieces/community/teable/src/lib/actions/get-base-schema-ai.ts
@@ -0,0 +1,51 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { TeableAuth } from '../auth';
+import { teableAgent } from '../common/agent';
+import { TeableAgentProps, teableProps } from '../common';
+import { teableClient } from '../common/client';
+import { teableOutputSchemas } from '../output-schemas';
+
+export const getBaseSchemaAi = createAction({
+ auth: TeableAuth,
+ name: 'get_base_schema_ai',
+ classification: 'READ',
+ displayName: 'Get Base Schema (Agent)',
+ description: 'Gets every table and field in a Teable base.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns every table in a Teable base with all its fields: field ID, name, type, primary/computed flags, and select options. Call this first, before you create, update, or search records. Needs the base ID from List Bases. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ baseId: TeableAgentProps.base_id,
+ },
+ outputSchema: teableOutputSchemas.baseSchema,
+ async run({ auth, propsValue }) {
+ const baseId = teableAgent.requireText({ value: propsValue.baseId, label: 'Base ID' });
+ const tables = await teableClient.listTables({ auth, baseId });
+ const tablesWithFields = [];
+ for (const table of tables) {
+ const fields = await teableClient.listFields({ auth, tableId: table.id });
+ tablesWithFields.push({
+ id: table.id,
+ name: table.name,
+ description: table.description ?? null,
+ fields: fields.map((field) => ({
+ id: field.id,
+ name: field.name,
+ type: field.type,
+ isPrimary: field.isPrimary ?? false,
+ writable: teableProps.isRecordWritableField(field),
+ notNull: field.notNull ?? false,
+ unique: field.unique ?? false,
+ options: (field.options?.choices ?? []).map((choice) => ({
+ id: choice.id,
+ name: choice.name,
+ })),
+ })),
+ });
+ }
+ return { baseId, tableCount: tablesWithFields.length, tables: tablesWithFields };
+ },
+});
diff --git a/packages/pieces/community/teable/src/lib/actions/list-bases.ts b/packages/pieces/community/teable/src/lib/actions/list-bases.ts
new file mode 100644
index 00000000000..d4e480a3fc8
--- /dev/null
+++ b/packages/pieces/community/teable/src/lib/actions/list-bases.ts
@@ -0,0 +1,23 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { TeableAuth } from '../auth';
+import { teableClient } from '../common/client';
+import { teableOutputSchemas } from '../output-schemas';
+
+export const listBasesAction = createAction({
+ auth: TeableAuth,
+ name: 'teable_list_bases',
+ classification: 'READ',
+ displayName: 'List Bases',
+ description: 'Lists all bases the connection has access to.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Returns every Teable base this connection can access, with its ID, name, space ID, and role. Call this first to find the base ID the other actions need. Read-only.',
+ idempotent: true,
+ },
+ props: {},
+ outputSchema: teableOutputSchemas.listBases,
+ async run(context) {
+ return teableClient.listBases({ auth: context.auth });
+ },
+});
diff --git a/packages/pieces/community/teable/src/lib/actions/list-fields.ts b/packages/pieces/community/teable/src/lib/actions/list-fields.ts
new file mode 100644
index 00000000000..a6904ca8e92
--- /dev/null
+++ b/packages/pieces/community/teable/src/lib/actions/list-fields.ts
@@ -0,0 +1,27 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { TeableAuth } from '../auth';
+import { TeableCommon } from '../common';
+import { teableClient } from '../common/client';
+import { teableOutputSchemas } from '../output-schemas';
+
+export const listFieldsAction = createAction({
+ auth: TeableAuth,
+ name: 'teable_list_fields',
+ classification: 'READ',
+ displayName: 'List Fields',
+ description: 'Lists all fields of a table.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Returns every field of a Teable table, with its ID, name, type, and select options. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ base_id: TeableCommon.base_id,
+ table_id: TeableCommon.table_id,
+ },
+ outputSchema: teableOutputSchemas.listFields,
+ async run(context) {
+ return teableClient.listFields({ auth: context.auth, tableId: context.propsValue.table_id });
+ },
+});
diff --git a/packages/pieces/community/teable/src/lib/actions/list-tables.ts b/packages/pieces/community/teable/src/lib/actions/list-tables.ts
new file mode 100644
index 00000000000..d3f51db956d
--- /dev/null
+++ b/packages/pieces/community/teable/src/lib/actions/list-tables.ts
@@ -0,0 +1,26 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { TeableAuth } from '../auth';
+import { TeableCommon } from '../common';
+import { teableClient } from '../common/client';
+import { teableOutputSchemas } from '../output-schemas';
+
+export const listTablesAction = createAction({
+ auth: TeableAuth,
+ name: 'teable_list_tables',
+ classification: 'READ',
+ displayName: 'List Tables',
+ description: 'Lists all tables in a base.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Returns every table in a Teable base, with its ID, name, and description. Needs the base ID from List Bases. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ base_id: TeableCommon.base_id,
+ },
+ outputSchema: teableOutputSchemas.listTables,
+ async run(context) {
+ return teableClient.listTables({ auth: context.auth, baseId: context.propsValue.base_id });
+ },
+});
diff --git a/packages/pieces/community/teable/src/lib/actions/list-views.ts b/packages/pieces/community/teable/src/lib/actions/list-views.ts
new file mode 100644
index 00000000000..b7183177ec0
--- /dev/null
+++ b/packages/pieces/community/teable/src/lib/actions/list-views.ts
@@ -0,0 +1,27 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { TeableAuth } from '../auth';
+import { TeableCommon } from '../common';
+import { teableClient } from '../common/client';
+import { teableOutputSchemas } from '../output-schemas';
+
+export const listViewsAction = createAction({
+ auth: TeableAuth,
+ name: 'teable_list_views',
+ classification: 'READ',
+ displayName: 'List Views',
+ description: 'Lists all views of a table.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Returns every view of a Teable table, with its ID, name, and type (grid, kanban, calendar, form, gallery). Use a view ID to scope List Records. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ base_id: TeableCommon.base_id,
+ table_id: TeableCommon.table_id,
+ },
+ outputSchema: teableOutputSchemas.listViews,
+ async run(context) {
+ return teableClient.listViews({ auth: context.auth, tableId: context.propsValue.table_id });
+ },
+});
diff --git a/packages/pieces/community/teable/src/lib/actions/search-records-ai.ts b/packages/pieces/community/teable/src/lib/actions/search-records-ai.ts
new file mode 100644
index 00000000000..cf8dc46f3bf
--- /dev/null
+++ b/packages/pieces/community/teable/src/lib/actions/search-records-ai.ts
@@ -0,0 +1,84 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { TeableAuth } from '../auth';
+import { teableAgent } from '../common/agent';
+import { TeableAgentProps } from '../common';
+import { teableClient } from '../common/client';
+import { teableOutputSchemas } from '../output-schemas';
+
+const MAX_LIMIT = 1000;
+
+export const searchRecordsAi = createAction({
+ auth: TeableAuth,
+ name: 'search_records_ai',
+ classification: 'SEARCH',
+ displayName: 'Search Records (Agent)',
+ description: 'Finds records in a Teable table by text or field values.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Finds records in a Teable table. Give a search text (matched against all fields), a JSON object of exact field values ({"Status": "Open"}), or both; with neither it lists the first records. Agents: use this instead of List Records. Needs the base ID and the table name or ID. Returns {records, recordCount, hasMore} with field values keyed by field name. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ baseId: TeableAgentProps.base_id,
+ table: TeableAgentProps.table,
+ search: Property.ShortText({
+ displayName: 'Search Text',
+ description: 'Only return records containing this text in any field.',
+ required: false,
+ }),
+ filters: Property.Json({
+ displayName: 'Field Filters',
+ description:
+ 'Exact matches keyed by field name or ID; all conditions must match.',
+ required: false,
+ }),
+ limit: Property.Number({
+ displayName: 'Limit',
+ description: `The maximum number of records to return (1-${MAX_LIMIT}).`,
+ required: false,
+ defaultValue: 50,
+ }),
+ },
+ outputSchema: teableOutputSchemas.searchRecords,
+ async run({ auth, propsValue }) {
+ const baseId = teableAgent.requireText({ value: propsValue.baseId, label: 'Base ID' });
+ const reference = teableAgent.requireText({ value: propsValue.table, label: 'Table' });
+ const limit = Number(propsValue.limit ?? 50);
+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {
+ throw new Error(`Limit must be a whole number between 1 and ${MAX_LIMIT}.`);
+ }
+ const table = await teableAgent.resolveTable({ auth, baseId, reference });
+ const fields = await teableClient.listFields({ auth, tableId: table.id });
+ const searchText =
+ typeof propsValue.search === 'string' && propsValue.search.trim().length > 0
+ ? propsValue.search.trim()
+ : undefined;
+ const filterInput =
+ propsValue.filters === undefined || propsValue.filters === null
+ ? {}
+ : teableAgent.parseFieldsInput(propsValue.filters);
+ const filterSet = Object.entries(filterInput).map(([key, value]) => {
+ const field = teableAgent.findColumn({ fields, reference: key });
+ if (value === undefined || value === null || typeof value === 'object') {
+ throw new Error(
+ `Field Filters value for "${field.name}" must be a single text, number, or boolean value.`
+ );
+ }
+ return { fieldId: field.id, operator: 'is', value };
+ });
+ const { records, hasMore } = await teableClient.listRecordsPaged({
+ auth,
+ tableId: table.id,
+ maxRecords: limit,
+ query: {
+ search: searchText !== undefined ? [searchText, '', 'true'] : undefined,
+ filter:
+ filterSet.length > 0
+ ? JSON.stringify({ conjunction: 'and', filterSet })
+ : undefined,
+ },
+ });
+ return { records, recordCount: records.length, hasMore };
+ },
+});
diff --git a/packages/pieces/community/teable/src/lib/actions/update-record-ai.ts b/packages/pieces/community/teable/src/lib/actions/update-record-ai.ts
new file mode 100644
index 00000000000..5a231083b88
--- /dev/null
+++ b/packages/pieces/community/teable/src/lib/actions/update-record-ai.ts
@@ -0,0 +1,45 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { TeableAuth } from '../auth';
+import { teableAgent } from '../common/agent';
+import { TeableAgentProps } from '../common';
+import { teableClient } from '../common/client';
+import { teableOutputSchemas } from '../output-schemas';
+
+export const updateRecordAi = createAction({
+ auth: TeableAuth,
+ name: 'update_record_ai',
+ classification: 'WRITE',
+ displayName: 'Update Record (Agent)',
+ description: 'Changes some fields of a Teable record using field names.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Changes the given fields of one existing Teable record; other fields stay as they are, and a value of null clears a field. Agents: use this instead of Update Record. Needs the base ID, the table name or ID, the record ID, and a JSON object of new values keyed by field name (case-insensitive) or field ID. Returns the updated record with values keyed by field name. Safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ baseId: TeableAgentProps.base_id,
+ table: TeableAgentProps.table,
+ recordId: TeableAgentProps.record_id,
+ fields: TeableAgentProps.fields,
+ },
+ outputSchema: teableOutputSchemas.recordCore,
+ async run({ auth, propsValue }) {
+ const baseId = teableAgent.requireText({ value: propsValue.baseId, label: 'Base ID' });
+ const reference = teableAgent.requireText({ value: propsValue.table, label: 'Table' });
+ const recordId = teableAgent.requireText({ value: propsValue.recordId, label: 'Record ID' });
+ const input = teableAgent.parseFieldsInput(propsValue.fields);
+ const table = await teableAgent.resolveTable({ auth, baseId, reference });
+ const fields = await teableClient.listFields({ auth, tableId: table.id });
+ const values = teableAgent.buildRecordFields({ fields, input, allowClear: true });
+ const updated = await teableClient.updateRecord({
+ auth,
+ tableId: table.id,
+ recordId,
+ fields: values,
+ fieldKeyType: 'id',
+ typecast: true,
+ });
+ return teableAgent.mapFieldIdsToNames({ fields, record: updated });
+ },
+});
diff --git a/packages/pieces/community/teable/src/lib/actions/update-record.ts b/packages/pieces/community/teable/src/lib/actions/update-record.ts
index bac507d61f9..7ef6128f154 100644
--- a/packages/pieces/community/teable/src/lib/actions/update-record.ts
+++ b/packages/pieces/community/teable/src/lib/actions/update-record.ts
@@ -1,39 +1,51 @@
-import {
- DynamicPropsValue,
- createAction,
-} from '@activepieces/pieces-framework';
-import { TeableCommon, makeClient } from '../common';
-import { TeableAuth, TeableAuthValue } from '../auth';
+import { DynamicPropsValue, createAction } from '@activepieces/pieces-framework';
+import { TeableCommon } from '../common';
+import { teableClient } from '../common/client';
+import { TeableAuth } from '../auth';
+import { teableOutputSchemas } from '../output-schemas';
export const updateRecordAction = createAction({
- auth: TeableAuth,
- name: 'teable_update_record',
- classification: 'WRITE',
- displayName: 'Update Record',
- description: 'Updates an existing record in a Teable table.',
- audience: 'both',
- aiMetadata: {
- description: 'Updates the field values of an existing record in a Teable table, identified by its record ID. Use to modify a known row; only the supplied non-empty fields are sent. Idempotent — re-applying the same field values to the same record yields the same state.',
- idempotent: true,
- },
- props: {
- base_id: TeableCommon.base_id,
- table_id: TeableCommon.table_id,
- record_id: TeableCommon.record_id,
- fields: TeableCommon.fields,
- },
- async run(context) {
- const { table_id, record_id } = context.propsValue;
- const dynamicFields: DynamicPropsValue = context.propsValue.fields;
-
- const fields: Record<string, unknown> = {};
- for (const [key, value] of Object.entries(dynamicFields)) {
- if (value !== undefined && value !== null && value !== '') {
- fields[key] = value;
- }
- }
-
- const client = makeClient(context.auth as TeableAuthValue);
- return await client.updateRecord(table_id, record_id, { record: { fields } });
- },
+ auth: TeableAuth,
+ name: 'teable_update_record',
+ classification: 'WRITE',
+ displayName: 'Update Record',
+ description: 'Updates an existing record in a Teable table.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Changes the given fields of one existing record; other fields keep their values, and Fields to Clear are emptied. Safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ base_id: TeableCommon.base_id,
+ table_id: TeableCommon.table_id,
+ record_id: TeableCommon.record_id,
+ fields: TeableCommon.fields,
+ fields_to_clear: TeableCommon.fields_to_clear,
+ },
+ async run(context) {
+ const { table_id, record_id } = context.propsValue;
+ const dynamicFields: DynamicPropsValue = context.propsValue.fields;
+ const fieldsToClear = context.propsValue.fields_to_clear ?? [];
+ const fields: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(dynamicFields)) {
+ if (value !== undefined && value !== null && value !== '') {
+ fields[key] = value;
+ }
+ }
+ for (const name of fieldsToClear) {
+ fields[name] = null;
+ }
+ if (Object.keys(fields).length === 0) {
+ throw new Error('Set at least one field value or pick a field to clear.');
+ }
+ return teableClient.updateRecord({
+ auth: context.auth,
+ tableId: table_id,
+ recordId: record_id,
+ fields,
+ typecast: true,
+ });
+ },
+ outputSchema: teableOutputSchemas.recordCore,
});
diff --git a/packages/pieces/community/teable/src/lib/actions/update-records.ts b/packages/pieces/community/teable/src/lib/actions/update-records.ts
new file mode 100644
index 00000000000..ba070723fce
--- /dev/null
+++ b/packages/pieces/community/teable/src/lib/actions/update-records.ts
@@ -0,0 +1,75 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { TeableAuth } from '../auth';
+import { TeableCommon } from '../common';
+import { teableClient } from '../common/client';
+import { teableOutputSchemas } from '../output-schemas';
+
+const MAX_BATCH_SIZE = 1000;
+
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function parseUpdatesInput(value: unknown): { id: string; fields: Record<string, unknown> }[] {
+ if (!Array.isArray(value) || value.length === 0) {
+ throw new Error(
+ 'Records must be a non-empty JSON array of objects with "id" and "fields", e.g. [{"id": "recXXX", "fields": {"Name": "Jane"}}].'
+ );
+ }
+ if (value.length > MAX_BATCH_SIZE) {
+ throw new Error(`Records holds ${value.length} items; the maximum per call is ${MAX_BATCH_SIZE}.`);
+ }
+ return value.map((item, index) => {
+ if (!isPlainObject(item)) {
+ throw new Error(`Records item ${index + 1} must be an object with "id" and "fields".`);
+ }
+ const id = item['id'];
+ const fields = item['fields'];
+ if (typeof id !== 'string' || id.trim().length === 0) {
+ throw new Error(`Records item ${index + 1} is missing a record "id".`);
+ }
+ if (!isPlainObject(fields) || Object.keys(fields).length === 0) {
+ throw new Error(
+ `Records item ${index + 1} must carry a non-empty "fields" object (use null as a value to clear a field).`
+ );
+ }
+ return {
+ id: id.trim(),
+ fields: Object.fromEntries(Object.entries(fields).filter(([, v]) => v !== undefined)),
+ };
+ });
+}
+
+export const updateRecordsAction = createAction({
+ auth: TeableAuth,
+ name: 'teable_update_records',
+ classification: 'WRITE',
+ displayName: 'Update Records',
+ description: 'Updates multiple records in a Teable table in one call.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Changes up to 1000 existing rows in one call. Records is a JSON array of {"id", "fields"} objects; a field value of null clears that field. Safe to retry with the same values.',
+ idempotent: true,
+ },
+ props: {
+ base_id: TeableCommon.base_id,
+ table_id: TeableCommon.table_id,
+ records: Property.Json({
+ displayName: 'Records',
+ description:
+ 'A JSON array of updates with record IDs; a null field value clears it.',
+ required: true,
+ }),
+ },
+ outputSchema: teableOutputSchemas.updatedRecords,
+ async run(context) {
+ const records = parseUpdatesInput(context.propsValue.records);
+ return teableClient.updateRecords({
+ auth: context.auth,
+ tableId: context.propsValue.table_id,
+ records,
+ typecast: true,
+ });
+ },
+});
diff --git a/packages/pieces/community/teable/src/lib/actions/upload-attachment.ts b/packages/pieces/community/teable/src/lib/actions/upload-attachment.ts
index d4aa76580ba..19386613388 100644
--- a/packages/pieces/community/teable/src/lib/actions/upload-attachment.ts
+++ b/packages/pieces/community/teable/src/lib/actions/upload-attachment.ts
@@ -1,6 +1,8 @@
-import { ApFile, createAction, Property } from '@activepieces/pieces-framework';
-import { TeableAuth, TeableAuthValue } from '../auth';
-import { makeClient, TeableCommon } from '../common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { TeableAuth } from '../auth';
+import { TeableCommon } from '../common';
+import { teableClient } from '../common/client';
+import { teableOutputSchemas } from '../output-schemas';
export const uploadAttachmentAction = createAction({
auth: TeableAuth,
@@ -10,58 +12,32 @@ export const uploadAttachmentAction = createAction({
description: 'Uploads a file as an attachment to a field in a Teable record.',
audience: 'both',
aiMetadata: {
- description: 'Attaches a file to an attachment-type field of an existing Teable record, accepting either a public URL or binary file data. Use to add a document or image to a known record; requires the table ID, record ID, and the attachment field. Not idempotent — each call adds another attachment to the field.',
+ description:
+ 'Attaches a file to an attachment field of an existing record. The File input accepts a URL or binary data. Each call adds another attachment, so a retry duplicates the file.',
idempotent: false,
},
props: {
base_id: TeableCommon.base_id,
table_id: TeableCommon.table_id,
record_id: TeableCommon.record_id,
- field_id: Property.Dropdown({
- auth: TeableAuth,
- displayName: 'Attachment Field',
- description: 'The attachment field to upload the file to.',
- required: true,
- refreshers: ['table_id'],
- options: async ({ auth, table_id }) => {
- if (!auth || !table_id) {
- return { disabled: true, options: [], placeholder: 'Select a table first.' };
- }
- const client = makeClient(auth as TeableAuthValue);
- const fields = await client.listFields(table_id as string);
- const attachmentFields = fields.filter((f) => f.type === 'attachment');
- return {
- disabled: false,
- options: attachmentFields.map((f) => ({ label: f.name, value: f.id })),
- };
- },
- }),
+ field_id: TeableCommon.attachment_field_id,
file: Property.File({
displayName: 'File',
description: 'The file to upload. Accepts a URL or a binary file.',
required: true,
}),
},
+ outputSchema: teableOutputSchemas.recordCore,
async run(context) {
- const { table_id, record_id, field_id } = context.propsValue;
- const client = makeClient(context.auth as TeableAuthValue);
- const file = context.propsValue.file as ApFile | string;
-
- const form = new FormData();
- if (typeof file === 'string' && /^https?:\/\//i.test(file)) {
- form.append('fileUrl', file);
- } else {
- const apFile = file as ApFile;
- const mimeType = apFile.extension
- ? `application/${apFile.extension.replace(/^\./, '')}`
- : 'application/octet-stream';
- form.append(
- 'file',
- new Blob([new Uint8Array(apFile.data)], { type: mimeType }),
- apFile.filename
- );
- }
-
- return await client.uploadAttachment(table_id, record_id, field_id, form);
+ const { table_id, record_id, field_id, file } = context.propsValue;
+ return teableClient.uploadAttachment({
+ auth: context.auth,
+ tableId: table_id,
+ recordId: record_id,
+ fieldId: field_id,
+ filename: file.filename,
+ extension: file.extension,
+ data: file.data,
+ });
},
});
diff --git a/packages/pieces/community/teable/src/lib/actions/upsert-record-ai.ts b/packages/pieces/community/teable/src/lib/actions/upsert-record-ai.ts
new file mode 100644
index 00000000000..5f260f2d849
--- /dev/null
+++ b/packages/pieces/community/teable/src/lib/actions/upsert-record-ai.ts
@@ -0,0 +1,40 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { TeableAuth } from '../auth';
+import { teableAgent } from '../common/agent';
+import { TeableAgentProps } from '../common';
+import { teableClient } from '../common/client';
+import { teableOutputSchemas } from '../output-schemas';
+
+export const upsertRecordAi = createAction({
+ auth: TeableAuth,
+ name: 'upsert_record_ai',
+ classification: 'WRITE',
+ displayName: 'Upsert Record (Agent)',
+ description: 'Updates the record whose key field matches, or creates it.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Finds the record whose key field exactly equals the key value in Fields (the Teable "is" filter on that field). If none exists it creates one; if one exists it updates it, where a null value clears that field; if several match it stops with an error and changes nothing. Use this to avoid duplicates, e.g. key on Email, but run upserts for the same key one at a time: Teable has no atomic create-if-absent, so two parallel calls with the same new key can both create a record; when the action detects that after creating, it returns a warning. Needs the base ID, the table name or ID, the key field, and Fields including the key value. Returns {action: "created" or "updated", record, warning?}. Safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ baseId: TeableAgentProps.base_id,
+ table: TeableAgentProps.table,
+ keyColumn: Property.ShortText({
+ displayName: 'Key Field (name or ID)',
+ description: 'The field that identifies the record, e.g. Email.',
+ required: true,
+ }),
+ fields: TeableAgentProps.fields,
+ },
+ outputSchema: teableOutputSchemas.upsertRecord,
+ async run({ auth, propsValue }) {
+ const baseId = teableAgent.requireText({ value: propsValue.baseId, label: 'Base ID' });
+ const reference = teableAgent.requireText({ value: propsValue.table, label: 'Table' });
+ const keyColumn = teableAgent.requireText({ value: propsValue.keyColumn, label: 'Key Field' });
+ const input = teableAgent.parseFieldsInput(propsValue.fields);
+ const table = await teableAgent.resolveTable({ auth, baseId, reference });
+ const fields = await teableClient.listFields({ auth, tableId: table.id });
+ return teableAgent.upsertRecord({ auth, table, fields, keyColumn, input });
+ },
+});
diff --git a/packages/pieces/community/teable/src/lib/auth.ts b/packages/pieces/community/teable/src/lib/auth.ts
index fcb9f97727f..2e4a613d6e3 100644
--- a/packages/pieces/community/teable/src/lib/auth.ts
+++ b/packages/pieces/community/teable/src/lib/auth.ts
@@ -1,8 +1,97 @@
-import { PieceAuth, Property } from '@activepieces/pieces-framework';
-import { AppConnectionType } from '@activepieces/pieces-framework';
-import { TeableClient } from './common/client';
+import { AppConnectionType, PieceAuth, Property } from '@activepieces/pieces-framework';
+import {
+ AuthenticationType,
+ HttpError,
+ HttpMethod,
+ httpClient,
+} from '@activepieces/pieces-common';
import { TEABLE_CLOUD_URL } from './common/constants';
+const TEABLE_APP_PATH_SEGMENTS = ['base', 'space', 'dashboard', 'setting', 'developer', 'invite', 'auth'];
+
+function normalizeBaseUrl(raw: string | undefined): string {
+ if (raw === undefined || raw.trim().length === 0) {
+ return TEABLE_CLOUD_URL;
+ }
+ const trimmed = raw.trim();
+ let parsed: URL;
+ try {
+ parsed = new URL(trimmed);
+ } catch {
+ throw new Error(
+ 'Base URL must be a full URL including the scheme, e.g. https://teable.example.com.'
+ );
+ }
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
+ throw new Error('Base URL must use http or https.');
+ }
+ if (parsed.username !== '' || parsed.password !== '') {
+ throw new Error('Base URL must not contain credentials.');
+ }
+ if (parsed.search !== '' || parsed.hash !== '') {
+ throw new Error('Base URL must not contain a query string or fragment.');
+ }
+ const path = parsed.pathname.replace(/\/+$/, '').replace(/\/api$/, '').replace(/\/+$/, '');
+ const firstSegment = path.split('/')[1] ?? '';
+ if (path !== '' && !TEABLE_APP_PATH_SEGMENTS.includes(firstSegment)) {
+ throw new Error(
+ `Base URL must be the instance origin only, e.g. https://teable.example.com — remove the path "${path}".`
+ );
+ }
+ return parsed.origin;
+}
+
+function getToken(auth: TeableAuthValue): string {
+ if (auth.type === AppConnectionType.CUSTOM_AUTH) {
+ return auth.props.token.trim();
+ }
+ return auth.access_token;
+}
+
+function getBaseUrl(auth: TeableAuthValue): string {
+ if (auth.type === AppConnectionType.CUSTOM_AUTH) {
+ return normalizeBaseUrl(auth.props.baseUrl);
+ }
+ return TEABLE_CLOUD_URL;
+}
+
+async function validateConnection({
+ token,
+ baseUrl,
+}: {
+ token: string;
+ baseUrl?: string;
+}): Promise<{ valid: true } | { valid: false; error: string }> {
+ let origin: string;
+ try {
+ origin = normalizeBaseUrl(baseUrl);
+ } catch (e) {
+ return { valid: false, error: e instanceof Error ? e.message : String(e) };
+ }
+ try {
+ await httpClient.sendRequest({
+ method: HttpMethod.GET,
+ url: `${origin}/api/base/access/all`,
+ authentication: {
+ type: AuthenticationType.BEARER_TOKEN,
+ token: token.trim(),
+ },
+ });
+ return { valid: true };
+ } catch (e) {
+ if (e instanceof HttpError && (e.response.status === 401 || e.response.status === 403)) {
+ return {
+ valid: false,
+ error: 'Invalid credentials. Check your personal access token and its scopes.',
+ };
+ }
+ return {
+ valid: false,
+ error: `Could not reach ${origin}: ${e instanceof Error ? e.message : String(e)}`,
+ };
+ }
+}
+
export const TeableAuth = [
PieceAuth.OAuth2({
description: 'Connect your Teable account using OAuth2 (Teable Cloud only).',
@@ -11,12 +100,17 @@ export const TeableAuth = [
required: true,
scope: [
'base|read',
+ 'base|read_all',
'table|read',
+ 'table|create',
'field|read',
+ 'field|create',
+ 'view|read',
'record|read',
'record|create',
'record|update',
'record|delete',
+ 'record|comment',
],
}),
PieceAuth.CustomAuth({
@@ -41,46 +135,31 @@ To obtain your token:
baseUrl: Property.ShortText({
displayName: 'Base URL',
description:
- 'Teable Cloud: https://app.teable.ai — for self-hosted, enter your own domain.',
+ 'Teable Cloud: https://app.teable.ai — for self-hosted, enter your instance origin, e.g. https://teable.example.com.',
required: false,
}),
},
validate: async ({ auth }) => {
- try {
- const client = new TeableClient(
- auth.token,
- auth.baseUrl || TEABLE_CLOUD_URL
- );
- await client.listBases();
- return { valid: true };
- } catch (e) {
- return {
- valid: false,
- error: e instanceof Error ? e.message : 'Invalid credentials. Check your token and Base URL.',
- };
- }
+ return validateConnection({ token: auth.token, baseUrl: auth.baseUrl });
},
}),
];
-export type TeableAuthValue = {
- type: AppConnectionType.OAUTH2;
- access_token: string;
-} | {
- type: AppConnectionType.CUSTOM_AUTH;
- props: { token: string; baseUrl?: string };
+export const teableAuthUtil = {
+ getToken,
+ getBaseUrl,
+ normalizeBaseUrl,
};
-export function getTeableToken(auth: TeableAuthValue): string {
- if (auth.type === AppConnectionType.OAUTH2) {
- return auth.access_token;
- }
- return auth.props.token;
-}
-
-export function getTeableBaseUrl(auth: TeableAuthValue): string {
- if (auth.type === AppConnectionType.OAUTH2) {
- return TEABLE_CLOUD_URL;
- }
- return auth.props.baseUrl || TEABLE_CLOUD_URL;
-}
+export type TeableAuthValue =
+ | {
+ type:
+ | AppConnectionType.OAUTH2
+ | AppConnectionType.CLOUD_OAUTH2
+ | AppConnectionType.PLATFORM_OAUTH2;
+ access_token: string;
+ }
+ | {
+ type: AppConnectionType.CUSTOM_AUTH;
+ props: { token: string; baseUrl?: string };
+ };
diff --git a/packages/pieces/community/teable/src/lib/common/agent.ts b/packages/pieces/community/teable/src/lib/common/agent.ts
new file mode 100644
index 00000000000..a453caccc37
--- /dev/null
+++ b/packages/pieces/community/teable/src/lib/common/agent.ts
@@ -0,0 +1,284 @@
+import { TeableAuthValue } from '../auth';
+import { teableClient, TeableField, TeableRecord, TeableTable } from './client';
+import { teableProps } from './index';
+
+function requireText({ value, label }: { value: unknown; label: string }): string {
+ const text =
+ typeof value === 'string' ? value.trim() : typeof value === 'number' ? String(value) : '';
+ if (text.length === 0) {
+ throw new Error(`${label} is required.`);
+ }
+ return text;
+}
+
+function parseFieldsInput(value: unknown): Record<string, unknown> {
+ const parsed: unknown = typeof value === 'string' ? parseJson(value) : value;
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
+ throw new Error(
+ 'Fields must be a JSON object keyed by column name or field ID, e.g. {"Name": "Jane", "Age": 30}.'
+ );
+ }
+ return Object.fromEntries(Object.entries(parsed));
+}
+
+function parseJson(text: string): unknown {
+ try {
+ return JSON.parse(text);
+ } catch {
+ throw new Error('Fields is not valid JSON. Send an object such as {"Name": "Jane"}.');
+ }
+}
+
+function pickTable({
+ tables,
+ reference,
+}: {
+ tables: TeableTable[];
+ reference: string;
+}): TeableTable {
+ const byId = tables.find((table) => table.id === reference);
+ if (byId) {
+ return byId;
+ }
+ const lowered = reference.toLowerCase();
+ const byName = tables.filter((table) => table.name.toLowerCase() === lowered);
+ if (byName.length === 1) {
+ return byName[0];
+ }
+ if (byName.length > 1) {
+ const ids = byName.map((table) => table.id).join(', ');
+ throw new Error(
+ `${byName.length} tables are named "${reference}" (IDs: ${ids}). Pass the table ID instead.`
+ );
+ }
+ const names = tables.map((table) => `${table.name} (${table.id})`).join(', ');
+ throw new Error(`Table "${reference}" was not found in this base. Tables: ${names || 'none'}.`);
+}
+
+async function resolveTable({
+ auth,
+ baseId,
+ reference,
+}: {
+ auth: TeableAuthValue;
+ baseId: string;
+ reference: string;
+}): Promise<TeableTable> {
+ const tables = await teableClient.listTables({ auth, baseId });
+ return pickTable({ tables, reference });
+}
+
+function writableNames(fields: TeableField[]): string {
+ return fields
+ .filter((field) => teableProps.isRecordWritableField(field))
+ .map((field) => field.name)
+ .join(', ');
+}
+
+function findColumn({
+ fields,
+ reference,
+}: {
+ fields: TeableField[];
+ reference: string;
+}): TeableField {
+ const trimmed = reference.trim();
+ const byId = fields.find((field) => field.id === trimmed);
+ if (byId) {
+ return byId;
+ }
+ const lowered = trimmed.toLowerCase();
+ const byName = fields.filter((field) => field.name.toLowerCase() === lowered);
+ if (byName.length === 1) {
+ return byName[0];
+ }
+ if (byName.length > 1) {
+ throw new Error(
+ `More than one column is named "${trimmed}". Use the field ID instead (see Get Base Schema (Agent)).`
+ );
+ }
+ throw new Error(
+ `Column "${trimmed}" does not exist in this table. Valid columns: ${writableNames(fields)}.`
+ );
+}
+
+function buildRecordFields({
+ fields,
+ input,
+ allowClear,
+}: {
+ fields: TeableField[];
+ input: Record<string, unknown>;
+ allowClear: boolean;
+}): Record<string, unknown> {
+ const values: Record<string, unknown> = {};
+ for (const [reference, value] of Object.entries(input)) {
+ const field = findColumn({ fields, reference });
+ if (!teableProps.isRecordWritableField(field)) {
+ throw new Error(
+ `Column "${field.name}" (${field.type}) cannot be written. Writable columns: ${writableNames(
+ fields
+ )}.`
+ );
+ }
+ if (field.id in values) {
+ throw new Error(`Column "${field.name}" is given more than once.`);
+ }
+ if (value === null || value === '') {
+ if (!allowClear) {
+ continue;
+ }
+ values[field.id] = null;
+ continue;
+ }
+ if (value === undefined) {
+ continue;
+ }
+ values[field.id] = value;
+ }
+ if (Object.keys(values).length === 0) {
+ throw new Error('Fields is empty. Give at least one column with a value.');
+ }
+ return values;
+}
+
+function mapFieldIdsToNames({
+ fields,
+ record,
+}: {
+ fields: TeableField[];
+ record: TeableRecord;
+}): TeableRecord {
+ const nameById = new Map(fields.map((field) => [field.id, field.name]));
+ const mapped: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(record.fields ?? {})) {
+ mapped[nameById.get(key) ?? key] = value;
+ }
+ return { ...record, fields: mapped };
+}
+
+function buildIsFilter({ fieldId, value }: { fieldId: string; value: unknown }): string {
+ return JSON.stringify({
+ conjunction: 'and',
+ filterSet: [{ fieldId, operator: 'is', value }],
+ });
+}
+
+async function findKeyMatches({
+ auth,
+ table,
+ key,
+ keyValue,
+}: {
+ auth: TeableAuthValue;
+ table: TeableTable;
+ key: TeableField;
+ keyValue: unknown;
+}): Promise<TeableRecord[]> {
+ const matches = await teableClient.listRecords({
+ auth,
+ tableId: table.id,
+ query: {
+ take: 2,
+ fieldKeyType: 'id',
+ filter: buildIsFilter({ fieldId: key.id, value: keyValue }),
+ },
+ });
+ return matches.records;
+}
+
+async function duplicateKeyWarning({
+ auth,
+ table,
+ key,
+ keyValue,
+}: {
+ auth: TeableAuthValue;
+ table: TeableTable;
+ key: TeableField;
+ keyValue: unknown;
+}): Promise<string | undefined> {
+ try {
+ const recheck = await findKeyMatches({ auth, table, key, keyValue });
+ if (recheck.length > 1) {
+ return `More than one record now matches ${key.name} = "${String(
+ keyValue
+ )}": a parallel upsert likely created a duplicate, since Teable has no atomic create-if-absent. Run same-key upserts one at a time and remove the extra record.`;
+ }
+ return undefined;
+ } catch {
+ return `The record was created, but the duplicate check could not run. Verify that no parallel upsert created a second record with ${key.name} = "${String(
+ keyValue
+ )}".`;
+ }
+}
+
+async function upsertRecord({
+ auth,
+ table,
+ fields,
+ keyColumn,
+ input,
+}: {
+ auth: TeableAuthValue;
+ table: TeableTable;
+ fields: TeableField[];
+ keyColumn: string;
+ input: Record<string, unknown>;
+}): Promise<{ action: 'created' | 'updated'; record: TeableRecord; warning?: string }> {
+ const key = findColumn({ fields, reference: keyColumn });
+ const updateValues = buildRecordFields({ fields, input, allowClear: true });
+ const keyValue = updateValues[key.id];
+ if (keyValue === undefined || keyValue === null) {
+ throw new Error(`Fields must include a value for the key column "${key.name}".`);
+ }
+ if (typeof keyValue === 'object') {
+ throw new Error(`The key column "${key.name}" must hold a single text or number value.`);
+ }
+ const matches = await findKeyMatches({ auth, table, key, keyValue });
+ if (matches.length > 1) {
+ throw new Error(
+ `More than one record matches ${key.name} = "${String(
+ keyValue
+ )}", refusing to guess. Use Update Record (Agent) with a record ID.`
+ );
+ }
+ const existing = matches[0];
+ if (existing === undefined) {
+ const createValues = buildRecordFields({ fields, input, allowClear: false });
+ const created = await teableClient.createRecords({
+ auth,
+ tableId: table.id,
+ records: [{ fields: createValues }],
+ fieldKeyType: 'id',
+ typecast: true,
+ });
+ const warning = await duplicateKeyWarning({ auth, table, key, keyValue });
+ return {
+ action: 'created',
+ record: mapFieldIdsToNames({ fields, record: created.records[0] }),
+ ...(warning !== undefined ? { warning } : {}),
+ };
+ }
+ const updated = await teableClient.updateRecord({
+ auth,
+ tableId: table.id,
+ recordId: existing.id,
+ fields: updateValues,
+ fieldKeyType: 'id',
+ typecast: true,
+ });
+ return { action: 'updated', record: mapFieldIdsToNames({ fields, record: updated }) };
+}
+
+export const teableAgent = {
+ requireText,
+ parseFieldsInput,
+ resolveTable,
+ findColumn,
+ buildRecordFields,
+ mapFieldIdsToNames,
+ buildIsFilter,
+ upsertRecord,
+ writableNames,
+};
diff --git a/packages/pieces/community/teable/src/lib/common/client.ts b/packages/pieces/community/teable/src/lib/common/client.ts
index c9c5a3ff293..fefb3b6d12c 100644
--- a/packages/pieces/community/teable/src/lib/common/client.ts
+++ b/packages/pieces/community/teable/src/lib/common/client.ts
@@ -1,219 +1,502 @@
import {
- HttpMessageBody,
- HttpMethod,
- QueryParams,
AuthenticationType,
+ HttpError,
+ HttpMethod,
httpClient,
} from '@activepieces/pieces-common';
-import { TEABLE_CLOUD_URL } from './constants';
-
-
-function emptyValueFilter(
- accessor: (key: string) => any
-): (key: string) => boolean {
- return (key: string) => {
- const val = accessor(key);
- return (
- val !== null &&
- val !== undefined &&
- (typeof val !== 'string' || val.length > 0) &&
- (!Array.isArray(val) || val.length > 0)
- );
- };
+import FormData from 'form-data';
+import mime from 'mime-types';
+import { TeableAuthValue, teableAuthUtil } from '../auth';
+import { TEABLE_MAX_PAGE_SIZE } from './constants';
+
+function buildQueryString(query: TeableQuery | undefined): string {
+ if (query === undefined) {
+ return '';
+ }
+ const params = new URLSearchParams();
+ for (const [key, value] of Object.entries(query)) {
+ if (value === undefined || value === null || value === '') {
+ continue;
+ }
+ if (Array.isArray(value)) {
+ for (const item of value) {
+ params.append(`${key}[]`, item);
+ }
+ continue;
+ }
+ params.append(key, String(value));
+ }
+ const text = params.toString();
+ return text.length > 0 ? `?${text}` : '';
}
-export function prepareQuery(request?: Record<string, any>): QueryParams {
- const params: QueryParams = {};
- if (!request) return params;
- Object.keys(request)
- .filter(emptyValueFilter((k) => request[k]))
- .forEach((k: string) => {
- const val = (request as Record<string, any>)[k];
- params[k] = Array.isArray(val) ? val : val.toString();
- });
- return params;
+async function makeRequest<T>({
+ auth,
+ method,
+ path,
+ query,
+ body,
+ headers,
+}: MakeRequestParams): Promise<T> {
+ const response = await httpClient.sendRequest<T>({
+ method,
+ url: `${teableAuthUtil.getBaseUrl(auth)}/api${path}${buildQueryString(query)}`,
+ authentication: {
+ type: AuthenticationType.BEARER_TOKEN,
+ token: teableAuthUtil.getToken(auth),
+ },
+ headers,
+ body,
+ });
+ return response.body;
}
+function errorStatus(error: unknown): number | undefined {
+ return error instanceof HttpError ? error.response.status : undefined;
+}
+async function listBases({ auth }: { auth: TeableAuthValue }): Promise<TeableBase[]> {
+ return makeRequest<TeableBase[]>({
+ auth,
+ method: HttpMethod.GET,
+ path: '/base/access/all',
+ });
+}
-export class TeableClient {
- private readonly apiBase: string;
+async function listTables({
+ auth,
+ baseId,
+}: {
+ auth: TeableAuthValue;
+ baseId: string;
+}): Promise<TeableTable[]> {
+ return makeRequest<TeableTable[]>({
+ auth,
+ method: HttpMethod.GET,
+ path: `/base/${encodeURIComponent(baseId)}/table`,
+ });
+}
- constructor(
- private token: string,
- teableUrl: string = TEABLE_CLOUD_URL
- ) {
- this.apiBase = `${teableUrl}/api`;
- }
+async function listFields({
+ auth,
+ tableId,
+}: {
+ auth: TeableAuthValue;
+ tableId: string;
+}): Promise<TeableField[]> {
+ return makeRequest<TeableField[]>({
+ auth,
+ method: HttpMethod.GET,
+ path: `/table/${encodeURIComponent(tableId)}/field`,
+ });
+}
- async makeRequest<T extends HttpMessageBody>(
- method: HttpMethod,
- resourceUri: string,
- query?: QueryParams,
- body: any | undefined = undefined
- ): Promise<T> {
- const res = await httpClient.sendRequest<T>({
- method,
- url: this.apiBase + resourceUri,
- authentication: {
- type: AuthenticationType.BEARER_TOKEN,
- token: this.token,
- },
- queryParams: query,
- body: body,
- });
+async function listViews({
+ auth,
+ tableId,
+}: {
+ auth: TeableAuthValue;
+ tableId: string;
+}): Promise<TeableView[]> {
+ return makeRequest<TeableView[]>({
+ auth,
+ method: HttpMethod.GET,
+ path: `/table/${encodeURIComponent(tableId)}/view`,
+ });
+}
- return res.body;
- }
+async function getRecord({
+ auth,
+ tableId,
+ recordId,
+ query,
+}: {
+ auth: TeableAuthValue;
+ tableId: string;
+ recordId: string;
+ query?: TeableQuery;
+}): Promise<TeableRecord> {
+ return makeRequest<TeableRecord>({
+ auth,
+ method: HttpMethod.GET,
+ path: `/table/${encodeURIComponent(tableId)}/record/${encodeURIComponent(recordId)}`,
+ query,
+ });
+}
- /**
- * GET /api/base/access/all
- * Returns all bases the token has access to.
- * @see https://help.teable.ai/en/api-reference/base/get-baseaccessall
- */
- async listBases() {
- return await this.makeRequest<
- {
- id: string;
- name: string;
- spaceId: string;
- icon: string | null;
- role: string;
- }[]
- >(HttpMethod.GET, '/base/access/all');
- }
+async function listRecords({
+ auth,
+ tableId,
+ query,
+}: {
+ auth: TeableAuthValue;
+ tableId: string;
+ query?: TeableQuery;
+}): Promise<TeableRecordListResponse> {
+ return makeRequest<TeableRecordListResponse>({
+ auth,
+ method: HttpMethod.GET,
+ path: `/table/${encodeURIComponent(tableId)}/record`,
+ query,
+ });
+}
- /**
- * GET /api/base/{baseId}/table
- * Returns all tables in the given base.
- * @see https://help.teable.ai/en/api-reference/table/list-tables
- */
- async listTables(baseId: string) {
- return await this.makeRequest<
- {
- id: string;
- name: string;
- dbTableName: string;
- description?: string;
- icon?: string;
- order: number;
- defaultViewId?: string;
- }[]
- >(HttpMethod.GET, `/base/${baseId}/table`);
+async function listRecordsPaged({
+ auth,
+ tableId,
+ query,
+ maxRecords,
+ skip,
+}: {
+ auth: TeableAuthValue;
+ tableId: string;
+ query?: TeableQuery;
+ maxRecords: number;
+ skip?: number;
+}): Promise<{ records: TeableRecord[]; hasMore: boolean }> {
+ const records: TeableRecord[] = [];
+ let offset = skip ?? 0;
+ let hasMore = false;
+ while (records.length < maxRecords) {
+ const take = Math.min(TEABLE_MAX_PAGE_SIZE, maxRecords - records.length);
+ const page = await listRecords({
+ auth,
+ tableId,
+ query: { ...query, take, skip: offset },
+ });
+ records.push(...page.records);
+ if (page.records.length < take) {
+ return { records, hasMore: false };
+ }
+ offset += page.records.length;
+ hasMore = true;
}
+ const lookahead = await listRecords({
+ auth,
+ tableId,
+ query: { ...query, take: 1, skip: offset },
+ });
+ return { records, hasMore: hasMore && lookahead.records.length > 0 };
+}
- /**
- * GET /api/table/{tableId}/field
- * Returns all fields in the given table.
- * @see https://help.teable.ai/en/api-reference/field/list-fields
- */
- async listFields(tableId: string) {
- return await this.makeRequest<
- {
- id: string;
- name: string;
- type: string;
- isComputed?: boolean;
- isPrimary?: boolean;
- options?: {
- choices?: { id: string; name: string; color?: string }[];
- [key: string]: unknown;
- };
- }[]
- >(HttpMethod.GET, `/table/${tableId}/field`);
- }
+async function createRecords({
+ auth,
+ tableId,
+ records,
+ fieldKeyType,
+ typecast,
+}: {
+ auth: TeableAuthValue;
+ tableId: string;
+ records: { fields: Record<string, unknown> }[];
+ fieldKeyType?: TeableFieldKeyType;
+ typecast?: boolean;
+}): Promise<{ records: TeableRecord[] }> {
+ return makeRequest<{ records: TeableRecord[] }>({
+ auth,
+ method: HttpMethod.POST,
+ path: `/table/${encodeURIComponent(tableId)}/record`,
+ body: {
+ records,
+ ...(fieldKeyType !== undefined ? { fieldKeyType } : {}),
+ ...(typecast !== undefined ? { typecast } : {}),
+ },
+ });
+}
- /**
- * GET /api/table/{tableId}/record/{recordId}
- * Retrieves a single record by its ID.
- * @see https://help.teable.ai/en/api-reference/record/get-record
- */
- async getRecord(
- tableId: string,
- recordId: string,
- query?: QueryParams
- ) {
- return await this.makeRequest<{
- id: string;
- fields: Record<string, unknown>;
- name: string;
- autoNumber: number;
- createdTime: string;
- lastModifiedTime: string;
- createdBy: string;
- lastModifiedBy: string;
- permissions: Record<string, unknown>;
- }>(HttpMethod.GET, `/table/${tableId}/record/${recordId}`, query);
- }
+async function updateRecord({
+ auth,
+ tableId,
+ recordId,
+ fields,
+ fieldKeyType,
+ typecast,
+}: {
+ auth: TeableAuthValue;
+ tableId: string;
+ recordId: string;
+ fields: Record<string, unknown>;
+ fieldKeyType?: TeableFieldKeyType;
+ typecast?: boolean;
+}): Promise<TeableRecord> {
+ return makeRequest<TeableRecord>({
+ auth,
+ method: HttpMethod.PATCH,
+ path: `/table/${encodeURIComponent(tableId)}/record/${encodeURIComponent(recordId)}`,
+ body: {
+ record: { fields },
+ ...(fieldKeyType !== undefined ? { fieldKeyType } : {}),
+ ...(typecast !== undefined ? { typecast } : {}),
+ },
+ });
+}
- /**
- * GET /api/table/{tableId}/record
- * Retrieves a list of records with support for filtering, sorting, and pagination.
- * @see https://help.teable.ai/en/api-reference/record/list-records
- */
- async listRecords(
- tableId: string,
- query?: QueryParams
- ) {
- return await this.makeRequest<{
- records: {
- id: string;
- fields: Record<string, unknown>;
- }[];
- }>(HttpMethod.GET, `/table/${tableId}/record`, query);
- }
+async function updateRecords({
+ auth,
+ tableId,
+ records,
+ fieldKeyType,
+ typecast,
+}: {
+ auth: TeableAuthValue;
+ tableId: string;
+ records: { id: string; fields: Record<string, unknown> }[];
+ fieldKeyType?: TeableFieldKeyType;
+ typecast?: boolean;
+}): Promise<TeableRecord[]> {
+ return makeRequest<TeableRecord[]>({
+ auth,
+ method: HttpMethod.PATCH,
+ path: `/table/${encodeURIComponent(tableId)}/record`,
+ body: {
+ records,
+ ...(fieldKeyType !== undefined ? { fieldKeyType } : {}),
+ ...(typecast !== undefined ? { typecast } : {}),
+ },
+ });
+}
- /**
- * POST /api/table/{tableId}/record
- * Creates one or more records.
- */
- async createRecord(tableId: string, request: object) {
- return await this.makeRequest(
- HttpMethod.POST,
- `/table/${tableId}/record`,
- undefined,
- request
- );
+async function deleteRecord({
+ auth,
+ tableId,
+ recordId,
+}: {
+ auth: TeableAuthValue;
+ tableId: string;
+ recordId: string;
+}): Promise<void> {
+ try {
+ await makeRequest<unknown>({
+ auth,
+ method: HttpMethod.DELETE,
+ path: `/table/${encodeURIComponent(tableId)}/record/${encodeURIComponent(recordId)}`,
+ });
+ } catch (error) {
+ if (errorStatus(error) === 404) {
+ throw new Error(
+ `Record ${recordId} was not found in table ${tableId}. It may already be deleted.`
+ );
+ }
+ throw error;
}
+}
- /**
- * DELETE /api/table/{tableId}/record/{recordId}
- * Deletes a single record.
- */
- async deleteRecord(tableId: string, recordId: string) {
- return await this.makeRequest(
- HttpMethod.DELETE,
- `/table/${tableId}/record/${recordId}`
- );
- }
+async function deleteRecords({
+ auth,
+ tableId,
+ recordIds,
+}: {
+ auth: TeableAuthValue;
+ tableId: string;
+ recordIds: string[];
+}): Promise<void> {
+ await makeRequest<unknown>({
+ auth,
+ method: HttpMethod.DELETE,
+ path: `/table/${encodeURIComponent(tableId)}/record`,
+ query: { recordIds },
+ });
+}
- /**
- * PATCH /api/table/{tableId}/record/{recordId}
- * Updates a single record.
- */
- async updateRecord(tableId: string, recordId: string, request: object) {
- return await this.makeRequest(
- HttpMethod.PATCH,
- `/table/${tableId}/record/${recordId}`,
- undefined,
- request
- );
- }
+async function createTable({
+ auth,
+ baseId,
+ body,
+}: {
+ auth: TeableAuthValue;
+ baseId: string;
+ body: Record<string, unknown>;
+}): Promise<TeableTable & { fields?: TeableField[]; views?: TeableView[] }> {
+ return makeRequest({
+ auth,
+ method: HttpMethod.POST,
+ path: `/base/${encodeURIComponent(baseId)}/table/`,
+ body,
+ });
+}
- /**
- * POST /api/table/{tableId}/record/{recordId}/{fieldId}/uploadAttachment
- * Uploads a file as an attachment to a specific field in a record.
- */
- async uploadAttachment(tableId: string, recordId: string, fieldId: string, form: FormData) {
- const res = await httpClient.sendRequest({
- method: HttpMethod.POST,
- url: `${this.apiBase}/table/${tableId}/record/${recordId}/${fieldId}/uploadAttachment`,
- authentication: {
- type: AuthenticationType.BEARER_TOKEN,
- token: this.token,
- },
- body: form,
- });
- return res.body;
- }
+async function createField({
+ auth,
+ tableId,
+ body,
+}: {
+ auth: TeableAuthValue;
+ tableId: string;
+ body: Record<string, unknown>;
+}): Promise<TeableField> {
+ return makeRequest<TeableField>({
+ auth,
+ method: HttpMethod.POST,
+ path: `/table/${encodeURIComponent(tableId)}/field`,
+ body,
+ });
+}
+
+async function createComment({
+ auth,
+ tableId,
+ recordId,
+ content,
+}: {
+ auth: TeableAuthValue;
+ tableId: string;
+ recordId: string;
+ content: unknown[];
+}): Promise<unknown> {
+ return makeRequest<unknown>({
+ auth,
+ method: HttpMethod.POST,
+ path: `/comment/${encodeURIComponent(tableId)}/${encodeURIComponent(recordId)}/create`,
+ body: { content },
+ });
+}
+
+async function getRowCount({
+ auth,
+ tableId,
+}: {
+ auth: TeableAuthValue;
+ tableId: string;
+}): Promise<number> {
+ const response = await makeRequest<{ rowCount: number }>({
+ auth,
+ method: HttpMethod.GET,
+ path: `/table/${encodeURIComponent(tableId)}/aggregation/row-count`,
+ });
+ return response.rowCount;
+}
+
+async function uploadAttachment({
+ auth,
+ tableId,
+ recordId,
+ fieldId,
+ filename,
+ extension,
+ data,
+}: {
+ auth: TeableAuthValue;
+ tableId: string;
+ recordId: string;
+ fieldId: string;
+ filename: string;
+ extension?: string;
+ data: Buffer;
+}): Promise<TeableRecord> {
+ const lookedUp = extension !== undefined ? mime.lookup(extension) : false;
+ const contentType = lookedUp === false ? 'application/octet-stream' : lookedUp;
+ const form = new FormData();
+ form.append('file', data, { filename, contentType });
+ const path = `/table/${encodeURIComponent(tableId)}/record/${encodeURIComponent(
+ recordId
+ )}/${encodeURIComponent(fieldId)}/uploadAttachment`;
+ const response = await httpClient.sendRequest<TeableRecord>({
+ method: HttpMethod.POST,
+ url: `${teableAuthUtil.getBaseUrl(auth)}/api${path}`,
+ headers: form.getHeaders(),
+ authentication: {
+ type: AuthenticationType.BEARER_TOKEN,
+ token: teableAuthUtil.getToken(auth),
+ },
+ body: form,
+ });
+ return response.body;
}
+
+export const teableClient = {
+ buildQueryString,
+ makeRequest,
+ errorStatus,
+ listBases,
+ listTables,
+ listFields,
+ listViews,
+ getRecord,
+ listRecords,
+ listRecordsPaged,
+ createRecords,
+ updateRecord,
+ updateRecords,
+ deleteRecord,
+ deleteRecords,
+ createTable,
+ createField,
+ createComment,
+ getRowCount,
+ uploadAttachment,
+};
+
+export type TeableQuery = Record<
+ string,
+ string | number | boolean | string[] | undefined | null
+>;
+
+export type TeableFieldKeyType = 'id' | 'name' | 'dbFieldName';
+
+export type MakeRequestParams = {
+ auth: TeableAuthValue;
+ method: HttpMethod;
+ path: string;
+ query?: TeableQuery;
+ body?: unknown;
+ headers?: Record<string, string>;
+};
+
+export type TeableBase = {
+ id: string;
+ name: string;
+ spaceId: string;
+ icon: string | null;
+ role: string;
+};
+
+export type TeableTable = {
+ id: string;
+ name: string;
+ dbTableName?: string;
+ description?: string;
+ icon?: string;
+ order?: number;
+ defaultViewId?: string;
+};
+
+export type TeableField = {
+ id: string;
+ name: string;
+ type: string;
+ description?: string;
+ isComputed?: boolean;
+ isPrimary?: boolean;
+ notNull?: boolean;
+ unique?: boolean;
+ dbFieldName?: string;
+ options?: {
+ choices?: { id: string; name: string; color?: string }[];
+ [key: string]: unknown;
+ };
+};
+
+export type TeableView = {
+ id: string;
+ name: string;
+ type: string;
+ order?: number;
+};
+
+export type TeableRecord = {
+ id: string;
+ fields: Record<string, unknown>;
+ name?: string;
+ autoNumber?: number;
+ createdTime?: string;
+ lastModifiedTime?: string;
+ createdBy?: string;
+ lastModifiedBy?: string;
+};
+
+export type TeableRecordListResponse = {
+ records: TeableRecord[];
+ extra?: {
+ nextCursor?: string | null;
+ };
+};
diff --git a/packages/pieces/community/teable/src/lib/common/constants.ts b/packages/pieces/community/teable/src/lib/common/constants.ts
index e8d91395fe7..08cf346514b 100644
--- a/packages/pieces/community/teable/src/lib/common/constants.ts
+++ b/packages/pieces/community/teable/src/lib/common/constants.ts
@@ -1,45 +1,58 @@
-// Teable field types as returned by GET /api/table/{tableId}/field
-// @see https://help.teable.ai/en/api-reference/field/list-fields
export enum TeableFieldType {
- SINGLE_LINE_TEXT = 'singleLineText',
- LONG_TEXT = 'longText',
- USER = 'user',
- CHECKBOX = 'checkbox',
- MULTIPLE_SELECT = 'multipleSelect',
- SINGLE_SELECT = 'singleSelect',
- DATE = 'date',
- NUMBER = 'number',
- RATING = 'rating',
- LINK = 'link',
- // Computed — read-only, excluded from create/update
- ATTACHMENT = 'attachment',
- FORMULA = 'formula',
- ROLLUP = 'rollup',
- CONDITIONAL_ROLLUP = 'conditionalRollup',
- CREATED_TIME = 'createdTime',
- LAST_MODIFIED_TIME = 'lastModifiedTime',
- CREATED_BY = 'createdBy',
- LAST_MODIFIED_BY = 'lastModifiedBy',
- AUTO_NUMBER = 'autoNumber',
- BUTTON = 'button',
+ SINGLE_LINE_TEXT = 'singleLineText',
+ LONG_TEXT = 'longText',
+ USER = 'user',
+ CHECKBOX = 'checkbox',
+ MULTIPLE_SELECT = 'multipleSelect',
+ SINGLE_SELECT = 'singleSelect',
+ DATE = 'date',
+ NUMBER = 'number',
+ RATING = 'rating',
+ LINK = 'link',
+ ATTACHMENT = 'attachment',
+ FORMULA = 'formula',
+ ROLLUP = 'rollup',
+ CONDITIONAL_ROLLUP = 'conditionalRollup',
+ CREATED_TIME = 'createdTime',
+ LAST_MODIFIED_TIME = 'lastModifiedTime',
+ CREATED_BY = 'createdBy',
+ LAST_MODIFIED_BY = 'lastModifiedBy',
+ AUTO_NUMBER = 'autoNumber',
+ BUTTON = 'button',
}
-export const TeableNumericFieldTypes: string[] = [
- TeableFieldType.NUMBER,
- TeableFieldType.RATING,
+export const TeableComputedFieldTypes: string[] = [
+ TeableFieldType.FORMULA,
+ TeableFieldType.ROLLUP,
+ TeableFieldType.CONDITIONAL_ROLLUP,
+ TeableFieldType.CREATED_TIME,
+ TeableFieldType.LAST_MODIFIED_TIME,
+ TeableFieldType.CREATED_BY,
+ TeableFieldType.LAST_MODIFIED_BY,
+ TeableFieldType.AUTO_NUMBER,
+ TeableFieldType.BUTTON,
];
-export const TeableComputedFieldTypes: string[] = [
- TeableFieldType.ATTACHMENT,
- TeableFieldType.FORMULA,
- TeableFieldType.ROLLUP,
- TeableFieldType.CONDITIONAL_ROLLUP,
- TeableFieldType.CREATED_TIME,
- TeableFieldType.LAST_MODIFIED_TIME,
- TeableFieldType.CREATED_BY,
- TeableFieldType.LAST_MODIFIED_BY,
- TeableFieldType.AUTO_NUMBER,
- TeableFieldType.BUTTON,
+export const TeableCreatableFieldTypes: string[] = [
+ TeableFieldType.SINGLE_LINE_TEXT,
+ TeableFieldType.LONG_TEXT,
+ TeableFieldType.USER,
+ TeableFieldType.ATTACHMENT,
+ TeableFieldType.CHECKBOX,
+ TeableFieldType.MULTIPLE_SELECT,
+ TeableFieldType.SINGLE_SELECT,
+ TeableFieldType.DATE,
+ TeableFieldType.NUMBER,
+ TeableFieldType.RATING,
+ TeableFieldType.FORMULA,
+ TeableFieldType.LINK,
+ TeableFieldType.CREATED_TIME,
+ TeableFieldType.LAST_MODIFIED_TIME,
+ TeableFieldType.CREATED_BY,
+ TeableFieldType.LAST_MODIFIED_BY,
+ TeableFieldType.AUTO_NUMBER,
];
export const TEABLE_CLOUD_URL = 'https://app.teable.ai';
+
+export const TEABLE_MAX_PAGE_SIZE = 1000;
diff --git a/packages/pieces/community/teable/src/lib/common/index.ts b/packages/pieces/community/teable/src/lib/common/index.ts
index 78d0c6da074..0d2e82b7016 100644
--- a/packages/pieces/community/teable/src/lib/common/index.ts
+++ b/packages/pieces/community/teable/src/lib/common/index.ts
@@ -1,139 +1,280 @@
import { DynamicPropsValue, Property } from '@activepieces/pieces-framework';
-import { TeableAuth, TeableAuthValue, getTeableToken, getTeableBaseUrl } from '../auth';
-import { TeableClient } from './client';
-import { TeableComputedFieldTypes, TeableFieldType } from './constants';
+import { TeableAuth } from '../auth';
+import { teableClient, TeableField } from './client';
+import { TeableComputedFieldTypes, TeableFieldType, TEABLE_MAX_PAGE_SIZE } from './constants';
-export function makeClient(auth: TeableAuthValue) {
- return new TeableClient(
- getTeableToken(auth),
- getTeableBaseUrl(auth)
- );
+function errorPlaceholder({ prefix, error }: { prefix: string; error: unknown }): string {
+ return `${prefix}: ${error instanceof Error ? error.message : String(error)}`;
}
-export const TeableCommon = {
- base_id: Property.Dropdown({
- auth: TeableAuth,
- displayName: 'Base',
- required: true,
- refreshers: [],
- options: async ({ auth }) => {
- if (!auth) {
- return { disabled: true, options: [], placeholder: 'Connect your account first.' };
- }
- const client = makeClient(auth as TeableAuthValue);
- const bases = await client.listBases();
- return {
- disabled: false,
- options: bases.map((b) => ({ label: b.name, value: b.id })),
- };
- },
- }),
- table_id: Property.Dropdown({
- auth: TeableAuth,
- displayName: 'Table',
- description: 'The table inside the selected base.',
- required: true,
- refreshers: ['base_id'],
- options: async ({ auth, base_id }) => {
- if (!auth || !base_id) {
- return { disabled: true, options: [], placeholder: 'Select a base first.' };
- }
- const client = makeClient(auth as TeableAuthValue);
- const tables = await client.listTables(base_id as string);
- return {
- disabled: false,
- options: tables.map((t) => ({ label: t.name, value: t.id })),
- };
- },
- }),
- record_id: Property.Dropdown({
- auth: TeableAuth,
- displayName: 'Record',
- description: 'The record to act on.',
- required: true,
- refreshers: ['table_id'],
- options: async ({ auth, table_id }) => {
- if (!auth || !table_id) {
- return { disabled: true, options: [], placeholder: 'Select a table first.' };
- }
- const client = makeClient(auth as TeableAuthValue);
- const response = await client.listRecords(table_id as string);
- return {
- disabled: false,
- options: response.records.map((r) => {
- const primaryValue = Object.values(r.fields)[0];
- const label = primaryValue !== undefined && primaryValue !== null && primaryValue !== ''
- ? String(primaryValue)
- : r.id;
- return { label, value: r.id };
- }),
- };
- },
- }),
- fields: Property.DynamicProperties({
- auth: TeableAuth,
- displayName: 'Fields',
- description: 'The fields to add to the record.',
- required: true,
- refreshers: ['auth', 'table_id'],
- props: async ({ auth, table_id }) => {
- if (!auth || !table_id) return {};
-
- const client = makeClient(auth as TeableAuthValue);
- const fields = await client.listFields(table_id as string);
+function isRecordWritableField(field: TeableField): boolean {
+ return (
+ field.isComputed !== true &&
+ !TeableComputedFieldTypes.includes(field.type) &&
+ field.type !== TeableFieldType.ATTACHMENT &&
+ field.type !== TeableFieldType.BUTTON
+ );
+}
- const props: DynamicPropsValue = {};
+function buildFieldProp(field: TeableField) {
+ const displayName = field.name;
+ const required = false;
+ const choices = field.options?.choices ?? [];
+ switch (field.type) {
+ case TeableFieldType.CHECKBOX:
+ return Property.Checkbox({ displayName, required });
+ case TeableFieldType.NUMBER:
+ case TeableFieldType.RATING:
+ return Property.Number({ displayName, required });
+ case TeableFieldType.DATE:
+ return Property.DateTime({ displayName, required });
+ case TeableFieldType.LONG_TEXT:
+ return Property.LongText({ displayName, required });
+ case TeableFieldType.MULTIPLE_SELECT:
+ return Property.StaticMultiSelectDropdown({
+ displayName,
+ required,
+ options: { options: choices.map((c) => ({ label: c.name, value: c.name })) },
+ });
+ case TeableFieldType.SINGLE_SELECT:
+ return Property.StaticDropdown({
+ displayName,
+ required,
+ options: { options: choices.map((c) => ({ label: c.name, value: c.name })) },
+ });
+ case TeableFieldType.LINK:
+ return Property.Array({
+ displayName,
+ description: 'Record IDs or primary field values of the linked records.',
+ required,
+ });
+ case TeableFieldType.USER:
+ return Property.Array({
+ displayName,
+ description: 'User names, emails, or IDs.',
+ required,
+ });
+ default:
+ return Property.ShortText({ displayName, required });
+ }
+}
- for (const field of fields) {
- // Skip computed / read-only fields
- if (field.isComputed || TeableComputedFieldTypes.includes(field.type)) {
- continue;
- }
+export const TeableCommon = {
+ base_id: Property.Dropdown({
+ auth: TeableAuth,
+ displayName: 'Base',
+ required: true,
+ refreshers: [],
+ options: async ({ auth }) => {
+ if (!auth) {
+ return { disabled: true, options: [], placeholder: 'Connect your account first.' };
+ }
+ try {
+ const bases = await teableClient.listBases({ auth });
+ return {
+ disabled: false,
+ options: bases.map((b) => ({ label: b.name, value: b.id })),
+ };
+ } catch (error) {
+ return {
+ disabled: true,
+ options: [],
+ placeholder: errorPlaceholder({ prefix: 'Error loading bases', error }),
+ };
+ }
+ },
+ }),
+ table_id: Property.Dropdown({
+ auth: TeableAuth,
+ displayName: 'Table',
+ description: 'The table inside the selected base.',
+ required: true,
+ refreshers: ['base_id'],
+ options: async ({ auth, base_id }) => {
+ if (!auth || !base_id) {
+ return { disabled: true, options: [], placeholder: 'Select a base first.' };
+ }
+ try {
+ const tables = await teableClient.listTables({ auth, baseId: String(base_id) });
+ return {
+ disabled: false,
+ options: tables.map((t) => ({ label: t.name, value: t.id })),
+ };
+ } catch (error) {
+ return {
+ disabled: true,
+ options: [],
+ placeholder: errorPlaceholder({ prefix: 'Error loading tables', error }),
+ };
+ }
+ },
+ }),
+ record_id: Property.Dropdown({
+ auth: TeableAuth,
+ displayName: 'Record',
+ description:
+ 'The record to act on. Shows the first 1000 records; pass a record ID directly for larger tables.',
+ required: true,
+ refreshers: ['table_id'],
+ options: async ({ auth, table_id }) => {
+ if (!auth || !table_id) {
+ return { disabled: true, options: [], placeholder: 'Select a table first.' };
+ }
+ try {
+ const response = await teableClient.listRecords({
+ auth,
+ tableId: String(table_id),
+ query: { take: TEABLE_MAX_PAGE_SIZE },
+ });
+ return {
+ disabled: false,
+ options: response.records.map((r) => ({
+ label: typeof r.name === 'string' && r.name.length > 0 ? r.name : r.id,
+ value: r.id,
+ })),
+ };
+ } catch (error) {
+ return {
+ disabled: true,
+ options: [],
+ placeholder: errorPlaceholder({ prefix: 'Error loading records', error }),
+ };
+ }
+ },
+ }),
+ view_id: Property.Dropdown({
+ auth: TeableAuth,
+ displayName: 'View',
+ description: 'Only return records visible in this view.',
+ required: false,
+ refreshers: ['table_id'],
+ options: async ({ auth, table_id }) => {
+ if (!auth || !table_id) {
+ return { disabled: true, options: [], placeholder: 'Select a table first.' };
+ }
+ try {
+ const views = await teableClient.listViews({ auth, tableId: String(table_id) });
+ return {
+ disabled: false,
+ options: views.map((v) => ({ label: `${v.name} (${v.type})`, value: v.id })),
+ };
+ } catch (error) {
+ return {
+ disabled: true,
+ options: [],
+ placeholder: errorPlaceholder({ prefix: 'Error loading views', error }),
+ };
+ }
+ },
+ }),
+ fields: Property.DynamicProperties({
+ auth: TeableAuth,
+ displayName: 'Fields',
+ description: 'The fields to set on the record.',
+ required: true,
+ refreshers: ['auth', 'table_id'],
+ props: async ({ auth, table_id }) => {
+ if (!auth || !table_id) {
+ return {};
+ }
+ const fields = await teableClient.listFields({ auth, tableId: String(table_id) });
+ const props: DynamicPropsValue = {};
+ for (const field of fields) {
+ if (isRecordWritableField(field)) {
+ props[field.name] = buildFieldProp(field);
+ }
+ }
+ return props;
+ },
+ }),
+ fields_to_clear: Property.MultiSelectDropdown({
+ auth: TeableAuth,
+ displayName: 'Fields to Clear',
+ description: 'Fields whose value should be removed from the record.',
+ required: false,
+ refreshers: ['table_id'],
+ options: async ({ auth, table_id }) => {
+ if (!auth || !table_id) {
+ return { disabled: true, options: [], placeholder: 'Select a table first.' };
+ }
+ try {
+ const fields = await teableClient.listFields({ auth, tableId: String(table_id) });
+ return {
+ disabled: false,
+ options: fields
+ .filter((f) => isRecordWritableField(f) || f.type === TeableFieldType.ATTACHMENT)
+ .map((f) => ({ label: f.name, value: f.name })),
+ };
+ } catch (error) {
+ return {
+ disabled: true,
+ options: [],
+ placeholder: errorPlaceholder({ prefix: 'Error loading fields', error }),
+ };
+ }
+ },
+ }),
+ attachment_field_id: Property.Dropdown({
+ auth: TeableAuth,
+ displayName: 'Attachment Field',
+ description: 'The attachment field to upload the file to.',
+ required: true,
+ refreshers: ['table_id'],
+ options: async ({ auth, table_id }) => {
+ if (!auth || !table_id) {
+ return { disabled: true, options: [], placeholder: 'Select a table first.' };
+ }
+ try {
+ const fields = await teableClient.listFields({ auth, tableId: String(table_id) });
+ const attachmentFields = fields.filter((f) => f.type === TeableFieldType.ATTACHMENT);
+ if (attachmentFields.length === 0) {
+ return {
+ disabled: true,
+ options: [],
+ placeholder: 'This table has no attachment fields.',
+ };
+ }
+ return {
+ disabled: false,
+ options: attachmentFields.map((f) => ({ label: f.name, value: f.id })),
+ };
+ } catch (error) {
+ return {
+ disabled: true,
+ options: [],
+ placeholder: errorPlaceholder({ prefix: 'Error loading fields', error }),
+ };
+ }
+ },
+ }),
+};
- const choices = field.options?.choices ?? [];
+export const TeableAgentProps = {
+ base_id: Property.ShortText({
+ displayName: 'Base ID',
+ description: 'The Teable base ID. Get it from List Bases.',
+ required: true,
+ }),
+ table: Property.ShortText({
+ displayName: 'Table (name or ID)',
+ description: 'The table name or table ID. Get both from Get Base Schema (Agent).',
+ required: true,
+ }),
+ record_id: Property.ShortText({
+ displayName: 'Record ID',
+ description: 'The ID of the record, e.g. from Search Records (Agent).',
+ required: true,
+ }),
+ fields: Property.Json({
+ displayName: 'Fields',
+ description:
+ 'A JSON object keyed by field name or field ID, e.g. {"Name": "Jane", "Age": 30, "Status": "Open"}. Select fields take the option name; link and user fields take names or IDs.',
+ required: true,
+ }),
+};
- switch (field.type as TeableFieldType) {
- case TeableFieldType.CHECKBOX:
- props[field.name] = Property.Checkbox({ displayName: field.name, required: false });
- break;
- case TeableFieldType.NUMBER:
- case TeableFieldType.RATING:
- props[field.name] = Property.Number({ displayName: field.name, required: false });
- break;
- case TeableFieldType.DATE:
- props[field.name] = Property.DateTime({ displayName: field.name, required: false });
- break;
- case TeableFieldType.LONG_TEXT:
- props[field.name] = Property.LongText({ displayName: field.name, required: false });
- break;
- case TeableFieldType.MULTIPLE_SELECT:
- props[field.name] = Property.StaticMultiSelectDropdown({
- displayName: field.name,
- required: false,
- options: { options: choices.map((c) => ({ label: c.name, value: c.name })) },
- });
- break;
- case TeableFieldType.SINGLE_SELECT:
- props[field.name] = Property.StaticDropdown({
- displayName: field.name,
- required: false,
- options: { options: choices.map((c) => ({ label: c.name, value: c.name })) },
- });
- break;
- case TeableFieldType.LINK:
- case TeableFieldType.USER:
- props[field.name] = Property.Array({ displayName: field.name, required: false });
- break;
- case TeableFieldType.SINGLE_LINE_TEXT:
- default:
- props[field.name] = Property.ShortText({ displayName: field.name, required: false });
- break;
- }
- }
- return props;
- },
- }),
+export const teableProps = {
+ isRecordWritableField,
};
-// Re-export for convenience
export { TeableFieldType, TeableComputedFieldTypes };
diff --git a/packages/pieces/community/teable/src/lib/common/polling.ts b/packages/pieces/community/teable/src/lib/common/polling.ts
new file mode 100644
index 00000000000..52abcc0112f
--- /dev/null
+++ b/packages/pieces/community/teable/src/lib/common/polling.ts
@@ -0,0 +1,294 @@
+import { Store } from '@activepieces/pieces-framework';
+import { TeableRecord } from './client';
+
+async function findAnchorIndex({
+ rowCount,
+ fetchPage,
+ epochOf,
+ anchorEpoch,
+}: FindAnchorIndexParams): Promise<number> {
+ let low = 0;
+ let high = rowCount;
+ while (low < high) {
+ const middle = Math.floor((low + high) / 2);
+ const page = await fetchPage({ skip: middle, take: 1 });
+ const record = page[0];
+ if (record === undefined || epochOf(record) >= anchorEpoch) {
+ high = middle;
+ } else {
+ low = middle + 1;
+ }
+ }
+ return low;
+}
+
+// Teable sorts every list without a viewId by the requested field, then by the
+// immutable __auto_number, so rows sharing a timestamp keep a fixed order between
+// polls and the resume point is the first row after (frontier epoch, max delivered autoNumber).
+async function findResumeStart({
+ rowCount,
+ fetchPage,
+ epochOf,
+ resumeFrom,
+}: FindResumeStartParams): Promise<number> {
+ const groupStart = await findAnchorIndex({
+ rowCount,
+ fetchPage,
+ epochOf,
+ anchorEpoch: resumeFrom.epoch,
+ });
+ const maxAutoNumber = resumeFrom.autoNumber;
+ let low = groupStart;
+ let high = maxAutoNumber !== undefined ? rowCount : groupStart + resumeFrom.ids.size;
+ while (low < high) {
+ const middle = Math.floor((low + high) / 2);
+ const page = await fetchPage({ skip: middle, take: 1 });
+ const record = page[0];
+ const beyondEmittedPrefix =
+ record === undefined ||
+ epochOf(record) > resumeFrom.epoch ||
+ (epochOf(record) === resumeFrom.epoch &&
+ (maxAutoNumber !== undefined && record.autoNumber !== undefined
+ ? record.autoNumber > maxAutoNumber
+ : !resumeFrom.ids.has(record.id)));
+ if (beyondEmittedPrefix) {
+ high = middle;
+ } else {
+ low = middle + 1;
+ }
+ }
+ return low;
+}
+
+async function scanFreshRecords({
+ rowCount,
+ fetchPage,
+ epochOf,
+ lastFetchEpochMS,
+ resumeFrom,
+}: ScanFreshRecordsParams): Promise<{ records: TeableRecord[]; caughtUp: boolean }> {
+ const collected = new Map<string, TeableRecord>();
+ let anchorEpoch = resumeFrom !== undefined ? resumeFrom.epoch : lastFetchEpochMS;
+ let seenAtAnchor = resumeFrom !== undefined ? new Set(resumeFrom.ids) : new Set<string>();
+ let nextSkip: number | undefined = undefined;
+ let expectedFirstId: string | undefined = undefined;
+ let caughtUp = false;
+ let iterations = 0;
+ if (resumeFrom !== undefined) {
+ const resumeStart = await findResumeStart({ rowCount, fetchPage, epochOf, resumeFrom });
+ nextSkip = Math.max(0, resumeStart - 1);
+ }
+ while (collected.size < MAX_RECORDS_PER_POLL && iterations < MAX_SCAN_ITERATIONS) {
+ iterations += 1;
+ if (nextSkip === undefined) {
+ const anchorIndex = await findAnchorIndex({ rowCount, fetchPage, epochOf, anchorEpoch });
+ nextSkip = Math.max(0, anchorIndex - 1);
+ expectedFirstId = undefined;
+ }
+ const page = await fetchPage({ skip: nextSkip, take: TRIGGER_PAGE_SIZE });
+ if (page.length === 0) {
+ caughtUp = true;
+ break;
+ }
+ const first = page[0];
+ const continuous =
+ nextSkip === 0 ||
+ (expectedFirstId !== undefined
+ ? first.id === expectedFirstId
+ : epochOf(first) < anchorEpoch || seenAtAnchor.has(first.id));
+ if (!continuous) {
+ nextSkip = undefined;
+ continue;
+ }
+ for (const record of page) {
+ const epoch = epochOf(record);
+ if (epoch > lastFetchEpochMS && !(epoch === anchorEpoch && seenAtAnchor.has(record.id))) {
+ collected.set(record.id, record);
+ }
+ }
+ const last = page[page.length - 1];
+ const lastEpoch = epochOf(last);
+ const tieIds = page
+ .filter((record) => epochOf(record) === lastEpoch)
+ .map((record) => record.id);
+ if (lastEpoch > anchorEpoch) {
+ anchorEpoch = lastEpoch;
+ seenAtAnchor = new Set(tieIds);
+ } else if (lastEpoch === anchorEpoch) {
+ for (const id of tieIds) {
+ seenAtAnchor.add(id);
+ }
+ }
+ if (page.length < TRIGGER_PAGE_SIZE) {
+ caughtUp = true;
+ break;
+ }
+ expectedFirstId = last.id;
+ nextSkip += page.length - 1;
+ }
+ return { records: [...collected.values()], caughtUp };
+}
+
+async function resolveFrontier({
+ store,
+ storeKey,
+ lastFetchEpochMS,
+}: {
+ store: Store;
+ storeKey: string;
+ lastFetchEpochMS: number;
+}): Promise<FrontierState | undefined> {
+ const stored = await store.get<FrontierState>(storeKey);
+ if (stored === null || stored === undefined) {
+ return undefined;
+ }
+ let resolved: FrontierState = stored;
+ if (stored.pending !== undefined) {
+ const committed = stored.pending.expectedLastPoll === lastFetchEpochMS;
+ resolved = {
+ epoch: stored.epoch,
+ ids: committed ? [...new Set([...stored.ids, ...stored.pending.ids])] : stored.ids,
+ autoNumber: committed
+ ? maxDefined(stored.autoNumber, stored.pending.autoNumber)
+ : stored.autoNumber,
+ };
+ }
+ if (resolved.epoch <= lastFetchEpochMS) {
+ await store.delete(storeKey);
+ return undefined;
+ }
+ if (stored.pending !== undefined) {
+ await store.put(storeKey, resolved);
+ }
+ return resolved;
+}
+
+async function pollFreshItems({
+ store,
+ storeKey,
+ rowCount,
+ fetchPage,
+ epochOf,
+ lastFetchEpochMS,
+}: PollFreshItemsParams): Promise<{ epochMilliSeconds: number; data: TeableRecord }[]> {
+ const frontier = await resolveFrontier({ store, storeKey, lastFetchEpochMS });
+ const { records, caughtUp } = await scanFreshRecords({
+ rowCount,
+ fetchPage,
+ epochOf,
+ lastFetchEpochMS,
+ resumeFrom:
+ frontier !== undefined
+ ? { epoch: frontier.epoch, ids: new Set(frontier.ids), autoNumber: frontier.autoNumber }
+ : undefined,
+ });
+ if (caughtUp) {
+ if (frontier !== undefined) {
+ await store.delete(storeKey);
+ }
+ return records.map((record) => ({ epochMilliSeconds: epochOf(record), data: record }));
+ }
+ if (records.length === 0) {
+ return [];
+ }
+ const boundaryEpoch = records.reduce((acc, record) => Math.max(acc, epochOf(record)), 0);
+ const fullyFetched = records.filter((record) => epochOf(record) < boundaryEpoch);
+ if (fullyFetched.length > 0) {
+ return fullyFetched.map((record) => ({ epochMilliSeconds: epochOf(record), data: record }));
+ }
+ const resumeEpoch = lastFetchEpochMS + 1;
+ const sameFrontier = frontier !== undefined && frontier.epoch === boundaryEpoch;
+ const confirmedIds = sameFrontier ? frontier.ids : [];
+ const pendingIds = records.map((record) => record.id);
+ const pendingAutoNumber = maxAutoNumberOf(records);
+ if (resumeEpoch >= boundaryEpoch || confirmedIds.length + pendingIds.length > MAX_TRACKED_TIE_IDS) {
+ if (frontier !== undefined) {
+ await store.delete(storeKey);
+ }
+ return records.map((record) => ({ epochMilliSeconds: epochOf(record), data: record }));
+ }
+ await store.put(storeKey, {
+ epoch: boundaryEpoch,
+ ids: confirmedIds,
+ autoNumber: sameFrontier ? frontier.autoNumber : undefined,
+ pending: { expectedLastPoll: resumeEpoch, ids: pendingIds, autoNumber: pendingAutoNumber },
+ });
+ return records.map((record) => ({ epochMilliSeconds: resumeEpoch, data: record }));
+}
+
+function maxDefined(a: number | undefined, b: number | undefined): number | undefined {
+ if (a === undefined) {
+ return b;
+ }
+ if (b === undefined) {
+ return a;
+ }
+ return Math.max(a, b);
+}
+
+function maxAutoNumberOf(records: TeableRecord[]): number | undefined {
+ let max: number | undefined = undefined;
+ for (const record of records) {
+ if (record.autoNumber === undefined) {
+ return undefined;
+ }
+ max = maxDefined(max, record.autoNumber);
+ }
+ return max;
+}
+
+export const teablePolling = {
+ scanFreshRecords,
+ pollFreshItems,
+};
+
+export const TRIGGER_PAGE_SIZE = 500;
+export const MAX_RECORDS_PER_POLL = 5000;
+export const MAX_SCAN_ITERATIONS = 40;
+export const MAX_TRACKED_TIE_IDS = 25000;
+
+type FetchPage = (params: { skip: number; take: number }) => Promise<TeableRecord[]>;
+
+type FindAnchorIndexParams = {
+ rowCount: number;
+ fetchPage: FetchPage;
+ epochOf: (record: TeableRecord) => number;
+ anchorEpoch: number;
+};
+
+type FindResumeStartParams = {
+ rowCount: number;
+ fetchPage: FetchPage;
+ epochOf: (record: TeableRecord) => number;
+ resumeFrom: ResumeFrom;
+};
+
+type ResumeFrom = { epoch: number; ids: Set<string>; autoNumber?: number };
+
+type ScanFreshRecordsParams = {
+ rowCount: number;
+ fetchPage: FetchPage;
+ epochOf: (record: TeableRecord) => number;
+ lastFetchEpochMS: number;
+ resumeFrom?: ResumeFrom;
+};
+
+type PollFreshItemsParams = {
+ store: Store;
+ storeKey: string;
+ rowCount: number;
+ fetchPage: FetchPage;
+ epochOf: (record: TeableRecord) => number;
+ lastFetchEpochMS: number;
+};
+
+export type FrontierState = {
+ epoch: number;
+ ids: string[];
+ autoNumber?: number;
+ pending?: {
+ expectedLastPoll: number;
+ ids: string[];
+ autoNumber?: number;
+ };
+};
diff --git a/packages/pieces/community/teable/src/lib/output-schemas.ts b/packages/pieces/community/teable/src/lib/output-schemas.ts
new file mode 100644
index 00000000000..80f32059d9b
--- /dev/null
+++ b/packages/pieces/community/teable/src/lib/output-schemas.ts
@@ -0,0 +1,271 @@
+import { OutputSchema } from '@activepieces/pieces-framework';
+
+const recordFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Record ID' },
+ { key: 'name', label: 'Record Name' },
+ { key: 'fields', label: 'Fields', dynamicKey: true },
+ { key: 'autoNumber', label: 'Auto Number', format: 'number' },
+ { key: 'createdTime', label: 'Created Time', format: 'datetime' },
+ { key: 'lastModifiedTime', label: 'Last Modified Time', format: 'datetime' },
+ { key: 'createdBy', label: 'Created By' },
+ { key: 'lastModifiedBy', label: 'Last Modified By' },
+];
+
+const fieldFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Field ID' },
+ { key: 'name', label: 'Field Name' },
+ { key: 'type', label: 'Type' },
+ { key: 'description', label: 'Description' },
+ { key: 'isPrimary', label: 'Is Primary', format: 'boolean' },
+ { key: 'isComputed', label: 'Is Computed', format: 'boolean' },
+ { key: 'notNull', label: 'Required', format: 'boolean' },
+ { key: 'unique', label: 'Unique', format: 'boolean' },
+ { key: 'dbFieldName', label: 'Database Field Name' },
+];
+
+const recordCoreFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Record ID' },
+ { key: 'fields', label: 'Fields', dynamicKey: true },
+];
+
+const record: OutputSchema = {
+ fields: recordFields,
+};
+
+const recordCore: OutputSchema = {
+ fields: recordCoreFields,
+};
+
+const createRecord: OutputSchema = {
+ fields: [
+ {
+ key: 'records',
+ label: 'Created Records',
+ labelKey: 'id',
+ listItems: recordCoreFields,
+ },
+ ],
+};
+
+const listRecords: OutputSchema = {
+ fields: [
+ {
+ key: 'records',
+ label: 'Records',
+ labelKey: 'name',
+ listItems: recordFields,
+ },
+ { key: 'recordCount', label: 'Record Count', format: 'number' },
+ { key: 'hasMore', label: 'Has More', format: 'boolean' },
+ ],
+};
+
+const updatedRecords: OutputSchema = {
+ itemLabel: '{id}',
+ fields: [
+ {
+ key: 'records',
+ label: 'Updated Records',
+ value: '',
+ labelKey: 'id',
+ listItems: recordCoreFields,
+ },
+ ],
+};
+
+const deleteRecord: OutputSchema = {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'recordId', label: 'Record ID' },
+ ],
+};
+
+const deleteRecords: OutputSchema = {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'deletedCount', label: 'Deleted Count', format: 'number' },
+ { key: 'recordIds', label: 'Record IDs' },
+ ],
+};
+
+const addComment: OutputSchema = {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'recordId', label: 'Record ID' },
+ { key: 'comment', label: 'Comment' },
+ ],
+};
+
+const listBases: OutputSchema = {
+ itemLabel: '{name}',
+ fields: [
+ {
+ key: 'bases',
+ label: 'Bases',
+ value: '',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Base ID' },
+ { key: 'name', label: 'Base Name' },
+ { key: 'spaceId', label: 'Space ID' },
+ { key: 'icon', label: 'Icon' },
+ { key: 'role', label: 'Role' },
+ ],
+ },
+ ],
+};
+
+const listTables: OutputSchema = {
+ itemLabel: '{name}',
+ fields: [
+ {
+ key: 'tables',
+ label: 'Tables',
+ value: '',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Table ID' },
+ { key: 'name', label: 'Table Name' },
+ { key: 'description', label: 'Description' },
+ { key: 'defaultViewId', label: 'Default View ID' },
+ { key: 'lastModifiedTime', label: 'Last Modified Time', format: 'datetime' },
+ ],
+ },
+ ],
+};
+
+const listFields: OutputSchema = {
+ itemLabel: '{name}',
+ fields: [
+ {
+ key: 'fields',
+ label: 'Fields',
+ value: '',
+ labelKey: 'name',
+ listItems: fieldFields,
+ },
+ ],
+};
+
+const listViews: OutputSchema = {
+ itemLabel: '{name}',
+ fields: [
+ {
+ key: 'views',
+ label: 'Views',
+ value: '',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'View ID' },
+ { key: 'name', label: 'View Name' },
+ { key: 'type', label: 'Type' },
+ ],
+ },
+ ],
+};
+
+const createTable: OutputSchema = {
+ fields: [
+ { key: 'id', label: 'Table ID' },
+ { key: 'name', label: 'Table Name' },
+ { key: 'description', label: 'Description' },
+ { key: 'dbTableName', label: 'Database Table Name' },
+ { key: 'defaultViewId', label: 'Default View ID' },
+ {
+ key: 'fields',
+ label: 'Fields',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Field ID' },
+ { key: 'name', label: 'Field Name' },
+ { key: 'type', label: 'Type' },
+ { key: 'isPrimary', label: 'Is Primary', format: 'boolean' },
+ ],
+ },
+ ],
+};
+
+const createField: OutputSchema = {
+ fields: fieldFields,
+};
+
+const baseSchema: OutputSchema = {
+ fields: [
+ { key: 'baseId', label: 'Base ID' },
+ { key: 'tableCount', label: 'Table Count', format: 'number' },
+ {
+ key: 'tables',
+ label: 'Tables',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Table ID' },
+ { key: 'name', label: 'Table Name' },
+ { key: 'description', label: 'Description' },
+ {
+ key: 'fields',
+ label: 'Fields',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Field ID' },
+ { key: 'name', label: 'Field Name' },
+ { key: 'type', label: 'Type' },
+ { key: 'isPrimary', label: 'Is Primary', format: 'boolean' },
+ { key: 'writable', label: 'Writable', format: 'boolean' },
+ { key: 'notNull', label: 'Required', format: 'boolean' },
+ { key: 'unique', label: 'Unique', format: 'boolean' },
+ {
+ key: 'options',
+ label: 'Select Options',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Option ID' },
+ { key: 'name', label: 'Option Name' },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+};
+
+const upsertRecord: OutputSchema = {
+ fields: [
+ { key: 'action', label: 'Action' },
+ { key: 'record', label: 'Record', children: recordCoreFields },
+ { key: 'warning', label: 'Warning' },
+ ],
+};
+
+const searchRecords: OutputSchema = {
+ fields: [
+ {
+ key: 'records',
+ label: 'Records',
+ labelKey: 'name',
+ listItems: recordFields,
+ },
+ { key: 'recordCount', label: 'Record Count', format: 'number' },
+ { key: 'hasMore', label: 'Has More', format: 'boolean' },
+ ],
+};
+
+export const teableOutputSchemas = {
+ record,
+ recordCore,
+ createRecord,
+ listRecords,
+ updatedRecords,
+ deleteRecord,
+ deleteRecords,
+ addComment,
+ listBases,
+ listTables,
+ listFields,
+ listViews,
+ createTable,
+ createField,
+ baseSchema,
+ upsertRecord,
+ searchRecords,
+};
diff --git a/packages/pieces/community/teable/src/lib/triggers/new-record.ts b/packages/pieces/community/teable/src/lib/triggers/new-record.ts
new file mode 100644
index 00000000000..aeb2aeb250e
--- /dev/null
+++ b/packages/pieces/community/teable/src/lib/triggers/new-record.ts
@@ -0,0 +1,117 @@
+import {
+ AppConnectionValueForAuthProperty,
+ createTrigger,
+ TriggerStrategy,
+} from '@activepieces/pieces-framework';
+import { DedupeStrategy, Polling, pollingHelper } from '@activepieces/pieces-common';
+import { TeableAuth, TeableAuthValue } from '../auth';
+import { TeableCommon } from '../common';
+import { teableClient, TeableRecord } from '../common/client';
+import { teablePolling } from '../common/polling';
+import { teableOutputSchemas } from '../output-schemas';
+
+const TEST_SAMPLE_SIZE = 5;
+
+function createdEpoch(record: TeableRecord): number {
+ return record.createdTime !== undefined ? new Date(record.createdTime).getTime() : 0;
+}
+
+async function fetchTailRecords({
+ auth,
+ tableId,
+ count,
+}: {
+ auth: TeableAuthValue;
+ tableId: string;
+ count: number;
+}): Promise<TeableRecord[]> {
+ const rowCount = await teableClient.getRowCount({ auth, tableId });
+ const skip = Math.max(0, rowCount - count);
+ const page = await teableClient.listRecords({
+ auth,
+ tableId,
+ query: { take: count, skip },
+ });
+ return page.records;
+}
+
+const polling: Polling<TeableTriggerAuth, Props> = {
+ strategy: DedupeStrategy.TIMEBASED,
+ items: async ({ auth, store, propsValue, lastFetchEpochMS }) => {
+ const tableId = propsValue.table_id;
+ if (lastFetchEpochMS === 0) {
+ const sample = await fetchTailRecords({ auth, tableId, count: TEST_SAMPLE_SIZE });
+ return sample
+ .map((record) => ({ epochMilliSeconds: createdEpoch(record), data: record }))
+ .sort((a, b) => b.epochMilliSeconds - a.epochMilliSeconds);
+ }
+ const rowCount = await teableClient.getRowCount({ auth, tableId });
+ const items = await teablePolling.pollFreshItems({
+ store,
+ storeKey: 'teable_new_record_frontier',
+ rowCount,
+ fetchPage: async ({ skip, take }) => {
+ const page = await teableClient.listRecords({
+ auth,
+ tableId,
+ query: { take, skip },
+ });
+ return page.records;
+ },
+ epochOf: createdEpoch,
+ lastFetchEpochMS,
+ });
+ return items.sort((a, b) => b.epochMilliSeconds - a.epochMilliSeconds);
+ },
+};
+
+export const newRecordTrigger = createTrigger({
+ auth: TeableAuth,
+ name: 'teable_new_record',
+ classification: 'READ',
+ displayName: 'New Record',
+ description: 'Triggers when a new record is created in a table.',
+ aiMetadata: {
+ description:
+ 'Fires when a new record is created in the selected Teable table. Polls on a schedule and emits each new record once, with its field values, ID, and creation time. Large backlogs are delivered across successive polls without loss; only in the extreme case of more than 25,000 records sharing one identical creation timestamp can records beyond that bound be skipped. Delivery is at-least-once: after a platform error during a poll, the next poll may deliver some records again rather than lose them.',
+ },
+ props: {
+ base_id: TeableCommon.base_id,
+ table_id: TeableCommon.table_id,
+ },
+ sampleData: {
+ id: 'recPJvqohF1HW69vfbl',
+ fields: {
+ Name: 'AP test rec 1',
+ Count: 1,
+ Notes: 'first',
+ },
+ name: 'AP test rec 1',
+ autoNumber: 1,
+ createdTime: '2026-10-08T17:14:37.172Z',
+ lastModifiedTime: '2026-10-08T17:14:37.172Z',
+ createdBy: 'usr639NrlzGxCX1oWEb',
+ lastModifiedBy: 'usr639NrlzGxCX1oWEb',
+ },
+ outputSchema: teableOutputSchemas.record,
+ type: TriggerStrategy.POLLING,
+ async test(context) {
+ return await pollingHelper.test(polling, context);
+ },
+ async onEnable(context) {
+ await pollingHelper.onEnable(polling, context);
+ },
+ async onDisable(context) {
+ await pollingHelper.onDisable(polling, context);
+ },
+ async run(context) {
+ return await pollingHelper.poll(polling, context);
+ },
+});
+
+type TeableTriggerAuth = AppConnectionValueForAuthProperty<(typeof TeableAuth)[number]>;
+
+type Props = {
+ base_id: string;
+ table_id: string;
+};
diff --git a/packages/pieces/community/teable/src/lib/triggers/updated-record.ts b/packages/pieces/community/teable/src/lib/triggers/updated-record.ts
new file mode 100644
index 00000000000..d6ecbcbd2dd
--- /dev/null
+++ b/packages/pieces/community/teable/src/lib/triggers/updated-record.ts
@@ -0,0 +1,207 @@
+import {
+ AppConnectionValueForAuthProperty,
+ createTrigger,
+ TriggerStrategy,
+} from '@activepieces/pieces-framework';
+import { DedupeStrategy, Polling, pollingHelper } from '@activepieces/pieces-common';
+import { TeableAuth, TeableAuthValue } from '../auth';
+import { TeableCommon } from '../common';
+import { teableClient, TeableField, TeableRecord } from '../common/client';
+import { TeableFieldType } from '../common/constants';
+import { teablePolling } from '../common/polling';
+import { teableOutputSchemas } from '../output-schemas';
+
+const PAGE_SIZE = 500;
+const TEST_SAMPLE_SIZE = 5;
+const TIME_FORMATTING_NONE = 'None';
+
+function modifiedEpoch(record: TeableRecord): number {
+ const timestamp = record.lastModifiedTime ?? record.createdTime;
+ return timestamp !== undefined ? new Date(timestamp).getTime() : 0;
+}
+
+function fieldModifiedEpoch({
+ record,
+ fieldName,
+}: {
+ record: TeableRecord;
+ fieldName: string;
+}): number {
+ const value = record.fields?.[fieldName];
+ if (typeof value === 'string' || typeof value === 'number') {
+ const epoch = new Date(value).getTime();
+ if (!Number.isNaN(epoch)) {
+ return epoch;
+ }
+ }
+ return modifiedEpoch(record);
+}
+
+async function requireLastModifiedField({
+ auth,
+ tableId,
+}: {
+ auth: TeableAuthValue;
+ tableId: string;
+}): Promise<TeableField> {
+ const fields = await teableClient.listFields({ auth, tableId });
+ const lastModifiedFields = fields.filter(
+ (field) => field.type === TeableFieldType.LAST_MODIFIED_TIME
+ );
+ if (lastModifiedFields.length === 0) {
+ throw new Error(
+ 'This table has no "Last modified time" field, so updates cannot be detected. In Teable, add a field of type "Last modified time" to the table, set its time format to 24 hour or 12 hour, then enable this trigger again.'
+ );
+ }
+ const preciseField = lastModifiedFields.find(showsTimeOfDay);
+ if (preciseField === undefined) {
+ throw new Error(
+ `The "Last modified time" field "${lastModifiedFields[0].name}" hides the time of day, so Teable sorts it by date only and changes made on the same day cannot be told apart. In Teable, edit that field and set its time format to 24 hour or 12 hour, then enable this trigger again.`
+ );
+ }
+ return preciseField;
+}
+
+// Teable sorts a date field by its formatted date string when the time format is
+// None (its default), and by the exact timestamp only when the time is shown.
+function showsTimeOfDay(field: TeableField): boolean {
+ const formatting = field.options?.['formatting'];
+ if (typeof formatting !== 'object' || formatting === null || !('time' in formatting)) {
+ return false;
+ }
+ return typeof formatting.time === 'string' && formatting.time !== TIME_FORMATTING_NONE;
+}
+
+async function fetchPreciseRecords({
+ auth,
+ tableId,
+ recordIds,
+}: {
+ auth: TeableAuthValue;
+ tableId: string;
+ recordIds: string[];
+}): Promise<TeableRecord[]> {
+ const records: TeableRecord[] = [];
+ for (let start = 0; start < recordIds.length; start += PAGE_SIZE) {
+ const page = await teableClient.listRecords({
+ auth,
+ tableId,
+ query: {
+ take: PAGE_SIZE,
+ selectedRecordIds: recordIds.slice(start, start + PAGE_SIZE),
+ },
+ });
+ records.push(...page.records);
+ }
+ return records;
+}
+
+async function fetchSampleRecords({
+ auth,
+ tableId,
+ fieldId,
+}: {
+ auth: TeableAuthValue;
+ tableId: string;
+ fieldId: string;
+}): Promise<TeableRecord[]> {
+ const orderBy = JSON.stringify([{ fieldId, order: 'desc' }]);
+ const sample = await teableClient.listRecords({
+ auth,
+ tableId,
+ query: { take: TEST_SAMPLE_SIZE, orderBy },
+ });
+ return fetchPreciseRecords({
+ auth,
+ tableId,
+ recordIds: sample.records.map((record) => record.id),
+ });
+}
+
+const polling: Polling<TeableTriggerAuth, Props> = {
+ strategy: DedupeStrategy.TIMEBASED,
+ items: async ({ auth, store, propsValue, lastFetchEpochMS }) => {
+ const tableId = propsValue.table_id;
+ const lastModifiedField = await requireLastModifiedField({ auth, tableId });
+ const epochOf = (record: TeableRecord) =>
+ fieldModifiedEpoch({ record, fieldName: lastModifiedField.name });
+ if (lastFetchEpochMS === 0) {
+ const sample = await fetchSampleRecords({ auth, tableId, fieldId: lastModifiedField.id });
+ return sample
+ .map((record) => ({ epochMilliSeconds: epochOf(record), data: record }))
+ .sort((a, b) => b.epochMilliSeconds - a.epochMilliSeconds);
+ }
+ const orderBy = JSON.stringify([{ fieldId: lastModifiedField.id, order: 'asc' }]);
+ const rowCount = await teableClient.getRowCount({ auth, tableId });
+ const items = await teablePolling.pollFreshItems({
+ store,
+ storeKey: 'teable_updated_record_frontier',
+ rowCount,
+ fetchPage: async ({ skip, take }) => {
+ const page = await teableClient.listRecords({
+ auth,
+ tableId,
+ query: { take, skip, orderBy },
+ });
+ return page.records;
+ },
+ epochOf,
+ lastFetchEpochMS,
+ });
+ return items.sort((a, b) => b.epochMilliSeconds - a.epochMilliSeconds);
+ },
+};
+
+export const updatedRecordTrigger = createTrigger({
+ auth: TeableAuth,
+ name: 'teable_updated_record',
+ classification: 'READ',
+ displayName: 'Updated Record',
+ description:
+ 'Triggers when a record is created or modified. The table must have a "Last modified time" field that shows the time.',
+ aiMetadata: {
+ description:
+ 'Fires when a record in the selected Teable table is created or modified. The table must contain a field of type "Last modified time" whose time format is 24 hour or 12 hour (with no time shown, which is the Teable default, it sorts by date only); enabling the trigger, or a later poll, fails with instructions when no such field exists. A record modified again later fires again. Large backlogs are delivered across successive polls without loss; only in the extreme case of more than 25,000 records sharing one identical "Last modified time" value can records beyond that bound be skipped. Delivery is at-least-once: after a platform error during a poll, the next poll may deliver some records again rather than lose them.',
+ },
+ props: {
+ base_id: TeableCommon.base_id,
+ table_id: TeableCommon.table_id,
+ },
+ sampleData: {
+ id: 'recql6P1Rc5fWQAlCbp',
+ fields: {
+ Name: 'AP test rec 2',
+ Count: 2,
+ Notes: 'updated by builder test',
+ Rating: 5,
+ },
+ name: 'AP test rec 2',
+ autoNumber: 2,
+ createdTime: '2026-10-08T17:14:37.172Z',
+ lastModifiedTime: '2026-10-08T17:15:12.724Z',
+ createdBy: 'usr639NrlzGxCX1oWEb',
+ lastModifiedBy: 'usr639NrlzGxCX1oWEb',
+ },
+ outputSchema: teableOutputSchemas.record,
+ type: TriggerStrategy.POLLING,
+ async test(context) {
+ return await pollingHelper.test(polling, context);
+ },
+ async onEnable(context) {
+ await requireLastModifiedField({ auth: context.auth, tableId: context.propsValue.table_id });
+ await pollingHelper.onEnable(polling, context);
+ },
+ async onDisable(context) {
+ await pollingHelper.onDisable(polling, context);
+ },
+ async run(context) {
+ return await pollingHelper.poll(polling, context);
+ },
+});
+
+type TeableTriggerAuth = AppConnectionValueForAuthProperty<(typeof TeableAuth)[number]>;
+
+type Props = {
+ base_id: string;
+ table_id: string;
+};
diff --git a/packages/pieces/community/teable/test/actions.test.ts b/packages/pieces/community/teable/test/actions.test.ts
new file mode 100644
index 00000000000..ee6fdf4dd41
--- /dev/null
+++ b/packages/pieces/community/teable/test/actions.test.ts
@@ -0,0 +1,229 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { updateRecordAction } from '../src/lib/actions/update-record';
+import { createRecordAction } from '../src/lib/actions/create-record';
+import { createRecordsAction } from '../src/lib/actions/create-records';
+import { updateRecordsAction } from '../src/lib/actions/update-records';
+import { deleteRecordsAction } from '../src/lib/actions/delete-records';
+import { findRecordsAction } from '../src/lib/actions/find-records';
+import { addCommentAction } from '../src/lib/actions/add-comment';
+import { runAction } from './helpers';
+
+const sendRequest = vi.fn();
+
+vi.mock('@activepieces/pieces-common', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();
+ return {
+ ...actual,
+ httpClient: {
+ sendRequest: (...args: unknown[]) => sendRequest(...args),
+ },
+ };
+});
+
+function calls(): { method: string; url: string; body?: unknown }[] {
+ return sendRequest.mock.calls.map((c) => c[0]);
+}
+
+beforeEach(() => {
+ sendRequest.mockReset();
+});
+
+describe('Update Record (builder)', () => {
+ it('omits empty inputs, sends null for Fields to Clear, and sets typecast', async () => {
+ sendRequest.mockResolvedValueOnce({ body: { id: 'rec1', fields: {} } });
+ await runAction({
+ action: updateRecordAction,
+ propsValue: {
+ base_id: 'bse1',
+ table_id: 'tbl1',
+ record_id: 'rec1',
+ fields: { Name: 'Jane', Notes: '', Age: undefined, Done: false, Zero: 0 },
+ fields_to_clear: ['Email'],
+ },
+ });
+ expect(calls()[0]).toMatchObject({
+ method: 'PATCH',
+ body: {
+ record: { fields: { Name: 'Jane', Done: false, Zero: 0, Email: null } },
+ typecast: true,
+ },
+ });
+ });
+
+ it('refuses an update with nothing to change', async () => {
+ await expect(
+ runAction({
+ action: updateRecordAction,
+ propsValue: {
+ base_id: 'bse1',
+ table_id: 'tbl1',
+ record_id: 'rec1',
+ fields: { Name: '' },
+ fields_to_clear: [],
+ },
+ })
+ ).rejects.toThrow(/Set at least one field value or pick a field to clear/);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+});
+
+describe('Create Record (builder)', () => {
+ it('keeps the records wrapper and sends typecast', async () => {
+ sendRequest.mockResolvedValueOnce({ body: { records: [{ id: 'rec1', fields: {} }] } });
+ const output = await runAction({
+ action: createRecordAction,
+ propsValue: { base_id: 'bse1', table_id: 'tbl1', fields: { Name: 'Jane' } },
+ });
+ expect(calls()[0]).toMatchObject({
+ method: 'POST',
+ body: { records: [{ fields: { Name: 'Jane' } }], typecast: true },
+ });
+ expect(output).toEqual({ records: [{ id: 'rec1', fields: {} }] });
+ });
+
+ it('refuses an empty record', async () => {
+ await expect(
+ runAction({
+ action: createRecordAction,
+ propsValue: { base_id: 'bse1', table_id: 'tbl1', fields: {} },
+ })
+ ).rejects.toThrow(/at least one field/);
+ });
+});
+
+describe('Create Records (batch)', () => {
+ it('wraps each item in a fields object', async () => {
+ sendRequest.mockResolvedValueOnce({ body: { records: [] } });
+ await runAction({
+ action: createRecordsAction,
+ propsValue: { base_id: 'bse1', table_id: 'tbl1', records: [{ Name: 'a' }, { Name: 'b' }] },
+ });
+ expect(calls()[0].body).toMatchObject({
+ records: [{ fields: { Name: 'a' } }, { fields: { Name: 'b' } }],
+ typecast: true,
+ });
+ });
+
+ it('refuses an empty array and non-object items', async () => {
+ await expect(
+ runAction({
+ action: createRecordsAction,
+ propsValue: { base_id: 'bse1', table_id: 'tbl1', records: [] },
+ })
+ ).rejects.toThrow(/non-empty JSON array/);
+ await expect(
+ runAction({
+ action: createRecordsAction,
+ propsValue: { base_id: 'bse1', table_id: 'tbl1', records: ['nope'] },
+ })
+ ).rejects.toThrow(/item 1 must be an object/);
+ });
+});
+
+describe('Update Records (batch)', () => {
+ it('requires id and non-empty fields per item and passes nulls through', async () => {
+ sendRequest.mockResolvedValueOnce({ body: [] });
+ await runAction({
+ action: updateRecordsAction,
+ propsValue: {
+ base_id: 'bse1',
+ table_id: 'tbl1',
+ records: [{ id: 'rec1', fields: { Name: 'Jane', Notes: null } }],
+ },
+ });
+ expect(calls()[0].body).toMatchObject({
+ records: [{ id: 'rec1', fields: { Name: 'Jane', Notes: null } }],
+ typecast: true,
+ });
+ await expect(
+ runAction({
+ action: updateRecordsAction,
+ propsValue: { base_id: 'bse1', table_id: 'tbl1', records: [{ fields: { Name: 'x' } }] },
+ })
+ ).rejects.toThrow(/item 1 is missing a record "id"/);
+ await expect(
+ runAction({
+ action: updateRecordsAction,
+ propsValue: { base_id: 'bse1', table_id: 'tbl1', records: [{ id: 'rec1', fields: {} }] },
+ })
+ ).rejects.toThrow(/non-empty "fields" object/);
+ });
+});
+
+describe('Delete Records (batch)', () => {
+ it('refuses an empty ID list without calling the API', async () => {
+ await expect(
+ runAction({
+ action: deleteRecordsAction,
+ propsValue: { base_id: 'bse1', table_id: 'tbl1', recordIds: [' ', ''] },
+ })
+ ).rejects.toThrow(/at least one record ID/);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('sends repeated recordIds params and returns a per-call summary', async () => {
+ sendRequest.mockResolvedValueOnce({ body: '' });
+ const output = await runAction({
+ action: deleteRecordsAction,
+ propsValue: { base_id: 'bse1', table_id: 'tbl1', recordIds: ['rec1', 'rec2'] },
+ });
+ expect(calls()[0].url).toContain('recordIds%5B%5D=rec1&recordIds%5B%5D=rec2');
+ expect(output).toEqual({ success: true, deletedCount: 2, recordIds: ['rec1', 'rec2'] });
+ });
+});
+
+describe('List Records (builder)', () => {
+ it('validates Max Records bounds before calling the API', async () => {
+ await expect(
+ runAction({
+ action: findRecordsAction,
+ propsValue: { base_id: 'bse1', table_id: 'tbl1', take: 5001 },
+ })
+ ).rejects.toThrow(/between 1 and 5000/);
+ await expect(
+ runAction({
+ action: findRecordsAction,
+ propsValue: { base_id: 'bse1', table_id: 'tbl1', take: 0 },
+ })
+ ).rejects.toThrow(/between 1 and 5000/);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('returns records with a count and hasMore flag', async () => {
+ sendRequest.mockResolvedValueOnce({ body: { records: [{ id: 'rec1', fields: {} }] } });
+ const output = await runAction({
+ action: findRecordsAction,
+ propsValue: { base_id: 'bse1', table_id: 'tbl1', take: 100 },
+ });
+ expect(output).toEqual({
+ records: [{ id: 'rec1', fields: {} }],
+ recordCount: 1,
+ hasMore: false,
+ });
+ });
+});
+
+describe('Add Comment', () => {
+ it('wraps plain text in the Teable rich-text shape', async () => {
+ sendRequest.mockResolvedValueOnce({ body: '' });
+ const output = await runAction({
+ action: addCommentAction,
+ propsValue: { base_id: 'bse1', table_id: 'tbl1', record_id: 'rec1', comment: ' Hi there ' },
+ });
+ expect(calls()[0]).toMatchObject({
+ method: 'POST',
+ url: 'https://app.teable.ai/api/comment/tbl1/rec1/create',
+ body: { content: [{ type: 'p', children: [{ type: 'span', value: 'Hi there' }] }] },
+ });
+ expect(output).toEqual({ success: true, recordId: 'rec1', comment: 'Hi there' });
+ });
+
+ it('refuses an empty comment', async () => {
+ await expect(
+ runAction({
+ action: addCommentAction,
+ propsValue: { base_id: 'bse1', table_id: 'tbl1', record_id: 'rec1', comment: ' ' },
+ })
+ ).rejects.toThrow(/Comment must not be empty/);
+ });
+});
diff --git a/packages/pieces/community/teable/test/agent.test.ts b/packages/pieces/community/teable/test/agent.test.ts
new file mode 100644
index 00000000000..ea3ac50a942
--- /dev/null
+++ b/packages/pieces/community/teable/test/agent.test.ts
@@ -0,0 +1,357 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { teableAgent } from '../src/lib/common/agent';
+import { TeableField } from '../src/lib/common/client';
+import { upsertRecordAi } from '../src/lib/actions/upsert-record-ai';
+import { createRecordAi } from '../src/lib/actions/create-record-ai';
+import { updateRecordAi } from '../src/lib/actions/update-record-ai';
+import { runAction } from './helpers';
+
+const sendRequest = vi.fn();
+
+vi.mock('@activepieces/pieces-common', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();
+ return {
+ ...actual,
+ httpClient: {
+ sendRequest: (...args: unknown[]) => sendRequest(...args),
+ },
+ };
+});
+
+const FIELDS: TeableField[] = [
+ { id: 'fldName', name: 'Name', type: 'singleLineText', isPrimary: true },
+ { id: 'fldEmail', name: 'Email', type: 'singleLineText' },
+ { id: 'fldAge', name: 'Age', type: 'number' },
+ { id: 'fldStatus', name: 'Status', type: 'singleSelect', options: { choices: [{ id: 'c1', name: 'Open' }] } },
+ { id: 'fldTotal', name: 'Total', type: 'formula', isComputed: true },
+];
+
+const TABLES = [
+ { id: 'tblContacts', name: 'Contacts' },
+ { id: 'tblOrders', name: 'Orders' },
+ { id: 'tblDup1', name: 'Twice' },
+ { id: 'tblDup2', name: 'Twice' },
+];
+
+function calls(): { method: string; url: string; body?: unknown }[] {
+ return sendRequest.mock.calls.map((c) => c[0]);
+}
+
+beforeEach(() => {
+ sendRequest.mockReset();
+});
+
+describe('resolveTable via actions', () => {
+ it('resolves a table by name case-insensitively', async () => {
+ sendRequest.mockResolvedValueOnce({ body: TABLES });
+ sendRequest.mockResolvedValueOnce({ body: FIELDS });
+ sendRequest.mockResolvedValueOnce({
+ body: { records: [{ id: 'rec1', fields: { fldName: 'Jane' } }] },
+ });
+ const output = await runAction({
+ action: createRecordAi,
+ propsValue: { baseId: 'bse1', table: 'contacts', fields: { Name: 'Jane' } },
+ });
+ expect(calls()[2].url).toContain('/api/table/tblContacts/record');
+ expect(output).toMatchObject({ id: 'rec1', fields: { Name: 'Jane' } });
+ });
+
+ it('refuses an ambiguous table name and lists the IDs', async () => {
+ sendRequest.mockResolvedValueOnce({ body: TABLES });
+ await expect(
+ runAction({
+ action: createRecordAi,
+ propsValue: { baseId: 'bse1', table: 'Twice', fields: { Name: 'x' } },
+ })
+ ).rejects.toThrow(/2 tables are named "Twice" \(IDs: tblDup1, tblDup2\)/);
+ });
+
+ it('names the available tables when the reference does not match', async () => {
+ sendRequest.mockResolvedValueOnce({ body: TABLES });
+ await expect(
+ runAction({
+ action: createRecordAi,
+ propsValue: { baseId: 'bse1', table: 'Nope', fields: { Name: 'x' } },
+ })
+ ).rejects.toThrow(/Table "Nope" was not found in this base. Tables: Contacts \(tblContacts\)/);
+ });
+});
+
+describe('buildRecordFields', () => {
+ it('maps names case-insensitively and field IDs to field IDs', () => {
+ const values = teableAgent.buildRecordFields({
+ fields: FIELDS,
+ input: { name: 'Jane', fldEmail: '[email protected]' },
+ allowClear: false,
+ });
+ expect(values).toEqual({ fldName: 'Jane', fldEmail: '[email protected]' });
+ });
+
+ it('rejects unknown columns and lists valid names', () => {
+ expect(() =>
+ teableAgent.buildRecordFields({ fields: FIELDS, input: { Nope: 1 }, allowClear: false })
+ ).toThrow(/Column "Nope" does not exist in this table. Valid columns: Name, Email, Age, Status/);
+ });
+
+ it('rejects computed columns', () => {
+ expect(() =>
+ teableAgent.buildRecordFields({ fields: FIELDS, input: { Total: 1 }, allowClear: false })
+ ).toThrow(/Column "Total" \(formula\) cannot be written/);
+ });
+
+ it('rejects the same column given twice', () => {
+ expect(() =>
+ teableAgent.buildRecordFields({
+ fields: FIELDS,
+ input: { Name: 'a', fldName: 'b' },
+ allowClear: false,
+ })
+ ).toThrow(/Column "Name" is given more than once/);
+ });
+
+ it('skips nulls on create but sends them on update (clear vs omit)', () => {
+ expect(() =>
+ teableAgent.buildRecordFields({ fields: FIELDS, input: { Name: null }, allowClear: false })
+ ).toThrow(/Fields is empty/);
+ const cleared = teableAgent.buildRecordFields({
+ fields: FIELDS,
+ input: { Name: null, Email: '' },
+ allowClear: true,
+ });
+ expect(cleared).toEqual({ fldName: null, fldEmail: null });
+ });
+
+ it('refuses an empty update', () => {
+ expect(() =>
+ teableAgent.buildRecordFields({ fields: FIELDS, input: {}, allowClear: true })
+ ).toThrow(/Fields is empty/);
+ });
+});
+
+describe('update_record_ai', () => {
+ it('sends typecast and field IDs, and clears nulls', async () => {
+ sendRequest.mockResolvedValueOnce({ body: TABLES });
+ sendRequest.mockResolvedValueOnce({ body: FIELDS });
+ sendRequest.mockResolvedValueOnce({
+ body: { id: 'rec1', fields: { fldName: 'Jane', fldEmail: null } },
+ });
+ await runAction({
+ action: updateRecordAi,
+ propsValue: {
+ baseId: 'bse1',
+ table: 'Contacts',
+ recordId: 'rec1',
+ fields: { Name: 'Jane', Email: null },
+ },
+ });
+ expect(calls()[2]).toMatchObject({
+ method: 'PATCH',
+ body: {
+ record: { fields: { fldName: 'Jane', fldEmail: null } },
+ fieldKeyType: 'id',
+ typecast: true,
+ },
+ });
+ });
+});
+
+describe('upsert_record_ai branches', () => {
+ function mockUpsertLookup(records: unknown[]) {
+ sendRequest.mockResolvedValueOnce({ body: TABLES });
+ sendRequest.mockResolvedValueOnce({ body: FIELDS });
+ sendRequest.mockResolvedValueOnce({ body: { records } });
+ }
+
+ it('creates when no record matches and rechecks the key afterwards', async () => {
+ mockUpsertLookup([]);
+ sendRequest.mockResolvedValueOnce({
+ body: { records: [{ id: 'recNew', fields: { fldEmail: '[email protected]' } }] },
+ });
+ sendRequest.mockResolvedValueOnce({
+ body: { records: [{ id: 'recNew', fields: { fldEmail: '[email protected]' } }] },
+ });
+ const output = await runAction({
+ action: upsertRecordAi,
+ propsValue: {
+ baseId: 'bse1',
+ table: 'Contacts',
+ keyColumn: 'Email',
+ fields: { Email: '[email protected]', Name: 'Jane' },
+ },
+ });
+ expect(output).toMatchObject({ action: 'created', record: { id: 'recNew' } });
+ expect(output).not.toHaveProperty('warning');
+ expect(calls()[3].method).toBe('POST');
+ const lookupUrl = calls()[2].url;
+ expect(lookupUrl).toContain('take=2');
+ expect(lookupUrl).toContain(encodeURIComponent('"fieldId":"fldEmail"'));
+ expect(calls()[4].url).toContain(encodeURIComponent('"fieldId":"fldEmail"'));
+ });
+
+ it('drops null values on the create branch', async () => {
+ mockUpsertLookup([]);
+ sendRequest.mockResolvedValueOnce({
+ body: { records: [{ id: 'recNew', fields: { fldEmail: '[email protected]' } }] },
+ });
+ sendRequest.mockResolvedValueOnce({
+ body: { records: [{ id: 'recNew', fields: { fldEmail: '[email protected]' } }] },
+ });
+ await runAction({
+ action: upsertRecordAi,
+ propsValue: {
+ baseId: 'bse1',
+ table: 'Contacts',
+ keyColumn: 'Email',
+ fields: { Email: '[email protected]', Name: null },
+ },
+ });
+ expect(calls()[3].body).toMatchObject({
+ records: [{ fields: { fldEmail: '[email protected]' } }],
+ });
+ const createFields = (calls()[3].body as { records: { fields: object }[] }).records[0]
+ .fields;
+ expect(createFields).not.toHaveProperty('fldName');
+ });
+
+ it('still returns the created record when the duplicate recheck fails', async () => {
+ mockUpsertLookup([]);
+ sendRequest.mockResolvedValueOnce({
+ body: { records: [{ id: 'recNew', fields: { fldEmail: '[email protected]' } }] },
+ });
+ sendRequest.mockRejectedValueOnce(new Error('429 Too Many Requests'));
+ const output = await runAction({
+ action: upsertRecordAi,
+ propsValue: {
+ baseId: 'bse1',
+ table: 'Contacts',
+ keyColumn: 'Email',
+ fields: { Email: '[email protected]' },
+ },
+ });
+ expect(output).toMatchObject({
+ action: 'created',
+ record: { id: 'recNew' },
+ warning: expect.stringMatching(/duplicate check could not run/),
+ });
+ });
+
+ it('warns when a parallel upsert double-created the key', async () => {
+ mockUpsertLookup([]);
+ sendRequest.mockResolvedValueOnce({
+ body: { records: [{ id: 'recNew', fields: { fldEmail: '[email protected]' } }] },
+ });
+ sendRequest.mockResolvedValueOnce({
+ body: {
+ records: [
+ { id: 'recNew', fields: {} },
+ { id: 'recOther', fields: {} },
+ ],
+ },
+ });
+ const output = await runAction({
+ action: upsertRecordAi,
+ propsValue: {
+ baseId: 'bse1',
+ table: 'Contacts',
+ keyColumn: 'Email',
+ fields: { Email: '[email protected]' },
+ },
+ });
+ expect(output).toMatchObject({
+ action: 'created',
+ warning: expect.stringMatching(/More than one record now matches Email/),
+ });
+ });
+
+ it('updates when exactly one record matches', async () => {
+ mockUpsertLookup([{ id: 'rec1', fields: {} }]);
+ sendRequest.mockResolvedValueOnce({ body: { id: 'rec1', fields: { fldEmail: '[email protected]' } } });
+ const output = await runAction({
+ action: upsertRecordAi,
+ propsValue: {
+ baseId: 'bse1',
+ table: 'Contacts',
+ keyColumn: 'Email',
+ fields: { Email: '[email protected]', Name: 'Jane' },
+ },
+ });
+ expect(output).toMatchObject({ action: 'updated', record: { id: 'rec1' } });
+ expect(calls()[3].method).toBe('PATCH');
+ expect(calls()[3].url).toContain('/record/rec1');
+ });
+
+ it('clears null values on the update branch', async () => {
+ mockUpsertLookup([{ id: 'rec1', fields: {} }]);
+ sendRequest.mockResolvedValueOnce({
+ body: { id: 'rec1', fields: { fldEmail: '[email protected]', fldName: null } },
+ });
+ await runAction({
+ action: upsertRecordAi,
+ propsValue: {
+ baseId: 'bse1',
+ table: 'Contacts',
+ keyColumn: 'Email',
+ fields: { Email: '[email protected]', Name: null },
+ },
+ });
+ expect(calls()[3]).toMatchObject({
+ method: 'PATCH',
+ body: {
+ record: { fields: { fldEmail: '[email protected]', fldName: null } },
+ fieldKeyType: 'id',
+ typecast: true,
+ },
+ });
+ });
+
+ it('refuses a null key value', async () => {
+ sendRequest.mockResolvedValueOnce({ body: TABLES });
+ sendRequest.mockResolvedValueOnce({ body: FIELDS });
+ await expect(
+ runAction({
+ action: upsertRecordAi,
+ propsValue: {
+ baseId: 'bse1',
+ table: 'Contacts',
+ keyColumn: 'Email',
+ fields: { Email: null, Name: 'Jane' },
+ },
+ })
+ ).rejects.toThrow(/Fields must include a value for the key column "Email"/);
+ });
+
+ it('refuses when several records match', async () => {
+ mockUpsertLookup([
+ { id: 'rec1', fields: {} },
+ { id: 'rec2', fields: {} },
+ ]);
+ await expect(
+ runAction({
+ action: upsertRecordAi,
+ propsValue: {
+ baseId: 'bse1',
+ table: 'Contacts',
+ keyColumn: 'Email',
+ fields: { Email: '[email protected]' },
+ },
+ })
+ ).rejects.toThrow(/More than one record matches Email/);
+ expect(calls()).toHaveLength(3);
+ });
+
+ it('requires the key value in Fields', async () => {
+ sendRequest.mockResolvedValueOnce({ body: TABLES });
+ sendRequest.mockResolvedValueOnce({ body: FIELDS });
+ await expect(
+ runAction({
+ action: upsertRecordAi,
+ propsValue: {
+ baseId: 'bse1',
+ table: 'Contacts',
+ keyColumn: 'Email',
+ fields: { Name: 'Jane' },
+ },
+ })
+ ).rejects.toThrow(/Fields must include a value for the key column "Email"/);
+ });
+});
diff --git a/packages/pieces/community/teable/test/auth.test.ts b/packages/pieces/community/teable/test/auth.test.ts
new file mode 100644
index 00000000000..92ee19f1c82
--- /dev/null
+++ b/packages/pieces/community/teable/test/auth.test.ts
@@ -0,0 +1,98 @@
+import { describe, expect, it } from 'vitest';
+import { AppConnectionType } from '@activepieces/pieces-framework';
+import { teableAuthUtil, TeableAuthValue } from '../src/lib/auth';
+
+describe('normalizeBaseUrl', () => {
+ it('defaults to Teable Cloud when empty', () => {
+ expect(teableAuthUtil.normalizeBaseUrl(undefined)).toBe('https://app.teable.ai');
+ expect(teableAuthUtil.normalizeBaseUrl('')).toBe('https://app.teable.ai');
+ expect(teableAuthUtil.normalizeBaseUrl(' ')).toBe('https://app.teable.ai');
+ });
+
+ it('trims and strips trailing slashes', () => {
+ expect(teableAuthUtil.normalizeBaseUrl(' https://app.teable.ai/ ')).toBe('https://app.teable.ai');
+ expect(teableAuthUtil.normalizeBaseUrl('https://teable.example.com///')).toBe('https://teable.example.com');
+ });
+
+ it('strips a trailing /api', () => {
+ expect(teableAuthUtil.normalizeBaseUrl('https://teable.example.com/api')).toBe('https://teable.example.com');
+ expect(teableAuthUtil.normalizeBaseUrl('https://teable.example.com/api/')).toBe('https://teable.example.com');
+ });
+
+ it('keeps a custom port', () => {
+ expect(teableAuthUtil.normalizeBaseUrl('http://localhost:3000')).toBe('http://localhost:3000');
+ });
+
+ it('rejects a URL without a scheme', () => {
+ expect(() => teableAuthUtil.normalizeBaseUrl('app.teable.ai')).toThrow(/scheme/);
+ });
+
+ it('rejects non-http schemes', () => {
+ expect(() => teableAuthUtil.normalizeBaseUrl('ftp://teable.example.com')).toThrow(/http/);
+ });
+
+ it('rejects embedded credentials', () => {
+ expect(() => teableAuthUtil.normalizeBaseUrl('https://user:[email protected]')).toThrow(
+ /credentials/
+ );
+ });
+
+ it('rejects paths beyond /api', () => {
+ expect(() => teableAuthUtil.normalizeBaseUrl('https://teable.example.com/tenant1')).toThrow(/path/);
+ expect(() => teableAuthUtil.normalizeBaseUrl('https://teable.example.com/../x')).toThrow(/path/);
+ });
+
+ it('neutralizes dot segments through URL normalization', () => {
+ expect(teableAuthUtil.normalizeBaseUrl('https://teable.example.com/..')).toBe(
+ 'https://teable.example.com'
+ );
+ });
+
+ it('rejects query strings and fragments', () => {
+ expect(() => teableAuthUtil.normalizeBaseUrl('https://teable.example.com/?x=1')).toThrow(
+ /query/
+ );
+ });
+});
+
+describe('getToken / getBaseUrl', () => {
+ const oauthTypes = [
+ AppConnectionType.OAUTH2,
+ AppConnectionType.CLOUD_OAUTH2,
+ AppConnectionType.PLATFORM_OAUTH2,
+ ] as const;
+
+ it.each(oauthTypes)('reads access_token and cloud URL for %s connections', (type) => {
+ const auth: TeableAuthValue = { type, access_token: 'oauth-token' };
+ expect(teableAuthUtil.getToken(auth)).toBe('oauth-token');
+ expect(teableAuthUtil.getBaseUrl(auth)).toBe('https://app.teable.ai');
+ });
+
+ it('reads the PAT and normalized base URL for CUSTOM_AUTH connections', () => {
+ const auth: TeableAuthValue = {
+ type: AppConnectionType.CUSTOM_AUTH,
+ props: { token: ' pat-token ', baseUrl: 'https://teable.example.com/' },
+ };
+ expect(teableAuthUtil.getToken(auth)).toBe('pat-token');
+ expect(teableAuthUtil.getBaseUrl(auth)).toBe('https://teable.example.com');
+ });
+
+ it('defaults CUSTOM_AUTH without a base URL to Teable Cloud', () => {
+ const auth: TeableAuthValue = {
+ type: AppConnectionType.CUSTOM_AUTH,
+ props: { token: 'pat-token' },
+ };
+ expect(teableAuthUtil.getBaseUrl(auth)).toBe('https://app.teable.ai');
+ });
+});
+
+describe('normalizeBaseUrl pasted app URLs', () => {
+ it('strips a pasted Teable app path down to the origin', () => {
+ expect(teableAuthUtil.normalizeBaseUrl('https://app.teable.ai/base/bseXXXXXXXXXXXXXXXX')).toBe(
+ 'https://app.teable.ai'
+ );
+ expect(teableAuthUtil.normalizeBaseUrl('https://teable.example.com/space/spcX')).toBe(
+ 'https://teable.example.com'
+ );
+ });
+});
diff --git a/packages/pieces/community/teable/test/client.test.ts b/packages/pieces/community/teable/test/client.test.ts
new file mode 100644
index 00000000000..50dff45bcb1
--- /dev/null
+++ b/packages/pieces/community/teable/test/client.test.ts
@@ -0,0 +1,135 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { teableClient, TeableRecord } from '../src/lib/common/client';
+import { PAT_AUTH, patAuthWithBaseUrl } from './helpers';
+
+const sendRequest = vi.fn();
+
+vi.mock('@activepieces/pieces-common', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();
+ return {
+ ...actual,
+ httpClient: {
+ sendRequest: (...args: unknown[]) => sendRequest(...args),
+ },
+ };
+});
+
+function makeRecords({ count, offset }: { count: number; offset: number }): TeableRecord[] {
+ return Array.from({ length: count }, (_, i) => ({
+ id: `rec${offset + i}`,
+ fields: { Name: `row ${offset + i}` },
+ }));
+}
+
+function requestUrls(): string[] {
+ return sendRequest.mock.calls.map((c) => c[0].url);
+}
+
+beforeEach(() => {
+ sendRequest.mockReset();
+});
+
+describe('buildQueryString', () => {
+ it('skips empty values and repeats array params with bracket keys', () => {
+ const query = teableClient.buildQueryString({
+ take: 10,
+ skip: 0,
+ filter: undefined,
+ search: '',
+ viewId: null,
+ selectedRecordIds: ['a', 'b'],
+ empty: [],
+ });
+ expect(query).toBe('?take=10&skip=0&selectedRecordIds%5B%5D=a&selectedRecordIds%5B%5D=b');
+ });
+
+ it('returns an empty string when nothing is set', () => {
+ expect(teableClient.buildQueryString({})).toBe('');
+ expect(teableClient.buildQueryString(undefined)).toBe('');
+ });
+});
+
+describe('request URLs stay on the connection host', () => {
+ it('targets the normalized self-hosted origin', async () => {
+ sendRequest.mockResolvedValueOnce({ body: [] });
+ await teableClient.listBases({ auth: patAuthWithBaseUrl('https://teable.example.com/') });
+ expect(requestUrls()).toEqual(['https://teable.example.com/api/base/access/all']);
+ });
+
+ it('URL-encodes path segments', async () => {
+ sendRequest.mockResolvedValueOnce({ body: { records: [] } });
+ await teableClient.listRecords({ auth: PAT_AUTH, tableId: 'tbl/..' });
+ expect(requestUrls()[0]).toBe('https://app.teable.ai/api/table/tbl%2F../record');
+ });
+});
+
+describe('listRecordsPaged', () => {
+ it('pages until the cap and reports hasMore from a lookahead', async () => {
+ sendRequest.mockResolvedValueOnce({ body: { records: makeRecords({ count: 1000, offset: 0 }) } });
+ sendRequest.mockResolvedValueOnce({ body: { records: makeRecords({ count: 500, offset: 1000 }) } });
+ sendRequest.mockResolvedValueOnce({ body: { records: makeRecords({ count: 1, offset: 1500 }) } });
+ const result = await teableClient.listRecordsPaged({
+ auth: PAT_AUTH,
+ tableId: 'tbl1',
+ maxRecords: 1500,
+ });
+ expect(result.records).toHaveLength(1500);
+ expect(result.hasMore).toBe(true);
+ expect(requestUrls()[0]).toContain('take=1000');
+ expect(requestUrls()[0]).toContain('skip=0');
+ expect(requestUrls()[1]).toContain('take=500');
+ expect(requestUrls()[1]).toContain('skip=1000');
+ expect(requestUrls()[2]).toContain('take=1');
+ });
+
+ it('stops early when a page comes back short', async () => {
+ sendRequest.mockResolvedValueOnce({ body: { records: makeRecords({ count: 42, offset: 0 }) } });
+ const result = await teableClient.listRecordsPaged({
+ auth: PAT_AUTH,
+ tableId: 'tbl1',
+ maxRecords: 500,
+ });
+ expect(result.records).toHaveLength(42);
+ expect(result.hasMore).toBe(false);
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ });
+
+ it('honors a skip offset', async () => {
+ sendRequest.mockResolvedValueOnce({ body: { records: [] } });
+ await teableClient.listRecordsPaged({
+ auth: PAT_AUTH,
+ tableId: 'tbl1',
+ maxRecords: 10,
+ skip: 30,
+ });
+ expect(requestUrls()[0]).toContain('skip=30');
+ });
+});
+
+describe('deleteRecord', () => {
+ it('maps a 404 to a clear error without leaking the token', async () => {
+ const { HttpError } = await import('@activepieces/pieces-common');
+ sendRequest.mockRejectedValueOnce(
+ new HttpError({ secret: 'request' }, { status: 404, responseBody: { message: 'not found' } })
+ );
+ await expect(
+ teableClient.deleteRecord({ auth: PAT_AUTH, tableId: 'tbl1', recordId: 'rec1' })
+ ).rejects.toThrow('Record rec1 was not found in table tbl1. It may already be deleted.');
+ try {
+ sendRequest.mockRejectedValueOnce(
+ new HttpError({}, { status: 404, responseBody: {} })
+ );
+ await teableClient.deleteRecord({ auth: PAT_AUTH, tableId: 'tbl1', recordId: 'rec1' });
+ } catch (e) {
+ expect(e instanceof Error ? e.message : '').not.toContain('teable_test_token');
+ }
+ });
+
+ it('rethrows other errors untouched', async () => {
+ const { HttpError } = await import('@activepieces/pieces-common');
+ sendRequest.mockRejectedValueOnce(new HttpError({}, { status: 500, responseBody: {} }));
+ await expect(
+ teableClient.deleteRecord({ auth: PAT_AUTH, tableId: 'tbl1', recordId: 'rec1' })
+ ).rejects.toBeInstanceOf(HttpError);
+ });
+});
diff --git a/packages/pieces/community/teable/test/helpers.ts b/packages/pieces/community/teable/test/helpers.ts
new file mode 100644
index 00000000000..01b66625a2e
--- /dev/null
+++ b/packages/pieces/community/teable/test/helpers.ts
@@ -0,0 +1,43 @@
+import {
+ ActionContext,
+ AppConnectionType,
+ AppConnectionValueForAuthProperty,
+ createMockActionContext,
+ InputPropertyMap,
+ StaticPropsValue,
+} from '@activepieces/pieces-framework';
+import { TeableAuth } from '../src/lib/auth';
+
+export const PAT_AUTH: TeableConnectionValue = {
+ type: AppConnectionType.CUSTOM_AUTH,
+ props: { token: 'teable_test_token', baseUrl: undefined },
+};
+
+export function patAuthWithBaseUrl(baseUrl: string): TeableConnectionValue {
+ return {
+ type: AppConnectionType.CUSTOM_AUTH,
+ props: { token: 'teable_test_token', baseUrl },
+ };
+}
+
+export function runAction({ action, propsValue, auth }: RunActionParams): Promise<unknown> {
+ const base = createMockActionContext<InputPropertyMap>({ propsValue });
+ const context: TeableActionContext = { ...base, auth: auth ?? PAT_AUTH };
+ return action.run(context);
+}
+
+export type TeableConnectionValue = AppConnectionValueForAuthProperty<
+ (typeof TeableAuth)[number]
+>;
+
+type TeableActionContext = ActionContext<(typeof TeableAuth)[number], InputPropertyMap>;
+
+export type TestAction = {
+ run(context: TeableActionContext): Promise<unknown>;
+};
+
+type RunActionParams = {
+ action: TestAction;
+ propsValue: StaticPropsValue<InputPropertyMap>;
+ auth?: TeableConnectionValue;
+};
diff --git a/packages/pieces/community/teable/test/triggers.test.ts b/packages/pieces/community/teable/test/triggers.test.ts
new file mode 100644
index 00000000000..c06cb9e5956
--- /dev/null
+++ b/packages/pieces/community/teable/test/triggers.test.ts
@@ -0,0 +1,520 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ createMockPollingTriggerContext,
+ InputPropertyMap,
+ Store,
+} from '@activepieces/pieces-framework';
+import { teableClient, TeableRecord } from '../src/lib/common/client';
+import { newRecordTrigger } from '../src/lib/triggers/new-record';
+import { updatedRecordTrigger } from '../src/lib/triggers/updated-record';
+import { PAT_AUTH } from './helpers';
+
+const BASE_EPOCH = Date.parse('2026-10-01T00:00:00.000Z');
+
+const LAST_MODIFIED_FIELD = {
+ id: 'fldLM',
+ name: 'LastModified',
+ type: 'lastModifiedTime',
+ options: { formatting: { date: 'YYYY-MM-DD', time: 'HH:mm', timeZone: 'UTC' } },
+};
+
+function iso(epoch: number): string {
+ return new Date(epoch).toISOString();
+}
+
+function makeRecords(count: number): TeableRecord[] {
+ return Array.from({ length: count }, (_, index) => {
+ const epoch = BASE_EPOCH + index * 1000;
+ return {
+ id: `rec${index}`,
+ fields: { LastModified: iso(epoch) },
+ createdTime: iso(epoch),
+ lastModifiedTime: iso(epoch),
+ autoNumber: index + 1,
+ };
+ });
+}
+
+function memoryStore(initial: Record<string, unknown>): Store {
+ const data = new Map<string, unknown>(Object.entries(initial));
+ return {
+ put: async (key, value) => {
+ data.set(key, value);
+ return value;
+ },
+ get: async (key) => {
+ const value = data.has(key) ? data.get(key) : null;
+ return value as never;
+ },
+ delete: async (key) => {
+ data.delete(key);
+ },
+ };
+}
+
+function pollContext({ store }: { store: Store }) {
+ const base = createMockPollingTriggerContext<InputPropertyMap>({
+ propsValue: { base_id: 'bse1', table_id: 'tbl1' },
+ });
+ return { ...base, auth: PAT_AUTH, store };
+}
+
+function mockListRecords(
+ records: TeableRecord[] | (() => TeableRecord[]),
+ beforeCall?: (query: Record<string, unknown> | undefined) => void
+) {
+ return vi
+ .spyOn(teableClient, 'listRecords')
+ .mockImplementation(async ({ query }) => {
+ beforeCall?.(query);
+ const stored = typeof records === 'function' ? records() : records;
+ let rows = [...stored].sort((a, b) => (a.autoNumber ?? 0) - (b.autoNumber ?? 0));
+ const orderBy = query?.['orderBy'];
+ if (typeof orderBy === 'string') {
+ const [{ order }] = JSON.parse(orderBy) as { order: 'asc' | 'desc' }[];
+ rows.sort(
+ (a, b) =>
+ Date.parse(a.lastModifiedTime ?? '') - Date.parse(b.lastModifiedTime ?? '')
+ );
+ if (order === 'desc') {
+ rows.reverse();
+ }
+ }
+ const selected = query?.['selectedRecordIds'];
+ if (Array.isArray(selected)) {
+ rows = rows.filter((row) => selected.includes(row.id));
+ }
+ const skip = typeof query?.['skip'] === 'number' ? query['skip'] : 0;
+ const take = typeof query?.['take'] === 'number' ? query['take'] : rows.length;
+ return { records: rows.slice(skip, skip + take) };
+ });
+}
+
+type DeliveredRecord = { id: string };
+
+type FrontierSnapshot = {
+ epoch: number;
+ ids: string[];
+ autoNumber?: number;
+ pending?: { expectedLastPoll: number; ids: string[]; autoNumber?: number };
+};
+
+function failingPutStore({
+ inner,
+ failures,
+}: {
+ inner: Store;
+ failures: Map<string, 'reject' | 'write-then-reject'>;
+}): Store {
+ return {
+ put: async (key, value) => {
+ const mode = failures.get(key);
+ if (mode !== undefined) {
+ failures.delete(key);
+ if (mode === 'reject') {
+ throw new Error(`simulated put failure for ${key}`);
+ }
+ await inner.put(key, value);
+ throw new Error(`simulated crash after writing ${key}`);
+ }
+ return inner.put(key, value);
+ },
+ get: (key) => inner.get(key),
+ delete: (key) => inner.delete(key),
+ };
+}
+
+async function runPoll(trigger: {
+ run(context: ReturnType<typeof pollContext>): Promise<unknown[]>;
+}, store: Store): Promise<DeliveredRecord[]> {
+ const delivered = await trigger.run(pollContext({ store }));
+ return delivered as DeliveredRecord[];
+}
+
+beforeEach(() => {
+ vi.restoreAllMocks();
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+function makeTieRecords({
+ count,
+ epoch,
+ startIndex = 0,
+}: {
+ count: number;
+ epoch: number;
+ startIndex?: number;
+}): TeableRecord[] {
+ return Array.from({ length: count }, (_, offset) => {
+ const index = startIndex + offset;
+ return {
+ id: `rec${index}`,
+ fields: { LastModified: iso(epoch) },
+ createdTime: iso(epoch),
+ lastModifiedTime: iso(epoch),
+ autoNumber: index + 1,
+ };
+ });
+}
+
+describe('same-timestamp group larger than the poll cap', () => {
+ const TIE_EPOCH = BASE_EPOCH + 10_000;
+
+ it('new record trigger resumes inside the group across polls and loses nothing', async () => {
+ const records = makeTieRecords({ count: 12500, epoch: TIE_EPOCH });
+ vi.spyOn(teableClient, 'getRowCount').mockResolvedValue(records.length);
+ mockListRecords(records);
+ const store = memoryStore({ lastPoll: BASE_EPOCH });
+
+ const poll1 = await runPoll(newRecordTrigger, store);
+ const frontier1 = await store.get<FrontierSnapshot>('teable_new_record_frontier');
+ expect(frontier1?.epoch).toBe(TIE_EPOCH);
+ expect(frontier1?.ids).toHaveLength(0);
+ expect(frontier1?.pending?.ids).toHaveLength(poll1.length);
+ expect(frontier1?.pending?.expectedLastPoll).toBe(BASE_EPOCH + 1);
+
+ const poll2 = await runPoll(newRecordTrigger, store);
+ const frontier2 = await store.get<FrontierSnapshot>('teable_new_record_frontier');
+ expect(frontier2?.ids).toHaveLength(poll1.length);
+ expect(frontier2?.pending?.ids).toHaveLength(poll2.length);
+
+ const poll3 = await runPoll(newRecordTrigger, store);
+ expect(await store.get('teable_new_record_frontier')).toBeNull();
+
+ const ids = [...poll1, ...poll2, ...poll3].map((record) => record.id);
+ expect(ids.length).toBe(12500);
+ expect(new Set(ids).size).toBe(12500);
+ expect(await runPoll(newRecordTrigger, store)).toEqual([]);
+ });
+
+ it('updated record trigger fires newer records only after the group completes', async () => {
+ const group = makeTieRecords({ count: 12500, epoch: TIE_EPOCH });
+ const newer = Array.from({ length: 100 }, (_, offset) => {
+ const epoch = TIE_EPOCH + (offset + 1) * 1000;
+ return {
+ id: `newer${offset}`,
+ fields: { LastModified: iso(epoch) },
+ createdTime: iso(epoch),
+ lastModifiedTime: iso(epoch),
+ };
+ });
+ const records = [...group, ...newer];
+ vi.spyOn(teableClient, 'getRowCount').mockResolvedValue(records.length);
+ vi.spyOn(teableClient, 'listFields').mockResolvedValue([
+ LAST_MODIFIED_FIELD,
+ ]);
+ mockListRecords(records);
+ const store = memoryStore({ lastPoll: BASE_EPOCH });
+
+ const poll1 = await runPoll(updatedRecordTrigger, store);
+ const poll2 = await runPoll(updatedRecordTrigger, store);
+ expect([...poll1, ...poll2].some((record) => record.id.startsWith('newer'))).toBe(false);
+ expect(
+ (await store.get<{ epoch: number }>('teable_updated_record_frontier'))?.epoch
+ ).toBe(TIE_EPOCH);
+
+ const poll3 = await runPoll(updatedRecordTrigger, store);
+ expect(poll3.filter((record) => record.id.startsWith('newer'))).toHaveLength(100);
+ expect(await store.get('teable_updated_record_frontier')).toBeNull();
+
+ const ids = [...poll1, ...poll2, ...poll3].map((record) => record.id);
+ expect(ids.length).toBe(12600);
+ expect(new Set(ids).size).toBe(12600);
+ expect(await runPoll(updatedRecordTrigger, store)).toEqual([]);
+ });
+});
+
+function shuffled<T>(items: T[], seed: number): T[] {
+ const result = [...items];
+ let state = seed;
+ for (let index = result.length - 1; index > 0; index -= 1) {
+ state = (state * 1103515245 + 12345) % 2147483648;
+ const swap = state % (index + 1);
+ [result[index], result[swap]] = [result[swap], result[index]];
+ }
+ return result;
+}
+
+describe('tie order between polls', () => {
+ it('loses nothing when tied rows come back from storage in a different order each poll', async () => {
+ const tied = makeTieRecords({ count: 12000, epoch: BASE_EPOCH + 10_000 });
+ const newer = makeTieRecords({ count: 50, epoch: BASE_EPOCH + 20_000, startIndex: 12000 });
+ let storage = [...tied, ...newer];
+ vi.spyOn(teableClient, 'getRowCount').mockResolvedValue(storage.length);
+ vi.spyOn(teableClient, 'listFields').mockResolvedValue([
+ LAST_MODIFIED_FIELD,
+ ]);
+ const queries: (Record<string, unknown> | undefined)[] = [];
+ mockListRecords(
+ () => storage,
+ (query) => queries.push(query)
+ );
+
+ for (const [trigger, storeKey] of [
+ [newRecordTrigger, 'teable_new_record_frontier'],
+ [updatedRecordTrigger, 'teable_updated_record_frontier'],
+ ] as const) {
+ const store = memoryStore({ lastPoll: BASE_EPOCH });
+ const polls: DeliveredRecord[][] = [];
+ for (let round = 0; round < 8; round += 1) {
+ storage = shuffled(storage, round + 1);
+ const poll = await runPoll(trigger, store);
+ if (poll.length === 0) {
+ break;
+ }
+ polls.push(poll);
+ const frontier = await store.get<FrontierSnapshot>(storeKey);
+ if (frontier !== null) {
+ expect(frontier.pending?.autoNumber).toBe(
+ Math.max(...poll.map((record) => Number(record.id.slice(3)) + 1))
+ );
+ }
+ }
+ const ids = polls.flat().map((record) => record.id);
+ expect(ids.length).toBe(12050);
+ expect(new Set(ids).size).toBe(12050);
+ }
+ expect(queries.every((query) => query?.['viewId'] === undefined)).toBe(true);
+ });
+});
+
+describe('at-least-once delivery', () => {
+ const TIE_EPOCH = BASE_EPOCH + 10_000;
+
+ it('re-emits the chunk when the checkpoint write fails, then confirms it', async () => {
+ const records = makeTieRecords({ count: 7000, epoch: TIE_EPOCH });
+ vi.spyOn(teableClient, 'getRowCount').mockResolvedValue(records.length);
+ mockListRecords(records);
+ const inner = memoryStore({ lastPoll: BASE_EPOCH });
+ const failures = new Map<string, 'reject' | 'write-then-reject'>([['lastPoll', 'reject']]);
+ const store = failingPutStore({ inner, failures });
+
+ await expect(runPoll(newRecordTrigger, store)).rejects.toThrow(/simulated put failure/);
+ expect(await inner.get('lastPoll')).toBe(BASE_EPOCH);
+ const afterFailure = await inner.get<FrontierSnapshot>('teable_new_record_frontier');
+ const markedIds = afterFailure?.pending?.ids ?? [];
+ expect(markedIds.length).toBeGreaterThan(0);
+
+ const poll2 = await runPoll(newRecordTrigger, store);
+ expect(new Set(poll2.map((record) => record.id))).toEqual(new Set(markedIds));
+
+ const poll3 = await runPoll(newRecordTrigger, store);
+ expect(await inner.get('teable_new_record_frontier')).toBeNull();
+ const ids = [...poll2, ...poll3].map((record) => record.id);
+ expect(ids.length).toBe(7000);
+ expect(new Set(ids).size).toBe(7000);
+ expect(await runPoll(newRecordTrigger, store)).toEqual([]);
+ });
+
+ it('re-emits the chunk after a crash right after the pending write', async () => {
+ const records = makeTieRecords({ count: 7000, epoch: TIE_EPOCH });
+ vi.spyOn(teableClient, 'getRowCount').mockResolvedValue(records.length);
+ mockListRecords(records);
+ const inner = memoryStore({ lastPoll: BASE_EPOCH });
+ const failures = new Map<string, 'reject' | 'write-then-reject'>([
+ ['teable_new_record_frontier', 'write-then-reject'],
+ ]);
+ const store = failingPutStore({ inner, failures });
+
+ await expect(runPoll(newRecordTrigger, store)).rejects.toThrow(/simulated crash/);
+ expect(await inner.get('lastPoll')).toBe(BASE_EPOCH);
+ const afterCrash = await inner.get<FrontierSnapshot>('teable_new_record_frontier');
+ const markedIds = afterCrash?.pending?.ids ?? [];
+ expect(markedIds.length).toBeGreaterThan(0);
+
+ const poll2 = await runPoll(newRecordTrigger, store);
+ expect(new Set(poll2.map((record) => record.id))).toEqual(new Set(markedIds));
+
+ const poll3 = await runPoll(newRecordTrigger, store);
+ const ids = [...poll2, ...poll3].map((record) => record.id);
+ expect(ids.length).toBe(7000);
+ expect(new Set(ids).size).toBe(7000);
+ expect(await runPoll(newRecordTrigger, store)).toEqual([]);
+ });
+});
+
+describe('tie-group forward progress', () => {
+ it('delivers a 22,000-record tie group completely within a constant per-poll budget', async () => {
+ const records = makeTieRecords({ count: 22000, epoch: BASE_EPOCH + 10_000 });
+ vi.spyOn(teableClient, 'getRowCount').mockResolvedValue(records.length);
+ let listCalls = 0;
+ mockListRecords(records, () => {
+ listCalls += 1;
+ });
+ const store = memoryStore({ lastPoll: BASE_EPOCH });
+
+ const polls: DeliveredRecord[][] = [];
+ const budgets: number[] = [];
+ for (let round = 0; round < 8; round += 1) {
+ listCalls = 0;
+ const poll = await runPoll(newRecordTrigger, store);
+ budgets.push(listCalls);
+ if (poll.length === 0) {
+ break;
+ }
+ polls.push(poll);
+ }
+
+ for (const budget of budgets) {
+ expect(budget).toBeLessThanOrEqual(60);
+ }
+ const ids = polls.flat().map((record) => record.id);
+ expect(ids.length).toBe(22000);
+ expect(new Set(ids).size).toBe(22000);
+ expect(polls.length).toBeLessThanOrEqual(5);
+ expect(await store.get('teable_new_record_frontier')).toBeNull();
+ });
+});
+
+describe('new record trigger overflow', () => {
+ it('delivers 12k records across three capped polls with no loss and no dupes', async () => {
+ const records = makeRecords(12000);
+ vi.spyOn(teableClient, 'getRowCount').mockResolvedValue(records.length);
+ mockListRecords(records);
+ const store = memoryStore({ lastPoll: BASE_EPOCH - 1 });
+
+ const polls = [
+ await runPoll(newRecordTrigger, store),
+ await runPoll(newRecordTrigger, store),
+ await runPoll(newRecordTrigger, store),
+ ];
+
+ expect(polls.flat().length).toBe(12000);
+ const ids = polls.flat().map((record) => record.id);
+ expect(new Set(ids).size).toBe(12000);
+ expect(await runPoll(newRecordTrigger, store)).toEqual([]);
+ });
+
+ it('does not lose records when rows are deleted mid-scan', async () => {
+ const records = makeRecords(1500);
+ vi.spyOn(teableClient, 'getRowCount').mockResolvedValue(records.length);
+ let pageFetches = 0;
+ mockListRecords(records, (query) => {
+ if (query?.['take'] === 500) {
+ pageFetches += 1;
+ if (pageFetches === 2) {
+ records.splice(5, 3);
+ }
+ }
+ });
+ const store = memoryStore({ lastPoll: BASE_EPOCH - 1 });
+
+ const delivered = await runPoll(newRecordTrigger, store);
+ const rest = await runPoll(newRecordTrigger, store);
+ const ids = new Set([...delivered, ...rest].map((record) => record.id));
+ expect(ids.size).toBe(1500);
+ });
+});
+
+describe('updated record trigger overflow', () => {
+ it('delivers 12k modified records across three capped polls with no loss and no dupes', async () => {
+ const records = makeRecords(12000);
+ vi.spyOn(teableClient, 'getRowCount').mockResolvedValue(records.length);
+ vi.spyOn(teableClient, 'listFields').mockResolvedValue([
+ LAST_MODIFIED_FIELD,
+ ]);
+ mockListRecords(records);
+ const store = memoryStore({ lastPoll: BASE_EPOCH - 1 });
+
+ const polls = [
+ await runPoll(updatedRecordTrigger, store),
+ await runPoll(updatedRecordTrigger, store),
+ await runPoll(updatedRecordTrigger, store),
+ ];
+
+ expect(polls.flat().length).toBe(12000);
+ const ids = polls.flat().map((record) => record.id);
+ expect(new Set(ids).size).toBe(12000);
+ expect(await runPoll(updatedRecordTrigger, store)).toEqual([]);
+ });
+
+ it('does not lose records when rows are edited mid-scan', async () => {
+ const records = makeRecords(2000);
+ vi.spyOn(teableClient, 'getRowCount').mockResolvedValue(records.length);
+ vi.spyOn(teableClient, 'listFields').mockResolvedValue([
+ LAST_MODIFIED_FIELD,
+ ]);
+ let pageFetches = 0;
+ mockListRecords(records, (query) => {
+ if (query?.['take'] === 500) {
+ pageFetches += 1;
+ if (pageFetches === 2) {
+ for (const index of [10, 11, 12]) {
+ const bumped = iso(BASE_EPOCH + 5_000_000 + index * 1000);
+ records[index] = {
+ ...records[index],
+ fields: { LastModified: bumped },
+ lastModifiedTime: bumped,
+ };
+ }
+ }
+ }
+ });
+ const store = memoryStore({ lastPoll: BASE_EPOCH - 1 });
+
+ const delivered = await runPoll(updatedRecordTrigger, store);
+ const rest = await runPoll(updatedRecordTrigger, store);
+ const ids = new Set([...delivered, ...rest].map((record) => record.id));
+ expect(ids.size).toBe(2000);
+ });
+
+ it('delivers a small batch in one poll once caught up', async () => {
+ const records = makeRecords(120);
+ vi.spyOn(teableClient, 'getRowCount').mockResolvedValue(records.length);
+ vi.spyOn(teableClient, 'listFields').mockResolvedValue([
+ LAST_MODIFIED_FIELD,
+ ]);
+ mockListRecords(records);
+ const store = memoryStore({ lastPoll: BASE_EPOCH + 99 * 1000 });
+
+ const delivered = await runPoll(updatedRecordTrigger, store);
+ expect(delivered).toHaveLength(20);
+ expect(await runPoll(updatedRecordTrigger, store)).toEqual([]);
+ });
+});
+
+describe('updated record trigger field requirements', () => {
+ const DATE_ONLY_FIELD = {
+ id: 'fldDay',
+ name: 'Modified day',
+ type: 'lastModifiedTime',
+ options: { formatting: { date: 'M/D/YYYY', time: 'None', timeZone: 'UTC' } },
+ };
+
+ it('refuses a field that hides the time of day, on enable and on poll', async () => {
+ vi.spyOn(teableClient, 'listFields').mockResolvedValue([DATE_ONLY_FIELD]);
+ const listRecords = mockListRecords(makeRecords(10));
+ const store = memoryStore({ lastPoll: BASE_EPOCH });
+
+ await expect(updatedRecordTrigger.onEnable(pollContext({ store }))).rejects.toThrow(
+ /"Modified day" hides the time of day/
+ );
+ await expect(runPoll(updatedRecordTrigger, store)).rejects.toThrow(/24 hour or 12 hour/);
+ expect(listRecords).not.toHaveBeenCalled();
+ });
+
+ it('treats a field without formatting as date-only, like Teable does', async () => {
+ vi.spyOn(teableClient, 'listFields').mockResolvedValue([
+ { id: 'fldLM', name: 'LastModified', type: 'lastModifiedTime' },
+ ]);
+ const store = memoryStore({ lastPoll: BASE_EPOCH });
+
+ await expect(runPoll(updatedRecordTrigger, store)).rejects.toThrow(/hides the time of day/);
+ });
+
+ it('sorts by the field that shows the time when the table has several', async () => {
+ const records = makeRecords(30);
+ vi.spyOn(teableClient, 'getRowCount').mockResolvedValue(records.length);
+ vi.spyOn(teableClient, 'listFields').mockResolvedValue([DATE_ONLY_FIELD, LAST_MODIFIED_FIELD]);
+ const orderBys = new Set<unknown>();
+ mockListRecords(records, (query) => orderBys.add(query?.['orderBy']));
+ const store = memoryStore({ lastPoll: BASE_EPOCH + 9 * 1000 });
+
+ const delivered = await runPoll(updatedRecordTrigger, store);
+ expect(delivered).toHaveLength(20);
+ expect([...orderBys]).toEqual([JSON.stringify([{ fieldId: 'fldLM', order: 'asc' }])]);
+ });
+});
diff --git a/packages/pieces/community/teable/vitest.config.ts b/packages/pieces/community/teable/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/teable/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'),
+ },
+ },
+})