Skip to content

开发环境设置

本指南将帮助您设置XAI-SDK的开发环境,以便您可以参与项目开发。

📋 系统要求

必需软件

  • Node.js: >= 18.0.0 (推荐使用LTS版本)
  • pnpm: >= 8.0.0 (包管理器)
  • Git: >= 2.20.0
  • TypeScript: >= 5.0.0 (全局安装可选)

推荐软件

  • VS Code: 推荐的代码编辑器
  • Docker: 用于容器化开发和测试
  • Postman: API测试工具

操作系统支持

  • macOS: >= 10.15
  • Windows: >= 10 (推荐使用WSL2)
  • Linux: Ubuntu >= 18.04, CentOS >= 7

🚀 快速开始

1. 克隆仓库

bash
# 克隆主仓库
git clone https://github.com/xai-sdk/xai-sdk.git
cd xai-sdk

# 或者克隆您的fork
git clone https://github.com/your-username/xai-sdk.git
cd xai-sdk

2. 安装依赖

bash
# 安装pnpm(如果尚未安装)
npm install -g pnpm

# 安装项目依赖
pnpm install

3. 环境配置

bash
# 复制环境变量模板
cp .env.example .env

# 编辑环境变量
vim .env

环境变量说明

bash
# API密钥(用于测试)
OPENAI_API_KEY=your_openai_api_key
ANTHROPIC_API_KEY=your_anthropic_api_key

# 开发环境设置
NODE_ENV=development
LOG_LEVEL=debug

# 测试配置
TEST_TIMEOUT=30000
TEST_PARALLEL=true

# 数据库配置(如果需要)
DATABASE_URL=sqlite://./dev.db

# Redis配置(如果需要)
REDIS_URL=redis://localhost:6379

4. 验证安装

bash
# 运行类型检查
pnpm type-check

# 运行代码检查
pnpm lint

# 运行测试
pnpm test

# 构建项目
pnpm build

🛠️ 开发工具配置

VS Code设置

推荐扩展

创建.vscode/extensions.json

json
{
  "recommendations": [
    "ms-vscode.vscode-typescript-next",
    "esbenp.prettier-vscode",
    "dbaeumer.vscode-eslint",
    "bradlc.vscode-tailwindcss",
    "ms-vscode.vscode-json",
    "redhat.vscode-yaml",
    "ms-vscode.test-adapter-converter",
    "hbenl.vscode-test-explorer"
  ]
}

工作区设置

创建.vscode/settings.json

json
{
  "typescript.preferences.importModuleSpecifier": "relative",
  "typescript.suggest.autoImports": true,
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true,
    "source.organizeImports": true
  },
  "files.associations": {
    "*.json": "jsonc"
  },
  "search.exclude": {
    "**/node_modules": true,
    "**/dist": true,
    "**/coverage": true
  },
  "files.watcherExclude": {
    "**/node_modules/**": true,
    "**/dist/**": true,
    "**/coverage/**": true
  }
}

调试配置

创建.vscode/launch.json

json
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug Tests",
      "type": "node",
      "request": "launch",
      "program": "${workspaceFolder}/node_modules/.bin/vitest",
      "args": ["run", "--reporter=verbose"],
      "env": {
        "NODE_ENV": "test"
      },
      "console": "integratedTerminal",
      "internalConsoleOptions": "neverOpen"
    },
    {
      "name": "Debug Example",
      "type": "node",
      "request": "launch",
      "program": "${workspaceFolder}/examples/basic-usage.ts",
      "outFiles": ["${workspaceFolder}/dist/**/*.js"],
      "env": {
        "NODE_ENV": "development"
      }
    }
  ]
}

Git配置

Git Hooks

我们使用husky来管理Git hooks:

bash
# 安装husky
pnpm add -D husky

# 初始化husky
pnpm husky install

# 添加pre-commit hook
pnpm husky add .husky/pre-commit "pnpm lint-staged"

# 添加commit-msg hook
pnpm husky add .husky/commit-msg "pnpm commitlint --edit $1"

提交信息规范

配置commitlint.config.js

