Skip to content

The open alternative to Salesforce, designed for AI.

Add Front components to SDK (#17259)

Charles Bochet29c0c952e70b
diff --git a/packages/create-twenty-app/README.md b/packages/create-twenty-app/README.md
index 3533dd42433..bdc0f6b6a99 100644
--- a/packages/create-twenty-app/README.md
+++ b/packages/create-twenty-app/README.md
@@ -35,7 +35,7 @@ yarn run help
yarn auth:login
# Add a new entity to your application (guided)
-yarn app:add
+yarn entity:add
# Generate a typed Twenty client and workspace entity types
yarn app:generate
@@ -60,7 +60,7 @@ yarn app:uninstall
- Example placeholders to help you add entities, actions, and sync logic
## Next steps
-- Explore the generated project and add your first entity with `yarn app:add`.
+- Explore the generated project and add your first entity with `yarn entity:add`.
- Keep your types up‑to‑date using `yarn app:generate`.
- Use `yarn app:dev` while you iterate to see changes instantly in your workspace.
diff --git a/packages/create-twenty-app/src/constants/base-application/README.md b/packages/create-twenty-app/src/constants/base-application/README.md
index 08c036ac602..e35357e492f 100644
--- a/packages/create-twenty-app/src/constants/base-application/README.md
+++ b/packages/create-twenty-app/src/constants/base-application/README.md
@@ -33,7 +33,7 @@ yarn auth:status # Check auth status
# Application
yarn app:dev # Start dev mode (sync + watch)
yarn app:sync # One-time sync
-yarn app:add # Add a new entity (function, object, role)
+yarn entity:add # Add a new entity (function, object, role)
yarn app:generate # Generate typed Twenty client
yarn app:logs # Stream function logs
yarn app:uninstall # Uninstall app from workspace
diff --git a/packages/create-twenty-app/src/constants/base-application/tsconfig.json b/packages/create-twenty-app/src/constants/base-application/tsconfig.json
index fb063259479..07fd3e1d2d6 100644
--- a/packages/create-twenty-app/src/constants/base-application/tsconfig.json
+++ b/packages/create-twenty-app/src/constants/base-application/tsconfig.json
@@ -5,6 +5,7 @@
"declaration": true,
"outDir": "./dist",
"rootDir": ".",
+ "jsx": "react-jsx",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"emitDecoratorMetadata": true,
diff --git a/packages/create-twenty-app/src/utils/app-template.ts b/packages/create-twenty-app/src/utils/app-template.ts
index 8251a8ca5a3..ad059419185 100644
--- a/packages/create-twenty-app/src/utils/app-template.ts
+++ b/packages/create-twenty-app/src/utils/app-template.ts
@@ -32,6 +32,10 @@ export const copyBaseApplicationProject = async ({
appDirectory: appFolderPath,
});
+ await createDefaultFrontComponent({
+ appDirectory: appFolderPath,
+ });
+
await createApplicationConfig({
displayName: appDisplayName,
description: appDescription,
@@ -115,6 +119,38 @@ export default defineRole({
await fs.writeFile(join(appDirectory, 'default-function.role.ts'), content);
};
+const createDefaultFrontComponent = async ({
+ appDirectory,
+}: {
+ appDirectory: string;
+}) => {
+ const universalIdentifier = v4();
+
+ const content = `import { defineFrontComponent } from 'twenty-sdk';
+
+export const HelloWorld = () => {
+ return (
+ <div style={{ padding: '20px', fontFamily: 'sans-serif' }}>
+ <h1>Hello, World!</h1>
+ <p>This is your first front component.</p>
+ </div>
+ );
+};
+
+export default defineFrontComponent({
+ universalIdentifier: '${universalIdentifier}',
+ name: 'hello-world',
+ description: 'A sample front component',
+ component: HelloWorld,
+});
+`;
+
+ await fs.writeFile(
+ join(appDirectory, 'hello-world.front-component.tsx'),
+ content,
+ );
+};
+
const createApplicationConfig = async ({
displayName,
description,
@@ -161,7 +197,7 @@ const createPackageJson = async ({
'auth:status': 'twenty auth:status',
'app:dev': 'twenty app:dev',
'app:sync': 'twenty app:sync',
- 'app:add': 'twenty app:add',
+ 'entity:add': 'twenty entity:add',
'app:generate': 'twenty app:generate',
'app:logs': 'twenty app:logs',
'app:uninstall': 'twenty app:uninstall',
@@ -175,6 +211,8 @@ const createPackageJson = async ({
devDependencies: {
typescript: '^5.9.3',
'@types/node': '^24.7.2',
+ '@types/react': '^19.0.2',
+ react: '^19.0.2',
eslint: '^9.32.0',
'typescript-eslint': '^8.50.0',
},
diff --git a/packages/twenty-sdk/README.md b/packages/twenty-sdk/README.md
index 8b87904f3a0..7015d0f30b7 100644
--- a/packages/twenty-sdk/README.md
+++ b/packages/twenty-sdk/README.md
@@ -102,7 +102,7 @@ Application development commands.
- `twenty app:uninstall [appPath]` — Uninstall the application from the current workspace.
- Note: `twenty app:delete` exists as a hidden alias for backward compatibility.
-- `twenty app:add [entityType]` — Add a new entity to your application.
+- `twenty entity:add [entityType]` — Add a new entity to your application.
- Arguments:
- `entityType`: one of `function` or `object`. If omitted, an interactive prompt is shown.
- Options:
@@ -134,7 +134,7 @@ twenty app:dev --debounce 1500
twenty app:sync
# Add a new object interactively
-twenty app:add
+twenty entity:add
# Generate client types
twenty app:generate
diff --git a/packages/twenty-sdk/package.json b/packages/twenty-sdk/package.json
index 6da9601ec5b..1a622e404ac 100644
--- a/packages/twenty-sdk/package.json
+++ b/packages/twenty-sdk/package.json
@@ -64,6 +64,7 @@
"@types/lodash.kebabcase": "^4.1.7",
"@types/lodash.startcase": "^4",
"@types/node": "^24.0.0",
+ "@types/react": "^19.0.2",
"jest": "^29.5.0",
"tsx": "^4.7.0",
"vite-plugin-dts": "^4.5.4",
diff --git a/packages/twenty-sdk/src/application/__tests__/define-front-component.spec.ts b/packages/twenty-sdk/src/application/__tests__/define-front-component.spec.ts
new file mode 100644
index 00000000000..a869eff263b
--- /dev/null
+++ b/packages/twenty-sdk/src/application/__tests__/define-front-component.spec.ts
@@ -0,0 +1,74 @@
+import { defineFrontComponent } from '../front-components/define-front-component';
+
+// Mock component for testing
+const MockComponent = () => null;
+
+describe('defineFrontComponent', () => {
+ const validConfig = {
+ universalIdentifier: 'e56d363b-0bdc-4d8a-a393-6f0d1c75bdcf',
+ name: 'My Component',
+ component: MockComponent,
+ };
+
+ it('should return the config when valid', () => {
+ const result = defineFrontComponent(validConfig);
+
+ expect(result).toEqual(validConfig);
+ });
+
+ it('should pass through optional fields', () => {
+ const config = {
+ ...validConfig,
+ description: 'A sample front component',
+ };
+
+ const result = defineFrontComponent(config);
+
+ expect(result.description).toBe('A sample front component');
+ });
+
+ it('should throw error when universalIdentifier is missing', () => {
+ const config = {
+ name: 'My Component',
+ component: MockComponent,
+ };
+
+ expect(() => defineFrontComponent(config as any)).toThrow(
+ 'FrontComponent must have a universalIdentifier',
+ );
+ });
+
+ it('should throw error when component is missing', () => {
+ const config = {
+ universalIdentifier: 'e56d363b-0bdc-4d8a-a393-6f0d1c75bdcf',
+ name: 'My Component',
+ };
+
+ expect(() => defineFrontComponent(config as any)).toThrow(
+ 'FrontComponent must have a component',
+ );
+ });
+
+ it('should throw error when component is not a function', () => {
+ const config = {
+ universalIdentifier: 'e56d363b-0bdc-4d8a-a393-6f0d1c75bdcf',
+ name: 'My Component',
+ component: 'not-a-function',
+ };
+
+ expect(() => defineFrontComponent(config as any)).toThrow(
+ 'FrontComponent must have a component',
+ );
+ });
+
+ it('should accept config without name', () => {
+ const config = {
+ universalIdentifier: 'e56d363b-0bdc-4d8a-a393-6f0d1c75bdcf',
+ component: MockComponent,
+ };
+
+ const result = defineFrontComponent(config as any);
+
+ expect(result.name).toBeUndefined();
+ });
+});
diff --git a/packages/twenty-sdk/src/application/front-components/define-front-component.ts b/packages/twenty-sdk/src/application/front-components/define-front-component.ts
new file mode 100644
index 00000000000..ed78a74c480
--- /dev/null
+++ b/packages/twenty-sdk/src/application/front-components/define-front-component.ts
@@ -0,0 +1,34 @@
+import { type FrontComponentConfig } from './front-component-config';
+
+/**
+ * Define a front component configuration with validation.
+ *
+ * @example
+ * ```typescript
+ * import { defineFrontComponent } from 'twenty-sdk';
+ *
+ * const MyComponent = () => {
+ * return <div>Hello World</div>;
+ * };
+ *
+ * export default defineFrontComponent({
+ * universalIdentifier: 'e56d363b-0bdc-4d8a-a393-6f0d1c75bdcf',
+ * name: 'My Component',
+ * description: 'A sample front component',
+ * component: MyComponent,
+ * });
+ * ```
+ */
+export const defineFrontComponent = <T extends FrontComponentConfig>(
+ config: T,
+): T => {
+ if (!config.universalIdentifier) {
+ throw new Error('FrontComponent must have a universalIdentifier');
+ }
+
+ if (typeof config.component !== 'function') {
+ throw new Error('FrontComponent must have a component');
+ }
+
+ return config;
+};
diff --git a/packages/twenty-sdk/src/application/front-components/front-component-config.ts b/packages/twenty-sdk/src/application/front-components/front-component-config.ts
new file mode 100644
index 00000000000..bda230b08b7
--- /dev/null
+++ b/packages/twenty-sdk/src/application/front-components/front-component-config.ts
@@ -0,0 +1,12 @@
+import { type FrontComponentManifest } from 'twenty-shared/application';
+
+export type FrontComponentType = React.ComponentType<any>;
+
+export type FrontComponentConfig = Omit<
+ FrontComponentManifest,
+ 'componentPath' | 'componentName'
+> & {
+ name?: string;
+ description?: string;
+ component: FrontComponentType;
+};
diff --git a/packages/twenty-sdk/src/application/index.ts b/packages/twenty-sdk/src/application/index.ts
index ae97f15dd37..512b2c85b05 100644
--- a/packages/twenty-sdk/src/application/index.ts
+++ b/packages/twenty-sdk/src/application/index.ts
@@ -24,6 +24,11 @@ export { Field } from './fields/field.decorator';
export { OnDeleteAction } from './fields/on-delete-action';
export { RelationType } from './fields/relation-type';
export { Relation } from './fields/relation.decorator';
+export { defineFrontComponent } from './front-components/define-front-component';
+export type {
+ FrontComponentType,
+ FrontComponentConfig,
+} from './front-components/front-component-config';
export { defineFunction } from './functions/define-function';
export type {
FunctionHandler,
diff --git a/packages/twenty-sdk/src/cli/__tests__/test-app/src/app/test.front-component.tsx b/packages/twenty-sdk/src/cli/__tests__/test-app/src/app/test.front-component.tsx
new file mode 100644
index 00000000000..2c584d4be04
--- /dev/null
+++ b/packages/twenty-sdk/src/cli/__tests__/test-app/src/app/test.front-component.tsx
@@ -0,0 +1,16 @@
+import { defineFrontComponent } from '@/application/front-components/define-front-component';
+
+export const TestComponent = () => {
+ return (
+ <div style={{ padding: '20px' }}>
+ <h1>Test Component</h1>
+ </div>
+ );
+};
+
+export default defineFrontComponent({
+ universalIdentifier: 'f1234567-abcd-4000-8000-000000000001',
+ name: 'test-component',
+ description: 'A test front component',
+ component: TestComponent,
+});
diff --git a/packages/twenty-sdk/src/cli/commands/app.command.ts b/packages/twenty-sdk/src/cli/commands/app.command.ts
index cb8cd04b8c7..f6d816ee22e 100644
--- a/packages/twenty-sdk/src/cli/commands/app.command.ts
+++ b/packages/twenty-sdk/src/cli/commands/app.command.ts
@@ -132,7 +132,7 @@ export const registerCommands = (program: Command): void => {
});
program
- .command('app:add [entityType]')
+ .command('entity:add [entityType]')
.option('--path <path>', 'Path in which the entity should be created.')
.description(
`Add a new entity to your application (${Object.values(SyncableEntity).join('|')})`,
diff --git a/packages/twenty-sdk/src/cli/commands/entity/entity-add.ts b/packages/twenty-sdk/src/cli/commands/entity/entity-add.ts
index b12e117259a..091f4a405de 100644
--- a/packages/twenty-sdk/src/cli/commands/entity/entity-add.ts
+++ b/packages/twenty-sdk/src/cli/commands/entity/entity-add.ts
@@ -1,4 +1,5 @@
import { CURRENT_EXECUTION_DIRECTORY } from '@/cli/utilities/config/constants/current-execution-directory';
+import { getFrontComponentBaseFile } from '@/cli/utilities/entity/utils/entity-front-component-template';
import { getFunctionBaseFile } from '@/cli/utilities/entity/utils/entity-function-template';
import { convertToLabel } from '@/cli/utilities/entity/utils/entity-label';
import { getNewObjectFileContent } from '@/cli/utilities/entity/utils/entity-object-template';
@@ -16,6 +17,7 @@ export enum SyncableEntity {
AGENT = 'agent',
OBJECT = 'object',
FUNCTION = 'function',
+ FRONT_COMPONENT = 'front-component',
ROLE = 'role',
}
@@ -82,6 +84,28 @@ export class EntityAddCommand {
return;
}
+ if (entity === SyncableEntity.FRONT_COMPONENT) {
+ const entityName = await this.getEntityName(entity);
+
+ // Use *.front-component.tsx naming convention
+ const frontComponentFileName = `${kebabcase(entityName)}.front-component.tsx`;
+
+ const decoratedFrontComponent = getFrontComponentBaseFile({
+ name: entityName,
+ });
+
+ const filePath = join(appPath, frontComponentFileName);
+
+ await fs.writeFile(filePath, decoratedFrontComponent);
+
+ console.log(
+ chalk.green(`✓ Created front component:`),
+ chalk.cyan(filePath.replace(CURRENT_EXECUTION_DIRECTORY + '/', '')),
+ );
+
+ return;
+ }
+
if (entity === SyncableEntity.ROLE) {
const entityName = await this.getEntityName(entity);
@@ -119,7 +143,12 @@ export class EntityAddCommand {
name: 'entity',
message: `What entity do you want to create?`,
default: '',
- choices: [SyncableEntity.FUNCTION, SyncableEntity.OBJECT, SyncableEntity.ROLE],
+ choices: [
+ SyncableEntity.FUNCTION,
+ SyncableEntity.FRONT_COMPONENT,
+ SyncableEntity.OBJECT,
+ SyncableEntity.ROLE,
+ ],
},
]);
diff --git a/packages/twenty-sdk/src/cli/utilities/entity/utils/__tests__/get-front-component-base-file.spec.ts b/packages/twenty-sdk/src/cli/utilities/entity/utils/__tests__/get-front-component-base-file.spec.ts
new file mode 100644
index 00000000000..05984e693c3
--- /dev/null
+++ b/packages/twenty-sdk/src/cli/utilities/entity/utils/__tests__/get-front-component-base-file.spec.ts
@@ -0,0 +1,55 @@
+import { getFrontComponentBaseFile } from '@/cli/utilities/entity/utils/entity-front-component-template';
+
+describe('getFrontComponentBaseFile', () => {
+ it('should render proper file using defineFrontComponent', () => {
+ const result = getFrontComponentBaseFile({
+ name: 'my-component',
+ universalIdentifier: '71e45a58-41da-4ae4-8b73-a543c0a9d3d4',
+ });
+
+ expect(result).toContain(
+ "import { defineFrontComponent } from 'twenty-sdk'",
+ );
+ expect(result).toContain('export default defineFrontComponent({');
+
+ expect(result).toContain(
+ "universalIdentifier: '71e45a58-41da-4ae4-8b73-a543c0a9d3d4'",
+ );
+ expect(result).toContain("name: 'my-component'");
+ expect(result).toContain('component: HelloWorld,');
+
+ expect(result).toContain('export const HelloWorld = () => {');
+
+ expect(result).toContain(
+ "description: 'Add a description for your front component'",
+ );
+ });
+
+ it('should generate unique UUID when not provided', () => {
+ const result = getFrontComponentBaseFile({
+ name: 'auto-uuid-component',
+ });
+
+ expect(result).toMatch(
+ /universalIdentifier: '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'/,
+ );
+ });
+
+ it('should use kebab-case for component name', () => {
+ const result = getFrontComponentBaseFile({
+ name: 'my-awesome-component',
+ });
+
+ expect(result).toContain("name: 'my-awesome-component'");
+ });
+
+ it('should include JSX in the component', () => {
+ const result = getFrontComponentBaseFile({
+ name: 'example-component',
+ });
+
+ expect(result).toContain('<div');
+ expect(result).toContain('<h1>Hello, World!</h1>');
+ expect(result).toContain('</div>');
+ });
+});
diff --git a/packages/twenty-sdk/src/cli/utilities/entity/utils/entity-front-component-template.ts b/packages/twenty-sdk/src/cli/utilities/entity/utils/entity-front-component-template.ts
new file mode 100644
index 00000000000..b872db8bdea
--- /dev/null
+++ b/packages/twenty-sdk/src/cli/utilities/entity/utils/entity-front-component-template.ts
@@ -0,0 +1,32 @@
+import kebabCase from 'lodash.kebabcase';
+import { v4 } from 'uuid';
+
+export const getFrontComponentBaseFile = ({
+ name,
+ universalIdentifier = v4(),
+}: {
+ name: string;
+ universalIdentifier?: string;
+}) => {
+ const kebabCaseName = kebabCase(name);
+
+ return `import { defineFrontComponent } from 'twenty-sdk';
+
+// React component - implement your UI here
+export const HelloWorld = () => {
+ return (
+ <div style={{ padding: '20px', fontFamily: 'sans-serif' }}>
+ <h1>Hello, World!</h1>
+ <p>This is your front component: ${kebabCaseName}</p>
+ </div>
+ );
+};
+
+export default defineFrontComponent({
+ universalIdentifier: '${universalIdentifier}',
+ name: '${kebabCaseName}',
+ description: 'Add a description for your front component',
+ component: HelloWorld,
+});
+`;
+};
diff --git a/packages/twenty-sdk/src/cli/utilities/file/utils/file-config-loader.ts b/packages/twenty-sdk/src/cli/utilities/file/utils/file-config-loader.ts
index 0382117b5f4..d5c731d7fb5 100644
--- a/packages/twenty-sdk/src/cli/utilities/file/utils/file-config-loader.ts
+++ b/packages/twenty-sdk/src/cli/utilities/file/utils/file-config-loader.ts
@@ -1,13 +1,21 @@
-import { createJiti } from 'jiti';
+import type { FrontComponentConfig, FunctionConfig } from '@/application';
import * as fs from 'fs-extra';
+import { createJiti } from 'jiti';
+import { type JitiOptions } from 'jiti/lib/types';
import path from 'path';
+import {
+ type FrontComponentManifest,
+ type ServerlessFunctionManifest,
+} from 'twenty-shared/application';
import { fileURLToPath } from 'url';
import { parseJsoncFile } from './file-jsonc';
-/**
- * Read tsconfig.json paths and convert them to jiti aliases.
- * Handles patterns like "generated/*": ["./generated/*"]
- */
+type ExtractOptions = {
+ propertyName: string;
+ entityType: string;
+ jsx?: boolean;
+};
+
const getTsconfigAliases = async (
appPath: string,
): Promise<Record<string, string>> => {
@@ -33,11 +41,8 @@ const getTsconfigAliases = async (
for (const [pattern, targets] of Object.entries(paths)) {
if (targets.length === 0) continue;
- // Remove trailing /* from pattern and target
const aliasKey = pattern.replace(/\/\*$/, '');
const targetPath = targets[0].replace(/\/\*$/, '');
-
- // Resolve the target path relative to baseUrl and appPath
const resolvedTarget = path.resolve(appPath, baseUrl, targetPath);
aliases[aliasKey] = resolvedTarget;
}
@@ -48,61 +53,46 @@ const getTsconfigAliases = async (
}
};
-/**
- * Create a jiti instance for loading TypeScript config files.
- * When appPath is provided, jiti will use the app's tsconfig.json for path resolution.
- */
-const createConfigLoader = async (appPath?: string) => {
+const createConfigLoader = async (
+ appPath?: string,
+ options: { jsx?: boolean } = {},
+) => {
const basePath = appPath ?? fileURLToPath(import.meta.url);
- const options: {
- moduleCache?: boolean;
- fsCache?: boolean;
- interopDefault?: boolean;
- alias?: Record<string, string>;
- } = {
- moduleCache: false, // Don't cache during dev for hot reload
+ const jitiOptions: JitiOptions = {
+ moduleCache: false,
fsCache: false,
interopDefault: true,
};
- // If appPath is provided, read tsconfig.json and set up aliases
+ if (options.jsx) {
+ jitiOptions.jsx = { runtime: 'automatic' };
+ }
+
if (appPath) {
const aliases = await getTsconfigAliases(appPath);
if (Object.keys(aliases).length > 0) {
- options.alias = aliases;
+ jitiOptions.alias = aliases;
}
}
- return createJiti(basePath, options);
+ return createJiti(basePath, jitiOptions);
};
-/**
- * Find the first valid config export from a module.
- * Priority:
- * 1. default export
- * 2. first named export that is a plain object (not a function, class, or primitive)
- */
const findConfigExport = <T>(
mod: Record<string, unknown>,
validator?: (value: unknown) => boolean,
): T | undefined => {
- // Priority 1: default export
if (mod.default !== undefined) {
if (!validator || validator(mod.default)) {
return mod.default as T;
}
}
- // Priority 2: first named export that passes validation (or is a plain object)
for (const [key, value] of Object.entries(mod)) {
if (key === 'default') continue;
if (value === undefined || value === null) continue;
-
- // Skip functions, classes, and primitives - we want config objects
if (typeof value !== 'object') continue;
-
- // Skip arrays
if (Array.isArray(value)) continue;
if (!validator || validator(value)) {
@@ -113,22 +103,6 @@ const findConfigExport = <T>(
return undefined;
};
-/**
- * Load a TypeScript config file using jiti runtime evaluation.
- * This allows importing constants and other modules in config files.
- *
- * Supports multiple export patterns:
- * - `export default { ... }`
- * - `export const anyName = { ... }` (any named export that is a plain object)
- *
- * @param filepath - Absolute path to the config file
- * @param appPath - Optional app path for tsconfig.json path resolution
- *
- * @example
- * ```typescript
- * const config = await loadConfig<AppDefinition>('/path/to/src/app/application.config.ts', '/path/to/app');
- * ```
- */
export const loadConfig = async <T>(
filepath: string,
appPath?: string,
@@ -137,7 +111,6 @@ export const loadConfig = async <T>(
try {
const mod = (await jiti.import(filepath)) as Record<string, unknown>;
-
const config = findConfigExport<T>(mod);
if (!config) {
@@ -157,39 +130,25 @@ export const loadConfig = async <T>(
}
};
-/**
- * Escape special regex characters in a string.
- */
const escapeRegExp = (string: string): string => {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
};
-/**
- * Extract the import path for a given identifier from source code.
- * Returns null if the identifier is not imported (i.e., defined locally).
- */
const extractImportPath = (
source: string,
identifier: string,
filepath: string,
appPath: string,
): string | null => {
- // Escape special regex characters in the identifier (e.g., $ in function names like $handler)
const escapedIdentifier = escapeRegExp(identifier);
- // Match: import { identifier } from 'path'
- // Match: import { original as identifier } from 'path'
- // Match: import identifier from 'path' (default import)
const patterns = [
- // Named import: import { foo } from 'path' or import { foo, bar } from 'path'
new RegExp(
`import\\s*\\{[^}]*\\b${escapedIdentifier}\\b[^}]*\\}\\s*from\\s*['"]([^'"]+)['"]`,
),
- // Aliased import: import { original as foo } from 'path'
new RegExp(
`import\\s*\\{[^}]*\\w+\\s+as\\s+${escapedIdentifier}[^}]*\\}\\s*from\\s*['"]([^'"]+)['"]`,
),
- // Default import: import foo from 'path'
new RegExp(`import\\s+${escapedIdentifier}\\s+from\\s*['"]([^'"]+)['"]`),
];
@@ -198,12 +157,10 @@ const extractImportPath = (
if (match) {
const importPath = match[1];
- // Resolve relative to the function file, then make relative to appPath
const fileDir = path.dirname(filepath);
const absolutePath = path.resolve(fileDir, importPath);
const relativePath = path.relative(appPath, absolutePath);
- // Add .ts extension if not present
const resultPath = relativePath.endsWith('.ts')
? relativePath
: `${relativePath}.ts`;
@@ -212,94 +169,101 @@ const extractImportPath = (
}
}
- // Handler is defined locally, not imported
return null;
};
-/**
- * Load a function module and extract handler info from config.handler property.
- *
- * The handler can be either:
- * 1. Imported from another file:
- * ```typescript
- * import { myHandler } from '../src/handlers/my-handler';
- * export const config = { handler: myHandler, ... };
- * ```
- *
- * 2. Defined locally in the same file:
- * ```typescript
- * export const myHandler = async () => { ... };
- * export const config = { handler: myHandler, ... };
- * ```
- *
- * @example
- * ```typescript
- * const { config, handlerName, handlerPath } = await loadFunctionModule(
- * '/path/to/src/app/functions/my-function.function.ts',
- * '/path/to/app'
- * );
- * ```
- */
-export const loadFunctionModule = async (
+const extractConfigFromFile = async <T extends Record<string, unknown>>(
filepath: string,
appPath: string,
-): Promise<{
- config: unknown;
- handlerName: string;
- handlerPath: string;
-}> => {
- const jiti = await createConfigLoader(appPath);
+ options: ExtractOptions,
+): Promise<{ config: T; entryName: string; entryPath: string }> => {
+ const { propertyName, entityType, jsx } = options;
+ const jiti = await createConfigLoader(appPath, { jsx });
try {
const mod = (await jiti.import(filepath)) as Record<string, unknown>;
- // Find config with a handler property
- const hasHandler = (value: unknown): boolean => {
+ const hasProperty = (value: unknown): boolean => {
return (
typeof value === 'object' &&
value !== null &&
- 'handler' in value &&
- typeof (value as { handler: unknown }).handler === 'function'
+ propertyName in value &&
+ typeof (value as Record<string, unknown>)[propertyName] === 'function'
);
};
- const config = findConfigExport<{ handler: Function }>(mod, hasHandler);
+ const config = findConfigExport<T & Record<string, Function>>(
+ mod,
+ hasProperty,
+ );
if (!config) {
throw new Error(
- `Function file ${filepath} must export a config object with a "handler" property`,
+ `${entityType} file ${filepath} must export a config object with a "${propertyName}" property`,
);
}
- // Get handler name from the function's name property
- const handlerName = config.handler.name;
+ const entryName = config[propertyName].name;
- if (!handlerName) {
+ if (!entryName) {
throw new Error(
- `Handler function in ${filepath} must be a named function`,
+ `${propertyName} function in ${filepath} must be a named function`,
);
}
- // Parse source to find where the handler is imported from
const source = await fs.readFile(filepath, 'utf8');
- const importPath = extractImportPath(
- source,
- handlerName,
- filepath,
- appPath,
- );
-
- // If handler is imported, use the import path; otherwise use the function file itself
- const handlerPath =
+ const importPath = extractImportPath(source, entryName, filepath, appPath);
+ const entryPath =
importPath ?? path.relative(appPath, filepath).replace(/\\/g, '/');
- return { config, handlerName, handlerPath };
+ return { config, entryName, entryPath };
} catch (error) {
if (error instanceof Error) {
throw new Error(
- `Failed to load function module from ${filepath}: ${error.message}`,
+ `Failed to load ${entityType.toLowerCase()} module from ${filepath}: ${error.message}`,
);
}
throw error;
}
};
+
+export const extractFunctionConfig = async (
+ filepath: string,
+ appPath: string,
+): Promise<ServerlessFunctionManifest> => {
+ const { config, entryName, entryPath } =
+ await extractConfigFromFile<FunctionConfig>(filepath, appPath, {
+ propertyName: 'handler',
+ entityType: 'Function',
+ });
+
+ return {
+ universalIdentifier: config.universalIdentifier,
+ name: config.name,
+ description: config.description,
+ timeoutSeconds: config.timeoutSeconds,
+ triggers: config.triggers ?? [],
+ handlerName: entryName,
+ handlerPath: entryPath,
+ };
+};
+
+export const extractFrontComponentConfig = async (
+ filepath: string,
+ appPath: string,
+): Promise<FrontComponentManifest> => {
+ const { config, entryName, entryPath } =
+ await extractConfigFromFile<FrontComponentConfig>(filepath, appPath, {
+ propertyName: 'component',
+ entityType: 'Front component',
+ jsx: true,
+ });
+
+ return {
+ universalIdentifier: config.universalIdentifier,
+ name: config.name,
+ description: config.description,
+ componentName: entryName,
+ componentPath: entryPath,
+ };
+};
diff --git a/packages/twenty-sdk/src/cli/utilities/manifest/utils/manifest-build.ts b/packages/twenty-sdk/src/cli/utilities/manifest/utils/manifest-build.ts
index 7bf82576658..95cb45415e9 100644
--- a/packages/twenty-sdk/src/cli/utilities/manifest/utils/manifest-build.ts
+++ b/packages/twenty-sdk/src/cli/utilities/manifest/utils/manifest-build.ts
@@ -1,6 +1,9 @@
-import { type FunctionConfig } from '@/application/functions/function-config';
import { type RoleConfig } from '@/application/role-config';
-import { loadConfig, loadFunctionModule } from '@/cli/utilities/file/utils/file-config-loader';
+import {
+ extractFrontComponentConfig,
+ extractFunctionConfig,
+ loadConfig,
+} from '@/cli/utilities/file/utils/file-config-loader';
import { findPathFile } from '@/cli/utilities/file/utils/file-find';
import { parseJsoncFile, parseTextFile } from '@/cli/utilities/file/utils/file-jsonc';
import { glob } from 'fast-glob';
@@ -9,6 +12,7 @@ import path, { posix, relative, sep } from 'path';
import {
type Application,
type ApplicationManifest,
+ type FrontComponentManifest,
type ObjectExtensionManifest,
type ObjectManifest,
type PackageJson,
@@ -113,9 +117,6 @@ const loadObjectExtensions = async (
return extensions;
};
-/**
- * Load all function definitions from src/app/ (any *.function.ts file).
- */
const loadFunctions = async (
appPath: string,
): Promise<ServerlessFunctionManifest[]> => {
@@ -125,23 +126,7 @@ const loadFunctions = async (
for (const filepath of functionFiles) {
try {
- const { config, handlerName, handlerPath } = await loadFunctionModule(
- filepath,
- appPath,
- );
- const fnConfig = config as FunctionConfig;
-
- const manifest: ServerlessFunctionManifest = {
- universalIdentifier: fnConfig.universalIdentifier,
- name: fnConfig.name,
- description: fnConfig.description,
- timeoutSeconds: fnConfig.timeoutSeconds,
- triggers: fnConfig.triggers ?? [],
- handlerPath,
- handlerName,
- };
-
- functions.push(manifest);
+ functions.push(await extractFunctionConfig(filepath, appPath));
} catch (error) {
const relPath = toPosixRelative(filepath, appPath);
throw new Error(
@@ -176,6 +161,30 @@ const loadRoles = async (appPath: string): Promise<RoleManifest[]> => {
return roles;
};
+const loadFrontComponents = async (
+ appPath: string,
+): Promise<FrontComponentManifest[]> => {
+ const componentFiles = await loadFiles(
+ ['src/app/**/*.front-component.tsx'],
+ appPath,
+ );
+
+ const components: FrontComponentManifest[] = [];
+
+ for (const filepath of componentFiles) {
+ try {
+ components.push(await extractFrontComponentConfig(filepath, appPath));
+ } catch (error) {
+ const relPath = toPosixRelative(filepath, appPath);
+ throw new Error(
+ `Failed to load front component from ${relPath}: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+ }
+
+ return components;
+};
+
/**
* Build a nested object structure from all TypeScript source files.
*/
@@ -276,6 +285,7 @@ export const buildManifest = async (
objects,
objectExtensions,
serverlessFunctions,
+ frontComponents,
roles,
sources,
shouldGenerate,
@@ -283,6 +293,7 @@ export const buildManifest = async (
loadObjects(appPath),
loadObjectExtensions(appPath),
loadFunctions(appPath),
+ loadFrontComponents(appPath),
loadRoles(appPath),
loadSources(appPath),
checkShouldGenerate(appPath),
@@ -295,6 +306,7 @@ export const buildManifest = async (
objectExtensions:
objectExtensions.length > 0 ? objectExtensions : undefined,
serverlessFunctions,
+ frontComponents: frontComponents.length > 0 ? frontComponents : undefined,
roles,
sources,
};
@@ -305,6 +317,7 @@ export const buildManifest = async (
objects,
objectExtensions,
serverlessFunctions,
+ frontComponents,
roles,
});
diff --git a/packages/twenty-sdk/src/cli/utilities/manifest/utils/manifest-display.ts b/packages/twenty-sdk/src/cli/utilities/manifest/utils/manifest-display.ts
index e5eb63ddcd8..1233ffa4b51 100644
--- a/packages/twenty-sdk/src/cli/utilities/manifest/utils/manifest-display.ts
+++ b/packages/twenty-sdk/src/cli/utilities/manifest/utils/manifest-display.ts
@@ -12,6 +12,11 @@ export const displayEntitySummary = (manifest: ApplicationManifest): void => {
console.log(
chalk.green(` ✓ Found ${manifest.serverlessFunctions.length} function(s)`),
);
+ console.log(
+ chalk.green(
+ ` ✓ Found ${manifest.frontComponents?.length ?? 0} front component(s)`,
+ ),
+ );
console.log(
chalk.green(` ✓ Found ${manifest.roles?.length ?? 'no'} role(s)`),
);
diff --git a/packages/twenty-sdk/src/cli/utilities/manifest/utils/manifest-validate.ts b/packages/twenty-sdk/src/cli/utilities/manifest/utils/manifest-validate.ts
index 5b771408c4a..7ff887fa5bd 100644
--- a/packages/twenty-sdk/src/cli/utilities/manifest/utils/manifest-validate.ts
+++ b/packages/twenty-sdk/src/cli/utilities/manifest/utils/manifest-validate.ts
@@ -1,5 +1,6 @@
import {
type ApplicationManifest,
+ type FrontComponentManifest,
type ServerlessFunctionManifest,
type ObjectExtensionManifest,
type ObjectManifest,
@@ -107,6 +108,16 @@ const collectAllIds = (
}
}
+ // Front Components
+ for (const component of manifest.frontComponents ?? []) {
+ if (component.universalIdentifier) {
+ ids.push({
+ id: component.universalIdentifier,
+ location: `front-components/${component.name ?? component.componentName}`,
+ });
+ }
+ }
+
return ids;
};
@@ -410,6 +421,25 @@ const validateRoles = (
}
};
+/**
+ * Validate front components.
+ */
+const validateFrontComponents = (
+ components: FrontComponentManifest[],
+ errors: ValidationError[],
+): void => {
+ for (const component of components) {
+ const componentPath = `front-components/${component.name ?? component.componentName ?? 'unknown'}`;
+
+ if (!component.universalIdentifier) {
+ errors.push({
+ path: componentPath,
+ message: 'Front component must have a universalIdentifier',
+ });
+ }
+ }
+};
+
/**
* Validate a complete application manifest.
*/
@@ -434,6 +464,9 @@ export const validateManifest = (
// Validate roles
validateRoles(manifest.roles ?? [], errors);
+ // Validate front components
+ validateFrontComponents(manifest.frontComponents ?? [], errors);
+
// Check for duplicate universalIdentifiers
const allIds = collectAllIds(manifest);
const duplicates = findDuplicates(allIds);
diff --git a/packages/twenty-sdk/src/cli/utilities/vite/manifest-plugin.ts b/packages/twenty-sdk/src/cli/utilities/vite/manifest-plugin.ts
index c7a9508458a..56a5ebe5a81 100644
--- a/packages/twenty-sdk/src/cli/utilities/vite/manifest-plugin.ts
+++ b/packages/twenty-sdk/src/cli/utilities/vite/manifest-plugin.ts
@@ -34,7 +34,7 @@ export const createManifestPlugin = (
callbacks: ManifestPluginCallbacks = {},
): Plugin => {
const isRelevantFile = (file: string): boolean => {
- return ['.ts', '.json'].some((ext) => file.endsWith(ext));
+ return ['.ts', '.tsx', '.json'].some((ext) => file.endsWith(ext));
};
return {
@@ -69,6 +69,15 @@ export const runManifestBuild = async (
}
}
+ const frontComponents = result.manifest.frontComponents;
+ if (frontComponents && frontComponents.length > 0) {
+ console.log(chalk.gray(` 📍 Front component entry points:`));
+ for (const component of frontComponents) {
+ const name = component.name || component.universalIdentifier;
+ console.log(chalk.gray(` - ${name} (${component.componentPath})`));
+ }
+ }
+
await writeManifestToOutput(appPath, result);
const newEntryPoints = extractFunctionEntryPoints(functions);
diff --git a/packages/twenty-sdk/tsconfig.json b/packages/twenty-sdk/tsconfig.json
index 3bbb87560d8..d92d92f0ff6 100644
--- a/packages/twenty-sdk/tsconfig.json
+++ b/packages/twenty-sdk/tsconfig.json
@@ -3,6 +3,7 @@
"allowJs": false,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
+ "jsx": "react-jsx",
"strictNullChecks": true,
"alwaysStrict": true,
"noImplicitAny": true,
diff --git a/packages/twenty-shared/src/application/applicationManifestType.ts b/packages/twenty-shared/src/application/applicationManifestType.ts
index eede5a81218..f3214d9baa4 100644
--- a/packages/twenty-shared/src/application/applicationManifestType.ts
+++ b/packages/twenty-shared/src/application/applicationManifestType.ts
@@ -3,6 +3,7 @@ import {
type ServerlessFunctionManifest,
type Application,
} from '@/application';
+import { type FrontComponentManifest } from '@/application/frontComponentManifestType';
import { type ObjectExtensionManifest } from '@/application/objectExtensionManifestType';
import { type RoleManifest } from '@/application/roleManifestType';
import { type Sources } from '@/types';
@@ -12,6 +13,7 @@ export type ApplicationManifest = {
objects: ObjectManifest[];
objectExtensions?: ObjectExtensionManifest[];
serverlessFunctions: ServerlessFunctionManifest[];
+ frontComponents?: FrontComponentManifest[];
roles?: RoleManifest[];
sources: Sources;
};
diff --git a/packages/twenty-shared/src/application/frontComponentManifestType.ts b/packages/twenty-shared/src/application/frontComponentManifestType.ts
new file mode 100644
index 00000000000..8372d500450
--- /dev/null
+++ b/packages/twenty-shared/src/application/frontComponentManifestType.ts
@@ -0,0 +1,7 @@
+export type FrontComponentManifest = {
+ universalIdentifier: string;
+ name?: string;
+ description?: string;
+ componentPath: string;
+ componentName: string;
+};
diff --git a/packages/twenty-shared/src/application/index.ts b/packages/twenty-shared/src/application/index.ts
index 251c6b3c283..2f4fbeaae1e 100644
--- a/packages/twenty-shared/src/application/index.ts
+++ b/packages/twenty-shared/src/application/index.ts
@@ -13,6 +13,7 @@ export type { ApplicationVariables } from './applicationVariablesType';
export { DEFAULT_API_KEY_NAME } from './constants/DefaultApiKeyName';
export { DEFAULT_API_URL_NAME } from './constants/DefaultApiUrlName';
export type { FieldManifest } from './fieldManifestType';
+export type { FrontComponentManifest } from './frontComponentManifestType';
export type { ObjectExtensionManifest } from './objectExtensionManifestType';
export type { ObjectManifest } from './objectManifestType';
export type { PackageJson } from './packageJsonType';
diff --git a/yarn.lock b/yarn.lock
index 061a0dda099..5ac33a95989 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -24395,6 +24395,15 @@ __metadata:
languageName: node
linkType: hard
+"@types/react@npm:^19.0.2":
+ version: 19.2.8
+ resolution: "@types/react@npm:19.2.8"
+ dependencies:
+ csstype: "npm:^3.2.2"
+ checksum: 10c0/832834998c4ee971fca72ecf1eb95dc924ad3931a2112c687a4dae498aabd115c5fa4db09186853e34a646226b0223808c8f867df03d17601168f9cf119448de
+ languageName: node
+ linkType: hard
+
"@types/readdir-glob@npm:*":
version: 1.1.5
resolution: "@types/readdir-glob@npm:1.1.5"
@@ -31558,6 +31567,13 @@ __metadata:
languageName: node
linkType: hard
+"csstype@npm:^3.2.2":
+ version: 3.2.3
+ resolution: "csstype@npm:3.2.3"
+ checksum: 10c0/cd29c51e70fa822f1cecd8641a1445bed7063697469d35633b516e60fe8c1bde04b08f6c5b6022136bb669b64c63d4173af54864510fbb4ee23281801841a3ce
+ languageName: node
+ linkType: hard
+
"cva@npm:1.0.0-beta.2":
version: 1.0.0-beta.2
resolution: "cva@npm:1.0.0-beta.2"
@@ -56991,6 +57007,7 @@ __metadata:
"@types/lodash.kebabcase": "npm:^4.1.7"
"@types/lodash.startcase": "npm:^4"
"@types/node": "npm:^24.0.0"
+ "@types/react": "npm:^19.0.2"
archiver: "npm:^7.0.1"
axios: "npm:^1.6.0"
chalk: "npm:^5.3.0"