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(softr): manage databases, tables, fields, records and app users from flows and AI agents (#16300)

Odai Ahmad63ca1127aef3
diff --git a/bun.lock b/bun.lock
index a70cd76c2c7..d90af3241ba 100644
--- a/bun.lock
+++ b/bun.lock
@@ -8650,7 +8650,7 @@
},
"packages/pieces/community/softr": {
"name": "@activepieces/piece-softr",
- "version": "0.2.1",
+ "version": "0.3.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -8660,6 +8660,7 @@
},
"devDependencies": {
"tslib": "^2.3.0",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/sofya": {
diff --git a/packages/pieces/community/softr/package.json b/packages/pieces/community/softr/package.json
index bca95650f10..5d4e10c1f66 100644
--- a/packages/pieces/community/softr/package.json
+++ b/packages/pieces/community/softr/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/piece-softr",
- "version": "0.2.1",
+ "version": "0.3.0",
"type": "commonjs",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
@@ -12,11 +12,13 @@
"@activepieces/core-utils": "workspace:*"
},
"devDependencies": {
- "tslib": "^2.3.0"
+ "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/softr/src/i18n/translation.json b/packages/pieces/community/softr/src/i18n/translation.json
index b9db9162956..b5cb1d72163 100644
--- a/packages/pieces/community/softr/src/i18n/translation.json
+++ b/packages/pieces/community/softr/src/i18n/translation.json
@@ -1,24 +1,73 @@
{
- "You can obtain your API key from [API Settings](https://studio.softr.io/user/apisettings).": "You can obtain your API key from [API Settings](https://studio.softr.io/user/apisettings).",
+ "Create a personal access token in Softr under **Workspace settings → API tokens** (see [Softr API setup](https://docs.softr.io/softr-api/softr-database-api/authorisation)). The token needs access to the workspace whose databases and apps you want to use.": "Create a personal access token in Softr under **Workspace settings → API tokens** (see [Softr API setup](https://docs.softr.io/softr-api/softr-database-api/authorisation)). The token needs access to the workspace whose databases and apps you want to use.",
"Create App User": "Create App User",
"Create Database Record": "Create Database Record",
"Delete App User": "Delete App User",
"Delete Database Record": "Delete Database Record",
"Find Database Record": "Find Database Record",
"Update Database Record": "Update Database Record",
+ "Get Database Record": "Get Database Record",
+ "Find Records": "Find Records",
+ "List Databases": "List Databases",
+ "List Tables": "List Tables",
+ "Get Table": "Get Table",
+ "Activate App User": "Activate App User",
+ "Deactivate App User": "Deactivate App User",
+ "Invite App User": "Invite App User",
+ "Generate Magic Link": "Generate Magic Link",
+ "Get Database": "Get Database",
+ "List Table Views": "List Table Views",
+ "Create Database": "Create Database",
+ "Update Database": "Update Database",
+ "Delete Database": "Delete Database",
+ "Create Table": "Create Table",
+ "Update Table": "Update Table",
+ "Delete Table": "Delete Table",
+ "Create Table Field": "Create Table Field",
+ "Get Table Field": "Get Table Field",
+ "Update Table Field": "Update Table Field",
+ "Delete Table Field": "Delete Table Field",
+ "Get Database Schema (Agent)": "Get Database Schema (Agent)",
+ "Create Record (Agent)": "Create Record (Agent)",
+ "Update Record (Agent)": "Update Record (Agent)",
+ "Upsert Record (Agent)": "Upsert Record (Agent)",
"Custom API Call": "Custom API Call",
"Creates a new user inside a Softr app.": "Creates a new user inside a Softr app.",
"Creates a new record.": "Creates a new record.",
"Deletes a user from a Softr app.": "Deletes a user from a Softr app.",
- "Deletes a existing database record.": "Deletes a existing database record.",
- "Finds a record in table.": "Finds a record in table.",
+ "Deletes an existing database record.": "Deletes an existing database record.",
+ "Finds the first record where a field equals a value.": "Finds the first record where a field equals a value.",
"Updates an existing database record.": "Updates an existing database record.",
+ "Retrieves a single record by its ID.": "Retrieves a single record by its ID.",
+ "Finds records that match one or more conditions, with sorting and paging.": "Finds records that match one or more conditions, with sorting and paging.",
+ "Lists the Softr databases the API key can access.": "Lists the Softr databases the API key can access.",
+ "Lists the tables in a Softr database, including their fields.": "Lists the tables in a Softr database, including their fields.",
+ "Retrieves a table and its field definitions.": "Retrieves a table and its field definitions.",
+ "Reactivates a deactivated user in a Softr app.": "Reactivates a deactivated user in a Softr app.",
+ "Deactivates a user in a Softr app so they can no longer log in.": "Deactivates a user in a Softr app so they can no longer log in.",
+ "Sends an invitation email to an existing user of a Softr app.": "Sends an invitation email to an existing user of a Softr app.",
+ "Generates a magic login link for a user of a Softr app.": "Generates a magic login link for a user of a Softr app.",
+ "Retrieves a Softr database by its ID.": "Retrieves a Softr database by its ID.",
+ "Lists the views of a Softr table.": "Lists the views of a Softr table.",
+ "Creates a new database in a Softr workspace.": "Creates a new database in a Softr workspace.",
+ "Renames a Softr database or changes its description.": "Renames a Softr database or changes its description.",
+ "Permanently deletes a Softr database.": "Permanently deletes a Softr database.",
+ "Creates a new table in a Softr database.": "Creates a new table in a Softr database.",
+ "Renames a Softr table or changes its description.": "Renames a Softr table or changes its description.",
+ "Permanently deletes a Softr table.": "Permanently deletes a Softr table.",
+ "Adds a new field (column) to a Softr table.": "Adds a new field (column) to a Softr table.",
+ "Retrieves one field definition of a Softr table.": "Retrieves one field definition of a Softr table.",
+ "Renames a field, changes its type, or changes its options.": "Renames a field, changes its type, or changes its options.",
+ "Permanently deletes a field (column) and all of its values.": "Permanently deletes a field (column) and all of its values.",
+ "Gets every table and column in a Softr database.": "Gets every table and column in a Softr database.",
+ "Adds a record to a Softr table using column names.": "Adds a record to a Softr table using column names.",
+ "Changes some columns of a Softr record using column names.": "Changes some columns of a Softr record using column names.",
+ "Updates the record whose key column matches, or creates it.": "Updates the record whose key column matches, or creates it.",
"Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",
"Email": "Email",
"Name": "Name",
"Password": "Password",
"Domain": "Domain",
- "Generate Magic Link": "Generate Magic Link",
"Database ID": "Database ID",
"Table ID": "Table ID",
"Fields": "Fields",
@@ -27,36 +76,107 @@
"Record ID": "Record ID",
"Field": "Field",
"Field Value": "Field Value",
+ "Conditions": "Conditions",
+ "Match": "Match",
+ "Sort By Field (name or ID)": "Sort By Field (name or ID)",
+ "Sort Direction": "Sort Direction",
+ "Limit": "Limit",
+ "Offset": "Offset",
+ "Workspace ID": "Workspace ID",
+ "Description": "Description",
+ "New Name": "New Name",
+ "New Description": "New Description",
+ "Force Delete (deletes all tables and records)": "Force Delete (deletes all tables and records)",
+ "Table Name": "Table Name",
+ "Primary Field Name": "Primary Field Name",
+ "Additional Fields": "Additional Fields",
+ "Clear Description": "Clear Description",
+ "Force Delete (deletes all records)": "Force Delete (deletes all records)",
+ "Field Name": "Field Name",
+ "Field Type": "Field Type",
+ "Options": "Options",
+ "New Options": "New Options",
+ "Table (name or ID)": "Table (name or ID)",
+ "Key Column (name or ID)": "Key Column (name or ID)",
"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 email address of the new user.": "The email address of the new user.",
"The full name of the new user.": "The full name of the new user.",
- "The password for the new user.": "The password for the new user.",
- "The domain or subdomain of the Softr app where the user will be created.": "The domain or subdomain of the Softr app where the user will be created.",
+ "The password for the new user. Leave empty to let Softr generate one.": "The password for the new user. Leave empty to let Softr generate one.",
+ "Domain of the published Softr app to add the user to.": "Domain of the published Softr app to add the user to.",
"If checked, a magic link will be generated for the user.": "If checked, a magic link will be generated for the user.",
- "Select the database to insert the record into": "Select the database to insert the record into",
- "Select the table to insert the record into": "Select the table to insert the record into",
- "The email address of the user to delete.": "The email address of the user to delete.",
- "The domain or subdomain of the Softr app (e.g., yourdomain.com or subdomain.softr.app).": "The domain or subdomain of the Softr app (e.g., yourdomain.com or subdomain.softr.app).",
+ "Select the database.": "Select the database.",
+ "Select the table.": "Select the table.",
+ "The email address of the app user.": "The email address of the app user.",
+ "The domain or subdomain of the published Softr app, e.g. myapp.softr.app or portal.example.com.": "The domain or subdomain of the published Softr app, e.g. myapp.softr.app or portal.example.com.",
+ "The ID of the record, e.g. from the Find Records action or the New Database Record trigger.": "The ID of the record, e.g. from the Find Records action or the New Database Record trigger.",
+ "The value to match exactly. Use \"true\" or \"false\" for checkbox fields.": "The value to match exactly. Use \"true\" or \"false\" for checkbox fields.",
+ "Each condition compares one field. Leave empty to return all records.": "Each condition compares one field. Leave empty to return all records.",
+ "Whether records must match all conditions or any of them.": "Whether records must match all conditions or any of them.",
+ "A field name or ID, or created_at / updated_at.": "A field name or ID, or created_at / updated_at.",
+ "Maximum number of records to return (1-200).": "Maximum number of records to return (1-200).",
+ "Number of matching records to skip, for paging through results.": "Number of matching records to skip, for paging through results.",
+ "Copy it from the Softr Studio URL, after /workspaces/.": "Copy it from the Softr Studio URL, after /workspaces/.",
+ "Leave empty to keep the current name.": "Leave empty to keep the current name.",
+ "Leave empty to keep the current description.": "Leave empty to keep the current description.",
+ "Without this, Softr only deletes an empty database.": "Without this, Softr only deletes an empty database.",
+ "Additional field to use as the primary field. Defaults to the first.": "Additional field to use as the primary field. Defaults to the first.",
+ "Without this, Softr only deletes an empty table.": "Without this, Softr only deletes an empty table.",
+ "Type-specific JSON options. LINKED_RECORD, LOOKUP, ROLLUP need them.": "Type-specific JSON options. LINKED_RECORD, LOOKUP, ROLLUP need them.",
+ "Leave empty to keep. When set, replaces all options and choices.": "Leave empty to keep. When set, replaces all options and choices.",
+ "The Softr database ID. Get it from List Databases.": "The Softr database ID. Get it from List Databases.",
+ "The table name or table ID. Get both from Get Database Schema (Agent).": "The table name or table ID. Get both from Get Database Schema (Agent).",
+ "A JSON object keyed by column name or field ID, e.g. {\"Name\": \"Jane\", \"Age\": 30, \"Status\": \"Open\"}. Select columns take the option label or ID; multi-select columns take a list.": "A JSON object keyed by column name or field ID, e.g. {\"Name\": \"Jane\", \"Age\": 30, \"Status\": \"Open\"}. Select columns take the option label or ID; multi-select columns take a list.",
+ "The ID of the record to change. Get it from Find Records.": "The ID of the record to change. Get it from Find Records.",
+ "The column that identifies the record, e.g. Email.": "The column that identifies the record, e.g. Email.",
"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.",
+ "All conditions (AND)": "All conditions (AND)",
+ "Any condition (OR)": "Any condition (OR)",
+ "Ascending": "Ascending",
+ "Descending": "Descending",
+ "SINGLE_LINE_TEXT": "SINGLE_LINE_TEXT",
+ "LONG_TEXT": "LONG_TEXT",
+ "NUMBER": "NUMBER",
+ "CURRENCY": "CURRENCY",
+ "PERCENT": "PERCENT",
+ "RATING": "RATING",
+ "CHECKBOX": "CHECKBOX",
+ "DATETIME": "DATETIME",
+ "DURATION": "DURATION",
+ "EMAIL": "EMAIL",
+ "URL": "URL",
+ "PHONE": "PHONE",
+ "SELECT": "SELECT",
+ "ATTACHMENT": "ATTACHMENT",
+ "LINKED_RECORD": "LINKED_RECORD",
+ "USER": "USER",
+ "LOOKUP": "LOOKUP",
+ "ROLLUP": "ROLLUP",
+ "FORMULA": "FORMULA",
+ "CREATED_AT": "CREATED_AT",
+ "UPDATED_AT": "UPDATED_AT",
+ "CREATED_BY": "CREATED_BY",
+ "UPDATED_BY": "UPDATED_BY",
+ "AUTONUMBER": "AUTONUMBER",
+ "RECORD_ID": "RECORD_ID",
"GET": "GET",
"POST": "POST",
"PATCH": "PATCH",
"PUT": "PUT",
"DELETE": "DELETE",
"HEAD": "HEAD",
- "None": "None",
- "JSON": "JSON",
- "Form Data": "Form Data",
- "Raw": "Raw",
"New Database Record": "New Database Record",
"Triggers when a new record is added.": "Triggers when a new record is added."
}
\ No newline at end of file
diff --git a/packages/pieces/community/softr/src/index.ts b/packages/pieces/community/softr/src/index.ts
index 91d074f60b8..e2d3ded05b5 100644
--- a/packages/pieces/community/softr/src/index.ts
+++ b/packages/pieces/community/softr/src/index.ts
@@ -1,39 +1,88 @@
-import { createPiece } from '@activepieces/pieces-framework';
+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';
+import { createCustomApiCallAction } from '@activepieces/pieces-common';
import { SoftrAuth } from './lib/common/auth';
+import { softrClient } from './lib/common/client';
import { createDatabaseRecord } from './lib/actions/create-database-record';
import { createAppUser } from './lib/actions/create-app-user';
import { deleteAppUser } from './lib/actions/delete-app-user';
import { deleteDatabaseRecord } from './lib/actions/delete-database-record';
import { findDatabaseRecord } from './lib/actions/find-database-record';
import { updateDatabaseRecord } from './lib/actions/update-database-record';
-import { createCustomApiCallAction } from '@activepieces/pieces-common';
-import { BASE_URL } from './lib/common/client';
-import { PieceCategory } from '@activepieces/pieces-framework';
+import { getDatabaseRecord } from './lib/actions/get-database-record';
+import { findRecords } from './lib/actions/find-records';
+import { listDatabases } from './lib/actions/list-databases';
+import { listTables } from './lib/actions/list-tables';
+import { getTable } from './lib/actions/get-table';
+import { activateAppUser } from './lib/actions/activate-app-user';
+import { deactivateAppUser } from './lib/actions/deactivate-app-user';
+import { inviteAppUser } from './lib/actions/invite-app-user';
+import { generateMagicLink } from './lib/actions/generate-magic-link';
+import { getDatabase } from './lib/actions/get-database';
+import { listTableViews } from './lib/actions/list-table-views';
+import { createDatabase } from './lib/actions/create-database';
+import { updateDatabase } from './lib/actions/update-database';
+import { deleteDatabase } from './lib/actions/delete-database';
+import { createTable } from './lib/actions/create-table';
+import { updateTable } from './lib/actions/update-table';
+import { deleteTable } from './lib/actions/delete-table';
+import { createTableField } from './lib/actions/create-table-field';
+import { getTableField } from './lib/actions/get-table-field';
+import { updateTableField } from './lib/actions/update-table-field';
+import { deleteTableField } from './lib/actions/delete-table-field';
+import { getDatabaseSchemaAi } from './lib/actions/get-database-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 { newDatabaseRecord } from './lib/triggers/new-database-record';
export const softr = createPiece({
- displayName: 'Softr',
- auth: SoftrAuth,
- minimumSupportedRelease: '0.36.1',
- logoUrl: 'https://cdn.activepieces.com/pieces/softr.png',
- categories:[PieceCategory.CONTENT_AND_FILES,PieceCategory.PRODUCTIVITY],
- authors: ['Sanket6652'],
- actions: [
- createAppUser,
- createDatabaseRecord,
- deleteAppUser,
- deleteDatabaseRecord,
- findDatabaseRecord,
- updateDatabaseRecord,
- createCustomApiCallAction({
- auth:SoftrAuth,
- baseUrl:()=>BASE_URL,
- authMapping:async (auth)=>{
- return{
- 'Softr-Api-Key':auth.secret_text
- }
- }
- })
- ],
- triggers: [newDatabaseRecord],
+ displayName: 'Softr',
+ auth: SoftrAuth,
+ minimumSupportedRelease: '0.36.1',
+ logoUrl: 'https://cdn.activepieces.com/pieces/softr.png',
+ categories: [PieceCategory.CONTENT_AND_FILES, PieceCategory.PRODUCTIVITY],
+ authors: ['Sanket6652'],
+ actions: [
+ createAppUser,
+ createDatabaseRecord,
+ deleteAppUser,
+ deleteDatabaseRecord,
+ findDatabaseRecord,
+ updateDatabaseRecord,
+ getDatabaseRecord,
+ findRecords,
+ listDatabases,
+ listTables,
+ getTable,
+ activateAppUser,
+ deactivateAppUser,
+ inviteAppUser,
+ generateMagicLink,
+ getDatabase,
+ listTableViews,
+ createDatabase,
+ updateDatabase,
+ deleteDatabase,
+ createTable,
+ updateTable,
+ deleteTable,
+ createTableField,
+ getTableField,
+ updateTableField,
+ deleteTableField,
+ getDatabaseSchemaAi,
+ createRecordAi,
+ updateRecordAi,
+ upsertRecordAi,
+ createCustomApiCallAction({
+ auth: SoftrAuth,
+ baseUrl: () => softrClient.baseUrl,
+ authMapping: async (auth) => {
+ return {
+ 'Softr-Api-Key': auth.secret_text,
+ };
+ },
+ }),
+ ],
+ triggers: [newDatabaseRecord],
});
diff --git a/packages/pieces/community/softr/src/lib/actions/activate-app-user.ts b/packages/pieces/community/softr/src/lib/actions/activate-app-user.ts
new file mode 100644
index 00000000000..d81821a2f57
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/actions/activate-app-user.ts
@@ -0,0 +1,32 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { SoftrAuth } from '../common/auth';
+import { softrAppUsers } from '../common/app-users';
+import { appDomainField, appUserEmailField } from '../common/props';
+import { softrOutputSchemas } from '../output-schemas';
+
+export const activateAppUser = createAction({
+ auth: SoftrAuth,
+ name: 'activateAppUser',
+ classification: 'WRITE',
+ displayName: 'Activate App User',
+ description: 'Reactivates a deactivated user in a Softr app.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Lets a deactivated user of a published Softr app log in again. Needs the app domain and the user email. Undoes Deactivate App User. Safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ email: appUserEmailField,
+ domain: appDomainField,
+ },
+ outputSchema: softrOutputSchemas.appUserStatus,
+ async run({ auth, propsValue }) {
+ return softrAppUsers.setUserStatus({
+ apiKey: auth.secret_text,
+ domain: propsValue.domain,
+ email: propsValue.email,
+ status: 'activate',
+ });
+ },
+});
diff --git a/packages/pieces/community/softr/src/lib/actions/create-app-user.ts b/packages/pieces/community/softr/src/lib/actions/create-app-user.ts
index dcf92d6728e..604038306ac 100644
--- a/packages/pieces/community/softr/src/lib/actions/create-app-user.ts
+++ b/packages/pieces/community/softr/src/lib/actions/create-app-user.ts
@@ -1,77 +1,76 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { httpClient, HttpMethod } from '@activepieces/pieces-common';
+import { HttpMethod } from '@activepieces/pieces-common';
import { SoftrAuth } from '../common/auth';
+import { softrClient } from '../common/client';
+import { softrOutputSchemas } from '../output-schemas';
export const createAppUser = createAction({
- auth: SoftrAuth,
- name: 'createAppUser',
- classification: 'WRITE',
- displayName: 'Create App User',
- description: 'Creates a new user inside a Softr app.',
- audience: 'both',
- aiMetadata: { description: 'Creates an end-user account in a Softr app, identified by its domain/subdomain, with an email, name, and password; optionally generates a magic login link. Use to provision app users programmatically. Not idempotent — each call attempts to create a new user, so repeating it will conflict on a duplicate email.', idempotent: false },
- props: {
- email: Property.ShortText({
- displayName: 'Email',
- description: 'The email address of the new user.',
- required: true,
- }),
- full_name: Property.ShortText({
- displayName: 'Name',
- description: 'The full name of the new user.',
- required: true,
- }),
- password: Property.ShortText({
- displayName: 'Password',
- description: 'The password for the new user.',
- required: true,
- }),
- domain: Property.ShortText({
- displayName: 'Domain',
- description:
- 'The domain or subdomain of the Softr app where the user will be created.',
- required: true,
- }),
- generate_magic_link: Property.Checkbox({
- displayName: 'Generate Magic Link',
- description: 'If checked, a magic link will be generated for the user.',
- required: false,
- defaultValue: false,
- }),
- },
- async run({ auth, propsValue }) {
- const { email, full_name, password, generate_magic_link, domain } =
- propsValue;
-
- // Build the request body
- const requestBody: any = {
- email,
- full_name,
- password,
- generate_magic_link,
- };
-
- try {
- const response = await httpClient.sendRequest({
- method: HttpMethod.POST,
- url: `https://studio-api.softr.io/v1/api/users`,
- headers: {
- 'Softr-Api-Key': auth.secret_text,
- 'Softr-Domain': domain,
- 'Content-Type': 'application/json',
- },
- body: requestBody,
- });
-
- return {
- success: true,
- user: response,
- message: 'User created successfully',
- };
- } catch (error: any) {
- throw new Error(
- `Failed to create user: ${error.message || String(error)}`
- );
- }
- },
+ auth: SoftrAuth,
+ name: 'createAppUser',
+ classification: 'WRITE',
+ displayName: 'Create App User',
+ description: 'Creates a new user inside a Softr app.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Creates a user account in a published Softr app. Needs the app domain, email and full name; the password is optional (Softr makes one if empty) and it can also return a magic login link. Returns the new user. A second call with the same email fails because the user already exists.',
+ idempotent: false,
+ },
+ props: {
+ email: Property.ShortText({
+ displayName: 'Email',
+ description: 'The email address of the new user.',
+ required: true,
+ }),
+ full_name: Property.ShortText({
+ displayName: 'Name',
+ description: 'The full name of the new user.',
+ required: true,
+ }),
+ password: Property.ShortText({
+ displayName: 'Password',
+ description: 'The password for the new user. Leave empty to let Softr generate one.',
+ required: false,
+ }),
+ domain: Property.ShortText({
+ displayName: 'Domain',
+ description: 'Domain of the published Softr app to add the user to.',
+ placeholder: 'myapp.softr.app',
+ required: true,
+ }),
+ generate_magic_link: Property.Checkbox({
+ displayName: 'Generate Magic Link',
+ description: 'If checked, a magic link will be generated for the user.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ outputSchema: softrOutputSchemas.createAppUser,
+ async run({ auth, propsValue }) {
+ const { email, full_name, password, generate_magic_link, domain } = propsValue;
+ const trimmedEmail = email.trim();
+ if (trimmedEmail.length === 0) {
+ throw new Error('Email is required.');
+ }
+ const response = await softrClient.studioRequest({
+ apiKey: auth.secret_text,
+ domain,
+ method: HttpMethod.POST,
+ path: '',
+ body: {
+ email: trimmedEmail,
+ full_name,
+ ...(password && password.length > 0 ? { password } : {}),
+ generate_magic_link: generate_magic_link ?? false,
+ },
+ });
+ return {
+ success: true,
+ message: 'User created successfully',
+ user: {
+ status: response.status,
+ body: response.body,
+ },
+ };
+ },
});
diff --git a/packages/pieces/community/softr/src/lib/actions/create-database-record.ts b/packages/pieces/community/softr/src/lib/actions/create-database-record.ts
index ccb00272ea7..cd9e24b846c 100644
--- a/packages/pieces/community/softr/src/lib/actions/create-database-record.ts
+++ b/packages/pieces/community/softr/src/lib/actions/create-database-record.ts
@@ -1,10 +1,8 @@
import { createAction } from '@activepieces/pieces-framework';
-import { HttpMethod } from '@activepieces/pieces-common';
import { SoftrAuth } from '../common/auth';
-import { makeRequest, transformRecordFields } from '../common/client';
import { databaseIdDropdown, tableFields, tableIdDropdown } from '../common/props';
-import { isNil } from '@activepieces/pieces-framework';
-import { TableField } from '../common/types';
+import { softrRecords } from '../common/records';
+import { softrOutputSchemas } from '../output-schemas';
export const createDatabaseRecord = createAction({
auth: SoftrAuth,
@@ -12,43 +10,24 @@ export const createDatabaseRecord = createAction({
classification: 'WRITE',
displayName: 'Create Database Record',
description: 'Creates a new record.',
- audience: 'both',
- aiMetadata: { description: 'Creates a new record in a chosen table of a Softr database, populating the supplied field values (empty values are dropped). Use to add a row when no matching record needs to be located first. Not idempotent — each call appends a new record.', idempotent: false },
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Adds one new record to a Softr table using the table field form. Empty values are skipped. Each call adds a new record, so a retry makes a duplicate.',
+ idempotent: false,
+ },
props: {
databaseId: databaseIdDropdown,
tableId: tableIdDropdown,
fields: tableFields,
},
+ outputSchema: softrOutputSchemas.record,
async run({ auth, propsValue }) {
- const { databaseId, tableId } = propsValue;
-
- const fields = propsValue.fields ?? {};
-
- const formattedFields: Record<string, any> = {};
-
- for (const [key, value] of Object.entries(fields)) {
- if (isNil(value) || value === '') continue;
- if (Array.isArray(value) && value.length === 0) continue;
- formattedFields[key] = value;
- }
-
- const response = await makeRequest<{
- data: { id: string; createdAt: string; updatedAt: string; fields: Record<string, any> };
- }>(auth, HttpMethod.POST, `/databases/${databaseId}/tables/${tableId}/records`, {
- fields: formattedFields,
+ return softrRecords.writeRecord({
+ apiKey: auth.secret_text,
+ databaseId: propsValue.databaseId,
+ tableId: propsValue.tableId,
+ fields: propsValue.fields,
});
-
- const tableReponse = await makeRequest<{
- data: {
- fields: TableField[];
- };
- }>(auth, HttpMethod.GET, `/databases/${databaseId}/tables/${tableId}`);
-
- const transformedFields = transformRecordFields(tableReponse.data.fields, response.data.fields);
-
- return {
- ...response.data,
- fields: transformedFields,
- };
},
});
diff --git a/packages/pieces/community/softr/src/lib/actions/create-database.ts b/packages/pieces/community/softr/src/lib/actions/create-database.ts
new file mode 100644
index 00000000000..5d74ee45d6f
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/actions/create-database.ts
@@ -0,0 +1,49 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { SoftrAuth } from '../common/auth';
+import { softrClient } from '../common/client';
+import { softrAdmin } from '../common/admin';
+import { SoftrDatabase, SoftrSingleResponse } from '../common/types';
+import { softrOutputSchemas } from '../output-schemas';
+
+export const createDatabase = createAction({
+ auth: SoftrAuth,
+ name: 'createDatabase',
+ classification: 'WRITE',
+ displayName: 'Create Database',
+ description: 'Creates a new database in a Softr workspace.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Creates a new, empty Softr database and returns its ID. Needs the workspace ID, which the user copies from the Softr Studio URL (no API can look it up). Add tables next with Create Table. Each call creates another database.',
+ idempotent: false,
+ },
+ props: {
+ workspaceId: Property.ShortText({
+ displayName: 'Workspace ID',
+ description: 'Copy it from the Softr Studio URL, after /workspaces/.',
+ required: true,
+ }),
+ name: Property.ShortText({
+ displayName: 'Name',
+ required: true,
+ }),
+ description: Property.LongText({
+ displayName: 'Description',
+ required: false,
+ }),
+ },
+ outputSchema: softrOutputSchemas.database,
+ async run({ auth, propsValue }) {
+ const workspaceId = softrAdmin.requireId({ value: propsValue.workspaceId, label: 'Workspace ID' });
+ const name = softrAdmin.requireId({ value: propsValue.name, label: 'Name' });
+ const description = softrAdmin.optionalText(propsValue.description);
+ const response = await softrClient.request<SoftrSingleResponse<SoftrDatabase>>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.POST,
+ path: '/databases',
+ body: { workspaceId, name, ...(description !== undefined ? { description } : {}) },
+ });
+ return response.data;
+ },
+});
diff --git a/packages/pieces/community/softr/src/lib/actions/create-record-ai.ts b/packages/pieces/community/softr/src/lib/actions/create-record-ai.ts
new file mode 100644
index 00000000000..6eef3e150b9
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/actions/create-record-ai.ts
@@ -0,0 +1,35 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { SoftrAuth } from '../common/auth';
+import { softrAgent } from '../common/agent';
+import { agentDatabaseIdField, agentFieldsJson, agentTableField } from '../common/props';
+import { softrRecords } from '../common/records';
+import { softrOutputSchemas } from '../output-schemas';
+
+export const createRecordAi = createAction({
+ auth: SoftrAuth,
+ name: 'create_record_ai',
+ classification: 'WRITE',
+ displayName: 'Create Record (Agent)',
+ description: 'Adds a record to a Softr table using column names.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Adds one new record to a Softr table. Agents: use this instead of Create Database Record. Needs the database ID, the table name or ID, and a JSON object of values keyed by column name or field ID (see Get Database Schema (Agent)). Returns the new record with values keyed by column name. Each call adds a new record, so a retry makes a duplicate; use Upsert Record (Agent) to avoid that.',
+ idempotent: false,
+ },
+ props: {
+ databaseId: agentDatabaseIdField,
+ table: agentTableField,
+ fields: agentFieldsJson,
+ },
+ outputSchema: softrOutputSchemas.record,
+ async run({ auth, propsValue }) {
+ const apiKey = auth.secret_text;
+ const databaseId = softrAgent.requireText({ value: propsValue.databaseId, label: 'Database ID' });
+ const reference = softrAgent.requireText({ value: propsValue.table, label: 'Table' });
+ const input = softrAgent.parseFieldsInput(propsValue.fields);
+ const table = await softrAgent.resolveTable({ apiKey, databaseId, reference });
+ const fields = softrAgent.buildFieldValues({ table, fields: input });
+ return softrRecords.writeRecord({ apiKey, databaseId, tableId: table.id, fields, tableFields: table.fields });
+ },
+});
diff --git a/packages/pieces/community/softr/src/lib/actions/create-table-field.ts b/packages/pieces/community/softr/src/lib/actions/create-table-field.ts
new file mode 100644
index 00000000000..59a4700adba
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/actions/create-table-field.ts
@@ -0,0 +1,52 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { SoftrAuth } from '../common/auth';
+import { softrClient } from '../common/client';
+import { softrAdmin } from '../common/admin';
+import { databaseIdDropdown, tableIdDropdown } from '../common/props';
+import { SoftrSingleResponse, TableField } from '../common/types';
+import { softrOutputSchemas } from '../output-schemas';
+
+export const createTableField = createAction({
+ auth: SoftrAuth,
+ name: 'createTableField',
+ classification: 'WRITE',
+ displayName: 'Create Table Field',
+ description: 'Adds a new field (column) to a Softr table.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Adds a column to a Softr table. Needs a name and a Softr field type; options are optional JSON, e.g. select choices or {"precision":"DATE"} for a date-only DATETIME. Returns the new field with its ID. Each call adds another column.',
+ idempotent: false,
+ },
+ props: {
+ databaseId: databaseIdDropdown,
+ tableId: tableIdDropdown,
+ name: Property.ShortText({
+ displayName: 'Field Name',
+ required: true,
+ }),
+ type: softrAdmin.fieldTypeDropdown({ required: true }),
+ options: Property.Json({
+ displayName: 'Options',
+ description: 'Type-specific JSON options. LINKED_RECORD, LOOKUP, ROLLUP need them.',
+ placeholder: '{"choices":[{"label":"Open"},{"label":"Closed"}]}',
+ required: false,
+ }),
+ },
+ outputSchema: softrOutputSchemas.field,
+ async run({ auth, propsValue }) {
+ const databaseId = softrAdmin.requireId({ value: propsValue.databaseId, label: 'Database ID' });
+ const tableId = softrAdmin.requireId({ value: propsValue.tableId, label: 'Table ID' });
+ const name = softrAdmin.requireId({ value: propsValue.name, label: 'Field name' });
+ const type = softrAdmin.readFieldType(propsValue.type);
+ const options = softrAdmin.parseOptions({ value: propsValue.options, label: 'Options' });
+ const response = await softrClient.request<SoftrSingleResponse<TableField>>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.POST,
+ path: `${softrClient.tablePath({ databaseId, tableId })}/fields`,
+ body: { name, type, ...(options !== undefined ? { options } : {}) },
+ });
+ return response.data;
+ },
+});
diff --git a/packages/pieces/community/softr/src/lib/actions/create-table.ts b/packages/pieces/community/softr/src/lib/actions/create-table.ts
new file mode 100644
index 00000000000..af850b3b7d2
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/actions/create-table.ts
@@ -0,0 +1,84 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { SoftrAuth } from '../common/auth';
+import { softrClient } from '../common/client';
+import { softrAdmin } from '../common/admin';
+import { databaseIdDropdown } from '../common/props';
+import { SoftrSingleResponse, SoftrTable } from '../common/types';
+import { softrOutputSchemas } from '../output-schemas';
+
+function readFields(rawFields: unknown[]): { name: string; type: string; options?: Record<string, unknown> }[] {
+ return rawFields.map((raw, index) => {
+ if (typeof raw !== 'object' || raw === null) {
+ throw new Error(`Field ${index + 1} is not valid.`);
+ }
+ const name = softrAdmin.requireId({ value: 'name' in raw ? raw.name : undefined, label: `Field ${index + 1} name` });
+ const type = softrAdmin.readFieldType('type' in raw ? raw.type : undefined);
+ const options = softrAdmin.parseOptions({ value: 'options' in raw ? raw.options : undefined, label: `Field ${index + 1} options` });
+ return { name, type, ...(options !== undefined ? { options } : {}) };
+ });
+}
+
+export const createTable = createAction({
+ auth: SoftrAuth,
+ name: 'createTable',
+ classification: 'WRITE',
+ displayName: 'Create Table',
+ description: 'Creates a new table in a Softr database.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Creates a table in a Softr database with the columns you list (name, type, optional JSON options). Primary Field Name picks the primary column; otherwise the first one is used. Returns the table with its field IDs. Each call creates another table.',
+ idempotent: false,
+ },
+ props: {
+ databaseId: databaseIdDropdown,
+ name: Property.ShortText({
+ displayName: 'Table Name',
+ required: true,
+ }),
+ description: Property.LongText({
+ displayName: 'Description',
+ required: false,
+ }),
+ primaryFieldName: Property.ShortText({
+ displayName: 'Primary Field Name',
+ description: 'Additional field to use as the primary field. Defaults to the first.',
+ required: false,
+ }),
+ fields: Property.Array({
+ displayName: 'Additional Fields',
+ required: false,
+ properties: {
+ name: Property.ShortText({ displayName: 'Field Name', required: true }),
+ type: softrAdmin.fieldTypeDropdown({ required: true }),
+ options: Property.LongText({
+ displayName: 'Options (JSON)',
+ description: 'Type-specific JSON options. LINKED_RECORD, LOOKUP, ROLLUP need them.',
+ placeholder: '{"choices":[{"label":"Open"},{"label":"Closed"}]}',
+ required: false,
+ }),
+ },
+ }),
+ },
+ outputSchema: softrOutputSchemas.table,
+ async run({ auth, propsValue }) {
+ const databaseId = softrAdmin.requireId({ value: propsValue.databaseId, label: 'Database ID' });
+ const name = softrAdmin.requireId({ value: propsValue.name, label: 'Table name' });
+ const description = softrAdmin.optionalText(propsValue.description);
+ const primaryFieldName = softrAdmin.optionalText(propsValue.primaryFieldName);
+ const fields = readFields(propsValue.fields ?? []);
+ const response = await softrClient.request<SoftrSingleResponse<SoftrTable>>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.POST,
+ path: `${softrClient.databasePath({ databaseId })}/tables`,
+ body: {
+ name,
+ ...(description !== undefined ? { description } : {}),
+ ...(primaryFieldName !== undefined ? { primaryFieldName } : {}),
+ ...(fields.length > 0 ? { fields } : {}),
+ },
+ });
+ return response.data;
+ },
+});
diff --git a/packages/pieces/community/softr/src/lib/actions/deactivate-app-user.ts b/packages/pieces/community/softr/src/lib/actions/deactivate-app-user.ts
new file mode 100644
index 00000000000..d4a657d6b55
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/actions/deactivate-app-user.ts
@@ -0,0 +1,32 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { SoftrAuth } from '../common/auth';
+import { softrAppUsers } from '../common/app-users';
+import { appDomainField, appUserEmailField } from '../common/props';
+import { softrOutputSchemas } from '../output-schemas';
+
+export const deactivateAppUser = createAction({
+ auth: SoftrAuth,
+ name: 'deactivateAppUser',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Deactivate App User',
+ description: 'Deactivates a user in a Softr app so they can no longer log in.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Stops a user of a published Softr app from logging in but keeps the account, which then no longer counts toward the plan user limit. Needs the app domain and user email. Prefer this over Delete App User when access may come back; undo it with Activate App User. Safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ email: appUserEmailField,
+ domain: appDomainField,
+ },
+ outputSchema: softrOutputSchemas.appUserStatus,
+ async run({ auth, propsValue }) {
+ return softrAppUsers.setUserStatus({
+ apiKey: auth.secret_text,
+ domain: propsValue.domain,
+ email: propsValue.email,
+ status: 'deactivate',
+ });
+ },
+});
diff --git a/packages/pieces/community/softr/src/lib/actions/delete-app-user.ts b/packages/pieces/community/softr/src/lib/actions/delete-app-user.ts
index 7e2829032cd..8447047c676 100644
--- a/packages/pieces/community/softr/src/lib/actions/delete-app-user.ts
+++ b/packages/pieces/community/softr/src/lib/actions/delete-app-user.ts
@@ -1,54 +1,40 @@
-import { createAction, Property } from '@activepieces/pieces-framework';
-import { HttpMethod, httpClient } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
import { SoftrAuth } from '../common/auth';
+import { softrClient } from '../common/client';
+import { appDomainField, appUserEmailField } from '../common/props';
export const deleteAppUser = createAction({
- auth: SoftrAuth,
- name: 'deleteAppUser',
- classification: 'DESTRUCTIVE',
- displayName: 'Delete App User',
- description: 'Deletes a user from a Softr app.',
- audience: 'both',
- aiMetadata: { description: 'Permanently removes an end-user from a Softr app, identified by the app domain/subdomain and the user email. Use to deprovision a known user. Idempotent in effect on a stable email — once the user is gone the account stays gone — though a repeat call returns a not-found error.', idempotent: true },
- props: {
- email: Property.ShortText({
- displayName: 'User Email',
- description: 'The email address of the user to delete.',
- required: true,
- }),
- domain: Property.ShortText({
- displayName: 'Softr Domain',
- description: 'The domain or subdomain of the Softr app (e.g., yourdomain.com or subdomain.softr.app).',
- required: true,
- }),
- },
- async run({ auth, propsValue }) {
- const { email, domain } = propsValue;
-
- try {
- const response = await httpClient.sendRequest({
- method: HttpMethod.DELETE,
- url: `https://studio-api.softr.io/v1/api/users/${encodeURIComponent(email)}`,
- headers: {
- 'Softr-Api-Key': auth.secret_text,
- 'Softr-Domain': domain,
- 'Content-Type': 'application/json',
- },
- });
-
- return {
- success: true,
- message: `User ${email} deleted successfully from ${domain}`,
- statusCode: response.status,
- };
- } catch (error: any) {
- if (error.response?.status === 404) {
- throw new Error(`User with email ${email} not found in app ${domain}`);
- } else if (error.response?.status === 403) {
- throw new Error(`Access denied. Check your API key and domain permissions`);
- } else {
- throw new Error(`Failed to delete user: ${error.message || String(error)}`);
- }
- }
- },
-});
\ No newline at end of file
+ auth: SoftrAuth,
+ name: 'deleteAppUser',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete App User',
+ description: 'Deletes a user from a Softr app.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Permanently deletes a user from a published Softr app. Needs the app domain and user email. This cannot be undone; to only block login, use Deactivate App User. A second call fails with not found.',
+ idempotent: false,
+ },
+ props: {
+ email: appUserEmailField,
+ domain: appDomainField,
+ },
+ async run({ auth, propsValue }) {
+ const email = propsValue.email.trim();
+ if (email.length === 0) {
+ throw new Error('User email is required.');
+ }
+ const response = await softrClient.studioRequest({
+ apiKey: auth.secret_text,
+ domain: propsValue.domain,
+ method: HttpMethod.DELETE,
+ path: `/${encodeURIComponent(email)}`,
+ });
+ return {
+ success: true,
+ message: `User ${email} deleted successfully from ${propsValue.domain.trim()}`,
+ statusCode: response.status,
+ };
+ },
+});
diff --git a/packages/pieces/community/softr/src/lib/actions/delete-database-record.ts b/packages/pieces/community/softr/src/lib/actions/delete-database-record.ts
index 8f9060cefe5..30f0f779abe 100644
--- a/packages/pieces/community/softr/src/lib/actions/delete-database-record.ts
+++ b/packages/pieces/community/softr/src/lib/actions/delete-database-record.ts
@@ -1,39 +1,40 @@
import { createAction } from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
import { SoftrAuth } from '../common/auth';
-import { makeRequest } from '../common/client';
-import {
- databaseIdDropdown,
- recordIdField,
- tableIdDropdown,
-} from '../common/props';
+import { softrClient } from '../common/client';
+import { databaseIdDropdown, recordIdField, tableIdDropdown } from '../common/props';
export const deleteDatabaseRecord = createAction({
- auth: SoftrAuth,
- name: 'deleteDatabaseRecord',
- classification: 'DESTRUCTIVE',
- displayName: 'Delete Database Record',
- description: 'Deletes a existing database record.',
- audience: 'both',
- aiMetadata: { description: 'Permanently deletes a single record from a chosen table of a Softr database, identified by its record ID. Use when you already hold the target record ID (e.g. from a find or trigger). Idempotent on a stable record ID — once deleted the record stays gone.', idempotent: true },
- props: {
- databaseId: databaseIdDropdown,
- tableId: tableIdDropdown,
- recordId: recordIdField,
- },
- async run({ auth, propsValue }) {
- const { databaseId, tableId, recordId } = propsValue;
-
- const response = await makeRequest(
- auth,
- HttpMethod.DELETE,
- `/databases/${databaseId}/tables/${tableId}/records/${recordId}`
- );
-
- return {
- success: true,
- message: 'Record deleted successfully',
- recordId: recordId,
- };
- },
+ auth: SoftrAuth,
+ name: 'deleteDatabaseRecord',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Database Record',
+ description: 'Deletes an existing database record.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Permanently deletes one record from a Softr table by its record ID (from Find Records or the trigger). This cannot be undone. A second call fails with not found.',
+ idempotent: false,
+ },
+ props: {
+ databaseId: databaseIdDropdown,
+ tableId: tableIdDropdown,
+ recordId: recordIdField,
+ },
+ async run({ auth, propsValue }) {
+ const recordId = propsValue.recordId.trim();
+ if (recordId.length === 0) {
+ throw new Error('Record ID is required.');
+ }
+ await softrClient.request({
+ apiKey: auth.secret_text,
+ method: HttpMethod.DELETE,
+ path: softrClient.recordPath({ databaseId: propsValue.databaseId, tableId: propsValue.tableId, recordId }),
+ });
+ return {
+ success: true,
+ message: 'Record deleted successfully',
+ recordId,
+ };
+ },
});
diff --git a/packages/pieces/community/softr/src/lib/actions/delete-database.ts b/packages/pieces/community/softr/src/lib/actions/delete-database.ts
new file mode 100644
index 00000000000..9754636dd0a
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/actions/delete-database.ts
@@ -0,0 +1,40 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { SoftrAuth } from '../common/auth';
+import { softrClient } from '../common/client';
+import { softrAdmin } from '../common/admin';
+import { databaseIdDropdown } from '../common/props';
+
+export const deleteDatabase = createAction({
+ auth: SoftrAuth,
+ name: 'deleteDatabase',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Database',
+ description: 'Permanently deletes a Softr database.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Permanently deletes a Softr database. With Force Delete it also deletes all its tables and records; without it, Softr refuses while the database still has tables. Only use when the user clearly asked for it: this cannot be undone.',
+ idempotent: false,
+ },
+ props: {
+ databaseId: databaseIdDropdown,
+ force: Property.Checkbox({
+ displayName: 'Force Delete (deletes all tables and records)',
+ description: 'Without this, Softr only deletes an empty database.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const databaseId = softrAdmin.requireId({ value: propsValue.databaseId, label: 'Database ID' });
+ const force = propsValue.force === true;
+ await softrClient.request({
+ apiKey: auth.secret_text,
+ method: HttpMethod.DELETE,
+ path: softrClient.databasePath({ databaseId }),
+ queryParams: force ? { force: 'true' } : undefined,
+ });
+ return { success: true, databaseId, force };
+ },
+});
diff --git a/packages/pieces/community/softr/src/lib/actions/delete-table-field.ts b/packages/pieces/community/softr/src/lib/actions/delete-table-field.ts
new file mode 100644
index 00000000000..af41e62b327
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/actions/delete-table-field.ts
@@ -0,0 +1,36 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { SoftrAuth } from '../common/auth';
+import { softrClient } from '../common/client';
+import { softrAdmin } from '../common/admin';
+import { databaseIdDropdown, tableFieldIdDropdown, tableIdDropdown } from '../common/props';
+
+export const deleteTableField = createAction({
+ auth: SoftrAuth,
+ name: 'deleteTableField',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Table Field',
+ description: 'Permanently deletes a field (column) and all of its values.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Permanently deletes a column from a Softr table, including its value in every record. Only use when the user clearly asked for it: this cannot be undone. A second call fails with not found.',
+ idempotent: false,
+ },
+ props: {
+ databaseId: databaseIdDropdown,
+ tableId: tableIdDropdown,
+ fieldId: tableFieldIdDropdown,
+ },
+ async run({ auth, propsValue }) {
+ const databaseId = softrAdmin.requireId({ value: propsValue.databaseId, label: 'Database ID' });
+ const tableId = softrAdmin.requireId({ value: propsValue.tableId, label: 'Table ID' });
+ const fieldId = softrAdmin.requireId({ value: propsValue.fieldId, label: 'Field ID' });
+ await softrClient.request({
+ apiKey: auth.secret_text,
+ method: HttpMethod.DELETE,
+ path: softrClient.fieldPath({ databaseId, tableId, fieldId }),
+ });
+ return { success: true, fieldId };
+ },
+});
diff --git a/packages/pieces/community/softr/src/lib/actions/delete-table.ts b/packages/pieces/community/softr/src/lib/actions/delete-table.ts
new file mode 100644
index 00000000000..27b5b90e9cf
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/actions/delete-table.ts
@@ -0,0 +1,42 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { SoftrAuth } from '../common/auth';
+import { softrClient } from '../common/client';
+import { softrAdmin } from '../common/admin';
+import { databaseIdDropdown, tableIdDropdown } from '../common/props';
+
+export const deleteTable = createAction({
+ auth: SoftrAuth,
+ name: 'deleteTable',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Table',
+ description: 'Permanently deletes a Softr table.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Permanently deletes a Softr table. With Force Delete it also deletes all its records; without it, Softr refuses while the table still has records. Only use when the user clearly asked for it: this cannot be undone.',
+ idempotent: false,
+ },
+ props: {
+ databaseId: databaseIdDropdown,
+ tableId: tableIdDropdown,
+ force: Property.Checkbox({
+ displayName: 'Force Delete (deletes all records)',
+ description: 'Without this, Softr only deletes an empty table.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const databaseId = softrAdmin.requireId({ value: propsValue.databaseId, label: 'Database ID' });
+ const tableId = softrAdmin.requireId({ value: propsValue.tableId, label: 'Table ID' });
+ const force = propsValue.force === true;
+ await softrClient.request({
+ apiKey: auth.secret_text,
+ method: HttpMethod.DELETE,
+ path: softrClient.tablePath({ databaseId, tableId }),
+ queryParams: force ? { force: 'true' } : undefined,
+ });
+ return { success: true, tableId, force };
+ },
+});
diff --git a/packages/pieces/community/softr/src/lib/actions/find-database-record.ts b/packages/pieces/community/softr/src/lib/actions/find-database-record.ts
index cb67625e2b4..fb606452010 100644
--- a/packages/pieces/community/softr/src/lib/actions/find-database-record.ts
+++ b/packages/pieces/community/softr/src/lib/actions/find-database-record.ts
@@ -1,82 +1,58 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { HttpMethod } from '@activepieces/pieces-common';
import { SoftrAuth } from '../common/auth';
-import { makeRequest, transformRecordFields } from '../common/client';
+import { softrClient } from '../common/client';
+import { softrRecords } from '../common/records';
import { databaseIdDropdown, tableFieldIdDropdown, tableIdDropdown } from '../common/props';
-import { TableField } from '../common/types';
+import { softrSearch } from '../common/search';
+import { softrOutputSchemas } from '../output-schemas';
export const findDatabaseRecord = createAction({
auth: SoftrAuth,
name: 'findDatabaseRecord',
classification: 'SEARCH',
displayName: 'Find Database Record',
- description: 'Finds a record in table.',
+ description: 'Finds the first record where a field equals a value.',
audience: 'both',
- aiMetadata: { description: 'Searches a chosen table of a Softr database for the first record where the selected field exactly equals (IS) the given value, returning a found flag and the matched record. Use to look up a record by a field value before updating or deleting it. Read-only and idempotent; matches only a single record (limit 1).', idempotent: true },
+ aiMetadata: {
+ description:
+ 'Finds the first record in a Softr table where one field equals a value. Returns found (true or false) and the record. For several conditions, other operators or many results, use Find Records. Read-only.',
+ idempotent: true,
+ },
props: {
databaseId: databaseIdDropdown,
tableId: tableIdDropdown,
fieldId: tableFieldIdDropdown,
fieldValue: Property.ShortText({
displayName: 'Field Value',
+ description: 'The value to match exactly. Use "true" or "false" for checkbox fields.',
required: true,
}),
},
+ outputSchema: softrOutputSchemas.findRecord,
async run({ auth, propsValue }) {
const { databaseId, tableId, fieldId, fieldValue } = propsValue;
-
- const requestBody = {
- paging: {
- limit: 1,
- },
- filter: {
- condition: {
- operator: 'AND',
- conditions: [
- {
- leftSide: fieldId,
- operator: 'IS',
- rightSide: fieldValue,
- },
- ],
- },
+ const apiKey = auth.secret_text;
+ const table = await softrClient.getTable({ apiKey, databaseId, tableId });
+ const field = softrSearch.resolveField({ fields: table.fields, reference: fieldId });
+ const condition = softrSearch.buildCondition({ field, operator: 'IS', value: fieldValue });
+
+ const response = await softrRecords.searchRecords({
+ apiKey,
+ databaseId,
+ tableId,
+ body: {
+ paging: { offset: 0, limit: 1 },
+ filter: { condition: { operator: 'AND', conditions: [condition] } },
},
- };
-
- const response = await makeRequest<{
- data: {
- fields: TableField[];
- }[];
- }>(
- auth,
- HttpMethod.POST,
- `/databases/${databaseId}/tables/${tableId}/records/search`,
- requestBody,
- );
+ });
- if (Array.isArray(response.data) && response.data.length === 0) {
- return {
- found: false,
- data: {},
- };
+ const foundRecord = response.data?.[0];
+ if (!foundRecord) {
+ return { found: false, data: {} };
}
-
- const foundRecord = response.data[0];
-
- const tableReponse = await makeRequest<{
- data: {
- fields: TableField[];
- };
- }>(auth, HttpMethod.GET, `/databases/${databaseId}/tables/${tableId}`);
-
- const transformedFields = transformRecordFields(tableReponse.data.fields, foundRecord.fields);
-
return {
found: true,
- data: {
- ...foundRecord,
- fields: transformedFields,
- },
+ data: softrClient.withFieldNames({ record: foundRecord, tableFields: table.fields }),
};
},
});
diff --git a/packages/pieces/community/softr/src/lib/actions/find-records.ts b/packages/pieces/community/softr/src/lib/actions/find-records.ts
new file mode 100644
index 00000000000..54f0e7f51eb
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/actions/find-records.ts
@@ -0,0 +1,187 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { SoftrAuth } from '../common/auth';
+import { softrClient } from '../common/client';
+import { softrRecords } from '../common/records';
+import { databaseIdDropdown, tableIdDropdown } from '../common/props';
+import { SoftrCondition, softrSearch } from '../common/search';
+import { TableField } from '../common/types';
+import { softrOutputSchemas } from '../output-schemas';
+
+const MAX_LIMIT = 200;
+
+function readText(value: unknown): string | undefined {
+ if (value === undefined || value === null) {
+ return undefined;
+ }
+ return typeof value === 'string' ? value : String(value);
+}
+
+function readConditions({ rawConditions, fields }: { rawConditions: unknown[]; fields: TableField[] }): SoftrCondition[] {
+ return rawConditions.map((raw, index) => {
+ if (typeof raw !== 'object' || raw === null) {
+ throw new Error(`Condition ${index + 1} is not valid.`);
+ }
+ const fieldReference = 'field' in raw ? readText(raw.field) : undefined;
+ const operator = 'operator' in raw ? readText(raw.operator) : undefined;
+ if (!fieldReference || fieldReference.trim().length === 0) {
+ throw new Error(`Condition ${index + 1} needs a field name or ID.`);
+ }
+ if (!operator || !softrSearch.operatorValues.includes(operator)) {
+ throw new Error(`Condition ${index + 1} has an unsupported operator "${operator ?? ''}".`);
+ }
+ const field = softrSearch.resolveField({ fields, reference: fieldReference });
+ return softrSearch.buildCondition({
+ field,
+ operator,
+ value: 'value' in raw ? raw.value : undefined,
+ upperBound: 'upperBound' in raw ? raw.upperBound : undefined,
+ });
+ });
+}
+
+function readWholeNumber({ value, name, min, max, fallback }: ReadNumberParams): number {
+ if (value === undefined || value === null) {
+ return fallback;
+ }
+ if (!Number.isInteger(value) || value < min || value > max) {
+ throw new Error(`${name} must be a whole number between ${min} and ${max}.`);
+ }
+ return value;
+}
+
+export const findRecords = createAction({
+ auth: SoftrAuth,
+ name: 'findRecords',
+ classification: 'SEARCH',
+ displayName: 'Find Records',
+ description: 'Finds records that match one or more conditions, with sorting and paging.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Searches a Softr table with one or more conditions (equals, contains, greater than, between, one of, is empty, ...) joined by AND or OR, with optional sorting. Give fields by name or ID; leave conditions empty to list the whole table. For between, put the upper limit in Upper Bound; for one of, separate values with commas. Returns up to 200 records plus the total count; use Offset for the next page. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ databaseId: databaseIdDropdown,
+ tableId: tableIdDropdown,
+ conditions: Property.Array({
+ displayName: 'Conditions',
+ description: 'Each condition compares one field. Leave empty to return all records.',
+ required: false,
+ properties: {
+ field: Property.ShortText({
+ displayName: 'Field (name or ID)',
+ required: true,
+ }),
+ operator: Property.StaticDropdown({
+ displayName: 'Operator',
+ required: true,
+ defaultValue: 'IS',
+ options: { options: softrSearch.operatorOptions },
+ }),
+ value: Property.ShortText({
+ displayName: 'Value',
+ description: 'Lower bound for "between". Dates: 2025-05-21 or PREDEFINED:TODAY.',
+ required: false,
+ }),
+ upperBound: Property.ShortText({
+ displayName: 'Upper Bound',
+ description: 'Only for "Is between" and "Is not between".',
+ required: false,
+ }),
+ },
+ }),
+ matchType: Property.StaticDropdown({
+ displayName: 'Match',
+ description: 'Whether records must match all conditions or any of them.',
+ required: true,
+ defaultValue: 'AND',
+ options: {
+ options: [
+ { label: 'All conditions (AND)', value: 'AND' },
+ { label: 'Any condition (OR)', value: 'OR' },
+ ],
+ },
+ }),
+ sortField: Property.ShortText({
+ displayName: 'Sort By Field (name or ID)',
+ description: 'A field name or ID, or created_at / updated_at.',
+ required: false,
+ }),
+ sortDirection: Property.StaticDropdown({
+ displayName: 'Sort Direction',
+ required: false,
+ defaultValue: 'ASC',
+ options: {
+ options: [
+ { label: 'Ascending', value: 'ASC' },
+ { label: 'Descending', value: 'DESC' },
+ ],
+ },
+ }),
+ limit: Property.Number({
+ displayName: 'Limit',
+ description: 'Maximum number of records to return (1-200).',
+ required: false,
+ defaultValue: 50,
+ }),
+ offset: Property.Number({
+ displayName: 'Offset',
+ description: 'Number of matching records to skip, for paging through results.',
+ required: false,
+ defaultValue: 0,
+ }),
+ },
+ outputSchema: softrOutputSchemas.findRecords,
+ async run({ auth, propsValue }) {
+ const { databaseId, tableId } = propsValue;
+ const apiKey = auth.secret_text;
+ const limit = readWholeNumber({ value: propsValue.limit, name: 'Limit', min: 1, max: MAX_LIMIT, fallback: 50 });
+ const offset = readWholeNumber({
+ value: propsValue.offset,
+ name: 'Offset',
+ min: 0,
+ max: Number.MAX_SAFE_INTEGER,
+ fallback: 0,
+ });
+ const matchType = propsValue.matchType === 'OR' ? 'OR' : 'AND';
+ const sortDirection = propsValue.sortDirection === 'DESC' ? 'DESC' : 'ASC';
+
+ const table = await softrClient.getTable({ apiKey, databaseId, tableId });
+ const conditions = readConditions({ rawConditions: propsValue.conditions ?? [], fields: table.fields });
+ const sortReference = propsValue.sortField?.trim();
+ const sortFieldId = sortReference ? softrSearch.resolveSortField({ fields: table.fields, reference: sortReference }) : undefined;
+
+ const response = await softrRecords.searchRecords({
+ apiKey,
+ databaseId,
+ tableId,
+ body: {
+ paging: { offset, limit },
+ ...(conditions.length > 0 ? { filter: { condition: { operator: matchType, conditions } } } : {}),
+ ...(sortFieldId ? { sorting: [{ sortingField: sortFieldId, sortType: sortDirection }] } : {}),
+ },
+ });
+
+ const records = (response.data ?? []).map((record) =>
+ softrClient.withFieldNames({ record, tableFields: table.fields }),
+ );
+ const total = response.metadata?.total ?? null;
+ return {
+ found: records.length > 0,
+ count: records.length,
+ total,
+ offset,
+ hasMore: total === null ? records.length === limit : offset + records.length < total,
+ records,
+ };
+ },
+});
+
+type ReadNumberParams = {
+ value: number | undefined | null;
+ name: string;
+ min: number;
+ max: number;
+ fallback: number;
+};
diff --git a/packages/pieces/community/softr/src/lib/actions/generate-magic-link.ts b/packages/pieces/community/softr/src/lib/actions/generate-magic-link.ts
new file mode 100644
index 00000000000..70c907e4a6b
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/actions/generate-magic-link.ts
@@ -0,0 +1,57 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { SoftrAuth } from '../common/auth';
+import { softrClient } from '../common/client';
+import { appDomainField, appUserEmailField } from '../common/props';
+import { softrOutputSchemas } from '../output-schemas';
+
+const LINK_KEYS = ['magic_link', 'magicLink', 'link', 'url'];
+
+function readMagicLink(body: unknown): string | null {
+ if (typeof body === 'string') {
+ const trimmed = body.trim().replace(/^"|"$/g, '');
+ return trimmed.length > 0 ? trimmed : null;
+ }
+ if (typeof body !== 'object' || body === null) {
+ return null;
+ }
+ const entries = Object.entries(body);
+ const match = entries.find(([key, value]) => LINK_KEYS.includes(key) && typeof value === 'string');
+ return match ? String(match[1]) : null;
+}
+
+export const generateMagicLink = createAction({
+ auth: SoftrAuth,
+ name: 'generateMagicLink',
+ classification: 'WRITE',
+ displayName: 'Generate Magic Link',
+ description: 'Generates a magic login link for a user of a Softr app.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Creates a magic login link for an existing user of a published Softr app and returns it, so you can send it another way. Needs the app domain and user email. Each call makes a new link.',
+ idempotent: false,
+ },
+ props: {
+ email: appUserEmailField,
+ domain: appDomainField,
+ },
+ outputSchema: softrOutputSchemas.magicLink,
+ async run({ auth, propsValue }) {
+ const email = propsValue.email.trim();
+ if (email.length === 0) {
+ throw new Error('User email is required.');
+ }
+ const response = await softrClient.studioRequest({
+ apiKey: auth.secret_text,
+ domain: propsValue.domain,
+ method: HttpMethod.POST,
+ path: `/magic-link/generate/${encodeURIComponent(email)}`,
+ });
+ const magicLink = readMagicLink(response.body);
+ if (magicLink === null) {
+ throw new Error('Softr did not return a magic link for this user.');
+ }
+ return { email, magicLink };
+ },
+});
diff --git a/packages/pieces/community/softr/src/lib/actions/get-database-record.ts b/packages/pieces/community/softr/src/lib/actions/get-database-record.ts
new file mode 100644
index 00000000000..0c4ca1906a9
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/actions/get-database-record.ts
@@ -0,0 +1,42 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { SoftrAuth } from '../common/auth';
+import { softrClient } from '../common/client';
+import { databaseIdDropdown, recordIdField, tableIdDropdown } from '../common/props';
+import { SoftrRecord, SoftrSingleResponse } from '../common/types';
+import { softrOutputSchemas } from '../output-schemas';
+
+export const getDatabaseRecord = createAction({
+ auth: SoftrAuth,
+ name: 'getDatabaseRecord',
+ classification: 'READ',
+ displayName: 'Get Database Record',
+ description: 'Retrieves a single record by its ID.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Gets one record from a Softr table by its record ID, with values keyed by column name. To look records up by value, use Find Records. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ databaseId: databaseIdDropdown,
+ tableId: tableIdDropdown,
+ recordId: recordIdField,
+ },
+ outputSchema: softrOutputSchemas.record,
+ async run({ auth, propsValue }) {
+ const { databaseId, tableId } = propsValue;
+ const recordId = propsValue.recordId.trim();
+ if (recordId.length === 0) {
+ throw new Error('Record ID is required.');
+ }
+ const apiKey = auth.secret_text;
+ const table = await softrClient.getTable({ apiKey, databaseId, tableId });
+ const response = await softrClient.request<SoftrSingleResponse<SoftrRecord>>({
+ apiKey,
+ method: HttpMethod.GET,
+ path: softrClient.recordPath({ databaseId, tableId, recordId }),
+ });
+ return softrClient.withFieldNames({ record: response.data, tableFields: table.fields });
+ },
+});
diff --git a/packages/pieces/community/softr/src/lib/actions/get-database-schema-ai.ts b/packages/pieces/community/softr/src/lib/actions/get-database-schema-ai.ts
new file mode 100644
index 00000000000..be0090071d3
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/actions/get-database-schema-ai.ts
@@ -0,0 +1,46 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { SoftrAuth } from '../common/auth';
+import { softrAgent } from '../common/agent';
+import { agentDatabaseIdField } from '../common/props';
+import { softrOutputSchemas } from '../output-schemas';
+
+export const getDatabaseSchemaAi = createAction({
+ auth: SoftrAuth,
+ name: 'get_database_schema_ai',
+ classification: 'READ',
+ displayName: 'Get Database Schema (Agent)',
+ description: 'Gets every table and column in a Softr database.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns every table in a Softr database with all its columns: field ID, column name, type, required, read-only and select options (ID and label). Call this first, before you create, update or search records. Needs the database ID from List Databases. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ databaseId: agentDatabaseIdField,
+ },
+ outputSchema: softrOutputSchemas.databaseSchema,
+ async run({ auth, propsValue }) {
+ const databaseId = softrAgent.requireText({ value: propsValue.databaseId, label: 'Database ID' });
+ const tables = await softrAgent.listTables({ apiKey: auth.secret_text, databaseId });
+ return {
+ databaseId,
+ tableCount: tables.length,
+ tables: tables.map((table) => ({
+ id: table.id,
+ name: table.name,
+ description: table.description ?? null,
+ primaryFieldId: table.primaryFieldId ?? null,
+ fields: (table.fields ?? []).map((field) => ({
+ id: field.id,
+ name: field.name,
+ type: field.type,
+ required: field.required ?? false,
+ readonly: field.readonly,
+ allowMultipleEntries: field.allowMultipleEntries,
+ options: (field.options?.choices ?? []).map((choice) => ({ id: choice.id, label: choice.label })),
+ })),
+ })),
+ };
+ },
+});
diff --git a/packages/pieces/community/softr/src/lib/actions/get-database.ts b/packages/pieces/community/softr/src/lib/actions/get-database.ts
new file mode 100644
index 00000000000..e32878e6f89
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/actions/get-database.ts
@@ -0,0 +1,35 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { SoftrAuth } from '../common/auth';
+import { softrClient } from '../common/client';
+import { softrAdmin } from '../common/admin';
+import { databaseIdDropdown } from '../common/props';
+import { SoftrDatabase, SoftrSingleResponse } from '../common/types';
+import { softrOutputSchemas } from '../output-schemas';
+
+export const getDatabase = createAction({
+ auth: SoftrAuth,
+ name: 'getDatabase',
+ classification: 'READ',
+ displayName: 'Get Database',
+ description: 'Retrieves a Softr database by its ID.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Gets one Softr database by ID: name, description, workspace ID and table count. Use List Databases to find the ID. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ databaseId: databaseIdDropdown,
+ },
+ outputSchema: softrOutputSchemas.database,
+ async run({ auth, propsValue }) {
+ const databaseId = softrAdmin.requireId({ value: propsValue.databaseId, label: 'Database ID' });
+ const response = await softrClient.request<SoftrSingleResponse<SoftrDatabase>>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ path: softrClient.databasePath({ databaseId }),
+ });
+ return response.data;
+ },
+});
diff --git a/packages/pieces/community/softr/src/lib/actions/get-table-field.ts b/packages/pieces/community/softr/src/lib/actions/get-table-field.ts
new file mode 100644
index 00000000000..3803bb99b81
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/actions/get-table-field.ts
@@ -0,0 +1,39 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { SoftrAuth } from '../common/auth';
+import { softrClient } from '../common/client';
+import { softrAdmin } from '../common/admin';
+import { databaseIdDropdown, tableFieldIdDropdown, tableIdDropdown } from '../common/props';
+import { SoftrSingleResponse, TableField } from '../common/types';
+import { softrOutputSchemas } from '../output-schemas';
+
+export const getTableField = createAction({
+ auth: SoftrAuth,
+ name: 'getTableField',
+ classification: 'READ',
+ displayName: 'Get Table Field',
+ description: 'Retrieves one field definition of a Softr table.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Gets one column of a Softr table by field ID: name, type, options (such as select choices), read-only and required. To see all columns at once, use Get Table. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ databaseId: databaseIdDropdown,
+ tableId: tableIdDropdown,
+ fieldId: tableFieldIdDropdown,
+ },
+ outputSchema: softrOutputSchemas.field,
+ async run({ auth, propsValue }) {
+ const databaseId = softrAdmin.requireId({ value: propsValue.databaseId, label: 'Database ID' });
+ const tableId = softrAdmin.requireId({ value: propsValue.tableId, label: 'Table ID' });
+ const fieldId = softrAdmin.requireId({ value: propsValue.fieldId, label: 'Field ID' });
+ const response = await softrClient.request<SoftrSingleResponse<TableField>>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ path: softrClient.fieldPath({ databaseId, tableId, fieldId }),
+ });
+ return response.data;
+ },
+});
diff --git a/packages/pieces/community/softr/src/lib/actions/get-table.ts b/packages/pieces/community/softr/src/lib/actions/get-table.ts
new file mode 100644
index 00000000000..0efe42abcdd
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/actions/get-table.ts
@@ -0,0 +1,31 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { SoftrAuth } from '../common/auth';
+import { softrClient } from '../common/client';
+import { databaseIdDropdown, tableIdDropdown } from '../common/props';
+import { softrOutputSchemas } from '../output-schemas';
+
+export const getTable = createAction({
+ auth: SoftrAuth,
+ name: 'getTable',
+ classification: 'READ',
+ displayName: 'Get Table',
+ description: 'Retrieves a table and its field definitions.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Gets one Softr table with all its columns: field IDs, names, types, select options, read-only and required. Use it before writing or searching records; agents can use Get Database Schema (Agent) to see every table in one call. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ databaseId: databaseIdDropdown,
+ tableId: tableIdDropdown,
+ },
+ outputSchema: softrOutputSchemas.table,
+ async run({ auth, propsValue }) {
+ return softrClient.getTable({
+ apiKey: auth.secret_text,
+ databaseId: propsValue.databaseId,
+ tableId: propsValue.tableId,
+ });
+ },
+});
diff --git a/packages/pieces/community/softr/src/lib/actions/invite-app-user.ts b/packages/pieces/community/softr/src/lib/actions/invite-app-user.ts
new file mode 100644
index 00000000000..ca291ac4210
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/actions/invite-app-user.ts
@@ -0,0 +1,38 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { SoftrAuth } from '../common/auth';
+import { softrClient } from '../common/client';
+import { appDomainField, appUserEmailField } from '../common/props';
+import { softrOutputSchemas } from '../output-schemas';
+
+export const inviteAppUser = createAction({
+ auth: SoftrAuth,
+ name: 'inviteAppUser',
+ classification: 'WRITE',
+ displayName: 'Invite App User',
+ description: 'Sends an invitation email to an existing user of a Softr app.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Sends a Softr invitation email to an existing user of a published Softr app and marks them Invited. Needs the app domain and user email; create the user first with Create App User. Each call sends another email.',
+ idempotent: false,
+ },
+ props: {
+ email: appUserEmailField,
+ domain: appDomainField,
+ },
+ outputSchema: softrOutputSchemas.appUserStatus,
+ async run({ auth, propsValue }) {
+ const email = propsValue.email.trim();
+ if (email.length === 0) {
+ throw new Error('User email is required.');
+ }
+ await softrClient.studioRequest({
+ apiKey: auth.secret_text,
+ domain: propsValue.domain,
+ method: HttpMethod.POST,
+ path: `/${encodeURIComponent(email)}/invite`,
+ });
+ return { success: true, email, message: 'Invitation sent' };
+ },
+});
diff --git a/packages/pieces/community/softr/src/lib/actions/list-databases.ts b/packages/pieces/community/softr/src/lib/actions/list-databases.ts
new file mode 100644
index 00000000000..70fec966b34
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/actions/list-databases.ts
@@ -0,0 +1,31 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { SoftrAuth } from '../common/auth';
+import { softrClient } from '../common/client';
+import { SoftrDatabase, SoftrListResponse } from '../common/types';
+import { softrOutputSchemas } from '../output-schemas';
+
+export const listDatabases = createAction({
+ auth: SoftrAuth,
+ name: 'listDatabases',
+ classification: 'SEARCH',
+ displayName: 'List Databases',
+ description: 'Lists the Softr databases the API key can access.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Lists every Softr database the API key can access, with ID, name and table count. Call this first to get the database ID that the other actions need. Read-only.',
+ idempotent: true,
+ },
+ props: {},
+ outputSchema: softrOutputSchemas.listDatabases,
+ async run({ auth }) {
+ const response = await softrClient.request<SoftrListResponse<SoftrDatabase>>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ path: '/databases',
+ });
+ const databases = response.data ?? [];
+ return { count: databases.length, databases };
+ },
+});
diff --git a/packages/pieces/community/softr/src/lib/actions/list-table-views.ts b/packages/pieces/community/softr/src/lib/actions/list-table-views.ts
new file mode 100644
index 00000000000..0d966a5d7c0
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/actions/list-table-views.ts
@@ -0,0 +1,38 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { SoftrAuth } from '../common/auth';
+import { softrClient } from '../common/client';
+import { softrAdmin } from '../common/admin';
+import { databaseIdDropdown, tableIdDropdown } from '../common/props';
+import { SoftrListResponse, SoftrTableView } from '../common/types';
+import { softrOutputSchemas } from '../output-schemas';
+
+export const listTableViews = createAction({
+ auth: SoftrAuth,
+ name: 'listTableViews',
+ classification: 'SEARCH',
+ displayName: 'List Table Views',
+ description: 'Lists the views of a Softr table.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Lists the views of a Softr table, with view IDs and names. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ databaseId: databaseIdDropdown,
+ tableId: tableIdDropdown,
+ },
+ outputSchema: softrOutputSchemas.tableViews,
+ async run({ auth, propsValue }) {
+ const databaseId = softrAdmin.requireId({ value: propsValue.databaseId, label: 'Database ID' });
+ const tableId = softrAdmin.requireId({ value: propsValue.tableId, label: 'Table ID' });
+ const response = await softrClient.request<SoftrListResponse<SoftrTableView>>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ path: `${softrClient.tablePath({ databaseId, tableId })}/views`,
+ });
+ const views = response.data ?? [];
+ return { count: views.length, views };
+ },
+});
diff --git a/packages/pieces/community/softr/src/lib/actions/list-tables.ts b/packages/pieces/community/softr/src/lib/actions/list-tables.ts
new file mode 100644
index 00000000000..675f5c659f0
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/actions/list-tables.ts
@@ -0,0 +1,34 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { SoftrAuth } from '../common/auth';
+import { softrClient } from '../common/client';
+import { databaseIdDropdown } from '../common/props';
+import { SoftrListResponse, SoftrTable } from '../common/types';
+import { softrOutputSchemas } from '../output-schemas';
+
+export const listTables = createAction({
+ auth: SoftrAuth,
+ name: 'listTables',
+ classification: 'SEARCH',
+ displayName: 'List Tables',
+ description: 'Lists the tables in a Softr database, including their fields.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Lists the tables in a Softr database with their IDs, names and columns. Agents: Get Database Schema (Agent) returns the same in a simpler shape, with select options. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ databaseId: databaseIdDropdown,
+ },
+ outputSchema: softrOutputSchemas.listTables,
+ async run({ auth, propsValue }) {
+ const response = await softrClient.request<SoftrListResponse<SoftrTable>>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ path: `/databases/${encodeURIComponent(propsValue.databaseId)}/tables`,
+ });
+ const tables = response.data ?? [];
+ return { count: tables.length, tables };
+ },
+});
diff --git a/packages/pieces/community/softr/src/lib/actions/update-database-record.ts b/packages/pieces/community/softr/src/lib/actions/update-database-record.ts
index 14b524dbfda..b70ac4139a9 100644
--- a/packages/pieces/community/softr/src/lib/actions/update-database-record.ts
+++ b/packages/pieces/community/softr/src/lib/actions/update-database-record.ts
@@ -1,10 +1,8 @@
import { createAction } from '@activepieces/pieces-framework';
-import { HttpMethod } from '@activepieces/pieces-common';
import { SoftrAuth } from '../common/auth';
-import { makeRequest, transformRecordFields } from '../common/client';
import { databaseIdDropdown, recordIdField, tableFields, tableIdDropdown } from '../common/props';
-import { isNil } from '@activepieces/pieces-framework';
-import { TableField } from '../common/types';
+import { softrRecords } from '../common/records';
+import { softrOutputSchemas } from '../output-schemas';
export const updateDatabaseRecord = createAction({
auth: SoftrAuth,
@@ -12,44 +10,33 @@ export const updateDatabaseRecord = createAction({
classification: 'WRITE',
displayName: 'Update Database Record',
description: 'Updates an existing database record.',
- audience: 'both',
- aiMetadata: { description: 'Updates an existing record in a chosen table of a Softr database, identified by its record ID, applying the supplied field values (empty values are dropped, so it is a partial patch — omitted fields are left unchanged). Use when you already hold the target record ID. Idempotent when called with the same field values.', idempotent: true },
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Changes some fields of one existing Softr record by its record ID, using the table field form. Only the given fields change; empty values are skipped, so it cannot clear a field. Safe to retry.',
+ idempotent: true,
+ },
props: {
databaseId: databaseIdDropdown,
tableId: tableIdDropdown,
recordId: recordIdField,
fields: tableFields,
},
+ outputSchema: softrOutputSchemas.record,
async run({ auth, propsValue }) {
- const { databaseId, tableId, recordId } = propsValue;
-
- const fields = propsValue.fields ?? {};
-
- const formattedFields: Record<string, any> = {};
-
- for (const [key, value] of Object.entries(fields)) {
- if (isNil(value) || value === '') continue;
- if (Array.isArray(value) && value.length === 0) continue;
- formattedFields[key] = value;
+ const recordId = propsValue.recordId.trim();
+ if (recordId.length === 0) {
+ throw new Error('Record ID is required.');
}
-
- const response = await makeRequest<{
- data: { id: string; createdAt: string; updatedAt: string; fields: Record<string, any> };
- }>(auth, HttpMethod.PATCH, `/databases/${databaseId}/tables/${tableId}/records/${recordId}`, {
- fields: formattedFields,
+ if (Object.keys(softrRecords.compactFieldValues(propsValue.fields)).length === 0) {
+ throw new Error('Provide a value for at least one field to update.');
+ }
+ return softrRecords.writeRecord({
+ apiKey: auth.secret_text,
+ databaseId: propsValue.databaseId,
+ tableId: propsValue.tableId,
+ recordId,
+ fields: propsValue.fields,
});
-
- const tableReponse = await makeRequest<{
- data: {
- fields: TableField[];
- };
- }>(auth, HttpMethod.GET, `/databases/${databaseId}/tables/${tableId}`);
-
- const transformedFields = transformRecordFields(tableReponse.data.fields, response.data.fields);
-
- return {
- ...response.data,
- fields: transformedFields,
- };
},
});
diff --git a/packages/pieces/community/softr/src/lib/actions/update-database.ts b/packages/pieces/community/softr/src/lib/actions/update-database.ts
new file mode 100644
index 00000000000..34d5026300b
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/actions/update-database.ts
@@ -0,0 +1,51 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { SoftrAuth } from '../common/auth';
+import { softrClient } from '../common/client';
+import { softrAdmin } from '../common/admin';
+import { databaseIdDropdown } from '../common/props';
+import { SoftrDatabase, SoftrSingleResponse } from '../common/types';
+import { softrOutputSchemas } from '../output-schemas';
+
+export const updateDatabase = createAction({
+ auth: SoftrAuth,
+ name: 'updateDatabase',
+ classification: 'WRITE',
+ displayName: 'Update Database',
+ description: 'Renames a Softr database or changes its description.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Renames a Softr database and/or changes its description. Only the values you give change; the API cannot clear a description. Safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ databaseId: databaseIdDropdown,
+ name: Property.ShortText({
+ displayName: 'New Name',
+ description: 'Leave empty to keep the current name.',
+ required: false,
+ }),
+ description: Property.LongText({
+ displayName: 'New Description',
+ description: 'Leave empty to keep the current description.',
+ required: false,
+ }),
+ },
+ outputSchema: softrOutputSchemas.database,
+ async run({ auth, propsValue }) {
+ const databaseId = softrAdmin.requireId({ value: propsValue.databaseId, label: 'Database ID' });
+ const body = softrAdmin.buildNameDescriptionUpdate({
+ name: propsValue.name,
+ description: propsValue.description,
+ clearDescription: false,
+ });
+ const response = await softrClient.request<SoftrSingleResponse<SoftrDatabase>>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.PUT,
+ path: softrClient.databasePath({ databaseId }),
+ body,
+ });
+ return response.data;
+ },
+});
diff --git a/packages/pieces/community/softr/src/lib/actions/update-record-ai.ts b/packages/pieces/community/softr/src/lib/actions/update-record-ai.ts
new file mode 100644
index 00000000000..206dbeaa343
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/actions/update-record-ai.ts
@@ -0,0 +1,41 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { SoftrAuth } from '../common/auth';
+import { softrAgent } from '../common/agent';
+import { agentDatabaseIdField, agentFieldsJson, agentTableField } from '../common/props';
+import { softrRecords } from '../common/records';
+import { softrOutputSchemas } from '../output-schemas';
+
+export const updateRecordAi = createAction({
+ auth: SoftrAuth,
+ name: 'update_record_ai',
+ classification: 'WRITE',
+ displayName: 'Update Record (Agent)',
+ description: 'Changes some columns of a Softr record using column names.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Changes the given columns of one existing Softr record; other columns stay as they are. Agents: use this instead of Update Database Record. Needs the database ID, the table name or ID, the record ID (from Find Records) and a JSON object of new values keyed by column name or field ID. Empty values are skipped, so it cannot clear a column. Returns the updated record. Safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ databaseId: agentDatabaseIdField,
+ table: agentTableField,
+ recordId: Property.ShortText({
+ displayName: 'Record ID',
+ description: 'The ID of the record to change. Get it from Find Records.',
+ required: true,
+ }),
+ fields: agentFieldsJson,
+ },
+ outputSchema: softrOutputSchemas.record,
+ async run({ auth, propsValue }) {
+ const apiKey = auth.secret_text;
+ const databaseId = softrAgent.requireText({ value: propsValue.databaseId, label: 'Database ID' });
+ const reference = softrAgent.requireText({ value: propsValue.table, label: 'Table' });
+ const recordId = softrAgent.requireText({ value: propsValue.recordId, label: 'Record ID' });
+ const input = softrAgent.parseFieldsInput(propsValue.fields);
+ const table = await softrAgent.resolveTable({ apiKey, databaseId, reference });
+ const fields = softrAgent.buildFieldValues({ table, fields: input });
+ return softrRecords.writeRecord({ apiKey, databaseId, tableId: table.id, recordId, fields, tableFields: table.fields });
+ },
+});
diff --git a/packages/pieces/community/softr/src/lib/actions/update-table-field.ts b/packages/pieces/community/softr/src/lib/actions/update-table-field.ts
new file mode 100644
index 00000000000..dc2411eaa4a
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/actions/update-table-field.ts
@@ -0,0 +1,67 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { SoftrAuth } from '../common/auth';
+import { softrClient } from '../common/client';
+import { softrAdmin } from '../common/admin';
+import { databaseIdDropdown, tableFieldIdDropdown, tableIdDropdown } from '../common/props';
+import { SoftrSingleResponse, TableField } from '../common/types';
+import { softrOutputSchemas } from '../output-schemas';
+
+export const updateTableField = createAction({
+ auth: SoftrAuth,
+ name: 'updateTableField',
+ classification: 'WRITE',
+ displayName: 'Update Table Field',
+ description: 'Renames a field, changes its type, or changes its options.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Changes a column of a Softr table: name, type and/or JSON options. Empty inputs keep the current value. New options replace all existing options, e.g. the full list of select choices. Changing the type can convert or drop data, so only do it when the user asked. Safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ databaseId: databaseIdDropdown,
+ tableId: tableIdDropdown,
+ fieldId: tableFieldIdDropdown,
+ name: Property.ShortText({
+ displayName: 'New Name',
+ description: 'Leave empty to keep the current name.',
+ required: false,
+ }),
+ type: softrAdmin.fieldTypeDropdown({ required: false }),
+ options: Property.Json({
+ displayName: 'New Options',
+ description: 'Leave empty to keep. When set, replaces all options and choices.',
+ required: false,
+ }),
+ },
+ outputSchema: softrOutputSchemas.field,
+ async run({ auth, propsValue }) {
+ const databaseId = softrAdmin.requireId({ value: propsValue.databaseId, label: 'Database ID' });
+ const tableId = softrAdmin.requireId({ value: propsValue.tableId, label: 'Table ID' });
+ const fieldId = softrAdmin.requireId({ value: propsValue.fieldId, label: 'Field ID' });
+ const name = softrAdmin.optionalText(propsValue.name);
+ const type = propsValue.type === undefined || propsValue.type === null || propsValue.type === '' ? undefined : softrAdmin.readFieldType(propsValue.type);
+ const options = softrAdmin.parseOptions({ value: propsValue.options, label: 'New Options' });
+ if (name === undefined && type === undefined && options === undefined) {
+ throw new Error('Provide a new name, type or options.');
+ }
+ const apiKey = auth.secret_text;
+ const path = softrClient.fieldPath({ databaseId, tableId, fieldId });
+ const current = await softrClient.request<SoftrSingleResponse<TableField>>({ apiKey, method: HttpMethod.GET, path });
+ const nextType = type ?? current.data.type;
+ const keepOptions = nextType === current.data.type ? current.data.options : undefined;
+ const nextOptions = options ?? keepOptions;
+ const response = await softrClient.request<SoftrSingleResponse<TableField>>({
+ apiKey,
+ method: HttpMethod.PUT,
+ path,
+ body: {
+ name: name ?? current.data.name,
+ type: nextType,
+ ...(nextOptions !== undefined && nextOptions !== null ? { options: nextOptions } : {}),
+ },
+ });
+ return response.data;
+ },
+});
diff --git a/packages/pieces/community/softr/src/lib/actions/update-table.ts b/packages/pieces/community/softr/src/lib/actions/update-table.ts
new file mode 100644
index 00000000000..87ac4f6f301
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/actions/update-table.ts
@@ -0,0 +1,60 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { SoftrAuth } from '../common/auth';
+import { softrClient } from '../common/client';
+import { softrAdmin } from '../common/admin';
+import { databaseIdDropdown, tableIdDropdown } from '../common/props';
+import { SoftrSingleResponse, SoftrTable } from '../common/types';
+import { softrOutputSchemas } from '../output-schemas';
+
+export const updateTable = createAction({
+ auth: SoftrAuth,
+ name: 'updateTable',
+ classification: 'WRITE',
+ displayName: 'Update Table',
+ description: 'Renames a Softr table or changes its description.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Renames a Softr table and/or changes its description (use Update Table Field for columns). Only the values you give change; tick Clear Description to blank it. Safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ databaseId: databaseIdDropdown,
+ tableId: tableIdDropdown,
+ name: Property.ShortText({
+ displayName: 'New Name',
+ description: 'Leave empty to keep the current name.',
+ required: false,
+ }),
+ description: Property.LongText({
+ displayName: 'New Description',
+ description: 'Leave empty to keep the current description.',
+ required: false,
+ }),
+ clearDescription: Property.Checkbox({
+ displayName: 'Clear Description',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ outputSchema: softrOutputSchemas.table,
+ async run({ auth, propsValue }) {
+ const databaseId = softrAdmin.requireId({ value: propsValue.databaseId, label: 'Database ID' });
+ const tableId = softrAdmin.requireId({ value: propsValue.tableId, label: 'Table ID' });
+ const body = softrAdmin.buildNameDescriptionUpdate({
+ name: propsValue.name,
+ description: propsValue.description,
+ clearDescription: propsValue.clearDescription,
+ });
+ const apiKey = auth.secret_text;
+ const name = body['name'] ?? (await softrClient.getTable({ apiKey, databaseId, tableId })).name;
+ const response = await softrClient.request<SoftrSingleResponse<SoftrTable>>({
+ apiKey,
+ method: HttpMethod.PUT,
+ path: softrClient.tablePath({ databaseId, tableId }),
+ body: { ...body, name },
+ });
+ return response.data;
+ },
+});
diff --git a/packages/pieces/community/softr/src/lib/actions/upsert-record-ai.ts b/packages/pieces/community/softr/src/lib/actions/upsert-record-ai.ts
new file mode 100644
index 00000000000..adf13a0031f
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/actions/upsert-record-ai.ts
@@ -0,0 +1,39 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { SoftrAuth } from '../common/auth';
+import { softrAgent } from '../common/agent';
+import { agentDatabaseIdField, agentFieldsJson, agentTableField } from '../common/props';
+import { softrOutputSchemas } from '../output-schemas';
+
+export const upsertRecordAi = createAction({
+ auth: SoftrAuth,
+ name: 'upsert_record_ai',
+ classification: 'WRITE',
+ displayName: 'Upsert Record (Agent)',
+ description: 'Updates the record whose key column matches, or creates it.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Finds the record whose key column equals the key value in Fields (matching ignores letter case). If none exists it creates one; if one exists it updates it; 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: Softr has no atomic create-if-absent, so two parallel calls with the same new key can both create a record. Needs the database ID, the table name or ID, the key column, and Fields including the key value. Returns {action: "created" or "updated", record}. Safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ databaseId: agentDatabaseIdField,
+ table: agentTableField,
+ keyField: Property.ShortText({
+ displayName: 'Key Column (name or ID)',
+ description: 'The column that identifies the record, e.g. Email.',
+ required: true,
+ }),
+ fields: agentFieldsJson,
+ },
+ outputSchema: softrOutputSchemas.upsertRecord,
+ async run({ auth, propsValue }) {
+ const apiKey = auth.secret_text;
+ const databaseId = softrAgent.requireText({ value: propsValue.databaseId, label: 'Database ID' });
+ const reference = softrAgent.requireText({ value: propsValue.table, label: 'Table' });
+ const keyField = softrAgent.requireText({ value: propsValue.keyField, label: 'Key Column' });
+ const fields = softrAgent.parseFieldsInput(propsValue.fields);
+ const table = await softrAgent.resolveTable({ apiKey, databaseId, reference });
+ return softrAgent.upsertRecord({ apiKey, databaseId, table, keyField, fields });
+ },
+});
diff --git a/packages/pieces/community/softr/src/lib/common/admin.ts b/packages/pieces/community/softr/src/lib/common/admin.ts
new file mode 100644
index 00000000000..e7ce50915f7
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/common/admin.ts
@@ -0,0 +1,114 @@
+import { Property } from '@activepieces/pieces-framework';
+
+const FIELD_TYPES = [
+ 'SINGLE_LINE_TEXT',
+ 'LONG_TEXT',
+ 'NUMBER',
+ 'CURRENCY',
+ 'PERCENT',
+ 'RATING',
+ 'CHECKBOX',
+ 'DATETIME',
+ 'DURATION',
+ 'EMAIL',
+ 'URL',
+ 'PHONE',
+ 'SELECT',
+ 'ATTACHMENT',
+ 'LINKED_RECORD',
+ 'USER',
+ 'LOOKUP',
+ 'ROLLUP',
+ 'FORMULA',
+ 'CREATED_AT',
+ 'UPDATED_AT',
+ 'CREATED_BY',
+ 'UPDATED_BY',
+ 'AUTONUMBER',
+ 'RECORD_ID',
+];
+
+function requireId({ 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 optionalText(value: unknown): string | undefined {
+ if (typeof value !== 'string') {
+ return undefined;
+ }
+ const trimmed = value.trim();
+ return trimmed.length > 0 ? trimmed : undefined;
+}
+
+function parseOptions({ value, label }: { value: unknown; label: string }): Record<string, unknown> | undefined {
+ if (value === undefined || value === null || value === '') {
+ return undefined;
+ }
+ const parsed: unknown = typeof value === 'string' ? safeParse({ text: value, label }) : value;
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
+ throw new Error(`${label} must be a JSON object, e.g. {"choices":[{"label":"Open"}]}.`);
+ }
+ return Object.fromEntries(Object.entries(parsed));
+}
+
+function safeParse({ text, label }: { text: string; label: string }): unknown {
+ try {
+ return JSON.parse(text);
+ } catch {
+ throw new Error(`${label} is not valid JSON.`);
+ }
+}
+
+function readFieldType(value: unknown): string {
+ const type = typeof value === 'string' ? value.trim().toUpperCase() : '';
+ if (!FIELD_TYPES.includes(type)) {
+ throw new Error(
+ `Field type "${String(value ?? '')}" cannot be created through the Softr API. Use one of: ${FIELD_TYPES.join(', ')}. For a date-only field use DATETIME with options {"precision":"DATE"}.`,
+ );
+ }
+ return type;
+}
+
+function buildNameDescriptionUpdate({ name, description, clearDescription }: NameDescriptionInput): Record<string, string> {
+ const body: Record<string, string> = {};
+ const trimmedName = optionalText(name);
+ if (trimmedName !== undefined) {
+ body['name'] = trimmedName;
+ }
+ if (clearDescription === true) {
+ body['description'] = '';
+ } else if (typeof description === 'string' && description.length > 0) {
+ body['description'] = description;
+ }
+ if (Object.keys(body).length === 0) {
+ throw new Error('Provide a new name or a new description.');
+ }
+ return body;
+}
+
+const fieldTypeDropdown = ({ required }: { required: boolean }) =>
+ Property.StaticDropdown({
+ displayName: 'Field Type',
+ required,
+ options: { options: FIELD_TYPES.map((type) => ({ label: type, value: type })) },
+ });
+
+type NameDescriptionInput = {
+ name: unknown;
+ description: unknown;
+ clearDescription: unknown;
+};
+
+export const softrAdmin = {
+ requireId,
+ optionalText,
+ parseOptions,
+ readFieldType,
+ buildNameDescriptionUpdate,
+ fieldTypeDropdown,
+ fieldTypes: FIELD_TYPES,
+};
diff --git a/packages/pieces/community/softr/src/lib/common/agent.ts b/packages/pieces/community/softr/src/lib/common/agent.ts
new file mode 100644
index 00000000000..7fddc5fe03b
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/common/agent.ts
@@ -0,0 +1,221 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { softrClient } from './client';
+import { softrRecords } from './records';
+import { softrSearch } from './search';
+import { SoftrListResponse, SoftrRecord, SoftrTable, TableField } from './types';
+
+const NUMERIC_TYPES = ['NUMBER', 'CURRENCY', 'PERCENT', 'RATING', 'DURATION'];
+
+async function listTables({ apiKey, databaseId }: { apiKey: string; databaseId: string }): Promise<SoftrTable[]> {
+ const response = await softrClient.request<SoftrListResponse<SoftrTable>>({
+ apiKey,
+ method: HttpMethod.GET,
+ path: `${softrClient.databasePath({ databaseId })}/tables`,
+ });
+ return response.data ?? [];
+}
+
+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 pickTable({ tables, reference }: { tables: SoftrTable[]; reference: string }): SoftrTable {
+ 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 database. Tables: ${names || 'none'}.`);
+}
+
+async function resolveTable({ apiKey, databaseId, reference }: ResolveTableParams): Promise<SoftrTable> {
+ const tables = await listTables({ apiKey, databaseId });
+ const table = pickTable({ tables, reference });
+ if (Array.isArray(table.fields)) {
+ return table;
+ }
+ return softrClient.getTable({ apiKey, databaseId, tableId: table.id });
+}
+
+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 writableNames(fields: TableField[]): string {
+ return fields
+ .filter((field) => !field.readonly)
+ .map((field) => field.name)
+ .join(', ');
+}
+
+function findColumn({ fields, reference }: { fields: TableField[]; reference: string }): TableField {
+ 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 Database Schema (Agent)).`);
+ }
+ throw new Error(`Column "${trimmed}" does not exist in this table. Valid columns: ${writableNames(fields)}.`);
+}
+
+function toChoiceId({ field, value }: { field: TableField; value: unknown }): string {
+ const choices = field.options?.choices ?? [];
+ const text = typeof value === 'string' ? value.trim() : String(value);
+ if (choices.length === 0) {
+ return text;
+ }
+ const match =
+ choices.find((choice) => choice.id === text) ??
+ choices.find((choice) => choice.label.toLowerCase() === text.toLowerCase());
+ if (!match) {
+ const labels = choices.map((choice) => choice.label).join(', ');
+ throw new Error(`A value given for column "${field.name}" is not one of its options. Options: ${labels}.`);
+ }
+ return match.id;
+}
+
+function convertSelect({ field, value }: { field: TableField; value: unknown }): string | string[] {
+ const items = Array.isArray(value) ? value : [value];
+ const ids = items.map((item) => toChoiceId({ field, value: item }));
+ if (field.allowMultipleEntries) {
+ return ids;
+ }
+ if (ids.length !== 1) {
+ throw new Error(`Column "${field.name}" holds a single option, so give one value (got ${ids.length}).`);
+ }
+ return ids[0];
+}
+
+function convertValue({ field, value }: { field: TableField; value: unknown }): unknown {
+ if (value === undefined || value === null || value === '') {
+ return value;
+ }
+ if (field.type === 'SELECT') {
+ return convertSelect({ field, value });
+ }
+ if (NUMERIC_TYPES.includes(field.type) || field.type === 'CHECKBOX') {
+ if (typeof value === 'object') {
+ throw new Error(`Column "${field.name}" (${field.type}) needs a single value, not a list or object.`);
+ }
+ return softrSearch.coerceScalar({ field, value });
+ }
+ return value;
+}
+
+function buildFieldValues({ table, fields }: { table: SoftrTable; fields: Record<string, unknown> }): Record<string, unknown> {
+ const values: Record<string, unknown> = {};
+ for (const [reference, value] of Object.entries(fields)) {
+ const field = findColumn({ fields: table.fields, reference });
+ if (field.readonly) {
+ throw new Error(`Column "${field.name}" (${field.type}) is read-only. Writable columns: ${writableNames(table.fields)}.`);
+ }
+ if (field.id in values) {
+ throw new Error(`Column "${field.name}" is given more than once.`);
+ }
+ values[field.id] = convertValue({ field, value });
+ }
+ const compacted = softrRecords.compactFieldValues(values);
+ if (Object.keys(compacted).length === 0) {
+ throw new Error('Fields is empty. Give at least one column with a non-empty value.');
+ }
+ return compacted;
+}
+
+async function upsertRecord({ apiKey, databaseId, table, keyField, fields }: UpsertParams): Promise<UpsertResult> {
+ const key = findColumn({ fields: table.fields, reference: keyField });
+ const values = buildFieldValues({ table, fields });
+ const keyValue = values[key.id];
+ if (keyValue === undefined) {
+ throw new Error(`Fields must include a value for the key column "${key.name}".`);
+ }
+ if (Array.isArray(keyValue)) {
+ throw new Error(`The key column "${key.name}" must hold a single value.`);
+ }
+ const condition = softrSearch.buildCondition({ field: key, operator: 'IS', value: keyValue });
+ const response = await softrRecords.searchRecords({
+ apiKey,
+ databaseId,
+ tableId: table.id,
+ body: {
+ paging: { offset: 0, limit: 2 },
+ filter: { condition: { operator: 'AND', conditions: [condition] } },
+ },
+ });
+ const matches = response.data ?? [];
+ const total = response.metadata?.total ?? matches.length;
+ if (total > 1 || matches.length > 1) {
+ throw new Error(
+ `${Math.max(total, matches.length)} records match the given ${key.name}, refusing to guess. Use Update Record (Agent) with a record ID.`,
+ );
+ }
+ const existing = matches[0];
+ const record = await softrRecords.writeRecord({
+ apiKey,
+ databaseId,
+ tableId: table.id,
+ recordId: existing?.id,
+ fields: values,
+ tableFields: table.fields,
+ });
+ return { action: existing ? 'updated' : 'created', record };
+}
+
+type ResolveTableParams = {
+ apiKey: string;
+ databaseId: string;
+ reference: string;
+};
+
+type UpsertParams = {
+ apiKey: string;
+ databaseId: string;
+ table: SoftrTable;
+ keyField: string;
+ fields: Record<string, unknown>;
+};
+
+type UpsertResult = {
+ action: 'created' | 'updated';
+ record: SoftrRecord;
+};
+
+export const softrAgent = {
+ listTables,
+ requireText,
+ resolveTable,
+ parseFieldsInput,
+ buildFieldValues,
+ upsertRecord,
+};
diff --git a/packages/pieces/community/softr/src/lib/common/app-users.ts b/packages/pieces/community/softr/src/lib/common/app-users.ts
new file mode 100644
index 00000000000..dbe83ec5556
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/common/app-users.ts
@@ -0,0 +1,33 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { softrClient } from './client';
+
+async function setUserStatus({ apiKey, domain, email, status }: SetUserStatusParams): Promise<UserStatusResult> {
+ const trimmedEmail = email.trim();
+ if (trimmedEmail.length === 0) {
+ throw new Error('User email is required.');
+ }
+ await softrClient.studioRequest({
+ apiKey,
+ domain,
+ method: HttpMethod.POST,
+ path: `/${encodeURIComponent(trimmedEmail)}/${status}`,
+ });
+ return { success: true, email: trimmedEmail, message: status === 'activate' ? 'User activated' : 'User deactivated' };
+}
+
+type SetUserStatusParams = {
+ apiKey: string;
+ domain: string;
+ email: string;
+ status: 'activate' | 'deactivate';
+};
+
+type UserStatusResult = {
+ success: true;
+ email: string;
+ message: string;
+};
+
+export const softrAppUsers = {
+ setUserStatus,
+};
diff --git a/packages/pieces/community/softr/src/lib/common/auth.ts b/packages/pieces/community/softr/src/lib/common/auth.ts
index a6a995d5f2c..47c47cbc6fd 100644
--- a/packages/pieces/community/softr/src/lib/common/auth.ts
+++ b/packages/pieces/community/softr/src/lib/common/auth.ts
@@ -1,32 +1,27 @@
import { PieceAuth } from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
-import { makeRequest } from './client';
-import { AppConnectionType } from '@activepieces/pieces-framework';
+import { softrClient } from './client';
export const SoftrAuth = PieceAuth.SecretText({
- displayName: 'API Key',
- description: `You can obtain your API key from [API Settings](https://studio.softr.io/user/apisettings).`,
- required: true,
- validate: async ({ auth }) => {
- if (auth) {
- try {
- await makeRequest({
- secret_text: auth,
- type: AppConnectionType.SECRET_TEXT,
- }, HttpMethod.GET, '/databases');
- return {
- valid: true,
- };
- } catch (error) {
- return {
- valid: false,
- error: 'Invalid API Key',
- };
- }
- }
- return {
- valid: false,
- error: 'Invalid API Key',
- };
- },
+ displayName: 'API Key',
+ description: `Create a personal access token in Softr under **Workspace settings → API tokens** (see [Softr API setup](https://docs.softr.io/softr-api/softr-database-api/authorisation)). The token needs access to the workspace whose databases and apps you want to use.`,
+ required: true,
+ validate: async ({ auth }) => {
+ if (!auth) {
+ return { valid: false, error: 'Enter your Softr API key.' };
+ }
+ try {
+ await softrClient.request({ apiKey: auth, method: HttpMethod.GET, path: '/databases' });
+ return { valid: true };
+ } catch (error) {
+ const status = softrClient.getErrorStatus(error);
+ if (status === 401 || status === 403) {
+ return { valid: false, error: 'Invalid API key. Check the token in your Softr workspace settings.' };
+ }
+ return {
+ valid: false,
+ error: `Could not verify the API key with Softr: ${error instanceof Error ? error.message : String(error)}`,
+ };
+ }
+ },
});
diff --git a/packages/pieces/community/softr/src/lib/common/client.ts b/packages/pieces/community/softr/src/lib/common/client.ts
index 8dfb7868759..d2c77fe1c64 100644
--- a/packages/pieces/community/softr/src/lib/common/client.ts
+++ b/packages/pieces/community/softr/src/lib/common/client.ts
@@ -1,49 +1,220 @@
-import { HttpMethod, httpClient } from '@activepieces/pieces-common';
-import { TableField } from './types';
-import { AppConnectionValueForAuthProperty } from '@activepieces/pieces-framework';
-import { SoftrAuth } from './auth';
-
-export const BASE_URL = `https://tables-api.softr.io/api/v1`;
-
-export async function makeRequest<T>(
- api_key: AppConnectionValueForAuthProperty<typeof SoftrAuth>,
- method: HttpMethod,
- path: string,
- body?: unknown
-) {
- try {
- const response = await httpClient.sendRequest<T>({
- method,
- url: `${BASE_URL}${path}`,
- headers: {
- 'Softr-Api-Key': api_key.secret_text,
- 'Content-Type': 'application/json',
- },
- body,
- });
- return response.body;
- } catch (error: any) {
- throw new Error(`Unexpected error: ${error.message || String(error)}`);
- }
-}
-
-
-export function transformRecordFields(
- tableFields: TableField[],
- tableValues: Record<string, any>,
-)
-{
- const fieldMap: Record<string, string> = tableFields.reduce((acc, field) => {
- acc[field.id] = field.name;
- return acc;
- }, {} as Record<string, string>);
-
- const transformedFields: Record<string, any> = {};
-
- for (const [key, value] of Object.entries(tableValues)) {
- const label = fieldMap[key] ?? key;
- transformedFields[label] = value;
- }
-
- return transformedFields;
-}
\ No newline at end of file
+import { HttpMethod, QueryParams, httpClient } from '@activepieces/pieces-common';
+import { SoftrRecord, SoftrSingleResponse, SoftrTable, TableField } from './types';
+
+const BASE_URL = 'https://tables-api.softr.io/api/v1';
+const STUDIO_USERS_URL = 'https://studio-api.softr.io/v1/api/users';
+const MAX_ERROR_TEXT_LENGTH = 500;
+const STUDIO_TIMEOUT_MS = 60_000;
+
+class SoftrApiError extends Error {
+ readonly status: number;
+ readonly responseBody: unknown;
+
+ constructor({ status, responseBody, message }: { status: number; responseBody: unknown; message: string }) {
+ super(message);
+ this.name = 'SoftrApiError';
+ this.status = status;
+ this.responseBody = responseBody;
+ }
+}
+
+async function request<T>({ apiKey, method, path, body, queryParams }: RequestParams): Promise<T> {
+ try {
+ const response = await httpClient.sendRequest<T>({
+ method,
+ url: `${BASE_URL}${path}`,
+ headers: {
+ 'Softr-Api-Key': apiKey,
+ 'Content-Type': 'application/json',
+ },
+ queryParams,
+ body,
+ });
+ return response.body;
+ } catch (error) {
+ throw toSoftrError(error);
+ }
+}
+
+// App user requests carry emails and passwords. The shared httpClient logs the full
+// request body on any error response before throwing (see FetchHttpClient), and the
+// engine does not redact that line, so these calls use fetch directly.
+async function studioRequest({ apiKey, domain, method, path, body }: StudioRequestParams): Promise<{ status: number; body: unknown }> {
+ const response = await fetch(`${STUDIO_USERS_URL}${path}`, {
+ method,
+ headers: {
+ 'Softr-Api-Key': apiKey,
+ 'Softr-Domain': normalizeDomain(domain),
+ 'Content-Type': 'application/json',
+ Accept: 'application/json, text/plain',
+ },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ redirect: 'manual',
+ signal: AbortSignal.timeout(STUDIO_TIMEOUT_MS),
+ });
+ const responseBody = await readBody(response);
+ if (response.status < 200 || response.status >= 300) {
+ throw new SoftrApiError({ status: response.status, responseBody, message: describeFailure({ status: response.status, responseBody }) });
+ }
+ return { status: response.status, body: responseBody };
+}
+
+async function readBody(response: Response): Promise<unknown> {
+ const text = await response.text();
+ if (text.length === 0) {
+ return undefined;
+ }
+ try {
+ return JSON.parse(text);
+ } catch {
+ return text;
+ }
+}
+
+async function getTable({ apiKey, databaseId, tableId }: { apiKey: string; databaseId: string; tableId: string }): Promise<SoftrTable> {
+ const response = await request<SoftrSingleResponse<SoftrTable>>({
+ apiKey,
+ method: HttpMethod.GET,
+ path: tablePath({ databaseId, tableId }),
+ });
+ return response.data;
+}
+
+function databasePath({ databaseId }: { databaseId: string }): string {
+ return `/databases/${encodeURIComponent(databaseId)}`;
+}
+
+function tablePath({ databaseId, tableId }: { databaseId: string; tableId: string }): string {
+ return `${databasePath({ databaseId })}/tables/${encodeURIComponent(tableId)}`;
+}
+
+function fieldPath({ databaseId, tableId, fieldId }: { databaseId: string; tableId: string; fieldId: string }): string {
+ return `${tablePath({ databaseId, tableId })}/fields/${encodeURIComponent(fieldId)}`;
+}
+
+function recordsPath({ databaseId, tableId }: { databaseId: string; tableId: string }): string {
+ return `${tablePath({ databaseId, tableId })}/records`;
+}
+
+function recordPath({ databaseId, tableId, recordId }: { databaseId: string; tableId: string; recordId: string }): string {
+ return `${recordsPath({ databaseId, tableId })}/${encodeURIComponent(recordId)}`;
+}
+
+function withFieldNames({ record, tableFields }: { record: SoftrRecord; tableFields: TableField[] }): SoftrRecord {
+ const namesById = new Map(tableFields.map((field) => [field.id, field.name]));
+ const fields = Object.fromEntries(
+ Object.entries(record.fields ?? {}).map(([key, value]) => [namesById.get(key) ?? key, value]),
+ );
+ return { ...record, fields };
+}
+
+function getErrorStatus(error: unknown): number | null {
+ return error instanceof SoftrApiError ? error.status : null;
+}
+
+function normalizeDomain(domain: string): string {
+ const normalized = domain.trim().replace(/^https?:\/\//i, '').replace(/\/+$/, '');
+ if (normalized.length === 0 || /[\s/?#@]/.test(normalized)) {
+ throw new Error('Enter the Softr app domain only, for example "myapp.softr.app" or "portal.example.com".');
+ }
+ return normalized;
+}
+
+function toSoftrError(error: unknown): unknown {
+ const failure = readHttpFailure(error);
+ if (failure === null) {
+ return error;
+ }
+ return new SoftrApiError({
+ status: failure.status,
+ responseBody: failure.responseBody,
+ message: describeFailure(failure),
+ });
+}
+
+function readHttpFailure(error: unknown): { status: number; responseBody: unknown } | null {
+ if (typeof error !== 'object' || error === null || !('response' in error)) {
+ return null;
+ }
+ const response = error.response;
+ if (typeof response !== 'object' || response === null || !('status' in response) || typeof response.status !== 'number') {
+ return null;
+ }
+ return { status: response.status, responseBody: 'body' in response ? response.body : undefined };
+}
+
+function describeFailure({ status, responseBody }: { status: number; responseBody: unknown }): string {
+ const vendor = readVendorError(responseBody);
+ const code = vendor.errorCode ? ` ${vendor.errorCode}` : '';
+ const text = vendor.message ?? STATUS_HINTS[status] ?? 'Request failed.';
+ const details = vendor.details ? ` Details: ${vendor.details}` : '';
+ const hint = vendor.message && STATUS_HINTS[status] ? ` ${STATUS_HINTS[status]}` : '';
+ return `Softr API error (${status}${code}): ${withPeriod(text)}${details}${hint}`;
+}
+
+function readVendorError(responseBody: unknown): { message?: string; errorCode?: string; details?: string } {
+ if (typeof responseBody === 'string') {
+ const trimmed = responseBody.trim();
+ return trimmed.length > 0 ? { message: truncate(trimmed) } : {};
+ }
+ if (typeof responseBody !== 'object' || responseBody === null) {
+ return {};
+ }
+ const message = 'message' in responseBody && typeof responseBody.message === 'string' ? responseBody.message : undefined;
+ const errorCode =
+ 'errorCode' in responseBody && typeof responseBody.errorCode === 'string'
+ ? responseBody.errorCode
+ : 'code' in responseBody && typeof responseBody.code === 'string'
+ ? responseBody.code
+ : undefined;
+ const details =
+ 'details' in responseBody && typeof responseBody.details === 'object' && responseBody.details !== null
+ ? truncate(JSON.stringify(responseBody.details))
+ : undefined;
+ return { message, errorCode, details };
+}
+
+function withPeriod(value: string): string {
+ return /[.!?]$/.test(value) ? value : `${value}.`;
+}
+
+function truncate(value: string): string {
+ return value.length > MAX_ERROR_TEXT_LENGTH ? `${value.slice(0, MAX_ERROR_TEXT_LENGTH)}...` : value;
+}
+
+const STATUS_HINTS: Record<number, string> = {
+ 401: 'Check that the API key on the connection is valid and, for app user actions, that the Softr domain is correct.',
+ 403: 'The API key does not have access to this resource.',
+ 404: 'The requested resource was not found. Check the IDs or email you entered.',
+ 429: 'Softr rate limit reached. Try again shortly.',
+};
+
+type RequestParams = {
+ apiKey: string;
+ method: HttpMethod;
+ path: string;
+ body?: unknown;
+ queryParams?: QueryParams;
+};
+
+type StudioRequestParams = {
+ apiKey: string;
+ domain: string;
+ method: HttpMethod;
+ path: string;
+ body?: unknown;
+};
+
+export const softrClient = {
+ baseUrl: BASE_URL,
+ request,
+ studioRequest,
+ getTable,
+ databasePath,
+ tablePath,
+ fieldPath,
+ recordsPath,
+ recordPath,
+ withFieldNames,
+ getErrorStatus,
+};
diff --git a/packages/pieces/community/softr/src/lib/common/props.ts b/packages/pieces/community/softr/src/lib/common/props.ts
index db22ee24422..072f4268429 100644
--- a/packages/pieces/community/softr/src/lib/common/props.ts
+++ b/packages/pieces/community/softr/src/lib/common/props.ts
@@ -1,13 +1,61 @@
import { DynamicPropsValue, Property } from '@activepieces/pieces-framework';
-import { makeRequest } from './client';
import { HttpMethod } from '@activepieces/pieces-common';
-import { TableField } from './types';
+import { softrClient } from './client';
import { SoftrAuth } from './auth';
+import { SoftrDatabase, SoftrListResponse, SoftrTable, TableField } from './types';
+
+function errorPlaceholder({ prefix, error }: { prefix: string; error: unknown }): string {
+ return `${prefix}: ${error instanceof Error ? error.message : String(error)}`;
+}
+
+function buildFieldProp(field: TableField) {
+ const displayName = field.name || field.id;
+ const required = false;
+ switch (field.type) {
+ case 'SINGLE_LINE_TEXT':
+ case 'EMAIL':
+ case 'URL':
+ case 'PHONE':
+ return Property.ShortText({ displayName, required });
+ case 'SELECT': {
+ const options = (field.options?.choices ?? []).map((option) => ({
+ label: option.label,
+ value: option.id,
+ }));
+ return field.allowMultipleEntries
+ ? Property.StaticMultiSelectDropdown({ displayName, required, options: { options } })
+ : Property.StaticDropdown({ displayName, required, options: { options } });
+ }
+ case 'LONG_TEXT':
+ return Property.LongText({ displayName, required });
+ case 'NUMBER':
+ case 'CURRENCY':
+ case 'PERCENT':
+ case 'RATING':
+ return Property.Number({ displayName, required });
+ case 'CHECKBOX':
+ return Property.Checkbox({ displayName, required });
+ case 'DATETIME':
+ return Property.DateTime({ displayName, required });
+ case 'DURATION':
+ return Property.Number({ displayName, description: 'Duration in seconds.', required });
+ case 'ATTACHMENT':
+ return Property.Array({ displayName, description: 'Public URLs of the files to attach.', required });
+ case 'DATE':
+ return Property.ShortText({
+ displayName,
+ description: 'Date in YYYY-MM-DD format.',
+ required,
+ });
+ default:
+ return null;
+ }
+}
export const databaseIdDropdown = Property.Dropdown({
auth: SoftrAuth,
displayName: 'Database ID',
- description: 'Select the database to insert the record into',
+ description: 'Select the database.',
required: true,
refreshers: [],
options: async ({ auth }) => {
@@ -18,11 +66,19 @@ export const databaseIdDropdown = Property.Dropdown({
placeholder: 'Please connect your account first',
};
}
-
try {
- const databases = await makeRequest<{
- data: { id: string; name: string }[];
- }>(auth, HttpMethod.GET, '/databases');
+ const databases = await softrClient.request<SoftrListResponse<SoftrDatabase>>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ path: '/databases',
+ });
+ if (databases.data.length === 0) {
+ return {
+ disabled: true,
+ options: [],
+ placeholder: 'No databases found in the workspaces this API key can access.',
+ };
+ }
return {
disabled: false,
options: databases.data.map((database) => ({
@@ -34,7 +90,7 @@ export const databaseIdDropdown = Property.Dropdown({
return {
disabled: true,
options: [],
- placeholder: 'Error loading teams',
+ placeholder: errorPlaceholder({ prefix: 'Error loading databases', error }),
};
}
},
@@ -42,7 +98,7 @@ export const databaseIdDropdown = Property.Dropdown({
export const tableIdDropdown = Property.Dropdown({
displayName: 'Table ID',
- description: 'Select the table to insert the record into',
+ description: 'Select the table.',
required: true,
refreshers: ['auth', 'databaseId'],
auth: SoftrAuth,
@@ -54,11 +110,12 @@ export const tableIdDropdown = Property.Dropdown({
placeholder: 'Please connect your account and select a database first',
};
}
-
try {
- const tables = await makeRequest<{
- data: { id: string; name: string }[];
- }>(auth, HttpMethod.GET, `/databases/${databaseId}/tables`);
+ const tables = await softrClient.request<SoftrListResponse<SoftrTable>>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ path: `/databases/${encodeURIComponent(String(databaseId))}/tables`,
+ });
return {
disabled: false,
options: tables.data.map((table) => ({
@@ -70,7 +127,7 @@ export const tableIdDropdown = Property.Dropdown({
return {
disabled: true,
options: [],
- placeholder: 'Error loading tables',
+ placeholder: errorPlaceholder({ prefix: 'Error loading tables', error }),
};
}
},
@@ -78,15 +135,16 @@ export const tableIdDropdown = Property.Dropdown({
export const recordIdField = Property.ShortText({
displayName: 'Record ID',
+ description: 'The ID of the record, e.g. from the Find Records action or the New Database Record trigger.',
required: true,
});
export const tableFieldIdDropdown = Property.Dropdown({
- displayName:'Field',
+ displayName: 'Field',
refreshers: ['auth', 'databaseId', 'tableId'],
auth: SoftrAuth,
- required:true,
- options:async ({auth,databaseId,tableId})=>{
+ required: true,
+ options: async ({ auth, databaseId, tableId }) => {
if (!auth || !databaseId || !tableId) {
return {
disabled: true,
@@ -94,17 +152,15 @@ export const tableFieldIdDropdown = Property.Dropdown({
placeholder: 'Please connect your account and select a table first.',
};
}
-
try {
- const response = await makeRequest<{
- data: {
- fields: TableField[];
- };
- }>(auth, HttpMethod.GET, `/databases/${databaseId}/tables/${tableId}`);
-
+ const table = await softrClient.getTable({
+ apiKey: auth.secret_text,
+ databaseId: String(databaseId),
+ tableId: String(tableId),
+ });
return {
disabled: false,
- options: response.data.fields.map((field) => ({
+ options: table.fields.map((field) => ({
label: field.name,
value: field.id,
})),
@@ -113,12 +169,11 @@ export const tableFieldIdDropdown = Property.Dropdown({
return {
disabled: true,
options: [],
- placeholder: 'Error loading Fields.',
+ placeholder: errorPlaceholder({ prefix: 'Error loading fields', error }),
};
}
-
- }
-})
+ },
+});
export const tableFields = Property.DynamicProperties({
displayName: 'Fields',
@@ -126,100 +181,56 @@ export const tableFields = Property.DynamicProperties({
refreshers: ['auth', 'databaseId', 'tableId'],
auth: SoftrAuth,
props: async ({ auth, databaseId, tableId }) => {
- if (!databaseId || !tableId||!auth) {
+ if (!databaseId || !tableId || !auth) {
return {};
}
-
try {
- const response = await makeRequest<{
- data: {
- fields: TableField[];
- };
- }>(auth, HttpMethod.GET, `/databases/${databaseId}/tables/${tableId}`);
-
- const tableData = response.data || response;
- const fields = tableData.fields || [];
+ const table = await softrClient.getTable({
+ apiKey: auth.secret_text,
+ databaseId: String(databaseId),
+ tableId: String(tableId),
+ });
const dynamicProps: DynamicPropsValue = {};
-
- fields.forEach((field) => {
- // Skip readonly fields
- if (field.readonly) {
- return;
+ for (const field of table.fields ?? []) {
+ const prop = field.readonly ? null : buildFieldProp(field);
+ if (prop !== null) {
+ dynamicProps[field.id] = prop;
}
+ }
+ return dynamicProps;
+ } catch {
+ return {};
+ }
+ },
+});
- const fieldId = field.id;
- const fieldName = field.name || fieldId;
- const fieldType = field.type;
- const isRequired = false;
+export const appDomainField = Property.ShortText({
+ displayName: 'Softr Domain',
+ description: 'The domain or subdomain of the published Softr app, e.g. myapp.softr.app or portal.example.com.',
+ required: true,
+});
- switch (fieldType) {
- case 'SINGLE_LINE_TEXT':
- case 'EMAIL':
- case 'URL':
- case 'PHONE':
- dynamicProps[fieldId] = Property.ShortText({
- displayName: fieldName,
- required: isRequired,
- });
- break;
+export const appUserEmailField = Property.ShortText({
+ displayName: 'User Email',
+ description: 'The email address of the app user.',
+ required: true,
+});
- case 'SELECT': {
- const options = field.options.choices
- ? field.options.choices.map((option) => ({
- label: option.label,
- value: option.id,
- }))
- : [];
- dynamicProps[fieldId] = field.allowMultipleEntries
- ? Property.StaticMultiSelectDropdown({
- displayName: fieldName,
- required: isRequired,
- options: { options },
- })
- : Property.StaticDropdown({
- displayName: fieldName,
- required: isRequired,
- options: { options },
- });
- break;
- }
- case 'LONG_TEXT':
- dynamicProps[fieldId] = Property.LongText({
- displayName: fieldName,
- required: isRequired,
- });
- break;
+export const agentDatabaseIdField = Property.ShortText({
+ displayName: 'Database ID',
+ description: 'The Softr database ID. Get it from List Databases.',
+ required: true,
+});
- case 'NUMBER':
- case 'CURRENCY':
- case 'PERCENT':
- case 'RATING':
- dynamicProps[fieldId] = Property.Number({
- displayName: fieldName,
- required: isRequired,
- });
- break;
- case 'CHECKBOX':
- dynamicProps[fieldId] = Property.Checkbox({
- displayName: fieldName,
- required: isRequired,
- });
- break;
- case 'DATETIME':
- dynamicProps[fieldId] = Property.DateTime({
- displayName: fieldName,
- required: isRequired,
- });
- break;
- default:
- break;
- }
- });
+export const agentTableField = Property.ShortText({
+ displayName: 'Table (name or ID)',
+ description: 'The table name or table ID. Get both from Get Database Schema (Agent).',
+ required: true,
+});
- return dynamicProps;
- } catch (error) {
- console.error('Error fetching table fields:', error);
- return {};
- }
- },
+export const agentFieldsJson = Property.Json({
+ displayName: 'Fields',
+ description:
+ 'A JSON object keyed by column name or field ID, e.g. {"Name": "Jane", "Age": 30, "Status": "Open"}. Select columns take the option label or ID; multi-select columns take a list.',
+ required: true,
});
diff --git a/packages/pieces/community/softr/src/lib/common/records.ts b/packages/pieces/community/softr/src/lib/common/records.ts
new file mode 100644
index 00000000000..1eaef8980f1
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/common/records.ts
@@ -0,0 +1,58 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { softrClient } from './client';
+import { SoftrListResponse, SoftrRecord, SoftrSingleResponse, TableField } from './types';
+
+function compactFieldValues(fields: Record<string, unknown> | undefined): Record<string, unknown> {
+ return Object.fromEntries(
+ Object.entries(fields ?? {}).filter(([, value]) => {
+ if (value === undefined || value === null || value === '') {
+ return false;
+ }
+ return !(Array.isArray(value) && value.length === 0);
+ }),
+ );
+}
+
+async function writeRecord({ apiKey, databaseId, tableId, recordId, fields, tableFields }: WriteRecordParams): Promise<SoftrRecord> {
+ const knownFields = tableFields ?? (await softrClient.getTable({ apiKey, databaseId, tableId })).fields;
+ const response = await softrClient.request<SoftrSingleResponse<SoftrRecord>>({
+ apiKey,
+ method: recordId ? HttpMethod.PATCH : HttpMethod.POST,
+ path: recordId
+ ? softrClient.recordPath({ databaseId, tableId, recordId })
+ : softrClient.recordsPath({ databaseId, tableId }),
+ body: { fields: compactFieldValues(fields) },
+ });
+ return softrClient.withFieldNames({ record: response.data, tableFields: knownFields });
+}
+
+async function searchRecords({ apiKey, databaseId, tableId, body }: SearchRecordsParams): Promise<SoftrListResponse<SoftrRecord>> {
+ return softrClient.request<SoftrListResponse<SoftrRecord>>({
+ apiKey,
+ method: HttpMethod.POST,
+ path: `${softrClient.recordsPath({ databaseId, tableId })}/search`,
+ body,
+ });
+}
+
+type WriteRecordParams = {
+ apiKey: string;
+ databaseId: string;
+ tableId: string;
+ recordId?: string;
+ fields: Record<string, unknown> | undefined;
+ tableFields?: TableField[];
+};
+
+type SearchRecordsParams = {
+ apiKey: string;
+ databaseId: string;
+ tableId: string;
+ body: Record<string, unknown>;
+};
+
+export const softrRecords = {
+ compactFieldValues,
+ writeRecord,
+ searchRecords,
+};
diff --git a/packages/pieces/community/softr/src/lib/common/search.ts b/packages/pieces/community/softr/src/lib/common/search.ts
new file mode 100644
index 00000000000..0b7a4e8f231
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/common/search.ts
@@ -0,0 +1,159 @@
+import { TableField } from './types';
+
+const NUMERIC_TYPES = ['NUMBER', 'CURRENCY', 'PERCENT', 'RATING', 'AUTONUMBER', 'DURATION'];
+const LIST_OPERATORS = ['IS_ONE_OF', 'IS_NOT_ONE_OF', 'HAS_ANY_OF', 'HAS_ALL_OF', 'HAS_NONE_OF'];
+const UNARY_OPERATORS = ['IS_EMPTY', 'IS_NOT_EMPTY'];
+const RANGE_OPERATORS = ['IS_BETWEEN', 'IS_NOT_BETWEEN'];
+const MAX_LISTED_FIELD_NAMES = 25;
+const SYSTEM_SORT_FIELDS = ['created_at', 'updated_at'];
+
+function resolveField({ fields, reference }: { fields: TableField[]; reference: string | undefined | null }): TableField {
+ const trimmed = typeof reference === 'string' ? reference.trim() : '';
+ if (!trimmed) {
+ throw new Error('Field is required: give a field ID or field name from the table.');
+ }
+ const byId = fields.find((field) => field.id === trimmed);
+ if (byId) {
+ return byId;
+ }
+ const byName = fields.filter((field) => field.name === trimmed);
+ if (byName.length === 1) {
+ return byName[0];
+ }
+ const byNameInsensitive = fields.filter((field) => field.name.toLowerCase() === trimmed.toLowerCase());
+ if (byNameInsensitive.length === 1) {
+ return byNameInsensitive[0];
+ }
+ const available = fields
+ .slice(0, MAX_LISTED_FIELD_NAMES)
+ .map((field) => field.name)
+ .join(', ');
+ if (byName.length > 1 || byNameInsensitive.length > 1) {
+ throw new Error(`More than one field is named "${trimmed}". Use the field ID instead (see the Get Table action).`);
+ }
+ throw new Error(`Field "${trimmed}" was not found in this table. Available fields: ${available}`);
+}
+
+function resolveSortField({ fields, reference }: { fields: TableField[]; reference: string }): string {
+ const lowered = reference.trim().toLowerCase();
+ if (SYSTEM_SORT_FIELDS.includes(lowered) && !fields.some((field) => field.id === reference.trim() || field.name === reference.trim())) {
+ return lowered;
+ }
+ return resolveField({ fields, reference }).id;
+}
+
+function toText(value: unknown): string {
+ if (value === undefined || value === null) {
+ return '';
+ }
+ return typeof value === 'string' ? value : String(value);
+}
+
+function coerceScalar({ field, value }: { field: TableField; value: unknown }): string | number | boolean {
+ if (typeof value === 'number' || typeof value === 'boolean') {
+ return value;
+ }
+ const text = toText(value).trim();
+ if (NUMERIC_TYPES.includes(field.type)) {
+ const parsed = Number(text);
+ if (text.length === 0 || Number.isNaN(parsed)) {
+ throw new Error(`Field "${field.name}" is a number field, so the value must be a number.`);
+ }
+ return parsed;
+ }
+ if (field.type === 'CHECKBOX') {
+ const lowered = text.toLowerCase();
+ if (lowered !== 'true' && lowered !== 'false') {
+ throw new Error(`Field "${field.name}" is a checkbox, so the value must be "true" or "false".`);
+ }
+ return lowered === 'true';
+ }
+ return toText(value);
+}
+
+function toList(value: unknown): string[] {
+ const items = Array.isArray(value) ? value.map(toText) : toText(value).split(',');
+ return items.map((item) => item.trim()).filter((item) => item.length > 0);
+}
+
+function buildCondition({ field, operator, value, upperBound }: BuildConditionParams): SoftrCondition {
+ if (UNARY_OPERATORS.includes(operator)) {
+ return { operator, leftSide: field.id };
+ }
+ if (RANGE_OPERATORS.includes(operator)) {
+ if (isBlank(value) || isBlank(upperBound)) {
+ throw new Error(`${operator} on field "${field.name}" needs both a value (lower bound) and an upper bound.`);
+ }
+ return {
+ operator,
+ leftSide: field.id,
+ lowerBound: coerceScalar({ field, value }),
+ upperBound: coerceScalar({ field, value: upperBound }),
+ };
+ }
+ if (LIST_OPERATORS.includes(operator)) {
+ const list = toList(value);
+ if (list.length === 0) {
+ throw new Error(`${operator} on field "${field.name}" needs at least one value (comma-separated).`);
+ }
+ return { operator, leftSide: field.id, rightSide: list };
+ }
+ if (isBlank(value)) {
+ throw new Error(`${operator} on field "${field.name}" needs a value.`);
+ }
+ return { operator, leftSide: field.id, rightSide: coerceScalar({ field, value }) };
+}
+
+function isBlank(value: unknown): boolean {
+ return value === undefined || value === null || (typeof value === 'string' && value.trim().length === 0);
+}
+
+const OPERATOR_OPTIONS = [
+ { label: 'Is (equals)', value: 'IS' },
+ { label: 'Is not', value: 'IS_NOT' },
+ { label: 'Contains', value: 'CONTAINS' },
+ { label: 'Does not contain', value: 'DOES_NOT_CONTAIN' },
+ { label: 'Starts with', value: 'STARTS_WITH' },
+ { label: 'Does not start with', value: 'DOES_NOT_START_WITH' },
+ { label: 'Ends with', value: 'ENDS_WITH' },
+ { label: 'Does not end with', value: 'DOES_NOT_END_WITH' },
+ { label: 'Greater than', value: 'GREATER_THAN' },
+ { label: 'Greater than or equal', value: 'GREATER_THAN_OR_EQUALS' },
+ { label: 'Less than', value: 'LESS_THAN' },
+ { label: 'Less than or equal', value: 'LESS_THAN_OR_EQUALS' },
+ { label: 'Is between (inclusive)', value: 'IS_BETWEEN' },
+ { label: 'Is not between', value: 'IS_NOT_BETWEEN' },
+ { label: 'Is one of (comma-separated)', value: 'IS_ONE_OF' },
+ { label: 'Is not one of (comma-separated)', value: 'IS_NOT_ONE_OF' },
+ { label: 'Has any of (comma-separated)', value: 'HAS_ANY_OF' },
+ { label: 'Has all of (comma-separated)', value: 'HAS_ALL_OF' },
+ { label: 'Has none of (comma-separated)', value: 'HAS_NONE_OF' },
+ { label: 'Is empty', value: 'IS_EMPTY' },
+ { label: 'Is not empty', value: 'IS_NOT_EMPTY' },
+];
+
+type BuildConditionParams = {
+ field: TableField;
+ operator: string;
+ value: unknown;
+ upperBound?: unknown;
+};
+
+type SoftrCondition = {
+ operator: string;
+ leftSide: string;
+ rightSide?: string | number | boolean | string[];
+ lowerBound?: string | number | boolean;
+ upperBound?: string | number | boolean;
+};
+
+export const softrSearch = {
+ resolveField,
+ resolveSortField,
+ buildCondition,
+ coerceScalar,
+ operatorOptions: OPERATOR_OPTIONS,
+ operatorValues: OPERATOR_OPTIONS.map((option) => option.value),
+};
+
+export type { SoftrCondition };
diff --git a/packages/pieces/community/softr/src/lib/common/types.ts b/packages/pieces/community/softr/src/lib/common/types.ts
index 976e70dd0b1..bedcb1726c3 100644
--- a/packages/pieces/community/softr/src/lib/common/types.ts
+++ b/packages/pieces/community/softr/src/lib/common/types.ts
@@ -4,7 +4,64 @@ export interface TableField {
type: string;
readonly: boolean;
allowMultipleEntries: boolean;
- options: {
+ description?: string | null;
+ required?: boolean;
+ locked?: boolean;
+ defaultValue?: string | null;
+ options?: {
choices?: { id: string; label: string }[];
};
}
+
+export interface SoftrTable {
+ id: string;
+ name: string;
+ description?: string | null;
+ primaryFieldId?: string;
+ defaultViewId?: string;
+ fields: TableField[];
+ createdAt?: string;
+ updatedAt?: string;
+}
+
+export interface SoftrDatabase {
+ id: string;
+ name: string;
+ description?: string | null;
+ workspaceId?: string;
+ tablesCount?: number;
+ createdAt?: string;
+ updatedAt?: string;
+}
+
+export interface SoftrTableView {
+ id: string;
+ tableId: string;
+ name: string;
+ description?: string | null;
+ createdAt?: string;
+ updatedAt?: string;
+}
+
+export interface SoftrRecord {
+ id: string;
+ tableId?: string;
+ createdAt: string;
+ updatedAt: string;
+ fields: Record<string, unknown>;
+}
+
+export interface SoftrListMetadata {
+ offset: number;
+ limit: number;
+ total: number;
+}
+
+export interface SoftrSingleResponse<T> {
+ data: T;
+}
+
+export interface SoftrListResponse<T> {
+ data: T[];
+ metadata?: SoftrListMetadata | null;
+}
diff --git a/packages/pieces/community/softr/src/lib/output-schemas.ts b/packages/pieces/community/softr/src/lib/output-schemas.ts
new file mode 100644
index 00000000000..887c892e647
--- /dev/null
+++ b/packages/pieces/community/softr/src/lib/output-schemas.ts
@@ -0,0 +1,202 @@
+import { OutputSchema } from '@activepieces/pieces-framework';
+
+const recordFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Record ID' },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+ { key: 'updatedAt', label: 'Updated At', format: 'datetime' },
+ { key: 'fields', label: 'Fields', dynamicKey: true, description: 'Record values keyed by field name.' },
+];
+
+const tableFieldFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Field ID' },
+ { key: 'name', label: 'Field Name' },
+ { key: 'type', label: 'Type' },
+ { key: 'readonly', label: 'Read Only', format: 'boolean' },
+ { key: 'required', label: 'Required', format: 'boolean' },
+ { key: 'allowMultipleEntries', label: 'Allows Multiple Values', format: 'boolean' },
+];
+
+const tableFieldsList: OutputSchema['fields'] = [
+ { key: 'id', label: 'Table ID' },
+ { key: 'name', label: 'Table Name' },
+ { key: 'description', label: 'Description' },
+ { key: 'primaryFieldId', label: 'Primary Field ID' },
+ { key: 'fields', label: 'Fields', labelKey: 'name', listItems: tableFieldFields },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+ { key: 'updatedAt', label: 'Updated At', format: 'datetime' },
+];
+
+const databaseFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Database ID' },
+ { key: 'name', label: 'Database Name' },
+ { key: 'description', label: 'Description' },
+ { key: 'workspaceId', label: 'Workspace ID' },
+ { key: 'tablesCount', label: 'Tables Count', format: 'number' },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+ { key: 'updatedAt', label: 'Updated At', format: 'datetime' },
+];
+
+const viewFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'View ID' },
+ { key: 'tableId', label: 'Table ID' },
+ { key: 'name', label: 'View Name' },
+ { key: 'description', label: 'Description' },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+ { key: 'updatedAt', label: 'Updated At', format: 'datetime' },
+];
+
+const record: OutputSchema = { fields: recordFields };
+
+const database: OutputSchema = { fields: databaseFields };
+
+const field: OutputSchema = {
+ fields: [
+ ...tableFieldFields,
+ { key: 'description', label: 'Description' },
+ { key: 'options', label: 'Options' },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+ { key: 'updatedAt', label: 'Updated At', format: 'datetime' },
+ ],
+};
+
+const tableViews: OutputSchema = {
+ fields: [
+ { key: 'count', label: 'Count', format: 'number' },
+ { key: 'views', label: 'Views', labelKey: 'name', listItems: viewFields },
+ ],
+};
+
+const findRecord: OutputSchema = {
+ fields: [
+ { key: 'found', label: 'Found', format: 'boolean' },
+ { key: 'data', label: 'Record', children: recordFields },
+ ],
+};
+
+const findRecords: OutputSchema = {
+ fields: [
+ { key: 'found', label: 'Found', format: 'boolean' },
+ { key: 'count', label: 'Records Returned', format: 'number' },
+ { key: 'total', label: 'Total Matches', format: 'number' },
+ { key: 'offset', label: 'Offset', format: 'number' },
+ { key: 'hasMore', label: 'Has More', format: 'boolean' },
+ { key: 'records', label: 'Records', labelKey: 'id', listItems: recordFields },
+ ],
+};
+
+const listDatabases: OutputSchema = {
+ fields: [
+ { key: 'count', label: 'Count', format: 'number' },
+ { key: 'databases', label: 'Databases', labelKey: 'name', listItems: databaseFields },
+ ],
+};
+
+const listTables: OutputSchema = {
+ fields: [
+ { key: 'count', label: 'Count', format: 'number' },
+ { key: 'tables', label: 'Tables', labelKey: 'name', listItems: tableFieldsList },
+ ],
+};
+
+const table: OutputSchema = { fields: tableFieldsList };
+
+const createAppUser: OutputSchema = {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'message', label: 'Message' },
+ {
+ key: 'user',
+ label: 'User',
+ children: [
+ { key: 'status', label: 'HTTP Status', format: 'number' },
+ {
+ key: 'body',
+ label: 'Softr User',
+ children: [
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'full_name', label: 'Full Name' },
+ { key: 'magic_link', label: 'Magic Link', format: 'url' },
+ { key: 'created', label: 'Created' },
+ { key: 'updated', label: 'Updated' },
+ ],
+ },
+ ],
+ },
+ ],
+};
+
+const appUserStatus: OutputSchema = {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'message', label: 'Message' },
+ ],
+};
+
+const magicLink: OutputSchema = {
+ fields: [
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'magicLink', label: 'Magic Link', format: 'url' },
+ ],
+};
+
+const schemaFieldFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Field ID' },
+ { key: 'name', label: 'Column Name' },
+ { key: 'type', label: 'Type' },
+ { key: 'required', label: 'Required', format: 'boolean' },
+ { key: 'readonly', label: 'Read Only', format: 'boolean' },
+ { key: 'allowMultipleEntries', label: 'Allows Multiple Values', format: 'boolean' },
+ {
+ key: 'options',
+ label: 'Select Options',
+ labelKey: 'label',
+ listItems: [
+ { key: 'id', label: 'Option ID' },
+ { key: 'label', label: 'Option Label' },
+ ],
+ },
+];
+
+const databaseSchema: OutputSchema = {
+ fields: [
+ { key: 'databaseId', label: 'Database 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: 'primaryFieldId', label: 'Primary Field ID' },
+ { key: 'fields', label: 'Fields', labelKey: 'name', listItems: schemaFieldFields },
+ ],
+ },
+ ],
+};
+
+const upsertRecord: OutputSchema = {
+ fields: [
+ { key: 'action', label: 'Action', description: 'created or updated.' },
+ { key: 'record', label: 'Record', children: recordFields },
+ ],
+};
+
+export const softrOutputSchemas = {
+ record,
+ databaseSchema,
+ upsertRecord,
+ database,
+ field,
+ tableViews,
+ findRecord,
+ findRecords,
+ listDatabases,
+ listTables,
+ table,
+ createAppUser,
+ appUserStatus,
+ magicLink,
+};
diff --git a/packages/pieces/community/softr/src/lib/triggers/new-database-record.ts b/packages/pieces/community/softr/src/lib/triggers/new-database-record.ts
index da00bc4efff..bb5fc90cb87 100644
--- a/packages/pieces/community/softr/src/lib/triggers/new-database-record.ts
+++ b/packages/pieces/community/softr/src/lib/triggers/new-database-record.ts
@@ -1,67 +1,66 @@
import { AppConnectionValueForAuthProperty, createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
-import { DedupeStrategy, Polling, pollingHelper, HttpMethod } from '@activepieces/pieces-common';
+import { DedupeStrategy, Polling, pollingHelper } from '@activepieces/pieces-common';
import dayjs from 'dayjs';
import { SoftrAuth } from '../common/auth';
-import { makeRequest, transformRecordFields } from '../common/client';
+import { softrClient } from '../common/client';
+import { softrRecords } from '../common/records';
import { databaseIdDropdown, tableIdDropdown } from '../common/props';
-import { TableField } from '../common/types';
+import { SoftrListResponse, SoftrRecord } from '../common/types';
+import { softrOutputSchemas } from '../output-schemas';
-type Props = {
- databaseId: string;
- tableId: string;
-};
+const PAGE_SIZE = 100;
+const PAGE_OVERLAP = 5;
+const TEST_SAMPLE_SIZE = 5;
+const CREATED_AT_SORT_FIELD = 'created_at';
+
+async function searchNewestFirst({ apiKey, databaseId, tableId, offset, limit }: SearchPageParams): Promise<SoftrListResponse<SoftrRecord>> {
+ return softrRecords.searchRecords({
+ apiKey,
+ databaseId,
+ tableId,
+ body: {
+ paging: { offset, limit },
+ sorting: [{ sortingField: CREATED_AT_SORT_FIELD, sortType: 'DESC' }],
+ },
+ });
+}
+
+async function fetchNewestRecords({ apiKey, databaseId, tableId, lastFetchEpochMS }: FetchNewestParams): Promise<SoftrRecord[]> {
+ if (lastFetchEpochMS === 0) {
+ const sample = await searchNewestFirst({ apiKey, databaseId, tableId, offset: 0, limit: TEST_SAMPLE_SIZE });
+ return sample.data ?? [];
+ }
+ const collected = new Map<string, SoftrRecord>();
+ let offset = 0;
+ let done = false;
+ while (!done) {
+ const page = await searchNewestFirst({ apiKey, databaseId, tableId, offset, limit: PAGE_SIZE });
+ const records = page.data ?? [];
+ const newer = records.filter((record) => dayjs(record.createdAt).valueOf() > lastFetchEpochMS);
+ for (const record of newer) {
+ collected.set(record.id, record);
+ }
+ const total = page.metadata?.total;
+ const reachedEnd = records.length < PAGE_SIZE || (total !== undefined && offset + records.length >= total);
+ done = reachedEnd || newer.length < records.length;
+ offset += PAGE_SIZE - PAGE_OVERLAP;
+ }
+ return [...collected.values()];
+}
const polling: Polling<AppConnectionValueForAuthProperty<typeof SoftrAuth>, Props> = {
strategy: DedupeStrategy.TIMEBASED,
items: async ({ auth, propsValue, lastFetchEpochMS }) => {
const { databaseId, tableId } = propsValue;
-
- let offset = 0;
- let hasMore = true;
- const isTest = lastFetchEpochMS === 0;
-
- const result = [];
-
- let count = 0;
-
- do {
- const response = await makeRequest<{
- data: { createdAt: string; fields: Record<string, any> }[];
- }>(
- auth,
- HttpMethod.GET,
- `/databases/${databaseId}/tables/${tableId}/records?limit=100&offset=${offset}`,
- );
-
- const items = response.data ?? [];
-
- result.push(...items);
-
- if (isTest) break;
- hasMore = items.length > 0;
- offset += 100;
- count++;
- } while (hasMore);
-
-
- console.log('COUNT',count)
-
- const tableReponse = await makeRequest<{
- data: {
- fields: TableField[];
- };
- }>(auth, HttpMethod.GET, `/databases/${databaseId}/tables/${tableId}`);
-
- return result.map((record) => {
- const transformedFields = transformRecordFields(tableReponse.data.fields, record.fields);
- return {
+ const apiKey = auth.secret_text;
+ const table = await softrClient.getTable({ apiKey, databaseId, tableId });
+ const records = await fetchNewestRecords({ apiKey, databaseId, tableId, lastFetchEpochMS });
+ return records
+ .map((record) => ({
epochMilliSeconds: dayjs(record.createdAt).valueOf(),
- data: {
- ...record,
- fields: transformedFields,
- },
- };
- });
+ data: softrClient.withFieldNames({ record, tableFields: table.fields }),
+ }))
+ .sort((a, b) => b.epochMilliSeconds - a.epochMilliSeconds);
},
};
@@ -72,35 +71,57 @@ export const newDatabaseRecord = createTrigger({
displayName: 'New Database Record',
description: 'Triggers when a new record is added.',
aiMetadata: {
- description: 'Fires when a new record is added to the selected table of a Softr database. Polls on a schedule and emits each newly created record, deduplicated by creation time.',
+ description:
+ 'Fires when a new record is added to the selected table of a Softr database. Polls on a schedule and emits each newly created record with field values keyed by field name, deduplicated by creation time.',
},
props: {
databaseId: databaseIdDropdown,
tableId: tableIdDropdown,
},
sampleData: {
- id: 'rec123456',
+ id: 'enzsqklVY6kWpm',
fields: {
- created_date: '2025-08-01T10:00:00Z',
- field1: 'Sample Value',
- field2: 'Another Value',
+ Title: 'Sample record',
+ Qty: 5,
+ Done: true,
+ Status: { id: 'e60f701b-7fbe-4543-8ded-08e568a9a7dc', label: 'Open' },
+ When: '2026-10-08T12:00:00.000Z',
},
+ createdAt: '2026-10-08T14:49:30.855Z',
+ updatedAt: '2026-10-08T14:49:30.855Z',
},
+ outputSchema: softrOutputSchemas.record,
type: TriggerStrategy.POLLING,
async test(context) {
- const { store, auth, propsValue, files } = context;
- return await pollingHelper.test(polling, { store, auth, propsValue, files });
+ return await pollingHelper.test(polling, context);
},
async onEnable(context) {
- const { store, auth, propsValue } = context;
- await pollingHelper.onEnable(polling, { store, auth, propsValue });
+ await pollingHelper.onEnable(polling, context);
},
async onDisable(context) {
- const { store, auth, propsValue } = context;
- await pollingHelper.onDisable(polling, { store, auth, propsValue });
+ await pollingHelper.onDisable(polling, context);
},
async run(context) {
- const { store, auth, propsValue, files } = context;
- return await pollingHelper.poll(polling, { store, auth, propsValue, files });
+ return await pollingHelper.poll(polling, context);
},
});
+
+type Props = {
+ databaseId: string;
+ tableId: string;
+};
+
+type SearchPageParams = {
+ apiKey: string;
+ databaseId: string;
+ tableId: string;
+ offset: number;
+ limit: number;
+};
+
+type FetchNewestParams = {
+ apiKey: string;
+ databaseId: string;
+ tableId: string;
+ lastFetchEpochMS: number;
+};
diff --git a/packages/pieces/community/softr/test/admin.test.ts b/packages/pieces/community/softr/test/admin.test.ts
new file mode 100644
index 00000000000..fc511c24800
--- /dev/null
+++ b/packages/pieces/community/softr/test/admin.test.ts
@@ -0,0 +1,137 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createDatabase } from '../src/lib/actions/create-database';
+import { updateDatabase } from '../src/lib/actions/update-database';
+import { deleteDatabase } from '../src/lib/actions/delete-database';
+import { createTable } from '../src/lib/actions/create-table';
+import { updateTable } from '../src/lib/actions/update-table';
+import { deleteTable } from '../src/lib/actions/delete-table';
+import { createTableField } from '../src/lib/actions/create-table-field';
+import { updateTableField } from '../src/lib/actions/update-table-field';
+import { deleteTableField } from '../src/lib/actions/delete-table-field';
+import { listTableViews } from '../src/lib/actions/list-table-views';
+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 API = 'https://tables-api.softr.io/api/v1';
+
+beforeEach(() => {
+ sendRequest.mockReset();
+ sendRequest.mockResolvedValue({ status: 200, body: { data: { id: 'x' } } });
+});
+
+function lastRequest() {
+ return sendRequest.mock.calls[sendRequest.mock.calls.length - 1][0];
+}
+
+describe('databases', () => {
+ it('creates a database with the workspace id', async () => {
+ await runAction({ action: createDatabase, propsValue: { workspaceId: ' ws1 ', name: 'AP test', description: '' } });
+ expect(lastRequest()).toMatchObject({ method: 'POST', url: `${API}/databases`, body: { workspaceId: 'ws1', name: 'AP test' } });
+ });
+
+ it('update sends only supplied values', async () => {
+ await runAction({ action: updateDatabase, propsValue: { databaseId: 'db1', description: 'D' } });
+ expect(lastRequest()).toMatchObject({ method: 'PUT', url: `${API}/databases/db1`, body: { description: 'D' } });
+ await runAction({ action: updateDatabase, propsValue: { databaseId: 'db1', name: 'New' } });
+ expect(lastRequest().body).toEqual({ name: 'New' });
+ });
+
+ it('update refuses an empty change', async () => {
+ await expect(runAction({ action: updateDatabase, propsValue: { databaseId: 'db1' } })).rejects.toThrow('Provide a new name');
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('delete refuses an empty id and only forces when asked', async () => {
+ await expect(runAction({ action: deleteDatabase, propsValue: { databaseId: ' ' } })).rejects.toThrow('Database ID is required');
+ expect(sendRequest).not.toHaveBeenCalled();
+ await runAction({ action: deleteDatabase, propsValue: { databaseId: 'db1' } });
+ expect(lastRequest()).toMatchObject({ method: 'DELETE', url: `${API}/databases/db1`, queryParams: undefined });
+ await runAction({ action: deleteDatabase, propsValue: { databaseId: 'db1', force: true } });
+ expect(lastRequest().queryParams).toEqual({ force: 'true' });
+ });
+});
+
+describe('tables and fields', () => {
+ it('creates a table with typed fields and parsed options', async () => {
+ await runAction({
+ action: createTable,
+ propsValue: {
+ databaseId: 'db1',
+ name: 'T',
+ fields: [
+ { name: 'Status', type: 'SELECT', options: '{"choices":[{"label":"Open"}]}' },
+ { name: 'Qty', type: 'NUMBER' },
+ ],
+ },
+ });
+ expect(lastRequest()).toMatchObject({
+ method: 'POST',
+ url: `${API}/databases/db1/tables`,
+ body: {
+ name: 'T',
+ fields: [
+ { name: 'Status', type: 'SELECT', options: { choices: [{ label: 'Open' }] } },
+ { name: 'Qty', type: 'NUMBER' },
+ ],
+ },
+ });
+ });
+
+ it('rejects bad options JSON and unknown types before any request', async () => {
+ await expect(
+ runAction({ action: createTable, propsValue: { databaseId: 'db1', name: 'T', fields: [{ name: 'A', type: 'SELECT', options: '{bad' }] } }),
+ ).rejects.toThrow('not valid JSON');
+ await expect(
+ runAction({ action: createTableField, propsValue: { databaseId: 'db1', tableId: 't1', name: 'A', type: 'DATE' } }),
+ ).rejects.toThrow('cannot be created through the Softr API');
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('table update always sends the name Softr requires, reading it when not supplied', async () => {
+ sendRequest.mockResolvedValueOnce({ status: 200, body: { data: { id: 't1', name: 'Current', fields: [] } } });
+ await runAction({ action: updateTable, propsValue: { databaseId: 'db1', tableId: 't1', clearDescription: true } });
+ expect(lastRequest()).toMatchObject({ method: 'PUT', url: `${API}/databases/db1/tables/t1`, body: { name: 'Current', description: '' } });
+ });
+
+ it('field update merges with the current definition so options are not wiped', async () => {
+ const choices = { choices: [{ id: 'c1', label: 'A' }] };
+ sendRequest.mockResolvedValueOnce({ status: 200, body: { data: { id: 'f1', name: 'Status', type: 'SELECT', options: choices } } });
+ await runAction({ action: updateTableField, propsValue: { databaseId: 'db1', tableId: 't1', fieldId: 'f1', name: 'Renamed' } });
+ expect(lastRequest()).toMatchObject({
+ method: 'PUT',
+ url: `${API}/databases/db1/tables/t1/fields/f1`,
+ body: { name: 'Renamed', type: 'SELECT', options: choices },
+ });
+ sendRequest.mockResolvedValueOnce({ status: 200, body: { data: { id: 'f1', name: 'Status', type: 'SELECT', options: choices } } });
+ await runAction({ action: updateTableField, propsValue: { databaseId: 'db1', tableId: 't1', fieldId: 'f1', type: 'LONG_TEXT' } });
+ expect(lastRequest().body).toEqual({ name: 'Status', type: 'LONG_TEXT' });
+ await expect(
+ runAction({ action: updateTableField, propsValue: { databaseId: 'db1', tableId: 't1', fieldId: 'f1' } }),
+ ).rejects.toThrow('Provide a new name, type or options');
+ });
+
+ it('deletes tables and fields', async () => {
+ await runAction({ action: deleteTable, propsValue: { databaseId: 'db1', tableId: 't1', force: true } });
+ expect(lastRequest()).toMatchObject({ method: 'DELETE', url: `${API}/databases/db1/tables/t1`, queryParams: { force: 'true' } });
+ await runAction({ action: deleteTableField, propsValue: { databaseId: 'db1', tableId: 't1', fieldId: 'f1' } });
+ expect(lastRequest()).toMatchObject({ method: 'DELETE', url: `${API}/databases/db1/tables/t1/fields/f1` });
+ });
+
+ it('lists table views', async () => {
+ sendRequest.mockResolvedValueOnce({ status: 200, body: { data: [{ id: 'v1', name: 'Grid' }] } });
+ const output = await runAction({ action: listTableViews, propsValue: { databaseId: 'db1', tableId: 't1' } });
+ expect(lastRequest().url).toBe(`${API}/databases/db1/tables/t1/views`);
+ expect(output).toEqual({ count: 1, views: [{ id: 'v1', name: 'Grid' }] });
+ });
+});
diff --git a/packages/pieces/community/softr/test/agent.test.ts b/packages/pieces/community/softr/test/agent.test.ts
new file mode 100644
index 00000000000..7a51a646a05
--- /dev/null
+++ b/packages/pieces/community/softr/test/agent.test.ts
@@ -0,0 +1,225 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createRecordAi } from '../src/lib/actions/create-record-ai';
+import { getDatabaseSchemaAi } from '../src/lib/actions/get-database-schema-ai';
+import { updateRecordAi } from '../src/lib/actions/update-record-ai';
+import { upsertRecordAi } from '../src/lib/actions/upsert-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 CONTACTS = {
+ id: 'tbl1',
+ name: 'Contacts',
+ primaryFieldId: 'f-name',
+ fields: [
+ { id: 'f-name', name: 'Name', type: 'SINGLE_LINE_TEXT', readonly: false, allowMultipleEntries: false, required: true },
+ { id: 'f-email', name: 'Email', type: 'EMAIL', readonly: false, allowMultipleEntries: false },
+ { id: 'f-age', name: 'Age', type: 'NUMBER', readonly: false, allowMultipleEntries: false },
+ {
+ id: 'f-status',
+ name: 'Status',
+ type: 'SELECT',
+ readonly: false,
+ allowMultipleEntries: false,
+ options: { choices: [{ id: 'opt-open', label: 'Open' }, { id: 'opt-done', label: 'Done' }] },
+ },
+ { id: 'f-rid', name: 'Record ID', type: 'RECORD_ID', readonly: true, allowMultipleEntries: false },
+ ],
+};
+
+const TABLES = [CONTACTS, { id: 'tbl2', name: 'Orders', fields: [] }];
+
+function savedRecord(fields: Record<string, unknown>) {
+ return { body: { data: { id: 'r1', createdAt: '2026-01-01T00:00:00Z', updatedAt: '2026-01-01T00:00:00Z', fields } } };
+}
+
+function calls(): { method: string; url: string; body?: unknown }[] {
+ return sendRequest.mock.calls.map((c) => c[0]);
+}
+
+beforeEach(() => {
+ sendRequest.mockReset();
+});
+
+describe('Get Database Schema (Agent)', () => {
+ it('returns every table with columns and select options in one call', async () => {
+ sendRequest.mockResolvedValueOnce({ body: { data: TABLES } });
+ const output = await runAction({ action: getDatabaseSchemaAi, propsValue: { databaseId: ' db1 ' } });
+ expect(calls()).toHaveLength(1);
+ expect(calls()[0].url).toBe('https://tables-api.softr.io/api/v1/databases/db1/tables');
+ expect(output).toMatchObject({
+ databaseId: 'db1',
+ tableCount: 2,
+ tables: [
+ {
+ id: 'tbl1',
+ name: 'Contacts',
+ fields: expect.arrayContaining([
+ {
+ id: 'f-status',
+ name: 'Status',
+ type: 'SELECT',
+ required: false,
+ readonly: false,
+ allowMultipleEntries: false,
+ options: [
+ { id: 'opt-open', label: 'Open' },
+ { id: 'opt-done', label: 'Done' },
+ ],
+ },
+ ]),
+ },
+ { id: 'tbl2', name: 'Orders', fields: [] },
+ ],
+ });
+ });
+});
+
+describe('Create Record (Agent)', () => {
+ it('resolves the table by name and columns by name (any case) or ID, converting values', async () => {
+ sendRequest.mockResolvedValueOnce({ body: { data: TABLES } }).mockResolvedValueOnce(savedRecord({ 'f-name': 'Jane', 'f-age': 30 }));
+ const output = await runAction({
+ action: createRecordAi,
+ propsValue: { databaseId: 'db1', table: 'contacts', fields: { name: 'Jane', 'f-age': '30', STATUS: 'open', Email: '' } },
+ });
+ expect(calls()).toHaveLength(2);
+ expect(calls()[1]).toMatchObject({
+ method: 'POST',
+ url: 'https://tables-api.softr.io/api/v1/databases/db1/tables/tbl1/records',
+ body: { fields: { 'f-name': 'Jane', 'f-age': 30, 'f-status': 'opt-open' } },
+ });
+ expect(output).toMatchObject({ id: 'r1', fields: { Name: 'Jane', Age: 30 } });
+ });
+
+ it.each([
+ [{ Name: 'A', Status: 'Secret-Diagnosis' }, 'is not one of its options'],
+ [{ Name: 'A', Age: 'Secret-Diagnosis' }, 'must be a number'],
+ ])('names the column but never echoes the value in a conversion error (%j)', async (fields, message) => {
+ sendRequest.mockResolvedValueOnce({ body: { data: TABLES } });
+ const error = await runAction({ action: createRecordAi, propsValue: { databaseId: 'db1', table: 'tbl1', fields } }).catch((e: unknown) => e);
+ expect(String(error)).toContain(message);
+ expect(String(error)).not.toContain('Secret-Diagnosis');
+ });
+
+ it('accepts a table ID', async () => {
+ sendRequest.mockResolvedValueOnce({ body: { data: TABLES } }).mockResolvedValueOnce(savedRecord({}));
+ await runAction({ action: createRecordAi, propsValue: { databaseId: 'db1', table: 'tbl1', fields: { Name: 'A' } } });
+ expect(calls()[1].url).toContain('/tables/tbl1/records');
+ });
+
+ it('rejects an ambiguous table name', async () => {
+ sendRequest.mockResolvedValueOnce({ body: { data: [CONTACTS, { ...CONTACTS, id: 'tbl9' }] } });
+ await expect(
+ runAction({ action: createRecordAi, propsValue: { databaseId: 'db1', table: 'Contacts', fields: { Name: 'A' } } }),
+ ).rejects.toThrow('2 tables are named "Contacts" (IDs: tbl1, tbl9)');
+ });
+
+ it('names the valid columns when one is unknown and writes nothing', async () => {
+ sendRequest.mockResolvedValueOnce({ body: { data: TABLES } });
+ await expect(
+ runAction({ action: createRecordAi, propsValue: { databaseId: 'db1', table: 'Contacts', fields: { Phone: '1' } } }),
+ ).rejects.toThrow('Column "Phone" does not exist in this table. Valid columns: Name, Email, Age, Status.');
+ expect(calls()).toHaveLength(1);
+ });
+
+ it('rejects unknown select options and read-only columns', async () => {
+ sendRequest.mockResolvedValue({ body: { data: TABLES } });
+ await expect(
+ runAction({ action: createRecordAi, propsValue: { databaseId: 'db1', table: 'Contacts', fields: { Status: 'Later' } } }),
+ ).rejects.toThrow('Options: Open, Done');
+ await expect(
+ runAction({ action: createRecordAi, propsValue: { databaseId: 'db1', table: 'Contacts', fields: { 'Record ID': 'x' } } }),
+ ).rejects.toThrow('is read-only');
+ });
+
+ it('rejects fields that are not a JSON object', async () => {
+ await expect(
+ runAction({ action: createRecordAi, propsValue: { databaseId: 'db1', table: 'Contacts', fields: '[1]' } }),
+ ).rejects.toThrow('Fields must be a JSON object');
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+});
+
+describe('Update Record (Agent)', () => {
+ it('patches only the given columns', async () => {
+ sendRequest.mockResolvedValueOnce({ body: { data: TABLES } }).mockResolvedValueOnce(savedRecord({ 'f-age': 31 }));
+ await runAction({ action: updateRecordAi, propsValue: { databaseId: 'db1', table: 'Contacts', recordId: ' r1 ', fields: { age: 31 } } });
+ expect(calls()[1]).toMatchObject({
+ method: 'PATCH',
+ url: 'https://tables-api.softr.io/api/v1/databases/db1/tables/tbl1/records/r1',
+ body: { fields: { 'f-age': 31 } },
+ });
+ });
+
+ it('refuses empty fields without writing', async () => {
+ sendRequest.mockResolvedValue({ body: { data: TABLES } });
+ await expect(
+ runAction({ action: updateRecordAi, propsValue: { databaseId: 'db1', table: 'Contacts', recordId: 'r1', fields: {} } }),
+ ).rejects.toThrow('Fields is empty');
+ await expect(
+ runAction({ action: updateRecordAi, propsValue: { databaseId: 'db1', table: 'Contacts', recordId: 'r1', fields: { Name: '' } } }),
+ ).rejects.toThrow('Fields is empty');
+ expect(calls().every((c) => c.method === 'GET')).toBe(true);
+ });
+});
+
+describe('Upsert Record (Agent)', () => {
+ function mockSearch({ total }: { total: number }) {
+ sendRequest.mockImplementation(async (req: { url: string; method: string }) => {
+ if (req.url.endsWith('/tables')) {
+ return { body: { data: TABLES } };
+ }
+ if (req.url.endsWith('/records/search')) {
+ const data = Array.from({ length: Math.min(total, 2) }, (_, i) => ({ id: `r${i + 1}`, fields: {} }));
+ return { body: { data, metadata: { offset: 0, limit: 2, total } } };
+ }
+ return savedRecord({ 'f-email': '[email protected]' });
+ });
+ }
+
+ const props = { databaseId: 'db1', table: 'Contacts', keyField: 'email', fields: { Email: '[email protected]', Name: 'Ann' } };
+
+ it('creates when no record matches the key', async () => {
+ mockSearch({ total: 0 });
+ const output = await runAction({ action: upsertRecordAi, propsValue: props });
+ expect(calls()[1].body).toEqual({
+ paging: { offset: 0, limit: 2 },
+ filter: { condition: { operator: 'AND', conditions: [{ operator: 'IS', leftSide: 'f-email', rightSide: '[email protected]' }] } },
+ });
+ expect(calls()[2]).toMatchObject({ method: 'POST', body: { fields: { 'f-email': '[email protected]', 'f-name': 'Ann' } } });
+ expect(output).toMatchObject({ action: 'created', record: { id: 'r1', fields: { Email: '[email protected]' } } });
+ });
+
+ it('updates the single matching record', async () => {
+ mockSearch({ total: 1 });
+ const output = await runAction({ action: upsertRecordAi, propsValue: props });
+ expect(calls()[2]).toMatchObject({ method: 'PATCH', url: expect.stringContaining('/tables/tbl1/records/r1') });
+ expect(output).toMatchObject({ action: 'updated' });
+ });
+
+ it('refuses to guess when several records match', async () => {
+ mockSearch({ total: 3 });
+ await expect(runAction({ action: upsertRecordAi, propsValue: props })).rejects.toThrow(
+ '3 records match the given Email, refusing to guess',
+ );
+ expect(calls()).toHaveLength(2);
+ });
+
+ it('needs the key value inside Fields', async () => {
+ mockSearch({ total: 0 });
+ await expect(
+ runAction({ action: upsertRecordAi, propsValue: { ...props, fields: { Name: 'Ann' } } }),
+ ).rejects.toThrow('Fields must include a value for the key column "Email"');
+ expect(calls()).toHaveLength(1);
+ });
+});
diff --git a/packages/pieces/community/softr/test/helpers.ts b/packages/pieces/community/softr/test/helpers.ts
new file mode 100644
index 00000000000..2848b405e6c
--- /dev/null
+++ b/packages/pieces/community/softr/test/helpers.ts
@@ -0,0 +1,36 @@
+import {
+ ActionContext,
+ AppConnectionType,
+ AppConnectionValueForAuthProperty,
+ AuthValidationServerContext,
+ createMockActionContext,
+ InputPropertyMap,
+ SecretTextProperty,
+ StaticPropsValue,
+} from '@activepieces/pieces-framework';
+
+export const TEST_AUTH: SecretTextConnection = { type: AppConnectionType.SECRET_TEXT, secret_text: 'softr_test_key' };
+
+export function runAction({ action, propsValue }: RunActionParams): Promise<unknown> {
+ const base = createMockActionContext<InputPropertyMap>({ propsValue });
+ const context: SoftrActionContext = { ...base, auth: TEST_AUTH };
+ return action.run(context);
+}
+
+export function authValidationServerContext(): AuthValidationServerContext {
+ const { apiUrl, publicUrl } = createMockActionContext<InputPropertyMap>({ propsValue: {} }).server;
+ return { apiUrl, publicUrl, mintOidcToken: async () => 'test-oidc-token' };
+}
+
+type SecretTextConnection = AppConnectionValueForAuthProperty<SecretTextProperty<true>>;
+
+type SoftrActionContext = ActionContext<SecretTextProperty<true>, InputPropertyMap>;
+
+export type TestAction = {
+ run(context: SoftrActionContext): Promise<unknown>;
+};
+
+type RunActionParams = {
+ action: TestAction;
+ propsValue: StaticPropsValue<InputPropertyMap>;
+};
diff --git a/packages/pieces/community/softr/test/softr.test.ts b/packages/pieces/community/softr/test/softr.test.ts
new file mode 100644
index 00000000000..157da215f5e
--- /dev/null
+++ b/packages/pieces/community/softr/test/softr.test.ts
@@ -0,0 +1,299 @@
+import { HttpError } from '@activepieces/pieces-common';
+import { createMockPollingTriggerContext, InputPropertyMap } from '@activepieces/pieces-framework';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { SoftrAuth } from '../src/lib/common/auth';
+import { softrSearch } from '../src/lib/common/search';
+import { createAppUser } from '../src/lib/actions/create-app-user';
+import { createDatabaseRecord } from '../src/lib/actions/create-database-record';
+import { updateDatabaseRecord } from '../src/lib/actions/update-database-record';
+import { findDatabaseRecord } from '../src/lib/actions/find-database-record';
+import { findRecords } from '../src/lib/actions/find-records';
+import { generateMagicLink } from '../src/lib/actions/generate-magic-link';
+import { activateAppUser } from '../src/lib/actions/activate-app-user';
+import { deactivateAppUser } from '../src/lib/actions/deactivate-app-user';
+import { newDatabaseRecord } from '../src/lib/triggers/new-database-record';
+import { authValidationServerContext, runAction, TEST_AUTH } 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 TABLE = {
+ id: 'tbl1',
+ name: 'Contacts',
+ fields: [
+ { id: 'f-name', name: 'Name', type: 'SINGLE_LINE_TEXT', readonly: false, allowMultipleEntries: false },
+ { id: 'f-age', name: 'Age', type: 'NUMBER', readonly: false, allowMultipleEntries: false },
+ { id: 'f-active', name: 'Active', type: 'CHECKBOX', readonly: false, allowMultipleEntries: false },
+ ],
+};
+
+function record({ id, createdAt }: { id: string; createdAt: string }) {
+ return { id, tableId: 'tbl1', createdAt, updatedAt: createdAt, fields: { 'f-name': `N ${id}` } };
+}
+
+function httpError({ status, body, requestBody }: { status: number; body: unknown; requestBody: unknown }) {
+ return new HttpError(requestBody, { status, responseBody: body });
+}
+
+type FetchCall = { url: string; method: string; headers: Record<string, string>; body: unknown };
+
+function stubStudio(reply: (call: FetchCall) => { status: number; body: unknown }): FetchCall[] {
+ const calls: FetchCall[] = [];
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (url: string, init: RequestInit) => {
+ const call: FetchCall = {
+ url,
+ method: String(init.method),
+ headers: Object(init.headers),
+ body: typeof init.body === 'string' ? JSON.parse(init.body) : undefined,
+ };
+ calls.push(call);
+ const { status, body } = reply(call);
+ return new Response(typeof body === 'string' ? body : JSON.stringify(body), { status });
+ }),
+ );
+ return calls;
+}
+
+beforeEach(() => {
+ sendRequest.mockReset();
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+describe('error handling', () => {
+ it('never logs or returns the password when Create App User fails', async () => {
+ const logged = vi.spyOn(console, 'error').mockImplementation(() => undefined);
+ stubStudio(() => ({ status: 409, body: { message: 'User already exists', code: 'CONFLICT' } }));
+ const result = runAction({
+ action: createAppUser,
+ propsValue: { email: '[email protected]', full_name: 'A', password: 'TopSecret-123', domain: 'app.softr.app' },
+ });
+ await expect(result).rejects.toThrow('Softr API error (409 CONFLICT): User already exists.');
+ const error = await result.catch((e: unknown) => e);
+ expect(JSON.stringify(error)).not.toContain('TopSecret');
+ expect(String(error)).not.toContain('TopSecret');
+ expect(error instanceof Error ? error.stack : '').not.toContain('TopSecret');
+ expect(JSON.stringify(logged.mock.calls)).not.toContain('TopSecret');
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('validate() only reports invalid credentials on 401/403', async () => {
+ sendRequest.mockRejectedValueOnce(httpError({ status: 401, body: { message: 'Unauthorized' }, requestBody: undefined }));
+ const invalid = await SoftrAuth.validate?.({ auth: 'k', server: authValidationServerContext() });
+ expect(invalid).toEqual({ valid: false, error: 'Invalid API key. Check the token in your Softr workspace settings.' });
+
+ sendRequest.mockRejectedValueOnce(httpError({ status: 429, body: { message: 'Too many requests' }, requestBody: undefined }));
+ const limited = await SoftrAuth.validate?.({ auth: 'k', server: authValidationServerContext() });
+ expect(limited?.valid).toBe(false);
+ expect(limited && 'error' in limited ? limited.error : '').toContain('Could not verify');
+ });
+});
+
+describe('app users', () => {
+ it('omits an empty password and strips the HTTP headers from the output', async () => {
+ const calls = stubStudio(() => ({ status: 200, body: { email: '[email protected]' } }));
+ const output = await runAction({
+ action: createAppUser,
+ propsValue: { email: ' [email protected] ', full_name: 'A', domain: 'https://app.softr.app/' },
+ });
+ expect(calls[0].url).toBe('https://studio-api.softr.io/v1/api/users');
+ expect(calls[0].headers['Softr-Domain']).toBe('app.softr.app');
+ expect(calls[0].body).toEqual({ email: '[email protected]', full_name: 'A', generate_magic_link: false });
+ expect(output).toEqual({ success: true, message: 'User created successfully', user: { status: 200, body: { email: '[email protected]' } } });
+ });
+
+ it('returns the magic link when Softr answers with plain text', async () => {
+ const calls = stubStudio(() => ({ status: 200, body: 'https://app.softr.app/?magic=abc' }));
+ const output = await runAction({ action: generateMagicLink, propsValue: { email: '[email protected]', domain: 'app.softr.app' } });
+ expect(calls[0].url).toBe('https://studio-api.softr.io/v1/api/users/magic-link/generate/a%2Bb%40c.co');
+ expect(output).toEqual({ email: '[email protected]', magicLink: 'https://app.softr.app/?magic=abc' });
+ });
+
+ it('activates and deactivates a user by encoded email', async () => {
+ const calls = stubStudio(() => ({ status: 200, body: {} }));
+ const off = await runAction({ action: deactivateAppUser, propsValue: { email: ' [email protected] ', domain: 'app.softr.app' } });
+ const on = await runAction({ action: activateAppUser, propsValue: { email: '[email protected]', domain: 'app.softr.app' } });
+ expect(calls.map((c) => [c.method, c.url])).toEqual([
+ ['POST', 'https://studio-api.softr.io/v1/api/users/a%2Bb%40c.co/deactivate'],
+ ['POST', 'https://studio-api.softr.io/v1/api/users/a%2Bb%40c.co/activate'],
+ ]);
+ expect(off).toEqual({ success: true, email: '[email protected]', message: 'User deactivated' });
+ expect(on).toEqual({ success: true, email: '[email protected]', message: 'User activated' });
+ });
+});
+
+describe('records', () => {
+ it('creates a record with one table read before the write and maps field IDs to names', async () => {
+ sendRequest
+ .mockResolvedValueOnce({ body: { data: TABLE } })
+ .mockResolvedValueOnce({ body: { data: { ...record({ id: 'r1', createdAt: '2026-01-01T00:00:00Z' }), fields: { 'f-name': 'Jane', 'f-age': 3 } } } });
+ const output = await runAction({
+ action: createDatabaseRecord,
+ propsValue: { databaseId: 'db1', tableId: 'tbl1', fields: { 'f-name': 'Jane', 'f-age': 3, 'f-active': '' } },
+ });
+ expect(sendRequest.mock.calls[1][0].url).toBe('https://tables-api.softr.io/api/v1/databases/db1/tables/tbl1/records');
+ expect(sendRequest.mock.calls[1][0].body).toEqual({ fields: { 'f-name': 'Jane', 'f-age': 3 } });
+ expect(output).toMatchObject({ id: 'r1', fields: { Name: 'Jane', Age: 3 } });
+ });
+
+ it('refuses an update with no field values', async () => {
+ await expect(
+ runAction({ action: updateDatabaseRecord, propsValue: { databaseId: 'db1', tableId: 'tbl1', recordId: 'r1', fields: { 'f-name': '' } } }),
+ ).rejects.toThrow('at least one field');
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('Find Database Record sends numbers as numbers', async () => {
+ sendRequest.mockResolvedValueOnce({ body: { data: TABLE } }).mockResolvedValueOnce({ body: { data: [], metadata: { total: 0 } } });
+ const output = await runAction({
+ action: findDatabaseRecord,
+ propsValue: { databaseId: 'db1', tableId: 'tbl1', fieldId: 'f-age', fieldValue: '5' },
+ });
+ expect(sendRequest.mock.calls[1][0].body.filter.condition.conditions[0]).toEqual({ operator: 'IS', leftSide: 'f-age', rightSide: 5 });
+ expect(output).toEqual({ found: false, data: {} });
+ });
+
+ it('Find Records builds conditions by field name, sorting and paging', async () => {
+ sendRequest
+ .mockResolvedValueOnce({ body: { data: TABLE } })
+ .mockResolvedValueOnce({ body: { data: [record({ id: 'r1', createdAt: '2026-01-01T00:00:00Z' })], metadata: { offset: 0, limit: 1, total: 3 } } });
+ const output = await runAction({
+ action: findRecords,
+ propsValue: {
+ databaseId: 'db1',
+ tableId: 'tbl1',
+ conditions: [
+ { field: 'name', operator: 'CONTAINS', value: 'ja' },
+ { field: 'Age', operator: 'IS_BETWEEN', value: '1', upperBound: '9' },
+ { field: 'Active', operator: 'IS', value: 'TRUE' },
+ { field: 'Name', operator: 'IS_ONE_OF', value: 'a, b' },
+ { field: 'Name', operator: 'IS_EMPTY' },
+ ],
+ matchType: 'OR',
+ sortField: 'created_at',
+ sortDirection: 'DESC',
+ limit: 1,
+ offset: 0,
+ },
+ });
+ expect(sendRequest.mock.calls[1][0].body).toEqual({
+ paging: { offset: 0, limit: 1 },
+ filter: {
+ condition: {
+ operator: 'OR',
+ conditions: [
+ { operator: 'CONTAINS', leftSide: 'f-name', rightSide: 'ja' },
+ { operator: 'IS_BETWEEN', leftSide: 'f-age', lowerBound: 1, upperBound: 9 },
+ { operator: 'IS', leftSide: 'f-active', rightSide: true },
+ { operator: 'IS_ONE_OF', leftSide: 'f-name', rightSide: ['a', 'b'] },
+ { operator: 'IS_EMPTY', leftSide: 'f-name' },
+ ],
+ },
+ },
+ sorting: [{ sortingField: 'created_at', sortType: 'DESC' }],
+ });
+ expect(output).toMatchObject({ found: true, count: 1, total: 3, offset: 0, hasMore: true });
+ });
+
+ it('rejects a non-numeric value for a number field', () => {
+ expect(() =>
+ softrSearch.buildCondition({ field: TABLE.fields[1], operator: 'GREATER_THAN', value: 'abc' }),
+ ).toThrow('must be a number');
+ });
+});
+
+describe('new record trigger', () => {
+ const stamp = (i: number) => new Date(Date.UTC(2026, 0, 1) + i * 60000).toISOString();
+
+ function mockTable({ total }: { total: number }) {
+ sendRequest.mockImplementation(async (req: { url: string; body?: { paging: { offset: number; limit: number }; sorting: unknown } }) => {
+ if (!req.url.endsWith('/records/search')) {
+ return { body: { data: TABLE } };
+ }
+ const { offset, limit } = req.body?.paging ?? { offset: 0, limit: 10 };
+ const newestFirst = Array.from({ length: total }, (_, k) => total - 1 - k);
+ const data = newestFirst.slice(offset, offset + limit).map((i) => record({ id: `r${i}`, createdAt: stamp(i) }));
+ return { body: { data, metadata: { offset, limit, total } } };
+ });
+ }
+
+ function storeWith(initial: Record<string, unknown>) {
+ const state = new Map(Object.entries(initial));
+ return {
+ get: async <T>(key: string): Promise<T | null> => {
+ const value = state.get(key);
+ return value === undefined ? null : JSON.parse(JSON.stringify(value));
+ },
+ put: async <T>(key: string, value: T): Promise<T> => {
+ state.set(key, value);
+ return value;
+ },
+ delete: async (key: string) => {
+ state.delete(key);
+ },
+ };
+ }
+
+ async function runTriggerHook({ hook, context }: { hook: (context: never) => Promise<unknown>; context: unknown }): Promise<unknown[]> {
+ const result: unknown = await Reflect.apply(hook, newDatabaseRecord, [context]);
+ return Array.isArray(result) ? result : [];
+ }
+
+ function readId(item: unknown): string {
+ return typeof item === 'object' && item !== null && 'id' in item ? String(item.id) : '';
+ }
+
+ function searchCalls() {
+ return sendRequest.mock.calls.filter((c) => c[0].url.endsWith('/records/search'));
+ }
+
+ it('test mode asks Softr for the five newest records sorted by created_at', async () => {
+ mockTable({ total: 1000 });
+ const base = createMockPollingTriggerContext<InputPropertyMap>({ propsValue: { databaseId: 'db1', tableId: 'tbl1' } });
+ const output = await runTriggerHook({ hook: newDatabaseRecord.test, context: { ...base, auth: TEST_AUTH, store: storeWith({}) } });
+ expect(output.map(readId)).toEqual(['r999', 'r998', 'r997', 'r996', 'r995']);
+ expect(searchCalls().length).toBe(1);
+ expect(searchCalls()[0][0].body).toEqual({ paging: { offset: 0, limit: 5 }, sorting: [{ sortingField: 'created_at', sortType: 'DESC' }] });
+ });
+
+ it('a poll pages newest-first only until it passes the checkpoint, with no gaps or duplicates', async () => {
+ mockTable({ total: 1000 });
+ const base = createMockPollingTriggerContext<InputPropertyMap>({ propsValue: { databaseId: 'db1', tableId: 'tbl1' } });
+ const checkpoint = new Date(stamp(850)).getTime();
+ const output = await runTriggerHook({
+ hook: newDatabaseRecord.run,
+ context: { ...base, auth: TEST_AUTH, store: storeWith({ lastPoll: checkpoint }) },
+ });
+ const ids = output.map(readId);
+ expect(ids.length).toBe(149);
+ expect(new Set(ids).size).toBe(149);
+ expect(ids[0]).toBe('r999');
+ expect(ids[ids.length - 1]).toBe('r851');
+ expect(searchCalls().length).toBe(2);
+ });
+
+ it('a poll with nothing new makes a single request', async () => {
+ mockTable({ total: 50 });
+ const base = createMockPollingTriggerContext<InputPropertyMap>({ propsValue: { databaseId: 'db1', tableId: 'tbl1' } });
+ const output = await runTriggerHook({
+ hook: newDatabaseRecord.run,
+ context: { ...base, auth: TEST_AUTH, store: storeWith({ lastPoll: new Date(stamp(49)).getTime() }) },
+ });
+ expect(output).toEqual([]);
+ expect(searchCalls().length).toBe(1);
+ });
+});
diff --git a/packages/pieces/community/softr/vitest.config.ts b/packages/pieces/community/softr/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/softr/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'),
+ },
+ },
+})