Compare commits
81
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cc5f3c40a0 | ||
|
|
c753b2bee1 | ||
|
|
70a060b4ee | ||
|
|
40ff109179 | ||
|
|
48172d60fd | ||
|
|
0b0ffcb8fa | ||
|
|
6552ec83ec | ||
|
|
602db4ffea | ||
|
|
3a9247d9d1 | ||
|
|
6b48f197d4 | ||
|
|
2a8912b17a | ||
|
|
55d675bba7 | ||
|
|
d9eb317bb5 | ||
|
|
3054679411 | ||
|
|
1b1d79b08f | ||
|
|
46e515436e | ||
|
|
49bdcd6bd5 | ||
|
|
3f01249967 | ||
|
|
4b6c8d52e5 | ||
|
|
b470cb21a1 | ||
|
|
172bbd01bc | ||
|
|
58f534939c | ||
|
|
0379aea0b1 | ||
|
|
f3e0c12ce6 | ||
|
|
0641e07ca6 | ||
|
|
dfd28f5b4a | ||
|
|
349bfc8462 | ||
|
|
262f9f5fe1 | ||
|
|
5f558e5539 | ||
|
|
1cb4c98cb3 | ||
|
|
a3c392ce8b | ||
|
|
ab13020e2b | ||
|
|
3f420c84d7 | ||
|
|
0ef4741473 | ||
|
|
b5db955ac8 | ||
|
|
2a6fcfcfb3 | ||
|
|
5bfa4c5c39 | ||
|
|
1685d066be | ||
|
|
6a3281a18d | ||
|
|
741e9a8f81 | ||
|
|
0897575fd0 | ||
|
|
501fcc737f | ||
|
|
c9deab4373 | ||
|
|
c1da7be6d7 | ||
|
|
c59f420d21 | ||
|
|
06d4d62e90 | ||
|
|
eb4665bc98 | ||
|
|
f19fcd0010 | ||
|
|
cb3e32df86 | ||
|
|
db5b4d9c6c | ||
|
|
660536d6bb | ||
|
|
e8f8189167 | ||
|
|
78473a606a | ||
|
|
b21fb4aa6f | ||
|
|
38664249cf | ||
|
|
69542898a1 | ||
|
|
09beddb63d | ||
|
|
2eac82c207 | ||
|
|
f262437da6 | ||
|
|
15d0970f72 | ||
|
|
1adc325887 | ||
|
|
5726bd6e17 | ||
|
|
102b49f919 | ||
|
|
2af3121c51 | ||
|
|
a024a04e01 | ||
|
|
f0c83434a7 | ||
|
|
b699619756 | ||
|
|
b2f053490d | ||
|
|
21de221420 | ||
|
|
d9b3507866 | ||
|
|
b346f4fb59 | ||
|
|
2c5af2654d | ||
|
|
6cbc7725b7 | ||
|
|
744ef3aa9d | ||
|
|
ef92d2d321 | ||
|
|
00c3cd1051 | ||
|
|
99f885306e | ||
|
|
413d1124bb | ||
|
|
ab5fb1f658 | ||
|
|
e4e7137660 | ||
|
|
7fb8cc1c39 |
@@ -1,18 +0,0 @@
|
||||
{
|
||||
"install": "curl -fsSL https://deb.nodesource.com/setup_24.x | sudo -E bash - && sudo apt-get install -y nodejs && node --version && yarn install && echo 'Setting up Docker Compose environment...' && cd packages/twenty-docker && cp -n docker-compose.yml docker-compose.dev.yml || true && echo 'Dependencies installed and docker-compose prepared'",
|
||||
"start": "sudo service docker start && echo 'Docker service started' && cd packages/twenty-docker && echo 'Installing yq for YAML processing...' && sudo apt-get update -qq && sudo apt-get install -y wget && wget -qO /usr/local/bin/yq https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 && sudo chmod +x /usr/local/bin/yq && echo 'Patching docker-compose for local development...' && yq eval 'del(.services.server.image)' -i docker-compose.dev.yml && yq eval '.services.server.build.context = \"../../\"' -i docker-compose.dev.yml && yq eval '.services.server.build.dockerfile = \"./packages/twenty-docker/twenty/Dockerfile\"' -i docker-compose.dev.yml && yq eval 'del(.services.worker.image)' -i docker-compose.dev.yml && yq eval '.services.worker.build.context = \"../../\"' -i docker-compose.dev.yml && yq eval '.services.worker.build.dockerfile = \"./packages/twenty-docker/twenty/Dockerfile\"' -i docker-compose.dev.yml && echo 'Setting up .env file with database configuration...' && echo 'SERVER_URL=http://localhost:3000' > .env && echo 'APP_SECRET='$(openssl rand -base64 32) >> .env && echo 'PG_DATABASE_PASSWORD='$(openssl rand -hex 16) >> .env && echo 'PG_DATABASE_URL=postgres://postgres:password@localhost:5432/postgres' >> .env && echo 'SIGN_IN_PREFILLED=true' >> .env && echo 'Building and starting services...' && docker-compose -f docker-compose.dev.yml up -d --build && echo 'Waiting for services to initialize...' && sleep 30 && echo 'Checking service health...' && docker-compose -f docker-compose.dev.yml ps && echo 'Environment setup complete!'",
|
||||
"terminals": [
|
||||
{
|
||||
"name": "Database Setup & Seed",
|
||||
"command": "sleep 40 && cd packages/twenty-docker && echo 'Waiting for PostgreSQL to be ready...' && until docker-compose -f docker-compose.dev.yml exec -T db pg_isready -U postgres; do echo 'Waiting for PostgreSQL...'; sleep 5; done && echo 'PostgreSQL is ready!' && echo 'Waiting for Twenty server to be healthy...' && until docker-compose -f docker-compose.dev.yml exec -T server curl --fail http://localhost:3000/healthz 2>/dev/null; do echo 'Waiting for server...'; sleep 5; done && echo 'Server is healthy!' && echo 'Running database setup and seeding...' && docker-compose -f docker-compose.dev.yml exec -T server npx nx database:reset twenty-server && echo 'Database seeded successfully!' && bash"
|
||||
},
|
||||
{
|
||||
"name": "Application Logs",
|
||||
"command": "sleep 35 && cd packages/twenty-docker && echo 'Following application logs...' && docker-compose -f docker-compose.dev.yml logs -f server worker"
|
||||
},
|
||||
{
|
||||
"name": "Service Monitor",
|
||||
"command": "sleep 15 && cd packages/twenty-docker && echo '=== Service Status Monitor ===' && while true; do clear; echo '=== Service Status at $(date) ===' && docker-compose -f docker-compose.dev.yml ps && echo '\\n=== Health Status ===' && (docker-compose -f docker-compose.dev.yml exec -T server curl -s http://localhost:3000/healthz 2>/dev/null && echo '✅ Twenty Server: Healthy') || echo '❌ Twenty Server: Not Ready' && (docker-compose -f docker-compose.dev.yml exec -T db pg_isready -U postgres 2>/dev/null && echo '✅ PostgreSQL: Ready') || echo '❌ PostgreSQL: Not Ready' && echo '\\n=== Database Connection Test ===' && docker-compose -f docker-compose.dev.yml exec -T server node -e \"const { Client } = require('pg'); const client = new Client({connectionString: process.env.PG_DATABASE_URL}); client.connect().then(() => {console.log('✅ Database Connection: OK'); client.end();}).catch(e => console.log('❌ Database Connection: Failed -', e.message));\" || echo 'Connection test failed' && sleep 45; done"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"install": "yarn install",
|
||||
"start": "sudo service docker start && sleep 2 && (docker start twenty_pg 2>/dev/null || make -C packages/twenty-docker postgres-on-docker) && (docker start twenty_redis 2>/dev/null || make -C packages/twenty-docker redis-on-docker) && until docker exec twenty_pg pg_isready -U postgres -h localhost 2>/dev/null; do sleep 1; done && echo 'PostgreSQL ready' && until docker exec twenty_redis redis-cli ping 2>/dev/null | grep -q PONG; do sleep 1; done && echo 'Redis ready' && bash packages/twenty-utils/setup-dev-env.sh && npx nx database:reset twenty-server",
|
||||
"start": "(sudo service docker start || service docker start || true) && bash packages/twenty-utils/setup-dev-env.sh && npx nx database:reset twenty-server",
|
||||
"terminals": [
|
||||
{
|
||||
"name": "Development Server",
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
storage: /tmp/verdaccio-storage
|
||||
auth:
|
||||
htpasswd:
|
||||
file: /tmp/verdaccio-htpasswd
|
||||
max_users: 100
|
||||
uplinks:
|
||||
npmjs:
|
||||
url: https://registry.npmjs.org/
|
||||
packages:
|
||||
'twenty-sdk':
|
||||
access: $all
|
||||
publish: $all
|
||||
'create-twenty-app':
|
||||
access: $all
|
||||
publish: $all
|
||||
'**':
|
||||
access: $all
|
||||
proxy: npmjs
|
||||
log: { type: stdout, format: pretty, level: warn }
|
||||
@@ -0,0 +1,182 @@
|
||||
name: CI Create App E2E
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
|
||||
jobs:
|
||||
changed-files-check:
|
||||
uses: ./.github/workflows/changed-files.yaml
|
||||
with:
|
||||
files: |
|
||||
packages/create-twenty-app/**
|
||||
packages/twenty-sdk/**
|
||||
packages/twenty-shared/**
|
||||
packages/twenty-server/**
|
||||
!packages/create-twenty-app/package.json
|
||||
!packages/twenty-sdk/package.json
|
||||
!packages/twenty-shared/package.json
|
||||
!packages/twenty-server/package.json
|
||||
create-app-e2e:
|
||||
needs: changed-files-check
|
||||
if: needs.changed-files-check.outputs.any_changed == 'true'
|
||||
timeout-minutes: 30
|
||||
runs-on: ubuntu-latest-4-cores
|
||||
services:
|
||||
postgres:
|
||||
image: twentycrm/twenty-postgres-spilo
|
||||
env:
|
||||
PGUSER_SUPERUSER: postgres
|
||||
PGPASSWORD_SUPERUSER: postgres
|
||||
ALLOW_NOSSL: 'true'
|
||||
SPILO_PROVIDER: 'local'
|
||||
ports:
|
||||
- 5432:5432
|
||||
options: >-
|
||||
--health-cmd pg_isready
|
||||
--health-interval 10s
|
||||
--health-timeout 5s
|
||||
--health-retries 5
|
||||
redis:
|
||||
image: redis
|
||||
ports:
|
||||
- 6379:6379
|
||||
steps:
|
||||
- name: Fetch custom Github Actions and base branch history
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 10
|
||||
|
||||
- name: Install dependencies
|
||||
uses: ./.github/actions/yarn-install
|
||||
|
||||
- name: Set CI version and prepare packages for publish
|
||||
run: |
|
||||
CI_VERSION="0.0.0-ci.$(date +%s)"
|
||||
echo "CI_VERSION=$CI_VERSION" >> $GITHUB_ENV
|
||||
npx nx run-many -t set-local-version -p twenty-sdk create-twenty-app --releaseVersion=$CI_VERSION
|
||||
|
||||
- name: Build packages
|
||||
run: |
|
||||
npx nx build twenty-sdk
|
||||
npx nx build create-twenty-app
|
||||
|
||||
- name: Install and start Verdaccio
|
||||
run: |
|
||||
npx verdaccio --config .github/verdaccio-config.yaml &
|
||||
|
||||
for i in $(seq 1 30); do
|
||||
if curl -s http://localhost:4873 > /dev/null 2>&1; then
|
||||
echo "Verdaccio is ready"
|
||||
break
|
||||
fi
|
||||
echo "Waiting for Verdaccio... ($i/30)"
|
||||
sleep 1
|
||||
done
|
||||
|
||||
- name: Publish packages to local registry
|
||||
run: |
|
||||
npm set //localhost:4873/:_authToken "ci-auth-token"
|
||||
|
||||
for pkg in twenty-sdk create-twenty-app; do
|
||||
cd packages/$pkg
|
||||
npm publish --registry http://localhost:4873 --tag ci
|
||||
cd ../..
|
||||
done
|
||||
|
||||
- name: Scaffold app using published create-twenty-app
|
||||
run: |
|
||||
npm install -g create-twenty-app@$CI_VERSION --registry http://localhost:4873
|
||||
create-twenty-app --version
|
||||
mkdir -p /tmp/e2e-test-workspace
|
||||
cd /tmp/e2e-test-workspace
|
||||
create-twenty-app test-app --exhaustive --display-name "Test App" --description "E2E test app"
|
||||
|
||||
- name: Install scaffolded app dependencies
|
||||
run: |
|
||||
cd /tmp/e2e-test-workspace/test-app
|
||||
echo 'npmRegistryServer: "http://localhost:4873"' >> .yarnrc.yml
|
||||
echo 'unsafeHttpWhitelist: ["localhost"]' >> .yarnrc.yml
|
||||
YARN_ENABLE_IMMUTABLE_INSTALLS=false yarn install --no-immutable
|
||||
|
||||
- name: Verify installed app versions
|
||||
run: |
|
||||
cd /tmp/e2e-test-workspace/test-app
|
||||
echo "--- Checking package.json references correct SDK version ---"
|
||||
node -e "
|
||||
const pkg = require('./package.json');
|
||||
const sdkVersion = pkg.devDependencies['twenty-sdk'];
|
||||
if (!sdkVersion.startsWith('0.0.0-ci.')) {
|
||||
console.error('Expected twenty-sdk version to start with 0.0.0-ci., got:', sdkVersion);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log('SDK version in scaffolded app:', sdkVersion);
|
||||
"
|
||||
|
||||
- name: Verify SDK CLI is available
|
||||
run: |
|
||||
cd /tmp/e2e-test-workspace/test-app
|
||||
npx --no-install twenty --version
|
||||
|
||||
- name: Setup server environment
|
||||
run: npx nx reset:env:e2e-testing-server twenty-server
|
||||
|
||||
- name: Build server
|
||||
run: npx nx build twenty-server
|
||||
|
||||
- name: Create and setup database
|
||||
run: |
|
||||
PGPASSWORD=postgres psql -h localhost -p 5432 -U postgres -d postgres -c 'CREATE DATABASE "default";'
|
||||
PGPASSWORD=postgres psql -h localhost -p 5432 -U postgres -d postgres -c 'CREATE DATABASE "test";'
|
||||
npx nx run twenty-server:database:reset
|
||||
|
||||
- name: Start server
|
||||
run: |
|
||||
npx nx start twenty-server &
|
||||
echo "Waiting for server to be ready..."
|
||||
timeout 60 bash -c 'until curl -s http://localhost:3000/health; do sleep 2; done'
|
||||
|
||||
- name: Authenticate with twenty-server
|
||||
env:
|
||||
SEED_API_KEY: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIyMDIwMjAyMC1lNmI1LTQ2ODAtOGEzMi1iODIwOTczNzE1NmIiLCJ1c2VySWQiOiIyMDIwMjAyMC1lNmI1LTQ2ODAtOGEzMi1iODIwOTczNzE1NmIiLCJ3b3Jrc3BhY2VJZCI6IjIwMjAyMDIwLTFjMjUtNGQwMi1iZjI1LTZhZWNjZjdlYTQxOSIsIndvcmtzcGFjZU1lbWJlcklkIjoiMjAyMDIwMjAtNDYzZi00MzViLTgyOGMtMTA3ZTAwN2EyNzExIiwidXNlcldvcmtzcGFjZUlkIjoiMjAyMDIwMjAtMWU3Yy00M2Q5LWE1ZGItNjg1YjUwNjlkODE2IiwidHlwZSI6IkFDQ0VTUyIsImF1dGhQcm92aWRlciI6InBhc3N3b3JkIiwiaWF0IjoxNzUxMjgxNzA0LCJleHAiOjIwNjY4NTc3MDR9.HMGqCsVlOAPVUBhKSGlD1X86VoHKt4LIUtET3CGIdik'
|
||||
run: |
|
||||
cd /tmp/e2e-test-workspace/test-app
|
||||
npx --no-install twenty auth:login --api-key $SEED_API_KEY --api-url http://localhost:3000
|
||||
|
||||
- name: Build scaffolded app
|
||||
run: |
|
||||
cd /tmp/e2e-test-workspace/test-app
|
||||
npx --no-install twenty app:build
|
||||
test -d .twenty/output
|
||||
|
||||
- name: Execute hello-world logic function
|
||||
run: |
|
||||
cd /tmp/e2e-test-workspace/test-app
|
||||
EXEC_OUTPUT=$(npx --no-install twenty function:execute --functionName hello-world-logic-function)
|
||||
echo "$EXEC_OUTPUT"
|
||||
echo "$EXEC_OUTPUT" | grep -q "Hello, World!"
|
||||
|
||||
- name: Run scaffolded app integration test
|
||||
run: |
|
||||
cd /tmp/e2e-test-workspace/test-app
|
||||
yarn test
|
||||
|
||||
ci-create-app-e2e-status-check:
|
||||
if: always() && !cancelled()
|
||||
timeout-minutes: 5
|
||||
runs-on: ubuntu-latest
|
||||
needs: [changed-files-check, create-app-e2e]
|
||||
steps:
|
||||
- name: Fail job if any needs failed
|
||||
if: contains(needs.*.result, 'failure')
|
||||
run: exit 1
|
||||
@@ -40,7 +40,8 @@ jobs:
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
token: ${{ github.token }}
|
||||
ref: ${{ github.event_name == 'pull_request' && github.head_ref || github.ref }}
|
||||
repository: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name || github.repository }}
|
||||
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.ref }}
|
||||
|
||||
- name: Install dependencies
|
||||
uses: ./.github/actions/yarn-install
|
||||
@@ -111,7 +112,7 @@ jobs:
|
||||
run: yarn docs:generate-paths
|
||||
|
||||
- name: Commit artifacts to pull request branch
|
||||
if: github.event_name == 'pull_request'
|
||||
if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository
|
||||
run: |
|
||||
git add packages/twenty-docs/docs.json packages/twenty-docs/navigation/navigation.template.json packages/twenty-shared/src/constants/DocumentationPaths.ts
|
||||
if git diff --staged --quiet --exit-code; then
|
||||
@@ -149,4 +150,3 @@ jobs:
|
||||
fi
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
|
||||
@@ -188,13 +188,22 @@ IMPORTANT: Use Context7 for code generation, setup or configuration steps, or li
|
||||
- Descriptive test names: "should [behavior] when [condition]"
|
||||
- Clear mocks between tests with `jest.clearAllMocks()`
|
||||
|
||||
## CI Environment (GitHub Actions)
|
||||
## Dev Environment Setup
|
||||
|
||||
When running in CI, the dev environment is **not** pre-configured. Dependencies are installed but builds, env files, and databases are not set up.
|
||||
All dev environments (Claude Code web, Cursor, local) use one script:
|
||||
|
||||
- **Before running tests, builds, lint, type checks, or DB operations**, run: `bash packages/twenty-utils/setup-dev-env.sh`
|
||||
```bash
|
||||
bash packages/twenty-utils/setup-dev-env.sh
|
||||
```
|
||||
|
||||
This handles everything: starts Postgres + Redis (auto-detects local services vs Docker), creates databases, and copies `.env` files. Idempotent — safe to run multiple times.
|
||||
|
||||
- `--docker` — force Docker mode (uses `packages/twenty-docker/docker-compose.dev.yml`)
|
||||
- `--down` — stop services
|
||||
- `--reset` — wipe data and restart fresh
|
||||
- **Skip the setup script** for tasks that only read code — architecture questions, code review, documentation, etc.
|
||||
- The script is idempotent and safe to run multiple times.
|
||||
|
||||
**Note:** CI workflows (GitHub Actions) manage services via Actions service containers and run setup steps individually — they don't use this script.
|
||||
|
||||
## Important Files
|
||||
- `nx.json` - Nx workspace configuration with task definitions
|
||||
|
||||
@@ -25,8 +25,8 @@
|
||||
# Installation
|
||||
|
||||
See:
|
||||
🚀 [Self-hosting](https://docs.twenty.com/developers/self-hosting/docker-compose)
|
||||
🖥️ [Local Setup](https://docs.twenty.com/developers/local-setup)
|
||||
🚀 [Self-hosting](https://docs.twenty.com/developers/self-host/capabilities/docker-compose)
|
||||
🖥️ [Local Setup](https://docs.twenty.com/developers/contribute/capabilities/local-setup)
|
||||
|
||||
# Why Twenty
|
||||
|
||||
@@ -36,7 +36,7 @@ We built Twenty for three reasons:
|
||||
|
||||
**A fresh start is required to build a better experience.** We can learn from past mistakes and craft a cohesive experience inspired by new UX patterns from tools like Notion, Airtable or Linear.
|
||||
|
||||
**We believe in Open-source and community.** Hundreds of developers are already building Twenty together. Once we have plugin capabilities, a whole ecosystem will grow around it.
|
||||
**We believe in open-source and community.** Hundreds of developers are already building Twenty together. Once we have plugin capabilities, a whole ecosystem will grow around it.
|
||||
|
||||
<br />
|
||||
|
||||
|
||||
@@ -136,6 +136,14 @@
|
||||
"cache": true,
|
||||
"dependsOn": ["^build"]
|
||||
},
|
||||
"set-local-version": {
|
||||
"executor": "nx:run-commands",
|
||||
"cache": false,
|
||||
"options": {
|
||||
"cwd": "{projectRoot}",
|
||||
"command": "npm pkg set version={args.releaseVersion}"
|
||||
}
|
||||
},
|
||||
"storybook:build": {
|
||||
"executor": "nx:run-commands",
|
||||
"cache": true,
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@apollo/client": "^3.7.17",
|
||||
"@apollo/client": "^4.0.0",
|
||||
"@floating-ui/react": "^0.24.3",
|
||||
"@linaria/core": "^6.2.0",
|
||||
"@linaria/react": "^6.2.1",
|
||||
@@ -164,6 +164,7 @@
|
||||
"tsc-alias": "^1.8.16",
|
||||
"tsconfig-paths": "^4.2.0",
|
||||
"tsx": "^4.17.0",
|
||||
"verdaccio": "^6.3.1",
|
||||
"vite": "^7.0.0",
|
||||
"vitest": "^4.0.18"
|
||||
},
|
||||
@@ -206,7 +207,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",
|
||||
|
||||
@@ -58,6 +58,12 @@ yarn twenty function:execute --preInstall
|
||||
# Execute the post-install function
|
||||
yarn twenty function:execute --postInstall
|
||||
|
||||
# Build the app for distribution
|
||||
yarn twenty app:build
|
||||
|
||||
# Publish the app to npm or directly to a Twenty server
|
||||
yarn twenty app:publish
|
||||
|
||||
# Uninstall the application from the current workspace
|
||||
yarn twenty app:uninstall
|
||||
```
|
||||
@@ -109,29 +115,40 @@ npx create-twenty-app@latest my-app -m
|
||||
- Use `yarn twenty app:dev` while you iterate — it watches, builds, and syncs changes to your workspace in real time.
|
||||
- `CoreApiClient` (for workspace data via `/graphql`) is auto-generated by `yarn twenty app:dev`. `MetadataApiClient` (for workspace configuration and file uploads via `/metadata`) ships pre-built with the SDK. Both are available via `import { CoreApiClient, MetadataApiClient } from 'twenty-sdk/clients'`.
|
||||
|
||||
## Publish your application
|
||||
## Build and publish your application
|
||||
|
||||
Applications are currently stored in `twenty/packages/twenty-apps`.
|
||||
Once your app is ready, build and publish it using the CLI:
|
||||
|
||||
You can share your application with all Twenty users:
|
||||
```bash
|
||||
# Build the app (output goes to .twenty/output/)
|
||||
yarn twenty app:build
|
||||
|
||||
# Build and create a tarball (.tgz) for distribution
|
||||
yarn twenty app:build --tarball
|
||||
|
||||
# Publish to npm (requires npm login)
|
||||
yarn twenty app:publish
|
||||
|
||||
# Publish with a dist-tag (e.g. beta, next)
|
||||
yarn twenty app:publish --tag beta
|
||||
|
||||
# Publish directly to a Twenty server (builds, uploads, and installs in one step)
|
||||
yarn twenty app:publish --server https://app.twenty.com
|
||||
```
|
||||
|
||||
### Publish to the Twenty marketplace
|
||||
|
||||
You can also contribute your application to the curated marketplace:
|
||||
|
||||
```bash
|
||||
# pull the Twenty project
|
||||
git clone https://github.com/twentyhq/twenty.git
|
||||
cd twenty
|
||||
|
||||
# create a new branch
|
||||
git checkout -b feature/my-awesome-app
|
||||
```
|
||||
|
||||
- Copy your app folder into `twenty/packages/twenty-apps`.
|
||||
- Commit your changes and open a pull request on https://github.com/twentyhq/twenty
|
||||
|
||||
```bash
|
||||
git commit -m "Add new application"
|
||||
git push
|
||||
```
|
||||
|
||||
Our team reviews contributions for quality, security, and reusability before merging.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "create-twenty-app",
|
||||
"version": "0.7.0-canary.0",
|
||||
"version": "0.7.0",
|
||||
"description": "Command-line interface to create Twenty application",
|
||||
"main": "dist/cli.cjs",
|
||||
"bin": "dist/cli.cjs",
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
"command": "node dist/cli.cjs"
|
||||
}
|
||||
},
|
||||
"set-local-version": {},
|
||||
"typecheck": {},
|
||||
"lint": {},
|
||||
"test": {
|
||||
|
||||
@@ -18,6 +18,15 @@ const program = new Command(packageJson.name)
|
||||
'-m, --minimal',
|
||||
'Create only core entities (application-config and default-role)',
|
||||
)
|
||||
.option('-n, --name <name>', 'Application name (skips prompt)')
|
||||
.option(
|
||||
'-d, --display-name <displayName>',
|
||||
'Application display name (skips prompt)',
|
||||
)
|
||||
.option(
|
||||
'--description <description>',
|
||||
'Application description (skips prompt)',
|
||||
)
|
||||
.helpOption('-h, --help', 'Display this help message.')
|
||||
.action(
|
||||
async (
|
||||
@@ -25,6 +34,9 @@ const program = new Command(packageJson.name)
|
||||
options?: {
|
||||
exhaustive?: boolean;
|
||||
minimal?: boolean;
|
||||
name?: string;
|
||||
displayName?: string;
|
||||
description?: string;
|
||||
},
|
||||
) => {
|
||||
const modeFlags = [options?.exhaustive, options?.minimal].filter(Boolean);
|
||||
@@ -47,9 +59,20 @@ const program = new Command(packageJson.name)
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (options?.name !== undefined && options.name.trim().length === 0) {
|
||||
console.error(chalk.red('Error: --name cannot be empty.'));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const mode: ScaffoldingMode = options?.minimal ? 'minimal' : 'exhaustive';
|
||||
|
||||
await new CreateAppCommand().execute(directory, mode);
|
||||
await new CreateAppCommand().execute({
|
||||
directory,
|
||||
mode,
|
||||
name: options?.name,
|
||||
displayName: options?.displayName,
|
||||
description: options?.description,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -11,3 +11,4 @@
|
||||
|
||||
- Creating an object without an index view associated. Unless this is a technical object, user will need to visualize it.
|
||||
- Creating a view without a navigationMenuItem associated. This will make the view available on the left sidebar.
|
||||
- Creating a front-end component that has a scroll instead of being responsive to its fixed widget height and width, unless it is specifically meant to be used in a canvas tab.
|
||||
|
||||
@@ -7,6 +7,7 @@ import * as fs from 'fs-extra';
|
||||
import inquirer from 'inquirer';
|
||||
import kebabCase from 'lodash.kebabcase';
|
||||
import * as path from 'path';
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
|
||||
import {
|
||||
type ExampleOptions,
|
||||
@@ -15,16 +16,23 @@ import {
|
||||
|
||||
const CURRENT_EXECUTION_DIRECTORY = process.env.INIT_CWD || process.cwd();
|
||||
|
||||
type CreateAppOptions = {
|
||||
directory?: string;
|
||||
mode?: ScaffoldingMode;
|
||||
name?: string;
|
||||
displayName?: string;
|
||||
description?: string;
|
||||
};
|
||||
|
||||
export class CreateAppCommand {
|
||||
async execute(
|
||||
directory?: string,
|
||||
mode: ScaffoldingMode = 'exhaustive',
|
||||
): Promise<void> {
|
||||
async execute(options: CreateAppOptions = {}): Promise<void> {
|
||||
try {
|
||||
const { appName, appDisplayName, appDirectory, appDescription } =
|
||||
await this.getAppInfos(directory);
|
||||
await this.getAppInfos(options);
|
||||
|
||||
const exampleOptions = this.resolveExampleOptions(mode);
|
||||
const exampleOptions = this.resolveExampleOptions(
|
||||
options.mode ?? 'exhaustive',
|
||||
);
|
||||
|
||||
await this.validateDirectory(appDirectory);
|
||||
|
||||
@@ -54,19 +62,25 @@ export class CreateAppCommand {
|
||||
}
|
||||
}
|
||||
|
||||
private async getAppInfos(directory?: string): Promise<{
|
||||
private async getAppInfos(options: CreateAppOptions): Promise<{
|
||||
appName: string;
|
||||
appDisplayName: string;
|
||||
appDescription: string;
|
||||
appDirectory: string;
|
||||
}> {
|
||||
const { directory } = options;
|
||||
|
||||
const hasName = isDefined(options.name) || isDefined(directory);
|
||||
const hasDisplayName = isDefined(options.displayName);
|
||||
const hasDescription = isDefined(options.description);
|
||||
|
||||
const { name, displayName, description } = await inquirer.prompt([
|
||||
{
|
||||
type: 'input',
|
||||
name: 'name',
|
||||
message: 'Application name:',
|
||||
when: () => !directory,
|
||||
default: 'my-awesome-app',
|
||||
when: () => !hasName,
|
||||
default: 'my-twenty-app',
|
||||
validate: (input) => {
|
||||
if (input.length === 0) return 'Application name is required';
|
||||
return true;
|
||||
@@ -76,25 +90,33 @@ export class CreateAppCommand {
|
||||
type: 'input',
|
||||
name: 'displayName',
|
||||
message: 'Application display name:',
|
||||
default: (answers: any) => {
|
||||
return convertToLabel(answers?.name ?? directory);
|
||||
when: () => !hasDisplayName,
|
||||
default: (answers: { name?: string }) => {
|
||||
return convertToLabel(
|
||||
answers?.name ?? options.name ?? directory ?? '',
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'input',
|
||||
name: 'description',
|
||||
message: 'Application description (optional):',
|
||||
when: () => !hasDescription,
|
||||
default: '',
|
||||
},
|
||||
]);
|
||||
|
||||
const computedName = name ?? directory;
|
||||
const appName = (
|
||||
options.name ??
|
||||
name ??
|
||||
directory ??
|
||||
'my-twenty-app'
|
||||
).trim();
|
||||
|
||||
const appName = computedName.trim();
|
||||
const appDisplayName =
|
||||
(options.displayName ?? displayName)?.trim() || convertToLabel(appName);
|
||||
|
||||
const appDisplayName = displayName.trim();
|
||||
|
||||
const appDescription = description.trim();
|
||||
const appDescription = (options.description ?? description ?? '').trim();
|
||||
|
||||
const appDirectory = directory
|
||||
? path.join(CURRENT_EXECUTION_DIRECTORY, directory)
|
||||
|
||||
@@ -30,12 +30,12 @@ export const copyBaseApplicationProject = async ({
|
||||
includeExampleIntegrationTest: exampleOptions.includeExampleIntegrationTest,
|
||||
});
|
||||
|
||||
await createYarnLock(appDirectory);
|
||||
|
||||
await createGitignore(appDirectory);
|
||||
|
||||
await createPublicAssetDirectory(appDirectory);
|
||||
|
||||
await createYarnLock(appDirectory);
|
||||
|
||||
const sourceFolderPath = join(appDirectory, SRC_FOLDER);
|
||||
|
||||
await fs.ensureDir(sourceFolderPath);
|
||||
@@ -142,13 +142,6 @@ const createPublicAssetDirectory = async (appDirectory: string) => {
|
||||
await fs.ensureDir(join(appDirectory, ASSETS_DIR));
|
||||
};
|
||||
|
||||
const createYarnLock = async (appDirectory: string) => {
|
||||
const yarnLockContent = `# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
|
||||
# yarn lockfile v1
|
||||
`;
|
||||
|
||||
await fs.writeFile(join(appDirectory, 'yarn.lock'), yarnLockContent);
|
||||
};
|
||||
const createGitignore = async (appDirectory: string) => {
|
||||
const gitignoreContent = `# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
@@ -590,6 +583,14 @@ export default defineApplication({
|
||||
await fs.writeFile(join(appDirectory, fileFolder ?? '', fileName), content);
|
||||
};
|
||||
|
||||
const createYarnLock = async (appDirectory: string) => {
|
||||
const yarnLockContent = `# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
|
||||
# yarn lockfile v1
|
||||
`;
|
||||
|
||||
await fs.writeFile(join(appDirectory, 'yarn.lock'), yarnLockContent);
|
||||
};
|
||||
|
||||
const createPackageJson = async ({
|
||||
appName,
|
||||
appDirectory,
|
||||
|
||||
+3
-3
@@ -30,7 +30,7 @@ type AnalysisResult = {
|
||||
commitments: Commitment[];
|
||||
};
|
||||
|
||||
type RichTextV2Data = {
|
||||
type RichTextData = {
|
||||
markdown: string;
|
||||
blocknote: null;
|
||||
};
|
||||
@@ -123,7 +123,7 @@ const createNoteInTwenty = async (
|
||||
bodyV2: {
|
||||
markdown: noteBodyMarkdown,
|
||||
blocknote: null,
|
||||
} satisfies RichTextV2Data,
|
||||
} satisfies RichTextData,
|
||||
};
|
||||
|
||||
try {
|
||||
@@ -159,7 +159,7 @@ const createTaskInTwenty = async (
|
||||
|
||||
const taskData: {
|
||||
title: string;
|
||||
bodyV2: RichTextV2Data;
|
||||
bodyV2: RichTextData;
|
||||
dueAt?: string;
|
||||
} = {
|
||||
title: actionItem.title,
|
||||
|
||||
@@ -10,3 +10,4 @@
|
||||
|
||||
- Creating an object without an index view associated. Unless this is a technical object, user will need to visualize it.
|
||||
- Creating a view without a navigationMenuItem associated. This will make the view available on the left sidebar.
|
||||
- Creating a front-end component that has a scroll instead of being responsive to its fixed widget height and width, unless it is specifically meant to be used in a canvas tab.
|
||||
|
||||
+3
-3
@@ -32,7 +32,7 @@ type AnalysisResult = {
|
||||
commitments: Commitment[];
|
||||
};
|
||||
|
||||
type RichTextV2Data = {
|
||||
type RichTextData = {
|
||||
markdown: string;
|
||||
blocknote: null;
|
||||
};
|
||||
@@ -362,7 +362,7 @@ const createNoteInTwenty = async (
|
||||
bodyV2: {
|
||||
markdown: noteBodyMarkdown,
|
||||
blocknote: null,
|
||||
} satisfies RichTextV2Data,
|
||||
} satisfies RichTextData,
|
||||
};
|
||||
|
||||
try {
|
||||
@@ -451,7 +451,7 @@ const createTaskInTwenty = async (
|
||||
|
||||
const taskData: {
|
||||
title: string;
|
||||
bodyV2: RichTextV2Data;
|
||||
bodyV2: RichTextData;
|
||||
dueAt?: string;
|
||||
assigneeId?: string;
|
||||
} = {
|
||||
|
||||
@@ -10,3 +10,4 @@
|
||||
|
||||
- Creating an object without an index view associated. Unless this is a technical object, user will need to visualize it.
|
||||
- Creating a view without a navigationMenuItem associated. This will make the view available on the left sidebar.
|
||||
- Creating a front-end component that has a scroll instead of being responsive to its fixed widget height and width, unless it is specifically meant to be used in a canvas tab.
|
||||
|
||||
@@ -7,3 +7,4 @@
|
||||
|
||||
- Creating an object without an index view associated. Unless this is a technical object, user will need to visualize it.
|
||||
- Creating a view without a navigationMenuItem associated. This will make the view available on the left sidebar.
|
||||
- Creating a front-end component that has a scroll instead of being responsive to its fixed widget height and width, unless it is specifically meant to be used in a canvas tab.
|
||||
|
||||
@@ -81,7 +81,7 @@ export default defineObject({
|
||||
},
|
||||
{
|
||||
universalIdentifier: TRANSCRIPT_FIELD_UNIVERSAL_IDENTIFIER,
|
||||
type: FieldType.RICH_TEXT_V2,
|
||||
type: FieldType.RICH_TEXT,
|
||||
name: 'transcript',
|
||||
label: 'Transcript',
|
||||
description: 'Human-readable transcript of the call',
|
||||
@@ -114,7 +114,7 @@ export default defineObject({
|
||||
},
|
||||
{
|
||||
universalIdentifier: SUMMARY_FIELD_UNIVERSAL_IDENTIFIER,
|
||||
type: FieldType.RICH_TEXT_V2,
|
||||
type: FieldType.RICH_TEXT,
|
||||
name: 'summary',
|
||||
label: 'Summary',
|
||||
description: 'AI-generated summary of the call',
|
||||
|
||||
+1
-1
@@ -16,7 +16,7 @@ Use this skill when a user asks you to summarize, analyze, or extract insights f
|
||||
|
||||
## How to Access the Data
|
||||
1. Use \`find_one_callRecording\` to fetch the call recording by its ID.
|
||||
2. Read the \`transcript\` field (RICH_TEXT_V2, markdown format) which contains the full conversation.
|
||||
2. Read the \`transcript\` field (RICH_TEXT, markdown format) which contains the full conversation.
|
||||
3. The transcript uses the format: **Speaker Name:** spoken text
|
||||
|
||||
## What to Produce
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
# Development infrastructure services only (Postgres + Redis).
|
||||
# Use this when developing locally against the source code.
|
||||
#
|
||||
# Usage:
|
||||
# docker compose -f docker-compose.dev.yml up -d
|
||||
# docker compose -f docker-compose.dev.yml down # stop
|
||||
# docker compose -f docker-compose.dev.yml down -v # stop + wipe data
|
||||
|
||||
name: twenty-dev
|
||||
|
||||
services:
|
||||
db:
|
||||
image: postgres:16
|
||||
volumes:
|
||||
- dev-db-data:/var/lib/postgresql/data
|
||||
ports:
|
||||
- "5432:5432"
|
||||
environment:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: postgres
|
||||
POSTGRES_DB: default
|
||||
healthcheck:
|
||||
test: pg_isready -U postgres -h localhost -d postgres
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
restart: unless-stopped
|
||||
|
||||
redis:
|
||||
image: redis:7
|
||||
ports:
|
||||
- "6379:6379"
|
||||
command: ["--maxmemory-policy", "noeviction"]
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
dev-db-data:
|
||||
@@ -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
|
||||
@@ -29,13 +28,11 @@ 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-sdk twenty-server
|
||||
|
||||
# Build the front
|
||||
FROM common-deps AS twenty-front-build
|
||||
|
||||
+2
-3
@@ -9,7 +9,7 @@ The goal here is to have a consistent codebase, which is easy to read and easy t
|
||||
|
||||
For this, it's better to be a bit more verbose than to be too concise.
|
||||
|
||||
Always keep in mind that people read code more often than they write it, specially on an open source project, where anyone can contribute.
|
||||
Always keep in mind that people read code more often than they write it, especially on an open source project, where anyone can contribute.
|
||||
|
||||
There are a lot of rules that are not defined here, but that are automatically checked by linters.
|
||||
|
||||
@@ -150,7 +150,7 @@ type MyType = {
|
||||
|
||||
### Use string literals instead of enums
|
||||
|
||||
[String literals](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types) are the go-to way to handle enum-like values in TypeScript. They are easier to extend with Pick and Omit, and offer a better developer experience, specially with code completion.
|
||||
[String literals](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types) are the go-to way to handle enum-like values in TypeScript. They are easier to extend with Pick and Omit, and offer a better developer experience, especially with code completion.
|
||||
|
||||
You can see why TypeScript recommends avoiding enums [here](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#enums).
|
||||
|
||||
@@ -288,4 +288,3 @@ An Oxlint rule, `typescript/consistent-type-imports`, enforces the no-type impor
|
||||
Please note that this rule specifically addresses rare edge cases where unintentional type imports occur. TypeScript itself discourages this practice, as mentioned in the [TypeScript 3.8 release notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html). In most situations, you should not need to use type-only imports.
|
||||
|
||||
To ensure your code complies with this rule, make sure to run Oxlint as part of your development workflow.
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ description: "The guide for contributors (or curious developers) who want to run
|
||||
## Prerequisites
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Linux and MacOS">
|
||||
<Tab title="Linux and macOS">
|
||||
|
||||
Before you can install and use Twenty, make sure you install the following on your computer:
|
||||
- [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
|
||||
@@ -31,7 +31,7 @@ wsl --install
|
||||
```
|
||||
You should now see a prompt to restart your computer. If not, restart it manually.
|
||||
|
||||
Upon restart, a powershell window will open and install Ubuntu. This may take up some time.
|
||||
Upon restart, a PowerShell window will open and install Ubuntu. This may take up some time.
|
||||
You'll see a prompt to create a username and password for your Ubuntu installation.
|
||||
|
||||
2. Install and configure git
|
||||
@@ -104,7 +104,7 @@ You should run all commands in the following steps from the root of the project.
|
||||
<Tabs>
|
||||
<Tab title="Linux">
|
||||
**Option 1 (preferred):** To provision your database locally:
|
||||
Use the following link to install Postgresql on your Linux machine: [Postgresql Installation](https://www.postgresql.org/download/linux/)
|
||||
Use the following link to install PostgreSQL on your Linux machine: [PostgreSQL Installation](https://www.postgresql.org/download/linux/)
|
||||
```bash
|
||||
psql postgres -c "CREATE DATABASE \"default\";" -c "CREATE DATABASE test;"
|
||||
```
|
||||
@@ -131,7 +131,7 @@ You should run all commands in the following steps from the root of the project.
|
||||
```
|
||||
|
||||
The installer might not create the `postgres` user by default when installing
|
||||
via Homebrew on MacOS. Instead, it creates a PostgreSQL role that matches your macOS
|
||||
via Homebrew on macOS. Instead, it creates a PostgreSQL role that matches your macOS
|
||||
username (e.g., "john").
|
||||
To check and create the `postgres` user if necessary, follow these steps:
|
||||
```bash
|
||||
@@ -174,8 +174,8 @@ You should run all commands in the following steps from the root of the project.
|
||||
<Tab title="Windows (WSL)">
|
||||
All the following steps are to be run in the WSL terminal (within your virtual machine)
|
||||
|
||||
**Option 1:** To provision your Postgresql locally:
|
||||
Use the following link to install Postgresql on your Linux virtual machine: [Postgresql Installation](https://www.postgresql.org/download/linux/)
|
||||
**Option 1:** To provision your PostgreSQL locally:
|
||||
Use the following link to install PostgreSQL on your Linux virtual machine: [PostgreSQL Installation](https://www.postgresql.org/download/linux/)
|
||||
```bash
|
||||
psql postgres -c "CREATE DATABASE \"default\";" -c "CREATE DATABASE test;"
|
||||
```
|
||||
@@ -190,10 +190,12 @@ You should run all commands in the following steps from the root of the project.
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
You can now access the database at [localhost:5432](localhost:5432), with user `postgres` and password `postgres` .
|
||||
You can now access the database at `localhost:5432`.
|
||||
|
||||
If you used the Docker option above, the default credentials are user `postgres` and password `postgres`. For native PostgreSQL installations, use the credentials and roles configured on your machine.
|
||||
|
||||
## Step 4: Set up a Redis Database (cache)
|
||||
Twenty requires a redis cache to provide the best performance
|
||||
Twenty requires a Redis cache to provide the best performance.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Linux">
|
||||
@@ -210,8 +212,10 @@ Twenty requires a redis cache to provide the best performance
|
||||
```bash
|
||||
brew install redis
|
||||
```
|
||||
Start your redis server:
|
||||
```brew services start redis```
|
||||
Start your Redis server:
|
||||
```bash
|
||||
brew services start redis
|
||||
```
|
||||
|
||||
**Option 2:** If you have docker installed:
|
||||
```bash
|
||||
@@ -229,11 +233,11 @@ Twenty requires a redis cache to provide the best performance
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
If you need a Client GUI, we recommend [redis insight](https://redis.io/insight/) (free version available)
|
||||
If you need a client GUI, we recommend [Redis Insight](https://redis.io/insight/) (free version available).
|
||||
|
||||
## Step 5: Setup environment variables
|
||||
## Step 5: Set up environment variables
|
||||
|
||||
Use environment variables or `.env` files to configure your project. More info [here](/developers/self-host/capabilities/setup)
|
||||
Use environment variables or `.env` files to configure your project. More info [here](/developers/self-host/capabilities/setup).
|
||||
|
||||
Copy the `.env.example` files in `/front` and `/server`:
|
||||
```bash
|
||||
|
||||
@@ -63,6 +63,12 @@ yarn twenty function:execute --preInstall
|
||||
# Execute the post-install function
|
||||
yarn twenty function:execute --postInstall
|
||||
|
||||
# Build the app for distribution
|
||||
yarn twenty app:build
|
||||
|
||||
# Publish the app to npm or a Twenty server
|
||||
yarn twenty app:publish
|
||||
|
||||
# Uninstall the application from the current workspace
|
||||
yarn twenty app:uninstall
|
||||
|
||||
@@ -1224,6 +1230,113 @@ Key points:
|
||||
|
||||
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):
|
||||
|
||||
## Building your app
|
||||
|
||||
Once you've developed your app with `app:dev`, use `app:build` to compile it into a distributable package.
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Build the app (output goes to .twenty/output/)
|
||||
yarn twenty app:build
|
||||
|
||||
# Build and create a tarball (.tgz) for distribution
|
||||
yarn twenty app:build --tarball
|
||||
```
|
||||
|
||||
The build process:
|
||||
|
||||
1. **Parses and validates the manifest** — reads all `defineX()` entities from your source files and validates the manifest structure.
|
||||
2. **Compiles logic functions and front components** — bundles TypeScript sources into ESM `.mjs` files using esbuild.
|
||||
3. **Generates checksums** — computes MD5 hashes for each built file, stored in the manifest as `builtHandlerChecksum` / `builtComponentChecksum`.
|
||||
4. **Generates the typed API client** — introspects the GraphQL schema and generates typed `CoreApiClient` and `MetadataApiClient` clients.
|
||||
5. **Runs a TypeScript type check** — runs `tsc --noEmit` to catch type errors before publishing.
|
||||
6. **Rebuilds with the generated client** — performs a second compilation pass so the generated client types are included.
|
||||
7. **Optionally creates a tarball** — if `--tarball` is passed, runs `npm pack` to create a `.tgz` file ready for distribution.
|
||||
|
||||
The build output in `.twenty/output/` contains:
|
||||
|
||||
```text
|
||||
.twenty/output/
|
||||
├── manifest.json # Manifest with checksums for all built files
|
||||
├── package.json # Copied from app root
|
||||
├── yarn.lock # Copied from app root
|
||||
├── src/
|
||||
│ ├── logic-functions/ # Compiled .mjs logic function files
|
||||
│ └── front-components/ # Compiled .mjs front component files
|
||||
├── public/ # Static assets (if any)
|
||||
└── my-app-1.0.0.tgz # Only with --tarball flag
|
||||
```
|
||||
|
||||
| Option | Description |
|
||||
|--------|-------------|
|
||||
| `[appPath]` | Path to the app directory (defaults to current directory) |
|
||||
| `--tarball` | Also pack the output into a `.tgz` tarball |
|
||||
|
||||
## Publishing your app
|
||||
|
||||
Use `app:publish` to distribute your app — either to the npm registry or directly to a Twenty server.
|
||||
|
||||
### Publish to npm (default)
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Publish to npm (requires npm login)
|
||||
yarn twenty app:publish
|
||||
|
||||
# Publish with a dist-tag (e.g. beta, next)
|
||||
yarn twenty app:publish --tag beta
|
||||
```
|
||||
|
||||
This builds the app and runs `npm publish` from the `.twenty/output/` directory. The published package can then be installed from the Twenty marketplace by any workspace.
|
||||
|
||||
### Publish to a Twenty server
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Publish directly to a Twenty server
|
||||
yarn twenty app:publish --server https://app.twenty.com
|
||||
```
|
||||
|
||||
This builds the app with a tarball, uploads it to the server via the `uploadAppTarball` GraphQL mutation, and triggers installation in one step. This is useful for private deployments or testing against a specific server.
|
||||
|
||||
| Option | Description |
|
||||
|--------|-------------|
|
||||
| `[appPath]` | Path to the app directory (defaults to current directory) |
|
||||
| `--server <url>` | Publish to a Twenty server instead of npm |
|
||||
| `--token <token>` | Authentication token for the target server |
|
||||
| `--tag <tag>` | npm dist-tag (e.g. `beta`, `next`) — only for npm publish |
|
||||
|
||||
## Application registration
|
||||
|
||||
Before an app can be installed in a workspace, it must be **registered**. A registration is a metadata record that describes where the app comes from and how to authenticate it. This is handled automatically by the CLI in most cases.
|
||||
|
||||
### Source types
|
||||
|
||||
Each registration has a **source type** that determines how the app's files are resolved during installation:
|
||||
|
||||
| Source type | How files are resolved | Typical use case |
|
||||
|-------------|----------------------|------------------|
|
||||
| `LOCAL` | Files are synced in real-time by the CLI watcher — installation is skipped | Development with `app:dev` |
|
||||
| `NPM` | Fetched from the npm registry via the `sourcePackage` field | Published apps on npm |
|
||||
| `TARBALL` | Extracted from an uploaded `.tgz` file stored on the server | Private apps published with `--server` |
|
||||
|
||||
### How registration happens
|
||||
|
||||
- **`app:dev`** — automatically creates a `LOCAL` registration the first time you run dev mode against a workspace.
|
||||
- **`app:publish --server`** — uploads a tarball and creates (or updates) a `TARBALL` registration, then installs the app.
|
||||
- **npm marketplace** — `NPM` registrations are created when apps are synced from the npm registry into the Twenty marketplace catalog.
|
||||
- **GraphQL API** — you can also create registrations programmatically via the `createApplicationRegistration` mutation.
|
||||
|
||||
### Registration vs installation
|
||||
|
||||
**Registration** and **installation** are separate concepts:
|
||||
|
||||
- A **registration** (`ApplicationRegistration`) is a global metadata record describing the app: its name, source type, OAuth credentials, and marketplace listing status. It exists independently of any workspace.
|
||||
- An **installation** (`Application`) is a per-workspace instance. When a user installs an app, Twenty resolves the package from the registration's source, writes the built files to storage, and synchronizes the manifest (creating objects, fields, logic functions, etc.) in that workspace.
|
||||
|
||||
One registration can be installed in many workspaces. Each workspace gets its own copy of the app's files and data model.
|
||||
|
||||
### OAuth credentials
|
||||
|
||||
Each registration includes OAuth credentials (`oAuthClientId` and `oAuthClientSecret`) generated at creation time. These are used by the app to authenticate API requests on behalf of users. The client secret is returned **once** at creation — store it securely. You can rotate it later via the `rotateApplicationRegistrationClientSecret` mutation.
|
||||
|
||||
## 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:
|
||||
|
||||
@@ -4,7 +4,7 @@ title: 1-Click w/ Docker Compose
|
||||
|
||||
|
||||
<Warning>
|
||||
Docker containers are for production hosting or self-hosting, for the contribution please check the [Local Setup](/developers/contribute/capabilities/local-setup).
|
||||
Docker containers are for production hosting or self-hosting. For contributing, please check the [Local Setup](/developers/contribute/capabilities/local-setup).
|
||||
</Warning>
|
||||
|
||||
## Overview
|
||||
@@ -13,7 +13,7 @@ This guide provides step-by-step instructions to install and configure the Twent
|
||||
|
||||
**Important:** Only modify settings explicitly mentioned in this guide. Altering other configurations may lead to issues.
|
||||
|
||||
See docs [Setup Environment Variables](/developers/self-host/capabilities/setup) for advanced configuration. All environment variables must be declared in the docker-compose.yml file at the server and / or worker level depending on the variable.
|
||||
See [Setup Environment Variables](/developers/self-host/capabilities/setup) for advanced configuration. All environment variables must be declared in the `docker-compose.yml` file at the server and/or worker level, depending on the variable.
|
||||
|
||||
## System Requirements
|
||||
|
||||
@@ -237,4 +237,3 @@ docker compose up -d
|
||||
|
||||
If you encounter any problem, check [Troubleshooting](/developers/self-host/capabilities/troubleshooting) for solutions.
|
||||
|
||||
|
||||
|
||||
@@ -289,43 +289,57 @@ yarn command:prod cron:workflow:automated-cron-trigger
|
||||
**Environment-only mode:** If you set `IS_CONFIG_VARIABLES_IN_DB_ENABLED=false`, add these variables to your `.env` file instead.
|
||||
</Warning>
|
||||
|
||||
## Logic Functions
|
||||
## Logic Functions & Code Interpreter
|
||||
|
||||
Twenty supports logic functions for workflows and custom logic. The execution environment is configured via the `SERVERLESS_TYPE` environment variable.
|
||||
Twenty supports logic functions for workflows and the code interpreter for AI data analysis. Both run user-provided code and require explicit configuration for security.
|
||||
|
||||
### Security Defaults
|
||||
|
||||
**In production (NODE_ENV=production):** Both logic functions and code interpreter default to **Disabled**. You must explicitly enable them with `LOGIC_FUNCTION_TYPE` and `CODE_INTERPRETER_TYPE` if you need these features.
|
||||
|
||||
**In development (NODE_ENV=development):** Both default to **LOCAL** for convenience when running locally.
|
||||
|
||||
<Warning>
|
||||
**Security Notice:** The local driver (`SERVERLESS_TYPE=LOCAL`) runs code directly on the host in a Node.js process with no sandboxing. It should only be used for trusted code in development. For production deployments handling untrusted code, we highly recommend using `SERVERLESS_TYPE=LAMBDA` or `SERVERLESS_TYPE=DISABLED`.
|
||||
**Security Notice:** The local driver (`LOGIC_FUNCTION_TYPE=LOCAL` or `CODE_INTERPRETER_TYPE=LOCAL`) runs code directly on the host in a Node.js process with no sandboxing. It should only be used for trusted code in development. For production deployments handling untrusted code, use `LOGIC_FUNCTION_TYPE=LAMBDA` or `CODE_INTERPRETER_TYPE=E2B` (with sandboxing), or keep them disabled.
|
||||
</Warning>
|
||||
|
||||
### Available Drivers
|
||||
### Logic Functions - Available Drivers
|
||||
|
||||
| Driver | Environment Variable | Use Case | Security Level |
|
||||
|--------|---------------------|----------|----------------|
|
||||
| Disabled | `SERVERLESS_TYPE=DISABLED` | Disable logic functions entirely | N/A |
|
||||
| Local | `SERVERLESS_TYPE=LOCAL` | Development and trusted environments | Low (no sandboxing) |
|
||||
| Lambda | `SERVERLESS_TYPE=LAMBDA` | Production with untrusted code | High (hardware-level isolation) |
|
||||
| Disabled | `LOGIC_FUNCTION_TYPE=DISABLED` | Disable logic functions entirely | N/A |
|
||||
| Local | `LOGIC_FUNCTION_TYPE=LOCAL` | Development and trusted environments | Low (no sandboxing) |
|
||||
| Lambda | `LOGIC_FUNCTION_TYPE=LAMBDA` | Production with untrusted code | High (hardware-level isolation) |
|
||||
|
||||
### Recommended Configuration
|
||||
### Logic Functions - Recommended Configuration
|
||||
|
||||
**For development:**
|
||||
```bash
|
||||
SERVERLESS_TYPE=LOCAL # default
|
||||
LOGIC_FUNCTION_TYPE=LOCAL # default when NODE_ENV=development
|
||||
```
|
||||
|
||||
**For production (AWS):**
|
||||
```bash
|
||||
SERVERLESS_TYPE=LAMBDA
|
||||
SERVERLESS_LAMBDA_REGION=us-east-1
|
||||
SERVERLESS_LAMBDA_ROLE=arn:aws:iam::123456789:role/your-lambda-role
|
||||
SERVERLESS_LAMBDA_ACCESS_KEY_ID=your-access-key
|
||||
SERVERLESS_LAMBDA_SECRET_ACCESS_KEY=your-secret-key
|
||||
LOGIC_FUNCTION_TYPE=LAMBDA
|
||||
LOGIC_FUNCTION_LAMBDA_REGION=us-east-1
|
||||
LOGIC_FUNCTION_LAMBDA_ROLE=arn:aws:iam::123456789:role/your-lambda-role
|
||||
LOGIC_FUNCTION_LAMBDA_ACCESS_KEY_ID=your-access-key
|
||||
LOGIC_FUNCTION_LAMBDA_SECRET_ACCESS_KEY=your-secret-key
|
||||
```
|
||||
|
||||
**To disable logic functions:**
|
||||
```bash
|
||||
SERVERLESS_TYPE=DISABLED
|
||||
LOGIC_FUNCTION_TYPE=DISABLED # default when NODE_ENV=production
|
||||
```
|
||||
|
||||
### Code Interpreter - Available Drivers
|
||||
|
||||
| Driver | Environment Variable | Use Case | Security Level |
|
||||
|--------|---------------------|----------|----------------|
|
||||
| Disabled | `CODE_INTERPRETER_TYPE=DISABLED` | Disable AI code execution | N/A |
|
||||
| Local | `CODE_INTERPRETER_TYPE=LOCAL` | Development only | Low (no sandboxing) |
|
||||
| E2B | `CODE_INTERPRETER_TYPE=E_2_B` | Production with sandboxed execution | High (isolated sandbox) |
|
||||
|
||||
<Note>
|
||||
When using `SERVERLESS_TYPE=DISABLED`, any attempt to execute a logic function will return an error. This is useful if you want to run Twenty without logic function capabilities.
|
||||
When using `LOGIC_FUNCTION_TYPE=DISABLED` or `CODE_INTERPRETER_TYPE=DISABLED`, any attempt to execute will return an error. This is useful if you want to run Twenty without these capabilities.
|
||||
</Note>
|
||||
|
||||
+2
-2
@@ -8,7 +8,7 @@ title: دليل الأسلوب
|
||||
|
||||
لهذا، من الأفضل أن تكون تفصيلًا أكثر قليلاً بدلاً من أن تكون موجزًا للغاية.
|
||||
|
||||
دائمًا ضع في اعتبارك أن الناس يقرؤون التعليمات البرمجية أكثر مما يكتبونها، وخاصة في المشاريع مفتوحة المصدر، حيث يمكن لأي شخص المساهمة.
|
||||
Always keep in mind that people read code more often than they write it, especially on an open source project, where anyone can contribute.
|
||||
|
||||
هناك العديد من القواعد التي لم يتم تعريفها هنا، ولكن يتم التحقق منها تلقائيًا بواسطة أدوات الفحص.
|
||||
|
||||
@@ -150,7 +150,7 @@ type MyType = {
|
||||
|
||||
### استخدم السلاسل النصية بدلاً من التعدادات
|
||||
|
||||
[الحروف المشفوعة](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types) هي الطريقة المفضلة للتعامل مع القيم الشبيهة بالأعداد المخصصة في TypeScript. من السهل توسيعها باستخدام Pick و Omit، وتقدم تجربة مطور أفضل، خاصة مع إكمال التعليمات البرمجية.
|
||||
[الحروف المشفوعة](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types) هي الطريقة المفضلة للتعامل مع القيم الشبيهة بالأعداد المخصصة في TypeScript. They are easier to extend with Pick and Omit, and offer a better developer experience, especially with code completion.
|
||||
|
||||
يمكنك معرفة السبب في أن TypeScript توصي بتجنب الأعداد [هنا](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#enums).
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ description: الدليل للمساهمين (أو المطورين الفضول
|
||||
## المتطلبات الأساسية
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Linux و MacOS">
|
||||
<Tab title="Linux and macOS">
|
||||
|
||||
قبل أن تتمكن من تثبيت واستخدام Twenty، تأكد من تثبيت الأمور التالية على جهاز الكمبيوتر الخاص بك:
|
||||
* [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
|
||||
@@ -30,7 +30,7 @@ wsl --install
|
||||
```
|
||||
يجب أن ترى الآن مطالبة لإعادة تشغيل جهاز الكمبيوتر الخاص بك. إذا لم يكن كذلك، فأعد تشغيله يدويًا.
|
||||
|
||||
عند إعادة التشغيل، ستُفتح نافذة PowerShell وسيتم تثبيت Ubuntu. قد يستغرق هذا وقتًا طويلاً.
|
||||
Upon restart, a PowerShell window will open and install Ubuntu. قد يستغرق هذا وقتًا طويلاً.
|
||||
سترى مطالبة لإنشاء اسم المستخدم وكلمة المرور لتثبيت Ubuntu الخاص بك.
|
||||
|
||||
2. تثبيت وإعداد git
|
||||
@@ -102,8 +102,8 @@ cd twenty
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Linux">
|
||||
**الخيار 1 (المفضل):** لتوفير قاعدة بياناتك محليًا:
|
||||
استخدم الرابط التالي لتثبيت Postgresql على جهاز Linux الخاص بك: [تثبيت Postgresql](https://www.postgresql.org/download/linux/)
|
||||
**Option 1 (preferred):** To provision your database locally:
|
||||
Use the following link to install PostgreSQL on your Linux machine: [PostgreSQL Installation](https://www.postgresql.org/download/linux/)
|
||||
```bash
|
||||
psql postgres -c "CREATE DATABASE \"default\";" -c "CREATE DATABASE test;"
|
||||
```
|
||||
@@ -129,8 +129,8 @@ cd twenty
|
||||
brew services list
|
||||
```
|
||||
|
||||
المثبت قد لا ينشئ المستخدم `postgres` افتراضيًا عند التثبيت
|
||||
عبر Homebrew على MacOS. بدلاً من ذلك، فإنه ينشئ دور PostgreSQL يطابق
|
||||
The installer might not create the `postgres` user by default when installing
|
||||
via Homebrew on macOS. بدلاً من ذلك، فإنه ينشئ دور PostgreSQL يطابق
|
||||
اسم المستخدم الخاص بك في MacOS (مثل "john").
|
||||
للتحقق وإنشاء المستخدم `postgres` إذا لزم الأمر، اتبع هذه الخطوات:
|
||||
```bash
|
||||
@@ -173,8 +173,8 @@ cd twenty
|
||||
<Tab title="ويندوز (WSL)">
|
||||
يجب أن تُنفذ جميع الخطوات التالية في تيرمينال WSL (داخل جهازك الافتراضي)
|
||||
|
||||
**الخيار 1:** لتوفير قاعدة بيانات Postgresql الخاصة بك محليًا:
|
||||
استخدم الرابط التالي لتثبيت Postgresql على جهاز Linux الافتراضي الخاص بك: [تثبيت Postgresql](https://www.postgresql.org/download/linux/)
|
||||
**Option 1:** To provision your PostgreSQL locally:
|
||||
Use the following link to install PostgreSQL on your Linux virtual machine: [PostgreSQL Installation](https://www.postgresql.org/download/linux/)
|
||||
```bash
|
||||
psql postgres -c "CREATE DATABASE \"default\";" -c "CREATE DATABASE test;"
|
||||
```
|
||||
@@ -189,11 +189,13 @@ cd twenty
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
يمكنك الآن الوصول إلى قاعدة البيانات على [localhost:5432](localhost:5432)، مع المستخدم `postgres` وكلمة المرور `postgres`.
|
||||
You can now access the database at `localhost:5432`.
|
||||
|
||||
If you used the Docker option above, the default credentials are user `postgres` and password `postgres`. For native PostgreSQL installations, use the credentials and roles configured on your machine.
|
||||
|
||||
## الخطوة 4: إعداد قاعدة بيانات Redis (للتخزين المؤقت)
|
||||
|
||||
يتطلب Twenty مخزن بيانات Redis لتقديم أفضل أداء
|
||||
Twenty requires a Redis cache to provide the best performance.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Linux">
|
||||
@@ -210,8 +212,10 @@ cd twenty
|
||||
```bash
|
||||
brew install redis
|
||||
```
|
||||
ابدأ خادم redis الخاص بك:
|
||||
`brew services start redis`
|
||||
Start your Redis server:
|
||||
```bash
|
||||
brew services start redis
|
||||
```
|
||||
|
||||
**الخيار 2:** إذا كنت قد قمت بتثبيت docker:
|
||||
```bash
|
||||
@@ -229,11 +233,11 @@ cd twenty
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
إذا كنت بحاجة إلى واجهة رسومية للعميل، نوصي بـ [redis insight](https://redis.io/insight/) (يتوفر إصدار مجاني)
|
||||
If you need a client GUI, we recommend [Redis Insight](https://redis.io/insight/) (free version available).
|
||||
|
||||
## الخطوة 5: إعداد متغيرات البيئة
|
||||
## Step 5: Set up environment variables
|
||||
|
||||
استخدم متغيرات البيئة أو ملفات `.env` لتكوين مشروعك. المزيد من المعلومات [هنا](/l/ar/developers/self-host/capabilities/setup)
|
||||
استخدم متغيرات البيئة أو ملفات `.env` لتكوين مشروعك. المزيد من المعلومات [هنا](/l/ar/developers/self-host/capabilities/setup).
|
||||
|
||||
انسخ ملفات `.env.example` الموجودة في `/front` و`/server`:
|
||||
|
||||
|
||||
@@ -64,6 +64,12 @@ yarn twenty function:execute --preInstall
|
||||
# نفّذ دالة ما بعد التثبيت
|
||||
yarn twenty function:execute --postInstall
|
||||
|
||||
# ابنِ التطبيق للتوزيع
|
||||
yarn twenty app:build
|
||||
|
||||
# انشر التطبيق إلى npm أو إلى خادم Twenty
|
||||
yarn twenty app:publish
|
||||
|
||||
# أزل تثبيت التطبيق من مساحة العمل الحالية
|
||||
yarn twenty app:uninstall
|
||||
|
||||
@@ -1240,6 +1246,113 @@ uploadFile(
|
||||
|
||||
استكشف مثالًا بسيطًا شاملًا من البداية إلى النهاية يوضح الكائنات والوظائف المنطقية والمكوّنات الأمامية ومشغّلات متعددة [هنا](https://github.com/twentyhq/twenty/tree/main/packages/twenty-apps/hello-world):
|
||||
|
||||
## بناء تطبيقك
|
||||
|
||||
بمجرد أن تطوّر تطبيقك باستخدام `app:dev`، استخدم `app:build` لإنشاء حزمة قابلة للتوزيع منه.
|
||||
|
||||
```bash filename="Terminal"
|
||||
# ابنِ التطبيق (الإخراج يذهب إلى .twenty/output/)
|
||||
yarn twenty app:build
|
||||
|
||||
# ابنِ وأنشئ ملف tarball (.tgz) للتوزيع
|
||||
yarn twenty app:build --tarball
|
||||
```
|
||||
|
||||
عملية البناء:
|
||||
|
||||
1. **يقوم بتحليل ملف البيان والتحقق من صحته** — يقرأ جميع الكيانات `defineX()` من ملفات المصدر لديك ويُتحقّق من بنية ملف البيان.
|
||||
2. **يُصرِّف دوال المنطق ومكوّنات الواجهة** — يُجمّع مصادر TypeScript إلى ملفات ESM `.mjs` باستخدام esbuild.
|
||||
3. **يولّد قيم التحقّق** — يحسب تجزئات MD5 لكل ملف مُبنًى، وتُخزَّن في ملف البيان كـ `builtHandlerChecksum` / `builtComponentChecksum`.
|
||||
4. **ينشئ عميل API مضبوط الأنواع** — يفحص مخطط GraphQL ويُنشئ عميلَي `CoreApiClient` و`MetadataApiClient` مضبوطي الأنواع.
|
||||
5. **يشغّل فحص الأنواع لـ TypeScript** — يشغّل `tsc --noEmit` لاكتشاف أخطاء الأنواع قبل النشر.
|
||||
6. **يعيد البناء باستخدام العميل المُولَّد** — يُجري مرحلة ترجمة ثانية بحيث تُدرَج أنواع العميل المُولَّد.
|
||||
7. **ينشئ أرشيف tar اختياريًا** — إذا تم تمرير `--tarball`، يشغّل `npm pack` لإنشاء ملف `.tgz` جاهز للتوزيع.
|
||||
|
||||
مخرجات البناء في `.twenty/output/` تتضمّن:
|
||||
|
||||
```text
|
||||
.twenty/output/
|
||||
├── manifest.json # Manifest with checksums for all built files
|
||||
├── package.json # Copied from app root
|
||||
├── yarn.lock # Copied from app root
|
||||
├── src/
|
||||
│ ├── logic-functions/ # Compiled .mjs logic function files
|
||||
│ └── front-components/ # Compiled .mjs front component files
|
||||
├── public/ # Static assets (if any)
|
||||
└── my-app-1.0.0.tgz # Only with --tarball flag
|
||||
```
|
||||
|
||||
| الخيار | الوصف |
|
||||
| ----------- | -------------------------------------------------- |
|
||||
| `[appPath]` | المسار إلى دليل التطبيق (افتراضيًا: الدليل الحالي) |
|
||||
| `--tarball` | قم أيضًا بحزم المخرجات في أرشيف `.tgz` |
|
||||
|
||||
## نشر تطبيقك
|
||||
|
||||
استخدم `app:publish` لتوزيع تطبيقك — إما إلى سجل npm أو مباشرةً إلى خادم Twenty.
|
||||
|
||||
### النشر إلى npm (الإعداد الافتراضي)
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Publish to npm (requires npm login)
|
||||
yarn twenty app:publish
|
||||
|
||||
# Publish with a dist-tag (e.g. beta, next)
|
||||
yarn twenty app:publish --tag beta
|
||||
```
|
||||
|
||||
يقوم هذا ببناء التطبيق وتشغيل `npm publish` من دليل `.twenty/output/`. بعد ذلك يمكن تثبيت الحزمة المنشورة من سوق Twenty بواسطة أي مساحة عمل.
|
||||
|
||||
### النشر إلى خادم Twenty
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Publish directly to a Twenty server
|
||||
yarn twenty app:publish --server https://app.twenty.com
|
||||
```
|
||||
|
||||
يقوم هذا ببناء التطبيق مع أرشيف tar، ويرفعه إلى الخادم عبر العملية `uploadAppTarball` في GraphQL، ويبدأ التثبيت في خطوة واحدة. يكون هذا مفيدًا لعمليات النشر الخاصة أو للاختبار مقابل خادم محدّد.
|
||||
|
||||
| الخيار | الوصف |
|
||||
| ----------------- | -------------------------------------------------------- |
|
||||
| `[appPath]` | المسار إلى دليل التطبيق (افتراضيًا: الدليل الحالي) |
|
||||
| `--server <url>` | انشر إلى خادم Twenty بدلًا من npm |
|
||||
| `--token <token>` | رمز المصادقة للخادم المستهدف |
|
||||
| `--tag <tag>` | علامة توزيع npm (مثل `beta`، `next`) — للنشر عبر npm فقط |
|
||||
|
||||
## تسجيل التطبيق
|
||||
|
||||
قبل أن يمكن تثبيت تطبيق في مساحة عمل، يجب أن يكون **مسجّلًا**. التسجيل هو سجل بيانات وصفية يوضّح مصدر التطبيق وكيفية مصادقته. يُعالَج هذا تلقائيًا بواسطة CLI في معظم الحالات.
|
||||
|
||||
### أنواع المصادر
|
||||
|
||||
لكل تسجيل **نوع مصدر** يحدّد كيفية تحديد ملفات التطبيق أثناء التثبيت:
|
||||
|
||||
| نوع المصدر | كيفية تحديد الملفات | حالة الاستخدام النموذجية |
|
||||
| ---------- | ------------------------------------------------------------------------- | --------------------------------------- |
|
||||
| `LOCAL` | تتم مزامنة الملفات في الوقت الفعلي بواسطة مُراقِب CLI — يتم تخطّي التثبيت | التطوير باستخدام `app:dev` |
|
||||
| `NPM` | تُجلب من سجل npm عبر الحقل `sourcePackage` | تطبيقات منشورة على npm |
|
||||
| `TARBALL` | تُستخرَج من ملف `.tgz` مرفوع ومخزَّن على الخادم | تطبيقات خاصة منشورة باستخدام `--server` |
|
||||
|
||||
### كيفية إجراء التسجيل
|
||||
|
||||
* **`app:dev`** — ينشئ تلقائيًا تسجيلًا من نوع `LOCAL` في المرة الأولى التي تشغّل فيها وضع التطوير لمساحة عمل.
|
||||
* **`app:publish --server`** — يرفع أرشيف tar وينشئ (أو يحدّث) تسجيلًا من نوع `TARBALL`، ثم يثبّت التطبيق.
|
||||
* **سوق npm** — يتم إنشاء تسجيلات `NPM` عند مزامنة التطبيقات من سجل npm إلى كتالوج سوق Twenty.
|
||||
* **واجهة برمجة تطبيقات GraphQL** — يمكنك أيضًا إنشاء التسجيلات برمجيًا عبر العملية `createApplicationRegistration`.
|
||||
|
||||
### التسجيل مقابل التثبيت
|
||||
|
||||
**التسجيل** و**التثبيت** مفهومان منفصلان:
|
||||
|
||||
* **التسجيل** (`ApplicationRegistration`) هو سجل بيانات وصفية عام يصف التطبيق: اسمه، نوع المصدر، بيانات اعتماد OAuth، وحالة إدراجه في السوق. وهو موجود بشكل مستقل عن أي مساحة عمل.
|
||||
* **التثبيت** (`Application`) هو مثيل لكل مساحة عمل. عند قيام مستخدم بتثبيت تطبيق، تقوم Twenty بحلّ الحزمة من مصدر التسجيل، وتكتب الملفات المُبنَاة إلى التخزين، وتزامن البيان التعريفي (إنشاء الكائنات والحقول ودوال المنطق، إلخ) في مساحة العمل تلك.
|
||||
|
||||
يمكن تثبيت تسجيل واحد في العديد من مساحات العمل. تحصل كل مساحة عمل على نسختها الخاصة من ملفات التطبيق ونموذج البيانات.
|
||||
|
||||
### بيانات اعتماد OAuth
|
||||
|
||||
يتضمن كل تسجيل بيانات اعتماد OAuth (`oAuthClientId` و`oAuthClientSecret`) يتم إنشاؤها وقت الإنشاء. يستخدمها التطبيق لمصادقة طلبات واجهة برمجة التطبيقات بالنيابة عن المستخدمين. يُعرَض سر العميل مرةً **واحدة** عند الإنشاء — خزّنه بأمان. يمكنك تدويره لاحقًا عبر العملية `rotateApplicationRegistrationClientSecret`.
|
||||
|
||||
## إعداد يدوي (بدون المهيئ)
|
||||
|
||||
بينما نوصي باستخدام `create-twenty-app` للحصول على أفضل تجربة للبدء، يمكنك أيضًا إعداد مشروع يدويًا. لا تثبّت CLI عالميًا. بدل ذلك، أضف `twenty-sdk` كاعتماد محلي واربط سكربتًا واحدًا في ملف package.json لديك:
|
||||
|
||||
@@ -3,7 +3,7 @@ title: بنقرة واحدة مع Docker Compose
|
||||
---
|
||||
|
||||
<Warning>
|
||||
الحاويات الخاصة بدوكر مخصصة للاستضافة الإنتاجية أو الاستضافة الذاتية، للتحقيق يرجى التحقق من [الإعداد المحلي](/l/ar/developers/contribute/capabilities/local-setup).
|
||||
Docker containers are for production hosting or self-hosting. For contributing, please check the [Local Setup](/l/ar/developers/contribute/capabilities/local-setup).
|
||||
</Warning>
|
||||
|
||||
## نظرة عامة
|
||||
@@ -12,7 +12,7 @@ title: بنقرة واحدة مع Docker Compose
|
||||
|
||||
**مهم:** عدّل الإعدادات المذكورة صراحة في هذا الدليل فقط. قد يؤدي تعديل التكوينات الأخرى إلى مشاكل.
|
||||
|
||||
راجع المستندات الخاصة بـ [إعداد متغيرات البيئة](/l/ar/developers/self-host/capabilities/setup) لإعداد متقدم. يجب إعلان جميع متغيرات البيئة في الملف docker-compose.yml على مستوى الخادم و/أو العامل بناءً على المتغير.
|
||||
See [Setup Environment Variables](/l/ar/developers/self-host/capabilities/setup) for advanced configuration. All environment variables must be declared in the `docker-compose.yml` file at the server and/or worker level, depending on the variable.
|
||||
|
||||
## متطلبات النظام
|
||||
|
||||
|
||||
@@ -297,46 +297,60 @@ yarn command:prod cron:workflow:automated-cron-trigger
|
||||
**وضع بيئي فقط:** إذا كنت قد ضبطت `IS_CONFIG_VARIABLES_IN_DB_ENABLED=false`، فأضف هذه المتغيرات إلى ملف `.env` الخاص بك بدلاً من ذلك.
|
||||
</Warning>
|
||||
|
||||
## الوظائف المنطقية
|
||||
## الوظائف المنطقية ومفسر الشيفرة
|
||||
|
||||
تدعم Twenty الوظائف المنطقية لعمليات سير العمل والمنطق المخصص. يتم تكوين بيئة التنفيذ عبر متغير البيئة `SERVERLESS_TYPE`.
|
||||
تدعم Twenty الوظائف المنطقية لعمليات سير العمل ومفسر الشيفرة لتحليل بيانات الذكاء الاصطناعي. كلاهما يقوم بتشغيل الشيفرة المقدمة من المستخدم ويتطلب تهيئة صريحة لأغراض الأمان.
|
||||
|
||||
### الإعدادات الافتراضية للأمان
|
||||
|
||||
**في بيئة الإنتاج (NODE_ENV=production):** يكون الإعداد الافتراضي لكل من الوظائف المنطقية ومفسر الشيفرة هو **معطل**. يجب تمكينهما صراحة باستخدام `LOGIC_FUNCTION_TYPE` و`CODE_INTERPRETER_TYPE` إذا كنت تحتاج إلى هذه الميزات.
|
||||
|
||||
**في بيئة التطوير (NODE_ENV=development):** يكون الإعداد الافتراضي لكليهما **LOCAL** لتسهيل التشغيل محلياً.
|
||||
|
||||
<Warning>
|
||||
**ملاحظة أمنية:** يقوم برنامج التشغيل المحلي (`SERVERLESS_TYPE=LOCAL`) بتشغيل الشيفرة مباشرةً على المضيف ضمن عملية Node.js من دون عزل. يجب استخدامه فقط للشيفرة الموثوقة أثناء التطوير. بالنسبة لعمليات النشر الإنتاجية التي تتعامل مع شيفرة غير موثوق بها، نوصي بشدة باستخدام `SERVERLESS_TYPE=LAMBDA` أو `SERVERLESS_TYPE=DISABLED`.
|
||||
**ملاحظة أمنية:** يقوم برنامج التشغيل المحلي (`LOGIC_FUNCTION_TYPE=LOCAL` أو `CODE_INTERPRETER_TYPE=LOCAL`) بتشغيل الشيفرة مباشرة على المضيف ضمن عملية Node.js من دون عزل. يجب استخدامه فقط للشيفرة الموثوقة أثناء التطوير. لعمليات النشر الإنتاجية التي تتعامل مع شيفرة غير موثوقة، استخدم `LOGIC_FUNCTION_TYPE=LAMBDA` أو `CODE_INTERPRETER_TYPE=E2B` (مع وضع الحماية)، أو اتركهما مُعطَّلَيْن.
|
||||
</Warning>
|
||||
|
||||
### برامج التشغيل المتاحة
|
||||
### الوظائف المنطقية - برامج التشغيل المتاحة
|
||||
|
||||
| برنامج التشغيل | متغير البيئة | حالة الاستخدام | مستوى الأمان |
|
||||
| -------------- | -------------------------- | ------------------------------- | ----------------------------- |
|
||||
| معطل | `SERVERLESS_TYPE=DISABLED` | تعطيل الوظائف المنطقية بالكامل | غير متاح |
|
||||
| محلي | `SERVERLESS_TYPE=LOCAL` | بيئات التطوير والبيئات الموثوقة | منخفض (من دون عزل) |
|
||||
| Lambda | `SERVERLESS_TYPE=LAMBDA` | الإنتاج مع شيفرة غير موثوق بها | مرتفع (عزل على مستوى الأجهزة) |
|
||||
| برنامج التشغيل | متغير البيئة | حالة الاستخدام | مستوى الأمان |
|
||||
| -------------- | ------------------------------ | ------------------------------- | ----------------------------- |
|
||||
| معطل | `LOGIC_FUNCTION_TYPE=DISABLED` | تعطيل الوظائف المنطقية بالكامل | غير متاح |
|
||||
| محلي | `LOGIC_FUNCTION_TYPE=LOCAL` | بيئات التطوير والبيئات الموثوقة | منخفض (من دون عزل) |
|
||||
| Lambda | `LOGIC_FUNCTION_TYPE=LAMBDA` | الإنتاج مع شيفرة غير موثوق بها | مرتفع (عزل على مستوى الأجهزة) |
|
||||
|
||||
### التكوين الموصى به
|
||||
### الوظائف المنطقية - الإعداد الموصى به
|
||||
|
||||
**للتطوير:**
|
||||
|
||||
```bash
|
||||
SERVERLESS_TYPE=LOCAL # default
|
||||
LOGIC_FUNCTION_TYPE=LOCAL # default when NODE_ENV=development
|
||||
```
|
||||
|
||||
**للإنتاج (AWS):**
|
||||
|
||||
```bash
|
||||
SERVERLESS_TYPE=LAMBDA
|
||||
SERVERLESS_LAMBDA_REGION=us-east-1
|
||||
SERVERLESS_LAMBDA_ROLE=arn:aws:iam::123456789:role/your-lambda-role
|
||||
SERVERLESS_LAMBDA_ACCESS_KEY_ID=your-access-key
|
||||
SERVERLESS_LAMBDA_SECRET_ACCESS_KEY=your-secret-key
|
||||
LOGIC_FUNCTION_TYPE=LAMBDA
|
||||
LOGIC_FUNCTION_LAMBDA_REGION=us-east-1
|
||||
LOGIC_FUNCTION_LAMBDA_ROLE=arn:aws:iam::123456789:role/your-lambda-role
|
||||
LOGIC_FUNCTION_LAMBDA_ACCESS_KEY_ID=your-access-key
|
||||
LOGIC_FUNCTION_LAMBDA_SECRET_ACCESS_KEY=your-secret-key
|
||||
```
|
||||
|
||||
**لتعطيل الوظائف المنطقية:**
|
||||
|
||||
```bash
|
||||
SERVERLESS_TYPE=DISABLED
|
||||
LOGIC_FUNCTION_TYPE=DISABLED # default when NODE_ENV=production
|
||||
```
|
||||
|
||||
### مفسر الشيفرة - برامج التشغيل المتاحة
|
||||
|
||||
| برنامج التشغيل | متغير البيئة | حالة الاستخدام | مستوى الأمان |
|
||||
| -------------- | -------------------------------- | ------------------------------------- | ------------------------ |
|
||||
| معطل | `CODE_INTERPRETER_TYPE=DISABLED` | تعطيل تنفيذ الشيفرة بالذكاء الاصطناعي | غير متاح |
|
||||
| محلي | `CODE_INTERPRETER_TYPE=LOCAL` | للتطوير فقط | منخفض (من دون عزل) |
|
||||
| E2B | `CODE_INTERPRETER_TYPE=E_2_B` | الإنتاج مع تنفيذ ضمن صندوق رمل معزول | مرتفعة (صندوق رمل معزول) |
|
||||
|
||||
<Note>
|
||||
عند استخدام `SERVERLESS_TYPE=DISABLED`، ستؤدي أي محاولة لتنفيذ وظيفة منطقية إلى إرجاع خطأ. يكون هذا مفيدًا إذا كنت ترغب في تشغيل Twenty من دون إمكانات الوظائف المنطقية.
|
||||
عند استخدام `LOGIC_FUNCTION_TYPE=DISABLED` أو `CODE_INTERPRETER_TYPE=DISABLED`، سترجع أي محاولة للتنفيذ خطأً. يكون هذا مفيدًا إذا كنت ترغب في تشغيل Twenty من دون هذه الإمكانات.
|
||||
</Note>
|
||||
|
||||
+2
-2
@@ -8,7 +8,7 @@ Das Ziel ist es, eine konsistente Codebasis zu haben, die leicht lesbar und einf
|
||||
|
||||
Hierfür ist es besser, etwas ausführlicher zu sein als zu knapp.
|
||||
|
||||
Denken Sie daran, dass Code häufiger gelesen als geschrieben wird, insbesondere bei einem Open-Source-Projekt, zu dem jeder beitragen kann.
|
||||
Always keep in mind that people read code more often than they write it, especially on an open source project, where anyone can contribute.
|
||||
|
||||
Es gibt viele Regeln, die hier nicht definiert sind, die aber automatisch durch Linters überprüft werden.
|
||||
|
||||
@@ -150,7 +150,7 @@ type MyType = {
|
||||
|
||||
### Verwenden Sie String-Literale anstelle von Enums
|
||||
|
||||
[String-Literale](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types) sind die bevorzugte Methode, um enum-ähnliche Werte in TypeScript zu handhaben. Sie sind einfacher mit Pick und Omit zu erweitern und bieten eine bessere Entwicklererfahrung, vor allem mit Code-Vervollständigung.
|
||||
[String-Literale](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types) sind die bevorzugte Methode, um enum-ähnliche Werte in TypeScript zu handhaben. They are easier to extend with Pick and Omit, and offer a better developer experience, especially with code completion.
|
||||
|
||||
Warum TypeScript empfiehlt, Enums zu vermeiden, sehen Sie [hier](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#enums).
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ description: Der Leitfaden für Mitwirkende (oder neugierige Entwickler), die Tw
|
||||
## Voraussetzungen
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Linux und MacOS">
|
||||
<Tab title="Linux and macOS">
|
||||
|
||||
Bevor Sie Twenty installieren und verwenden können, stellen Sie sicher, dass Sie Folgendes auf Ihrem Computer installiert haben:
|
||||
* [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
|
||||
@@ -30,7 +30,7 @@ wsl --install
|
||||
```
|
||||
Sie sollten nun eine Aufforderung sehen, Ihren Computer neu zu starten. Wenn nicht, starten Sie ihn manuell neu.
|
||||
|
||||
Nach dem Neustart wird ein PowerShell-Fenster geöffnet und Ubuntu installiert. Dies kann einige Zeit in Anspruch nehmen.
|
||||
Upon restart, a PowerShell window will open and install Ubuntu. Dies kann einige Zeit in Anspruch nehmen.
|
||||
Sie werden aufgefordert, einen Benutzernamen und ein Passwort für Ihre Ubuntu-Installation zu erstellen.
|
||||
|
||||
2. Git installieren und konfigurieren
|
||||
@@ -102,8 +102,8 @@ Alle folgenden Befehle innerhalb des Projekts sind vom Stammverzeichnis aus ausz
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Linux">
|
||||
**Option 1 (bevorzugt):** Um Ihre Datenbank lokal bereitzustellen:
|
||||
Verwenden Sie den folgenden Link, um PostgreSQL auf Ihrem Linux-Rechner zu installieren: [Postgresql-Installation](https://www.postgresql.org/download/linux/)
|
||||
**Option 1 (preferred):** To provision your database locally:
|
||||
Use the following link to install PostgreSQL on your Linux machine: [PostgreSQL Installation](https://www.postgresql.org/download/linux/)
|
||||
```bash
|
||||
psql postgres -c "CREATE DATABASE \"default\";" -c "CREATE DATABASE test;"
|
||||
```
|
||||
@@ -129,8 +129,8 @@ Alle folgenden Befehle innerhalb des Projekts sind vom Stammverzeichnis aus ausz
|
||||
brew services list
|
||||
```
|
||||
|
||||
Der Installer erstellt möglicherweise nicht standardmäßig den Benutzer `postgres`, wenn er
|
||||
über Homebrew auf MacOS installiert wird. Stattdessen wird eine PostgreSQL-Rolle erstellt, die Ihrem macOS
|
||||
The installer might not create the `postgres` user by default when installing
|
||||
via Homebrew on macOS. Stattdessen wird eine PostgreSQL-Rolle erstellt, die Ihrem macOS
|
||||
Benutzernamen (z. B. "john") entspricht.
|
||||
Um zu überprüfen und, falls erforderlich, den Benutzer `postgres` zu erstellen, führen Sie folgende Schritte aus:
|
||||
```bash
|
||||
@@ -173,8 +173,8 @@ Alle folgenden Befehle innerhalb des Projekts sind vom Stammverzeichnis aus ausz
|
||||
<Tab title="Windows (WSL)">
|
||||
Alle folgenden Schritte sind im WSL-Terminal auszuführen (innerhalb Ihrer virtuellen Maschine)
|
||||
|
||||
**Option 1:** Um Ihr PostgreSQL lokal bereitzustellen:
|
||||
Verwenden Sie den folgenden Link, um PostgreSQL auf Ihrer Linux-VM zu installieren: [Postgresql-Installation](https://www.postgresql.org/download/linux/)
|
||||
**Option 1:** To provision your PostgreSQL locally:
|
||||
Use the following link to install PostgreSQL on your Linux virtual machine: [PostgreSQL Installation](https://www.postgresql.org/download/linux/)
|
||||
```bash
|
||||
psql postgres -c "CREATE DATABASE \"default\";" -c "CREATE DATABASE test;"
|
||||
```
|
||||
@@ -189,11 +189,13 @@ Alle folgenden Befehle innerhalb des Projekts sind vom Stammverzeichnis aus ausz
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
Sie können jetzt über [localhost:5432](localhost:5432) auf die Datenbank zugreifen, mit dem Benutzer `postgres` und dem Passwort `postgres`.
|
||||
You can now access the database at `localhost:5432`.
|
||||
|
||||
If you used the Docker option above, the default credentials are user `postgres` and password `postgres`. For native PostgreSQL installations, use the credentials and roles configured on your machine.
|
||||
|
||||
## Schritt 4: Einrichten einer Redis-Datenbank (Cache)
|
||||
|
||||
Twenty benötigt einen Redis-Cache, um die beste Leistung zu bieten
|
||||
Twenty requires a Redis cache to provide the best performance.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Linux">
|
||||
@@ -210,8 +212,10 @@ Twenty benötigt einen Redis-Cache, um die beste Leistung zu bieten
|
||||
```bash
|
||||
brew install redis
|
||||
```
|
||||
Starten Sie Ihren Redis-Server:
|
||||
`brew services start redis`
|
||||
Start your Redis server:
|
||||
```bash
|
||||
brew services start redis
|
||||
```
|
||||
|
||||
**Option 2:** Wenn Sie Docker installiert haben:
|
||||
```bash
|
||||
@@ -229,11 +233,11 @@ Twenty benötigt einen Redis-Cache, um die beste Leistung zu bieten
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
Wenn Sie eine Client-GUI benötigen, empfehlen wir [redis insight](https://redis.io/insight/) (kostenlose Version verfügbar)
|
||||
If you need a client GUI, we recommend [Redis Insight](https://redis.io/insight/) (free version available).
|
||||
|
||||
## Schritt 5: Einrichten von Umgebungsvariablen
|
||||
## Step 5: Set up environment variables
|
||||
|
||||
Verwenden Sie Umgebungsvariablen oder `.env`-Dateien, um Ihr Projekt zu konfigurieren. Weitere Informationen [hier](/l/de/developers/self-host/capabilities/setup)
|
||||
Verwenden Sie Umgebungsvariablen oder `.env`-Dateien, um Ihr Projekt zu konfigurieren. Weitere Informationen [hier](/l/de/developers/self-host/capabilities/setup).
|
||||
|
||||
Kopieren Sie die `.env.example`-Dateien in `/front` und `/server`:
|
||||
|
||||
|
||||
@@ -64,11 +64,17 @@ yarn twenty function:execute --preInstall
|
||||
# Die Post-Installationsfunktion ausführen
|
||||
yarn twenty function:execute --postInstall
|
||||
|
||||
# Die Anwendung für die Verteilung erstellen
|
||||
yarn twenty app:build
|
||||
|
||||
# Die Anwendung auf npm oder einen Twenty-Server veröffentlichen
|
||||
yarn twenty app:publish
|
||||
|
||||
# Die Anwendung aus dem aktuellen Arbeitsbereich deinstallieren
|
||||
yarn twenty app:uninstall
|
||||
|
||||
# Hilfe zu Befehlen anzeigen
|
||||
yarn twenty 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).
|
||||
@@ -1240,6 +1246,113 @@ Hauptpunkte:
|
||||
|
||||
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):
|
||||
|
||||
## Erstellen Ihrer App
|
||||
|
||||
Sobald Sie Ihre App mit `app:dev` entwickelt haben, verwenden Sie `app:build`, um sie in ein verteilbares Paket zu kompilieren.
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Die App erstellen (Ausgabe nach .twenty/output/)
|
||||
yarn twenty app:build
|
||||
|
||||
# Build ausführen und ein Tarball (.tgz) für die Verteilung erstellen
|
||||
yarn twenty app:build --tarball
|
||||
```
|
||||
|
||||
Der Build-Prozess:
|
||||
|
||||
1. **Parst und validiert das Manifest** — liest alle `defineX()`-Entitäten aus Ihren Quelldateien und validiert die Manifeststruktur.
|
||||
2. **Kompiliert Logikfunktionen und Front-Komponenten** — bündelt TypeScript-Quellcode in ESM `.mjs`-Dateien mit esbuild.
|
||||
3. **Erzeugt Checksummen** — berechnet MD5-Hashes für jede erstellte Datei, die im Manifest als `builtHandlerChecksum` / `builtComponentChecksum` gespeichert werden.
|
||||
4. **Generiert den typisierten API-Client** — führt eine Introspektion des GraphQL-Schemas durch und generiert die typisierten Clients `CoreApiClient` und `MetadataApiClient`.
|
||||
5. **Führt eine TypeScript-Typprüfung aus** — führt `tsc --noEmit` aus, um Typfehler vor der Veröffentlichung zu erkennen.
|
||||
6. **Baut mit dem generierten Client neu** — führt einen zweiten Kompiliervorgang durch, damit die generierten Client-Typen enthalten sind.
|
||||
7. **Erstellt optional einen Tarball** — wenn `--tarball` übergeben wird, wird `npm pack` ausgeführt, um eine `.tgz`-Datei zu erstellen, die für die Verteilung bereit ist.
|
||||
|
||||
Der Build-Output in `.twenty/output/` enthält:
|
||||
|
||||
```text
|
||||
.twenty/output/
|
||||
├── manifest.json # Manifest with checksums for all built files
|
||||
├── package.json # Copied from app root
|
||||
├── yarn.lock # Copied from app root
|
||||
├── src/
|
||||
│ ├── logic-functions/ # Compiled .mjs logic function files
|
||||
│ └── front-components/ # Compiled .mjs front component files
|
||||
├── public/ # Static assets (if any)
|
||||
└── my-app-1.0.0.tgz # Only with --tarball flag
|
||||
```
|
||||
|
||||
| Option | Beschreibung |
|
||||
| ----------- | -------------------------------------------------------------- |
|
||||
| `[appPath]` | Pfad zum App-Verzeichnis (standardmäßig aktuelles Verzeichnis) |
|
||||
| `--tarball` | Den Output zusätzlich in einen `.tgz`-Tarball packen |
|
||||
|
||||
## Veröffentlichen Ihrer App
|
||||
|
||||
Verwenden Sie `app:publish`, um Ihre App zu verteilen — entweder zur npm-Registry oder direkt zu einem Twenty-Server.
|
||||
|
||||
### Bei npm veröffentlichen (Standard)
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Publish to npm (requires npm login)
|
||||
yarn twenty app:publish
|
||||
|
||||
# Publish with a dist-tag (e.g. beta, next)
|
||||
yarn twenty app:publish --tag beta
|
||||
```
|
||||
|
||||
Dies baut die App und führt `npm publish` aus dem Verzeichnis `.twenty/output/` aus. Das veröffentlichte Paket kann dann von jedem Arbeitsbereich über den Twenty-Marktplatz installiert werden.
|
||||
|
||||
### Auf einem Twenty-Server veröffentlichen
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Publish directly to a Twenty server
|
||||
yarn twenty app:publish --server https://app.twenty.com
|
||||
```
|
||||
|
||||
Dies erstellt beim Build einen Tarball, lädt ihn über die GraphQL-Mutation `uploadAppTarball` auf den Server hoch und stößt die Installation in einem Schritt an. Dies ist nützlich für private Bereitstellungen oder Tests gegen einen bestimmten Server.
|
||||
|
||||
| Option | Beschreibung |
|
||||
| ----------------- | ------------------------------------------------------------------ |
|
||||
| `[appPath]` | Pfad zum App-Verzeichnis (standardmäßig aktuelles Verzeichnis) |
|
||||
| `--server <url>` | Auf einen Twenty-Server anstelle von npm veröffentlichen |
|
||||
| `--token <token>` | Authentifizierungstoken für den Zielserver |
|
||||
| `--tag <tag>` | npm dist-tag (z. B. `beta`, `next`) — nur für npm-Veröffentlichung |
|
||||
|
||||
## Anwendungsregistrierung
|
||||
|
||||
Bevor eine App in einem Arbeitsbereich installiert werden kann, muss sie **registriert** werden. Eine Registrierung ist ein Metadatensatz, der beschreibt, woher die App stammt und wie sie authentifiziert wird. Dies wird in den meisten Fällen automatisch durch die CLI erledigt.
|
||||
|
||||
### Quelltypen
|
||||
|
||||
Jede Registrierung hat einen **Quelltyp**, der bestimmt, wie die Dateien der App während der Installation aufgelöst werden:
|
||||
|
||||
| Quelltyp | Wie Dateien aufgelöst werden | Typischer Anwendungsfall |
|
||||
| --------- | ---------------------------------------------------------------------------------------------- | ------------------------------------------------------ |
|
||||
| `LOCAL` | Dateien werden in Echtzeit vom CLI-Watcher synchronisiert — die Installation wird übersprungen | Entwicklung mit `app:dev` |
|
||||
| `NPM` | Über das Feld `sourcePackage` aus der npm-Registry abgerufen | Veröffentlichte Apps auf npm |
|
||||
| `TARBALL` | Aus einer hochgeladenen, auf dem Server gespeicherten `.tgz`-Datei extrahiert | Private Apps, die mit `--server` veröffentlicht wurden |
|
||||
|
||||
### Wie die Registrierung erfolgt
|
||||
|
||||
* **`app:dev`** — erstellt beim ersten Ausführen des Dev-Modus für einen Arbeitsbereich automatisch eine `LOCAL`-Registrierung.
|
||||
* **`app:publish --server`** — lädt einen Tarball hoch und erstellt (oder aktualisiert) eine `TARBALL`-Registrierung und installiert anschließend die App.
|
||||
* **npm-Marktplatz** — `NPM`-Registrierungen werden erstellt, wenn Apps aus der npm-Registry in den Twenty-Marktplatzkatalog synchronisiert werden.
|
||||
* **GraphQL-API** — Sie können Registrierungen auch programmgesteuert über die Mutation `createApplicationRegistration` erstellen.
|
||||
|
||||
### Registrierung vs. Installation
|
||||
|
||||
**Registrierung** und **Installation** sind unterschiedliche Konzepte:
|
||||
|
||||
* Eine **Registrierung** (`ApplicationRegistration`) ist ein globaler Metadatensatz, der die App beschreibt: ihren Namen, den Quelltyp, die OAuth-Anmeldedaten und den Status der Marktplatzlistung. Sie existiert unabhängig von jedem Arbeitsbereich.
|
||||
* Eine **Installation** (`Application`) ist eine Instanz pro Arbeitsbereich. Wenn ein Benutzer eine App installiert, ermittelt Twenty das Paket aus der Quelle der Registrierung, schreibt die erstellten Dateien in den Speicher und synchronisiert das Manifest (wobei Objekte, Felder, Logikfunktionen usw. erstellt werden) in diesem Arbeitsbereich.
|
||||
|
||||
Eine Registrierung kann in vielen Arbeitsbereichen installiert werden. Jeder Arbeitsbereich erhält seine eigene Kopie der Dateien und des Datenmodells der App.
|
||||
|
||||
### OAuth-Anmeldedaten
|
||||
|
||||
Jede Registrierung enthält OAuth-Anmeldedaten (`oAuthClientId` und `oAuthClientSecret`), die bei der Erstellung generiert werden. Diese werden von der App verwendet, um API-Anfragen im Namen der Benutzer zu authentifizieren. Das Client-Secret wird bei der Erstellung **einmalig** zurückgegeben — bewahren Sie es sicher auf. Sie können es später über die Mutation `rotateApplicationRegistrationClientSecret` rotieren.
|
||||
|
||||
## 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:
|
||||
|
||||
@@ -3,7 +3,7 @@ title: 1-Klick mit Docker Compose
|
||||
---
|
||||
|
||||
<Warning>
|
||||
Docker-Container sind für die Produktion oder das Selbsthosten bestimmt. Für Beiträge siehe bitte das [Lokale Setup](/l/de/developers/contribute/capabilities/local-setup).
|
||||
Docker containers are for production hosting or self-hosting. For contributing, please check the [Local Setup](/l/de/developers/contribute/capabilities/local-setup).
|
||||
</Warning>
|
||||
|
||||
## Überblick
|
||||
@@ -12,7 +12,7 @@ Diese Anleitung enthält Schritt-für-Schritt-Anweisungen, um die Twenty-Anwendu
|
||||
|
||||
**Wichtig:** Ändern Sie nur die in dieser Anleitung explizit erwähnten Einstellungen. Andere Konfigurationen zu ändern, kann zu Problemen führen.
|
||||
|
||||
Siehe die Dokumentation [Umgebungsvariablen einrichten](/l/de/developers/self-host/capabilities/setup) zur erweiterten Konfiguration. Alle Umgebungsvariablen müssen in der Datei docker-compose.yml auf Server- und/oder Worker-Ebene deklariert werden, je nach Variable.
|
||||
See [Setup Environment Variables](/l/de/developers/self-host/capabilities/setup) for advanced configuration. All environment variables must be declared in the `docker-compose.yml` file at the server and/or worker level, depending on the variable.
|
||||
|
||||
## Systemanforderungen
|
||||
|
||||
|
||||
@@ -297,46 +297,60 @@ yarn command:prod cron:workflow:automated-cron-trigger
|
||||
**Nur-Umgebungsmodus:** Wenn Sie `IS_CONFIG_VARIABLES_IN_DB_ENABLED=false` setzen, fügen Sie diese Variablen stattdessen Ihrer `.env`-Datei hinzu.
|
||||
</Warning>
|
||||
|
||||
## Logikfunktionen
|
||||
## Logikfunktionen & Code-Interpreter
|
||||
|
||||
Twenty unterstützt Logikfunktionen für Workflows und benutzerdefinierte Logik. Die Ausführungsumgebung wird über die Umgebungsvariable `SERVERLESS_TYPE` konfiguriert.
|
||||
Twenty unterstützt Logikfunktionen für Workflows und den Code-Interpreter für KI-Datenanalyse. Beide führen vom Benutzer bereitgestellten Code aus und erfordern aus Sicherheitsgründen eine explizite Konfiguration.
|
||||
|
||||
### Sicherheits-Standardeinstellungen
|
||||
|
||||
**In Produktion (NODE_ENV=production):** Sowohl Logikfunktionen als auch der Code-Interpreter sind standardmäßig **deaktiviert**. Sie müssen sie, wenn Sie diese Funktionen benötigen, explizit mit `LOGIC_FUNCTION_TYPE` und `CODE_INTERPRETER_TYPE` aktivieren.
|
||||
|
||||
**In der Entwicklung (NODE_ENV=development):** Beide sind der Einfachheit halber beim lokalen Betrieb standardmäßig **LOCAL**.
|
||||
|
||||
<Warning>
|
||||
**Sicherheitshinweis:** Der lokale Treiber (`SERVERLESS_TYPE=LOCAL`) führt Code ohne Sandbox direkt auf dem Host in einem Node.js-Prozess aus. Er sollte nur für vertrauenswürdigen Code in der Entwicklung verwendet werden. Für Produktivbereitstellungen, die nicht vertrauenswürdigen Code verarbeiten, empfehlen wir nachdrücklich, `SERVERLESS_TYPE=LAMBDA` oder `SERVERLESS_TYPE=DISABLED` zu verwenden.
|
||||
**Sicherheitshinweis:** Der lokale Treiber (`LOGIC_FUNCTION_TYPE=LOCAL` oder `CODE_INTERPRETER_TYPE=LOCAL`) führt Code ohne Sandbox direkt auf dem Host in einem Node.js-Prozess aus. Er sollte nur für vertrauenswürdigen Code in der Entwicklung verwendet werden. Für Produktionsbereitstellungen, die nicht vertrauenswürdigen Code verarbeiten, verwenden Sie `LOGIC_FUNCTION_TYPE=LAMBDA` oder `CODE_INTERPRETER_TYPE=E2B` (mit Sandbox-Isolierung), oder lassen Sie sie deaktiviert.
|
||||
</Warning>
|
||||
|
||||
### Verfügbare Treiber
|
||||
### Logikfunktionen - Verfügbare Treiber
|
||||
|
||||
| Treiber | Umgebungsvariable | Anwendungsfall | Sicherheitsstufe |
|
||||
| ----------- | -------------------------- | -------------------------------------------------- | ---------------------------------- |
|
||||
| Deaktiviert | `SERVERLESS_TYPE=DISABLED` | Logikfunktionen vollständig deaktivieren | N/A |
|
||||
| Lokal | `SERVERLESS_TYPE=LOCAL` | Entwicklung und vertrauenswürdige Umgebungen | Niedrig (keine Sandbox) |
|
||||
| Lambda | `SERVERLESS_TYPE=LAMBDA` | Produktivbetrieb mit nicht vertrauenswürdigem Code | Hoch (Isolation auf Hardwareebene) |
|
||||
| Treiber | Umgebungsvariable | Anwendungsfall | Sicherheitsstufe |
|
||||
| ----------- | ------------------------------ | -------------------------------------------------- | ---------------------------------- |
|
||||
| Deaktiviert | `LOGIC_FUNCTION_TYPE=DISABLED` | Logikfunktionen vollständig deaktivieren | N/A |
|
||||
| Lokal | `LOGIC_FUNCTION_TYPE=LOCAL` | Entwicklung und vertrauenswürdige Umgebungen | Niedrig (keine Sandbox) |
|
||||
| Lambda | `LOGIC_FUNCTION_TYPE=LAMBDA` | Produktivbetrieb mit nicht vertrauenswürdigem Code | Hoch (Isolation auf Hardwareebene) |
|
||||
|
||||
### Empfohlene Konfiguration
|
||||
### Logikfunktionen - Empfohlene Konfiguration
|
||||
|
||||
**Für die Entwicklung:**
|
||||
|
||||
```bash
|
||||
SERVERLESS_TYPE=LOCAL # default
|
||||
LOGIC_FUNCTION_TYPE=LOCAL # default when NODE_ENV=development
|
||||
```
|
||||
|
||||
**Für den Produktivbetrieb (AWS):**
|
||||
|
||||
```bash
|
||||
SERVERLESS_TYPE=LAMBDA
|
||||
SERVERLESS_LAMBDA_REGION=us-east-1
|
||||
SERVERLESS_LAMBDA_ROLE=arn:aws:iam::123456789:role/your-lambda-role
|
||||
SERVERLESS_LAMBDA_ACCESS_KEY_ID=your-access-key
|
||||
SERVERLESS_LAMBDA_SECRET_ACCESS_KEY=your-secret-key
|
||||
LOGIC_FUNCTION_TYPE=LAMBDA
|
||||
LOGIC_FUNCTION_LAMBDA_REGION=us-east-1
|
||||
LOGIC_FUNCTION_LAMBDA_ROLE=arn:aws:iam::123456789:role/your-lambda-role
|
||||
LOGIC_FUNCTION_LAMBDA_ACCESS_KEY_ID=your-access-key
|
||||
LOGIC_FUNCTION_LAMBDA_SECRET_ACCESS_KEY=your-secret-key
|
||||
```
|
||||
|
||||
**Zum Deaktivieren von Logikfunktionen:**
|
||||
|
||||
```bash
|
||||
SERVERLESS_TYPE=DISABLED
|
||||
LOGIC_FUNCTION_TYPE=DISABLED # default when NODE_ENV=production
|
||||
```
|
||||
|
||||
### Code-Interpreter - Verfügbare Treiber
|
||||
|
||||
| Treiber | Umgebungsvariable | Anwendungsfall | Sicherheitsstufe |
|
||||
| ----------- | -------------------------------- | ------------------------------------------ | ------------------------ |
|
||||
| Deaktiviert | `CODE_INTERPRETER_TYPE=DISABLED` | KI-Codeausführung deaktivieren | N/A |
|
||||
| Lokal | `CODE_INTERPRETER_TYPE=LOCAL` | Nur für die Entwicklung | Niedrig (keine Sandbox) |
|
||||
| E2B | `CODE_INTERPRETER_TYPE=E_2_B` | Produktion mit Ausführung in einer Sandbox | Hoch (isolierte Sandbox) |
|
||||
|
||||
<Note>
|
||||
Bei Verwendung von `SERVERLESS_TYPE=DISABLED` führt jeder Versuch, eine Logikfunktion auszuführen, zu einem Fehler. Dies ist nützlich, wenn Sie Twenty ohne Unterstützung für Logikfunktionen betreiben möchten.
|
||||
Bei Verwendung von `LOGIC_FUNCTION_TYPE=DISABLED` oder `CODE_INTERPRETER_TYPE=DISABLED` führt jeder Ausführungsversuch zu einem Fehler. Dies ist nützlich, wenn Sie Twenty ohne diese Funktionen betreiben möchten.
|
||||
</Note>
|
||||
|
||||
+2
-2
@@ -8,7 +8,7 @@ L'obiettivo qui è avere una base di codice coerente, facile da leggere e da man
|
||||
|
||||
Per questo, è meglio essere un po' più dettagliati che troppo concisi.
|
||||
|
||||
Tieni sempre a mente che le persone leggono il codice più spesso di quanto non lo scrivano, soprattutto in un progetto open source, dove chiunque può contribuire.
|
||||
Always keep in mind that people read code more often than they write it, especially on an open source project, where anyone can contribute.
|
||||
|
||||
Ci sono molte regole che non sono definite qui, ma che vengono controllate automaticamente dai linters.
|
||||
|
||||
@@ -150,7 +150,7 @@ type MyType = {
|
||||
|
||||
### Usa letterali di stringa invece di enum
|
||||
|
||||
[I letterali di stringa](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types) sono la modalità preferita per gestire valori simili agli enum in TypeScript. Sono più facili da estendere con Pick e Omit e offrono una migliore esperienza per lo sviluppatore, in particolare con il completamento del codice.
|
||||
[I letterali di stringa](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types) sono la modalità preferita per gestire valori simili agli enum in TypeScript. They are easier to extend with Pick and Omit, and offer a better developer experience, especially with code completion.
|
||||
|
||||
Puoi vedere perché TypeScript consiglia di evitare gli enum [qui](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#enums).
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ description: La guida per i collaboratori (o sviluppatori curiosi) che vogliono
|
||||
## Prerequisiti
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Linux e MacOS">
|
||||
<Tab title="Linux and macOS">
|
||||
|
||||
Prima di poter installare e usare Twenty, assicurati di installare quanto segue sul tuo computer:
|
||||
* [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
|
||||
@@ -30,7 +30,7 @@ wsl --install
|
||||
```
|
||||
Dovresti ora vedere un prompt per riavviare il computer. In caso contrario, riavvialo manualmente.
|
||||
|
||||
Al riavvio, si aprirà una finestra di PowerShell e installerà Ubuntu. Questo potrebbe richiedere un po' di tempo.
|
||||
Upon restart, a PowerShell window will open and install Ubuntu. Questo potrebbe richiedere un po' di tempo.
|
||||
Vedrai un prompt per creare un nome utente e una password per la tua installazione di Ubuntu.
|
||||
|
||||
2. Installa e configura Git
|
||||
@@ -102,8 +102,8 @@ Dovresti eseguire tutti i comandi nei passaggi successivi dalla radice del proge
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Linux">
|
||||
**Opzione 1 (preferita):** Per predisporre il database in locale:
|
||||
Usa il seguente link per installare PostgreSQL sulla tua macchina Linux: [Installazione di PostgreSQL](https://www.postgresql.org/download/linux/)
|
||||
**Option 1 (preferred):** To provision your database locally:
|
||||
Use the following link to install PostgreSQL on your Linux machine: [PostgreSQL Installation](https://www.postgresql.org/download/linux/)
|
||||
```bash
|
||||
psql postgres -c "CREATE DATABASE \"default\";" -c "CREATE DATABASE test;"
|
||||
```
|
||||
@@ -129,8 +129,8 @@ Dovresti eseguire tutti i comandi nei passaggi successivi dalla radice del proge
|
||||
brew services list
|
||||
```
|
||||
|
||||
L'installatore potrebbe non creare l'utente `postgres` di default quando si installa
|
||||
tramite Homebrew su MacOS. Invece, crea un ruolo di PostgreSQL che corrisponde al tuo nome utente macOS
|
||||
The installer might not create the `postgres` user by default when installing
|
||||
via Homebrew on macOS. Invece, crea un ruolo di PostgreSQL che corrisponde al tuo nome utente macOS
|
||||
(es., "john").
|
||||
Per controllare e creare l'utente `postgres` se necessario, segui questi passaggi:
|
||||
```bash
|
||||
@@ -173,8 +173,8 @@ Dovresti eseguire tutti i comandi nei passaggi successivi dalla radice del proge
|
||||
<Tab title="Windows (WSL)">
|
||||
Tutti i passaggi seguenti devono essere eseguiti nel terminale WSL (all'interno della tua macchina virtuale)
|
||||
|
||||
**Opzione 1:** Per predisporre PostgreSQL in locale:
|
||||
Usa il seguente link per installare PostgreSQL nella tua macchina virtuale Linux: [Installazione di PostgreSQL](https://www.postgresql.org/download/linux/)
|
||||
**Option 1:** To provision your PostgreSQL locally:
|
||||
Use the following link to install PostgreSQL on your Linux virtual machine: [PostgreSQL Installation](https://www.postgresql.org/download/linux/)
|
||||
```bash
|
||||
psql postgres -c "CREATE DATABASE \"default\";" -c "CREATE DATABASE test;"
|
||||
```
|
||||
@@ -189,11 +189,13 @@ Dovresti eseguire tutti i comandi nei passaggi successivi dalla radice del proge
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
Puoi ora accedere al database su [localhost:5432](localhost:5432), con utente `postgres` e password `postgres`.
|
||||
You can now access the database at `localhost:5432`.
|
||||
|
||||
If you used the Docker option above, the default credentials are user `postgres` and password `postgres`. For native PostgreSQL installations, use the credentials and roles configured on your machine.
|
||||
|
||||
## Passaggio 4: Configura un database Redis (cache)
|
||||
|
||||
Twenty richiede una cache Redis per offrire le migliori prestazioni
|
||||
Twenty requires a Redis cache to provide the best performance.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Linux">
|
||||
@@ -210,8 +212,10 @@ Twenty richiede una cache Redis per offrire le migliori prestazioni
|
||||
```bash
|
||||
brew install redis
|
||||
```
|
||||
Avvia il tuo server Redis:
|
||||
`brew services start redis`
|
||||
Start your Redis server:
|
||||
```bash
|
||||
brew services start redis
|
||||
```
|
||||
|
||||
**Opzione 2:** Se hai Docker installato:
|
||||
```bash
|
||||
@@ -229,11 +233,11 @@ Twenty richiede una cache Redis per offrire le migliori prestazioni
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
Se hai bisogno di una GUI client, ti consigliamo [Redis Insight](https://redis.io/insight/) (versione gratuita disponibile)
|
||||
If you need a client GUI, we recommend [Redis Insight](https://redis.io/insight/) (free version available).
|
||||
|
||||
## Passaggio 5: Configura le variabili d'ambiente
|
||||
## Step 5: Set up environment variables
|
||||
|
||||
Usa variabili d'ambiente o file `.env` per configurare il tuo progetto. Maggiori informazioni [qui](/l/it/developers/self-host/capabilities/setup)
|
||||
Usa variabili d'ambiente o file `.env` per configurare il tuo progetto. Maggiori informazioni [qui](/l/it/developers/self-host/capabilities/setup).
|
||||
|
||||
Copia i file `.env.example` in `/front` e `/server`:
|
||||
|
||||
|
||||
@@ -64,6 +64,12 @@ yarn twenty function:execute --preInstall
|
||||
# Esegui la funzione post-installazione
|
||||
yarn twenty function:execute --postInstall
|
||||
|
||||
# Compila l'app per la distribuzione
|
||||
yarn twenty app:build
|
||||
|
||||
# Pubblica l'app su npm o su un server Twenty
|
||||
yarn twenty app:publish
|
||||
|
||||
# Disinstalla l'applicazione dallo spazio di lavoro corrente
|
||||
yarn twenty app:uninstall
|
||||
|
||||
@@ -1240,6 +1246,113 @@ Punti chiave:
|
||||
|
||||
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):
|
||||
|
||||
## Compilazione della tua app
|
||||
|
||||
Una volta che hai sviluppato la tua app con `app:dev`, usa `app:build` per compilarla in un pacchetto distribuibile.
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Compila l'app (l'output va in .twenty/output/)
|
||||
yarn twenty app:build
|
||||
|
||||
# Compila e crea un tarball (.tgz) per la distribuzione
|
||||
yarn twenty app:build --tarball
|
||||
```
|
||||
|
||||
Il processo di compilazione:
|
||||
|
||||
1. **Analizza e convalida il manifest** — legge tutte le entità `defineX()` dai tuoi file sorgente e convalida la struttura del manifest.
|
||||
2. **Compila le funzioni di logica e i componenti front-end** — raggruppa i sorgenti TypeScript in file ESM `.mjs` usando esbuild.
|
||||
3. **Genera i checksum** — calcola gli hash MD5 per ogni file compilato, memorizzati nel manifest come `builtHandlerChecksum` / `builtComponentChecksum`.
|
||||
4. **Genera il client API tipizzato** — esegue l'analisi dello schema GraphQL e genera i client tipizzati `CoreApiClient` e `MetadataApiClient`.
|
||||
5. **Esegue un controllo dei tipi di TypeScript** — esegue `tsc --noEmit` per intercettare gli errori di tipo prima della pubblicazione.
|
||||
6. **Ricompila con il client generato** — esegue una seconda passata di compilazione in modo da includere i tipi del client generato.
|
||||
7. **Crea facoltativamente un tarball** — se viene passato `--tarball`, esegue `npm pack` per creare un file `.tgz` pronto per la distribuzione.
|
||||
|
||||
L'output della build in `.twenty/output/` contiene:
|
||||
|
||||
```text
|
||||
.twenty/output/
|
||||
├── manifest.json # Manifest con checksum per tutti i file compilati
|
||||
├── package.json # Copiato dalla radice dell'app
|
||||
├── yarn.lock # Copiato dalla radice dell'app
|
||||
├── src/
|
||||
│ ├── logic-functions/ # File .mjs compilati delle funzioni logiche
|
||||
│ └── front-components/ # File .mjs compilati dei componenti front-end
|
||||
├── public/ # Asset statici (se presenti)
|
||||
└── my-app-1.0.0.tgz # Solo con il flag --tarball
|
||||
```
|
||||
|
||||
| Opzione | Descrizione |
|
||||
| ----------- | ------------------------------------------------------------------- |
|
||||
| `[appPath]` | Percorso della directory dell'app (predefinito: directory corrente) |
|
||||
| `--tarball` | Imballa anche l'output in un tarball `.tgz` |
|
||||
|
||||
## Pubblicazione della tua app
|
||||
|
||||
Usa `app:publish` per distribuire la tua app — al registro npm oppure direttamente a un server Twenty.
|
||||
|
||||
### Pubblica su npm (predefinito)
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Pubblica su npm (richiede l'accesso a npm)
|
||||
yarn twenty app:publish
|
||||
|
||||
# Pubblica con un dist-tag (ad es. beta, next)
|
||||
yarn twenty app:publish --tag beta
|
||||
```
|
||||
|
||||
Questo compila l'app ed esegue `npm publish` dalla directory `.twenty/output/`. Il pacchetto pubblicato può quindi essere installato dal marketplace di Twenty da qualsiasi area di lavoro.
|
||||
|
||||
### Pubblica su un server Twenty
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Pubblica direttamente su un server Twenty
|
||||
yarn twenty app:publish --server https://app.twenty.com
|
||||
```
|
||||
|
||||
Questo compila l'app con un tarball, lo carica sul server tramite la mutation GraphQL `uploadAppTarball` e avvia l'installazione in un unico passaggio. Questo è utile per distribuzioni private o per effettuare test su un server specifico.
|
||||
|
||||
| Opzione | Descrizione |
|
||||
| ----------------- | -------------------------------------------------------------------------- |
|
||||
| `[appPath]` | Percorso della directory dell'app (predefinito: directory corrente) |
|
||||
| `--server <url>` | Pubblica su un server Twenty invece di npm |
|
||||
| `--token <token>` | Token di autenticazione per il server di destinazione |
|
||||
| `--tag <tag>` | dist-tag di npm (ad es. `beta`, `next`) — solo per la pubblicazione su npm |
|
||||
|
||||
## Registrazione dell'applicazione
|
||||
|
||||
Prima che un'app possa essere installata in un'area di lavoro, deve essere **registrata**. Una registrazione è un record di metadati che descrive l'origine dell'app e come autenticarla. Nella maggior parte dei casi questo è gestito automaticamente dalla CLI.
|
||||
|
||||
### Tipi di origine
|
||||
|
||||
Ogni registrazione ha un **tipo di origine** che determina come vengono risolti i file dell'app durante l'installazione:
|
||||
|
||||
| Tipo di origine | Come vengono risolti i file | Caso d'uso tipico |
|
||||
| --------------- | ---------------------------------------------------------------------------------------------- | ------------------------------------- |
|
||||
| `LOCAL` | I file sono sincronizzati in tempo reale dal watcher della CLI — l'installazione viene saltata | Sviluppo con `app:dev` |
|
||||
| `NPM` | Recuperati dal registro npm tramite il campo `sourcePackage` | App pubblicate su npm |
|
||||
| `TARBALL` | Estratti da un file `.tgz` caricato e archiviato sul server | App private pubblicate con `--server` |
|
||||
|
||||
### Come avviene la registrazione
|
||||
|
||||
* **`app:dev`** — crea automaticamente una registrazione `LOCAL` la prima volta che esegui la modalità di sviluppo su un'area di lavoro.
|
||||
* **`app:publish --server`** — carica un tarball e crea (o aggiorna) una registrazione `TARBALL`, quindi installa l'app.
|
||||
* **Marketplace npm** — le registrazioni `NPM` vengono create quando le app vengono sincronizzate dal registro npm nel catalogo del marketplace di Twenty.
|
||||
* **GraphQL API** — puoi anche creare registrazioni in modo programmatico tramite la mutation `createApplicationRegistration`.
|
||||
|
||||
### Registrazione vs installazione
|
||||
|
||||
**Registrazione** e **installazione** sono concetti distinti:
|
||||
|
||||
* Una **registrazione** (`ApplicationRegistration`) è un record di metadati globale che descrive l'app: il suo nome, il tipo di origine, le credenziali OAuth e lo stato di pubblicazione nel marketplace. Esiste indipendentemente da qualsiasi area di lavoro.
|
||||
* Un'**installazione** (`Application`) è un'istanza per area di lavoro. Quando un utente installa un'app, Twenty risolve il pacchetto dalla sorgente della registrazione, scrive i file compilati nell'archiviazione e sincronizza il manifest (creando oggetti, campi, funzioni logiche, ecc.) in quell'area di lavoro.
|
||||
|
||||
Una registrazione può essere installata in molte aree di lavoro. Ogni area di lavoro ottiene la propria copia dei file dell'app e del modello di dati.
|
||||
|
||||
### Credenziali OAuth
|
||||
|
||||
Ogni registrazione include credenziali OAuth (`oAuthClientId` e `oAuthClientSecret`) generate al momento della creazione. Queste vengono utilizzate dall'app per autenticare le richieste API per conto degli utenti. Il client secret viene restituito **una sola volta** alla creazione — conservalo in modo sicuro. Puoi ruotarlo in seguito tramite la mutation `rotateApplicationRegistrationClientSecret`.
|
||||
|
||||
## 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:
|
||||
|
||||
@@ -3,7 +3,7 @@ title: 1-Click con Docker Compose
|
||||
---
|
||||
|
||||
<Warning>
|
||||
I container Docker sono per hosting in produzione o auto-hosting, per il contributo consulta il [Setup Locale](/l/it/developers/contribute/capabilities/local-setup).
|
||||
Docker containers are for production hosting or self-hosting. For contributing, please check the [Local Setup](/l/it/developers/contribute/capabilities/local-setup).
|
||||
</Warning>
|
||||
|
||||
## Panoramica
|
||||
@@ -12,7 +12,7 @@ Questa guida fornisce istruzioni passo passo per installare e configurare l'appl
|
||||
|
||||
**Importante:** Modifica solo le impostazioni esplicitamente menzionate in questa guida. Modificare altre configurazioni potrebbe portare a problemi.
|
||||
|
||||
Consulta i documenti [Configurazione delle Variabili di Ambiente](/l/it/developers/self-host/capabilities/setup) per configurazioni avanzate. Tutte le variabili di ambiente devono essere dichiarate nel file docker-compose.yml a livello di server e/o di worker a seconda della variabile.
|
||||
See [Setup Environment Variables](/l/it/developers/self-host/capabilities/setup) for advanced configuration. All environment variables must be declared in the `docker-compose.yml` file at the server and/or worker level, depending on the variable.
|
||||
|
||||
## Requisiti di Sistema
|
||||
|
||||
|
||||
@@ -296,46 +296,60 @@ yarn command:prod cron:workflow:automated-cron-trigger
|
||||
**Modalità solo ambiente:** Se imposti `IS_CONFIG_VARIABLES_IN_DB_ENABLED=false`, aggiungi queste variabili al tuo file `.env` invece.
|
||||
</Warning>
|
||||
|
||||
## Funzioni logiche
|
||||
## Funzioni logiche & interprete del codice
|
||||
|
||||
Twenty supporta le funzioni logiche per i workflow e la logica personalizzata. L'ambiente di esecuzione è configurato tramite la variabile di ambiente `SERVERLESS_TYPE`.
|
||||
Twenty supporta le funzioni logiche per i workflow e l'interprete del codice per l'analisi dei dati con IA. Entrambi eseguono codice fornito dall'utente e richiedono una configurazione esplicita per motivi di sicurezza.
|
||||
|
||||
### Impostazioni di sicurezza predefinite
|
||||
|
||||
**In produzione (NODE_ENV=production):** Sia le funzioni logiche sia l'interprete del codice hanno come impostazione predefinita **Disabilitato**. È necessario abilitarli esplicitamente con `LOGIC_FUNCTION_TYPE` e `CODE_INTERPRETER_TYPE` se queste funzionalità sono necessarie.
|
||||
|
||||
**In sviluppo (NODE_ENV=development):** Entrambi sono impostati su **LOCAL** per comodità quando vengono eseguiti in locale.
|
||||
|
||||
<Warning>
|
||||
**Avviso di sicurezza:** Il driver locale (`SERVERLESS_TYPE=LOCAL`) esegue il codice direttamente sull'host in un processo Node.js senza sandboxing. Dovrebbe essere utilizzato solo per codice attendibile in fase di sviluppo. Per le distribuzioni in produzione che gestiscono codice non attendibile, consigliamo vivamente di usare `SERVERLESS_TYPE=LAMBDA` o `SERVERLESS_TYPE=DISABLED`.
|
||||
**Avviso di sicurezza:** Il driver locale (`LOGIC_FUNCTION_TYPE=LOCAL` o `CODE_INTERPRETER_TYPE=LOCAL`) esegue il codice direttamente sull'host in un processo Node.js senza sandboxing. Dovrebbe essere utilizzato solo per codice attendibile in fase di sviluppo. Per le distribuzioni in produzione che gestiscono codice non affidabile, usa `LOGIC_FUNCTION_TYPE=LAMBDA` o `CODE_INTERPRETER_TYPE=E2B` (con sandboxing), oppure lasciali disabilitati.
|
||||
</Warning>
|
||||
|
||||
### Driver disponibili
|
||||
### Funzioni logiche - Driver disponibili
|
||||
|
||||
| Driver | Variabile di ambiente | Caso d'uso | Livello di sicurezza |
|
||||
| ------------ | -------------------------- | -------------------------------------------- | ------------------------------------ |
|
||||
| Disabilitato | `SERVERLESS_TYPE=DISABLED` | Disabilita completamente le funzioni logiche | N/A |
|
||||
| Locale | `SERVERLESS_TYPE=LOCAL` | Ambienti di sviluppo e attendibili | Basso (nessuna sandbox) |
|
||||
| Lambda | `SERVERLESS_TYPE=LAMBDA` | Produzione con codice non attendibile | Alto (isolamento a livello hardware) |
|
||||
| Driver | Variabile di ambiente | Caso d'uso | Livello di sicurezza |
|
||||
| ------------ | ------------------------------ | -------------------------------------------- | ------------------------------------ |
|
||||
| Disabilitato | `LOGIC_FUNCTION_TYPE=DISABLED` | Disabilita completamente le funzioni logiche | N/A |
|
||||
| Locale | `LOGIC_FUNCTION_TYPE=LOCAL` | Ambienti di sviluppo e attendibili | Basso (nessuna sandbox) |
|
||||
| Lambda | `LOGIC_FUNCTION_TYPE=LAMBDA` | Produzione con codice non attendibile | Alto (isolamento a livello hardware) |
|
||||
|
||||
### Configurazione consigliata
|
||||
### Funzioni logiche - Configurazione consigliata
|
||||
|
||||
**Per lo sviluppo:**
|
||||
|
||||
```bash
|
||||
SERVERLESS_TYPE=LOCAL # default
|
||||
LOGIC_FUNCTION_TYPE=LOCAL # default when NODE_ENV=development
|
||||
```
|
||||
|
||||
**Per la produzione (AWS):**
|
||||
|
||||
```bash
|
||||
SERVERLESS_TYPE=LAMBDA
|
||||
SERVERLESS_LAMBDA_REGION=us-east-1
|
||||
SERVERLESS_LAMBDA_ROLE=arn:aws:iam::123456789:role/your-lambda-role
|
||||
SERVERLESS_LAMBDA_ACCESS_KEY_ID=your-access-key
|
||||
SERVERLESS_LAMBDA_SECRET_ACCESS_KEY=your-secret-key
|
||||
LOGIC_FUNCTION_TYPE=LAMBDA
|
||||
LOGIC_FUNCTION_LAMBDA_REGION=us-east-1
|
||||
LOGIC_FUNCTION_LAMBDA_ROLE=arn:aws:iam::123456789:role/your-lambda-role
|
||||
LOGIC_FUNCTION_LAMBDA_ACCESS_KEY_ID=your-access-key
|
||||
LOGIC_FUNCTION_LAMBDA_SECRET_ACCESS_KEY=your-secret-key
|
||||
```
|
||||
|
||||
**Per disabilitare le funzioni logiche:**
|
||||
|
||||
```bash
|
||||
SERVERLESS_TYPE=DISABLED
|
||||
LOGIC_FUNCTION_TYPE=DISABLED # default when NODE_ENV=production
|
||||
```
|
||||
|
||||
### Interprete del codice - Driver disponibili
|
||||
|
||||
| Driver | Variabile di ambiente | Caso d'uso | Livello di sicurezza |
|
||||
| ------------ | -------------------------------- | ------------------------------------- | ----------------------- |
|
||||
| Disabilitato | `CODE_INTERPRETER_TYPE=DISABLED` | Disabilita l'esecuzione del codice IA | N/A |
|
||||
| Locale | `CODE_INTERPRETER_TYPE=LOCAL` | Solo per lo sviluppo | Basso (nessuna sandbox) |
|
||||
| E2B | `CODE_INTERPRETER_TYPE=E_2_B` | Produzione con esecuzione in sandbox | Alta (sandbox isolata) |
|
||||
|
||||
<Note>
|
||||
Quando si utilizza `SERVERLESS_TYPE=DISABLED`, qualsiasi tentativo di eseguire una funzione logica restituirà un errore. Ciò è utile se si desidera eseguire Twenty senza il supporto per le funzioni logiche.
|
||||
Quando si utilizza `LOGIC_FUNCTION_TYPE=DISABLED` o `CODE_INTERPRETER_TYPE=DISABLED`, qualsiasi tentativo di esecuzione restituirà un errore. Ciò è utile se si desidera eseguire Twenty senza queste funzionalità.
|
||||
</Note>
|
||||
|
||||
+2
-2
@@ -8,7 +8,7 @@ O objetivo aqui é ter uma base de código consistente, fácil de ler e fácil d
|
||||
|
||||
Para isso, é melhor ser um pouco mais detalhado do que ser muito conciso.
|
||||
|
||||
Sempre tenha em mente que as pessoas leem código mais frequentemente do que o escrevem, especialmente em um projeto de código aberto, onde qualquer um pode contribuir.
|
||||
Always keep in mind that people read code more often than they write it, especially on an open source project, where anyone can contribute.
|
||||
|
||||
Há muitas regras que não estão definidas aqui, mas que são verificadas automaticamente por linters.
|
||||
|
||||
@@ -150,7 +150,7 @@ type MyType = {
|
||||
|
||||
### Use literais de string em vez de enums
|
||||
|
||||
[Literals de string](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types) são o caminho a seguir para lidar com valores tipo enum no TypeScript. Eles são mais fáceis de estender com Pick e Omit, e oferecem uma melhor experiência de desenvolvedor, especialmente com autocomplete.
|
||||
[Literals de string](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types) são o caminho a seguir para lidar com valores tipo enum no TypeScript. They are easier to extend with Pick and Omit, and offer a better developer experience, especially with code completion.
|
||||
|
||||
Você pode ver porque o TypeScript recomenda evitar enums [aqui](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#enums).
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ description: O guia para contribuidores (ou desenvolvedores curiosos) que deseja
|
||||
## Pré-requisitos
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Linux e MacOS">
|
||||
<Tab title="Linux and macOS">
|
||||
|
||||
Antes de instalar e usar o Twenty, certifique-se de instalar o seguinte em seu computador:
|
||||
* [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
|
||||
@@ -30,7 +30,7 @@ wsl --install
|
||||
```
|
||||
Você deve agora ver um aviso para reiniciar o computador. Caso contrário, reinicie-o manualmente.
|
||||
|
||||
Ao reiniciar, uma janela do powershell será aberta e instalará o Ubuntu. Isso pode levar algum tempo.
|
||||
Upon restart, a PowerShell window will open and install Ubuntu. Isso pode levar algum tempo.
|
||||
Você verá uma solicitação para criar um nome de usuário e senha para sua instalação do Ubuntu.
|
||||
|
||||
2. Instalar e configurar o git
|
||||
@@ -102,8 +102,8 @@ Você deve executar todos os comandos nas etapas seguintes a partir da raiz do p
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Linux">
|
||||
**Opção 1 (preferencial):** Para prover seu banco de dados localmente:
|
||||
Use o seguinte link para instalar o Postgresql na sua máquina Linux: [Instalação do Postgresql](https://www.postgresql.org/download/linux/)
|
||||
**Option 1 (preferred):** To provision your database locally:
|
||||
Use the following link to install PostgreSQL on your Linux machine: [PostgreSQL Installation](https://www.postgresql.org/download/linux/)
|
||||
```bash
|
||||
psql postgres -c "CREATE DATABASE \"default\";" -c "CREATE DATABASE test;"
|
||||
```
|
||||
@@ -129,8 +129,8 @@ Você deve executar todos os comandos nas etapas seguintes a partir da raiz do p
|
||||
brew services list
|
||||
```
|
||||
|
||||
O instalador pode não criar o usuário `postgres` por padrão ao instalar
|
||||
via Homebrew no MacOS. Em vez disso, ele cria uma função PostgreSQL que corresponde ao seu nome de usuário do macOS
|
||||
The installer might not create the `postgres` user by default when installing
|
||||
via Homebrew on macOS. Em vez disso, ele cria uma função PostgreSQL que corresponde ao seu nome de usuário do macOS
|
||||
(por exemplo, "john").
|
||||
Para verificar e criar o usuário `postgres`, se necessário, siga estas etapas:
|
||||
```bash
|
||||
@@ -173,8 +173,8 @@ Você deve executar todos os comandos nas etapas seguintes a partir da raiz do p
|
||||
<Tab title="Windows (WSL)">
|
||||
Todos os passos a seguir devem ser executados no terminal WSL (dentro da sua máquina virtual)
|
||||
|
||||
**Opção 1:** Para provisionar seu Postgresql localmente:
|
||||
Use o seguinte link para instalar o Postgresql em sua máquina virtual Linux: [Instalação do Postgresql](https://www.postgresql.org/download/linux/)
|
||||
**Option 1:** To provision your PostgreSQL locally:
|
||||
Use the following link to install PostgreSQL on your Linux virtual machine: [PostgreSQL Installation](https://www.postgresql.org/download/linux/)
|
||||
```bash
|
||||
psql postgres -c "CREATE DATABASE \"default\";" -c "CREATE DATABASE test;"
|
||||
```
|
||||
@@ -189,11 +189,13 @@ Você deve executar todos os comandos nas etapas seguintes a partir da raiz do p
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
Você pode agora acessar o banco de dados em [localhost:5432](localhost:5432), com o usuário `postgres` e senha `postgres`.
|
||||
You can now access the database at `localhost:5432`.
|
||||
|
||||
If you used the Docker option above, the default credentials are user `postgres` and password `postgres`. For native PostgreSQL installations, use the credentials and roles configured on your machine.
|
||||
|
||||
## Passo 4: Configurar um Banco de Dados Redis (cache)
|
||||
|
||||
O Twenty requer um cache redis para oferecer o melhor desempenho
|
||||
Twenty requires a Redis cache to provide the best performance.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Linux">
|
||||
@@ -210,8 +212,10 @@ O Twenty requer um cache redis para oferecer o melhor desempenho
|
||||
```bash
|
||||
brew install redis
|
||||
```
|
||||
Inicie seu servidor redis:
|
||||
`brew services start redis`
|
||||
Start your Redis server:
|
||||
```bash
|
||||
brew services start redis
|
||||
```
|
||||
|
||||
**Opção 2:** Se você tem o docker instalado:
|
||||
```bash
|
||||
@@ -229,11 +233,11 @@ O Twenty requer um cache redis para oferecer o melhor desempenho
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
Se precisar de uma GUI de Cliente, recomendamos o [redis insight](https://redis.io/insight/) (versão gratuita disponível)
|
||||
If you need a client GUI, we recommend [Redis Insight](https://redis.io/insight/) (free version available).
|
||||
|
||||
## Passo 5: Configurar variáveis de ambiente
|
||||
## Step 5: Set up environment variables
|
||||
|
||||
Use variáveis de ambiente ou arquivos `.env` para configurar seu projeto. Mais informações [aqui](/l/pt/developers/self-host/capabilities/setup)
|
||||
Use variáveis de ambiente ou arquivos `.env` para configurar seu projeto. Mais informações [aqui](/l/pt/developers/self-host/capabilities/setup).
|
||||
|
||||
Copie os arquivos `.env.example` em `/front` e `/server`:
|
||||
|
||||
|
||||
@@ -49,25 +49,31 @@ npx create-twenty-app@latest my-app --minimal
|
||||
A partir daqui você pode:
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Add a new entity to your application (guided)
|
||||
# Adicionar uma nova entidade à sua aplicação (assistido)
|
||||
yarn twenty entity:add
|
||||
|
||||
# Watch your application's function logs
|
||||
# Acompanhar os logs das funções da sua aplicação
|
||||
yarn twenty function:logs
|
||||
|
||||
# Execute a function by name
|
||||
# Executar uma função pelo nome
|
||||
yarn twenty function:execute -n my-function -p '{"name": "test"}'
|
||||
|
||||
# Execute the pre-install function
|
||||
# Executar a função de pré-instalação
|
||||
yarn twenty function:execute --preInstall
|
||||
|
||||
# Execute the post-install function
|
||||
# Executar a função de pós-instalação
|
||||
yarn twenty function:execute --postInstall
|
||||
|
||||
# Uninstall the application from the current workspace
|
||||
# Compilar a aplicação para distribuição
|
||||
yarn twenty app:build
|
||||
|
||||
# Publicar a aplicação no npm ou em um servidor Twenty
|
||||
yarn twenty app:publish
|
||||
|
||||
# Desinstalar a aplicação do espaço de trabalho atual
|
||||
yarn twenty app:uninstall
|
||||
|
||||
# Display commands' help
|
||||
# Exibir a ajuda dos comandos
|
||||
yarn twenty help
|
||||
```
|
||||
|
||||
@@ -1241,6 +1247,113 @@ Pontos-chave:
|
||||
|
||||
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):
|
||||
|
||||
## Compilando seu app
|
||||
|
||||
Depois de desenvolver seu app com `app:dev`, use `app:build` para compilá-lo em um pacote distribuível.
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Compilar o app (a saída vai para .twenty/output/)
|
||||
yarn twenty app:build
|
||||
|
||||
# Compilar e criar um tarball (.tgz) para distribuição
|
||||
yarn twenty app:build --tarball
|
||||
```
|
||||
|
||||
O processo de build:
|
||||
|
||||
1. **Analisa e valida o manifesto** — lê todas as entidades `defineX()` dos seus arquivos de código-fonte e valida a estrutura do manifesto.
|
||||
2. **Compila funções de lógica e componentes de front-end** — empacota o código-fonte TypeScript em arquivos ESM `.mjs` usando o esbuild.
|
||||
3. **Gera checksums** — calcula hashes MD5 para cada arquivo gerado, armazenados no manifesto como `builtHandlerChecksum` / `builtComponentChecksum`.
|
||||
4. **Gera o cliente de API tipado** — inspeciona o esquema GraphQL e gera clientes tipados `CoreApiClient` e `MetadataApiClient`.
|
||||
5. **Executa uma verificação de tipos do TypeScript** — executa `tsc --noEmit` para detectar erros de tipo antes da publicação.
|
||||
6. **Reconstrói com o cliente gerado** — realiza uma segunda passagem de compilação para que os tipos do cliente gerado sejam incluídos.
|
||||
7. **Opcionalmente cria um tarball** — se `--tarball` for passado, executa `npm pack` para criar um arquivo `.tgz` pronto para distribuição.
|
||||
|
||||
A saída da compilação em `.twenty/output/` contém:
|
||||
|
||||
```text
|
||||
.twenty/output/
|
||||
├── manifest.json # Manifesto com somas de verificação para todos os arquivos compilados
|
||||
├── package.json # Copiado da raiz do aplicativo
|
||||
├── yarn.lock # Copiado da raiz do aplicativo
|
||||
├── src/
|
||||
│ ├── logic-functions/ # Arquivos .mjs compilados de funções de lógica
|
||||
│ └── front-components/ # Arquivos .mjs compilados de componentes de front-end
|
||||
├── public/ # Recursos estáticos (se houver)
|
||||
└── my-app-1.0.0.tgz # Apenas com a opção --tarball
|
||||
```
|
||||
|
||||
| Opção | Descrição |
|
||||
| ----------- | --------------------------------------------------------- |
|
||||
| `[appPath]` | Caminho para o diretório do app (padrão: diretório atual) |
|
||||
| `--tarball` | Também empacota a saída em um tarball `.tgz` |
|
||||
|
||||
## Publicando seu app
|
||||
|
||||
Use `app:publish` para distribuir seu app — ou para o registro do npm ou diretamente para um servidor Twenty.
|
||||
|
||||
### Publicar no npm (padrão)
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Publish to npm (requires npm login)
|
||||
yarn twenty app:publish
|
||||
|
||||
# Publish with a dist-tag (e.g. beta, next)
|
||||
yarn twenty app:publish --tag beta
|
||||
```
|
||||
|
||||
Isso compila o app e executa `npm publish` a partir do diretório `.twenty/output/`. O pacote publicado pode então ser instalado no marketplace da Twenty por qualquer espaço de trabalho.
|
||||
|
||||
### Publicar em um servidor Twenty
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Publish directly to a Twenty server
|
||||
yarn twenty app:publish --server https://app.twenty.com
|
||||
```
|
||||
|
||||
Isso compila o app com um tarball, faz o upload para o servidor via a mutação GraphQL `uploadAppTarball` e aciona a instalação em uma única etapa. Isso é útil para implantações privadas ou para testar em um servidor específico.
|
||||
|
||||
| Opção | Descrição |
|
||||
| ----------------- | --------------------------------------------------------------------- |
|
||||
| `[appPath]` | Caminho para o diretório do app (padrão: diretório atual) |
|
||||
| `--server <url>` | Publicar em um servidor Twenty em vez de no npm |
|
||||
| `--token <token>` | Token de autenticação para o servidor de destino |
|
||||
| `--tag <tag>` | dist-tag do npm (ex.: `beta`, `next`) — apenas para publicação no npm |
|
||||
|
||||
## Registro de aplicação
|
||||
|
||||
Antes que um app possa ser instalado em um espaço de trabalho, ele precisa ser **registrado**. Um registro é um registro de metadados que descreve de onde o app vem e como autenticá-lo. Isso é tratado automaticamente pela CLI na maioria dos casos.
|
||||
|
||||
### Tipos de origem
|
||||
|
||||
Cada registro tem um **tipo de origem** que determina como os arquivos do app são resolvidos durante a instalação:
|
||||
|
||||
| Tipo de origem | Como os arquivos são resolvidos | Caso de uso típico |
|
||||
| -------------- | ------------------------------------------------------------------------------------------- | --------------------------------------- |
|
||||
| `LOCAL` | Os arquivos são sincronizados em tempo real pelo observador da CLI — a instalação é omitida | Desenvolvimento com `app:dev` |
|
||||
| `NPM` | Obtidos do registro npm por meio do campo `sourcePackage` | Apps publicados no npm |
|
||||
| `TARBALL` | Extraídos de um arquivo `.tgz` enviado e armazenado no servidor | Apps privados publicados com `--server` |
|
||||
|
||||
### Como o registro acontece
|
||||
|
||||
* **`app:dev`** — cria automaticamente um registro `LOCAL` na primeira vez que você executa o modo de desenvolvimento em um espaço de trabalho.
|
||||
* **`app:publish --server`** — faz o upload de um tarball e cria (ou atualiza) um registro `TARBALL`, e em seguida instala o app.
|
||||
* **marketplace do npm** — registros `NPM` são criados quando apps são sincronizados do registro npm para o catálogo do marketplace da Twenty.
|
||||
* **API GraphQL** — você também pode criar registros programaticamente por meio da mutação `createApplicationRegistration`.
|
||||
|
||||
### Registro vs instalação
|
||||
|
||||
**Registro** e **instalação** são conceitos distintos:
|
||||
|
||||
* Um **registro** (`ApplicationRegistration`) é um registro global de metadados que descreve o app: seu nome, tipo de origem, credenciais OAuth e status de listagem no marketplace. Ele existe independentemente de qualquer espaço de trabalho.
|
||||
* Uma **instalação** (`Application`) é uma instância por espaço de trabalho. Quando um usuário instala um app, a Twenty resolve o pacote a partir da origem do registro, grava os arquivos compilados no armazenamento e sincroniza o manifesto (criando objetos, campos, funções de lógica etc.). naquele espaço de trabalho.
|
||||
|
||||
Um registro pode ser instalado em muitos espaços de trabalho. Cada espaço de trabalho recebe sua própria cópia dos arquivos e do modelo de dados do app.
|
||||
|
||||
### Credenciais OAuth
|
||||
|
||||
Cada registro inclui credenciais OAuth (`oAuthClientId` e `oAuthClientSecret`) geradas no momento da criação. Elas são usadas pelo app para autenticar requisições de API em nome dos usuários. O segredo do cliente é retornado **uma única vez** na criação — armazene-o com segurança. Você pode rotacioná-lo posteriormente por meio da mutação `rotateApplicationRegistrationClientSecret`.
|
||||
|
||||
## 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:
|
||||
|
||||
@@ -3,7 +3,7 @@ title: 1-Clique c/ Docker Compose
|
||||
---
|
||||
|
||||
<Warning>
|
||||
Contêineres Docker são para hospedagem de produção ou auto-hospedagem, para contribuições, por favor, verifique o [Setup Local](/l/pt/developers/contribute/capabilities/local-setup).
|
||||
Docker containers are for production hosting or self-hosting. For contributing, please check the [Local Setup](/l/pt/developers/contribute/capabilities/local-setup).
|
||||
</Warning>
|
||||
|
||||
## Visão geral
|
||||
@@ -12,7 +12,7 @@ Este guia fornece instruções passo a passo para instalar e configurar o aplica
|
||||
|
||||
**Importante:** Modifique apenas as configurações explicitamente mencionadas neste guia. Alterar outras configurações pode levar a problemas.
|
||||
|
||||
Veja a documentação [Configurar Variáveis de Ambiente](/l/pt/developers/self-host/capabilities/setup) para configuração avançada. Todas as variáveis de ambiente devem ser declaradas no arquivo docker-compose.yml no nível do servidor e/ou trabalhador, dependendo da variável.
|
||||
See [Setup Environment Variables](/l/pt/developers/self-host/capabilities/setup) for advanced configuration. All environment variables must be declared in the `docker-compose.yml` file at the server and/or worker level, depending on the variable.
|
||||
|
||||
## Requisitos do Sistema
|
||||
|
||||
|
||||
@@ -297,46 +297,60 @@ yarn command:prod cron:workflow:automated-cron-trigger
|
||||
**Modo somente ambiente:** Se você definir `IS_CONFIG_VARIABLES_IN_DB_ENABLED=false`, adicione estas variáveis ao seu arquivo `.env`.
|
||||
</Warning>
|
||||
|
||||
## Funções lógicas
|
||||
## Funções lógicas e interpretador de código
|
||||
|
||||
O Twenty oferece suporte a funções lógicas para fluxos de trabalho e lógica personalizada. O ambiente de execução é configurado por meio da variável de ambiente `SERVERLESS_TYPE`.
|
||||
O Twenty oferece suporte a funções lógicas para fluxos de trabalho e ao interpretador de código para análise de dados com IA. Ambos executam código fornecido pelo usuário e exigem configuração explícita por motivos de segurança.
|
||||
|
||||
### Padrões de segurança
|
||||
|
||||
**Em produção (NODE_ENV=production):** Tanto as funções lógicas quanto o interpretador de código têm como padrão **Desativado**. Você deve habilitá-los explicitamente com `LOGIC_FUNCTION_TYPE` e `CODE_INTERPRETER_TYPE` se precisar desses recursos.
|
||||
|
||||
**Em desenvolvimento (NODE_ENV=development):** Ambos têm como padrão **LOCAL** por conveniência ao executar localmente.
|
||||
|
||||
<Warning>
|
||||
**Aviso de segurança:** O driver local (`SERVERLESS_TYPE=LOCAL`) executa código diretamente no host em um processo Node.js sem sandbox. Deve ser usado apenas para código confiável em desenvolvimento. Para implantações de produção que lidam com código não confiável, recomendamos fortemente usar `SERVERLESS_TYPE=LAMBDA` ou `SERVERLESS_TYPE=DISABLED`.
|
||||
**Aviso de segurança:** O driver local (`LOGIC_FUNCTION_TYPE=LOCAL` ou `CODE_INTERPRETER_TYPE=LOCAL`) executa código diretamente no host em um processo Node.js sem sandbox. Deve ser usado apenas para código confiável em desenvolvimento. Para implantações de produção que lidam com código não confiável, use `LOGIC_FUNCTION_TYPE=LAMBDA` ou `CODE_INTERPRETER_TYPE=E2B` (com sandbox), ou mantenha-os desativados.
|
||||
</Warning>
|
||||
|
||||
### Drivers disponíveis
|
||||
### Funções lógicas - Drivers disponíveis
|
||||
|
||||
| Driver | Variável de ambiente | Caso de uso | Nível de segurança |
|
||||
| ---------- | -------------------------- | ------------------------------------------ | -------------------------------------- |
|
||||
| Desativado | `SERVERLESS_TYPE=DISABLED` | Desativar completamente as funções lógicas | N/A |
|
||||
| Local | `SERVERLESS_TYPE=LOCAL` | Desenvolvimento e ambientes confiáveis | Baixo (sem sandbox) |
|
||||
| Lambda | `SERVERLESS_TYPE=LAMBDA` | Produção com código não confiável | Alto (isolamento em nível de hardware) |
|
||||
| Driver | Variável de ambiente | Caso de uso | Nível de segurança |
|
||||
| ---------- | ------------------------------ | ------------------------------------------ | -------------------------------------- |
|
||||
| Desativado | `LOGIC_FUNCTION_TYPE=DISABLED` | Desativar completamente as funções lógicas | N/A |
|
||||
| Local | `LOGIC_FUNCTION_TYPE=LOCAL` | Desenvolvimento e ambientes confiáveis | Baixo (sem sandbox) |
|
||||
| Lambda | `LOGIC_FUNCTION_TYPE=LAMBDA` | Produção com código não confiável | Alto (isolamento em nível de hardware) |
|
||||
|
||||
### Configuração recomendada
|
||||
### Funções lógicas - Configuração recomendada
|
||||
|
||||
**Para desenvolvimento:**
|
||||
|
||||
```bash
|
||||
SERVERLESS_TYPE=LOCAL # default
|
||||
LOGIC_FUNCTION_TYPE=LOCAL # default when NODE_ENV=development
|
||||
```
|
||||
|
||||
**Para produção (AWS):**
|
||||
|
||||
```bash
|
||||
SERVERLESS_TYPE=LAMBDA
|
||||
SERVERLESS_LAMBDA_REGION=us-east-1
|
||||
SERVERLESS_LAMBDA_ROLE=arn:aws:iam::123456789:role/your-lambda-role
|
||||
SERVERLESS_LAMBDA_ACCESS_KEY_ID=your-access-key
|
||||
SERVERLESS_LAMBDA_SECRET_ACCESS_KEY=your-secret-key
|
||||
LOGIC_FUNCTION_TYPE=LAMBDA
|
||||
LOGIC_FUNCTION_LAMBDA_REGION=us-east-1
|
||||
LOGIC_FUNCTION_LAMBDA_ROLE=arn:aws:iam::123456789:role/your-lambda-role
|
||||
LOGIC_FUNCTION_LAMBDA_ACCESS_KEY_ID=your-access-key
|
||||
LOGIC_FUNCTION_LAMBDA_SECRET_ACCESS_KEY=your-secret-key
|
||||
```
|
||||
|
||||
**Para desativar as funções lógicas:**
|
||||
|
||||
```bash
|
||||
SERVERLESS_TYPE=DISABLED
|
||||
LOGIC_FUNCTION_TYPE=DISABLED # default when NODE_ENV=production
|
||||
```
|
||||
|
||||
### Interpretador de código - Drivers disponíveis
|
||||
|
||||
| Driver | Variável de ambiente | Caso de uso | Nível de segurança |
|
||||
| ---------- | -------------------------------- | ------------------------------------ | ---------------------- |
|
||||
| Desativado | `CODE_INTERPRETER_TYPE=DISABLED` | Desativar a execução de código de IA | N/A |
|
||||
| Local | `CODE_INTERPRETER_TYPE=LOCAL` | Apenas para desenvolvimento | Baixo (sem sandbox) |
|
||||
| E2B | `CODE_INTERPRETER_TYPE=E_2_B` | Produção com execução em sandbox | Alto (sandbox isolado) |
|
||||
|
||||
<Note>
|
||||
Ao usar `SERVERLESS_TYPE=DISABLED`, qualquer tentativa de executar uma função lógica retornará um erro. Isso é útil se você quiser executar o Twenty sem recursos de funções lógicas.
|
||||
Ao usar `LOGIC_FUNCTION_TYPE=DISABLED` ou `CODE_INTERPRETER_TYPE=DISABLED`, qualquer tentativa de execução retornará um erro. Isso é útil se você quiser executar o Twenty sem esses recursos.
|
||||
</Note>
|
||||
|
||||
+2
-2
@@ -8,7 +8,7 @@ Scopul aici este de a avea o bază de cod coerentă, ușor de citit și ușor de
|
||||
|
||||
Pentru aceasta, este mai bine să fie mai detaliat decât prea concis.
|
||||
|
||||
Ține mereu minte că oamenii citesc codul mai des decât îl scriu, mai ales într-un proiect open-source, unde oricine poate contribui.
|
||||
Always keep in mind that people read code more often than they write it, especially on an open source project, where anyone can contribute.
|
||||
|
||||
Există multe reguli care nu sunt definite aici, dar care sunt verificate automat de linters.
|
||||
|
||||
@@ -150,7 +150,7 @@ type MyType = {
|
||||
|
||||
### Folosește litere de șir în loc de enum
|
||||
|
||||
[Literele de șir](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types) sunt metoda standard pentru manipularea valorilor similare cu enum în TypeScript. Sunt mai ușor de extins cu Pick și Omit, oferind o experiență mai bună dezvoltatorilor, mai ales cu completarea codului.
|
||||
[Literele de șir](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types) sunt metoda standard pentru manipularea valorilor similare cu enum în TypeScript. They are easier to extend with Pick and Omit, and offer a better developer experience, especially with code completion.
|
||||
|
||||
Poți vedea de ce TypeScript recomandă evitarea enumurilor [aici](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#enums).
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ description: Ghidul pentru contribuitori (sau dezvoltatori curioși) care doresc
|
||||
## Cerințe
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Linux și MacOS">
|
||||
<Tab title="Linux și macOS">
|
||||
|
||||
Înainte de a instala și utiliza Twenty, asigurați-vă că instalați următoarele pe computerul dvs.:
|
||||
* [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
|
||||
@@ -129,8 +129,8 @@ Trebuie să rulați toate comenzile în pașii următori de la rădăcina proiec
|
||||
brew services list
|
||||
```
|
||||
|
||||
Instalatorul s-ar putea să nu creeze implicit utilizatorul `postgres` atunci când instalați
|
||||
prin Homebrew pe MacOS. În schimb, creează un rol PostgreSQL care se potrivește cu numele de utilizator al
|
||||
Instalatorul s-ar putea să nu creeze implicit utilizatorul `postgres` la instalarea
|
||||
prin Homebrew pe macOS. În schimb, creează un rol PostgreSQL care se potrivește cu numele de utilizator al
|
||||
macOS-ului dvs. (de ex., "john").
|
||||
Pentru a verifica și crea utilizatorul `postgres` dacă este necesar, urmați acești pași:
|
||||
```bash
|
||||
@@ -189,11 +189,13 @@ Trebuie să rulați toate comenzile în pașii următori de la rădăcina proiec
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
Acum puteți accesa baza de date la [localhost:5432](localhost:5432), cu utilizator `postgres` și parolă `postgres`.
|
||||
You can now access the database at `localhost:5432`.
|
||||
|
||||
If you used the Docker option above, the default credentials are user `postgres` and password `postgres`. For native PostgreSQL installations, use the credentials and roles configured on your machine.
|
||||
|
||||
## Pasul 4: Configurați o bază de date Redis (cache)
|
||||
|
||||
Twenty necesită un cache Redis pentru a oferi cea mai bună performanță
|
||||
Twenty requires a Redis cache to provide the best performance.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Linux">
|
||||
@@ -210,8 +212,10 @@ Twenty necesită un cache Redis pentru a oferi cea mai bună performanță
|
||||
```bash
|
||||
brew install redis
|
||||
```
|
||||
Porniți serverul Redis:
|
||||
`brew services start redis`
|
||||
Start your Redis server:
|
||||
```bash
|
||||
brew services start redis
|
||||
```
|
||||
|
||||
**Opțiunea 2:** Dacă aveți docker instalat:
|
||||
```bash
|
||||
@@ -229,11 +233,11 @@ Twenty necesită un cache Redis pentru a oferi cea mai bună performanță
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
Dacă aveți nevoie de o interfață grafică pentru client, vă recomandăm [Redis Insight](https://redis.io/insight/) (versiune gratuită disponibilă)
|
||||
If you need a client GUI, we recommend [Redis Insight](https://redis.io/insight/) (free version available).
|
||||
|
||||
## Pasul 5: Configurați variabilele de mediu
|
||||
## Step 5: Set up environment variables
|
||||
|
||||
Utilizați variabile de mediu sau fișiere `.env` pentru a configura proiectul dvs. Mai multe informații [aici](/l/ro/developers/self-host/capabilities/setup)
|
||||
Utilizați variabile de mediu sau fișiere `.env` pentru a configura proiectul dvs. Mai multe informații [aici](/l/ro/developers/self-host/capabilities/setup).
|
||||
|
||||
Copiați fișierele `.env.example` din `/front` și `/server`:
|
||||
|
||||
|
||||
@@ -49,26 +49,32 @@ npx create-twenty-app@latest my-app --minimal
|
||||
De aici puteți:
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Adaugă o entitate nouă în aplicația ta (ghidat)
|
||||
# Add a new entity to your application (guided)
|
||||
yarn twenty entity:add
|
||||
|
||||
# Urmărește jurnalele funcțiilor aplicației tale
|
||||
# Watch your application's function logs
|
||||
yarn twenty function:logs
|
||||
|
||||
# Execută o funcție după nume
|
||||
# Execute a function by name
|
||||
yarn twenty function:execute -n my-function -p '{"name": "test"}'
|
||||
|
||||
# Execută funcția de pre-instalare
|
||||
# Execute the pre-install function
|
||||
yarn twenty function:execute --preInstall
|
||||
|
||||
# Execută funcția post-instalare
|
||||
# Execute the post-install function
|
||||
yarn twenty function:execute --postInstall
|
||||
|
||||
# Dezinstalează aplicația din spațiul de lucru curent
|
||||
# Build the app for distribution
|
||||
yarn twenty app:build
|
||||
|
||||
# Publish the app to npm or a Twenty server
|
||||
yarn twenty app:publish
|
||||
|
||||
# Uninstall the application from the current workspace
|
||||
yarn twenty app:uninstall
|
||||
|
||||
# Afișează ajutorul pentru comenzi
|
||||
yarn twenty help},{
|
||||
# Display commands' help
|
||||
yarn twenty help
|
||||
```
|
||||
|
||||
Consultați și: paginile de referință CLI pentru [create-twenty-app](https://www.npmjs.com/package/create-twenty-app) și [twenty-sdk CLI](https://www.npmjs.com/package/twenty-sdk).
|
||||
@@ -1240,6 +1246,113 @@ Puncte cheie:
|
||||
|
||||
Explorați un exemplu minim, cap la cap, care demonstrează obiecte, funcții de logică, componente Front și declanșatoare multiple [aici](https://github.com/twentyhq/twenty/tree/main/packages/twenty-apps/hello-world):
|
||||
|
||||
## Building your app
|
||||
|
||||
Once you've developed your app with `app:dev`, use `app:build` to compile it into a distributable package.
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Build the app (output goes to .twenty/output/)
|
||||
yarn twenty app:build
|
||||
|
||||
# Build and create a tarball (.tgz) for distribution
|
||||
yarn twenty app:build --tarball
|
||||
```
|
||||
|
||||
The build process:
|
||||
|
||||
1. **Parses and validates the manifest** — reads all `defineX()` entities from your source files and validates the manifest structure.
|
||||
2. **Compiles logic functions and front components** — bundles TypeScript sources into ESM `.mjs` files using esbuild.
|
||||
3. **Generates checksums** — computes MD5 hashes for each built file, stored in the manifest as `builtHandlerChecksum` / `builtComponentChecksum`.
|
||||
4. **Generează clientul API tipizat** — examinează schema GraphQL și generează clienți tipizați `CoreApiClient` și `MetadataApiClient`.
|
||||
5. **Rulează o verificare a tipurilor TypeScript** — rulează `tsc --noEmit` pentru a detecta erorile de tip înainte de publicare.
|
||||
6. **Reconstruiește cu clientul generat** — efectuează o a doua trecere de compilare astfel încât tipurile clientului generat să fie incluse.
|
||||
7. **Creează opțional un tarball** — dacă se trece `--tarball`, rulează `npm pack` pentru a crea un fișier `.tgz` gata pentru distribuire.
|
||||
|
||||
Rezultatul build-ului din `.twenty/output/` conține:
|
||||
|
||||
```text
|
||||
.twenty/output/
|
||||
├── manifest.json # Manifest cu sume de control pentru toate fișierele generate
|
||||
├── package.json # Copiat din rădăcina aplicației
|
||||
├── yarn.lock # Copiat din rădăcina aplicației
|
||||
├── src/
|
||||
│ ├── logic-functions/ # Fișiere .mjs de funcții de logică compilate
|
||||
│ └── front-components/ # Fișiere .mjs de componente front-end compilate
|
||||
├── public/ # Resurse statice (dacă există)
|
||||
└── my-app-1.0.0.tgz # Doar cu opțiunea --tarball
|
||||
```
|
||||
|
||||
| Opțiune | Descriere |
|
||||
| ----------- | -------------------------------------------------------------- |
|
||||
| `[appPath]` | Calea către directorul aplicației (implicit directorul curent) |
|
||||
| `--tarball` | De asemenea, împachetează rezultatul într-un tarball `.tgz` |
|
||||
|
||||
## Publicarea aplicației
|
||||
|
||||
Folosește `app:publish` pentru a distribui aplicația — fie în registrul npm, fie direct pe un server Twenty.
|
||||
|
||||
### Publicare pe npm (implicit)
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Publicare pe npm (necesită autentificare npm)
|
||||
yarn twenty app:publish
|
||||
|
||||
# Publicare cu un dist-tag (de ex. beta, next)
|
||||
yarn twenty app:publish --tag beta
|
||||
```
|
||||
|
||||
Aceasta construiește aplicația și rulează `npm publish` din directorul `.twenty/output/`. Pachetul publicat poate fi apoi instalat din marketplace-ul Twenty de către orice spațiu de lucru.
|
||||
|
||||
### Publicare pe un server Twenty
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Publicare direct pe un server Twenty
|
||||
yarn twenty app:publish --server https://app.twenty.com
|
||||
```
|
||||
|
||||
Aceasta construiește aplicația cu un tarball, o încarcă pe server prin mutația GraphQL `uploadAppTarball` și declanșează instalarea într-un singur pas. Acest lucru este util pentru implementări private sau pentru testare pe un server specific.
|
||||
|
||||
| Opțiune | Descriere |
|
||||
| ----------------- | -------------------------------------------------------------------- |
|
||||
| `[appPath]` | Calea către directorul aplicației (implicit directorul curent) |
|
||||
| `--server <url>` | Publică pe un server Twenty în loc de npm |
|
||||
| `--token <token>` | Jeton de autentificare pentru serverul țintă |
|
||||
| `--tag <tag>` | npm dist-tag (de ex. `beta`, `next`) — doar pentru publicarea pe npm |
|
||||
|
||||
## Înregistrarea aplicației
|
||||
|
||||
Înainte ca o aplicație să poată fi instalată într-un spațiu de lucru, aceasta trebuie să fie **înregistrată**. O înregistrare este o înregistrare de metadate care descrie de unde provine aplicația și cum se autentifică. Acest lucru este gestionat automat de CLI în cele mai multe cazuri.
|
||||
|
||||
### Tipuri de sursă
|
||||
|
||||
Fiecare înregistrare are un **tip de sursă** care determină modul în care fișierele aplicației sunt preluate în timpul instalării:
|
||||
|
||||
| Tip de sursă | Cum sunt preluate fișierele | Caz de utilizare tipic |
|
||||
| ------------ | ---------------------------------------------------------------------------------------- | ----------------------------------------- |
|
||||
| `LOCAL` | Fișierele sunt sincronizate în timp real de către watcher-ul CLI — instalarea este omisă | Dezvoltare cu `app:dev` |
|
||||
| `NPM` | Obținute din registrul npm prin câmpul `sourcePackage` | Aplicații publicate pe npm |
|
||||
| `TARBALL` | Extrase dintr-un fișier `.tgz` încărcat, stocat pe server | Aplicații private publicate cu `--server` |
|
||||
|
||||
### Cum are loc înregistrarea
|
||||
|
||||
* **`app:dev`** — creează automat o înregistrare `LOCAL` prima dată când rulezi modul de dezvoltare pentru un spațiu de lucru.
|
||||
* **`app:publish --server`** — încarcă un tarball și creează (sau actualizează) o înregistrare `TARBALL`, apoi instalează aplicația.
|
||||
* **marketplace-ul npm** — înregistrările `NPM` sunt create când aplicațiile sunt sincronizate din registrul npm în catalogul marketplace-ului Twenty.
|
||||
* **API GraphQL** — poți de asemenea să creezi înregistrări programatic prin mutația `createApplicationRegistration`.
|
||||
|
||||
### Înregistrare vs instalare
|
||||
|
||||
**Înregistrarea** și **instalarea** sunt concepte separate:
|
||||
|
||||
* O **înregistrare** (`ApplicationRegistration`) este o înregistrare globală de metadate care descrie aplicația: numele ei, tipul de sursă, acreditările OAuth și statutul listării în marketplace. Există independent de orice spațiu de lucru.
|
||||
* O **instalare** (`Application`) este o instanță per spațiu de lucru. Când un utilizator instalează o aplicație, Twenty rezolvă pachetul din sursa înregistrării, scrie fișierele compilate în stocare și sincronizează manifestul (creând obiecte, câmpuri, funcții de logică etc.) în acel spațiu de lucru.
|
||||
|
||||
O singură înregistrare poate fi instalată în multe spații de lucru. Fiecare spațiu de lucru primește propria copie a fișierelor și a modelului de date al aplicației.
|
||||
|
||||
### Acreditări OAuth
|
||||
|
||||
Fiecare înregistrare include acreditări OAuth (`oAuthClientId` și `oAuthClientSecret`) generate la momentul creării. Acestea sunt folosite de aplicație pentru a autentifica cererile API în numele utilizatorilor. Secretul clientului este returnat **o singură dată** la creare — păstrează-l în siguranță. Îl poți roti ulterior prin mutația `rotateApplicationRegistrationClientSecret`.
|
||||
|
||||
## Configurare manuală (fără generator)
|
||||
|
||||
Deși recomandăm utilizarea `create-twenty-app` pentru cea mai bună experiență de început, puteți configura și un proiect manual. Nu instalați CLI-ul global. În schimb, adăugați `twenty-sdk` ca dependență locală și conectați un singur script în package.json-ul dvs.:
|
||||
|
||||
@@ -3,7 +3,7 @@ title: 1-Click cu Docker Compose
|
||||
---
|
||||
|
||||
<Warning>
|
||||
Containerele Docker sunt pentru găzduire în producție sau auto-găzduire; pentru a contribui, consultați [Configurare locală](/l/ro/developers/contribute/capabilities/local-setup).
|
||||
Docker containers are for production hosting or self-hosting. For contributing, please check the [Local Setup](/l/ro/developers/contribute/capabilities/local-setup).
|
||||
</Warning>
|
||||
|
||||
## Prezentare generală
|
||||
@@ -12,7 +12,7 @@ Acest ghid oferă instrucțiuni pas cu pas pentru a instala și configura aplica
|
||||
|
||||
**Important:** Modificați numai setările menționate explicit în acest ghid. Modificarea altor configurații poate duce la probleme.
|
||||
|
||||
Consultați documentația [Setup Environment Variables](/l/ro/developers/self-host/capabilities/setup) pentru configurare avansată. Toate variabilele de mediu trebuie declarate în fișierul docker-compose.yml la nivel de server și/sau de lucru, în funcție de variabilă.
|
||||
See [Setup Environment Variables](/l/ro/developers/self-host/capabilities/setup) for advanced configuration. All environment variables must be declared in the `docker-compose.yml` file at the server and/or worker level, depending on the variable.
|
||||
|
||||
## Cerințe de Sistem
|
||||
|
||||
|
||||
@@ -297,46 +297,60 @@ yarn command:prod cron:workflow:automated-cron-trigger
|
||||
**Mod doar pentru mediu:** Dacă setați `IS_CONFIG_VARIABLES_IN_DB_ENABLED=false`, adăugați aceste variabile în fișierul dvs. `.env` în schimb.
|
||||
</Warning>
|
||||
|
||||
## Funcții logice
|
||||
## Funcții logice și interpretor de cod
|
||||
|
||||
Twenty acceptă funcții logice pentru fluxuri de lucru și logică personalizată. Mediul de execuție este configurat prin variabila de mediu `SERVERLESS_TYPE`.
|
||||
Twenty acceptă funcții logice pentru fluxuri de lucru și interpretorul de cod pentru analiza datelor cu AI. Ambele rulează cod furnizat de utilizator și necesită o configurare explicită din motive de securitate.
|
||||
|
||||
### Valori implicite de securitate
|
||||
|
||||
**În producție (NODE_ENV=production):** Atât funcțiile logice, cât și interpretorul de cod au implicit valoarea **Dezactivat**. Trebuie să le activezi explicit cu `LOGIC_FUNCTION_TYPE` și `CODE_INTERPRETER_TYPE` dacă ai nevoie de aceste funcționalități.
|
||||
|
||||
**În dezvoltare (NODE_ENV=development):** Ambele au implicit valoarea **LOCAL** pentru comoditate când rulezi local.
|
||||
|
||||
<Warning>
|
||||
**Atenționare de securitate:** Driverul local (`SERVERLESS_TYPE=LOCAL`) rulează codul direct pe gazdă într-un proces Node.js, fără sandboxing. Ar trebui utilizat doar pentru cod de încredere, în dezvoltare. Pentru implementări de producție care gestionează cod neverificat, recomandăm cu tărie utilizarea `SERVERLESS_TYPE=LAMBDA` sau `SERVERLESS_TYPE=DISABLED`.
|
||||
**Atenționare de securitate:** Driverul local (`LOGIC_FUNCTION_TYPE=LOCAL` sau `CODE_INTERPRETER_TYPE=LOCAL`) rulează codul direct pe gazdă într-un proces Node.js, fără sandboxing. Ar trebui utilizat doar pentru cod de încredere, în dezvoltare. Pentru implementări în producție care gestionează cod neverificat, folosiți `LOGIC_FUNCTION_TYPE=LAMBDA` sau `CODE_INTERPRETER_TYPE=E2B` (cu sandboxing) ori păstrați-le dezactivate.
|
||||
</Warning>
|
||||
|
||||
### Drivere disponibile
|
||||
### Funcții logice - Drivere disponibile
|
||||
|
||||
| Driver | Variabilă de mediu | Caz de utilizare | Nivel de securitate |
|
||||
| ---------- | -------------------------- | ------------------------------------- | -------------------------------------- |
|
||||
| Dezactivat | `SERVERLESS_TYPE=DISABLED` | Dezactivează complet funcțiile logice | N/A |
|
||||
| Local | `SERVERLESS_TYPE=LOCAL` | Dezvoltare și medii de încredere | Scăzut (fără sandboxing) |
|
||||
| Lambda | `SERVERLESS_TYPE=LAMBDA` | Producție cu cod neverificat | Ridicat (izolare la nivel de hardware) |
|
||||
| Driver | Variabilă de mediu | Caz de utilizare | Nivel de securitate |
|
||||
| ---------- | ------------------------------ | ------------------------------------- | -------------------------------------- |
|
||||
| Dezactivat | `LOGIC_FUNCTION_TYPE=DISABLED` | Dezactivează complet funcțiile logice | N/A |
|
||||
| Local | `LOGIC_FUNCTION_TYPE=LOCAL` | Dezvoltare și medii de încredere | Scăzut (fără sandboxing) |
|
||||
| Lambda | `LOGIC_FUNCTION_TYPE=LAMBDA` | Producție cu cod neverificat | Ridicat (izolare la nivel de hardware) |
|
||||
|
||||
### Configurație recomandată
|
||||
### Funcții logice - Configurare recomandată
|
||||
|
||||
**Pentru dezvoltare:**
|
||||
|
||||
```bash
|
||||
SERVERLESS_TYPE=LOCAL # default
|
||||
LOGIC_FUNCTION_TYPE=LOCAL # default when NODE_ENV=development
|
||||
```
|
||||
|
||||
**Pentru producție (AWS):**
|
||||
|
||||
```bash
|
||||
SERVERLESS_TYPE=LAMBDA
|
||||
SERVERLESS_LAMBDA_REGION=us-east-1
|
||||
SERVERLESS_LAMBDA_ROLE=arn:aws:iam::123456789:role/your-lambda-role
|
||||
SERVERLESS_LAMBDA_ACCESS_KEY_ID=your-access-key
|
||||
SERVERLESS_LAMBDA_SECRET_ACCESS_KEY=your-secret-key
|
||||
LOGIC_FUNCTION_TYPE=LAMBDA
|
||||
LOGIC_FUNCTION_LAMBDA_REGION=us-east-1
|
||||
LOGIC_FUNCTION_LAMBDA_ROLE=arn:aws:iam::123456789:role/your-lambda-role
|
||||
LOGIC_FUNCTION_LAMBDA_ACCESS_KEY_ID=your-access-key
|
||||
LOGIC_FUNCTION_LAMBDA_SECRET_ACCESS_KEY=your-secret-key
|
||||
```
|
||||
|
||||
**Pentru a dezactiva funcțiile logice:**
|
||||
|
||||
```bash
|
||||
SERVERLESS_TYPE=DISABLED
|
||||
LOGIC_FUNCTION_TYPE=DISABLED # default when NODE_ENV=production
|
||||
```
|
||||
|
||||
### Interpretor de cod - Drivere disponibile
|
||||
|
||||
| Driver | Variabilă de mediu | Caz de utilizare | Nivel de securitate |
|
||||
| ---------- | -------------------------------- | ---------------------------------------- | ------------------------ |
|
||||
| Dezactivat | `CODE_INTERPRETER_TYPE=DISABLED` | Dezactivați execuția codului de către AI | N/A |
|
||||
| Local | `CODE_INTERPRETER_TYPE=LOCAL` | Doar pentru dezvoltare | Scăzut (fără sandboxing) |
|
||||
| E2B | `CODE_INTERPRETER_TYPE=E_2_B` | Producție cu execuție în sandbox | Ridicat (sandbox izolat) |
|
||||
|
||||
<Note>
|
||||
Când se utilizează `SERVERLESS_TYPE=DISABLED`, orice încercare de a executa o funcție logică va returna o eroare. Acest lucru este util dacă doriți să rulați Twenty fără capabilități de funcții logice.
|
||||
Când utilizați `LOGIC_FUNCTION_TYPE=DISABLED` sau `CODE_INTERPRETER_TYPE=DISABLED`, orice încercare de execuție va returna o eroare. Acest lucru este util dacă doriți să rulați Twenty fără aceste capabilități.
|
||||
</Note>
|
||||
|
||||
+2
-2
@@ -8,7 +8,7 @@ title: Руководство по стилю
|
||||
|
||||
Для этого лучше быть немного более многословными, чем слишком краткими.
|
||||
|
||||
Всегда держите в голове, что код читают чаще, чем пишут, особенно в проекте с открытым исходным кодом, где к нему может присоединиться кто угодно.
|
||||
Always keep in mind that people read code more often than they write it, especially on an open source project, where anyone can contribute.
|
||||
|
||||
Существует много правил, которые здесь не описаны, но автоматически проверяются линтерами.
|
||||
|
||||
@@ -150,7 +150,7 @@ type MyType = {
|
||||
|
||||
### Используйте строковые литералы вместо перечислений.
|
||||
|
||||
[Строковые литералы](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types) - это основной способ обработки значений, напоминающих перечисление, в TypeScript. Они легче расширяются с помощью Pick и Omit и обеспечивают лучшее взаимодействие с разработчиком, особенно с автозаполнением кода.
|
||||
[Строковые литералы](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types) - это основной способ обработки значений, напоминающих перечисление, в TypeScript. They are easier to extend with Pick and Omit, and offer a better developer experience, especially with code completion.
|
||||
|
||||
Вы можете увидеть, почему TypeScript рекомендует избегать перечислений [здесь](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#enums).
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ description: Руководство для участников (или любо
|
||||
## Требования
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Linux и MacOS">
|
||||
<Tab title="Linux and macOS">
|
||||
|
||||
Прежде чем установить и использовать Twenty, убедитесь, что у вас установлено следующее:
|
||||
* [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
|
||||
@@ -30,7 +30,7 @@ wsl --install
|
||||
```
|
||||
Теперь должно появиться приглашение на перезагрузку компьютера. Если нет, перезагрузите его вручную.
|
||||
|
||||
После перезагрузки откроется окно PowerShell и установит Ubuntu. Это может занять некоторое время.
|
||||
Upon restart, a PowerShell window will open and install Ubuntu. Это может занять некоторое время.
|
||||
Появится запрос на создание имени пользователя и пароля для вашей установки Ubuntu.
|
||||
|
||||
2. Установите и настройте git
|
||||
@@ -102,8 +102,8 @@ cd twenty
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Linux">
|
||||
**Опция 1 (предпочтительно):** Чтобы настроить вашу базу данных локально:
|
||||
Используйте следующую ссылку для установки Postgresql на вашу Linux машину: [Установка Postgresql](https://www.postgresql.org/download/linux/)
|
||||
**Option 1 (preferred):** To provision your database locally:
|
||||
Use the following link to install PostgreSQL on your Linux machine: [PostgreSQL Installation](https://www.postgresql.org/download/linux/)
|
||||
```bash
|
||||
psql postgres -c "CREATE DATABASE \"default\";" -c "CREATE DATABASE test;"
|
||||
```
|
||||
@@ -129,8 +129,8 @@ cd twenty
|
||||
brew services list
|
||||
```
|
||||
|
||||
Установщик может не создать пользователя `postgres` по умолчанию при установке
|
||||
через Homebrew на MacOS. Вместо этого он создает роль PostgreSQL, которая совпадает с вашим именем пользователя в MacOS
|
||||
The installer might not create the `postgres` user by default when installing
|
||||
via Homebrew on macOS. Вместо этого он создает роль PostgreSQL, которая совпадает с вашим именем пользователя в MacOS
|
||||
например, "john".
|
||||
Чтобы проверить и создать пользователя `postgres`, при необходимости выполните следующие шаги:
|
||||
```bash
|
||||
@@ -173,8 +173,8 @@ cd twenty
|
||||
<Tab title="Windows (WSL)">
|
||||
Все последующие шаги следует выполнять в терминале WSL (внутри вашей виртуальной машины)
|
||||
|
||||
**Опция 1:** Чтобы настроить вашу базу данных Postgresql локально:
|
||||
Используйте следующую ссылку для установки Postgresql на вашу Linux виртуальную машину: [Установка Postgresql](https://www.postgresql.org/download/linux/)
|
||||
**Option 1:** To provision your PostgreSQL locally:
|
||||
Use the following link to install PostgreSQL on your Linux virtual machine: [PostgreSQL Installation](https://www.postgresql.org/download/linux/)
|
||||
```bash
|
||||
psql postgres -c "CREATE DATABASE \"default\";" -c "CREATE DATABASE test;"
|
||||
```
|
||||
@@ -189,11 +189,13 @@ cd twenty
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
Теперь вы можете получить доступ к базе данных по адресу [localhost:5432](localhost:5432), с пользователем `postgres` и паролем `postgres`.
|
||||
You can now access the database at `localhost:5432`.
|
||||
|
||||
If you used the Docker option above, the default credentials are user `postgres` and password `postgres`. For native PostgreSQL installations, use the credentials and roles configured on your machine.
|
||||
|
||||
## Шаг 4: Настройка базы данных Redis (кэш)
|
||||
|
||||
Twenty требует кэша Redis для обеспечения наилучшей производительности
|
||||
Twenty requires a Redis cache to provide the best performance.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Linux">
|
||||
@@ -210,8 +212,10 @@ Twenty требует кэша Redis для обеспечения наилуч
|
||||
```bash
|
||||
brew install redis
|
||||
```
|
||||
Запустите сервер redis:
|
||||
`brew services start redis`
|
||||
Start your Redis server:
|
||||
```bash
|
||||
brew services start redis
|
||||
```
|
||||
|
||||
**Опция 2:** Если у вас установлен docker:
|
||||
```bash
|
||||
@@ -229,11 +233,11 @@ Twenty требует кэша Redis для обеспечения наилуч
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
Если вам нужен графический интерфейс клиента, мы рекомендуем [redis insight](https://redis.io/insight/) (доступна бесплатная версия)
|
||||
If you need a client GUI, we recommend [Redis Insight](https://redis.io/insight/) (free version available).
|
||||
|
||||
## Шаг 5: Настройка переменных окружения
|
||||
## Step 5: Set up environment variables
|
||||
|
||||
Используйте переменные окружения или файлы `.env` для настройки вашего проекта. Подробнее [здесь](/l/ru/developers/self-host/capabilities/setup)
|
||||
Используйте переменные окружения или файлы `.env` для настройки вашего проекта. Подробнее [здесь](/l/ru/developers/self-host/capabilities/setup).
|
||||
|
||||
Скопируйте `.env.example` файлы в `/front` и `/server`:
|
||||
|
||||
|
||||
@@ -64,6 +64,12 @@ yarn twenty function:execute --preInstall
|
||||
# Выполнить послеустановочную функцию
|
||||
yarn twenty function:execute --postInstall
|
||||
|
||||
# Собрать приложение для распространения
|
||||
yarn twenty app:build
|
||||
|
||||
# Опубликовать приложение в npm или на сервер Twenty
|
||||
yarn twenty app:publish
|
||||
|
||||
# Удалить приложение из текущего рабочего пространства
|
||||
yarn twenty app:uninstall
|
||||
|
||||
@@ -1240,6 +1246,113 @@ uploadFile(
|
||||
|
||||
Ознакомьтесь с минимальным сквозным примером, демонстрирующим объекты, логические функции, фронт-компоненты и несколько триггеров, [здесь](https://github.com/twentyhq/twenty/tree/main/packages/twenty-apps/hello-world):
|
||||
|
||||
## Сборка вашего приложения
|
||||
|
||||
После того как вы разработали приложение с помощью `app:dev`, используйте `app:build`, чтобы скомпилировать его в распространяемый пакет.
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Собрать приложение (результат сохраняется в .twenty/output/)
|
||||
yarn twenty app:build
|
||||
|
||||
# Собрать и создать tarball (.tgz) для распространения
|
||||
yarn twenty app:build --tarball
|
||||
```
|
||||
|
||||
Процесс сборки:
|
||||
|
||||
1. **Разбирает и проверяет манифест** — читает все сущности `defineX()` из ваших исходных файлов и проверяет структуру манифеста.
|
||||
2. **Компилирует логические функции и фронтенд-компоненты** — упаковывает исходники TypeScript в ESM-файлы `.mjs` с помощью esbuild.
|
||||
3. **Генерирует контрольные суммы** — вычисляет хэши MD5 для каждого собранного файла, сохраняемые в манифесте как `builtHandlerChecksum` / `builtComponentChecksum`.
|
||||
4. **Генерирует типизированный клиент API** — проводит интроспекцию схемы GraphQL и генерирует типизированные клиенты `CoreApiClient` и `MetadataApiClient`.
|
||||
5. **Запускает проверку типов TypeScript** — выполняет `tsc --noEmit`, чтобы обнаружить ошибки типов перед публикацией.
|
||||
6. **Пересобирает со сгенерированным клиентом** — выполняет второй проход компиляции, чтобы включить сгенерированные типы клиента.
|
||||
7. **Опционально создаёт tar-архив** — если передан `--tarball`, выполняет `npm pack` для создания файла `.tgz`, готового к распространению.
|
||||
|
||||
Результат сборки в `.twenty/output/` содержит:
|
||||
|
||||
```text
|
||||
.twenty/output/
|
||||
├── manifest.json # Manifest with checksums for all built files
|
||||
├── package.json # Copied from app root
|
||||
├── yarn.lock # Copied from app root
|
||||
├── src/
|
||||
│ ├── logic-functions/ # Compiled .mjs logic function files
|
||||
│ └── front-components/ # Compiled .mjs front component files
|
||||
├── public/ # Static assets (if any)
|
||||
└── my-app-1.0.0.tgz # Only with --tarball flag
|
||||
```
|
||||
|
||||
| Вариант | Описание |
|
||||
| ----------- | ----------------------------------------------------------- |
|
||||
| `[appPath]` | Путь к каталогу приложения (по умолчанию — текущий каталог) |
|
||||
| `--tarball` | Также упаковать результат в tar-архив `.tgz` |
|
||||
|
||||
## Публикация вашего приложения
|
||||
|
||||
Используйте `app:publish` для распространения вашего приложения — либо в реестр npm, либо напрямую на сервер Twenty.
|
||||
|
||||
### Публикация в npm (по умолчанию)
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Publish to npm (requires npm login)
|
||||
yarn twenty app:publish
|
||||
|
||||
# Publish with a dist-tag (e.g. beta, next)
|
||||
yarn twenty app:publish --tag beta
|
||||
```
|
||||
|
||||
Это собирает приложение и выполняет `npm publish` из каталога `.twenty/output/`. Опубликованный пакет затем может быть установлен из маркетплейса Twenty любым рабочим пространством.
|
||||
|
||||
### Публикация на сервер Twenty
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Publish directly to a Twenty server
|
||||
yarn twenty app:publish --server https://app.twenty.com
|
||||
```
|
||||
|
||||
Это собирает приложение с tar-архивом, загружает его на сервер через мутацию GraphQL `uploadAppTarball` и запускает установку в один шаг. Это полезно для приватных развёртываний или тестирования на конкретном сервере.
|
||||
|
||||
| Вариант | Описание |
|
||||
| ----------------- | --------------------------------------------------------------------- |
|
||||
| `[appPath]` | Путь к каталогу приложения (по умолчанию — текущий каталог) |
|
||||
| `--server <url>` | Публиковать на сервер Twenty вместо npm |
|
||||
| `--token <token>` | Токен аутентификации для целевого сервера |
|
||||
| `--tag <tag>` | dist-тег npm (например, `beta`, `next`) — только для публикации в npm |
|
||||
|
||||
## Регистрация приложения
|
||||
|
||||
Прежде чем приложение можно будет установить в рабочем пространстве, его необходимо **зарегистрировать**. Регистрация — это запись метаданных, описывающая, откуда берётся приложение и как его аутентифицировать. В большинстве случаев это делает CLI автоматически.
|
||||
|
||||
### Типы источников
|
||||
|
||||
У каждой регистрации есть **тип источника**, который определяет, как файлы приложения будут получены при установке:
|
||||
|
||||
| Тип источника | Как получаются файлы | Типичный сценарий использования |
|
||||
| ------------- | ----------------------------------------------------------------------------------- | ------------------------------------------------- |
|
||||
| `LOCAL` | Файлы синхронизируются в реальном времени наблюдателем CLI — установка пропускается | Разработка с `app:dev` |
|
||||
| `NPM` | Получается из реестра npm через поле `sourcePackage` | Опубликованные приложения в npm |
|
||||
| `TARBALL` | Извлекается из загруженного файла `.tgz`, хранящегося на сервере | Приватные приложения, опубликованные с `--server` |
|
||||
|
||||
### Как происходит регистрация
|
||||
|
||||
* **`app:dev`** — автоматически создаёт регистрацию `LOCAL` при первом запуске режима разработки для рабочего пространства.
|
||||
* **`app:publish --server`** — загружает tar-архив и создаёт (или обновляет) регистрацию `TARBALL`, затем устанавливает приложение.
|
||||
* **маркетплейс npm** — регистрации `NPM` создаются, когда приложения синхронизируются из реестра npm в каталог маркетплейса Twenty.
|
||||
* **GraphQL API** — вы также можете создавать регистрации программно через мутацию `createApplicationRegistration`.
|
||||
|
||||
### Регистрация и установка
|
||||
|
||||
**Регистрация** и **установка** — это разные понятия:
|
||||
|
||||
* **Регистрация** (`ApplicationRegistration`) — это глобальная запись метаданных, описывающая приложение: его имя, тип источника, учётные данные OAuth и статус публикации в маркетплейсе. Она существует независимо от какого-либо рабочего пространства.
|
||||
* **Установка** (`Application`) — это экземпляр для каждого рабочего пространства. Когда пользователь устанавливает приложение, Twenty получает пакет из источника, указанного в регистрации, записывает собранные файлы в хранилище и синхронизирует манифест (создавая объекты, поля, логические функции и т. д.) в этом рабочем пространстве.
|
||||
|
||||
Одну и ту же регистрацию можно установить во многих рабочих пространствах. Каждое рабочее пространство получает свою собственную копию файлов приложения и модели данных.
|
||||
|
||||
### Учётные данные OAuth
|
||||
|
||||
Каждая регистрация включает учётные данные OAuth (`oAuthClientId` и `oAuthClientSecret`), сгенерированные при создании. Они используются приложением для аутентификации запросов к API от имени пользователей. Секрет клиента возвращается **один раз** при создании — храните его в надёжном месте. Позже вы можете сменить его через мутацию `rotateApplicationRegistrationClientSecret`.
|
||||
|
||||
## Ручная настройка (без генератора)
|
||||
|
||||
Хотя мы рекомендуем использовать `create-twenty-app` для наилучшего старта, вы также можете настроить проект вручную. Не устанавливайте CLI глобально. Вместо этого добавьте `twenty-sdk` как локальную зависимость и настройте один скрипт в вашем package.json:
|
||||
|
||||
@@ -3,7 +3,7 @@ title: В один клик с Docker Compose
|
||||
---
|
||||
|
||||
<Warning>
|
||||
Контейнеры Docker предназначены для продакшен-размещения или самостоятельного хостинга; для участия в разработке ознакомьтесь с разделом [Локальная установка](/l/ru/developers/contribute/capabilities/local-setup).
|
||||
Docker containers are for production hosting or self-hosting. For contributing, please check the [Local Setup](/l/ru/developers/contribute/capabilities/local-setup).
|
||||
</Warning>
|
||||
|
||||
## Обзор
|
||||
@@ -12,7 +12,7 @@ title: В один клик с Docker Compose
|
||||
|
||||
**Важно:** изменяйте только те настройки, которые явно упоминаются в этом руководстве. Изменение других конфигураций может привести к проблемам.
|
||||
|
||||
См. документацию [Настройка переменных окружения](/l/ru/developers/self-host/capabilities/setup) для расширенной конфигурации. Все переменные окружения должны быть задекларированы в файле docker-compose.yml на уровне сервера и / или рабочего потока в зависимости от переменной.
|
||||
See [Setup Environment Variables](/l/ru/developers/self-host/capabilities/setup) for advanced configuration. All environment variables must be declared in the `docker-compose.yml` file at the server and/or worker level, depending on the variable.
|
||||
|
||||
## Системные требования
|
||||
|
||||
|
||||
@@ -296,46 +296,60 @@ yarn command:prod cron:workflow:automated-cron-trigger
|
||||
**Режим только для среды:** если вы установили `IS_CONFIG_VARIABLES_IN_DB_ENABLED=false`, добавьте эти переменные в свой `.env` файл вместо этого.
|
||||
</Warning>
|
||||
|
||||
## Логические функции
|
||||
## Логические функции и интерпретатор кода
|
||||
|
||||
Twenty поддерживает логические функции для рабочих процессов и пользовательской логики. Среда выполнения настраивается через переменную окружения `SERVERLESS_TYPE`.
|
||||
Twenty поддерживает логические функции для рабочих процессов и интерпретатор кода для анализа данных ИИ. Оба запускают предоставленный пользователем код и требуют явной настройки в целях безопасности.
|
||||
|
||||
### Настройки безопасности по умолчанию
|
||||
|
||||
**В продакшене (NODE_ENV=production):** логические функции и интерпретатор кода по умолчанию — **Отключено**. Если вам нужны эти функции, вы должны явно включить их с помощью `LOGIC_FUNCTION_TYPE` и `CODE_INTERPRETER_TYPE`.
|
||||
|
||||
**В разработке (NODE_ENV=development):** оба по умолчанию — **LOCAL** для удобства при локальном запуске.
|
||||
|
||||
<Warning>
|
||||
**Уведомление о безопасности:** локальный драйвер (`SERVERLESS_TYPE=LOCAL`) выполняет код напрямую на хосте в процессе Node.js без изоляции. Его следует использовать только для доверенного кода в разработке. Для промышленных развертываний, обрабатывающих недоверенный код, настоятельно рекомендуем использовать `SERVERLESS_TYPE=LAMBDA` или `SERVERLESS_TYPE=DISABLED`.
|
||||
**Уведомление о безопасности:** локальный драйвер (`LOGIC_FUNCTION_TYPE=LOCAL` или `CODE_INTERPRETER_TYPE=LOCAL`) выполняет код напрямую на хосте в процессе Node.js без изоляции. Его следует использовать только для доверенного кода в разработке. Для рабочих развёртываний, обрабатывающих недоверенный код, используйте `LOGIC_FUNCTION_TYPE=LAMBDA` или `CODE_INTERPRETER_TYPE=E2B` (с песочницей) либо оставьте их отключёнными.
|
||||
</Warning>
|
||||
|
||||
### Доступные драйверы
|
||||
### Логические функции — доступные драйверы
|
||||
|
||||
| Драйвер | Переменная окружения | Сценарий использования | Уровень безопасности |
|
||||
| --------- | -------------------------- | -------------------------------------- | ----------------------------------------- |
|
||||
| Отключено | `SERVERLESS_TYPE=DISABLED` | Полностью отключить логические функции | Н/Д |
|
||||
| Локальный | `SERVERLESS_TYPE=LOCAL` | Разработка и доверенные среды | Низкий (без изоляции) |
|
||||
| Lambda | `SERVERLESS_TYPE=LAMBDA` | Продакшн с недоверенным кодом | Высокий (изоляция на уровне оборудования) |
|
||||
| Драйвер | Переменная окружения | Сценарий использования | Уровень безопасности |
|
||||
| --------- | ------------------------------ | -------------------------------------- | ----------------------------------------- |
|
||||
| Отключено | `LOGIC_FUNCTION_TYPE=DISABLED` | Полностью отключить логические функции | Н/Д |
|
||||
| Локальный | `LOGIC_FUNCTION_TYPE=LOCAL` | Разработка и доверенные среды | Низкий (без изоляции) |
|
||||
| Lambda | `LOGIC_FUNCTION_TYPE=LAMBDA` | Продакшн с недоверенным кодом | Высокий (изоляция на уровне оборудования) |
|
||||
|
||||
### Рекомендуемая конфигурация
|
||||
### Логические функции — рекомендуемая конфигурация
|
||||
|
||||
**Для разработки:**
|
||||
|
||||
```bash
|
||||
SERVERLESS_TYPE=LOCAL # default
|
||||
LOGIC_FUNCTION_TYPE=LOCAL # default when NODE_ENV=development
|
||||
```
|
||||
|
||||
**Для продакшна (AWS):**
|
||||
|
||||
```bash
|
||||
SERVERLESS_TYPE=LAMBDA
|
||||
SERVERLESS_LAMBDA_REGION=us-east-1
|
||||
SERVERLESS_LAMBDA_ROLE=arn:aws:iam::123456789:role/your-lambda-role
|
||||
SERVERLESS_LAMBDA_ACCESS_KEY_ID=your-access-key
|
||||
SERVERLESS_LAMBDA_SECRET_ACCESS_KEY=your-secret-key
|
||||
LOGIC_FUNCTION_TYPE=LAMBDA
|
||||
LOGIC_FUNCTION_LAMBDA_REGION=us-east-1
|
||||
LOGIC_FUNCTION_LAMBDA_ROLE=arn:aws:iam::123456789:role/your-lambda-role
|
||||
LOGIC_FUNCTION_LAMBDA_ACCESS_KEY_ID=your-access-key
|
||||
LOGIC_FUNCTION_LAMBDA_SECRET_ACCESS_KEY=your-secret-key
|
||||
```
|
||||
|
||||
**Чтобы отключить логические функции:**
|
||||
|
||||
```bash
|
||||
SERVERLESS_TYPE=DISABLED
|
||||
LOGIC_FUNCTION_TYPE=DISABLED # default when NODE_ENV=production
|
||||
```
|
||||
|
||||
### Интерпретатор кода — доступные драйверы
|
||||
|
||||
| Драйвер | Переменная окружения | Сценарий использования | Уровень безопасности |
|
||||
| --------- | -------------------------------- | ----------------------------------------------------- | --------------------------------- |
|
||||
| Отключено | `CODE_INTERPRETER_TYPE=DISABLED` | Отключить выполнение кода ИИ | Н/Д |
|
||||
| Локальный | `CODE_INTERPRETER_TYPE=LOCAL` | Только для разработки | Низкий (без изоляции) |
|
||||
| E2B | `CODE_INTERPRETER_TYPE=E_2_B` | Рабочая среда с изолированным исполнением в песочнице | Высокий (изолированная песочница) |
|
||||
|
||||
<Note>
|
||||
При использовании `SERVERLESS_TYPE=DISABLED` любая попытка выполнить логическую функцию вернет ошибку. Это полезно, если вы хотите запускать Twenty без возможностей логических функций.
|
||||
При использовании `LOGIC_FUNCTION_TYPE=DISABLED` или `CODE_INTERPRETER_TYPE=DISABLED` любая попытка выполнения вернёт ошибку. Это полезно, если вы хотите запускать Twenty без этих возможностей.
|
||||
</Note>
|
||||
|
||||
+2
-2
@@ -8,7 +8,7 @@ Buradaki amaç, okunması ve bakımı kolay tutarlı bir kod tabanı oluşturmak
|
||||
|
||||
Bunun için, biraz daha ayrıntılı olmak, çok kısa olmaktan daha iyidir.
|
||||
|
||||
İnsanların kodu yazmaktan daha sık okuduğunu her zaman aklınızda bulundurun; özellikle herkesin katkıda bulunabildiği açık kaynak bir projede.
|
||||
Always keep in mind that people read code more often than they write it, especially on an open source project, where anyone can contribute.
|
||||
|
||||
Burada tanımlanmayan, ancak linters tarafından otomatik olarak kontrol edilen birçok kural vardır.
|
||||
|
||||
@@ -149,7 +149,7 @@ type MyType = {
|
||||
|
||||
### enum'lar yerine string literal'leri kullanın
|
||||
|
||||
[String literalleri](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types), TypeScript'te enum benzeri değerleri yönetmek için en iyi yöntemdir. Pick ve Omit ile genişletilmesi daha kolay olur ve özellikle kod tamamlama ile daha iyi bir geliştirici deneyimi sunarlar.
|
||||
[String literalleri](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types), TypeScript'te enum benzeri değerleri yönetmek için en iyi yöntemdir. They are easier to extend with Pick and Omit, and offer a better developer experience, especially with code completion.
|
||||
|
||||
TypeScript, enum'ların neden kaçınılması gereken bir seçenek olduğunu [burada](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#enums) açıklamaktadır.
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ description: Twenty'i yerel olarak çalıştırmak isteyen katkıda bulunanlar (
|
||||
## Ön Gereksinimler
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Linux ve MacOS">
|
||||
<Tab title="Linux and macOS">
|
||||
|
||||
Twenty'i yüklemeden ve kullanmadan önce bilgisayarınıza aşağıdakileri yüklediğinizden emin olun:
|
||||
* [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
|
||||
@@ -30,7 +30,7 @@ wsl --install
|
||||
```
|
||||
Şimdi bilgisayarınızı yeniden başlatmanız gerektiğine dair bir uyarı göreceksiniz. Eğer görmüyorsanız, manuel olarak yeniden başlatın.
|
||||
|
||||
Yeniden başladıktan sonra bir powershell penceresi açılacak ve Ubuntu yüklenecek. Bu biraz zaman alabilir.
|
||||
Upon restart, a PowerShell window will open and install Ubuntu. Bu biraz zaman alabilir.
|
||||
Ubuntu kurulumunuz için bir kullanıcı adı ve şifre oluşturmanız gerektiğine dair bir uyarı göreceksiniz.
|
||||
|
||||
2. git'i Yükleyin ve Yapılandırın
|
||||
@@ -102,8 +102,8 @@ Sonraki adımlardaki tüm komutları projenin kök dizininden çalıştırmalıs
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Linux">
|
||||
**Seçenek 1 (tercih edilen):** Veritabanınızı yerel olarak kurmak için:
|
||||
Linux makinenize Postgresql yüklemek için şu bağlantıyı kullanın: [Postgresql Kurulumu](https://www.postgresql.org/download/linux/)
|
||||
**Option 1 (preferred):** To provision your database locally:
|
||||
Use the following link to install PostgreSQL on your Linux machine: [PostgreSQL Installation](https://www.postgresql.org/download/linux/)
|
||||
```bash
|
||||
psql postgres -c "CREATE DATABASE \"default\";" -c "CREATE DATABASE test;"
|
||||
```
|
||||
@@ -129,7 +129,8 @@ Sonraki adımlardaki tüm komutları projenin kök dizininden çalıştırmalıs
|
||||
brew services list
|
||||
```
|
||||
|
||||
Yükleyici, MacOS'ta Homebrew ile yüklenirken varsayılan olarak `postgres` kullanıcısını oluşturmayabilir. Bunun yerine, macOS kullanıcı adınıza (ör. "john") uygun bir PostgreSQL rolü oluşturur.
|
||||
The installer might not create the `postgres` user by default when installing
|
||||
via Homebrew on macOS. Bunun yerine, macOS kullanıcı adınıza (ör. "john") uygun bir PostgreSQL rolü oluşturur.
|
||||
Gerekiyorsa `postgres` kullanıcısını kontrol etmek ve oluşturtmak için şu adımları izleyin:
|
||||
```bash
|
||||
# PostgreSQL'e Bağlan
|
||||
@@ -171,8 +172,8 @@ Sonraki adımlardaki tüm komutları projenin kök dizininden çalıştırmalıs
|
||||
<Tab title="Windows (WSL)">
|
||||
Aşağıdaki tüm adımlar WSL terminalinde (sanallaştırma makineniz içinde) çalıştırılmalıdır.
|
||||
|
||||
**Seçenek 1:** Postgresql'i yerel olarak sağlamak için:
|
||||
Linux sanal makinenize Postgresql yüklemek için şu bağlantıyı kullanın: [Postgresql Kurulumu](https://www.postgresql.org/download/linux/)
|
||||
**Option 1:** To provision your PostgreSQL locally:
|
||||
Use the following link to install PostgreSQL on your Linux virtual machine: [PostgreSQL Installation](https://www.postgresql.org/download/linux/)
|
||||
```bash
|
||||
psql postgres -c "CREATE DATABASE \"default\";" -c "CREATE DATABASE test;"
|
||||
```
|
||||
@@ -187,11 +188,13 @@ Sonraki adımlardaki tüm komutları projenin kök dizininden çalıştırmalıs
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
Veritabanına [localhost:5432](localhost:5432) adresinden, kullanıcı `postgres` ve şifre `postgres` ile şimdi erişebilirsiniz.
|
||||
You can now access the database at `localhost:5432`.
|
||||
|
||||
If you used the Docker option above, the default credentials are user `postgres` and password `postgres`. For native PostgreSQL installations, use the credentials and roles configured on your machine.
|
||||
|
||||
## Adım 4: Redis Veritabanı (önbellek) Kurun
|
||||
|
||||
Twenty, en iyi performansı sağlamak için bir redis önbelleğe ihtiyaç duyar
|
||||
Twenty requires a Redis cache to provide the best performance.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Linux">
|
||||
@@ -208,8 +211,10 @@ Twenty, en iyi performansı sağlamak için bir redis önbelleğe ihtiyaç duyar
|
||||
```bash
|
||||
brew install redis
|
||||
```
|
||||
Redis sunucunuzu başlatın:
|
||||
`brew services start redis`
|
||||
Start your Redis server:
|
||||
```bash
|
||||
brew services start redis
|
||||
```
|
||||
|
||||
**Seçenek 2:** Eğer docker yüklüyse:
|
||||
```bash
|
||||
@@ -227,11 +232,11 @@ Twenty, en iyi performansı sağlamak için bir redis önbelleğe ihtiyaç duyar
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
Bir İstemci GUI'ye ihtiyacınız varsa, [redis insight](https://redis.io/insight/) (ücretsiz sürüm mevcut) öneriyoruz.
|
||||
If you need a client GUI, we recommend [Redis Insight](https://redis.io/insight/) (free version available).
|
||||
|
||||
## Adım 5: Çevresel değişkenleri ayarlayın
|
||||
## Step 5: Set up environment variables
|
||||
|
||||
Projenizi yapılandırmak için çevresel değişkenler veya `.env` dosyaları kullanın. Daha fazla bilgi [burada](/l/tr/developers/self-host/capabilities/setup)
|
||||
Projenizi yapılandırmak için çevresel değişkenler veya `.env` dosyaları kullanın. Daha fazla bilgi [burada](/l/tr/developers/self-host/capabilities/setup).
|
||||
|
||||
`.env.example` dosyalarını `/front` ve `/server` içine kopyalayın:
|
||||
|
||||
|
||||
@@ -64,6 +64,12 @@ yarn twenty function:execute --preInstall
|
||||
# Execute the post-install function
|
||||
yarn twenty function:execute --postInstall
|
||||
|
||||
# Build the app for distribution
|
||||
yarn twenty app:build
|
||||
|
||||
# Publish the app to npm or a Twenty server
|
||||
yarn twenty app:publish
|
||||
|
||||
# Uninstall the application from the current workspace
|
||||
yarn twenty app:uninstall
|
||||
|
||||
@@ -1240,6 +1246,113 @@ uploadFile(
|
||||
|
||||
Nesneleri, mantık fonksiyonlarını, ön uç bileşenlerini ve birden çok tetikleyiciyi gösteren minimal, uçtan uca bir örneği [buradan](https://github.com/twentyhq/twenty/tree/main/packages/twenty-apps/hello-world) inceleyin:
|
||||
|
||||
## Uygulamanızı derleme
|
||||
|
||||
Uygulamanızı `app:dev` ile geliştirdikten sonra, `app:build` kullanarak onu dağıtılabilir bir pakete derleyin.
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Build the app (output goes to .twenty/output/)
|
||||
yarn twenty app:build
|
||||
|
||||
# Build and create a tarball (.tgz) for distribution
|
||||
yarn twenty app:build --tarball
|
||||
```
|
||||
|
||||
Derleme süreci:
|
||||
|
||||
1. **Manifesti ayrıştırır ve doğrular** — kaynak dosyalarınızdaki tüm `defineX()` varlıklarını okur ve manifest yapısını doğrular.
|
||||
2. **Mantık işlevlerini ve ön bileşenleri derler** — TypeScript kaynaklarını esbuild kullanarak ESM `.mjs` dosyalarına paketler.
|
||||
3. **Sağlama toplamları üretir** — her bir oluşturulan dosya için MD5 karmalarını hesaplar ve manifestte `builtHandlerChecksum` / `builtComponentChecksum` olarak saklar.
|
||||
4. **Tipli API istemcisini oluşturur** — GraphQL şemasını inceleyip tipli `CoreApiClient` ve `MetadataApiClient` istemcilerini üretir.
|
||||
5. **TypeScript tip denetimi çalıştırır** — yayımlamadan önce tip hatalarını yakalamak için `tsc --noEmit` çalıştırır.
|
||||
6. **Oluşturulan istemciyle yeniden derler** — oluşturulan istemci tiplerinin dahil edilmesi için ikinci bir derleme geçişi yapar.
|
||||
7. **İsteğe bağlı olarak bir tarball oluşturur** — `--tarball` iletilirse, dağıtıma hazır bir `.tgz` dosyası oluşturmak için `npm pack` çalıştırır.
|
||||
|
||||
`.twenty/output/` içindeki derleme çıktısı şunları içerir:
|
||||
|
||||
```text
|
||||
.twenty/output/
|
||||
├── manifest.json # Manifest with checksums for all built files
|
||||
├── package.json # Copied from app root
|
||||
├── yarn.lock # Copied from app root
|
||||
├── src/
|
||||
│ ├── logic-functions/ # Compiled .mjs logic function files
|
||||
│ └── front-components/ # Compiled .mjs front component files
|
||||
├── public/ # Static assets (if any)
|
||||
└── my-app-1.0.0.tgz # Only with --tarball flag
|
||||
```
|
||||
|
||||
| Seçenek | Açıklama |
|
||||
| ----------- | --------------------------------------------------------- |
|
||||
| `[appPath]` | Uygulama dizininin yolu (varsayılan olarak geçerli dizin) |
|
||||
| `--tarball` | Çıktıyı ayrıca bir `.tgz` tarball olarak paketler |
|
||||
|
||||
## Uygulamanızı yayımlama
|
||||
|
||||
Uygulamanızı dağıtmak için `app:publish` komutunu kullanın — npm kayıt defterine ya da doğrudan bir Twenty sunucusuna yayımlayın.
|
||||
|
||||
### npm'ye yayımlama (varsayılan)
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Publish to npm (requires npm login)
|
||||
yarn twenty app:publish
|
||||
|
||||
# Publish with a dist-tag (e.g. beta, next)
|
||||
yarn twenty app:publish --tag beta
|
||||
```
|
||||
|
||||
Bu, uygulamayı derler ve `.twenty/output/` dizininden `npm publish` çalıştırır. Yayımlanan paket daha sonra Twenty pazar yerinden herhangi bir çalışma alanı tarafından kurulabilir.
|
||||
|
||||
### Bir Twenty sunucusuna yayımlama
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Publish directly to a Twenty server
|
||||
yarn twenty app:publish --server https://app.twenty.com
|
||||
```
|
||||
|
||||
Bu, uygulamayı bir tarball ile derler, `uploadAppTarball` GraphQL mutasyonu aracılığıyla sunucuya yükler ve tek adımda kurulumu tetikler. Bu, özel dağıtımlar veya belirli bir sunucuya karşı test yapmak için kullanışlıdır.
|
||||
|
||||
| Seçenek | Açıklama |
|
||||
| ----------------- | ---------------------------------------------------------------- |
|
||||
| `[appPath]` | Uygulama dizininin yolu (varsayılan olarak geçerli dizin) |
|
||||
| `--server <url>` | npm yerine bir Twenty sunucusuna yayımlar |
|
||||
| `--token <token>` | Hedef sunucu için kimlik doğrulama belirteci |
|
||||
| `--tag <tag>` | npm dist-tag (örn. `beta`, `next`) — yalnızca npm yayımlama için |
|
||||
|
||||
## Uygulama kaydı
|
||||
|
||||
Bir uygulama bir çalışma alanına kurulmadan önce kaydedilmelidir. Kayıt, uygulamanın nereden geldiğini ve nasıl kimlik doğrulanacağını açıklayan bir meta veri kaydıdır. Bu, çoğu durumda CLI tarafından otomatik olarak gerçekleştirilir.
|
||||
|
||||
### Kaynak türleri
|
||||
|
||||
Her kaydın, kurulum sırasında uygulamanın dosyalarının nasıl çözümleneceğini belirleyen bir kaynak türü vardır:
|
||||
|
||||
| Kaynak türü | Dosyaların nasıl çözümlendiği | Tipik kullanım durumu |
|
||||
| ----------- | ----------------------------------------------------------------------------------- | ------------------------------------------ |
|
||||
| `LOCAL` | Dosyalar, CLI izleyici tarafından gerçek zamanlı olarak eşitlenir — kurulum atlanır | `app:dev` ile geliştirme |
|
||||
| `NPM` | `sourcePackage` alanı aracılığıyla npm kayıt defterinden alınır | npm'de yayımlanan uygulamalar |
|
||||
| `TARBALL` | Sunucuda depolanan, yüklenmiş bir `.tgz` dosyasından çıkarılır | `--server` ile yayımlanan özel uygulamalar |
|
||||
|
||||
### Kayıt nasıl gerçekleşir
|
||||
|
||||
* **`app:dev`** — bir çalışma alanına karşı geliştirme modunu ilk kez çalıştırdığınızda otomatik olarak bir `LOCAL` kaydı oluşturur.
|
||||
* **`app:publish --server`** — bir tarball yükler ve bir `TARBALL` kaydı oluşturur (veya günceller), ardından uygulamayı kurar.
|
||||
* **npm pazar yeri** — uygulamalar npm kayıt defterinden Twenty pazar yeri kataloğuna eşitlendiğinde `NPM` kayıtları oluşturulur.
|
||||
* **GraphQL API** — `createApplicationRegistration` mutasyonu aracılığıyla programatik olarak da kayıtlar oluşturabilirsiniz.
|
||||
|
||||
### Kayıt ve kurulum
|
||||
|
||||
**Kayıt** ve **kurulum** ayrı kavramlardır:
|
||||
|
||||
* Bir kayıt (`ApplicationRegistration`), uygulamayı tanımlayan genel bir meta veri kaydıdır: adı, kaynak türü, OAuth kimlik bilgileri ve pazar yeri listeleme durumu. Herhangi bir çalışma alanından bağımsız olarak var olur.
|
||||
* Bir kurulum (`Application`), çalışma alanı başına bir örnektir. Bir kullanıcı bir uygulamayı kurduğunda, Twenty paketi kaydın kaynağından çözümler, derlenen dosyaları depolamaya yazar ve manifesti (nesneler, alanlar, mantık işlevleri vb. oluşturarak) eşitler o çalışma alanında.
|
||||
|
||||
Bir kayıt birçok çalışma alanına kurulabilir. Her çalışma alanı, uygulamanın dosyalarının ve veri modelinin kendi kopyasını alır.
|
||||
|
||||
### OAuth kimlik bilgileri
|
||||
|
||||
Her kayıt, oluşturma sırasında üretilen OAuth kimlik bilgilerini (`oAuthClientId` ve `oAuthClientSecret`) içerir. Bunlar, kullanıcılar adına API isteklerini kimlik doğrulamak için uygulama tarafından kullanılır. İstemci gizli anahtarı oluşturma sırasında yalnızca bir kez sağlanır — onu güvenli bir şekilde saklayın. Bunu daha sonra `rotateApplicationRegistrationClientSecret` mutasyonu aracılığıyla yenileyebilirsiniz.
|
||||
|
||||
## Manuel kurulum (scaffolder olmadan)
|
||||
|
||||
En iyi başlangıç deneyimi için `create-twenty-app` kullanmanızı önersek de, bir projeyi manuel olarak da kurabilirsiniz. CLI'yi global olarak kurmayın. Bunun yerine `twenty-sdk`'yi yerel bir bağımlılık olarak ekleyin ve package.json içinde tek bir betik tanımlayın:
|
||||
|
||||
@@ -3,7 +3,7 @@ title: 1-Tıklama ile Docker Compose
|
||||
---
|
||||
|
||||
<Warning>
|
||||
Docker konteynerleri, üretim ortamında veya kendi sunucunuzda barındırma içindir; katkıda bulunmak için [Yerel Kurulum](/l/tr/developers/contribute/capabilities/local-setup) sayfasına bakın.
|
||||
Docker containers are for production hosting or self-hosting. For contributing, please check the [Local Setup](/l/tr/developers/contribute/capabilities/local-setup).
|
||||
</Warning>
|
||||
|
||||
## Genel Bakış
|
||||
@@ -12,7 +12,7 @@ Bu kılavuz, Docker Compose kullanarak Twenty uygulamasını kurmak ve yapıland
|
||||
|
||||
**Önemli:** Yalnızca bu kılavuzda açıkça belirtilen ayarları değiştirin. Diğer yapılandırmaları değiştirmek sorunlara yol açabilir.
|
||||
|
||||
İleri düzey yapılandırma için belgelerdeki [Ortam Değişkenlerini Ayarlama](/l/tr/developers/self-host/capabilities/setup) bölümüne bakın. Tüm ortam değişkenleri, sunucu ve / veya işçi düzeyine bağlı olarak docker-compose.yml dosyasında ilan edilmelidir.
|
||||
See [Setup Environment Variables](/l/tr/developers/self-host/capabilities/setup) for advanced configuration. All environment variables must be declared in the `docker-compose.yml` file at the server and/or worker level, depending on the variable.
|
||||
|
||||
## Sistem Gereksinimleri
|
||||
|
||||
|
||||
@@ -297,46 +297,60 @@ yarn command:prod cron:workflow:automated-cron-trigger
|
||||
**Çevre-yalnızca modu:** `IS_CONFIG_VARIABLES_IN_DB_ENABLED=false` ayarlarsanız, bu değişkenleri `.env` dosyanıza ekleyin.
|
||||
</Warning>
|
||||
|
||||
## Mantıksal işlevler
|
||||
## Mantıksal İşlevler ve Kod Yorumlayıcısı
|
||||
|
||||
Twenty, iş akışları ve özel mantık için mantıksal işlevleri destekler. Yürütme ortamı, `SERVERLESS_TYPE` ortam değişkeni aracılığıyla yapılandırılır.
|
||||
Twenty, iş akışları için mantıksal işlevleri ve yapay zekâ veri analizi için kod yorumlayıcısını destekler. Her ikisi de kullanıcı tarafından sağlanan kodu çalıştırır ve güvenlik için açık bir yapılandırma gerektirir.
|
||||
|
||||
### Güvenlik Varsayılanları
|
||||
|
||||
**Üretimde (NODE_ENV=production):** Hem mantıksal işlevler hem de kod yorumlayıcı varsayılan olarak **Devre Dışı**dır. Bu özelliklere ihtiyacınız varsa, onları `LOGIC_FUNCTION_TYPE` ve `CODE_INTERPRETER_TYPE` ile açıkça etkinleştirmeniz gerekir.
|
||||
|
||||
**Geliştirmede (NODE_ENV=development):** Yerel olarak çalıştırırken kolaylık olması için her ikisinin varsayılanı **LOCAL**dır.
|
||||
|
||||
<Warning>
|
||||
**Güvenlik Notu:** Yerel sürücü (`SERVERLESS_TYPE=LOCAL`), herhangi bir sandbox olmadan kodu ana makinede doğrudan bir Node.js sürecinde çalıştırır. Yalnızca geliştirirken güvenilen kod için kullanılmalıdır. Güvenilmeyen kodu işleyen üretim dağıtımları için `SERVERLESS_TYPE=LAMBDA` veya `SERVERLESS_TYPE=DISABLED` kullanmanızı şiddetle öneririz.
|
||||
**Güvenlik Notu:** Yerel sürücü (`LOGIC_FUNCTION_TYPE=LOCAL` veya `CODE_INTERPRETER_TYPE=LOCAL`), herhangi bir sandbox olmadan kodu ana makinede doğrudan bir Node.js sürecinde çalıştırır. Yalnızca geliştirirken güvenilen kod için kullanılmalıdır. Üretim dağıtımlarında güvenilmeyen kodu işlerken, `LOGIC_FUNCTION_TYPE=LAMBDA` veya `CODE_INTERPRETER_TYPE=E2B` (korumalı alanla) kullanın ya da bunları devre dışı bırakın.
|
||||
</Warning>
|
||||
|
||||
### Kullanılabilir Sürücüler
|
||||
### Mantıksal İşlevler - Kullanılabilir Sürücüler
|
||||
|
||||
| Sürücü | Ortam Değişkeni | Kullanım alanı | Güvenlik Düzeyi |
|
||||
| ---------- | -------------------------- | ---------------------------------------------- | ------------------------------------ |
|
||||
| Devre dışı | `SERVERLESS_TYPE=DISABLED` | Mantıksal işlevleri tamamen devre dışı bırakın | Uygulanamaz |
|
||||
| Yerel | `SERVERLESS_TYPE=LOCAL` | Geliştirme ve güvenilir ortamlar | Düşük (sandbox yok) |
|
||||
| Lambda | `SERVERLESS_TYPE=LAMBDA` | Güvenilmeyen kodla üretim | Yüksek (donanım düzeyinde izolasyon) |
|
||||
| Sürücü | Ortam Değişkeni | Kullanım alanı | Güvenlik Düzeyi |
|
||||
| ---------- | ------------------------------ | ---------------------------------------------- | ------------------------------------ |
|
||||
| Devre dışı | `LOGIC_FUNCTION_TYPE=DISABLED` | Mantıksal işlevleri tamamen devre dışı bırakın | Uygulanamaz |
|
||||
| Yerel | `LOGIC_FUNCTION_TYPE=LOCAL` | Geliştirme ve güvenilir ortamlar | Düşük (sandbox yok) |
|
||||
| Lambda | `LOGIC_FUNCTION_TYPE=LAMBDA` | Güvenilmeyen kodla üretim | Yüksek (donanım düzeyinde izolasyon) |
|
||||
|
||||
### Önerilen Yapılandırma
|
||||
### Mantıksal İşlevler - Önerilen Yapılandırma
|
||||
|
||||
**Geliştirme için:**
|
||||
|
||||
```bash
|
||||
SERVERLESS_TYPE=LOCAL # default
|
||||
LOGIC_FUNCTION_TYPE=LOCAL # default when NODE_ENV=development
|
||||
```
|
||||
|
||||
**Üretim için (AWS):**
|
||||
|
||||
```bash
|
||||
SERVERLESS_TYPE=LAMBDA
|
||||
SERVERLESS_LAMBDA_REGION=us-east-1
|
||||
SERVERLESS_LAMBDA_ROLE=arn:aws:iam::123456789:role/your-lambda-role
|
||||
SERVERLESS_LAMBDA_ACCESS_KEY_ID=your-access-key
|
||||
SERVERLESS_LAMBDA_SECRET_ACCESS_KEY=your-secret-key
|
||||
LOGIC_FUNCTION_TYPE=LAMBDA
|
||||
LOGIC_FUNCTION_LAMBDA_REGION=us-east-1
|
||||
LOGIC_FUNCTION_LAMBDA_ROLE=arn:aws:iam::123456789:role/your-lambda-role
|
||||
LOGIC_FUNCTION_LAMBDA_ACCESS_KEY_ID=your-access-key
|
||||
LOGIC_FUNCTION_LAMBDA_SECRET_ACCESS_KEY=your-secret-key
|
||||
```
|
||||
|
||||
**Mantıksal işlevleri devre dışı bırakmak için:**
|
||||
|
||||
```bash
|
||||
SERVERLESS_TYPE=DISABLED
|
||||
LOGIC_FUNCTION_TYPE=DISABLED # default when NODE_ENV=production
|
||||
```
|
||||
|
||||
### Kod Yorumlayıcısı - Kullanılabilir Sürücüler
|
||||
|
||||
| Sürücü | Ortam Değişkeni | Kullanım Senaryosu | Güvenlik Düzeyi |
|
||||
| ---------- | -------------------------------- | --------------------------------------------- | --------------------------------- |
|
||||
| Devre dışı | `CODE_INTERPRETER_TYPE=DISABLED` | Yapay zekâ kod yürütmesini devre dışı bırakın | Uygulanamaz |
|
||||
| Yerel | `CODE_INTERPRETER_TYPE=LOCAL` | Yalnızca geliştirme için | Düşük (sandbox yok) |
|
||||
| E2B | `CODE_INTERPRETER_TYPE=E_2_B` | Korumalı alanlı yürütmeyle üretim | Yüksek (yalıtılmış korumalı alan) |
|
||||
|
||||
<Note>
|
||||
`SERVERLESS_TYPE=DISABLED` kullanıldığında, bir mantıksal işlevi yürütmeye yönelik herhangi bir girişim bir hata döndürür. Bu, Twenty'yi mantıksal işlev yetenekleri olmadan çalıştırmak istiyorsanız kullanışlıdır.
|
||||
`LOGIC_FUNCTION_TYPE=DISABLED` veya `CODE_INTERPRETER_TYPE=DISABLED` kullanıldığında, herhangi bir yürütme girişimi bir hata döndürür. Bu, Twenty'yi bu yetenekler olmadan çalıştırmak istiyorsanız kullanışlıdır.
|
||||
</Note>
|
||||
|
||||
+2
-2
@@ -8,7 +8,7 @@ title: 样式指南
|
||||
|
||||
为此,比起过于简洁,冗长一些更好。
|
||||
|
||||
请始终记住,人们阅读代码的次数远多于他们编写代码的次数,特别是在开源项目中,任何人都可以贡献。
|
||||
Always keep in mind that people read code more often than they write it, especially on an open source project, where anyone can contribute.
|
||||
|
||||
有很多规则没有在此定义,但可以通过linters自动检查。
|
||||
|
||||
@@ -150,7 +150,7 @@ type MyType = {
|
||||
|
||||
### 使用字符串字面量代替枚举
|
||||
|
||||
[字符串字面量](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types)是TypeScript中处理枚举值的首选方式。 它们可以更轻松地使用Pick和Omit扩展,并提供更好的开发者体验,特别是在代码补全时。
|
||||
[字符串字面量](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types)是TypeScript中处理枚举值的首选方式。 They are easier to extend with Pick and Omit, and offer a better developer experience, especially with code completion.
|
||||
|
||||
您可以查看[这里](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#enums)了解为什么TypeScript建议避免使用枚举。
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ description: 本指南适用于希望在本地运行 Twenty 的贡献者或好
|
||||
## 先决条件
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Linux 和 MacOS">
|
||||
<Tab title="Linux and macOS">
|
||||
|
||||
在安装和使用 Twenty 之前,请确保在您的计算机上安装以下内容:
|
||||
* [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
|
||||
@@ -30,7 +30,7 @@ wsl --install
|
||||
```
|
||||
现在您应该看到一个提示,要求您重启计算机。 如果没有,请手动重启。
|
||||
|
||||
重启后,一个 powershell 窗口将打开并安装 Ubuntu。 这可能需要一些时间。
|
||||
Upon restart, a PowerShell window will open and install Ubuntu. 这可能需要一些时间。
|
||||
您将看到一个提示,要求为您的 Ubuntu 安装创建用户名和密码。
|
||||
|
||||
2. 安装和配置 git
|
||||
@@ -102,8 +102,8 @@ cd twenty
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Linux">
|
||||
\*\*选项 1(推荐):\*\*在本地供应您的数据库:
|
||||
使用以下链接在 Linux 机器上安装 Postgresql:[Postgresql 安装](https://www.postgresql.org/download/linux/)
|
||||
**Option 1 (preferred):** To provision your database locally:
|
||||
Use the following link to install PostgreSQL on your Linux machine: [PostgreSQL Installation](https://www.postgresql.org/download/linux/)
|
||||
```bash
|
||||
psql postgres -c "CREATE DATABASE \"default\";" -c "CREATE DATABASE test;"
|
||||
```
|
||||
@@ -129,7 +129,8 @@ cd twenty
|
||||
brew services list
|
||||
```
|
||||
|
||||
安装器在通过 Homebrew 安装时可能不会默认创建 `postgres` 用户。 相反,它会创建一个与您的 macOS 用户名(例如,“john”)匹配的 PostgreSQL 角色。
|
||||
The installer might not create the `postgres` user by default when installing
|
||||
via Homebrew on macOS. 相反,它会创建一个与您的 macOS 用户名(例如,“john”)匹配的 PostgreSQL 角色。
|
||||
按照以下步骤检查并在必要时创建 `postgres` 用户:
|
||||
```bash
|
||||
# Connect to PostgreSQL
|
||||
@@ -171,8 +172,8 @@ cd twenty
|
||||
<Tab title="Windows (WSL)">
|
||||
以下所有步骤应在 WSL 终端(在您的虚拟机内)中运行
|
||||
|
||||
\*\*选项 1:\*\*在本地提供您的 Postgresql:
|
||||
使用以下链接在 Linux 虚拟机上安装 Postgresql:[Postgresql 安装](https://www.postgresql.org/download/linux/)
|
||||
**Option 1:** To provision your PostgreSQL locally:
|
||||
Use the following link to install PostgreSQL on your Linux virtual machine: [PostgreSQL Installation](https://www.postgresql.org/download/linux/)
|
||||
```bash
|
||||
psql postgres -c "CREATE DATABASE \"default\";" -c "CREATE DATABASE test;"
|
||||
```
|
||||
@@ -187,11 +188,13 @@ cd twenty
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
您现在可以在 [localhost:5432](localhost:5432) 访问数据库,用户名 `postgres`,密码 `postgres`。
|
||||
You can now access the database at `localhost:5432`.
|
||||
|
||||
If you used the Docker option above, the default credentials are user `postgres` and password `postgres`. For native PostgreSQL installations, use the credentials and roles configured on your machine.
|
||||
|
||||
## 步骤 4:设置 Redis 数据库(缓存)
|
||||
|
||||
Twenty 需要 Redis 缓存来提供最佳性能
|
||||
Twenty requires a Redis cache to provide the best performance.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Linux">
|
||||
@@ -208,8 +211,10 @@ Twenty 需要 Redis 缓存来提供最佳性能
|
||||
```bash
|
||||
brew install redis
|
||||
```
|
||||
启动您的 redis server:
|
||||
`brew services start redis`
|
||||
Start your Redis server:
|
||||
```bash
|
||||
brew services start redis
|
||||
```
|
||||
|
||||
\*\*选项 2:\*\*如果您已安装 docker:
|
||||
```bash
|
||||
@@ -227,11 +232,11 @@ Twenty 需要 Redis 缓存来提供最佳性能
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
如果您需要客户端 GUI,我们推荐 [redis insight](https://redis.io/insight/)(提供免费版)
|
||||
If you need a client GUI, we recommend [Redis Insight](https://redis.io/insight/) (free version available).
|
||||
|
||||
## 步骤 5:设置环境变量
|
||||
## Step 5: Set up environment variables
|
||||
|
||||
使用环境变量或 `.env` 文件配置您的项目。 更多信息请参见 [此处](/l/zh/developers/self-host/capabilities/setup)
|
||||
使用环境变量或 `.env` 文件配置您的项目。 更多信息请参见 [此处](/l/zh/developers/self-host/capabilities/setup).
|
||||
|
||||
复制 `/front` 和 `/server` 目录中的 `.env.example` 文件:
|
||||
|
||||
|
||||
@@ -49,25 +49,31 @@ 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
|
||||
|
||||
# 从当前工作区卸载该应用
|
||||
# Build the app for distribution
|
||||
yarn twenty app:build
|
||||
|
||||
# Publish the app to npm or a Twenty server
|
||||
yarn twenty app:publish
|
||||
|
||||
# Uninstall the application from the current workspace
|
||||
yarn twenty app:uninstall
|
||||
|
||||
# 显示命令帮助
|
||||
# Display commands' help
|
||||
yarn twenty help
|
||||
```
|
||||
|
||||
@@ -1240,6 +1246,113 @@ uploadFile(
|
||||
|
||||
在[此处](https://github.com/twentyhq/twenty/tree/main/packages/twenty-apps/hello-world)查看一个最小的端到端示例,展示对象、逻辑函数、前端组件和多种触发器:
|
||||
|
||||
## Building your app
|
||||
|
||||
Once you've developed your app with `app:dev`, use `app:build` to compile it into a distributable package.
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Build the app (output goes to .twenty/output/)
|
||||
yarn twenty app:build
|
||||
|
||||
# Build and create a tarball (.tgz) for distribution
|
||||
yarn twenty app:build --tarball
|
||||
```
|
||||
|
||||
The build process:
|
||||
|
||||
1. **Parses and validates the manifest** — reads all `defineX()` entities from your source files and validates the manifest structure.
|
||||
2. **Compiles logic functions and front components** — bundles TypeScript sources into ESM `.mjs` files using esbuild.
|
||||
3. **Generates checksums** — computes MD5 hashes for each built file, stored in the manifest as `builtHandlerChecksum` / `builtComponentChecksum`.
|
||||
4. **生成类型化的 API 客户端** — 对 GraphQL 架构进行自省,并生成带类型的 `CoreApiClient` 和 `MetadataApiClient` 客户端。
|
||||
5. **运行 TypeScript 类型检查** — 运行 `tsc --noEmit` 以在发布前捕获类型错误。
|
||||
6. **使用生成的客户端重新构建** — 执行第二次编译,以便包含生成的客户端类型。
|
||||
7. **可选地创建一个 tar 包** — 如果传入 `--tarball`,则运行 `npm pack` 以创建用于分发的 `.tgz` 文件。
|
||||
|
||||
`.twenty/output/` 中的构建产物包含:
|
||||
|
||||
```text
|
||||
.twenty/output/
|
||||
├── manifest.json # Manifest with checksums for all built files
|
||||
├── package.json # Copied from app root
|
||||
├── yarn.lock # Copied from app root
|
||||
├── src/
|
||||
│ ├── logic-functions/ # Compiled .mjs logic function files
|
||||
│ └── front-components/ # Compiled .mjs front component files
|
||||
├── public/ # Static assets (if any)
|
||||
└── my-app-1.0.0.tgz # Only with --tarball flag
|
||||
```
|
||||
|
||||
| 选项 | 描述 |
|
||||
| ----------- | ----------------------- |
|
||||
| `[appPath]` | 应用目录的路径(默认为当前目录) |
|
||||
| `--tarball` | 同时将输出打包为一个 `.tgz` tar 包 |
|
||||
|
||||
## 发布你的应用
|
||||
|
||||
使用 `app:publish` 分发你的应用 — 可以发布到 npm 注册表,或直接发布到 Twenty 服务器。
|
||||
|
||||
### 发布到 npm(默认)
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Publish to npm (requires npm login)
|
||||
yarn twenty app:publish
|
||||
|
||||
# Publish with a dist-tag (e.g. beta, next)
|
||||
yarn twenty app:publish --tag beta
|
||||
```
|
||||
|
||||
这会构建应用,并在 `.twenty/output/` 目录下运行 `npm publish`。 发布后的软件包可由任何工作区从 Twenty 市场进行安装。
|
||||
|
||||
### 发布到 Twenty 服务器
|
||||
|
||||
```bash filename="Terminal"
|
||||
# Publish directly to a Twenty server
|
||||
yarn twenty app:publish --server https://app.twenty.com
|
||||
```
|
||||
|
||||
这会以 tar 包方式构建应用,通过 `uploadAppTarball` GraphQL 变更将其上传到服务器,并在一步中触发安装。 这对于私有部署或针对特定服务器进行测试非常有用。
|
||||
|
||||
| 选项 | 描述 |
|
||||
| ----------------- | ------------------------------------------ |
|
||||
| `[appPath]` | 应用目录的路径(默认为当前目录) |
|
||||
| `--server <url>` | 发布到 Twenty 服务器(而非 npm) |
|
||||
| `--token <token>` | 目标服务器的身份验证令牌 |
|
||||
| `--tag <tag>` | npm dist-tag(例如 `beta`、`next`)— 仅用于发布到 npm |
|
||||
|
||||
## 应用注册
|
||||
|
||||
在应用安装到工作区之前,必须先进行**注册**。 注册是一条元数据记录,用于描述应用的来源以及如何对其进行身份验证。 在大多数情况下,CLI 会自动处理这一流程。
|
||||
|
||||
### 来源类型
|
||||
|
||||
每个注册都有一个**来源类型**,用于决定安装期间如何解析应用的文件:
|
||||
|
||||
| 来源类型 | 文件的解析方式 | 典型用例 |
|
||||
| --------- | -------------------------------- | --------------------- |
|
||||
| `LOCAL` | 文件由 CLI 监听器实时同步——跳过安装步骤 | 使用 `app:dev` 进行开发 |
|
||||
| `NPM` | 通过 `sourcePackage` 字段从 npm 注册表获取 | 在 npm 上发布的应用 |
|
||||
| `TARBALL` | 从存储在服务器上的已上传 `.tgz` 文件中解压获得 | 使用 `--server` 发布的私有应用 |
|
||||
|
||||
### 注册如何进行
|
||||
|
||||
* **`app:dev`** — 第一次针对某个工作区运行开发模式时,会自动创建一个 `LOCAL` 注册。
|
||||
* **`app:publish --server`** — 上传一个 tar 包并创建(或更新)一个 `TARBALL` 注册,然后安装应用。
|
||||
* **npm 市场** — 当应用从 npm 注册表同步到 Twenty 市场目录时,会创建 `NPM` 注册。
|
||||
* **GraphQL API** — 你也可以通过 `createApplicationRegistration` 变更以编程方式创建注册。
|
||||
|
||||
### 注册与安装
|
||||
|
||||
**注册** 与 **安装** 是两个独立的概念:
|
||||
|
||||
* **注册**(`ApplicationRegistration`)是一条全局元数据记录,用于描述应用:其名称、来源类型、OAuth 凭据以及在市场中的上架状态。 它独立于任何工作区存在。
|
||||
* **安装**(`Application`)是一个按工作区划分的实例。 当用户安装一个应用时,Twenty 会根据注册的来源解析软件包,将构建生成的文件写入存储,并同步清单(创建对象、字段、逻辑函数等) 到该工作区中。
|
||||
|
||||
一个注册可以安装到多个工作区。 每个工作区都会获得应用文件和数据模型的独立副本。
|
||||
|
||||
### OAuth 凭据
|
||||
|
||||
每个注册都包含在创建时生成的 OAuth 凭据(`oAuthClientId` 和 `oAuthClientSecret`)。 应用使用这些凭据代表用户对 API 请求进行身份验证。 客户端密钥在创建时只会返回**一次**——请妥善保管。 你可以稍后通过 `rotateApplicationRegistrationClientSecret` 变更来轮换它。
|
||||
|
||||
## 手动设置(不使用脚手架)
|
||||
|
||||
虽然我们建议使用 `create-twenty-app` 以获得最佳的上手体验,但你也可以手动设置项目。 不要全局安装 CLI。 相反,请将 `twenty-sdk` 添加为本地依赖,并在你的 package.json 中配置一个脚本:
|
||||
|
||||
@@ -3,7 +3,7 @@ title: 1-点击使用Docker Compose
|
||||
---
|
||||
|
||||
<Warning>
|
||||
Docker容器用于生产托管或自托管,关于贡献,请查看[本地设置](/l/zh/developers/contribute/capabilities/local-setup)。
|
||||
Docker containers are for production hosting or self-hosting. For contributing, please check the [Local Setup](/l/zh/developers/contribute/capabilities/local-setup).
|
||||
</Warning>
|
||||
|
||||
## 概览
|
||||
@@ -12,7 +12,7 @@ Docker容器用于生产托管或自托管,关于贡献,请查看[本地设
|
||||
|
||||
**重要:** 仅修改本指南中明确提到的设置。 更改其他配置可能会导致问题。
|
||||
|
||||
请参阅文档[设置环境变量](/l/zh/developers/self-host/capabilities/setup)获取高级配置。 所有环境变量必须在docker-compose.yml文件中根据变量声明在服务器和/或工作器级别。
|
||||
See [Setup Environment Variables](/l/zh/developers/self-host/capabilities/setup) for advanced configuration. All environment variables must be declared in the `docker-compose.yml` file at the server and/or worker level, depending on the variable.
|
||||
|
||||
## 系统要求
|
||||
|
||||
|
||||
@@ -297,46 +297,60 @@ yarn command:prod cron:workflow:automated-cron-trigger
|
||||
**仅限环境模式:** 如果你设置 `IS_CONFIG_VARIABLES_IN_DB_ENABLED=false`,请将这些变量添加到 `.env` 文件中。
|
||||
</Warning>
|
||||
|
||||
## 逻辑函数
|
||||
## 逻辑函数与代码解释器
|
||||
|
||||
Twenty 支持用于工作流和自定义逻辑的逻辑函数。 执行环境通过 `SERVERLESS_TYPE` 环境变量进行配置。
|
||||
Twenty 支持用于工作流的逻辑函数,以及用于 AI 数据分析的代码解释器。 二者都会运行用户提供的代码,并要求进行显式配置以确保安全。
|
||||
|
||||
### 安全默认设置
|
||||
|
||||
**在生产环境(NODE_ENV=production):** 逻辑函数和代码解释器的默认设置为**禁用**。 如需这些功能,必须通过 `LOGIC_FUNCTION_TYPE` 和 `CODE_INTERPRETER_TYPE` 显式启用它们。
|
||||
|
||||
**在开发环境(NODE_ENV=development):** 为方便在本地运行,二者默认均为**LOCAL**。
|
||||
|
||||
<Warning>
|
||||
\*\*安全提示:\*\*本地驱动(`SERVERLESS_TYPE=LOCAL`)在没有沙箱的情况下,在主机上的 Node.js 进程中直接运行代码。 它应仅在开发环境中用于可信代码。 对于在生产环境中处理不受信任代码的部署,我们强烈建议使用 `SERVERLESS_TYPE=LAMBDA` 或 `SERVERLESS_TYPE=DISABLED`。
|
||||
**安全提示:** 本地驱动(`LOGIC_FUNCTION_TYPE=LOCAL` 或 `CODE_INTERPRETER_TYPE=LOCAL`)会在没有沙箱的情况下,在主机上的 Node.js 进程中直接运行代码。 它应仅在开发环境中用于可信代码。 对于在生产环境中处理不受信任代码的部署,请使用 `LOGIC_FUNCTION_TYPE=LAMBDA` 或 `CODE_INTERPRETER_TYPE=E2B`(使用沙盒),或将它们保持禁用。
|
||||
</Warning>
|
||||
|
||||
### 可用驱动
|
||||
### 逻辑函数 - 可用驱动程序
|
||||
|
||||
| 驱动 | 环境变量 | 用例 | 安全级别 |
|
||||
| ------ | -------------------------- | -------------- | -------- |
|
||||
| 禁用 | `SERVERLESS_TYPE=DISABLED` | 完全禁用逻辑函数 | 不适用 |
|
||||
| 本地 | `SERVERLESS_TYPE=LOCAL` | 开发和可信环境 | 低(无沙箱) |
|
||||
| Lambda | `SERVERLESS_TYPE=LAMBDA` | 生产环境(处理不受信任代码) | 高(硬件级隔离) |
|
||||
| 驱动 | 环境变量 | 用例 | 安全级别 |
|
||||
| ------ | ------------------------------ | -------------- | -------- |
|
||||
| 禁用 | `LOGIC_FUNCTION_TYPE=DISABLED` | 完全禁用逻辑函数 | 不适用 |
|
||||
| 本地 | `LOGIC_FUNCTION_TYPE=LOCAL` | 开发和可信环境 | 低(无沙箱) |
|
||||
| Lambda | `LOGIC_FUNCTION_TYPE=LAMBDA` | 生产环境(处理不受信任代码) | 高(硬件级隔离) |
|
||||
|
||||
### 推荐配置
|
||||
### 逻辑函数 - 推荐配置
|
||||
|
||||
**用于开发:**
|
||||
|
||||
```bash
|
||||
SERVERLESS_TYPE=LOCAL # default
|
||||
LOGIC_FUNCTION_TYPE=LOCAL # default when NODE_ENV=development
|
||||
```
|
||||
|
||||
**用于生产(AWS):**
|
||||
|
||||
```bash
|
||||
SERVERLESS_TYPE=LAMBDA
|
||||
SERVERLESS_LAMBDA_REGION=us-east-1
|
||||
SERVERLESS_LAMBDA_ROLE=arn:aws:iam::123456789:role/your-lambda-role
|
||||
SERVERLESS_LAMBDA_ACCESS_KEY_ID=your-access-key
|
||||
SERVERLESS_LAMBDA_SECRET_ACCESS_KEY=your-secret-key
|
||||
LOGIC_FUNCTION_TYPE=LAMBDA
|
||||
LOGIC_FUNCTION_LAMBDA_REGION=us-east-1
|
||||
LOGIC_FUNCTION_LAMBDA_ROLE=arn:aws:iam::123456789:role/your-lambda-role
|
||||
LOGIC_FUNCTION_LAMBDA_ACCESS_KEY_ID=your-access-key
|
||||
LOGIC_FUNCTION_LAMBDA_SECRET_ACCESS_KEY=your-secret-key
|
||||
```
|
||||
|
||||
**要禁用逻辑函数:**
|
||||
|
||||
```bash
|
||||
SERVERLESS_TYPE=DISABLED
|
||||
LOGIC_FUNCTION_TYPE=DISABLED # default when NODE_ENV=production
|
||||
```
|
||||
|
||||
### 代码解释器 - 可用驱动程序
|
||||
|
||||
| 驱动 | 环境变量 | 用例 | 安全级别 |
|
||||
| --- | -------------------------------- | ----------- | ------- |
|
||||
| 禁用 | `CODE_INTERPRETER_TYPE=DISABLED` | 禁用 AI 代码执行 | 不适用 |
|
||||
| 本地 | `CODE_INTERPRETER_TYPE=LOCAL` | 仅限开发环境 | 低(无沙箱) |
|
||||
| E2B | `CODE_INTERPRETER_TYPE=E_2_B` | 生产环境(沙盒化执行) | 高(隔离沙盒) |
|
||||
|
||||
<Note>
|
||||
使用 `SERVERLESS_TYPE=DISABLED` 时,任何尝试执行逻辑函数的操作都会返回错误。 如果你想在不启用逻辑函数能力的情况下运行 Twenty,这将很有用。
|
||||
当使用 `LOGIC_FUNCTION_TYPE=DISABLED` 或 `CODE_INTERPRETER_TYPE=DISABLED` 时,任何执行尝试都会返回错误。 如果你想在不启用这些功能的情况下运行 Twenty,这将很有用。
|
||||
</Note>
|
||||
|
||||
@@ -45,13 +45,10 @@ module.exports = {
|
||||
plugins: [
|
||||
'typescript',
|
||||
'typescript-operations',
|
||||
'typescript-react-apollo',
|
||||
'typed-document-node',
|
||||
],
|
||||
config: {
|
||||
skipTypename: false,
|
||||
withHooks: true,
|
||||
withHOC: false,
|
||||
withComponent: false,
|
||||
scalars: {
|
||||
DateTime: 'string',
|
||||
UUID: 'string',
|
||||
|
||||
@@ -21,13 +21,10 @@ module.exports = {
|
||||
plugins: [
|
||||
'typescript',
|
||||
'typescript-operations',
|
||||
'typescript-react-apollo',
|
||||
'typed-document-node',
|
||||
],
|
||||
config: {
|
||||
skipTypename: false,
|
||||
withHooks: true,
|
||||
withHOC: false,
|
||||
withComponent: false,
|
||||
scalars: {
|
||||
DateTime: 'string',
|
||||
},
|
||||
|
||||
@@ -24,12 +24,12 @@ const jestConfig = {
|
||||
testEnvironmentOptions: {},
|
||||
|
||||
transformIgnorePatterns: [
|
||||
'/node_modules/(?!(twenty-ui)/.*)',
|
||||
'../../node_modules/(?!(twenty-ui)/.*)',
|
||||
'/node_modules/(?!(twenty-ui|apollo-upload-client|extract-files|is-plain-obj)/.*)',
|
||||
'../../node_modules/(?!(twenty-ui|apollo-upload-client|extract-files|is-plain-obj)/.*)',
|
||||
'../../twenty-ui/',
|
||||
],
|
||||
transform: {
|
||||
'^.+\\.(ts|js|tsx|jsx)$': [
|
||||
'^.+\\.(ts|js|tsx|jsx|mjs)$': [
|
||||
'@swc/jest',
|
||||
{
|
||||
jsc: {
|
||||
@@ -61,8 +61,8 @@ const jestConfig = {
|
||||
extensionsToTreatAsEsm: ['.ts', '.tsx'],
|
||||
coverageThreshold: {
|
||||
global: {
|
||||
statements: 49.1,
|
||||
lines: 47.7,
|
||||
statements: 48.8,
|
||||
lines: 47.5,
|
||||
functions: 39.5,
|
||||
},
|
||||
},
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@ai-sdk/react": "3.0.99",
|
||||
"@apollo/client": "^3.7.17",
|
||||
"@apollo/client": "^4.0.0",
|
||||
"@blocknote/mantine": "^0.47.1",
|
||||
"@blocknote/react": "^0.47.1",
|
||||
"@blocknote/xl-docx-exporter": "^0.47.1",
|
||||
@@ -77,8 +77,8 @@
|
||||
"@types/marked": "^6.0.0",
|
||||
"@xyflow/react": "^12.4.2",
|
||||
"ai": "6.0.97",
|
||||
"apollo-link-rest": "^0.9.0",
|
||||
"apollo-upload-client": "^17.0.0",
|
||||
"apollo-link-rest": "^0.10.0-rc.2",
|
||||
"apollo-upload-client": "^19.0.0",
|
||||
"buffer": "^6.0.3",
|
||||
"cron-parser": "5.1.1",
|
||||
"date-fns": "^2.30.0",
|
||||
@@ -126,7 +126,6 @@
|
||||
"@lingui/vite-plugin": "^5.1.2",
|
||||
"@playwright/test": "^1.56.1",
|
||||
"@tiptap/suggestion": "3.4.2",
|
||||
"@types/apollo-upload-client": "^17.0.2",
|
||||
"@types/file-saver": "^2.0.7",
|
||||
"@types/js-cookie": "^3.0.3",
|
||||
"@types/json-logic-js": "^2",
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,56 @@
|
||||
import { SKELETON_LOADER_HEIGHT_SIZES } from '@/activities/components/SkeletonLoader';
|
||||
import { PageBody } from '@/ui/layout/page/components/PageBody';
|
||||
import { PAGE_BAR_MIN_HEIGHT } from '@/ui/layout/page/constants/PageBarMinHeight';
|
||||
import { styled } from '@linaria/react';
|
||||
import { useContext } from 'react';
|
||||
import Skeleton, { SkeletonTheme } from 'react-loading-skeleton';
|
||||
import { ThemeContext, themeCssVariables } from 'twenty-ui/theme-constants';
|
||||
|
||||
const StyledHeaderSkeleton = styled.div`
|
||||
align-items: center;
|
||||
background: ${themeCssVariables.background.noisy};
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
gap: ${themeCssVariables.spacing[2]};
|
||||
justify-content: space-between;
|
||||
min-height: ${PAGE_BAR_MIN_HEIGHT}px;
|
||||
padding: ${themeCssVariables.spacing[3]};
|
||||
`;
|
||||
|
||||
const StyledHeaderLeft = styled.div`
|
||||
flex: 1;
|
||||
`;
|
||||
|
||||
export const PageContentSkeletonLoader = () => {
|
||||
const { theme } = useContext(ThemeContext);
|
||||
|
||||
return (
|
||||
<>
|
||||
<StyledHeaderSkeleton>
|
||||
<StyledHeaderLeft>
|
||||
<SkeletonTheme
|
||||
baseColor={theme.background.tertiary}
|
||||
highlightColor={theme.background.transparent.lighter}
|
||||
borderRadius={4}
|
||||
>
|
||||
<Skeleton
|
||||
height={SKELETON_LOADER_HEIGHT_SIZES.standard.s}
|
||||
width={104}
|
||||
/>
|
||||
</SkeletonTheme>
|
||||
</StyledHeaderLeft>
|
||||
<SkeletonTheme
|
||||
baseColor={theme.background.tertiary}
|
||||
highlightColor={theme.background.transparent.lighter}
|
||||
borderRadius={4}
|
||||
>
|
||||
<Skeleton
|
||||
width={132}
|
||||
height={SKELETON_LOADER_HEIGHT_SIZES.standard.s}
|
||||
/>
|
||||
</SkeletonTheme>
|
||||
</StyledHeaderSkeleton>
|
||||
<PageBody>{null}</PageBody>
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -1,100 +1,14 @@
|
||||
import { SKELETON_LOADER_HEIGHT_SIZES } from '@/activities/components/SkeletonLoader';
|
||||
import { PageContentSkeletonLoader } from '~/loading/components/PageContentSkeletonLoader';
|
||||
import { styled } from '@linaria/react';
|
||||
import { useContext } from 'react';
|
||||
import Skeleton, { SkeletonTheme } from 'react-loading-skeleton';
|
||||
import {
|
||||
MOBILE_VIEWPORT,
|
||||
ThemeContext,
|
||||
themeCssVariables,
|
||||
} from 'twenty-ui/theme-constants';
|
||||
|
||||
const StyledMainContainer = styled.div`
|
||||
background: ${themeCssVariables.background.noisy};
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
flex: 1 1 auto;
|
||||
flex-direction: row;
|
||||
gap: 8px;
|
||||
min-height: 0;
|
||||
padding-left: 0;
|
||||
width: 100%;
|
||||
|
||||
@media (max-width: ${MOBILE_VIEWPORT}px) {
|
||||
padding-left: 12px;
|
||||
padding-bottom: 0;
|
||||
}
|
||||
`;
|
||||
|
||||
const StyledPanel = styled.div`
|
||||
background: ${themeCssVariables.background.primary};
|
||||
border: 1px solid ${themeCssVariables.border.color.medium};
|
||||
border-radius: ${themeCssVariables.border.radius.md};
|
||||
height: 100%;
|
||||
overflow: auto;
|
||||
width: 100%;
|
||||
`;
|
||||
|
||||
const StyledHeaderContainer = styled.div`
|
||||
flex: 1;
|
||||
`;
|
||||
const StyledRightPanelContainer = styled.div`
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
`;
|
||||
|
||||
const StyledRightPanelFlexContainer = styled.div`
|
||||
align-items: center;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
height: 32px;
|
||||
justify-content: flex-end;
|
||||
margin-bottom: 12px;
|
||||
`;
|
||||
|
||||
const StyledSkeletonHeaderLoader = () => {
|
||||
const { theme } = useContext(ThemeContext);
|
||||
return (
|
||||
<StyledHeaderContainer>
|
||||
<SkeletonTheme
|
||||
baseColor={theme.background.tertiary}
|
||||
highlightColor={theme.background.transparent.lighter}
|
||||
borderRadius={4}
|
||||
>
|
||||
<Skeleton
|
||||
height={SKELETON_LOADER_HEIGHT_SIZES.standard.s}
|
||||
width={104}
|
||||
/>
|
||||
</SkeletonTheme>
|
||||
</StyledHeaderContainer>
|
||||
);
|
||||
};
|
||||
|
||||
const StyledSkeletonAddLoader = () => {
|
||||
const { theme } = useContext(ThemeContext);
|
||||
return (
|
||||
<SkeletonTheme
|
||||
baseColor={theme.background.tertiary}
|
||||
highlightColor={theme.background.transparent.lighter}
|
||||
borderRadius={4}
|
||||
>
|
||||
<Skeleton width={132} height={SKELETON_LOADER_HEIGHT_SIZES.standard.s} />
|
||||
</SkeletonTheme>
|
||||
);
|
||||
};
|
||||
|
||||
const RightPanelSkeleton = () => (
|
||||
<StyledMainContainer>
|
||||
<StyledPanel></StyledPanel>
|
||||
</StyledMainContainer>
|
||||
);
|
||||
|
||||
export const RightPanelSkeletonLoader = () => (
|
||||
<StyledRightPanelContainer>
|
||||
<StyledRightPanelFlexContainer>
|
||||
<StyledSkeletonHeaderLoader />
|
||||
<StyledSkeletonAddLoader />
|
||||
</StyledRightPanelFlexContainer>
|
||||
<RightPanelSkeleton />
|
||||
<PageContentSkeletonLoader />
|
||||
</StyledRightPanelContainer>
|
||||
);
|
||||
|
||||
@@ -13,11 +13,9 @@ const StyledContainer = styled.div`
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
gap: 12px;
|
||||
height: 100dvh;
|
||||
min-width: ${NAVIGATION_DRAWER_CONSTRAINTS.default}px;
|
||||
overflow: hidden;
|
||||
padding: 12px 8px 12px 8px;
|
||||
width: 100%;
|
||||
|
||||
@media (max-width: ${MOBILE_VIEWPORT}px) {
|
||||
@@ -25,6 +23,11 @@ const StyledContainer = styled.div`
|
||||
}
|
||||
`;
|
||||
|
||||
const StyledLeftPanelWrapper = styled.div`
|
||||
flex-shrink: 0;
|
||||
padding: 12px 0 12px 8px;
|
||||
`;
|
||||
|
||||
export const UserOrMetadataLoader = () => {
|
||||
const showAuthModal = useShowAuthModal();
|
||||
|
||||
@@ -36,7 +39,9 @@ export const UserOrMetadataLoader = () => {
|
||||
backdropZIndex={RootStackingContextZIndices.RootModalBackDrop}
|
||||
/>
|
||||
)}
|
||||
<LeftPanelSkeletonLoader />
|
||||
<StyledLeftPanelWrapper>
|
||||
<LeftPanelSkeletonLoader />
|
||||
</StyledLeftPanelWrapper>
|
||||
<RightPanelSkeletonLoader />
|
||||
</StyledContainer>
|
||||
);
|
||||
|
||||
+4
-4
@@ -6,11 +6,11 @@ import {
|
||||
PageDecorator,
|
||||
type PageDecoratorArgs,
|
||||
} from '~/testing/decorators/PageDecorator';
|
||||
import { PrefetchLoadingDecorator } from '~/testing/decorators/PrefetchLoadingDecorator';
|
||||
import { LoadingDecorator } from '~/testing/decorators/LoadingDecorator';
|
||||
import { graphqlMocks } from '~/testing/graphqlMocks';
|
||||
|
||||
const meta: Meta<PageDecoratorArgs> = {
|
||||
title: 'App/Loading/PrefetchLoading',
|
||||
title: 'App/Loading',
|
||||
component: RecordIndexPage,
|
||||
args: {
|
||||
routePath: '/objects/:objectNamePlural',
|
||||
@@ -20,7 +20,7 @@ const meta: Meta<PageDecoratorArgs> = {
|
||||
},
|
||||
parameters: {
|
||||
msw: graphqlMocks,
|
||||
prefetchLoadingSetDelay: 1000,
|
||||
loadingSetDelay: 1000,
|
||||
},
|
||||
tags: ['no-tests'],
|
||||
};
|
||||
@@ -32,7 +32,7 @@ export type Story = StoryObj<typeof RecordIndexPage>;
|
||||
export const Default: Story = {
|
||||
// oxlint-disable-next-line @typescripttypescript/ban-ts-comment
|
||||
// @ts-ignore
|
||||
decorators: [PrefetchLoadingDecorator, PageDecorator],
|
||||
decorators: [LoadingDecorator, PageDecorator],
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import { getOperationName } from '@apollo/client/utilities';
|
||||
import { getOperationName } from '~/utils/getOperationName';
|
||||
import { type Meta, type StoryObj } from '@storybook/react-vite';
|
||||
import { HttpResponse, graphql, http } from 'msw';
|
||||
import { expect, within } from 'storybook/test';
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user