All files / src/services template-download-service.ts

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

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 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
import * as fs from 'node:fs'
import * as os from 'node:os'
import * as path from 'node:path'
import { pluginLogger as logger } from '@dalidev/core'
 
// 模板验证结果接口
export interface TemplateValidationResult {
  isValid: boolean
  errors: string[]
  warnings: string[]
  templateInfo?: {
    name: string
    description?: string
    version?: string
    dependencies?: string[]
    mainFile?: string
  }
}
 
// 模板下载结果接口
export interface TemplateDownloadResult {
  templateId: string
  templateName: string
  downloadPath: string
  localPath: string
  dependencies: string[]
  validation: TemplateValidationResult
  fileStructure: string
  downloadTime: number
  size: number
}
 
// 模板下载服务类
export class TemplateDownloadService {
  private readonly templatesDir: string
  private readonly maxAge = 24 * 60 * 60 * 1000 // 24小时缓存
 
  constructor(workspaceRoot: string) {
    this.templatesDir = this.getTemplatesDir(workspaceRoot)
    this.ensureTemplatesDir()
  }
 
  private getTemplatesDir(workspaceRoot: string): string {
    // 首先尝试在工作区根目录创建模板目录
    const workspaceTemplatesDir = path.join(workspaceRoot, '.dalidev-templates')
 
    try {
      this.testDirectoryAccess(workspaceTemplatesDir)
      return workspaceTemplatesDir
    }
    catch (workspaceError) {
      logger.warn('Download', `无法在工作区创建模板目录`, { error: workspaceError })
 
      // 回退策略1: 尝试用户主目录
      try {
        const homeTemplatesDir = path.join(os.homedir(), '.dalidev-templates')
        this.testDirectoryAccess(homeTemplatesDir)
        logger.info('Download', `使用用户主目录作为模板目录`, { path: homeTemplatesDir })
        return homeTemplatesDir
      }
      catch (homeError) {
        logger.warn('Download', `无法在用户主目录创建模板目录`, { error: homeError })
 
        // 回退策略2: 使用系统临时目录
        try {
          const tmpTemplatesDir = path.join(os.tmpdir(), '.dalidev-templates')
          this.testDirectoryAccess(tmpTemplatesDir)
          logger.info('Download', `使用临时目录作为模板目录`, { path: tmpTemplatesDir })
          return tmpTemplatesDir
        }
        catch (tmpError) {
          const errorMsg = `所有模板目录创建策略都失败了。工作区错误: ${workspaceError}; 主目录错误: ${homeError}; 临时目录错误: ${tmpError}`
          logger.error('Download', `模板目录创建失败`, { workspaceError, homeError, tmpError })
          throw new Error(errorMsg)
        }
      }
    }
  }
 
