Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
80e675f430 | ||
|
|
29091ca369 | ||
|
|
5e71b7cb9c | ||
|
|
a641fbe804 | ||
|
|
f536c4d8b3 |
@@ -11,7 +11,7 @@ permissions:
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event_name == 'merge_group' && github.event.merge_group.base_ref || github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name != 'merge_group' }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
e2e-test:
|
||||
|
||||
@@ -206,7 +206,6 @@
|
||||
"packages/twenty-e2e-testing",
|
||||
"packages/twenty-shared",
|
||||
"packages/twenty-sdk",
|
||||
"packages/twenty-standard-application",
|
||||
"packages/twenty-apps",
|
||||
"packages/twenty-cli",
|
||||
"packages/create-twenty-app",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
## Base documentation
|
||||
|
||||
- Documentation: https://docs.twenty.com/developers/extend/capabilities/apps
|
||||
- Rich app example: https://github.com/twentyhq/twenty/tree/main/packages/twenty-sdk/src/app-seeds/rich-app
|
||||
- Rich app example: https://github.com/twentyhq/twenty/tree/main/packages/twenty-sdk/src/cli/__tests__/apps/rich-app
|
||||
|
||||
## UUID requirement
|
||||
|
||||
|
||||
@@ -386,12 +386,6 @@ describe('copyBaseApplicationProject', () => {
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
expect(
|
||||
await fs.pathExists(
|
||||
join(testAppDirectory, '.github', 'workflows', 'ci.yml'),
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
// Install functions should always exist
|
||||
expect(
|
||||
await fs.pathExists(
|
||||
@@ -470,12 +464,6 @@ describe('copyBaseApplicationProject', () => {
|
||||
join(srcPath, '__tests__', 'app-install.integration-test.ts'),
|
||||
),
|
||||
).toBe(false);
|
||||
|
||||
expect(
|
||||
await fs.pathExists(
|
||||
join(testAppDirectory, '.github', 'workflows', 'ci.yml'),
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -110,37 +110,6 @@ describe('scaffoldIntegrationTest', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('github workflow', () => {
|
||||
it('should create .github/workflows/ci.yml with correct structure', async () => {
|
||||
await scaffoldIntegrationTest({
|
||||
appDirectory: testAppDirectory,
|
||||
sourceFolderPath,
|
||||
});
|
||||
|
||||
const workflowPath = join(
|
||||
testAppDirectory,
|
||||
'.github',
|
||||
'workflows',
|
||||
'ci.yml',
|
||||
);
|
||||
|
||||
expect(await fs.pathExists(workflowPath)).toBe(true);
|
||||
|
||||
const content = await fs.readFile(workflowPath, 'utf8');
|
||||
|
||||
expect(content).toContain('name: CI');
|
||||
expect(content).toContain('TWENTY_VERSION: latest');
|
||||
expect(content).toContain('twenty-version: ${{ env.TWENTY_VERSION }}');
|
||||
expect(content).toContain('actions/checkout@v4');
|
||||
expect(content).toContain('spawn-twenty-docker-image@main');
|
||||
expect(content).toContain('actions/setup-node@v4');
|
||||
expect(content).toContain('yarn install --immutable');
|
||||
expect(content).toContain('yarn test');
|
||||
expect(content).toContain('TWENTY_API_URL');
|
||||
expect(content).toContain('TWENTY_TEST_API_KEY');
|
||||
});
|
||||
});
|
||||
|
||||
describe('tsconfig.spec.json', () => {
|
||||
it('should create tsconfig.spec.json extending the base tsconfig', async () => {
|
||||
await scaffoldIntegrationTest({
|
||||
|
||||
@@ -25,7 +25,6 @@ export const scaffoldIntegrationTest = async ({
|
||||
|
||||
await createVitestConfig(appDirectory);
|
||||
await createTsconfigSpec(appDirectory);
|
||||
await createGithubWorkflow(appDirectory);
|
||||
};
|
||||
|
||||
const createVitestConfig = async (appDirectory: string) => {
|
||||
@@ -212,56 +211,3 @@ describe('App installation', () => {
|
||||
await fs.ensureDir(join(appDirectory, fileFolder ?? ''));
|
||||
await fs.writeFile(join(appDirectory, fileFolder ?? '', fileName), content);
|
||||
};
|
||||
|
||||
const DEFAULT_TWENTY_VERSION = 'latest';
|
||||
|
||||
const createGithubWorkflow = async (appDirectory: string) => {
|
||||
const content = `name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request: {}
|
||||
|
||||
env:
|
||||
TWENTY_VERSION: ${DEFAULT_TWENTY_VERSION}
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Spawn Twenty instance
|
||||
id: twenty
|
||||
uses: twentyhq/twenty/.github/actions/spawn-twenty-docker-image@main
|
||||
with:
|
||||
twenty-version: \${{ env.TWENTY_VERSION }}
|
||||
github-token: \${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Enable Corepack
|
||||
run: corepack enable
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: '.nvmrc'
|
||||
cache: 'yarn'
|
||||
|
||||
- name: Install dependencies
|
||||
run: yarn install --immutable
|
||||
|
||||
- name: Run integration tests
|
||||
run: yarn test
|
||||
env:
|
||||
TWENTY_API_URL: \${{ steps.twenty.outputs.server-url }}
|
||||
TWENTY_TEST_API_KEY: \${{ steps.twenty.outputs.access-token }}
|
||||
`;
|
||||
|
||||
const workflowDir = join(appDirectory, '.github', 'workflows');
|
||||
|
||||
await fs.ensureDir(workflowDir);
|
||||
await fs.writeFile(join(workflowDir, 'ci.yml'), content);
|
||||
};
|
||||
|
||||
@@ -1,3 +1,2 @@
|
||||
generated
|
||||
.twenty
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
## Base documentation
|
||||
|
||||
- Documentation: https://docs.twenty.com/developers/extend/capabilities/apps
|
||||
- Rich app example: https://github.com/twentyhq/twenty/tree/main/packages/twenty-sdk/src/app-seeds/rich-app
|
||||
- Rich app example: https://github.com/twentyhq/twenty/tree/main/packages/twenty-sdk/src/cli/__tests__/apps/rich-app
|
||||
|
||||
## UUID requirement
|
||||
- All generated UUIDs must be valid UUID v4.
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
import { defineLogicFunction, RoutePayload } from "twenty-sdk";
|
||||
import { MetadataApiClient } from 'twenty-sdk/clients';
|
||||
import { MetadataApiClient } from 'twenty-sdk/generated';
|
||||
|
||||
export const OAUTH_TOKEN_PAIRS_PATH = '/oauth/token-pairs';
|
||||
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ import {
|
||||
type DatabaseEventPayload,
|
||||
type ObjectRecordUpdateEvent,
|
||||
} from 'twenty-sdk';
|
||||
import { CoreApiClient } from 'twenty-sdk/clients';
|
||||
import { CoreApiClient } from 'twenty-sdk/generated';
|
||||
|
||||
type CompanyRecord = {
|
||||
id: string;
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
## Base documentation
|
||||
|
||||
- Documentation: https://docs.twenty.com/developers/extend/capabilities/apps
|
||||
- Rich app example: https://github.com/twentyhq/twenty/tree/main/packages/twenty-sdk/src/app-seeds/rich-app
|
||||
- Rich app example: https://github.com/twentyhq/twenty/tree/main/packages/twenty-sdk/src/cli/__tests__/apps/rich-app
|
||||
|
||||
## UUID requirement
|
||||
|
||||
- All generated UUIDs must be valid UUID v4.
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
## Base documentation
|
||||
|
||||
- Documentation: https://docs.twenty.com/developers/extend/capabilities/apps
|
||||
- Rich app example: https://github.com/twentyhq/twenty/tree/main/packages/twenty-sdk/src/app-seeds/rich-app
|
||||
- Rich app example: https://github.com/twentyhq/twenty/tree/main/packages/twenty-sdk/src/cli/__tests__/apps/rich-app
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ import {
|
||||
} from 'src/constants/seed-call-recordings-universal-identifiers';
|
||||
import { MOCK_CALL_RECORDINGS } from 'src/data/mock-call-recordings';
|
||||
import { defineFrontComponent } from 'twenty-sdk';
|
||||
import { CoreApiClient } from 'twenty-sdk/clients';
|
||||
import { CoreApiClient } from 'twenty-sdk/generated';
|
||||
|
||||
type SeedStatus = 'seeding' | 'done' | 'error';
|
||||
|
||||
|
||||
+2
-4
@@ -6,7 +6,7 @@ import {
|
||||
SUMMARIZE_PERSON_RECORDINGS_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER,
|
||||
} from 'src/constants/summarize-person-recordings-universal-identifiers';
|
||||
import { defineFrontComponent, useRecordId } from 'twenty-sdk';
|
||||
import { CoreApiClient } from 'twenty-sdk/clients';
|
||||
import { CoreApiClient } from 'twenty-sdk/generated';
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
|
||||
const SUMMARIZATION_SYSTEM_PROMPT = [
|
||||
@@ -40,9 +40,7 @@ const summarizeAllRecordings = async (
|
||||
const summariesText = recordings
|
||||
.map(
|
||||
(recording, index) =>
|
||||
`### ${index + 1}. ${recording.name ?? 'Untitled'} (${
|
||||
recording.createdAt
|
||||
})\n${recording.summary?.markdown ?? 'No summary available'}`,
|
||||
`### ${index + 1}. ${recording.name ?? 'Untitled'} (${recording.createdAt})\n${recording.summary?.markdown ?? 'No summary available'}`,
|
||||
)
|
||||
.join('\n\n---\n\n');
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useRecordId } from 'twenty-sdk';
|
||||
import { CoreApiClient } from 'twenty-sdk/clients';
|
||||
import { CoreApiClient } from 'twenty-sdk/generated';
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
|
||||
type CallRecording = {
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
} from 'src/utils/match-participants';
|
||||
import { summarizeTranscript } from 'src/utils/summarize-transcript';
|
||||
import { defineLogicFunction } from 'twenty-sdk';
|
||||
import { CoreApiClient, MetadataApiClient } from 'twenty-sdk/clients';
|
||||
import { CoreApiClient, MetadataApiClient } from 'twenty-sdk/generated';
|
||||
import { z } from 'zod';
|
||||
|
||||
interface LocalTranscriptWord {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { CoreApiClient } from 'twenty-sdk/clients';
|
||||
import { CoreApiClient } from 'twenty-sdk/generated';
|
||||
|
||||
export interface Participant {
|
||||
id: string;
|
||||
|
||||
+2
-8
@@ -5,14 +5,8 @@ import {
|
||||
type ObjectRecordUpdateEvent,
|
||||
} from 'twenty-sdk';
|
||||
import { SELF_HOSTING_USER_NAME_SINGULAR } from 'src/objects/selfHostingUser.object';
|
||||
import { CoreApiClient } from 'twenty-sdk/clients';
|
||||
|
||||
type SelfHostingUser = {
|
||||
id: string;
|
||||
email?: { primaryEmail?: string };
|
||||
name?: { firstName?: string; lastName?: string };
|
||||
personId?: string;
|
||||
};
|
||||
import { type SelfHostingUser } from 'twenty-sdk/generated/core';
|
||||
import { CoreApiClient } from 'twenty-sdk/generated';
|
||||
|
||||
const handler = async (
|
||||
params: DatabaseEventPayload<
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
import { defineLogicFunction, type RoutePayload } from 'twenty-sdk';
|
||||
import { CoreApiClient } from 'twenty-sdk/clients';
|
||||
import { CoreApiClient } from 'twenty-sdk/generated';
|
||||
import { type TelemetryEvent } from 'src/logic-functions/types/telemetry-event.type';
|
||||
|
||||
export const main = async (
|
||||
|
||||
@@ -15,7 +15,6 @@ COPY ./packages/twenty-ui/package.json /app/packages/twenty-ui/
|
||||
COPY ./packages/twenty-shared/package.json /app/packages/twenty-shared/
|
||||
COPY ./packages/twenty-front/package.json /app/packages/twenty-front/
|
||||
COPY ./packages/twenty-sdk/package.json /app/packages/twenty-sdk/
|
||||
COPY ./packages/twenty-standard-application/package.json /app/packages/twenty-standard-application/
|
||||
|
||||
# Install all dependencies
|
||||
RUN yarn && yarn cache clean && npx nx reset
|
||||
@@ -27,15 +26,11 @@ FROM common-deps AS twenty-server-build
|
||||
# Copy sourcecode after installing dependences to accelerate subsequents builds
|
||||
COPY ./packages/twenty-emails /app/packages/twenty-emails
|
||||
COPY ./packages/twenty-shared /app/packages/twenty-shared
|
||||
COPY ./packages/twenty-ui /app/packages/twenty-ui
|
||||
COPY ./packages/twenty-sdk /app/packages/twenty-sdk
|
||||
COPY ./packages/twenty-standard-application /app/packages/twenty-standard-application
|
||||
COPY ./packages/twenty-server /app/packages/twenty-server
|
||||
|
||||
RUN npx nx build twenty-standard-application
|
||||
RUN npx nx run twenty-server:build
|
||||
|
||||
RUN yarn workspaces focus --production twenty-emails twenty-shared twenty-sdk twenty-standard-application twenty-server
|
||||
RUN yarn workspaces focus --production twenty-emails twenty-shared twenty-server
|
||||
|
||||
# Build the front
|
||||
FROM common-deps AS twenty-front-build
|
||||
|
||||
@@ -1,140 +0,0 @@
|
||||
---
|
||||
title: APIs
|
||||
description: Query and modify your CRM data programmatically using REST or GraphQL.
|
||||
---
|
||||
|
||||
import { VimeoEmbed } from '/snippets/vimeo-embed.mdx';
|
||||
|
||||
Twenty was built to be developer-friendly, offering powerful APIs that adapt to your custom data model. We provide four distinct API types to meet different integration needs.
|
||||
|
||||
## Developer-First Approach
|
||||
|
||||
Twenty generates APIs specifically for your data model:
|
||||
- **No long IDs required**: Use your object and field names directly in endpoints
|
||||
- **Standard and custom objects treated equally**: Your custom objects get the same API treatment as built-in ones
|
||||
- **Dedicated endpoints**: Each object and field gets its own API endpoint
|
||||
- **Custom documentation**: Generated specifically for your workspace's data model
|
||||
|
||||
<Note>
|
||||
Your personalized API documentation is available under **Settings → API & Webhooks** after creating an API key. Since Twenty generates APIs that match your custom data model, the documentation is unique to your workspace.
|
||||
</Note>
|
||||
|
||||
## The Two API Types
|
||||
|
||||
### Core API
|
||||
Accessed on `/rest/` or `/graphql/`
|
||||
|
||||
Work with your actual **records** (the data):
|
||||
- Create, read, update, delete People, Companies, Opportunities, etc.
|
||||
- Query and filter data
|
||||
- Manage record relationships
|
||||
|
||||
### Metadata API
|
||||
Accessed on `/rest/metadata/` or `/metadata/`
|
||||
|
||||
Manage your **workspace and data model**:
|
||||
- Create, modify, or delete objects and fields
|
||||
- Configure workspace settings
|
||||
- Define relationships between objects
|
||||
|
||||
## REST vs GraphQL
|
||||
|
||||
Both Core and Metadata APIs are available in REST and GraphQL formats:
|
||||
|
||||
| Format | Available Operations |
|
||||
|--------|---------------------|
|
||||
| **REST** | CRUD, batch operations, upserts |
|
||||
| **GraphQL** | Same + **batch upserts**, relationship queries in one call |
|
||||
|
||||
Choose based on your needs — both formats access the same data.
|
||||
|
||||
## API Endpoints
|
||||
|
||||
| Environment | Base URL |
|
||||
|-------------|----------|
|
||||
| **Cloud** | `https://api.twenty.com/` |
|
||||
| **Self-Hosted** | `https://{your-domain}/` |
|
||||
|
||||
## Authentication
|
||||
|
||||
Every API request requires an API key in the header:
|
||||
|
||||
```
|
||||
Authorization: Bearer YOUR_API_KEY
|
||||
```
|
||||
|
||||
### Create an API Key
|
||||
|
||||
1. Go to **Settings → APIs & Webhooks**
|
||||
2. Click **+ Create key**
|
||||
3. Configure:
|
||||
- **Name**: Descriptive name for the key
|
||||
- **Expiration Date**: When the key expires
|
||||
4. Click **Save**
|
||||
5. **Copy immediately** — the key is only shown once
|
||||
|
||||
<VimeoEmbed videoId="928786722" title="Creating API key" />
|
||||
|
||||
<Warning>
|
||||
Your API key grants access to sensitive data. Don't share it with untrusted services. If compromised, disable it immediately and generate a new one.
|
||||
</Warning>
|
||||
|
||||
### Assign a Role to an API Key
|
||||
|
||||
For better security, assign a specific role to limit access:
|
||||
|
||||
1. Go to **Settings → Roles**
|
||||
2. Click on the role to assign
|
||||
3. Open the **Assignment** tab
|
||||
4. Under **API Keys**, click **+ Assign to API key**
|
||||
5. Select the API key
|
||||
|
||||
The key will inherit that role's permissions. See [Permissions](/user-guide/permissions-access/capabilities/permissions) for details.
|
||||
|
||||
### Manage API Keys
|
||||
|
||||
**Regenerate**: Settings → APIs & Webhooks → Click key → **Regenerate**
|
||||
|
||||
**Delete**: Settings → APIs & Webhooks → Click key → **Delete**
|
||||
|
||||
## API Playground
|
||||
|
||||
Test your APIs directly in the browser with our built-in playground — available for both **REST** and **GraphQL**.
|
||||
|
||||
### Access the Playground
|
||||
|
||||
1. Go to **Settings → APIs & Webhooks**
|
||||
2. Create an API key (required)
|
||||
3. Click on **REST API** or **GraphQL API** to open the playground
|
||||
|
||||
### What You Get
|
||||
|
||||
- **Interactive documentation**: Generated for your specific data model
|
||||
- **Live testing**: Execute real API calls against your workspace
|
||||
- **Schema explorer**: Browse available objects, fields, and relationships
|
||||
- **Request builder**: Construct queries with autocomplete
|
||||
|
||||
The playground reflects your custom objects and fields, so documentation is always accurate for your workspace.
|
||||
|
||||
## Batch Operations
|
||||
|
||||
Both REST and GraphQL support batch operations:
|
||||
- **Batch size**: Up to 60 records per request
|
||||
- **Operations**: Create, update, delete multiple records
|
||||
|
||||
**GraphQL-only features:**
|
||||
- **Batch Upsert**: Create or update in one call
|
||||
- Use plural object names (e.g., `CreateCompanies` instead of `CreateCompany`)
|
||||
|
||||
## Rate Limits
|
||||
|
||||
API requests are throttled to ensure platform stability:
|
||||
|
||||
| Limit | Value |
|
||||
|-------|-------|
|
||||
| **Requests** | 100 calls per minute |
|
||||
| **Batch size** | 60 records per call |
|
||||
|
||||
<Tip>
|
||||
Use batch operations to maximize throughput — process up to 60 records in a single API call instead of making individual requests.
|
||||
</Tip>
|
||||
@@ -1,677 +0,0 @@
|
||||
---
|
||||
title: Building Apps
|
||||
description: Define objects, logic functions, front components, and more with the Twenty SDK.
|
||||
---
|
||||
|
||||
<Warning>
|
||||
Apps are currently in alpha testing. The feature is functional but still evolving.
|
||||
</Warning>
|
||||
|
||||
## Use the SDK resources (types & config)
|
||||
|
||||
The twenty-sdk provides typed building blocks and helper functions you use inside your app. Below are the key pieces you'll touch most often.
|
||||
|
||||
### Helper functions
|
||||
|
||||
The SDK provides helper functions for defining your app entities. As described in [Entity detection](/developers/extend/apps/getting-started#entity-detection), you must use `export default define<Entity>({...})` for your entities to be detected:
|
||||
|
||||
| Function | Purpose |
|
||||
|----------|---------|
|
||||
| `defineApplication` | Configure application metadata (required, one per app) |
|
||||
| `defineObject` | Define custom objects with fields |
|
||||
| `defineLogicFunction` | Define logic functions with handlers |
|
||||
| `definePreInstallLogicFunction` | Define a pre-install logic function (one per app) |
|
||||
| `definePostInstallLogicFunction` | Define a post-install logic function (one per app) |
|
||||
| `defineFrontComponent` | Define front components for custom UI |
|
||||
| `defineRole` | Configure role permissions and object access |
|
||||
| `defineField` | Extend existing objects with additional fields |
|
||||
| `defineView` | Define saved views for objects |
|
||||
| `defineNavigationMenuItem` | Define sidebar navigation links |
|
||||
| `defineSkill` | Define AI agent skills |
|
||||
|
||||
These functions validate your configuration at build time and provide IDE autocompletion and type safety.
|
||||
|
||||
### Defining objects
|
||||
|
||||
Custom objects describe both schema and behavior for records in your workspace. Use `defineObject()` to define objects with built-in validation:
|
||||
|
||||
```typescript
|
||||
// src/app/postCard.object.ts
|
||||
import { defineObject, FieldType } from 'twenty-sdk';
|
||||
|
||||
enum PostCardStatus {
|
||||
DRAFT = 'DRAFT',
|
||||
SENT = 'SENT',
|
||||
DELIVERED = 'DELIVERED',
|
||||
RETURNED = 'RETURNED',
|
||||
}
|
||||
|
||||
export default defineObject({
|
||||
universalIdentifier: '54b589ca-eeed-4950-a176-358418b85c05',
|
||||
nameSingular: 'postCard',
|
||||
namePlural: 'postCards',
|
||||
labelSingular: 'Post Card',
|
||||
labelPlural: 'Post Cards',
|
||||
description: 'A post card object',
|
||||
icon: 'IconMail',
|
||||
fields: [
|
||||
{
|
||||
universalIdentifier: '58a0a314-d7ea-4865-9850-7fb84e72f30b',
|
||||
name: 'content',
|
||||
type: FieldType.TEXT,
|
||||
label: 'Content',
|
||||
description: "Postcard's content",
|
||||
icon: 'IconAbc',
|
||||
},
|
||||
{
|
||||
universalIdentifier: 'c6aa31f3-da76-4ac6-889f-475e226009ac',
|
||||
name: 'recipientName',
|
||||
type: FieldType.FULL_NAME,
|
||||
label: 'Recipient name',
|
||||
icon: 'IconUser',
|
||||
},
|
||||
{
|
||||
universalIdentifier: '95045777-a0ad-49ec-98f9-22f9fc0c8266',
|
||||
name: 'recipientAddress',
|
||||
type: FieldType.ADDRESS,
|
||||
label: 'Recipient address',
|
||||
icon: 'IconHome',
|
||||
},
|
||||
{
|
||||
universalIdentifier: '87b675b8-dd8c-4448-b4ca-20e5a2234a1e',
|
||||
name: 'status',
|
||||
type: FieldType.SELECT,
|
||||
label: 'Status',
|
||||
icon: 'IconSend',
|
||||
defaultValue: `'${PostCardStatus.DRAFT}'`,
|
||||
options: [
|
||||
{ value: PostCardStatus.DRAFT, label: 'Draft', position: 0, color: 'gray' },
|
||||
{ value: PostCardStatus.SENT, label: 'Sent', position: 1, color: 'orange' },
|
||||
{ value: PostCardStatus.DELIVERED, label: 'Delivered', position: 2, color: 'green' },
|
||||
{ value: PostCardStatus.RETURNED, label: 'Returned', position: 3, color: 'orange' },
|
||||
],
|
||||
},
|
||||
{
|
||||
universalIdentifier: 'e06abe72-5b44-4e7f-93be-afc185a3c433',
|
||||
name: 'deliveredAt',
|
||||
type: FieldType.DATE_TIME,
|
||||
label: 'Delivered at',
|
||||
icon: 'IconCheck',
|
||||
isNullable: true,
|
||||
defaultValue: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Key points:
|
||||
|
||||
- Use `defineObject()` for built-in validation and better IDE support.
|
||||
- The `universalIdentifier` must be unique and stable across deployments.
|
||||
- Each field requires a `name`, `type`, `label`, and its own stable `universalIdentifier`.
|
||||
- The `fields` array is optional — you can define objects without custom fields.
|
||||
- You can scaffold new objects using `yarn twenty entity:add`, which guides you through naming, fields, and relationships.
|
||||
|
||||
<Note>
|
||||
**Base fields are created automatically.** When you define a custom object, Twenty automatically adds standard fields
|
||||
such as `id`, `name`, `createdAt`, `updatedAt`, `createdBy`, `updatedBy` and `deletedAt`.
|
||||
You don't need to define these in your `fields` array — only add your custom fields.
|
||||
You can override default fields by defining a field with the same name in your `fields` array,
|
||||
but this is not recommended.
|
||||
</Note>
|
||||
|
||||
|
||||
### Application config (application-config.ts)
|
||||
|
||||
Every app has a single `application-config.ts` file that describes:
|
||||
|
||||
- **Who the app is**: identifiers, display name, and description.
|
||||
- **How its functions run**: which role they use for permissions.
|
||||
- **(Optional) variables**: key–value pairs exposed to your functions as environment variables.
|
||||
- **(Optional) pre-install function**: a logic function that runs before the app is installed.
|
||||
- **(Optional) post-install function**: a logic function that runs after the app is installed.
|
||||
|
||||
Use `defineApplication()` to define your application configuration:
|
||||
|
||||
```typescript
|
||||
// src/application-config.ts
|
||||
import { defineApplication } from 'twenty-sdk';
|
||||
import { DEFAULT_ROLE_UNIVERSAL_IDENTIFIER } from 'src/roles/default-role';
|
||||
|
||||
export default defineApplication({
|
||||
universalIdentifier: '4ec0391d-18d5-411c-b2f3-266ddc1c3ef7',
|
||||
displayName: 'My Twenty App',
|
||||
description: 'My first Twenty app',
|
||||
icon: 'IconWorld',
|
||||
applicationVariables: {
|
||||
DEFAULT_RECIPIENT_NAME: {
|
||||
universalIdentifier: '19e94e59-d4fe-4251-8981-b96d0a9f74de',
|
||||
description: 'Default recipient name for postcards',
|
||||
value: 'Jane Doe',
|
||||
isSecret: false,
|
||||
},
|
||||
},
|
||||
defaultRoleUniversalIdentifier: DEFAULT_ROLE_UNIVERSAL_IDENTIFIER,
|
||||
});
|
||||
```
|
||||
|
||||
Notes:
|
||||
- `universalIdentifier` fields are deterministic IDs you own; generate them once and keep them stable across syncs.
|
||||
- `applicationVariables` become environment variables for your functions (for example, `DEFAULT_RECIPIENT_NAME` is available as `process.env.DEFAULT_RECIPIENT_NAME`).
|
||||
- `defaultRoleUniversalIdentifier` must match the role file (see below).
|
||||
- Pre-install and post-install functions are automatically detected during the manifest build. See [Pre-install functions](#pre-install-functions) and [Post-install functions](#post-install-functions).
|
||||
|
||||
#### Roles and permissions
|
||||
|
||||
Applications can define roles that encapsulate permissions on your workspace's objects and actions. The field `defaultRoleUniversalIdentifier` in `application-config.ts` designates the default role used by your app's logic functions.
|
||||
|
||||
- The runtime API key injected as `TWENTY_API_KEY` is derived from this default function role.
|
||||
- The typed client will be restricted to the permissions granted to that role.
|
||||
- Follow least‑privilege: create a dedicated role with only the permissions your functions need, then reference its universal identifier.
|
||||
|
||||
##### Default function role (*.role.ts)
|
||||
|
||||
When you scaffold a new app, the CLI also creates a default role file. Use `defineRole()` to define roles with built-in validation:
|
||||
|
||||
```typescript
|
||||
// src/roles/default-role.ts
|
||||
import { defineRole, PermissionFlag } from 'twenty-sdk';
|
||||
|
||||
export const DEFAULT_ROLE_UNIVERSAL_IDENTIFIER =
|
||||
'b648f87b-1d26-4961-b974-0908fd991061';
|
||||
|
||||
export default defineRole({
|
||||
universalIdentifier: DEFAULT_ROLE_UNIVERSAL_IDENTIFIER,
|
||||
label: 'Default function role',
|
||||
description: 'Default role for function Twenty client',
|
||||
canReadAllObjectRecords: false,
|
||||
canUpdateAllObjectRecords: false,
|
||||
canSoftDeleteAllObjectRecords: false,
|
||||
canDestroyAllObjectRecords: false,
|
||||
canUpdateAllSettings: false,
|
||||
canBeAssignedToAgents: false,
|
||||
canBeAssignedToUsers: false,
|
||||
canBeAssignedToApiKeys: false,
|
||||
objectPermissions: [
|
||||
{
|
||||
objectUniversalIdentifier: '9f9882af-170c-4879-b013-f9628b77c050',
|
||||
canReadObjectRecords: true,
|
||||
canUpdateObjectRecords: true,
|
||||
canSoftDeleteObjectRecords: false,
|
||||
canDestroyObjectRecords: false,
|
||||
},
|
||||
],
|
||||
fieldPermissions: [
|
||||
{
|
||||
objectUniversalIdentifier: '9f9882af-170c-4879-b013-f9628b77c050',
|
||||
fieldUniversalIdentifier: 'b2c37dc0-8ae7-470e-96cd-1476b47dfaff',
|
||||
canReadFieldValue: false,
|
||||
canUpdateFieldValue: false,
|
||||
},
|
||||
],
|
||||
permissionFlags: [PermissionFlag.APPLICATIONS],
|
||||
});
|
||||
```
|
||||
|
||||
The `universalIdentifier` of this role is then referenced in `application-config.ts` as `defaultRoleUniversalIdentifier`. In other words:
|
||||
|
||||
- **\*.role.ts** defines what the default function role can do.
|
||||
- **application-config.ts** points to that role so your functions inherit its permissions.
|
||||
|
||||
Notes:
|
||||
- Start from the scaffolded role, then progressively restrict it following least‑privilege.
|
||||
- Replace the `objectPermissions` and `fieldPermissions` with the objects/fields your functions need.
|
||||
- `permissionFlags` control access to platform-level capabilities. Keep them minimal; add only what you need.
|
||||
- See a working example in the Hello World app: [`packages/twenty-apps/hello-world/src/roles/function-role.ts`](https://github.com/twentyhq/twenty/blob/main/packages/twenty-apps/hello-world/src/roles/function-role.ts).
|
||||
|
||||
### Logic function config and entrypoint
|
||||
|
||||
Each function file uses `defineLogicFunction()` to export a configuration with a handler and optional triggers.
|
||||
|
||||
```typescript
|
||||
// src/app/createPostCard.logic-function.ts
|
||||
import { defineLogicFunction } from 'twenty-sdk';
|
||||
import type { DatabaseEventPayload, ObjectRecordCreateEvent, CronPayload, RoutePayload } from 'twenty-sdk';
|
||||
import { CoreApiClient, type Person } from 'twenty-sdk/generated';
|
||||
|
||||
const handler = async (params: RoutePayload) => {
|
||||
const client = new CoreApiClient();
|
||||
const name = 'name' in params.queryStringParameters
|
||||
? params.queryStringParameters.name ?? process.env.DEFAULT_RECIPIENT_NAME ?? 'Hello world'
|
||||
: 'Hello world';
|
||||
|
||||
const result = await client.mutation({
|
||||
createPostCard: {
|
||||
__args: { data: { name } },
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
});
|
||||
return result;
|
||||
};
|
||||
|
||||
export default defineLogicFunction({
|
||||
universalIdentifier: 'e56d363b-0bdc-4d8a-a393-6f0d1c75bdcf',
|
||||
name: 'create-new-post-card',
|
||||
timeoutSeconds: 2,
|
||||
handler,
|
||||
triggers: [
|
||||
// Public HTTP route trigger '/s/post-card/create'
|
||||
{
|
||||
universalIdentifier: 'c9f84c8d-b26d-40d1-95dd-4f834ae5a2c6',
|
||||
type: 'route',
|
||||
path: '/post-card/create',
|
||||
httpMethod: 'GET',
|
||||
isAuthRequired: false,
|
||||
},
|
||||
// Cron trigger (CRON pattern)
|
||||
// {
|
||||
// universalIdentifier: 'dd802808-0695-49e1-98c9-d5c9e2704ce2',
|
||||
// type: 'cron',
|
||||
// pattern: '0 0 1 1 *',
|
||||
// },
|
||||
// Database event trigger
|
||||
// {
|
||||
// universalIdentifier: '203f1df3-4a82-4d06-a001-b8cf22a31156',
|
||||
// type: 'databaseEvent',
|
||||
// eventName: 'person.updated',
|
||||
// updatedFields: ['name'],
|
||||
// },
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Common trigger types:
|
||||
- **route**: Exposes your function on an HTTP path and method **under the `/s/` endpoint**:
|
||||
> e.g. `path: '/post-card/create',` -> call on `<APP_URL>/s/post-card/create`
|
||||
- **cron**: Runs your function on a schedule using a CRON expression.
|
||||
- **databaseEvent**: Runs on workspace object lifecycle events. When the event operation is `updated`, specific fields to listen to can be specified in the `updatedFields` array. If left undefined or empty, any update will trigger the function.
|
||||
> e.g. `person.updated`
|
||||
|
||||
Notes:
|
||||
- The `triggers` array is optional. Functions without triggers can be used as utility functions called by other functions.
|
||||
- You can mix multiple trigger types in a single function.
|
||||
|
||||
### Pre-install functions
|
||||
|
||||
A pre-install function is a logic function that runs automatically before your app is installed on a workspace. This is useful for validation tasks, prerequisite checks, or preparing workspace state before the main installation proceeds.
|
||||
|
||||
When you scaffold a new app with `create-twenty-app`, a pre-install function is generated for you at `src/logic-functions/pre-install.ts`:
|
||||
|
||||
```typescript
|
||||
// src/logic-functions/pre-install.ts
|
||||
import { definePreInstallLogicFunction, type InstallLogicFunctionPayload } from 'twenty-sdk';
|
||||
|
||||
const handler = async (payload: InstallLogicFunctionPayload): Promise<void> => {
|
||||
console.log('Pre install logic function executed successfully!', payload.previousVersion);
|
||||
};
|
||||
|
||||
export default definePreInstallLogicFunction({
|
||||
universalIdentifier: '<generated-uuid>',
|
||||
name: 'pre-install',
|
||||
description: 'Runs before installation to prepare the application.',
|
||||
timeoutSeconds: 300,
|
||||
handler,
|
||||
});
|
||||
```
|
||||
|
||||
You can also manually execute the pre-install function at any time using the CLI:
|
||||
|
||||
```bash filename="Terminal"
|
||||
yarn twenty function:execute --preInstall
|
||||
```
|
||||
|
||||
Key points:
|
||||
- Pre-install functions use `definePreInstallLogicFunction()` — a specialized variant that omits trigger settings (`cronTriggerSettings`, `databaseEventTriggerSettings`, `httpRouteTriggerSettings`, `isTool`).
|
||||
- The handler receives an `InstallLogicFunctionPayload` with `{ previousVersion: string }` — the version of the app that was previously installed (or an empty string for fresh installs).
|
||||
- Only one pre-install function is allowed per application. The manifest build will error if more than one is detected.
|
||||
- The function's `universalIdentifier` is automatically set as `preInstallLogicFunctionUniversalIdentifier` on the application manifest during the build — you do not need to reference it in `defineApplication()`.
|
||||
- The default timeout is set to 300 seconds (5 minutes) to allow for longer preparation tasks.
|
||||
- Pre-install functions do not need triggers — they are invoked by the platform before installation or manually via `function:execute --preInstall`.
|
||||
|
||||
### Post-install functions
|
||||
|
||||
A post-install function is a logic function that runs automatically after your app is installed on a workspace. This is useful for one-time setup tasks such as seeding default data, creating initial records, or configuring workspace settings.
|
||||
|
||||
When you scaffold a new app with `create-twenty-app`, a post-install function is generated for you at `src/logic-functions/post-install.ts`:
|
||||
|
||||
```typescript
|
||||
// src/logic-functions/post-install.ts
|
||||
import { definePostInstallLogicFunction, type InstallLogicFunctionPayload } from 'twenty-sdk';
|
||||
|
||||
const handler = async (payload: InstallLogicFunctionPayload): Promise<void> => {
|
||||
console.log('Post install logic function executed successfully!', payload.previousVersion);
|
||||
};
|
||||
|
||||
export default definePostInstallLogicFunction({
|
||||
universalIdentifier: '<generated-uuid>',
|
||||
name: 'post-install',
|
||||
description: 'Runs after installation to set up the application.',
|
||||
timeoutSeconds: 300,
|
||||
handler,
|
||||
});
|
||||
```
|
||||
|
||||
You can also manually execute the post-install function at any time using the CLI:
|
||||
|
||||
```bash filename="Terminal"
|
||||
yarn twenty function:execute --postInstall
|
||||
```
|
||||
|
||||
Key points:
|
||||
- Post-install functions use `definePostInstallLogicFunction()` — a specialized variant that omits trigger settings (`cronTriggerSettings`, `databaseEventTriggerSettings`, `httpRouteTriggerSettings`, `isTool`).
|
||||
- The handler receives an `InstallLogicFunctionPayload` with `{ previousVersion: string }` — the version of the app that was previously installed (or an empty string for fresh installs).
|
||||
- Only one post-install function is allowed per application. The manifest build will error if more than one is detected.
|
||||
- The function's `universalIdentifier` is automatically set as `postInstallLogicFunctionUniversalIdentifier` on the application manifest during the build — you do not need to reference it in `defineApplication()`.
|
||||
- The default timeout is set to 300 seconds (5 minutes) to allow for longer setup tasks like data seeding.
|
||||
- Post-install functions do not need triggers — they are invoked by the platform during installation or manually via `function:execute --postInstall`.
|
||||
|
||||
### Route trigger payload
|
||||
|
||||
<Warning>
|
||||
**Breaking change (v1.16, January 2026):** The route trigger payload format has changed. Prior to v1.16, query parameters, path parameters, and body were sent directly as the payload. Starting with v1.16, they are nested inside a structured `RoutePayload` object.
|
||||
|
||||
**Before v1.16:**
|
||||
```typescript
|
||||
const handler = async (params) => {
|
||||
const { param1, param2 } = params; // Direct access
|
||||
};
|
||||
```
|
||||
|
||||
**After v1.16:**
|
||||
```typescript
|
||||
const handler = async (event: RoutePayload) => {
|
||||
const { param1, param2 } = event.body; // Access via .body
|
||||
const { queryParam } = event.queryStringParameters;
|
||||
const { id } = event.pathParameters;
|
||||
};
|
||||
```
|
||||
|
||||
**To migrate existing functions:** Update your handler to destructure from `event.body`, `event.queryStringParameters`, or `event.pathParameters` instead of directly from the params object.
|
||||
</Warning>
|
||||
|
||||
When a route trigger invokes your logic function, it receives a `RoutePayload` object that follows the AWS HTTP API v2 format. Import the type from `twenty-sdk`:
|
||||
|
||||
```typescript
|
||||
import { defineLogicFunction, type RoutePayload } from 'twenty-sdk';
|
||||
|
||||
const handler = async (event: RoutePayload) => {
|
||||
// Access request data
|
||||
const { headers, queryStringParameters, pathParameters, body } = event;
|
||||
|
||||
// HTTP method and path are available in requestContext
|
||||
const { method, path } = event.requestContext.http;
|
||||
|
||||
return { message: 'Success' };
|
||||
};
|
||||
```
|
||||
|
||||
The `RoutePayload` type has the following structure:
|
||||
|
||||
| Property | Type | Description |
|
||||
|----------|------|-------------|
|
||||
| `headers` | `Record<string, string \| undefined>` | HTTP headers (only those listed in `forwardedRequestHeaders`) |
|
||||
| `queryStringParameters` | `Record<string, string \| undefined>` | Query string parameters (multiple values joined with commas) |
|
||||
| `pathParameters` | `Record<string, string \| undefined>` | Path parameters extracted from the route pattern (e.g., `/users/:id` → `{ id: '123' }`) |
|
||||
| `body` | `object \| null` | Parsed request body (JSON) |
|
||||
| `isBase64Encoded` | `boolean` | Whether the body is base64 encoded |
|
||||
| `requestContext.http.method` | `string` | HTTP method (GET, POST, PUT, PATCH, DELETE) |
|
||||
| `requestContext.http.path` | `string` | Raw request path |
|
||||
|
||||
### Forwarding HTTP headers
|
||||
|
||||
By default, HTTP headers from incoming requests are **not** passed to your logic function for security reasons. To access specific headers, explicitly list them in the `forwardedRequestHeaders` array:
|
||||
|
||||
```typescript
|
||||
export default defineLogicFunction({
|
||||
universalIdentifier: 'e56d363b-0bdc-4d8a-a393-6f0d1c75bdcf',
|
||||
name: 'webhook-handler',
|
||||
handler,
|
||||
triggers: [
|
||||
{
|
||||
universalIdentifier: 'c9f84c8d-b26d-40d1-95dd-4f834ae5a2c6',
|
||||
type: 'route',
|
||||
path: '/webhook',
|
||||
httpMethod: 'POST',
|
||||
isAuthRequired: false,
|
||||
forwardedRequestHeaders: ['x-webhook-signature', 'content-type'],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
In your handler, you can then access these headers:
|
||||
|
||||
```typescript
|
||||
const handler = async (event: RoutePayload) => {
|
||||
const signature = event.headers['x-webhook-signature'];
|
||||
const contentType = event.headers['content-type'];
|
||||
|
||||
// Validate webhook signature...
|
||||
return { received: true };
|
||||
};
|
||||
```
|
||||
|
||||
<Note>
|
||||
Header names are normalized to lowercase. Access them using lowercase keys (for example, `event.headers['content-type']`).
|
||||
</Note>
|
||||
|
||||
You can create new functions in two ways:
|
||||
|
||||
- **Scaffolded**: Run `yarn twenty entity:add` and choose the option to add a new logic function. This generates a starter file with a handler and config.
|
||||
- **Manual**: Create a new `*.logic-function.ts` file and use `defineLogicFunction()`, following the same pattern.
|
||||
|
||||
### Marking a logic function as a tool
|
||||
|
||||
Logic functions can be exposed as **tools** for AI agents and workflows. When a function is marked as a tool, it becomes discoverable by Twenty's AI features and can be selected as a step in workflow automations.
|
||||
|
||||
To mark a logic function as a tool, set `isTool: true` and provide a `toolInputSchema` describing the expected input parameters using [JSON Schema](https://json-schema.org/):
|
||||
|
||||
```typescript
|
||||
// src/logic-functions/enrich-company.logic-function.ts
|
||||
import { defineLogicFunction } from 'twenty-sdk';
|
||||
import { CoreApiClient } from 'twenty-sdk/generated';
|
||||
|
||||
const handler = async (params: { companyName: string; domain?: string }) => {
|
||||
const client = new CoreApiClient();
|
||||
|
||||
const result = await client.mutation({
|
||||
createTask: {
|
||||
__args: {
|
||||
data: {
|
||||
title: `Enrich data for ${params.companyName}`,
|
||||
body: `Domain: ${params.domain ?? 'unknown'}`,
|
||||
},
|
||||
},
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
return { taskId: result.createTask.id };
|
||||
};
|
||||
|
||||
export default defineLogicFunction({
|
||||
universalIdentifier: 'f47ac10b-58cc-4372-a567-0e02b2c3d479',
|
||||
name: 'enrich-company',
|
||||
description: 'Enrich a company record with external data',
|
||||
timeoutSeconds: 10,
|
||||
handler,
|
||||
isTool: true,
|
||||
toolInputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
companyName: {
|
||||
type: 'string',
|
||||
description: 'The name of the company to enrich',
|
||||
},
|
||||
domain: {
|
||||
type: 'string',
|
||||
description: 'The company website domain (optional)',
|
||||
},
|
||||
},
|
||||
required: ['companyName'],
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Key points:
|
||||
|
||||
- **`isTool`** (`boolean`, default: `false`): When set to `true`, the function is registered as a tool and becomes available to AI agents and workflow automations.
|
||||
- **`toolInputSchema`** (`object`, optional): A JSON Schema object that describes the parameters your function accepts. AI agents use this schema to understand what inputs the tool expects and to validate calls. If omitted, the schema defaults to `{ type: 'object', properties: {} }` (no parameters).
|
||||
- Functions with `isTool: false` (or unset) are **not** exposed as tools. They can still be executed directly or called by other functions, but will not appear in tool discovery.
|
||||
- **Tool naming**: When exposed as a tool, the function name is automatically normalized to `logic_function_<name>` (lowercased, non-alphanumeric characters replaced with underscores). For example, `enrich-company` becomes `logic_function_enrich_company`.
|
||||
- You can combine `isTool` with triggers — a function can be both a tool (callable by AI agents) and triggered by events (cron, database events, routes) at the same time.
|
||||
|
||||
<Note>
|
||||
**Write a good `description`.** AI agents rely on the function's `description` field to decide when to use the tool. Be specific about what the tool does and when it should be called.
|
||||
</Note>
|
||||
|
||||
### Front components
|
||||
|
||||
Front components let you build custom React components that render within Twenty's UI. Use `defineFrontComponent()` to define components with built-in validation:
|
||||
|
||||
```typescript
|
||||
// src/front-components/my-widget.tsx
|
||||
import { defineFrontComponent } from 'twenty-sdk';
|
||||
|
||||
const MyWidget = () => {
|
||||
return (
|
||||
<div style={{ padding: '20px', fontFamily: 'sans-serif' }}>
|
||||
<h1>My Custom Widget</h1>
|
||||
<p>This is a custom front component for Twenty.</p>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default defineFrontComponent({
|
||||
universalIdentifier: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
|
||||
name: 'my-widget',
|
||||
description: 'A custom widget component',
|
||||
component: MyWidget,
|
||||
});
|
||||
```
|
||||
|
||||
Key points:
|
||||
- Front components are React components that render in isolated contexts within Twenty.
|
||||
- The `component` field references your React component.
|
||||
- Components are built and synced automatically during `yarn twenty app:dev`.
|
||||
|
||||
You can create new front components in two ways:
|
||||
|
||||
- **Scaffolded**: Run `yarn twenty entity:add` and choose the option to add a new front component.
|
||||
- **Manual**: Create a new `.tsx` file and use `defineFrontComponent()`, following the same pattern.
|
||||
|
||||
### Skills
|
||||
|
||||
Skills define reusable instructions and capabilities that AI agents can use within your workspace. Use `defineSkill()` to define skills with built-in validation:
|
||||
|
||||
```typescript
|
||||
// src/skills/example-skill.ts
|
||||
import { defineSkill } from 'twenty-sdk';
|
||||
|
||||
export default defineSkill({
|
||||
universalIdentifier: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
|
||||
name: 'sales-outreach',
|
||||
label: 'Sales Outreach',
|
||||
description: 'Guides the AI agent through a structured sales outreach process',
|
||||
icon: 'IconBrain',
|
||||
content: `You are a sales outreach assistant. When reaching out to a prospect:
|
||||
1. Research the company and recent news
|
||||
2. Identify the prospect's role and likely pain points
|
||||
3. Draft a personalized message referencing specific details
|
||||
4. Keep the tone professional but conversational`,
|
||||
});
|
||||
```
|
||||
|
||||
Key points:
|
||||
- `name` is a unique identifier string for the skill (kebab-case recommended).
|
||||
- `label` is the human-readable display name shown in the UI.
|
||||
- `content` contains the skill instructions — this is the text the AI agent uses.
|
||||
- `icon` (optional) sets the icon displayed in the UI.
|
||||
- `description` (optional) provides additional context about the skill's purpose.
|
||||
|
||||
You can create new skills in two ways:
|
||||
|
||||
- **Scaffolded**: Run `yarn twenty entity:add` and choose the option to add a new skill.
|
||||
- **Manual**: Create a new file and use `defineSkill()`, following the same pattern.
|
||||
|
||||
### Generated typed clients
|
||||
|
||||
Two typed clients are auto-generated by `yarn twenty app:dev` and stored in `node_modules/twenty-sdk/generated` based on your workspace schema:
|
||||
|
||||
- **`CoreApiClient`** — queries the `/graphql` endpoint for workspace data
|
||||
- **`MetadataApiClient`** — queries the `/metadata` endpoint for workspace configuration and file uploads
|
||||
|
||||
```typescript
|
||||
import { CoreApiClient, MetadataApiClient } from 'twenty-sdk/generated';
|
||||
|
||||
const client = new CoreApiClient();
|
||||
const { me } = await client.query({ me: { id: true, displayName: true } });
|
||||
|
||||
const metadataClient = new MetadataApiClient();
|
||||
const { currentWorkspace } = await metadataClient.query({ currentWorkspace: { id: true } });
|
||||
```
|
||||
|
||||
Both clients are re-generated automatically by `yarn twenty app:dev` whenever your objects or fields change.
|
||||
|
||||
#### Runtime credentials in logic functions
|
||||
|
||||
When your function runs on Twenty, the platform injects credentials as environment variables before your code executes:
|
||||
|
||||
- `TWENTY_API_URL`: Base URL of the Twenty API your app targets.
|
||||
- `TWENTY_API_KEY`: Short‑lived key scoped to your application's default function role.
|
||||
|
||||
Notes:
|
||||
- You do not need to pass URL or API key to the generated client. It reads `TWENTY_API_URL` and `TWENTY_API_KEY` from process.env at runtime.
|
||||
- The API key's permissions are determined by the role referenced in your `application-config.ts` via `defaultRoleUniversalIdentifier`. This is the default role used by logic functions of your application.
|
||||
- Applications can define roles to follow least‑privilege. Grant only the permissions your functions need, then point `defaultRoleUniversalIdentifier` to that role's universal identifier.
|
||||
|
||||
#### Uploading files
|
||||
|
||||
The generated `MetadataApiClient` includes an `uploadFile` method for attaching files to file-type fields on your workspace objects. Because standard GraphQL clients do not support multipart file uploads natively, the client provides this dedicated method that implements the [GraphQL multipart request specification](https://github.com/jaydenseric/graphql-multipart-request-spec) under the hood.
|
||||
|
||||
```typescript
|
||||
import { MetadataApiClient } from 'twenty-sdk/generated';
|
||||
import * as fs from 'fs';
|
||||
|
||||
const metadataClient = new MetadataApiClient();
|
||||
|
||||
const fileBuffer = fs.readFileSync('./invoice.pdf');
|
||||
|
||||
const uploadedFile = await metadataClient.uploadFile(
|
||||
fileBuffer, // file contents as a Buffer
|
||||
'invoice.pdf', // filename
|
||||
'application/pdf', // MIME type (defaults to 'application/octet-stream')
|
||||
'58a0a314-d7ea-4865-9850-7fb84e72f30b', // field universal identifier
|
||||
);
|
||||
|
||||
console.log(uploadedFile);
|
||||
// { id: '...', path: '...', size: 12345, createdAt: '...', url: 'https://...' }
|
||||
```
|
||||
|
||||
The method signature:
|
||||
|
||||
```typescript
|
||||
uploadFile(
|
||||
fileBuffer: Buffer,
|
||||
filename: string,
|
||||
contentType: string,
|
||||
fieldMetadataUniversalIdentifier: string,
|
||||
): Promise<{ id: string; path: string; size: number; createdAt: string; url: string }>
|
||||
```
|
||||
|
||||
| Parameter | Type | Description |
|
||||
|-----------|------|-------------|
|
||||
| `fileBuffer` | `Buffer` | The raw file contents |
|
||||
| `filename` | `string` | The name of the file (used for storage and display) |
|
||||
| `contentType` | `string` | MIME type of the file (defaults to `application/octet-stream` if omitted) |
|
||||
| `fieldMetadataUniversalIdentifier` | `string` | The `universalIdentifier` of the file-type field on your object |
|
||||
|
||||
Key points:
|
||||
- The `uploadFile` method is available on `MetadataApiClient` because the upload mutation is resolved by the `/metadata` endpoint.
|
||||
- It uses the field's `universalIdentifier` (not its workspace-specific ID), so your upload code works across any workspace where your app is installed — consistent with how apps reference fields everywhere else.
|
||||
- The returned `url` is a signed URL you can use to access the uploaded file.
|
||||
|
||||
### Hello World example
|
||||
|
||||
Explore a minimal, end-to-end example that demonstrates objects, logic functions, front components, and multiple triggers [here](https://github.com/twentyhq/twenty/tree/main/packages/twenty-apps/hello-world).
|
||||
@@ -1,231 +0,0 @@
|
||||
---
|
||||
title: Getting Started
|
||||
description: Create your first Twenty app in minutes.
|
||||
---
|
||||
|
||||
<Warning>
|
||||
Apps are currently in alpha testing. The feature is functional but still evolving.
|
||||
</Warning>
|
||||
|
||||
Apps let you extend Twenty with custom objects, fields, logic functions, AI skills, and UI components — all managed as code.
|
||||
|
||||
**What you can do today:**
|
||||
- Define custom objects and fields as code (managed data model)
|
||||
- Build logic functions with custom triggers (HTTP routes, cron, database events)
|
||||
- Define skills for AI agents
|
||||
- Build front components that render inside Twenty's UI
|
||||
- Deploy the same app across multiple workspaces
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Node.js 24+ and Yarn 4
|
||||
- A Twenty workspace and an API key (create one at https://app.twenty.com/settings/api-webhooks)
|
||||
|
||||
## Getting Started
|
||||
|
||||
Create a new app using the official scaffolder, then authenticate and start developing:
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Scaffold a new app (includes all examples by default)
|
||||
npx create-twenty-app@latest my-twenty-app
|
||||
cd my-twenty-app
|
||||
|
||||
# Start dev mode: automatically syncs local changes to your workspace
|
||||
yarn twenty app:dev
|
||||
```
|
||||
|
||||
The scaffolder supports two modes for controlling which example files are included:
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Default (exhaustive): all examples (object, field, logic function, front component, view, navigation menu item, skill)
|
||||
npx create-twenty-app@latest my-app
|
||||
|
||||
# Minimal: only core files (application-config.ts and default-role.ts)
|
||||
npx create-twenty-app@latest my-app --minimal
|
||||
```
|
||||
|
||||
From here you can:
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Add a new entity to your application (guided)
|
||||
yarn twenty entity:add
|
||||
|
||||
# Watch your application's function logs
|
||||
yarn twenty function:logs
|
||||
|
||||
# Execute a function by name
|
||||
yarn twenty function:execute -n my-function -p '{"name": "test"}'
|
||||
|
||||
# Execute the pre-install function
|
||||
yarn twenty function:execute --preInstall
|
||||
|
||||
# Execute the post-install function
|
||||
yarn twenty function:execute --postInstall
|
||||
|
||||
# Uninstall the application from the current workspace
|
||||
yarn twenty app:uninstall
|
||||
|
||||
# Display commands' help
|
||||
yarn twenty help
|
||||
```
|
||||
|
||||
See also: the CLI reference pages for [create-twenty-app](https://www.npmjs.com/package/create-twenty-app) and [twenty-sdk CLI](https://www.npmjs.com/package/twenty-sdk).
|
||||
|
||||
## Project structure (scaffolded)
|
||||
|
||||
When you run `npx create-twenty-app@latest my-twenty-app`, the scaffolder:
|
||||
|
||||
- Copies a minimal base application into `my-twenty-app/`
|
||||
- Adds a local `twenty-sdk` dependency and Yarn 4 configuration
|
||||
- Creates config files and scripts wired to the `twenty` CLI
|
||||
- Generates core files (application config, default function role, pre-install and post-install functions) plus example files based on the scaffolding mode
|
||||
|
||||
A freshly scaffolded app with the default `--exhaustive` mode looks like this:
|
||||
|
||||
```text filename="my-twenty-app/"
|
||||
my-twenty-app/
|
||||
package.json
|
||||
yarn.lock
|
||||
.gitignore
|
||||
.nvmrc
|
||||
.yarnrc.yml
|
||||
.yarn/
|
||||
install-state.gz
|
||||
.oxlintrc.json
|
||||
tsconfig.json
|
||||
README.md
|
||||
public/ # Public assets folder (images, fonts, etc.)
|
||||
src/
|
||||
├── application-config.ts # Required - main application configuration
|
||||
├── roles/
|
||||
│ └── default-role.ts # Default role for logic functions
|
||||
├── objects/
|
||||
│ └── example-object.ts # Example custom object definition
|
||||
├── fields/
|
||||
│ └── example-field.ts # Example standalone field definition
|
||||
├── logic-functions/
|
||||
│ ├── hello-world.ts # Example logic function
|
||||
│ ├── pre-install.ts # Pre-install logic function
|
||||
│ └── post-install.ts # Post-install logic function
|
||||
├── front-components/
|
||||
│ └── hello-world.tsx # Example front component
|
||||
├── views/
|
||||
│ └── example-view.ts # Example saved view definition
|
||||
├── navigation-menu-items/
|
||||
│ └── example-navigation-menu-item.ts # Example sidebar navigation link
|
||||
└── skills/
|
||||
└── example-skill.ts # Example AI agent skill definition
|
||||
```
|
||||
|
||||
With `--minimal`, only the core files are created (`application-config.ts`, `roles/default-role.ts`, `logic-functions/pre-install.ts`, and `logic-functions/post-install.ts`).
|
||||
|
||||
At a high level:
|
||||
|
||||
- **package.json**: Declares the app name, version, engines (Node 24+, Yarn 4), and adds `twenty-sdk` plus a `twenty` script that delegates to the local `twenty` CLI. Run `yarn twenty help` to list all available commands.
|
||||
- **.gitignore**: Ignores common artifacts such as `node_modules`, `.yarn`, `generated/` (typed client), `dist/`, `build/`, coverage folders, log files, and `.env*` files.
|
||||
- **yarn.lock**, **.yarnrc.yml**, **.yarn/**: Lock and configure the Yarn 4 toolchain used by the project.
|
||||
- **.nvmrc**: Pins the Node.js version expected by the project.
|
||||
- **.oxlintrc.json** and **tsconfig.json**: Provide linting and TypeScript configuration for your app's TypeScript sources.
|
||||
- **README.md**: A short README in the app root with basic instructions.
|
||||
- **public/**: A folder for storing public assets (images, fonts, static files) that will be served with your application. Files placed here are uploaded during sync and accessible at runtime.
|
||||
- **src/**: The main place where you define your application-as-code
|
||||
|
||||
### Entity detection
|
||||
|
||||
The SDK detects entities by parsing your TypeScript files for **`export default define<Entity>({...})`** calls. Each entity type has a corresponding helper function exported from `twenty-sdk`:
|
||||
|
||||
| Helper function | Entity type |
|
||||
|-----------------|-------------|
|
||||
| `defineObject` | Custom object definitions |
|
||||
| `defineLogicFunction` | Logic function definitions |
|
||||
| `definePreInstallLogicFunction` | Pre-install logic function (runs before installation) |
|
||||
| `definePostInstallLogicFunction` | Post-install logic function (runs after installation) |
|
||||
| `defineFrontComponent` | Front component definitions |
|
||||
| `defineRole` | Role definitions |
|
||||
| `defineField` | Field extensions for existing objects |
|
||||
| `defineView` | Saved view definitions |
|
||||
| `defineNavigationMenuItem` | Navigation menu item definitions |
|
||||
| `defineSkill` | AI agent skill definitions |
|
||||
|
||||
<Note>
|
||||
**File naming is flexible.** Entity detection is AST-based — the SDK scans your source files for the `export default define<Entity>({...})` pattern. You can organize your files and folders however you like. Grouping by entity type (e.g., `logic-functions/`, `roles/`) is just a convention for code organization, not a requirement.
|
||||
</Note>
|
||||
|
||||
Example of a detected entity:
|
||||
```typescript
|
||||
// This file can be named anything and placed anywhere in src/
|
||||
import { defineObject, FieldType } from 'twenty-sdk';
|
||||
|
||||
export default defineObject({
|
||||
universalIdentifier: '...',
|
||||
nameSingular: 'postCard',
|
||||
// ... rest of config
|
||||
});
|
||||
```
|
||||
|
||||
Later commands will add more files and folders:
|
||||
|
||||
- `yarn twenty app:dev` will auto-generate two typed API clients in `node_modules/twenty-sdk/generated`: `CoreApiClient` (for workspace data via `/graphql`) and `MetadataApiClient` (for workspace configuration and file uploads via `/metadata`).
|
||||
- `yarn twenty entity:add` will add entity definition files under `src/` for your custom objects, functions, front components, roles, skills, and more.
|
||||
|
||||
## Authentication
|
||||
|
||||
The first time you run `yarn twenty auth:login`, you'll be prompted for:
|
||||
|
||||
- API URL (defaults to http://localhost:3000 or your current workspace profile)
|
||||
- API key
|
||||
|
||||
Your credentials are stored per-user in `~/.twenty/config.json`. You can maintain multiple profiles and switch between them.
|
||||
|
||||
### Managing workspaces
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Login interactively (recommended)
|
||||
yarn twenty auth:login
|
||||
|
||||
# Login to a specific workspace profile
|
||||
yarn twenty auth:login --workspace my-custom-workspace
|
||||
|
||||
# List all configured workspaces
|
||||
yarn twenty auth:list
|
||||
|
||||
# Switch the default workspace (interactive)
|
||||
yarn twenty auth:switch
|
||||
|
||||
# Switch to a specific workspace
|
||||
yarn twenty auth:switch production
|
||||
|
||||
# Check current authentication status
|
||||
yarn twenty auth:status
|
||||
```
|
||||
|
||||
Once you've switched workspaces with `yarn twenty auth:switch`, all subsequent commands will use that workspace by default. You can still override it temporarily with `--workspace <name>`.
|
||||
|
||||
## Manual setup (without the scaffolder)
|
||||
|
||||
While we recommend using `create-twenty-app` for the best getting-started experience, you can also set up a project manually. Do not install the CLI globally. Instead, add `twenty-sdk` as a local dependency and wire a single script in your package.json:
|
||||
|
||||
```bash filename="Terminal"
|
||||
yarn add -D twenty-sdk
|
||||
```
|
||||
|
||||
Then add a `twenty` script:
|
||||
|
||||
```json filename="package.json"
|
||||
{
|
||||
"scripts": {
|
||||
"twenty": "twenty"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Now you can run all commands via `yarn twenty <command>`, e.g. `yarn twenty app:dev`, `yarn twenty help`, etc.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- Authentication errors: run `yarn twenty auth:login` and ensure your API key has the required permissions.
|
||||
- Cannot connect to server: verify the API URL and that the Twenty server is reachable.
|
||||
- Types or client missing/outdated: restart `yarn twenty app:dev` — it auto-generates the typed client.
|
||||
- Dev mode not syncing: ensure `yarn twenty app:dev` is running and that changes are not ignored by your environment.
|
||||
|
||||
Discord Help Channel: https://discord.com/channels/1130383047699738754/1130386664812982322
|
||||
@@ -1,119 +0,0 @@
|
||||
---
|
||||
title: Publishing
|
||||
description: Distribute your Twenty app to the marketplace or deploy it internally.
|
||||
---
|
||||
|
||||
<Warning>
|
||||
Apps are currently in alpha testing. The feature is functional but still evolving.
|
||||
</Warning>
|
||||
|
||||
## Overview
|
||||
|
||||
Once your app is [built and tested locally](/developers/extend/apps/building), you have two paths for distributing it:
|
||||
|
||||
- **Publish to npm** — list your app in the Twenty marketplace for any workspace to discover and install.
|
||||
- **Push a tarball** — deploy your app to a specific Twenty server for internal use without making it publicly available.
|
||||
|
||||
## Publishing to npm
|
||||
|
||||
Publishing to npm makes your app discoverable in the Twenty marketplace. Any Twenty workspace can browse, install, and upgrade marketplace apps directly from the UI.
|
||||
|
||||
### Requirements
|
||||
|
||||
- An [npm](https://www.npmjs.com) account
|
||||
- Your package name **must** use the `twenty-app-` prefix (e.g., `twenty-app-postcard-sender`)
|
||||
|
||||
### Steps
|
||||
|
||||
1. **Build your app** — the CLI compiles your TypeScript sources and generates the application manifest:
|
||||
|
||||
```bash filename="Terminal"
|
||||
yarn twenty app:build
|
||||
```
|
||||
|
||||
2. **Publish to npm** — push the built package to the npm registry:
|
||||
|
||||
```bash filename="Terminal"
|
||||
npx twenty app:publish
|
||||
```
|
||||
|
||||
### Auto-discovery
|
||||
|
||||
Packages with the `twenty-app-` prefix are automatically discovered by the Twenty marketplace catalog. Once published, your app appears in the marketplace within a few minutes — no manual registration or approval required.
|
||||
|
||||
### CI publishing
|
||||
|
||||
The scaffolded project includes a GitHub Actions workflow that publishes on every release. It runs `app:build`, then `npm publish --provenance` from the build output:
|
||||
|
||||
```yaml filename=".github/workflows/publish.yml"
|
||||
name: Publish
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "24"
|
||||
registry-url: https://registry.npmjs.org
|
||||
- run: yarn install --immutable
|
||||
- run: npx twenty app:build
|
||||
- run: npm publish --provenance --access public
|
||||
working-directory: .twenty/output
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
```
|
||||
|
||||
For other CI systems (GitLab CI, CircleCI, etc.), the same three commands apply: `yarn install`, `npx twenty app:build`, then `npm publish` from `.twenty/output`.
|
||||
|
||||
<Tip>
|
||||
**npm provenance** is optional but recommended. Publishing with `--provenance` adds a trust badge to your npm listing, letting users verify the package was built from a specific commit in a public CI pipeline. See the [npm provenance docs](https://docs.npmjs.com/generating-provenance-statements) for setup instructions.
|
||||
</Tip>
|
||||
|
||||
## Internal distribution
|
||||
|
||||
For apps you don't want publicly available — proprietary tools, enterprise-only integrations, or experimental builds — you can push a tarball directly to a Twenty server.
|
||||
|
||||
### Push a tarball
|
||||
|
||||
Build your app and deploy it to a specific server in one step:
|
||||
|
||||
```bash filename="Terminal"
|
||||
npx twenty app:publish --server <server-url>
|
||||
```
|
||||
|
||||
Any workspace on that server can then install and upgrade the app from the **Applications** settings page.
|
||||
|
||||
### Version management
|
||||
|
||||
To release an update:
|
||||
|
||||
1. Bump the `version` field in your `package.json`
|
||||
2. Push a new tarball with `npx twenty app:publish --server <server-url>`
|
||||
3. Workspaces on that server will see the upgrade available in their settings
|
||||
|
||||
<Note>
|
||||
Internal apps are scoped to the server they're pushed to. They won't appear in the public marketplace and can't be installed by workspaces on other servers.
|
||||
</Note>
|
||||
|
||||
## App categories
|
||||
|
||||
Twenty organizes apps into three categories based on how they're distributed:
|
||||
|
||||
| Category | How it works | Visible in marketplace? |
|
||||
|----------|-------------|------------------------|
|
||||
| **Development** | Local dev mode apps running via `yarn twenty app:dev`. Used for building and testing. | No |
|
||||
| **Published** | Apps published to npm with the `twenty-app-` prefix. Listed in the marketplace for any workspace to install. | Yes |
|
||||
| **Internal** | Apps deployed via tarball to a specific server. Available only to workspaces on that server. | No |
|
||||
|
||||
<Tip>
|
||||
Start in **Development** mode while building your app. When it's ready, choose **Published** (npm) for broad distribution or **Internal** (tarball) for private deployment.
|
||||
</Tip>
|
||||
@@ -319,71 +319,6 @@ Key points:
|
||||
but this is not recommended.
|
||||
</Note>
|
||||
|
||||
### Defining fields on existing objects
|
||||
|
||||
Use `defineField()` to add custom fields to existing objects — both standard objects (like `company`, `person`, `opportunity`) and custom objects defined by other apps. Each field lives in its own file and references the target object by its `universalIdentifier`.
|
||||
|
||||
To reference standard objects, import `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS` from `twenty-sdk`. This constant provides stable identifiers for all built-in objects and their fields:
|
||||
|
||||
```typescript
|
||||
// src/fields/apollo-total-funding.field.ts
|
||||
import {
|
||||
defineField,
|
||||
FieldType,
|
||||
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS,
|
||||
} from 'twenty-sdk';
|
||||
|
||||
export default defineField({
|
||||
universalIdentifier: 'c90ae72d-4ddf-4f22-882f-eef98c91e40e',
|
||||
objectUniversalIdentifier:
|
||||
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company.universalIdentifier,
|
||||
type: FieldType.CURRENCY,
|
||||
name: 'apolloTotalFunding',
|
||||
label: 'Total Funding',
|
||||
description: 'Total funding raised by the company',
|
||||
icon: 'IconCash',
|
||||
});
|
||||
```
|
||||
|
||||
Key points:
|
||||
|
||||
- `objectUniversalIdentifier` tells Twenty which object to attach the field to. Use `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.<objectName>.universalIdentifier` for standard objects.
|
||||
- Each field requires its own stable `universalIdentifier`, a `name`, `type`, `label`, and the target `objectUniversalIdentifier`.
|
||||
- You can scaffold new fields using `yarn twenty entity:add` and choosing the field option.
|
||||
- `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS` is also exported as `STANDARD_OBJECT` for convenience — both refer to the same constant.
|
||||
|
||||
Available standard objects include: `attachment`, `blocklist`, `calendarChannel`, `calendarEvent`, `calendarEventParticipant`, `company`, `connectedAccount`, `dashboard`, `favorite`, `favoriteFolder`, `message`, `messageChannel`, `messageParticipant`, `messageThread`, `note`, `noteTarget`, `opportunity`, `person`, `task`, `taskTarget`, `timelineActivity`, `workflow`, `workflowAutomatedTrigger`, `workflowRun`, `workflowVersion`, and `workspaceMember`.
|
||||
|
||||
Each standard object also exposes its field identifiers. For example, to reference a specific field on a standard object in role permissions:
|
||||
|
||||
```typescript
|
||||
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company.fields.name.universalIdentifier
|
||||
```
|
||||
|
||||
#### Relation fields on existing objects
|
||||
|
||||
You can also define relation fields that link existing objects to your custom objects:
|
||||
|
||||
```typescript
|
||||
// src/fields/people-on-call-recording.field.ts
|
||||
import { defineField, FieldType, RelationType, STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS } from 'twenty-sdk';
|
||||
import { CALL_RECORDING_OBJECT_UNIVERSAL_IDENTIFIER } from 'src/objects/call-recording';
|
||||
import { CALL_RECORDING_ON_PERSON_ID } from 'src/fields/call-recording-on-person.field';
|
||||
|
||||
export default defineField({
|
||||
universalIdentifier: '4a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d',
|
||||
objectUniversalIdentifier:
|
||||
CALL_RECORDING_OBJECT_UNIVERSAL_IDENTIFIER,
|
||||
type: FieldType.RELATION,
|
||||
name: 'person',
|
||||
label: 'Person',
|
||||
relationTargetObjectMetadataUniversalIdentifier:
|
||||
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.person.universalIdentifier,
|
||||
relationTargetFieldMetadataUniversalIdentifier:
|
||||
CALL_RECORDING_ON_PERSON_ID,
|
||||
relationType: RelationType.MANY_TO_ONE,
|
||||
});
|
||||
```
|
||||
|
||||
### Application config (application-config.ts)
|
||||
|
||||
@@ -825,255 +760,6 @@ You can create new front components in two ways:
|
||||
- **Scaffolded**: Run `yarn twenty entity:add` and choose the option to add a new front component.
|
||||
- **Manual**: Create a new `.tsx` file and use `defineFrontComponent()`, following the same pattern.
|
||||
|
||||
#### Where front components can be used
|
||||
|
||||
Front components can render in two locations within Twenty:
|
||||
|
||||
- **Side panel** — Non-headless front components open in the right-hand side panel. This is the default behavior when a front component is triggered from the command menu.
|
||||
- **Widgets (dashboards and record pages)** — Front components can be embedded as widgets inside page layouts. When configuring a dashboard or a record page layout, users can add a front component widget.
|
||||
|
||||
#### Headless vs non-headless
|
||||
|
||||
Front components come in two rendering modes controlled by the `isHeadless` option:
|
||||
|
||||
**Non-headless (default)** — The component renders a visible UI. When triggered from the command menu it opens in the side panel. This is the default behavior when `isHeadless` is `false` or omitted.
|
||||
|
||||
**Headless** — The component mounts invisibly in the background. It does not open the side panel. Headless components are designed for actions that execute logic and then unmount themselves — for example, running an async task, navigating to a page, or showing a confirmation modal. They pair naturally with the SDK Command components described below.
|
||||
|
||||
```typescript
|
||||
export default defineFrontComponent({
|
||||
universalIdentifier: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
|
||||
name: 'my-action',
|
||||
description: 'Runs an action without opening the side panel',
|
||||
component: MyAction,
|
||||
isHeadless: true,
|
||||
command: {
|
||||
universalIdentifier: 'b2c3d4e5-f6a7-8901-bcde-f12345678901',
|
||||
label: 'Run my action',
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
#### Adding command menu items
|
||||
|
||||
To make a front component appear as an item in Twenty's command menu, add the `command` property to `defineFrontComponent()`. When users open the command menu (Cmd+K / Ctrl+K), the item shows up and triggers the front component on click.
|
||||
|
||||
The `command` object accepts the following fields:
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `universalIdentifier` | `string` (required) | Unique ID for the command menu item |
|
||||
| `label` | `string` (required) | Display label shown in the command menu |
|
||||
| `icon` | `string` (optional) | Icon name (e.g., `'IconSparkles'`) |
|
||||
| `isPinned` | `boolean` (optional) | Whether the command is pinned at the top of the menu |
|
||||
| `availabilityType` | `'GLOBAL' \| 'RECORD_SELECTION'` (optional) | `GLOBAL` shows the command everywhere; `RECORD_SELECTION` shows it only in record contexts |
|
||||
| `availabilityObjectUniversalIdentifier` | `string` (optional) | Restrict the command to a specific object type (e.g., Person) |
|
||||
|
||||
Here is an example from the call-recording app that adds a command scoped to Person records:
|
||||
|
||||
```typescript
|
||||
import { defineFrontComponent } from 'twenty-sdk';
|
||||
|
||||
export default defineFrontComponent({
|
||||
universalIdentifier: 'c3d4e5f6-a7b8-9012-cdef-123456789012',
|
||||
name: 'Summarize Person Call Recordings',
|
||||
description: 'Generates a summary of call recordings for a person',
|
||||
component: SummarizePersonRecordings,
|
||||
command: {
|
||||
universalIdentifier: 'd4e5f6a7-b8c9-0123-defa-234567890123',
|
||||
label: 'Summarize call recordings',
|
||||
icon: 'IconSparkles',
|
||||
isPinned: false,
|
||||
availabilityType: 'RECORD_SELECTION',
|
||||
availabilityObjectUniversalIdentifier:
|
||||
'20202020-e674-48e5-a542-72570eee7213',
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
When the command is synced, it appears in the command menu. If the front component is non-headless the side panel opens with the component rendered inside. If it is headless the component mounts in the background and executes its logic.
|
||||
|
||||
#### SDK Command components
|
||||
|
||||
The `twenty-sdk` package provides four Command helper components designed for headless front components. Each component executes an action on mount, handles errors by showing a snackbar notification, and automatically unmounts the front component when done.
|
||||
|
||||
Import them from `twenty-sdk/command`:
|
||||
|
||||
- **`Command`** — Runs an async callback via the `execute` prop.
|
||||
- **`CommandLink`** — Navigates to an app path. Props: `to`, `params`, `queryParams`, `options`.
|
||||
- **`CommandModal`** — Opens a confirmation modal. If the user confirms, executes the `execute` callback. Props: `title`, `subtitle`, `execute`, `confirmButtonText`, `confirmButtonAccent`.
|
||||
- **`CommandOpenSidePanelPage`** — Opens a specific side panel page. Props: `page`, `pageTitle`, `pageIcon`.
|
||||
|
||||
Here is a full example of a headless front component using `Command` to run an action from the command menu:
|
||||
|
||||
```typescript
|
||||
// src/front-components/run-action.tsx
|
||||
import { defineFrontComponent } from 'twenty-sdk';
|
||||
import { Command } from 'twenty-sdk/command';
|
||||
import { CoreApiClient } from 'twenty-sdk/clients';
|
||||
|
||||
const RunAction = () => {
|
||||
const execute = async () => {
|
||||
const client = new CoreApiClient();
|
||||
|
||||
await client.mutation({
|
||||
createTask: {
|
||||
__args: { data: { title: 'Created by my app' } },
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return <Command execute={execute} />;
|
||||
};
|
||||
|
||||
export default defineFrontComponent({
|
||||
universalIdentifier: 'e5f6a7b8-c9d0-1234-efab-345678901234',
|
||||
name: 'run-action',
|
||||
description: 'Creates a task from the command menu',
|
||||
component: RunAction,
|
||||
isHeadless: true,
|
||||
command: {
|
||||
universalIdentifier: 'f6a7b8c9-d0e1-2345-fabc-456789012345',
|
||||
label: 'Run my action',
|
||||
icon: 'IconPlayerPlay',
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
And an example using `CommandModal` to ask for confirmation before executing:
|
||||
|
||||
```typescript
|
||||
// src/front-components/delete-draft.tsx
|
||||
import { defineFrontComponent } from 'twenty-sdk';
|
||||
import { CommandModal } from 'twenty-sdk/command';
|
||||
|
||||
const DeleteDraft = () => {
|
||||
const execute = async () => {
|
||||
// perform the deletion
|
||||
};
|
||||
|
||||
return (
|
||||
<CommandModal
|
||||
title="Delete draft?"
|
||||
subtitle="This action cannot be undone."
|
||||
execute={execute}
|
||||
confirmButtonText="Delete"
|
||||
confirmButtonAccent="danger"
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default defineFrontComponent({
|
||||
universalIdentifier: 'a7b8c9d0-e1f2-3456-abcd-567890123456',
|
||||
name: 'delete-draft',
|
||||
description: 'Deletes a draft with confirmation',
|
||||
component: DeleteDraft,
|
||||
isHeadless: true,
|
||||
command: {
|
||||
universalIdentifier: 'b8c9d0e1-f2a3-4567-bcde-678901234567',
|
||||
label: 'Delete draft',
|
||||
icon: 'IconTrash',
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
#### Execution context
|
||||
|
||||
Every front component receives an execution context that provides information about where and how it is running. Access context values using hooks from `twenty-sdk`:
|
||||
|
||||
| Hook | Return type | Description |
|
||||
|------|-------------|-------------|
|
||||
| `useFrontComponentId()` | `string` | The unique ID of the current front component instance |
|
||||
| `useRecordId()` | `string \| null` | The ID of the current record, when the component runs in a record context (e.g., a record page widget or a command scoped to a record). Returns `null` otherwise. |
|
||||
| `useUserId()` | `string \| null` | The ID of the current user |
|
||||
|
||||
```typescript
|
||||
import { useRecordId, useUserId } from 'twenty-sdk';
|
||||
|
||||
const MyWidget = () => {
|
||||
const recordId = useRecordId();
|
||||
const userId = useUserId();
|
||||
|
||||
return (
|
||||
<div>
|
||||
<p>Record: {recordId ?? 'none'}</p>
|
||||
<p>User: {userId ?? 'anonymous'}</p>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
The context is reactive — if the surrounding record changes, hooks automatically return the updated values.
|
||||
|
||||
#### Host API functions
|
||||
|
||||
Front components run in an isolated sandbox but can interact with Twenty's UI through a set of functions provided by the host. Import them directly from `twenty-sdk`:
|
||||
|
||||
```typescript
|
||||
import {
|
||||
navigate,
|
||||
closeSidePanel,
|
||||
enqueueSnackbar,
|
||||
unmountFrontComponent,
|
||||
openSidePanelPage,
|
||||
openCommandConfirmationModal,
|
||||
} from 'twenty-sdk';
|
||||
```
|
||||
|
||||
| Function | Signature | Description |
|
||||
|----------|-----------|-------------|
|
||||
| `navigate` | `(to, params?, queryParams?, options?) => Promise<void>` | Navigate to a typed app path within Twenty |
|
||||
| `closeSidePanel` | `() => Promise<void>` | Close the side panel |
|
||||
| `enqueueSnackbar` | `(params) => Promise<void>` | Show a snackbar notification. Params: `message`, `variant` (`'error'`, `'success'`, `'info'`, `'warning'`), optional `duration`, `detailedMessage`, `dedupeKey` |
|
||||
| `unmountFrontComponent` | `() => Promise<void>` | Unmount the current front component (used by headless components to clean up after execution) |
|
||||
| `openSidePanelPage` | `(params) => Promise<void>` | Open a page in the side panel. Params: `page`, `pageTitle`, `pageIcon`, `shouldResetSearchState` |
|
||||
| `openCommandConfirmationModal` | `(params) => Promise<'confirm' \| 'cancel'>` | Show a confirmation modal and wait for the user's response. Params: `title`, `subtitle`, `confirmButtonText`, `confirmButtonAccent` (`'default'`, `'blue'`, `'danger'`) |
|
||||
|
||||
Here is an example that uses the host API to show a snackbar and close the side panel after an action completes:
|
||||
|
||||
```typescript
|
||||
import { defineFrontComponent, useRecordId } from 'twenty-sdk';
|
||||
import { enqueueSnackbar, closeSidePanel } from 'twenty-sdk';
|
||||
import { CoreApiClient } from 'twenty-sdk/clients';
|
||||
|
||||
const ArchiveRecord = () => {
|
||||
const recordId = useRecordId();
|
||||
|
||||
const handleArchive = async () => {
|
||||
const client = new CoreApiClient();
|
||||
|
||||
await client.mutation({
|
||||
updateTask: {
|
||||
__args: { id: recordId, data: { status: 'ARCHIVED' } },
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
await enqueueSnackbar({
|
||||
message: 'Record archived',
|
||||
variant: 'success',
|
||||
});
|
||||
|
||||
await closeSidePanel();
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ padding: '20px' }}>
|
||||
<p>Archive this record?</p>
|
||||
<button onClick={handleArchive}>Archive</button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default defineFrontComponent({
|
||||
universalIdentifier: 'c9d0e1f2-a3b4-5678-cdef-789012345678',
|
||||
name: 'archive-record',
|
||||
description: 'Archives the current record',
|
||||
component: ArchiveRecord,
|
||||
});
|
||||
```
|
||||
|
||||
### Skills
|
||||
|
||||
Skills define reusable instructions and capabilities that AI agents can use within your workspace. Use `defineSkill()` to define skills with built-in validation:
|
||||
|
||||
@@ -14,18 +14,20 @@ Twenty is designed to be extensible. Use our APIs, webhooks, and app framework t
|
||||
|
||||
- **APIs**: Query and modify your CRM data programmatically using REST or GraphQL
|
||||
- **Webhooks**: Receive real-time notifications when events occur in Twenty
|
||||
- **Apps**: Build custom applications that extend Twenty's capabilities
|
||||
- **Apps**: Build custom applications that extend Twenty's capabilities - Coming soon!
|
||||
|
||||
## Getting Started
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="APIs" icon="code" href="/developers/extend/api">
|
||||
<Card title="APIs" icon="code" href="/developers/extend/capabilities/apis">
|
||||
Connect to Twenty programmatically
|
||||
</Card>
|
||||
<Card title="Webhooks" icon="bell" href="/developers/extend/webhooks">
|
||||
<Card title="Webhooks" icon="bell" href="/developers/extend/capabilities/webhooks">
|
||||
Get notified of events in real-time
|
||||
</Card>
|
||||
<Card title="Apps" icon="puzzle-piece" href="/developers/extend/apps/getting-started">
|
||||
Build customizations as code
|
||||
<Card title="Apps" icon="puzzle-piece" href="/developers/extend/capabilities/apps">
|
||||
Build customizations as code (Alpha)
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
---
|
||||
title: Webhooks
|
||||
description: Receive real-time notifications when events occur in your CRM.
|
||||
---
|
||||
|
||||
import { VimeoEmbed } from '/snippets/vimeo-embed.mdx';
|
||||
|
||||
|
||||
Webhooks push data to your systems in real-time when events occur in Twenty — no polling required. Use them to keep external systems in sync, trigger automations, or send alerts.
|
||||
|
||||
## Create a Webhook
|
||||
|
||||
1. Go to **Settings → APIs & Webhooks → Webhooks**
|
||||
2. Click **+ Create webhook**
|
||||
3. Enter your webhook URL (must be publicly accessible)
|
||||
4. Click **Save**
|
||||
|
||||
The webhook activates immediately and starts sending notifications.
|
||||
|
||||
<VimeoEmbed videoId="928786708" title="Creating a webhook" />
|
||||
|
||||
### Manage Webhooks
|
||||
|
||||
**Edit**: Click the webhook → Update URL → **Save**
|
||||
|
||||
**Delete**: Click the webhook → **Delete** → Confirm
|
||||
|
||||
## Events
|
||||
|
||||
Twenty sends webhooks for these event types:
|
||||
|
||||
| Event | Example |
|
||||
|-------|---------|
|
||||
| **Record Created** | `person.created`, `company.created`, `note.created` |
|
||||
| **Record Updated** | `person.updated`, `company.updated`, `opportunity.updated` |
|
||||
| **Record Deleted** | `person.deleted`, `company.deleted` |
|
||||
|
||||
All event types are sent to your webhook URL. Event filtering may be added in future releases.
|
||||
|
||||
## Payload Format
|
||||
|
||||
Each webhook sends an HTTP POST with a JSON body:
|
||||
|
||||
```json
|
||||
{
|
||||
"event": "person.created",
|
||||
"data": {
|
||||
"id": "abc12345",
|
||||
"firstName": "Alice",
|
||||
"lastName": "Doe",
|
||||
"email": "alice@example.com",
|
||||
"createdAt": "2025-02-10T15:30:45Z",
|
||||
"createdBy": "user_123"
|
||||
},
|
||||
"timestamp": "2025-02-10T15:30:50Z"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Description |
|
||||
|-------|-------------|
|
||||
| `event` | What happened (e.g., `person.created`) |
|
||||
| `data` | The full record that was created/updated/deleted |
|
||||
| `timestamp` | When the event occurred (UTC) |
|
||||
|
||||
<Note>
|
||||
Respond with a **2xx HTTP status** (200-299) to acknowledge receipt. Non-2xx responses are logged as delivery failures.
|
||||
</Note>
|
||||
|
||||
## Webhook Validation
|
||||
|
||||
Twenty signs each webhook request for security. Validate signatures to ensure requests are authentic.
|
||||
|
||||
### Headers
|
||||
|
||||
| Header | Description |
|
||||
|--------|-------------|
|
||||
| `X-Twenty-Webhook-Signature` | HMAC SHA256 signature |
|
||||
| `X-Twenty-Webhook-Timestamp` | Request timestamp |
|
||||
|
||||
### Validation Steps
|
||||
|
||||
1. Get the timestamp from `X-Twenty-Webhook-Timestamp`
|
||||
2. Create the string: `{timestamp}:{JSON payload}`
|
||||
3. Compute HMAC SHA256 using your webhook secret
|
||||
4. Compare with `X-Twenty-Webhook-Signature`
|
||||
|
||||
### Example (Node.js)
|
||||
|
||||
```javascript
|
||||
const crypto = require("crypto");
|
||||
|
||||
const timestamp = req.headers["x-twenty-webhook-timestamp"];
|
||||
const payload = JSON.stringify(req.body);
|
||||
const secret = "your-webhook-secret";
|
||||
|
||||
const stringToSign = `${timestamp}:${payload}`;
|
||||
const expectedSignature = crypto
|
||||
.createHmac("sha256", secret)
|
||||
.update(stringToSign)
|
||||
.digest("hex");
|
||||
|
||||
const receivedSignature = req.headers["x-twenty-webhook-signature"];
|
||||
const isValid = crypto.timingSafeEqual(
|
||||
Buffer.from(expectedSignature, "hex"),
|
||||
Buffer.from(receivedSignature, "hex")
|
||||
);
|
||||
```
|
||||
|
||||
## Webhooks vs Workflows
|
||||
|
||||
| Method | Direction | Use Case |
|
||||
|--------|-----------|----------|
|
||||
| **Webhooks** | OUT | Automatically notify external systems of any record change |
|
||||
| **Workflow + HTTP Request** | OUT | Send data out with custom logic (filters, transformations) |
|
||||
| **Workflow Webhook Trigger** | IN | Receive data into Twenty from external systems |
|
||||
|
||||
For receiving external data, see [Set Up a Webhook Trigger](/user-guide/workflows/how-tos/connect-to-other-tools/set-up-a-webhook-trigger).
|
||||
+76
-106
@@ -358,14 +358,13 @@
|
||||
"group": "Extend",
|
||||
"icon": "plug",
|
||||
"pages": [
|
||||
"developers/extend/api",
|
||||
"developers/extend/webhooks",
|
||||
"developers/extend/extend",
|
||||
{
|
||||
"group": "Apps",
|
||||
"group": "Capabilities",
|
||||
"pages": [
|
||||
"developers/extend/apps/getting-started",
|
||||
"developers/extend/apps/building",
|
||||
"developers/extend/apps/publishing"
|
||||
"developers/extend/capabilities/apis",
|
||||
"developers/extend/capabilities/webhooks",
|
||||
"developers/extend/capabilities/apps"
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -804,14 +803,13 @@
|
||||
"group": "Étendre",
|
||||
"icon": "plug",
|
||||
"pages": [
|
||||
"l/fr/developers/extend/api",
|
||||
"l/fr/developers/extend/webhooks",
|
||||
"l/fr/developers/extend/extend",
|
||||
{
|
||||
"group": "Apps",
|
||||
"group": "Capacités",
|
||||
"pages": [
|
||||
"l/fr/developers/extend/apps/getting-started",
|
||||
"l/fr/developers/extend/apps/building",
|
||||
"l/fr/developers/extend/apps/publishing"
|
||||
"l/fr/developers/extend/capabilities/apis",
|
||||
"l/fr/developers/extend/capabilities/webhooks",
|
||||
"l/fr/developers/extend/capabilities/apps"
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -1250,14 +1248,13 @@
|
||||
"group": "التوسيع",
|
||||
"icon": "plug",
|
||||
"pages": [
|
||||
"l/ar/developers/extend/api",
|
||||
"l/ar/developers/extend/webhooks",
|
||||
"l/ar/developers/extend/extend",
|
||||
{
|
||||
"group": "التطبيقات",
|
||||
"group": "القدرات",
|
||||
"pages": [
|
||||
"l/ar/developers/extend/apps/getting-started",
|
||||
"l/ar/developers/extend/apps/building",
|
||||
"l/ar/developers/extend/apps/publishing"
|
||||
"l/ar/developers/extend/capabilities/apis",
|
||||
"l/ar/developers/extend/capabilities/webhooks",
|
||||
"l/ar/developers/extend/capabilities/apps"
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -1696,14 +1693,13 @@
|
||||
"group": "Rozšíření",
|
||||
"icon": "plug",
|
||||
"pages": [
|
||||
"l/cs/developers/extend/api",
|
||||
"l/cs/developers/extend/webhooks",
|
||||
"l/cs/developers/extend/extend",
|
||||
{
|
||||
"group": "Apps",
|
||||
"group": "Možnosti",
|
||||
"pages": [
|
||||
"l/cs/developers/extend/apps/getting-started",
|
||||
"l/cs/developers/extend/apps/building",
|
||||
"l/cs/developers/extend/apps/publishing"
|
||||
"l/cs/developers/extend/capabilities/apis",
|
||||
"l/cs/developers/extend/capabilities/webhooks",
|
||||
"l/cs/developers/extend/capabilities/apps"
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -2142,14 +2138,13 @@
|
||||
"group": "Erweitern",
|
||||
"icon": "plug",
|
||||
"pages": [
|
||||
"l/de/developers/extend/api",
|
||||
"l/de/developers/extend/webhooks",
|
||||
"l/de/developers/extend/extend",
|
||||
{
|
||||
"group": "Apps",
|
||||
"group": "Funktionen",
|
||||
"pages": [
|
||||
"l/de/developers/extend/apps/getting-started",
|
||||
"l/de/developers/extend/apps/building",
|
||||
"l/de/developers/extend/apps/publishing"
|
||||
"l/de/developers/extend/capabilities/apis",
|
||||
"l/de/developers/extend/capabilities/webhooks",
|
||||
"l/de/developers/extend/capabilities/apps"
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -2588,14 +2583,13 @@
|
||||
"group": "Ampliar",
|
||||
"icon": "plug",
|
||||
"pages": [
|
||||
"l/es/developers/extend/api",
|
||||
"l/es/developers/extend/webhooks",
|
||||
"l/es/developers/extend/extend",
|
||||
{
|
||||
"group": "Apps",
|
||||
"group": "Capacidades",
|
||||
"pages": [
|
||||
"l/es/developers/extend/apps/getting-started",
|
||||
"l/es/developers/extend/apps/building",
|
||||
"l/es/developers/extend/apps/publishing"
|
||||
"l/es/developers/extend/capabilities/apis",
|
||||
"l/es/developers/extend/capabilities/webhooks",
|
||||
"l/es/developers/extend/capabilities/apps"
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -3034,14 +3028,13 @@
|
||||
"group": "Estendi",
|
||||
"icon": "plug",
|
||||
"pages": [
|
||||
"l/it/developers/extend/api",
|
||||
"l/it/developers/extend/webhooks",
|
||||
"l/it/developers/extend/extend",
|
||||
{
|
||||
"group": "App",
|
||||
"group": "Funzionalità",
|
||||
"pages": [
|
||||
"l/it/developers/extend/apps/getting-started",
|
||||
"l/it/developers/extend/apps/building",
|
||||
"l/it/developers/extend/apps/publishing"
|
||||
"l/it/developers/extend/capabilities/apis",
|
||||
"l/it/developers/extend/capabilities/webhooks",
|
||||
"l/it/developers/extend/capabilities/apps"
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -3480,14 +3473,13 @@
|
||||
"group": "拡張",
|
||||
"icon": "plug",
|
||||
"pages": [
|
||||
"l/ja/developers/extend/api",
|
||||
"l/ja/developers/extend/webhooks",
|
||||
"l/ja/developers/extend/extend",
|
||||
{
|
||||
"group": "Apps",
|
||||
"group": "機能",
|
||||
"pages": [
|
||||
"l/ja/developers/extend/apps/getting-started",
|
||||
"l/ja/developers/extend/apps/building",
|
||||
"l/ja/developers/extend/apps/publishing"
|
||||
"l/ja/developers/extend/capabilities/apis",
|
||||
"l/ja/developers/extend/capabilities/webhooks",
|
||||
"l/ja/developers/extend/capabilities/apps"
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -3926,14 +3918,13 @@
|
||||
"group": "확장",
|
||||
"icon": "plug",
|
||||
"pages": [
|
||||
"l/ko/developers/extend/api",
|
||||
"l/ko/developers/extend/webhooks",
|
||||
"l/ko/developers/extend/extend",
|
||||
{
|
||||
"group": "Apps",
|
||||
"group": "기능",
|
||||
"pages": [
|
||||
"l/ko/developers/extend/apps/getting-started",
|
||||
"l/ko/developers/extend/apps/building",
|
||||
"l/ko/developers/extend/apps/publishing"
|
||||
"l/ko/developers/extend/capabilities/apis",
|
||||
"l/ko/developers/extend/capabilities/webhooks",
|
||||
"l/ko/developers/extend/capabilities/apps"
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -4372,14 +4363,13 @@
|
||||
"group": "Extend",
|
||||
"icon": "plug",
|
||||
"pages": [
|
||||
"l/pt/developers/extend/api",
|
||||
"l/pt/developers/extend/webhooks",
|
||||
"l/pt/developers/extend/extend",
|
||||
{
|
||||
"group": "Aplicativos",
|
||||
"group": "Capabilities",
|
||||
"pages": [
|
||||
"l/pt/developers/extend/apps/getting-started",
|
||||
"l/pt/developers/extend/apps/building",
|
||||
"l/pt/developers/extend/apps/publishing"
|
||||
"l/pt/developers/extend/capabilities/apis",
|
||||
"l/pt/developers/extend/capabilities/webhooks",
|
||||
"l/pt/developers/extend/capabilities/apps"
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -4818,14 +4808,13 @@
|
||||
"group": "Extend",
|
||||
"icon": "plug",
|
||||
"pages": [
|
||||
"l/ro/developers/extend/api",
|
||||
"l/ro/developers/extend/webhooks",
|
||||
"l/ro/developers/extend/extend",
|
||||
{
|
||||
"group": "Aplicații",
|
||||
"group": "Capabilities",
|
||||
"pages": [
|
||||
"l/ro/developers/extend/apps/getting-started",
|
||||
"l/ro/developers/extend/apps/building",
|
||||
"l/ro/developers/extend/apps/publishing"
|
||||
"l/ro/developers/extend/capabilities/apis",
|
||||
"l/ro/developers/extend/capabilities/webhooks",
|
||||
"l/ro/developers/extend/capabilities/apps"
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -5264,14 +5253,13 @@
|
||||
"group": "Расширяйте",
|
||||
"icon": "plug",
|
||||
"pages": [
|
||||
"l/ru/developers/extend/api",
|
||||
"l/ru/developers/extend/webhooks",
|
||||
"l/ru/developers/extend/extend",
|
||||
{
|
||||
"group": "Приложения",
|
||||
"group": "Возможности",
|
||||
"pages": [
|
||||
"l/ru/developers/extend/apps/getting-started",
|
||||
"l/ru/developers/extend/apps/building",
|
||||
"l/ru/developers/extend/apps/publishing"
|
||||
"l/ru/developers/extend/capabilities/apis",
|
||||
"l/ru/developers/extend/capabilities/webhooks",
|
||||
"l/ru/developers/extend/capabilities/apps"
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -5710,14 +5698,13 @@
|
||||
"group": "Genişlet",
|
||||
"icon": "plug",
|
||||
"pages": [
|
||||
"l/tr/developers/extend/api",
|
||||
"l/tr/developers/extend/webhooks",
|
||||
"l/tr/developers/extend/extend",
|
||||
{
|
||||
"group": "Uygulamalar",
|
||||
"group": "Yetkinlikler",
|
||||
"pages": [
|
||||
"l/tr/developers/extend/apps/getting-started",
|
||||
"l/tr/developers/extend/apps/building",
|
||||
"l/tr/developers/extend/apps/publishing"
|
||||
"l/tr/developers/extend/capabilities/apis",
|
||||
"l/tr/developers/extend/capabilities/webhooks",
|
||||
"l/tr/developers/extend/capabilities/apps"
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -6156,14 +6143,13 @@
|
||||
"group": "扩展",
|
||||
"icon": "plug",
|
||||
"pages": [
|
||||
"l/zh/developers/extend/api",
|
||||
"l/zh/developers/extend/webhooks",
|
||||
"l/zh/developers/extend/extend",
|
||||
{
|
||||
"group": "应用",
|
||||
"group": "功能",
|
||||
"pages": [
|
||||
"l/zh/developers/extend/apps/getting-started",
|
||||
"l/zh/developers/extend/apps/building",
|
||||
"l/zh/developers/extend/apps/publishing"
|
||||
"l/zh/developers/extend/capabilities/apis",
|
||||
"l/zh/developers/extend/capabilities/webhooks",
|
||||
"l/zh/developers/extend/capabilities/apps"
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -6286,22 +6272,6 @@
|
||||
}
|
||||
},
|
||||
"redirects": [
|
||||
{
|
||||
"source": "/developers/extend/capabilities/api",
|
||||
"destination": "/developers/extend/api"
|
||||
},
|
||||
{
|
||||
"source": "/developers/extend/capabilities/apis",
|
||||
"destination": "/developers/extend/api"
|
||||
},
|
||||
{
|
||||
"source": "/developers/extend/capabilities/webhooks",
|
||||
"destination": "/developers/extend/webhooks"
|
||||
},
|
||||
{
|
||||
"source": "/developers/extend/capabilities/apps",
|
||||
"destination": "/developers/extend/apps/getting-started"
|
||||
},
|
||||
{
|
||||
"source": "/developers/local-setup",
|
||||
"destination": "/developers/contribute/capabilities/local-setup"
|
||||
@@ -6332,27 +6302,27 @@
|
||||
},
|
||||
{
|
||||
"source": "/developers/api-and-webhooks",
|
||||
"destination": "/developers/extend/api"
|
||||
"destination": "/developers/extend/extend"
|
||||
},
|
||||
{
|
||||
"source": "/developers/api-and-webhooks/apis-overview",
|
||||
"destination": "/developers/extend/api"
|
||||
"destination": "/developers/extend/capabilities/apis"
|
||||
},
|
||||
{
|
||||
"source": "/developers/api-and-webhooks/api",
|
||||
"destination": "/developers/extend/api"
|
||||
"destination": "/developers/extend/capabilities/apis"
|
||||
},
|
||||
{
|
||||
"source": "/developers/api-and-webhooks/api-keys",
|
||||
"destination": "/developers/extend/api"
|
||||
"destination": "/developers/extend/capabilities/apis"
|
||||
},
|
||||
{
|
||||
"source": "/developers/api-and-webhooks/webhooks",
|
||||
"destination": "/developers/extend/webhooks"
|
||||
"destination": "/developers/extend/capabilities/webhooks"
|
||||
},
|
||||
{
|
||||
"source": "/developers/api-and-webhooks/integrations",
|
||||
"destination": "/developers/extend/api"
|
||||
"destination": "/developers/extend/capabilities/apis"
|
||||
},
|
||||
{
|
||||
"source": "/developers/bugs-and-requests",
|
||||
|
||||
@@ -1,147 +0,0 @@
|
||||
---
|
||||
title: واجهات برمجة التطبيقات
|
||||
description: استعلم وعدّل بيانات إدارة علاقات العملاء (CRM) لديك برمجياً باستخدام REST أو GraphQL.
|
||||
---
|
||||
|
||||
import { VimeoEmbed } from '/snippets/vimeo-embed.mdx';
|
||||
|
||||
تم تصميم Twenty ليكون صديقًا للمطورين، حيث يوفر واجهات برمجة قوية تتكيف مع نموذج البيانات المخصص. نحن نوفر أربعة أنواع متميزة من واجهات برمجة التطبيقات لتلبية احتياجات التكامل المختلفة.
|
||||
|
||||
## نهج المطوّر أولاً
|
||||
|
||||
تقوم Twenty بإنشاء واجهات برمجة التطبيقات خصيصاً لنموذج بياناتك:
|
||||
|
||||
* **لا حاجة إلى معرفات طويلة**: استخدم أسماء الكائنات والحقول مباشرة في نقاط النهاية
|
||||
* **معاملة متساوية للكائنات القياسية والمخصصة**: تحصل كائناتك المخصصة على نفس معاملة واجهة برمجة التطبيقات كما هو الحال مع الكائنات المضمنة
|
||||
* **نقاط نهاية مخصصة**: يحصل كل كائن وحقل على نقطة نهاية API الخاصة به
|
||||
* **وثائق مخصصة**: يتم إنشاؤها خصيصًا لنموذج بيانات مساحة عملك
|
||||
|
||||
<Note>
|
||||
وثائق واجهة برمجة التطبيقات المخصصة لك متاحة ضمن **الإعدادات → واجهات برمجة التطبيقات وخطافات الويب** بعد إنشاء مفتاح API. نظرًا لأن Twenty تُنشئ واجهات برمجة تطبيقات تتطابق مع نموذج البيانات المخصص لديك، فإن الوثائق فريدة لمساحة عملك.
|
||||
</Note>
|
||||
|
||||
## نوعا واجهات برمجة التطبيقات
|
||||
|
||||
### واجهة برمجة التطبيقات الأساسية
|
||||
|
||||
يتم الوصول إليها عبر `/rest/` أو `/graphql/`
|
||||
|
||||
تعامَل مع **السجلات** الفعلية لديك (البيانات):
|
||||
|
||||
* إنشاء وقراءة وتحديث وحذف الأشخاص والشركات والفرص، إلخ.
|
||||
* استعلام وتصفية البيانات
|
||||
* إدارة العلاقات بين السجلات
|
||||
|
||||
### واجهة برمجة البيانات الوصفية
|
||||
|
||||
يتم الوصول إليها عبر `/rest/metadata/` أو `/metadata/`
|
||||
|
||||
إدارة **مساحة العمل ونموذج البيانات** لديك:
|
||||
|
||||
* إنشاء أو تعديل أو حذف الكائنات والحقول
|
||||
* تكوين إعدادات مساحة العمل
|
||||
* تعريف العلاقات بين الكائنات
|
||||
|
||||
## REST مقابل GraphQL
|
||||
|
||||
تتوفر واجهات برمجة التطبيقات الأساسية وواجهات البيانات الوصفية بصيغتي REST وGraphQL:
|
||||
|
||||
| التنسيق | العمليات المتاحة |
|
||||
| ----------- | ----------------------------------------------------------------------------- |
|
||||
| **REST** | CRUD، عمليات الدفعات، إدراج/تحديث |
|
||||
| **GraphQL** | نفس الشيء + **عمليات إدراج/تحديث مجمعة**، واستعلامات العلاقات في استدعاء واحد |
|
||||
|
||||
اختر بناءً على احتياجاتك — كلا الصيغتين تصلان إلى البيانات نفسها.
|
||||
|
||||
## نقاط نهاية API
|
||||
|
||||
| البيئة | عنوان URL الأساسي |
|
||||
| --------------------- | ------------------------- |
|
||||
| **السحابة** | `https://api.twenty.com/` |
|
||||
| **الاستضافة الذاتية** | `https://{your-domain}/` |
|
||||
|
||||
## المصادقة
|
||||
|
||||
كل طلب API يتطلب تضمين مفتاح API في رأس الطلب:
|
||||
|
||||
```
|
||||
Authorization: Bearer YOUR_API_KEY
|
||||
```
|
||||
|
||||
### قم بإنشاء مفتاح API
|
||||
|
||||
1. انتقل إلى **الإعدادات → واجهات برمجة التطبيقات وخطافات الويب**
|
||||
2. انقر على **+ إنشاء مفتاح**
|
||||
3. التكوين:
|
||||
* **الاسم**: اسم وصفي للمفتاح
|
||||
* **تاريخ الانتهاء**: متى تنتهي صلاحية المفتاح
|
||||
4. انقر على **حفظ**
|
||||
5. **انسخه فوراً** — يظهر المفتاح مرة واحدة فقط
|
||||
|
||||
<VimeoEmbed videoId="928786722" title="إنشاء مفتاح API" />
|
||||
|
||||
<Warning>
|
||||
يمنح مفتاح API الخاص بك الوصول إلى بيانات حساسة. لا تشاركه مع خدمات غير موثوقة. إذا تم اختراقه، عطّلْه فوراً وأنشئ مفتاحاً جديداً.
|
||||
</Warning>
|
||||
|
||||
### تعيين دور لمفتاح API
|
||||
|
||||
لتحسين الأمان، عيّن دوراً محدداً لتقييد الوصول:
|
||||
|
||||
1. اذهب إلى **الإعدادات → الأدوار**
|
||||
2. انقر على الدور الذي ترغب في تعيينه
|
||||
3. افتح علامة التبويب **التعيين**
|
||||
4. ضمن **مفاتيح API**، انقر على **+ تعيين إلى مفتاح API**
|
||||
5. حدد مفتاح API
|
||||
|
||||
سيرث المفتاح أذونات ذلك الدور. راجع [الأذونات](/l/ar/user-guide/permissions-access/capabilities/permissions) للحصول على التفاصيل.
|
||||
|
||||
### إدارة مفاتيح API
|
||||
|
||||
**إعادة التوليد**: الإعدادات → واجهات برمجة التطبيقات وخطافات الويب → انقر على المفتاح → **إعادة التوليد**
|
||||
|
||||
**حذف**: الإعدادات → واجهات برمجة التطبيقات وخطافات الويب → انقر على المفتاح → **حذف**
|
||||
|
||||
## ملعب واجهة برمجة التطبيقات
|
||||
|
||||
اختبر واجهات برمجة التطبيقات لديك مباشرة في المتصفح باستخدام الملعب المدمج لدينا — متاح لكلٍ من **REST** و**GraphQL**.
|
||||
|
||||
### الوصول إلى الملعب
|
||||
|
||||
1. انتقل إلى **الإعدادات → واجهات برمجة التطبيقات وخطافات الويب**
|
||||
2. أنشئ مفتاح API (مطلوب)
|
||||
3. انقر على **REST API** أو **GraphQL API** لفتح الملعب
|
||||
|
||||
### ما الذي ستحصل عليه
|
||||
|
||||
* **وثائق تفاعلية**: يتم إنشاؤها لنموذج البيانات المحدد لديك
|
||||
* **اختبارات حيّة**: تنفيذ استدعاءات API فعلية على مساحة عملك
|
||||
* **مستكشف المخطط**: تصفح الكائنات والحقول والعلاقات المتاحة
|
||||
* **منشئ الطلبات**: أنشئ الاستعلامات مع الإكمال التلقائي
|
||||
|
||||
يعكس الملعب الكائنات والحقول المخصصة لديك، لذا تكون الوثائق دائماً دقيقة لمساحة عملك.
|
||||
|
||||
## عمليات الدفعات
|
||||
|
||||
كلٌ من REST وGraphQL يدعمان عمليات الدفعات:
|
||||
|
||||
* **حجم الدفعة**: حتى 60 سجل لكل طلب
|
||||
* **العمليات**: إنشاء وتحديث وحذف سجلات متعددة
|
||||
|
||||
**ميزات خاصة بـ GraphQL:**
|
||||
|
||||
* **إدراج/تحديث دفعي**: إنشاء أو تحديث في استدعاء واحد
|
||||
* استخدم الأسماء الجمع للكائنات (على سبيل المثال، `CreateCompanies` بدلاً من `CreateCompany`)
|
||||
|
||||
## حدود المعدل
|
||||
|
||||
يتم تنظيم طلبات API لضمان استقرار المنصة:
|
||||
|
||||
| الحد | القيمة |
|
||||
| -------------- | ---------------------- |
|
||||
| **الطلبات** | 100 استدعاء في الدقيقة |
|
||||
| **حجم الدفعة** | 60 سجل لكل استدعاء |
|
||||
|
||||
<Tip>
|
||||
استخدم عمليات الدفعات لزيادة الإنتاجية — عالج ما يصل إلى 60 سجلًا في استدعاء API واحد بدلاً من إجراء طلبات فردية.
|
||||
</Tip>
|
||||
@@ -1,689 +0,0 @@
|
||||
---
|
||||
title: بناء التطبيقات
|
||||
description: عرّف الكائنات، والدوال المنطقية، ومكوّنات الواجهة الأمامية، وغير ذلك باستخدام Twenty SDK.
|
||||
---
|
||||
|
||||
<Warning>
|
||||
التطبيقات حاليًا في مرحلة الاختبار الألفا. الميزة تعمل لكنها لا تزال قيد التطور.
|
||||
</Warning>
|
||||
|
||||
## استخدم موارد SDK (الأنواع والتكوين)
|
||||
|
||||
يوفّر twenty-sdk كتلَ بناءٍ مضبوطة الأنواع ودوال مساعدة تستخدمها داخل تطبيقك. فيما يلي الأجزاء الأساسية التي ستتعامل معها غالبًا.
|
||||
|
||||
### دوال مساعدة
|
||||
|
||||
يوفّر SDK دوالًا مساعدة لتعريف كيانات تطبيقك. كما هو موضح في [اكتشاف الكيانات](/l/ar/developers/extend/apps/getting-started#entity-detection)، يجب استخدام `export default define<Entity>({...})` كي يتم اكتشاف كياناتك:
|
||||
|
||||
| دالة | الغرض |
|
||||
| -------------------------------- | ---------------------------------------------------- |
|
||||
| `defineApplication` | تهيئة بيانات التعريف للتطبيق (مطلوب، واحد لكل تطبيق) |
|
||||
| `defineObject` | تعريف كائنات مخصصة مع حقول |
|
||||
| `defineLogicFunction` | تعريف وظائف منطقية مع معالجات |
|
||||
| `definePreInstallLogicFunction` | تعريف دالة منطقية لما قبل التثبيت (واحدة لكل تطبيق) |
|
||||
| `definePostInstallLogicFunction` | تعريف دالة منطقية لما بعد التثبيت (واحدة لكل تطبيق) |
|
||||
| `defineFrontComponent` | عرِّف مكوّنات أمامية لواجهة مستخدم مخصّصة |
|
||||
| `defineRole` | تهيئة صلاحيات الدور والوصول إلى الكائنات |
|
||||
| `defineField` | وسّع الكائنات الموجودة بحقول إضافية |
|
||||
| `defineView` | تعريف العروض المحفوظة للكائنات |
|
||||
| `defineNavigationMenuItem` | تعريف روابط التنقل في الشريط الجانبي |
|
||||
| `defineSkill` | عرّف مهارات وكيل الذكاء الاصطناعي |
|
||||
|
||||
تتحقق هذه الدوال من تكوينك وقت البناء وتوفّر إكمالًا تلقائيًا في بيئة التطوير وأمان الأنواع.
|
||||
|
||||
### تعريف الكائنات
|
||||
|
||||
تصف الكائنات المخصصة كلًا من المخطط والسلوك للسجلات في مساحة عملك. استخدم `defineObject()` لتعريف كائنات مع تحقق مدمج:
|
||||
|
||||
```typescript
|
||||
// src/app/postCard.object.ts
|
||||
import { defineObject, FieldType } from 'twenty-sdk';
|
||||
|
||||
enum PostCardStatus {
|
||||
DRAFT = 'DRAFT',
|
||||
SENT = 'SENT',
|
||||
DELIVERED = 'DELIVERED',
|
||||
RETURNED = 'RETURNED',
|
||||
}
|
||||
|
||||
export default defineObject({
|
||||
universalIdentifier: '54b589ca-eeed-4950-a176-358418b85c05',
|
||||
nameSingular: 'postCard',
|
||||
namePlural: 'postCards',
|
||||
labelSingular: 'Post Card',
|
||||
labelPlural: 'Post Cards',
|
||||
description: 'A post card object',
|
||||
icon: 'IconMail',
|
||||
fields: [
|
||||
{
|
||||
universalIdentifier: '58a0a314-d7ea-4865-9850-7fb84e72f30b',
|
||||
name: 'content',
|
||||
type: FieldType.TEXT,
|
||||
label: 'Content',
|
||||
description: "Postcard's content",
|
||||
icon: 'IconAbc',
|
||||
},
|
||||
{
|
||||
universalIdentifier: 'c6aa31f3-da76-4ac6-889f-475e226009ac',
|
||||
name: 'recipientName',
|
||||
type: FieldType.FULL_NAME,
|
||||
label: 'Recipient name',
|
||||
icon: 'IconUser',
|
||||
},
|
||||
{
|
||||
universalIdentifier: '95045777-a0ad-49ec-98f9-22f9fc0c8266',
|
||||
name: 'recipientAddress',
|
||||
type: FieldType.ADDRESS,
|
||||
label: 'Recipient address',
|
||||
icon: 'IconHome',
|
||||
},
|
||||
{
|
||||
universalIdentifier: '87b675b8-dd8c-4448-b4ca-20e5a2234a1e',
|
||||
name: 'status',
|
||||
type: FieldType.SELECT,
|
||||
label: 'Status',
|
||||
icon: 'IconSend',
|
||||
defaultValue: `'${PostCardStatus.DRAFT}'`,
|
||||
options: [
|
||||
{ value: PostCardStatus.DRAFT, label: 'Draft', position: 0, color: 'gray' },
|
||||
{ value: PostCardStatus.SENT, label: 'Sent', position: 1, color: 'orange' },
|
||||
{ value: PostCardStatus.DELIVERED, label: 'Delivered', position: 2, color: 'green' },
|
||||
{ value: PostCardStatus.RETURNED, label: 'Returned', position: 3, color: 'orange' },
|
||||
],
|
||||
},
|
||||
{
|
||||
universalIdentifier: 'e06abe72-5b44-4e7f-93be-afc185a3c433',
|
||||
name: 'deliveredAt',
|
||||
type: FieldType.DATE_TIME,
|
||||
label: 'Delivered at',
|
||||
icon: 'IconCheck',
|
||||
isNullable: true,
|
||||
defaultValue: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
النقاط الرئيسية:
|
||||
|
||||
* استخدم `defineObject()` للحصول على تحقق مدمج ودعم أفضل من IDE.
|
||||
* `universalIdentifier` يجب أن يكون فريدًا وثابتًا عبر عمليات النشر.
|
||||
* يتطلب كل حقل `name` و`type` و`label` ومعرّف `universalIdentifier` ثابتًا خاصًا به.
|
||||
* المصفوفة `fields` اختيارية — يمكنك تعريف كائنات بدون حقول مخصصة.
|
||||
* يمكنك إنشاء كائنات جديدة باستخدام `yarn twenty entity:add`، والذي يرشدك خلال التسمية والحقول والعلاقات.
|
||||
|
||||
<Note>
|
||||
**يتم إنشاء الحقول الأساسية تلقائيًا.** عند تعريف كائن مخصص، يضيف Twenty تلقائيًا حقولًا قياسية
|
||||
مثل `id` و`name` و`createdAt` و`updatedAt` و`createdBy` و`updatedBy` و`deletedAt`.
|
||||
لا تحتاج إلى تعريف هذه في مصفوفة `fields` — أضف فقط حقولك المخصصة.
|
||||
يمكنك تجاوز الحقول الافتراضية من خلال تعريف حقل بالاسم نفسه في مصفوفة `fields` الخاصة بك،
|
||||
لكن هذا غير مستحسن.
|
||||
</Note>
|
||||
|
||||
### تكوين التطبيق (application-config.ts)
|
||||
|
||||
كل تطبيق لديه ملف واحد `application-config.ts` يصف:
|
||||
|
||||
* **هوية التطبيق**: المعرفات، اسم العرض، والوصف.
|
||||
* **كيفية تشغيل وظائفه**: الدور الذي تستخدمه للأذونات.
|
||||
* **متغيرات (اختياري)**: أزواج مفتاح-قيمة تُعرض لوظائفك كمتغيرات بيئة.
|
||||
* **(اختياري) دالة ما قبل التثبيت**: دالة منطقية تعمل قبل تثبيت التطبيق.
|
||||
* **(اختياري) دالة ما بعد التثبيت**: دالة منطقية تعمل بعد تثبيت التطبيق.
|
||||
|
||||
استخدم `defineApplication()` لتعريف تهيئة تطبيقك:
|
||||
|
||||
```typescript
|
||||
// src/application-config.ts
|
||||
import { defineApplication } from 'twenty-sdk';
|
||||
import { DEFAULT_ROLE_UNIVERSAL_IDENTIFIER } from 'src/roles/default-role';
|
||||
|
||||
export default defineApplication({
|
||||
universalIdentifier: '4ec0391d-18d5-411c-b2f3-266ddc1c3ef7',
|
||||
displayName: 'My Twenty App',
|
||||
description: 'My first Twenty app',
|
||||
icon: 'IconWorld',
|
||||
applicationVariables: {
|
||||
DEFAULT_RECIPIENT_NAME: {
|
||||
universalIdentifier: '19e94e59-d4fe-4251-8981-b96d0a9f74de',
|
||||
description: 'Default recipient name for postcards',
|
||||
value: 'Jane Doe',
|
||||
isSecret: false,
|
||||
},
|
||||
},
|
||||
defaultRoleUniversalIdentifier: DEFAULT_ROLE_UNIVERSAL_IDENTIFIER,
|
||||
});
|
||||
```
|
||||
|
||||
الملاحظات:
|
||||
|
||||
* حقول `universalIdentifier` هي معرّفات حتمية تخصك؛ أنشئها مرة واحدة واحتفظ بها ثابتة عبر عمليات المزامنة.
|
||||
* `applicationVariables` تصبح متغيرات بيئة لوظائفك (على سبيل المثال، `DEFAULT_RECIPIENT_NAME` متاح كـ `process.env.DEFAULT_RECIPIENT_NAME`).
|
||||
* `defaultRoleUniversalIdentifier` يجب أن يطابق ملف الدور (انظر أدناه).
|
||||
* يتم اكتشاف دوال ما قبل التثبيت وما بعد التثبيت تلقائيًا أثناء إنشاء ملف البيان. راجع [دوال ما قبل التثبيت](#pre-install-functions) و[دوال ما بعد التثبيت](#post-install-functions).
|
||||
|
||||
#### الأدوار والصلاحيات
|
||||
|
||||
يمكن للتطبيقات تعريف أدوار تُغلّف الصلاحيات على كائنات وإجراءات مساحة العمل لديك. يعين الحقل `defaultRoleUniversalIdentifier` في `application-config.ts` الدور الافتراضي الذي تستخدمه وظائف المنطق في تطبيقك.
|
||||
|
||||
* مفتاح واجهة البرمجة في وقت التشغيل المحقون باسم `TWENTY_API_KEY` مستمد من دور الوظيفة الافتراضي هذا.
|
||||
* سيُقيَّد العميل مضبوط الأنواع بالأذونات الممنوحة لذلك الدور.
|
||||
* اتبع مبدأ أقل الامتياز: أنشئ دورًا مخصصًا بالأذونات التي تحتاجها وظائفك فقط، ثم أشِر إلى معرّفه الشامل.
|
||||
|
||||
##### الدور الافتراضي للوظيفة (*.role.ts)
|
||||
|
||||
عند توليد تطبيق جديد بالقالب، ينشئ CLI أيضًا ملف دور افتراضي. استخدم `defineRole()` لتعريف أدوار مع تحقق مدمج:
|
||||
|
||||
```typescript
|
||||
// src/roles/default-role.ts
|
||||
import { defineRole, PermissionFlag } from 'twenty-sdk';
|
||||
|
||||
export const DEFAULT_ROLE_UNIVERSAL_IDENTIFIER =
|
||||
'b648f87b-1d26-4961-b974-0908fd991061';
|
||||
|
||||
export default defineRole({
|
||||
universalIdentifier: DEFAULT_ROLE_UNIVERSAL_IDENTIFIER,
|
||||
label: 'Default function role',
|
||||
description: 'Default role for function Twenty client',
|
||||
canReadAllObjectRecords: false,
|
||||
canUpdateAllObjectRecords: false,
|
||||
canSoftDeleteAllObjectRecords: false,
|
||||
canDestroyAllObjectRecords: false,
|
||||
canUpdateAllSettings: false,
|
||||
canBeAssignedToAgents: false,
|
||||
canBeAssignedToUsers: false,
|
||||
canBeAssignedToApiKeys: false,
|
||||
objectPermissions: [
|
||||
{
|
||||
objectUniversalIdentifier: '9f9882af-170c-4879-b013-f9628b77c050',
|
||||
canReadObjectRecords: true,
|
||||
canUpdateObjectRecords: true,
|
||||
canSoftDeleteObjectRecords: false,
|
||||
canDestroyObjectRecords: false,
|
||||
},
|
||||
],
|
||||
fieldPermissions: [
|
||||
{
|
||||
objectUniversalIdentifier: '9f9882af-170c-4879-b013-f9628b77c050',
|
||||
fieldUniversalIdentifier: 'b2c37dc0-8ae7-470e-96cd-1476b47dfaff',
|
||||
canReadFieldValue: false,
|
||||
canUpdateFieldValue: false,
|
||||
},
|
||||
],
|
||||
permissionFlags: [PermissionFlag.APPLICATIONS],
|
||||
});
|
||||
```
|
||||
|
||||
يُشار بعد ذلك إلى `universalIdentifier` لهذا الدور في `application-config.ts` باسم `defaultRoleUniversalIdentifier`. بعبارة أخرى:
|
||||
|
||||
* **\\*.role.ts** يحدد ما يمكن أن يفعله الدور الافتراضي للوظيفة.
|
||||
* **application-config.ts** يشير إلى ذلك الدور بحيث ترث وظائفك أذوناته.
|
||||
|
||||
الملاحظات:
|
||||
|
||||
* ابدأ من الدور المُنشأ بالقالب، ثم قيّده تدريجيًا باتباع مبدأ أقل الامتياز.
|
||||
* استبدل `objectPermissions` و`fieldPermissions` بالكائنات/الحقول التي تحتاجها وظائفك.
|
||||
* `permissionFlags` تتحكم في الوصول إلى القدرات على مستوى المنصة. اجعلها في الحد الأدنى؛ أضف فقط ما تحتاجه.
|
||||
* اطّلع على مثال عملي في تطبيق Hello World: [`packages/twenty-apps/hello-world/src/roles/function-role.ts`](https://github.com/twentyhq/twenty/blob/main/packages/twenty-apps/hello-world/src/roles/function-role.ts).
|
||||
|
||||
### تكوين الوظيفة المنطقية ونقطة الدخول
|
||||
|
||||
كل ملف وظيفة يستخدم `defineLogicFunction()` لتصدير تكوين مع معالج ومشغّلات اختيارية.
|
||||
|
||||
```typescript
|
||||
// src/app/createPostCard.logic-function.ts
|
||||
import { defineLogicFunction } from 'twenty-sdk';
|
||||
import type { DatabaseEventPayload, ObjectRecordCreateEvent, CronPayload, RoutePayload } from 'twenty-sdk';
|
||||
import { CoreApiClient, type Person } from 'twenty-sdk/generated';
|
||||
|
||||
const handler = async (params: RoutePayload) => {
|
||||
const client = new CoreApiClient();
|
||||
const name = 'name' in params.queryStringParameters
|
||||
? params.queryStringParameters.name ?? process.env.DEFAULT_RECIPIENT_NAME ?? 'Hello world'
|
||||
: 'Hello world';
|
||||
|
||||
const result = await client.mutation({
|
||||
createPostCard: {
|
||||
__args: { data: { name } },
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
});
|
||||
return result;
|
||||
};
|
||||
|
||||
export default defineLogicFunction({
|
||||
universalIdentifier: 'e56d363b-0bdc-4d8a-a393-6f0d1c75bdcf',
|
||||
name: 'create-new-post-card',
|
||||
timeoutSeconds: 2,
|
||||
handler,
|
||||
triggers: [
|
||||
// Public HTTP route trigger '/s/post-card/create'
|
||||
{
|
||||
universalIdentifier: 'c9f84c8d-b26d-40d1-95dd-4f834ae5a2c6',
|
||||
type: 'route',
|
||||
path: '/post-card/create',
|
||||
httpMethod: 'GET',
|
||||
isAuthRequired: false,
|
||||
},
|
||||
// Cron trigger (CRON pattern)
|
||||
// {
|
||||
// universalIdentifier: 'dd802808-0695-49e1-98c9-d5c9e2704ce2',
|
||||
// type: 'cron',
|
||||
// pattern: '0 0 1 1 *',
|
||||
// },
|
||||
// Database event trigger
|
||||
// {
|
||||
// universalIdentifier: '203f1df3-4a82-4d06-a001-b8cf22a31156',
|
||||
// type: 'databaseEvent',
|
||||
// eventName: 'person.updated',
|
||||
// updatedFields: ['name'],
|
||||
// },
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
أنواع المشغلات الشائعة:
|
||||
|
||||
* **route**: يعرِض وظيفتك على مسار وطريقة HTTP **تحت نقطة النهاية `/s/`**:
|
||||
|
||||
> مثال: `path: '/post-card/create',` -> الاستدعاء على `<APP_URL>/s/post-card/create`
|
||||
|
||||
* **cron**: يشغّل وظيفتك على جدول باستخدام تعبير CRON.
|
||||
* **databaseEvent**: يعمل على أحداث دورة حياة كائنات مساحة العمل. عندما تكون عملية الحدث هي `updated`، يمكن تحديد الحقول المحددة المراد الاستماع إليها في مصفوفة `updatedFields`. إذا تُركت غير معرّفة أو فارغة، فسيؤدي أي تحديث إلى تشغيل الدالة.
|
||||
|
||||
> مثال: `person.updated`
|
||||
|
||||
الملاحظات:
|
||||
|
||||
* المصفوفة `triggers` اختيارية. يمكن استخدام الوظائف بدون مشغلات كوظائف مساعدة تُستدعى بواسطة وظائف أخرى.
|
||||
* يمكنك مزج أنواع متعددة من المشغلات في وظيفة واحدة.
|
||||
|
||||
### دوال ما قبل التثبيت
|
||||
|
||||
دالة ما قبل التثبيت هي دالة منطقية تعمل تلقائيًا قبل تثبيت تطبيقك على مساحة عمل. يفيد ذلك في مهام التحقق، وفحص المتطلبات المسبقة، أو تجهيز حالة مساحة العمل قبل متابعة التثبيت الرئيسي.
|
||||
|
||||
عند إنشاء هيكل تطبيق جديد باستخدام `create-twenty-app`، يتم إنشاء دالة ما قبل التثبيت لك في `src/logic-functions/pre-install.ts`:
|
||||
|
||||
```typescript
|
||||
// src/logic-functions/pre-install.ts
|
||||
import { definePreInstallLogicFunction, type InstallLogicFunctionPayload } from 'twenty-sdk';
|
||||
|
||||
const handler = async (payload: InstallLogicFunctionPayload): Promise<void> => {
|
||||
console.log('Pre install logic function executed successfully!', payload.previousVersion);
|
||||
};
|
||||
|
||||
export default definePreInstallLogicFunction({
|
||||
universalIdentifier: '<generated-uuid>',
|
||||
name: 'pre-install',
|
||||
description: 'Runs before installation to prepare the application.',
|
||||
timeoutSeconds: 300,
|
||||
handler,
|
||||
});
|
||||
```
|
||||
|
||||
يمكنك أيضًا تنفيذ دالة ما قبل التثبيت يدويًا في أي وقت باستخدام CLI:
|
||||
|
||||
```bash filename="Terminal"
|
||||
yarn twenty function:execute --preInstall
|
||||
```
|
||||
|
||||
النقاط الرئيسية:
|
||||
|
||||
* تستخدم دوال ما قبل التثبيت `definePreInstallLogicFunction()` — وهو إصدار متخصص يستبعد إعدادات المُشغِّل (`cronTriggerSettings` و`databaseEventTriggerSettings` و`httpRouteTriggerSettings` و`isTool`).
|
||||
* يتلقى المُعالج `InstallLogicFunctionPayload` يحوي `{ previousVersion: string }` — إصدار التطبيق الذي كان مُثبّتًا سابقًا (أو سلسلة فارغة للتثبيتات الجديدة).
|
||||
* يُسمح بدالة ما قبل التثبيت واحدة فقط لكل تطبيق. سيُنتج إنشاء ملف البيان خطأً إذا تم اكتشاف أكثر من واحدة.
|
||||
* يتم تعيين `universalIdentifier` للدالة تلقائيًا كـ `preInstallLogicFunctionUniversalIdentifier` في بيان التطبيق أثناء الإنشاء — لست بحاجة إلى الإشارة إليه في `defineApplication()`.
|
||||
* تم ضبط المهلة الافتراضية على 300 ثانية (5 دقائق) للسماح بمهام التحضير الأطول.
|
||||
* لا تحتاج دوال ما قبل التثبيت إلى مُشغِّلات — إذ يستدعيها النظام الأساسي قبل التثبيت أو يدويًا عبر `function:execute --preInstall`.
|
||||
|
||||
### دوال ما بعد التثبيت
|
||||
|
||||
دالة ما بعد التثبيت هي دالة منطقية تعمل تلقائيًا بعد تثبيت تطبيقك على مساحة عمل. هذا مفيد لمهام الإعداد لمرة واحدة مثل تهيئة البيانات الافتراضية، وإنشاء السجلات الأولية، أو تكوين إعدادات مساحة العمل.
|
||||
|
||||
عند إنشاء هيكل تطبيق جديد باستخدام `create-twenty-app`، يتم إنشاء دالة ما بعد التثبيت لك في `src/logic-functions/post-install.ts`:
|
||||
|
||||
```typescript
|
||||
// src/logic-functions/post-install.ts
|
||||
import { definePostInstallLogicFunction, type InstallLogicFunctionPayload } from 'twenty-sdk';
|
||||
|
||||
const handler = async (payload: InstallLogicFunctionPayload): Promise<void> => {
|
||||
console.log('Post install logic function executed successfully!', payload.previousVersion);
|
||||
};
|
||||
|
||||
export default definePostInstallLogicFunction({
|
||||
universalIdentifier: '<generated-uuid>',
|
||||
name: 'post-install',
|
||||
description: 'Runs after installation to set up the application.',
|
||||
timeoutSeconds: 300,
|
||||
handler,
|
||||
});
|
||||
```
|
||||
|
||||
يمكنك أيضًا تنفيذ دالة ما بعد التثبيت يدويًا في أي وقت باستخدام CLI:
|
||||
|
||||
```bash filename="Terminal"
|
||||
yarn twenty function:execute --postInstall
|
||||
```
|
||||
|
||||
النقاط الرئيسية:
|
||||
|
||||
* تستخدم دوال ما بعد التثبيت `definePostInstallLogicFunction()` — وهو إصدار متخصص يستبعد إعدادات المُشغِّل (`cronTriggerSettings` و`databaseEventTriggerSettings` و`httpRouteTriggerSettings` و`isTool`).
|
||||
* يتلقى المُعالج `InstallLogicFunctionPayload` يحوي `{ previousVersion: string }` — إصدار التطبيق الذي كان مُثبّتًا سابقًا (أو سلسلة فارغة للتثبيتات الجديدة).
|
||||
* يُسمح بدالة ما بعد التثبيت واحدة فقط لكل تطبيق. سيُنتج إنشاء ملف البيان خطأً إذا تم اكتشاف أكثر من واحدة.
|
||||
* يتم تعيين `universalIdentifier` للدالة تلقائيًا كـ `postInstallLogicFunctionUniversalIdentifier` في بيان التطبيق أثناء الإنشاء — لست بحاجة إلى الإشارة إليه في `defineApplication()`.
|
||||
* تم تعيين مهلة افتراضية إلى 300 ثانية (5 دقائق) للسماح بمهام الإعداد الأطول مثل تهيئة البيانات.
|
||||
* لا تحتاج دوال ما بعد التثبيت إلى مُشغِّلات — حيث يستدعيها النظام الأساسي أثناء التثبيت أو يدويًا عبر `function:execute --postInstall`.
|
||||
|
||||
### حمولة مشغل المسار
|
||||
|
||||
<Warning>
|
||||
**تغيير غير متوافق (v1.16، يناير 2026):** لقد تغير تنسيق حمولة مشغل المسار. قبل v1.16، كانت معلمات الاستعلام، ومعلمات المسار، وجسم الطلب تُرسل مباشرةً كحمولة. بدءًا من v1.16، أصبحت متداخلة داخل كائن منظَّم `RoutePayload`.
|
||||
|
||||
**قبل v1.16:**
|
||||
```typescript
|
||||
const handler = async (params) => {
|
||||
const { param1, param2 } = params; // Direct access
|
||||
};
|
||||
```
|
||||
|
||||
**بعد v1.16:**
|
||||
```typescript
|
||||
const handler = async (event: RoutePayload) => {
|
||||
const { param1, param2 } = event.body; // Access via .body
|
||||
const { queryParam } = event.queryStringParameters;
|
||||
const { id } = event.pathParameters;
|
||||
};
|
||||
```
|
||||
|
||||
**لترحيل الدوال الحالية:** حدّث المعالج لديك لفكّ البنية من `event.body` أو `event.queryStringParameters` أو `event.pathParameters` بدلاً من القراءة مباشرةً من كائن params.
|
||||
</Warning>
|
||||
|
||||
عندما يستدعي مشغّل المسار وظيفتك المنطقية، يتلقى كائنًا من النوع `RoutePayload` يتبع تنسيق AWS HTTP API v2. استورد النوع من `twenty-sdk`:
|
||||
|
||||
```typescript
|
||||
import { defineLogicFunction, type RoutePayload } from 'twenty-sdk';
|
||||
|
||||
const handler = async (event: RoutePayload) => {
|
||||
// Access request data
|
||||
const { headers, queryStringParameters, pathParameters, body } = event;
|
||||
|
||||
// HTTP method and path are available in requestContext
|
||||
const { method, path } = event.requestContext.http;
|
||||
|
||||
return { message: 'Success' };
|
||||
};
|
||||
```
|
||||
|
||||
يحتوي نوع `RoutePayload` على البنية التالية:
|
||||
|
||||
| الخاصية | النوع | الوصف |
|
||||
| ---------------------------- | ------------------------------------- | --------------------------------------------------------------------------------------- |
|
||||
| `headers` | `Record<string, string \| undefined>` | رؤوس HTTP (فقط تلك المدرجة في `forwardedRequestHeaders`) |
|
||||
| `queryStringParameters` | `Record<string, string \| undefined>` | معلمات سلسلة الاستعلام (تُضمّ القيم المتعددة باستخدام فواصل) |
|
||||
| `pathParameters` | `Record<string, string \| undefined>` | معلمات المسار المستخرجة من نمط المسار (على سبيل المثال، `/users/:id` → `{ id: '123' }`) |
|
||||
| `المحتوى` | `object \| null` | جسم الطلب المُحلَّل (JSON) |
|
||||
| `isBase64Encoded` | `قيمة منطقية` | ما إذا كان جسم الطلب مُرمَّزًا بترميز base64 |
|
||||
| `requestContext.http.method` | `string` | طريقة HTTP (GET, POST, PUT, PATCH, DELETE) |
|
||||
| `requestContext.http.path` | `string` | المسار الخام للطلب |
|
||||
|
||||
### تمرير رؤوس HTTP
|
||||
|
||||
افتراضيًا، **لا** تُمرَّر رؤوس HTTP من الطلبات الواردة إلى دالتك المنطقية لأسباب أمنية. للوصول إلى رؤوس محددة، قم بإدراجها صراحةً في مصفوفة `forwardedRequestHeaders`:
|
||||
|
||||
```typescript
|
||||
export default defineLogicFunction({
|
||||
universalIdentifier: 'e56d363b-0bdc-4d8a-a393-6f0d1c75bdcf',
|
||||
name: 'webhook-handler',
|
||||
handler,
|
||||
triggers: [
|
||||
{
|
||||
universalIdentifier: 'c9f84c8d-b26d-40d1-95dd-4f834ae5a2c6',
|
||||
type: 'route',
|
||||
path: '/webhook',
|
||||
httpMethod: 'POST',
|
||||
isAuthRequired: false,
|
||||
forwardedRequestHeaders: ['x-webhook-signature', 'content-type'],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
في المعالج الخاص بك، يمكنك حينها الوصول إلى هذه الرؤوس:
|
||||
|
||||
```typescript
|
||||
const handler = async (event: RoutePayload) => {
|
||||
const signature = event.headers['x-webhook-signature'];
|
||||
const contentType = event.headers['content-type'];
|
||||
|
||||
// Validate webhook signature...
|
||||
return { received: true };
|
||||
};
|
||||
```
|
||||
|
||||
<Note>
|
||||
تُحوَّل أسماء الرؤوس إلى أحرف صغيرة. يمكنك الوصول إليها باستخدام مفاتيح بأحرف صغيرة (على سبيل المثال، `event.headers['content-type']`).
|
||||
</Note>
|
||||
|
||||
يمكنك إنشاء وظائف جديدة بطريقتين:
|
||||
|
||||
* **مُنشأ بالقالب**: شغّل `yarn twenty entity:add` واختر خيار إضافة دالة منطقية جديدة. يُولّد هذا ملفًا مبدئيًا مع معالج وتكوين.
|
||||
* **يدوي**: أنشئ ملفًا جديدًا `*.logic-function.ts` واستخدم `defineLogicFunction()` مع اتباع النمط نفسه.
|
||||
|
||||
### تمييز دالة منطقية كأداة
|
||||
|
||||
يمكن إتاحة الدوال المنطقية بوصفها **أدوات** لوكلاء الذكاء الاصطناعي وسير العمل. عندما يتم تمييز دالة كأداة، تصبح قابلة للاكتشاف بواسطة ميزات الذكاء الاصطناعي الخاصة بـ Twenty ويمكن اختيارها كخطوة في أتمتة سير العمل.
|
||||
|
||||
لتمييز دالة منطقية كأداة، عيّن `isTool: true` وقدّم `toolInputSchema` يصف معاملات الإدخال المتوقعة باستخدام [مخطط JSON](https://json-schema.org/):
|
||||
|
||||
```typescript
|
||||
// src/logic-functions/enrich-company.logic-function.ts
|
||||
import { defineLogicFunction } from 'twenty-sdk';
|
||||
import { CoreApiClient } from 'twenty-sdk/generated';
|
||||
|
||||
const handler = async (params: { companyName: string; domain?: string }) => {
|
||||
const client = new CoreApiClient();
|
||||
|
||||
const result = await client.mutation({
|
||||
createTask: {
|
||||
__args: {
|
||||
data: {
|
||||
title: `Enrich data for ${params.companyName}`,
|
||||
body: `Domain: ${params.domain ?? 'unknown'}`,
|
||||
},
|
||||
},
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
return { taskId: result.createTask.id };
|
||||
};
|
||||
|
||||
export default defineLogicFunction({
|
||||
universalIdentifier: 'f47ac10b-58cc-4372-a567-0e02b2c3d479',
|
||||
name: 'enrich-company',
|
||||
description: 'Enrich a company record with external data',
|
||||
timeoutSeconds: 10,
|
||||
handler,
|
||||
isTool: true,
|
||||
toolInputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
companyName: {
|
||||
type: 'string',
|
||||
description: 'The name of the company to enrich',
|
||||
},
|
||||
domain: {
|
||||
type: 'string',
|
||||
description: 'The company website domain (optional)',
|
||||
},
|
||||
},
|
||||
required: ['companyName'],
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
النقاط الرئيسية:
|
||||
|
||||
* **`isTool`** (`boolean`, الافتراضي: `false`): عند ضبطه على `true`، يتم تسجيل الدالة كأداة وتصبح متاحة لوكلاء الذكاء الاصطناعي ولأتمتة سير العمل.
|
||||
* **`toolInputSchema`** (`object`, اختياري): كائن JSON Schema يصف المعلمات التي تقبلها دالتك. يستخدم وكلاء الذكاء الاصطناعي هذا المخطط لفهم المدخلات التي تتوقعها الأداة وللتحقق من صحة الاستدعاءات. إذا تم إغفاله، فالقيمة الافتراضية للمخطط هي `{ type: 'object', properties: {} }` (من دون معلمات).
|
||||
* الدوال التي لديها `isTool: false` (أو غير معيَّنة) **غير** معروضة كأدوات. لا يزال بالإمكان تنفيذها مباشرةً أو استدعاؤها بواسطة دوال أخرى، لكنها لن تظهر في اكتشاف الأدوات.
|
||||
* **تسمية الأداة**: عند كشفها كأداة، يتم تطبيع اسم الدالة تلقائيًا إلى `logic_function_<name>` (تحويله إلى أحرف صغيرة، واستبدال المحارف غير الأبجدية الرقمية بشرطات سفلية). على سبيل المثال، `enrich-company` تصبح `logic_function_enrich_company`.
|
||||
* يمكنك دمج `isTool` مع المشغِّلات — إذ يمكن للدالة أن تكون أداة (قابلة للاستدعاء من قِبل وكلاء الذكاء الاصطناعي) وأن تُشغَّل بواسطة أحداث (cron، وأحداث قاعدة البيانات، والمسارات) في الوقت نفسه.
|
||||
|
||||
<Note>
|
||||
**اكتب `description` جيدًا.** يعتمد وكلاء الذكاء الاصطناعي على حقل `description` الخاص بالدالة لتحديد وقت استخدام الأداة. كن محددًا بشأن ما تفعله الأداة ومتى ينبغي استدعاؤها.
|
||||
</Note>
|
||||
|
||||
### المكوّنات الأمامية
|
||||
|
||||
تتيح لك المكوّنات الأمامية إنشاء مكوّنات React مخصّصة تُعرَض داخل واجهة مستخدم Twenty. استخدم `defineFrontComponent()` لتعريف مكوّنات مع تحقّق مدمج:
|
||||
|
||||
```typescript
|
||||
// src/front-components/my-widget.tsx
|
||||
import { defineFrontComponent } from 'twenty-sdk';
|
||||
|
||||
const MyWidget = () => {
|
||||
return (
|
||||
<div style={{ padding: '20px', fontFamily: 'sans-serif' }}>
|
||||
<h1>My Custom Widget</h1>
|
||||
<p>This is a custom front component for Twenty.</p>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default defineFrontComponent({
|
||||
universalIdentifier: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
|
||||
name: 'my-widget',
|
||||
description: 'A custom widget component',
|
||||
component: MyWidget,
|
||||
});
|
||||
```
|
||||
|
||||
النقاط الرئيسية:
|
||||
|
||||
* المكوّنات الأمامية هي مكوّنات React تُعرَض ضمن سياقات معزولة داخل Twenty.
|
||||
* يشير الحقل `component` إلى مكوّن React الخاص بك.
|
||||
* يتم بناء المكوّنات ومزامنتها تلقائيًا أثناء `yarn twenty app:dev`.
|
||||
|
||||
يمكنك إنشاء مكوّنات أمامية جديدة بطريقتين:
|
||||
|
||||
* **مُنشأ بالقالب**: شغّل `yarn twenty entity:add` واختر خيار إضافة مكوّن أمامي جديد.
|
||||
* **يدوي**: أنشئ ملفًا جديدًا `.tsx` واستخدم `defineFrontComponent()` مع اتباع النمط نفسه.
|
||||
|
||||
### المهارات
|
||||
|
||||
تُحدِّد المهارات تعليمات وإمكانات قابلة لإعادة الاستخدام يمكن لوكلاء الذكاء الاصطناعي استخدامها داخل مساحة العمل لديك. استخدم `defineSkill()` لتعريف مهارات مع تحقّق مدمج:
|
||||
|
||||
```typescript
|
||||
// src/skills/example-skill.ts
|
||||
import { defineSkill } from 'twenty-sdk';
|
||||
|
||||
export default defineSkill({
|
||||
universalIdentifier: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
|
||||
name: 'sales-outreach',
|
||||
label: 'Sales Outreach',
|
||||
description: 'Guides the AI agent through a structured sales outreach process',
|
||||
icon: 'IconBrain',
|
||||
content: `You are a sales outreach assistant. When reaching out to a prospect:
|
||||
1. Research the company and recent news
|
||||
2. Identify the prospect's role and likely pain points
|
||||
3. Draft a personalized message referencing specific details
|
||||
4. Keep the tone professional but conversational`,
|
||||
});
|
||||
```
|
||||
|
||||
النقاط الرئيسية:
|
||||
|
||||
* `name` هي سلسلة معرّف فريدة للمهارة (يُنصَح باستخدام kebab-case).
|
||||
* `label` هو اسم العرض المقروء للبشر الظاهر في واجهة المستخدم.
|
||||
* `content` يحتوي على تعليمات المهارة — وهو النص الذي يستخدمه وكيل الذكاء الاصطناعي.
|
||||
* `icon` (اختياري) يحدّد الأيقونة المعروضة في واجهة المستخدم.
|
||||
* `description` (اختياري) يوفّر سياقًا إضافيًا حول غرض المهارة.
|
||||
|
||||
يمكنك إنشاء مهارات جديدة بطريقتين:
|
||||
|
||||
* **مُنشأ بالقالب**: شغِّل `yarn twenty entity:add` واختر خيار إضافة مهارة جديدة.
|
||||
* **يدوي**: أنشئ ملفًا جديدًا واستخدم `defineSkill()` مع اتباع النمط نفسه.
|
||||
|
||||
### عملاء مُولَّدون مضبوطو الأنواع
|
||||
|
||||
يتم توليد عميلين مضبوطي الأنواع تلقائيًا بواسطة `yarn twenty app:dev` وتخزينهما في `node_modules/twenty-sdk/generated` استنادًا إلى مخطط مساحة العمل لديك:
|
||||
|
||||
* **`CoreApiClient`** — يُجري استعلامات إلى نقطة النهاية `/graphql` للحصول على بيانات مساحة العمل
|
||||
* **`MetadataApiClient`** — يستعلم عن نقطة النهاية `/metadata` لتكوين مساحة العمل وتحميل الملفات.
|
||||
|
||||
```typescript
|
||||
import { CoreApiClient, MetadataApiClient } from 'twenty-sdk/generated';
|
||||
|
||||
const client = new CoreApiClient();
|
||||
const { me } = await client.query({ me: { id: true, displayName: true } });
|
||||
|
||||
const metadataClient = new MetadataApiClient();
|
||||
const { currentWorkspace } = await metadataClient.query({ currentWorkspace: { id: true } });
|
||||
```
|
||||
|
||||
يُعاد توليد كلا العميلين تلقائيًا بواسطة `yarn twenty app:dev` كلما تغيّرت كائناتك أو حقولك.
|
||||
|
||||
#### بيانات الاعتماد وقت التشغيل في الدوال المنطقية
|
||||
|
||||
عندما تعمل دالتك على Twenty، يقوم النظام الأساسي بحقن بيانات الاعتماد كمتغيرات بيئة قبل تنفيذ كودك:
|
||||
|
||||
* `TWENTY_API_URL`: عنوان URL الأساسي لواجهة Twenty البرمجية التي يستهدفها تطبيقك.
|
||||
* `TWENTY_API_KEY`: مفتاح قصير العمر ذو نطاق يقتصر على الدور الافتراضي لوظيفة تطبيقك.
|
||||
|
||||
الملاحظات:
|
||||
|
||||
* لا تحتاج إلى تمرير عنوان URL أو مفتاح واجهة برمجة التطبيقات إلى العميل المُولَّد. يقوم بقراءة `TWENTY_API_URL` و`TWENTY_API_KEY` من process.env وقت التشغيل.
|
||||
* تُحدَّد أذونات مفتاح واجهة برمجة التطبيقات بواسطة الدور المشار إليه في `application-config.ts` عبر `defaultRoleUniversalIdentifier`. هذا هو الدور الافتراضي الذي تستخدمه الدوال المنطقية في تطبيقك.
|
||||
* يمكن للتطبيقات تعريف أدوار لاتباع مبدأ أقل الامتياز. امنح فقط الأذونات التي تحتاجها وظائفك، ثم وجّه `defaultRoleUniversalIdentifier` إلى المعرّف الشامل لذلك الدور.
|
||||
|
||||
#### رفع الملفات
|
||||
|
||||
يتضمن `MetadataApiClient` المُولَّد طريقة `uploadFile` لإرفاق الملفات بالحقول من نوع ملف ضمن كائنات مساحة العمل الخاصة بك. نظرًا لأن عملاء GraphQL القياسيون لا يدعمون تحميل الملفات متعددة الأجزاء افتراضيًا، يوفر العميل هذه الطريقة المخصصة التي تطبق [مواصفة طلب GraphQL متعدد الأجزاء](https://github.com/jaydenseric/graphql-multipart-request-spec) في الخلفية.
|
||||
|
||||
```typescript
|
||||
import { MetadataApiClient } from 'twenty-sdk/generated';
|
||||
import * as fs from 'fs';
|
||||
|
||||
const metadataClient = new MetadataApiClient();
|
||||
|
||||
const fileBuffer = fs.readFileSync('./invoice.pdf');
|
||||
|
||||
const uploadedFile = await metadataClient.uploadFile(
|
||||
fileBuffer, // file contents as a Buffer
|
||||
'invoice.pdf', // filename
|
||||
'application/pdf', // MIME type (defaults to 'application/octet-stream')
|
||||
'58a0a314-d7ea-4865-9850-7fb84e72f30b', // field universal identifier
|
||||
);
|
||||
|
||||
console.log(uploadedFile);
|
||||
// { id: '...', path: '...', size: 12345, createdAt: '...', url: 'https://...' }
|
||||
```
|
||||
|
||||
توقيع الطريقة:
|
||||
|
||||
```typescript
|
||||
uploadFile(
|
||||
fileBuffer: Buffer,
|
||||
filename: string,
|
||||
contentType: string,
|
||||
fieldMetadataUniversalIdentifier: string,
|
||||
): Promise<{ id: string; path: string; size: number; createdAt: string; url: string }>
|
||||
```
|
||||
|
||||
| المعلمة | النوع | الوصف |
|
||||
| ---------------------------------- | -------- | ---------------------------------------------------------------------------------- |
|
||||
| `fileBuffer` | `Buffer` | المحتوى الخام للملف |
|
||||
| `filename` | `string` | اسم الملف (يُستخدم للتخزين والعرض) |
|
||||
| `contentType` | `string` | نوع MIME للملف (القيمة الافتراضية هي `application/octet-stream` إذا لم يتم تحديده) |
|
||||
| `fieldMetadataUniversalIdentifier` | `string` | قيمة `universalIdentifier` لحقل نوع الملف في كائنك |
|
||||
|
||||
النقاط الرئيسية:
|
||||
|
||||
* تتوفر طريقة `uploadFile` على `MetadataApiClient` لأن عملية الـ mutation الخاصة بالرفع تُعالَج عبر نقطة النهاية `/metadata`.
|
||||
* تستخدم `universalIdentifier` الخاص بالحقل (وليس المعرّف الخاص بمساحة العمل)، ليعمل كود الرفع لديك عبر أي مساحة عمل مُثبَّت فيها تطبيقك — بما يتماشى مع كيفية إشارة التطبيقات إلى الحقول في كل مكان آخر.
|
||||
* العنوان `url` المُعاد هو عنوان URL موقّع يمكنك استخدامه للوصول إلى الملف المرفوع.
|
||||
|
||||
### مثال Hello World
|
||||
|
||||
استكشف مثالًا بسيطًا شاملًا من البداية إلى النهاية يوضح الكائنات والوظائف المنطقية والمكوّنات الأمامية ومشغّلات متعددة [هنا](https://github.com/twentyhq/twenty/tree/main/packages/twenty-apps/hello-world).
|
||||
@@ -1,233 +0,0 @@
|
||||
---
|
||||
title: البدء
|
||||
description: أنشئ أول تطبيق Twenty خلال دقائق.
|
||||
---
|
||||
|
||||
<Warning>
|
||||
التطبيقات حاليًا في مرحلة الاختبار الألفا. الميزة تعمل لكنها لا تزال قيد التطور.
|
||||
</Warning>
|
||||
|
||||
تتيح لك التطبيقات توسيع Twenty باستخدام كائنات وحقول ووظائف منطقية ومهارات ذكاء اصطناعي ومكونات واجهة مستخدم مخصصة — جميعها تُدار ككود.
|
||||
|
||||
**ما الذي يمكنك فعله اليوم:**
|
||||
|
||||
* عرِّف كائنات وحقولًا مخصصة على شكل كود (نموذج بيانات مُدار)
|
||||
* أنشئ وظائف منطقية مع مشغلات مخصصة (مسارات HTTP، cron، أحداث قاعدة البيانات)
|
||||
* حدد المهارات لوكلاء الذكاء الاصطناعي
|
||||
* أنشئ مكونات واجهية تُعرَض داخل واجهة مستخدم Twenty
|
||||
* انشر التطبيق نفسه عبر مساحات عمل متعددة
|
||||
|
||||
## المتطلبات الأساسية
|
||||
|
||||
* Node.js 24+ وYarn 4
|
||||
* مساحة عمل Twenty ومفتاح واجهة برمجة التطبيقات (أنشئ واحدًا على https://app.twenty.com/settings/api-webhooks)
|
||||
|
||||
## البدء
|
||||
|
||||
أنشئ تطبيقًا جديدًا باستخدام المُهيئ الرسمي، ثم قم بالمصادقة وابدأ التطوير:
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Scaffold a new app (includes all examples by default)
|
||||
npx create-twenty-app@latest my-twenty-app
|
||||
cd my-twenty-app
|
||||
|
||||
# Start dev mode: automatically syncs local changes to your workspace
|
||||
yarn twenty app:dev
|
||||
```
|
||||
|
||||
يدعم المُهيئ وضعين للتحكم في ملفات الأمثلة التي سيتم تضمينها:
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Default (exhaustive): all examples (object, field, logic function, front component, view, navigation menu item, skill)
|
||||
npx create-twenty-app@latest my-app
|
||||
|
||||
# Minimal: only core files (application-config.ts and default-role.ts)
|
||||
npx create-twenty-app@latest my-app --minimal
|
||||
```
|
||||
|
||||
من هنا يمكنك:
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Add a new entity to your application (guided)
|
||||
yarn twenty entity:add
|
||||
|
||||
# Watch your application's function logs
|
||||
yarn twenty function:logs
|
||||
|
||||
# Execute a function by name
|
||||
yarn twenty function:execute -n my-function -p '{"name": "test"}'
|
||||
|
||||
# Execute the pre-install function
|
||||
yarn twenty function:execute --preInstall
|
||||
|
||||
# Execute the post-install function
|
||||
yarn twenty function:execute --postInstall
|
||||
|
||||
# Uninstall the application from the current workspace
|
||||
yarn twenty app:uninstall
|
||||
|
||||
# Display commands' help
|
||||
yarn twenty help
|
||||
```
|
||||
|
||||
راجع أيضًا: صفحات مرجع CLI لـ [create-twenty-app](https://www.npmjs.com/package/create-twenty-app) و[twenty-sdk CLI](https://www.npmjs.com/package/twenty-sdk).
|
||||
|
||||
## هيكل المشروع (مُنشأ بالقالب)
|
||||
|
||||
عند تشغيل `npx create-twenty-app@latest my-twenty-app`، يقوم المُهيئ بما يلي:
|
||||
|
||||
* ينسخ تطبيقًا أساسيًا مصغّرًا إلى `my-twenty-app/`
|
||||
* يضيف اعتمادًا محليًا `twenty-sdk` وتهيئة Yarn 4
|
||||
* ينشئ ملفات ضبط ونصوصًا مرتبطة بـ `twenty` CLI
|
||||
* يُنشئ الملفات الأساسية (تهيئة التطبيق، دور الدالة الافتراضي، دالتا ما قبل التثبيت وما بعد التثبيت) بالإضافة إلى ملفات أمثلة استنادًا إلى وضع الإنشاء.
|
||||
|
||||
يبدو التطبيق المُنشأ حديثًا باستخدام الوضع الافتراضي `--exhaustive` كما يلي:
|
||||
|
||||
```text filename="my-twenty-app/"
|
||||
my-twenty-app/
|
||||
package.json
|
||||
yarn.lock
|
||||
.gitignore
|
||||
.nvmrc
|
||||
.yarnrc.yml
|
||||
.yarn/
|
||||
install-state.gz
|
||||
.oxlintrc.json
|
||||
tsconfig.json
|
||||
README.md
|
||||
public/ # Public assets folder (images, fonts, etc.)
|
||||
src/
|
||||
├── application-config.ts # Required - main application configuration
|
||||
├── roles/
|
||||
│ └── default-role.ts # Default role for logic functions
|
||||
├── objects/
|
||||
│ └── example-object.ts # Example custom object definition
|
||||
├── fields/
|
||||
│ └── example-field.ts # Example standalone field definition
|
||||
├── logic-functions/
|
||||
│ ├── hello-world.ts # Example logic function
|
||||
│ ├── pre-install.ts # Pre-install logic function
|
||||
│ └── post-install.ts # Post-install logic function
|
||||
├── front-components/
|
||||
│ └── hello-world.tsx # Example front component
|
||||
├── views/
|
||||
│ └── example-view.ts # Example saved view definition
|
||||
├── navigation-menu-items/
|
||||
│ └── example-navigation-menu-item.ts # Example sidebar navigation link
|
||||
└── skills/
|
||||
└── example-skill.ts # Example AI agent skill definition
|
||||
```
|
||||
|
||||
مع `--minimal`، سيتم إنشاء الملفات الأساسية فقط (`application-config.ts`، `roles/default-role.ts`، `logic-functions/pre-install.ts`، و`logic-functions/post-install.ts`).
|
||||
|
||||
بشكل عام:
|
||||
|
||||
* **package.json**: يصرّح باسم التطبيق والإصدار والمحرّكات (Node 24+، Yarn 4)، ويضيف `twenty-sdk` بالإضافة إلى نص برمجي `twenty` يفوِّض إلى `twenty` CLI المحلي. شغِّل `yarn twenty help` لعرض جميع الأوامر المتاحة.
|
||||
* **.gitignore**: يتجاهل العناصر الشائعة مثل `node_modules` و`.yarn` و`generated/` (عميل مضبوط الأنواع) و`dist/` و`build/` ومجلدات التغطية وملفات السجلات وملفات `.env*`.
|
||||
* **yarn.lock**، **.yarnrc.yml**، **.yarn/**: تقوم بقفل وتكوين حزمة أدوات Yarn 4 المستخدمة في المشروع.
|
||||
* **.nvmrc**: يثبّت إصدار Node.js المتوقع للمشروع.
|
||||
* **.oxlintrc.json** و **tsconfig.json**: يقدّمان إعدادات الفحص والتهيئة لـ TypeScript لمصادر TypeScript في تطبيقك.
|
||||
* **README.md**: ملف README قصير في جذر التطبيق يتضمن تعليمات أساسية.
|
||||
* **public/**: مجلد لتخزين الأصول العامة (صور، خطوط، ملفات ثابتة) التي سيتم تقديمها مع تطبيقك. الملفات الموضوعة هنا تُرفع أثناء المزامنة وتكون متاحة أثناء وقت التشغيل.
|
||||
* **src/**: المكان الرئيسي حيث تعرّف تطبيقك ككود
|
||||
|
||||
### اكتشاف الكيانات
|
||||
|
||||
يكتشف SDK الكيانات عبر تحليل ملفات TypeScript الخاصة بك بحثًا عن استدعاءات **`export default define<Entity>({...})`**. يحتوي كل نوع كيان على دالة مساعدة مقابلة يتم تصديرها من `twenty-sdk`:
|
||||
|
||||
| دالة مساعدة | نوع الكيان |
|
||||
| -------------------------------- | ---------------------------------------------- |
|
||||
| `defineObject` | تعريفات كائنات مخصصة |
|
||||
| `defineLogicFunction` | تعريفات الوظائف المنطقية |
|
||||
| `definePreInstallLogicFunction` | دالة منطقية لما قبل التثبيت (تعمل قبل التثبيت) |
|
||||
| `definePostInstallLogicFunction` | دالة منطقية لما بعد التثبيت (تعمل بعد التثبيت) |
|
||||
| `defineFrontComponent` | تعريفات المكونات الواجهية |
|
||||
| `defineRole` | تعريفات الأدوار |
|
||||
| `defineField` | امتدادات الحقول للكائنات الموجودة |
|
||||
| `defineView` | تعريفات العروض المحفوظة |
|
||||
| `defineNavigationMenuItem` | تعريفات عناصر قائمة التنقل |
|
||||
| `defineSkill` | تعريفات مهارات وكلاء الذكاء الاصطناعي |
|
||||
|
||||
<Note>
|
||||
**تسمية الملفات مرنة.** يعتمد اكتشاف الكيانات على بنية الشجرة المجردة (AST) — إذ يقوم SDK بفحص ملفات المصدر لديك بحثًا عن النمط `export default define<Entity>({...})`. يمكنك تنظيم ملفاتك ومجلداتك كيفما تشاء. التجميع حسب نوع الكيان (مثلًا، `logic-functions/` و`roles/`) هو مجرد عرف لتنظيم الشيفرة، وليس مطلبًا إلزاميًا.
|
||||
</Note>
|
||||
|
||||
مثال على كيان تم اكتشافه:
|
||||
|
||||
```typescript
|
||||
// This file can be named anything and placed anywhere in src/
|
||||
import { defineObject, FieldType } from 'twenty-sdk';
|
||||
|
||||
export default defineObject({
|
||||
universalIdentifier: '...',
|
||||
nameSingular: 'postCard',
|
||||
// ... rest of config
|
||||
});
|
||||
```
|
||||
|
||||
ستضيف الأوامر اللاحقة مزيدًا من الملفات والمجلدات:
|
||||
|
||||
* سيقوم `yarn twenty app:dev` بتوليد عميلين API مضبوطي الأنواع تلقائيًا في `node_modules/twenty-sdk/generated`: `CoreApiClient` (لبيانات مساحة العمل عبر `/graphql`) و`MetadataApiClient` (لتكوين مساحة العمل وتحميل الملفات عبر `/metadata`).
|
||||
* `yarn twenty entity:add` سيضيف ملفات تعريف الكيانات ضمن `src/` لكائناتك المخصّصة، والوظائف، ومكوّنات الواجهة الأمامية، والأدوار، والمهارات، وغير ذلك.
|
||||
|
||||
## المصادقة
|
||||
|
||||
في المرة الأولى التي تشغّل فيها `yarn twenty auth:login`، سيُطلب منك إدخال:
|
||||
|
||||
* عنوان URL لواجهة برمجة التطبيقات (الافتراضي http://localhost:3000 أو ملف تعريف مساحة العمل الحالية لديك)
|
||||
* مفتاح واجهة برمجة التطبيقات
|
||||
|
||||
تُخزَّن بيانات اعتمادك لكل مستخدم في `~/.twenty/config.json`. يمكنك الاحتفاظ بملفات تعريف متعددة والتبديل بينها.
|
||||
|
||||
### إدارة مساحات العمل
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Login interactively (recommended)
|
||||
yarn twenty auth:login
|
||||
|
||||
# Login to a specific workspace profile
|
||||
yarn twenty auth:login --workspace my-custom-workspace
|
||||
|
||||
# List all configured workspaces
|
||||
yarn twenty auth:list
|
||||
|
||||
# Switch the default workspace (interactive)
|
||||
yarn twenty auth:switch
|
||||
|
||||
# Switch to a specific workspace
|
||||
yarn twenty auth:switch production
|
||||
|
||||
# Check current authentication status
|
||||
yarn twenty auth:status
|
||||
```
|
||||
|
||||
بمجرد أن تقوم بالتبديل بين مساحات العمل باستخدام `yarn twenty auth:switch`، ستستخدم جميع الأوامر اللاحقة تلك المساحة افتراضيًا. لا يزال بإمكانك تجاوزه مؤقتًا باستخدام `--workspace <name>`.
|
||||
|
||||
## إعداد يدوي (بدون المهيئ)
|
||||
|
||||
بينما نوصي باستخدام `create-twenty-app` للحصول على أفضل تجربة للبدء، يمكنك أيضًا إعداد مشروع يدويًا. لا تثبّت CLI عالميًا. بدل ذلك، أضف `twenty-sdk` كاعتماد محلي واربط سكربتًا واحدًا في ملف package.json لديك:
|
||||
|
||||
```bash filename="Terminal"
|
||||
yarn add -D twenty-sdk
|
||||
```
|
||||
|
||||
ثم أضف سكربتًا باسم `twenty`:
|
||||
|
||||
```json filename="package.json"
|
||||
{
|
||||
"scripts": {
|
||||
"twenty": "twenty"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
الآن يمكنك تشغيل جميع الأوامر عبر `yarn twenty <command>`، مثلًا: `yarn twenty app:dev`، `yarn twenty help`، إلخ.
|
||||
|
||||
## استكشاف الأخطاء وإصلاحها
|
||||
|
||||
* أخطاء المصادقة: شغّل `yarn twenty auth:login` وتأكد من أن مفتاح واجهة برمجة التطبيقات لديك يمتلك الأذونات المطلوبة.
|
||||
* يتعذّر الاتصال بالخادم: تحقق من عنوان URL لواجهة برمجة التطبيقات وأن خادم Twenty قابل للوصول.
|
||||
* الأنواع أو العميل مفقود/قديم: أعد تشغيل `yarn twenty app:dev` — فهو ينشئ العميل مضبوط الأنواع بشكل تلقائي.
|
||||
* وضع التطوير لا يزامن: تأكد من أن `yarn twenty app:dev` قيد التشغيل وأن التغييرات ليست متجاهلة من بيئتك.
|
||||
|
||||
قناة المساعدة على Discord: https://discord.com/channels/1130383047699738754/1130386664812982322
|
||||
@@ -1,119 +0,0 @@
|
||||
---
|
||||
title: النشر
|
||||
description: وزّع تطبيق Twenty الخاص بك على سوق Twenty أو انشره داخليًا.
|
||||
---
|
||||
|
||||
<Warning>
|
||||
التطبيقات حاليًا في مرحلة الاختبار الألفا. الميزة تعمل لكنها لا تزال قيد التطور.
|
||||
</Warning>
|
||||
|
||||
## نظرة عامة
|
||||
|
||||
بمجرد أن يكون تطبيقك [مبنيًا ومختبرًا محليًا](/l/ar/developers/extend/apps/building)، لديك مساران لتوزيعه:
|
||||
|
||||
* **النشر على npm** — أدرج تطبيقك في سوق Twenty ليتسنى لأي مساحة عمل اكتشافه وتثبيته.
|
||||
* **إرسال tarball** — انشر تطبيقك إلى خادم Twenty معيّن للاستخدام الداخلي من دون جعله متاحًا للعامة.
|
||||
|
||||
## النشر على npm
|
||||
|
||||
يُتيح النشر على npm إمكانية العثور على تطبيقك في سوق Twenty. يمكن لأي مساحة عمل في Twenty استعراض تطبيقات السوق وتثبيتها وترقيتها مباشرةً من واجهة المستخدم.
|
||||
|
||||
### المتطلبات
|
||||
|
||||
* حساب على [npm](https://www.npmjs.com)
|
||||
* يجب أن يستخدم اسم الحزمة البادئة `twenty-app-` (مثلًا، `twenty-app-postcard-sender`)
|
||||
|
||||
### الخطوات
|
||||
|
||||
1. **قم ببناء تطبيقك** — تقوم أداة CLI بتجميع مصادر TypeScript الخاصة بك وإنشاء ملف بيان التطبيق:
|
||||
|
||||
```bash filename="Terminal"
|
||||
yarn twenty app:build
|
||||
```
|
||||
|
||||
2. **النشر على npm** — ادفع الحزمة المبنية إلى سجل npm:
|
||||
|
||||
```bash filename="Terminal"
|
||||
npx twenty app:publish
|
||||
```
|
||||
|
||||
### الاكتشاف التلقائي
|
||||
|
||||
تُكتشف الحِزم التي تحمل البادئة `twenty-app-` تلقائيًا بواسطة فهرس سوق Twenty. بعد نشره، سيظهر تطبيقك في السوق خلال بضع دقائق — من دون الحاجة إلى تسجيل يدوي أو موافقة يدوية.
|
||||
|
||||
### النشر عبر CI
|
||||
|
||||
يتضمن المشروع المُولَّد سير عمل GitHub Actions يقوم بالنشر عند كل إصدار. يشغِّل `app:build`، ثم ينفِّذ `npm publish --provenance` من مخرجات البناء:
|
||||
|
||||
```yaml filename=".github/workflows/publish.yml"
|
||||
name: Publish
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "24"
|
||||
registry-url: https://registry.npmjs.org
|
||||
- run: yarn install --immutable
|
||||
- run: npx twenty app:build
|
||||
- run: npm publish --provenance --access public
|
||||
working-directory: .twenty/output
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
```
|
||||
|
||||
بالنسبة لأنظمة CI الأخرى (GitLab CI، CircleCI، إلخ)، تنطبق الأوامر الثلاثة نفسها: `yarn install`، ثم `npx twenty app:build`، ثم `npm publish` من `.twenty/output`.
|
||||
|
||||
<Tip>
|
||||
**npm provenance** اختياري ولكنه موصى به. يضيف النشر باستخدام `--provenance` شارة ثقة إلى إدراجك على npm، مما يتيح للمستخدمين التحقق من أن الحزمة تم بناؤها من التزام محدد ضمن خط أنابيب CI عام. راجع [وثائق npm provenance](https://docs.npmjs.com/generating-provenance-statements) للحصول على تعليمات الإعداد.
|
||||
</Tip>
|
||||
|
||||
## التوزيع الداخلي
|
||||
|
||||
بالنسبة للتطبيقات التي لا تريد إتاحتها للعامة — مثل الأدوات المملوكة، أو عمليات التكامل الخاصة بالمؤسسات فقط، أو الإصدارات التجريبية — يمكنك إرسال tarball مباشرةً إلى خادم Twenty.
|
||||
|
||||
### إرسال tarball
|
||||
|
||||
قم ببناء تطبيقك وانشره إلى خادم محدد في خطوة واحدة:
|
||||
|
||||
```bash filename="Terminal"
|
||||
npx twenty app:publish --server <server-url>
|
||||
```
|
||||
|
||||
يمكن لأي مساحة عمل على ذلك الخادم بعدها تثبيت التطبيق وترقيته من صفحة الإعدادات **التطبيقات**.
|
||||
|
||||
### إدارة الإصدارات
|
||||
|
||||
لطرح تحديث:
|
||||
|
||||
1. ارفع قيمة الحقل `version` في ملف `package.json`
|
||||
2. أرسل tarball جديدًا باستخدام `npx twenty app:publish --server <server-url>`
|
||||
3. سترى مساحات العمل على ذلك الخادم الترقية متاحة في إعداداتها
|
||||
|
||||
<Note>
|
||||
التطبيقات الداخلية مقتصرة على الخادم الذي تُرسل إليه. لن تظهر في السوق العام ولا يمكن لمساحات العمل على خوادم أخرى تثبيتها.
|
||||
</Note>
|
||||
|
||||
## فئات التطبيقات
|
||||
|
||||
تُنظِّم Twenty التطبيقات في ثلاث فئات استنادًا إلى طريقة توزيعها:
|
||||
|
||||
| الفئة | كيف يعمل | مرئي في سوق Twenty؟ |
|
||||
| ----------- | ---------------------------------------------------------------------------------------------------- | ------------------- |
|
||||
| **التطوير** | تطبيقات وضع التطوير المحلي التي تعمل عبر `yarn twenty app:dev`. تُستخدم للبناء والاختبار. | لا |
|
||||
| **منشور** | تطبيقات منشورة على npm مع البادئة `twenty-app-`. مدرجة في سوق Twenty لتتمكن أي مساحة عمل من تثبيتها. | نعم |
|
||||
| **داخلي** | تطبيقات منشورة عبر tarball إلى خادم محدد. متاحة فقط لمساحات العمل على ذلك الخادم. | لا |
|
||||
|
||||
<Tip>
|
||||
ابدأ في وضع **التطوير** أثناء بناء تطبيقك. عندما يصبح جاهزًا، اختر **منشور** (npm) للتوزيع الواسع أو **داخلي** (tarball) للنشر الخاص.
|
||||
</Tip>
|
||||
@@ -171,7 +171,7 @@ export default defineObject({
|
||||
|
||||
ستضيف الأوامر اللاحقة مزيدًا من الملفات والمجلدات:
|
||||
|
||||
* سيقوم `yarn twenty app:dev` بتوليد عميلين API مضبوطي الأنواع تلقائيًا في `node_modules/twenty-sdk/clients`: `CoreApiClient` (لبيانات مساحة العمل عبر `/graphql`) و`MetadataApiClient` (لتكوين مساحة العمل وتحميل الملفات عبر `/metadata`).
|
||||
* سيقوم `yarn twenty app:dev` بتوليد عميلين API مضبوطي الأنواع تلقائيًا في `node_modules/twenty-sdk/generated`: `CoreApiClient` (لبيانات مساحة العمل عبر `/graphql`) و`MetadataApiClient` (لتكوين مساحة العمل وتحميل الملفات عبر `/metadata`).
|
||||
* `yarn twenty entity:add` سيضيف ملفات تعريف الكيانات ضمن `src/` لكائناتك المخصّصة، والوظائف، ومكوّنات الواجهة الأمامية، والأدوار، والمهارات، وغير ذلك.
|
||||
|
||||
## المصادقة
|
||||
@@ -228,7 +228,7 @@ yarn twenty auth:status
|
||||
| `defineView()` | تعريف العروض المحفوظة للكائنات |
|
||||
| `defineNavigationMenuItem()` | تعريف روابط التنقل في الشريط الجانبي |
|
||||
| `defineSkill()` | عرّف مهارات وكيل الذكاء الاصطناعي |
|
||||
| `defineAgent()` | عرِّف وكلاء الذكاء الاصطناعي باستخدام موجهات النظام |
|
||||
| `defineAgent()` | Define AI agents with system prompts |
|
||||
|
||||
تتحقق هذه الدوال من تكوينك وقت البناء وتوفّر إكمالًا تلقائيًا في بيئة التطوير وأمان الأنواع.
|
||||
|
||||
@@ -321,72 +321,6 @@ export default defineObject({
|
||||
لكن هذا غير مستحسن.
|
||||
</Note>
|
||||
|
||||
### تعريف الحقول على الكائنات الموجودة
|
||||
|
||||
استخدم `defineField()` لإضافة حقول مخصصة إلى الكائنات الموجودة — سواء الكائنات القياسية (مثل `company` و`person` و`opportunity`) أو الكائنات المخصصة التي تُعرِّفها تطبيقات أخرى. يوجد كل حقل في ملفه الخاص ويشير إلى الكائن الهدف بواسطة `universalIdentifier` الخاص به.
|
||||
|
||||
للإشارة إلى الكائنات القياسية، استورد `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS` من `twenty-sdk`. يوفر هذا الثابت معرِّفات مستقرة لجميع الكائنات المضمنة وحقولها:
|
||||
|
||||
```typescript
|
||||
// src/fields/apollo-total-funding.field.ts
|
||||
import {
|
||||
defineField,
|
||||
FieldType,
|
||||
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS,
|
||||
} from 'twenty-sdk';
|
||||
|
||||
export default defineField({
|
||||
universalIdentifier: 'c90ae72d-4ddf-4f22-882f-eef98c91e40e',
|
||||
objectUniversalIdentifier:
|
||||
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company.universalIdentifier,
|
||||
type: FieldType.CURRENCY,
|
||||
name: 'apolloTotalFunding',
|
||||
label: 'Total Funding',
|
||||
description: 'Total funding raised by the company',
|
||||
icon: 'IconCash',
|
||||
});
|
||||
```
|
||||
|
||||
النقاط الرئيسية:
|
||||
|
||||
* `objectUniversalIdentifier` يُحدِّد لـ Twenty الكائن الذي سيُرفَق به الحقل. استخدم `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.<objectName>.universalIdentifier` للكائنات القياسية.
|
||||
* يتطلب كل حقل `universalIdentifier` ثابتًا خاصًا به، و`name`، و`type`، و`label`، و`objectUniversalIdentifier` الخاص بالكائن الهدف.
|
||||
* يمكنك إنشاء حقول جديدة باستخدام `yarn twenty entity:add` واختيار خيار الحقل.
|
||||
* يُصدَّر `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS` أيضًا باسم `STANDARD_OBJECT` لسهولة الاستخدام — كلاهما يشير إلى الثابت نفسه.
|
||||
|
||||
تشمل الكائنات القياسية المتاحة: `attachment`، `blocklist`، `calendarChannel`، `calendarEvent`، `calendarEventParticipant`، `company`، `connectedAccount`، `dashboard`، `favorite`، `favoriteFolder`، `message`، `messageChannel`، `messageParticipant`، `messageThread`، `note`، `noteTarget`، `opportunity`، `person`، `task`، `taskTarget`، `timelineActivity`، `workflow`، `workflowAutomatedTrigger`، `workflowRun`، `workflowVersion`، و`workspaceMember`.
|
||||
|
||||
يُوفِّر كل كائن قياسي أيضًا معرّفات حقوله. على سبيل المثال، للإشارة إلى حقل محدد على كائن قياسي ضمن أذونات الأدوار:
|
||||
|
||||
```typescript
|
||||
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company.fields.name.universalIdentifier
|
||||
```
|
||||
|
||||
#### حقول العلاقات على الكائنات الموجودة
|
||||
|
||||
يمكنك أيضًا تعريف حقول علاقات تربط الكائنات الموجودة بكائناتك المخصصة:
|
||||
|
||||
```typescript
|
||||
// src/fields/people-on-call-recording.field.ts
|
||||
import { defineField, FieldType, RelationType, STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS } from 'twenty-sdk';
|
||||
import { CALL_RECORDING_OBJECT_UNIVERSAL_IDENTIFIER } from 'src/objects/call-recording';
|
||||
import { CALL_RECORDING_ON_PERSON_ID } from 'src/fields/call-recording-on-person.field';
|
||||
|
||||
export default defineField({
|
||||
universalIdentifier: '4a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d',
|
||||
objectUniversalIdentifier:
|
||||
CALL_RECORDING_OBJECT_UNIVERSAL_IDENTIFIER,
|
||||
type: FieldType.RELATION,
|
||||
name: 'person',
|
||||
label: 'Person',
|
||||
relationTargetObjectMetadataUniversalIdentifier:
|
||||
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.person.universalIdentifier,
|
||||
relationTargetFieldMetadataUniversalIdentifier:
|
||||
CALL_RECORDING_ON_PERSON_ID,
|
||||
relationType: RelationType.MANY_TO_ONE,
|
||||
});
|
||||
```
|
||||
|
||||
### تكوين التطبيق (application-config.ts)
|
||||
|
||||
كل تطبيق لديه ملف واحد `application-config.ts` يصف:
|
||||
@@ -500,7 +434,7 @@ export default defineRole({
|
||||
// src/app/createPostCard.logic-function.ts
|
||||
import { defineLogicFunction } from 'twenty-sdk';
|
||||
import type { DatabaseEventPayload, ObjectRecordCreateEvent, CronPayload, RoutePayload } from 'twenty-sdk';
|
||||
import { CoreApiClient, type Person } from 'twenty-sdk/clients';
|
||||
import { CoreApiClient, type Person } from 'twenty-sdk/generated';
|
||||
|
||||
const handler = async (params: RoutePayload) => {
|
||||
const client = new CoreApiClient();
|
||||
@@ -745,7 +679,7 @@ const handler = async (event: RoutePayload) => {
|
||||
```typescript
|
||||
// src/logic-functions/enrich-company.logic-function.ts
|
||||
import { defineLogicFunction } from 'twenty-sdk';
|
||||
import { CoreApiClient } from 'twenty-sdk/clients';
|
||||
import { CoreApiClient } from 'twenty-sdk/generated';
|
||||
|
||||
const handler = async (params: { companyName: string; domain?: string }) => {
|
||||
const client = new CoreApiClient();
|
||||
@@ -837,255 +771,6 @@ export default defineFrontComponent({
|
||||
* **مُنشأ بالقالب**: شغّل `yarn twenty entity:add` واختر خيار إضافة مكوّن أمامي جديد.
|
||||
* **يدوي**: أنشئ ملفًا جديدًا `.tsx` واستخدم `defineFrontComponent()` مع اتباع النمط نفسه.
|
||||
|
||||
#### أين يمكن استخدام مكوّنات الواجهة الأمامية
|
||||
|
||||
يمكن عرض مكوّنات الواجهة الأمامية في موقعين داخل Twenty:
|
||||
|
||||
* **اللوحة الجانبية** — المكوّنات غير عديمة الرأس تفتح في اللوحة الجانبية اليمنى. هذا هو السلوك الافتراضي عندما يتم تشغيل مكوّن واجهة أمامية من قائمة الأوامر.
|
||||
* **الويدجت (لوحات المعلومات وصفحات السجلات)** — يمكن تضمين مكوّنات الواجهة الأمامية كويدجت داخل تخطيطات الصفحات. عند تكوين لوحة معلومات أو تخطيط صفحة سجل، يمكن للمستخدمين إضافة ويدجت لمكوّن واجهة أمامية.
|
||||
|
||||
#### عديم الرأس مقابل غير عديم الرأس
|
||||
|
||||
تأتي مكوّنات الواجهة الأمامية بوضعَي عرض يتحكّم بهما الخيار `isHeadless`:
|
||||
|
||||
**غير عديم الرأس (افتراضي)** — يعرض المكوّن واجهة مستخدم مرئية. عند تشغيله من قائمة الأوامر يفتح في اللوحة الجانبية. هذا هو السلوك الافتراضي عندما تكون `isHeadless` تساوي `false` أو يتم تجاهلها.
|
||||
|
||||
**عديم الرأس** — يتم تركيب المكوّن بشكل غير مرئي في الخلفية. لا يفتح اللوحة الجانبية. تم تصميم المكوّنات عديمة الرأس لإجراءات تنفّذ منطقًا ثم تُزيل تركيبها ذاتيًا — على سبيل المثال، تشغيل مهمة غير متزامنة، أو الانتقال إلى صفحة، أو إظهار نافذة تأكيد منبثقة. تتوافق بشكل طبيعي مع مكوّنات Command في SDK الموصوفة أدناه.
|
||||
|
||||
```typescript
|
||||
export default defineFrontComponent({
|
||||
universalIdentifier: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
|
||||
name: 'my-action',
|
||||
description: 'Runs an action without opening the side panel',
|
||||
component: MyAction,
|
||||
isHeadless: true,
|
||||
command: {
|
||||
universalIdentifier: 'b2c3d4e5-f6a7-8901-bcde-f12345678901',
|
||||
label: 'Run my action',
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
#### إضافة عناصر قائمة الأوامر
|
||||
|
||||
لجعل مكوّن واجهة أمامية يظهر كعنصر في قائمة الأوامر في Twenty، أضف الخاصية `command` إلى `defineFrontComponent()`. عند فتح المستخدمين لقائمة الأوامر (Cmd+K / Ctrl+K)، يظهر العنصر ويشغّل مكوّن الواجهة الأمامية عند النقر.
|
||||
|
||||
يقبل كائن `command` الحقول التالية:
|
||||
|
||||
| الحقل | النوع | الوصف |
|
||||
| --------------------------------------- | ------------------------------------------ | ------------------------------------------------------------------------------- |
|
||||
| `universalIdentifier` | `string` (إلزامي) | معرّف فريد لعنصر قائمة الأوامر |
|
||||
| `التسمية` | `string` (إلزامي) | التسمية المعروضة في قائمة الأوامر |
|
||||
| `أيقونة` | `string` (اختياري) | اسم الأيقونة (مثال: `'IconSparkles'`) |
|
||||
| `isPinned` | `boolean` (اختياري) | ما إذا كان الأمر مثبتًا أعلى القائمة |
|
||||
| `availabilityType` | `'GLOBAL' \| 'RECORD_SELECTION'` (اختياري) | `GLOBAL` يعرض الأمر في كل مكان؛ `RECORD_SELECTION` يعرضه فقط في سياقات السجلّات |
|
||||
| `availabilityObjectUniversalIdentifier` | `string` (اختياري) | تقييد الأمر بنوع كائن محدّد (مثال: Person) |
|
||||
|
||||
إليك مثالًا من تطبيق تسجيل المكالمات يضيف أمرًا محصورًا بسجلات Person:
|
||||
|
||||
```typescript
|
||||
import { defineFrontComponent } from 'twenty-sdk';
|
||||
|
||||
export default defineFrontComponent({
|
||||
universalIdentifier: 'c3d4e5f6-a7b8-9012-cdef-123456789012',
|
||||
name: 'Summarize Person Call Recordings',
|
||||
description: 'Generates a summary of call recordings for a person',
|
||||
component: SummarizePersonRecordings,
|
||||
command: {
|
||||
universalIdentifier: 'd4e5f6a7-b8c9-0123-defa-234567890123',
|
||||
label: 'Summarize call recordings',
|
||||
icon: 'IconSparkles',
|
||||
isPinned: false,
|
||||
availabilityType: 'RECORD_SELECTION',
|
||||
availabilityObjectUniversalIdentifier:
|
||||
'20202020-e674-48e5-a542-72570eee7213',
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
عند مزامنة الأمر، يظهر في قائمة الأوامر. إذا كان مكوّن الواجهة الأمامية غير عديم الرأس، تُفتح اللوحة الجانبية مع عرض المكوّن بداخلها. إذا كان عديم الرأس، فسيتم تركيب المكوّن في الخلفية وتنفيذ منطقه.
|
||||
|
||||
#### مكوّنات Command في SDK
|
||||
|
||||
توفر حزمة `twenty-sdk` أربعة مكوّنات مساعدة من نوع Command مصممة للمكوّنات عديمة الرأس في الواجهة الأمامية. كل مكوّن ينفّذ إجراءً عند التركيب، ويتعامل مع الأخطاء بعرض إشعار Snackbar، ويزيل تركيب مكوّن الواجهة الأمامية تلقائيًا عند الانتهاء.
|
||||
|
||||
استوردها من `twenty-sdk/command`:
|
||||
|
||||
* **`Command`** — يشغّل رد نداء غير متزامن عبر الخاصية `execute`.
|
||||
* **`CommandLink`** — ينتقل إلى مسار في التطبيق. الخصائص: `to`، `params`، `queryParams`، `options`.
|
||||
* **`CommandModal`** — يفتح نافذة تأكيد منبثقة. إذا أكّد المستخدم، ينفّذ رد النداء `execute`. الخصائص: `title`، `subtitle`، `execute`، `confirmButtonText`، `confirmButtonAccent`.
|
||||
* **`CommandOpenSidePanelPage`** — يفتح صفحة محدّدة في اللوحة الجانبية. الخصائص: `page`، `pageTitle`، `pageIcon`.
|
||||
|
||||
فيما يلي مثال كامل لمكوّن واجهة أمامية عديم الرأس يستخدم `Command` لتشغيل إجراء من قائمة الأوامر:
|
||||
|
||||
```typescript
|
||||
// src/front-components/run-action.tsx
|
||||
import { defineFrontComponent } from 'twenty-sdk';
|
||||
import { Command } from 'twenty-sdk/command';
|
||||
import { CoreApiClient } from 'twenty-sdk/clients';
|
||||
|
||||
const RunAction = () => {
|
||||
const execute = async () => {
|
||||
const client = new CoreApiClient();
|
||||
|
||||
await client.mutation({
|
||||
createTask: {
|
||||
__args: { data: { title: 'Created by my app' } },
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return <Command execute={execute} />;
|
||||
};
|
||||
|
||||
export default defineFrontComponent({
|
||||
universalIdentifier: 'e5f6a7b8-c9d0-1234-efab-345678901234',
|
||||
name: 'run-action',
|
||||
description: 'Creates a task from the command menu',
|
||||
component: RunAction,
|
||||
isHeadless: true,
|
||||
command: {
|
||||
universalIdentifier: 'f6a7b8c9-d0e1-2345-fabc-456789012345',
|
||||
label: 'Run my action',
|
||||
icon: 'IconPlayerPlay',
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
ومثال يستخدم `CommandModal` لطلب التأكيد قبل التنفيذ:
|
||||
|
||||
```typescript
|
||||
// src/front-components/delete-draft.tsx
|
||||
import { defineFrontComponent } from 'twenty-sdk';
|
||||
import { CommandModal } from 'twenty-sdk/command';
|
||||
|
||||
const DeleteDraft = () => {
|
||||
const execute = async () => {
|
||||
// perform the deletion
|
||||
};
|
||||
|
||||
return (
|
||||
<CommandModal
|
||||
title="Delete draft?"
|
||||
subtitle="This action cannot be undone."
|
||||
execute={execute}
|
||||
confirmButtonText="Delete"
|
||||
confirmButtonAccent="danger"
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default defineFrontComponent({
|
||||
universalIdentifier: 'a7b8c9d0-e1f2-3456-abcd-567890123456',
|
||||
name: 'delete-draft',
|
||||
description: 'Deletes a draft with confirmation',
|
||||
component: DeleteDraft,
|
||||
isHeadless: true,
|
||||
command: {
|
||||
universalIdentifier: 'b8c9d0e1-f2a3-4567-bcde-678901234567',
|
||||
label: 'Delete draft',
|
||||
icon: 'IconTrash',
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
#### سياق التنفيذ
|
||||
|
||||
يتلقّى كل مكوّن واجهة أمامية سياق تنفيذ يوفّر معلومات حول مكان وكيفية تشغيله. يمكنك الوصول إلى قيم السياق باستخدام الخطافات من `twenty-sdk`:
|
||||
|
||||
| الخطّاف | نوع القيمة المرجعة | الوصف |
|
||||
| ----------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------- |
|
||||
| `useFrontComponentId()` | `string` | المعرّف الفريد لمثيل مكوّن الواجهة الأمامية الحالي |
|
||||
| `useRecordId()` | `string \| null` | معرّف السجل الحالي، عندما يعمل المكوّن في سياق سجل (مثال: ويدجت صفحة سجل أو أمر محصور بسجل). يُرجع `null` خلاف ذلك. |
|
||||
| `useUserId()` | `string \| null` | معرّف المستخدم الحالي |
|
||||
|
||||
```typescript
|
||||
import { useRecordId, useUserId } from 'twenty-sdk';
|
||||
|
||||
const MyWidget = () => {
|
||||
const recordId = useRecordId();
|
||||
const userId = useUserId();
|
||||
|
||||
return (
|
||||
<div>
|
||||
<p>Record: {recordId ?? 'none'}</p>
|
||||
<p>User: {userId ?? 'anonymous'}</p>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
السياق تفاعلي — إذا تغيّر السجل المحيط، فستُرجع الخطافات القيم المحدّثة تلقائيًا.
|
||||
|
||||
#### دوال واجهة برمجة تطبيقات المضيف
|
||||
|
||||
تعمل مكوّنات الواجهة الأمامية في بيئة معزولة، لكنها تستطيع التفاعل مع واجهة مستخدم Twenty عبر مجموعة من الدوال التي يوفّرها المضيف. استوردها مباشرةً من `twenty-sdk`:
|
||||
|
||||
```typescript
|
||||
import {
|
||||
navigate,
|
||||
closeSidePanel,
|
||||
enqueueSnackbar,
|
||||
unmountFrontComponent,
|
||||
openSidePanelPage,
|
||||
openCommandConfirmationModal,
|
||||
} from 'twenty-sdk';
|
||||
```
|
||||
|
||||
| دالة | التوقيع | الوصف |
|
||||
| ------------------------------ | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `التنقل` | `(to, params?, queryParams?, options?) => Promise<void>` | الانتقال إلى مسار تطبيق محدّد النوع داخل Twenty |
|
||||
| `closeSidePanel` | `() => Promise<void>` | إغلاق اللوحة الجانبية |
|
||||
| `enqueueSnackbar` | `(params) => Promise<void>` | عرض إشعار Snackbar. المعاملات: `message`، `variant` (`'error'`، `'success'`، `'info'`، `'warning'`)، `duration` اختياري، `detailedMessage`، `dedupeKey` |
|
||||
| `unmountFrontComponent` | `() => Promise<void>` | إلغاء تركيب مكوّن الواجهة الأمامية الحالي (تستخدمه المكوّنات عديمة الرأس للتنظيف بعد التنفيذ) |
|
||||
| `openSidePanelPage` | `(params) => Promise<void>` | فتح صفحة في اللوحة الجانبية. المعاملات: `page`، `pageTitle`، `pageIcon`، `shouldResetSearchState` |
|
||||
| `openCommandConfirmationModal` | `(params) => Promise<'confirm' \| 'cancel'>` | عرض نافذة تأكيد منبثقة والانتظار لرد المستخدم. المعاملات: `title`، `subtitle`، `confirmButtonText`، `confirmButtonAccent` (`'default'`، `'blue'`، `'danger'`) |
|
||||
|
||||
فيما يلي مثال يستخدم واجهة برمجة تطبيقات المضيف لعرض Snackbar وإغلاق اللوحة الجانبية بعد اكتمال الإجراء:
|
||||
|
||||
```typescript
|
||||
import { defineFrontComponent, useRecordId } from 'twenty-sdk';
|
||||
import { enqueueSnackbar, closeSidePanel } from 'twenty-sdk';
|
||||
import { CoreApiClient } from 'twenty-sdk/clients';
|
||||
|
||||
const ArchiveRecord = () => {
|
||||
const recordId = useRecordId();
|
||||
|
||||
const handleArchive = async () => {
|
||||
const client = new CoreApiClient();
|
||||
|
||||
await client.mutation({
|
||||
updateTask: {
|
||||
__args: { id: recordId, data: { status: 'ARCHIVED' } },
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
await enqueueSnackbar({
|
||||
message: 'Record archived',
|
||||
variant: 'success',
|
||||
});
|
||||
|
||||
await closeSidePanel();
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ padding: '20px' }}>
|
||||
<p>Archive this record?</p>
|
||||
<button onClick={handleArchive}>Archive</button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default defineFrontComponent({
|
||||
universalIdentifier: 'c9d0e1f2-a3b4-5678-cdef-789012345678',
|
||||
name: 'archive-record',
|
||||
description: 'Archives the current record',
|
||||
component: ArchiveRecord,
|
||||
});
|
||||
```
|
||||
|
||||
### المهارات
|
||||
|
||||
تُحدِّد المهارات تعليمات وإمكانات قابلة لإعادة الاستخدام يمكن لوكلاء الذكاء الاصطناعي استخدامها داخل مساحة العمل لديك. استخدم `defineSkill()` لتعريف مهارات مع تحقّق مدمج:
|
||||
@@ -1121,9 +806,9 @@ export default defineSkill({
|
||||
* **مُنشأ بالقالب**: شغِّل `yarn twenty entity:add` واختر خيار إضافة مهارة جديدة.
|
||||
* **يدوي**: أنشئ ملفًا جديدًا واستخدم `defineSkill()` مع اتباع النمط نفسه.
|
||||
|
||||
### الوكلاء
|
||||
### Agents
|
||||
|
||||
تمكّنك ميزة الوكلاء من تعريف وكلاء ذكاء اصطناعي قادرين على العمل ضمن مساحة عملك، باستخدام موجهات النظام. استخدم `defineAgent()` لتعريف وكلاء مع تحقق مدمج:
|
||||
Agents define AI agents with system prompts that can operate within your workspace. Use `defineAgent()` to define agents with built-in validation:
|
||||
|
||||
```typescript
|
||||
// src/agents/example-agent.ts
|
||||
@@ -1145,27 +830,26 @@ export default defineAgent({
|
||||
|
||||
النقاط الرئيسية:
|
||||
|
||||
* `name` هي سلسلة معرّف فريدة للوكيل (يُنصَح باستخدام kebab-case).
|
||||
* `name` is a unique identifier string for the agent (kebab-case recommended).
|
||||
* `label` هو اسم العرض المقروء للبشر الظاهر في واجهة المستخدم.
|
||||
* `prompt` يحتوي موجه النظام — وهو نص التعليمات الذي يحدد سلوك الوكيل.
|
||||
* `prompt` contains the system prompt — this is the instruction text that defines the agent's behavior.
|
||||
* `icon` (اختياري) يحدّد الأيقونة المعروضة في واجهة المستخدم.
|
||||
* `description` (اختياري) يوفّر سياقًا إضافيًا حول غرض الوكيل.
|
||||
* `description` (optional) provides additional context about the agent's purpose.
|
||||
|
||||
يمكنك إنشاء وكلاء جدد بطريقتين:
|
||||
You can create new agents in two ways:
|
||||
|
||||
* **مُنشأ بالقالب**: شغِّل `yarn twenty entity:add` واختر خيار إضافة وكيل جديد.
|
||||
* **يدوي**: أنشئ ملفًا جديدًا واستخدم `defineAgent()` مع اتباع النمط نفسه.
|
||||
* **Scaffolded**: Run `yarn twenty entity:add` and choose the option to add a new agent.
|
||||
* **Manual**: Create a new file and use `defineAgent()`, following the same pattern.
|
||||
|
||||
### عملاء مُولَّدون مضبوطو الأنواع
|
||||
|
||||
يتم توليد عميلين مضبوطي الأنواع تلقائيًا بواسطة `yarn twenty app:dev` وتخزينهما في `node_modules/twenty-sdk/clients` استنادًا إلى مخطط مساحة العمل لديك:
|
||||
يتم توليد عميلين مضبوطي الأنواع تلقائيًا بواسطة `yarn twenty app:dev` وتخزينهما في `node_modules/twenty-sdk/generated` استنادًا إلى مخطط مساحة العمل لديك:
|
||||
|
||||
* **`CoreApiClient`** — يُجري استعلامات إلى نقطة النهاية `/graphql` للحصول على بيانات مساحة العمل
|
||||
* **`MetadataApiClient`** — يستعلم عن نقطة النهاية `/metadata` لتكوين مساحة العمل وتحميل الملفات.
|
||||
|
||||
```typescript
|
||||
import { CoreApiClient } from 'twenty-sdk/clients';
|
||||
import { MetadataApiClient } from 'twenty-sdk/clients';
|
||||
import { CoreApiClient, MetadataApiClient } from 'twenty-sdk/generated';
|
||||
|
||||
const client = new CoreApiClient();
|
||||
const { me } = await client.query({ me: { id: true, displayName: true } });
|
||||
@@ -1174,7 +858,7 @@ const metadataClient = new MetadataApiClient();
|
||||
const { currentWorkspace } = await metadataClient.query({ currentWorkspace: { id: true } });
|
||||
```
|
||||
|
||||
`CoreApiClient` يُعاد توليده تلقائيًا بواسطة `yarn twenty app:dev` كلما تغيّرت كائناتك أو حقولك. `MetadataApiClient` يأتي مُجهزًا مسبقًا مع SDK.
|
||||
يُعاد توليد كلا العميلين تلقائيًا بواسطة `yarn twenty app:dev` كلما تغيّرت كائناتك أو حقولك.
|
||||
|
||||
#### بيانات الاعتماد وقت التشغيل في الوظائف المنطقية
|
||||
|
||||
@@ -1191,10 +875,10 @@ const { currentWorkspace } = await metadataClient.query({ currentWorkspace: { id
|
||||
|
||||
#### رفع الملفات
|
||||
|
||||
يتضمن `MetadataApiClient` طريقة `uploadFile` لإرفاق الملفات بالحقول من نوع ملف ضمن كائنات مساحة العمل الخاصة بك. نظرًا لأن عملاء GraphQL القياسيون لا يدعمون تحميل الملفات متعددة الأجزاء افتراضيًا، يوفر العميل هذه الطريقة المخصصة التي تطبق [مواصفة طلب GraphQL متعدد الأجزاء](https://github.com/jaydenseric/graphql-multipart-request-spec) في الخلفية.
|
||||
يتضمن `MetadataApiClient` المُولَّد طريقة `uploadFile` لإرفاق الملفات بالحقول من نوع ملف ضمن كائنات مساحة العمل الخاصة بك. نظرًا لأن عملاء GraphQL القياسيون لا يدعمون تحميل الملفات متعددة الأجزاء افتراضيًا، يوفر العميل هذه الطريقة المخصصة التي تطبق [مواصفة طلب GraphQL متعدد الأجزاء](https://github.com/jaydenseric/graphql-multipart-request-spec) في الخلفية.
|
||||
|
||||
```typescript
|
||||
import { MetadataApiClient } from 'twenty-sdk/clients';
|
||||
import { MetadataApiClient } from 'twenty-sdk/generated';
|
||||
import * as fs from 'fs';
|
||||
|
||||
const metadataClient = new MetadataApiClient();
|
||||
|
||||
@@ -15,18 +15,18 @@ description: وسّع وظائف Twenty باستخدام واجهات برمجة
|
||||
|
||||
* **واجهات برمجة التطبيقات**: استعلم وعدّل بيانات إدارة علاقات العملاء (CRM) لديك برمجياً باستخدام REST أو GraphQL
|
||||
* **خطافات الويب**: استقبل إشعارات في الوقت الفعلي عند وقوع أحداث في Twenty
|
||||
* **التطبيقات**: أنشئ تطبيقات مخصصة توسّع قدرات Twenty
|
||||
* **التطبيقات**: أنشئ تطبيقات مخصصة توسّع قدرات Twenty - قريباً!
|
||||
|
||||
## البدء
|
||||
|
||||
<CardGroup cols={٢}>
|
||||
<Card title="واجهات برمجة التطبيقات" icon="كود" href="/l/ar/developers/extend/api">
|
||||
<Card title="واجهات برمجة التطبيقات" icon="كود" href="/l/ar/developers/extend/capabilities/apis">
|
||||
اتصل بـ Twenty برمجياً
|
||||
</Card>
|
||||
<Card title="الويب هوكس" icon="bell" href="/l/ar/developers/extend/webhooks">
|
||||
<Card title="الويب هوكس" icon="bell" href="/l/ar/developers/extend/capabilities/webhooks">
|
||||
احصل على إشعارات بالأحداث في الوقت الفعلي
|
||||
</Card>
|
||||
<Card title="التطبيقات" icon="puzzle-piece" href="/l/ar/developers/extend/apps/getting-started">
|
||||
أنشئ تخصيصات كرمز برمجي
|
||||
<Card title="التطبيقات" icon="puzzle-piece" href="/l/ar/developers/extend/capabilities/apps">
|
||||
أنشئ تخصيصات كرمز برمجي (ألفا)
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
---
|
||||
title: خطافات الويب
|
||||
description: استقبل إشعارات في الوقت الفعلي عند وقوع أحداث في نظام إدارة علاقات العملاء (CRM) الخاص بك.
|
||||
---
|
||||
|
||||
import { VimeoEmbed } from '/snippets/vimeo-embed.mdx';
|
||||
|
||||
تدفع خطافات الويب البيانات إلى أنظمتك في الوقت الفعلي عند وقوع أحداث في Twenty — دون الحاجة إلى الاستطلاع الدوري. استخدمها للحفاظ على تزامن الأنظمة الخارجية، وتشغيل الأتمتة، أو إرسال التنبيهات.
|
||||
|
||||
## إنشاء خطاف ويب
|
||||
|
||||
1. انتقل إلى **الإعدادات → APIs & Webhooks → Webhooks**
|
||||
2. انقر على **+ إنشاء خطاف ويب**
|
||||
3. أدخل عنوان URL لخطاف الويب الخاص بك (يجب أن يكون قابلاً للوصول علنًا)
|
||||
4. انقر على **حفظ**
|
||||
|
||||
يتم تفعيل خطاف الويب فورًا ويبدأ في إرسال الإشعارات.
|
||||
|
||||
<VimeoEmbed videoId="928786708" title="إنشاء خطاف ويب" />
|
||||
|
||||
### إدارة خطافات الويب
|
||||
|
||||
**تحرير**: انقر على خطاف الويب → تحديث عنوان URL → **حفظ**
|
||||
|
||||
**حذف**: انقر على خطاف الويب → **حذف** → تأكيد
|
||||
|
||||
## الأحداث
|
||||
|
||||
يرسل Twenty خطافات الويب لأنواع الأحداث التالية:
|
||||
|
||||
| حدث | مثال |
|
||||
| --------------- | ---------------------------------------------------------- |
|
||||
| **إنشاء سجل** | `person.created`, `company.created`, `note.created` |
|
||||
| **تحديث السجل** | `person.updated`, `company.updated`, `opportunity.updated` |
|
||||
| **حذف السجل** | `person.deleted`, `company.deleted` |
|
||||
|
||||
يتم إرسال جميع أنواع الأحداث إلى عنوان URL لخطاف الويب الخاص بك. قد تتم إضافة تصفية الأحداث في الإصدارات المستقبلية.
|
||||
|
||||
## تنسيق الحمولة
|
||||
|
||||
يرسل كل خطاف ويب طلب HTTP من نوع POST يتضمن جسمًا بصيغة JSON:
|
||||
|
||||
```json
|
||||
{
|
||||
"event": "person.created",
|
||||
"data": {
|
||||
"id": "abc12345",
|
||||
"firstName": "Alice",
|
||||
"lastName": "Doe",
|
||||
"email": "alice@example.com",
|
||||
"createdAt": "2025-02-10T15:30:45Z",
|
||||
"createdBy": "user_123"
|
||||
},
|
||||
"timestamp": "2025-02-10T15:30:50Z"
|
||||
}
|
||||
```
|
||||
|
||||
| الحقل | الوصف |
|
||||
| ----------- | ----------------------------------------------- |
|
||||
| `event` | ما الذي حدث (على سبيل المثال، `person.created`) |
|
||||
| `data` | السجل الكامل الذي تم إنشاؤه/تحديثه/حذفه |
|
||||
| `timestamp` | وقت حدوث الحدث (UTC) |
|
||||
|
||||
<Note>
|
||||
استجب بحالة **HTTP 2xx** (200-299) لتأكيد الاستلام. تُسجَّل الاستجابات غير 2xx كإخفاقات في التسليم.
|
||||
</Note>
|
||||
|
||||
## التحقق من صحة خطاف الويب
|
||||
|
||||
يقوم Twenty بتوقيع كل طلب خطاف ويب لأغراض الأمان. تحقّق من التواقيع للتأكد من أن الطلبات أصيلة.
|
||||
|
||||
### الرؤوس
|
||||
|
||||
| الترويسة | الوصف |
|
||||
| ---------------------------- | ------------------- |
|
||||
| `X-Twenty-Webhook-Signature` | توقيع HMAC SHA256 |
|
||||
| `X-Twenty-Webhook-Timestamp` | الطابع الزمني للطلب |
|
||||
|
||||
### خطوات التحقق
|
||||
|
||||
1. احصل على الطابع الزمني من `X-Twenty-Webhook-Timestamp`
|
||||
2. أنشئ السلسلة: `{timestamp}:{JSON payload}`
|
||||
3. احسب HMAC SHA256 باستخدام سر خطاف الويب الخاص بك
|
||||
4. قارِن مع `X-Twenty-Webhook-Signature`
|
||||
|
||||
### مثال (Node.js)
|
||||
|
||||
```javascript
|
||||
const crypto = require("crypto");
|
||||
|
||||
const timestamp = req.headers["x-twenty-webhook-timestamp"];
|
||||
const payload = JSON.stringify(req.body);
|
||||
const secret = "your-webhook-secret";
|
||||
|
||||
const stringToSign = `${timestamp}:${payload}`;
|
||||
const expectedSignature = crypto
|
||||
.createHmac("sha256", secret)
|
||||
.update(stringToSign)
|
||||
.digest("hex");
|
||||
|
||||
const receivedSignature = req.headers["x-twenty-webhook-signature"];
|
||||
const isValid = crypto.timingSafeEqual(
|
||||
Buffer.from(expectedSignature, "hex"),
|
||||
Buffer.from(receivedSignature, "hex")
|
||||
);
|
||||
```
|
||||
|
||||
## خطافات الويب مقابل سير العمل
|
||||
|
||||
| طريقة | الاتجاه | حالة الاستخدام |
|
||||
| ----------------------------- | ------- | ----------------------------------------------------------- |
|
||||
| **خطافات الويب** | OUT | إخطار الأنظمة الخارجية تلقائيًا بأي تغيير في السجل |
|
||||
| **سير العمل + طلب HTTP** | OUT | إرسال البيانات إلى الخارج بمنطق مخصص (عوامل تصفية، تحويلات) |
|
||||
| **مشغّل خطاف ويب لسير العمل** | IN | استقبال البيانات في Twenty من الأنظمة الخارجية |
|
||||
|
||||
لاستقبال البيانات الخارجية، راجع [إعداد مشغّل خطاف الويب](/l/ar/user-guide/workflows/how-tos/connect-to-other-tools/set-up-a-webhook-trigger).
|
||||
@@ -149,8 +149,8 @@
|
||||
"extend": {
|
||||
"label": "التوسيع",
|
||||
"groups": {
|
||||
"apps": {
|
||||
"label": "التطبيقات"
|
||||
"extendCapabilities": {
|
||||
"label": "القدرات"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -24,7 +24,7 @@ import { VimeoEmbed } from '/snippets/vimeo-embed.mdx';
|
||||
* يتم تصدير **الأعمدة المرئية** فقط
|
||||
* يتم تصدير **السجلات المصفّاة** فقط (استنادًا إلى العرض الحالي لديك)
|
||||
|
||||
<Note>بالنسبة لعمليات التصدير الأكبر (أكثر من 20,000 سجل)، استخدم عوامل التصفية للتصدير على دفعات أو استخدم [واجهة برمجة التطبيقات (API)](/l/ar/developers/extend/api).</Note>
|
||||
<Note>بالنسبة لعمليات التصدير الأكبر (أكثر من 20,000 سجل)، استخدم عوامل التصفية للتصدير على دفعات أو استخدم [واجهة برمجة التطبيقات (API)](/l/ar/developers/extend/capabilities/apis).</Note>
|
||||
|
||||
### الصلاحيات
|
||||
|
||||
@@ -148,7 +148,7 @@ import { VimeoEmbed } from '/snippets/vimeo-embed.mdx';
|
||||
2. استخدم واجهة برمجة تطبيقات GraphQL للاستعلام عن السجلات
|
||||
3. عالج النتائج في تطبيقك
|
||||
|
||||
راجع: [وثائق واجهة برمجة التطبيقات (API)](/l/ar/developers/extend/api)
|
||||
راجع: [وثائق واجهة برمجة التطبيقات (API)](/l/ar/developers/extend/capabilities/apis)
|
||||
|
||||
## نصائح وأفضل الممارسات
|
||||
|
||||
@@ -206,4 +206,4 @@ import { VimeoEmbed } from '/snippets/vimeo-embed.mdx';
|
||||
|
||||
* [كيفية تحديث السجلات الموجودة](/l/ar/user-guide/data-migration/how-tos/update-existing-records-via-import) — حرّر وأعد استيراد ملف التصدير الخاص بك
|
||||
* [كيفية استيراد البيانات عبر واجهة برمجة التطبيقات (API)](/l/ar/user-guide/data-migration/how-tos/import-data-via-api) — لمجموعات البيانات الكبيرة
|
||||
* [وثائق واجهة برمجة التطبيقات (API)](/l/ar/developers/extend/api) — أنشئ عمليات سير عمل تصدير مخصصة
|
||||
* [وثائق واجهة برمجة التطبيقات (API)](/l/ar/developers/extend/capabilities/apis) — أنشئ عمليات سير عمل تصدير مخصصة
|
||||
|
||||
@@ -57,10 +57,10 @@ description: متى وكيف تستخدم واجهات API الخاصة بـ Twe
|
||||
|
||||
تدعم Twenty نوعين من واجهات API:
|
||||
|
||||
| واجهة برمجة التطبيقات | الأفضل لـ | التوثيق |
|
||||
| --------------------- | ------------------------------------------------------ | ----------------------------------- |
|
||||
| **GraphQL** | استعلامات مرنة، وجلب البيانات المرتبطة، وعمليات معقّدة | [وثائق API](/l/ar/developers/extend/api) |
|
||||
| **REST** | عمليات CRUD بسيطة، وأنماط REST مألوفة | [وثائق API](/l/ar/developers/extend/api) |
|
||||
| واجهة برمجة التطبيقات | الأفضل لـ | التوثيق |
|
||||
| --------------------- | ------------------------------------------------------ | ------------------------------------------------- |
|
||||
| **GraphQL** | استعلامات مرنة، وجلب البيانات المرتبطة، وعمليات معقّدة | [وثائق API](/l/ar/developers/extend/capabilities/apis) |
|
||||
| **REST** | عمليات CRUD بسيطة، وأنماط REST مألوفة | [وثائق API](/l/ar/developers/extend/capabilities/apis) |
|
||||
|
||||
كلتا واجهتي API تدعمان:
|
||||
|
||||
@@ -173,4 +173,4 @@ description: متى وكيف تستخدم واجهات API الخاصة بـ Twe
|
||||
|
||||
للحصول على تفاصيل التنفيذ الكاملة وأمثلة الشيفرة ومرجع المخطط (schema):
|
||||
|
||||
* [وثائق API](/l/ar/developers/extend/api)
|
||||
* [وثائق API](/l/ar/developers/extend/capabilities/apis)
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@ description: Twenty هو نظام إدارة علاقات العملاء (CRM)
|
||||
* **لوحات التحكم:** تتبع الأداء باستخدام تقارير مخصصة وتصوّرات مرئية. [عرض لوحات التحكم](/l/ar/user-guide/dashboards/overview).
|
||||
* **الأذونات والوصول:** تحكّم في مَن يمكنه عرض بياناتك وتحريرها وإدارتها باستخدام أذونات مستندة إلى الأدوار. [تكوين الوصول](/l/ar/user-guide/permissions-access/overview).
|
||||
* **الملاحظات والمهام:** أنشئ ملاحظات ومهام مرتبطة بسجلاتك لتحسين التعاون.
|
||||
* **واجهة برمجة التطبيقات والويب هوكس:** الاتصال بالتطبيقات الأخرى وإنشاء عمليات تكامل مخصصة. [ابدأ التكامل](/l/ar/developers/extend/api).
|
||||
* **واجهة برمجة التطبيقات والويب هوكس:** الاتصال بالتطبيقات الأخرى وإنشاء عمليات تكامل مخصصة. [ابدأ التكامل](/l/ar/developers/extend/capabilities/apis).
|
||||
|
||||
## انضم الآن
|
||||
|
||||
|
||||
+1
-1
@@ -95,7 +95,7 @@ description: اعرض بيانات من سجلات مرتبطة (مثل معلو
|
||||
* حجم الشركة: `{{searchRecords[0].employees}}`
|
||||
|
||||
<Note>
|
||||
**قيود المهام والملاحظات**: العلاقات في المهام والملاحظات مُحدّدة في الشفرة كعلاقات متعدّدة-لمتعدّدة وليست متاحة بعد في محفّزات أو إجراءات سير العمل. للوصول إلى هذه العلاقات، استخدم بدلًا من ذلك [API](/l/ar/developers/extend/api).
|
||||
**قيود المهام والملاحظات**: العلاقات في المهام والملاحظات مُحدّدة في الشفرة كعلاقات متعدّدة-لمتعدّدة وليست متاحة بعد في محفّزات أو إجراءات سير العمل. للوصول إلى هذه العلاقات، استخدم بدلًا من ذلك [API](/l/ar/developers/extend/capabilities/apis).
|
||||
</Note>
|
||||
|
||||
## مزامنة ثنائية الاتجاه
|
||||
|
||||
+1
-1
@@ -77,7 +77,7 @@ To avoid unnecessary [re-renders](/l/cs/developers/contribute/capabilities/front
|
||||
|
||||
### Správa stavu
|
||||
|
||||
[Jotai](https://jotai.org/) handles state management.
|
||||
[Jotai](https://jotai.org/) zajišťuje správu stavu.
|
||||
|
||||
Podívejte se na [osvědčené postupy](/l/cs/developers/contribute/capabilities/frontend-development/best-practices-front#state-management) pro více informací o správě stavu.
|
||||
|
||||
|
||||
@@ -171,7 +171,7 @@ export default defineObject({
|
||||
|
||||
Pozdější příkazy přidají další soubory a složky:
|
||||
|
||||
* `yarn twenty app:dev` will auto-generate two typed API clients in `node_modules/twenty-sdk/clients`: `CoreApiClient` (for workspace data via `/graphql`) and `MetadataApiClient` (for workspace configuration and file uploads via `/metadata`).
|
||||
* `yarn twenty app:dev` automaticky vygeneruje dva typované API klienty v `node_modules/twenty-sdk/generated`: `CoreApiClient` (pro data pracovního prostoru přes `/graphql`) a `MetadataApiClient` (pro konfiguraci pracovního prostoru a nahrávání souborů přes `/metadata`).
|
||||
* `yarn twenty entity:add` přidá soubory s definicemi entit do `src/` pro vaše vlastní objekty, funkce, frontové komponenty, role, dovednosti a další.
|
||||
|
||||
## Ověření
|
||||
@@ -228,7 +228,7 @@ SDK poskytuje pomocné funkce pro definování entit vaší aplikace. Jak je pop
|
||||
| `defineView()` | Definujte uložená zobrazení pro objekty |
|
||||
| `defineNavigationMenuItem()` | Definujte odkazy postranní navigace |
|
||||
| `defineSkill()` | Definuje dovednosti agenta AI |
|
||||
| `defineAgent()` | Definujte AI agenty pomocí systémových promptů |
|
||||
| `defineAgent()` | Define AI agents with system prompts |
|
||||
|
||||
Tyto funkce validují vaši konfiguraci v době sestavení a poskytují automatické doplňování v IDE a typovou bezpečnost.
|
||||
|
||||
@@ -434,7 +434,7 @@ Každý soubor funkce používá `defineLogicFunction()` k exportu konfigurace s
|
||||
// src/app/createPostCard.logic-function.ts
|
||||
import { defineLogicFunction } from 'twenty-sdk';
|
||||
import type { DatabaseEventPayload, ObjectRecordCreateEvent, CronPayload, RoutePayload } from 'twenty-sdk';
|
||||
import { CoreApiClient, type Person } from 'twenty-sdk/clients';
|
||||
import { CoreApiClient, type Person } from 'twenty-sdk/generated';
|
||||
|
||||
const handler = async (params: RoutePayload) => {
|
||||
const client = new CoreApiClient();
|
||||
@@ -679,7 +679,7 @@ Chcete-li označit logickou funkci jako nástroj, nastavte `isTool: true` a posk
|
||||
```typescript
|
||||
// src/logic-functions/enrich-company.logic-function.ts
|
||||
import { defineLogicFunction } from 'twenty-sdk';
|
||||
import { CoreApiClient } from 'twenty-sdk/clients';
|
||||
import { CoreApiClient } from 'twenty-sdk/generated';
|
||||
|
||||
const handler = async (params: { companyName: string; domain?: string }) => {
|
||||
const client = new CoreApiClient();
|
||||
@@ -808,7 +808,7 @@ Nové dovednosti můžete vytvářet dvěma způsoby:
|
||||
|
||||
### Agenti
|
||||
|
||||
Agenti jsou AI agenti se systémovými prompty, kteří mohou fungovat ve vašem pracovním prostoru. K definování agentů s vestavěnou validací použijte `defineAgent()`:
|
||||
Agents define AI agents with system prompts that can operate within your workspace. Use `defineAgent()` to define agents with built-in validation:
|
||||
|
||||
```typescript
|
||||
// src/agents/example-agent.ts
|
||||
@@ -830,27 +830,26 @@ export default defineAgent({
|
||||
|
||||
Hlavní body:
|
||||
|
||||
* `name` je jedinečný identifikátor agenta (doporučuje se kebab-case).
|
||||
* `name` is a unique identifier string for the agent (kebab-case recommended).
|
||||
* `label` je uživatelsky čitelný název zobrazovaný v UI.
|
||||
* `prompt` obsahuje systémový prompt — jde o instrukční text, který určuje chování agenta.
|
||||
* `prompt` contains the system prompt — this is the instruction text that defines the agent's behavior.
|
||||
* `icon` (volitelné) nastavuje ikonu zobrazovanou v UI.
|
||||
* `description` (volitelné) poskytuje doplňující kontext o účelu agenta.
|
||||
* `description` (optional) provides additional context about the agent's purpose.
|
||||
|
||||
Nové agenty můžete vytvářet dvěma způsoby:
|
||||
You can create new agents in two ways:
|
||||
|
||||
* **Vygenerované**: Spusťte `yarn twenty entity:add` a zvolte možnost přidat nového agenta.
|
||||
* **Ruční**: Vytvořte nový soubor a použijte `defineAgent()` podle stejného vzoru.
|
||||
* **Scaffolded**: Run `yarn twenty entity:add` and choose the option to add a new agent.
|
||||
* **Manual**: Create a new file and use `defineAgent()`, following the same pattern.
|
||||
|
||||
### Generované typované klienty
|
||||
|
||||
Two typed clients are auto-generated by `yarn twenty app:dev` and stored in `node_modules/twenty-sdk/clients` based on your workspace schema:
|
||||
Dva typované klienty jsou automaticky generovány pomocí `yarn twenty app:dev` a ukládají se do `node_modules/twenty-sdk/generated` podle schématu vašeho pracovního prostoru:
|
||||
|
||||
* **`CoreApiClient`** — provádí dotazy na endpoint `/graphql` za účelem získání dat pracovního prostoru
|
||||
* **`MetadataApiClient`** — odesílá dotazy na endpoint `/metadata` pro konfiguraci pracovního prostoru a nahrávání souborů
|
||||
|
||||
```typescript
|
||||
import { CoreApiClient } from 'twenty-sdk/clients';
|
||||
import { MetadataApiClient } from 'twenty-sdk/clients';
|
||||
import { CoreApiClient, MetadataApiClient } from 'twenty-sdk/generated';
|
||||
|
||||
const client = new CoreApiClient();
|
||||
const { me } = await client.query({ me: { id: true, displayName: true } });
|
||||
@@ -859,7 +858,7 @@ const metadataClient = new MetadataApiClient();
|
||||
const { currentWorkspace } = await metadataClient.query({ currentWorkspace: { id: true } });
|
||||
```
|
||||
|
||||
`CoreApiClient` is re-generated automatically by `yarn twenty app:dev` whenever your objects or fields change. `MetadataApiClient` ships pre-built with the SDK.
|
||||
Oba klienti se automaticky znovu generují pomocí `yarn twenty app:dev` kdykoli se změní vaše objekty nebo pole.
|
||||
|
||||
#### Běhové přihlašovací údaje v logických funkcích
|
||||
|
||||
@@ -876,10 +875,10 @@ Poznámky:
|
||||
|
||||
#### Nahrávání souborů
|
||||
|
||||
The `MetadataApiClient` includes an `uploadFile` method for attaching files to file-type fields on your workspace objects. Protože standardní klienti GraphQL nativně nepodporují nahrávání souborů pomocí multipart, klient poskytuje tuto speciální metodu, která interně implementuje [specifikaci multipart požadavků GraphQL](https://github.com/jaydenseric/graphql-multipart-request-spec).
|
||||
Vygenerovaný `MetadataApiClient` obsahuje metodu `uploadFile` pro připojování souborů k polím typu souboru u objektů ve vašem pracovním prostoru. Protože standardní klienti GraphQL nativně nepodporují nahrávání souborů pomocí multipart, klient poskytuje tuto speciální metodu, která interně implementuje [specifikaci multipart požadavků GraphQL](https://github.com/jaydenseric/graphql-multipart-request-spec).
|
||||
|
||||
```typescript
|
||||
import { MetadataApiClient } from 'twenty-sdk/clients';
|
||||
import { MetadataApiClient } from 'twenty-sdk/generated';
|
||||
import * as fs from 'fs';
|
||||
|
||||
const metadataClient = new MetadataApiClient();
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
---
|
||||
title: Rozšiřte
|
||||
description: Rozšiřte funkčnost Twenty pomocí rozhraní API, webhooků a vlastních aplikací.
|
||||
redirect: /developers/introduction
|
||||
---
|
||||
|
||||
<Frame>
|
||||
@@ -21,13 +20,13 @@ Twenty je navrženo tak, aby bylo rozšiřitelné. Použijte naše rozhraní API
|
||||
## Začínáme
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="API" icon="kód" href="/l/cs/developers/api">
|
||||
<Card title="API" icon="kód" href="/l/cs/developers/extend/capabilities/apis">
|
||||
Programově se připojte k Twenty
|
||||
</Card>
|
||||
<Card title="Webhooky" icon="bell" href="/l/cs/developers/webhooks">
|
||||
<Card title="Webhooky" icon="bell" href="/l/cs/developers/extend/capabilities/webhooks">
|
||||
Dostávejte oznámení o událostech v reálném čase
|
||||
</Card>
|
||||
<Card title="Aplikace" icon="puzzle-piece" href="/l/cs/developers/apps/apps">
|
||||
<Card title="Aplikace" icon="puzzle-piece" href="/l/cs/developers/extend/capabilities/apps">
|
||||
Vytvářejte přizpůsobení jako kód (Alpha)
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
@@ -5,28 +5,18 @@ description: Vítejte v dokumentaci pro vývojáře Twenty, která je vaším zd
|
||||
|
||||
import { CardTitle } from "/snippets/card-title.mdx"
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card href="/l/cs/developers/api" icon="code">
|
||||
<CardTitle>API</CardTitle>
|
||||
Dotazujte a upravujte data CRM pomocí REST nebo GraphQL.
|
||||
<CardGroup cols={3}>
|
||||
<Card href="/l/cs/developers/extend/extend" img="/images/user-guide/integrations/plug.png">
|
||||
<CardTitle>Rozšiřte</CardTitle>
|
||||
Vytvářejte integrace pomocí API, webhooků a vlastních aplikací.
|
||||
</Card>
|
||||
|
||||
<Card href="/l/cs/developers/webhooks" icon="bell">
|
||||
<CardTitle>Webhooks</CardTitle>
|
||||
Přijímejte oznámení v reálném čase při výskytu událostí.
|
||||
</Card>
|
||||
|
||||
<Card href="/l/cs/developers/apps/apps" icon="puzzle-piece">
|
||||
<CardTitle>Apps</CardTitle>
|
||||
Vytvářejte vlastní aplikace rozšiřující možnosti Twenty.
|
||||
</Card>
|
||||
|
||||
<Card href="/l/cs/developers/self-host/self-host" icon="desktop">
|
||||
<Card href="/l/cs/developers/self-host/self-host" img="/images/user-guide/what-is-twenty/20.png">
|
||||
<CardTitle>Hostujte sami</CardTitle>
|
||||
Nasaďte a spravujte Twenty na vlastní infrastruktuře.
|
||||
</Card>
|
||||
|
||||
<Card href="/l/cs/developers/contribute/contribute" icon="github">
|
||||
<Card href="/l/cs/developers/contribute/contribute" img="/images/user-guide/github/github-header.png">
|
||||
<CardTitle>Přispějte</CardTitle>
|
||||
Připojte se k naší open-source komunitě a přispívejte do Twenty.
|
||||
</Card>
|
||||
|
||||
@@ -24,7 +24,7 @@ Exportujte data svého pracovního prostoru do CSV pro zálohování, vytvářen
|
||||
* Exportují se pouze **viditelné sloupce**
|
||||
* Exportují se pouze **filtrované záznamy** (podle vašeho aktuálního zobrazení)
|
||||
|
||||
<Note>U větších exportů (20 000+ záznamů) použijte filtry pro export po dávkách nebo použijte [API](/l/cs/developers/api).</Note>
|
||||
<Note>U větších exportů (20 000+ záznamů) použijte filtry pro export po dávkách nebo použijte [API](/l/cs/developers/extend/capabilities/apis).</Note>
|
||||
|
||||
### Oprávnění
|
||||
|
||||
@@ -148,7 +148,7 @@ API nemá limit počtu záznamů:
|
||||
2. Použijte GraphQL API k dotazování na záznamy
|
||||
3. Zpracujte výsledky ve své aplikaci
|
||||
|
||||
Viz: [Dokumentace API](/l/cs/developers/api)
|
||||
Viz: [Dokumentace API](/l/cs/developers/extend/capabilities/apis)
|
||||
|
||||
## Tipy a osvědčené postupy
|
||||
|
||||
@@ -206,4 +206,4 @@ Exportované soubory mohou obsahovat citlivá data:
|
||||
|
||||
* [Jak aktualizovat existující záznamy](/l/cs/user-guide/data-migration/how-tos/update-existing-records-via-import) — upravte a znovu importujte svůj export
|
||||
* [Jak importovat data přes API](/l/cs/user-guide/data-migration/how-tos/import-data-via-api) — pro velké datové sady
|
||||
* [Dokumentace API](/l/cs/developers/api) — vytvářejte vlastní pracovní postupy pro export
|
||||
* [Dokumentace API](/l/cs/developers/extend/capabilities/apis) — vytvářejte vlastní pracovní postupy pro export
|
||||
|
||||
@@ -59,8 +59,8 @@ Twenty podporuje dva typy API:
|
||||
|
||||
| API | Vhodné pro | Dokumentace |
|
||||
| ----------- | ----------------------------------------------------------------- | ------------------------------------------------------- |
|
||||
| **GraphQL** | Flexibilní dotazy, získávání souvisejících dat, komplexní operace | [Dokumentace API](/l/cs/developers/api) |
|
||||
| **REST** | Jednoduché CRUD operace, známé postupy REST | [Dokumentace API](/l/cs/developers/api) |
|
||||
| **GraphQL** | Flexibilní dotazy, získávání souvisejících dat, komplexní operace | [Dokumentace API](/l/cs/developers/extend/capabilities/apis) |
|
||||
| **REST** | Jednoduché CRUD operace, známé postupy REST | [Dokumentace API](/l/cs/developers/extend/capabilities/apis) |
|
||||
|
||||
Obě API podporují:
|
||||
|
||||
@@ -173,4 +173,4 @@ Kontaktujte nás na [contact@twenty.com](mailto:contact@twenty.com) nebo prozkou
|
||||
|
||||
Úplné podrobnosti implementace, ukázky kódu a referenci schématu najdete zde:
|
||||
|
||||
* [Dokumentace API](/l/cs/developers/api)
|
||||
* [Dokumentace API](/l/cs/developers/extend/capabilities/apis)
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@ Open-source je základ našeho přístupu, zajišťuje, že Twenty se vyvíjí s
|
||||
* **Přehledy:** Sledujte výkon pomocí vlastních sestav a vizualizací. [Zobrazit přehledy](/l/cs/user-guide/dashboards/overview).
|
||||
* **Oprávnění a přístup:** Ovládejte, kdo může zobrazit, upravovat a spravovat vaše data pomocí oprávnění založených na rolích. [Nastavte přístup](/l/cs/user-guide/permissions-access/overview).
|
||||
* **Poznámky a úkoly:** Vytvářejte poznámky a úkoly propojené s vašimi záznamy pro lepší spolupráci.
|
||||
* **API & Webhooks:** Připojte se k dalším aplikacím a vytvářejte vlastní integrace. [Začněte integraci](/l/cs/developers/api).
|
||||
* **API & Webhooks:** Připojte se k dalším aplikacím a vytvářejte vlastní integrace. [Začněte integraci](/l/cs/developers/extend/capabilities/apis).
|
||||
|
||||
## Připojte se nyní
|
||||
|
||||
|
||||
+1
-1
@@ -95,7 +95,7 @@ Vytvořte cílová pole v **Nastavení → Datový model → Příležitosti**:
|
||||
* Velikost společnosti: `{{searchRecords[0].employees}}`
|
||||
|
||||
<Note>
|
||||
**Omezení pro Úkoly a Poznámky**: Relace u Úkolů a Poznámek jsou napevno nastaveny jako mnoho k mnoha a zatím nejsou k dispozici ve spouštěčích ani akcích pracovních postupů. Pro přístup k těmto relacím použijte místo toho [API](/l/cs/developers/api).
|
||||
**Omezení pro Úkoly a Poznámky**: Relace u Úkolů a Poznámek jsou napevno nastaveny jako mnoho k mnoha a zatím nejsou k dispozici ve spouštěčích ani akcích pracovních postupů. Pro přístup k těmto relacím použijte místo toho [API](/l/cs/developers/extend/capabilities/apis).
|
||||
</Note>
|
||||
|
||||
## Oboustranná synchronizace
|
||||
|
||||
@@ -1,147 +0,0 @@
|
||||
---
|
||||
title: APIs
|
||||
description: Abfragen und ändern Sie Ihre CRM-Daten programmatisch mit REST oder GraphQL.
|
||||
---
|
||||
|
||||
import { VimeoEmbed } from '/snippets/vimeo-embed.mdx';
|
||||
|
||||
Twenty wurde so entwickelt, dass es entwicklerfreundlich ist und leistungsstarke APIs bietet, die sich an Ihr individuelles Datenmodell anpassen. Wir bieten vier verschiedene API-Typen, um unterschiedlichen Integrationsanforderungen gerecht zu werden.
|
||||
|
||||
## Developer-First-Ansatz
|
||||
|
||||
Twenty generiert APIs speziell für Ihr Datenmodell:
|
||||
|
||||
* **Keine langen IDs erforderlich**: Verwenden Sie Ihre Objekt- und Feldnamen direkt in Endpunkten
|
||||
* **Standard- und benutzerdefinierte Objekte werden gleich behandelt**: Ihre benutzerdefinierten Objekte erhalten dieselbe API-Behandlung wie integrierte Objekte
|
||||
* **Dedizierte Endpunkte**: Jedes Objekt und Feld erhält seinen eigenen API-Endpunkt
|
||||
* **Benutzerdefinierte Dokumentation**: Speziell für das Datenmodell Ihres Arbeitsbereichs generiert
|
||||
|
||||
<Note>
|
||||
Ihre personalisierte API-Dokumentation ist nach dem Erstellen eines API-Schlüssels unter **Einstellungen → API & Webhooks** verfügbar. Da Twenty APIs erzeugt, die Ihrem benutzerdefinierten Datenmodell entsprechen, ist die Dokumentation für Ihren Arbeitsbereich einzigartig.
|
||||
</Note>
|
||||
|
||||
## Die beiden API-Typen
|
||||
|
||||
### Core API
|
||||
|
||||
Zugriff auf `/rest/` oder `/graphql/`
|
||||
|
||||
Arbeiten Sie mit Ihren tatsächlichen **Datensätzen** (den Daten):
|
||||
|
||||
* Personen, Unternehmen, Opportunities usw. erstellen, lesen, aktualisieren und löschen
|
||||
* Daten abfragen und filtern
|
||||
* Datensatzbeziehungen verwalten
|
||||
|
||||
### Metadata API
|
||||
|
||||
Zugriff auf `/rest/metadata/` oder `/metadata/`
|
||||
|
||||
Verwalten Sie Ihren **Arbeitsbereich und Ihr Datenmodell**:
|
||||
|
||||
* Objekte und Felder erstellen, ändern oder löschen
|
||||
* Arbeitsbereichseinstellungen konfigurieren
|
||||
* Beziehungen zwischen Objekten definieren
|
||||
|
||||
## REST vs GraphQL
|
||||
|
||||
Sowohl Core- als auch Metadata-APIs sind in REST- und GraphQL-Formaten verfügbar:
|
||||
|
||||
| Format | Verfügbare Vorgänge |
|
||||
| ----------- | ------------------------------------------------------------------- |
|
||||
| **REST** | CRUD, Batch-Vorgänge, Upserts |
|
||||
| **GraphQL** | Dasselbe plus **Batch-Upserts**, Beziehungsabfragen in einem Aufruf |
|
||||
|
||||
Wählen Sie je nach Bedarf — beide Formate greifen auf dieselben Daten zu.
|
||||
|
||||
## API-Endpunkte
|
||||
|
||||
| Umgebung | Basis-URL |
|
||||
| ----------------- | ------------------------- |
|
||||
| **Cloud** | `https://api.twenty.com/` |
|
||||
| **Selbsthosting** | `https://{your-domain}/` |
|
||||
|
||||
## Authentifizierung
|
||||
|
||||
Jede API-Anfrage erfordert einen API-Schlüssel im Header:
|
||||
|
||||
```
|
||||
Authorization: Bearer YOUR_API_KEY
|
||||
```
|
||||
|
||||
### API-Schlüssel erstellen
|
||||
|
||||
1. Gehen Sie zu **Einstellungen → APIs & Webhooks**
|
||||
2. Klicken Sie auf **+ Schlüssel erstellen**
|
||||
3. Konfigurieren:
|
||||
* **Name**: Beschreibender Name für den Schlüssel
|
||||
* **Ablaufdatum**: Wann der Schlüssel abläuft
|
||||
4. Klicken Sie auf **Speichern**
|
||||
5. **Sofort kopieren** — der Schlüssel wird nur einmal angezeigt
|
||||
|
||||
<VimeoEmbed videoId="928786722" title="API-Schlüssel erstellen" />
|
||||
|
||||
<Warning>
|
||||
Ihr API-Schlüssel gewährt Zugriff auf sensible Daten. Teilen Sie ihn nicht mit nicht vertrauenswürdigen Diensten. Wenn er kompromittiert wurde, deaktivieren Sie ihn umgehend und erstellen Sie einen neuen.
|
||||
</Warning>
|
||||
|
||||
### Einem API-Schlüssel eine Rolle zuweisen
|
||||
|
||||
Für mehr Sicherheit weisen Sie eine spezifische Rolle zu, um den Zugriff zu beschränken:
|
||||
|
||||
1. Gehen Sie zu **Einstellungen → Rollen**
|
||||
2. Klicken Sie auf die Rolle, die Sie zuweisen möchten
|
||||
3. Öffnen Sie den Tab **Zuweisungen**
|
||||
4. Unter **API-Schlüssel** auf **+ API-Schlüssel zuweisen** klicken
|
||||
5. Wählen Sie den API-Schlüssel aus
|
||||
|
||||
Der Schlüssel übernimmt die Berechtigungen dieser Rolle. Siehe [Berechtigungen](/l/de/user-guide/permissions-access/capabilities/permissions) für Details.
|
||||
|
||||
### API-Schlüssel verwalten
|
||||
|
||||
**Neu generieren**: Einstellungen → APIs & Webhooks → Schlüssel anklicken → **Neu generieren**
|
||||
|
||||
**Löschen**: Einstellungen → APIs & Webhooks → Schlüssel anklicken → **Löschen**
|
||||
|
||||
## API-Playground
|
||||
|
||||
Testen Sie Ihre APIs direkt im Browser mit unserem integrierten Playground — verfügbar für **REST** und **GraphQL**.
|
||||
|
||||
### Auf den Playground zugreifen
|
||||
|
||||
1. Gehen Sie zu **Einstellungen → APIs & Webhooks**
|
||||
2. API-Schlüssel erstellen (erforderlich)
|
||||
3. Klicken Sie auf **REST API** oder **GraphQL API**, um den Playground zu öffnen
|
||||
|
||||
### Was Sie erhalten
|
||||
|
||||
* **Interaktive Dokumentation**: Für Ihr spezifisches Datenmodell generiert
|
||||
* **Live-Tests**: Führen Sie echte API-Aufrufe gegen Ihren Arbeitsbereich aus
|
||||
* **Schema-Explorer**: Verfügbare Objekte, Felder und Beziehungen durchsuchen
|
||||
* **Request-Builder**: Abfragen mit Autovervollständigung erstellen
|
||||
|
||||
Der Playground spiegelt Ihre benutzerdefinierten Objekte und Felder wider, sodass die Dokumentation für Ihren Arbeitsbereich stets korrekt ist.
|
||||
|
||||
## Batch-Vorgänge
|
||||
|
||||
Sowohl REST als auch GraphQL unterstützen Batch-Vorgänge:
|
||||
|
||||
* **Batch-Größe**: Bis zu 60 Datensätze pro Anfrage
|
||||
* **Vorgänge**: Mehrere Datensätze erstellen, aktualisieren, löschen
|
||||
|
||||
**GraphQL-Exklusivfunktionen:**
|
||||
|
||||
* **Batch-Upsert**: Erstellen oder Aktualisieren in einem Aufruf
|
||||
* Verwenden Sie Pluralobjektnamen (z. B. `CreateCompanies` statt `CreateCompany`)
|
||||
|
||||
## Rate Limits
|
||||
|
||||
API-Anfragen werden gedrosselt, um die Stabilität der Plattform zu gewährleisten:
|
||||
|
||||
| Limit | Wert |
|
||||
| --------------- | ------------------------ |
|
||||
| **Anfragen** | 100 Aufrufe pro Minute |
|
||||
| **Batch-Größe** | 60 Datensätze pro Aufruf |
|
||||
|
||||
<Tip>
|
||||
Verwenden Sie Batch-Vorgänge, um den Durchsatz zu maximieren — verarbeiten Sie bis zu 60 Datensätze in einem einzelnen API-Aufruf, statt einzelne Anfragen zu senden.
|
||||
</Tip>
|
||||
@@ -1,689 +0,0 @@
|
||||
---
|
||||
title: Apps erstellen
|
||||
description: Definieren Sie Objekte, Logikfunktionen, Frontend-Komponenten und mehr mit dem Twenty SDK.
|
||||
---
|
||||
|
||||
<Warning>
|
||||
Apps befinden sich derzeit in der Alpha-Testphase. Die Funktion ist funktionsfähig, entwickelt sich jedoch noch weiter.
|
||||
</Warning>
|
||||
|
||||
## SDK-Ressourcen verwenden (Typen & Konfiguration)
|
||||
|
||||
Das twenty-sdk stellt typisierte Bausteine und Hilfsfunktionen bereit, die Sie in Ihrer App verwenden. Im Folgenden finden Sie die wichtigsten Bausteine, mit denen Sie am häufigsten arbeiten.
|
||||
|
||||
### Hilfsfunktionen
|
||||
|
||||
Das SDK stellt Hilfsfunktionen bereit, um die Entitäten Ihrer App zu definieren. Wie in [Entitätserkennung](/l/de/developers/extend/apps/getting-started#entity-detection) beschrieben, müssen Sie `export default define<Entity>({...})` verwenden, damit Ihre Entitäten erkannt werden:
|
||||
|
||||
| Funktion | Zweck |
|
||||
| -------------------------------- | --------------------------------------------------------------- |
|
||||
| `defineApplication` | Anwendungsmetadaten konfigurieren (erforderlich, eine pro App) |
|
||||
| `defineObject` | Benutzerdefinierte Objekte mit Feldern definieren |
|
||||
| `defineLogicFunction` | Logikfunktionen mit Handlern definieren |
|
||||
| `definePreInstallLogicFunction` | Eine Pre-Installations-Logikfunktion definieren (eine pro App) |
|
||||
| `definePostInstallLogicFunction` | Eine Post-Installations-Logikfunktion definieren (eine pro App) |
|
||||
| `defineFrontComponent` | Frontend-Komponenten für benutzerdefinierte UI definieren |
|
||||
| `defineRole` | Rollenberechtigungen und Objektzugriff konfigurieren |
|
||||
| `defineField` | Bestehende Objekte mit zusätzlichen Feldern erweitern |
|
||||
| `defineView` | Gespeicherte Views für Objekte definieren |
|
||||
| `defineNavigationMenuItem` | Seitenleisten-Navigationslinks definieren |
|
||||
| `defineSkill` | Skills für KI-Agenten definieren |
|
||||
|
||||
Diese Funktionen validieren Ihre Konfiguration zur Build-Zeit und bieten IDE-Autovervollständigung sowie Typsicherheit.
|
||||
|
||||
### Objekte definieren
|
||||
|
||||
Benutzerdefinierte Objekte beschreiben sowohl Schema als auch Verhalten für Datensätze in Ihrem Workspace. Verwenden Sie `defineObject()`, um Objekte mit eingebauter Validierung zu definieren:
|
||||
|
||||
```typescript
|
||||
// src/app/postCard.object.ts
|
||||
import { defineObject, FieldType } from 'twenty-sdk';
|
||||
|
||||
enum PostCardStatus {
|
||||
DRAFT = 'DRAFT',
|
||||
SENT = 'SENT',
|
||||
DELIVERED = 'DELIVERED',
|
||||
RETURNED = 'RETURNED',
|
||||
}
|
||||
|
||||
export default defineObject({
|
||||
universalIdentifier: '54b589ca-eeed-4950-a176-358418b85c05',
|
||||
nameSingular: 'postCard',
|
||||
namePlural: 'postCards',
|
||||
labelSingular: 'Post Card',
|
||||
labelPlural: 'Post Cards',
|
||||
description: 'A post card object',
|
||||
icon: 'IconMail',
|
||||
fields: [
|
||||
{
|
||||
universalIdentifier: '58a0a314-d7ea-4865-9850-7fb84e72f30b',
|
||||
name: 'content',
|
||||
type: FieldType.TEXT,
|
||||
label: 'Content',
|
||||
description: "Postcard's content",
|
||||
icon: 'IconAbc',
|
||||
},
|
||||
{
|
||||
universalIdentifier: 'c6aa31f3-da76-4ac6-889f-475e226009ac',
|
||||
name: 'recipientName',
|
||||
type: FieldType.FULL_NAME,
|
||||
label: 'Recipient name',
|
||||
icon: 'IconUser',
|
||||
},
|
||||
{
|
||||
universalIdentifier: '95045777-a0ad-49ec-98f9-22f9fc0c8266',
|
||||
name: 'recipientAddress',
|
||||
type: FieldType.ADDRESS,
|
||||
label: 'Recipient address',
|
||||
icon: 'IconHome',
|
||||
},
|
||||
{
|
||||
universalIdentifier: '87b675b8-dd8c-4448-b4ca-20e5a2234a1e',
|
||||
name: 'status',
|
||||
type: FieldType.SELECT,
|
||||
label: 'Status',
|
||||
icon: 'IconSend',
|
||||
defaultValue: `'${PostCardStatus.DRAFT}'`,
|
||||
options: [
|
||||
{ value: PostCardStatus.DRAFT, label: 'Draft', position: 0, color: 'gray' },
|
||||
{ value: PostCardStatus.SENT, label: 'Sent', position: 1, color: 'orange' },
|
||||
{ value: PostCardStatus.DELIVERED, label: 'Delivered', position: 2, color: 'green' },
|
||||
{ value: PostCardStatus.RETURNED, label: 'Returned', position: 3, color: 'orange' },
|
||||
],
|
||||
},
|
||||
{
|
||||
universalIdentifier: 'e06abe72-5b44-4e7f-93be-afc185a3c433',
|
||||
name: 'deliveredAt',
|
||||
type: FieldType.DATE_TIME,
|
||||
label: 'Delivered at',
|
||||
icon: 'IconCheck',
|
||||
isNullable: true,
|
||||
defaultValue: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Hauptpunkte:
|
||||
|
||||
* Verwenden Sie `defineObject()` für eingebaute Validierung und bessere IDE-Unterstützung.
|
||||
* Der `universalIdentifier` muss eindeutig und über Deployments hinweg stabil sein.
|
||||
* Jedes Feld benötigt `name`, `type`, `label` und einen eigenen stabilen `universalIdentifier`.
|
||||
* Das Array `fields` ist optional — Sie können Objekte ohne benutzerdefinierte Felder definieren.
|
||||
* Sie können mit `yarn twenty entity:add` neue Objekte erzeugen; der Assistent führt Sie durch Benennung, Felder und Beziehungen.
|
||||
|
||||
<Note>
|
||||
**Basisfelder werden automatisch erstellt.** Wenn Sie ein benutzerdefiniertes Objekt definieren, fügt Twenty automatisch Standardfelder hinzu
|
||||
wie `id`, `name`, `createdAt`, `updatedAt`, `createdBy`, `updatedBy` und `deletedAt`.
|
||||
Sie müssen diese nicht in Ihrem `fields`-Array definieren — fügen Sie nur Ihre benutzerdefinierten Felder hinzu.
|
||||
Sie können Standardfelder überschreiben, indem Sie in Ihrem `fields`-Array ein Feld mit demselben Namen definieren,
|
||||
dies wird jedoch nicht empfohlen.
|
||||
</Note>
|
||||
|
||||
### Anwendungskonfiguration (application-config.ts)
|
||||
|
||||
Jede App hat eine einzelne Datei `application-config.ts`, die Folgendes beschreibt:
|
||||
|
||||
* **Was die App ist**: Bezeichner, Anzeigename und Beschreibung.
|
||||
* **Wie ihre Funktionen ausgeführt werden**: welche Rolle sie für Berechtigungen verwenden.
|
||||
* **(Optional) Variablen**: Schlüssel–Wert-Paare, die Ihren Funktionen als Umgebungsvariablen zur Verfügung gestellt werden.
|
||||
* **(Optional) Pre-Installationsfunktion**: eine Logikfunktion, die vor der Installation der App ausgeführt wird.
|
||||
* **(Optional) Post-Installationsfunktion**: eine Logikfunktion, die nach der Installation der App ausgeführt wird.
|
||||
|
||||
Verwenden Sie `defineApplication()`, um Ihre Anwendungskonfiguration zu definieren:
|
||||
|
||||
```typescript
|
||||
// src/application-config.ts
|
||||
import { defineApplication } from 'twenty-sdk';
|
||||
import { DEFAULT_ROLE_UNIVERSAL_IDENTIFIER } from 'src/roles/default-role';
|
||||
|
||||
export default defineApplication({
|
||||
universalIdentifier: '4ec0391d-18d5-411c-b2f3-266ddc1c3ef7',
|
||||
displayName: 'My Twenty App',
|
||||
description: 'My first Twenty app',
|
||||
icon: 'IconWorld',
|
||||
applicationVariables: {
|
||||
DEFAULT_RECIPIENT_NAME: {
|
||||
universalIdentifier: '19e94e59-d4fe-4251-8981-b96d0a9f74de',
|
||||
description: 'Default recipient name for postcards',
|
||||
value: 'Jane Doe',
|
||||
isSecret: false,
|
||||
},
|
||||
},
|
||||
defaultRoleUniversalIdentifier: DEFAULT_ROLE_UNIVERSAL_IDENTIFIER,
|
||||
});
|
||||
```
|
||||
|
||||
Notizen:
|
||||
|
||||
* `universalIdentifier`-Felder sind deterministische IDs, die Sie besitzen; generieren Sie sie einmal und halten Sie sie über Synchronisierungen hinweg stabil.
|
||||
* `applicationVariables` werden zu Umgebungsvariablen für Ihre Funktionen (zum Beispiel ist `DEFAULT_RECIPIENT_NAME` als `process.env.DEFAULT_RECIPIENT_NAME` verfügbar).
|
||||
* `defaultRoleUniversalIdentifier` muss mit der Rollendatei übereinstimmen (siehe unten).
|
||||
* Pre-Installations- und Post-Installationsfunktionen werden während des Manifest-Builds automatisch erkannt. Siehe [Pre-Installationsfunktionen](#pre-install-functions) und [Post-Installationsfunktionen](#post-install-functions).
|
||||
|
||||
#### Rollen und Berechtigungen
|
||||
|
||||
Anwendungen können Rollen definieren, die Berechtigungen für die Objekte und Aktionen Ihres Workspaces kapseln. Das Feld `defaultRoleUniversalIdentifier` in `application-config.ts` legt die Standardrolle fest, die von den Logikfunktionen Ihrer App verwendet wird.
|
||||
|
||||
* Der zur Laufzeit als `TWENTY_API_KEY` injizierte API-Schlüssel wird von dieser Standard-Funktionsrolle abgeleitet.
|
||||
* Der typisierte Client ist auf die dieser Rolle gewährten Berechtigungen beschränkt.
|
||||
* Befolgen Sie das Least-Privilege-Prinzip: Erstellen Sie eine dedizierte Rolle nur mit den Berechtigungen, die Ihre Funktionen benötigen, und verweisen Sie dann auf deren universellen Bezeichner.
|
||||
|
||||
##### Standard-Funktionsrolle (*.role.ts)
|
||||
|
||||
Wenn Sie eine neue App erzeugen, erstellt die CLI auch eine Standard-Rolldatei. Verwenden Sie `defineRole()`, um Rollen mit eingebauter Validierung zu definieren:
|
||||
|
||||
```typescript
|
||||
// src/roles/default-role.ts
|
||||
import { defineRole, PermissionFlag } from 'twenty-sdk';
|
||||
|
||||
export const DEFAULT_ROLE_UNIVERSAL_IDENTIFIER =
|
||||
'b648f87b-1d26-4961-b974-0908fd991061';
|
||||
|
||||
export default defineRole({
|
||||
universalIdentifier: DEFAULT_ROLE_UNIVERSAL_IDENTIFIER,
|
||||
label: 'Default function role',
|
||||
description: 'Default role for function Twenty client',
|
||||
canReadAllObjectRecords: false,
|
||||
canUpdateAllObjectRecords: false,
|
||||
canSoftDeleteAllObjectRecords: false,
|
||||
canDestroyAllObjectRecords: false,
|
||||
canUpdateAllSettings: false,
|
||||
canBeAssignedToAgents: false,
|
||||
canBeAssignedToUsers: false,
|
||||
canBeAssignedToApiKeys: false,
|
||||
objectPermissions: [
|
||||
{
|
||||
objectUniversalIdentifier: '9f9882af-170c-4879-b013-f9628b77c050',
|
||||
canReadObjectRecords: true,
|
||||
canUpdateObjectRecords: true,
|
||||
canSoftDeleteObjectRecords: false,
|
||||
canDestroyObjectRecords: false,
|
||||
},
|
||||
],
|
||||
fieldPermissions: [
|
||||
{
|
||||
objectUniversalIdentifier: '9f9882af-170c-4879-b013-f9628b77c050',
|
||||
fieldUniversalIdentifier: 'b2c37dc0-8ae7-470e-96cd-1476b47dfaff',
|
||||
canReadFieldValue: false,
|
||||
canUpdateFieldValue: false,
|
||||
},
|
||||
],
|
||||
permissionFlags: [PermissionFlag.APPLICATIONS],
|
||||
});
|
||||
```
|
||||
|
||||
Der `universalIdentifier` dieser Rolle wird anschließend in `application-config.ts` als `defaultRoleUniversalIdentifier` referenziert. Anders ausgedrückt:
|
||||
|
||||
* **\*.role.ts** definiert, was die Standard-Funktionsrolle darf.
|
||||
* **application-config.ts** verweist auf diese Rolle, sodass Ihre Funktionen deren Berechtigungen erben.
|
||||
|
||||
Notizen:
|
||||
|
||||
* Beginnen Sie mit der vorab erstellten Rolle und schränken Sie sie schrittweise gemäß dem Least-Privilege-Prinzip ein.
|
||||
* Ersetzen Sie `objectPermissions` und `fieldPermissions` durch die Objekte/Felder, die Ihre Funktionen benötigen.
|
||||
* `permissionFlags` steuern den Zugriff auf Funktionen auf Plattformebene. Halten Sie sie minimal; fügen Sie nur hinzu, was Sie benötigen.
|
||||
* Ein funktionierendes Beispiel finden Sie in der Hello-World-App: [`packages/twenty-apps/hello-world/src/roles/function-role.ts`](https://github.com/twentyhq/twenty/blob/main/packages/twenty-apps/hello-world/src/roles/function-role.ts).
|
||||
|
||||
### Konfiguration von Logikfunktionen und Einstiegspunkt
|
||||
|
||||
Jede Funktionsdatei verwendet `defineLogicFunction()`, um eine Konfiguration mit einem Handler und optionalen Triggern zu exportieren.
|
||||
|
||||
```typescript
|
||||
// src/app/createPostCard.logic-function.ts
|
||||
import { defineLogicFunction } from 'twenty-sdk';
|
||||
import type { DatabaseEventPayload, ObjectRecordCreateEvent, CronPayload, RoutePayload } from 'twenty-sdk';
|
||||
import { CoreApiClient, type Person } from 'twenty-sdk/generated';
|
||||
|
||||
const handler = async (params: RoutePayload) => {
|
||||
const client = new CoreApiClient();
|
||||
const name = 'name' in params.queryStringParameters
|
||||
? params.queryStringParameters.name ?? process.env.DEFAULT_RECIPIENT_NAME ?? 'Hello world'
|
||||
: 'Hello world';
|
||||
|
||||
const result = await client.mutation({
|
||||
createPostCard: {
|
||||
__args: { data: { name } },
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
});
|
||||
return result;
|
||||
};
|
||||
|
||||
export default defineLogicFunction({
|
||||
universalIdentifier: 'e56d363b-0bdc-4d8a-a393-6f0d1c75bdcf',
|
||||
name: 'create-new-post-card',
|
||||
timeoutSeconds: 2,
|
||||
handler,
|
||||
triggers: [
|
||||
// Public HTTP route trigger '/s/post-card/create'
|
||||
{
|
||||
universalIdentifier: 'c9f84c8d-b26d-40d1-95dd-4f834ae5a2c6',
|
||||
type: 'route',
|
||||
path: '/post-card/create',
|
||||
httpMethod: 'GET',
|
||||
isAuthRequired: false,
|
||||
},
|
||||
// Cron trigger (CRON pattern)
|
||||
// {
|
||||
// universalIdentifier: 'dd802808-0695-49e1-98c9-d5c9e2704ce2',
|
||||
// type: 'cron',
|
||||
// pattern: '0 0 1 1 *',
|
||||
// },
|
||||
// Database event trigger
|
||||
// {
|
||||
// universalIdentifier: '203f1df3-4a82-4d06-a001-b8cf22a31156',
|
||||
// type: 'databaseEvent',
|
||||
// eventName: 'person.updated',
|
||||
// updatedFields: ['name'],
|
||||
// },
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Häufige Trigger-Typen:
|
||||
|
||||
* **route**: Stellt Ihre Funktion unter einem HTTP-Pfad und einer Methode **unter dem Endpunkt `/s/`** bereit:
|
||||
|
||||
> z. B. `path: '/post-card/create',` -> Aufruf unter `<APP_URL>/s/post-card/create`
|
||||
|
||||
* **cron**: Führt Ihre Funktion nach Zeitplan mithilfe eines CRON-Ausdrucks aus.
|
||||
* **databaseEvent**: Wird bei Lebenszyklusereignissen von Workspace-Objekten ausgeführt. Wenn die Ereignisoperation `updated` ist, können bestimmte zu überwachende Felder im Array `updatedFields` angegeben werden. Wenn das Array undefiniert oder leer ist, löst jede Aktualisierung die Funktion aus.
|
||||
|
||||
> z. B. `person.updated`
|
||||
|
||||
Notizen:
|
||||
|
||||
* Das Array `triggers` ist optional. Funktionen ohne Trigger können als von anderen Funktionen aufgerufene Utility-Funktionen verwendet werden.
|
||||
* Sie können mehrere Trigger-Typen in einer Funktion kombinieren.
|
||||
|
||||
### Pre-Installationsfunktionen
|
||||
|
||||
Eine Pre-Installationsfunktion ist eine Logikfunktion, die automatisch ausgeführt wird, bevor Ihre App in einem Arbeitsbereich installiert wird. Dies ist nützlich für Validierungsaufgaben, Überprüfungen von Voraussetzungen oder die Vorbereitung des Status des Arbeitsbereichs, bevor die Hauptinstallation fortgesetzt wird.
|
||||
|
||||
Wenn Sie mit `create-twenty-app` eine neue App erstellen, wird für Sie eine Pre-Installationsfunktion unter `src/logic-functions/pre-install.ts` erzeugt:
|
||||
|
||||
```typescript
|
||||
// src/logic-functions/pre-install.ts
|
||||
import { definePreInstallLogicFunction, type InstallLogicFunctionPayload } from 'twenty-sdk';
|
||||
|
||||
const handler = async (payload: InstallLogicFunctionPayload): Promise<void> => {
|
||||
console.log('Pre install logic function executed successfully!', payload.previousVersion);
|
||||
};
|
||||
|
||||
export default definePreInstallLogicFunction({
|
||||
universalIdentifier: '<generated-uuid>',
|
||||
name: 'pre-install',
|
||||
description: 'Runs before installation to prepare the application.',
|
||||
timeoutSeconds: 300,
|
||||
handler,
|
||||
});
|
||||
```
|
||||
|
||||
Sie können die Pre-Installationsfunktion auch jederzeit manuell über die CLI ausführen:
|
||||
|
||||
```bash filename="Terminal"
|
||||
yarn twenty function:execute --preInstall
|
||||
```
|
||||
|
||||
Hauptpunkte:
|
||||
|
||||
* Pre-Installationsfunktionen verwenden `definePreInstallLogicFunction()` — eine spezialisierte Variante, die Trigger-Einstellungen (`cronTriggerSettings`, `databaseEventTriggerSettings`, `httpRouteTriggerSettings`, `isTool`) weglässt.
|
||||
* Der Handler erhält ein `InstallLogicFunctionPayload` mit `{ previousVersion: string }` — die Version der App, die zuvor installiert war (oder eine leere Zeichenkette bei Neuinstallationen).
|
||||
* Pro Anwendung ist nur eine Pre-Installationsfunktion zulässig. Der Manifest-Build schlägt fehl, wenn mehr als eine erkannt wird.
|
||||
* Der `universalIdentifier` der Funktion wird während des Builds im Anwendungsmanifest automatisch als `preInstallLogicFunctionUniversalIdentifier` gesetzt — Sie müssen ihn nicht in `defineApplication()` referenzieren.
|
||||
* Das standardmäßige Timeout ist auf 300 Sekunden (5 Minuten) festgelegt, um längere Vorbereitungsvorgänge zu ermöglichen.
|
||||
* Pre-Installationsfunktionen benötigen keine Trigger — sie werden von der Plattform vor der Installation oder manuell über `function:execute --preInstall` aufgerufen.
|
||||
|
||||
### Post-Installationsfunktionen
|
||||
|
||||
Eine Post-Installationsfunktion ist eine Logikfunktion, die automatisch ausgeführt wird, nachdem Ihre App in einem Arbeitsbereich installiert wurde. Dies ist nützlich für einmalige Einrichtungsvorgänge wie das Befüllen mit Standarddaten, das Erstellen erster Datensätze oder das Konfigurieren von Arbeitsbereichseinstellungen.
|
||||
|
||||
Wenn Sie mit `create-twenty-app` eine neue App erstellen, wird für Sie eine Post-Installationsfunktion unter `src/logic-functions/post-install.ts` erzeugt:
|
||||
|
||||
```typescript
|
||||
// src/logic-functions/post-install.ts
|
||||
import { definePostInstallLogicFunction, type InstallLogicFunctionPayload } from 'twenty-sdk';
|
||||
|
||||
const handler = async (payload: InstallLogicFunctionPayload): Promise<void> => {
|
||||
console.log('Post install logic function executed successfully!', payload.previousVersion);
|
||||
};
|
||||
|
||||
export default definePostInstallLogicFunction({
|
||||
universalIdentifier: '<generated-uuid>',
|
||||
name: 'post-install',
|
||||
description: 'Runs after installation to set up the application.',
|
||||
timeoutSeconds: 300,
|
||||
handler,
|
||||
});
|
||||
```
|
||||
|
||||
Sie können die Post-Installationsfunktion auch jederzeit manuell über die CLI ausführen:
|
||||
|
||||
```bash filename="Terminal"
|
||||
yarn twenty function:execute --postInstall
|
||||
```
|
||||
|
||||
Hauptpunkte:
|
||||
|
||||
* Post-Installationsfunktionen verwenden `definePostInstallLogicFunction()` — eine spezialisierte Variante, die Trigger-Einstellungen (`cronTriggerSettings`, `databaseEventTriggerSettings`, `httpRouteTriggerSettings`, `isTool`) weglässt.
|
||||
* Der Handler erhält ein `InstallLogicFunctionPayload` mit `{ previousVersion: string }` — die Version der App, die zuvor installiert war (oder eine leere Zeichenkette bei Neuinstallationen).
|
||||
* Pro Anwendung ist nur eine Post-Installationsfunktion zulässig. Der Manifest-Build schlägt fehl, wenn mehr als eine erkannt wird.
|
||||
* Der `universalIdentifier` der Funktion wird während des Builds im Anwendungsmanifest automatisch als `postInstallLogicFunctionUniversalIdentifier` gesetzt — Sie müssen ihn nicht in `defineApplication()` referenzieren.
|
||||
* Das standardmäßige Timeout ist auf 300 Sekunden (5 Minuten) festgelegt, um längere Einrichtungsvorgänge wie Daten-Seeding zu ermöglichen.
|
||||
* Post-Installationsfunktionen benötigen keine Trigger — sie werden von der Plattform während der Installation oder manuell über `function:execute --postInstall` aufgerufen.
|
||||
|
||||
### Routen-Trigger-Payload
|
||||
|
||||
<Warning>
|
||||
**Breaking Change (v1.16, Januar 2026):** Das Format der Routen-Trigger-Payload hat sich geändert. Vor v1.16 wurden Query-Parameter, Pfadparameter und der Body direkt als Payload gesendet. Ab v1.16 sind sie innerhalb eines strukturierten `RoutePayload`-Objekts verschachtelt.
|
||||
|
||||
**Vor v1.16:**
|
||||
```typescript
|
||||
const handler = async (params) => {
|
||||
const { param1, param2 } = params; // Direct access
|
||||
};
|
||||
```
|
||||
|
||||
**Nach v1.16:**
|
||||
```typescript
|
||||
const handler = async (event: RoutePayload) => {
|
||||
const { param1, param2 } = event.body; // Access via .body
|
||||
const { queryParam } = event.queryStringParameters;
|
||||
const { id } = event.pathParameters;
|
||||
};
|
||||
```
|
||||
|
||||
**So migrieren Sie bestehende Funktionen:** Aktualisieren Sie Ihren Handler, sodass er nicht mehr direkt aus dem params-Objekt destrukturiert, sondern aus `event.body`, `event.queryStringParameters` oder `event.pathParameters`.
|
||||
</Warning>
|
||||
|
||||
Wenn ein Routen-Trigger Ihre Logikfunktion aufruft, erhält sie ein `RoutePayload`-Objekt, das dem AWS HTTP API v2-Format entspricht. Importieren Sie den Typ aus `twenty-sdk`:
|
||||
|
||||
```typescript
|
||||
import { defineLogicFunction, type RoutePayload } from 'twenty-sdk';
|
||||
|
||||
const handler = async (event: RoutePayload) => {
|
||||
// Access request data
|
||||
const { headers, queryStringParameters, pathParameters, body } = event;
|
||||
|
||||
// HTTP method and path are available in requestContext
|
||||
const { method, path } = event.requestContext.http;
|
||||
|
||||
return { message: 'Success' };
|
||||
};
|
||||
```
|
||||
|
||||
Der Typ `RoutePayload` hat die folgende Struktur:
|
||||
|
||||
| Eigenschaft | Typ | Beschreibung |
|
||||
| ---------------------------- | ------------------------------------- | ------------------------------------------------------------------------------------- |
|
||||
| `headers` | `Record<string, string \| undefined>` | HTTP-Header (nur die in `forwardedRequestHeaders` aufgelisteten) |
|
||||
| `queryStringParameters` | `Record<string, string \| undefined>` | Query-String-Parameter (mehrere Werte mit Kommas verbunden) |
|
||||
| `pathParameters` | `Record<string, string \| undefined>` | Aus dem Routenmuster extrahierte Pfadparameter (z. B. `/users/:id` → `{ id: '123' }`) |
|
||||
| `body` | `object \| null` | Geparster Request-Body (JSON) |
|
||||
| `isBase64Encoded` | `boolean` | Gibt an, ob der Body Base64-codiert ist |
|
||||
| `requestContext.http.method` | `string` | HTTP-Methode (GET, POST, PUT, PATCH, DELETE) |
|
||||
| `requestContext.http.path` | `string` | Rohpfad der Anfrage |
|
||||
|
||||
### Weiterleiten von HTTP-Headern
|
||||
|
||||
Standardmäßig werden HTTP-Header von eingehenden Anfragen aus Sicherheitsgründen nicht an Ihre Logikfunktion weitergegeben. Um auf bestimmte Header zuzugreifen, listen Sie diese explizit im Array `forwardedRequestHeaders` auf:
|
||||
|
||||
```typescript
|
||||
export default defineLogicFunction({
|
||||
universalIdentifier: 'e56d363b-0bdc-4d8a-a393-6f0d1c75bdcf',
|
||||
name: 'webhook-handler',
|
||||
handler,
|
||||
triggers: [
|
||||
{
|
||||
universalIdentifier: 'c9f84c8d-b26d-40d1-95dd-4f834ae5a2c6',
|
||||
type: 'route',
|
||||
path: '/webhook',
|
||||
httpMethod: 'POST',
|
||||
isAuthRequired: false,
|
||||
forwardedRequestHeaders: ['x-webhook-signature', 'content-type'],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
In Ihrem Handler können Sie anschließend auf diese Header zugreifen:
|
||||
|
||||
```typescript
|
||||
const handler = async (event: RoutePayload) => {
|
||||
const signature = event.headers['x-webhook-signature'];
|
||||
const contentType = event.headers['content-type'];
|
||||
|
||||
// Validate webhook signature...
|
||||
return { received: true };
|
||||
};
|
||||
```
|
||||
|
||||
<Note>
|
||||
Header-Namen werden in Kleinbuchstaben normalisiert. Greifen Sie mit Schlüsseln in Kleinbuchstaben darauf zu (zum Beispiel `event.headers['content-type']`).
|
||||
</Note>
|
||||
|
||||
Sie können neue Funktionen auf zwei Arten erstellen:
|
||||
|
||||
* **Generiert**: Führen Sie `yarn twenty entity:add` aus und wählen Sie die Option zum Hinzufügen einer neuen Logikfunktion. Dadurch wird eine Starterdatei mit Handler und Konfiguration erzeugt.
|
||||
* **Manuell**: Erstellen Sie eine neue `*.logic-function.ts`-Datei und verwenden Sie `defineLogicFunction()` nach demselben Muster.
|
||||
|
||||
### Eine Logikfunktion als Tool markieren
|
||||
|
||||
Logikfunktionen können als **Tools** für KI-Agenten und Workflows verfügbar gemacht werden. Wenn eine Funktion als Tool markiert ist, wird sie von den KI-Funktionen von Twenty auffindbar und kann als Schritt in Workflow-Automatisierungen ausgewählt werden.
|
||||
|
||||
Um eine Logikfunktion als Tool zu markieren, setzen Sie `isTool: true` und geben Sie ein `toolInputSchema` an, das die erwarteten Eingabeparameter mithilfe von [JSON Schema](https://json-schema.org/) beschreibt:
|
||||
|
||||
```typescript
|
||||
// src/logic-functions/enrich-company.logic-function.ts
|
||||
import { defineLogicFunction } from 'twenty-sdk';
|
||||
import { CoreApiClient } from 'twenty-sdk/generated';
|
||||
|
||||
const handler = async (params: { companyName: string; domain?: string }) => {
|
||||
const client = new CoreApiClient();
|
||||
|
||||
const result = await client.mutation({
|
||||
createTask: {
|
||||
__args: {
|
||||
data: {
|
||||
title: `Enrich data for ${params.companyName}`,
|
||||
body: `Domain: ${params.domain ?? 'unknown'}`,
|
||||
},
|
||||
},
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
return { taskId: result.createTask.id };
|
||||
};
|
||||
|
||||
export default defineLogicFunction({
|
||||
universalIdentifier: 'f47ac10b-58cc-4372-a567-0e02b2c3d479',
|
||||
name: 'enrich-company',
|
||||
description: 'Enrich a company record with external data',
|
||||
timeoutSeconds: 10,
|
||||
handler,
|
||||
isTool: true,
|
||||
toolInputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
companyName: {
|
||||
type: 'string',
|
||||
description: 'The name of the company to enrich',
|
||||
},
|
||||
domain: {
|
||||
type: 'string',
|
||||
description: 'The company website domain (optional)',
|
||||
},
|
||||
},
|
||||
required: ['companyName'],
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Hauptpunkte:
|
||||
|
||||
* **`isTool`** (`boolean`, Standard: `false`): Wenn auf `true` gesetzt, wird die Funktion als Tool registriert und steht KI-Agenten und Workflow-Automatisierungen zur Verfügung.
|
||||
* **`toolInputSchema`** (`object`, optional): Ein JSON-Schema-Objekt, das die Parameter beschreibt, die Ihre Funktion akzeptiert. KI-Agenten verwenden dieses Schema, um zu verstehen, welche Eingaben das Tool erwartet, und um Aufrufe zu validieren. Falls weggelassen, lautet der Standardwert für das Schema `{ type: 'object', properties: {} }` (keine Parameter).
|
||||
* Funktionen mit `isTool: false` (oder nicht gesetzt) werden **nicht** als Tools bereitgestellt. Sie können weiterhin direkt ausgeführt oder von anderen Funktionen aufgerufen werden, erscheinen jedoch nicht in der Tool-Erkennung.
|
||||
* **Tool-Benennung**: Wenn als Tool bereitgestellt, wird der Funktionsname automatisch zu `logic_function_<name>` normalisiert (in Kleinbuchstaben umgewandelt, nicht alphanumerische Zeichen durch Unterstriche ersetzt). Beispielsweise wird `enrich-company` zu `logic_function_enrich_company`.
|
||||
* Sie können `isTool` mit Triggern kombinieren — eine Funktion kann gleichzeitig sowohl ein Tool (von KI-Agenten aufrufbar) als auch durch Ereignisse (Cron, Datenbankereignisse, Routen) ausgelöst werden.
|
||||
|
||||
<Note>
|
||||
**Schreiben Sie eine gute `description`.** KI-Agenten verlassen sich auf das `description`-Feld der Funktion, um zu entscheiden, wann das Tool verwendet werden soll. Seien Sie konkret darin, was das Tool tut und wann es aufgerufen werden soll.
|
||||
</Note>
|
||||
|
||||
### Frontend-Komponenten
|
||||
|
||||
Frontend-Komponenten ermöglichen es Ihnen, benutzerdefinierte React-Komponenten zu erstellen, die innerhalb der Twenty-UI gerendert werden. Verwenden Sie `defineFrontComponent()`, um Komponenten mit eingebauter Validierung zu definieren:
|
||||
|
||||
```typescript
|
||||
// src/front-components/my-widget.tsx
|
||||
import { defineFrontComponent } from 'twenty-sdk';
|
||||
|
||||
const MyWidget = () => {
|
||||
return (
|
||||
<div style={{ padding: '20px', fontFamily: 'sans-serif' }}>
|
||||
<h1>My Custom Widget</h1>
|
||||
<p>This is a custom front component for Twenty.</p>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default defineFrontComponent({
|
||||
universalIdentifier: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
|
||||
name: 'my-widget',
|
||||
description: 'A custom widget component',
|
||||
component: MyWidget,
|
||||
});
|
||||
```
|
||||
|
||||
Hauptpunkte:
|
||||
|
||||
* Frontend-Komponenten sind React-Komponenten, die in isolierten Kontexten innerhalb von Twenty gerendert werden.
|
||||
* Das Feld `component` verweist auf Ihre React-Komponente.
|
||||
* Komponenten werden während `yarn twenty app:dev` automatisch gebaut und synchronisiert.
|
||||
|
||||
Sie können neue Frontend-Komponenten auf zwei Arten erstellen:
|
||||
|
||||
* **Generiert**: Führen Sie `yarn twenty entity:add` aus und wählen Sie die Option zum Hinzufügen einer neuen Frontend-Komponente.
|
||||
* **Manuell**: Erstellen Sie eine neue `.tsx`-Datei und verwenden Sie `defineFrontComponent()` nach demselben Muster.
|
||||
|
||||
### Fähigkeiten
|
||||
|
||||
Skills definieren wiederverwendbare Anweisungen und Fähigkeiten, die KI-Agenten in Ihrem Arbeitsbereich verwenden können. Verwenden Sie `defineSkill()`, um Skills mit eingebauter Validierung zu definieren:
|
||||
|
||||
```typescript
|
||||
// src/skills/example-skill.ts
|
||||
import { defineSkill } from 'twenty-sdk';
|
||||
|
||||
export default defineSkill({
|
||||
universalIdentifier: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
|
||||
name: 'sales-outreach',
|
||||
label: 'Sales Outreach',
|
||||
description: 'Guides the AI agent through a structured sales outreach process',
|
||||
icon: 'IconBrain',
|
||||
content: `You are a sales outreach assistant. When reaching out to a prospect:
|
||||
1. Research the company and recent news
|
||||
2. Identify the prospect's role and likely pain points
|
||||
3. Draft a personalized message referencing specific details
|
||||
4. Keep the tone professional but conversational`,
|
||||
});
|
||||
```
|
||||
|
||||
Hauptpunkte:
|
||||
|
||||
* `name` ist eine eindeutige Kennung (als Zeichenfolge) für den Skill (kebab-case empfohlen).
|
||||
* `label` ist der menschenlesbare Anzeigename, der in der UI angezeigt wird.
|
||||
* `content` enthält die Skill-Anweisungen — dies ist der Text, den der KI-Agent verwendet.
|
||||
* `icon` (optional) legt das in der UI angezeigte Symbol fest.
|
||||
* `description` (optional) liefert zusätzlichen Kontext zum Zweck des Skills.
|
||||
|
||||
Sie können neue Skills auf zwei Arten erstellen:
|
||||
|
||||
* **Generiert**: Führen Sie `yarn twenty entity:add` aus und wählen Sie die Option zum Hinzufügen eines neuen Skills.
|
||||
* **Manuell**: Erstellen Sie eine neue Datei und verwenden Sie `defineSkill()` nach demselben Muster.
|
||||
|
||||
### Generierte typisierte Clients
|
||||
|
||||
Zwei typisierte Clients werden von `yarn twenty app:dev` automatisch generiert und basierend auf Ihrem Arbeitsbereichs-Schema in `node_modules/twenty-sdk/generated` gespeichert:
|
||||
|
||||
* **`CoreApiClient`** — fragt den `/graphql`-Endpunkt nach Arbeitsbereichsdaten ab
|
||||
* **`MetadataApiClient`** — ruft über den Endpunkt `/metadata` die Arbeitsbereichskonfiguration und Datei-Uploads ab.
|
||||
|
||||
```typescript
|
||||
import { CoreApiClient, MetadataApiClient } from 'twenty-sdk/generated';
|
||||
|
||||
const client = new CoreApiClient();
|
||||
const { me } = await client.query({ me: { id: true, displayName: true } });
|
||||
|
||||
const metadataClient = new MetadataApiClient();
|
||||
const { currentWorkspace } = await metadataClient.query({ currentWorkspace: { id: true } });
|
||||
```
|
||||
|
||||
Beide Clients werden von `yarn twenty app:dev` automatisch neu generiert, sobald sich Ihre Objekte oder Felder ändern.
|
||||
|
||||
#### Laufzeit-Anmeldedaten in Logikfunktionen
|
||||
|
||||
Wenn Ihre Funktion auf Twenty läuft, injiziert die Plattform vor der Ausführung Ihres Codes Anmeldedaten als Umgebungsvariablen:
|
||||
|
||||
* `TWENTY_API_URL`: Basis-URL der Twenty-API, auf die Ihre App abzielt.
|
||||
* `TWENTY_API_KEY`: Kurzlebiger Schlüssel, der auf die Standard-Funktionsrolle Ihrer Anwendung begrenzt ist.
|
||||
|
||||
Notizen:
|
||||
|
||||
* Sie müssen dem generierten Client weder URL noch API-Schlüssel übergeben. Er liest `TWENTY_API_URL` und `TWENTY_API_KEY` zur Laufzeit aus process.env.
|
||||
* Die Berechtigungen des API-Schlüssels werden durch die Rolle bestimmt, auf die in Ihrer `application-config.ts` über `defaultRoleUniversalIdentifier` verwiesen wird. Dies ist die Standardrolle, die von den Logikfunktionen Ihrer Anwendung verwendet wird.
|
||||
* Anwendungen können Rollen definieren, um das Least-Privilege-Prinzip einzuhalten. Gewähren Sie nur die Berechtigungen, die Ihre Funktionen benötigen, und verweisen Sie dann mit `defaultRoleUniversalIdentifier` auf den universellen Bezeichner dieser Rolle.
|
||||
|
||||
#### Dateien hochladen
|
||||
|
||||
Der generierte `MetadataApiClient` enthält eine Methode `uploadFile`, um Dateien an Felder des Typs Datei in Ihren Arbeitsbereichsobjekten anzuhängen. Da Standard-GraphQL-Clients Multipart-Datei-Uploads nicht nativ unterstützen, stellt der Client diese dedizierte Methode bereit, die unter der Haube die [GraphQL-Multipart-Anfragespezifikation](https://github.com/jaydenseric/graphql-multipart-request-spec) implementiert.
|
||||
|
||||
```typescript
|
||||
import { MetadataApiClient } from 'twenty-sdk/generated';
|
||||
import * as fs from 'fs';
|
||||
|
||||
const metadataClient = new MetadataApiClient();
|
||||
|
||||
const fileBuffer = fs.readFileSync('./invoice.pdf');
|
||||
|
||||
const uploadedFile = await metadataClient.uploadFile(
|
||||
fileBuffer, // file contents as a Buffer
|
||||
'invoice.pdf', // filename
|
||||
'application/pdf', // MIME type (defaults to 'application/octet-stream')
|
||||
'58a0a314-d7ea-4865-9850-7fb84e72f30b', // field universal identifier
|
||||
);
|
||||
|
||||
console.log(uploadedFile);
|
||||
// { id: '...', path: '...', size: 12345, createdAt: '...', url: 'https://...' }
|
||||
```
|
||||
|
||||
Die Methodensignatur:
|
||||
|
||||
```typescript
|
||||
uploadFile(
|
||||
fileBuffer: Buffer,
|
||||
filename: string,
|
||||
contentType: string,
|
||||
fieldMetadataUniversalIdentifier: string,
|
||||
): Promise<{ id: string; path: string; size: number; createdAt: string; url: string }>
|
||||
```
|
||||
|
||||
| Parameter | Typ | Beschreibung |
|
||||
| ---------------------------------- | -------- | ------------------------------------------------------------------------------- |
|
||||
| `fileBuffer` | `Buffer` | Der Rohinhalt der Datei |
|
||||
| `filename` | `string` | Der Name der Datei (wird für Speicherung und Anzeige verwendet) |
|
||||
| `contentType` | `string` | MIME-Typ der Datei (standardmäßig `application/octet-stream`, wenn weggelassen) |
|
||||
| `fieldMetadataUniversalIdentifier` | `string` | Der `universalIdentifier` des Dateityp-Felds in Ihrem Objekt |
|
||||
|
||||
Hauptpunkte:
|
||||
|
||||
* Die Methode `uploadFile` ist auf dem `MetadataApiClient` verfügbar, weil die Upload-Mutation vom Endpunkt `/metadata` aufgelöst wird.
|
||||
* Sie verwendet den `universalIdentifier` des Feldes (nicht dessen arbeitsbereichsspezifische ID), sodass Ihr Upload-Code in jedem Arbeitsbereich funktioniert, in dem Ihre App installiert ist — im Einklang damit, wie Apps Felder überall sonst referenzieren.
|
||||
* Die zurückgegebene `url` ist eine signierte URL, mit der Sie auf die hochgeladene Datei zugreifen können.
|
||||
|
||||
### Hello-World-Beispiel
|
||||
|
||||
Ein minimales End-to-End-Beispiel, das Objekte, Logikfunktionen, Frontend-Komponenten und mehrere Trigger demonstriert, finden Sie [hier](https://github.com/twentyhq/twenty/tree/main/packages/twenty-apps/hello-world).
|
||||
@@ -1,233 +0,0 @@
|
||||
---
|
||||
title: Erste Schritte
|
||||
description: Erstellen Sie in wenigen Minuten Ihre erste Twenty-App.
|
||||
---
|
||||
|
||||
<Warning>
|
||||
Apps befinden sich derzeit in der Alpha-Testphase. Die Funktion ist funktionsfähig, entwickelt sich jedoch noch weiter.
|
||||
</Warning>
|
||||
|
||||
Apps ermöglichen es Ihnen, Twenty mit benutzerdefinierten Objekten, Feldern, Logikfunktionen, KI-Fähigkeiten und UI-Komponenten zu erweitern — alles als Code verwaltet.
|
||||
|
||||
**Was Sie heute tun können:**
|
||||
|
||||
* Benutzerdefinierte Objekte und Felder als Code definieren (verwaltetes Datenmodell)
|
||||
* Erstellen Sie Logikfunktionen mit benutzerdefinierten Triggern (HTTP-Routen, cron, Datenbankereignisse)
|
||||
* Fähigkeiten für KI-Agenten definieren
|
||||
* Erstellen Sie Frontend-Komponenten, die in der Twenty-UI gerendert werden
|
||||
* Dieselbe App in mehreren Workspaces bereitstellen
|
||||
|
||||
## Voraussetzungen
|
||||
|
||||
* Node.js 24+ und Yarn 4
|
||||
* Ein Twenty-Workspace und ein API-Schlüssel (unter https://app.twenty.com/settings/api-webhooks erstellen)
|
||||
|
||||
## Erste Schritte
|
||||
|
||||
Erstellen Sie mit dem offiziellen Scaffolder eine neue App, authentifizieren Sie sich und beginnen Sie mit der Entwicklung:
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Scaffold a new app (includes all examples by default)
|
||||
npx create-twenty-app@latest my-twenty-app
|
||||
cd my-twenty-app
|
||||
|
||||
# Start dev mode: automatically syncs local changes to your workspace
|
||||
yarn twenty app:dev
|
||||
```
|
||||
|
||||
Das Scaffolding-Tool unterstützt zwei Modi, um zu steuern, welche Beispieldateien enthalten sind:
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Default (exhaustive): all examples (object, field, logic function, front component, view, navigation menu item, skill)
|
||||
npx create-twenty-app@latest my-app
|
||||
|
||||
# Minimal: only core files (application-config.ts and default-role.ts)
|
||||
npx create-twenty-app@latest my-app --minimal
|
||||
```
|
||||
|
||||
Von hier aus können Sie:
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Add a new entity to your application (guided)
|
||||
yarn twenty entity:add
|
||||
|
||||
# Watch your application's function logs
|
||||
yarn twenty function:logs
|
||||
|
||||
# Execute a function by name
|
||||
yarn twenty function:execute -n my-function -p '{"name": "test"}'
|
||||
|
||||
# Execute the pre-install function
|
||||
yarn twenty function:execute --preInstall
|
||||
|
||||
# Execute the post-install function
|
||||
yarn twenty function:execute --postInstall
|
||||
|
||||
# Uninstall the application from the current workspace
|
||||
yarn twenty app:uninstall
|
||||
|
||||
# Display commands' help
|
||||
yarn twenty help
|
||||
```
|
||||
|
||||
Siehe auch: die CLI-Referenzseiten für [create-twenty-app](https://www.npmjs.com/package/create-twenty-app) und [twenty-sdk CLI](https://www.npmjs.com/package/twenty-sdk).
|
||||
|
||||
## Projektstruktur (vom Scaffolder erzeugt)
|
||||
|
||||
Wenn Sie `npx create-twenty-app@latest my-twenty-app` ausführen, erledigt der Scaffolder Folgendes:
|
||||
|
||||
* Kopiert eine minimale Basisanwendung nach `my-twenty-app/`
|
||||
* Fügt eine lokale `twenty-sdk`-Abhängigkeit und die Yarn-4-Konfiguration hinzu
|
||||
* Erstellt Konfigurationsdateien und Skripte, die an die `twenty`-CLI angebunden sind
|
||||
* Erzeugt Kerndateien (Anwendungskonfiguration, Standardrolle für Logikfunktionen, Pre-Installations- und Post-Installationsfunktionen) sowie Beispieldateien entsprechend dem Scaffolding-Modus
|
||||
|
||||
Eine frisch erstellte App mit dem Standardmodus `--exhaustive` sieht so aus:
|
||||
|
||||
```text filename="my-twenty-app/"
|
||||
my-twenty-app/
|
||||
package.json
|
||||
yarn.lock
|
||||
.gitignore
|
||||
.nvmrc
|
||||
.yarnrc.yml
|
||||
.yarn/
|
||||
install-state.gz
|
||||
.oxlintrc.json
|
||||
tsconfig.json
|
||||
README.md
|
||||
public/ # Public assets folder (images, fonts, etc.)
|
||||
src/
|
||||
├── application-config.ts # Required - main application configuration
|
||||
├── roles/
|
||||
│ └── default-role.ts # Default role for logic functions
|
||||
├── objects/
|
||||
│ └── example-object.ts # Example custom object definition
|
||||
├── fields/
|
||||
│ └── example-field.ts # Example standalone field definition
|
||||
├── logic-functions/
|
||||
│ ├── hello-world.ts # Example logic function
|
||||
│ ├── pre-install.ts # Pre-install logic function
|
||||
│ └── post-install.ts # Post-install logic function
|
||||
├── front-components/
|
||||
│ └── hello-world.tsx # Example front component
|
||||
├── views/
|
||||
│ └── example-view.ts # Example saved view definition
|
||||
├── navigation-menu-items/
|
||||
│ └── example-navigation-menu-item.ts # Example sidebar navigation link
|
||||
└── skills/
|
||||
└── example-skill.ts # Example AI agent skill definition
|
||||
```
|
||||
|
||||
Mit `--minimal` werden nur die Kerndateien erstellt (`application-config.ts`, `roles/default-role.ts`, `logic-functions/pre-install.ts` und `logic-functions/post-install.ts`).
|
||||
|
||||
Auf hoher Ebene:
|
||||
|
||||
* **package.json**: Deklariert den App-Namen, die Version und die Engines (Node 24+, Yarn 4) und fügt `twenty-sdk` sowie ein `twenty`-Skript hinzu, das an die lokale `twenty`-CLI delegiert. Führen Sie `yarn twenty help` aus, um alle verfügbaren Befehle aufzulisten.
|
||||
* **.gitignore**: Ignoriert übliche Artefakte wie `node_modules`, `.yarn`, `generated/` (typisierter Client), `dist/`, `build/`, Coverage-Ordner, Logdateien und `.env*`-Dateien.
|
||||
* **yarn.lock**, **.yarnrc.yml**, **.yarn/**: Fixieren und konfigurieren die vom Projekt verwendete Yarn-4-Toolchain.
|
||||
* **.nvmrc**: Legt die vom Projekt erwartete Node.js-Version fest.
|
||||
* **.oxlintrc.json** und **tsconfig.json**: Stellen Linting und TypeScript-Konfiguration für die TypeScript-Quellen Ihrer App bereit.
|
||||
* **README.md**: Ein kurzes README im App-Root mit grundlegenden Anweisungen.
|
||||
* **public/**: Ein Ordner zum Speichern öffentlicher Assets (Bilder, Schriftarten, statische Dateien), die zusammen mit Ihrer Anwendung bereitgestellt werden. Hier abgelegte Dateien werden während der Synchronisierung hochgeladen und sind zur Laufzeit zugänglich.
|
||||
* **src/**: Der Hauptort, an dem Sie Ihre Anwendung als Code definieren
|
||||
|
||||
### Entitätserkennung
|
||||
|
||||
Das SDK erkennt Entitäten, indem es Ihre TypeScript-Dateien nach Aufrufen von **`export default define<Entity>({...})`** parst. Für jeden Entitätstyp gibt es eine entsprechende Hilfsfunktion, die aus `twenty-sdk` exportiert wird:
|
||||
|
||||
| Hilfsfunktion | Entitätstyp |
|
||||
| -------------------------------- | ------------------------------------------------------------------------ |
|
||||
| `defineObject` | Benutzerdefinierte Objektdefinitionen |
|
||||
| `defineLogicFunction` | Definitionen von Logikfunktionen |
|
||||
| `definePreInstallLogicFunction` | Pre-Installations-Logikfunktion (wird vor der Installation ausgeführt) |
|
||||
| `definePostInstallLogicFunction` | Post-Installations-Logikfunktion (wird nach der Installation ausgeführt) |
|
||||
| `defineFrontComponent` | Definitionen von Frontend-Komponenten |
|
||||
| `defineRole` | Rollendefinitionen |
|
||||
| `defineField` | Felderweiterungen für bestehende Objekte |
|
||||
| `defineView` | Gespeicherte View-Definitionen |
|
||||
| `defineNavigationMenuItem` | Definitionen von Navigationsmenüeinträgen |
|
||||
| `defineSkill` | Skill-Definitionen für KI-Agenten |
|
||||
|
||||
<Note>
|
||||
**Dateibenennung ist flexibel.** Die Entitätserkennung ist AST-basiert — das SDK durchsucht Ihre Quelldateien nach dem Muster `export default define<Entity>({...})`. Sie können Ihre Dateien und Ordner nach Belieben organisieren. Die Gruppierung nach Entitätstyp (z. B. `logic-functions/`, `roles/`) ist lediglich eine Konvention zur Codeorganisation, keine Voraussetzung.
|
||||
</Note>
|
||||
|
||||
Beispiel für eine erkannte Entität:
|
||||
|
||||
```typescript
|
||||
// This file can be named anything and placed anywhere in src/
|
||||
import { defineObject, FieldType } from 'twenty-sdk';
|
||||
|
||||
export default defineObject({
|
||||
universalIdentifier: '...',
|
||||
nameSingular: 'postCard',
|
||||
// ... rest of config
|
||||
});
|
||||
```
|
||||
|
||||
Spätere Befehle fügen weitere Dateien und Ordner hinzu:
|
||||
|
||||
* `yarn twenty app:dev` generiert automatisch zwei typisierte API-Clients in `node_modules/twenty-sdk/generated`: `CoreApiClient` (für Arbeitsbereichsdaten über `/graphql`) und `MetadataApiClient` (für Arbeitsbereichskonfiguration und Datei-Uploads über `/metadata`).
|
||||
* `yarn twenty entity:add` fügt unter `src/` Entitätsdefinitionsdateien für Ihre benutzerdefinierten Objekte, Funktionen, Frontend-Komponenten, Rollen, Skills und mehr hinzu.
|
||||
|
||||
## Authentifizierung
|
||||
|
||||
Wenn Sie `yarn twenty auth:login` zum ersten Mal ausführen, werden Sie nach Folgendem gefragt:
|
||||
|
||||
* API-URL (standardmäßig http://localhost:3000 oder Ihr aktuelles Workspace-Profil)
|
||||
* API-Schlüssel
|
||||
|
||||
Ihre Anmeldedaten werden pro Benutzer in `~/.twenty/config.json` gespeichert. Sie können mehrere Profile verwalten und zwischen ihnen wechseln.
|
||||
|
||||
### Arbeitsbereiche verwalten
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Login interactively (recommended)
|
||||
yarn twenty auth:login
|
||||
|
||||
# Login to a specific workspace profile
|
||||
yarn twenty auth:login --workspace my-custom-workspace
|
||||
|
||||
# List all configured workspaces
|
||||
yarn twenty auth:list
|
||||
|
||||
# Switch the default workspace (interactive)
|
||||
yarn twenty auth:switch
|
||||
|
||||
# Switch to a specific workspace
|
||||
yarn twenty auth:switch production
|
||||
|
||||
# Check current authentication status
|
||||
yarn twenty auth:status
|
||||
```
|
||||
|
||||
Sobald Sie mit `yarn twenty auth:switch` den Arbeitsbereich gewechselt haben, verwenden alle nachfolgenden Befehle standardmäßig diesen Arbeitsbereich. Sie können es weiterhin vorübergehend mit `--workspace <name>` überschreiben.
|
||||
|
||||
## Manuelle Einrichtung (ohne Scaffolder)
|
||||
|
||||
Wir empfehlen zwar `create-twenty-app` für das beste Einstiegserlebnis, Sie können ein Projekt aber auch manuell einrichten. Installieren Sie die CLI nicht global. Fügen Sie stattdessen `twenty-sdk` als lokale Abhängigkeit hinzu und binden Sie ein einzelnes Skript in Ihrer package.json ein:
|
||||
|
||||
```bash filename="Terminal"
|
||||
yarn add -D twenty-sdk
|
||||
```
|
||||
|
||||
Fügen Sie dann ein `twenty`-Skript hinzu:
|
||||
|
||||
```json filename="package.json"
|
||||
{
|
||||
"scripts": {
|
||||
"twenty": "twenty"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Jetzt können Sie alle Befehle über `yarn twenty <command>` ausführen, z. B. `yarn twenty app:dev`, `yarn twenty help` usw.
|
||||
|
||||
## Fehlerbehebung
|
||||
|
||||
* Authentifizierungsfehler: Führen Sie `yarn twenty auth:login` aus und stellen Sie sicher, dass Ihr API-Schlüssel die erforderlichen Berechtigungen hat.
|
||||
* Verbindung zum Server nicht möglich: Überprüfen Sie die API-URL und dass der Twenty-Server erreichbar ist.
|
||||
* Typen oder Client fehlen/veraltet: Starten Sie `yarn twenty app:dev` neu — der typisierte Client wird automatisch generiert.
|
||||
* Dev-Modus synchronisiert nicht: Stellen Sie sicher, dass `yarn twenty app:dev` läuft und dass Änderungen von Ihrer Umgebung nicht ignoriert werden.
|
||||
|
||||
Discord-Hilfekanal: https://discord.com/channels/1130383047699738754/1130386664812982322
|
||||
@@ -1,119 +0,0 @@
|
||||
---
|
||||
title: Veröffentlichen
|
||||
description: Veröffentlichen Sie Ihre Twenty-App auf dem Twenty-Marktplatz oder stellen Sie sie intern bereit.
|
||||
---
|
||||
|
||||
<Warning>
|
||||
Apps befinden sich derzeit in der Alpha-Testphase. Die Funktion ist funktionsfähig, entwickelt sich jedoch noch weiter.
|
||||
</Warning>
|
||||
|
||||
## Übersicht
|
||||
|
||||
Sobald Ihre App [lokal gebaut und getestet](/l/de/developers/extend/apps/building) wurde, haben Sie zwei Möglichkeiten, sie zu verteilen:
|
||||
|
||||
* **Auf npm veröffentlichen** — führen Sie Ihre App im Twenty-Marktplatz auf, damit jeder Arbeitsbereich sie entdecken und installieren kann.
|
||||
* **Einen Tarball pushen** — stellen Sie Ihre App auf einem bestimmten Twenty-Server für die interne Nutzung bereit, ohne sie öffentlich verfügbar zu machen.
|
||||
|
||||
## Auf npm veröffentlichen
|
||||
|
||||
Die Veröffentlichung auf npm macht Ihre App im Twenty-Marktplatz auffindbar. Jeder Twenty-Arbeitsbereich kann Marktplatz-Apps direkt über die Benutzeroberfläche durchsuchen, installieren und aktualisieren.
|
||||
|
||||
### Anforderungen
|
||||
|
||||
* Ein [npm](https://www.npmjs.com)-Konto
|
||||
* Ihr Paketname **muss** das Präfix `twenty-app-` verwenden (z. B. `twenty-app-postcard-sender`)
|
||||
|
||||
### Schritte
|
||||
|
||||
1. **App erstellen** — die CLI kompiliert Ihre TypeScript-Quellen und erzeugt das Anwendungsmanifest:
|
||||
|
||||
```bash filename="Terminal"
|
||||
yarn twenty app:build
|
||||
```
|
||||
|
||||
2. **Auf npm veröffentlichen** — pushen Sie das gebaute Paket in die npm-Registry:
|
||||
|
||||
```bash filename="Terminal"
|
||||
npx twenty app:publish
|
||||
```
|
||||
|
||||
### Automatische Erkennung
|
||||
|
||||
Pakete mit dem Präfix `twenty-app-` werden vom Twenty-Marktplatzkatalog automatisch erkannt. Nach der Veröffentlichung erscheint Ihre App innerhalb weniger Minuten im Marktplatz — keine manuelle Registrierung oder Genehmigung erforderlich.
|
||||
|
||||
### CI-Veröffentlichung
|
||||
|
||||
Das vorgefertigte Projekt enthält einen GitHub-Actions-Workflow, der bei jedem Release eine Veröffentlichung durchführt. Er führt `app:build` aus und danach `npm publish --provenance` aus dem Build-Output:
|
||||
|
||||
```yaml filename=".github/workflows/publish.yml"
|
||||
name: Publish
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "24"
|
||||
registry-url: https://registry.npmjs.org
|
||||
- run: yarn install --immutable
|
||||
- run: npx twenty app:build
|
||||
- run: npm publish --provenance --access public
|
||||
working-directory: .twenty/output
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
```
|
||||
|
||||
Für andere CI-Systeme (GitLab CI, CircleCI usw.) gelten die gleichen drei Befehle: `yarn install`, `npx twenty app:build` und anschließend `npm publish` aus `.twenty/output`.
|
||||
|
||||
<Tip>
|
||||
**npm-Provenance** ist optional, wird jedoch empfohlen. Das Veröffentlichen mit `--provenance` fügt Ihrem npm-Eintrag ein Vertrauensabzeichen hinzu, sodass Nutzer überprüfen können, dass das Paket aus einem bestimmten Commit in einer öffentlichen CI-Pipeline gebaut wurde. Siehe die [npm-Provenance-Dokumentation](https://docs.npmjs.com/generating-provenance-statements) für Einrichtungshinweise.
|
||||
</Tip>
|
||||
|
||||
## Interne Verteilung
|
||||
|
||||
Für Apps, die Sie nicht öffentlich verfügbar machen möchten — proprietäre Tools, nur für Unternehmen bestimmte Integrationen oder experimentelle Builds — können Sie einen Tarball direkt auf einen Twenty-Server pushen.
|
||||
|
||||
### Einen Tarball pushen
|
||||
|
||||
Erstellen Sie Ihre App und stellen Sie sie in einem Schritt auf einem bestimmten Server bereit:
|
||||
|
||||
```bash filename="Terminal"
|
||||
npx twenty app:publish --server <server-url>
|
||||
```
|
||||
|
||||
Jeder Arbeitsbereich auf diesem Server kann die App anschließend über die Seite **Applications** in den Einstellungen installieren und aktualisieren.
|
||||
|
||||
### Versionsverwaltung
|
||||
|
||||
So veröffentlichen Sie ein Update:
|
||||
|
||||
1. Erhöhen Sie das Feld `version` in Ihrer `package.json`
|
||||
2. Pushen Sie einen neuen Tarball mit `npx twenty app:publish --server <server-url>`
|
||||
3. Arbeitsbereiche auf diesem Server sehen in ihren Einstellungen, dass ein Upgrade verfügbar ist.
|
||||
|
||||
<Note>
|
||||
Interne Apps sind auf den Server beschränkt, auf den sie gepusht werden. Sie erscheinen nicht im öffentlichen Marktplatz und können von Arbeitsbereichen auf anderen Servern nicht installiert werden.
|
||||
</Note>
|
||||
|
||||
## App-Kategorien
|
||||
|
||||
Twenty organisiert Apps in drei Kategorien, basierend auf ihrer Vertriebsart:
|
||||
|
||||
| Kategorie | Wie es funktioniert | Im Marktplatz sichtbar? |
|
||||
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------ | ----------------------- |
|
||||
| **Entwicklung** | Lokale Apps im Entwicklungsmodus, die über `yarn twenty app:dev` ausgeführt werden. Zum Erstellen und Testen verwendet. | Nein |
|
||||
| **Veröffentlicht** | Auf npm veröffentlichte Apps mit dem Präfix `twenty-app-`. Im Marktplatz gelistet, damit jeder Arbeitsbereich sie installieren kann. | Ja |
|
||||
| **Intern** | Apps, die per Tarball auf einen bestimmten Server bereitgestellt werden. Nur für Arbeitsbereiche auf diesem Server verfügbar. | Nein |
|
||||
|
||||
<Tip>
|
||||
Beginnen Sie im **Entwicklungsmodus**, während Sie Ihre App erstellen. Wenn sie bereit ist, wählen Sie **Veröffentlicht** (npm) für die breite Verteilung oder **Intern** (Tarball) für die private Bereitstellung.
|
||||
</Tip>
|
||||
@@ -171,7 +171,7 @@ export default defineObject({
|
||||
|
||||
Spätere Befehle fügen weitere Dateien und Ordner hinzu:
|
||||
|
||||
* `yarn twenty app:dev` generiert automatisch zwei typisierte API-Clients in `node_modules/twenty-sdk/clients`: `CoreApiClient` (für Arbeitsbereichsdaten über `/graphql`) und `MetadataApiClient` (für Arbeitsbereichskonfiguration und Datei-Uploads über `/metadata`).
|
||||
* `yarn twenty app:dev` generiert automatisch zwei typisierte API-Clients in `node_modules/twenty-sdk/generated`: `CoreApiClient` (für Arbeitsbereichsdaten über `/graphql`) und `MetadataApiClient` (für Arbeitsbereichskonfiguration und Datei-Uploads über `/metadata`).
|
||||
* `yarn twenty entity:add` fügt unter `src/` Entitätsdefinitionsdateien für Ihre benutzerdefinierten Objekte, Funktionen, Frontend-Komponenten, Rollen, Skills und mehr hinzu.
|
||||
|
||||
## Authentifizierung
|
||||
@@ -228,7 +228,7 @@ Das SDK stellt Hilfsfunktionen bereit, um die Entitäten Ihrer App zu definieren
|
||||
| `defineView()` | Gespeicherte Views für Objekte definieren |
|
||||
| `defineNavigationMenuItem()` | Seitenleisten-Navigationslinks definieren |
|
||||
| `defineSkill()` | Definieren Sie Skills für KI-Agenten |
|
||||
| `defineAgent()` | Definieren Sie KI-Agenten mit System-Prompts |
|
||||
| `defineAgent()` | Define AI agents with system prompts |
|
||||
|
||||
Diese Funktionen validieren Ihre Konfiguration zur Build-Zeit und bieten IDE-Autovervollständigung sowie Typsicherheit.
|
||||
|
||||
@@ -321,72 +321,6 @@ Sie können Standardfelder überschreiben, indem Sie in Ihrem `fields`-Array ein
|
||||
dies wird jedoch nicht empfohlen.
|
||||
</Note>
|
||||
|
||||
### Felder für bestehende Objekte definieren
|
||||
|
||||
Verwenden Sie `defineField()`, um benutzerdefinierte Felder zu bestehenden Objekten hinzuzufügen — sowohl zu Standardobjekten (wie `company`, `person`, `opportunity`) als auch zu benutzerdefinierten Objekten, die von anderen Apps definiert werden. Jedes Feld befindet sich in einer eigenen Datei und verweist auf das Zielobjekt über dessen `universalIdentifier`.
|
||||
|
||||
Um auf Standardobjekte zu verweisen, importieren Sie `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS` aus `twenty-sdk`. Diese Konstante stellt stabile Bezeichner für alle integrierten Objekte und deren Felder bereit:
|
||||
|
||||
```typescript
|
||||
// src/fields/apollo-total-funding.field.ts
|
||||
import {
|
||||
defineField,
|
||||
FieldType,
|
||||
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS,
|
||||
} from 'twenty-sdk';
|
||||
|
||||
export default defineField({
|
||||
universalIdentifier: 'c90ae72d-4ddf-4f22-882f-eef98c91e40e',
|
||||
objectUniversalIdentifier:
|
||||
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company.universalIdentifier,
|
||||
type: FieldType.CURRENCY,
|
||||
name: 'apolloTotalFunding',
|
||||
label: 'Total Funding',
|
||||
description: 'Total funding raised by the company',
|
||||
icon: 'IconCash',
|
||||
});
|
||||
```
|
||||
|
||||
Hauptpunkte:
|
||||
|
||||
* `objectUniversalIdentifier` teilt Twenty mit, an welches Objekt das Feld angehängt werden soll. Verwenden Sie `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.<objectName>.universalIdentifier` für Standardobjekte.
|
||||
* Jedes Feld benötigt einen eigenen stabilen `universalIdentifier`, `name`, `type`, `label` und den Ziel-`objectUniversalIdentifier`.
|
||||
* Sie können mit `yarn twenty entity:add` neue Felder anlegen, indem Sie die Feldoption wählen.
|
||||
* `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS` wird der Einfachheit halber auch als `STANDARD_OBJECT` exportiert — beide verweisen auf dieselbe Konstante.
|
||||
|
||||
Verfügbare Standardobjekte sind unter anderem: `attachment`, `blocklist`, `calendarChannel`, `calendarEvent`, `calendarEventParticipant`, `company`, `connectedAccount`, `dashboard`, `favorite`, `favoriteFolder`, `message`, `messageChannel`, `messageParticipant`, `messageThread`, `note`, `noteTarget`, `opportunity`, `person`, `task`, `taskTarget`, `timelineActivity`, `workflow`, `workflowAutomatedTrigger`, `workflowRun`, `workflowVersion` und `workspaceMember`.
|
||||
|
||||
Jedes Standardobjekt stellt außerdem seine Feldbezeichner bereit. Beispielsweise, um in Rollenberechtigungen auf ein bestimmtes Feld eines Standardobjekts zu verweisen:
|
||||
|
||||
```typescript
|
||||
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company.fields.name.universalIdentifier
|
||||
```
|
||||
|
||||
#### Beziehungsfelder bei bestehenden Objekten
|
||||
|
||||
Sie können auch Beziehungsfelder definieren, die bestehende Objekte mit Ihren benutzerdefinierten Objekten verknüpfen:
|
||||
|
||||
```typescript
|
||||
// src/fields/people-on-call-recording.field.ts
|
||||
import { defineField, FieldType, RelationType, STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS } from 'twenty-sdk';
|
||||
import { CALL_RECORDING_OBJECT_UNIVERSAL_IDENTIFIER } from 'src/objects/call-recording';
|
||||
import { CALL_RECORDING_ON_PERSON_ID } from 'src/fields/call-recording-on-person.field';
|
||||
|
||||
export default defineField({
|
||||
universalIdentifier: '4a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d',
|
||||
objectUniversalIdentifier:
|
||||
CALL_RECORDING_OBJECT_UNIVERSAL_IDENTIFIER,
|
||||
type: FieldType.RELATION,
|
||||
name: 'person',
|
||||
label: 'Person',
|
||||
relationTargetObjectMetadataUniversalIdentifier:
|
||||
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.person.universalIdentifier,
|
||||
relationTargetFieldMetadataUniversalIdentifier:
|
||||
CALL_RECORDING_ON_PERSON_ID,
|
||||
relationType: RelationType.MANY_TO_ONE,
|
||||
});
|
||||
```
|
||||
|
||||
### Anwendungskonfiguration (application-config.ts)
|
||||
|
||||
Jede App hat eine einzelne Datei `application-config.ts`, die Folgendes beschreibt:
|
||||
@@ -500,7 +434,7 @@ Jede Funktionsdatei verwendet `defineLogicFunction()`, um eine Konfiguration mit
|
||||
// src/app/createPostCard.logic-function.ts
|
||||
import { defineLogicFunction } from 'twenty-sdk';
|
||||
import type { DatabaseEventPayload, ObjectRecordCreateEvent, CronPayload, RoutePayload } from 'twenty-sdk';
|
||||
import { CoreApiClient, type Person } from 'twenty-sdk/clients';
|
||||
import { CoreApiClient, type Person } from 'twenty-sdk/generated';
|
||||
|
||||
const handler = async (params: RoutePayload) => {
|
||||
const client = new CoreApiClient();
|
||||
@@ -745,7 +679,7 @@ Um eine Logikfunktion als Tool zu markieren, setzen Sie `isTool: true` und geben
|
||||
```typescript
|
||||
// src/logic-functions/enrich-company.logic-function.ts
|
||||
import { defineLogicFunction } from 'twenty-sdk';
|
||||
import { CoreApiClient } from 'twenty-sdk/clients';
|
||||
import { CoreApiClient } from 'twenty-sdk/generated';
|
||||
|
||||
const handler = async (params: { companyName: string; domain?: string }) => {
|
||||
const client = new CoreApiClient();
|
||||
@@ -837,255 +771,6 @@ Sie können neue Frontend-Komponenten auf zwei Arten erstellen:
|
||||
* **Generiert**: Führen Sie `yarn twenty entity:add` aus und wählen Sie die Option zum Hinzufügen einer neuen Frontend-Komponente.
|
||||
* **Manuell**: Erstellen Sie eine neue `.tsx`-Datei und verwenden Sie `defineFrontComponent()` nach demselben Muster.
|
||||
|
||||
#### Wo Front-Komponenten verwendet werden können
|
||||
|
||||
Front-Komponenten können an zwei Stellen innerhalb von Twenty gerendert werden:
|
||||
|
||||
* **Seitenpanel** — Nicht-Headless-Front-Komponenten werden im rechten Seitenpanel geöffnet. Dies ist das Standardverhalten, wenn eine Front-Komponente über das Befehlsmenü ausgelöst wird.
|
||||
* **Widgets (Dashboards und Datensatzseiten)** — Front-Komponenten können als Widgets in Seitenlayouts eingebettet werden. Beim Konfigurieren eines Dashboards oder eines Datensatzseiten-Layouts können Benutzer ein Front-Komponenten-Widget hinzufügen.
|
||||
|
||||
#### Headless vs. Nicht-Headless
|
||||
|
||||
Front-Komponenten gibt es in zwei Rendering-Modi, die durch die Option `isHeadless` gesteuert werden:
|
||||
|
||||
**Nicht-Headless (Standard)** — Die Komponente rendert eine sichtbare UI. Wird sie über das Befehlsmenü ausgelöst, öffnet sie sich im Seitenpanel. Dies ist das Standardverhalten, wenn `isHeadless` `false` ist oder weggelassen wird.
|
||||
|
||||
**Headless** — Die Komponente wird unsichtbar im Hintergrund gemountet. Sie öffnet das Seitenpanel nicht. Headless-Komponenten sind für Aktionen konzipiert, die Logik ausführen und sich anschließend selbst unmounten — zum Beispiel das Ausführen einer asynchronen Aufgabe, das Navigieren zu einer Seite oder das Anzeigen eines Bestätigungsdialogs. Sie lassen sich gut mit den unten beschriebenen SDK-Command-Komponenten kombinieren.
|
||||
|
||||
```typescript
|
||||
export default defineFrontComponent({
|
||||
universalIdentifier: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
|
||||
name: 'my-action',
|
||||
description: 'Runs an action without opening the side panel',
|
||||
component: MyAction,
|
||||
isHeadless: true,
|
||||
command: {
|
||||
universalIdentifier: 'b2c3d4e5-f6a7-8901-bcde-f12345678901',
|
||||
label: 'Run my action',
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
#### Befehlsmenü-Einträge hinzufügen
|
||||
|
||||
Damit eine Front-Komponente als Eintrag im Befehlsmenü von Twenty erscheint, fügen Sie die Eigenschaft `command` zu `defineFrontComponent()` hinzu. Wenn Benutzer das Befehlsmenü öffnen (Cmd+K / Ctrl+K), erscheint der Eintrag und löst beim Klicken die Front-Komponente aus.
|
||||
|
||||
Das Objekt `command` akzeptiert die folgenden Felder:
|
||||
|
||||
| Feld | Typ | Beschreibung |
|
||||
| --------------------------------------- | ------------------------------------------- | ----------------------------------------------------------------------------------------------- |
|
||||
| `universalIdentifier` | `string` (erforderlich) | Eindeutige ID für den Befehlsmenü-Eintrag |
|
||||
| `beschriftung` | `string` (erforderlich) | Angezeigtes Label im Befehlsmenü |
|
||||
| `symbol` | `string` (optional) | Iconname (z. B. 'IconSparkles') |
|
||||
| `isPinned` | `boolean` (optional) | Ob der Befehl oben im Menü angeheftet ist |
|
||||
| `availabilityType` | `'GLOBAL' \| 'RECORD_SELECTION'` (optional) | `GLOBAL` zeigt den Befehl überall an; `RECORD_SELECTION` zeigt ihn nur in Datensatzkontexten an |
|
||||
| `availabilityObjectUniversalIdentifier` | `string` (optional) | Beschränkt den Befehl auf einen bestimmten Objekttyp (z. B. Person) |
|
||||
|
||||
Hier ist ein Beispiel aus der Call-Recording-App, das einen auf Person-Datensätze beschränkten Befehl hinzufügt:
|
||||
|
||||
```typescript
|
||||
import { defineFrontComponent } from 'twenty-sdk';
|
||||
|
||||
export default defineFrontComponent({
|
||||
universalIdentifier: 'c3d4e5f6-a7b8-9012-cdef-123456789012',
|
||||
name: 'Summarize Person Call Recordings',
|
||||
description: 'Generates a summary of call recordings for a person',
|
||||
component: SummarizePersonRecordings,
|
||||
command: {
|
||||
universalIdentifier: 'd4e5f6a7-b8c9-0123-defa-234567890123',
|
||||
label: 'Summarize call recordings',
|
||||
icon: 'IconSparkles',
|
||||
isPinned: false,
|
||||
availabilityType: 'RECORD_SELECTION',
|
||||
availabilityObjectUniversalIdentifier:
|
||||
'20202020-e674-48e5-a542-72570eee7213',
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Wenn der Befehl synchronisiert wird, erscheint er im Befehlsmenü. Wenn die Front-Komponente Nicht-Headless ist, öffnet sich das Seitenpanel und die Komponente wird darin gerendert. Wenn sie Headless ist, wird die Komponente im Hintergrund gemountet und führt ihre Logik aus.
|
||||
|
||||
#### SDK-Command-Komponenten
|
||||
|
||||
Das Paket `twenty-sdk` stellt vier Command-Hilfskomponenten bereit, die für Headless-Front-Komponenten ausgelegt sind. Jede Komponente führt beim Mounten eine Aktion aus, behandelt Fehler durch Anzeige einer Snackbar-Benachrichtigung und unmountet die Front-Komponente nach Abschluss automatisch.
|
||||
|
||||
Importieren Sie sie aus `twenty-sdk/command`:
|
||||
|
||||
* **`Command`** — Führt einen asynchronen Callback über das Prop `execute` aus.
|
||||
* **`CommandLink`** — Navigiert zu einem App-Pfad. Props: `to`, `params`, `queryParams`, `options`.
|
||||
* **`CommandModal`** — Öffnet einen Bestätigungsdialog. Bestätigt der Benutzer, wird der Callback `execute` ausgeführt. Props: `title`, `subtitle`, `execute`, `confirmButtonText`, `confirmButtonAccent`.
|
||||
* **`CommandOpenSidePanelPage`** — Öffnet eine bestimmte Seite im Seitenpanel. Props: `page`, `pageTitle`, `pageIcon`.
|
||||
|
||||
Hier ist ein vollständiges Beispiel einer Headless-Front-Komponente, die `Command` verwendet, um eine Aktion aus dem Befehlsmenü auszuführen:
|
||||
|
||||
```typescript
|
||||
// src/front-components/run-action.tsx
|
||||
import { defineFrontComponent } from 'twenty-sdk';
|
||||
import { Command } from 'twenty-sdk/command';
|
||||
import { CoreApiClient } from 'twenty-sdk/clients';
|
||||
|
||||
const RunAction = () => {
|
||||
const execute = async () => {
|
||||
const client = new CoreApiClient();
|
||||
|
||||
await client.mutation({
|
||||
createTask: {
|
||||
__args: { data: { title: 'Created by my app' } },
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return <Command execute={execute} />;
|
||||
};
|
||||
|
||||
export default defineFrontComponent({
|
||||
universalIdentifier: 'e5f6a7b8-c9d0-1234-efab-345678901234',
|
||||
name: 'run-action',
|
||||
description: 'Creates a task from the command menu',
|
||||
component: RunAction,
|
||||
isHeadless: true,
|
||||
command: {
|
||||
universalIdentifier: 'f6a7b8c9-d0e1-2345-fabc-456789012345',
|
||||
label: 'Run my action',
|
||||
icon: 'IconPlayerPlay',
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Und ein Beispiel, das `CommandModal` verwendet, um vor der Ausführung um Bestätigung zu bitten:
|
||||
|
||||
```typescript
|
||||
// src/front-components/delete-draft.tsx
|
||||
import { defineFrontComponent } from 'twenty-sdk';
|
||||
import { CommandModal } from 'twenty-sdk/command';
|
||||
|
||||
const DeleteDraft = () => {
|
||||
const execute = async () => {
|
||||
// perform the deletion
|
||||
};
|
||||
|
||||
return (
|
||||
<CommandModal
|
||||
title="Delete draft?"
|
||||
subtitle="This action cannot be undone."
|
||||
execute={execute}
|
||||
confirmButtonText="Delete"
|
||||
confirmButtonAccent="danger"
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default defineFrontComponent({
|
||||
universalIdentifier: 'a7b8c9d0-e1f2-3456-abcd-567890123456',
|
||||
name: 'delete-draft',
|
||||
description: 'Deletes a draft with confirmation',
|
||||
component: DeleteDraft,
|
||||
isHeadless: true,
|
||||
command: {
|
||||
universalIdentifier: 'b8c9d0e1-f2a3-4567-bcde-678901234567',
|
||||
label: 'Delete draft',
|
||||
icon: 'IconTrash',
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
#### Ausführungskontext
|
||||
|
||||
Jede Front-Komponente erhält einen Ausführungskontext, der Informationen darüber liefert, wo und wie sie ausgeführt wird. Greifen Sie mit Hooks aus `twenty-sdk` auf Kontextwerte zu:
|
||||
|
||||
| Hook | Rückgabetyp | Beschreibung |
|
||||
| ----------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `useFrontComponentId()` | `string` | Die eindeutige ID der aktuellen Front-Komponenteninstanz |
|
||||
| `useRecordId()` | `string \| null` | Die ID des aktuellen Datensatzes, wenn die Komponente in einem Datensatzkontext ausgeführt wird (z. B. ein Widget auf einer Datensatzseite oder ein auf einen Datensatz beschränkter Befehl). Andernfalls wird `null` zurückgegeben. |
|
||||
| `useUserId()` | `string \| null` | Die ID des aktuellen Benutzers |
|
||||
|
||||
```typescript
|
||||
import { useRecordId, useUserId } from 'twenty-sdk';
|
||||
|
||||
const MyWidget = () => {
|
||||
const recordId = useRecordId();
|
||||
const userId = useUserId();
|
||||
|
||||
return (
|
||||
<div>
|
||||
<p>Record: {recordId ?? 'none'}</p>
|
||||
<p>User: {userId ?? 'anonymous'}</p>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
Der Kontext ist reaktiv — ändert sich der umgebende Datensatz, liefern die Hooks automatisch die aktualisierten Werte.
|
||||
|
||||
#### Host-API-Funktionen
|
||||
|
||||
Front-Komponenten laufen in einer isolierten Sandbox, können jedoch über eine Reihe vom Host bereitgestellter Funktionen mit der UI von Twenty interagieren. Importieren Sie sie direkt aus `twenty-sdk`:
|
||||
|
||||
```typescript
|
||||
import {
|
||||
navigate,
|
||||
closeSidePanel,
|
||||
enqueueSnackbar,
|
||||
unmountFrontComponent,
|
||||
openSidePanelPage,
|
||||
openCommandConfirmationModal,
|
||||
} from 'twenty-sdk';
|
||||
```
|
||||
|
||||
| Funktion | Signatur | Beschreibung |
|
||||
| ------------------------------ | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `navigieren` | `(to, params?, queryParams?, options?) => Promise<void>` | Navigieren Sie zu einem typisierten App-Pfad innerhalb von Twenty |
|
||||
| `closeSidePanel` | `() => Promise<void>` | Seitenpanel schließen |
|
||||
| `enqueueSnackbar` | `(params) => Promise<void>` | Eine Snackbar-Benachrichtigung anzeigen. Parameter: `message`, `variant` (`'error'`, `'success'`, `'info'`, `'warning'`), optional `duration`, `detailedMessage`, `dedupeKey` |
|
||||
| `unmountFrontComponent` | `() => Promise<void>` | Die aktuelle Front-Komponente unmounten (wird von Headless-Komponenten verwendet, um nach der Ausführung aufzuräumen) |
|
||||
| `openSidePanelPage` | `(params) => Promise<void>` | Eine Seite im Seitenpanel öffnen. Parameter: `page`, `pageTitle`, `pageIcon`, `shouldResetSearchState` |
|
||||
| `openCommandConfirmationModal` | `(params) => Promise<'confirm' \| 'cancel'>` | Einen Bestätigungsdialog anzeigen und auf die Antwort des Benutzers warten. Parameter: `title`, `subtitle`, `confirmButtonText`, `confirmButtonAccent` (`'default'`, `'blue'`, `'danger'`) |
|
||||
|
||||
Hier ist ein Beispiel, das die Host-API verwendet, um nach Abschluss einer Aktion eine Snackbar anzuzeigen und das Seitenpanel zu schließen:
|
||||
|
||||
```typescript
|
||||
import { defineFrontComponent, useRecordId } from 'twenty-sdk';
|
||||
import { enqueueSnackbar, closeSidePanel } from 'twenty-sdk';
|
||||
import { CoreApiClient } from 'twenty-sdk/clients';
|
||||
|
||||
const ArchiveRecord = () => {
|
||||
const recordId = useRecordId();
|
||||
|
||||
const handleArchive = async () => {
|
||||
const client = new CoreApiClient();
|
||||
|
||||
await client.mutation({
|
||||
updateTask: {
|
||||
__args: { id: recordId, data: { status: 'ARCHIVED' } },
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
await enqueueSnackbar({
|
||||
message: 'Record archived',
|
||||
variant: 'success',
|
||||
});
|
||||
|
||||
await closeSidePanel();
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ padding: '20px' }}>
|
||||
<p>Archive this record?</p>
|
||||
<button onClick={handleArchive}>Archive</button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default defineFrontComponent({
|
||||
universalIdentifier: 'c9d0e1f2-a3b4-5678-cdef-789012345678',
|
||||
name: 'archive-record',
|
||||
description: 'Archives the current record',
|
||||
component: ArchiveRecord,
|
||||
});
|
||||
```
|
||||
|
||||
### Fähigkeiten
|
||||
|
||||
Skills definieren wiederverwendbare Anweisungen und Fähigkeiten, die KI-Agenten in Ihrem Arbeitsbereich verwenden können. Verwenden Sie `defineSkill()`, um Skills mit eingebauter Validierung zu definieren:
|
||||
@@ -1123,7 +808,7 @@ Sie können neue Skills auf zwei Arten erstellen:
|
||||
|
||||
### Agenten
|
||||
|
||||
Mit Agents definieren Sie KI-Agenten mit System-Prompts, die in Ihrem Arbeitsbereich arbeiten können. Verwenden Sie `defineAgent()`, um Agenten mit eingebauter Validierung zu definieren:
|
||||
Agents define AI agents with system prompts that can operate within your workspace. Use `defineAgent()` to define agents with built-in validation:
|
||||
|
||||
```typescript
|
||||
// src/agents/example-agent.ts
|
||||
@@ -1145,27 +830,26 @@ export default defineAgent({
|
||||
|
||||
Hauptpunkte:
|
||||
|
||||
* `name` ist eine eindeutige Kennung (als Zeichenfolge) für den Agenten (kebab-case empfohlen).
|
||||
* `name` is a unique identifier string for the agent (kebab-case recommended).
|
||||
* `label` ist der menschenlesbare Anzeigename, der in der UI angezeigt wird.
|
||||
* `prompt` enthält den System-Prompt — dies ist der Anweisungstext, der das Verhalten des Agenten definiert.
|
||||
* `prompt` contains the system prompt — this is the instruction text that defines the agent's behavior.
|
||||
* `icon` (optional) legt das in der UI angezeigte Symbol fest.
|
||||
* `description` (optional) liefert zusätzlichen Kontext zum Zweck des Agenten.
|
||||
* `description` (optional) provides additional context about the agent's purpose.
|
||||
|
||||
Sie können neue Agenten auf zwei Arten erstellen:
|
||||
You can create new agents in two ways:
|
||||
|
||||
* **Generiert**: Führen Sie `yarn twenty entity:add` aus und wählen Sie die Option zum Hinzufügen eines neuen Agenten.
|
||||
* **Manuell**: Erstellen Sie eine neue Datei und verwenden Sie `defineAgent()` nach demselben Muster.
|
||||
* **Scaffolded**: Run `yarn twenty entity:add` and choose the option to add a new agent.
|
||||
* **Manual**: Create a new file and use `defineAgent()`, following the same pattern.
|
||||
|
||||
### Generierte typisierte Clients
|
||||
|
||||
Zwei typisierte Clients werden von `yarn twenty app:dev` automatisch generiert und basierend auf Ihrem Arbeitsbereichs-Schema in `node_modules/twenty-sdk/clients` gespeichert:
|
||||
Zwei typisierte Clients werden von `yarn twenty app:dev` automatisch generiert und basierend auf Ihrem Arbeitsbereichs-Schema in `node_modules/twenty-sdk/generated` gespeichert:
|
||||
|
||||
* **`CoreApiClient`** — fragt den `/graphql`-Endpunkt nach Arbeitsbereichsdaten ab
|
||||
* **`MetadataApiClient`** — ruft über den Endpunkt `/metadata` die Arbeitsbereichskonfiguration und Datei-Uploads ab.
|
||||
|
||||
```typescript
|
||||
import { CoreApiClient } from 'twenty-sdk/clients';
|
||||
import { MetadataApiClient } from 'twenty-sdk/clients';
|
||||
import { CoreApiClient, MetadataApiClient } from 'twenty-sdk/generated';
|
||||
|
||||
const client = new CoreApiClient();
|
||||
const { me } = await client.query({ me: { id: true, displayName: true } });
|
||||
@@ -1174,7 +858,7 @@ const metadataClient = new MetadataApiClient();
|
||||
const { currentWorkspace } = await metadataClient.query({ currentWorkspace: { id: true } });
|
||||
```
|
||||
|
||||
`CoreApiClient` wird von `yarn twenty app:dev` automatisch neu generiert, sobald sich Ihre Objekte oder Felder ändern. `MetadataApiClient` ist im SDK bereits enthalten.
|
||||
Beide Clients werden von `yarn twenty app:dev` automatisch neu generiert, sobald sich Ihre Objekte oder Felder ändern.
|
||||
|
||||
#### Laufzeit-Anmeldedaten in Logikfunktionen
|
||||
|
||||
@@ -1191,10 +875,10 @@ Notizen:
|
||||
|
||||
#### Dateien hochladen
|
||||
|
||||
Der `MetadataApiClient` enthält eine Methode `uploadFile`, um Dateien an Felder des Typs Datei in Ihren Arbeitsbereichsobjekten anzuhängen. Da Standard-GraphQL-Clients Multipart-Datei-Uploads nicht nativ unterstützen, stellt der Client diese dedizierte Methode bereit, die unter der Haube die [GraphQL-Multipart-Anfragespezifikation](https://github.com/jaydenseric/graphql-multipart-request-spec) implementiert.
|
||||
Der generierte `MetadataApiClient` enthält eine Methode `uploadFile`, um Dateien an Felder des Typs Datei in Ihren Arbeitsbereichsobjekten anzuhängen. Da Standard-GraphQL-Clients Multipart-Datei-Uploads nicht nativ unterstützen, stellt der Client diese dedizierte Methode bereit, die unter der Haube die [GraphQL-Multipart-Anfragespezifikation](https://github.com/jaydenseric/graphql-multipart-request-spec) implementiert.
|
||||
|
||||
```typescript
|
||||
import { MetadataApiClient } from 'twenty-sdk/clients';
|
||||
import { MetadataApiClient } from 'twenty-sdk/generated';
|
||||
import * as fs from 'fs';
|
||||
|
||||
const metadataClient = new MetadataApiClient();
|
||||
@@ -1223,12 +907,12 @@ uploadFile(
|
||||
): Promise<{ id: string; path: string; size: number; createdAt: string; url: string }>
|
||||
```
|
||||
|
||||
| Parameter | Typ | Beschreibung |
|
||||
| ---------------------------------- | -------------- | ------------------------------------------------------------------------------- |
|
||||
| `fileBuffer` | `Buffer` | Der Rohinhalt der Datei |
|
||||
| `filename` | `string` | Der Name der Datei (wird für Speicherung und Anzeige verwendet) |
|
||||
| `contentType` | `string` | MIME-Typ der Datei (standardmäßig `application/octet-stream`, wenn weggelassen) |
|
||||
| `fieldMetadataUniversalIdentifier` | `Zeichenkette` | Der `universalIdentifier` des Dateityp-Felds in Ihrem Objekt |
|
||||
| Parameter | Typ | Beschreibung |
|
||||
| ---------------------------------- | -------- | ------------------------------------------------------------------------------- |
|
||||
| `fileBuffer` | `Buffer` | Der Rohinhalt der Datei |
|
||||
| `filename` | `string` | Der Name der Datei (wird für Speicherung und Anzeige verwendet) |
|
||||
| `contentType` | `string` | MIME-Typ der Datei (standardmäßig `application/octet-stream`, wenn weggelassen) |
|
||||
| `fieldMetadataUniversalIdentifier` | `string` | Der `universalIdentifier` des Dateityp-Felds in Ihrem Objekt |
|
||||
|
||||
Hauptpunkte:
|
||||
|
||||
|
||||
@@ -15,18 +15,18 @@ Twenty ist darauf ausgelegt, erweiterbar zu sein. Verwenden Sie unsere APIs, Web
|
||||
|
||||
* **APIs**: Abfragen und ändern Sie Ihre CRM-Daten programmatisch mit REST oder GraphQL
|
||||
* **Webhooks**: Erhalten Sie Benachrichtigungen in Echtzeit, wenn Ereignisse in Twenty auftreten
|
||||
* **Apps**: Erstellen Sie benutzerdefinierte Anwendungen, die die Funktionalität von Twenty erweitern
|
||||
* **Apps**: Erstellen Sie benutzerdefinierte Anwendungen, die die Funktionalität von Twenty erweitern - Demnächst verfügbar!
|
||||
|
||||
## Erste Schritte
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="APIs" icon="code" href="/l/de/developers/extend/api">
|
||||
<Card title="APIs" icon="code" href="/l/de/developers/extend/capabilities/apis">
|
||||
Verbinden Sie sich programmgesteuert mit Twenty
|
||||
</Card>
|
||||
<Card title="Webhooks" icon="bell" href="/l/de/developers/extend/webhooks">
|
||||
<Card title="Webhooks" icon="bell" href="/l/de/developers/extend/capabilities/webhooks">
|
||||
Erhalten Sie Benachrichtigungen über Ereignisse in Echtzeit
|
||||
</Card>
|
||||
<Card title="Apps" icon="puzzle-piece" href="/l/de/developers/extend/apps/getting-started">
|
||||
Erstellen Sie Anpassungen als Code
|
||||
<Card title="Apps" icon="puzzle-piece" href="/l/de/developers/extend/capabilities/apps">
|
||||
Erstellen Sie Anpassungen als Code (Alpha)
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
---
|
||||
title: Webhooks
|
||||
description: Erhalten Sie Benachrichtigungen in Echtzeit, wenn Ereignisse in Ihrem CRM auftreten.
|
||||
---
|
||||
|
||||
import { VimeoEmbed } from '/snippets/vimeo-embed.mdx';
|
||||
|
||||
Webhooks übermitteln Daten in Echtzeit an Ihre Systeme, wenn Ereignisse in Twenty auftreten — kein Polling erforderlich. Verwenden Sie sie, um externe Systeme synchron zu halten, Automatisierungen auszulösen oder Benachrichtigungen zu senden.
|
||||
|
||||
## Webhook erstellen
|
||||
|
||||
1. Gehen Sie zu **Einstellungen → APIs & Webhooks → Webhooks**
|
||||
2. Klicken Sie auf **+ Webhook erstellen**
|
||||
3. Geben Sie Ihre Webhook-URL ein (muss öffentlich zugänglich sein)
|
||||
4. Klicken Sie auf **Speichern**
|
||||
|
||||
Der Webhook wird sofort aktiviert und beginnt, Benachrichtigungen zu senden.
|
||||
|
||||
<VimeoEmbed videoId="928786708" title="Webhook erstellen" />
|
||||
|
||||
### Webhooks verwalten
|
||||
|
||||
**Bearbeiten**: Klicken Sie auf den Webhook → URL aktualisieren → **Speichern**
|
||||
|
||||
**Löschen**: Klicken Sie auf den Webhook → **Löschen** → Bestätigen
|
||||
|
||||
## Ereignisse
|
||||
|
||||
Twenty sendet Webhooks für diese Ereignistypen:
|
||||
|
||||
| Ereignis | Beispiel |
|
||||
| -------------------------- | ---------------------------------------------------------- |
|
||||
| **Datensatz erstellt** | `person.created`, `company.created`, `note.created` |
|
||||
| **Datensatz aktualisiert** | `person.updated`, `company.updated`, `opportunity.updated` |
|
||||
| **Datensatz gelöscht** | `person.deleted`, `company.deleted` |
|
||||
|
||||
Alle Ereignistypen werden an Ihre Webhook-URL gesendet. Eine Ereignisfilterung kann in zukünftigen Versionen hinzugefügt werden.
|
||||
|
||||
## Payload-Format
|
||||
|
||||
Jeder Webhook sendet eine HTTP-POST-Anfrage mit einem JSON-Body:
|
||||
|
||||
```json
|
||||
{
|
||||
"event": "person.created",
|
||||
"data": {
|
||||
"id": "abc12345",
|
||||
"firstName": "Alice",
|
||||
"lastName": "Doe",
|
||||
"email": "alice@example.com",
|
||||
"createdAt": "2025-02-10T15:30:45Z",
|
||||
"createdBy": "user_123"
|
||||
},
|
||||
"timestamp": "2025-02-10T15:30:50Z"
|
||||
}
|
||||
```
|
||||
|
||||
| Feld | Beschreibung |
|
||||
| ----------- | -------------------------------------------------------------------- |
|
||||
| `event` | Was passiert ist (z. B. `person.created`) |
|
||||
| `data` | Der vollständige Datensatz, der erstellt/aktualisiert/gelöscht wurde |
|
||||
| `timestamp` | Wann das Ereignis auftrat (UTC) |
|
||||
|
||||
<Note>
|
||||
Antworten Sie mit einem **2xx-HTTP-Status** (200-299), um den Empfang zu bestätigen. Nicht-2xx-Antworten werden als Zustellfehler protokolliert.
|
||||
</Note>
|
||||
|
||||
## Webhook-Validierung
|
||||
|
||||
Twenty signiert jede Webhook-Anfrage zu Sicherheitszwecken. Validieren Sie die Signaturen, um sicherzustellen, dass die Anfragen authentisch sind.
|
||||
|
||||
### Header
|
||||
|
||||
| Header | Beschreibung |
|
||||
| ---------------------------- | ----------------------- |
|
||||
| `X-Twenty-Webhook-Signature` | HMAC-SHA256-Signatur |
|
||||
| `X-Twenty-Webhook-Timestamp` | Zeitstempel der Anfrage |
|
||||
|
||||
### Validierungsschritte
|
||||
|
||||
1. Den Zeitstempel aus `X-Twenty-Webhook-Timestamp` abrufen
|
||||
2. Zeichenfolge erstellen: `{timestamp}:{JSON payload}`
|
||||
3. Den HMAC-SHA256-Hash mit Ihrem Webhook-Geheimnis berechnen
|
||||
4. Mit `X-Twenty-Webhook-Signature` vergleichen
|
||||
|
||||
### Beispiel (Node.js)
|
||||
|
||||
```javascript
|
||||
const crypto = require("crypto");
|
||||
|
||||
const timestamp = req.headers["x-twenty-webhook-timestamp"];
|
||||
const payload = JSON.stringify(req.body);
|
||||
const secret = "your-webhook-secret";
|
||||
|
||||
const stringToSign = `${timestamp}:${payload}`;
|
||||
const expectedSignature = crypto
|
||||
.createHmac("sha256", secret)
|
||||
.update(stringToSign)
|
||||
.digest("hex");
|
||||
|
||||
const receivedSignature = req.headers["x-twenty-webhook-signature"];
|
||||
const isValid = crypto.timingSafeEqual(
|
||||
Buffer.from(expectedSignature, "hex"),
|
||||
Buffer.from(receivedSignature, "hex")
|
||||
);
|
||||
```
|
||||
|
||||
## Webhooks vs Workflows
|
||||
|
||||
| Methode | Richtung | Anwendungsfall |
|
||||
| ---------------------------- | -------- | -------------------------------------------------------------------------------- |
|
||||
| **Webhooks** | OUT | Externe Systeme automatisch über jede Datensatzänderung benachrichtigen |
|
||||
| **Workflow + HTTP-Anfrage** | OUT | Daten mit benutzerdefinierter Logik (Filter, Transformationen) nach außen senden |
|
||||
| **Workflow-Webhook-Trigger** | IN | Daten aus externen Systemen in Twenty empfangen |
|
||||
|
||||
Für den Empfang externer Daten siehe [Webhook-Trigger einrichten](/l/de/user-guide/workflows/how-tos/connect-to-other-tools/set-up-a-webhook-trigger).
|
||||
@@ -149,8 +149,8 @@
|
||||
"extend": {
|
||||
"label": "Erweitern",
|
||||
"groups": {
|
||||
"apps": {
|
||||
"label": "Apps"
|
||||
"extendCapabilities": {
|
||||
"label": "Funktionen"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -24,7 +24,7 @@ Exportieren Sie die Daten Ihres Arbeitsbereichs als CSV für Backups, Berichte o
|
||||
* Nur **sichtbare Spalten** werden exportiert
|
||||
* Nur **gefilterte Datensätze** werden exportiert (basierend auf Ihrer aktuellen Ansicht)
|
||||
|
||||
<Note>Für größere Exporte (mehr als 20.000 Datensätze) verwenden Sie Filter, um stapelweise zu exportieren, oder nutzen Sie die [API](/l/de/developers/extend/api).</Note>
|
||||
<Note>Für größere Exporte (mehr als 20.000 Datensätze) verwenden Sie Filter, um stapelweise zu exportieren, oder nutzen Sie die [API](/l/de/developers/extend/capabilities/apis).</Note>
|
||||
|
||||
### Berechtigungen
|
||||
|
||||
@@ -148,7 +148,7 @@ Die API hat kein Datensatzlimit:
|
||||
2. Verwenden Sie die GraphQL-API, um Datensätze abzufragen
|
||||
3. Verarbeiten Sie die Ergebnisse in Ihrer Anwendung
|
||||
|
||||
Siehe: [API-Dokumentation](/l/de/developers/extend/api)
|
||||
Siehe: [API-Dokumentation](/l/de/developers/extend/capabilities/apis)
|
||||
|
||||
## Tipps und Best Practices
|
||||
|
||||
@@ -206,4 +206,4 @@ Exportierte Dateien können sensible Daten enthalten:
|
||||
|
||||
* [So aktualisieren Sie vorhandene Datensätze](/l/de/user-guide/data-migration/how-tos/update-existing-records-via-import) — bearbeiten Sie Ihren Export und importieren Sie ihn erneut
|
||||
* [So importieren Sie Daten über die API](/l/de/user-guide/data-migration/how-tos/import-data-via-api) — für große Datensätze
|
||||
* [API-Dokumentation](/l/de/developers/extend/api) — erstellen Sie benutzerdefinierte Export-Workflows
|
||||
* [API-Dokumentation](/l/de/developers/extend/capabilities/apis) — erstellen Sie benutzerdefinierte Export-Workflows
|
||||
|
||||
@@ -57,10 +57,10 @@ Jeder, der Ihren API-Schlüssel besitzt, kann auf die Daten Ihres Arbeitsbereich
|
||||
|
||||
Twenty unterstützt zwei API-Typen:
|
||||
|
||||
| API | Am besten geeignet für | Dokumentation |
|
||||
| ----------- | ---------------------------------------------------------------- | ------------------------------------------- |
|
||||
| **GraphQL** | Flexible Abfragen, Abruf verknüpfter Daten, komplexe Operationen | [API-Dokumentation](/l/de/developers/extend/api) |
|
||||
| **REST** | Einfache CRUD-Operationen, vertraute REST-Muster | [API-Dokumentation](/l/de/developers/extend/api) |
|
||||
| API | Am besten geeignet für | Dokumentation |
|
||||
| ----------- | ---------------------------------------------------------------- | --------------------------------------------------------- |
|
||||
| **GraphQL** | Flexible Abfragen, Abruf verknüpfter Daten, komplexe Operationen | [API-Dokumentation](/l/de/developers/extend/capabilities/apis) |
|
||||
| **REST** | Einfache CRUD-Operationen, vertraute REST-Muster | [API-Dokumentation](/l/de/developers/extend/capabilities/apis) |
|
||||
|
||||
Beide APIs unterstützen:
|
||||
|
||||
@@ -173,4 +173,4 @@ Kontaktieren Sie uns unter [contact@twenty.com](mailto:contact@twenty.com) oder
|
||||
|
||||
Für vollständige Implementierungsdetails, Codebeispiele und Schema-Referenz:
|
||||
|
||||
* [API-Dokumentation](/l/de/developers/extend/api)
|
||||
* [API-Dokumentation](/l/de/developers/extend/capabilities/apis)
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@ Open-Source ist das Fundament unseres Ansatzes, das sicherstellt, dass Twenty si
|
||||
* **Dashboards:** Verfolgen Sie die Leistung mit benutzerdefinierten Berichten und Visualisierungen. [Dashboards anzeigen](/l/de/user-guide/dashboards/overview).
|
||||
* **Berechtigungen & Zugriff:** Steuern Sie mithilfe rollenbasierter Berechtigungen, wer Ihre Daten anzeigen, bearbeiten und verwalten kann. [Zugriff konfigurieren](/l/de/user-guide/permissions-access/overview).
|
||||
* **Notizen & Aufgaben:** Erstellen Sie Notizen und Aufgaben, die mit Ihren Datensätzen verknüpft sind, für eine bessere Zusammenarbeit.
|
||||
* **API & Webhooks:** Verbinden Sie sich mit anderen Apps und erstellen Sie benutzerdefinierte Integrationen. [Integration starten](/l/de/developers/extend/api).
|
||||
* **API & Webhooks:** Verbinden Sie sich mit anderen Apps und erstellen Sie benutzerdefinierte Integrationen. [Integration starten](/l/de/developers/extend/capabilities/apis).
|
||||
|
||||
## Jetzt beitreten
|
||||
|
||||
|
||||
+1
-1
@@ -95,7 +95,7 @@ Erstellen Sie die Zielfelder in **Settings → Data Model → Opportunities**:
|
||||
* Unternehmensgröße: `{{searchRecords[0].employees}}`
|
||||
|
||||
<Note>
|
||||
**Einschränkung bei Aufgaben und Notizen**: Beziehungen bei Aufgaben und Notizen sind fest als Viele-zu-Viele implementiert und stehen in Workflow-Auslösern oder -Aktionen noch nicht zur Verfügung. Um auf diese Beziehungen zuzugreifen, verwenden Sie stattdessen die [API](/l/de/developers/extend/api).
|
||||
**Einschränkung bei Aufgaben und Notizen**: Beziehungen bei Aufgaben und Notizen sind fest als Viele-zu-Viele implementiert und stehen in Workflow-Auslösern oder -Aktionen noch nicht zur Verfügung. Um auf diese Beziehungen zuzugreifen, verwenden Sie stattdessen die [API](/l/de/developers/extend/capabilities/apis).
|
||||
</Note>
|
||||
|
||||
## Bidirektionale Synchronisierung
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
---
|
||||
title: Ampliar
|
||||
description: Amplía la funcionalidad de Twenty con APIs, webhooks y aplicaciones personalizadas.
|
||||
redirect: /developers/introduction
|
||||
---
|
||||
|
||||
<Frame>
|
||||
@@ -21,15 +20,15 @@ Twenty está diseñado para ser extensible. Usa nuestras APIs, webhooks y el fra
|
||||
## Primeros pasos
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="APIs" icon="código" href="/l/es/developers/api">
|
||||
<Card title="APIs" icon="código" href="/l/es/developers/extend/capabilities/apis">
|
||||
Conéctate a Twenty de forma programática
|
||||
</Card>
|
||||
|
||||
<Card title="Webhooks" icon="bell" href="/l/es/developers/webhooks">
|
||||
<Card title="Webhooks" icon="bell" href="/l/es/developers/extend/capabilities/webhooks">
|
||||
Recibe notificaciones de eventos en tiempo real
|
||||
</Card>
|
||||
|
||||
<Card title="Aplicaciones" icon="puzzle-piece" href="/l/es/developers/apps/apps">
|
||||
<Card title="Aplicaciones" icon="puzzle-piece" href="/l/es/developers/extend/capabilities/apps">
|
||||
Crea personalizaciones como código (Alpha)
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
@@ -5,28 +5,18 @@ description: Bienvenido a la documentación para desarrolladores de Twenty, tus
|
||||
|
||||
import { CardTitle } from "/snippets/card-title.mdx"
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card href="/l/es/developers/api" icon="code">
|
||||
<CardTitle>API</CardTitle>
|
||||
Consulta y modifica los datos de tu CRM con REST o GraphQL.
|
||||
<CardGroup cols={3}>
|
||||
<Card href="/l/es/developers/extend/extend" img="/images/user-guide/integrations/plug.png">
|
||||
<CardTitle>Ampliar</CardTitle>
|
||||
Crea integraciones con APIs, webhooks y aplicaciones personalizadas.
|
||||
</Card>
|
||||
|
||||
<Card href="/l/es/developers/webhooks" icon="bell">
|
||||
<CardTitle>Webhooks</CardTitle>
|
||||
Recibe notificaciones en tiempo real cuando ocurran eventos.
|
||||
</Card>
|
||||
|
||||
<Card href="/l/es/developers/apps/apps" icon="puzzle-piece">
|
||||
<CardTitle>Apps</CardTitle>
|
||||
Crea aplicaciones personalizadas que amplíen las capacidades de Twenty.
|
||||
</Card>
|
||||
|
||||
<Card href="/l/es/developers/self-host/self-host" icon="desktop">
|
||||
<Card href="/l/es/developers/self-host/self-host" img="/images/user-guide/what-is-twenty/20.png">
|
||||
<CardTitle>Autoalojar</CardTitle>
|
||||
Despliega y administra Twenty en tu propia infraestructura.
|
||||
</Card>
|
||||
|
||||
<Card href="/l/es/developers/contribute/contribute" icon="github">
|
||||
<Card href="/l/es/developers/contribute/contribute" img="/images/user-guide/github/github-header.png">
|
||||
<CardTitle>Contribuir</CardTitle>
|
||||
Únete a nuestra comunidad de código abierto y contribuye a Twenty.
|
||||
</Card>
|
||||
|
||||
@@ -24,7 +24,7 @@ Exporta los datos de tu espacio de trabajo a CSV para copias de seguridad, infor
|
||||
* Solo se exportan las **columnas visibles**
|
||||
* Solo se exportan los **registros filtrados** (según tu vista actual)
|
||||
|
||||
<Note>Para exportaciones más grandes (más de 20.000 registros), usa filtros para exportar por lotes o usa la [API](/l/es/developers/api).</Note>
|
||||
<Note>Para exportaciones más grandes (más de 20.000 registros), usa filtros para exportar por lotes o usa la [API](/l/es/developers/extend/capabilities/apis).</Note>
|
||||
|
||||
### Permisos
|
||||
|
||||
@@ -148,7 +148,7 @@ La API no tiene límite de registros:
|
||||
2. Usa la API de GraphQL para consultar registros
|
||||
3. Procesa los resultados en tu aplicación
|
||||
|
||||
Consulta: [Documentación de la API](/l/es/developers/api)
|
||||
Consulta: [Documentación de la API](/l/es/developers/extend/capabilities/apis)
|
||||
|
||||
## Consejos y mejores prácticas
|
||||
|
||||
@@ -206,4 +206,4 @@ Los archivos exportados pueden contener datos sensibles:
|
||||
|
||||
* [Cómo actualizar registros existentes](/l/es/user-guide/data-migration/how-tos/update-existing-records-via-import) — edita y vuelve a importar tu exportación
|
||||
* [Cómo importar datos mediante la API](/l/es/user-guide/data-migration/how-tos/import-data-via-api) — para conjuntos de datos grandes
|
||||
* [Documentación de la API](/l/es/developers/api) — crea flujos de trabajo de exportación personalizados
|
||||
* [Documentación de la API](/l/es/developers/extend/capabilities/apis) — crea flujos de trabajo de exportación personalizados
|
||||
|
||||
@@ -59,8 +59,8 @@ Twenty admite dos tipos de API:
|
||||
|
||||
| API | Ideal para | Documentación |
|
||||
| ----------- | --------------------------------------------------------------------------- | --------------------------------------------------------------- |
|
||||
| **GraphQL** | Consultas flexibles, obtención de datos relacionados, operaciones complejas | [Documentación de la API](/l/es/developers/api) |
|
||||
| **REST** | Operaciones CRUD simples, patrones REST familiares | [Documentación de la API](/l/es/developers/api) |
|
||||
| **GraphQL** | Consultas flexibles, obtención de datos relacionados, operaciones complejas | [Documentación de la API](/l/es/developers/extend/capabilities/apis) |
|
||||
| **REST** | Operaciones CRUD simples, patrones REST familiares | [Documentación de la API](/l/es/developers/extend/capabilities/apis) |
|
||||
|
||||
Ambas APIs admiten:
|
||||
|
||||
@@ -173,4 +173,4 @@ Contáctanos en [contact@twenty.com](mailto:contact@twenty.com) o explora nuestr
|
||||
|
||||
Para conocer todos los detalles de implementación, ejemplos de código y referencia de esquemas:
|
||||
|
||||
* [Documentación de la API](/l/es/developers/api)
|
||||
* [Documentación de la API](/l/es/developers/extend/capabilities/apis)
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@ El código abierto es la base de nuestro enfoque, asegurando que Twenty evolucio
|
||||
* **Tableros:** Rastree el rendimiento con informes y visualizaciones personalizadas. [Ver tableros](/l/es/user-guide/dashboards/overview).
|
||||
* **Permisos y acceso:** Controle quién puede ver, editar y administrar sus datos con permisos basados en roles. [Configurar el acceso](/l/es/user-guide/permissions-access/overview).
|
||||
* **Notas y tareas:** Cree notas y tareas vinculadas a sus registros para una mejor colaboración.
|
||||
* **API y Webhooks:** Conéctese con otras aplicaciones y cree integraciones personalizadas. [Comienza a integrar](/l/es/developers/api).
|
||||
* **API y Webhooks:** Conéctese con otras aplicaciones y cree integraciones personalizadas. [Comienza a integrar](/l/es/developers/extend/capabilities/apis).
|
||||
|
||||
## Únete ahora
|
||||
|
||||
|
||||
+1
-1
@@ -95,7 +95,7 @@ Crea los campos de destino en **Configuración → Modelo de datos → Oportunid
|
||||
* Tamaño de la empresa: `{{searchRecords[0].employees}}`
|
||||
|
||||
<Note>
|
||||
**Limitación de Tareas y Notas**: Las relaciones en Tareas y Notas están codificadas como de muchos a muchos y aún no están disponibles en los desencadenantes o acciones de flujos de trabajo. Para acceder a estas relaciones, usa la [API](/l/es/developers/api).
|
||||
**Limitación de Tareas y Notas**: Las relaciones en Tareas y Notas están codificadas como de muchos a muchos y aún no están disponibles en los desencadenantes o acciones de flujos de trabajo. Para acceder a estas relaciones, usa la [API](/l/es/developers/extend/capabilities/apis).
|
||||
</Note>
|
||||
|
||||
## Sincronización bidireccional
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
---
|
||||
title: Étendre
|
||||
description: Étendez les fonctionnalités de Twenty avec des API, des webhooks et des applications personnalisées.
|
||||
redirect: /developers/introduction
|
||||
---
|
||||
|
||||
<Frame>
|
||||
@@ -21,15 +20,15 @@ Twenty est conçu pour être extensible. Utilisez nos API, nos webhooks et notre
|
||||
## Prise en main
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="API" icon="code" href="/l/fr/developers/api">
|
||||
<Card title="API" icon="code" href="/l/fr/developers/extend/capabilities/apis">
|
||||
Connectez-vous à Twenty par programmation
|
||||
</Card>
|
||||
|
||||
<Card title="Webhooks" icon="bell" href="/l/fr/developers/webhooks">
|
||||
<Card title="Webhooks" icon="bell" href="/l/fr/developers/extend/capabilities/webhooks">
|
||||
Recevez des notifications d'événements en temps réel
|
||||
</Card>
|
||||
|
||||
<Card title="Applications" icon="puzzle-piece" href="/l/fr/developers/apps/apps">
|
||||
<Card title="Applications" icon="puzzle-piece" href="/l/fr/developers/extend/capabilities/apps">
|
||||
Créez des personnalisations sous forme de code (Alpha)
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
@@ -5,28 +5,18 @@ description: Bienvenue dans la documentation pour développeurs de Twenty, vos r
|
||||
|
||||
import { CardTitle } from "/snippets/card-title.mdx"
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card href="/l/fr/developers/api" icon="code">
|
||||
<CardTitle>API</CardTitle>
|
||||
Interrogez et modifiez vos données CRM avec REST ou GraphQL.
|
||||
<CardGroup cols={3}>
|
||||
<Card href="/l/fr/developers/extend/extend" img="/images/user-guide/integrations/plug.png">
|
||||
<CardTitle>Étendre</CardTitle>
|
||||
Créez des intégrations avec des API, des webhooks et des applications personnalisées.
|
||||
</Card>
|
||||
|
||||
<Card href="/l/fr/developers/webhooks" icon="bell">
|
||||
<CardTitle>Webhooks</CardTitle>
|
||||
Recevez des notifications en temps réel lors d'événements.
|
||||
</Card>
|
||||
|
||||
<Card href="/l/fr/developers/apps/apps" icon="puzzle-piece">
|
||||
<CardTitle>Apps</CardTitle>
|
||||
Créez des applications personnalisées qui étendent les capacités de Twenty.
|
||||
</Card>
|
||||
|
||||
<Card href="/l/fr/developers/self-host/self-host" icon="desktop">
|
||||
<Card href="/l/fr/developers/self-host/self-host" img="/images/user-guide/what-is-twenty/20.png">
|
||||
<CardTitle>Auto-héberger</CardTitle>
|
||||
Déployez et gérez Twenty sur votre propre infrastructure.
|
||||
</Card>
|
||||
|
||||
<Card href="/l/fr/developers/contribute/contribute" icon="github">
|
||||
<Card href="/l/fr/developers/contribute/contribute" img="/images/user-guide/github/github-header.png">
|
||||
<CardTitle>Contribuer</CardTitle>
|
||||
Rejoignez notre communauté open source et contribuez à Twenty.
|
||||
</Card>
|
||||
|
||||
@@ -24,7 +24,7 @@ Exportez les données de votre espace de travail en CSV pour des sauvegardes, de
|
||||
* Seules les **colonnes visibles** sont exportées
|
||||
* Seuls les **enregistrements filtrés** sont exportés (selon votre vue actuelle)
|
||||
|
||||
<Note>Pour des exports plus volumineux (plus de 20 000 enregistrements), utilisez des filtres pour exporter par lots ou utilisez l'[API](/l/fr/developers/api).</Note>
|
||||
<Note>Pour des exports plus volumineux (plus de 20 000 enregistrements), utilisez des filtres pour exporter par lots ou utilisez l'[API](/l/fr/developers/extend/capabilities/apis).</Note>
|
||||
|
||||
### Autorisations
|
||||
|
||||
@@ -148,7 +148,7 @@ L'API n'a pas de limite d'enregistrements :
|
||||
2. Utilisez l'API GraphQL pour interroger les enregistrements
|
||||
3. Traitez les résultats dans votre application
|
||||
|
||||
Voir : [Documentation de l'API](/l/fr/developers/api)
|
||||
Voir : [Documentation de l'API](/l/fr/developers/extend/capabilities/apis)
|
||||
|
||||
## Conseils et bonnes pratiques
|
||||
|
||||
@@ -206,4 +206,4 @@ Les fichiers exportés peuvent contenir des données sensibles :
|
||||
|
||||
* [Comment mettre à jour des enregistrements existants](/l/fr/user-guide/data-migration/how-tos/update-existing-records-via-import) — modifiez et réimportez votre export
|
||||
* [Comment importer des données via l'API](/l/fr/user-guide/data-migration/how-tos/import-data-via-api) — pour de grands jeux de données
|
||||
* [Documentation de l'API](/l/fr/developers/api) — créez des flux de travail d'exportation personnalisés
|
||||
* [Documentation de l'API](/l/fr/developers/extend/capabilities/apis) — créez des flux de travail d'exportation personnalisés
|
||||
|
||||
@@ -59,8 +59,8 @@ Twenty prend en charge deux types d'API :
|
||||
|
||||
| API | Idéal pour | Documentation |
|
||||
| ----------- | ----------------------------------------------------------------------- | -------------------------------------------------------------- |
|
||||
| **GraphQL** | Requêtes flexibles, récupération de données liées, opérations complexes | [Documentation de l'API](/l/fr/developers/api) |
|
||||
| **REST** | Opérations CRUD simples, modèles REST familiers | [Documentation de l'API](/l/fr/developers/api) |
|
||||
| **GraphQL** | Requêtes flexibles, récupération de données liées, opérations complexes | [Documentation de l'API](/l/fr/developers/extend/capabilities/apis) |
|
||||
| **REST** | Opérations CRUD simples, modèles REST familiers | [Documentation de l'API](/l/fr/developers/extend/capabilities/apis) |
|
||||
|
||||
Les deux API prennent en charge :
|
||||
|
||||
@@ -173,4 +173,4 @@ Contactez-nous à [contact@twenty.com](mailto:contact@twenty.com) ou découvrez
|
||||
|
||||
Pour les détails complets de mise en œuvre, des exemples de code et la référence du schéma :
|
||||
|
||||
* [Documentation de l'API](/l/fr/developers/api)
|
||||
* [Documentation de l'API](/l/fr/developers/extend/capabilities/apis)
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@ L'open-source est la pierre angulaire de notre approche, garantissant que Twenty
|
||||
* **Tableaux de bord :** Suivez les performances grâce à des rapports et des visualisations personnalisés. [Voir les tableaux de bord](/l/fr/user-guide/dashboards/overview).
|
||||
* **Autorisations et accès :** Contrôlez qui peut voir, modifier et gérer vos données grâce à des autorisations basées sur les rôles. [Configurer l'accès](/l/fr/user-guide/permissions-access/overview).
|
||||
* **Notes et tâches :** Créez des notes et des tâches liées à vos enregistrements pour une meilleure collaboration.
|
||||
* **API & Webhooks :** Connectez-vous à d'autres applications et créez des intégrations personnalisées. [Commencez l'intégration](/l/fr/developers/api).
|
||||
* **API & Webhooks :** Connectez-vous à d'autres applications et créez des intégrations personnalisées. [Commencez l'intégration](/l/fr/developers/extend/capabilities/apis).
|
||||
|
||||
## Rejoignez maintenant
|
||||
|
||||
|
||||
+1
-1
@@ -95,7 +95,7 @@ Créez les champs de destination dans **Paramètres → Modèle de données →
|
||||
* Taille de l'entreprise : `{{searchRecords[0].employees}}`
|
||||
|
||||
<Note>
|
||||
**Limitation concernant les tâches et les notes** : Les relations sur les tâches et les notes sont codées en dur en plusieurs-à-plusieurs et ne sont pas encore disponibles dans les déclencheurs ou actions de workflows. Pour accéder à ces relations, utilisez plutôt l'[API](/l/fr/developers/api).
|
||||
**Limitation concernant les tâches et les notes** : Les relations sur les tâches et les notes sont codées en dur en plusieurs-à-plusieurs et ne sont pas encore disponibles dans les déclencheurs ou actions de workflows. Pour accéder à ces relations, utilisez plutôt l'[API](/l/fr/developers/extend/capabilities/apis).
|
||||
</Note>
|
||||
|
||||
## Synchronisation bidirectionnelle
|
||||
|
||||
@@ -1,147 +0,0 @@
|
||||
---
|
||||
title: API
|
||||
description: Interroga e modifica i dati del tuo CRM in modo programmatico usando REST o GraphQL.
|
||||
---
|
||||
|
||||
import { VimeoEmbed } from '/snippets/vimeo-embed.mdx';
|
||||
|
||||
Twenty è stato progettato per essere adatto agli sviluppatori, offrendo potenti API che si adattano al tuo modello di dati personalizzato. Forniamo quattro tipi distinti di API per soddisfare diverse esigenze di integrazione.
|
||||
|
||||
## Approccio incentrato sullo sviluppatore
|
||||
|
||||
Twenty genera API specifiche per il tuo modello di dati:
|
||||
|
||||
* **Nessun ID lungo richiesto**: Utilizza direttamente i nomi degli oggetti e dei campi negli endpoint
|
||||
* **Oggetti standard e personalizzati trattati allo stesso modo**: I tuoi oggetti personalizzati ricevono lo stesso trattamento API di quelli predefiniti
|
||||
* **Endpoint dedicati**: Ogni oggetto e campo ottiene il proprio endpoint API
|
||||
* **Documentazione personalizzata**: Generata specificamente per il modello di dati del tuo workspace
|
||||
|
||||
<Note>
|
||||
La documentazione personalizzata delle tue API è disponibile in **Impostazioni → API & Webhooks** dopo aver creato una chiave API. Poiché Twenty genera API che corrispondono al tuo modello di dati personalizzato, la documentazione è unica per il tuo workspace.
|
||||
</Note>
|
||||
|
||||
## I due tipi di API
|
||||
|
||||
### Core API
|
||||
|
||||
Accessibile su `/rest/` o `/graphql/`
|
||||
|
||||
Lavora con i tuoi **record** reali (i dati):
|
||||
|
||||
* Crea, leggi, aggiorna, elimina Persone, Aziende, Opportunità, ecc.
|
||||
* Interroga e filtra i dati
|
||||
* Gestisci le relazioni tra i record
|
||||
|
||||
### Metadata API
|
||||
|
||||
Accessibile su `/rest/metadata/` o `/metadata/`
|
||||
|
||||
Gestisci il tuo **workspace e il modello di dati**:
|
||||
|
||||
* Crea, modifica o elimina oggetti e campi
|
||||
* Configura le impostazioni del workspace
|
||||
* Definisci le relazioni tra oggetti
|
||||
|
||||
## REST vs GraphQL
|
||||
|
||||
Sia le API Core che le API Metadata sono disponibili nei formati REST e GraphQL:
|
||||
|
||||
| Formato | Operazioni disponibili |
|
||||
| ----------- | ------------------------------------------------------------------------------------- |
|
||||
| **REST** | CRUD, operazioni batch, upsert |
|
||||
| **GraphQL** | Stesse funzionalità + **upsert in batch**, query sulle relazioni in un'unica chiamata |
|
||||
|
||||
Scegli in base alle tue esigenze — entrambi i formati accedono agli stessi dati.
|
||||
|
||||
## Endpoint API
|
||||
|
||||
| Ambiente | URL di base |
|
||||
| ----------------- | ------------------------- |
|
||||
| **Cloud** | `https://api.twenty.com/` |
|
||||
| **Auto-ospitato** | `https://{your-domain}/` |
|
||||
|
||||
## Autenticazione
|
||||
|
||||
Ogni richiesta API richiede una chiave API nell'intestazione:
|
||||
|
||||
```
|
||||
Authorization: Bearer YOUR_API_KEY
|
||||
```
|
||||
|
||||
### Crea una chiave API
|
||||
|
||||
1. Vai a **Impostazioni → APIs & Webhooks**
|
||||
2. Fai clic su **+ Crea chiave**
|
||||
3. Configura:
|
||||
* **Nome**: Nome descrittivo per la chiave
|
||||
* **Data di scadenza**: Quando la chiave scade
|
||||
4. Fai clic su **Salva**
|
||||
5. **Copia subito** — la chiave viene mostrata una sola volta
|
||||
|
||||
<VimeoEmbed videoId="928786722" title="Creazione della chiave API" />
|
||||
|
||||
<Warning>
|
||||
La tua chiave API concede l'accesso a dati sensibili. Non condividerla con servizi non affidabili. Se compromessa, disabilitala immediatamente e generane una nuova.
|
||||
</Warning>
|
||||
|
||||
### Assegna un ruolo a una chiave API
|
||||
|
||||
Per una maggiore sicurezza, assegna un ruolo specifico per limitare l'accesso:
|
||||
|
||||
1. Vai a **Impostazioni → Ruoli**
|
||||
2. Fai clic sul ruolo da assegnare
|
||||
3. Apri la scheda **Assegnazione**
|
||||
4. In **Chiavi API**, fai clic su **+ Assegna alla chiave API**
|
||||
5. Seleziona la chiave API
|
||||
|
||||
La chiave erediterà le autorizzazioni di quel ruolo. Vedi [Autorizzazioni](/l/it/user-guide/permissions-access/capabilities/permissions) per i dettagli.
|
||||
|
||||
### Gestisci chiavi API
|
||||
|
||||
**Rigenera**: Impostazioni → APIs & Webhooks → Fai clic sulla chiave → **Rigenera**
|
||||
|
||||
**Elimina**: Impostazioni → APIs & Webhooks → Fai clic sulla chiave → **Elimina**
|
||||
|
||||
## Playground API
|
||||
|
||||
Testa le tue API direttamente nel browser con il nostro playground integrato — disponibile sia per **REST** sia per **GraphQL**.
|
||||
|
||||
### Accedi al Playground
|
||||
|
||||
1. Vai a **Impostazioni → APIs & Webhooks**
|
||||
2. Crea una chiave API (obbligatorio)
|
||||
3. Fai clic su **REST API** o **GraphQL API** per aprire il playground
|
||||
|
||||
### Cosa ottieni
|
||||
|
||||
* **Documentazione interattiva**: Generata per il tuo specifico modello di dati
|
||||
* **Test in tempo reale**: Esegui chiamate API reali sul tuo workspace
|
||||
* **Esploratore dello schema**: Sfoglia gli oggetti, i campi e le relazioni disponibili
|
||||
* **Generatore di richieste**: Crea query con completamento automatico
|
||||
|
||||
Il playground riflette i tuoi oggetti e campi personalizzati, quindi la documentazione è sempre accurata per il tuo workspace.
|
||||
|
||||
## Operazioni Batch
|
||||
|
||||
Sia REST che GraphQL supportano operazioni batch:
|
||||
|
||||
* **Dimensione batch**: Fino a 60 record per richiesta
|
||||
* **Operazioni**: Creare, aggiornare, eliminare più record
|
||||
|
||||
**Funzionalità esclusive di GraphQL:**
|
||||
|
||||
* **Upsert in batch**: Crea o aggiorna in un'unica chiamata
|
||||
* Usa nomi oggetto al plurale (ad es. `CreateCompanies` invece di `CreateCompany`)
|
||||
|
||||
## Limiti di frequenza delle API
|
||||
|
||||
Le richieste API sono limitate per garantire la stabilità della piattaforma:
|
||||
|
||||
| Limite | Valore |
|
||||
| -------------------- | ---------------------- |
|
||||
| **Richieste** | 100 chiamate al minuto |
|
||||
| **Dimensione batch** | 60 record per chiamata |
|
||||
|
||||
<Tip>
|
||||
Usa le operazioni batch per massimizzare il throughput — elabora fino a 60 record in una singola chiamata API invece di effettuare richieste individuali.
|
||||
</Tip>
|
||||
@@ -1,689 +0,0 @@
|
||||
---
|
||||
title: Creazione di app
|
||||
description: Definisci oggetti, funzioni logiche, componenti front-end e molto altro con il Twenty SDK.
|
||||
---
|
||||
|
||||
<Warning>
|
||||
Le app sono attualmente in fase alfa. La funzionalità è funzionante ma ancora in evoluzione.
|
||||
</Warning>
|
||||
|
||||
## Usa le risorse dell'SDK (tipi e configurazione)
|
||||
|
||||
Il pacchetto twenty-sdk fornisce blocchi tipizzati e funzioni helper da usare nella tua app. Di seguito gli elementi principali con cui interagirai più spesso.
|
||||
|
||||
### Funzioni helper
|
||||
|
||||
L'SDK fornisce funzioni helper per definire le entità della tua app. Come descritto in [Rilevamento delle entità](/l/it/developers/extend/apps/getting-started#entity-detection), devi usare `export default define<Entity>({...})` affinché le tue entità vengano rilevate:
|
||||
|
||||
| Funzione | Scopo |
|
||||
| -------------------------------- | ----------------------------------------------------------------------- |
|
||||
| `defineApplication` | Configura i metadati dell'applicazione (obbligatorio, uno per app) |
|
||||
| `defineObject` | Definisci oggetti personalizzati con campi |
|
||||
| `defineLogicFunction` | Definisci funzioni logiche con handler |
|
||||
| `definePreInstallLogicFunction` | Definisci una funzione logica di pre-installazione (una per app) |
|
||||
| `definePostInstallLogicFunction` | Definisci una funzione logica di post-installazione (una per app) |
|
||||
| `defineFrontComponent` | Definisci componenti front-end per un'interfaccia utente personalizzata |
|
||||
| `defineRole` | Configura i permessi dei ruoli e l'accesso agli oggetti |
|
||||
| `defineField` | Estendi gli oggetti esistenti con campi aggiuntivi |
|
||||
| `defineView` | Definisci viste salvate per gli oggetti |
|
||||
| `defineNavigationMenuItem` | Definisci i link di navigazione della barra laterale |
|
||||
| `defineSkill` | Definisci le competenze dell'agente IA |
|
||||
|
||||
Queste funzioni convalidano la configurazione in fase di build e offrono il completamento automatico nell'IDE e la sicurezza dei tipi.
|
||||
|
||||
### Definizione degli oggetti
|
||||
|
||||
Gli oggetti personalizzati descrivono sia lo schema sia il comportamento per i record nel tuo spazio di lavoro. Usa `defineObject()` per definire oggetti con convalida integrata:
|
||||
|
||||
```typescript
|
||||
// src/app/postCard.object.ts
|
||||
import { defineObject, FieldType } from 'twenty-sdk';
|
||||
|
||||
enum PostCardStatus {
|
||||
DRAFT = 'DRAFT',
|
||||
SENT = 'SENT',
|
||||
DELIVERED = 'DELIVERED',
|
||||
RETURNED = 'RETURNED',
|
||||
}
|
||||
|
||||
export default defineObject({
|
||||
universalIdentifier: '54b589ca-eeed-4950-a176-358418b85c05',
|
||||
nameSingular: 'postCard',
|
||||
namePlural: 'postCards',
|
||||
labelSingular: 'Post Card',
|
||||
labelPlural: 'Post Cards',
|
||||
description: 'A post card object',
|
||||
icon: 'IconMail',
|
||||
fields: [
|
||||
{
|
||||
universalIdentifier: '58a0a314-d7ea-4865-9850-7fb84e72f30b',
|
||||
name: 'content',
|
||||
type: FieldType.TEXT,
|
||||
label: 'Content',
|
||||
description: "Postcard's content",
|
||||
icon: 'IconAbc',
|
||||
},
|
||||
{
|
||||
universalIdentifier: 'c6aa31f3-da76-4ac6-889f-475e226009ac',
|
||||
name: 'recipientName',
|
||||
type: FieldType.FULL_NAME,
|
||||
label: 'Recipient name',
|
||||
icon: 'IconUser',
|
||||
},
|
||||
{
|
||||
universalIdentifier: '95045777-a0ad-49ec-98f9-22f9fc0c8266',
|
||||
name: 'recipientAddress',
|
||||
type: FieldType.ADDRESS,
|
||||
label: 'Recipient address',
|
||||
icon: 'IconHome',
|
||||
},
|
||||
{
|
||||
universalIdentifier: '87b675b8-dd8c-4448-b4ca-20e5a2234a1e',
|
||||
name: 'status',
|
||||
type: FieldType.SELECT,
|
||||
label: 'Status',
|
||||
icon: 'IconSend',
|
||||
defaultValue: `'${PostCardStatus.DRAFT}'`,
|
||||
options: [
|
||||
{ value: PostCardStatus.DRAFT, label: 'Draft', position: 0, color: 'gray' },
|
||||
{ value: PostCardStatus.SENT, label: 'Sent', position: 1, color: 'orange' },
|
||||
{ value: PostCardStatus.DELIVERED, label: 'Delivered', position: 2, color: 'green' },
|
||||
{ value: PostCardStatus.RETURNED, label: 'Returned', position: 3, color: 'orange' },
|
||||
],
|
||||
},
|
||||
{
|
||||
universalIdentifier: 'e06abe72-5b44-4e7f-93be-afc185a3c433',
|
||||
name: 'deliveredAt',
|
||||
type: FieldType.DATE_TIME,
|
||||
label: 'Delivered at',
|
||||
icon: 'IconCheck',
|
||||
isNullable: true,
|
||||
defaultValue: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Punti chiave:
|
||||
|
||||
* Usa `defineObject()` per una convalida integrata e un migliore supporto IDE.
|
||||
* Il `universalIdentifier` deve essere univoco e stabile tra i deployment.
|
||||
* Ogni campo richiede un `name`, `type`, `label` e il proprio `universalIdentifier` stabile.
|
||||
* L'array `fields` è facoltativo: puoi definire oggetti senza campi personalizzati.
|
||||
* Puoi generare nuovi oggetti con `yarn twenty entity:add`, che ti guida nella denominazione, nei campi e nelle relazioni.
|
||||
|
||||
<Note>
|
||||
**I campi base vengono creati automaticamente.** Quando definisci un oggetto personalizzato, Twenty aggiunge automaticamente i campi standard
|
||||
come `id`, `name`, `createdAt`, `updatedAt`, `createdBy`, `updatedBy` e `deletedAt`.
|
||||
Non è necessario definirli nel tuo array `fields` — aggiungi solo i tuoi campi personalizzati.
|
||||
Puoi sovrascrivere i campi predefiniti definendo un campo con lo stesso nome nel tuo array `fields`,
|
||||
ma non è consigliato.
|
||||
</Note>
|
||||
|
||||
### Configurazione dell'applicazione (application-config.ts)
|
||||
|
||||
Ogni app ha un singolo file `application-config.ts` che descrive:
|
||||
|
||||
* **Identità dell'app**: identificatori, nome visualizzato e descrizione.
|
||||
* **Come vengono eseguite le sue funzioni**: quale ruolo usano per i permessi.
|
||||
* **Variabili (opzionali)**: coppie chiave–valore esposte alle funzioni come variabili d'ambiente.
|
||||
* **(Opzionale) funzione di pre-installazione**: una funzione logica che viene eseguita prima che l'app venga installata.
|
||||
* **(Opzionale) funzione post-installazione**: una funzione logica che viene eseguita dopo l'installazione dell'app.
|
||||
|
||||
Usa `defineApplication()` per definire la configurazione della tua applicazione:
|
||||
|
||||
```typescript
|
||||
// src/application-config.ts
|
||||
import { defineApplication } from 'twenty-sdk';
|
||||
import { DEFAULT_ROLE_UNIVERSAL_IDENTIFIER } from 'src/roles/default-role';
|
||||
|
||||
export default defineApplication({
|
||||
universalIdentifier: '4ec0391d-18d5-411c-b2f3-266ddc1c3ef7',
|
||||
displayName: 'My Twenty App',
|
||||
description: 'My first Twenty app',
|
||||
icon: 'IconWorld',
|
||||
applicationVariables: {
|
||||
DEFAULT_RECIPIENT_NAME: {
|
||||
universalIdentifier: '19e94e59-d4fe-4251-8981-b96d0a9f74de',
|
||||
description: 'Default recipient name for postcards',
|
||||
value: 'Jane Doe',
|
||||
isSecret: false,
|
||||
},
|
||||
},
|
||||
defaultRoleUniversalIdentifier: DEFAULT_ROLE_UNIVERSAL_IDENTIFIER,
|
||||
});
|
||||
```
|
||||
|
||||
Note:
|
||||
|
||||
* I campi `universalIdentifier` sono ID deterministici sotto il tuo controllo; generali una volta e mantienili stabili tra le sincronizzazioni.
|
||||
* `applicationVariables` diventano variabili d'ambiente per le tue funzioni (ad esempio, `DEFAULT_RECIPIENT_NAME` è disponibile come `process.env.DEFAULT_RECIPIENT_NAME`).
|
||||
* `defaultRoleUniversalIdentifier` deve corrispondere al file del ruolo (vedi sotto).
|
||||
* Le funzioni di pre-installazione e post-installazione vengono rilevate automaticamente durante la build del manifesto. Vedi [Funzioni di pre-installazione](#pre-install-functions) e [Funzioni di post-installazione](#post-install-functions).
|
||||
|
||||
#### Ruoli e permessi
|
||||
|
||||
Le applicazioni possono definire ruoli che incapsulano i permessi sugli oggetti e sulle azioni del tuo spazio di lavoro. Il campo `defaultRoleUniversalIdentifier` in `application-config.ts` indica il ruolo predefinito utilizzato dalle funzioni logiche della tua app.
|
||||
|
||||
* La chiave API di runtime iniettata come `TWENTY_API_KEY` è derivata da questo ruolo funzione predefinito.
|
||||
* Il client tipizzato sarà limitato ai permessi concessi a quel ruolo.
|
||||
* Segui il principio del privilegio minimo: crea un ruolo dedicato con solo i permessi necessari alle tue funzioni, quindi fai riferimento al suo identificatore universale.
|
||||
|
||||
##### Ruolo funzione predefinito (*.role.ts)
|
||||
|
||||
Quando generi una nuova app con lo scaffolder, la CLI crea anche un file di ruolo predefinito. Usa `defineRole()` per definire ruoli con convalida integrata:
|
||||
|
||||
```typescript
|
||||
// src/roles/default-role.ts
|
||||
import { defineRole, PermissionFlag } from 'twenty-sdk';
|
||||
|
||||
export const DEFAULT_ROLE_UNIVERSAL_IDENTIFIER =
|
||||
'b648f87b-1d26-4961-b974-0908fd991061';
|
||||
|
||||
export default defineRole({
|
||||
universalIdentifier: DEFAULT_ROLE_UNIVERSAL_IDENTIFIER,
|
||||
label: 'Default function role',
|
||||
description: 'Default role for function Twenty client',
|
||||
canReadAllObjectRecords: false,
|
||||
canUpdateAllObjectRecords: false,
|
||||
canSoftDeleteAllObjectRecords: false,
|
||||
canDestroyAllObjectRecords: false,
|
||||
canUpdateAllSettings: false,
|
||||
canBeAssignedToAgents: false,
|
||||
canBeAssignedToUsers: false,
|
||||
canBeAssignedToApiKeys: false,
|
||||
objectPermissions: [
|
||||
{
|
||||
objectUniversalIdentifier: '9f9882af-170c-4879-b013-f9628b77c050',
|
||||
canReadObjectRecords: true,
|
||||
canUpdateObjectRecords: true,
|
||||
canSoftDeleteObjectRecords: false,
|
||||
canDestroyObjectRecords: false,
|
||||
},
|
||||
],
|
||||
fieldPermissions: [
|
||||
{
|
||||
objectUniversalIdentifier: '9f9882af-170c-4879-b013-f9628b77c050',
|
||||
fieldUniversalIdentifier: 'b2c37dc0-8ae7-470e-96cd-1476b47dfaff',
|
||||
canReadFieldValue: false,
|
||||
canUpdateFieldValue: false,
|
||||
},
|
||||
],
|
||||
permissionFlags: [PermissionFlag.APPLICATIONS],
|
||||
});
|
||||
```
|
||||
|
||||
L'`universalIdentifier` di questo ruolo viene quindi referenziato in `application-config.ts` come `defaultRoleUniversalIdentifier`. In altre parole:
|
||||
|
||||
* **\*.role.ts** definisce ciò che il ruolo funzione predefinito può fare.
|
||||
* **application-config.ts** punta a quel ruolo in modo che le tue funzioni ne ereditino i permessi.
|
||||
|
||||
Note:
|
||||
|
||||
* Parti dal ruolo generato dallo scaffolder, quindi restringilo progressivamente seguendo il principio del privilegio minimo.
|
||||
* Sostituisci `objectPermissions` e `fieldPermissions` con gli oggetti/campi di cui le tue funzioni hanno bisogno.
|
||||
* `permissionFlags` controllano l'accesso alle funzionalità a livello di piattaforma. Mantienili al minimo; aggiungi solo ciò che ti serve.
|
||||
* Vedi un esempio funzionante nell'app Hello World: [`packages/twenty-apps/hello-world/src/roles/function-role.ts`](https://github.com/twentyhq/twenty/blob/main/packages/twenty-apps/hello-world/src/roles/function-role.ts).
|
||||
|
||||
### Configurazione e punto di ingresso della funzione logica
|
||||
|
||||
Ogni file di funzione usa `defineLogicFunction()` per esportare una configurazione con un handler e trigger opzionali.
|
||||
|
||||
```typescript
|
||||
// src/app/createPostCard.logic-function.ts
|
||||
import { defineLogicFunction } from 'twenty-sdk';
|
||||
import type { DatabaseEventPayload, ObjectRecordCreateEvent, CronPayload, RoutePayload } from 'twenty-sdk';
|
||||
import { CoreApiClient, type Person } from 'twenty-sdk/generated';
|
||||
|
||||
const handler = async (params: RoutePayload) => {
|
||||
const client = new CoreApiClient();
|
||||
const name = 'name' in params.queryStringParameters
|
||||
? params.queryStringParameters.name ?? process.env.DEFAULT_RECIPIENT_NAME ?? 'Hello world'
|
||||
: 'Hello world';
|
||||
|
||||
const result = await client.mutation({
|
||||
createPostCard: {
|
||||
__args: { data: { name } },
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
});
|
||||
return result;
|
||||
};
|
||||
|
||||
export default defineLogicFunction({
|
||||
universalIdentifier: 'e56d363b-0bdc-4d8a-a393-6f0d1c75bdcf',
|
||||
name: 'create-new-post-card',
|
||||
timeoutSeconds: 2,
|
||||
handler,
|
||||
triggers: [
|
||||
// Public HTTP route trigger '/s/post-card/create'
|
||||
{
|
||||
universalIdentifier: 'c9f84c8d-b26d-40d1-95dd-4f834ae5a2c6',
|
||||
type: 'route',
|
||||
path: '/post-card/create',
|
||||
httpMethod: 'GET',
|
||||
isAuthRequired: false,
|
||||
},
|
||||
// Cron trigger (CRON pattern)
|
||||
// {
|
||||
// universalIdentifier: 'dd802808-0695-49e1-98c9-d5c9e2704ce2',
|
||||
// type: 'cron',
|
||||
// pattern: '0 0 1 1 *',
|
||||
// },
|
||||
// Database event trigger
|
||||
// {
|
||||
// universalIdentifier: '203f1df3-4a82-4d06-a001-b8cf22a31156',
|
||||
// type: 'databaseEvent',
|
||||
// eventName: 'person.updated',
|
||||
// updatedFields: ['name'],
|
||||
// },
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Tipi di trigger comuni:
|
||||
|
||||
* **route**: Espone la funzione su un percorso e metodo HTTP **sotto l'endpoint `/s/`**:
|
||||
|
||||
> es. `path: '/post-card/create',` -> chiamata su `<APP_URL>/s/post-card/create`
|
||||
|
||||
* **cron**: Esegue la tua funzione secondo una pianificazione utilizzando un'espressione CRON.
|
||||
* **databaseEvent**: Viene eseguito sugli eventi del ciclo di vita degli oggetti dello spazio di lavoro. Quando l'operazione dell'evento è `updated`, è possibile specificare campi specifici da monitorare nell'array `updatedFields`. Se lasciato non definito o vuoto, qualsiasi aggiornamento attiverà la funzione.
|
||||
|
||||
> es. `person.updated`
|
||||
|
||||
Note:
|
||||
|
||||
* L'array `triggers` è facoltativo. Le funzioni senza trigger possono essere utilizzate come funzioni di utilità richiamate da altre funzioni.
|
||||
* Puoi combinare più tipi di trigger in un'unica funzione.
|
||||
|
||||
### Funzioni di pre-installazione
|
||||
|
||||
Una funzione di pre-installazione è una funzione logica che viene eseguita automaticamente prima che la tua app venga installata in uno spazio di lavoro. È utile per attività di convalida, controlli dei prerequisiti o per preparare lo stato dello spazio di lavoro prima che proceda l'installazione principale.
|
||||
|
||||
Quando esegui lo scaffolding di una nuova app con `create-twenty-app`, viene generata una funzione di pre-installazione in `src/logic-functions/pre-install.ts`:
|
||||
|
||||
```typescript
|
||||
// src/logic-functions/pre-install.ts
|
||||
import { definePreInstallLogicFunction, type InstallLogicFunctionPayload } from 'twenty-sdk';
|
||||
|
||||
const handler = async (payload: InstallLogicFunctionPayload): Promise<void> => {
|
||||
console.log('Pre install logic function executed successfully!', payload.previousVersion);
|
||||
};
|
||||
|
||||
export default definePreInstallLogicFunction({
|
||||
universalIdentifier: '<generated-uuid>',
|
||||
name: 'pre-install',
|
||||
description: 'Runs before installation to prepare the application.',
|
||||
timeoutSeconds: 300,
|
||||
handler,
|
||||
});
|
||||
```
|
||||
|
||||
Puoi anche eseguire manualmente la funzione di pre-installazione in qualsiasi momento utilizzando la CLI:
|
||||
|
||||
```bash filename="Terminal"
|
||||
yarn twenty function:execute --preInstall
|
||||
```
|
||||
|
||||
Punti chiave:
|
||||
|
||||
* Le funzioni di pre-installazione utilizzano `definePreInstallLogicFunction()` — una variante specializzata che omette le impostazioni dei trigger (`cronTriggerSettings`, `databaseEventTriggerSettings`, `httpRouteTriggerSettings`, `isTool`).
|
||||
* L'handler riceve un `InstallLogicFunctionPayload` con `{ previousVersion: string }` — la versione dell'app precedentemente installata (oppure una stringa vuota per nuove installazioni).
|
||||
* È consentita una sola funzione di pre-installazione per applicazione. La build del manifesto genererà un errore se ne viene rilevata più di una.
|
||||
* L'`universalIdentifier` della funzione viene impostato automaticamente come `preInstallLogicFunctionUniversalIdentifier` nel manifesto dell'applicazione durante la build — non è necessario farvi riferimento in `defineApplication()`.
|
||||
* Il timeout predefinito è impostato a 300 secondi (5 minuti) per consentire attività di preparazione più lunghe.
|
||||
* Le funzioni di pre-installazione non necessitano di trigger — vengono invocate dalla piattaforma prima dell'installazione o manualmente tramite `function:execute --preInstall`.
|
||||
|
||||
### Funzioni post-installazione
|
||||
|
||||
Una funzione post-installazione è una funzione logica che viene eseguita automaticamente dopo che la tua app è stata installata in uno spazio di lavoro. Questo è utile per attività di configurazione una tantum come il popolamento di dati predefiniti, la creazione di record iniziali o la configurazione delle impostazioni dello spazio di lavoro.
|
||||
|
||||
Quando esegui lo scaffolding di una nuova app con `create-twenty-app`, viene generata automaticamente una funzione di post-installazione in `src/logic-functions/post-install.ts`:
|
||||
|
||||
```typescript
|
||||
// src/logic-functions/post-install.ts
|
||||
import { definePostInstallLogicFunction, type InstallLogicFunctionPayload } from 'twenty-sdk';
|
||||
|
||||
const handler = async (payload: InstallLogicFunctionPayload): Promise<void> => {
|
||||
console.log('Post install logic function executed successfully!', payload.previousVersion);
|
||||
};
|
||||
|
||||
export default definePostInstallLogicFunction({
|
||||
universalIdentifier: '<generated-uuid>',
|
||||
name: 'post-install',
|
||||
description: 'Runs after installation to set up the application.',
|
||||
timeoutSeconds: 300,
|
||||
handler,
|
||||
});
|
||||
```
|
||||
|
||||
Puoi anche eseguire manualmente la funzione di post-installazione in qualsiasi momento utilizzando la CLI:
|
||||
|
||||
```bash filename="Terminal"
|
||||
yarn twenty function:execute --postInstall
|
||||
```
|
||||
|
||||
Punti chiave:
|
||||
|
||||
* Le funzioni di post-installazione utilizzano `definePostInstallLogicFunction()` — una variante specializzata che omette le impostazioni dei trigger (`cronTriggerSettings`, `databaseEventTriggerSettings`, `httpRouteTriggerSettings`, `isTool`).
|
||||
* L'handler riceve un `InstallLogicFunctionPayload` con `{ previousVersion: string }` — la versione dell'app precedentemente installata (oppure una stringa vuota per nuove installazioni).
|
||||
* È consentita una sola funzione di post-installazione per applicazione. La build del manifesto genererà un errore se ne viene rilevata più di una.
|
||||
* L'`universalIdentifier` della funzione viene impostato automaticamente come `postInstallLogicFunctionUniversalIdentifier` nel manifesto dell'applicazione durante la build — non è necessario farvi riferimento in `defineApplication()`.
|
||||
* Il timeout predefinito è impostato a 300 secondi (5 minuti) per consentire attività di configurazione più lunghe, come il popolamento dei dati.
|
||||
* Le funzioni di post-installazione non necessitano di trigger — vengono invocate dalla piattaforma durante l'installazione o manualmente tramite `function:execute --postInstall`.
|
||||
|
||||
### Payload del trigger di route
|
||||
|
||||
<Warning>
|
||||
**Modifica non retrocompatibile (v1.16, gennaio 2026):** Il formato del payload del trigger di route è cambiato. Prima della v1.16, i parametri di query, i parametri di percorso e il corpo venivano inviati direttamente come payload. A partire dalla v1.16, sono annidati all'interno di un oggetto `RoutePayload` strutturato.
|
||||
|
||||
**Prima della v1.16:**
|
||||
```typescript
|
||||
const handler = async (params) => {
|
||||
const { param1, param2 } = params; // Direct access
|
||||
};
|
||||
```
|
||||
|
||||
**Dopo la v1.16:**
|
||||
```typescript
|
||||
const handler = async (event: RoutePayload) => {
|
||||
const { param1, param2 } = event.body; // Access via .body
|
||||
const { queryParam } = event.queryStringParameters;
|
||||
const { id } = event.pathParameters;
|
||||
};
|
||||
```
|
||||
|
||||
**Per migrare le funzioni esistenti:** Aggiorna l'handler per estrarre i dati da `event.body`, `event.queryStringParameters` o `event.pathParameters` invece che direttamente dall'oggetto `params`.
|
||||
</Warning>
|
||||
|
||||
Quando un trigger di route invoca la tua funzione logica, questa riceve un oggetto `RoutePayload` che segue il formato AWS HTTP API v2. Importa il tipo da `twenty-sdk`:
|
||||
|
||||
```typescript
|
||||
import { defineLogicFunction, type RoutePayload } from 'twenty-sdk';
|
||||
|
||||
const handler = async (event: RoutePayload) => {
|
||||
// Access request data
|
||||
const { headers, queryStringParameters, pathParameters, body } = event;
|
||||
|
||||
// HTTP method and path are available in requestContext
|
||||
const { method, path } = event.requestContext.http;
|
||||
|
||||
return { message: 'Success' };
|
||||
};
|
||||
```
|
||||
|
||||
Il tipo `RoutePayload` ha la seguente struttura:
|
||||
|
||||
| Proprietà | Tipo | Descrizione |
|
||||
| ---------------------------- | ------------------------------------- | ----------------------------------------------------------------------------------------------- |
|
||||
| `headers` | `Record<string, string \| undefined>` | Intestazioni HTTP (solo quelle elencate in `forwardedRequestHeaders`) |
|
||||
| `queryStringParameters` | `Record<string, string \| undefined>` | Parametri della query string (valori multipli uniti da virgole) |
|
||||
| `pathParameters` | `Record<string, string \| undefined>` | Parametri di percorso estratti dal pattern della route (ad es., `/users/:id` → `{ id: '123' }`) |
|
||||
| `body` | `object \| null` | Corpo della richiesta analizzato (JSON) |
|
||||
| `isBase64Encoded` | `boolean` | Indica se il corpo è codificato in base64 |
|
||||
| `requestContext.http.method` | `string` | Metodo HTTP (GET, POST, PUT, PATCH, DELETE) |
|
||||
| `requestContext.http.path` | `string` | Percorso della richiesta non elaborato |
|
||||
|
||||
### Inoltro delle intestazioni HTTP
|
||||
|
||||
Per impostazione predefinita, le intestazioni HTTP delle richieste in ingresso **non** vengono passate alla tua funzione logica per motivi di sicurezza. Per accedere a intestazioni specifiche, elencale esplicitamente nell'array `forwardedRequestHeaders`:
|
||||
|
||||
```typescript
|
||||
export default defineLogicFunction({
|
||||
universalIdentifier: 'e56d363b-0bdc-4d8a-a393-6f0d1c75bdcf',
|
||||
name: 'webhook-handler',
|
||||
handler,
|
||||
triggers: [
|
||||
{
|
||||
universalIdentifier: 'c9f84c8d-b26d-40d1-95dd-4f834ae5a2c6',
|
||||
type: 'route',
|
||||
path: '/webhook',
|
||||
httpMethod: 'POST',
|
||||
isAuthRequired: false,
|
||||
forwardedRequestHeaders: ['x-webhook-signature', 'content-type'],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Nel tuo handler, puoi quindi accedere a queste intestazioni:
|
||||
|
||||
```typescript
|
||||
const handler = async (event: RoutePayload) => {
|
||||
const signature = event.headers['x-webhook-signature'];
|
||||
const contentType = event.headers['content-type'];
|
||||
|
||||
// Validate webhook signature...
|
||||
return { received: true };
|
||||
};
|
||||
```
|
||||
|
||||
<Note>
|
||||
I nomi delle intestazioni vengono normalizzati in minuscolo. Accedile usando chiavi in minuscolo (ad esempio, `event.headers['content-type']`).
|
||||
</Note>
|
||||
|
||||
Puoi creare nuove funzioni in due modi:
|
||||
|
||||
* **Generata dallo scaffolder**: Esegui `yarn twenty entity:add` e scegli l'opzione per aggiungere una nuova funzione logica. Questo genera un file iniziale con un handler e una configurazione.
|
||||
* **Manuale**: Crea un nuovo file `*.logic-function.ts` e usa `defineLogicFunction()`, seguendo lo stesso schema.
|
||||
|
||||
### Contrassegnare una funzione logica come strumento
|
||||
|
||||
Le funzioni logiche possono essere esposte come **strumenti** per gli agenti di IA e i flussi di lavoro. Quando una funzione è contrassegnata come strumento, diventa individuabile dalle funzionalità di IA di Twenty e può essere selezionata come passaggio nelle automazioni dei flussi di lavoro.
|
||||
|
||||
Per contrassegnare una funzione logica come strumento, imposta `isTool: true` e fornisci un `toolInputSchema` che descriva i parametri di input attesi utilizzando [JSON Schema](https://json-schema.org/):
|
||||
|
||||
```typescript
|
||||
// src/logic-functions/enrich-company.logic-function.ts
|
||||
import { defineLogicFunction } from 'twenty-sdk';
|
||||
import { CoreApiClient } from 'twenty-sdk/generated';
|
||||
|
||||
const handler = async (params: { companyName: string; domain?: string }) => {
|
||||
const client = new CoreApiClient();
|
||||
|
||||
const result = await client.mutation({
|
||||
createTask: {
|
||||
__args: {
|
||||
data: {
|
||||
title: `Enrich data for ${params.companyName}`,
|
||||
body: `Domain: ${params.domain ?? 'unknown'}`,
|
||||
},
|
||||
},
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
return { taskId: result.createTask.id };
|
||||
};
|
||||
|
||||
export default defineLogicFunction({
|
||||
universalIdentifier: 'f47ac10b-58cc-4372-a567-0e02b2c3d479',
|
||||
name: 'enrich-company',
|
||||
description: 'Enrich a company record with external data',
|
||||
timeoutSeconds: 10,
|
||||
handler,
|
||||
isTool: true,
|
||||
toolInputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
companyName: {
|
||||
type: 'string',
|
||||
description: 'The name of the company to enrich',
|
||||
},
|
||||
domain: {
|
||||
type: 'string',
|
||||
description: 'The company website domain (optional)',
|
||||
},
|
||||
},
|
||||
required: ['companyName'],
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Punti chiave:
|
||||
|
||||
* **`isTool`** (`boolean`, predefinito: `false`): Quando impostato su `true`, la funzione viene registrata come strumento e diventa disponibile per gli agenti IA e le automazioni dei flussi di lavoro.
|
||||
* **`toolInputSchema`** (`object`, opzionale): Un oggetto JSON Schema che descrive i parametri accettati dalla funzione. Gli agenti IA utilizzano questo schema per capire quali input si aspetta lo strumento e per convalidare le chiamate. Se omesso, lo schema assume il valore predefinito `{ type: 'object', properties: {} }` (nessun parametro).
|
||||
* Le funzioni con `isTool: false` (o non impostato) **non** vengono esposte come strumenti. Possono comunque essere eseguite direttamente o chiamate da altre funzioni, ma non compariranno nell'individuazione degli strumenti.
|
||||
* **Denominazione dello strumento**: Quando esposta come strumento, il nome della funzione viene normalizzato automaticamente in `logic_function_<name>` (in minuscolo, i caratteri non alfanumerici vengono sostituiti da trattini bassi). Ad esempio, `enrich-company` diventa `logic_function_enrich_company`.
|
||||
* È possibile combinare `isTool` con i trigger — una funzione può essere sia uno strumento (invocabile dagli agenti IA) sia attivata da eventi (cron, eventi del database, routes) contemporaneamente.
|
||||
|
||||
<Note>
|
||||
**Scrivi una buona `description`.** Gli agenti IA fanno affidamento sul campo `description` della funzione per decidere quando usare lo strumento. Sii specifico su cosa fa lo strumento e quando dovrebbe essere invocato.
|
||||
</Note>
|
||||
|
||||
### Componenti front-end
|
||||
|
||||
I componenti front-end ti consentono di creare componenti React personalizzati che vengono renderizzati all'interno dell'interfaccia di Twenty. Usa `defineFrontComponent()` per definire componenti con convalida integrata:
|
||||
|
||||
```typescript
|
||||
// src/front-components/my-widget.tsx
|
||||
import { defineFrontComponent } from 'twenty-sdk';
|
||||
|
||||
const MyWidget = () => {
|
||||
return (
|
||||
<div style={{ padding: '20px', fontFamily: 'sans-serif' }}>
|
||||
<h1>My Custom Widget</h1>
|
||||
<p>This is a custom front component for Twenty.</p>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default defineFrontComponent({
|
||||
universalIdentifier: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
|
||||
name: 'my-widget',
|
||||
description: 'A custom widget component',
|
||||
component: MyWidget,
|
||||
});
|
||||
```
|
||||
|
||||
Punti chiave:
|
||||
|
||||
* I componenti front-end sono componenti React che eseguono il rendering in contesti isolati all'interno di Twenty.
|
||||
* Il campo `component` fa riferimento al tuo componente React.
|
||||
* I componenti vengono compilati e sincronizzati automaticamente durante `yarn twenty app:dev`.
|
||||
|
||||
Puoi creare nuovi componenti front-end in due modi:
|
||||
|
||||
* **Generata dallo scaffolder**: Esegui `yarn twenty entity:add` e scegli l'opzione per aggiungere un nuovo componente front-end.
|
||||
* **Manuale**: Crea un nuovo file `.tsx` e usa `defineFrontComponent()`, seguendo lo stesso schema.
|
||||
|
||||
### Abilità
|
||||
|
||||
Le skill definiscono istruzioni e capacità riutilizzabili che gli agenti IA possono utilizzare all'interno del tuo spazio di lavoro. Usa `defineSkill()` per definire skill con convalida integrata:
|
||||
|
||||
```typescript
|
||||
// src/skills/example-skill.ts
|
||||
import { defineSkill } from 'twenty-sdk';
|
||||
|
||||
export default defineSkill({
|
||||
universalIdentifier: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
|
||||
name: 'sales-outreach',
|
||||
label: 'Sales Outreach',
|
||||
description: 'Guides the AI agent through a structured sales outreach process',
|
||||
icon: 'IconBrain',
|
||||
content: `You are a sales outreach assistant. When reaching out to a prospect:
|
||||
1. Research the company and recent news
|
||||
2. Identify the prospect's role and likely pain points
|
||||
3. Draft a personalized message referencing specific details
|
||||
4. Keep the tone professional but conversational`,
|
||||
});
|
||||
```
|
||||
|
||||
Punti chiave:
|
||||
|
||||
* `name` è una stringa identificativa univoca per la skill (kebab-case consigliato).
|
||||
* `label` è il nome di visualizzazione leggibile mostrato nell'UI.
|
||||
* `content` contiene le istruzioni della skill — questo è il testo che l'agente IA utilizza.
|
||||
* `icon` (opzionale) imposta l'icona visualizzata nell'UI.
|
||||
* `description` (opzionale) fornisce contesto aggiuntivo sullo scopo della skill.
|
||||
|
||||
Puoi creare nuove skill in due modi:
|
||||
|
||||
* **Generata dallo scaffolder**: Esegui `yarn twenty entity:add` e scegli l'opzione per aggiungere una nuova skill.
|
||||
* **Manuale**: Crea un nuovo file e usa `defineSkill()`, seguendo lo stesso schema.
|
||||
|
||||
### Client tipizzati generati
|
||||
|
||||
Due client tipizzati sono generati automaticamente da `yarn twenty app:dev` e salvati in `node_modules/twenty-sdk/generated` in base allo schema del tuo spazio di lavoro:
|
||||
|
||||
* **`CoreApiClient`** — interroga l'endpoint `/graphql` per i dati dello spazio di lavoro
|
||||
* **`MetadataApiClient`** — interroga l'endpoint `/metadata` per la configurazione dello spazio di lavoro e il caricamento dei file
|
||||
|
||||
```typescript
|
||||
import { CoreApiClient, MetadataApiClient } from 'twenty-sdk/generated';
|
||||
|
||||
const client = new CoreApiClient();
|
||||
const { me } = await client.query({ me: { id: true, displayName: true } });
|
||||
|
||||
const metadataClient = new MetadataApiClient();
|
||||
const { currentWorkspace } = await metadataClient.query({ currentWorkspace: { id: true } });
|
||||
```
|
||||
|
||||
Entrambi i client vengono rigenerati automaticamente da `yarn twenty app:dev` ogni volta che i tuoi oggetti o campi cambiano.
|
||||
|
||||
#### Credenziali di runtime nelle funzioni logiche
|
||||
|
||||
Quando la tua funzione viene eseguita su Twenty, la piattaforma inietta le credenziali come variabili d'ambiente prima dell'esecuzione del tuo codice:
|
||||
|
||||
* `TWENTY_API_URL`: URL di base dell'API Twenty a cui punta la tua app.
|
||||
* `TWENTY_API_KEY`: Chiave a breve durata con ambito al ruolo funzione predefinito della tua applicazione.
|
||||
|
||||
Note:
|
||||
|
||||
* Non è necessario passare URL o chiave API al client generato. Legge `TWENTY_API_URL` e `TWENTY_API_KEY` da process.env in fase di esecuzione.
|
||||
* I permessi della chiave API sono determinati dal ruolo referenziato nel tuo `application-config.ts` tramite `defaultRoleUniversalIdentifier`. Questo è il ruolo predefinito utilizzato dalle funzioni logiche della tua applicazione.
|
||||
* Le applicazioni possono definire ruoli per seguire il principio del privilegio minimo. Concedi solo i permessi necessari alle tue funzioni, quindi punta `defaultRoleUniversalIdentifier` all'identificatore universale di quel ruolo.
|
||||
|
||||
#### Caricamento dei file
|
||||
|
||||
Il `MetadataApiClient` generato include un metodo `uploadFile` per allegare file ai campi di tipo file sugli oggetti del tuo spazio di lavoro. Poiché i client GraphQL standard non supportano nativamente il caricamento di file multipart, il client fornisce questo metodo dedicato che implementa la [specifica della richiesta GraphQL multipart](https://github.com/jaydenseric/graphql-multipart-request-spec) dietro le quinte.
|
||||
|
||||
```typescript
|
||||
import { MetadataApiClient } from 'twenty-sdk/generated';
|
||||
import * as fs from 'fs';
|
||||
|
||||
const metadataClient = new MetadataApiClient();
|
||||
|
||||
const fileBuffer = fs.readFileSync('./invoice.pdf');
|
||||
|
||||
const uploadedFile = await metadataClient.uploadFile(
|
||||
fileBuffer, // file contents as a Buffer
|
||||
'invoice.pdf', // filename
|
||||
'application/pdf', // MIME type (defaults to 'application/octet-stream')
|
||||
'58a0a314-d7ea-4865-9850-7fb84e72f30b', // field universal identifier
|
||||
);
|
||||
|
||||
console.log(uploadedFile);
|
||||
// { id: '...', path: '...', size: 12345, createdAt: '...', url: 'https://...' }
|
||||
```
|
||||
|
||||
La firma del metodo:
|
||||
|
||||
```typescript
|
||||
uploadFile(
|
||||
fileBuffer: Buffer,
|
||||
filename: string,
|
||||
contentType: string,
|
||||
fieldMetadataUniversalIdentifier: string,
|
||||
): Promise<{ id: string; path: string; size: number; createdAt: string; url: string }>
|
||||
```
|
||||
|
||||
| Parametro | Tipo | Descrizione |
|
||||
| ---------------------------------- | -------- | ------------------------------------------------------------------------ |
|
||||
| `fileBuffer` | `Buffer` | Il contenuto grezzo del file |
|
||||
| `filename` | `string` | Il nome del file (utilizzato per l'archiviazione e la visualizzazione) |
|
||||
| `contentType` | `string` | Tipo MIME del file (predefinito su `application/octet-stream` se omesso) |
|
||||
| `fieldMetadataUniversalIdentifier` | `string` | L'`universalIdentifier` del campo di tipo file nel tuo oggetto |
|
||||
|
||||
Punti chiave:
|
||||
|
||||
* Il metodo `uploadFile` è disponibile su `MetadataApiClient` perché la mutazione di upload viene risolta dall'endpoint `/metadata`.
|
||||
* Usa l'`universalIdentifier` del campo (non il suo ID specifico dello spazio di lavoro), quindi il tuo codice di upload funziona in qualsiasi spazio di lavoro in cui la tua app è installata — coerentemente con il modo in cui le app fanno riferimento ai campi altrove.
|
||||
* L'`url` restituito è un URL firmato che puoi usare per accedere al file caricato.
|
||||
|
||||
### Esempio Hello World
|
||||
|
||||
Esplora un esempio minimale end-to-end che dimostra oggetti, funzioni logiche, componenti front-end e trigger multipli [qui](https://github.com/twentyhq/twenty/tree/main/packages/twenty-apps/hello-world).
|
||||
@@ -1,233 +0,0 @@
|
||||
---
|
||||
title: Per iniziare
|
||||
description: Crea la tua prima app Twenty in pochi minuti.
|
||||
---
|
||||
|
||||
<Warning>
|
||||
Le app sono attualmente in fase alfa. La funzionalità è funzionante ma ancora in evoluzione.
|
||||
</Warning>
|
||||
|
||||
Le app ti permettono di estendere Twenty con oggetti, campi, funzioni logiche, competenze IA e componenti UI personalizzati — il tutto gestito come codice.
|
||||
|
||||
**Cosa puoi fare oggi:**
|
||||
|
||||
* Definisci oggetti e campi personalizzati come codice (modello dati gestito)
|
||||
* Crea funzioni logiche con trigger personalizzati (route HTTP, cron, eventi del database)
|
||||
* Definisci le abilità per gli agenti IA
|
||||
* Crea componenti front-end che vengono renderizzati all'interno della UI di Twenty
|
||||
* Distribuisci la stessa app su più spazi di lavoro
|
||||
|
||||
## Prerequisiti
|
||||
|
||||
* Node.js 24+ e Yarn 4
|
||||
* Uno spazio di lavoro Twenty e una chiave API (creane una su https://app.twenty.com/settings/api-webhooks)
|
||||
|
||||
## Per iniziare
|
||||
|
||||
Crea una nuova app utilizzando lo scaffolder ufficiale, quindi autenticati e inizia a sviluppare:
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Scaffold a new app (includes all examples by default)
|
||||
npx create-twenty-app@latest my-twenty-app
|
||||
cd my-twenty-app
|
||||
|
||||
# Start dev mode: automatically syncs local changes to your workspace
|
||||
yarn twenty app:dev
|
||||
```
|
||||
|
||||
Lo strumento di scaffolding supporta due modalità per controllare quali file di esempio vengono inclusi:
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Default (exhaustive): all examples (object, field, logic function, front component, view, navigation menu item, skill)
|
||||
npx create-twenty-app@latest my-app
|
||||
|
||||
# Minimal: only core files (application-config.ts and default-role.ts)
|
||||
npx create-twenty-app@latest my-app --minimal
|
||||
```
|
||||
|
||||
Da qui puoi:
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Add a new entity to your application (guided)
|
||||
yarn twenty entity:add
|
||||
|
||||
# Watch your application's function logs
|
||||
yarn twenty function:logs
|
||||
|
||||
# Execute a function by name
|
||||
yarn twenty function:execute -n my-function -p '{"name": "test"}'
|
||||
|
||||
# Execute the pre-install function
|
||||
yarn twenty function:execute --preInstall
|
||||
|
||||
# Execute the post-install function
|
||||
yarn twenty function:execute --postInstall
|
||||
|
||||
# Uninstall the application from the current workspace
|
||||
yarn twenty app:uninstall
|
||||
|
||||
# Display commands' help
|
||||
yarn twenty help
|
||||
```
|
||||
|
||||
Vedi anche: le pagine di riferimento della CLI per [create-twenty-app](https://www.npmjs.com/package/create-twenty-app) e [twenty-sdk CLI](https://www.npmjs.com/package/twenty-sdk).
|
||||
|
||||
## Struttura del progetto (generata dallo scaffolder)
|
||||
|
||||
Quando esegui `npx create-twenty-app@latest my-twenty-app`, lo scaffolder:
|
||||
|
||||
* Copia un'applicazione base minimale in `my-twenty-app/`
|
||||
* Aggiunge una dipendenza locale `twenty-sdk` e la configurazione di Yarn 4
|
||||
* Crea file di configurazione e script collegati alla CLI `twenty`
|
||||
* Genera i file principali (configurazione dell'applicazione, ruolo predefinito per le funzioni logiche, funzioni di pre-installazione e post-installazione) più i file di esempio in base alla modalità di scaffolding
|
||||
|
||||
Un'app appena creata con la modalità predefinita `--exhaustive` si presenta così:
|
||||
|
||||
```text filename="my-twenty-app/"
|
||||
my-twenty-app/
|
||||
package.json
|
||||
yarn.lock
|
||||
.gitignore
|
||||
.nvmrc
|
||||
.yarnrc.yml
|
||||
.yarn/
|
||||
install-state.gz
|
||||
.oxlintrc.json
|
||||
tsconfig.json
|
||||
README.md
|
||||
public/ # Public assets folder (images, fonts, etc.)
|
||||
src/
|
||||
├── application-config.ts # Required - main application configuration
|
||||
├── roles/
|
||||
│ └── default-role.ts # Default role for logic functions
|
||||
├── objects/
|
||||
│ └── example-object.ts # Example custom object definition
|
||||
├── fields/
|
||||
│ └── example-field.ts # Example standalone field definition
|
||||
├── logic-functions/
|
||||
│ ├── hello-world.ts # Example logic function
|
||||
│ ├── pre-install.ts # Pre-install logic function
|
||||
│ └── post-install.ts # Post-install logic function
|
||||
├── front-components/
|
||||
│ └── hello-world.tsx # Example front component
|
||||
├── views/
|
||||
│ └── example-view.ts # Example saved view definition
|
||||
├── navigation-menu-items/
|
||||
│ └── example-navigation-menu-item.ts # Example sidebar navigation link
|
||||
└── skills/
|
||||
└── example-skill.ts # Example AI agent skill definition
|
||||
```
|
||||
|
||||
Con `--minimal`, vengono creati solo i file principali (`application-config.ts`, `roles/default-role.ts`, `logic-functions/pre-install.ts` e `logic-functions/post-install.ts`).
|
||||
|
||||
A livello generale:
|
||||
|
||||
* **package.json**: Dichiara il nome dell'app, la versione, i motori (Node 24+, Yarn 4) e aggiunge `twenty-sdk` più uno script `twenty` che delega alla CLI locale `twenty`. Esegui `yarn twenty help` per elencare tutti i comandi disponibili.
|
||||
* **.gitignore**: Ignora i file generati comuni come `node_modules`, `.yarn`, `generated/` (client tipizzato), `dist/`, `build/`, cartelle di coverage, file di log e file `.env*`.
|
||||
* **yarn.lock**, **.yarnrc.yml**, **.yarn/**: Bloccano e configurano la toolchain Yarn 4 utilizzata dal progetto.
|
||||
* **.nvmrc**: Fissa la versione di Node.js prevista dal progetto.
|
||||
* **.oxlintrc.json** e **tsconfig.json**: Forniscono linting e configurazione TypeScript per i sorgenti TypeScript della tua app.
|
||||
* **README.md**: Un breve README nella radice dell'app con istruzioni di base.
|
||||
* **public/**: Una cartella per archiviare risorse pubbliche (immagini, font, file statici) che saranno servite con la tua applicazione. I file collocati qui vengono caricati durante la sincronizzazione e sono accessibili in fase di esecuzione.
|
||||
* **src/**: Il luogo principale in cui definisci la tua applicazione come codice
|
||||
|
||||
### Rilevamento delle entità
|
||||
|
||||
L'SDK rileva le entità analizzando i tuoi file TypeScript alla ricerca di chiamate **`export default define<Entity>({...})`**. Ogni tipo di entità ha una corrispondente funzione helper esportata da `twenty-sdk`:
|
||||
|
||||
| Funzione helper | Tipo di entità |
|
||||
| -------------------------------- | ------------------------------------------------------------------------------ |
|
||||
| `defineObject` | Definizioni di oggetti personalizzati |
|
||||
| `defineLogicFunction` | Definizioni di funzioni logiche |
|
||||
| `definePreInstallLogicFunction` | Funzione logica di pre-installazione (viene eseguita prima dell'installazione) |
|
||||
| `definePostInstallLogicFunction` | Funzione logica di post-installazione (viene eseguita dopo l'installazione) |
|
||||
| `defineFrontComponent` | Definizioni dei componenti front-end |
|
||||
| `defineRole` | Definizioni di ruoli |
|
||||
| `defineField` | Estensioni di campo per oggetti esistenti |
|
||||
| `defineView` | Definizioni di viste salvate |
|
||||
| `defineNavigationMenuItem` | Definizioni delle voci del menu di navigazione |
|
||||
| `defineSkill` | Definizioni delle competenze degli agenti IA |
|
||||
|
||||
<Note>
|
||||
**La denominazione dei file è flessibile.** Il rilevamento delle entità è basato sull'AST — l'SDK esegue la scansione dei file sorgente alla ricerca del pattern `export default define<Entity>({...})`. Puoi organizzare file e cartelle come preferisci. Raggruppare per tipo di entità (ad es., `logic-functions/`, `roles/`) è solo una convenzione per l'organizzazione del codice, non un requisito.
|
||||
</Note>
|
||||
|
||||
Esempio di entità rilevata:
|
||||
|
||||
```typescript
|
||||
// This file can be named anything and placed anywhere in src/
|
||||
import { defineObject, FieldType } from 'twenty-sdk';
|
||||
|
||||
export default defineObject({
|
||||
universalIdentifier: '...',
|
||||
nameSingular: 'postCard',
|
||||
// ... rest of config
|
||||
});
|
||||
```
|
||||
|
||||
Comandi successivi aggiungeranno altri file e cartelle:
|
||||
|
||||
* `yarn twenty app:dev` genererà automaticamente due client API tipizzati in `node_modules/twenty-sdk/generated`: `CoreApiClient` (per i dati dell'area di lavoro tramite `/graphql`) e `MetadataApiClient` (per la configurazione dell'area di lavoro e il caricamento di file tramite `/metadata`).
|
||||
* `yarn twenty entity:add` aggiungerà file di definizione delle entità sotto `src/` per i tuoi oggetti, funzioni, componenti front-end, ruoli, competenze e altro ancora.
|
||||
|
||||
## Autenticazione
|
||||
|
||||
La prima volta che esegui `yarn twenty auth:login`, ti verranno richiesti:
|
||||
|
||||
* URL dell'API (predefinito a http://localhost:3000 o al profilo dello spazio di lavoro corrente)
|
||||
* Chiave API
|
||||
|
||||
Le tue credenziali sono archiviate per utente in `~/.twenty/config.json`. Puoi mantenere più profili e passare da uno all'altro.
|
||||
|
||||
### Gestione delle aree di lavoro
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Login interactively (recommended)
|
||||
yarn twenty auth:login
|
||||
|
||||
# Login to a specific workspace profile
|
||||
yarn twenty auth:login --workspace my-custom-workspace
|
||||
|
||||
# List all configured workspaces
|
||||
yarn twenty auth:list
|
||||
|
||||
# Switch the default workspace (interactive)
|
||||
yarn twenty auth:switch
|
||||
|
||||
# Switch to a specific workspace
|
||||
yarn twenty auth:switch production
|
||||
|
||||
# Check current authentication status
|
||||
yarn twenty auth:status
|
||||
```
|
||||
|
||||
Una volta che hai cambiato area di lavoro con `yarn twenty auth:switch`, tutti i comandi successivi utilizzeranno quell'area di lavoro per impostazione predefinita. Puoi comunque sovrascriverla temporaneamente con `--workspace <name>`.
|
||||
|
||||
## Configurazione manuale (senza lo scaffolder)
|
||||
|
||||
Sebbene consigliamo di utilizzare `create-twenty-app` per la migliore esperienza iniziale, puoi anche configurare un progetto manualmente. Non installare la CLI globalmente. Invece, aggiungi `twenty-sdk` come dipendenza locale e collega un unico script nel tuo package.json:
|
||||
|
||||
```bash filename="Terminal"
|
||||
yarn add -D twenty-sdk
|
||||
```
|
||||
|
||||
Quindi aggiungi uno script `twenty`:
|
||||
|
||||
```json filename="package.json"
|
||||
{
|
||||
"scripts": {
|
||||
"twenty": "twenty"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Ora puoi eseguire tutti i comandi tramite `yarn twenty <command>`, ad es. `yarn twenty app:dev`, `yarn twenty help`, ecc.
|
||||
|
||||
## Risoluzione dei problemi
|
||||
|
||||
* Errori di autenticazione: esegui `yarn twenty auth:login` e assicurati che la tua chiave API abbia i permessi richiesti.
|
||||
* Impossibile connettersi al server: verifica l'URL dell'API e che il server Twenty sia raggiungibile.
|
||||
* Tipi o client mancanti/obsoleti: riavvia `yarn twenty app:dev` — genera automaticamente il client tipizzato.
|
||||
* Modalità di sviluppo non sincronizzata: assicurati che `yarn twenty app:dev` sia in esecuzione e che le modifiche non vengano ignorate dal tuo ambiente.
|
||||
|
||||
Canale di supporto su Discord: https://discord.com/channels/1130383047699738754/1130386664812982322
|
||||
@@ -1,119 +0,0 @@
|
||||
---
|
||||
title: Pubblicazione
|
||||
description: Distribuisci la tua app Twenty nel marketplace oppure distribuiscila internamente.
|
||||
---
|
||||
|
||||
<Warning>
|
||||
Le app sono attualmente in fase alfa. La funzionalità è funzionante ma ancora in evoluzione.
|
||||
</Warning>
|
||||
|
||||
## Panoramica
|
||||
|
||||
Una volta che la tua app è stata [compilata e testata localmente](/l/it/developers/extend/apps/building), hai due modalità per distribuirla:
|
||||
|
||||
* **Pubblica su npm** — elenca la tua app nel marketplace di Twenty affinché qualsiasi spazio di lavoro possa scoprirla e installarla.
|
||||
* **Esegui il push di un tarball** — distribuisci la tua app su un server Twenty specifico per uso interno senza renderla pubblicamente disponibile.
|
||||
|
||||
## Pubblicazione su npm
|
||||
|
||||
La pubblicazione su npm rende la tua app scopribile nel marketplace di Twenty. Qualsiasi spazio di lavoro Twenty può sfogliare, installare e aggiornare le app del marketplace direttamente dall'interfaccia utente.
|
||||
|
||||
### Requisiti
|
||||
|
||||
* Un account [npm](https://www.npmjs.com)
|
||||
* Il nome del tuo pacchetto **deve** usare il prefisso `twenty-app-` (es. `twenty-app-postcard-sender`)
|
||||
|
||||
### Passaggi
|
||||
|
||||
1. **Compila la tua app** — la CLI compila i tuoi sorgenti TypeScript e genera il manifest dell'applicazione:
|
||||
|
||||
```bash filename="Terminal"
|
||||
yarn twenty app:build
|
||||
```
|
||||
|
||||
2. **Pubblica su npm** — esegui il push del pacchetto compilato al registro npm:
|
||||
|
||||
```bash filename="Terminal"
|
||||
npx twenty app:publish
|
||||
```
|
||||
|
||||
### Rilevamento automatico
|
||||
|
||||
I pacchetti con il prefisso `twenty-app-` vengono rilevati automaticamente dal catalogo del marketplace di Twenty. Una volta pubblicata, la tua app compare nel marketplace entro pochi minuti — non è richiesta alcuna registrazione o approvazione manuale.
|
||||
|
||||
### Pubblicazione con CI
|
||||
|
||||
Il progetto generato include un workflow di GitHub Actions che pubblica a ogni release. Esegue `app:build`, quindi `npm publish --provenance` dall'output di build:
|
||||
|
||||
```yaml filename=".github/workflows/publish.yml"
|
||||
name: Publish
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "24"
|
||||
registry-url: https://registry.npmjs.org
|
||||
- run: yarn install --immutable
|
||||
- run: npx twenty app:build
|
||||
- run: npm publish --provenance --access public
|
||||
working-directory: .twenty/output
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
```
|
||||
|
||||
Per altri sistemi CI (GitLab CI, CircleCI, ecc.), si applicano gli stessi tre comandi: `yarn install`, `npx twenty app:build`, quindi `npm publish` da `.twenty/output`.
|
||||
|
||||
<Tip>
|
||||
**npm provenance** è opzionale ma consigliata. La pubblicazione con `--provenance` aggiunge un badge di attendibilità alla tua scheda npm, consentendo agli utenti di verificare che il pacchetto sia stato creato a partire da uno specifico commit in una pipeline CI pubblica. Consulta la [documentazione su npm provenance](https://docs.npmjs.com/generating-provenance-statements) per le istruzioni di configurazione.
|
||||
</Tip>
|
||||
|
||||
## Distribuzione interna
|
||||
|
||||
Per le app che non vuoi rendere pubbliche — strumenti proprietari, integrazioni solo per l'azienda o build sperimentali — puoi eseguire il push di un tarball direttamente su un server Twenty.
|
||||
|
||||
### Push di un tarball
|
||||
|
||||
Compila la tua app e distribuiscila su un server specifico in un solo passaggio:
|
||||
|
||||
```bash filename="Terminal"
|
||||
npx twenty app:publish --server <server-url>
|
||||
```
|
||||
|
||||
Qualsiasi spazio di lavoro su quel server può quindi installare e aggiornare l'app dalla pagina delle impostazioni **Applicazioni**.
|
||||
|
||||
### Gestione delle versioni
|
||||
|
||||
Per rilasciare un aggiornamento:
|
||||
|
||||
1. Incrementa il campo `version` nel tuo `package.json`
|
||||
2. Esegui il push di un nuovo tarball con `npx twenty app:publish --server <server-url>`
|
||||
3. Gli spazi di lavoro su quel server vedranno l'aggiornamento disponibile nelle proprie impostazioni
|
||||
|
||||
<Note>
|
||||
Le app interne sono limitate al server su cui vengono caricate. Non compariranno nel marketplace pubblico e non potranno essere installate dagli spazi di lavoro su altri server.
|
||||
</Note>
|
||||
|
||||
## Categorie di app
|
||||
|
||||
Twenty organizza le app in tre categorie in base a come vengono distribuite:
|
||||
|
||||
| Categoria | Come funziona | Visibile nel marketplace? |
|
||||
| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | ------------------------- |
|
||||
| **Sviluppo** | App in modalità di sviluppo locale eseguite tramite `yarn twenty app:dev`. Usate per la compilazione e i test. | No |
|
||||
| **Pubblicata** | App pubblicate su npm con il prefisso `twenty-app-`. Elencate nel marketplace per l'installazione da parte di qualsiasi spazio di lavoro. | Sì |
|
||||
| **Interna** | App distribuite tramite tarball su un server specifico. Disponibili solo per gli spazi di lavoro su quel server. | No |
|
||||
|
||||
<Tip>
|
||||
Inizia in modalità **Sviluppo** mentre crei la tua app. Quando è pronta, scegli **Pubblicata** (npm) per un'ampia distribuzione oppure **Interna** (tarball) per una distribuzione privata.
|
||||
</Tip>
|
||||
@@ -171,7 +171,7 @@ export default defineObject({
|
||||
|
||||
Comandi successivi aggiungeranno altri file e cartelle:
|
||||
|
||||
* `yarn twenty app:dev` genererà automaticamente due client API tipizzati in `node_modules/twenty-sdk/clients`: `CoreApiClient` (per i dati dell'area di lavoro tramite `/graphql`) e `MetadataApiClient` (per la configurazione dell'area di lavoro e il caricamento di file tramite `/metadata`).
|
||||
* `yarn twenty app:dev` genererà automaticamente due client API tipizzati in `node_modules/twenty-sdk/generated`: `CoreApiClient` (per i dati dell'area di lavoro tramite `/graphql`) e `MetadataApiClient` (per la configurazione dell'area di lavoro e il caricamento di file tramite `/metadata`).
|
||||
* `yarn twenty entity:add` will add entity definition files under `src/` for your custom objects, functions, front components, roles, skills, and more.
|
||||
|
||||
## Autenticazione
|
||||
@@ -228,7 +228,7 @@ L'SDK fornisce funzioni helper per definire le entità della tua app. Come descr
|
||||
| `defineView()` | Definisce viste salvate per gli oggetti |
|
||||
| `defineNavigationMenuItem()` | Definisce i link di navigazione della barra laterale |
|
||||
| `defineSkill()` | Define AI agent skills |
|
||||
| `defineAgent()` | Definisci agenti IA con prompt di sistema |
|
||||
| `defineAgent()` | Define AI agents with system prompts |
|
||||
|
||||
Queste funzioni convalidano la configurazione in fase di build e offrono il completamento automatico nell'IDE e la sicurezza dei tipi.
|
||||
|
||||
@@ -321,72 +321,6 @@ Puoi sovrascrivere i campi predefiniti definendo un campo con lo stesso nome nel
|
||||
ma non è consigliato.
|
||||
</Note>
|
||||
|
||||
### Definire campi sugli oggetti esistenti
|
||||
|
||||
Usa `defineField()` per aggiungere campi personalizzati agli oggetti esistenti — sia agli oggetti standard (come `company`, `person`, `opportunity`) sia agli oggetti personalizzati definiti da altre app. Ogni campo risiede nel proprio file e fa riferimento all'oggetto di destinazione tramite il suo `universalIdentifier`.
|
||||
|
||||
Per fare riferimento agli oggetti standard, importa `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS` da `twenty-sdk`. Questa costante fornisce identificatori stabili per tutti gli oggetti integrati e per i relativi campi:
|
||||
|
||||
```typescript
|
||||
// src/fields/apollo-total-funding.field.ts
|
||||
import {
|
||||
defineField,
|
||||
FieldType,
|
||||
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS,
|
||||
} from 'twenty-sdk';
|
||||
|
||||
export default defineField({
|
||||
universalIdentifier: 'c90ae72d-4ddf-4f22-882f-eef98c91e40e',
|
||||
objectUniversalIdentifier:
|
||||
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company.universalIdentifier,
|
||||
type: FieldType.CURRENCY,
|
||||
name: 'apolloTotalFunding',
|
||||
label: 'Total Funding',
|
||||
description: 'Total funding raised by the company',
|
||||
icon: 'IconCash',
|
||||
});
|
||||
```
|
||||
|
||||
Punti chiave:
|
||||
|
||||
* `objectUniversalIdentifier` indica a Twenty a quale oggetto associare il campo. Usa `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.<objectName>.universalIdentifier` per gli oggetti standard.
|
||||
* Ogni campo richiede un proprio `universalIdentifier` stabile, un `name`, `type`, `label` e l'`objectUniversalIdentifier` di destinazione.
|
||||
* Puoi generare nuovi campi usando `yarn twenty entity:add` e scegliendo l'opzione campo.
|
||||
* `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS` è anche esportato come `STANDARD_OBJECT` per comodità — entrambi si riferiscono alla stessa costante.
|
||||
|
||||
Gli oggetti standard disponibili includono: `attachment`, `blocklist`, `calendarChannel`, `calendarEvent`, `calendarEventParticipant`, `company`, `connectedAccount`, `dashboard`, `favorite`, `favoriteFolder`, `message`, `messageChannel`, `messageParticipant`, `messageThread`, `note`, `noteTarget`, `opportunity`, `person`, `task`, `taskTarget`, `timelineActivity`, `workflow`, `workflowAutomatedTrigger`, `workflowRun`, `workflowVersion` e `workspaceMember`.
|
||||
|
||||
Ogni oggetto standard espone anche gli identificatori dei propri campi. Ad esempio, per fare riferimento a un campo specifico su un oggetto standard nelle autorizzazioni dei ruoli:
|
||||
|
||||
```typescript
|
||||
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company.fields.name.universalIdentifier
|
||||
```
|
||||
|
||||
#### Campi di relazione su oggetti esistenti
|
||||
|
||||
Puoi anche definire campi di relazione che collegano oggetti esistenti ai tuoi oggetti personalizzati:
|
||||
|
||||
```typescript
|
||||
// src/fields/people-on-call-recording.field.ts
|
||||
import { defineField, FieldType, RelationType, STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS } from 'twenty-sdk';
|
||||
import { CALL_RECORDING_OBJECT_UNIVERSAL_IDENTIFIER } from 'src/objects/call-recording';
|
||||
import { CALL_RECORDING_ON_PERSON_ID } from 'src/fields/call-recording-on-person.field';
|
||||
|
||||
export default defineField({
|
||||
universalIdentifier: '4a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d',
|
||||
objectUniversalIdentifier:
|
||||
CALL_RECORDING_OBJECT_UNIVERSAL_IDENTIFIER,
|
||||
type: FieldType.RELATION,
|
||||
name: 'person',
|
||||
label: 'Person',
|
||||
relationTargetObjectMetadataUniversalIdentifier:
|
||||
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.person.universalIdentifier,
|
||||
relationTargetFieldMetadataUniversalIdentifier:
|
||||
CALL_RECORDING_ON_PERSON_ID,
|
||||
relationType: RelationType.MANY_TO_ONE,
|
||||
});
|
||||
```
|
||||
|
||||
### Configurazione dell'applicazione (application-config.ts)
|
||||
|
||||
Ogni app ha un singolo file `application-config.ts` che descrive:
|
||||
@@ -500,7 +434,7 @@ Ogni file di funzione usa `defineLogicFunction()` per esportare una configurazio
|
||||
// src/app/createPostCard.logic-function.ts
|
||||
import { defineLogicFunction } from 'twenty-sdk';
|
||||
import type { DatabaseEventPayload, ObjectRecordCreateEvent, CronPayload, RoutePayload } from 'twenty-sdk';
|
||||
import { CoreApiClient, type Person } from 'twenty-sdk/clients';
|
||||
import { CoreApiClient, type Person } from 'twenty-sdk/generated';
|
||||
|
||||
const handler = async (params: RoutePayload) => {
|
||||
const client = new CoreApiClient();
|
||||
@@ -745,7 +679,7 @@ Per contrassegnare una funzione logica come strumento, imposta `isTool: true` e
|
||||
```typescript
|
||||
// src/logic-functions/enrich-company.logic-function.ts
|
||||
import { defineLogicFunction } from 'twenty-sdk';
|
||||
import { CoreApiClient } from 'twenty-sdk/clients';
|
||||
import { CoreApiClient } from 'twenty-sdk/generated';
|
||||
|
||||
const handler = async (params: { companyName: string; domain?: string }) => {
|
||||
const client = new CoreApiClient();
|
||||
@@ -837,255 +771,6 @@ Puoi creare nuovi componenti front-end in due modi:
|
||||
* **Generata dallo scaffolder**: Esegui `yarn twenty entity:add` e scegli l'opzione per aggiungere un nuovo componente front-end.
|
||||
* **Manuale**: Crea un nuovo file `.tsx` e usa `defineFrontComponent()`, seguendo lo stesso schema.
|
||||
|
||||
#### Dove possono essere utilizzati i componenti front.
|
||||
|
||||
I componenti front possono essere renderizzati in due posizioni all'interno di Twenty:
|
||||
|
||||
* **Pannello laterale** — I componenti front non headless si aprono nel pannello laterale destro. Questo è il comportamento predefinito quando un componente front viene avviato dal menu comandi.
|
||||
* **Widget (dashboard e pagine dei record)** — I componenti front possono essere incorporati come widget all'interno dei layout di pagina. Quando si configura una dashboard o il layout di una pagina record, gli utenti possono aggiungere un widget del componente front.
|
||||
|
||||
#### Headless vs non headless
|
||||
|
||||
I componenti front prevedono due modalità di rendering controllate dall'opzione `isHeadless`:
|
||||
|
||||
**Non headless (predefinito)** — Il componente renderizza un'interfaccia utente visibile. Quando viene avviato dal menu comandi, si apre nel pannello laterale. Questo è il comportamento predefinito quando `isHeadless` è `false` o omesso.
|
||||
|
||||
**Headless** — Il componente viene montato in modo invisibile in background. Non apre il pannello laterale. I componenti headless sono pensati per azioni che eseguono una logica e poi si smontano — ad esempio, eseguire un'attività asincrona, navigare a una pagina o mostrare una finestra modale di conferma. Si abbinano naturalmente ai componenti Command dell'SDK descritti di seguito.
|
||||
|
||||
```typescript
|
||||
export default defineFrontComponent({
|
||||
universalIdentifier: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
|
||||
name: 'my-action',
|
||||
description: 'Runs an action without opening the side panel',
|
||||
component: MyAction,
|
||||
isHeadless: true,
|
||||
command: {
|
||||
universalIdentifier: 'b2c3d4e5-f6a7-8901-bcde-f12345678901',
|
||||
label: 'Run my action',
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
#### Aggiungere voci al menu comandi
|
||||
|
||||
Per far comparire un componente front come voce nel menu comandi di Twenty, aggiungi la proprietà `command` a `defineFrontComponent()`. Quando gli utenti aprono il menu comandi (Cmd+K / Ctrl+K), la voce viene mostrata e al clic attiva il componente front.
|
||||
|
||||
L'oggetto `command` accetta i seguenti campi:
|
||||
|
||||
| Campo | Tipo | Descrizione |
|
||||
| --------------------------------------- | ---------------------------------------------- | --------------------------------------------------------------------------------------------- |
|
||||
| `universalIdentifier` | `string` (obbligatorio) | ID univoco per la voce del menu comandi |
|
||||
| `etichetta` | `string` (obbligatorio) | Etichetta visualizzata nel menu comandi |
|
||||
| `icona` | `string` (facoltativo) | Nome dell'icona (ad es., `'IconSparkles'`) |
|
||||
| `isPinned` | `boolean` (facoltativo) | Indica se il comando è fissato in alto nel menu |
|
||||
| `availabilityType` | `'GLOBAL' \| 'RECORD_SELECTION'` (facoltativo) | `GLOBAL` mostra il comando ovunque; `RECORD_SELECTION` lo mostra solo nei contesti dei record |
|
||||
| `availabilityObjectUniversalIdentifier` | `string` (facoltativo) | Limita il comando a uno specifico tipo di oggetto (ad es., Person) |
|
||||
|
||||
Ecco un esempio dall'app di registrazione delle chiamate che aggiunge un comando limitato ai record Person:
|
||||
|
||||
```typescript
|
||||
import { defineFrontComponent } from 'twenty-sdk';
|
||||
|
||||
export default defineFrontComponent({
|
||||
universalIdentifier: 'c3d4e5f6-a7b8-9012-cdef-123456789012',
|
||||
name: 'Summarize Person Call Recordings',
|
||||
description: 'Generates a summary of call recordings for a person',
|
||||
component: SummarizePersonRecordings,
|
||||
command: {
|
||||
universalIdentifier: 'd4e5f6a7-b8c9-0123-defa-234567890123',
|
||||
label: 'Summarize call recordings',
|
||||
icon: 'IconSparkles',
|
||||
isPinned: false,
|
||||
availabilityType: 'RECORD_SELECTION',
|
||||
availabilityObjectUniversalIdentifier:
|
||||
'20202020-e674-48e5-a542-72570eee7213',
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Quando il comando viene sincronizzato, appare nel menu comandi. Se il componente front è non headless, si apre il pannello laterale con il componente renderizzato al suo interno. Se è headless, il componente viene montato in background ed esegue la propria logica.
|
||||
|
||||
#### Componenti Command dell'SDK
|
||||
|
||||
Il pacchetto `twenty-sdk` fornisce quattro componenti di supporto Command progettati per i componenti front headless. Ogni componente esegue un'azione al montaggio, gestisce gli errori mostrando una notifica snackbar e smonta automaticamente il componente front al termine.
|
||||
|
||||
Importali da `twenty-sdk/command`:
|
||||
|
||||
* **`Command`** — Esegue una callback asincrona tramite la prop `execute`.
|
||||
* **`CommandLink`** — Naviga verso un percorso dell'app. Props: `to`, `params`, `queryParams`, `options`.
|
||||
* **`CommandModal`** — Apre una finestra modale di conferma. Se l'utente conferma, esegue la callback `execute`. Props: `title`, `subtitle`, `execute`, `confirmButtonText`, `confirmButtonAccent`.
|
||||
* **`CommandOpenSidePanelPage`** — Apre una specifica pagina del pannello laterale. Props: `page`, `pageTitle`, `pageIcon`.
|
||||
|
||||
Ecco un esempio completo di componente front headless che usa `Command` per eseguire un'azione dal menu comandi:
|
||||
|
||||
```typescript
|
||||
// src/front-components/run-action.tsx
|
||||
import { defineFrontComponent } from 'twenty-sdk';
|
||||
import { Command } from 'twenty-sdk/command';
|
||||
import { CoreApiClient } from 'twenty-sdk/clients';
|
||||
|
||||
const RunAction = () => {
|
||||
const execute = async () => {
|
||||
const client = new CoreApiClient();
|
||||
|
||||
await client.mutation({
|
||||
createTask: {
|
||||
__args: { data: { title: 'Created by my app' } },
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return <Command execute={execute} />;
|
||||
};
|
||||
|
||||
export default defineFrontComponent({
|
||||
universalIdentifier: 'e5f6a7b8-c9d0-1234-efab-345678901234',
|
||||
name: 'run-action',
|
||||
description: 'Creates a task from the command menu',
|
||||
component: RunAction,
|
||||
isHeadless: true,
|
||||
command: {
|
||||
universalIdentifier: 'f6a7b8c9-d0e1-2345-fabc-456789012345',
|
||||
label: 'Run my action',
|
||||
icon: 'IconPlayerPlay',
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
E un esempio che usa `CommandModal` per chiedere conferma prima di eseguire:
|
||||
|
||||
```typescript
|
||||
// src/front-components/delete-draft.tsx
|
||||
import { defineFrontComponent } from 'twenty-sdk';
|
||||
import { CommandModal } from 'twenty-sdk/command';
|
||||
|
||||
const DeleteDraft = () => {
|
||||
const execute = async () => {
|
||||
// perform the deletion
|
||||
};
|
||||
|
||||
return (
|
||||
<CommandModal
|
||||
title="Delete draft?"
|
||||
subtitle="This action cannot be undone."
|
||||
execute={execute}
|
||||
confirmButtonText="Delete"
|
||||
confirmButtonAccent="danger"
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default defineFrontComponent({
|
||||
universalIdentifier: 'a7b8c9d0-e1f2-3456-abcd-567890123456',
|
||||
name: 'delete-draft',
|
||||
description: 'Deletes a draft with confirmation',
|
||||
component: DeleteDraft,
|
||||
isHeadless: true,
|
||||
command: {
|
||||
universalIdentifier: 'b8c9d0e1-f2a3-4567-bcde-678901234567',
|
||||
label: 'Delete draft',
|
||||
icon: 'IconTrash',
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
#### Contesto di esecuzione
|
||||
|
||||
Ogni componente front riceve un contesto di esecuzione che fornisce informazioni su dove e come sta funzionando. Accedi ai valori del contesto usando gli hook di `twenty-sdk`:
|
||||
|
||||
| Hook | Tipo restituito | Descrizione |
|
||||
| ----------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `useFrontComponentId()` | `string` | L'ID univoco dell'istanza corrente del componente front |
|
||||
| `useRecordId()` | `string \| null` | L'ID del record corrente, quando il componente viene eseguito in un contesto di record (ad es., un widget di pagina record o un comando con ambito a un record). In caso contrario, restituisce `null`. |
|
||||
| `useUserId()` | `string \| null` | L'ID dell'utente corrente |
|
||||
|
||||
```typescript
|
||||
import { useRecordId, useUserId } from 'twenty-sdk';
|
||||
|
||||
const MyWidget = () => {
|
||||
const recordId = useRecordId();
|
||||
const userId = useUserId();
|
||||
|
||||
return (
|
||||
<div>
|
||||
<p>Record: {recordId ?? 'none'}</p>
|
||||
<p>User: {userId ?? 'anonymous'}</p>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
Il contesto è reattivo — se il record circostante cambia, gli hook restituiscono automaticamente i valori aggiornati.
|
||||
|
||||
#### Funzioni dell'API host
|
||||
|
||||
I componenti front vengono eseguiti in una sandbox isolata ma possono interagire con l'interfaccia di Twenty tramite un insieme di funzioni fornite dall'host. Importale direttamente da `twenty-sdk`:
|
||||
|
||||
```typescript
|
||||
import {
|
||||
navigate,
|
||||
closeSidePanel,
|
||||
enqueueSnackbar,
|
||||
unmountFrontComponent,
|
||||
openSidePanelPage,
|
||||
openCommandConfirmationModal,
|
||||
} from 'twenty-sdk';
|
||||
```
|
||||
|
||||
| Funzione | Firma | Descrizione |
|
||||
| ------------------------------ | -------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `naviga` | `(to, params?, queryParams?, options?) => Promise<void>` | Naviga verso un percorso tipizzato dell'app all'interno di Twenty |
|
||||
| `closeSidePanel` | `() => Promise<void>` | Chiudi il pannello laterale |
|
||||
| `enqueueSnackbar` | `(params) => Promise<void>` | Mostra una notifica snackbar. Parametri: `message`, `variant` (`'error'`, `'success'`, `'info'`, `'warning'`), `duration` opzionale, `detailedMessage`, `dedupeKey` |
|
||||
| `unmountFrontComponent` | `() => Promise<void>` | Smonta il componente front corrente (usato dai componenti headless per pulire dopo l'esecuzione) |
|
||||
| `openSidePanelPage` | `(params) => Promise<void>` | Apri una pagina nel pannello laterale. Parametri: `page`, `pageTitle`, `pageIcon`, `shouldResetSearchState` |
|
||||
| `openCommandConfirmationModal` | `(params) => Promise<'confirm' \| 'cancel'>` | Mostra una finestra modale di conferma e attende la risposta dell'utente. Parametri: `title`, `subtitle`, `confirmButtonText`, `confirmButtonAccent` (`'default'`, `'blue'`, `'danger'`) |
|
||||
|
||||
Ecco un esempio che usa l'API host per mostrare una snackbar e chiudere il pannello laterale dopo il completamento di un'azione:
|
||||
|
||||
```typescript
|
||||
import { defineFrontComponent, useRecordId } from 'twenty-sdk';
|
||||
import { enqueueSnackbar, closeSidePanel } from 'twenty-sdk';
|
||||
import { CoreApiClient } from 'twenty-sdk/clients';
|
||||
|
||||
const ArchiveRecord = () => {
|
||||
const recordId = useRecordId();
|
||||
|
||||
const handleArchive = async () => {
|
||||
const client = new CoreApiClient();
|
||||
|
||||
await client.mutation({
|
||||
updateTask: {
|
||||
__args: { id: recordId, data: { status: 'ARCHIVED' } },
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
await enqueueSnackbar({
|
||||
message: 'Record archived',
|
||||
variant: 'success',
|
||||
});
|
||||
|
||||
await closeSidePanel();
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ padding: '20px' }}>
|
||||
<p>Archive this record?</p>
|
||||
<button onClick={handleArchive}>Archive</button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default defineFrontComponent({
|
||||
universalIdentifier: 'c9d0e1f2-a3b4-5678-cdef-789012345678',
|
||||
name: 'archive-record',
|
||||
description: 'Archives the current record',
|
||||
component: ArchiveRecord,
|
||||
});
|
||||
```
|
||||
|
||||
### Abilità
|
||||
|
||||
Skills define reusable instructions and capabilities that AI agents can use within your workspace. Use `defineSkill()` to define skills with built-in validation:
|
||||
@@ -1123,7 +808,7 @@ You can create new skills in two ways:
|
||||
|
||||
### Agenti
|
||||
|
||||
Gli Agenti definiscono agenti IA con prompt di sistema che possono operare all'interno del tuo spazio di lavoro. Usa `defineAgent()` per definire agenti con convalida integrata:
|
||||
Agents define AI agents with system prompts that can operate within your workspace. Use `defineAgent()` to define agents with built-in validation:
|
||||
|
||||
```typescript
|
||||
// src/agents/example-agent.ts
|
||||
@@ -1145,27 +830,26 @@ export default defineAgent({
|
||||
|
||||
Punti chiave:
|
||||
|
||||
* `name` è una stringa identificativa univoca per l'agente (kebab-case consigliato).
|
||||
* `label` è il nome di visualizzazione leggibile mostrato nell'UI.
|
||||
* `prompt` contiene il prompt di sistema — è il testo di istruzioni che definisce il comportamento dell'agente.
|
||||
* `icon` (opzionale) imposta l'icona visualizzata nell'UI.
|
||||
* `description` (opzionale) fornisce contesto aggiuntivo sullo scopo dell'agente.
|
||||
* `name` is a unique identifier string for the agent (kebab-case recommended).
|
||||
* `label` is the human-readable display name shown in the UI.
|
||||
* `prompt` contains the system prompt — this is the instruction text that defines the agent's behavior.
|
||||
* `icon` (optional) sets the icon displayed in the UI.
|
||||
* `description` (optional) provides additional context about the agent's purpose.
|
||||
|
||||
Puoi creare nuovi agenti in due modi:
|
||||
You can create new agents in two ways:
|
||||
|
||||
* **Generata dallo scaffolder**: Esegui `yarn twenty entity:add` e scegli l'opzione per aggiungere un nuovo agente.
|
||||
* **Manuale**: Crea un nuovo file e usa `defineAgent()`, seguendo lo stesso schema.
|
||||
* **Scaffolded**: Run `yarn twenty entity:add` and choose the option to add a new agent.
|
||||
* **Manual**: Create a new file and use `defineAgent()`, following the same pattern.
|
||||
|
||||
### Client tipizzati generati
|
||||
|
||||
Due client tipizzati sono generati automaticamente da `yarn twenty app:dev` e salvati in `node_modules/twenty-sdk/clients` in base allo schema della tua area di lavoro:
|
||||
Due client tipizzati sono generati automaticamente da `yarn twenty app:dev` e salvati in `node_modules/twenty-sdk/generated` in base allo schema della tua area di lavoro:
|
||||
|
||||
* **`CoreApiClient`** — interroga l'endpoint `/graphql` per i dati dell'area di lavoro
|
||||
* **`MetadataApiClient`** — interroga l'endpoint `/metadata` per la configurazione dello spazio di lavoro e il caricamento dei file
|
||||
|
||||
```typescript
|
||||
import { CoreApiClient } from 'twenty-sdk/clients';
|
||||
import { MetadataApiClient } from 'twenty-sdk/clients';
|
||||
import { CoreApiClient, MetadataApiClient } from 'twenty-sdk/generated';
|
||||
|
||||
const client = new CoreApiClient();
|
||||
const { me } = await client.query({ me: { id: true, displayName: true } });
|
||||
@@ -1174,7 +858,7 @@ const metadataClient = new MetadataApiClient();
|
||||
const { currentWorkspace } = await metadataClient.query({ currentWorkspace: { id: true } });
|
||||
```
|
||||
|
||||
`CoreApiClient` viene rigenerato automaticamente da `yarn twenty app:dev` ogni volta che i tuoi oggetti o campi cambiano. `MetadataApiClient` è fornito pronto all'uso con l'SDK.
|
||||
Entrambi i client vengono rigenerati automaticamente da `yarn twenty app:dev` ogni volta che i tuoi oggetti o campi cambiano.
|
||||
|
||||
#### Credenziali di runtime nelle funzioni logiche
|
||||
|
||||
@@ -1191,10 +875,10 @@ Note:
|
||||
|
||||
#### Caricamento dei file
|
||||
|
||||
Il `MetadataApiClient` include un metodo `uploadFile` per allegare file ai campi di tipo file sugli oggetti del tuo spazio di lavoro. Poiché i client GraphQL standard non supportano nativamente il caricamento di file multipart, il client fornisce questo metodo dedicato che implementa la [specifica della richiesta GraphQL multipart](https://github.com/jaydenseric/graphql-multipart-request-spec) dietro le quinte.
|
||||
Il `MetadataApiClient` generato include un metodo `uploadFile` per allegare file ai campi di tipo file sugli oggetti del tuo spazio di lavoro. Poiché i client GraphQL standard non supportano nativamente il caricamento di file multipart, il client fornisce questo metodo dedicato che implementa la [specifica della richiesta GraphQL multipart](https://github.com/jaydenseric/graphql-multipart-request-spec) dietro le quinte.
|
||||
|
||||
```typescript
|
||||
import { MetadataApiClient } from 'twenty-sdk/clients';
|
||||
import { MetadataApiClient } from 'twenty-sdk/generated';
|
||||
import * as fs from 'fs';
|
||||
|
||||
const metadataClient = new MetadataApiClient();
|
||||
|
||||
@@ -15,18 +15,18 @@ Twenty è progettato per essere estensibile. Usa le nostre API, i webhook e il f
|
||||
|
||||
* **API**: Interroga e modifica i dati del tuo CRM in modo programmatico usando REST o GraphQL
|
||||
* **Webhook**: Ricevi notifiche in tempo reale quando si verificano eventi in Twenty
|
||||
* **App**: Crea applicazioni personalizzate che estendono le capacità di Twenty
|
||||
* **App**: Crea applicazioni personalizzate che estendono le capacità di Twenty - In arrivo!
|
||||
|
||||
## Per iniziare
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="API" icon="codice" href="/l/it/developers/extend/api">
|
||||
<Card title="API" icon="codice" href="/l/it/developers/extend/capabilities/apis">
|
||||
Connettiti a Twenty in modo programmatico
|
||||
</Card>
|
||||
<Card title="Webhooks" icon="bell" href="/l/it/developers/extend/webhooks">
|
||||
<Card title="Webhooks" icon="bell" href="/l/it/developers/extend/capabilities/webhooks">
|
||||
Ricevi notifiche sugli eventi in tempo reale
|
||||
</Card>
|
||||
<Card title="App" icon="puzzle-piece" href="/l/it/developers/extend/apps/getting-started">
|
||||
Crea personalizzazioni come codice
|
||||
<Card title="App" icon="puzzle-piece" href="/l/it/developers/extend/capabilities/apps">
|
||||
Crea personalizzazioni come codice (Alpha)
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
---
|
||||
title: Webhooks
|
||||
description: Ricevi notifiche in tempo reale quando si verificano eventi nel tuo CRM.
|
||||
---
|
||||
|
||||
import { VimeoEmbed } from '/snippets/vimeo-embed.mdx';
|
||||
|
||||
I webhook inviano dati ai tuoi sistemi in tempo reale quando si verificano eventi in Twenty — senza necessità di polling. Usali per mantenere sincronizzati i sistemi esterni, attivare automazioni o inviare avvisi.
|
||||
|
||||
## Crea un Webhook
|
||||
|
||||
1. Vai a **Impostazioni → API e Webhook → Webhook**
|
||||
2. Clicca su **+ Crea webhook**
|
||||
3. Inserisci l'URL del tuo webhook (deve essere pubblicamente accessibile)
|
||||
4. Clicca su **Salva**
|
||||
|
||||
Il webhook si attiva immediatamente e inizia a inviare notifiche.
|
||||
|
||||
<VimeoEmbed videoId="928786708" title="Creazione di un webhook" />
|
||||
|
||||
### Gestisci Webhook
|
||||
|
||||
**Modifica**: Fai clic sul webhook → Aggiorna URL → **Salva**
|
||||
|
||||
**Elimina**: Fai clic sul webhook → **Elimina** → Conferma
|
||||
|
||||
## Eventi
|
||||
|
||||
Twenty invia webhook per questi tipi di eventi:
|
||||
|
||||
| Evento | Esempio |
|
||||
| --------------------- | ---------------------------------------------------------- |
|
||||
| **Record creato** | `person.created`, `company.created`, `note.created` |
|
||||
| **Record aggiornato** | `person.updated`, `company.updated`, `opportunity.updated` |
|
||||
| **Record eliminato** | `person.deleted`, `company.deleted` |
|
||||
|
||||
Tutti i tipi di eventi vengono inviati all'URL del tuo webhook. Il filtraggio degli eventi potrebbe essere aggiunto nelle versioni future.
|
||||
|
||||
## Formato del payload
|
||||
|
||||
Ogni webhook invia una richiesta HTTP POST con un corpo JSON:
|
||||
|
||||
```json
|
||||
{
|
||||
"event": "person.created",
|
||||
"data": {
|
||||
"id": "abc12345",
|
||||
"firstName": "Alice",
|
||||
"lastName": "Doe",
|
||||
"email": "alice@example.com",
|
||||
"createdAt": "2025-02-10T15:30:45Z",
|
||||
"createdBy": "user_123"
|
||||
},
|
||||
"timestamp": "2025-02-10T15:30:50Z"
|
||||
}
|
||||
```
|
||||
|
||||
| Campo | Descrizione |
|
||||
| ----------- | ---------------------------------------------------------- |
|
||||
| `event` | Cosa è successo (ad es., `person.created`) |
|
||||
| `data` | Il record completo che è stato creato/aggiornato/eliminato |
|
||||
| `timestamp` | Quando si è verificato l'evento (UTC) |
|
||||
|
||||
<Note>
|
||||
Rispondi con uno **status HTTP 2xx** (200-299) per confermare la ricezione. Le risposte non 2xx vengono registrate come errori di consegna.
|
||||
</Note>
|
||||
|
||||
## Convalida del Webhook
|
||||
|
||||
Twenty firma ogni richiesta webhook per motivi di sicurezza. Convalida le firme per assicurarti che le richieste siano autentiche.
|
||||
|
||||
### Intestazioni
|
||||
|
||||
| Intestazione | Descrizione |
|
||||
| ---------------------------- | ------------------------- |
|
||||
| `X-Twenty-Webhook-Signature` | Firma HMAC SHA256 |
|
||||
| `X-Twenty-Webhook-Timestamp` | Timestamp della richiesta |
|
||||
|
||||
### Passaggi di convalida
|
||||
|
||||
1. Ottieni il timestamp da `X-Twenty-Webhook-Timestamp`
|
||||
2. Crea la stringa: `{timestamp}:{JSON payload}`
|
||||
3. Calcola HMAC SHA256 usando il segreto del tuo webhook
|
||||
4. Confronta con `X-Twenty-Webhook-Signature`
|
||||
|
||||
### Esempio (Node.js)
|
||||
|
||||
```javascript
|
||||
const crypto = require("crypto");
|
||||
|
||||
const timestamp = req.headers["x-twenty-webhook-timestamp"];
|
||||
const payload = JSON.stringify(req.body);
|
||||
const secret = "your-webhook-secret";
|
||||
|
||||
const stringToSign = `${timestamp}:${payload}`;
|
||||
const expectedSignature = crypto
|
||||
.createHmac("sha256", secret)
|
||||
.update(stringToSign)
|
||||
.digest("hex");
|
||||
|
||||
const receivedSignature = req.headers["x-twenty-webhook-signature"];
|
||||
const isValid = crypto.timingSafeEqual(
|
||||
Buffer.from(expectedSignature, "hex"),
|
||||
Buffer.from(receivedSignature, "hex")
|
||||
);
|
||||
```
|
||||
|
||||
## Webhooks vs Workflows
|
||||
|
||||
| Metodo | Direzione | Caso d'uso |
|
||||
| -------------------------------- | --------- | ------------------------------------------------------------------------ |
|
||||
| **Webhooks** | OUT | Notifica automaticamente ai sistemi esterni qualsiasi modifica ai record |
|
||||
| **Workflow + HTTP Request** | OUT | Invia dati in uscita con logica personalizzata (filtri, trasformazioni) |
|
||||
| **Trigger webhook del Workflow** | IN | Ricevi dati in Twenty da sistemi esterni |
|
||||
|
||||
Per la ricezione di dati esterni, vedi [Configura un trigger webhook](/l/it/user-guide/workflows/how-tos/connect-to-other-tools/set-up-a-webhook-trigger).
|
||||
@@ -149,8 +149,8 @@
|
||||
"extend": {
|
||||
"label": "Estendi",
|
||||
"groups": {
|
||||
"apps": {
|
||||
"label": "App"
|
||||
"extendCapabilities": {
|
||||
"label": "Funzionalità"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -24,7 +24,7 @@ Esporta i dati del tuo spazio di lavoro in CSV per backup, reportistica o migraz
|
||||
* Vengono esportate solo le **colonne visibili**
|
||||
* Vengono esportati solo i **record filtrati** (in base alla vista corrente)
|
||||
|
||||
<Note>Per esportazioni più grandi (oltre 20.000 record), usa i filtri per esportare a lotti oppure usa le [API](/l/it/developers/extend/api).</Note>
|
||||
<Note>Per esportazioni più grandi (oltre 20.000 record), usa i filtri per esportare a lotti oppure usa le [API](/l/it/developers/extend/capabilities/apis).</Note>
|
||||
|
||||
### Permessi
|
||||
|
||||
@@ -148,7 +148,7 @@ Le API non hanno un limite di record:
|
||||
2. Usa le API GraphQL per interrogare i record
|
||||
3. Elabora i risultati nella tua applicazione
|
||||
|
||||
Vedi: [Documentazione API](/l/it/developers/extend/api)
|
||||
Vedi: [Documentazione API](/l/it/developers/extend/capabilities/apis)
|
||||
|
||||
## Suggerimenti e buone pratiche
|
||||
|
||||
@@ -206,4 +206,4 @@ I file esportati possono contenere dati sensibili:
|
||||
|
||||
* [Come aggiornare i record esistenti](/l/it/user-guide/data-migration/how-tos/update-existing-records-via-import) — modifica e reimporta la tua esportazione
|
||||
* [Come importare i dati tramite API](/l/it/user-guide/data-migration/how-tos/import-data-via-api) — per set di dati di grandi dimensioni
|
||||
* [Documentazione API](/l/it/developers/extend/api) — crea flussi di lavoro di esportazione personalizzati
|
||||
* [Documentazione API](/l/it/developers/extend/capabilities/apis) — crea flussi di lavoro di esportazione personalizzati
|
||||
|
||||
@@ -57,10 +57,10 @@ Chiunque abbia la tua chiave API può accedere ai dati del tuo spazio di lavoro
|
||||
|
||||
Twenty supporta due tipi di API:
|
||||
|
||||
| API | Ideale per | Documentazione |
|
||||
| ----------- | ------------------------------------------------------------------ | -------------------------------------------- |
|
||||
| **GraphQL** | Query flessibili, recupero di dati correlati, operazioni complesse | [Documentazione API](/l/it/developers/extend/api) |
|
||||
| **REST** | Operazioni CRUD semplici, pattern REST familiari | [Documentazione API](/l/it/developers/extend/api) |
|
||||
| API | Ideale per | Documentazione |
|
||||
| ----------- | ------------------------------------------------------------------ | ---------------------------------------------------------- |
|
||||
| **GraphQL** | Query flessibili, recupero di dati correlati, operazioni complesse | [Documentazione API](/l/it/developers/extend/capabilities/apis) |
|
||||
| **REST** | Operazioni CRUD semplici, pattern REST familiari | [Documentazione API](/l/it/developers/extend/capabilities/apis) |
|
||||
|
||||
Entrambe le API supportano:
|
||||
|
||||
@@ -173,4 +173,4 @@ Contattaci a [contact@twenty.com](mailto:contact@twenty.com) oppure scopri i nos
|
||||
|
||||
Per i dettagli completi di implementazione, esempi di codice e riferimento allo schema:
|
||||
|
||||
* [Documentazione API](/l/it/developers/extend/api)
|
||||
* [Documentazione API](/l/it/developers/extend/capabilities/apis)
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@ L'open-source è la base del nostro approccio, garantendo che Twenty evolva con
|
||||
* **Dashboard:** Monitora le prestazioni con report e visualizzazioni personalizzati. [Visualizza le dashboard](/l/it/user-guide/dashboards/overview).
|
||||
* **Autorizzazioni e accesso:** Controlla chi può visualizzare, modificare e gestire i tuoi dati con autorizzazioni basate sui ruoli. [Configura l'accesso](/l/it/user-guide/permissions-access/overview).
|
||||
* **Note e attività:** Crea note e attività collegate ai tuoi record per una collaborazione migliore.
|
||||
* **API e Webhooks:** Connettiti ad altre app e crea integrazioni personalizzate. [Inizia a integrare](/l/it/developers/extend/api).
|
||||
* **API e Webhooks:** Connettiti ad altre app e crea integrazioni personalizzate. [Inizia a integrare](/l/it/developers/extend/capabilities/apis).
|
||||
|
||||
## Unisciti ora
|
||||
|
||||
|
||||
+1
-1
@@ -95,7 +95,7 @@ Crea i campi di destinazione in **Impostazioni → Modello dati → Opportunità
|
||||
* Dimensione aziendale: `{{searchRecords[0].employees}}`
|
||||
|
||||
<Note>
|
||||
**Limitazione di Attività e Note**: Le relazioni su Attività e Note sono codificate come molte-a-molte e non sono ancora disponibili nei trigger o nelle azioni dei flussi di lavoro. Per accedere a queste relazioni, usa invece le [API](/l/it/developers/extend/api).
|
||||
**Limitazione di Attività e Note**: Le relazioni su Attività e Note sono codificate come molte-a-molte e non sono ancora disponibili nei trigger o nelle azioni dei flussi di lavoro. Per accedere a queste relazioni, usa invece le [API](/l/it/developers/extend/capabilities/apis).
|
||||
</Note>
|
||||
|
||||
## Sincronizzazione bidirezionale
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
---
|
||||
title: 拡張
|
||||
description: API、Webhook、カスタムアプリで Twenty の機能を拡張できます。
|
||||
redirect: /developers/introduction
|
||||
---
|
||||
|
||||
<Frame>
|
||||
@@ -21,15 +20,15 @@ Twenty は拡張性を念頭に設計されています。 当社の API、Webho
|
||||
## 始めに
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="API" icon="コード" href="/l/ja/developers/api">
|
||||
<Card title="API" icon="コード" href="/l/ja/developers/extend/capabilities/apis">
|
||||
プログラムから Twenty に接続
|
||||
</Card>
|
||||
|
||||
<Card title="ウェブフック" icon="bell" href="/l/ja/developers/webhooks">
|
||||
<Card title="ウェブフック" icon="bell" href="/l/ja/developers/extend/capabilities/webhooks">
|
||||
イベントの通知をリアルタイムで受け取る
|
||||
</Card>
|
||||
|
||||
<Card title="アプリ" icon="puzzle-piece" href="/l/ja/developers/apps/apps">
|
||||
<Card title="アプリ" icon="puzzle-piece" href="/l/ja/developers/extend/capabilities/apps">
|
||||
カスタマイズをコードとして構築(アルファ版)
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
@@ -1,33 +1,23 @@
|
||||
---
|
||||
title: 始めに
|
||||
description: Twenty 開発者ドキュメントへようこそ。Twenty の拡張、セルフホスティング、貢献のためのリソースです。
|
||||
description: Welcome to Twenty Developer Documentation, your resources for extending, self-hosting, and contributing to Twenty.
|
||||
---
|
||||
|
||||
import { CardTitle } from "/snippets/card-title.mdx"
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card href="/l/ja/developers/api" icon="code">
|
||||
<CardTitle>API</CardTitle>
|
||||
REST または GraphQL で CRM データをクエリおよび変更します。
|
||||
<CardGroup cols={3}>
|
||||
<Card href="/l/ja/developers/extend/extend" img="/images/user-guide/integrations/plug.png">
|
||||
<CardTitle>Extend</CardTitle>
|
||||
Build integrations with APIs, webhooks, and custom apps.
|
||||
</Card>
|
||||
|
||||
<Card href="/l/ja/developers/webhooks" icon="bell">
|
||||
<CardTitle>Webhooks</CardTitle>
|
||||
イベント発生時にリアルタイムで通知を受け取ります。
|
||||
</Card>
|
||||
|
||||
<Card href="/l/ja/developers/apps/apps" icon="puzzle-piece">
|
||||
<CardTitle>Apps</CardTitle>
|
||||
Twenty の機能を拡張するカスタムアプリケーションを構築します。
|
||||
</Card>
|
||||
|
||||
<Card href="/l/ja/developers/self-host/self-host" icon="desktop">
|
||||
<Card href="/l/ja/developers/self-host/self-host" img="/images/user-guide/what-is-twenty/20.png">
|
||||
<CardTitle>Self-Host</CardTitle>
|
||||
ご自身のインフラストラクチャで Twenty をデプロイおよび管理します。
|
||||
Deploy and manage Twenty on your own infrastructure.
|
||||
</Card>
|
||||
|
||||
<Card href="/l/ja/developers/contribute/contribute" icon="github">
|
||||
<Card href="/l/ja/developers/contribute/contribute" img="/images/user-guide/github/github-header.png">
|
||||
<CardTitle>Contribute</CardTitle>
|
||||
オープンソースコミュニティに参加し、Twenty に貢献しましょう。
|
||||
Join our open-source community and contribute to Twenty.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
@@ -24,7 +24,7 @@ import { VimeoEmbed } from '/snippets/vimeo-embed.mdx';
|
||||
* **表示されている列**のみがエクスポートされます
|
||||
* **フィルターで絞り込まれたレコード**のみがエクスポートされます(現在のビューに基づきます)
|
||||
|
||||
<Note>大規模なエクスポート(20,000 件超)では、フィルターを使ってバッチに分けてエクスポートするか、[API](/l/ja/developers/api) を使用してください。</Note>
|
||||
<Note>大規模なエクスポート(20,000 件超)では、フィルターを使ってバッチに分けてエクスポートするか、[API](/l/ja/developers/extend/capabilities/apis) を使用してください。</Note>
|
||||
|
||||
### 権限
|
||||
|
||||
@@ -148,7 +148,7 @@ API にはレコード数の上限がありません:
|
||||
2. GraphQL API を使用してレコードをクエリします
|
||||
3. アプリケーションで結果を処理
|
||||
|
||||
参照:[API ドキュメント](/l/ja/developers/api)
|
||||
参照:[API ドキュメント](/l/ja/developers/extend/capabilities/apis)
|
||||
|
||||
## ヒントとベストプラクティス
|
||||
|
||||
@@ -206,4 +206,4 @@ API にはレコード数の上限がありません:
|
||||
|
||||
* [既存レコードを更新する方法](/l/ja/user-guide/data-migration/how-tos/update-existing-records-via-import) — エクスポートを編集して再インポート
|
||||
* [API でデータをインポートする方法](/l/ja/user-guide/data-migration/how-tos/import-data-via-api) — 大規模データセット向け
|
||||
* [API ドキュメント](/l/ja/developers/api) — カスタムのエクスポートワークフローを構築
|
||||
* [API ドキュメント](/l/ja/developers/extend/capabilities/apis) — カスタムのエクスポートワークフローを構築
|
||||
|
||||
@@ -59,8 +59,8 @@ Twenty は 2 種類の API をサポートしています:
|
||||
|
||||
| API | 最適な用途 | ドキュメント |
|
||||
| ----------- | ------------------------------ | -------------------------------------------------- |
|
||||
| **GraphQL** | 柔軟なクエリ、関連データの取得、複雑な操作に最適 | [API ドキュメント](/l/ja/developers/api) |
|
||||
| **REST** | シンプルな CRUD 操作、馴染みのある REST パターン | [API ドキュメント](/l/ja/developers/api) |
|
||||
| **GraphQL** | 柔軟なクエリ、関連データの取得、複雑な操作に最適 | [API ドキュメント](/l/ja/developers/extend/capabilities/apis) |
|
||||
| **REST** | シンプルな CRUD 操作、馴染みのある REST パターン | [API ドキュメント](/l/ja/developers/extend/capabilities/apis) |
|
||||
|
||||
両方の API でサポートされる内容:
|
||||
|
||||
@@ -173,4 +173,4 @@ GraphQL API は **バッチ アップサート**をサポートしています
|
||||
|
||||
実装の詳細、コード例、スキーマリファレンスについては次を参照してください:
|
||||
|
||||
* [API ドキュメント](/l/ja/developers/api)
|
||||
* [API ドキュメント](/l/ja/developers/extend/capabilities/apis)
|
||||
|
||||
+1
-1
@@ -39,7 +39,7 @@ description: Twenty is an open-source CRM that gives you the building blocks to
|
||||
* **ダッシュボード:** カスタムレポートや可視化でパフォーマンスを追跡します。 [ダッシュボードを表示](/l/ja/user-guide/dashboards/overview)。
|
||||
* **権限とアクセス:** ロールベースの権限で、誰がデータを閲覧、編集、管理できるかを制御します。 [アクセスを設定](/l/ja/user-guide/permissions-access/overview)。
|
||||
* **ノートとタスク:** より良いコラボレーションのために、レコードに関連付けられたノートやタスクを作成します。
|
||||
* **APIおよびWebhooks:** 他のアプリと接続し、カスタム統合を構築します。 [統合を開始](/l/ja/developers/api).
|
||||
* **APIおよびWebhooks:** 他のアプリと接続し、カスタム統合を構築します。 [統合を開始](/l/ja/developers/extend/capabilities/apis).
|
||||
|
||||
## 今すぐ参加
|
||||
|
||||
|
||||
+1
-1
@@ -95,7 +95,7 @@ description: ワークフローを使用して、関連レコードのデータ
|
||||
* 会社規模: `{{searchRecords[0].employees}}`
|
||||
|
||||
<Note>
|
||||
**タスクとノートの制限**: タスクとノートのリレーションは多対多としてハードコードされており、ワークフローのトリガーやアクションではまだ使用できません。 これらのリレーションにアクセスするには、代わりに[API](/l/ja/developers/api)を使用してください。
|
||||
**タスクとノートの制限**: タスクとノートのリレーションは多対多としてハードコードされており、ワークフローのトリガーやアクションではまだ使用できません。 これらのリレーションにアクセスするには、代わりに[API](/l/ja/developers/extend/capabilities/apis)を使用してください。
|
||||
</Note>
|
||||
|
||||
## 双方向同期
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
---
|
||||
title: 확장
|
||||
description: API, 웹훅 및 맞춤형 앱으로 Twenty의 기능을 확장하세요.
|
||||
redirect: /developers/introduction
|
||||
---
|
||||
|
||||
<Frame>
|
||||
@@ -21,15 +20,15 @@ Twenty는 확장 가능하도록 설계되었습니다. 당사의 API, 웹훅
|
||||
## 시작하기
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="API" icon="코드" href="/l/ko/developers/api">
|
||||
<Card title="API" icon="코드" href="/l/ko/developers/extend/capabilities/apis">
|
||||
프로그래밍 방식으로 Twenty에 연결하세요
|
||||
</Card>
|
||||
|
||||
<Card title="웹훅" icon="bell" href="/l/ko/developers/webhooks">
|
||||
<Card title="웹훅" icon="bell" href="/l/ko/developers/extend/capabilities/webhooks">
|
||||
이벤트에 대한 실시간 알림을 받으세요
|
||||
</Card>
|
||||
|
||||
<Card title="앱" icon="puzzle-piece" href="/l/ko/developers/apps/apps">
|
||||
<Card title="앱" icon="puzzle-piece" href="/l/ko/developers/extend/capabilities/apps">
|
||||
코드로 사용자 지정을 구축하세요(알파)
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
@@ -5,28 +5,18 @@ description: Twenty 개발자 문서에 오신 것을 환영합니다. 이 문
|
||||
|
||||
import { CardTitle } from "/snippets/card-title.mdx"
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card href="/l/ko/developers/api" icon="code">
|
||||
<CardTitle>API</CardTitle>
|
||||
REST 또는 GraphQL로 CRM 데이터를 쿼리하고 수정합니다.
|
||||
<CardGroup cols={3}>
|
||||
<Card href="/l/ko/developers/extend/extend" img="/images/user-guide/integrations/plug.png">
|
||||
<CardTitle>확장</CardTitle>
|
||||
API, 웹훅 및 맞춤형 앱과의 통합을 구축하세요.
|
||||
</Card>
|
||||
|
||||
<Card href="/l/ko/developers/webhooks" icon="bell">
|
||||
<CardTitle>Webhooks</CardTitle>
|
||||
이벤트 발생 시 실시간 알림을 받습니다.
|
||||
</Card>
|
||||
|
||||
<Card href="/l/ko/developers/apps/apps" icon="puzzle-piece">
|
||||
<CardTitle>Apps</CardTitle>
|
||||
Twenty의 기능을 확장하는 맞춤형 애플리케이션을 구축하세요.
|
||||
</Card>
|
||||
|
||||
<Card href="/l/ko/developers/self-host/self-host" icon="desktop">
|
||||
<Card href="/l/ko/developers/self-host/self-host" img="/images/user-guide/what-is-twenty/20.png">
|
||||
<CardTitle>자체 호스팅</CardTitle>
|
||||
자체 인프라에 Twenty를 배포하고 관리하세요.
|
||||
</Card>
|
||||
|
||||
<Card href="/l/ko/developers/contribute/contribute" icon="github">
|
||||
<Card href="/l/ko/developers/contribute/contribute" img="/images/user-guide/github/github-header.png">
|
||||
<CardTitle>기여</CardTitle>
|
||||
오픈 소스 커뮤니티에 참여하고 Twenty에 기여하세요.
|
||||
</Card>
|
||||
|
||||
@@ -24,7 +24,7 @@ import { VimeoEmbed } from '/snippets/vimeo-embed.mdx';
|
||||
* **표시된 열**만 내보내집니다
|
||||
* **필터링된 레코드**만 내보내집니다(현재 보기 기준)
|
||||
|
||||
<Note>더 큰 내보내기(20,000개 이상의 레코드)에는 필터를 사용해 배치로 내보내거나 [API](/l/ko/developers/api)를 사용하세요.</Note>
|
||||
<Note>더 큰 내보내기(20,000개 이상의 레코드)에는 필터를 사용해 배치로 내보내거나 [API](/l/ko/developers/extend/capabilities/apis)를 사용하세요.</Note>
|
||||
|
||||
### 권한
|
||||
|
||||
@@ -148,7 +148,7 @@ API에는 레코드 수 한도가 없습니다:
|
||||
2. GraphQL API를 사용해 레코드를 쿼리하세요
|
||||
3. 애플리케이션에서 결과를 처리하세요
|
||||
|
||||
참고: [API 문서](/l/ko/developers/api)
|
||||
참고: [API 문서](/l/ko/developers/extend/capabilities/apis)
|
||||
|
||||
## 팁 및 모범 사례
|
||||
|
||||
@@ -206,4 +206,4 @@ API에는 레코드 수 한도가 없습니다:
|
||||
|
||||
* [기존 레코드를 업데이트하는 방법](/l/ko/user-guide/data-migration/how-tos/update-existing-records-via-import) — 내보낸 파일을 편집한 뒤 다시 가져오세요
|
||||
* [API로 데이터 가져오는 방법](/l/ko/user-guide/data-migration/how-tos/import-data-via-api) — 대용량 데이터셋용
|
||||
* [API 문서](/l/ko/developers/api) — 맞춤 내보내기 워크플로우를 구축하세요
|
||||
* [API 문서](/l/ko/developers/extend/capabilities/apis) — 맞춤 내보내기 워크플로우를 구축하세요
|
||||
|
||||
@@ -59,8 +59,8 @@ Twenty는 두 가지 유형의 API를 지원합니다:
|
||||
|
||||
| API | 적합한 용도 | 문서 |
|
||||
| ----------- | ----------------------------- | ---------------------------------------------- |
|
||||
| **GraphQL** | 유연한 쿼리, 연관 데이터 조회, 복잡한 작업에 적합 | [API 문서](/l/ko/developers/api) |
|
||||
| **REST** | 단순한 CRUD 작업, 익숙한 REST 패턴 | [API 문서](/l/ko/developers/api) |
|
||||
| **GraphQL** | 유연한 쿼리, 연관 데이터 조회, 복잡한 작업에 적합 | [API 문서](/l/ko/developers/extend/capabilities/apis) |
|
||||
| **REST** | 단순한 CRUD 작업, 익숙한 REST 패턴 | [API 문서](/l/ko/developers/extend/capabilities/apis) |
|
||||
|
||||
두 API 모두 다음을 지원합니다:
|
||||
|
||||
@@ -173,4 +173,4 @@ GraphQL API는 **배치 업서트**를 지원합니다 — 레코드가 있으
|
||||
|
||||
전체 구현 세부정보, 코드 예제, 스키마 참조는 다음을 확인하세요:
|
||||
|
||||
* [API 문서](/l/ko/developers/api)
|
||||
* [API 문서](/l/ko/developers/extend/capabilities/apis)
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@ description: Twenty는 비즈니스에 필요한 것을 정확히 만들 수 있
|
||||
* **대시보드:** 맞춤형 보고서와 시각화를 통해 성과를 추적하세요. [대시보드 보기](/l/ko/user-guide/dashboards/overview).
|
||||
* **권한 및 액세스:** 역할 기반 권한을 통해 누가 데이터를 보기, 편집, 관리할 수 있는지 제어하세요. [액세스 구성](/l/ko/user-guide/permissions-access/overview).
|
||||
* **노트 및 작업:** 더 나은 협업을 위해 레코드에 연결된 노트와 작업을 생성하세요.
|
||||
* **API 및 웹훅:** 다른 앱과 연결하고 맞춤형 통합을 구축하세요. [통합 시작하기](/l/ko/developers/api).
|
||||
* **API 및 웹훅:** 다른 앱과 연결하고 맞춤형 통합을 구축하세요. [통합 시작하기](/l/ko/developers/extend/capabilities/apis).
|
||||
|
||||
## 지금 가입하세요
|
||||
|
||||
|
||||
+1
-1
@@ -95,7 +95,7 @@ description: "워크플로우를 사용해 관련 레코드의 데이터를 표
|
||||
* 회사 규모: `{{searchRecords[0].employees}}`
|
||||
|
||||
<Note>
|
||||
**작업 및 노트 제한 사항**: 작업과 노트의 관계는 다대다로 하드코딩되어 있으며, 워크플로우 트리거 또는 액션에서 아직 사용할 수 없습니다. 이러한 관계에 액세스하려면 대신 [API](/l/ko/developers/api)를 사용하세요.
|
||||
**작업 및 노트 제한 사항**: 작업과 노트의 관계는 다대다로 하드코딩되어 있으며, 워크플로우 트리거 또는 액션에서 아직 사용할 수 없습니다. 이러한 관계에 액세스하려면 대신 [API](/l/ko/developers/extend/capabilities/apis)를 사용하세요.
|
||||
</Note>
|
||||
|
||||
## 양방향 동기화
|
||||
|
||||
@@ -1,147 +0,0 @@
|
||||
---
|
||||
title: APIs
|
||||
description: Consulte e modifique seus dados de CRM programaticamente usando REST ou GraphQL.
|
||||
---
|
||||
|
||||
import { VimeoEmbed } from '/snippets/vimeo-embed.mdx';
|
||||
|
||||
O Twenty foi desenvolvido para ser amigável ao desenvolvedor, oferecendo APIs poderosas que se adaptam ao seu modelo de dados personalizado. Oferecemos quatro tipos distintos de API para atender diferentes necessidades de integração.
|
||||
|
||||
## Abordagem Focada no Desenvolvedor
|
||||
|
||||
Twenty gera APIs especificamente para o seu modelo de dados:
|
||||
|
||||
* **Nenhum ID longo necessário**: Use os nomes dos seus objetos e campos diretamente nos endpoints
|
||||
* **Objetos padrão e personalizados tratados igualmente**: Seus objetos personalizados recebem o mesmo tratamento de API que os incorporados
|
||||
* **Endpoints dedicados**: Cada objeto e campo tem seu próprio endpoint de API
|
||||
* **Documentação personalizada**: Gerada especificamente para o modelo de dados do seu workspace
|
||||
|
||||
<Note>
|
||||
Sua documentação de API personalizada fica disponível em **Configurações → API & Webhooks** após criar uma chave de API. Como o Twenty gera APIs que correspondem ao seu modelo de dados personalizado, a documentação é exclusiva do seu workspace.
|
||||
</Note>
|
||||
|
||||
## Os dois tipos de API
|
||||
|
||||
### Core API
|
||||
|
||||
Acessada em `/rest/` ou `/graphql/`
|
||||
|
||||
Trabalhe com seus **registros** (os dados):
|
||||
|
||||
* Criar, ler, atualizar e excluir Pessoas, Empresas, Oportunidades, etc.
|
||||
* Consultar e filtrar dados
|
||||
* Gerenciar relações de registros
|
||||
|
||||
### Metadata API
|
||||
|
||||
Acessada em `/rest/metadata/` ou `/metadata/`
|
||||
|
||||
Gerencie seu **workspace e modelo de dados**:
|
||||
|
||||
* Criar, modificar ou excluir objetos e campos
|
||||
* Configurar as configurações do workspace
|
||||
* Defina relacionamentos entre objetos
|
||||
|
||||
## REST vs GraphQL
|
||||
|
||||
As APIs Core e Metadata estão disponíveis nos formatos REST e GraphQL:
|
||||
|
||||
| Formato | Operações disponíveis |
|
||||
| ----------- | --------------------------------------------------------------------------------- |
|
||||
| **REST** | CRUD, operações em lote, upserts |
|
||||
| **GraphQL** | Os mesmos + **upserts em lote**, consultas de relacionamento em uma única chamada |
|
||||
|
||||
Escolha com base nas suas necessidades — ambos os formatos acessam os mesmos dados.
|
||||
|
||||
## Endpoints de API
|
||||
|
||||
| Ambiente | URL base |
|
||||
| ------------------ | ------------------------- |
|
||||
| **Nuvem** | `https://api.twenty.com/` |
|
||||
| **Auto-hospedado** | `https://{your-domain}/` |
|
||||
|
||||
## Autenticação
|
||||
|
||||
Toda solicitação de API requer uma chave de API no cabeçalho:
|
||||
|
||||
```
|
||||
Authorization: Bearer YOUR_API_KEY
|
||||
```
|
||||
|
||||
### Criar uma Chave de API
|
||||
|
||||
1. Vá para **Configurações → APIs & Webhooks**
|
||||
2. Clique em **+ Criar chave**
|
||||
3. Configurar:
|
||||
* **Nome**: Nome descritivo para a chave
|
||||
* **Data de expiração**: Quando a chave expira
|
||||
4. Clique em **Salvar**
|
||||
5. **Copie imediatamente** — a chave é exibida apenas uma vez
|
||||
|
||||
<VimeoEmbed videoId="928786722" title="Criando chave de API" />
|
||||
|
||||
<Warning>
|
||||
Sua chave de API concede acesso a dados confidenciais. Não a compartilhe com serviços não confiáveis. Se for comprometida, desative-a imediatamente e gere uma nova.
|
||||
</Warning>
|
||||
|
||||
### Atribuir uma função a uma chave de API
|
||||
|
||||
Para maior segurança, atribua uma função específica para limitar o acesso:
|
||||
|
||||
1. Vá para **Configurações → Funções**
|
||||
2. Clique na função que deseja atribuir
|
||||
3. Abra a aba de **Atribuição**
|
||||
4. Em **Chaves de API**, clique em **+ Atribuir à chave de API**
|
||||
5. Selecione a chave de API
|
||||
|
||||
A chave herdará as permissões dessa função. Veja [Permissões](/l/pt/user-guide/permissions-access/capabilities/permissions) para obter detalhes.
|
||||
|
||||
### Gerenciar Chaves de API
|
||||
|
||||
**Regenerar**: Configurações → APIs & Webhooks → Clique na chave → **Regenerar**
|
||||
|
||||
**Excluir**: Configurações → APIs & Webhooks → Clique na chave → **Excluir**
|
||||
|
||||
## Playground de API
|
||||
|
||||
Teste suas APIs diretamente no navegador com nosso playground integrado — disponível tanto para **REST** quanto para **GraphQL**.
|
||||
|
||||
### Acesse o Playground
|
||||
|
||||
1. Vá para **Configurações → APIs & Webhooks**
|
||||
2. Crie uma chave de API (obrigatório)
|
||||
3. Clique em **REST API** ou **GraphQL API** para abrir o playground
|
||||
|
||||
### O que você obtém
|
||||
|
||||
* **Documentação interativa**: Gerada para o seu modelo de dados específico
|
||||
* **Testes ao vivo**: Execute chamadas de API reais no seu workspace
|
||||
* **Explorador de esquema**: Navegue pelos objetos, campos e relacionamentos disponíveis
|
||||
* **Construtor de solicitações**: Construa consultas com preenchimento automático
|
||||
|
||||
O playground reflete seus objetos e campos personalizados, portanto, a documentação está sempre precisa para o seu workspace.
|
||||
|
||||
## Operações em Lote
|
||||
|
||||
Tanto REST quanto GraphQL suportam operações em lote:
|
||||
|
||||
* **Tamanho do lote**: Até 60 registros por requisição
|
||||
* **Operações**: Criar, atualizar e excluir vários registros
|
||||
|
||||
**Recursos exclusivos do GraphQL:**
|
||||
|
||||
* **Upsert em lote**: Criar ou atualizar em uma única chamada
|
||||
* Use nomes de objetos no plural (por exemplo, `CreateCompanies` em vez de `CreateCompany`)
|
||||
|
||||
## Limites de taxa
|
||||
|
||||
As solicitações de API são limitadas para garantir a estabilidade da plataforma:
|
||||
|
||||
| Limite | Valor |
|
||||
| ------------------- | ------------------------ |
|
||||
| **Solicitações** | 100 chamadas por minuto |
|
||||
| **Tamanho do lote** | 60 registros por chamada |
|
||||
|
||||
<Tip>
|
||||
Use operações em lote para maximizar a taxa de transferência — processe até 60 registros em uma única chamada de API em vez de fazer solicitações individuais.
|
||||
</Tip>
|
||||
@@ -1,689 +0,0 @@
|
||||
---
|
||||
title: Criando aplicativos
|
||||
description: Defina objetos, funções de lógica, componentes de front-end e muito mais com o SDK da Twenty.
|
||||
---
|
||||
|
||||
<Warning>
|
||||
Os aplicativos estão atualmente em testes alfa. O recurso é funcional, mas ainda está evoluindo.
|
||||
</Warning>
|
||||
|
||||
## Use os recursos do SDK (tipos e configuração)
|
||||
|
||||
O twenty-sdk fornece blocos de construção tipados e funções utilitárias que você usa dentro do seu aplicativo. A seguir estão as partes principais que você usará com mais frequência.
|
||||
|
||||
### Funções utilitárias
|
||||
|
||||
O SDK fornece funções utilitárias para definir as entidades do seu app. Conforme descrito em [Detecção de entidades](/l/pt/developers/extend/apps/getting-started#entity-detection), você deve usar `export default define<Entity>({...})` para que suas entidades sejam detectadas:
|
||||
|
||||
| Função | Finalidade |
|
||||
| -------------------------------- | ------------------------------------------------------------------ |
|
||||
| `defineApplication` | Configurar metadados do aplicativo (obrigatório, um por app) |
|
||||
| `defineObject` | Define objetos personalizados com campos |
|
||||
| `defineLogicFunction` | Defina funções de lógica com handlers |
|
||||
| `definePreInstallLogicFunction` | Defina uma função de lógica de pré-instalação (uma por aplicativo) |
|
||||
| `definePostInstallLogicFunction` | Defina uma função de lógica de pós-instalação (uma por aplicativo) |
|
||||
| `defineFrontComponent` | Definir componentes de front-end para UI personalizada |
|
||||
| `defineRole` | Configura permissões de papéis e acesso a objetos |
|
||||
| `defineField` | Estender objetos existentes com campos adicionais |
|
||||
| `defineView` | Define visualizações salvas para objetos |
|
||||
| `defineNavigationMenuItem` | Define links de navegação da barra lateral |
|
||||
| `defineSkill` | Define habilidades de agente de IA |
|
||||
|
||||
Essas funções validam sua configuração em tempo de compilação e oferecem autocompletar na IDE e segurança de tipos.
|
||||
|
||||
### Definindo objetos
|
||||
|
||||
Objetos personalizados descrevem tanto o esquema quanto o comportamento de registros no seu espaço de trabalho. Use `defineObject()` para definir objetos com validação integrada:
|
||||
|
||||
```typescript
|
||||
// src/app/postCard.object.ts
|
||||
import { defineObject, FieldType } from 'twenty-sdk';
|
||||
|
||||
enum PostCardStatus {
|
||||
DRAFT = 'DRAFT',
|
||||
SENT = 'SENT',
|
||||
DELIVERED = 'DELIVERED',
|
||||
RETURNED = 'RETURNED',
|
||||
}
|
||||
|
||||
export default defineObject({
|
||||
universalIdentifier: '54b589ca-eeed-4950-a176-358418b85c05',
|
||||
nameSingular: 'postCard',
|
||||
namePlural: 'postCards',
|
||||
labelSingular: 'Post Card',
|
||||
labelPlural: 'Post Cards',
|
||||
description: 'A post card object',
|
||||
icon: 'IconMail',
|
||||
fields: [
|
||||
{
|
||||
universalIdentifier: '58a0a314-d7ea-4865-9850-7fb84e72f30b',
|
||||
name: 'content',
|
||||
type: FieldType.TEXT,
|
||||
label: 'Content',
|
||||
description: "Postcard's content",
|
||||
icon: 'IconAbc',
|
||||
},
|
||||
{
|
||||
universalIdentifier: 'c6aa31f3-da76-4ac6-889f-475e226009ac',
|
||||
name: 'recipientName',
|
||||
type: FieldType.FULL_NAME,
|
||||
label: 'Recipient name',
|
||||
icon: 'IconUser',
|
||||
},
|
||||
{
|
||||
universalIdentifier: '95045777-a0ad-49ec-98f9-22f9fc0c8266',
|
||||
name: 'recipientAddress',
|
||||
type: FieldType.ADDRESS,
|
||||
label: 'Recipient address',
|
||||
icon: 'IconHome',
|
||||
},
|
||||
{
|
||||
universalIdentifier: '87b675b8-dd8c-4448-b4ca-20e5a2234a1e',
|
||||
name: 'status',
|
||||
type: FieldType.SELECT,
|
||||
label: 'Status',
|
||||
icon: 'IconSend',
|
||||
defaultValue: `'${PostCardStatus.DRAFT}'`,
|
||||
options: [
|
||||
{ value: PostCardStatus.DRAFT, label: 'Draft', position: 0, color: 'gray' },
|
||||
{ value: PostCardStatus.SENT, label: 'Sent', position: 1, color: 'orange' },
|
||||
{ value: PostCardStatus.DELIVERED, label: 'Delivered', position: 2, color: 'green' },
|
||||
{ value: PostCardStatus.RETURNED, label: 'Returned', position: 3, color: 'orange' },
|
||||
],
|
||||
},
|
||||
{
|
||||
universalIdentifier: 'e06abe72-5b44-4e7f-93be-afc185a3c433',
|
||||
name: 'deliveredAt',
|
||||
type: FieldType.DATE_TIME,
|
||||
label: 'Delivered at',
|
||||
icon: 'IconCheck',
|
||||
isNullable: true,
|
||||
defaultValue: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Pontos-chave:
|
||||
|
||||
* Use `defineObject()` para validação integrada e melhor suporte na IDE.
|
||||
* O `universalIdentifier` deve ser exclusivo e estável entre implantações.
|
||||
* Cada campo requer `name`, `type`, `label` e seu próprio `universalIdentifier` estável.
|
||||
* O array `fields` é opcional — você pode definir objetos sem campos personalizados.
|
||||
* Você pode criar novos objetos usando `yarn twenty entity:add`, que orienta você sobre nomeação, campos e relacionamentos.
|
||||
|
||||
<Note>
|
||||
**Os campos base são criados automaticamente.** Quando você define um objeto personalizado, o Twenty adiciona automaticamente campos padrão
|
||||
como `id`, `name`, `createdAt`, `updatedAt`, `createdBy`, `updatedBy` e `deletedAt`.
|
||||
Você não precisa definir esses no seu array `fields` — adicione apenas seus campos personalizados.
|
||||
Você pode substituir os campos padrão definindo um campo com o mesmo nome no seu array `fields`,
|
||||
mas isso não é recomendado.
|
||||
</Note>
|
||||
|
||||
### Configuração do aplicativo (application-config.ts)
|
||||
|
||||
Todo aplicativo tem um único arquivo `application-config.ts` que descreve:
|
||||
|
||||
* **O que é o aplicativo**: identificadores, nome de exibição e descrição.
|
||||
* **Como suas funções são executadas**: qual papel usam para permissões.
|
||||
* **Variáveis (opcional)**: pares chave–valor expostos às suas funções como variáveis de ambiente.
|
||||
* **(Opcional) função de pré-instalação**: uma função de lógica que é executada antes da instalação do aplicativo.
|
||||
* **(Opcional) função de pós-instalação**: uma função de lógica que é executada após a instalação do aplicativo.
|
||||
|
||||
Use `defineApplication()` para definir a configuração do seu aplicativo:
|
||||
|
||||
```typescript
|
||||
// src/application-config.ts
|
||||
import { defineApplication } from 'twenty-sdk';
|
||||
import { DEFAULT_ROLE_UNIVERSAL_IDENTIFIER } from 'src/roles/default-role';
|
||||
|
||||
export default defineApplication({
|
||||
universalIdentifier: '4ec0391d-18d5-411c-b2f3-266ddc1c3ef7',
|
||||
displayName: 'My Twenty App',
|
||||
description: 'My first Twenty app',
|
||||
icon: 'IconWorld',
|
||||
applicationVariables: {
|
||||
DEFAULT_RECIPIENT_NAME: {
|
||||
universalIdentifier: '19e94e59-d4fe-4251-8981-b96d0a9f74de',
|
||||
description: 'Default recipient name for postcards',
|
||||
value: 'Jane Doe',
|
||||
isSecret: false,
|
||||
},
|
||||
},
|
||||
defaultRoleUniversalIdentifier: DEFAULT_ROLE_UNIVERSAL_IDENTIFIER,
|
||||
});
|
||||
```
|
||||
|
||||
Notas:
|
||||
|
||||
* `universalIdentifier` são IDs determinísticos que você controla; gere-os uma vez e mantenha-os estáveis entre sincronizações.
|
||||
* `applicationVariables` tornam-se variáveis de ambiente para suas funções (por exemplo, `DEFAULT_RECIPIENT_NAME` fica disponível como `process.env.DEFAULT_RECIPIENT_NAME`).
|
||||
* `defaultRoleUniversalIdentifier` deve corresponder ao arquivo do papel (veja abaixo).
|
||||
* As funções de pré-instalação e pós-instalação são detectadas automaticamente durante a geração do manifesto. Consulte [Funções de pré-instalação](#pre-install-functions) e [Funções de pós-instalação](#post-install-functions).
|
||||
|
||||
#### Papéis e permissões
|
||||
|
||||
Os aplicativos podem definir papéis que encapsulam permissões sobre os objetos e ações do seu espaço de trabalho. O campo `defaultRoleUniversalIdentifier` em `application-config.ts` designa o papel padrão usado pelas funções de lógica do seu app.
|
||||
|
||||
* A chave de API em tempo de execução, injetada como `TWENTY_API_KEY`, é derivada desse papel padrão de função.
|
||||
* O cliente tipado ficará restrito às permissões concedidas a esse papel.
|
||||
* Siga o princípio do menor privilégio: crie um papel dedicado com apenas as permissões de que suas funções precisam e, em seguida, faça referência ao seu identificador universal.
|
||||
|
||||
##### Papel de função padrão (*.role.ts)
|
||||
|
||||
Ao criar um novo aplicativo com o scaffold, a CLI também cria um arquivo de papel padrão. Use `defineRole()` para definir papéis com validação integrada:
|
||||
|
||||
```typescript
|
||||
// src/roles/default-role.ts
|
||||
import { defineRole, PermissionFlag } from 'twenty-sdk';
|
||||
|
||||
export const DEFAULT_ROLE_UNIVERSAL_IDENTIFIER =
|
||||
'b648f87b-1d26-4961-b974-0908fd991061';
|
||||
|
||||
export default defineRole({
|
||||
universalIdentifier: DEFAULT_ROLE_UNIVERSAL_IDENTIFIER,
|
||||
label: 'Default function role',
|
||||
description: 'Default role for function Twenty client',
|
||||
canReadAllObjectRecords: false,
|
||||
canUpdateAllObjectRecords: false,
|
||||
canSoftDeleteAllObjectRecords: false,
|
||||
canDestroyAllObjectRecords: false,
|
||||
canUpdateAllSettings: false,
|
||||
canBeAssignedToAgents: false,
|
||||
canBeAssignedToUsers: false,
|
||||
canBeAssignedToApiKeys: false,
|
||||
objectPermissions: [
|
||||
{
|
||||
objectUniversalIdentifier: '9f9882af-170c-4879-b013-f9628b77c050',
|
||||
canReadObjectRecords: true,
|
||||
canUpdateObjectRecords: true,
|
||||
canSoftDeleteObjectRecords: false,
|
||||
canDestroyObjectRecords: false,
|
||||
},
|
||||
],
|
||||
fieldPermissions: [
|
||||
{
|
||||
objectUniversalIdentifier: '9f9882af-170c-4879-b013-f9628b77c050',
|
||||
fieldUniversalIdentifier: 'b2c37dc0-8ae7-470e-96cd-1476b47dfaff',
|
||||
canReadFieldValue: false,
|
||||
canUpdateFieldValue: false,
|
||||
},
|
||||
],
|
||||
permissionFlags: [PermissionFlag.APPLICATIONS],
|
||||
});
|
||||
```
|
||||
|
||||
O `universalIdentifier` desse papel é então referenciado em `application-config.ts` como `defaultRoleUniversalIdentifier`. Em outras palavras:
|
||||
|
||||
* **\*.role.ts** define o que o papel de função padrão pode fazer.
|
||||
* **application-config.ts** aponta para esse papel para que suas funções herdem suas permissões.
|
||||
|
||||
Notas:
|
||||
|
||||
* Comece pelo papel gerado pelo scaffold e depois restrinja-o progressivamente seguindo o princípio do menor privilégio.
|
||||
* Substitua `objectPermissions` e `fieldPermissions` pelos objetos/campos de que suas funções precisam.
|
||||
* `permissionFlags` controlam o acesso a recursos em nível de plataforma. Mantenha-os mínimos; adicione apenas o que for necessário.
|
||||
* Veja um exemplo funcional no app Hello World: [`packages/twenty-apps/hello-world/src/roles/function-role.ts`](https://github.com/twentyhq/twenty/blob/main/packages/twenty-apps/hello-world/src/roles/function-role.ts).
|
||||
|
||||
### Configuração de função de lógica e ponto de entrada
|
||||
|
||||
Cada arquivo de função usa `defineLogicFunction()` para exportar uma configuração com um handler e gatilhos opcionais.
|
||||
|
||||
```typescript
|
||||
// src/app/createPostCard.logic-function.ts
|
||||
import { defineLogicFunction } from 'twenty-sdk';
|
||||
import type { DatabaseEventPayload, ObjectRecordCreateEvent, CronPayload, RoutePayload } from 'twenty-sdk';
|
||||
import { CoreApiClient, type Person } from 'twenty-sdk/generated';
|
||||
|
||||
const handler = async (params: RoutePayload) => {
|
||||
const client = new CoreApiClient();
|
||||
const name = 'name' in params.queryStringParameters
|
||||
? params.queryStringParameters.name ?? process.env.DEFAULT_RECIPIENT_NAME ?? 'Hello world'
|
||||
: 'Hello world';
|
||||
|
||||
const result = await client.mutation({
|
||||
createPostCard: {
|
||||
__args: { data: { name } },
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
});
|
||||
return result;
|
||||
};
|
||||
|
||||
export default defineLogicFunction({
|
||||
universalIdentifier: 'e56d363b-0bdc-4d8a-a393-6f0d1c75bdcf',
|
||||
name: 'create-new-post-card',
|
||||
timeoutSeconds: 2,
|
||||
handler,
|
||||
triggers: [
|
||||
// Public HTTP route trigger '/s/post-card/create'
|
||||
{
|
||||
universalIdentifier: 'c9f84c8d-b26d-40d1-95dd-4f834ae5a2c6',
|
||||
type: 'route',
|
||||
path: '/post-card/create',
|
||||
httpMethod: 'GET',
|
||||
isAuthRequired: false,
|
||||
},
|
||||
// Cron trigger (CRON pattern)
|
||||
// {
|
||||
// universalIdentifier: 'dd802808-0695-49e1-98c9-d5c9e2704ce2',
|
||||
// type: 'cron',
|
||||
// pattern: '0 0 1 1 *',
|
||||
// },
|
||||
// Database event trigger
|
||||
// {
|
||||
// universalIdentifier: '203f1df3-4a82-4d06-a001-b8cf22a31156',
|
||||
// type: 'databaseEvent',
|
||||
// eventName: 'person.updated',
|
||||
// updatedFields: ['name'],
|
||||
// },
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Tipos de gatilho comuns:
|
||||
|
||||
* **route**: Expõe sua função em um caminho e método HTTP **no endpoint `/s/`**:
|
||||
|
||||
> por exemplo, `path: '/post-card/create',` -> chamar em `<APP_URL>/s/post-card/create`
|
||||
|
||||
* **cron**: Executa sua função em um agendamento usando uma expressão CRON.
|
||||
* **databaseEvent**: Executa em eventos do ciclo de vida de objetos do espaço de trabalho. Quando a operação do evento é `updated`, campos específicos a serem observados podem ser especificados no array `updatedFields`. Se deixar indefinido ou vazio, qualquer atualização acionará a função.
|
||||
|
||||
> por exemplo, `person.updated`
|
||||
|
||||
Notas:
|
||||
|
||||
* O array `triggers` é opcional. Funções sem gatilhos podem ser usadas como funções utilitárias chamadas por outras funções.
|
||||
* Você pode misturar vários tipos de gatilho em uma única função.
|
||||
|
||||
### Funções de pré-instalação
|
||||
|
||||
Uma função de pré-instalação é uma função de lógica que é executada automaticamente antes de o seu aplicativo ser instalado em um espaço de trabalho. Isso é útil para tarefas de validação, verificações de pré-requisitos ou para preparar o estado do espaço de trabalho antes que a instalação principal prossiga.
|
||||
|
||||
Ao criar a estrutura de um novo app com `create-twenty-app`, uma função de pré-instalação é gerada para você em `src/logic-functions/pre-install.ts`:
|
||||
|
||||
```typescript
|
||||
// src/logic-functions/pre-install.ts
|
||||
import { definePreInstallLogicFunction, type InstallLogicFunctionPayload } from 'twenty-sdk';
|
||||
|
||||
const handler = async (payload: InstallLogicFunctionPayload): Promise<void> => {
|
||||
console.log('Pre install logic function executed successfully!', payload.previousVersion);
|
||||
};
|
||||
|
||||
export default definePreInstallLogicFunction({
|
||||
universalIdentifier: '<generated-uuid>',
|
||||
name: 'pre-install',
|
||||
description: 'Runs before installation to prepare the application.',
|
||||
timeoutSeconds: 300,
|
||||
handler,
|
||||
});
|
||||
```
|
||||
|
||||
Você também pode executar manualmente a função de pré-instalação a qualquer momento usando a CLI:
|
||||
|
||||
```bash filename="Terminal"
|
||||
yarn twenty function:execute --preInstall
|
||||
```
|
||||
|
||||
Pontos-chave:
|
||||
|
||||
* As funções de pré-instalação usam `definePreInstallLogicFunction()` — uma variante especializada que omite as configurações de gatilho (`cronTriggerSettings`, `databaseEventTriggerSettings`, `httpRouteTriggerSettings`, `isTool`).
|
||||
* O manipulador recebe um `InstallLogicFunctionPayload` com `{ previousVersion: string }` — a versão do app que foi instalada anteriormente (ou uma string vazia para instalações novas).
|
||||
* É permitida apenas uma função de pré-instalação por app. A geração do manifesto apresentará erro se mais de uma for detectada.
|
||||
* O `universalIdentifier` da função é definido automaticamente como `preInstallLogicFunctionUniversalIdentifier` no manifesto do aplicativo durante a geração — você não precisa referenciá-lo em `defineApplication()`.
|
||||
* O tempo limite padrão é definido como 300 segundos (5 minutos) para permitir tarefas de preparação mais longas.
|
||||
* As funções de pré-instalação não precisam de gatilhos — elas são invocadas pela plataforma antes da instalação ou manualmente via `function:execute --preInstall`.
|
||||
|
||||
### Funções de pós-instalação
|
||||
|
||||
Uma função de pós-instalação é uma função de lógica que é executada automaticamente após o seu aplicativo ser instalado em um espaço de trabalho. Isso é útil para tarefas de configuração únicas, como preencher dados padrão, criar registros iniciais ou configurar as configurações do espaço de trabalho.
|
||||
|
||||
Ao criar a estrutura de um novo app com `create-twenty-app`, uma função de pós-instalação é gerada para você em `src/logic-functions/post-install.ts`:
|
||||
|
||||
```typescript
|
||||
// src/logic-functions/post-install.ts
|
||||
import { definePostInstallLogicFunction, type InstallLogicFunctionPayload } from 'twenty-sdk';
|
||||
|
||||
const handler = async (payload: InstallLogicFunctionPayload): Promise<void> => {
|
||||
console.log('Post install logic function executed successfully!', payload.previousVersion);
|
||||
};
|
||||
|
||||
export default definePostInstallLogicFunction({
|
||||
universalIdentifier: '<generated-uuid>',
|
||||
name: 'post-install',
|
||||
description: 'Runs after installation to set up the application.',
|
||||
timeoutSeconds: 300,
|
||||
handler,
|
||||
});
|
||||
```
|
||||
|
||||
Você também pode executar manualmente a função de pós-instalação a qualquer momento usando a CLI:
|
||||
|
||||
```bash filename="Terminal"
|
||||
yarn twenty function:execute --postInstall
|
||||
```
|
||||
|
||||
Pontos-chave:
|
||||
|
||||
* As funções de pós-instalação usam `definePostInstallLogicFunction()` — uma variante especializada que omite as configurações de gatilho (`cronTriggerSettings`, `databaseEventTriggerSettings`, `httpRouteTriggerSettings`, `isTool`).
|
||||
* O manipulador recebe um `InstallLogicFunctionPayload` com `{ previousVersion: string }` — a versão do app que foi instalada anteriormente (ou uma string vazia para instalações novas).
|
||||
* É permitida apenas uma função de pós-instalação por app. A geração do manifesto apresentará erro se mais de uma for detectada.
|
||||
* O `universalIdentifier` da função é definido automaticamente como `postInstallLogicFunctionUniversalIdentifier` no manifesto do aplicativo durante a geração — você não precisa referenciá-lo em `defineApplication()`.
|
||||
* O tempo limite padrão é definido como 300 segundos (5 minutos) para permitir tarefas de configuração mais longas, como o pré-carregamento de dados.
|
||||
* As funções de pós-instalação não precisam de gatilhos — elas são invocadas pela plataforma durante a instalação ou manualmente via `function:execute --postInstall`.
|
||||
|
||||
### Payload de gatilho de rota
|
||||
|
||||
<Warning>
|
||||
**Alteração incompatível (v1.16, janeiro de 2026):** O formato do payload de gatilho de rota mudou. Antes da v1.16, os parâmetros de consulta, parâmetros de caminho e corpo eram enviados diretamente como o payload. A partir da v1.16, eles ficam aninhados dentro de um objeto estruturado `RoutePayload`.
|
||||
|
||||
**Antes da v1.16:**
|
||||
```typescript
|
||||
const handler = async (params) => {
|
||||
const { param1, param2 } = params; // Direct access
|
||||
};
|
||||
```
|
||||
|
||||
**Depois da v1.16:**
|
||||
```typescript
|
||||
const handler = async (event: RoutePayload) => {
|
||||
const { param1, param2 } = event.body; // Access via .body
|
||||
const { queryParam } = event.queryStringParameters;
|
||||
const { id } = event.pathParameters;
|
||||
};
|
||||
```
|
||||
|
||||
**Para migrar funções existentes:** Atualize seu handler para desestruturar de `event.body`, `event.queryStringParameters` ou `event.pathParameters` em vez de diretamente do objeto de parâmetros.
|
||||
</Warning>
|
||||
|
||||
Quando um gatilho de rota invoca sua função de lógica, ela recebe um objeto `RoutePayload` que segue o formato do AWS HTTP API v2. Importe o tipo de `twenty-sdk`:
|
||||
|
||||
```typescript
|
||||
import { defineLogicFunction, type RoutePayload } from 'twenty-sdk';
|
||||
|
||||
const handler = async (event: RoutePayload) => {
|
||||
// Access request data
|
||||
const { headers, queryStringParameters, pathParameters, body } = event;
|
||||
|
||||
// HTTP method and path are available in requestContext
|
||||
const { method, path } = event.requestContext.http;
|
||||
|
||||
return { message: 'Success' };
|
||||
};
|
||||
```
|
||||
|
||||
O tipo `RoutePayload` tem a seguinte estrutura:
|
||||
|
||||
| Propriedade | Tipo | Descrição |
|
||||
| ---------------------------- | ------------------------------------- | ----------------------------------------------------------------------------------------------- |
|
||||
| `headers` | `Record<string, string \| undefined>` | Cabeçalhos HTTP (apenas aqueles listados em `forwardedRequestHeaders`) |
|
||||
| `queryStringParameters` | `Record<string, string \| undefined>` | Parâmetros de query string (valores múltiplos unidos por vírgulas) |
|
||||
| `pathParameters` | `Record<string, string \| undefined>` | Parâmetros de caminho extraídos do padrão de rota (por exemplo, `/users/:id` → `{ id: '123' }`) |
|
||||
| `body` | `object \| null` | Corpo da requisição analisado (JSON) |
|
||||
| `isBase64Encoded` | `boolean` | Se o corpo está codificado em base64 |
|
||||
| `requestContext.http.method` | `string` | Método HTTP (GET, POST, PUT, PATCH, DELETE) |
|
||||
| `requestContext.http.path` | `string` | Caminho bruto da requisição |
|
||||
|
||||
### Encaminhamento de cabeçalhos HTTP
|
||||
|
||||
Por padrão, os cabeçalhos HTTP das requisições recebidas **não** são repassados para sua função de lógica por motivos de segurança. Para acessar cabeçalhos específicos, liste-os explicitamente no array `forwardedRequestHeaders`:
|
||||
|
||||
```typescript
|
||||
export default defineLogicFunction({
|
||||
universalIdentifier: 'e56d363b-0bdc-4d8a-a393-6f0d1c75bdcf',
|
||||
name: 'webhook-handler',
|
||||
handler,
|
||||
triggers: [
|
||||
{
|
||||
universalIdentifier: 'c9f84c8d-b26d-40d1-95dd-4f834ae5a2c6',
|
||||
type: 'route',
|
||||
path: '/webhook',
|
||||
httpMethod: 'POST',
|
||||
isAuthRequired: false,
|
||||
forwardedRequestHeaders: ['x-webhook-signature', 'content-type'],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
No seu handler, você pode então acessar esses cabeçalhos:
|
||||
|
||||
```typescript
|
||||
const handler = async (event: RoutePayload) => {
|
||||
const signature = event.headers['x-webhook-signature'];
|
||||
const contentType = event.headers['content-type'];
|
||||
|
||||
// Validate webhook signature...
|
||||
return { received: true };
|
||||
};
|
||||
```
|
||||
|
||||
<Note>
|
||||
Os nomes dos cabeçalhos são normalizados para minúsculas. Acesse-os usando chaves em minúsculas (por exemplo, `event.headers['content-type']`).
|
||||
</Note>
|
||||
|
||||
Você pode criar novas funções de duas formas:
|
||||
|
||||
* **Gerado automaticamente**: Execute `yarn twenty entity:add` e escolha a opção para adicionar uma nova função de lógica. Isso gera um arquivo inicial com um handler e configuração.
|
||||
* **Manual**: Crie um novo arquivo `*.logic-function.ts` e use `defineLogicFunction()`, seguindo o mesmo padrão.
|
||||
|
||||
### Marcar uma função lógica como ferramenta
|
||||
|
||||
Funções lógicas podem ser expostas como **ferramentas** para agentes de IA e fluxos de trabalho. Quando uma função é marcada como ferramenta, ela fica disponível para os recursos de IA do Twenty e pode ser selecionada como uma etapa em automações de fluxos de trabalho.
|
||||
|
||||
Para marcar uma função lógica como ferramenta, defina `isTool: true` e forneça um `toolInputSchema` descrevendo os parâmetros de entrada esperados usando [JSON Schema](https://json-schema.org/):
|
||||
|
||||
```typescript
|
||||
// src/logic-functions/enrich-company.logic-function.ts
|
||||
import { defineLogicFunction } from 'twenty-sdk';
|
||||
import { CoreApiClient } from 'twenty-sdk/generated';
|
||||
|
||||
const handler = async (params: { companyName: string; domain?: string }) => {
|
||||
const client = new CoreApiClient();
|
||||
|
||||
const result = await client.mutation({
|
||||
createTask: {
|
||||
__args: {
|
||||
data: {
|
||||
title: `Enrich data for ${params.companyName}`,
|
||||
body: `Domain: ${params.domain ?? 'unknown'}`,
|
||||
},
|
||||
},
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
return { taskId: result.createTask.id };
|
||||
};
|
||||
|
||||
export default defineLogicFunction({
|
||||
universalIdentifier: 'f47ac10b-58cc-4372-a567-0e02b2c3d479',
|
||||
name: 'enrich-company',
|
||||
description: 'Enrich a company record with external data',
|
||||
timeoutSeconds: 10,
|
||||
handler,
|
||||
isTool: true,
|
||||
toolInputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
companyName: {
|
||||
type: 'string',
|
||||
description: 'The name of the company to enrich',
|
||||
},
|
||||
domain: {
|
||||
type: 'string',
|
||||
description: 'The company website domain (optional)',
|
||||
},
|
||||
},
|
||||
required: ['companyName'],
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Pontos-chave:
|
||||
|
||||
* **`isTool`** (`boolean`, padrão: `false`): Quando definido como `true`, a função é registrada como uma ferramenta e fica disponível para agentes de IA e automações de fluxos de trabalho.
|
||||
* **`toolInputSchema`** (`object`, opcional): Um objeto JSON Schema que descreve os parâmetros que sua função aceita. Os agentes de IA usam esse esquema para entender quais entradas a ferramenta espera e para validar as chamadas. Se omitido, o esquema tem como padrão `{ type: 'object', properties: {} }` (sem parâmetros).
|
||||
* Funções com `isTool: false` (ou não definido) **não** são expostas como ferramentas. Elas ainda podem ser executadas diretamente ou chamadas por outras funções, mas não aparecerão na descoberta de ferramentas.
|
||||
* **Nomenclatura de ferramentas**: Quando exposta como uma ferramenta, o nome da função é automaticamente normalizado para `logic_function_<name>` (em minúsculas, caracteres não alfanuméricos substituídos por sublinhados). Por exemplo, `enrich-company` torna-se `logic_function_enrich_company`.
|
||||
* Você pode combinar `isTool` com gatilhos — uma função pode ser ao mesmo tempo uma ferramenta (chamável por agentes de IA) e acionada por eventos (cron, eventos de banco de dados, rotas) simultaneamente.
|
||||
|
||||
<Note>
|
||||
**Escreva uma boa `description`.** Os agentes de IA dependem do campo `description` da função para decidir quando usar a ferramenta. Seja específico sobre o que a ferramenta faz e quando ela deve ser chamada.
|
||||
</Note>
|
||||
|
||||
### Componentes de front-end
|
||||
|
||||
Componentes de front-end permitem criar componentes React personalizados que são renderizados na UI do Twenty. Use `defineFrontComponent()` para definir componentes com validação integrada:
|
||||
|
||||
```typescript
|
||||
// src/front-components/my-widget.tsx
|
||||
import { defineFrontComponent } from 'twenty-sdk';
|
||||
|
||||
const MyWidget = () => {
|
||||
return (
|
||||
<div style={{ padding: '20px', fontFamily: 'sans-serif' }}>
|
||||
<h1>My Custom Widget</h1>
|
||||
<p>This is a custom front component for Twenty.</p>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default defineFrontComponent({
|
||||
universalIdentifier: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
|
||||
name: 'my-widget',
|
||||
description: 'A custom widget component',
|
||||
component: MyWidget,
|
||||
});
|
||||
```
|
||||
|
||||
Pontos-chave:
|
||||
|
||||
* Componentes de front-end são componentes React que renderizam em contextos isolados dentro do Twenty.
|
||||
* O campo `component` faz referência ao seu componente React.
|
||||
* Os componentes são compilados e sincronizados automaticamente durante `yarn twenty app:dev`.
|
||||
|
||||
Você pode criar novos componentes de front-end de duas formas:
|
||||
|
||||
* **Gerado automaticamente**: Execute `yarn twenty entity:add` e escolha a opção para adicionar um novo componente de front-end.
|
||||
* **Manual**: Crie um novo arquivo `.tsx` e use `defineFrontComponent()`, seguindo o mesmo padrão.
|
||||
|
||||
### Habilidades
|
||||
|
||||
As habilidades definem instruções e capacidades reutilizáveis que os agentes de IA podem usar no seu espaço de trabalho. Use `defineSkill()` para definir habilidades com validação integrada:
|
||||
|
||||
```typescript
|
||||
// src/skills/example-skill.ts
|
||||
import { defineSkill } from 'twenty-sdk';
|
||||
|
||||
export default defineSkill({
|
||||
universalIdentifier: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
|
||||
name: 'sales-outreach',
|
||||
label: 'Sales Outreach',
|
||||
description: 'Guides the AI agent through a structured sales outreach process',
|
||||
icon: 'IconBrain',
|
||||
content: `You are a sales outreach assistant. When reaching out to a prospect:
|
||||
1. Research the company and recent news
|
||||
2. Identify the prospect's role and likely pain points
|
||||
3. Draft a personalized message referencing specific details
|
||||
4. Keep the tone professional but conversational`,
|
||||
});
|
||||
```
|
||||
|
||||
Pontos-chave:
|
||||
|
||||
* `name` é uma string de identificador exclusivo para a habilidade (recomenda-se kebab-case).
|
||||
* `label` é o nome de exibição legível por humanos mostrado na UI.
|
||||
* `content` contém as instruções da habilidade — este é o texto que o agente de IA usa.
|
||||
* `icon` (opcional) define o ícone exibido na UI.
|
||||
* `description` (opcional) fornece contexto adicional sobre a finalidade da habilidade.
|
||||
|
||||
Você pode criar novas habilidades de duas formas:
|
||||
|
||||
* **Gerado automaticamente**: Execute `yarn twenty entity:add` e escolha a opção para adicionar uma nova habilidade.
|
||||
* **Manual**: Crie um novo arquivo e use `defineSkill()`, seguindo o mesmo padrão.
|
||||
|
||||
### Clientes tipados gerados
|
||||
|
||||
Dois clientes tipados são gerados automaticamente pelo `yarn twenty app:dev` e armazenados em `node_modules/twenty-sdk/generated` com base no esquema do seu espaço de trabalho:
|
||||
|
||||
* **`CoreApiClient`** — consulta o endpoint `/graphql` para dados do espaço de trabalho
|
||||
* **`MetadataApiClient`** — consulta o endpoint `/metadata` para obter a configuração do espaço de trabalho e o carregamento de arquivos
|
||||
|
||||
```typescript
|
||||
import { CoreApiClient, MetadataApiClient } from 'twenty-sdk/generated';
|
||||
|
||||
const client = new CoreApiClient();
|
||||
const { me } = await client.query({ me: { id: true, displayName: true } });
|
||||
|
||||
const metadataClient = new MetadataApiClient();
|
||||
const { currentWorkspace } = await metadataClient.query({ currentWorkspace: { id: true } });
|
||||
```
|
||||
|
||||
Ambos os clientes são regenerados automaticamente pelo `yarn twenty app:dev` sempre que seus objetos ou campos forem alterados.
|
||||
|
||||
#### Credenciais em tempo de execução em funções de lógica
|
||||
|
||||
Quando sua função é executada no Twenty, a plataforma injeta credenciais como variáveis de ambiente antes da execução do seu código:
|
||||
|
||||
* `TWENTY_API_URL`: URL base da API do Twenty que seu aplicativo usa como alvo.
|
||||
* `TWENTY_API_KEY`: Chave de curta duração com escopo para o papel de função padrão do seu aplicativo.
|
||||
|
||||
Notas:
|
||||
|
||||
* Você não precisa passar a URL ou a chave de API para o cliente gerado. Ele lê `TWENTY_API_URL` e `TWENTY_API_KEY` de process.env em tempo de execução.
|
||||
* As permissões da chave de API são determinadas pelo papel referenciado no seu `application-config.ts` via `defaultRoleUniversalIdentifier`. Este é o papel padrão usado pelas funções de lógica do seu app.
|
||||
* Os aplicativos podem definir papéis para seguir o princípio do menor privilégio. Conceda apenas as permissões de que suas funções precisam e, em seguida, aponte `defaultRoleUniversalIdentifier` para o identificador universal desse papel.
|
||||
|
||||
#### Carregamento de arquivos
|
||||
|
||||
O `MetadataApiClient` gerado inclui um método `uploadFile` para anexar arquivos a campos do tipo arquivo nos objetos do seu espaço de trabalho. Como os clientes GraphQL padrão não suportam nativamente o carregamento de arquivos multipart, o cliente fornece este método dedicado que implementa, nos bastidores, a [especificação de solicitações multipart do GraphQL](https://github.com/jaydenseric/graphql-multipart-request-spec).
|
||||
|
||||
```typescript
|
||||
import { MetadataApiClient } from 'twenty-sdk/generated';
|
||||
import * as fs from 'fs';
|
||||
|
||||
const metadataClient = new MetadataApiClient();
|
||||
|
||||
const fileBuffer = fs.readFileSync('./invoice.pdf');
|
||||
|
||||
const uploadedFile = await metadataClient.uploadFile(
|
||||
fileBuffer, // file contents as a Buffer
|
||||
'invoice.pdf', // filename
|
||||
'application/pdf', // MIME type (defaults to 'application/octet-stream')
|
||||
'58a0a314-d7ea-4865-9850-7fb84e72f30b', // field universal identifier
|
||||
);
|
||||
|
||||
console.log(uploadedFile);
|
||||
// { id: '...', path: '...', size: 12345, createdAt: '...', url: 'https://...' }
|
||||
```
|
||||
|
||||
A assinatura do método:
|
||||
|
||||
```typescript
|
||||
uploadFile(
|
||||
fileBuffer: Buffer,
|
||||
filename: string,
|
||||
contentType: string,
|
||||
fieldMetadataUniversalIdentifier: string,
|
||||
): Promise<{ id: string; path: string; size: number; createdAt: string; url: string }>
|
||||
```
|
||||
|
||||
| Parâmetro | Tipo | Descrição |
|
||||
| ---------------------------------- | -------- | ------------------------------------------------------------------------ |
|
||||
| `fileBuffer` | `Buffer` | O conteúdo bruto do arquivo |
|
||||
| `filename` | `string` | O nome do arquivo (usado para armazenamento e exibição) |
|
||||
| `contentType` | `string` | Tipo MIME do arquivo (padrão para `application/octet-stream` se omitido) |
|
||||
| `fieldMetadataUniversalIdentifier` | `string` | O `universalIdentifier` do campo do tipo arquivo no seu objeto |
|
||||
|
||||
Pontos-chave:
|
||||
|
||||
* O método `uploadFile` está disponível no `MetadataApiClient` porque a mutação de upload é resolvida pelo endpoint `/metadata`.
|
||||
* Ele usa o `universalIdentifier` do campo (não o ID específico do espaço de trabalho), de modo que seu código de upload funcione em qualquer espaço de trabalho onde seu app esteja instalado — consistente com a forma como os apps referenciam campos em qualquer outro lugar.
|
||||
* A `url` retornada é um URL assinado que você pode usar para acessar o arquivo enviado.
|
||||
|
||||
### Exemplo Hello World
|
||||
|
||||
Explore um exemplo mínimo de ponta a ponta que demonstra objetos, funções de lógica, componentes de front-end e vários gatilhos [aqui](https://github.com/twentyhq/twenty/tree/main/packages/twenty-apps/hello-world).
|
||||
@@ -1,233 +0,0 @@
|
||||
---
|
||||
title: Primeiros passos
|
||||
description: Crie seu primeiro app do Twenty em minutos.
|
||||
---
|
||||
|
||||
<Warning>
|
||||
Os aplicativos estão atualmente em testes alfa. O recurso é funcional, mas ainda está evoluindo.
|
||||
</Warning>
|
||||
|
||||
Os apps permitem que você estenda o Twenty com objetos, campos, funções de lógica, habilidades de IA e componentes de UI personalizados — tudo gerenciado como código.
|
||||
|
||||
**O que você pode fazer hoje:**
|
||||
|
||||
* Defina objetos e campos personalizados como código (modelo de dados gerenciado)
|
||||
* Crie funções de lógica com gatilhos personalizados (rotas HTTP, cron, eventos de banco de dados)
|
||||
* Defina habilidades para agentes de IA
|
||||
* Crie componentes de front-end que renderizam dentro da UI do Twenty
|
||||
* Implemente o mesmo aplicativo em vários espaços de trabalho
|
||||
|
||||
## Pré-requisitos
|
||||
|
||||
* Node.js 24+ e Yarn 4
|
||||
* Um espaço de trabalho do Twenty e uma chave de API (crie uma em https://app.twenty.com/settings/api-webhooks)
|
||||
|
||||
## Primeiros passos
|
||||
|
||||
Crie um novo aplicativo usando o gerador oficial, depois autentique-se e comece a desenvolver:
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Scaffold a new app (includes all examples by default)
|
||||
npx create-twenty-app@latest my-twenty-app
|
||||
cd my-twenty-app
|
||||
|
||||
# Start dev mode: automatically syncs local changes to your workspace
|
||||
yarn twenty app:dev
|
||||
```
|
||||
|
||||
O gerador de estrutura oferece suporte a dois modos para controlar quais arquivos de exemplo são incluídos:
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Default (exhaustive): all examples (object, field, logic function, front component, view, navigation menu item, skill)
|
||||
npx create-twenty-app@latest my-app
|
||||
|
||||
# Minimal: only core files (application-config.ts and default-role.ts)
|
||||
npx create-twenty-app@latest my-app --minimal
|
||||
```
|
||||
|
||||
A partir daqui você pode:
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Add a new entity to your application (guided)
|
||||
yarn twenty entity:add
|
||||
|
||||
# Watch your application's function logs
|
||||
yarn twenty function:logs
|
||||
|
||||
# Execute a function by name
|
||||
yarn twenty function:execute -n my-function -p '{"name": "test"}'
|
||||
|
||||
# Execute the pre-install function
|
||||
yarn twenty function:execute --preInstall
|
||||
|
||||
# Execute the post-install function
|
||||
yarn twenty function:execute --postInstall
|
||||
|
||||
# Uninstall the application from the current workspace
|
||||
yarn twenty app:uninstall
|
||||
|
||||
# Display commands' help
|
||||
yarn twenty help
|
||||
```
|
||||
|
||||
Veja também: as páginas de referência da CLI para [create-twenty-app](https://www.npmjs.com/package/create-twenty-app) e [twenty-sdk CLI](https://www.npmjs.com/package/twenty-sdk).
|
||||
|
||||
## Estrutura do projeto (com scaffold)
|
||||
|
||||
Ao executar `npx create-twenty-app@latest my-twenty-app`, o gerador:
|
||||
|
||||
* Copia um aplicativo base mínimo para `my-twenty-app/`
|
||||
* Adiciona uma dependência local `twenty-sdk` e a configuração do Yarn 4
|
||||
* Cria arquivos de configuração e scripts conectados à CLI `twenty`
|
||||
* Gera arquivos principais (configuração da aplicação, papel padrão para funções de lógica, funções de pré-instalação e pós-instalação) além de arquivos de exemplo com base no modo de geração de estrutura
|
||||
|
||||
Um app recém-criado com o modo padrão `--exhaustive` fica assim:
|
||||
|
||||
```text filename="my-twenty-app/"
|
||||
my-twenty-app/
|
||||
package.json
|
||||
yarn.lock
|
||||
.gitignore
|
||||
.nvmrc
|
||||
.yarnrc.yml
|
||||
.yarn/
|
||||
install-state.gz
|
||||
.oxlintrc.json
|
||||
tsconfig.json
|
||||
README.md
|
||||
public/ # Public assets folder (images, fonts, etc.)
|
||||
src/
|
||||
├── application-config.ts # Required - main application configuration
|
||||
├── roles/
|
||||
│ └── default-role.ts # Default role for logic functions
|
||||
├── objects/
|
||||
│ └── example-object.ts # Example custom object definition
|
||||
├── fields/
|
||||
│ └── example-field.ts # Example standalone field definition
|
||||
├── logic-functions/
|
||||
│ ├── hello-world.ts # Example logic function
|
||||
│ ├── pre-install.ts # Pre-install logic function
|
||||
│ └── post-install.ts # Post-install logic function
|
||||
├── front-components/
|
||||
│ └── hello-world.tsx # Example front component
|
||||
├── views/
|
||||
│ └── example-view.ts # Example saved view definition
|
||||
├── navigation-menu-items/
|
||||
│ └── example-navigation-menu-item.ts # Example sidebar navigation link
|
||||
└── skills/
|
||||
└── example-skill.ts # Example AI agent skill definition
|
||||
```
|
||||
|
||||
Com `--minimal`, apenas os arquivos principais são criados (`application-config.ts`, `roles/default-role.ts`, `logic-functions/pre-install.ts` e `logic-functions/post-install.ts`).
|
||||
|
||||
Em alto nível:
|
||||
|
||||
* **package.json**: Declara o nome do app, versão, engines (Node 24+, Yarn 4), e adiciona `twenty-sdk` além de um script `twenty` que delega para a CLI `twenty` local. Execute `yarn twenty help` para listar todos os comandos disponíveis.
|
||||
* **.gitignore**: Ignora artefatos comuns como `node_modules`, `.yarn`, `generated/` (cliente tipado), `dist/`, `build/`, pastas de cobertura, arquivos de log e arquivos `.env*`.
|
||||
* **yarn.lock**, **.yarnrc.yml**, **.yarn/**: Bloqueiam e configuram a ferramenta Yarn 4 usada pelo projeto.
|
||||
* **.nvmrc**: Fixa a versão do Node.js esperada pelo projeto.
|
||||
* **.oxlintrc.json** e **tsconfig.json**: Fornecem lint e configuração do TypeScript para os fontes TypeScript do seu aplicativo.
|
||||
* **README.md**: Um README curto na raiz do aplicativo com instruções básicas.
|
||||
* **public/**: Uma pasta para armazenar recursos públicos (imagens, fontes, arquivos estáticos) que serão servidos com sua aplicação. Os arquivos colocados aqui são enviados durante a sincronização e ficam acessíveis em tempo de execução.
|
||||
* **src/**: O local principal onde você define seu aplicativo como código
|
||||
|
||||
### Detecção de entidades
|
||||
|
||||
O SDK detecta entidades analisando seus arquivos TypeScript em busca de chamadas **`export default define<Entity>({...})`**. Cada tipo de entidade tem uma função utilitária correspondente exportada de `twenty-sdk`:
|
||||
|
||||
| Função utilitária | Tipo de entidade |
|
||||
| -------------------------------- | -------------------------------------------------------------------- |
|
||||
| `defineObject` | Definições de objetos personalizados |
|
||||
| `defineLogicFunction` | Definições de funções de lógica |
|
||||
| `definePreInstallLogicFunction` | Função de lógica de pré-instalação (é executada antes da instalação) |
|
||||
| `definePostInstallLogicFunction` | Função de lógica de pós-instalação (é executada após a instalação) |
|
||||
| `defineFrontComponent` | Definições de componentes de front-end |
|
||||
| `defineRole` | Definições de papéis |
|
||||
| `defineField` | Extensões de campos para objetos existentes |
|
||||
| `defineView` | Definições de visualizações salvas |
|
||||
| `defineNavigationMenuItem` | Definições de itens do menu de navegação |
|
||||
| `defineSkill` | Definições de habilidades de agente de IA |
|
||||
|
||||
<Note>
|
||||
**A nomeação de arquivos é flexível.** A detecção de entidades é baseada em AST — o SDK varre seus arquivos fonte em busca do padrão `export default define<Entity>({...})`. Você pode organizar seus arquivos e pastas como quiser. Agrupar por tipo de entidade (por exemplo, `logic-functions/`, `roles/`) é apenas uma convenção para organização do código, não um requisito.
|
||||
</Note>
|
||||
|
||||
Exemplo de uma entidade detectada:
|
||||
|
||||
```typescript
|
||||
// This file can be named anything and placed anywhere in src/
|
||||
import { defineObject, FieldType } from 'twenty-sdk';
|
||||
|
||||
export default defineObject({
|
||||
universalIdentifier: '...',
|
||||
nameSingular: 'postCard',
|
||||
// ... rest of config
|
||||
});
|
||||
```
|
||||
|
||||
Comandos posteriores adicionarão mais arquivos e pastas:
|
||||
|
||||
* `yarn twenty app:dev` irá gerar automaticamente dois clientes de API tipados em `node_modules/twenty-sdk/generated`: `CoreApiClient` (para dados do espaço de trabalho via `/graphql`) e `MetadataApiClient` (para configuração do espaço de trabalho e envio de arquivos via `/metadata`).
|
||||
* `yarn twenty entity:add` adicionará arquivos de definição de entidade em `src/` para seus objetos, funções, componentes de front-end, papéis e habilidades personalizados, entre outros.
|
||||
|
||||
## Autenticação
|
||||
|
||||
Na primeira vez que você executar `yarn twenty auth:login`, será solicitado o seguinte:
|
||||
|
||||
* URL da API (padrão: http://localhost:3000 ou o perfil do seu espaço de trabalho atual)
|
||||
* Chave de API
|
||||
|
||||
Suas credenciais são armazenadas por usuário em `~/.twenty/config.json`. Você pode manter vários perfis e alternar entre eles.
|
||||
|
||||
### Gerenciando espaços de trabalho
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Login interactively (recommended)
|
||||
yarn twenty auth:login
|
||||
|
||||
# Login to a specific workspace profile
|
||||
yarn twenty auth:login --workspace my-custom-workspace
|
||||
|
||||
# List all configured workspaces
|
||||
yarn twenty auth:list
|
||||
|
||||
# Switch the default workspace (interactive)
|
||||
yarn twenty auth:switch
|
||||
|
||||
# Switch to a specific workspace
|
||||
yarn twenty auth:switch production
|
||||
|
||||
# Check current authentication status
|
||||
yarn twenty auth:status
|
||||
```
|
||||
|
||||
Depois que você alternar os espaços de trabalho com `yarn twenty auth:switch`, todos os comandos subsequentes usarão esse espaço de trabalho por padrão. Você ainda pode substituí-lo temporariamente com `--workspace <name>`.
|
||||
|
||||
## Configuração manual (sem o gerador)
|
||||
|
||||
Embora recomendemos usar `create-twenty-app` para a melhor experiência inicial, você também pode configurar um projeto manualmente. Não instale a CLI globalmente. Em vez disso, adicione `twenty-sdk` como uma dependência local e configure um único script no seu package.json:
|
||||
|
||||
```bash filename="Terminal"
|
||||
yarn add -D twenty-sdk
|
||||
```
|
||||
|
||||
Em seguida, adicione um script `twenty`:
|
||||
|
||||
```json filename="package.json"
|
||||
{
|
||||
"scripts": {
|
||||
"twenty": "twenty"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Agora você pode executar todos os comandos via `yarn twenty <command>`, por exemplo, `yarn twenty app:dev`, `yarn twenty help`, etc.
|
||||
|
||||
## Resolução de Problemas
|
||||
|
||||
* Erros de autenticação: execute `yarn twenty auth:login` e certifique-se de que sua chave de API tenha as permissões necessárias.
|
||||
* Não é possível conectar ao servidor: verifique a URL da API e se o servidor do Twenty está acessível.
|
||||
* Tipos ou cliente ausentes/desatualizados: reinicie `yarn twenty app:dev` — ele gera automaticamente o cliente tipado.
|
||||
* Modo de desenvolvimento não sincronizando: certifique-se de que `yarn twenty app:dev` esteja em execução e de que as alterações não estejam sendo ignoradas pelo seu ambiente.
|
||||
|
||||
Canal de ajuda no Discord: https://discord.com/channels/1130383047699738754/1130386664812982322
|
||||
@@ -1,119 +0,0 @@
|
||||
---
|
||||
title: Publicação
|
||||
description: Distribua seu aplicativo Twenty no Marketplace ou implante-o internamente.
|
||||
---
|
||||
|
||||
<Warning>
|
||||
Os aplicativos estão atualmente em testes alfa. O recurso é funcional, mas ainda está evoluindo.
|
||||
</Warning>
|
||||
|
||||
## Visão Geral
|
||||
|
||||
Depois que seu aplicativo estiver [compilado e testado localmente](/l/pt/developers/extend/apps/building), você tem dois caminhos para distribuí-lo:
|
||||
|
||||
* **Publicar no npm** — liste seu aplicativo no Marketplace da Twenty para que qualquer espaço de trabalho possa descobrir e instalar.
|
||||
* **Enviar um tarball** — implante seu aplicativo em um servidor Twenty específico para uso interno sem torná-lo público.
|
||||
|
||||
## Publicação no npm
|
||||
|
||||
Publicar no npm torna seu aplicativo descobrível no Marketplace da Twenty. Qualquer espaço de trabalho da Twenty pode navegar, instalar e atualizar aplicativos do Marketplace diretamente pela UI.
|
||||
|
||||
### Requisitos
|
||||
|
||||
* Uma conta no [npm](https://www.npmjs.com)
|
||||
* O nome do seu pacote **deve** usar o prefixo `twenty-app-` (por exemplo, `twenty-app-postcard-sender`)
|
||||
|
||||
### Etapas
|
||||
|
||||
1. **Compile seu aplicativo** — a CLI compila seus códigos-fonte TypeScript e gera o manifesto do aplicativo:
|
||||
|
||||
```bash filename="Terminal"
|
||||
yarn twenty app:build
|
||||
```
|
||||
|
||||
2. **Publicar no npm** — envie o pacote compilado para o registro do npm:
|
||||
|
||||
```bash filename="Terminal"
|
||||
npx twenty app:publish
|
||||
```
|
||||
|
||||
### Descoberta automática
|
||||
|
||||
Pacotes com o prefixo `twenty-app-` são detectados automaticamente pelo catálogo do Marketplace da Twenty. Depois de publicado, seu aplicativo aparece no Marketplace em poucos minutos — sem necessidade de registro manual ou aprovação.
|
||||
|
||||
### Publicação via CI
|
||||
|
||||
O projeto gerado inclui um workflow do GitHub Actions que publica a cada lançamento. Ele executa `app:build` e depois `npm publish --provenance` a partir da saída do build:
|
||||
|
||||
```yaml filename=".github/workflows/publish.yml"
|
||||
name: Publish
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "24"
|
||||
registry-url: https://registry.npmjs.org
|
||||
- run: yarn install --immutable
|
||||
- run: npx twenty app:build
|
||||
- run: npm publish --provenance --access public
|
||||
working-directory: .twenty/output
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
```
|
||||
|
||||
Para outros sistemas de CI (GitLab CI, CircleCI etc.), aplicam-se os mesmos três comandos: `yarn install`, `npx twenty app:build` e depois `npm publish` a partir de `.twenty/output`.
|
||||
|
||||
<Tip>
|
||||
**Proveniência do npm** é opcional, mas recomendada. Publicar com `--provenance` adiciona um selo de confiança à sua listagem no npm, permitindo que os usuários verifiquem que o pacote foi construído a partir de um commit específico em um pipeline de CI público. Consulte a [documentação de proveniência do npm](https://docs.npmjs.com/generating-provenance-statements) para instruções de configuração.
|
||||
</Tip>
|
||||
|
||||
## Distribuição interna
|
||||
|
||||
Para aplicativos que você não quer disponibilizar publicamente — ferramentas proprietárias, integrações apenas para empresas ou builds experimentais — você pode enviar um tarball diretamente para um servidor Twenty.
|
||||
|
||||
### Enviar um tarball
|
||||
|
||||
Compile seu aplicativo e implante-o em um servidor específico em uma única etapa:
|
||||
|
||||
```bash filename="Terminal"
|
||||
npx twenty app:publish --server <server-url>
|
||||
```
|
||||
|
||||
Qualquer espaço de trabalho nesse servidor pode então instalar e atualizar o aplicativo na página de configurações de **Aplicativos**.
|
||||
|
||||
### Gerenciamento de versões
|
||||
|
||||
Para lançar uma atualização:
|
||||
|
||||
1. Atualize o campo `version` no seu `package.json`
|
||||
2. Envie um novo tarball com `npx twenty app:publish --server <server-url>`
|
||||
3. Os espaços de trabalho nesse servidor verão a atualização disponível nas suas configurações
|
||||
|
||||
<Note>
|
||||
Aplicativos internos ficam restritos ao servidor para o qual são enviados. Eles não aparecem no Marketplace público e não podem ser instalados por espaços de trabalho em outros servidores.
|
||||
</Note>
|
||||
|
||||
## Categorias de aplicativos
|
||||
|
||||
A Twenty organiza os aplicativos em três categorias com base em como são distribuídos:
|
||||
|
||||
| Categoria | Como Funciona | Visível no Marketplace? |
|
||||
| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- |
|
||||
| **Desenvolvimento** | Aplicativos em modo de desenvolvimento local executados via `yarn twenty app:dev`. Usados para compilação e testes. | Não |
|
||||
| **Publicado** | Aplicativos publicados no npm com o prefixo `twenty-app-`. Listados no Marketplace para que qualquer espaço de trabalho possa instalar. | Sim |
|
||||
| **Interno** | Aplicativos implantados via tarball em um servidor específico. Disponível apenas para espaços de trabalho nesse servidor. | Não |
|
||||
|
||||
<Tip>
|
||||
Comece no modo de **Desenvolvimento** enquanto cria seu aplicativo. Quando estiver pronto, escolha **Publicado** (npm) para ampla distribuição ou **Interno** (tarball) para implantação privada.
|
||||
</Tip>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user