### Development Commands
Source: https://github.com/tiijeij8/constella/blob/master/README.md
Commands for installing dependencies and starting development environments for Web and Electron.
```bash
npm install
npm run dev
npm run dev:electron
npm run build
```
--------------------------------
### 在 Vue 组件中使用错误处理
Source: https://github.com/tiijeij8/constella/blob/master/src/utils/ERROR_HANDLING.md
在 Vue 3 setup 组件中集成错误处理逻辑的示例。
```vue
```
--------------------------------
### LaTeX Matrix Syntax
Source: https://github.com/tiijeij8/constella/blob/master/docs/EDITOR_GUIDE.md
Provides an example of LaTeX syntax for creating a matrix within mathematical formulas.
```latex
$$
\begin{pmatrix}
a & b \\
c & d
\end{pmatrix}
$$
```
--------------------------------
### Markdown Basic Syntax Examples
Source: https://github.com/tiijeij8/constella/blob/master/docs/EDITOR_GUIDE.md
Demonstrates basic Markdown syntax for mathematical formulas, including inline and block equations. Uses KaTeX for rendering.
```markdown
行内公式:$E = mc^2$
块级公式:
$$
\int_{a}^{b} f(x) \, dx
$$
```
--------------------------------
### Mermaid Flowchart Example
Source: https://github.com/tiijeij8/constella/blob/master/docs/EDITOR_GUIDE.md
An example of a Mermaid flowchart definition. Use the `/mermaid-flow` command to insert this template.
```mermaid
flowchart TD
A[开始] --> B{条件判断}
B -->|是| C[执行操作]
B -->|否| D[其他操作]
C --> E[结束]
D --> E
```
--------------------------------
### Mermaid Sequence Diagram Example
Source: https://github.com/tiijeij8/constella/blob/master/docs/EDITOR_GUIDE.md
An example of a Mermaid sequence diagram definition. Use the `/mermaid-seq` command to insert this template.
```mermaid
sequenceDiagram
participant A as 客户端
participant B as 服务器
A->>B: 请求
B-->>A: 响应
```
--------------------------------
### Mermaid Mindmap Example
Source: https://github.com/tiijeij8/constella/blob/master/docs/EDITOR_GUIDE.md
An example of a Mermaid mindmap definition. Use the `/mermaid-mindmap` command to insert this template.
```mermaid
mindmap
root((中心主题))
分支1
子项A
分支2
子项B
```
--------------------------------
### TypeScript Code Highlighting Example
Source: https://github.com/tiijeij8/constella/blob/master/docs/EDITOR_GUIDE.md
Demonstrates how to use TypeScript syntax highlighting in markdown code blocks. Ensure the language identifier is correctly specified.
```typescript
function hello(name: string) {
console.log(`Hello, ${name}`)
}
```
--------------------------------
### Usage Example: Handling API Errors
Source: https://github.com/tiijeij8/constella/blob/master/src/utils/ERROR_HANDLING.md
Demonstrates how to use the imported error handling utilities in TypeScript code.
```APIDOC
## Usage
### 1. Import Error Handling Utilities
```typescript
import { handleApiError, showError, getErrorMessage } from '@/utils/errorHandler'
```
### 2. Handle API Errors
#### Method A: Using handleApiError
```typescript
const result = await apiService.login(email, password)
if (!result.success) {
// Automatically get localized message based on error code
const errorMessage = handleApiError(result)
console.error(errorMessage)
// Or display directly
showError(result)
}
```
#### Method B: Using getErrorMessage
```typescript
const result = await apiService.register(username, email, password)
if (!result.success) {
// Manually get error message
const message = getErrorMessage(result.errorCode, result.message)
alert(message)
}
```
### 3. Usage in Components
```vue
```
```
--------------------------------
### Plugin Management IPC
Source: https://context7.com/tiijeij8/constella/llms.txt
Methods for installing, listing, enabling, and removing plugins, including support for development plugins.
```APIDOC
## IPC Plugin Management
### Description
Provides methods to manage plugin lifecycle, including installation from packages, listing installed plugins, toggling status, and managing development plugins.
### Methods
- **installPluginPackage(path?)**: Installs a plugin from a .constella-plugin or .zip file.
- **listInstalledPlugins()**: Returns a list of all installed plugins.
- **setInstalledPluginEnabled(id, enabled)**: Enables or disables an installed plugin.
- **removeInstalledPlugin(id)**: Uninstalls a plugin.
- **addDevelopmentPlugin(path)**: Registers a local directory as a development plugin.
- **listDevelopmentPlugins()**: Lists all registered development plugins.
- **setDevelopmentPluginEnabled(id, enabled)**: Toggles status for a development plugin.
- **removeDevelopmentPlugin(id)**: Removes a development plugin registration.
```
--------------------------------
### GET /health
Source: https://context7.com/tiijeij8/constella/llms.txt
Verifies the backend server connection status and retrieves application metadata.
```APIDOC
## GET /health
### Description
Verifies the backend server connection status and returns server health information and application metadata.
### Method
GET
### Endpoint
/health
### Response
#### Success Response (200)
- **app** (string) - Application name
- **version** (string) - Application version
- **instanceId** (string) - Unique instance identifier
```
--------------------------------
### Error Code Mapping Files
Source: https://github.com/tiijeij8/constella/blob/master/src/utils/ERROR_HANDLING.md
Examples of the JSON files used for mapping error codes to human-readable messages in different languages.
```APIDOC
## Error Code Mapping Files
### zh-CN.json (Chinese)
```json
{
"AUTH_MISSING_FIELDS": "请填写所有必填字段",
"AUTH_EMAIL_EXISTS": "该邮箱已被注册",
"AUTH_INVALID_CREDENTIALS": "邮箱或密码错误",
...
}
```
### en-US.json (English)
```json
{
"AUTH_MISSING_FIELDS": "Please fill in all required fields",
"AUTH_EMAIL_EXISTS": "This email is already registered",
"AUTH_INVALID_CREDENTIALS": "Invalid email or password",
...
}
```
```
--------------------------------
### Source Code Execution
Source: https://github.com/tiijeij8/constella/blob/master/README.md
Steps to clone and run the project from source.
```bash
git clone https://github.com/TiiJeiJ8/constella.git
cd web
npm install
npm run dev
```
--------------------------------
### 项目初始化与运行命令
Source: https://context7.com/tiijeij8/constella/llms.txt
包含克隆仓库、安装依赖以及启动 Web 和 Electron 开发环境的常用命令。
```bash
git clone https://github.com/TiiJeiJ8/constella.git
cd constella/web
# 安装依赖 (Node.js >= 20)
npm install
# 启动 Web 开发服务器
npm run dev
# 启动 Electron 开发模式 (需要后端服务)
npm run dev:electron
# 启动 Electron 开发模式 (跳过后端)
npm run dev:electron-no-backend
# 构建 Web 产物
npm run build
# 构建 Electron 桌面端
npm run build:electron
```
--------------------------------
### Build Commands
Source: https://github.com/tiijeij8/constella/blob/master/README.md
Commands for building the Web and Electron production artifacts.
```bash
npm run build
npm run build:electron
```
--------------------------------
### LaTeX Fraction Syntax
Source: https://github.com/tiijeij8/constella/blob/master/docs/EDITOR_GUIDE.md
Illustrates different LaTeX syntaxes for creating fractions within mathematical formulas using KaTeX.
```latex
$\frac{a}{b}$
$\dfrac{a}{b}$
$\tfrac{a}{b}$
```
--------------------------------
### Project Structure
Source: https://github.com/tiijeij8/constella/blob/master/README.md
Overview of the source directory layout.
```text
src/
├─ components/ # 通用 UI 组件
├─ plugins/ # 节点插件
├─ composables/ # 组合式逻辑
├─ services/ # API 与协作服务
├─ locales/ # 国际化资源
├─ views/ # 页面视图
└─ assets/ # 静态资源
electron/ # Electron 主进程与 preload
public/ # 公共资源
docs/ # 使用与开发文档
```
--------------------------------
### 配置开发环境变量
Source: https://context7.com/tiijeij8/constella/llms.txt
设置 WebSocket 服务器地址的开发环境配置文件示例。
```bash
# .env.development
VITE_WS_URL=localhost:3000 # WebSocket 服务器地址 (可选,默认从后端 URL 推导)
```
--------------------------------
### 编写运行时插件模块
Source: https://context7.com/tiijeij8/constella/llms.txt
运行时插件必须通过 window.__CONSTELLA_PLUGIN_API__.vue 访问 Vue,禁止直接 import。包含渲染器和编辑器两个核心模块。
```javascript
// dist/renderer.js - 运行时渲染器模块
const { h, ref, computed, watch, onMounted } = window.__CONSTELLA_PLUGIN_API__.vue
export default {
name: 'NoticeCardRenderer',
props: {
content: { type: Object, required: true },
width: { type: Number, required: true },
height: { type: Number, required: true },
displayMode: { type: String, default: 'full' },
scale: { type: Number, default: 1 }
},
setup(props) {
const parsedData = computed(() => {
try {
return JSON.parse(props.content.data || '{}')
} catch {
return { title: '', message: '' }
}
})
return () => h('div', {
class: 'notice-card',
style: {
padding: '16px',
backgroundColor: '#fef3c7',
borderLeft: '4px solid #f59e0b',
height: '100%'
}
}, [
h('h3', { style: { margin: '0 0 8px 0' } }, parsedData.value.title),
h('p', { style: { margin: 0 } }, parsedData.value.message)
])
}
}
// dist/editor.js - 运行时编辑器模块
const { h, ref, watch, onMounted } = window.__CONSTELLA_PLUGIN_API__.vue
export default {
name: 'NoticeCardEditor',
props: {
content: { type: Object, required: true },
onUpdate: { type: Function, required: true },
onClose: { type: Function, required: true }
},
setup(props) {
const title = ref('')
const message = ref('')
onMounted(() => {
try {
const data = JSON.parse(props.content.data || '{}')
title.value = data.title || ''
message.value = data.message || ''
} catch {}
})
const save = () => {
props.onUpdate(JSON.stringify({ title: title.value, message: message.value }))
props.onClose()
}
return () => h('div', { class: 'editor-form' }, [
h('input', {
value: title.value,
onInput: (e) => title.value = e.target.value,
placeholder: '标题'
}),
h('textarea', {
value: message.value,
onInput: (e) => message.value = e.target.value,
placeholder: '消息内容'
}),
h('button', { onClick: save }, '保存')
])
}
}
```
--------------------------------
### 配置 manifest.json 入口文件
Source: https://github.com/tiijeij8/constella/blob/master/docs/PLUGIN_PACKAGE_FORMAT.md
定义插件元数据、节点配置及多语言资源映射的 JSON 结构。
```json
{
"id": "com.example.todo",
"name": "Todo Plugin",
"version": "1.0.0",
"description": "Checklist node plugin",
"author": "Example Studio",
"homepage": "https://example.com",
"engine": {
"constella": "^1.1.0"
},
"nodes": [
{
"kind": "todo",
"label": "Todo",
"description": "Checklist node",
"icon": "assets/icon.png",
"renderer": "dist/renderer.js",
"editor": "dist/editor.js",
"editable": true,
"supportsCardMode": true,
"supportsFontSizeControl": false
}
],
"i18n": {
"zh-CN": "i18n/zh-CN.json",
"en-US": "i18n/en-US.json"
},
"permissions": []
}
```
--------------------------------
### 内置插件目录结构
Source: https://github.com/tiijeij8/constella/blob/master/docs/PLUGIN_DEVELOPMENT_ARCHITECTURE_4.0.md
推荐的内置插件文件组织方式,包含元数据定义、入口文件及 Vue 组件。
```text
src/plugins/my-plugin/
manifest.ts
index.ts
MyRenderer.vue
MyEditor.vue
```
--------------------------------
### 使用插件注册表 API
Source: https://context7.com/tiijeij8/constella/llms.txt
通过 pluginRegistry 管理节点插件的注册、获取、查询及监听目录变化。需从 ./src/plugins 导入相关类型和实例。
```typescript
import {
pluginRegistry,
pluginCatalogVersion,
getPluginsMeta,
type NodePlugin,
type PluginMeta,
type ContentKind
} from './src/plugins'
// 注册插件
const customPlugin: NodePlugin = {
meta: {
kind: 'custom-note',
label: '自定义笔记',
icon: 'icon-note',
description: '带有特殊格式的笔记节点',
editable: true,
supportsCardMode: true,
supportsFontSizeControl: true
},
renderer: CustomNoteRenderer, // Vue 组件
editor: CustomNoteEditor, // Vue 组件 (可选)
onDblClick: (content) => { // 自定义双击处理 (可选)
if (content.kind === 'custom-note') {
// 返回 true 阻止打开默认编辑器
return true
}
return false
}
}
pluginRegistry.register(customPlugin)
// 获取插件
const plugin = pluginRegistry.get('markdown')
const renderer = pluginRegistry.getRenderer('markdown')
const editor = pluginRegistry.getEditor('markdown')
const meta = pluginRegistry.getMeta('markdown')
// 检查插件是否存在
if (pluginRegistry.has('custom-note')) {
console.log('自定义插件已注册')
}
// 获取所有已注册类型
const kinds = pluginRegistry.getRegisteredKinds()
// ['blank', 'text', 'markdown', 'image', 'hyperlink', 'quote-card', 'custom-note']
// 获取所有插件元数据
const allMeta = getPluginsMeta()
// 监听插件目录变化
watch(pluginCatalogVersion, (version) => {
console.log('插件目录已更新,版本:', version)
})
```
--------------------------------
### LaTeX Piecewise Function Syntax
Source: https://github.com/tiijeij8/constella/blob/master/docs/EDITOR_GUIDE.md
Demonstrates LaTeX syntax for defining piecewise functions in mathematical formulas.
```latex
$$ f(x) = \begin{cases}
x^2 & x \geq 0 \\
-x^2 & x < 0
\end{cases} $$
```
--------------------------------
### WebSocket Configuration
Source: https://github.com/tiijeij8/constella/blob/master/README.md
Environment variable for manually specifying the WebSocket URL in development.
```text
VITE_WS_URL=localhost:3000
```
--------------------------------
### 导入错误处理工具
Source: https://github.com/tiijeij8/constella/blob/master/src/utils/ERROR_HANDLING.md
在 TypeScript 文件中导入必要的错误处理函数。
```typescript
import { handleApiError, showError, getErrorMessage } from '@/utils/errorHandler'
```
--------------------------------
### 发现局域网服务器 IPC
Source: https://context7.com/tiijeij8/constella/llms.txt
使用 discoverLanServers 扫描局域网内的 Constella 后端,支持 mDNS 和子网扫描。
```typescript
// 发现局域网服务器 (支持 mDNS/Bonjour 和子网扫描回退)
const servers = await window.electronAPI.discoverLanServers(2000) // 超时 2 秒
servers.forEach(server => {
console.log('发现服务器:', server)
// {
// id: 'constella-instance-uuid',
// name: 'My Constella Server',
// url: 'http://192.168.1.100:3000',
// host: '192.168.1.100',
// port: 3000,
// apiPrefix: '/api/v1',
// websocketPath: '/ws',
// version: '1.1.0',
// addresses: ['192.168.1.100'],
// discoveredAt: '2024-01-15T10:30:00.000Z'
// }
})
// 连接到发现的服务器
if (servers.length > 0) {
apiService.setBaseUrl(servers[0].url)
}
```
--------------------------------
### LaTeX Superscript and Subscript Syntax
Source: https://github.com/tiijeij8/constella/blob/master/docs/EDITOR_GUIDE.md
Shows LaTeX syntax for creating superscripts and subscripts in mathematical formulas.
```latex
$x^2$
$x_i$
$x_i^2$
$x^{2n}$
```
--------------------------------
### 添加新的错误码示例
Source: https://github.com/tiijeij8/constella/blob/master/src/utils/ERROR_HANDLING.md
展示如何在多语言映射文件中添加新的错误码。
```json
// zh-CN.json
{
"NEW_ERROR_CODE": "新的错误提示"
}
// en-US.json
{
"NEW_ERROR_CODE": "New error message"
}
```
--------------------------------
### 定义插件目录结构
Source: https://github.com/tiijeij8/constella/blob/master/docs/PLUGIN_PACKAGE_FORMAT.md
展示了插件根目录的标准文件布局,包含入口文件、资源文件及构建产物。
```text
my-plugin/
manifest.json
dist/
renderer.js
editor.js
i18n/
zh-CN.json
en-US.json
assets/
icon.png
```
--------------------------------
### Runtime Plugin Manifest
Source: https://context7.com/tiijeij8/constella/llms.txt
Specification for the manifest.json file used for distributing runtime plugins.
```APIDOC
## manifest.json
### Description
Defines the structure for a distributable plugin package.
### Fields
- **id** (string) - Required - Unique plugin identifier.
- **name** (string) - Required - Human-readable name.
- **version** (string) - Required - Semantic version.
- **engine** (object) - Required - Compatibility requirements (e.g., constella version).
- **nodes** (array) - Required - List of node definitions provided by the plugin.
- **i18n** (object) - Optional - Paths to localization files.
```
--------------------------------
### 运行时插件 manifest.json 配置
Source: https://context7.com/tiijeij8/constella/llms.txt
定义用户分发插件的安装包格式,包含插件元数据、节点定义及 i18n 路径映射。
```json
{
"id": "com.example.notice-card",
"name": "Notice Card Plugin",
"version": "1.0.0",
"description": "显示带标题和消息的通知卡片节点",
"author": "Example Studio",
"homepage": "https://example.com",
"engine": {
"constella": "^1.1.0"
},
"nodes": [
{
"kind": "notice-card",
"label": "通知卡片",
"description": "在高亮面板中显示标题和消息",
"icon": "assets/icon.png",
"renderer": "dist/renderer.js",
"editor": "dist/editor.js",
"editable": true,
"supportsCardMode": true,
"supportsFontSizeControl": false
}
],
"i18n": {
"zh-CN": "i18n/zh-CN.json",
"en-US": "i18n/en-US.json"
},
"permissions": []
}
```
--------------------------------
### Resource Upload API
Source: https://context7.com/tiijeij8/constella/llms.txt
Endpoints for uploading and managing assets within a room.
```APIDOC
## POST /rooms/{roomId}/assets
### Description
Uploads a file asset to a specific room.
### Parameters
#### Path Parameters
- **roomId** (string) - Required
## GET /rooms/{roomId}/assets
### Description
Retrieves a list of assets for a specific room.
### Parameters
#### Path Parameters
- **roomId** (string) - Required
```
--------------------------------
### 管理插件安装与开发 IPC
Source: https://context7.com/tiijeij8/constella/llms.txt
通过 window.electronAPI 调用主进程接口进行插件的安装、启用、卸载及开发模式管理。
```typescript
// 渲染进程中通过 preload 暴露的 API 调用
// 安装插件包 (.constella-plugin 或 .zip)
const installedPlugin = await window.electronAPI.installPluginPackage()
// 或指定路径: await window.electronAPI.installPluginPackage('/path/to/plugin.constella-plugin')
console.log('已安装插件:', installedPlugin)
// {
// id: 'com.example.notice-card',
// name: 'Notice Card Plugin',
// version: '1.0.0',
// enabled: true,
// source: 'archive',
// installDir: '/Users/.../plugins/installed/com.example.notice-card__1.0.0',
// manifest: { ... }
// }
// 获取已安装插件列表
const installedPlugins = await window.electronAPI.listInstalledPlugins()
// 启用/禁用插件
await window.electronAPI.setInstalledPluginEnabled('com.example.notice-card', false)
// 卸载插件
await window.electronAPI.removeInstalledPlugin('com.example.notice-card')
// 开发插件管理 (需开启开发者模式)
const devPlugin = await window.electronAPI.addDevelopmentPlugin('/path/to/dev-plugin')
const devPlugins = await window.electronAPI.listDevelopmentPlugins()
await window.electronAPI.setDevelopmentPluginEnabled('dev.my-plugin', true)
await window.electronAPI.removeDevelopmentPlugin('dev.my-plugin')
```
--------------------------------
### 项目文件结构概览
Source: https://github.com/tiijeij8/constella/blob/master/src/utils/ERROR_HANDLING.md
展示前端错误处理相关文件的目录结构。
```text
web/src/
├── locales/
│ ├── errors/
│ │ ├── zh-CN.json # 中文错误码映射
│ │ └── en-US.json # 英文错误码映射
│ ├── zh-CN.json # 中文主翻译文件
│ ├── en-US.json # 英文主翻译文件
│ └── index.ts # i18n 配置
├── utils/
│ └── errorHandler.ts # 错误处理工具
└── services/
└── api.ts # API 服务
```
--------------------------------
### User Authentication API
Source: https://context7.com/tiijeij8/constella/llms.txt
Endpoints for user registration, login, and token management.
```APIDOC
## POST /auth/register
### Description
Registers a new user account.
### Parameters
#### Request Body
- **username** (string) - Required
- **email** (string) - Required
- **password** (string) - Required
## POST /auth/login
### Description
Authenticates a user and returns access and refresh tokens.
### Parameters
#### Request Body
- **email** (string) - Required
- **password** (string) - Required
### Response
#### Success Response (200)
- **access_token** (string) - JWT access token
- **refresh_token** (string) - JWT refresh token
- **user_id** (string) - Unique user identifier
## POST /auth/refresh
### Description
Refreshes the access token using a valid refresh token.
### Parameters
#### Request Body
- **refresh_token** (string) - Required
```
--------------------------------
### Plugin Registry API
Source: https://context7.com/tiijeij8/constella/llms.txt
Methods for interacting with the plugin registry to register, retrieve, and verify node plugins.
```APIDOC
## pluginRegistry.register(plugin)
### Description
Registers a new node plugin into the system.
### Parameters
- **plugin** (NodePlugin) - Required - The plugin object containing meta, renderer, and optional editor/event handlers.
## pluginRegistry.get(kind)
### Description
Retrieves a registered plugin by its kind.
### Parameters
- **kind** (string) - Required - The unique identifier for the plugin type.
## pluginRegistry.getRegisteredKinds()
### Description
Returns a list of all currently registered plugin kinds.
## getPluginsMeta()
### Description
Retrieves metadata for all registered plugins.
```
--------------------------------
### Implement Real-time Chat with useYjsChat
Source: https://context7.com/tiijeij8/constella/llms.txt
Handle room-based chat message synchronization, including sending, deleting, and unread message tracking.
```typescript
import { useYjsChat, type ChatMessage } from './src/composables/useYjsChat'
const {
messages, // Ref - 消息列表
unreadCount, // Ref - 未读消息数
sendMessage, // 发送消息
deleteMessage, // 删除消息
markAsRead, // 标记已读
initialize // 初始化
} = useYjsChat({
getDoc: () => yjsDoc,
userName: '用户昵称',
userId: 'user-uuid'
})
// 初始化聊天
initialize()
// 发送消息
sendMessage('大家好!这是我的第一条消息。')
// 渲染消息列表
messages.value.forEach((msg: ChatMessage) => {
console.log(`${msg.userName}: ${msg.content}`)
console.log(` - 时间: ${new Date(msg.timestamp).toLocaleString()}`)
console.log(` - 颜色: ${msg.userColor}`) // 基于用户ID生成的稳定颜色
console.log(` - 是否自己: ${msg.isOwn}`)
})
// 打开聊天面板时标记已读
function openChatPanel() {
markAsRead()
console.log('未读数:', unreadCount.value) // 应为 0
}
// 删除自己的消息
const myMessage = messages.value.find(m => m.isOwn)
if (myMessage) {
deleteMessage(myMessage.id)
}
```
--------------------------------
### Manage Collaborative Rooms API
Source: https://context7.com/tiijeij8/constella/llms.txt
Provides methods for creating, listing, joining, and deleting collaborative rooms. Private rooms require a password for access.
```typescript
import { apiService } from './src/services/api'
// 创建房间
const createResult = await apiService.createRoom({
name: '项目讨论室',
description: '团队头脑风暴空间',
is_private: true,
password: 'roomPassword',
settings: { maxUsers: 10 }
})
if (createResult.success) {
const roomId = createResult.data.id
console.log('房间创建成功:', roomId)
}
// 获取房间列表 (支持分页和用户过滤)
const roomsResult = await apiService.getRooms({
page: 1,
limit: 20,
userId: 'user-123' // 可选:只获取特定用户的房间
})
// 获取所有房间 (包含私密房间)
const allRoomsResult = await apiService.getAllRooms({ page: 1, limit: 50 })
// 获取房间详情
const roomDetail = await apiService.getRoomById('room-uuid-here')
// 加入房间 (私密房间需要密码)
const joinResult = await apiService.joinRoom('room-uuid', 'password')
// 获取当前用户加入的房间
const myRooms = await apiService.getMyRooms()
// 删除房间
const deleteResult = await apiService.deleteRoom('room-uuid', 'password')
```
--------------------------------
### Adding New Error Codes
Source: https://github.com/tiijeij8/constella/blob/master/src/utils/ERROR_HANDLING.md
Instructions on how to define and add new error codes to the system.
```APIDOC
## Adding New Error Codes
1. Define the error code in the backend (see `server/docs/ERROR_CODES.md`)
2. Add the Chinese translation in `web/src/locales/errors/zh-CN.json`
3. Add the English translation in `web/src/locales/errors/en-US.json`
Example:
```json
// zh-CN.json
{
"NEW_ERROR_CODE": "新的错误提示"
}
// en-US.json
{
"NEW_ERROR_CODE": "New error message"
}
```
```
--------------------------------
### 引入宿主 Vue API
Source: https://github.com/tiijeij8/constella/blob/master/docs/PLUGIN_PACKAGE_FORMAT.md
在运行时模块中通过 window 对象获取 Vue 相关 API,避免直接打包 Vue 依赖。
```js
const { h, ref, computed } = window.__CONSTELLA_PLUGIN_API__.vue
```
--------------------------------
### Initialize Yjs Collaboration Composable
Source: https://context7.com/tiijeij8/constella/llms.txt
Establishes a WebSocket connection and manages Yjs document synchronization. Provides access to shared data structures like Y.Map and Y.Array.
```typescript
import { useYjs } from './src/composables/useYjs'
const {
doc, // Y.Doc 实例
provider, // WebsocketProvider 引用
isConnected, // 连接状态
isSynced, // 同步状态
connect, // 连接方法
disconnect, // 断开方法
getMap, // 获取 Y.Map
getArray // 获取 Y.Array
} = useYjs({
roomId: 'room-uuid',
token: 'optional-relay-token', // 可选,未提供时自动获取
onConnect: () => console.log('WebSocket 已连接'),
onDisconnect: () => console.log('已断开连接'),
onSync: (synced) => console.log('同步状态:', synced ? '已同步' : '同步中'),
onError: (error) => console.error('连接错误:', error)
})
// 连接到协作服务器
await connect()
// 获取共享数据结构
const nodesMap = getMap('nodes') // Y.Map>
const edgesMap = getMap('edges') // Y.Map>
const chatArray = getArray('_chat_messages') // Y.Array
// 组件卸载时自动断开
// 或手动断开: disconnect()
```
--------------------------------
### Room Management API
Source: https://context7.com/tiijeij8/constella/llms.txt
Endpoints for managing collaborative rooms including creation, listing, joining, and deletion.
```APIDOC
## POST /rooms
### Description
Creates a new collaborative room.
### Parameters
#### Request Body
- **name** (string) - Required
- **description** (string) - Optional
- **is_private** (boolean) - Required
- **password** (string) - Optional
- **settings** (object) - Optional
## GET /rooms
### Description
Retrieves a list of rooms with pagination and filtering.
### Parameters
#### Query Parameters
- **page** (number) - Required
- **limit** (number) - Required
- **userId** (string) - Optional
## POST /rooms/{roomId}/join
### Description
Joins a specific room.
### Parameters
#### Path Parameters
- **roomId** (string) - Required
#### Request Body
- **password** (string) - Optional
```
--------------------------------
### 定义内置节点插件
Source: https://context7.com/tiijeij8/constella/llms.txt
创建符合插件架构 4.0 规范的内置插件,包含 manifest 定义、i18n 资源及插件导出。
```typescript
// src/plugins/markdown/manifest.ts
import type { PluginMeta } from '../index'
export const manifest: PluginMeta = {
kind: 'markdown',
label: 'Markdown', // UI 回退显示名
icon: 'icon-markdown',
description: 'Markdown 富文本',
editable: true,
supportsCardMode: true,
supportsFontSizeControl: true
}
// src/plugins/markdown/index.ts
import type { NodePlugin, PluginI18nMessages } from '../index'
import MarkdownRenderer from './MarkdownRenderer.vue'
import { manifest } from './manifest'
// 插件 i18n 资源
export const pluginI18n: PluginI18nMessages = {
'zh-CN': {
canvas: {
nodeTypes: { markdown: 'Markdown' },
nodeTypeDesc: { markdown: 'Markdown 富文本' }
}
},
'en-US': {
canvas: {
nodeTypes: { markdown: 'Markdown' },
nodeTypeDesc: { markdown: 'Markdown rich text' }
}
}
}
// 导出插件定义
export const pluginPlugin: NodePlugin = {
meta: manifest,
renderer: MarkdownRenderer
// 使用通用编辑器,不需要自定义 editor
}
```
--------------------------------
### Manage User Authentication API
Source: https://context7.com/tiijeij8/constella/llms.txt
Handles user registration, login, and token refresh. Access tokens and refresh tokens are stored in localStorage for session persistence.
```typescript
import { apiService } from './src/services/api'
// 用户注册
const registerResult = await apiService.register(
'username',
'user@example.com',
'securePassword123'
)
if (registerResult.success) {
console.log('注册成功:', registerResult.data)
}
// 用户登录
const loginResult = await apiService.login('user@example.com', 'password123')
if (loginResult.success) {
// Token 自动存储到 localStorage
localStorage.setItem('access_token', loginResult.data.access_token)
localStorage.setItem('refresh_token', loginResult.data.refresh_token)
localStorage.setItem('user_id', loginResult.data.user_id)
console.log('登录成功,用户ID:', loginResult.data.user_id)
}
// 刷新 Token (通常由 API 服务自动处理 401 响应)
const refreshResult = await apiService.refreshToken(
localStorage.getItem('refresh_token')!
)
if (refreshResult.success) {
localStorage.setItem('access_token', refreshResult.data.access_token)
}
```
--------------------------------
### Upload and Manage Room Assets API
Source: https://context7.com/tiijeij8/constella/llms.txt
Handles file uploads and asset management within a room. Uploaded assets return a constella:// protocol URL.
```typescript
import { apiService } from './src/services/api'
// 上传资源文件
const fileInput = document.querySelector('#file-input')
const file = fileInput?.files?.[0]
if (file) {
const uploadResult = await apiService.uploadAsset('room-uuid', file)
if (uploadResult.success) {
// 返回 constella:// 协议的资源路径
console.log('资源URL:', uploadResult.data)
// 输出: 'constella://uploads/assets/image-123.png'
}
}
// 获取房间资源列表
const assetsResult = await apiService.getAssets('room-uuid')
console.log('资源列表:', assetsResult.data)
// 删除资源
await apiService.deleteAsset('room-uuid', 'asset-uuid')
```
--------------------------------
### LAN Service Discovery IPC
Source: https://context7.com/tiijeij8/constella/llms.txt
Methods for discovering Constella backend servers on the local network.
```APIDOC
## IPC LAN Service Discovery
### Description
Discovers Constella instances running on the local network using mDNS/Bonjour or subnet scanning.
### Method
- **discoverLanServers(timeout)**
### Parameters
- **timeout** (number) - Required - Discovery duration in milliseconds.
### Response
- **servers** (Array) - List of discovered server objects containing id, name, url, host, port, and version.
```
--------------------------------
### Manage Canvas Nodes with useYjsNodes
Source: https://context7.com/tiijeij8/constella/llms.txt
Use this composable to handle CRDT-based node synchronization, including creation, updates, deletion, and undo/redo operations.
```typescript
import { useYjsNodes, type CanvasNode, type RenderNode } from './src/composables/useYjsNodes'
const {
nodes, // Ref - 响应式节点列表
isInitialized, // 初始化状态
canUndo, // 可撤销状态
canRedo, // 可重做状态
initialize, // 初始化方法
createNode, // 创建节点
updateNode, // 更新节点
updateNodePosition, // 更新位置
updateNodeContent, // 更新内容
updateNodeKind, // 更新类型
deleteNode, // 删除单个节点
deleteNodes, // 批量删除节点
getNode, // 获取节点
undo, // 撤销
redo // 重做
} = useYjsNodes({
getDoc: () => yjsDoc, // 返回 Y.Doc 的函数
onNodesChange: (nodes) => console.log('节点变更:', nodes.length)
})
// 初始化
initialize()
// 创建节点
const newNode: CanvasNode = {
id: `node-${Date.now()}`,
x: 100,
y: 200,
width: 200,
height: 150,
fill: '#667eea',
stroke: '#5568d3',
content: {
kind: 'markdown',
data: '# 标题\n\n这是节点内容',
displayMode: 'full'
},
zIndex: 1
}
createNode(newNode)
// 更新节点位置 (拖拽时调用)
updateNodePosition('node-id', 300, 400)
// 更新节点属性
updateNode('node-id', {
width: 250,
height: 180,
fill: '#10b981'
})
// 更新节点内容
updateNodeContent('node-id', '# 新标题\n\n更新后的内容')
// 更新节点类型
updateNodeKind('node-id', 'text')
// 批量删除节点
deleteNodes(['node-1', 'node-2', 'node-3'])
// 撤销/重做
if (canUndo.value) undo()
if (canRedo.value) redo()
```
--------------------------------
### useYjsChat - Real-time Chat
Source: https://context7.com/tiijeij8/constella/llms.txt
Manages real-time chat message synchronization within a room, including sending, deleting, and unread status tracking.
```APIDOC
## useYjsChat
### Description
Manages real-time chat message synchronization, supporting message history, unread counts, and user-specific message management.
### Methods
- **initialize()**: Initializes the chat synchronization.
- **sendMessage(content: string)**: Sends a new message to the room.
- **deleteMessage(id: string)**: Deletes a message by its ID.
- **markAsRead()**: Marks all current messages as read.
```
--------------------------------
### 定义错误码映射文件
Source: https://github.com/tiijeij8/constella/blob/master/src/utils/ERROR_HANDLING.md
展示中文和英文错误码映射的 JSON 格式。
```json
{
"AUTH_MISSING_FIELDS": "请填写所有必填字段",
"AUTH_EMAIL_EXISTS": "该邮箱已被注册",
"AUTH_INVALID_CREDENTIALS": "邮箱或密码错误",
...
}
```
```json
{
"AUTH_MISSING_FIELDS": "Please fill in all required fields",
"AUTH_EMAIL_EXISTS": "This email is already registered",
"AUTH_INVALID_CREDENTIALS": "Invalid email or password",
...
}
```
--------------------------------
### API 响应格式示例
Source: https://github.com/tiijeij8/constella/blob/master/src/utils/ERROR_HANDLING.md
展示 API 成功与失败时的 JSON 响应结构。
```json
{
"success": true,
"code": 200,
"message": "Login successful",
"data": {
"access_token": "...",
"refresh_token": "..."
}
}
```
```json
{
"success": false,
"code": 401,
"message": "Invalid email or password",
"errorCode": "AUTH_INVALID_CREDENTIALS"
}
```
--------------------------------
### 处理 API 错误的方法
Source: https://github.com/tiijeij8/constella/blob/master/src/utils/ERROR_HANDLING.md
展示使用 handleApiError 和 getErrorMessage 处理 API 响应错误的两种方式。
```typescript
const result = await apiService.login(email, password)
if (!result.success) {
// 自动根据错误码获取本地化消息
const errorMessage = handleApiError(result)
console.error(errorMessage)
// 或直接显示
showError(result)
}
```
```typescript
const result = await apiService.register(username, email, password)
if (!result.success) {
// 手动获取错误消息
const message = getErrorMessage(result.errorCode, result.message)
alert(message)
}
```
--------------------------------
### useYjsNodes - Node Management
Source: https://context7.com/tiijeij8/constella/llms.txt
Manages canvas node CRDT synchronization, including creation, updates, deletion, and undo/redo functionality.
```APIDOC
## useYjsNodes
### Description
Manages canvas node CRDT synchronization, supporting node creation, updates, deletion, and undo/redo operations.
### Methods
- **initialize()**: Initializes the Yjs node management.
- **createNode(node: CanvasNode)**: Adds a new node to the canvas.
- **updateNodePosition(id: string, x: number, y: number)**: Updates the position of a specific node.
- **updateNodeContent(id: string, content: string)**: Updates the content of a specific node.
- **updateNodeKind(id: string, kind: string)**: Updates the type/kind of a specific node.
- **updateNode(id: string, props: Partial)**: Updates arbitrary node properties.
- **deleteNode(id: string)**: Deletes a single node.
- **deleteNodes(ids: string[])**: Batch deletes nodes.
- **undo()**: Reverts the last operation.
- **redo()**: Re-applies the last undone operation.
```
--------------------------------
### Manage Canvas Edges with useYjsEdges
Source: https://context7.com/tiijeij8/constella/llms.txt
Manage CRDT-synchronized connections between nodes, supporting various styles and arrow configurations.
```typescript
import { useYjsEdges, type CanvasEdge, type EdgeType, type ArrowType } from './src/composables/useYjsEdges'
const {
edges, // Ref - 响应式连线列表
initialize, // 初始化方法
createEdge, // 创建连线
updateEdge, // 更新连线
deleteEdge, // 删除连线
deleteEdges, // 批量删除
deleteEdgesByNode, // 删除节点相关连线
getEdge, // 获取连线
getEdgesByNode // 获取节点的所有连线
} = useYjsEdges({
getDoc: () => yjsDoc,
onEdgesChange: (edges) => console.log('连线变更:', edges.length)
})
// 初始化
initialize()
// 创建连线
const edgeId = createEdge({
sourceId: 'node-1', // 起始节点
targetId: 'node-2', // 目标节点
sourceAnchor: 'right', // 起始锚点: top | right | bottom | left | center
targetAnchor: 'left', // 目标锚点
type: 'bezier', // 连线类型: straight | bezier | step
color: '#667eea', // 颜色
strokeWidth: 2, // 线宽
dashArray: [5, 3], // 虚线样式 (可选)
startArrow: 'none', // 起始箭头: none | arrow | diamond | circle
endArrow: 'arrow', // 结束箭头
label: '关联', // 标签文本 (可选)
labelPosition: 0.5, // 标签位置 0-1
zIndex: 0 // 层级
})
// 更新连线
updateEdge(edgeId, {
color: '#ef4444',
strokeWidth: 3,
type: 'straight'
})
// 删除节点时清理相关连线
deleteEdgesByNode('node-1')
// 获取节点的所有连接
const connectedEdges = getEdgesByNode('node-2')
console.log('连接数量:', connectedEdges.length)
```