  private testDirectoryAccess(dir: string): void {
    try {
      if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true })
      }
      // 测试写权限
      const testFile = path.join(dir, '.write-test')
      fs.writeFileSync(testFile, 'test')
      fs.unlinkSync(testFile)
    }
    catch (error) {
      throw new Error(`无法创建或写入目录 ${dir}: ${error instanceof Error ? error.message : String(error)}`)
    }
  }
 
  private ensureTemplatesDir(): void {
    try {
      this.testDirectoryAccess(this.templatesDir)
    }
    catch (error) {
      throw new Error(`模板目录初始化失败: ${error instanceof Error ? error.message : String(error)}`)
    }
  }
 
  private cleanupOldTemplates(): void {
    try {
      const files = fs.readdirSync(this.templatesDir)
      const now = Date.now()
 
      for (const file of files) {
        const filePath = path.join(this.templatesDir, file)
        const stats = fs.statSync(filePath)
 
        if (now - stats.mtime.getTime() > this.maxAge) {
          if (stats.isDirectory()) {
            fs.rmSync(filePath, { recursive: true, force: true })
          }
          else {
            fs.unlinkSync(filePath)
          }
          logger.info('Download', `清理过期模板`, { file })
        }
      }
    }
    catch (error) {
      logger.error('Download', '清理过期模板失败', { error })
    }
  }
 
  async downloadTemplate(templateUrl: string, templateId: string, templateName: string): Promise<TemplateDownloadResult> {
    const startTime = Date.now()
    this.cleanupOldTemplates()
    const templateDir = path.join(this.templatesDir, String(templateId))
 
    try {
      logger.info('Download', `开始下载模板`, { templateUrl, templateId, templateName })
 
      // 构建完整的模板下载URL
      let fullUrl = templateUrl
      if (!templateUrl.startsWith('http')) {
        const baseUrl = 'https://ued.zuoyebang.cc/documents/dalidev'
        fullUrl = `${baseUrl}${templateUrl}`
      }
 
      const response = await fetch(fullUrl)
      if (!response.ok) {
        throw new Error(`下载模板失败: ${response.status} ${response.statusText}`)
      }
 
      // 获取zip文件数据
      const zipBuffer = await response.arrayBuffer()
      const downloadSize = zipBuffer.byteLength
 
      // 确保模板目录存在
      if (fs.existsSync(templateDir)) {
        fs.rmSync(templateDir, { recursive: true, force: true })
      }
      fs.mkdirSync(templateDir, { recursive: true })
 
      // 解压zip文件
      try {
        const AdmZip = (await import('adm-zip')).default
        const { Buffer } = await import('node:buffer')
        const zip = new AdmZip(Buffer.from(zipBuffer))
        zip.extractAllTo(templateDir, true)
 
        logger.info('Download', `模板下载并解压成功`, { templateId, size: downloadSize })
      }
      catch (error) {
        logger.error('Download', `解压zip文件失败`, { error, templateId })
        throw new Error(`解压模板失败: ${error instanceof Error ? error.message : String(error)}`)
      }
 
      // 验证模板完整性
      const validation = await this.validateTemplate(templateDir)
      const downloadTime = Date.now() - startTime
 
      return {
        templateId,
        templateName,
        downloadPath: templateUrl,
        localPath: templateDir,
        validation,
        fileStructure: this.generateFileStructure(templateDir),
        downloadTime,
        size: downloadSize,
        dependencies: validation.templateInfo?.dependencies || [],
      }
    }
    catch (error) {
      logger.error('Download', `下载模板失败`, { templateId, templateName, error })
      throw error
    }
  }
 
  // 验证模板完整性和结构
  private async validateTemplate(templateDir: string): Promise<TemplateValidationResult> {
    const errors: string[] = []
    const warnings: string[] = []
    let templateInfo: TemplateValidationResult['templateInfo']
 
    try {
      // 检查模板目录是否存在
      if (!fs.existsSync(templateDir)) {
        errors.push('模板目录不存在')
        return { isValid: false, errors, warnings }
      }
 
      // 检查是否为空目录
      const files = fs.readdirSync(templateDir)
      if (files.length === 0) {
        errors.push('模板目录为空')
        return { isValid: false, errors, warnings }
      }
 
      // 查找并验证 template.json 配置文件
      const templateJsonPath = path.join(templateDir, 'template.json')
      if (fs.existsSync(templateJsonPath)) {
        try {
          const templateContent = fs.readFileSync(templateJsonPath, 'utf-8')
          const templateConfig = JSON.parse(templateContent)
 
          templateInfo = {
            name: templateConfig.name || 'Unknown',
            description: templateConfig.description,
            version: templateConfig.version,
            dependencies: templateConfig.dependencies,
            mainFile: templateConfig.main || 'index.vue',
          }
 
          // 验证必需字段
          if (!templateConfig.name) {
            warnings.push('template.json 缺少 name 字段')
          }
          if (!templateConfig.description) {
            warnings.push('template.json 缺少 description 字段')
          }
        }
        catch (error) {
          errors.push(`template.json 解析失败: ${error instanceof Error ? error.message : String(error)}`)
        }
      }
      else {
        warnings.push('缺少 template.json 配置文件')
      }
 
      // 检查目录结构合理性
      this.validateDirectoryStructure(templateDir, errors, warnings)
    }
    catch (error) {
      errors.push(`模板验证过程中发生错误: ${error instanceof Error ? error.message : String(error)}`)
    }
 
    return {
      isValid: errors.length === 0,
      errors,
      warnings,
      templateInfo,
    }
  }
 
  // 验证目录结构
  private validateDirectoryStructure(templateDir: string, errors: string[], warnings: string[]): void {
    try {
      const items = fs.readdirSync(templateDir, { withFileTypes: true })
 
      // 检查是否有可疑的大文件
      for (const item of items) {
        if (item.isFile()) {
          const filePath = path.join(templateDir, item.name)
          const stats = fs.statSync(filePath)
 
          // 检查单个文件是否过大 (>10MB)
          if (stats.size > 10 * 1024 * 1024) {
            warnings.push(`文件 ${item.name} 较大 (${Math.round(stats.size / 1024 / 1024)}MB)`)
          }
        }
      }
 
      // 检查是否包含不应该的文件
      const suspiciousFiles = ['node_modules', '.git', 'dist', 'build', '.DS_Store']
      const foundSuspicious = items.filter(item =>
        suspiciousFiles.some(suspicious => item.name.includes(suspicious)),
      )
 
      if (foundSuspicious.length > 0) {
        warnings.push(`包含可能不需要的文件/目录: ${foundSuspicious.map(f => f.name).join(', ')}`)
      }
    }
    catch (error) {
      warnings.push(`目录结构验证失败: ${error instanceof Error ? error.message : String(error)}`)
    }
  }
 
  // 计算目录大小
  private getDirectorySize(dirPath: string): number {
    let totalSize = 0
 
    const calculateSize = (currentPath: string, depth: number = 0) => {
      if (depth > 10)
        return // 防止过深递归
 
      try {
        const items = fs.readdirSync(currentPath, { withFileTypes: true })
 
        for (const item of items) {
          const itemPath = path.join(currentPath, item.name)
 
          if (item.isDirectory() && !item.name.includes('node_modules')) {
            calculateSize(itemPath, depth + 1)
          }
          else if (item.isFile()) {
            const stats = fs.statSync(itemPath)
            totalSize += stats.size
          }
        }
      }
      catch {
        // 忽略读取错误
      }
    }
 
    calculateSize(dirPath)
    return totalSize
  }
 
  // 生成文件结构树
  generateFileStructure(templateDir: string): string {
    try {
      const structure = this.buildFileTree(templateDir, '', 0)
      return structure
    }
    catch (error) {
      logger.error('Download', '生成文件结构失败', { error })
      return '文件结构生成失败'
    }
  }
 
  private buildFileTree(dirPath: string, prefix: string, depth: number): string {
    if (depth > 5)
      return '' // 限制深度避免过深
 
    const items = fs.readdirSync(dirPath, { withFileTypes: true })
    let result = ''
 
    // 过滤掉隐藏文件和一些不需要的文件
    const filteredItems = items.filter(item =>
      !item.name.startsWith('.')
      && !item.name.includes('node_modules')
      && !item.name.includes('dist'),
    )
 
    filteredItems.forEach((item, index) => {
      const isLast = index === filteredItems.length - 1
      const currentPrefix = isLast ? '└── ' : '├── '
      const nextPrefix = isLast ? '    ' : '│   '
 
      result += `${prefix}${currentPrefix}${item.name}\n`
 
      if (item.isDirectory()) {
        const subDirPath = path.join(dirPath, item.name)
        result += this.buildFileTree(subDirPath, prefix + nextPrefix, depth + 1)
      }
    })
 
    return result
  }
 
  // 获取模板目录路径
  public getTemplatesDirectory(): string {
    return this.templatesDir
  }
 
  /**
   * 处理模板请求,返回处理后的prompt
   * @param templates 模板下载结果
   * @returns 模板信息
   */
  public processTemplateRequest(templates: TemplateDownloadResult[]): string {
    const dependenciesStr = templates.map(t => t.dependencies.join(',')).join('\n')
    return templates.map(t => `
      模板名称:${t.templateName}
      模板文件结构:${t.fileStructure}
      模板的存储路径:${t.localPath}
      ${dependenciesStr.length > 0 ? `模板依赖:${dependenciesStr}, 请确保已经安装这些依赖,没有安装,请先安装` : ''}
    `).join('\n')
  }
}