AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(bika): find, create and update records from flows and AI agents (#16217)
Odai Ahmadaa97965aef26
diff --git a/bun.lock b/bun.lockindex 4bbf8299159..dc695145beb 100644--- a/bun.lock+++ b/bun.lock@@ -1190,7 +1190,7 @@},"packages/pieces/community/bika": {"name": "@activepieces/piece-bika",- "version": "0.2.0",+ "version": "0.3.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -1199,6 +1199,7 @@},"devDependencies": {"tslib": "^2.3.0",+ "vitest": "3.2.6",},},"packages/pieces/community/billplz": {diff --git a/packages/pieces/community/bika/package.json b/packages/pieces/community/bika/package.jsonindex ac541a1bac9..0631b459eb3 100644--- a/packages/pieces/community/bika/package.json+++ b/packages/pieces/community/bika/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-bika",- "version": "0.2.0",+ "version": "0.3.0","type": "commonjs","main": "./dist/src/index.js","types": "./dist/src/index.d.ts",@@ -11,11 +11,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/bika/src/i18n/translation.json b/packages/pieces/community/bika/src/i18n/translation.jsonindex 7f8a4d38f16..8a69f8d602c 100644--- a/packages/pieces/community/bika/src/i18n/translation.json+++ b/packages/pieces/community/bika/src/i18n/translation.json@@ -1,19 +1,35 @@{"Interactive spreadsheets with collaboration": "Interactive spreadsheets with collaboration","Token": "Token",- "The token of the Bika account": "The token of the Bika account",- "\n To obtain your Bika token, follow these steps:\n\n 1. Log in to your Bika account.\n 2. Visit https://bika.com.\n 3. Click on your profile picture (Bottom left).\n 4. Click on \"My Settings\".\n 5. Click on \"Developer\".\n 6. Click on \"Generate new token\".\n 7. Copy the token.\n ": "\n To obtain your Bika token, follow these steps:\n\n 1. Log in to your Bika account.\n 2. Visit https://bika.com.\n 3. Click on your profile picture (Bottom left).\n 4. Click on \"My Settings\".\n 5. Click on \"Developer\".\n 6. Click on \"Generate new token\".\n 7. Copy the token.\n ",+ "The API token from Bika (My Settings > Developer).": "The API token from Bika (My Settings > Developer).",+ "Connect Bika.ai with a personal API token.\n\n1. Sign in to [Bika.ai](https://bika.ai).\n2. Click your avatar at the bottom left and open **My Settings**.\n3. Open **Developer** and click **Generate new token**.\n4. Copy the token and paste it below.\n\nThe token can reach every space your Bika user belongs to. On the Free plan each space allows 100 API requests a month.": "Connect Bika.ai with a personal API token.\n\n1. Sign in to [Bika.ai](https://bika.ai).\n2. Click your avatar at the bottom left and open **My Settings**.\n3. Open **Developer** and click **Generate new token**.\n4. Copy the token and paste it below.\n\nThe token can reach every space your Bika user belongs to. On the Free plan each space allows 100 API requests a month.","Create Record": "Create Record","Find Records": "Find Records","Get Record": "Get Record","Update Record": "Update Record","Delete Record": "Delete Record",+ "List Spaces": "List Spaces",+ "List Databases": "List Databases",+ "Get Database Fields": "Get Database Fields",+ "Find Records (by ID)": "Find Records (by ID)",+ "Get Record (by ID)": "Get Record (by ID)",+ "Create Record (by ID)": "Create Record (by ID)",+ "Update Record (by ID)": "Update Record (by ID)",+ "Delete Record (by ID)": "Delete Record (by ID)","Custom API Call": "Custom API Call","Creates a new record in database.": "Creates a new record in database.","Finds records in database.": "Finds records in database.","Retrieves a record in database by ID.": "Retrieves a record in database by ID.","Updates an existing record in database.": "Updates an existing record in database.","Deletes a record in database by ID.": "Deletes a record in database by ID.",+ "Lists the Bika spaces this account belongs to.": "Lists the Bika spaces this account belongs to.",+ "Lists the databases in a space.": "Lists the databases in a space.",+ "Lists the fields (columns) of a database.": "Lists the fields (columns) of a database.",+ "Searches the records of a database.": "Searches the records of a database.",+ "Gets one record by its ID.": "Gets one record by its ID.",+ "Creates a record from a JSON object of field values.": "Creates a record from a JSON object of field values.",+ "Updates fields of a record from a JSON object of field values.": "Updates fields of a record from a JSON object of field values.",+ "Permanently deletes a record by its ID.": "Permanently deletes a record by its ID.","Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint","Space": "Space","Database": "Database",@@ -21,32 +37,55 @@"Max Records": "Max Records","Page Size": "Page Size","Filter": "Filter",+ "Offset": "Offset","Record ID": "Record ID",+ "Space ID": "Space ID",+ "Database ID": "Database ID",+ "Sort Field": "Sort Field",+ "Sort Order": "Sort Order",+ "Limit": "Limit","Method": "Method","Headers": "Headers","Query Parameters": "Query Parameters","Body Type": "Body Type","Body": "Body",- "Response is Binary ?": "Response is Binary ?",- "No Error on Failure": "No Error on Failure",- "Timeout (in seconds)": "Timeout (in seconds)",+ "Response is Binary": "Response is Binary",+ "Return Error as Output": "Return Error as Output",+ "Timeout": "Timeout","Follow redirects": "Follow redirects",- "The fields to add to the record.": "The fields to add to the record.",- "How many records are returned in total.": "How many records are returned in total.",- "How many records are returned per page (max 1000).": "How many records are returned per page (max 1000).",- "The filter to apply to the records (see https://bika.ai/help/guide/developer/filter-query-language).": "The filter to apply to the records (see https://bika.ai/help/guide/developer/filter-query-language).",- "The ID of the record to update.": "The ID of the record to update.",- "The ID of the record to delete.": "The ID of the record to delete.",+ "The Bika space that holds the database.": "The Bika space that holds the database.",+ "The database (table) to work with.": "The database (table) to work with.",+ "The values for the new record. Empty inputs are left blank.": "The values for the new record. Empty inputs are left blank.",+ "How many records to return in total (default 100, at most 1,000).": "How many records to return in total (default 100, at most 1,000).",+ "How many records to fetch per API request (default 100, at most 1,000). Larger pages use fewer of your Bika API requests.": "How many records to fetch per API request (default 100, at most 1,000). Larger pages use fewer of your Bika API requests.",+ "Only return records that match, for example {Stage}==\"Close Deals\";{Score}>10. Put field names with spaces in {}, join conditions with ; (and) or , (or). See https://bika.ai/help/guide/developer/filter-query-language.": "Only return records that match, for example {Stage}==\"Close Deals\";{Score}>10. Put field names with spaces in {}, join conditions with ; (and) or , (or). See https://bika.ai/help/guide/developer/filter-query-language.",+ "To continue a previous search, paste the offset it returned. Leave empty to start from the first record.": "To continue a previous search, paste the offset it returned. Leave empty to start from the first record.",+ "The ID of the record to get (starts with \"rec\").": "The ID of the record to get (starts with \"rec\").",+ "The ID of the record to update (starts with \"rec\").": "The ID of the record to update (starts with \"rec\").",+ "The new values. Empty inputs keep their current value.": "The new values. Empty inputs keep their current value.",+ "The ID of the record to delete (starts with \"rec\").": "The ID of the record to delete (starts with \"rec\").",+ "The space ID (starts with \"spc\"). Use List Spaces to find it.": "The space ID (starts with \"spc\"). Use List Spaces to find it.",+ "The database ID (starts with \"dat\"). Use List Databases to find it.": "The database ID (starts with \"dat\"). Use List Databases to find it.",+ "For example {Stage}==\"Close Deals\";Score>10. Leave empty to list all records.": "For example {Stage}==\"Close Deals\";Score>10. Leave empty to list all records.",+ "Field names to return. Leave empty to return all fields.": "Field names to return. Leave empty to return all fields.",+ "A field name to sort by. Sorted results come back in one page only (no Offset).": "A field name to sort by. Sorted results come back in one page only (no Offset).",+ "How many records to return (1 to 100, default 20).": "How many records to return (1 to 100, default 20).",+ "The next_offset from a previous call, to get the next page.": "The next_offset from a previous call, to get the next page.",+ "The record ID (starts with \"rec\").": "The record ID (starts with \"rec\").",+ "Field values keyed by field name, for example {\"Full name\": \"Ada Lovelace\", \"Stage\": \"Identify Needs\"}.": "Field values keyed by field name, for example {\"Full name\": \"Ada Lovelace\", \"Stage\": \"Identify Needs\"}.",+ "Field values to change, keyed by field name, for example {\"Stage\": \"Close Deals\", \"Notes\": null}.": "Field values to change, keyed by field name, for example {\"Stage\": \"Close Deals\", \"Notes\": null}.","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.",+ "Ascending": "Ascending",+ "Descending": "Descending","GET": "GET","POST": "POST","PATCH": "PATCH","PUT": "PUT","DELETE": "DELETE",- "HEAD": "HEAD",- "None": "None",- "JSON": "JSON",- "Form Data": "Form Data",- "Raw": "Raw"+ "HEAD": "HEAD"}\ No newline at end of filediff --git a/packages/pieces/community/bika/src/index.ts b/packages/pieces/community/bika/src/index.tsindex d12c86f4a16..815aeef05eb 100644--- a/packages/pieces/community/bika/src/index.ts+++ b/packages/pieces/community/bika/src/index.ts@@ -1,39 +1,48 @@import { createCustomApiCallAction } from '@activepieces/pieces-common';-import {- createPiece,- PieceAuth,- PiecePropValueSchema,-} from '@activepieces/pieces-framework';-import { PieceCategory } from '@activepieces/pieces-framework';+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';+import { createRecordByIdAction } from './lib/actions/ai/create-record-by-id';+import { deleteRecordByIdAction } from './lib/actions/ai/delete-record-by-id';+import { findRecordsByIdAction } from './lib/actions/ai/find-records-by-id';+import { getDatabaseFieldsByIdAction } from './lib/actions/ai/get-database-fields-by-id';+import { getRecordByIdAction } from './lib/actions/ai/get-record-by-id';+import { listDatabasesByIdAction } from './lib/actions/ai/list-databases-by-id';+import { updateRecordByIdAction } from './lib/actions/ai/update-record-by-id';import { createRecordAction } from './lib/actions/create-record';+import { deleteRecordAction } from './lib/actions/delete-record';+import { findRecordAction } from './lib/actions/find-record';import { findRecordsAction } from './lib/actions/find-records';-import { findRecordAction} from './lib/actions/find-record';-import {deleteRecordAction } from './lib/actions/delete-record';+import { listSpacesAction } from './lib/actions/list-spaces';import { updateRecordAction } from './lib/actions/update-record';-import { makeClient } from './lib/common';import { BikaAuth } from './lib/auth';+import { BIKA_API_BASE } from './lib/common/client';export const bika = createPiece({displayName: 'Bika.ai',auth: BikaAuth,- description: `Interactive spreadsheets with collaboration`,- minimumSupportedRelease: '0.30.0',+ description: 'Interactive spreadsheets with collaboration',+ minimumSupportedRelease: '0.88.2',logoUrl: 'https://cdn.activepieces.com/pieces/bika.png',categories: [PieceCategory.PRODUCTIVITY],- authors: [- 'codegino'- ],+ authors: ['codegino'],actions: [createRecordAction,findRecordsAction,findRecordAction,updateRecordAction,deleteRecordAction,+ listSpacesAction,+ listDatabasesByIdAction,+ getDatabaseFieldsByIdAction,+ findRecordsByIdAction,+ getRecordByIdAction,+ createRecordByIdAction,+ updateRecordByIdAction,+ deleteRecordByIdAction,createCustomApiCallAction({- baseUrl: () => 'https://bika.ai/api/openapi/bika',+ baseUrl: () => BIKA_API_BASE,auth: BikaAuth,authMapping: async (auth) => ({- Authorization: `Bearer ${(auth).props.token}`,+ Authorization: `Bearer ${auth.props.token.trim()}`,}),}),],diff --git a/packages/pieces/community/bika/src/lib/actions/ai/create-record-by-id.ts b/packages/pieces/community/bika/src/lib/actions/ai/create-record-by-id.tsnew file mode 100644index 00000000000..5c3210c5138--- /dev/null+++ b/packages/pieces/community/bika/src/lib/actions/ai/create-record-by-id.ts@@ -0,0 +1,38 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { BikaAuth } from '../../auth';+import { bikaOperations } from '../../common/operations';+import { bikaProps } from '../../common/props';+import { bikaOutputSchemas } from '../../output-schemas';++export const createRecordByIdAction = createAction({+ auth: BikaAuth,+ name: 'create_record_by_id',+ classification: 'WRITE',+ displayName: 'Create Record (by ID)',+ description: 'Creates a record from a JSON object of field values.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates one record in a Bika.ai database, given its space and database IDs, from a JSON object keyed by exact field names (from Get Database Fields). Formats: text, URL, email and phone as strings; numbers as numbers; checkbox as true/false; single select as the option name; multi select as a list of option names; member as a list of member IDs; link as a list of record IDs; date as ISO 8601; date range as "start/end". Leave out read-only fields (formula, lookup, auto number, created/modified time and by). Each call adds a new record, so a retry creates a duplicate.',+ idempotent: false,+ },+ props: {+ space_id: bikaProps.spaceIdText(),+ database_id: bikaProps.databaseIdText(),+ fields: Property.Json({+ displayName: 'Fields',+ description: 'Field values keyed by field name, for example {"Full name": "Ada Lovelace", "Stage": "Identify Needs"}.',+ required: true,+ defaultValue: {},+ }),+ },+ outputSchema: bikaOutputSchemas.agentRecord,+ async run(context) {+ return bikaOperations.agentCreate({+ auth: context.auth,+ spaceId: context.propsValue.space_id,+ databaseId: context.propsValue.database_id,+ fields: context.propsValue.fields,+ });+ },+});diff --git a/packages/pieces/community/bika/src/lib/actions/ai/delete-record-by-id.ts b/packages/pieces/community/bika/src/lib/actions/ai/delete-record-by-id.tsnew file mode 100644index 00000000000..06cd0d8fefe--- /dev/null+++ b/packages/pieces/community/bika/src/lib/actions/ai/delete-record-by-id.ts@@ -0,0 +1,33 @@+import { createAction } from '@activepieces/pieces-framework';+import { BikaAuth } from '../../auth';+import { bikaOperations } from '../../common/operations';+import { bikaProps } from '../../common/props';+import { bikaOutputSchemas } from '../../output-schemas';++export const deleteRecordByIdAction = createAction({+ auth: BikaAuth,+ name: 'delete_record_by_id',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Record (by ID)',+ description: 'Permanently deletes a record by its ID.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Permanently deletes one Bika.ai record, given its space, database and record IDs. There is no undo; confirm the record with Get Record (by ID) first if unsure. A retry after success fails with not found.',+ idempotent: false,+ },+ props: {+ space_id: bikaProps.spaceIdText(),+ database_id: bikaProps.databaseIdText(),+ record_id: bikaProps.recordIdText({ description: 'The ID of the record to delete (starts with "rec").' }),+ },+ outputSchema: bikaOutputSchemas.agentDeleted,+ async run(context) {+ return bikaOperations.agentDelete({+ auth: context.auth,+ spaceId: context.propsValue.space_id,+ databaseId: context.propsValue.database_id,+ recordId: context.propsValue.record_id,+ });+ },+});diff --git a/packages/pieces/community/bika/src/lib/actions/ai/find-records-by-id.ts b/packages/pieces/community/bika/src/lib/actions/ai/find-records-by-id.tsnew file mode 100644index 00000000000..f3c21713d97--- /dev/null+++ b/packages/pieces/community/bika/src/lib/actions/ai/find-records-by-id.ts@@ -0,0 +1,75 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { BikaAuth } from '../../auth';+import { bikaOperations } from '../../common/operations';+import { bikaProps } from '../../common/props';+import { bikaOutputSchemas } from '../../output-schemas';++export const findRecordsByIdAction = createAction({+ auth: BikaAuth,+ name: 'find_records_by_id',+ classification: 'SEARCH',+ displayName: 'Find Records (by ID)',+ description: 'Searches the records of a database.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Searches records of a Bika.ai database, given its space and database IDs, with an optional filter in the Bika filter query language (field==value, field names with spaces in {}, ; for AND or , for OR but never both, dates compared by day), optional sort and field list. Returns up to Limit records (default 20, max 100) with has_more and next_offset for paging; sorted results cannot be paged, so with a sort raise Limit or narrow the filter instead. Read-only.',+ idempotent: true,+ },+ props: {+ space_id: bikaProps.spaceIdText(),+ database_id: bikaProps.databaseIdText(),+ filter: Property.LongText({+ displayName: 'Filter',+ description: 'For example {Stage}=="Close Deals";Score>10. Leave empty to list all records.',+ required: false,+ }),+ fields: Property.Array({+ displayName: 'Fields',+ description: 'Field names to return. Leave empty to return all fields.',+ required: false,+ }),+ sort_field: Property.ShortText({+ displayName: 'Sort Field',+ description: 'A field name to sort by. Sorted results come back in one page only (no Offset).',+ required: false,+ }),+ sort_order: Property.StaticDropdown({+ displayName: 'Sort Order',+ required: false,+ defaultValue: 'asc',+ options: {+ options: [+ { label: 'Ascending', value: 'asc' },+ { label: 'Descending', value: 'desc' },+ ],+ },+ }),+ limit: Property.Number({+ displayName: 'Limit',+ description: 'How many records to return (1 to 100, default 20).',+ required: false,+ defaultValue: 20,+ }),+ offset: Property.ShortText({+ displayName: 'Offset',+ description: 'The next_offset from a previous call, to get the next page.',+ required: false,+ }),+ },+ outputSchema: bikaOutputSchemas.agentFind,+ async run(context) {+ const props = context.propsValue;+ return bikaOperations.agentFind({+ auth: context.auth,+ spaceId: props.space_id,+ databaseId: props.database_id,+ filter: props.filter,+ fields: props.fields,+ sortField: props.sort_field,+ sortOrder: props.sort_order,+ limit: props.limit,+ offset: props.offset,+ });+ },+});diff --git a/packages/pieces/community/bika/src/lib/actions/ai/get-database-fields-by-id.ts b/packages/pieces/community/bika/src/lib/actions/ai/get-database-fields-by-id.tsnew file mode 100644index 00000000000..6942adba494--- /dev/null+++ b/packages/pieces/community/bika/src/lib/actions/ai/get-database-fields-by-id.ts@@ -0,0 +1,31 @@+import { createAction } from '@activepieces/pieces-framework';+import { BikaAuth } from '../../auth';+import { bikaOperations } from '../../common/operations';+import { bikaProps } from '../../common/props';+import { bikaOutputSchemas } from '../../output-schemas';++export const getDatabaseFieldsByIdAction = createAction({+ auth: BikaAuth,+ name: 'get_database_fields_by_id',+ classification: 'READ',+ displayName: 'Get Database Fields',+ description: 'Lists the fields (columns) of a database.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the fields (columns) of a Bika.ai database, given its space and database IDs: exact name, type, whether it is writable, the value format to write, and option names for select fields. Call it before creating, updating or filtering records so field names and values match. Read-only.',+ idempotent: true,+ },+ props: {+ space_id: bikaProps.spaceIdText(),+ database_id: bikaProps.databaseIdText(),+ },+ outputSchema: bikaOutputSchemas.fields,+ async run(context) {+ return bikaOperations.getFields({+ auth: context.auth,+ spaceId: context.propsValue.space_id,+ databaseId: context.propsValue.database_id,+ });+ },+});diff --git a/packages/pieces/community/bika/src/lib/actions/ai/get-record-by-id.ts b/packages/pieces/community/bika/src/lib/actions/ai/get-record-by-id.tsnew file mode 100644index 00000000000..3d8fb4e3bd3--- /dev/null+++ b/packages/pieces/community/bika/src/lib/actions/ai/get-record-by-id.ts@@ -0,0 +1,33 @@+import { createAction } from '@activepieces/pieces-framework';+import { BikaAuth } from '../../auth';+import { bikaOperations } from '../../common/operations';+import { bikaProps } from '../../common/props';+import { bikaOutputSchemas } from '../../output-schemas';++export const getRecordByIdAction = createAction({+ auth: BikaAuth,+ name: 'get_record_by_id',+ classification: 'READ',+ displayName: 'Get Record (by ID)',+ description: 'Gets one record by its ID.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Gets one Bika.ai record, given its space, database and record IDs, with its cell values keyed by field name. Use Find Records (by ID) when you do not know the record ID. Read-only.',+ idempotent: true,+ },+ props: {+ space_id: bikaProps.spaceIdText(),+ database_id: bikaProps.databaseIdText(),+ record_id: bikaProps.recordIdText({ description: 'The record ID (starts with "rec").' }),+ },+ outputSchema: bikaOutputSchemas.agentRecord,+ async run(context) {+ return bikaOperations.agentGet({+ auth: context.auth,+ spaceId: context.propsValue.space_id,+ databaseId: context.propsValue.database_id,+ recordId: context.propsValue.record_id,+ });+ },+});diff --git a/packages/pieces/community/bika/src/lib/actions/ai/list-databases-by-id.ts b/packages/pieces/community/bika/src/lib/actions/ai/list-databases-by-id.tsnew file mode 100644index 00000000000..b652eec104e--- /dev/null+++ b/packages/pieces/community/bika/src/lib/actions/ai/list-databases-by-id.ts@@ -0,0 +1,26 @@+import { createAction } from '@activepieces/pieces-framework';+import { BikaAuth } from '../../auth';+import { bikaOperations } from '../../common/operations';+import { bikaProps } from '../../common/props';+import { bikaOutputSchemas } from '../../output-schemas';++export const listDatabasesByIdAction = createAction({+ auth: BikaAuth,+ name: 'list_databases_by_id',+ classification: 'SEARCH',+ displayName: 'List Databases',+ description: 'Lists the databases in a space.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists the databases (tables) in a Bika.ai space, given its space ID from List Spaces, with each database ID, name and folder path (first 200). Use it to find the database ID that Get Database Fields and the record actions need. Read-only.',+ idempotent: true,+ },+ props: {+ space_id: bikaProps.spaceIdText(),+ },+ outputSchema: bikaOutputSchemas.databases,+ async run(context) {+ return bikaOperations.listDatabases({ auth: context.auth, spaceId: context.propsValue.space_id });+ },+});diff --git a/packages/pieces/community/bika/src/lib/actions/ai/update-record-by-id.ts b/packages/pieces/community/bika/src/lib/actions/ai/update-record-by-id.tsnew file mode 100644index 00000000000..0302a10e7de--- /dev/null+++ b/packages/pieces/community/bika/src/lib/actions/ai/update-record-by-id.ts@@ -0,0 +1,40 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { BikaAuth } from '../../auth';+import { bikaOperations } from '../../common/operations';+import { bikaProps } from '../../common/props';+import { bikaOutputSchemas } from '../../output-schemas';++export const updateRecordByIdAction = createAction({+ auth: BikaAuth,+ name: 'update_record_by_id',+ classification: 'WRITE',+ displayName: 'Update Record (by ID)',+ description: 'Updates fields of a record from a JSON object of field values.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Updates one Bika.ai record, given its space, database and record IDs, from a JSON object keyed by exact field names; only the listed fields change and null clears a field. Value formats are the same as Create Record (by ID). Repeating the call with the same values leaves the record in the same state.',+ idempotent: true,+ },+ props: {+ space_id: bikaProps.spaceIdText(),+ database_id: bikaProps.databaseIdText(),+ record_id: bikaProps.recordIdText({ description: 'The ID of the record to update (starts with "rec").' }),+ fields: Property.Json({+ displayName: 'Fields',+ description: 'Field values to change, keyed by field name, for example {"Stage": "Close Deals", "Notes": null}.',+ required: true,+ defaultValue: {},+ }),+ },+ outputSchema: bikaOutputSchemas.agentRecord,+ async run(context) {+ return bikaOperations.agentUpdate({+ auth: context.auth,+ spaceId: context.propsValue.space_id,+ databaseId: context.propsValue.database_id,+ recordId: context.propsValue.record_id,+ fields: context.propsValue.fields,+ });+ },+});diff --git a/packages/pieces/community/bika/src/lib/actions/create-record.ts b/packages/pieces/community/bika/src/lib/actions/create-record.tsindex c78aca6967a..7bb6a21c900 100644--- a/packages/pieces/community/bika/src/lib/actions/create-record.ts+++ b/packages/pieces/community/bika/src/lib/actions/create-record.ts@@ -1,9 +1,8 @@-import {- DynamicPropsValue,- createAction,-} from '@activepieces/pieces-framework';-import { BikaCommon, createNewFields, makeClient } from '../common';+import { createAction } from '@activepieces/pieces-framework';import { BikaAuth } from '../auth';+import { bikaOperations } from '../common/operations';+import { bikaProps } from '../common/props';+import { bikaOutputSchemas } from '../output-schemas';export const createRecordAction = createAction({auth: BikaAuth,@@ -11,52 +10,24 @@ export const createRecordAction = createAction({classification: 'WRITE',displayName: 'Create Record',description: 'Creates a new record in database.',- audience: 'both',- aiMetadata: { description: 'Creates a new record in a Bika.ai database table, populating its fields. Requires a space and database (table) to target; field values must match the database schema (read-only field types like formulas and autonumber are ignored). Not idempotent: each call appends a new record.', idempotent: false },+ audience: 'human',+ aiMetadata: {+ description:+ 'Creates one record in a Bika.ai database picked from dropdowns, with one input per writable field; files given for attachment fields are uploaded first. Read-only fields (formula, lookup, auto number, created/modified time and by) are not offered. Each call adds a new record, so a retry creates a duplicate.',+ idempotent: false,+ },props: {- space_id: BikaCommon.space_id,- database_id: BikaCommon.database_id,- fields: BikaCommon.fields,+ space_id: bikaProps.space(),+ database_id: bikaProps.database(),+ fields: bikaProps.fields({ description: 'The values for the new record. Empty inputs are left blank.' }),},+ outputSchema: bikaOutputSchemas.humanCreatedRecord,async run(context) {- const auth = context.auth;- const databaseId = context.propsValue.database_id;- const spaceId = context.propsValue.space_id;- const dynamicFields: DynamicPropsValue = context.propsValue.fields;- const fields: {- [n: string]: any;- } = {};-- const props = Object.entries(dynamicFields);- for (const [propertyKey, propertyValue] of props) {- if (propertyValue !== undefined && propertyValue !== '') {- fields[propertyKey] = propertyValue;- }- }-- const newFields: Record<string, unknown> = await createNewFields(- auth,- spaceId,- databaseId,- fields- );-- const client = makeClient(- context.auth.props,- );- const response: any = await client.createRecord(spaceId, databaseId , {- records: [- {- fields: {- ...newFields,- },- },- ],+ return bikaOperations.humanCreate({+ auth: context.auth,+ spaceId: context.propsValue.space_id,+ databaseId: context.propsValue.database_id,+ fields: context.propsValue.fields,});-- if (!response.success) {- throw new Error(JSON.stringify(response, undefined, 2));- }- return response;},});diff --git a/packages/pieces/community/bika/src/lib/actions/delete-record.ts b/packages/pieces/community/bika/src/lib/actions/delete-record.tsindex d9202be2176..4fdfe1b72d1 100644--- a/packages/pieces/community/bika/src/lib/actions/delete-record.ts+++ b/packages/pieces/community/bika/src/lib/actions/delete-record.ts@@ -1,9 +1,8 @@-import {- Property,- createAction,-} from '@activepieces/pieces-framework';-import { BikaCommon, makeClient } from '../common';+import { createAction } from '@activepieces/pieces-framework';import { BikaAuth } from '../auth';+import { bikaOperations } from '../common/operations';+import { bikaProps } from '../common/props';+import { bikaOutputSchemas } from '../output-schemas';export const deleteRecordAction = createAction({auth: BikaAuth,@@ -11,35 +10,24 @@ export const deleteRecordAction = createAction({classification: 'DESTRUCTIVE',displayName: 'Delete Record',description: 'Deletes a record in database by ID.',- audience: 'both',- aiMetadata: { description: 'Deletes a single record from a Bika.ai database by its record ID, within a given space and database. Use to permanently remove a known record. Idempotent in effect: once removed, repeating the call leaves the record absent.', idempotent: true },+ audience: 'human',+ aiMetadata: {+ description:+ 'Permanently deletes one Bika.ai record by its record ID from a database picked from dropdowns. A retry after success fails with not found.',+ idempotent: false,+ },props: {- space_id: BikaCommon.space_id,- database_id: BikaCommon.database_id,- recordId: Property.ShortText({- displayName: 'Record ID',- description: 'The ID of the record to delete.',- required: true,- }),+ space_id: bikaProps.space(),+ database_id: bikaProps.database(),+ recordId: bikaProps.recordId({ description: 'The ID of the record to delete (starts with "rec").' }),},+ outputSchema: bikaOutputSchemas.humanDeleted,async run(context) {- const databaseId = context.propsValue.database_id;- const spaceId = context.propsValue.space_id;- const recordId = context.propsValue.recordId;-- const client = makeClient(- context.auth.props,- );-- const response: any = await client.deleteRecord(- spaceId,- databaseId,- recordId,- );-- if (!response.success) {- throw new Error(JSON.stringify(response, undefined, 2));- }- return response;+ return bikaOperations.humanDelete({+ auth: context.auth,+ spaceId: context.propsValue.space_id,+ databaseId: context.propsValue.database_id,+ recordId: context.propsValue.recordId,+ });},});diff --git a/packages/pieces/community/bika/src/lib/actions/find-record.ts b/packages/pieces/community/bika/src/lib/actions/find-record.tsindex 206efc08aa4..cf5a25f98a4 100644--- a/packages/pieces/community/bika/src/lib/actions/find-record.ts+++ b/packages/pieces/community/bika/src/lib/actions/find-record.ts@@ -1,10 +1,8 @@-import {- PiecePropValueSchema,- Property,- createAction,-} from '@activepieces/pieces-framework';-import { BikaCommon, makeClient } from '../common';+import { createAction } from '@activepieces/pieces-framework';import { BikaAuth } from '../auth';+import { bikaOperations } from '../common/operations';+import { bikaProps } from '../common/props';+import { bikaOutputSchemas } from '../output-schemas';export const findRecordAction = createAction({auth: BikaAuth,@@ -12,34 +10,24 @@ export const findRecordAction = createAction({classification: 'READ',displayName: 'Get Record',description: 'Retrieves a record in database by ID.',- audience: 'both',- aiMetadata: { description: 'Retrieves a single record from a Bika.ai database by its record ID. Use when you already know the exact record ID; to search by field values or fetch multiple rows use Find Records instead. Read-only and idempotent.', idempotent: true },+ audience: 'human',+ aiMetadata: {+ description:+ 'Gets one Bika.ai record by its record ID from a database picked from dropdowns. Use Find Records to search by field values instead. Read-only.',+ idempotent: true,+ },props: {- space_id: BikaCommon.space_id,- database_id: BikaCommon.database_id,- recordId: Property.ShortText({- displayName: 'Record ID',- required: true,- }),+ space_id: bikaProps.space(),+ database_id: bikaProps.database(),+ recordId: bikaProps.recordId({ description: 'The ID of the record to get (starts with "rec").' }),},+ outputSchema: bikaOutputSchemas.humanRecord,async run(context) {- const databaseId = context.propsValue.database_id;- const spaceId = context.propsValue.space_id;- const recordId = context.propsValue.recordId;-- const client = makeClient(- context.auth.props,- );-- const response: any = await client.findRecord(- spaceId,- databaseId,- recordId,- );-- if (!response.success) {- throw new Error(JSON.stringify(response, undefined, 2));- }- return response;+ return bikaOperations.humanGet({+ auth: context.auth,+ spaceId: context.propsValue.space_id,+ databaseId: context.propsValue.database_id,+ recordId: context.propsValue.recordId,+ });},});diff --git a/packages/pieces/community/bika/src/lib/actions/find-records.ts b/packages/pieces/community/bika/src/lib/actions/find-records.tsindex 1f48a682ddb..5cd10cb8db2 100644--- a/packages/pieces/community/bika/src/lib/actions/find-records.ts+++ b/packages/pieces/community/bika/src/lib/actions/find-records.ts@@ -1,11 +1,8 @@-import {- PiecePropValueSchema,- Property,- createAction,-} from '@activepieces/pieces-framework';-import { BikaCommon, makeClient } from '../common';+import { createAction, Property } from '@activepieces/pieces-framework';import { BikaAuth } from '../auth';-import { prepareQuery } from '../common/client';+import { bikaOperations } from '../common/operations';+import { bikaProps } from '../common/props';+import { bikaOutputSchemas } from '../output-schemas';export const findRecordsAction = createAction({auth: BikaAuth,@@ -13,51 +10,47 @@ export const findRecordsAction = createAction({classification: 'SEARCH',displayName: 'Find Records',description: 'Finds records in database.',- audience: 'both',- aiMetadata: { description: 'Lists records from a Bika.ai database, optionally narrowed by a filter expression (Bika filter-query-language); with no filter it returns all records up to the configured limits. Use to search or page through a table when you need multiple matching rows rather than a single known ID. Read-only and idempotent.', idempotent: true },+ audience: 'human',+ aiMetadata: {+ description:+ 'Lists records of a Bika.ai database picked from dropdowns, optionally narrowed by a filter in the Bika filter query language, following pages up to Max Records (default 100, at most 1,000). Returns hasMore and an offset to continue. Read-only.',+ idempotent: true,+ },props: {- space_id: BikaCommon.space_id,- database_id: BikaCommon.database_id,+ space_id: bikaProps.space(),+ database_id: bikaProps.database(),maxRecords: Property.Number({displayName: 'Max Records',- description: 'How many records are returned in total.',+ description: 'How many records to return in total (default 100, at most 1,000).',required: false,}),pageSize: Property.Number({displayName: 'Page Size',- description: 'How many records are returned per page (max 1000).',+ description: 'How many records to fetch per API request (default 100, at most 1,000). Larger pages use fewer of your Bika API requests.',required: false,}),filter: Property.LongText({displayName: 'Filter',description:- 'The filter to apply to the records (see https://bika.ai/help/guide/developer/filter-query-language).',+ 'Only return records that match, for example {Stage}=="Close Deals";{Score}>10. Put field names with spaces in {}, join conditions with ; (and) or , (or). See https://bika.ai/help/guide/developer/filter-query-language.',+ required: false,+ }),+ offset: Property.ShortText({+ displayName: 'Offset',+ description: 'To continue a previous search, paste the offset it returned. Leave empty to start from the first record.',required: false,}),},+ outputSchema: bikaOutputSchemas.humanFind,async run(context) {- const databaseId = context.propsValue.database_id;- const spaceId = context.propsValue.space_id;- const maxRecords = context.propsValue.maxRecords;- const pageSize = context.propsValue.pageSize ?? 100;- const filter = context.propsValue.filter;-- const client = makeClient(- context.auth.props,- );- const response: any = await client.listRecords(- spaceId,- databaseId,- prepareQuery({- pageSize,- maxRecords,- filter,- })- );-- if (!response.success) {- throw new Error(JSON.stringify(response, undefined, 2));- }- return response;+ return bikaOperations.humanFind({+ auth: context.auth,+ spaceId: context.propsValue.space_id,+ databaseId: context.propsValue.database_id,+ filter: context.propsValue.filter,+ maxRecords: context.propsValue.maxRecords,+ pageSize: context.propsValue.pageSize,+ offset: context.propsValue.offset,+ });},});diff --git a/packages/pieces/community/bika/src/lib/actions/list-spaces.ts b/packages/pieces/community/bika/src/lib/actions/list-spaces.tsnew file mode 100644index 00000000000..a1486490e3f--- /dev/null+++ b/packages/pieces/community/bika/src/lib/actions/list-spaces.ts@@ -0,0 +1,23 @@+import { createAction } from '@activepieces/pieces-framework';+import { BikaAuth } from '../auth';+import { bikaOperations } from '../common/operations';+import { bikaOutputSchemas } from '../output-schemas';++export const listSpacesAction = createAction({+ auth: BikaAuth,+ name: 'list_spaces',+ classification: 'SEARCH',+ displayName: 'List Spaces',+ description: 'Lists the Bika spaces this account belongs to.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists the Bika.ai spaces the connected token can reach, with each space ID, name and plan. Start here to get the space ID that List Databases and every record action need. Read-only; costs one API request.',+ idempotent: true,+ },+ props: {},+ outputSchema: bikaOutputSchemas.spaces,+ async run(context) {+ return bikaOperations.listSpaces({ auth: context.auth });+ },+});diff --git a/packages/pieces/community/bika/src/lib/actions/update-record.ts b/packages/pieces/community/bika/src/lib/actions/update-record.tsindex 9937ec83e16..d2a3edfd715 100644--- a/packages/pieces/community/bika/src/lib/actions/update-record.ts+++ b/packages/pieces/community/bika/src/lib/actions/update-record.ts@@ -1,66 +1,35 @@-import {- DynamicPropsValue,- PiecePropValueSchema,- Property,- createAction,-} from '@activepieces/pieces-framework';-import { BikaCommon, createNewFields, makeClient } from '../common';+import { createAction } from '@activepieces/pieces-framework';import { BikaAuth } from '../auth';+import { bikaOperations } from '../common/operations';+import { bikaProps } from '../common/props';+import { bikaOutputSchemas } from '../output-schemas';export const updateRecordAction = createAction({- auth: BikaAuth,- name: 'bika_update_record',- classification: 'WRITE',- displayName: 'Update Record',- description: 'Updates an existing record in database.',- audience: 'both',- aiMetadata: { description: 'Updates the fields of an existing Bika.ai record identified by its record ID, within a given space and database. Use when modifying a known record; provide only the fields to change (read-only field types are ignored). Idempotent: repeating with the same input leaves the record in the same state.', idempotent: true },- props: {- space_id: BikaCommon.space_id,- database_id: BikaCommon.database_id,- recordId: Property.ShortText({- displayName: 'Record ID',- description: 'The ID of the record to update.',- required: true,- }),- fields: BikaCommon.fields,- },- async run(context) {- const auth = context.auth;- const databaseId = context.propsValue.database_id;- const spaceId = context.propsValue.space_id;- const recordId = context.propsValue.recordId;- const dynamicFields: DynamicPropsValue = context.propsValue.fields;- const fields: {- [n: string]: any;- } = {};-- const props = Object.entries(dynamicFields);- for (const [propertyKey, propertyValue] of props) {- if (propertyValue !== undefined && propertyValue !== '') {- fields[propertyKey] = propertyValue;- }- }-- const newFields: Record<string, unknown> = await createNewFields(- auth,- spaceId,- databaseId,- fields,- );-- const client = makeClient(context.auth.props);-- const response: any = await client.updateRecord(spaceId, databaseId, recordId, {- fields: {- ...newFields,- },- });-- if (!response.success) {- throw new Error(JSON.stringify(response, undefined, 2));- }-- return response;- },+ auth: BikaAuth,+ name: 'bika_update_record',+ classification: 'WRITE',+ displayName: 'Update Record',+ description: 'Updates an existing record in database.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Updates the fields of one existing Bika.ai record, given its record ID, in a database picked from dropdowns. Only the fields you fill in are changed; empty inputs keep their current value. Repeating the call with the same values leaves the record in the same state.',+ idempotent: true,+ },+ props: {+ space_id: bikaProps.space(),+ database_id: bikaProps.database(),+ recordId: bikaProps.recordId({ description: 'The ID of the record to update (starts with "rec").' }),+ fields: bikaProps.fields({ description: 'The new values. Empty inputs keep their current value.' }),+ },+ outputSchema: bikaOutputSchemas.humanRecord,+ async run(context) {+ return bikaOperations.humanUpdate({+ auth: context.auth,+ spaceId: context.propsValue.space_id,+ databaseId: context.propsValue.database_id,+ recordId: context.propsValue.recordId,+ fields: context.propsValue.fields,+ });+ },});diff --git a/packages/pieces/community/bika/src/lib/auth.ts b/packages/pieces/community/bika/src/lib/auth.tsindex 8891ae7b99e..996d757a84d 100644--- a/packages/pieces/community/bika/src/lib/auth.ts+++ b/packages/pieces/community/bika/src/lib/auth.ts@@ -1,40 +1,34 @@-import { PieceAuth, PiecePropValueSchema } from '@activepieces/pieces-framework';-import { makeClient } from './common';+import { AppConnectionValueForAuthProperty, PieceAuth } from '@activepieces/pieces-framework';+import { BikaApiError, bikaClient } from './common/client';export const BikaAuth = PieceAuth.CustomAuth({required: true,- description: `- To obtain your Bika token, follow these steps:+ description: `Connect Bika.ai with a personal API token.- 1. Log in to your Bika account.- 2. Visit https://bika.com.- 3. Click on your profile picture (Bottom left).- 4. Click on "My Settings".- 5. Click on "Developer".- 6. Click on "Generate new token".- 7. Copy the token.- `,+1. Sign in to [Bika.ai](https://bika.ai).+2. Click your avatar at the bottom left and open **My Settings**.+3. Open **Developer** and click **Generate new token**.+4. Copy the token and paste it below.++The token can reach every space your Bika user belongs to. On the Free plan each space allows 100 API requests a month.`,props: {token: PieceAuth.SecretText({displayName: 'Token',- description: 'The token of the Bika account',+ description: 'The API token from Bika (My Settings > Developer).',required: true,}),},validate: async ({ auth }) => {try {- const client = makeClient(- auth as PiecePropValueSchema<typeof BikaAuth>- );- await client.listSpaces();- return {- valid: true,- };- } catch (e) {- return {- valid: false,- error: 'Invalid Token.',- };+ await bikaClient.listSpaces({ token: auth.token });+ return { valid: true };+ } catch (error) {+ if (error instanceof BikaApiError && (error.status === 401 || error.status === 403)) {+ return { valid: false, error: 'Invalid token. Generate a new token in Bika (My Settings > Developer) and paste it here.' };+ }+ return { valid: false, error: `Could not check the token with Bika: ${error instanceof Error ? error.message : String(error)}` };}},});++export type BikaConnection = AppConnectionValueForAuthProperty<typeof BikaAuth>;diff --git a/packages/pieces/community/bika/src/lib/common/client.ts b/packages/pieces/community/bika/src/lib/common/client.tsindex e65b977c8b5..834b34d3a6b 100644--- a/packages/pieces/community/bika/src/lib/common/client.ts+++ b/packages/pieces/community/bika/src/lib/common/client.ts@@ -1,147 +1,487 @@-import {- HttpMessageBody,- HttpMethod,- QueryParams,- AuthenticationType,- httpClient,-} from '@activepieces/pieces-common';-import { BikaFieldType } from './constants';--function emptyValueFilter(- accessor: (key: string) => any-): (key: string) => boolean {- return (key: string) => {- const val = accessor(key);- return (- val !== null &&- val !== undefined &&- (typeof val != 'string' || val.length > 0)- );+import { randomBytes } from 'crypto';+import { AuthenticationType, httpClient, HttpMethod, QueryParams } from '@activepieces/pieces-common';++export const BIKA_API_BASE = 'https://bika.ai/api/openapi/bika';++const REQUEST_TIMEOUT_MS = 60_000;+const RATE_LIMIT_WAIT_MS = 1_500;+const MAX_ERROR_TEXT = 500;+const MIME_TYPES: Record<string, string> = {+ png: 'image/png',+ jpg: 'image/jpeg',+ jpeg: 'image/jpeg',+ gif: 'image/gif',+ webp: 'image/webp',+ svg: 'image/svg+xml',+ pdf: 'application/pdf',+ txt: 'text/plain',+ csv: 'text/csv',+ json: 'application/json',+ doc: 'application/msword',+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',+ xls: 'application/vnd.ms-excel',+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',+ mp3: 'audio/mpeg',+ mp4: 'video/mp4',+ zip: 'application/zip',+};++export class BikaApiError extends Error {+ readonly status: number;+ readonly code: number | undefined;+ readonly responseBody: unknown;++ constructor({ operation, status, responseBody }: { operation: string; status: number; responseBody: unknown }) {+ const code = isRecord(responseBody) && typeof responseBody['code'] === 'number' ? responseBody['code'] : undefined;+ super(`Bika could not ${operation} (HTTP ${status}${code !== undefined && code !== status ? `, code ${code}` : ''}): ${describe({ status, responseBody })}`);+ this.name = 'BikaApiError';+ this.status = status;+ this.code = code;+ this.responseBody = responseBody;+ }+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}++function vendorMessage(responseBody: unknown): string {+ if (typeof responseBody === 'string' && responseBody.trim().length > 0) {+ return responseBody.trim().slice(0, MAX_ERROR_TEXT);+ }+ if (isRecord(responseBody)) {+ const message = responseBody['message'];+ if (typeof message === 'string' && message.length > 0) {+ return message.slice(0, MAX_ERROR_TEXT);+ }+ return JSON.stringify(responseBody).slice(0, MAX_ERROR_TEXT);+ }+ return 'no details returned';+}++function isQuotaMessage(text: string): boolean {+ return /quota|API_REQUEST|usage limit|exceed/i.test(text);+}++function describe({ status, responseBody }: { status: number; responseBody: unknown }): string {+ const detail = vendorMessage(responseBody);+ if (isQuotaMessage(detail)) {+ return `the Bika space has reached its monthly API request quota (the Free plan allows 100 requests a month). Upgrade the space plan or wait for the next month. ${detail}`;+ }+ if (status !== 404 && /not found/i.test(detail)) {+ return `not found. Check the space, database and record IDs. ${detail}`;+ }+ switch (status) {+ case 401:+ return `the API token is invalid or was revoked. Create a new token in Bika (My Settings > Developer) and reconnect. ${detail}`;+ case 403:+ return `the token's user has no access to this space, database or record. ${detail}`;+ case 404:+ return `not found. Check the space, database and record IDs. ${detail}`;+ case 429:+ return `Bika rate limit reached (the Free plan allows 2 requests per second); try again in a minute. ${detail}`;+ default:+ return detail;+ }+}++function statusOf(error: unknown): number | undefined {+ if (!(error instanceof Error)) {+ return undefined;+ }+ const response: unknown = Reflect.get(error, 'response');+ if (isRecord(response) && typeof response['status'] === 'number') {+ return response['status'];+ }+ return undefined;+}++function responseBodyOf(error: unknown): unknown {+ if (!(error instanceof Error)) {+ return undefined;+ }+ const response: unknown = Reflect.get(error, 'response');+ return isRecord(response) ? response['body'] : undefined;+}++function seg({ value, label }: { value: unknown; label: string }): string {+ if (typeof value !== 'string' && typeof value !== 'number') {+ throw new Error(`${label} is required.`);+ }+ const text = String(value).trim();+ if (text.length === 0) {+ throw new Error(`${label} is required.`);+ }+ if (!/^[A-Za-z0-9_-]+$/.test(text)) {+ throw new Error(`${label} "${text.slice(0, 100)}" is not a valid Bika ID. Use the ID only (letters and digits, for example rec... or dat...).`);+ }+ return text;+}++function wait(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++async function request({+ token,+ method,+ path,+ queryParams,+ body,+ contentType,+ operation,+}: {+ token: string;+ method: HttpMethod;+ path: string;+ queryParams?: QueryParams;+ body?: unknown;+ contentType?: string;+ operation: string;+}): Promise<BikaEnvelope> {+ for (let attempt = 0; ; attempt++) {+ try {+ const response = await httpClient.sendRequest<unknown>({+ method,+ url: `${BIKA_API_BASE}${path}`,+ authentication: { type: AuthenticationType.BEARER_TOKEN, token: token.trim() },+ headers: contentType === undefined ? { Accept: 'application/json' } : { Accept: 'application/json', 'Content-Type': contentType },+ queryParams,+ body,+ timeout: REQUEST_TIMEOUT_MS,+ });+ return unwrap({ operation, status: response.status, responseBody: response.body });+ } catch (error) {+ if (error instanceof BikaApiError) {+ throw error;+ }+ const status = statusOf(error);+ if (status === undefined) {+ throw error;+ }+ const responseBody = responseBodyOf(error);+ if (status === 429 && attempt === 0 && !isQuotaMessage(vendorMessage(responseBody))) {+ await wait(RATE_LIMIT_WAIT_MS);+ continue;+ }+ throw new BikaApiError({ operation, status, responseBody });+ }+ }+}++function unwrap({ operation, status, responseBody }: { operation: string; status: number; responseBody: unknown }): BikaEnvelope {+ if (!isRecord(responseBody) || responseBody['success'] !== true) {+ throw new BikaApiError({ operation, status: isRecord(responseBody) && typeof responseBody['code'] === 'number' ? responseBody['code'] : status, responseBody });+ }+ return {+ success: true,+ code: typeof responseBody['code'] === 'number' ? responseBody['code'] : status,+ message: typeof responseBody['message'] === 'string' ? responseBody['message'] : '',+ data: responseBody['data'],+ };+}++function databasePath({ spaceId, databaseId }: { spaceId: unknown; databaseId: unknown }): string {+ return `/v2/spaces/${seg({ value: spaceId, label: 'Space ID' })}/resources/databases/${seg({ value: databaseId, label: 'Database ID' })}/records`;+}++async function listSpaces({ token }: { token: string }) {+ return request({ token, method: HttpMethod.GET, path: '/v1/spaces', operation: 'list spaces' });+}++async function listNodes({ token, spaceId }: { token: string; spaceId: unknown }) {+ return request({+ token,+ method: HttpMethod.GET,+ path: `/v1/spaces/${seg({ value: spaceId, label: 'Space ID' })}/nodes`,+ operation: 'list the space resources',+ });+}++async function listDatabases({ token, spaceId }: { token: string; spaceId: unknown }): Promise<BikaNode[]> {+ const response = await listNodes({ token, spaceId });+ return toNodes(response.data).filter((node) => node.type === 'DATABASE');+}++async function getFields({ token, spaceId, databaseId }: { token: string; spaceId: unknown; databaseId: unknown }) {+ return request({+ token,+ method: HttpMethod.GET,+ path: `/v1/spaces/${seg({ value: spaceId, label: 'Space ID' })}/resources/databases/${seg({ value: databaseId, label: 'Database ID' })}/fields`,+ operation: 'read the database fields',+ });+}++async function listRecordsPage({+ token,+ spaceId,+ databaseId,+ query,+}: {+ token: string;+ spaceId: unknown;+ databaseId: unknown;+ query: QueryParams;+}) {+ return request({+ token,+ method: HttpMethod.GET,+ path: databasePath({ spaceId, databaseId }),+ queryParams: query,+ operation: 'list records',+ });+}++async function getRecord({ token, spaceId, databaseId, recordId }: { token: string; spaceId: unknown; databaseId: unknown; recordId: unknown }) {+ return request({+ token,+ method: HttpMethod.GET,+ path: `${databasePath({ spaceId, databaseId })}/${seg({ value: recordId, label: 'Record ID' })}`,+ operation: 'get the record',+ });+}++async function createRecord({ token, spaceId, databaseId, fields }: { token: string; spaceId: unknown; databaseId: unknown; fields: Record<string, unknown> }) {+ return request({+ token,+ method: HttpMethod.POST,+ path: databasePath({ spaceId, databaseId }),+ body: { fieldKey: 'name', records: [{ fields }] },+ operation: 'create the record',+ });+}++async function updateRecord({+ token,+ spaceId,+ databaseId,+ recordId,+ fields,+}: {+ token: string;+ spaceId: unknown;+ databaseId: unknown;+ recordId: unknown;+ fields: Record<string, unknown>;+}) {+ return request({+ token,+ method: HttpMethod.PUT,+ path: `${databasePath({ spaceId, databaseId })}/${seg({ value: recordId, label: 'Record ID' })}`,+ body: { fieldKey: 'name', fields },+ operation: 'update the record',+ });+}++async function deleteRecord({ token, spaceId, databaseId, recordId }: { token: string; spaceId: unknown; databaseId: unknown; recordId: unknown }) {+ return request({+ token,+ method: HttpMethod.DELETE,+ path: `${databasePath({ spaceId, databaseId })}/${seg({ value: recordId, label: 'Record ID' })}`,+ operation: 'delete the record',+ });+}++async function uploadAttachment({+ token,+ spaceId,+ file,+}: {+ token: string;+ spaceId: unknown;+ file: { filename: string; data: Buffer };+}): Promise<BikaUploadedAttachment> {+ const multipart = multipartBody(file);+ const response = await request({+ token,+ method: HttpMethod.POST,+ path: `/v1/spaces/${seg({ value: spaceId, label: 'Space ID' })}/attachments`,+ body: multipart.body,+ contentType: multipart.contentType,+ operation: `upload the file "${file.filename}"`,+ });+ const first = findAttachment(response.data);+ if (first === undefined) {+ throw new Error(`Bika accepted the file "${file.filename}" but returned no attachment ID: ${JSON.stringify(response.data ?? null).slice(0, MAX_ERROR_TEXT)}`);+ }+ return {+ id: first['id'],+ name: typeof first['name'] === 'string' ? first['name'] : file.filename,+ mimeType: typeof first['mimeType'] === 'string' ? first['mimeType'] : undefined,+ size: typeof first['size'] === 'number' ? first['size'] : undefined,};}-export function prepareQuery(request?: Record<string, any>): QueryParams {- const params: QueryParams = {};- if (!request) return params;- Object.keys(request)- .filter(emptyValueFilter((k) => request[k]))- .forEach((k: string) => {- params[k] = (request as Record<string, any>)[k].toString();- });- return params;-}---export class BikaClient {- constructor( private token: string, private bikaUrl = "https://bika.ai") {}-- async makeRequest<T extends HttpMessageBody>(- method: HttpMethod,- resourceUri: string,- query?: QueryParams,- body: any | undefined = undefined- ): Promise<T> {- const baseUrl = this.bikaUrl.replace(/\/$/, '');-- const res = await httpClient.sendRequest<T>({- method: method,- url: `${baseUrl}/api/openapi/bika` + resourceUri,- authentication: {- type: AuthenticationType.BEARER_TOKEN,- token: this.token,- },- queryParams: query,- body: body,- });-- return res.body;- }-- async listSpaces() {- return await this.makeRequest<{- data: {- id: string;- name: string;- }[];- }>(HttpMethod.GET, '/v1/spaces');- }- async listDatabases(space_id: string) {- return await this.makeRequest<{- data: {- id: string;- name: string;- }[];- }>(HttpMethod.GET, `/v1/spaces/${space_id}/nodes`);- }-- async getDatabaseFields(space_id: string, database_id: string) {- return await this.makeRequest<{- data: {- id: string;- name: string;- type: BikaFieldType;- desc: string;- property?: {- format?: string;- defaultValue?: string;- options?: {- name: string;- id?: string;- }[];- };- }[];- }>(HttpMethod.GET, `/v1/spaces/${space_id}/resources/databases/${database_id}/fields`);- }-- async createRecord(space_id: string, database_id: string, request: object) {- return await this.makeRequest(- HttpMethod.POST,- `/v2/spaces/${space_id}/resources/databases/${database_id}/records`,- undefined,- request- );- }- async deleteRecord(space_id: string, database_id: string, record_id: string) {- return await this.makeRequest(- HttpMethod.DELETE,- `/v2/spaces/${space_id}/resources/databases/${database_id}/records/${record_id}`- );- }- async updateRecord(space_id: string, database_id: string, record_id: string, request: object) {- return await this.makeRequest(- HttpMethod.PUT,- `/v2/spaces/${space_id}/resources/databases/${database_id}/records/${record_id}`,- undefined,- request- );- }-- async findRecord(space_id: string, database_id: string, record_id: string, query?: QueryParams) {- return await this.makeRequest<{- data: {- total: number;- records: {- recordId: string;- createdAt: number;- updatedAt: number;- fields: Record<string, unknown>;- }[];- };- }>(HttpMethod.GET, `/v2/spaces/${space_id}/resources/databases/${database_id}/records/${record_id}`, query);- }--- async listRecords(space_id: string, database_id: string, query?: QueryParams) {- return await this.makeRequest<{- data: {- total: number;- records: {- recordId: string;- createdAt: number;- updatedAt: number;- fields: Record<string, unknown>;- }[];- };- }>(HttpMethod.GET, `/v2/spaces/${space_id}/resources/databases/${database_id}/records`, query);+function multipartBody(file: { filename: string; data: Buffer }): { body: Buffer; contentType: string } {+ const boundary = `----ActivepiecesBika${randomBytes(12).toString('hex')}`;+ const safeName = file.filename.replace(/["\r\n\\]/g, '_');+ const head = Buffer.from(+ `--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${safeName}"\r\nContent-Type: ${mimeType(file.filename)}\r\n\r\n`,+ 'utf8',+ );+ const tail = Buffer.from(`\r\n--${boundary}--\r\n`, 'utf8');+ return { body: Buffer.concat([head, file.data, tail]), contentType: `multipart/form-data; boundary=${boundary}` };+}++function mimeType(filename: string): string {+ const extension = filename.includes('.') ? filename.split('.').pop()?.toLowerCase() ?? '' : '';+ return MIME_TYPES[extension] ?? 'application/octet-stream';+}++function findAttachment(data: unknown): Record<string, unknown> & { id: string } | undefined {+ const candidates: unknown[] = [];+ if (Array.isArray(data)) {+ candidates.push(data[0]);+ } else if (isRecord(data)) {+ candidates.push(data);+ for (const key of ['attachment', 'attachments', 'data']) {+ const nested = data[key];+ candidates.push(Array.isArray(nested) ? nested[0] : nested);+ }+ }+ for (const candidate of candidates) {+ if (isRecord(candidate) && typeof candidate['id'] === 'string') {+ return { ...candidate, id: candidate['id'] };+ }}+ return undefined;+}++function text(value: unknown): string | undefined {+ return typeof value === 'string' ? value : undefined;+}++function toSpaces(data: unknown): BikaSpace[] {+ return (Array.isArray(data) ? data : []).filter(isRecord).map((space) => {+ const subscription = isRecord(space['subscription']) ? space['subscription'] : {};+ return {+ id: String(space['id'] ?? ''),+ name: String(space['name'] ?? ''),+ createdAt: text(space['createdAt']),+ memberCount: typeof space['memberCount'] === 'number' ? space['memberCount'] : undefined,+ plan: text(subscription['plan']),+ };+ });}++function toNodes(data: unknown): BikaNode[] {+ return (Array.isArray(data) ? data : []).filter(isRecord).map((node) => ({+ id: String(node['id'] ?? ''),+ name: String(node['name'] ?? ''),+ type: String(node['type'] ?? ''),+ parentId: text(node['parentId']),+ path: text(node['path']),+ }));+}++function toFields(data: unknown): BikaField[] {+ return (Array.isArray(data) ? data : []).filter(isRecord).map((field) => {+ const property = isRecord(field['property']) ? field['property'] : {};+ const options = Array.isArray(property['options']) ? property['options'].filter(isRecord) : [];+ return {+ id: String(field['id'] ?? ''),+ name: String(field['name'] ?? ''),+ type: String(field['type'] ?? ''),+ description: text(field['description']),+ primary: field['primary'] === true,+ options: options.map((option) => ({ id: text(option['id']), name: String(option['name'] ?? '') })),+ };+ });+}++function toRecord(data: unknown): BikaRecord {+ if (!isRecord(data) || typeof data['id'] !== 'string') {+ throw new Error('Bika returned a record without an ID.');+ }+ return {+ id: data['id'],+ fields: isRecord(data['fields']) ? data['fields'] : {},+ createdAt: text(data['createdAt']),+ updatedAt: text(data['updatedAt']),+ };+}++function toRecordPage(data: unknown): BikaRecordPage {+ const page = isRecord(data) ? data : {};+ const records = Array.isArray(page['records']) ? page['records'] : [];+ const offset = text(page['offset']);+ return {+ records: records.map(toRecord),+ hasMore: page['hasMore'] === true && offset !== undefined && offset.length > 0,+ offset: offset !== undefined && offset.length > 0 ? offset : undefined,+ };+}++function toCreatedRecord(data: unknown): BikaRecord {+ const records = isRecord(data) && Array.isArray(data['records']) ? data['records'] : [];+ return toRecord(records[0]);+}++export const bikaHelpers = { isRecord, seg, wait, isQuotaMessage };++export const bikaParse = { toSpaces, toNodes, toFields, toRecord, toRecordPage, toCreatedRecord };++export const bikaClient = {+ listSpaces,+ listNodes,+ listDatabases,+ getFields,+ listRecordsPage,+ getRecord,+ createRecord,+ updateRecord,+ deleteRecord,+ uploadAttachment,+};++export type BikaEnvelope = {+ success: boolean;+ code: number;+ message: string;+ data: unknown;+};++export type BikaSpace = {+ id: string;+ name: string;+ createdAt?: string;+ memberCount?: number;+ plan?: string;+};++export type BikaNode = {+ id: string;+ name: string;+ type: string;+ parentId?: string;+ path?: string;+};++export type BikaField = {+ id: string;+ name: string;+ type: string;+ description?: string;+ primary: boolean;+ options: { id?: string; name: string }[];+};++export type BikaRecord = {+ id: string;+ fields: Record<string, unknown>;+ createdAt?: string;+ updatedAt?: string;+};++export type BikaRecordPage = {+ records: BikaRecord[];+ hasMore: boolean;+ offset?: string;+};++export type BikaUploadedAttachment = {+ id: string;+ name: string;+ mimeType?: string;+ size?: number;+};diff --git a/packages/pieces/community/bika/src/lib/common/constants.ts b/packages/pieces/community/bika/src/lib/common/constants.tsindex 7deb8713f98..82ff9e7ab52 100644--- a/packages/pieces/community/bika/src/lib/common/constants.ts+++ b/packages/pieces/community/bika/src/lib/common/constants.ts@@ -1,33 +1,64 @@-export const enum BikaFieldType {- SINGLE_TEXT = 'SINGLE_TEXT',- LINK = 'LINK',- LOOKUP = 'LOOKUP',- SINGLE_SELECT = 'SINGLE_SELECT',- MEMBER = 'MEMBER',- DATETIME = 'DATETIME',- NUMBER = 'NUMBER',- FORMULA = 'FORMULA',- LONG_TEXT = 'LONG_TEXT',- MULTI_SELECT = 'MULTI_SELECT',- CURRENCY = 'CURRENCY',- PERCENT = 'PERCENT',- RATING = 'RATING',- CHECKBOX = 'CHECKBOX',- URL = 'URL',- PHONE = 'PHONE',- EMAIL = 'EMAIL',- AUTONUMBER = 'AUTONUMBER',- CREATED_BY = 'CREATED_BY',- LAST_MODIFIED_BY = 'LAST_MODIFIED_BY',- CASCADER = 'CASCADER',- CREATED_TIME = 'CREATED_TIME',- LAST_MODIFIED_TIME = 'LAST_MODIFIED_TIME',- ATTACHMENT = 'ATTACHMENT',+export enum BikaFieldType {+ SINGLE_TEXT = 'SINGLE_TEXT',+ LONG_TEXT = 'LONG_TEXT',+ URL = 'URL',+ EMAIL = 'EMAIL',+ PHONE = 'PHONE',+ NUMBER = 'NUMBER',+ CURRENCY = 'CURRENCY',+ PERCENT = 'PERCENT',+ RATING = 'RATING',+ CHECKBOX = 'CHECKBOX',+ SINGLE_SELECT = 'SINGLE_SELECT',+ MULTI_SELECT = 'MULTI_SELECT',+ MEMBER = 'MEMBER',+ DATETIME = 'DATETIME',+ DATERANGE = 'DATERANGE',+ ATTACHMENT = 'ATTACHMENT',+ LINK = 'LINK',+ ONE_WAY_LINK = 'ONE_WAY_LINK',+ LOOKUP = 'LOOKUP',+ FORMULA = 'FORMULA',+ AUTO_NUMBER = 'AUTO_NUMBER',+ CREATED_TIME = 'CREATED_TIME',+ MODIFIED_TIME = 'MODIFIED_TIME',+ CREATED_BY = 'CREATED_BY',+ MODIFIED_BY = 'MODIFIED_BY',+ CASCADER = 'CASCADER',+ JSON = 'JSON',+ AI_TEXT = 'AI_TEXT',+ WORK_DOC = 'WORK_DOC',+ BUTTON = 'BUTTON',}-export const BikaNumericFieldTypes = [- BikaFieldType.NUMBER,- BikaFieldType.RATING,- BikaFieldType.CURRENCY,- BikaFieldType.PERCENT,+export const BIKA_WRITE_FORMATS: Record<string, string> = {+ [BikaFieldType.SINGLE_TEXT]: 'string',+ [BikaFieldType.LONG_TEXT]: 'string',+ [BikaFieldType.URL]: 'string (URL)',+ [BikaFieldType.EMAIL]: 'string (email address)',+ [BikaFieldType.PHONE]: 'string (phone number)',+ [BikaFieldType.NUMBER]: 'number',+ [BikaFieldType.CURRENCY]: 'number',+ [BikaFieldType.PERCENT]: 'number',+ [BikaFieldType.RATING]: 'number',+ [BikaFieldType.CHECKBOX]: 'boolean',+ [BikaFieldType.SINGLE_SELECT]: 'string: one option name',+ [BikaFieldType.MULTI_SELECT]: 'array of option names',+ [BikaFieldType.MEMBER]: 'array of member, team or role IDs',+ [BikaFieldType.DATETIME]: 'ISO 8601 date-time string',+ [BikaFieldType.DATERANGE]: 'string "start/end" with two ISO 8601 date-times',+ [BikaFieldType.ATTACHMENT]: 'array of {"id": "<attachment ID>"} objects from an earlier upload',+ [BikaFieldType.LINK]: 'array of record IDs from the linked database',+ [BikaFieldType.ONE_WAY_LINK]: 'array of record IDs from the linked database',+};++export const BIKA_READ_ONLY_FIELD_TYPES: string[] = [+ BikaFieldType.LOOKUP,+ BikaFieldType.FORMULA,+ BikaFieldType.AUTO_NUMBER,+ BikaFieldType.CREATED_TIME,+ BikaFieldType.MODIFIED_TIME,+ BikaFieldType.CREATED_BY,+ BikaFieldType.MODIFIED_BY,+ BikaFieldType.BUTTON,];diff --git a/packages/pieces/community/bika/src/lib/common/index.ts b/packages/pieces/community/bika/src/lib/common/index.tsdeleted file mode 100644index 999c612c60e..00000000000--- a/packages/pieces/community/bika/src/lib/common/index.ts+++ /dev/null@@ -1,250 +0,0 @@-import { AppConnectionValueForAuthProperty, DynamicPropsValue, PiecePropValueSchema, Property } from '@activepieces/pieces-framework';-import { BikaAuth } from '../auth';-import { BikaClient } from './client';-import { BikaFieldType, BikaNumericFieldTypes } from './constants';--export function makeClient(auth: PiecePropValueSchema<typeof BikaAuth>) {- const client = new BikaClient(auth.token);- return client;-}--export const BikaCommon = {- space_id: Property.Dropdown({- auth: BikaAuth,- displayName: 'Space',- required: true,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- options: [],- placeholder: 'Connect your account first.',- };- }- const client = makeClient(auth.props);- const res = await client.listSpaces();- return {- disabled: false,- options: res.data.map((space) => {- return {- label: space.name,- value: space.id,- };- }),- };- },- }),- database_id: Property.Dropdown({- auth: BikaAuth,- displayName: 'Database',- required: true,- refreshers: ['space_id'],- options: async ({ auth, space_id }) => {- if (!auth || !space_id) {- return {- disabled: true,- options: [],- placeholder: 'Connect your account first and select space.',- };- }- const client = makeClient(auth.props);- const res = await client.listDatabases(space_id as string);-- return {- disabled: false,- options: res.data.map((database) => {- return {- label: database.name,- value: database.id,- };- }),- };- },- }),- fields: Property.DynamicProperties({- auth: BikaAuth,- displayName: 'Fields',- description: 'The fields to add to the record.',- required: true,- refreshers: ['auth', 'space_id', 'database_id'],- props: async ({ auth, space_id, database_id }) => {- if(!auth || !space_id || !database_id) return {};-- const client = makeClient(auth.props);- const res = await client.getDatabaseFields(space_id as unknown as string, database_id as unknown as string);-- const props: DynamicPropsValue = {};-- for (const field of res.data) {- if (- ![- BikaFieldType.AUTONUMBER,- BikaFieldType.CASCADER,- BikaFieldType.CREATED_BY,- BikaFieldType.CREATED_TIME,- BikaFieldType.FORMULA,- BikaFieldType.LAST_MODIFIED_BY,- BikaFieldType.LAST_MODIFIED_TIME,- BikaFieldType.LOOKUP,- ].includes(field.type)- ) {- switch (field.type) {- case BikaFieldType.ATTACHMENT:- props[field.name] = Property.File({- displayName: field.name,- required: false,- });- break;- case BikaFieldType.CHECKBOX:- props[field.name] = Property.Checkbox({- displayName: field.name,- required: false,- });- break;- case BikaFieldType.CURRENCY:- case BikaFieldType.NUMBER:- case BikaFieldType.PERCENT:- case BikaFieldType.RATING:- props[field.name] = Property.Number({- displayName: field.name,- required: false,- });- break;- case BikaFieldType.DATETIME:- props[field.name] = Property.DateTime({- displayName: field.name,- required: false,- });- break;- case BikaFieldType.EMAIL:- case BikaFieldType.PHONE:- case BikaFieldType.SINGLE_TEXT:- case BikaFieldType.URL:- props[field.name] = Property.ShortText({- displayName: field.name,- required: false,- });- break;- case BikaFieldType.LONG_TEXT:- props[field.name] = Property.LongText({- displayName: field.name,- required: false,- });- break;- case BikaFieldType.MULTI_SELECT:- props[field.name] = Property.StaticMultiSelectDropdown({- displayName: field.name,- required: false,- options: {- options: field.property?.options?.map((option) => ({- label: option.name,- value: option.name,- })) || [],- },- });- break;- case BikaFieldType.SINGLE_SELECT:- props[field.name] = Property.StaticDropdown({- displayName: field.name,- required: false,- options: {- options: field.property?.options?.map((option) => ({- label: option.name,- value: option.name,- })) || [],- },- });- break;- case BikaFieldType.MEMBER:- props[field.name] = Property.StaticMultiSelectDropdown({- displayName: field.name,- required: false,- options: {- options:- field.property?.options?.map((option) => {- return {- label: option.name,- value: option.id,- };- }) || [],- },- });- break;- case BikaFieldType.LINK:- props[field.name] = Property.Array({- displayName: field.name,- required: false,- });- break;- }- }- }- return props;- },- }),-};--export async function createNewFields(- auth: AppConnectionValueForAuthProperty<typeof BikaAuth>,- space_id: string,- database_id: string,- fields: Record<string, unknown>,-) {- if (!auth) return fields;- if (!database_id) return fields;-- const newFields: Record<string, unknown> = {};-- const client = makeClient(auth.props);- const res = await client.getDatabaseFields(space_id,database_id);-- for(const field of res.data) {- if (- [- BikaFieldType.AUTONUMBER,- BikaFieldType.CASCADER,- BikaFieldType.CREATED_BY,- BikaFieldType.CREATED_TIME,- BikaFieldType.FORMULA,- BikaFieldType.LAST_MODIFIED_TIME,- BikaFieldType.LAST_MODIFIED_BY,- BikaFieldType.LOOKUP,- ].includes(field.type) || !(field.name in fields)- ) {- continue; // Skip irrelevant or missing fields- }-- const key = field.name;-- // Handle numeric fields- if(BikaNumericFieldTypes.includes(field.type))- {- newFields[key] = Number(fields[key]);- }- // Handle member fields- else if(field.type === BikaFieldType.MEMBER)- {- newFields[key] = field.property?.options?.filter(- (member) => member.id === `${fields[key]}`,- );- }- // Handle multi-select and two-way-link fields- else if([BikaFieldType.MULTI_SELECT].includes(field.type))- {- if(!Array.isArray(fields[key]) || (fields[key] as Array<unknown>).length === 0)- {- continue; // Skip empty fields- }- newFields[key] = fields[key];- }- // Handle all other fields- else- {- newFields[key] = fields[key];- }--- }- return newFields;-}diff --git a/packages/pieces/community/bika/src/lib/common/operations.ts b/packages/pieces/community/bika/src/lib/common/operations.tsnew file mode 100644index 00000000000..e8d33d47cb0--- /dev/null+++ b/packages/pieces/community/bika/src/lib/common/operations.ts@@ -0,0 +1,337 @@+import { QueryParams } from '@activepieces/pieces-common';+import { BikaConnection } from '../auth';+import { bikaClient, BikaEnvelope, bikaHelpers, bikaParse, BikaRecord } from './client';+import { bikaShape } from './shape';++const HUMAN_DEFAULT_MAX_RECORDS = 100;+const HUMAN_MAX_RECORDS = 1_000;+const HUMAN_DEFAULT_PAGE_SIZE = 100;+const HUMAN_MAX_PAGES = 20;+const PAGE_GAP_MS = 600;+const AGENT_DEFAULT_LIMIT = 20;+const AGENT_MAX_LIMIT = 100;+const AGENT_MAX_DATABASES = 200;++export const bikaOperations = {+ humanCreate,+ humanUpdate,+ humanGet,+ humanDelete,+ humanFind,+ listSpaces,+ listDatabases,+ getFields,+ agentFind,+ agentGet,+ agentCreate,+ agentUpdate,+ agentDelete,+};++async function humanCreate({ auth, spaceId, databaseId, fields }: { auth: BikaConnection; spaceId: unknown; databaseId: unknown; fields: unknown }): Promise<BikaEnvelope> {+ const target = ids({ spaceId, databaseId });+ const values = await humanValues({ auth, spaceId: target.spaceId, fields, emptyMessage: 'Fill in at least one field to create a record.' });+ return bikaClient.createRecord({ token: auth.props.token, ...target, fields: values });+}++async function humanUpdate({+ auth,+ spaceId,+ databaseId,+ recordId,+ fields,+}: {+ auth: BikaConnection;+ spaceId: unknown;+ databaseId: unknown;+ recordId: unknown;+ fields: unknown;+}): Promise<BikaEnvelope> {+ const target = ids({ spaceId, databaseId });+ const record = bikaShape.requireId({ value: recordId, label: 'Record ID' });+ const values = await humanValues({ auth, spaceId: target.spaceId, fields, emptyMessage: 'Fill in at least one field to update.' });+ return bikaClient.updateRecord({ token: auth.props.token, ...target, recordId: record, fields: values });+}++async function humanGet({ auth, spaceId, databaseId, recordId }: { auth: BikaConnection; spaceId: unknown; databaseId: unknown; recordId: unknown }): Promise<BikaEnvelope> {+ const target = ids({ spaceId, databaseId });+ const record = bikaShape.requireId({ value: recordId, label: 'Record ID' });+ return bikaClient.getRecord({ token: auth.props.token, ...target, recordId: record });+}++async function humanDelete({ auth, spaceId, databaseId, recordId }: { auth: BikaConnection; spaceId: unknown; databaseId: unknown; recordId: unknown }): Promise<BikaEnvelope> {+ const target = ids({ spaceId, databaseId });+ const record = bikaShape.requireId({ value: recordId, label: 'Record ID' });+ return bikaClient.deleteRecord({ token: auth.props.token, ...target, recordId: record });+}++async function humanFind({+ auth,+ spaceId,+ databaseId,+ filter,+ maxRecords,+ pageSize,+ offset,+}: {+ auth: BikaConnection;+ spaceId: unknown;+ databaseId: unknown;+ filter: unknown;+ maxRecords: unknown;+ pageSize: unknown;+ offset: unknown;+}) {+ const target = ids({ spaceId, databaseId });+ const max = Math.min(wholeNumber({ value: maxRecords, label: 'Max Records', min: 1, max: Number.MAX_SAFE_INTEGER, fallback: HUMAN_DEFAULT_MAX_RECORDS }), HUMAN_MAX_RECORDS);+ const requestedPage = Math.min(wholeNumber({ value: pageSize, label: 'Page Size', min: 1, max: Number.MAX_SAFE_INTEGER, fallback: HUMAN_DEFAULT_PAGE_SIZE }), 1_000);+ const size = Math.max(requestedPage, Math.ceil(max / HUMAN_MAX_PAGES));+ const filterText = bikaShape.optionalText(filter);+ let cursor = bikaShape.optionalText(offset);+ let records: BikaRecord[] = [];+ let hasMore = true;+ let last: BikaEnvelope | undefined;+ let pages = 0;+ while (records.length < max && hasMore && pages < HUMAN_MAX_PAGES) {+ if (last !== undefined) {+ await bikaHelpers.wait(PAGE_GAP_MS);+ }+ last = await bikaClient.listRecordsPage({+ token: auth.props.token,+ ...target,+ query: recordQuery({ pageSize: Math.min(size, max - records.length), filter: filterText, offset: cursor }),+ });+ pages += 1;+ const page = bikaParse.toRecordPage(last.data);+ records = [...records, ...page.records];+ hasMore = page.hasMore;+ cursor = page.offset;+ if (page.records.length === 0) {+ break;+ }+ }+ const returned = records.slice(0, max);+ return {+ success: true,+ code: last?.code ?? 200,+ message: last?.message ?? 'SUCCESS',+ data: {+ records: returned,+ hasMore: hasMore || records.length > max,+ offset: hasMore && records.length <= max ? cursor ?? null : null,+ },+ };+}++async function listSpaces({ auth }: { auth: BikaConnection }) {+ const response = await bikaClient.listSpaces({ token: auth.props.token });+ const spaces = bikaParse.toSpaces(response.data).map((space) => ({+ id: space.id,+ name: space.name,+ plan: space.plan ?? null,+ member_count: space.memberCount ?? null,+ created_at: space.createdAt ?? null,+ }));+ return { spaces, count: spaces.length };+}++async function listDatabases({ auth, spaceId }: { auth: BikaConnection; spaceId: unknown }) {+ const space = bikaShape.requireId({ value: spaceId, label: 'Space ID' });+ const databases = await bikaClient.listDatabases({ token: auth.props.token, spaceId: space });+ const shaped = databases.slice(0, AGENT_MAX_DATABASES).map((database) => ({+ id: database.id,+ name: database.name,+ path: database.path ?? null,+ parent_id: database.parentId ?? null,+ }));+ return { space_id: space, databases: shaped, count: shaped.length, truncated: databases.length > AGENT_MAX_DATABASES };+}++async function getFields({ auth, spaceId, databaseId }: { auth: BikaConnection; spaceId: unknown; databaseId: unknown }) {+ const target = ids({ spaceId, databaseId });+ const response = await bikaClient.getFields({ token: auth.props.token, ...target });+ const fields = bikaParse.toFields(response.data).map(bikaShape.agentField);+ return { database_id: target.databaseId, fields, count: fields.length };+}++async function agentFind({+ auth,+ spaceId,+ databaseId,+ filter,+ fields,+ sortField,+ sortOrder,+ limit,+ offset,+}: {+ auth: BikaConnection;+ spaceId: unknown;+ databaseId: unknown;+ filter: unknown;+ fields: unknown;+ sortField: unknown;+ sortOrder: unknown;+ limit: unknown;+ offset: unknown;+}) {+ const target = ids({ spaceId, databaseId });+ const size = wholeNumber({ value: limit, label: 'Limit', min: 1, max: AGENT_MAX_LIMIT, fallback: AGENT_DEFAULT_LIMIT });+ const order = bikaShape.optionalText(sortOrder);+ if (order !== undefined && order !== 'asc' && order !== 'desc') {+ throw new Error('Sort Order must be "asc" or "desc".');+ }+ const sort = bikaShape.optionalText(sortField);+ const cursor = bikaShape.optionalText(offset);+ if (sort !== undefined && cursor !== undefined) {+ throw new Error('Bika cannot page through sorted results: its offset ignores the sort. Remove Sort Field to page with Offset, or raise Limit (up to 100) and narrow the Filter.');+ }+ const response = await bikaClient.listRecordsPage({+ token: auth.props.token,+ ...target,+ query: recordQuery({+ pageSize: size,+ filter: bikaShape.optionalText(filter),+ offset: cursor,+ sortField: sort,+ sortOrder: order,+ }),+ });+ const page = bikaParse.toRecordPage(response.data);+ const wanted = textList(fields);+ const records = page.records.slice(0, size).map((record) => (wanted.length === 0 ? record : { ...record, fields: pick({ fields: record.fields, names: wanted }) }));+ const shaped = bikaShape.agentRecords({ records, databaseId: target.databaseId });+ return {+ records: shaped.records,+ count: shaped.records.length,+ has_more: page.hasMore,+ next_offset: sort === undefined ? page.offset ?? null : null,+ truncated_fields: shaped.truncatedFields,+ };+}++async function agentGet({ auth, spaceId, databaseId, recordId }: { auth: BikaConnection; spaceId: unknown; databaseId: unknown; recordId: unknown }) {+ const response = await humanGet({ auth, spaceId, databaseId, recordId });+ return flatRecord({ record: bikaParse.toRecord(response.data), databaseId: String(databaseId).trim() });+}++async function agentCreate({ auth, spaceId, databaseId, fields }: { auth: BikaConnection; spaceId: unknown; databaseId: unknown; fields: unknown }) {+ const target = ids({ spaceId, databaseId });+ const values = bikaShape.parseFieldsJson({ value: fields, label: 'Fields' });+ const response = await bikaClient.createRecord({ token: auth.props.token, ...target, fields: values });+ return flatRecord({ record: bikaParse.toCreatedRecord(response.data), databaseId: target.databaseId });+}++async function agentUpdate({+ auth,+ spaceId,+ databaseId,+ recordId,+ fields,+}: {+ auth: BikaConnection;+ spaceId: unknown;+ databaseId: unknown;+ recordId: unknown;+ fields: unknown;+}) {+ const target = ids({ spaceId, databaseId });+ const record = bikaShape.requireId({ value: recordId, label: 'Record ID' });+ const values = bikaShape.parseFieldsJson({ value: fields, label: 'Fields' });+ const response = await bikaClient.updateRecord({ token: auth.props.token, ...target, recordId: record, fields: values });+ return flatRecord({ record: bikaParse.toRecord(response.data), databaseId: target.databaseId });+}++async function agentDelete({ auth, spaceId, databaseId, recordId }: { auth: BikaConnection; spaceId: unknown; databaseId: unknown; recordId: unknown }) {+ const response = await humanDelete({ auth, spaceId, databaseId, recordId });+ const data = bikaHelpers.isRecord(response.data) ? response.data : {};+ return {+ id: typeof data['id'] === 'string' ? data['id'] : String(recordId).trim(),+ deleted: data['deleted'] !== false,+ };+}++function flatRecord({ record, databaseId }: { record: BikaRecord; databaseId: string }) {+ const shaped = bikaShape.agentRecord({ record, databaseId });+ return { ...shaped.record, truncated_fields: shaped.truncatedFields };+}++async function humanValues({+ auth,+ spaceId,+ fields,+ emptyMessage,+}: {+ auth: BikaConnection;+ spaceId: string;+ fields: unknown;+ emptyMessage: string;+}): Promise<Record<string, unknown>> {+ const cleaned = bikaShape.cleanHumanFields(fields);+ if (Object.keys(cleaned).length === 0) {+ throw new Error(emptyMessage);+ }+ return bikaShape.uploadFiles({ token: auth.props.token, spaceId, fields: cleaned });+}++function ids({ spaceId, databaseId }: { spaceId: unknown; databaseId: unknown }) {+ return {+ spaceId: bikaShape.requireId({ value: spaceId, label: 'Space ID' }),+ databaseId: bikaShape.requireId({ value: databaseId, label: 'Database ID' }),+ };+}++function recordQuery({+ pageSize,+ filter,+ offset,+ sortField,+ sortOrder,+}: {+ pageSize: number;+ filter?: string;+ offset?: string;+ sortField?: string;+ sortOrder?: string;+}): QueryParams {+ const query: QueryParams = { pageSize: String(pageSize), fieldKey: 'name', cellFormat: 'json' };+ if (filter !== undefined) {+ query['filter'] = filter;+ }+ if (offset !== undefined) {+ query['offset'] = offset;+ }+ if (sortField !== undefined) {+ query['sort[0][field]'] = sortField;+ query['sort[0][order]'] = sortOrder ?? 'asc';+ }+ return query;+}++function pick({ fields, names }: { fields: Record<string, unknown>; names: string[] }): Record<string, unknown> {+ return Object.fromEntries(names.filter((name) => name in fields).map((name) => [name, fields[name]]));+}++function textList(value: unknown): string[] {+ if (Array.isArray(value)) {+ return value.flatMap((item) => (typeof item === 'string' && item.trim().length > 0 ? [item.trim()] : []));+ }+ if (typeof value === 'string' && value.trim().length > 0) {+ return value+ .split(',')+ .map((item) => item.trim())+ .filter((item) => item.length > 0);+ }+ return [];+}++function wholeNumber({ value, label, min, max, fallback }: { value: unknown; label: string; min: number; max: number; fallback: number }): number {+ if (value === undefined || value === null || value === '') {+ return fallback;+ }+ const parsed = typeof value === 'number' ? value : typeof value === 'string' ? Number(value.trim()) : Number.NaN;+ if (!Number.isInteger(parsed) || parsed < min || parsed > max) {+ throw new Error(max === Number.MAX_SAFE_INTEGER ? `${label} must be a whole number of at least ${min}.` : `${label} must be a whole number from ${min} to ${max}.`);+ }+ return parsed;+}diff --git a/packages/pieces/community/bika/src/lib/common/props.ts b/packages/pieces/community/bika/src/lib/common/props.tsnew file mode 100644index 00000000000..0fe577d6f0c--- /dev/null+++ b/packages/pieces/community/bika/src/lib/common/props.ts@@ -0,0 +1,187 @@+import { DynamicPropsValue, Property } from '@activepieces/pieces-framework';+import { BikaAuth } from '../auth';+import { bikaClient, BikaField, bikaParse } from './client';+import { BIKA_READ_ONLY_FIELD_TYPES, BikaFieldType } from './constants';++export const bikaProps = {+ space: spaceDropdown,+ database: databaseDropdown,+ fields: fieldsDynamic,+ recordId,+ spaceIdText,+ databaseIdText,+ recordIdText,+};++function spaceDropdown() {+ return Property.Dropdown({+ auth: BikaAuth,+ displayName: 'Space',+ description: 'The Bika space that holds the database.',+ required: true,+ refreshers: [],+ options: async ({ auth }) => {+ if (!auth) {+ return { disabled: true, options: [], placeholder: 'Connect your Bika account first.' };+ }+ try {+ const response = await bikaClient.listSpaces({ token: auth.props.token });+ const spaces = bikaParse.toSpaces(response.data).filter((space) => space.id.length > 0);+ if (spaces.length === 0) {+ return { disabled: true, options: [], placeholder: 'This Bika account has no spaces.' };+ }+ return { disabled: false, options: spaces.map((space) => ({ label: space.name, value: space.id })) };+ } catch (error) {+ return { disabled: true, options: [], placeholder: errorPlaceholder({ error, what: 'spaces' }) };+ }+ },+ });+}++function databaseDropdown() {+ return Property.Dropdown({+ auth: BikaAuth,+ displayName: 'Database',+ description: 'The database (table) to work with.',+ required: true,+ refreshers: ['space_id'],+ options: async ({ auth, space_id }) => {+ if (!auth) {+ return { disabled: true, options: [], placeholder: 'Connect your Bika account first.' };+ }+ if (typeof space_id !== 'string' || space_id.length === 0) {+ return { disabled: true, options: [], placeholder: 'Select a space first.' };+ }+ try {+ const databases = await bikaClient.listDatabases({ token: auth.props.token, spaceId: space_id });+ if (databases.length === 0) {+ return { disabled: true, options: [], placeholder: 'This space has no databases yet. Create one in Bika first.' };+ }+ return {+ disabled: false,+ options: databases.map((database) => ({ label: databaseLabel(database), value: database.id })),+ };+ } catch (error) {+ return { disabled: true, options: [], placeholder: errorPlaceholder({ error, what: 'databases' }) };+ }+ },+ });+}++function fieldsDynamic({ description }: { description: string }) {+ return Property.DynamicProperties({+ auth: BikaAuth,+ displayName: 'Fields',+ description,+ required: true,+ refreshers: ['auth', 'space_id', 'database_id'],+ props: async ({ auth, space_id, database_id }) => {+ if (!auth || typeof space_id !== 'string' || typeof database_id !== 'string' || space_id.length === 0 || database_id.length === 0) {+ return {};+ }+ try {+ const response = await bikaClient.getFields({ token: auth.props.token, spaceId: space_id, databaseId: database_id });+ return Object.fromEntries(+ bikaParse.toFields(response.data)+ .filter((field) => !BIKA_READ_ONLY_FIELD_TYPES.includes(field.type))+ .map((field) => [field.name, fieldProperty(field)])+ .filter((entry): entry is [string, NonNullable<ReturnType<typeof fieldProperty>>] => entry[1] !== null),+ );+ } catch (error) {+ const props: DynamicPropsValue = {+ load_error: Property.MarkDown({ value: `Could not load the database fields: ${error instanceof Error ? error.message : String(error)}` }),+ };+ return props;+ }+ },+ });+}++function recordId({ description }: { description: string }) {+ return Property.ShortText({ displayName: 'Record ID', description, required: true });+}++function spaceIdText() {+ return Property.ShortText({+ displayName: 'Space ID',+ description: 'The space ID (starts with "spc"). Use List Spaces to find it.',+ required: true,+ });+}++function databaseIdText() {+ return Property.ShortText({+ displayName: 'Database ID',+ description: 'The database ID (starts with "dat"). Use List Databases to find it.',+ required: true,+ });+}++function recordIdText({ description }: { description: string }) {+ return Property.ShortText({ displayName: 'Record ID', description, required: true });+}++function fieldProperty(field: BikaField) {+ const base = { displayName: field.name, description: field.description || undefined, required: false };+ switch (field.type) {+ case BikaFieldType.SINGLE_TEXT:+ case BikaFieldType.URL:+ case BikaFieldType.EMAIL:+ case BikaFieldType.PHONE:+ return Property.ShortText(base);+ case BikaFieldType.LONG_TEXT:+ return Property.LongText(base);+ case BikaFieldType.NUMBER:+ case BikaFieldType.CURRENCY:+ case BikaFieldType.PERCENT:+ case BikaFieldType.RATING:+ return Property.Number(base);+ case BikaFieldType.CHECKBOX:+ return Property.Checkbox(base);+ case BikaFieldType.DATETIME:+ return Property.DateTime(base);+ case BikaFieldType.DATERANGE:+ return Property.ShortText({+ ...base,+ description: 'Start and end as two ISO dates joined by "/", for example 2026-01-01T09:00:00Z/2026-01-05T17:00:00Z.',+ });+ case BikaFieldType.SINGLE_SELECT:+ return Property.StaticDropdown({+ ...base,+ options: { options: field.options.map((option) => ({ label: option.name, value: option.name })) },+ });+ case BikaFieldType.MULTI_SELECT:+ return Property.StaticMultiSelectDropdown({+ ...base,+ options: { options: field.options.map((option) => ({ label: option.name, value: option.name })) },+ });+ case BikaFieldType.MEMBER:+ return Property.Array({+ ...base,+ description: 'Member, team or role IDs. Map them from the member field of a Get Record or Find Records step.',+ });+ case BikaFieldType.LINK:+ case BikaFieldType.ONE_WAY_LINK:+ return Property.Array({+ ...base,+ description: 'Record IDs from the linked database (they start with "rec").',+ });+ case BikaFieldType.ATTACHMENT:+ return Property.File({+ ...base,+ description: 'A file to upload to Bika and attach to this field.',+ });+ default:+ return null;+ }+}++function databaseLabel(database: { name: string; path?: string }): string {+ const folder = (database.path ?? '').replace(/^\/ROOT\/?/, '');+ return folder.length > 0 ? `${database.name} (${folder})` : database.name;+}++function errorPlaceholder({ error, what }: { error: unknown; what: string }): string {+ const message = error instanceof Error ? error.message : String(error);+ return `Could not load ${what}: ${message}`.slice(0, 300);+}diff --git a/packages/pieces/community/bika/src/lib/common/shape.ts b/packages/pieces/community/bika/src/lib/common/shape.tsnew file mode 100644index 00000000000..0809f97a662--- /dev/null+++ b/packages/pieces/community/bika/src/lib/common/shape.ts@@ -0,0 +1,194 @@+import { bikaClient, BikaField, bikaHelpers, BikaRecord } from './client';+import { BIKA_READ_ONLY_FIELD_TYPES, BIKA_WRITE_FORMATS } from './constants';++const MAX_TEXT_LENGTH = 4_000;+const MAX_ARRAY_ITEMS = 100;++export const bikaShape = {+ requireId,+ optionalText,+ parseFieldsJson,+ agentRecord,+ agentRecords,+ agentField,+ cleanHumanFields,+ uploadFiles,+ MAX_TEXT_LENGTH,+};++function requireId({ value, label }: { value: unknown; label: string }): string {+ return bikaHelpers.seg({ value, label });+}++function optionalText(value: unknown): string | undefined {+ if (typeof value !== 'string') {+ return undefined;+ }+ const trimmed = value.trim();+ return trimmed.length > 0 ? trimmed : undefined;+}++function parseFieldsJson({ value, label }: { value: unknown; label: string }): Record<string, unknown> {+ const parsed = typeof value === 'string' ? parseJson({ text: value, label }) : value;+ if (!bikaHelpers.isRecord(parsed)) {+ throw new Error(`${label} must be a JSON object keyed by field name, for example {"Name": "Ada", "Score": 5}.`);+ }+ const entries = Object.entries(parsed).filter(([key, fieldValue]) => key.trim().length > 0 && fieldValue !== undefined);+ if (entries.length === 0) {+ throw new Error(`${label} is empty. Add at least one field value.`);+ }+ return Object.fromEntries(entries);+}++function agentRecord({ record, databaseId }: { record: BikaRecord; databaseId: string }) {+ const capped = capFields(record.fields);+ return {+ record: {+ id: record.id,+ database_id: databaseId,+ created_at: record.createdAt ?? null,+ updated_at: record.updatedAt ?? null,+ fields: capped.fields,+ },+ truncatedFields: capped.truncated,+ };+}++function agentRecords({ records, databaseId }: { records: BikaRecord[]; databaseId: string }) {+ const shaped = records.map((record) => agentRecord({ record, databaseId }));+ const truncated = new Set<string>();+ for (const item of shaped) {+ for (const name of item.truncatedFields) {+ truncated.add(name);+ }+ }+ return { records: shaped.map((item) => item.record), truncatedFields: [...truncated] };+}++function agentField(field: BikaField) {+ const writable = !BIKA_READ_ONLY_FIELD_TYPES.includes(field.type) && BIKA_WRITE_FORMATS[field.type] !== undefined;+ return {+ id: field.id,+ name: field.name,+ type: field.type,+ primary: field.primary,+ writable,+ value_format: writable ? BIKA_WRITE_FORMATS[field.type] : BIKA_READ_ONLY_FIELD_TYPES.includes(field.type) ? 'read-only' : 'not supported by these actions',+ options: field.options.map((option) => option.name),+ description: optionalText(field.description) ?? null,+ };+}++function cleanHumanFields(fields: unknown): Record<string, unknown> {+ if (!bikaHelpers.isRecord(fields)) {+ return {};+ }+ for (const [name, value] of Object.entries(fields)) {+ if (typeof value === 'number' && !Number.isFinite(value)) {+ throw new Error(`The value for "${name}" is not a valid number.`);+ }+ }+ return Object.fromEntries(+ Object.entries(fields).filter(([, value]) => {+ if (value === undefined || value === null) {+ return false;+ }+ if (typeof value === 'string') {+ return value.length > 0;+ }+ if (Array.isArray(value)) {+ return value.length > 0;+ }+ return true;+ }),+ );+}++async function uploadFiles({ token, spaceId, fields }: { token: string; spaceId: string; fields: Record<string, unknown> }): Promise<Record<string, unknown>> {+ const result: Record<string, unknown> = {};+ for (const [name, value] of Object.entries(fields)) {+ const files = fileList(value);+ if (files === null) {+ result[name] = value;+ continue;+ }+ const uploaded = [];+ for (const file of files) {+ const attachment = await bikaClient.uploadAttachment({ token, spaceId, file });+ uploaded.push({ id: attachment.id, name: file.filename });+ }+ result[name] = uploaded;+ }+ return result;+}++function fileList(value: unknown): { filename: string; data: Buffer }[] | null {+ if (isFile(value)) {+ return [{ filename: value.filename, data: value.data }];+ }+ if (Array.isArray(value) && value.length > 0 && value.every(isFile)) {+ return value.map((file) => ({ filename: file.filename, data: file.data }));+ }+ return null;+}++function isFile(value: unknown): value is { filename: string; data: Buffer } {+ return bikaHelpers.isRecord(value) && typeof value['filename'] === 'string' && Buffer.isBuffer(value['data']);+}++function capFields(fields: Record<string, unknown>): { fields: Record<string, unknown>; truncated: string[] } {+ const truncated: string[] = [];+ const capped = Object.fromEntries(+ Object.entries(fields).map(([name, value]) => {+ const result = capValue(value);+ if (result.truncated) {+ truncated.push(name);+ }+ return [name, result.value];+ }),+ );+ return { fields: capped, truncated };+}++function capValue(value: unknown): { value: unknown; truncated: boolean } {+ if (typeof value === 'string') {+ return value.length > MAX_TEXT_LENGTH ? { value: value.slice(0, MAX_TEXT_LENGTH), truncated: true } : { value, truncated: false };+ }+ if (Array.isArray(value)) {+ const results = value.slice(0, MAX_ARRAY_ITEMS).map((item) => (isAttachment(item) ? { value: shapeAttachment(item), truncated: false } : capValue(item)));+ return {+ value: results.map((result) => result.value),+ truncated: value.length > MAX_ARRAY_ITEMS || results.some((result) => result.truncated),+ };+ }+ if (bikaHelpers.isRecord(value)) {+ const results = Object.entries(value).map(([key, item]) => ({ key, result: capValue(item) }));+ return {+ value: Object.fromEntries(results.map(({ key, result }) => [key, result.value])),+ truncated: results.some(({ result }) => result.truncated),+ };+ }+ return { value, truncated: false };+}++function isAttachment(value: unknown): value is Record<string, unknown> {+ return bikaHelpers.isRecord(value) && typeof value['id'] === 'string' && typeof value['mimeType'] === 'string';+}++function shapeAttachment(value: Record<string, unknown>) {+ return {+ id: value['id'],+ name: typeof value['name'] === 'string' ? value['name'] : null,+ mime_type: value['mimeType'],+ size: typeof value['size'] === 'number' ? value['size'] : null,+ url: typeof value['url'] === 'string' ? value['url'] : null,+ };+}++function parseJson({ text, label }: { text: string; label: string }): unknown {+ try {+ return JSON.parse(text);+ } catch {+ throw new Error(`${label} is not valid JSON.`);+ }+}diff --git a/packages/pieces/community/bika/src/lib/output-schemas.ts b/packages/pieces/community/bika/src/lib/output-schemas.tsnew file mode 100644index 00000000000..384a135043f--- /dev/null+++ b/packages/pieces/community/bika/src/lib/output-schemas.ts@@ -0,0 +1,155 @@+import { OutputSchema } from '@activepieces/pieces-framework';++const envelopeFields: OutputSchema['fields'] = [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'code', label: 'Status Code', format: 'number' },+ { key: 'message', label: 'Message' },+];++const bikaRecordFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Record ID', description: 'The record ID (starts with "rec"). Use it to read, update or delete this record later.' },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+ { key: 'updatedAt', label: 'Updated At', format: 'datetime' },+ {+ key: 'fields',+ label: 'Fields',+ dynamicKey: true,+ description: 'The cell values keyed by field name. The names depend on the database.',+ },+];++const agentRecordFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Record ID' },+ { key: 'database_id', label: 'Database ID' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },+ {+ key: 'fields',+ label: 'Fields',+ dynamicKey: true,+ description: 'Cell values keyed by field name. Text longer than 4,000 characters is cut; attachments are {id, name, mime_type, size, url}.',+ },+];++const truncatedFieldsField: OutputSchema['fields'][number] = {+ key: 'truncated_fields',+ label: 'Truncated Fields',+ description: 'Names of fields whose text (over 4,000 characters) or list (over 100 items) was cut.',+};++export const bikaOutputSchemas = {+ humanCreatedRecord: {+ fields: [+ ...envelopeFields,+ {+ key: 'data',+ label: 'Data',+ children: [{ key: 'records', label: 'Created Records', labelKey: 'id', listItems: bikaRecordFields }],+ },+ ],+ },+ humanRecord: {+ fields: [...envelopeFields, { key: 'data', label: 'Record', children: bikaRecordFields }],+ },+ humanDeleted: {+ fields: [+ ...envelopeFields,+ {+ key: 'data',+ label: 'Data',+ children: [+ { key: 'id', label: 'Record ID' },+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ ],+ },+ ],+ },+ humanFind: {+ fields: [+ ...envelopeFields,+ {+ key: 'data',+ label: 'Data',+ children: [+ { key: 'records', label: 'Records', labelKey: 'id', listItems: bikaRecordFields },+ { key: 'hasMore', label: 'Has More', format: 'boolean' },+ { key: 'offset', label: 'Next Offset', description: 'Pass it as Offset to fetch the next records.' },+ ],+ },+ ],+ },+ spaces: {+ fields: [+ {+ key: 'spaces',+ label: 'Spaces',+ labelKey: 'name',+ listItems: [+ { key: 'id', label: 'Space ID' },+ { key: 'name', label: 'Name' },+ { key: 'plan', label: 'Plan' },+ { key: 'member_count', label: 'Members', format: 'number' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ ],+ },+ databases: {+ fields: [+ { key: 'space_id', label: 'Space ID' },+ {+ key: 'databases',+ label: 'Databases',+ labelKey: 'name',+ listItems: [+ { key: 'id', label: 'Database ID' },+ { key: 'name', label: 'Name' },+ { key: 'path', label: 'Folder Path' },+ { key: 'parent_id', label: 'Parent Folder ID' },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ { key: 'truncated', label: 'Truncated', format: 'boolean', description: 'True when the space has more than 200 databases and only the first 200 are listed.' },+ ],+ },+ fields: {+ fields: [+ { key: 'database_id', label: 'Database ID' },+ {+ key: 'fields',+ label: 'Fields',+ labelKey: 'name',+ listItems: [+ { key: 'id', label: 'Field ID' },+ { key: 'name', label: 'Name' },+ { key: 'type', label: 'Type' },+ { key: 'primary', label: 'Primary', format: 'boolean' },+ { key: 'writable', label: 'Writable', format: 'boolean' },+ { key: 'value_format', label: 'Value Format', description: 'How to write a value for this field.' },+ { key: 'options', label: 'Options', description: 'Option names for select fields.' },+ { key: 'description', label: 'Description' },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ ],+ },+ agentFind: {+ fields: [+ { key: 'records', label: 'Records', labelKey: 'id', listItems: agentRecordFields },+ { key: 'count', label: 'Count', format: 'number' },+ { key: 'has_more', label: 'Has More', format: 'boolean' },+ { key: 'next_offset', label: 'Next Offset', description: 'Pass it as Offset to get the next page; null when there are no more records.' },+ truncatedFieldsField,+ ],+ },+ agentRecord: {+ fields: [...agentRecordFields, truncatedFieldsField],+ },+ agentDeleted: {+ fields: [+ { key: 'id', label: 'Record ID' },+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ ],+ },+} satisfies Record<string, OutputSchema>;diff --git a/packages/pieces/community/bika/test/actions.test.ts b/packages/pieces/community/bika/test/actions.test.tsnew file mode 100644index 00000000000..9ca866b8857--- /dev/null+++ b/packages/pieces/community/bika/test/actions.test.ts@@ -0,0 +1,244 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { createRecordByIdAction } from '../src/lib/actions/ai/create-record-by-id';+import { deleteRecordByIdAction } from '../src/lib/actions/ai/delete-record-by-id';+import { findRecordsByIdAction } from '../src/lib/actions/ai/find-records-by-id';+import { getDatabaseFieldsByIdAction } from '../src/lib/actions/ai/get-database-fields-by-id';+import { getRecordByIdAction } from '../src/lib/actions/ai/get-record-by-id';+import { listDatabasesByIdAction } from '../src/lib/actions/ai/list-databases-by-id';+import { updateRecordByIdAction } from '../src/lib/actions/ai/update-record-by-id';+import { createRecordAction } from '../src/lib/actions/create-record';+import { deleteRecordAction } from '../src/lib/actions/delete-record';+import { findRecordAction } from '../src/lib/actions/find-record';+import { findRecordsAction } from '../src/lib/actions/find-records';+import { listSpacesAction } from '../src/lib/actions/list-spaces';+import { updateRecordAction } from '../src/lib/actions/update-record';+import { bikaHelpers } from '../src/lib/common/client';+import { context, ok, RECORDS_PATH, stubFetch } from './helpers';++afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++const record = { id: 'rec1', fields: { Name: 'Ada' }, createdAt: '2026-10-07T10:00:00.000Z', updatedAt: '2026-10-07T11:00:00.000Z' };+const file = { filename: 'photo.png', extension: 'png', data: Buffer.from('png'), base64: Buffer.from('png').toString('base64') };++describe('human actions', () => {+ test('create sends one request with typed values and no field re-fetch', async () => {+ const seen = stubFetch(() => ok({ records: [record] }));+ const result = await createRecordAction.run(+ context({ space_id: 'spc1', database_id: 'dat1', fields: { Name: 'Ada', Score: 5, Done: false, Empty: '', Tags: [], Sales: ['mem1'], Note: undefined } }),+ );+ expect(seen).toHaveLength(1);+ expect(seen[0].method).toBe('POST');+ expect(seen[0].path).toBe(RECORDS_PATH);+ expect(seen[0].json).toEqual({ fieldKey: 'name', records: [{ fields: { Name: 'Ada', Score: 5, Done: false, Sales: ['mem1'] } }] });+ expect(result).toEqual({ success: true, code: 200, message: 'SUCCESS', data: { records: [record] } });+ });++ test('create uploads files first and sends attachment ids', async () => {+ const seen = stubFetch((request) =>+ request.path.endsWith('/attachments') ? ok([{ id: 'att1', name: 'photo.png', mimeType: 'image/png', size: 3, path: 'p', bucket: 'b' }]) : ok({ records: [record] }),+ );+ await createRecordAction.run(context({ space_id: 'spc1', database_id: 'dat1', fields: { Name: 'Ada', Photo: file } }));+ expect(seen.map((request) => request.path)).toEqual(['/api/openapi/bika/v1/spaces/spc1/attachments', RECORDS_PATH]);+ expect(seen[1].json).toEqual({ fieldKey: 'name', records: [{ fields: { Name: 'Ada', Photo: [{ id: 'att1', name: 'photo.png' }] } }] });+ });++ test('create refuses an empty record and NaN numbers before any request', async () => {+ const seen = stubFetch(() => ok({}));+ await expect(createRecordAction.run(context({ space_id: 'spc1', database_id: 'dat1', fields: { Name: '' } }))).rejects.toThrow('at least one field');+ await expect(createRecordAction.run(context({ space_id: 'spc1', database_id: 'dat1', fields: { Score: Number.NaN } }))).rejects.toThrow('not a valid number');+ expect(seen).toHaveLength(0);+ });++ test('update sends PUT with only the filled fields', async () => {+ const seen = stubFetch(() => ok(record));+ const result = await updateRecordAction.run(context({ space_id: 'spc1', database_id: 'dat1', recordId: ' rec1 ', fields: { Name: 'Ada', Other: '' } }));+ expect(seen[0].method).toBe('PUT');+ expect(seen[0].path).toBe(`${RECORDS_PATH}/rec1`);+ expect(seen[0].json).toEqual({ fieldKey: 'name', fields: { Name: 'Ada' } });+ expect(result).toMatchObject({ success: true, data: record });+ });++ test('get and delete keep the Bika envelope', async () => {+ let seen = stubFetch(() => ok(record));+ expect(await findRecordAction.run(context({ space_id: 'spc1', database_id: 'dat1', recordId: 'rec1' }))).toMatchObject({ success: true, data: record });+ expect(seen[0].method).toBe('GET');+ seen = stubFetch(() => ok({ id: 'rec1', deleted: true }));+ expect(await deleteRecordAction.run(context({ space_id: 'spc1', database_id: 'dat1', recordId: 'rec1' }))).toMatchObject({ data: { id: 'rec1', deleted: true } });+ expect(seen[0].method).toBe('DELETE');+ });++ test('find follows the offset cursor up to Max Records', async () => {+ const seen = stubFetch((request) =>+ request.query.get('offset') === null+ ? ok({ records: [record, { ...record, id: 'rec2' }], hasMore: true, offset: 'cur1' })+ : ok({ records: [{ ...record, id: 'rec3' }], hasMore: true, offset: 'cur2' }),+ );+ const result = await findRecordsAction.run(context({ space_id: 'spc1', database_id: 'dat1', maxRecords: 3, pageSize: 2, filter: 'Name=="Ada"' }));+ expect(seen).toHaveLength(2);+ expect(seen[0].query.get('pageSize')).toBe('2');+ expect(seen[0].query.get('filter')).toBe('Name=="Ada"');+ expect(seen[1].query.get('offset')).toBe('cur1');+ expect(seen[1].query.get('pageSize')).toBe('1');+ expect(result.data.records.map((item) => item.id)).toEqual(['rec1', 'rec2', 'rec3']);+ expect(result.data).toMatchObject({ hasMore: true, offset: 'cur2' });+ });++ test('find stops after 20 requests on short pages and returns the cursor', async () => {+ vi.spyOn(bikaHelpers, 'wait').mockResolvedValue(undefined);+ const seen = stubFetch((_request, index) => ok({ records: [{ ...record, id: `rec${index}` }], hasMore: true, offset: `cur${index}` }));+ const result = await findRecordsAction.run(context({ space_id: 'spc1', database_id: 'dat1', maxRecords: 1000, pageSize: 50 }));+ expect(seen).toHaveLength(20);+ expect(result.data.records).toHaveLength(20);+ expect(result.data).toMatchObject({ hasMore: true, offset: 'cur19' });+ });++ test('find stops when Bika has no more records and defaults to 100', async () => {+ const seen = stubFetch(() => ok({ records: [record], hasMore: false }));+ const result = await findRecordsAction.run(context({ space_id: 'spc1', database_id: 'dat1' }));+ expect(seen).toHaveLength(1);+ expect(seen[0].query.get('pageSize')).toBe('100');+ expect(result.data).toEqual({ records: [record], hasMore: false, offset: null });+ });+});++describe('agent actions', () => {+ test('list spaces is flat', async () => {+ stubFetch(() => ok([{ id: 'spc1', name: 'Team', memberCount: 3, createdAt: '2026-01-01T00:00:00.000Z', subscription: { plan: 'FREE' } }]));+ expect(await listSpacesAction.run(context({}))).toEqual({+ spaces: [{ id: 'spc1', name: 'Team', plan: 'FREE', member_count: 3, created_at: '2026-01-01T00:00:00.000Z' }],+ count: 1,+ });+ });++ test('list databases keeps only databases', async () => {+ stubFetch(() =>+ ok([+ { id: 'rot1', name: 'ROOT', type: 'ROOT' },+ { id: 'dat1', name: 'CRM', type: 'DATABASE', parentId: 'nod1', path: '/ROOT/Sales' },+ ]),+ );+ expect(await listDatabasesByIdAction.run(context({ space_id: 'spc1' }))).toEqual({+ space_id: 'spc1',+ databases: [{ id: 'dat1', name: 'CRM', path: '/ROOT/Sales', parent_id: 'nod1' }],+ count: 1,+ truncated: false,+ });+ });++ test('get database fields says what is writable and how', async () => {+ stubFetch(() =>+ ok([+ { id: 'f1', name: 'Stage', type: 'SINGLE_SELECT', primary: false, property: { options: [{ id: 'o1', name: 'Open' }] } },+ { id: 'f2', name: 'Edited', type: 'MODIFIED_TIME', primary: false },+ { id: 'f3', name: 'Owner', type: 'MEMBER', property: {} },+ ]),+ );+ const result = await getDatabaseFieldsByIdAction.run(context({ space_id: 'spc1', database_id: 'dat1' }));+ expect(result.fields[0]).toMatchObject({ name: 'Stage', writable: true, options: ['Open'], value_format: 'string: one option name' });+ expect(result.fields[1]).toMatchObject({ name: 'Edited', writable: false, value_format: 'read-only' });+ expect(result.fields[2]).toMatchObject({ name: 'Owner', writable: true, value_format: 'array of member, team or role IDs' });+ });++ test('find records sends filter, fields, sort and limit, and caps long text', async () => {+ const long = 'x'.repeat(5000);+ const seen = stubFetch(() =>+ ok({+ records: [+ {+ id: 'rec1',+ fields: { Other: 'dropped', Notes: long, Files: [{ id: 'att1', name: 'a.png', size: 3, mimeType: 'image/png', url: 'https://s/a.png', thumbnailUrl: null }] },+ createdAt: '2026-10-07T10:00:00.000Z',+ },+ ],+ hasMore: true,+ offset: 'next',+ }),+ );+ const result = await findRecordsByIdAction.run(+ context({ space_id: 'spc1', database_id: 'dat1', filter: '{Stage}=="Open"', fields: ['Notes', 'Files'], sort_field: 'Notes', sort_order: 'desc', limit: 5 }),+ );+ expect(seen[0].query.get('pageSize')).toBe('5');+ expect([...seen[0].query.keys()].some((key) => key.startsWith('fields'))).toBe(false);+ expect(seen[0].query.get('sort[0][field]')).toBe('Notes');+ expect(seen[0].query.get('sort[0][order]')).toBe('desc');+ expect(seen[0].query.get('filter')).toBe('{Stage}=="Open"');+ expect(result).toMatchObject({ count: 1, has_more: true, next_offset: null, truncated_fields: ['Notes'] });+ expect(String(result.records[0].fields['Notes'])).toHaveLength(4000);+ expect(Object.keys(result.records[0].fields)).toEqual(['Notes', 'Files']);+ expect(result.records[0].fields['Files']).toEqual([{ id: 'att1', name: 'a.png', mime_type: 'image/png', size: 3, url: 'https://s/a.png' }]);+ });++ test('find records caps nested lists and objects and reports the field', async () => {+ const long = 'x'.repeat(5000);+ stubFetch(() =>+ ok({+ records: [+ {+ id: 'rec1',+ fields: {+ Nested: [[long]],+ Meta: { note: long, tags: Array.from({ length: 150 }, (_item, index) => `t${index}`) },+ Small: { note: 'ok', list: [['a']] },+ },+ },+ ],+ hasMore: false,+ }),+ );+ const result = await findRecordsByIdAction.run(context({ space_id: 'spc1', database_id: 'dat1' }));+ expect(result.truncated_fields).toEqual(['Nested', 'Meta']);+ expect(result.records[0].fields['Nested']).toEqual([['x'.repeat(4000)]]);+ expect(result.records[0].fields['Meta']).toEqual({ note: 'x'.repeat(4000), tags: Array.from({ length: 100 }, (_item, index) => `t${index}`) });+ expect(result.records[0].fields['Small']).toEqual({ note: 'ok', list: [['a']] });+ });++ test('find records validates limit and sort order before calling Bika', async () => {+ const seen = stubFetch(() => ok({ records: [], hasMore: false }));+ await expect(findRecordsByIdAction.run(context({ space_id: 'spc1', database_id: 'dat1', limit: 500 }))).rejects.toThrow('from 1 to 100');+ await expect(findRecordsByIdAction.run(context({ space_id: 'spc1', database_id: 'dat1', sort_order: 'up' }))).rejects.toThrow('asc');+ await expect(findRecordsByIdAction.run(context({ space_id: 'spc1', database_id: 'dat1', sort_field: 'Name', offset: 'abc' }))).rejects.toThrow('cannot page through sorted');+ expect(seen).toHaveLength(0);+ });++ test('unsorted find returns the cursor for the next page', async () => {+ const seen = stubFetch(() => ok({ records: [record], hasMore: true, offset: 'cur9' }));+ const result = await findRecordsByIdAction.run(context({ space_id: 'spc1', database_id: 'dat1', offset: 'cur8' }));+ expect(seen[0].query.get('offset')).toBe('cur8');+ expect(seen[0].query.get('pageSize')).toBe('20');+ expect(result).toMatchObject({ has_more: true, next_offset: 'cur9' });+ });++ test('get, create, update and delete return flat records', async () => {+ let seen = stubFetch(() => ok(record));+ expect(await getRecordByIdAction.run(context({ space_id: 'spc1', database_id: 'dat1', record_id: 'rec1' }))).toEqual({+ id: 'rec1',+ database_id: 'dat1',+ created_at: record.createdAt,+ updated_at: record.updatedAt,+ fields: { Name: 'Ada' },+ truncated_fields: [],+ });++ seen = stubFetch(() => ok({ records: [record] }));+ await createRecordByIdAction.run(context({ space_id: 'spc1', database_id: 'dat1', fields: '{"Name": "Ada", "Score": 5}' }));+ expect(seen[0].json).toEqual({ fieldKey: 'name', records: [{ fields: { Name: 'Ada', Score: 5 } }] });++ seen = stubFetch(() => ok(record));+ await updateRecordByIdAction.run(context({ space_id: 'spc1', database_id: 'dat1', record_id: 'rec1', fields: { Notes: null } }));+ expect(seen[0].json).toEqual({ fieldKey: 'name', fields: { Notes: null } });++ stubFetch(() => ok({ id: 'rec1', deleted: true }));+ expect(await deleteRecordByIdAction.run(context({ space_id: 'spc1', database_id: 'dat1', record_id: 'rec1' }))).toEqual({ id: 'rec1', deleted: true });+ });++ test('create refuses non-object or empty fields', async () => {+ const seen = stubFetch(() => ok({}));+ await expect(createRecordByIdAction.run(context({ space_id: 'spc1', database_id: 'dat1', fields: '[1]' }))).rejects.toThrow('JSON object');+ await expect(createRecordByIdAction.run(context({ space_id: 'spc1', database_id: 'dat1', fields: {} }))).rejects.toThrow('empty');+ await expect(createRecordByIdAction.run(context({ space_id: 'spc1', database_id: 'dat1', fields: '{bad' }))).rejects.toThrow('not valid JSON');+ expect(seen).toHaveLength(0);+ });+});diff --git a/packages/pieces/community/bika/test/auth.test.ts b/packages/pieces/community/bika/test/auth.test.tsnew file mode 100644index 00000000000..6827a6fe9b8--- /dev/null+++ b/packages/pieces/community/bika/test/auth.test.ts@@ -0,0 +1,34 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { BikaAuth } from '../src/lib/auth';+import { ok, stubFetch } from './helpers';++afterEach(() => {+ vi.unstubAllGlobals();+});++const validate = (token: string) => {+ if (!BikaAuth.validate) {+ throw new Error('validate missing');+ }+ return BikaAuth.validate({ auth: { token }, server: { apiUrl: '', publicUrl: '', token: '' } });+};++describe('auth validate', () => {+ test('accepts a working token', async () => {+ const seen = stubFetch(() => ok([]));+ expect(await validate(' tok ')).toEqual({ valid: true });+ expect(seen[0].url).toBe('https://bika.ai/api/openapi/bika/v1/spaces');+ });++ test('says invalid token only on 401 or 403', async () => {+ stubFetch(() => ({ status: 401, body: { success: false, code: 401, message: 'Unauthorized' } }));+ expect(await validate('bad')).toMatchObject({ valid: false, error: expect.stringContaining('Invalid token') });+ });++ test('passes other failures through instead of blaming the token', async () => {+ stubFetch(() => ({ status: 500, body: { success: false, code: 500, message: 'Server busy' } }));+ const result = await validate('tok');+ expect(result).toMatchObject({ valid: false, error: expect.stringContaining('Server busy') });+ expect(JSON.stringify(result)).not.toContain('Invalid token');+ });+});diff --git a/packages/pieces/community/bika/test/client.test.ts b/packages/pieces/community/bika/test/client.test.tsnew file mode 100644index 00000000000..ca6f95aa60b--- /dev/null+++ b/packages/pieces/community/bika/test/client.test.ts@@ -0,0 +1,95 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { BikaApiError, bikaClient } from '../src/lib/common/client';+import { ok, RECORDS_PATH, stubFetch, TOKEN } from './helpers';++afterEach(() => {+ vi.unstubAllGlobals();+ vi.useRealTimers();+});++describe('bika client', () => {+ test('sends a trimmed bearer token to the fixed Bika host', async () => {+ const seen = stubFetch(() => ok({ id: 'rec1', fields: {} }));+ await bikaClient.getRecord({ token: ` ${TOKEN} `, spaceId: 'spc1', databaseId: 'dat1', recordId: 'rec1' });+ expect(seen[0].url).toBe(`https://bika.ai${RECORDS_PATH}/rec1`);+ expect(seen[0].headers.get('authorization')).toBe(`Bearer ${TOKEN}`);+ });++ test('rejects IDs that would change the path before any request', async () => {+ const seen = stubFetch(() => ok({}));+ await expect(bikaClient.getRecord({ token: TOKEN, spaceId: 'spc1', databaseId: '../x', recordId: 'rec1' })).rejects.toThrow('not a valid Bika ID');+ await expect(bikaClient.getRecord({ token: TOKEN, spaceId: 'spc1', databaseId: 'dat1', recordId: '' })).rejects.toThrow('Record ID is required');+ expect(seen).toHaveLength(0);+ });++ test('maps HTTP errors to readable messages and keeps the body as responseBody', async () => {+ stubFetch(() => ({ status: 401, body: { success: false, code: 401, message: 'Unauthorized', data: {} } }));+ const error = await bikaClient.listSpaces({ token: TOKEN }).catch((caught: unknown) => caught);+ expect(error).toBeInstanceOf(BikaApiError);+ expect(error).toMatchObject({ status: 401, message: expect.stringContaining('token is invalid') });+ expect(Object.keys(error instanceof Error ? error : {})).not.toContain('body');++ stubFetch(() => ({ status: 404, body: { success: false, code: 404, message: 'Record not found' } }));+ await expect(bikaClient.getRecord({ token: TOKEN, spaceId: 'spc1', databaseId: 'dat1', recordId: 'rec9' })).rejects.toThrow(/not found.*Record not found/);+ });++ test('explains a not-found record that Bika reports as HTTP 500', async () => {+ stubFetch(() => ({ status: 500, body: { success: false, code: 500, message: 'Record not found: rec9', data: {} } }));+ await expect(bikaClient.getRecord({ token: TOKEN, spaceId: 'spc1', databaseId: 'dat1', recordId: 'rec9' })).rejects.toThrow(+ 'Bika could not get the record (HTTP 500): not found. Check the space, database and record IDs. Record not found: rec9',+ );+ });++ test('treats a 200 with success false as a failure', async () => {+ stubFetch(() => ({ body: { success: false, code: 500, message: 'Field "Nope" does not exist' } }));+ await expect(bikaClient.createRecord({ token: TOKEN, spaceId: 'spc1', databaseId: 'dat1', fields: { Nope: 1 } })).rejects.toThrow('Field "Nope" does not exist');+ });++ test('retries a 429 rate limit once', async () => {+ const seen = stubFetch((_request, index) => (index === 0 ? { status: 429, body: { success: false, code: 429, message: 'Too many requests' } } : ok([])));+ await bikaClient.listSpaces({ token: TOKEN });+ expect(seen).toHaveLength(2);+ });++ test('does not retry when the monthly quota is used up and says so', async () => {+ const seen = stubFetch(() => ({ status: 429, body: { success: false, code: 429, message: 'API_REQUEST quota exceeded' } }));+ await expect(bikaClient.listSpaces({ token: TOKEN })).rejects.toThrow('monthly API request quota');+ expect(seen).toHaveLength(1);+ });++ test('lists only DATABASE nodes from the flat node list', async () => {+ stubFetch(() =>+ ok([+ { id: 'rot1', name: 'ROOT', type: 'ROOT', parentId: null },+ { id: 'fld1', name: 'CRM', type: 'FOLDER', path: '/ROOT' },+ { id: 'dat1', name: 'CRM Database', type: 'DATABASE', parentId: 'fld1', path: '/ROOT/CRM' },+ { id: 'fom1', name: 'Form', type: 'FORM', path: '/ROOT/CRM' },+ ]),+ );+ const databases = await bikaClient.listDatabases({ token: TOKEN, spaceId: 'spc1' });+ expect(databases).toEqual([{ id: 'dat1', name: 'CRM Database', type: 'DATABASE', parentId: 'fld1', path: '/ROOT/CRM' }]);+ });++ test('reads the attachment id from an object or nested response, and shows the body when missing', async () => {+ stubFetch(() => ok({ attachment: { id: 'att2', name: 'b.txt' } }));+ expect(await bikaClient.uploadAttachment({ token: TOKEN, spaceId: 'spc1', file: { filename: 'b.txt', data: Buffer.from('b') } })).toMatchObject({ id: 'att2' });+ stubFetch(() => ok({ id: 'att3' }));+ expect(await bikaClient.uploadAttachment({ token: TOKEN, spaceId: 'spc1', file: { filename: 'c.txt', data: Buffer.from('c') } })).toMatchObject({ id: 'att3', name: 'c.txt' });+ stubFetch(() => ok({ path: 'x' }));+ await expect(bikaClient.uploadAttachment({ token: TOKEN, spaceId: 'spc1', file: { filename: 'd.txt', data: Buffer.from('d') } })).rejects.toThrow('returned no attachment ID: {"path":"x"}');+ });++ test('uploads a file as multipart and returns the attachment id', async () => {+ const seen = stubFetch(() => ok([{ id: 'att1', name: 'a.txt', path: 'p', bucket: 'b', mimeType: 'text/plain', size: 3 }]));+ const uploaded = await bikaClient.uploadAttachment({ token: TOKEN, spaceId: 'spc1', file: { filename: 'a.txt', data: Buffer.from('abc') } });+ expect(seen[0].path).toBe('/api/openapi/bika/v1/spaces/spc1/attachments');+ expect(seen[0].method).toBe('POST');+ const contentType = seen[0].headers.get('content-type') ?? '';+ expect(contentType).toMatch(/^multipart\/form-data; boundary=----ActivepiecesBika[0-9a-f]+$/);+ const boundary = contentType.split('boundary=')[1];+ expect(seen[0].bytes).toBe(+ `--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="a.txt"\r\nContent-Type: text/plain\r\n\r\nabc\r\n--${boundary}--\r\n`,+ );+ expect(uploaded).toMatchObject({ id: 'att1', name: 'a.txt' });+ });+});diff --git a/packages/pieces/community/bika/test/helpers.ts b/packages/pieces/community/bika/test/helpers.tsnew file mode 100644index 00000000000..b7ba38d67d3--- /dev/null+++ b/packages/pieces/community/bika/test/helpers.ts@@ -0,0 +1,60 @@+import { vi } from 'vitest';++export const TOKEN = 'bkt_test_token';++export function connection() {+ return { type: 'CUSTOM_AUTH', props: { token: ` ${TOKEN} ` } };+}++export function stubFetch(respond: (request: SeenRequest, index: number) => FakeReply): SeenRequest[] {+ const seen: SeenRequest[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = input instanceof Request ? input.url : String(input);+ const headers = new Headers(init?.headers);+ const parsed = new URL(url);+ const raw = init?.body;+ const text = typeof raw === 'string' ? raw : '';+ const bytes = Buffer.isBuffer(raw) ? raw.toString('latin1') : '';+ const request: SeenRequest = {+ url,+ method: (init?.method ?? 'GET').toUpperCase(),+ path: parsed.pathname,+ query: parsed.searchParams,+ headers,+ json: text ? JSON.parse(text) : null,+ bytes,+ };+ seen.push(request);+ const reply = respond(request, seen.length - 1);+ return new Response(reply.body === undefined ? '' : JSON.stringify(reply.body), {+ status: reply.status ?? 200,+ headers: { 'content-type': 'application/json' },+ });+ }),+ );+ return seen;+}++export function ok(data: unknown) {+ return { body: { success: true, code: 200, message: 'SUCCESS', data } };+}++export function context(propsValue: Record<string, unknown>) {+ return { auth: connection(), propsValue, store: {}, files: {}, server: { apiUrl: '', publicUrl: '', token: '' } };+}++export const RECORDS_PATH = '/api/openapi/bika/v2/spaces/spc1/resources/databases/dat1/records';++export type SeenRequest = {+ url: string;+ method: string;+ path: string;+ query: URLSearchParams;+ headers: Headers;+ json: unknown;+ bytes: string;+};++export type FakeReply = { status?: number; body?: unknown };diff --git a/packages/pieces/community/bika/test/metadata.test.ts b/packages/pieces/community/bika/test/metadata.test.tsnew file mode 100644index 00000000000..9ffb0f49c4c--- /dev/null+++ b/packages/pieces/community/bika/test/metadata.test.ts@@ -0,0 +1,48 @@+import { describe, expect, test } from 'vitest';+import { bika } from '../src';++const actions = Object.values(bika.actions());+const nonCustom = actions.filter((action) => action.name !== 'custom_api_call');++describe('piece metadata', () => {+ test('13 actions plus custom API call, no triggers', () => {+ expect(nonCustom).toHaveLength(13);+ expect(actions).toHaveLength(14);+ expect(Object.keys(bika.triggers())).toHaveLength(0);+ });++ test('legacy action names are kept and are human-only', () => {+ for (const name of ['bika_create_record', 'bika_update_record', 'bika_delete_record', 'bika_find_record', 'bika_find_records']) {+ const action = nonCustom.find((item) => item.name === name);+ expect(action?.audience, name).toBe('human');+ }+ });++ test('audience split is 5 human, 7 ai, 1 both', () => {+ const count = (audience: string) => nonCustom.filter((action) => action.audience === audience).length;+ expect([count('human'), count('ai'), count('both')]).toEqual([5, 7, 1]);+ });++ test.each(nonCustom.map((action) => [action.name, action]))('%s declares classification, aiMetadata and outputSchema', (_name, action) => {+ expect(['READ', 'SEARCH', 'WRITE', 'DESTRUCTIVE']).toContain(action.classification);+ expect(action.aiMetadata?.description?.length ?? 0).toBeGreaterThan(60);+ expect(typeof action.aiMetadata?.idempotent).toBe('boolean');+ expect(action.outputSchema?.fields.length).toBeGreaterThan(0);+ });++ test('actions visible to agents use no dropdowns', () => {+ for (const action of nonCustom.filter((item) => item.audience !== 'human')) {+ const types = Object.values(action.props).map((prop: unknown) => (prop !== null && typeof prop === 'object' ? Reflect.get(prop, 'type') : undefined));+ expect(types, action.name).not.toContain('DROPDOWN');+ expect(types, action.name).not.toContain('DYNAMIC');+ }+ });++ test('deletes are destructive and not idempotent', () => {+ const destructive = nonCustom.filter((action) => action.classification === 'DESTRUCTIVE');+ expect(destructive.map((action) => action.name).sort()).toEqual(['bika_delete_record', 'delete_record_by_id']);+ for (const action of destructive) {+ expect(action.aiMetadata?.idempotent).toBe(false);+ }+ });+});diff --git a/packages/pieces/community/bika/test/props.test.ts b/packages/pieces/community/bika/test/props.test.tsnew file mode 100644index 00000000000..650ea7197e3--- /dev/null+++ b/packages/pieces/community/bika/test/props.test.ts@@ -0,0 +1,63 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { bikaProps } from '../src/lib/common/props';+import { connection, ok, stubFetch } from './helpers';++afterEach(() => {+ vi.unstubAllGlobals();+});++const ctx = { server: { apiUrl: '', publicUrl: '', token: '' }, project: { id: 'p', externalId: async () => undefined }, flows: {} };++describe('dropdowns', () => {+ test('database dropdown lists only databases with their folder', async () => {+ stubFetch(() =>+ ok([+ { id: 'rot1', name: 'ROOT', type: 'ROOT' },+ { id: 'dat1', name: 'CRM Database', type: 'DATABASE', path: '/ROOT/A Simple CRM' },+ { id: 'dat2', name: 'Top', type: 'DATABASE', path: '/ROOT' },+ ]),+ );+ const result = await bikaProps.database().options({ auth: connection(), space_id: 'spc1' }, ctx);+ expect(result).toEqual({+ disabled: false,+ options: [+ { label: 'CRM Database (A Simple CRM)', value: 'dat1' },+ { label: 'Top', value: 'dat2' },+ ],+ });+ });++ test('dropdowns show a reason instead of throwing', async () => {+ stubFetch(() => ({ status: 429, body: { success: false, code: 429, message: 'API_REQUEST quota exceeded' } }));+ const spaces = await bikaProps.space().options({ auth: connection() }, ctx);+ expect(spaces).toMatchObject({ disabled: true, placeholder: expect.stringContaining('quota') });+ expect(await bikaProps.database().options({ auth: connection(), space_id: undefined }, ctx)).toMatchObject({ disabled: true, placeholder: 'Select a space first.' });+ });++ test('fields offer an input per writable type, with arrays for member and link', async () => {+ stubFetch(() =>+ ok([+ { id: 'f1', name: 'Name', type: 'LONG_TEXT' },+ { id: 'f2', name: 'Sales', type: 'MEMBER', property: {} },+ { id: 'f3', name: 'Stage', type: 'SINGLE_SELECT', property: { options: [{ id: 'o1', name: 'Open' }] } },+ { id: 'f4', name: 'Edited', type: 'MODIFIED_TIME' },+ { id: 'f5', name: 'Count', type: 'AUTO_NUMBER' },+ { id: 'f6', name: 'Period', type: 'DATERANGE' },+ { id: 'f7', name: 'Visits', type: 'ONE_WAY_LINK' },+ { id: 'f8', name: 'Files', type: 'ATTACHMENT' },+ { id: 'f9', name: 'Score', type: 'RATING' },+ ]),+ );+ const props = await bikaProps.fields({ description: 'x' }).props({ auth: connection(), space_id: 'spc1', database_id: 'dat1' }, ctx);+ const types = Object.fromEntries(Object.entries(props).map(([name, prop]) => [name, Reflect.get(prop, 'type')]));+ expect(types).toEqual({+ Name: 'LONG_TEXT',+ Sales: 'ARRAY',+ Stage: 'STATIC_DROPDOWN',+ Period: 'SHORT_TEXT',+ Visits: 'ARRAY',+ Files: 'FILE',+ Score: 'NUMBER',+ });+ });+});diff --git a/packages/pieces/community/bika/vitest.config.ts b/packages/pieces/community/bika/vitest.config.tsnew file mode 100644index 00000000000..79c97261904--- /dev/null+++ b/packages/pieces/community/bika/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'),+ },+ },+})