javascript
module.exports = {
  extends: ['@commitlint/config-conventional'],
  rules: {
    'type-enum': [
      2,
      'always',
      [
        'feat',
        'fix',
        'docs',
        'style',
        'refactor',
        'test',
        'chore',
        'perf',
        'ci',
        'build',
        'revert',
      ],
    ],
    'subject-max-length': [2, 'always', 100],
    'body-max-line-length': [2, 'always', 100],
  },
};

📦 项目结构详解

xai-sdk/
├── .github/                 # GitHub配置
│   ├── workflows/          # CI/CD工作流
│   ├── ISSUE_TEMPLATE/     # Issue模板
│   └── PULL_REQUEST_TEMPLATE.md
├── .vscode/                # VS Code配置
├── docs/                   # 文档
│   ├── api/               # API文档
│   ├── guide/             # 用户指南
│   └── examples/          # 示例代码
├── src/                    # 源代码
│   ├── core/              # 核心功能
│   │   ├── sdk.ts         # 主SDK类
│   │   ├── config.ts      # 配置管理
│   │   └── types.ts       # 类型定义
│   ├── adapters/          # 适配器
│   │   ├── base.ts        # 基础适配器
│   │   ├── openai.ts      # OpenAI适配器
│   │   └── anthropic.ts   # Anthropic适配器
│   ├── plugins/           # 插件系统
│   │   ├── manager.ts     # 插件管理器
│   │   ├── base.ts        # 基础插件类
│   │   └── registry.ts    # 插件注册表
│   ├── tools/             # 工具系统
│   │   ├── manager.ts     # 工具管理器
│   │   ├── builtin/       # 内置工具
│   │   └── types.ts       # 工具类型
│   ├── middleware/        # 中间件
│   ├── cache/             # 缓存系统
│   ├── events/            # 事件系统
│   └── utils/             # 工具函数
├── tests/                  # 测试文件
│   ├── unit/              # 单元测试
│   ├── integration/       # 集成测试
│   ├── e2e/               # 端到端测试
│   └── fixtures/          # 测试数据
├── examples/               # 示例代码
├── scripts/                # 构建脚本
├── dist/                   # 构建输出
├── coverage/               # 测试覆盖率报告
├── package.json           # 项目配置
├── tsconfig.json          # TypeScript配置
├── vite.config.ts         # Vite配置
├── vitest.config.ts       # 测试配置
├── eslint.config.js       # ESLint配置
├── prettier.config.js     # Prettier配置
└── README.md              # 项目说明

🧪 测试环境

测试框架

我们使用Vitest作为测试框架:

typescript
// vitest.config.ts
import { defineConfig } from 'vitest/config';
import path from 'path';

export default defineConfig({
  test: {
    globals: true,
    environment: 'node',
    setupFiles: ['./tests/setup.ts'],
    coverage: {
      provider: 'v8',
      reporter: ['text', 'json', 'html'],
      exclude: [
        'node_modules/',
        'tests/',
        'dist/',
        '**/*.d.ts',
        '**/*.config.*',
      ],
    },
  },
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
});

测试命令

bash
# 运行所有测试
pnpm test

# 运行单元测试
pnpm test:unit

# 运行集成测试
pnpm test:integration

# 运行端到端测试
pnpm test:e2e

# 生成覆盖率报告
pnpm test:coverage

# 监听模式
pnpm test:watch

# 运行特定测试文件
pnpm test src/core/sdk.test.ts

测试数据库

对于需要数据库的测试,我们使用SQLite内存数据库:

typescript
// tests/setup.ts
import { beforeAll, afterAll } from 'vitest';
import { setupTestDatabase, teardownTestDatabase } from './utils/database';

beforeAll(async () => {
  await setupTestDatabase();
});

afterAll(async () => {
  await teardownTestDatabase();
});

🔧 构建系统

构建配置

我们使用Vite进行构建:

typescript
// vite.config.ts
import { defineConfig } from 'vite';
import { resolve } from 'path';
import dts from 'vite-plugin-dts';

export default defineConfig({
  build: {
    lib: {
      entry: resolve(__dirname, 'src/index.ts'),
      name: 'XAI_SDK',
      fileName: format => `xai-sdk.${format}.js`,
      formats: ['es', 'cjs', 'umd'],
    },
    rollupOptions: {
      external: ['node:fs', 'node:path', 'node:crypto'],
      output: {
        globals: {
          'node:fs': 'fs',
          'node:path': 'path',
          'node:crypto': 'crypto',
        },
      },
    },
  },
  plugins: [
    dts({
      insertTypesEntry: true,
    }),
  ],
});

