All files / src/server/routes template-selection.ts

0% Statements 0/251
0% Branches 0/1
0% Functions 0/1
0% Lines 0/251

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
import type express from 'express'
import type { TemplateDownloadResult } from '../../services/template-download-service'
import { pluginLogger } from '@dalidev/core'
import { TemplateDownloadService } from '../../services/template-download-service'
 
// 内存存储模板选择会话数据
interface TemplateSelectionSession {
  sessionId: string
  data: any
  status: 'waiting' | 'completed' | 'cancelled'
  timestamp: number
  result?: {
    selectedTemplates: Array<{
      id: string
      name: string
      category: string
      description?: string
      path?: string
      zipUrl?: string
      packages?: string[]
    }>
  }
}
 
// 内存存储
const templateSelectionSessions = new Map<string, TemplateSelectionSession>()
 
export function registerTemplateSelectionRoutes(app: express.Express) {
  // 创建或更新模板选择会话数据
  app.post('/api/template-selection/session/:sessionId', (req, res) => {
    try {
      const { sessionId } = req.params
      const { data, status, timestamp } = req.body
 
      if (!sessionId) {
        return res.status(400).json({ success: false, error: 'sessionId is required' })
      }
 
      // 创建或更新会话到内存
      const session: TemplateSelectionSession = {
        sessionId,
        data: data || {},
        status: status || 'waiting',
        timestamp: timestamp || Date.now(),
      }
 
      templateSelectionSessions.set(sessionId, session)
 
      pluginLogger.info('Server', `创建/更新模板选择会话到内存`, { sessionId })
      res.json({ success: true, message: `Session ${sessionId} created/updated`, data: session })
    }
    catch (error) {
      pluginLogger.error('Server', '创建/更新模板选择会话失败', { error })
      res.status(500).json({ success: false, error: error instanceof Error ? error.message : String(error) })
    }
  })
 
  // 获取模板选择会话数据
  app.get('/api/template-selection/session/:sessionId', (req, res) => {
    try {
      const { sessionId } = req.params
      if (!sessionId) {
        return res.status(400).json({ success: false, error: 'sessionId is required' })
      }
 
      const session = templateSelectionSessions.get(sessionId)
      if (!session) {
        return res.status(404).json({ success: false, error: `Session ${sessionId} not found` })
      }
 
      pluginLogger.info('Server', `获取模板选择会话数据`, { sessionId })
      res.json({ success: true, data: session })
    }
    catch (error) {
      pluginLogger.error('Server', '获取模板选择会话数据失败', { error })
      res.status(500).json({ success: false, error: error instanceof Error ? error.message : String(error) })
    }
  })
 
  // 完成模板选择会话
  app.post('/api/template-selection/complete', (req, res) => {
    pluginLogger.info('Server', '完成模板选择会话', { req: req.body })
    try {
      const { sessionId, result } = req.body
      if (!sessionId) {
        pluginLogger.error('Server', '完成模板选择会话失败', { error: 'sessionId is required' })
        return res.status(400).json({ success: false, error: 'sessionId is required' })
      }
      if (!result || !result.selectedTemplates) {
        pluginLogger.error('Server', '完成模板选择会话失败', { error: 'result with selectedTemplates is required' })
        return res.status(400).json({ success: false, error: 'result with selectedTemplates is required' })
      }
 
      const session = templateSelectionSessions.get(sessionId)
      if (!session) {
        pluginLogger.error('Server', '完成模板选择会话失败', { error: `Session ${sessionId} not found` })
        return res.status(400).json({ success: false, error: `Session ${sessionId} not found` })
      }
 
      // 更新会话状态
      session.status = 'completed'
      session.result = result
      templateSelectionSessions.set(sessionId, session)
 
      pluginLogger.info('Server', `模板选择会话完成`, { sessionId, templateCount: result.selectedTemplates.length })
      res.json({
        success: true,
        message: `Template selection session ${sessionId} completed`,
        data: { sessionId, templateCount: result.selectedTemplates.length, status: 'completed' },
      })
    }
    catch (error) {
      pluginLogger.error('Server', '完成模板选择会话失败', { error })
      res.status(500).json({ success: false, error: error instanceof Error ? error.message : String(error) })
    }
  })
 
  // 取消模板选择会话
  app.post('/api/template-selection/cancel', (req, res) => {
    try {
      const { sessionId } = req.body
      if (!sessionId) {
        return res.status(400).json({ success: false, error: 'sessionId is required' })
      }
 
      const session = templateSelectionSessions.get(sessionId)
      if (!session) {
        return res.status(404).json({ success: false, error: `Session ${sessionId} not found` })
      }
 
      // 更新会话状态
      session.status = 'cancelled'
      templateSelectionSessions.set(sessionId, session)
 
      pluginLogger.info('Server', `模板选择会话已取消`, { sessionId })
      res.json({
        success: true,
        message: `Template selection session ${sessionId} cancelled`,
        data: { sessionId, status: 'cancelled' },
      })
    }
    catch (error) {
      pluginLogger.error('Server', '取消模板选择会话失败', { error })
      res.status(500).json({ success: false, error: error instanceof Error ? error.message : String(error) })
    }
  })
 
  // 获取所有活动会话(可选的调试接口)
  app.get('/api/template-selection/sessions', (req, res) => {
    try {
      const sessions = Array.from(templateSelectionSessions.entries()).map(([id, session]) => ({
        sessionId: id,
        status: session.status,
        timestamp: session.timestamp,
        hasResult: !!session.result,
      }))
 
      res.json({
        success: true,
        data: {
          totalSessions: sessions.length,
          sessions,
        },
      })
    }
    catch (error) {
      pluginLogger.error('Server', '获取会话列表失败', { error })
      res.status(500).json({ success: false, error: error instanceof Error ? error.message : String(error) })
    }
  })
 
  // 下载单个模板
  app.post('/api/template-selection/download', async (req, res) => {
    try {
      const { templateUrl, templateId, templateName, workspaceRoot } = req.body
 
      if (!templateUrl || !templateId || !templateName || !workspaceRoot) {
        return res.status(400).json({
          success: false,
          error: 'templateUrl, templateId, templateName and workspaceRoot are required',
        })
      }
 
      pluginLogger.info('Server', '开始下载模板', { templateId, templateName, templateUrl })
 
      const downloadService = new TemplateDownloadService(workspaceRoot)
      const result = await downloadService.downloadTemplate(templateUrl, templateId, templateName)
 
      pluginLogger.info('Server', '模板下载成功', { templateId, size: result.size })
      res.json({ success: true, data: result })
    }
    catch (error) {
      pluginLogger.error('Server', '下载模板失败', { error })
      res.status(500).json({
        success: false,
        error: error instanceof Error ? error.message : String(error),
      })
    }
  })
 
  // 批量下载模板
  app.post('/api/template-selection/download-batch', async (req, res) => {
    try {
      const { templates, workspaceRoot } = req.body
 
      if (!templates || !Array.isArray(templates) || !workspaceRoot) {
        return res.status(400).json({
          success: false,
          error: 'templates array and workspaceRoot are required',
        })
      }
 
      pluginLogger.info('Server', '开始批量下载模板', { templateCount: templates.length })
 
      const downloadService = new TemplateDownloadService(workspaceRoot)
      const results: Array<{ template: any, result?: TemplateDownloadResult, error?: string }> = []
 
      for (const template of templates) {
        try {
          if (!template.zipUrl && !template.path) {
            results.push({
              template,
              error: '缺少下载地址',
            })
            continue
          }
 
          const templateUrl = template.zipUrl || template.path
          const result = await downloadService.downloadTemplate(templateUrl, template.id, template.name)
          results.push({ template, result })
 
          pluginLogger.info('Server', '模板下载成功', { templateId: template.id, size: result.size })
        }
        catch (error) {
          pluginLogger.error('Server', '下载模板失败', { templateId: template.id, error })
          results.push({
            template,
            error: error instanceof Error ? error.message : String(error),
          })
        }
      }
 
      const successCount = results.filter(r => r.result).length
      const failCount = results.filter(r => r.error).length
 
      pluginLogger.info('Server', '批量下载完成', {
        total: templates.length,
        success: successCount,
        failed: failCount,
      })
 
      res.json({
        success: true,
        data: {
          total: templates.length,
          successCount,
          failCount,
          results,
          prompt: downloadService.processTemplateRequest(results.map(r => r.result)),
        },
      })
    }
    catch (error) {
      pluginLogger.error('Server', '批量下载模板失败', { error })
      res.status(500).json({
        success: false,
        error: error instanceof Error ? error.message : String(error),
      })
    }
  })
 
  // 获取模板目录信息
  app.get('/api/template-selection/templates-dir/:workspaceRoot', (req, res) => {
    try {
      const workspaceRoot = decodeURIComponent(req.params.workspaceRoot)
 
      if (!workspaceRoot) {
        return res.status(400).json({ success: false, error: 'workspaceRoot is required' })
      }
 
      const downloadService = new TemplateDownloadService(workspaceRoot)
      const templatesDir = downloadService.getTemplatesDirectory()
 
      res.json({
        success: true,
        data: {
          templatesDirectory: templatesDir,
          workspaceRoot,
        },
      })
    }
    catch (error) {
      pluginLogger.error('Server', '获取模板目录信息失败', { error })
      res.status(500).json({
        success: false,
        error: error instanceof Error ? error.message : String(error),
      })
    }
  })
 
  // 清理过期会话(可选的维护接口)
  app.post('/api/template-selection/cleanup', (req, res) => {
    try {
      const now = Date.now()
      const maxAge = 24 * 60 * 60 * 1000 // 24小时
      let cleanedCount = 0
 
      for (const [sessionId, session] of templateSelectionSessions.entries()) {
        if (now - session.timestamp > maxAge) {
          templateSelectionSessions.delete(sessionId)
          cleanedCount++
        }
      }
 
      pluginLogger.info('Server', `清理了过期会话`, { cleanedCount, remainingSessions: templateSelectionSessions.size })
      res.json({
        success: true,
        message: `Cleaned up ${cleanedCount} expired sessions`,
        data: { cleanedCount, remainingSessions: templateSelectionSessions.size },
      })
    }
    catch (error) {
      pluginLogger.error('Server', '清理过期会话失败', { error })
      res.status(500).json({ success: false, error: error instanceof Error ? error.message : String(error) })
    }
  })
}