构建命令

bash
# 开发构建
pnpm build:dev

# 生产构建
pnpm build

# 监听构建
pnpm build:watch

# 清理构建产物
pnpm clean

# 类型检查
pnpm type-check

# 代码检查
pnpm lint

# 代码格式化
pnpm format

🐳 Docker开发环境

Dockerfile

dockerfile
# Dockerfile.dev
FROM node:18-alpine

WORKDIR /app

# 安装pnpm
RUN npm install -g pnpm

# 复制package文件
COPY package.json pnpm-lock.yaml ./

# 安装依赖
RUN pnpm install

# 复制源代码
COPY . .

# 暴露端口
EXPOSE 3000

# 启动开发服务器
CMD ["pnpm", "dev"]

Docker Compose

yaml
# docker-compose.dev.yml
version: '3.8'

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile.dev
    volumes:
      - .:/app
      - /app/node_modules
    ports:
      - '3000:3000'
    environment:
      - NODE_ENV=development
    depends_on:
      - redis
      - postgres

  redis:
    image: redis:7-alpine
    ports:
      - '6379:6379'

  postgres:
    image: postgres:15-alpine
    environment:
      POSTGRES_DB: xai_sdk_dev
      POSTGRES_USER: dev
      POSTGRES_PASSWORD: dev
    ports:
      - '5432:5432'
    volumes:
      - postgres_data:/var/lib/postgresql/data

volumes:
  postgres_data:

使用Docker开发

bash
# 启动开发环境
docker-compose -f docker-compose.dev.yml up -d

# 查看日志
docker-compose -f docker-compose.dev.yml logs -f app

# 进入容器
docker-compose -f docker-compose.dev.yml exec app sh

# 停止环境
docker-compose -f docker-compose.dev.yml down

📊 性能监控

性能测试

typescript
// tests/performance/benchmark.test.ts
import { describe, it, expect } from 'vitest';
import { performance } from 'perf_hooks';
import { XAI_SDK } from '../../src';

describe('Performance Tests', () => {
  it('should handle 100 concurrent requests', async () => {
    const sdk = new XAI_SDK(/* config */);
    const start = performance.now();

    const promises = Array.from({ length: 100 }, () =>
      sdk.chat([{ role: 'user', content: 'Hello' }])
    );

    await Promise.all(promises);
    const end = performance.now();

    expect(end - start).toBeLessThan(10000); // 10秒内完成
  });
});

内存监控

typescript
// scripts/memory-monitor.ts
function monitorMemory() {
  const usage = process.memoryUsage();
  console.log({
    rss: `${Math.round(usage.rss / 1024 / 1024)} MB`,
    heapTotal: `${Math.round(usage.heapTotal / 1024 / 1024)} MB`,
    heapUsed: `${Math.round(usage.heapUsed / 1024 / 1024)} MB`,
    external: `${Math.round(usage.external / 1024 / 1024)} MB`,
  });
}

setInterval(monitorMemory, 5000);

🚨 故障排除

常见问题

1. 依赖安装失败

bash
# 清理缓存
pnpm store prune
rm -rf node_modules pnpm-lock.yaml
pnpm install

2. 类型检查错误

bash
# 重新生成类型
pnpm build:types

# 检查TypeScript配置
pnpm tsc --noEmit

3. 测试失败

bash
# 清理测试缓存
pnpm test --clearCache

# 运行单个测试文件
pnpm test --reporter=verbose src/core/sdk.test.ts

4. 构建失败

bash
# 清理构建产物
pnpm clean

# 重新构建
pnpm build

调试技巧

  1. 使用调试器:在VS Code中设置断点
  2. 日志输出:使用console.log或调试日志
  3. 测试隔离:运行单个测试文件
  4. 环境变量:检查环境变量设置
  5. 网络问题:检查API密钥和网络连接

📚 学习资源

相关技术文档

推荐阅读


现在您已经设置好了完整的开发环境!如果遇到任何问题,请查看故障排除部分或在GitHub上提出Issue。

Released under the MIT License.