nanoppa commited on
Commit
d9b2169
·
verified ·
1 Parent(s): a6eb137

Upload 49 files

Browse files
Files changed (50) hide show
  1. .gitattributes +2 -0
  2. CLAUDE.md +257 -0
  3. Dockerfile +21 -0
  4. LICENSE +674 -0
  5. configs/dev/service.yml +6 -0
  6. configs/dev/system.yml +14 -0
  7. doc/example-0.png +3 -0
  8. doc/example-1.jpeg +3 -0
  9. docs/JIMENG-4.1-4.5.md +170 -0
  10. libs.d.ts +0 -0
  11. package-lock.json +0 -0
  12. package.json +51 -0
  13. public/welcome.html +10 -0
  14. src/api/consts/exceptions.ts +13 -0
  15. src/api/controllers/chat.ts +524 -0
  16. src/api/controllers/core.ts +437 -0
  17. src/api/controllers/images.ts +1480 -0
  18. src/api/controllers/videos.ts +1570 -0
  19. src/api/routes/chat.ts +36 -0
  20. src/api/routes/images.ts +199 -0
  21. src/api/routes/index.ts +33 -0
  22. src/api/routes/models.ts +135 -0
  23. src/api/routes/ping.ts +6 -0
  24. src/api/routes/token.ts +39 -0
  25. src/api/routes/video.ts +6 -0
  26. src/api/routes/videos.ts +135 -0
  27. src/daemon.ts +82 -0
  28. src/index.ts +32 -0
  29. src/lib/config.ts +14 -0
  30. src/lib/configs/model-config.ts +407 -0
  31. src/lib/configs/service-config.ts +68 -0
  32. src/lib/configs/system-config.ts +84 -0
  33. src/lib/consts/exceptions.ts +5 -0
  34. src/lib/environment.ts +44 -0
  35. src/lib/exceptions/APIException.ts +14 -0
  36. src/lib/exceptions/Exception.ts +47 -0
  37. src/lib/http-status-codes.ts +61 -0
  38. src/lib/initialize.ts +28 -0
  39. src/lib/interfaces/ICompletionMessage.ts +4 -0
  40. src/lib/logger.ts +184 -0
  41. src/lib/request/Request.ts +95 -0
  42. src/lib/response/Body.ts +41 -0
  43. src/lib/response/FailureBody.ts +31 -0
  44. src/lib/response/Response.ts +63 -0
  45. src/lib/response/SuccessfulBody.ts +19 -0
  46. src/lib/server.ts +241 -0
  47. src/lib/util.ts +307 -0
  48. tsconfig.json +16 -0
  49. vercel.json +27 -0
  50. yarn.lock +1419 -0
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ doc/example-0.png filter=lfs diff=lfs merge=lfs -text
37
+ doc/example-1.jpeg filter=lfs diff=lfs merge=lfs -text
CLAUDE.md ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CLAUDE.md
2
+
3
+ 本文件为 Claude Code (claude.ai/claude-code) 在此代码仓库中工作时提供指导。
4
+
5
+ ## 项目概述
6
+
7
+ 即梦 AI 免费 API 服务 - 逆向工程的 API 服务器,提供 OpenAI 兼容接口,封装即梦 AI 的图像和视频生成能力。
8
+
9
+ **版本:** v0.8.0
10
+
11
+ **核心功能:**
12
+ - 文生图:支持 jimeng-5.0-preview、jimeng-4.6、jimeng-4.5 等多款模型,最高 4K 分辨率
13
+ - 图生图:多图合成,支持 1-10 张输入图片
14
+ - 视频生成:jimeng-video-3.5-pro 等模型,支持首帧/尾帧控制
15
+ - Seedance 2.0:多图智能视频生成,支持 @1、@2 占位符引用图片
16
+ - OpenAI 兼容:完全兼容 OpenAI API 格式,无缝对接现有客户端
17
+ - 多账号支持:支持多个 sessionid 轮询使用
18
+
19
+ ## 构建和开发命令
20
+
21
+ ```bash
22
+ # 安装依赖
23
+ npm install
24
+
25
+ # 开发模式(热重载)
26
+ npm run dev
27
+
28
+ # 生产环境构建
29
+ npm run build
30
+
31
+ # 启动生产服务
32
+ npm start
33
+ ```
34
+
35
+ ## Docker 命令
36
+
37
+ ```bash
38
+ # 构建 Docker 镜像
39
+ docker build -t jimeng-free-api-all:latest .
40
+
41
+ # 运行容器
42
+ docker run -it -d --init --name jimeng-free-api-all -p 8000:8000 -e TZ=Asia/Shanghai jimeng-free-api-all:latest
43
+
44
+ # 使用 Docker Hub 预构建镜像
45
+ docker pull wwwzhouhui569/jimeng-free-api-all:latest
46
+ docker run -it -d --init --name jimeng-free-api-all -p 8000:8000 -e TZ=Asia/Shanghai wwwzhouhui569/jimeng-free-api-all:latest
47
+ ```
48
+
49
+ ## 项目架构
50
+
51
+ ```
52
+ src/
53
+ ├── index.ts # 应用入口
54
+ ├── daemon.ts # 守护进程管理
55
+ ├── api/
56
+ │ ├── controllers/ # 业务逻辑控制器
57
+ │ │ ├── core.ts # 核心工具(Token处理、积分管理、请求封装)
58
+ │ │ ├── images.ts # 图像生成逻辑(文生图、图生图)
59
+ │ │ ├── videos.ts # 视频生成逻辑(含 Seedance 2.0)
60
+ │ │ └── chat.ts # 对话补全逻辑
61
+ │ ├── routes/ # API 路由定义
62
+ │ │ ├── index.ts # 路由聚合器
63
+ │ │ ├── images.ts # /v1/images/* 端点
64
+ │ │ ├── videos.ts # /v1/videos/* 端点
65
+ │ │ ├── video.ts # /v1/video/* 端点(videos 的包装路由)
66
+ │ │ ├── chat.ts # /v1/chat/* 端点
67
+ │ │ ├── models.ts # /v1/models 端点
68
+ │ │ ├── ping.ts # /ping 健康检查端点
69
+ │ │ └── token.ts # /token/* Token管理端点
70
+ │ └── consts/
71
+ │ └── exceptions.ts # API 异常定义
72
+ └── lib/
73
+ ├── server.ts # Koa 服务器配置(含中间件栈)
74
+ ├── config.ts # 配置管理
75
+ ├── logger.ts # 日志工具
76
+ ├── util.ts # 辅助工具函数
77
+ ├── environment.ts # 环境变量
78
+ ├── initialize.ts # 初始化逻辑
79
+ ├── http-status-codes.ts # HTTP 状态码
80
+ ├── request/
81
+ │ └── Request.ts # 请求解析与验证(含文件上传规范化)
82
+ ├── response/
83
+ │ ├── Response.ts # 响应包装器
84
+ │ ├── Body.ts # 响应体
85
+ │ └── FailureBody.ts # 错误响应体
86
+ ├── exceptions/
87
+ │ ├── Exception.ts # 基础异常类
88
+ │ └── APIException.ts # API 异常类
89
+ ├── interfaces/
90
+ │ └── ICompletionMessage.ts # 对话消息接口
91
+ └── configs/ # 配置模式
92
+ ├── model-config.ts # 模型配置(模型参数、分辨率映射等)
93
+ ├── service-config.ts # 服务配置
94
+ └── system-config.ts # 系统配置
95
+ ```
96
+
97
+ ## API 端点
98
+
99
+ | 端点 | 方法 | 说明 |
100
+ |------|------|------|
101
+ | `/v1/chat/completions` | POST | OpenAI 兼容的对话接口(用于图像/视频生成) |
102
+ | `/v1/images/generations` | POST | 文生图接口 |
103
+ | `/v1/images/compositions` | POST | 图生图接口(支持文件上传) |
104
+ | `/v1/videos/generations` | POST | 视频生成接口(含 Seedance 2.0) |
105
+ | `/v1/video/generations` | POST | 视频生成接口(别名路由) |
106
+ | `/v1/models` | GET | 获取可用模型列表 |
107
+ | `/token/check` | POST | 检查 Token 有效性 |
108
+ | `/token/points` | POST | 查询账户积分 |
109
+ | `/ping` | GET | 健康检查端点 |
110
+
111
+ ## 关键技术细节
112
+
113
+ ### 认证方式
114
+ - 使用即梦网站的 `sessionid` Cookie 作为 Bearer Token
115
+ - 多账号支持:逗号分隔多个 sessionid:`Authorization: Bearer sessionid1,sessionid2`
116
+ - 每次请求随机选择一个 sessionid 使用
117
+
118
+ ### 模型映射
119
+
120
+ #### 图像模型
121
+ | 用户模型名 | 内部模型名 | Draft 版本 | 说明 |
122
+ |-----------|-----------|-----------|------|
123
+ | `jimeng-5.0-preview` | `high_aes_general_v50` | 3.3.9 | 5.0 预览版,最新模型 |
124
+ | `jimeng-4.6` | `high_aes_general_v42` | 3.3.9 | 推荐使用 |
125
+ | `jimeng-4.5` | `high_aes_general_v40l` | 3.3.4 | 高质量模型 |
126
+ | `jimeng-4.1` | `high_aes_general_v41` | 3.3.4 | 高质量模型 |
127
+ | `jimeng-4.0` | `high_aes_general_v40` | 3.3.4 | 稳定版本 |
128
+ | `jimeng-3.1` | `high_aes_general_v30l_art_fangzhou` | - | 艺术风格 |
129
+ | `jimeng-3.0` | `high_aes_general_v30l` | - | 通用模型 |
130
+ | `jimeng-2.1` | - | - | 旧版模型 |
131
+ | `jimeng-2.0-pro` | - | - | 旧版专业模型 |
132
+ | `jimeng-2.0` | - | - | 旧版模型 |
133
+ | `jimeng-1.4` | - | - | 早期模型 |
134
+ | `jimeng-xl-pro` | - | - | XL 专业模型 |
135
+
136
+ #### 视频模型
137
+ | 用户模型名 | 内部模型名 | 说明 |
138
+ |-----------|-----------|------|
139
+ | `jimeng-video-3.5-pro` | `dreamina_ic_generate_video_model_vgfm_3.5_pro` | 最新视频模型 |
140
+ | `jimeng-video-3.0` | - | 视频生成 3.0 |
141
+ | `jimeng-video-3.0-pro` | - | 视频生成 3.0 专业版 |
142
+ | `jimeng-video-2.0` | - | 视频生成 2.0 |
143
+ | `jimeng-video-2.0-pro` | - | 视频生成 2.0 专业版 |
144
+ | `seedance-2.0` | `dreamina_seedance_40_pro` | 多图智能视频生成 |
145
+ | `seedance-2.0-pro` | `dreamina_seedance_40_pro` | 多图智能视频生成专业版 |
146
+
147
+ ### 请求参数
148
+
149
+ #### 文生图参数 (`/v1/images/generations`)
150
+ | 参数 | 类型 | 必填 | 默认值 | 说明 |
151
+ |------|------|------|--------|------|
152
+ | model | string | 否 | jimeng-4.5 | 模型名称 |
153
+ | prompt | string | 是 | - | 提示词,jimeng-4.x/5.x 支持多图生成 |
154
+ | negative_prompt | string | 否 | "" | 反向提示词 |
155
+ | ratio | string | 否 | 1:1 | 宽高比:1:1, 4:3, 3:4, 16:9, 9:16, 3:2, 2:3, 21:9 |
156
+ | resolution | string | 否 | 2k | 分辨率:1k, 2k, 4k |
157
+ | sample_strength | float | 否 | 0.5 | 精细度 0.0-1.0 |
158
+ | response_format | string | 否 | url | url 或 b64_json |
159
+
160
+ #### 图生图参数 (`/v1/images/compositions`)
161
+ - 与文生图相同的参数
162
+ - 额外支持 multipart/form-data 文件上传
163
+ - `images` 字段:图片 URL 数组,1-10 张
164
+
165
+ #### 视频生成参数 (`/v1/videos/generations`)
166
+ | 参数 | 类型 | 必填 | 默认值 | 说明 |
167
+ |------|------|------|--------|------|
168
+ | model | string | 否 | jimeng-video-3.0 | 模型名称 |
169
+ | prompt | string | 否 | - | 视频描述(图生视频时可选) |
170
+ | ratio | string | 否 | 1:1 | 宽高比:1:1, 4:3, 3:4, 16:9, 9:16 |
171
+ | resolution | string | 否 | 720p | 分辨率:480p, 720p, 1080p |
172
+ | duration | number | 否 | 5 | 时长:4(Seedance)、5 或 10 秒 |
173
+ | file_paths / filePaths | array | 否 | [] | 首帧/尾帧图片 URL |
174
+ | files | file[] | 否 | - | 上传的图片(multipart) |
175
+
176
+ #### Seedance 2.0 专用参数
177
+ - 使用 `unified_edit_input` 结构,包含 `material_list` 和 `meta_list`
178
+ - 内部模型:`dreamina_seedance_40_pro`
179
+ - Draft 版本:3.3.9
180
+ - 提示词占位符:`@1`、`@2`、`@图1`、`@图2`、`@image1`、`@image2` 引用上传的图片
181
+
182
+ ### 文件上传
183
+ - 支持 multipart/form-data 文件上传
184
+ - koa-body 配置最大文件大小 100MB
185
+ - files 字段可以是对象或数组格式(在 Request.ts 中自动规范化)
186
+ - 支持 formLimit/jsonLimit/textLimit:100mb
187
+
188
+ ### 分辨率支持
189
+
190
+ #### 图片分辨率
191
+ | 分辨率 | 1:1 | 4:3 | 3:4 | 16:9 | 9:16 | 3:2 | 2:3 | 21:9 |
192
+ |--------|-----|-----|-----|------|------|-----|-----|------|
193
+ | 1k | 1024×1024 | 768×1024 | 1024×768 | 1024×576 | 576×1024 | 1024×682 | 682×1024 | 1195×512 |
194
+ | 2k | 2048×2048 | 2304×1728 | 1728×2304 | 2560×1440 | 1440×2560 | 2496×1664 | 1664×2496 | 3024×1296 |
195
+ | 4k | 4096×4096 | 4608×3456 | 3456×4608 | 5120×2880 | 2880×5120 | 4992×3328 | 3328×4992 | 6048×2592 |
196
+
197
+ #### 视频分辨率
198
+ | 分辨率 | 1:1 | 4:3 | 3:4 | 16:9 | 9:16 |
199
+ |--------|-----|-----|-----|------|------|
200
+ | 480p | 480×480 | 640×480 | 480×640 | 854×480 | 480×854 |
201
+ | 720p | 720×720 | 960×720 | 720×960 | 1280×720 | 720×1280 |
202
+ | 1080p | 1080×1080 | 1440×1080 | 1080×1440 | 1920×1080 | 1080×1920 |
203
+
204
+ ### 服务器中间件栈
205
+ 1. **CORS 跨域支持**:`koa2-cors()`
206
+ 2. **Range 请求**:`koaRange`(支持分段内容传输)
207
+ 3. **自定义异常处理器**:捕获错误并返回 FailureBody 响应
208
+ 4. **自定义 JSON 解析器**:处理 POST/PUT/PATCH 请求的 JSON(清理问题 Unicode 字符,跳过 multipart 请求)
209
+ 5. **Body 解析器**:`koa-body`(multipart: true,maxFileSize: 100MB)
210
+
211
+ ## 开发规范
212
+
213
+ 1. **TypeScript**:项目使用 TypeScript + ESM 模块
214
+ 2. **路径别名**:使用 `@/` 别名指向 `src/` 目录
215
+ 3. **日志**:使用 `@/lib/logger.ts` 中的 logger 保持输出一致
216
+ 4. **配置**:环境配置在 `configs/` 目录,通过 `@/lib/config.ts` 加载
217
+ 5. **API 兼容性**:维护 OpenAI API 兼容性,确保客户端集成正常
218
+ 6. **Node.js 版本**:≥16.0.0
219
+
220
+ ## 测试 API 调用
221
+
222
+ ```bash
223
+ # 文生图(使用最新模型)
224
+ curl -X POST http://localhost:8000/v1/images/generations \
225
+ -H "Content-Type: application/json" \
226
+ -H "Authorization: Bearer your_sessionid" \
227
+ -d '{"model": "jimeng-5.0-preview", "prompt": "美丽的日落风景", "ratio": "16:9", "resolution": "2k"}'
228
+
229
+ # 视频生成
230
+ curl -X POST http://localhost:8000/v1/videos/generations \
231
+ -H "Content-Type: application/json" \
232
+ -H "Authorization: Bearer your_sessionid" \
233
+ -d '{"model": "jimeng-video-3.5-pro", "prompt": "一只小猫在草地上玩耍", "ratio": "16:9", "resolution": "720p"}'
234
+
235
+ # Seedance 2.0 多图视频(文件上传)
236
+ curl -X POST http://localhost:8000/v1/videos/generations \
237
+ -H "Authorization: Bearer your_sessionid" \
238
+ -F "model=seedance-2.0" \
239
+ -F "prompt=@1 和 @2 两人开始跳舞" \
240
+ -F "ratio=4:3" \
241
+ -F "duration=4" \
242
+ -F "files=@/path/to/image1.jpg" \
243
+ -F "files=@/path/to/image2.jpg"
244
+
245
+ # 健康检查
246
+ curl http://localhost:8000/ping
247
+
248
+ # Token 检查
249
+ curl -X POST http://localhost:8000/token/check \
250
+ -H "Content-Type: application/json" \
251
+ -d '{"token": "your_sessionid"}'
252
+ ```
253
+
254
+ ## 配置
255
+
256
+ 默认端口:8000
257
+ 配置文件在 `configs/` 目录,使用 YAML 格式。
Dockerfile ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM node:lts AS BUILD_IMAGE
2
+
3
+ WORKDIR /app
4
+
5
+ COPY . /app
6
+
7
+ RUN yarn install --registry https://registry.npmmirror.com/ --ignore-engines && yarn run build
8
+
9
+ FROM node:lts-alpine
10
+
11
+ COPY --from=BUILD_IMAGE /app/configs /app/configs
12
+ COPY --from=BUILD_IMAGE /app/package.json /app/package.json
13
+ COPY --from=BUILD_IMAGE /app/dist /app/dist
14
+ COPY --from=BUILD_IMAGE /app/public /app/public
15
+ COPY --from=BUILD_IMAGE /app/node_modules /app/node_modules
16
+
17
+ WORKDIR /app
18
+
19
+ EXPOSE 8000
20
+
21
+ CMD ["npm", "start"]
LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
configs/dev/service.yml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # 服务名称
2
+ name: jimeng-free-api
3
+ # 服务绑定主机地址
4
+ host: '0.0.0.0'
5
+ # 服务绑定端口
6
+ port: 8000
configs/dev/system.yml ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 是否开启请求日志
2
+ requestLog: true
3
+ # 临时目录路径
4
+ tmpDir: ./tmp
5
+ # 日志目录路径
6
+ logDir: ./logs
7
+ # 日志写入间隔(毫秒)
8
+ logWriteInterval: 200
9
+ # 日志文件有效期(毫秒)
10
+ logFileExpires: 2626560000
11
+ # 公共目录路径
12
+ publicDir: ./public
13
+ # 临时文件有效期(毫秒)
14
+ tmpFileExpires: 86400000
doc/example-0.png ADDED

Git LFS Details

  • SHA256: a3f80fec0ed607802d7a1c91a1c0592d77952fa39841749391415b4ba2064568
  • Pointer size: 131 Bytes
  • Size of remote file: 459 kB
doc/example-1.jpeg ADDED

Git LFS Details

  • SHA256: f581d9c180ba7501081f11c759ee65f8ee35b375e81ea90e5de0d39ec67bbbf1
  • Pointer size: 131 Bytes
  • Size of remote file: 315 kB
docs/JIMENG-4.1-4.5.md ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 即梦 AI 4.1 和 4.5 模型支持
2
+
3
+ 本文档介绍了 jimeng-free-api-all 项目对即梦 AI 新增的 4.1 和 4.5 模型的支持。
4
+
5
+ ## 新增模型
6
+
7
+ ### jimeng-4.5
8
+ - **内部模型名**: `high_aes_general_v45`
9
+ - **版本**: 3.2.9
10
+ - **特性**:
11
+ - 支持文生图(Text-to-Image)
12
+ - 支持图生图(Image-to-Image)
13
+ - 支持多图连续生成
14
+ - 最高支持 2048x2048 分辨率
15
+
16
+ ### jimeng-4.1
17
+ - **内部模型名**: `high_aes_general_v41`
18
+ - **版本**: 3.2.9
19
+ - **特性**:
20
+ - 支持文生图(Text-to-Image)
21
+ - 支持图生图(Image-to-Image)
22
+ - 支持多图连续生成
23
+ - 最高支持 2048x2048 分辨率
24
+
25
+ ## 与旧版本的差异
26
+
27
+ | 特性 | jimeng-4.5/4.1 | jimeng-4.0 | jimeng-3.1 |
28
+ |------|----------------|------------|------------|
29
+ | Draft版本 | 3.2.9 | 3.0.2 | 3.0.2 |
30
+ | 多图生成 | ✅ | ✅ | ❌ |
31
+ | 最大分辨率 | 2048x2048 | 2048x2048 | 1024x1024 |
32
+ | 采样强度范围 | 0.1-1.0 | 0.1-1.0 | 0.1-0.8 |
33
+
34
+ ## API 使用
35
+
36
+ ### 1. 文生图
37
+
38
+ ```bash
39
+ curl -X POST http://localhost:8000/v1/images/generations \
40
+ -H "Content-Type: application/json" \
41
+ -H "Authorization: Bearer YOUR_SESSION_ID" \
42
+ -d '{
43
+ "model": "jimeng-4.5",
44
+ "prompt": "一只可爱的小猫在花园里玩耍",
45
+ "width": 1024,
46
+ "height": 1024,
47
+ "sample_strength": 0.7
48
+ }'
49
+ ```
50
+
51
+ ### 2. 多图连续生成
52
+
53
+ ```bash
54
+ curl -X POST http://localhost:8000/v1/images/generations \
55
+ -H "Content-Type: application/json" \
56
+ -H "Authorization: Bearer YOUR_SESSION_ID" \
57
+ -d '{
58
+ "model": "jimeng-4.5",
59
+ "prompt": "生成4张连续场景的图片:春夏秋冬四季风景",
60
+ "width": 1024,
61
+ "height": 1024,
62
+ "sample_strength": 0.6
63
+ }'
64
+ ```
65
+
66
+ ### 3. 图生图
67
+
68
+ ```bash
69
+ curl -X POST http://localhost:8000/v1/images/compositions \
70
+ -H "Content-Type: application/json" \
71
+ -H "Authorization: Bearer YOUR_SESSION_ID" \
72
+ -d '{
73
+ "model": "jimeng-4.1",
74
+ "prompt": "将这些图片合成为一幅美丽的风景画",
75
+ "images": [
76
+ "https://example.com/image1.jpg",
77
+ "https://example.com/image2.jpg"
78
+ ],
79
+ "width": 2560,
80
+ "height": 1440,
81
+ "sample_strength": 0.6
82
+ }'
83
+ ```
84
+
85
+ ## 参数说明
86
+
87
+ ### 支持的分辨率
88
+
89
+ - 512x512
90
+ - 768x768
91
+ - 1024x1024(默认)
92
+ - 1280x720
93
+ - 720x1280
94
+ - 1536x864
95
+ - 864x1536
96
+ - 2048x2048(仅 4.1 和 4.5)
97
+
98
+ ### 采样强度(sample_strength)
99
+
100
+ - 范围:0.1 - 1.0
101
+ - 默认:0.5
102
+ - 说明:控制生成图片与提示词的契合度,值越高越贴近提示词
103
+
104
+ ## 最佳实践
105
+
106
+ 1. **使用提示词**
107
+ - 4.5 和 4.1 版本对中文提示词支持更好
108
+ - 建议使用详细的描述性提示词
109
+
110
+ 2. **多图生成**
111
+ - 使用 "连续"、"绘本"、"故事" 等关键词触发多图生成
112
+ - 使用 "X张" 指定生成图片数量
113
+
114
+ 3. **分辨率选择**
115
+ - 普通场景使用 1024x1024
116
+ - 需要高清细节时使用 2048x2048
117
+ - 宽屏场景使用 1280x720
118
+
119
+ ## 测试
120
+
121
+ 项目提供了测试脚本 `test/test-new-models.js`:
122
+
123
+ ```bash
124
+ # 安装依赖
125
+ npm install
126
+
127
+ # 修改脚本中的 SESSION_ID
128
+ vim test/test-new-models.js
129
+
130
+ # 运行测试
131
+ npm run test:models
132
+ # 或直接运行
133
+ node test/test-new-models.js
134
+ ```
135
+
136
+ ## 注意事项
137
+
138
+ 1. 新模型需要更多的积分消耗
139
+ 2. 生成时间可能比旧模型稍长
140
+ 3. 建议在生产环境使用前充分测试
141
+ 4. 遵守即梦 AI 的使用条款和限制
142
+
143
+ ## 故障排除
144
+
145
+ ### 常见错误
146
+
147
+ 1. **参数验证失败**
148
+ - 检查分辨率是否在支持列表中
149
+ - 检查采样强度是否在 0.1-1.0 范围内
150
+
151
+ 2. **模型不支持**
152
+ - 确保使用的是正确的模型名称(jimeng-4.5 或 jimeng-4.1)
153
+ - 查看模型列表确认可用性
154
+
155
+ 3. **生成失败**
156
+ - 检查积分是否充足
157
+ - 检查提示词是否符合内容规范
158
+ - 查看日志获取详细错误信息
159
+
160
+ ## 更新日志
161
+
162
+ ### v4.5 支持 (2024-12-07)
163
+ - 新增 jimeng-4.5 模型支持
164
+ - 支持最高 2048x2048 分辨率
165
+ - 优化了提示词理解能力
166
+
167
+ ### v4.1 支持 (2024-12-07)
168
+ - 新增 jimeng-4.1 模型支持
169
+ - 改进了图像生成质量
170
+ - 增强了多图生成功能
libs.d.ts ADDED
File without changes
package-lock.json ADDED
The diff for this file is too large to render. See raw diff
 
package.json ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "jimeng-free-api",
3
+ "version": "0.8.0",
4
+ "description": "jimeng Free API Server",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "module": "dist/index.mjs",
8
+ "types": "dist/index.d.ts",
9
+ "directories": {
10
+ "dist": "dist"
11
+ },
12
+ "files": [
13
+ "dist/"
14
+ ],
15
+ "scripts": {
16
+ "dev": "tsup src/index.ts --format cjs,esm --sourcemap --dts --publicDir public --watch --onSuccess \"node --enable-source-maps --no-node-snapshot dist/index.js\"",
17
+ "start": "node --enable-source-maps --no-node-snapshot dist/index.js",
18
+ "build": "tsup src/index.ts --format cjs,esm --sourcemap --dts --clean --publicDir public"
19
+ },
20
+ "author": "Vinlic",
21
+ "license": "ISC",
22
+ "dependencies": {
23
+ "axios": "^1.6.7",
24
+ "colors": "^1.4.0",
25
+ "crc-32": "^1.2.2",
26
+ "cron": "^3.1.6",
27
+ "date-fns": "^3.3.1",
28
+ "eventsource-parser": "^1.1.2",
29
+ "form-data": "^4.0.0",
30
+ "fs-extra": "^11.2.0",
31
+ "koa": "^2.15.0",
32
+ "koa-body": "^5.0.0",
33
+ "koa-bodyparser": "^4.4.1",
34
+ "koa-range": "^0.3.0",
35
+ "koa-router": "^12.0.1",
36
+ "koa2-cors": "^2.0.6",
37
+ "lodash": "^4.17.21",
38
+ "mime": "^4.0.1",
39
+ "minimist": "^1.2.8",
40
+ "randomstring": "^1.3.0",
41
+ "semver": "^7.7.2",
42
+ "uuid": "^9.0.1",
43
+ "yaml": "^2.3.4"
44
+ },
45
+ "devDependencies": {
46
+ "@types/lodash": "^4.14.202",
47
+ "@types/mime": "^3.0.4",
48
+ "tsup": "^8.0.2",
49
+ "typescript": "^5.3.3"
50
+ }
51
+ }
public/welcome.html ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <meta charset="utf-8"/>
5
+ <title>🚀 服务已启动</title>
6
+ </head>
7
+ <body>
8
+ <p>jimeng-free-api已启动!<br>请通过LobeChat / NextChat / Dify等客户端或OpenAI SDK接入!</p>
9
+ </body>
10
+ </html>
src/api/consts/exceptions.ts ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export default {
2
+ API_TEST: [-9999, 'API异常错误'],
3
+ API_REQUEST_PARAMS_INVALID: [-2000, '请求参数非法'],
4
+ API_REQUEST_FAILED: [-2001, '请求失败'],
5
+ API_TOKEN_EXPIRES: [-2002, 'Token已失效'],
6
+ API_FILE_URL_INVALID: [-2003, '远程文件URL非法'],
7
+ API_FILE_EXECEEDS_SIZE: [-2004, '远程文件超出大小'],
8
+ API_CHAT_STREAM_PUSHING: [-2005, '已有对话流正在输出'],
9
+ API_CONTENT_FILTERED: [-2006, '内容由于合规问题已被阻止生成'],
10
+ API_IMAGE_GENERATION_FAILED: [-2007, '图像生成失败'],
11
+ API_VIDEO_GENERATION_FAILED: [-2008, '视频生成失败'],
12
+ API_IMAGE_GENERATION_INSUFFICIENT_POINTS: [-2009, '即梦积分不足'],
13
+ }
src/api/controllers/chat.ts ADDED
@@ -0,0 +1,524 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import _ from "lodash";
2
+ import { PassThrough } from "stream";
3
+
4
+ import APIException from "@/lib/exceptions/APIException.ts";
5
+ import EX from "@/api/consts/exceptions.ts";
6
+ import logger from "@/lib/logger.ts";
7
+ import util from "@/lib/util.ts";
8
+ import { generateImages, DEFAULT_MODEL } from "./images.ts";
9
+ import { generateVideo, generateSeedanceVideo, isSeedanceModel, DEFAULT_MODEL as DEFAULT_VIDEO_MODEL } from "./videos.ts";
10
+
11
+ // 最大重试次数
12
+ const MAX_RETRY_COUNT = 3;
13
+ // 重试延迟
14
+ const RETRY_DELAY = 5000;
15
+
16
+ /**
17
+ * 解析模型
18
+ *
19
+ * @param model 模型名称
20
+ * @returns 模型信息
21
+ */
22
+ function parseModel(model: string) {
23
+ const [_model, size] = model.split(":");
24
+ const [_, width, height] = /(\d+)[\W\w](\d+)/.exec(size) ?? [];
25
+ return {
26
+ model: _model,
27
+ width: size ? Math.ceil(parseInt(width) / 2) * 2 : 1024,
28
+ height: size ? Math.ceil(parseInt(height) / 2) * 2 : 1024,
29
+ };
30
+ }
31
+
32
+ /**
33
+ * 检测是否为视频生成请求
34
+ *
35
+ * @param model 模型名称
36
+ * @returns 是否为视频生成请求
37
+ */
38
+ function isVideoModel(model: string) {
39
+ return model.startsWith("jimeng-video") || model.startsWith("seedance-");
40
+ }
41
+
42
+ /**
43
+ * 同步对话补全
44
+ *
45
+ * @param messages 参考gpt系列消息格式,多轮对话请完整提供上下文
46
+ * @param refreshToken 用于刷新access_token的refresh_token
47
+ * @param assistantId 智能体ID,默认使用jimeng原版
48
+ * @param retryCount 重试次数
49
+ */
50
+ export async function createCompletion(
51
+ messages: any[],
52
+ refreshToken: string,
53
+ _model = DEFAULT_MODEL,
54
+ retryCount = 0
55
+ ) {
56
+ return (async () => {
57
+ if (messages.length === 0)
58
+ throw new APIException(EX.API_REQUEST_PARAMS_INVALID, "消息不能为空");
59
+
60
+ const { model, width, height } = parseModel(_model);
61
+ logger.info(messages);
62
+
63
+ // 检查是否为视频生成请求
64
+ if (isVideoModel(_model)) {
65
+ try {
66
+ // 视频生成
67
+ logger.info(`开始生成视频,模型: ${_model}`);
68
+
69
+ let videoUrl: string;
70
+
71
+ // 判断是否为 Seedance 模型
72
+ if (isSeedanceModel(_model)) {
73
+ // Seedance 模型需要图片,在 chat 模式下不支持图片上传
74
+ // 返回友好提示
75
+ return {
76
+ id: util.uuid(),
77
+ model: _model,
78
+ object: "chat.completion",
79
+ choices: [
80
+ {
81
+ index: 0,
82
+ message: {
83
+ role: "assistant",
84
+ content: `Seedance 2.0 是多图智能视频生成模型,需要上传图片才能生成视频。\n\n请使用 POST /v1/videos/generations API 接口:\n\n\`\`\`bash\ncurl -X POST http://localhost:3000/v1/videos/generations \\\n -H "Authorization: your_token" \\\n -F "model=seedance-2.0" \\\n -F "prompt=@1 图片中的人物开始跳舞" \\\n -F "ratio=4:3" \\\n -F "duration=4" \\\n -F "files=@/path/to/image1.jpg" \\\n -F "files=@/path/to/image2.jpg"\n\`\`\`\n\n**参数说明:**\n- \`model\`: seedance-2.0 或 seedance-2.0-pro\n- \`prompt\`: 提示词,使用 @1, @2 等引用上传的图片\n- \`ratio\`: 视频比例 (默认 4:3)\n- \`duration\`: 视频时长 (默认 4 秒)\n- \`files\`: 上传的图片文件(支持多张)`,
85
+ },
86
+ finish_reason: "stop",
87
+ },
88
+ ],
89
+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
90
+ created: util.unixTimestamp(),
91
+ };
92
+ }
93
+
94
+ videoUrl = await generateVideo(
95
+ _model,
96
+ messages[messages.length - 1].content,
97
+ {
98
+ ratio: "16:9",
99
+ resolution: "720p", // 默认分辨率
100
+ },
101
+ refreshToken
102
+ );
103
+
104
+ logger.info(`视频生成成功,URL: ${videoUrl}`);
105
+ return {
106
+ id: util.uuid(),
107
+ model: _model,
108
+ object: "chat.completion",
109
+ choices: [
110
+ {
111
+ index: 0,
112
+ message: {
113
+ role: "assistant",
114
+ content: `![video](${videoUrl})\n`,
115
+ },
116
+ finish_reason: "stop",
117
+ },
118
+ ],
119
+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
120
+ created: util.unixTimestamp(),
121
+ };
122
+ } catch (error) {
123
+ logger.error(`视频生成失败: ${error.message}`);
124
+ // 如果是积分不足等特定错误,直接抛出
125
+ if (error instanceof APIException) {
126
+ throw error;
127
+ }
128
+
129
+ // 其他错误返回友好提示
130
+ return {
131
+ id: util.uuid(),
132
+ model: _model,
133
+ object: "chat.completion",
134
+ choices: [
135
+ {
136
+ index: 0,
137
+ message: {
138
+ role: "assistant",
139
+ content: `生成视频失败: ${error.message}\n\n如果您在即梦官网看到已生成的视频,可能是获取结果时出现了问题,请前往即梦官网查看。`,
140
+ },
141
+ finish_reason: "stop",
142
+ },
143
+ ],
144
+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
145
+ created: util.unixTimestamp(),
146
+ };
147
+ }
148
+ } else {
149
+ // 图像生成
150
+ const imageUrls = await generateImages(
151
+ model,
152
+ messages[messages.length - 1].content,
153
+ {
154
+ width,
155
+ height,
156
+ },
157
+ refreshToken
158
+ );
159
+
160
+ return {
161
+ id: util.uuid(),
162
+ model: _model || model,
163
+ object: "chat.completion",
164
+ choices: [
165
+ {
166
+ index: 0,
167
+ message: {
168
+ role: "assistant",
169
+ content: imageUrls.reduce(
170
+ (acc, url, i) => acc + `![image_${i}](${url})\n`,
171
+ ""
172
+ ),
173
+ },
174
+ finish_reason: "stop",
175
+ },
176
+ ],
177
+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
178
+ created: util.unixTimestamp(),
179
+ };
180
+ }
181
+ })().catch((err) => {
182
+ if (retryCount < MAX_RETRY_COUNT) {
183
+ logger.error(`Response error: ${err.stack}`);
184
+ logger.warn(`Try again after ${RETRY_DELAY / 1000}s...`);
185
+ return (async () => {
186
+ await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY));
187
+ return createCompletion(messages, refreshToken, _model, retryCount + 1);
188
+ })();
189
+ }
190
+ throw err;
191
+ });
192
+ }
193
+
194
+ /**
195
+ * 流式对话补全
196
+ *
197
+ * @param messages 参考gpt系列消息格式,多轮对话请完整提供上下文
198
+ * @param refreshToken 用于刷新access_token的refresh_token
199
+ * @param assistantId 智能体ID,默认使用jimeng原版
200
+ * @param retryCount 重试次数
201
+ */
202
+ export async function createCompletionStream(
203
+ messages: any[],
204
+ refreshToken: string,
205
+ _model = DEFAULT_MODEL,
206
+ retryCount = 0
207
+ ) {
208
+ return (async () => {
209
+ const { model, width, height } = parseModel(_model);
210
+ logger.info(messages);
211
+
212
+ const stream = new PassThrough();
213
+
214
+ if (messages.length === 0) {
215
+ logger.warn("消息为空,返回空流");
216
+ stream.end("data: [DONE]\n\n");
217
+ return stream;
218
+ }
219
+
220
+ // 检查是否为视频生成请求
221
+ if (isVideoModel(_model)) {
222
+ // 视频生成
223
+ stream.write(
224
+ "data: " +
225
+ JSON.stringify({
226
+ id: util.uuid(),
227
+ model: _model,
228
+ object: "chat.completion.chunk",
229
+ choices: [
230
+ {
231
+ index: 0,
232
+ delta: { role: "assistant", content: "🎬 视频生成中,请稍候...\n这可能需要1-2分钟,请耐心等待" },
233
+ finish_reason: null,
234
+ },
235
+ ],
236
+ }) +
237
+ "\n\n"
238
+ );
239
+
240
+ // 视频生成
241
+ logger.info(`开始生成视频,提示词: ${messages[messages.length - 1].content}`);
242
+
243
+ // 进度更新定时器
244
+ const progressInterval = setInterval(() => {
245
+ stream.write(
246
+ "data: " +
247
+ JSON.stringify({
248
+ id: util.uuid(),
249
+ model: _model,
250
+ object: "chat.completion.chunk",
251
+ choices: [
252
+ {
253
+ index: 0,
254
+ delta: { role: "assistant", content: "." },
255
+ finish_reason: null,
256
+ },
257
+ ],
258
+ }) +
259
+ "\n\n"
260
+ );
261
+ }, 5000);
262
+
263
+ // 设置超时,防止无限等待
264
+ const timeoutId = setTimeout(() => {
265
+ clearInterval(progressInterval);
266
+ logger.warn(`视频生成超时(2分钟),提示用户前往即梦官网查看`);
267
+ stream.write(
268
+ "data: " +
269
+ JSON.stringify({
270
+ id: util.uuid(),
271
+ model: _model,
272
+ object: "chat.completion.chunk",
273
+ choices: [
274
+ {
275
+ index: 1,
276
+ delta: {
277
+ role: "assistant",
278
+ content: "\n\n视频生成时间较长(已等待2分钟),但视频可能仍在生成中。\n\n请前往即梦官网查看您的视频:\n1. 访问 https://jimeng.jianying.com/ai-tool/video/generate\n2. 登录后查看您的创作历史\n3. 如果视频已生成,您可以直接在官网下载或分享\n\n您也可以继续等待,系统将在后台继续尝试获取视频(最长约20分钟)。",
279
+ },
280
+ finish_reason: "stop",
281
+ },
282
+ ],
283
+ }) +
284
+ "\n\n"
285
+ );
286
+ // 注意:这里不结束流,让后台继续尝试获取视频
287
+ // stream.end("data: [DONE]\n\n");
288
+ }, 2 * 60 * 1000);
289
+
290
+ logger.info(`开始生成视频,模型: ${_model}, 提示词: ${messages[messages.length - 1].content.substring(0, 50)}...`);
291
+
292
+ // 先给用户一个初始提示
293
+ stream.write(
294
+ "data: " +
295
+ JSON.stringify({
296
+ id: util.uuid(),
297
+ model: _model,
298
+ object: "chat.completion.chunk",
299
+ choices: [
300
+ {
301
+ index: 0,
302
+ delta: {
303
+ role: "assistant",
304
+ content: "\n\n🎬 视频生成已开始,这可能需要几分钟时间...",
305
+ },
306
+ finish_reason: null,
307
+ },
308
+ ],
309
+ }) +
310
+ "\n\n"
311
+ );
312
+
313
+ generateVideo(
314
+ _model,
315
+ messages[messages.length - 1].content,
316
+ { ratio: "16:9", resolution: "720p" },
317
+ refreshToken
318
+ )
319
+ .then((videoUrl) => {
320
+ clearInterval(progressInterval);
321
+ clearTimeout(timeoutId);
322
+
323
+ logger.info(`视频生成成功,URL: ${videoUrl}`);
324
+
325
+ stream.write(
326
+ "data: " +
327
+ JSON.stringify({
328
+ id: util.uuid(),
329
+ model: _model,
330
+ object: "chat.completion.chunk",
331
+ choices: [
332
+ {
333
+ index: 1,
334
+ delta: {
335
+ role: "assistant",
336
+ content: `\n\n✅ 视频生成完成!\n\n![video](${videoUrl})\n\n您可以:\n1. 直接查看上方视频\n2. 使用以下链接下载或分享:${videoUrl}`,
337
+ },
338
+ finish_reason: null,
339
+ },
340
+ ],
341
+ }) +
342
+ "\n\n"
343
+ );
344
+
345
+ stream.write(
346
+ "data: " +
347
+ JSON.stringify({
348
+ id: util.uuid(),
349
+ model: _model,
350
+ object: "chat.completion.chunk",
351
+ choices: [
352
+ {
353
+ index: 2,
354
+ delta: {
355
+ role: "assistant",
356
+ content: "",
357
+ },
358
+ finish_reason: "stop",
359
+ },
360
+ ],
361
+ }) +
362
+ "\n\n"
363
+ );
364
+ stream.end("data: [DONE]\n\n");
365
+ })
366
+ .catch((err) => {
367
+ clearInterval(progressInterval);
368
+ clearTimeout(timeoutId);
369
+
370
+ logger.error(`视频生成失败: ${err.message}`);
371
+ logger.error(`错误详情: ${JSON.stringify(err)}`);
372
+
373
+ // 记录详细错误信息
374
+ logger.error(`视频生成失败: ${err.message}`);
375
+ logger.error(`错误详情: ${JSON.stringify(err)}`);
376
+
377
+ // 构建更详细的错误信息
378
+ let errorMessage = `⚠️ 视频生成过程中遇到问题: ${err.message}`;
379
+
380
+ // 如果是历史记录不存在的错误,提供更具体的建议
381
+ if (err.message.includes("历史记录不存在")) {
382
+ errorMessage += "\n\n可能原因:\n1. 视频生成请求已发送,但API无法获取历史记录\n2. 视频生成服务暂时不可用\n3. 历史记录ID无效或已过期\n\n建议操作:\n1. 请前往即梦官网查看您的视频是否已生成:https://jimeng.jianying.com/ai-tool/video/generate\n2. 如果官网已显示视频,但这里无法获取,可能是API连接问题\n3. 如果官网也没有显示,请稍后再试或重新生成视频";
383
+ } else if (err.message.includes("获取视频生成结果超时")) {
384
+ errorMessage += "\n\n视频生成可能仍在进行中,但等待时间已超过系统设定的限制。\n\n请前往即梦官网查看您的视频:https://jimeng.jianying.com/ai-tool/video/generate\n\n如果您在官网上看到视频已生成,但这里无法显示,可能是因为:\n1. 获取结果的过程超时\n2. 网络连接问题\n3. API访问限制";
385
+ } else {
386
+ errorMessage += "\n\n如果您在即梦官网看到已生成的视频,可能是获取结果时出现了问题。\n\n请访问即梦官网查看您的创作历史:https://jimeng.jianying.com/ai-tool/video/generate";
387
+ }
388
+
389
+ // 添加历史ID信息,方便用户在官网查找
390
+ if (err.historyId) {
391
+ errorMessage += `\n\n历史记录ID: ${err.historyId}(您可以使用此ID在官网搜索您的视频)`;
392
+ }
393
+
394
+ stream.write(
395
+ "data: " +
396
+ JSON.stringify({
397
+ id: util.uuid(),
398
+ model: _model,
399
+ object: "chat.completion.chunk",
400
+ choices: [
401
+ {
402
+ index: 1,
403
+ delta: {
404
+ role: "assistant",
405
+ content: `\n\n${errorMessage}`,
406
+ },
407
+ finish_reason: "stop",
408
+ },
409
+ ],
410
+ }) +
411
+ "\n\n"
412
+ );
413
+ stream.end("data: [DONE]\n\n");
414
+ });
415
+ } else {
416
+ // 图像生成
417
+ stream.write(
418
+ "data: " +
419
+ JSON.stringify({
420
+ id: util.uuid(),
421
+ model: _model || model,
422
+ object: "chat.completion.chunk",
423
+ choices: [
424
+ {
425
+ index: 0,
426
+ delta: { role: "assistant", content: "🎨 图像生成中,请稍候..." },
427
+ finish_reason: null,
428
+ },
429
+ ],
430
+ }) +
431
+ "\n\n"
432
+ );
433
+
434
+ generateImages(
435
+ model,
436
+ messages[messages.length - 1].content,
437
+ { width, height },
438
+ refreshToken
439
+ )
440
+ .then((imageUrls) => {
441
+ for (let i = 0; i < imageUrls.length; i++) {
442
+ const url = imageUrls[i];
443
+ stream.write(
444
+ "data: " +
445
+ JSON.stringify({
446
+ id: util.uuid(),
447
+ model: _model || model,
448
+ object: "chat.completion.chunk",
449
+ choices: [
450
+ {
451
+ index: i + 1,
452
+ delta: {
453
+ role: "assistant",
454
+ content: `![image_${i}](${url})\n`,
455
+ },
456
+ finish_reason: i < imageUrls.length - 1 ? null : "stop",
457
+ },
458
+ ],
459
+ }) +
460
+ "\n\n"
461
+ );
462
+ }
463
+ stream.write(
464
+ "data: " +
465
+ JSON.stringify({
466
+ id: util.uuid(),
467
+ model: _model || model,
468
+ object: "chat.completion.chunk",
469
+ choices: [
470
+ {
471
+ index: imageUrls.length + 1,
472
+ delta: {
473
+ role: "assistant",
474
+ content: "图像生成完成!",
475
+ },
476
+ finish_reason: "stop",
477
+ },
478
+ ],
479
+ }) +
480
+ "\n\n"
481
+ );
482
+ stream.end("data: [DONE]\n\n");
483
+ })
484
+ .catch((err) => {
485
+ stream.write(
486
+ "data: " +
487
+ JSON.stringify({
488
+ id: util.uuid(),
489
+ model: _model || model,
490
+ object: "chat.completion.chunk",
491
+ choices: [
492
+ {
493
+ index: 1,
494
+ delta: {
495
+ role: "assistant",
496
+ content: `生成图片失败: ${err.message}`,
497
+ },
498
+ finish_reason: "stop",
499
+ },
500
+ ],
501
+ }) +
502
+ "\n\n"
503
+ );
504
+ stream.end("data: [DONE]\n\n");
505
+ });
506
+ }
507
+ return stream;
508
+ })().catch((err) => {
509
+ if (retryCount < MAX_RETRY_COUNT) {
510
+ logger.error(`Response error: ${err.stack}`);
511
+ logger.warn(`Try again after ${RETRY_DELAY / 1000}s...`);
512
+ return (async () => {
513
+ await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY));
514
+ return createCompletionStream(
515
+ messages,
516
+ refreshToken,
517
+ _model,
518
+ retryCount + 1
519
+ );
520
+ })();
521
+ }
522
+ throw err;
523
+ });
524
+ }
src/api/controllers/core.ts ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { PassThrough } from "stream";
2
+ import path from "path";
3
+ import _ from "lodash";
4
+ import mime from "mime";
5
+ import axios, { AxiosRequestConfig, AxiosResponse } from "axios";
6
+
7
+ import APIException from "@/lib/exceptions/APIException.ts";
8
+ import EX from "@/api/consts/exceptions.ts";
9
+ import { createParser } from "eventsource-parser";
10
+ import logger from "@/lib/logger.ts";
11
+ import util from "@/lib/util.ts";
12
+
13
+ // 模型名称
14
+ const MODEL_NAME = "jimeng";
15
+ // 默认的AgentID
16
+ const DEFAULT_ASSISTANT_ID = 513695;
17
+ // 版本号
18
+ const VERSION_CODE = "5.8.0";
19
+ // 平台代码
20
+ const PLATFORM_CODE = "7";
21
+ // 设备ID
22
+ const DEVICE_ID = Math.random() * 999999999999999999 + 7000000000000000000;
23
+ // WebID
24
+ const WEB_ID = Math.random() * 999999999999999999 + 7000000000000000000;
25
+ // 用户ID
26
+ const USER_ID = util.uuid(false);
27
+ // 最大重试次数
28
+ const MAX_RETRY_COUNT = 3;
29
+ // 重试延迟
30
+ const RETRY_DELAY = 5000;
31
+ // 伪装headers
32
+ const FAKE_HEADERS = {
33
+ Accept: "application/json, text/plain, */*",
34
+ "Accept-Encoding": "gzip, deflate, br, zstd",
35
+ "Accept-language": "zh-CN,zh;q=0.9",
36
+ "Cache-control": "no-cache",
37
+ Appid: DEFAULT_ASSISTANT_ID,
38
+ Appvr: VERSION_CODE,
39
+ Origin: "https://jimeng.jianying.com",
40
+ Pragma: "no-cache",
41
+ Priority: "u=1, i",
42
+ Referer: "https://jimeng.jianying.com",
43
+ Pf: PLATFORM_CODE,
44
+ "Sec-Ch-Ua":
45
+ '"Google Chrome";v="142", "Chromium";v="142", "Not_A Brand";v="99"',
46
+ "Sec-Ch-Ua-Mobile": "?0",
47
+ "Sec-Ch-Ua-Platform": '"Windows"',
48
+ "Sec-Fetch-Dest": "empty",
49
+ "Sec-Fetch-Mode": "cors",
50
+ "Sec-Fetch-Site": "same-origin",
51
+ "User-Agent":
52
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36",
53
+ };
54
+ // 文件最大大小
55
+ const FILE_MAX_SIZE = 100 * 1024 * 1024;
56
+
57
+ /**
58
+ * 获取缓存中的access_token
59
+ *
60
+ * 目前jimeng的access_token是固定的,暂无刷新功能
61
+ *
62
+ * @param refreshToken 用于刷新access_token的refresh_token
63
+ */
64
+ export async function acquireToken(refreshToken: string): Promise<string> {
65
+ return refreshToken;
66
+ }
67
+
68
+ /**
69
+ * 生成cookie
70
+ */
71
+ export function generateCookie(refreshToken: string) {
72
+ return [
73
+ `_tea_web_id=${WEB_ID}`,
74
+ `is_staff_user=false`,
75
+ `store-region=cn-gd`,
76
+ `store-region-src=uid`,
77
+ `sid_guard=${refreshToken}%7C${util.unixTimestamp()}%7C5184000%7CMon%2C+03-Feb-2025+08%3A17%3A09+GMT`,
78
+ `uid_tt=${USER_ID}`,
79
+ `uid_tt_ss=${USER_ID}`,
80
+ `sid_tt=${refreshToken}`,
81
+ `sessionid=${refreshToken}`,
82
+ `sessionid_ss=${refreshToken}`,
83
+ `sid_tt=${refreshToken}`
84
+ ].join("; ");
85
+ }
86
+
87
+ /**
88
+ * 获取积分信息
89
+ *
90
+ * @param refreshToken 用于刷新access_token的refresh_token
91
+ */
92
+ export async function getCredit(refreshToken: string) {
93
+ const {
94
+ credit: { gift_credit, purchase_credit, vip_credit }
95
+ } = await request("POST", "/commerce/v1/benefits/user_credit", refreshToken, {
96
+ data: {},
97
+ headers: {
98
+ // Cookie: 'x-web-secsdk-uid=ef44bd0d-0cf6-448c-b517-fd1b5a7267ba; s_v_web_id=verify_m4b1lhlu_DI8qKRlD_7mJJ_4eqx_9shQ_s8eS2QLAbc4n; passport_csrf_token=86f3619c0c4a9c13f24117f71dc18524; passport_csrf_token_default=86f3619c0c4a9c13f24117f71dc18524; n_mh=9-mIeuD4wZnlYrrOvfzG3MuT6aQmCUtmr8FxV8Kl8xY; sid_guard=a7eb745aec44bb3186dbc2083ea9e1a6%7C1733386629%7C5184000%7CMon%2C+03-Feb-2025+08%3A17%3A09+GMT; uid_tt=59a46c7d3f34bda9588b93590cca2e12; uid_tt_ss=59a46c7d3f34bda9588b93590cca2e12; sid_tt=a7eb745aec44bb3186dbc2083ea9e1a6; sessionid=a7eb745aec44bb3186dbc2083ea9e1a6; sessionid_ss=a7eb745aec44bb3186dbc2083ea9e1a6; is_staff_user=false; sid_ucp_v1=1.0.0-KGRiOGY2ODQyNWU1OTk3NzRhYTE2ZmZhYmFjNjdmYjY3NzRmZGRiZTgKHgjToPCw0cwbEIXDxboGGJ-tHyAMMITDxboGOAhAJhoCaGwiIGE3ZWI3NDVhZWM0NGJiMzE4NmRiYzIwODNlYTllMWE2; ssid_ucp_v1=1.0.0-KGRiOGY2ODQyNWU1OTk3NzRhYTE2ZmZhYmFjNjdmYjY3NzRmZGRiZTgKHgjToPCw0cwbEIXDxboGGJ-tHyAMMITDxboGOAhAJhoCaGwiIGE3ZWI3NDVhZWM0NGJiMzE4NmRiYzIwODNlYTllMWE2; store-region=cn-gd; store-region-src=uid; user_spaces_idc={"7444764277623653426":"lf"}; ttwid=1|cxHJViEev1mfkjntdMziir8SwbU8uPNVSaeh9QpEUs8|1733966961|d8d52f5f56607427691be4ac44253f7870a34d25dd05a01b4d89b8a7c5ea82ad; _tea_web_id=7444838473275573797; fpk1=fa6c6a4d9ba074b90003896f36b6960066521c1faec6a60bdcb69ec8ddf85e8360b4c0704412848ec582b2abca73d57a; odin_tt=efe9dc150207879b88509e651a1c4af4e7ffb4cfcb522425a75bd72fbf894eda570bbf7ffb551c8b1de0aa2bfa0bd1be6c4157411ecdcf4464fcaf8dd6657d66',
99
+ Referer: "https://jimeng.jianying.com/ai-tool/image/generate",
100
+ // "Device-Time": 1733966964,
101
+ // Sign: "f3dbb824b378abea7c03cbb152b3a365"
102
+ }
103
+ });
104
+ logger.info(`\n积分信息: \n赠送积分: ${gift_credit}, 购买积分: ${purchase_credit}, VIP积分: ${vip_credit}`);
105
+ return {
106
+ giftCredit: gift_credit,
107
+ purchaseCredit: purchase_credit,
108
+ vipCredit: vip_credit,
109
+ totalCredit: gift_credit + purchase_credit + vip_credit
110
+ }
111
+ }
112
+
113
+ /**
114
+ * 接收今日积分
115
+ *
116
+ * @param refreshToken 用于刷新access_token的refresh_token
117
+ */
118
+ export async function receiveCredit(refreshToken: string) {
119
+ logger.info("���在收取今日积分...")
120
+ const { cur_total_credits, receive_quota } = await request("POST", "/commerce/v1/benefits/credit_receive", refreshToken, {
121
+ data: {
122
+ time_zone: "Asia/Shanghai"
123
+ },
124
+ headers: {
125
+ Referer: "https://jimeng.jianying.com/ai-tool/image/generate"
126
+ }
127
+ });
128
+ logger.info(`\n今日${receive_quota}积分收取成功\n剩余积分: ${cur_total_credits}`);
129
+ return cur_total_credits;
130
+ }
131
+
132
+ /**
133
+ * 请求jimeng
134
+ *
135
+ * @param method 请求方法
136
+ * @param uri 请求路径
137
+ * @param params 请求参数
138
+ * @param headers 请求头
139
+ */
140
+ export async function request(
141
+ method: string,
142
+ uri: string,
143
+ refreshToken: string,
144
+ options: AxiosRequestConfig = {}
145
+ ) {
146
+ const token = await acquireToken(refreshToken);
147
+ const deviceTime = util.unixTimestamp();
148
+ const sign = util.md5(
149
+ `9e2c|${uri.slice(-7)}|${PLATFORM_CODE}|${VERSION_CODE}|${deviceTime}||11ac`
150
+ );
151
+
152
+ const fullUrl = `https://jimeng.jianying.com${uri}`;
153
+ const requestParams = {
154
+ aid: DEFAULT_ASSISTANT_ID,
155
+ device_platform: "web",
156
+ region: "CN",
157
+ webId: WEB_ID,
158
+ da_version: "3.3.2",
159
+ web_component_open_flag: 1,
160
+ web_version: "7.5.0",
161
+ aigc_features: "app_lip_sync",
162
+ ...(options.params || {}),
163
+ };
164
+
165
+ const headers = {
166
+ ...FAKE_HEADERS,
167
+ Cookie: generateCookie(token),
168
+ "Device-Time": deviceTime,
169
+ Sign: sign,
170
+ "Sign-Ver": "1",
171
+ ...(options.headers || {}),
172
+ };
173
+
174
+ logger.info(`发送请求: ${method.toUpperCase()} ${fullUrl}`);
175
+ logger.info(`请求参数: ${JSON.stringify(requestParams)}`);
176
+ logger.info(`请求数据: ${JSON.stringify(options.data || {})}`);
177
+
178
+ // 添加重试逻辑
179
+ let retries = 0;
180
+ const maxRetries = 3; // 最大重试次数
181
+ let lastError = null;
182
+
183
+ while (retries <= maxRetries) {
184
+ try {
185
+ if (retries > 0) {
186
+ logger.info(`第 ${retries} 次重试请求: ${method.toUpperCase()} ${fullUrl}`);
187
+ // 重试前等待一段时间
188
+ await new Promise(resolve => setTimeout(resolve, 1000 * retries));
189
+ }
190
+
191
+ const response = await axios.request({
192
+ method,
193
+ url: fullUrl,
194
+ params: requestParams,
195
+ headers: headers,
196
+ timeout: 45000, // 增加超时时间到45秒
197
+ validateStatus: () => true, // 允许任何状态码
198
+ ..._.omit(options, "params", "headers"),
199
+ });
200
+
201
+ // 记录响应状态和头信息
202
+ logger.info(`响应状态: ${response.status} ${response.statusText}`);
203
+
204
+ // 流式响应直接返回response
205
+ if (options.responseType == "stream") return response;
206
+
207
+ // 记录响应数据摘要
208
+ const responseDataSummary = JSON.stringify(response.data).substring(0, 500) +
209
+ (JSON.stringify(response.data).length > 500 ? "..." : "");
210
+ logger.info(`响应数据摘要: ${responseDataSummary}`);
211
+
212
+ // 检查HTTP状态码
213
+ if (response.status >= 400) {
214
+ logger.warn(`HTTP错误: ${response.status} ${response.statusText}`);
215
+ if (retries < maxRetries) {
216
+ retries++;
217
+ continue;
218
+ }
219
+ }
220
+
221
+ return checkResult(response);
222
+ }
223
+ catch (error) {
224
+ lastError = error;
225
+ logger.error(`请求失败 (尝试 ${retries + 1}/${maxRetries + 1}): ${error.message}`);
226
+
227
+ // 如果是网络错误或超时,尝试重试
228
+ if ((error.code === 'ECONNABORTED' || error.code === 'ETIMEDOUT' ||
229
+ error.message.includes('timeout') || error.message.includes('network')) &&
230
+ retries < maxRetries) {
231
+ retries++;
232
+ continue;
233
+ }
234
+
235
+ // 其他错误直接抛出
236
+ break;
237
+ }
238
+ }
239
+
240
+ // 所有重试都失败了,抛出最后一个错误
241
+ logger.error(`请求失败,已重试 ${retries} 次: ${lastError.message}`);
242
+ if (lastError.response) {
243
+ logger.error(`响应状态: ${lastError.response.status}`);
244
+ logger.error(`响应数据: ${JSON.stringify(lastError.response.data)}`);
245
+ }
246
+ throw lastError;
247
+ }
248
+
249
+ /**
250
+ * 预检查文件URL有效性
251
+ *
252
+ * @param fileUrl 文件URL
253
+ */
254
+ export async function checkFileUrl(fileUrl: string) {
255
+ if (util.isBASE64Data(fileUrl)) return;
256
+ const result = await axios.head(fileUrl, {
257
+ timeout: 15000,
258
+ validateStatus: () => true,
259
+ });
260
+ if (result.status >= 400)
261
+ throw new APIException(
262
+ EX.API_FILE_URL_INVALID,
263
+ `File ${fileUrl} is not valid: [${result.status}] ${result.statusText}`
264
+ );
265
+ // 检查文件大小
266
+ if (result.headers && result.headers["content-length"]) {
267
+ const fileSize = parseInt(result.headers["content-length"], 10);
268
+ if (fileSize > FILE_MAX_SIZE)
269
+ throw new APIException(
270
+ EX.API_FILE_EXECEEDS_SIZE,
271
+ `File ${fileUrl} is not valid`
272
+ );
273
+ }
274
+ }
275
+
276
+ /**
277
+ * 上传文件
278
+ *
279
+ * @param refreshToken 用于刷新access_token的refresh_token
280
+ * @param fileUrl 文件URL或BASE64数据
281
+ * @param isVideoImage 是否是用于视频图像
282
+ * @returns 上传结果,包含image_uri
283
+ */
284
+ export async function uploadFile(
285
+ refreshToken: string,
286
+ fileUrl: string,
287
+ isVideoImage: boolean = false
288
+ ) {
289
+ try {
290
+ logger.info(`开始上传文件: ${fileUrl}, 视频图像模式: ${isVideoImage}`);
291
+
292
+ // 预检查远程文件URL可用性
293
+ await checkFileUrl(fileUrl);
294
+
295
+ let filename, fileData, mimeType;
296
+ // 如果是BASE64数据则直接转换为Buffer
297
+ if (util.isBASE64Data(fileUrl)) {
298
+ mimeType = util.extractBASE64DataFormat(fileUrl);
299
+ const ext = mime.getExtension(mimeType);
300
+ filename = `${util.uuid()}.${ext}`;
301
+ fileData = Buffer.from(util.removeBASE64DataHeader(fileUrl), "base64");
302
+ logger.info(`处理BASE64数据,文件名: ${filename}, 类型: ${mimeType}, 大小: ${fileData.length}字节`);
303
+ }
304
+ // 下载文件到内存,如果您的服务器内存很小,建议考虑改造为流直传到下一个接口上,避免停留占用内存
305
+ else {
306
+ filename = path.basename(fileUrl);
307
+ logger.info(`开始下载远程文件: ${fileUrl}`);
308
+ ({ data: fileData } = await axios.get(fileUrl, {
309
+ responseType: "arraybuffer",
310
+ // 100M限制
311
+ maxContentLength: FILE_MAX_SIZE,
312
+ // 60秒超时
313
+ timeout: 60000,
314
+ }));
315
+ logger.info(`文件下载完成,文件名: ${filename}, 大小: ${fileData.length}字节`);
316
+ }
317
+
318
+ // 获取文件的MIME类型
319
+ mimeType = mimeType || mime.getType(filename);
320
+ logger.info(`文件MIME类型: ${mimeType}`);
321
+
322
+ // 构建FormData
323
+ const formData = new FormData();
324
+ const blob = new Blob([fileData], { type: mimeType });
325
+ formData.append('file', blob, filename);
326
+
327
+ // 获取上传凭证
328
+ logger.info(`请求上传凭证,场景: ${isVideoImage ? 'video_cover' : 'aigc_image'}`);
329
+ const uploadProofUrl = 'https://imagex.bytedanceapi.com/';
330
+ const proofResult = await request(
331
+ 'POST',
332
+ '/mweb/v1/get_upload_image_proof',
333
+ refreshToken,
334
+ {
335
+ data: {
336
+ scene: isVideoImage ? 'video_cover' : 'aigc_image',
337
+ file_name: filename,
338
+ file_size: fileData.length,
339
+ }
340
+ }
341
+ );
342
+
343
+ if (!proofResult || !proofResult.proof_info) {
344
+ logger.error(`获取上传凭证失败: ${JSON.stringify(proofResult)}`);
345
+ throw new APIException(EX.API_REQUEST_FAILED, '获取上传凭证失败');
346
+ }
347
+
348
+ logger.info(`获取上传凭证成功`);
349
+
350
+ // 上传文件
351
+ const { proof_info } = proofResult;
352
+ logger.info(`开始上传文件到: ${uploadProofUrl}`);
353
+
354
+ const uploadResult = await axios.post(
355
+ uploadProofUrl,
356
+ formData,
357
+ {
358
+ headers: {
359
+ ...proof_info.headers,
360
+ 'Content-Type': 'multipart/form-data',
361
+ },
362
+ params: proof_info.query_params,
363
+ timeout: 60000,
364
+ validateStatus: () => true, // 允许任何状态码以便详细处理
365
+ }
366
+ );
367
+
368
+ logger.info(`上传响应状态: ${uploadResult.status}`);
369
+
370
+ if (!uploadResult || uploadResult.status !== 200) {
371
+ logger.error(`上传文件失败: 状态码 ${uploadResult?.status}, 响应: ${JSON.stringify(uploadResult?.data)}`);
372
+ throw new APIException(EX.API_REQUEST_FAILED, `上传文件失败: 状态码 ${uploadResult?.status}`);
373
+ }
374
+
375
+ // 验证 proof_info.image_uri 是否存在
376
+ if (!proof_info.image_uri) {
377
+ logger.error(`上传凭证中缺少 image_uri: ${JSON.stringify(proof_info)}`);
378
+ throw new APIException(EX.API_REQUEST_FAILED, '上传凭证中缺少 image_uri');
379
+ }
380
+
381
+ logger.info(`文件上传成功: ${proof_info.image_uri}`);
382
+
383
+ // 返回上传结果
384
+ return {
385
+ image_uri: proof_info.image_uri,
386
+ uri: proof_info.image_uri,
387
+ }
388
+ } catch (error) {
389
+ logger.error(`文件上传过程中发生错误: ${error.message}`);
390
+ throw error;
391
+ }
392
+ }
393
+
394
+ /**
395
+ * 检查请求结果
396
+ *
397
+ * @param result 结果
398
+ */
399
+ export function checkResult(result: AxiosResponse) {
400
+ const { ret, errmsg, data } = result.data;
401
+ if (!_.isFinite(Number(ret))) return result.data;
402
+ if (ret === '0') return data;
403
+ if (ret === '5000')
404
+ throw new APIException(EX.API_IMAGE_GENERATION_INSUFFICIENT_POINTS, `[无法生成图像]: 即梦积分可能不足,${errmsg}`);
405
+ throw new APIException(EX.API_REQUEST_FAILED, `[请求jimeng失败]: ${errmsg}`);
406
+ }
407
+
408
+ /**
409
+ * Token切分
410
+ *
411
+ * @param authorization 认证字符串
412
+ */
413
+ export function tokenSplit(authorization: string) {
414
+ return authorization.replace("Bearer ", "").split(",");
415
+ }
416
+
417
+ /**
418
+ * 获取Token存活状态
419
+ */
420
+ export async function getTokenLiveStatus(refreshToken: string) {
421
+ const result = await request(
422
+ "POST",
423
+ "/passport/account/info/v2",
424
+ refreshToken,
425
+ {
426
+ params: {
427
+ account_sdk_source: "web",
428
+ },
429
+ }
430
+ );
431
+ try {
432
+ const { user_id } = checkResult(result);
433
+ return !!user_id;
434
+ } catch (err) {
435
+ return false;
436
+ }
437
+ }
src/api/controllers/images.ts ADDED
@@ -0,0 +1,1480 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import _ from "lodash";
2
+ import crypto from "crypto";
3
+
4
+ import APIException from "@/lib/exceptions/APIException.ts";
5
+ import EX from "@/api/consts/exceptions.ts";
6
+ import util from "@/lib/util.ts";
7
+ import { getCredit, receiveCredit, request } from "./core.ts";
8
+ import logger from "@/lib/logger.ts";
9
+ import { getModelConfig } from "@/lib/configs/model-config.ts";
10
+
11
+ const DEFAULT_ASSISTANT_ID = 513695;
12
+ export const DEFAULT_MODEL = "jimeng-4.5";
13
+ const DRAFT_VERSION = "3.3.4";
14
+ const DRAFT_MIN_VERSION = "3.0.2";
15
+
16
+ // 支持的图片比例和分辨率配置
17
+ const RESOLUTION_OPTIONS: {
18
+ [resolution: string]: {
19
+ [ratio: string]: { width: number; height: number; ratio: number };
20
+ };
21
+ } = {
22
+ "1k": {
23
+ "1:1": { width: 1024, height: 1024, ratio: 1 },
24
+ "4:3": { width: 768, height: 1024, ratio: 4 },
25
+ "3:4": { width: 1024, height: 768, ratio: 2 },
26
+ "16:9": { width: 1024, height: 576, ratio: 3 },
27
+ "9:16": { width: 576, height: 1024, ratio: 5 },
28
+ "3:2": { width: 1024, height: 682, ratio: 7 },
29
+ "2:3": { width: 682, height: 1024, ratio: 6 },
30
+ "21:9": { width: 1195, height: 512, ratio: 8 },
31
+ },
32
+ "2k": {
33
+ "1:1": { width: 2048, height: 2048, ratio: 1 },
34
+ "4:3": { width: 2304, height: 1728, ratio: 4 },
35
+ "3:4": { width: 1728, height: 2304, ratio: 2 },
36
+ "16:9": { width: 2560, height: 1440, ratio: 3 },
37
+ "9:16": { width: 1440, height: 2560, ratio: 5 },
38
+ "3:2": { width: 2496, height: 1664, ratio: 7 },
39
+ "2:3": { width: 1664, height: 2496, ratio: 6 },
40
+ "21:9": { width: 3024, height: 1296, ratio: 8 },
41
+ },
42
+ "4k": {
43
+ "1:1": { width: 4096, height: 4096, ratio: 101 },
44
+ "4:3": { width: 4608, height: 3456, ratio: 104 },
45
+ "3:4": { width: 3456, height: 4608, ratio: 102 },
46
+ "16:9": { width: 5120, height: 2880, ratio: 103 },
47
+ "9:16": { width: 2880, height: 5120, ratio: 105 },
48
+ "3:2": { width: 4992, height: 3328, ratio: 107 },
49
+ "2:3": { width: 3328, height: 4992, ratio: 106 },
50
+ "21:9": { width: 6048, height: 2592, ratio: 108 },
51
+ },
52
+ };
53
+
54
+ // 解析分辨率参数
55
+ function resolveResolution(
56
+ resolution: string = "2k",
57
+ ratio: string = "1:1"
58
+ ): { width: number; height: number; imageRatio: number; resolutionType: string } {
59
+ const resolutionGroup = RESOLUTION_OPTIONS[resolution];
60
+ if (!resolutionGroup) {
61
+ const supportedResolutions = Object.keys(RESOLUTION_OPTIONS).join(", ");
62
+ throw new Error(`不支持的分辨率 "${resolution}"。支持的分辨率: ${supportedResolutions}`);
63
+ }
64
+
65
+ const ratioConfig = resolutionGroup[ratio];
66
+ if (!ratioConfig) {
67
+ const supportedRatios = Object.keys(resolutionGroup).join(", ");
68
+ throw new Error(`在 "${resolution}" 分辨率下,不支持的比例 "${ratio}"。支持的比例: ${supportedRatios}`);
69
+ }
70
+
71
+ return {
72
+ width: ratioConfig.width,
73
+ height: ratioConfig.height,
74
+ imageRatio: ratioConfig.ratio,
75
+ resolutionType: resolution,
76
+ };
77
+ }
78
+
79
+ // 模型特定的版本配置
80
+ const MODEL_DRAFT_VERSIONS: { [key: string]: string } = {
81
+ "jimeng-5.0-preview": "3.3.9",
82
+ "jimeng-4.6": "3.3.9",
83
+ "jimeng-4.5": "3.3.4",
84
+ "jimeng-4.1": "3.3.4",
85
+ "jimeng-4.0": "3.3.4",
86
+ "jimeng-3.1": "3.0.2",
87
+ "jimeng-3.0": "3.0.2",
88
+ "jimeng-2.1": "3.0.2",
89
+ "jimeng-2.0-pro": "3.0.2",
90
+ "jimeng-2.0": "3.0.2",
91
+ "jimeng-1.4": "3.0.2",
92
+ "jimeng-xl-pro": "3.0.2",
93
+ };
94
+
95
+ // 获取模型对应的draft版本
96
+ function getDraftVersion(model: string): string {
97
+ try {
98
+ const config = getModelConfig(model);
99
+ return config.draftVersion;
100
+ } catch (e) {
101
+ // 如果配置中没有,使用旧的映射
102
+ return MODEL_DRAFT_VERSIONS[model] || DRAFT_VERSION;
103
+ }
104
+ }
105
+ const MODEL_MAP = {
106
+ "jimeng-5.0-preview": "high_aes_general_v50",
107
+ "jimeng-4.6": "high_aes_general_v42",
108
+ "jimeng-4.5": "high_aes_general_v40l",
109
+ "jimeng-4.1": "high_aes_general_v41",
110
+ "jimeng-4.0": "high_aes_general_v40",
111
+ "jimeng-3.1": "high_aes_general_v30l_art_fangzhou:general_v3.0_18b",
112
+ "jimeng-3.0": "high_aes_general_v30l:general_v3.0_18b",
113
+ "jimeng-2.1": "high_aes_general_v21_L:general_v2.1_L",
114
+ "jimeng-2.0-pro": "high_aes_general_v20_L:general_v2.0_L",
115
+ "jimeng-2.0": "high_aes_general_v20:general_v2.0",
116
+ "jimeng-1.4": "high_aes_general_v14:general_v1.4",
117
+ "jimeng-xl-pro": "text2img_xl_sft",
118
+ };
119
+
120
+ // 向后兼容的函数
121
+ export function getModel(model: string) {
122
+ try {
123
+ const config = getModelConfig(model);
124
+ return config.internalModel;
125
+ } catch (e) {
126
+ // 如果配置中没有,使用旧的映射
127
+ return MODEL_MAP[model] || MODEL_MAP[DEFAULT_MODEL];
128
+ }
129
+ }
130
+
131
+
132
+ // AWS4-HMAC-SHA256 签名生成函数
133
+ function createSignature(
134
+ method: string,
135
+ url: string,
136
+ headers: { [key: string]: string },
137
+ accessKeyId: string,
138
+ secretAccessKey: string,
139
+ sessionToken?: string,
140
+ payload: string = ''
141
+ ) {
142
+ const urlObj = new URL(url);
143
+ const pathname = urlObj.pathname || '/';
144
+ const search = urlObj.search;
145
+
146
+ // 创建规范请求
147
+ const timestamp = headers['x-amz-date'];
148
+ const date = timestamp.substr(0, 8);
149
+ const region = 'cn-north-1';
150
+ const service = 'imagex';
151
+
152
+ // 规范化查询参数 - 手动处理以确保正确的顺序
153
+ const queryParams: Array<[string, string]> = [];
154
+ const searchParams = new URLSearchParams(search);
155
+ searchParams.forEach((value, key) => {
156
+ queryParams.push([key, value]);
157
+ });
158
+
159
+ // 按键名排序 - 大小写敏感,先大写字母,后小写字母
160
+ queryParams.sort(([a], [b]) => {
161
+ // AWS要求大小写敏感的ASCII排序
162
+ if (a < b) return -1;
163
+ if (a > b) return 1;
164
+ return 0;
165
+ });
166
+
167
+ // 构建规范查询字符串(不进行额外编码,因为URL中已经编码)
168
+ const canonicalQueryString = queryParams
169
+ .map(([key, value]) => `${key}=${value}`)
170
+ .join('&');
171
+
172
+ // 规范化头部 - 只包含必要的头部
173
+ const headersToSign: { [key: string]: string } = {
174
+ 'x-amz-date': timestamp
175
+ };
176
+
177
+ // 添加 session token
178
+ if (sessionToken) {
179
+ headersToSign['x-amz-security-token'] = sessionToken;
180
+ }
181
+
182
+ // 如果是POST请求且包含payload,添加content-sha256头
183
+ let payloadHash = crypto.createHash('sha256').update('').digest('hex'); // 默认空payload
184
+ if (method.toUpperCase() === 'POST' && payload) {
185
+ payloadHash = crypto.createHash('sha256').update(payload, 'utf8').digest('hex');
186
+ headersToSign['x-amz-content-sha256'] = payloadHash;
187
+ }
188
+
189
+ const signedHeaders = Object.keys(headersToSign)
190
+ .map(key => key.toLowerCase())
191
+ .sort()
192
+ .join(';');
193
+
194
+ const canonicalHeaders = Object.keys(headersToSign)
195
+ .sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()))
196
+ .map(key => `${key.toLowerCase()}:${headersToSign[key].trim()}\n`)
197
+ .join('');
198
+
199
+ // 创建规范请求
200
+ const canonicalRequest = [
201
+ method.toUpperCase(),
202
+ pathname,
203
+ canonicalQueryString,
204
+ canonicalHeaders,
205
+ signedHeaders,
206
+ payloadHash
207
+ ].join('\n');
208
+
209
+ // 调试输出
210
+ logger.debug(`规范请求:
211
+ Method: ${method.toUpperCase()}
212
+ Path: ${pathname}
213
+ Query: ${canonicalQueryString}
214
+ Headers: ${canonicalHeaders}
215
+ SignedHeaders: ${signedHeaders}
216
+ PayloadHash: ${payloadHash}
217
+ ---完整规范请求---
218
+ ${canonicalRequest}
219
+ ---结束---`);
220
+
221
+ // 创建待签名字符串
222
+ const credentialScope = `${date}/${region}/${service}/aws4_request`;
223
+ const stringToSign = [
224
+ 'AWS4-HMAC-SHA256',
225
+ timestamp,
226
+ credentialScope,
227
+ crypto.createHash('sha256').update(canonicalRequest, 'utf8').digest('hex')
228
+ ].join('\n');
229
+
230
+ logger.debug(`待签名字符串:
231
+ ${stringToSign}`);
232
+
233
+ // 生成签名
234
+ const kDate = crypto.createHmac('sha256', `AWS4${secretAccessKey}`).update(date).digest();
235
+ const kRegion = crypto.createHmac('sha256', kDate).update(region).digest();
236
+ const kService = crypto.createHmac('sha256', kRegion).update(service).digest();
237
+ const kSigning = crypto.createHmac('sha256', kService).update('aws4_request').digest();
238
+ const signature = crypto.createHmac('sha256', kSigning).update(stringToSign, 'utf8').digest('hex');
239
+
240
+ return `AWS4-HMAC-SHA256 Credential=${accessKeyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;
241
+ }
242
+
243
+ // 计算文件的CRC32值
244
+ function calculateCRC32(buffer: ArrayBuffer): string {
245
+ const crcTable = [];
246
+ for (let i = 0; i < 256; i++) {
247
+ let crc = i;
248
+ for (let j = 0; j < 8; j++) {
249
+ crc = (crc & 1) ? (0xEDB88320 ^ (crc >>> 1)) : (crc >>> 1);
250
+ }
251
+ crcTable[i] = crc;
252
+ }
253
+
254
+ let crc = 0 ^ (-1);
255
+ const bytes = new Uint8Array(buffer);
256
+ for (let i = 0; i < bytes.length; i++) {
257
+ crc = (crc >>> 8) ^ crcTable[(crc ^ bytes[i]) & 0xFF];
258
+ }
259
+ return ((crc ^ (-1)) >>> 0).toString(16).padStart(8, '0');
260
+ }
261
+
262
+ // 图片上传功能:将外部图片URL上传到即梦系统
263
+ async function uploadImageFromUrl(imageUrl: string, refreshToken: string): Promise<string> {
264
+ try {
265
+ logger.info(`开始上传图片: ${imageUrl}`);
266
+
267
+ // 第一步:获取上传令牌
268
+ const tokenResult = await request("post", "/mweb/v1/get_upload_token", refreshToken, {
269
+ data: {
270
+ scene: 2, // AIGC 图片上传场景
271
+ },
272
+ });
273
+
274
+ const { access_key_id, secret_access_key, session_token, service_id } = tokenResult;
275
+ if (!access_key_id || !secret_access_key || !session_token) {
276
+ throw new Error("获取上传令牌失败");
277
+ }
278
+
279
+ // 使用固定的service_id
280
+ const actualServiceId = service_id || "tb4s082cfz";
281
+
282
+ logger.info(`获取上传令牌成功: service_id=${actualServiceId}`);
283
+
284
+ // 下载图片数据
285
+ const imageResponse = await fetch(imageUrl);
286
+ if (!imageResponse.ok) {
287
+ throw new Error(`下载图片失败: ${imageResponse.status}`);
288
+ }
289
+
290
+ const imageBuffer = await imageResponse.arrayBuffer();
291
+ const fileSize = imageBuffer.byteLength;
292
+ const crc32 = calculateCRC32(imageBuffer);
293
+
294
+ logger.info(`图片下载完成: 大小=${fileSize}字节, CRC32=${crc32}`);
295
+
296
+ // 第二步:申请图片上传权限
297
+ // 使用UTC时间格式 YYYYMMDD'T'HHMMSS'Z'
298
+ const now = new Date();
299
+ const timestamp = now.toISOString().replace(/[:\-]/g, '').replace(/\.\d{3}Z$/, 'Z');
300
+
301
+ // 生成随机字符串作为签名参数
302
+ const randomStr = Math.random().toString(36).substring(2, 12);
303
+ // 保持原始的参数顺序(这是API期望的顺序)
304
+ const applyUrl = `https://imagex.bytedanceapi.com/?Action=ApplyImageUpload&Version=2018-08-01&ServiceId=${actualServiceId}&FileSize=${fileSize}&s=${randomStr}`;
305
+
306
+ logger.debug(`原始URL: ${applyUrl}`);
307
+
308
+ // 构建AWS签名所需的头部
309
+ const requestHeaders = {
310
+ 'x-amz-date': timestamp,
311
+ 'x-amz-security-token': session_token
312
+ };
313
+
314
+ // 生成AWS签名
315
+ const authorization = createSignature('GET', applyUrl, requestHeaders, access_key_id, secret_access_key, session_token);
316
+
317
+ // 调试日志
318
+ logger.info(`AWS签名调试信息:
319
+ URL: ${applyUrl}
320
+ AccessKeyId: ${access_key_id}
321
+ SessionToken: ${session_token ? '存在' : '不存在'}
322
+ Timestamp: ${timestamp}
323
+ Authorization: ${authorization}
324
+ `);
325
+
326
+ const applyResponse = await fetch(applyUrl, {
327
+ method: 'GET',
328
+ headers: {
329
+ 'accept': '*/*',
330
+ 'accept-language': 'zh-CN,zh;q=0.9',
331
+ 'authorization': authorization,
332
+ 'origin': 'https://jimeng.jianying.com',
333
+ 'referer': 'https://jimeng.jianying.com/ai-tool/generate',
334
+ 'sec-ch-ua': '"Not A(Brand";v="8", "Chromium";v="132", "Google Chrome";v="132"',
335
+ 'sec-ch-ua-mobile': '?0',
336
+ 'sec-ch-ua-platform': '"Windows"',
337
+ 'sec-fetch-dest': 'empty',
338
+ 'sec-fetch-mode': 'cors',
339
+ 'sec-fetch-site': 'cross-site',
340
+ 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36',
341
+ 'x-amz-date': timestamp,
342
+ 'x-amz-security-token': session_token,
343
+ },
344
+ });
345
+
346
+ if (!applyResponse.ok) {
347
+ const errorText = await applyResponse.text();
348
+ throw new Error(`申请上传权限失败: ${applyResponse.status} - ${errorText}`);
349
+ }
350
+
351
+ const applyResult = await applyResponse.json();
352
+
353
+ // 检查是否有错误
354
+ if (applyResult?.ResponseMetadata?.Error) {
355
+ throw new Error(`申请上传权限失败: ${JSON.stringify(applyResult.ResponseMetadata.Error)}`);
356
+ }
357
+
358
+ logger.info(`申请上传权限成功`);
359
+
360
+ // 解析上传信息
361
+ const uploadAddress = applyResult?.Result?.UploadAddress;
362
+ if (!uploadAddress || !uploadAddress.StoreInfos || !uploadAddress.UploadHosts) {
363
+ throw new Error(`获取上传地址失败: ${JSON.stringify(applyResult)}`);
364
+ }
365
+
366
+ const storeInfo = uploadAddress.StoreInfos[0];
367
+ const uploadHost = uploadAddress.UploadHosts[0];
368
+ const auth = storeInfo.Auth;
369
+
370
+ // 构建上传URL
371
+ const uploadUrl = `https://${uploadHost}/upload/v1/${storeInfo.StoreUri}`;
372
+
373
+ // 提取图片ID (StoreUri最后一个斜杠后的部分)
374
+ const imageId = storeInfo.StoreUri.split('/').pop();
375
+
376
+ logger.info(`准备上传图片: imageId=${imageId}, uploadUrl=${uploadUrl}`);
377
+
378
+ // 第三步:上传图片文件
379
+ const uploadResponse = await fetch(uploadUrl, {
380
+ method: 'POST',
381
+ headers: {
382
+ 'Accept': '*/*',
383
+ 'Accept-Language': 'zh-CN,zh;q=0.9',
384
+ 'Authorization': auth,
385
+ 'Connection': 'keep-alive',
386
+ 'Content-CRC32': crc32,
387
+ 'Content-Disposition': 'attachment; filename="undefined"',
388
+ 'Content-Type': 'application/octet-stream',
389
+ 'Origin': 'https://jimeng.jianying.com',
390
+ 'Referer': 'https://jimeng.jianying.com/ai-tool/generate',
391
+ 'Sec-Fetch-Dest': 'empty',
392
+ 'Sec-Fetch-Mode': 'cors',
393
+ 'Sec-Fetch-Site': 'cross-site',
394
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36',
395
+ 'X-Storage-U': '704135154117550', // 用户ID,可以从token或其他地方获取
396
+ },
397
+ body: imageBuffer,
398
+ });
399
+
400
+ if (!uploadResponse.ok) {
401
+ const errorText = await uploadResponse.text();
402
+ throw new Error(`图片上传失败: ${uploadResponse.status} - ${errorText}`);
403
+ }
404
+
405
+ logger.info(`图片文件上传成功`);
406
+
407
+ // 第四步:提交上传
408
+ const commitUrl = `https://imagex.bytedanceapi.com/?Action=CommitImageUpload&Version=2018-08-01&ServiceId=${actualServiceId}`;
409
+
410
+ const commitTimestamp = new Date().toISOString().replace(/[:\-]/g, '').replace(/\.\d{3}Z$/, 'Z');
411
+ const commitPayload = JSON.stringify({
412
+ SessionKey: uploadAddress.SessionKey,
413
+ SuccessActionStatus: "200"
414
+ });
415
+
416
+ // 计算payload的SHA256哈希值
417
+ const payloadHash = crypto.createHash('sha256').update(commitPayload, 'utf8').digest('hex');
418
+
419
+ // 构建AWS签名所需的头部
420
+ const commitRequestHeaders = {
421
+ 'x-amz-date': commitTimestamp,
422
+ 'x-amz-security-token': session_token,
423
+ 'x-amz-content-sha256': payloadHash
424
+ };
425
+
426
+ // 生成AWS签名
427
+ const commitAuthorization = createSignature('POST', commitUrl, commitRequestHeaders, access_key_id, secret_access_key, session_token, commitPayload);
428
+
429
+ const commitResponse = await fetch(commitUrl, {
430
+ method: 'POST',
431
+ headers: {
432
+ 'accept': '*/*',
433
+ 'accept-language': 'zh-CN,zh;q=0.9',
434
+ 'authorization': commitAuthorization,
435
+ 'content-type': 'application/json',
436
+ 'origin': 'https://jimeng.jianying.com',
437
+ 'referer': 'https://jimeng.jianying.com/ai-tool/generate',
438
+ 'sec-ch-ua': '"Not A(Brand";v="8", "Chromium";v="132", "Google Chrome";v="132"',
439
+ 'sec-ch-ua-mobile': '?0',
440
+ 'sec-ch-ua-platform': '"Windows"',
441
+ 'sec-fetch-dest': 'empty',
442
+ 'sec-fetch-mode': 'cors',
443
+ 'sec-fetch-site': 'cross-site',
444
+ 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36',
445
+ 'x-amz-date': commitTimestamp,
446
+ 'x-amz-security-token': session_token,
447
+ 'x-amz-content-sha256': payloadHash,
448
+ },
449
+ body: commitPayload,
450
+ });
451
+
452
+ if (!commitResponse.ok) {
453
+ const errorText = await commitResponse.text();
454
+ throw new Error(`提交上传失败: ${commitResponse.status} - ${errorText}`);
455
+ }
456
+
457
+ const commitResult = await commitResponse.json();
458
+
459
+ // 检查提交结果
460
+ if (commitResult?.ResponseMetadata?.Error) {
461
+ throw new Error(`提交上传失败: ${JSON.stringify(commitResult.ResponseMetadata.Error)}`);
462
+ }
463
+
464
+ if (!commitResult?.Result?.Results || commitResult.Result.Results.length === 0) {
465
+ throw new Error(`提交上传响应缺少结果: ${JSON.stringify(commitResult)}`);
466
+ }
467
+
468
+ const uploadResult = commitResult.Result.Results[0];
469
+ if (uploadResult.UriStatus !== 2000) {
470
+ throw new Error(`图片上传状态异常: UriStatus=${uploadResult.UriStatus}`);
471
+ }
472
+
473
+ // 获取完整的URI(包含前缀)
474
+ const fullImageUri = uploadResult.Uri; // 如: "tos-cn-i-tb4s082cfz/bab623359bd9410da0c1f07897b16fec"
475
+
476
+ // 验证图片信息
477
+ const pluginResult = commitResult.Result?.PluginResult?.[0];
478
+ if (pluginResult) {
479
+ logger.info(`图片上传成功详情:`, {
480
+ imageUri: pluginResult.ImageUri,
481
+ sourceUri: pluginResult.SourceUri,
482
+ size: `${pluginResult.ImageWidth}x${pluginResult.ImageHeight}`,
483
+ format: pluginResult.ImageFormat,
484
+ fileSize: pluginResult.ImageSize,
485
+ md5: pluginResult.ImageMd5
486
+ });
487
+
488
+ // 优先使用PluginResult中的ImageUri,因为它可能是最准确的
489
+ if (pluginResult.ImageUri) {
490
+ logger.info(`图片上传完成: ${pluginResult.ImageUri}`);
491
+ return pluginResult.ImageUri; // 返回完整的URI
492
+ }
493
+ }
494
+
495
+ logger.info(`图片上传完成: ${fullImageUri}`);
496
+ return fullImageUri; // 返回完整的URI
497
+
498
+ } catch (error) {
499
+ logger.error(`图片上传失败: ${error.message}`);
500
+ throw error;
501
+ }
502
+ }
503
+
504
+ // 从Buffer上传图片
505
+ async function uploadImageBuffer(buffer: Buffer, refreshToken: string): Promise<string> {
506
+ try {
507
+ logger.info(`开始从Buffer上传图片,大小: ${buffer.length}字节`);
508
+
509
+ // 获取上传凭证
510
+ const proofResult = await request(
511
+ 'POST',
512
+ '/mweb/v1/get_upload_image_proof',
513
+ refreshToken,
514
+ {
515
+ data: {
516
+ scene: 'aigc_image',
517
+ file_name: `${util.uuid()}.jpg`,
518
+ file_size: buffer.length,
519
+ }
520
+ }
521
+ );
522
+
523
+ if (!proofResult || !proofResult.proof_info) {
524
+ logger.error(`获取上传凭证失败: ${JSON.stringify(proofResult)}`);
525
+ throw new APIException(EX.API_REQUEST_FAILED, '获取上传凭证失败');
526
+ }
527
+
528
+ logger.info(`获取上传凭证成功`);
529
+
530
+ // 上传文件
531
+ const { proof_info } = proofResult;
532
+ const uploadProofUrl = 'https://imagex.bytedanceapi.com/';
533
+
534
+ const formData = new FormData();
535
+ const blob = new Blob([buffer], { type: 'image/jpeg' });
536
+ formData.append('file', blob, `${util.uuid()}.jpg`);
537
+
538
+ const uploadResult = await fetch(uploadProofUrl + '?' + new URLSearchParams(proof_info.query_params).toString(), {
539
+ method: 'POST',
540
+ headers: proof_info.headers,
541
+ body: formData,
542
+ });
543
+
544
+ if (!uploadResult.ok) {
545
+ logger.error(`上传文件失败: 状态码 ${uploadResult.status}`);
546
+ throw new APIException(EX.API_REQUEST_FAILED, `上传文件失败: 状态码 ${uploadResult.status}`);
547
+ }
548
+
549
+ // 验证 proof_info.image_uri 是否存在
550
+ if (!proof_info.image_uri) {
551
+ logger.error(`上传凭证中缺少 image_uri: ${JSON.stringify(proof_info)}`);
552
+ throw new APIException(EX.API_REQUEST_FAILED, '上传凭证中缺少 image_uri');
553
+ }
554
+
555
+ logger.info(`Buffer图片上传成功: ${proof_info.image_uri}`);
556
+ return proof_info.image_uri;
557
+ } catch (error) {
558
+ logger.error(`Buffer图片上传失败: ${error.message}`);
559
+ throw error;
560
+ }
561
+ }
562
+
563
+ // 图片合成功能:先上传图片,然后进行图生图
564
+ export async function generateImageComposition(
565
+ _model: string,
566
+ prompt: string,
567
+ imageUrls: (string | Buffer)[],
568
+ {
569
+ ratio = "1:1",
570
+ resolution = "2k",
571
+ sampleStrength = 0.5,
572
+ negativePrompt = "",
573
+ intelligentRatio = false,
574
+ }: {
575
+ ratio?: string;
576
+ resolution?: string;
577
+ sampleStrength?: number;
578
+ negativePrompt?: string;
579
+ intelligentRatio?: boolean;
580
+ },
581
+ refreshToken: string
582
+ ) {
583
+ const model = getModel(_model);
584
+ const draftVersion = getDraftVersion(_model);
585
+ const imageCount = imageUrls.length;
586
+
587
+ // 解析分辨率
588
+ const resolutionResult = resolveResolution(resolution, ratio);
589
+ const { width, height, imageRatio, resolutionType } = resolutionResult;
590
+
591
+ logger.info(`使用模型: ${_model} 映射模型: ${model} 图生图功能 ${imageCount}张图片 ${width}x${height} (${ratio}@${resolution}) 精细度: ${sampleStrength}`);
592
+
593
+ const { totalCredit } = await getCredit(refreshToken);
594
+ if (totalCredit <= 0)
595
+ await receiveCredit(refreshToken);
596
+
597
+ // 上传所有输入图片
598
+ const uploadedImageIds: string[] = [];
599
+ for (let i = 0; i < imageUrls.length; i++) {
600
+ try {
601
+ const image = imageUrls[i];
602
+ let imageId: string;
603
+ if (typeof image === 'string') {
604
+ logger.info(`正在处理第 ${i + 1}/${imageCount} 张图片 (URL)...`);
605
+ imageId = await uploadImageFromUrl(image, refreshToken);
606
+ } else {
607
+ logger.info(`正在处理第 ${i + 1}/${imageCount} 张图片 (Buffer)...`);
608
+ imageId = await uploadImageBuffer(image, refreshToken);
609
+ }
610
+ uploadedImageIds.push(imageId);
611
+ logger.info(`图片 ${i + 1}/${imageCount} 上传成功: ${imageId}`);
612
+ } catch (error) {
613
+ logger.error(`图片 ${i + 1}/${imageCount} 上传失败: ${error.message}`);
614
+ throw new APIException(EX.API_IMAGE_GENERATION_FAILED, `图片上传失败: ${error.message}`);
615
+ }
616
+ }
617
+
618
+ logger.info(`所有图片上传完成,开始图生图: ${uploadedImageIds.join(', ')}`);
619
+
620
+ const componentId = util.uuid();
621
+ const submitId = util.uuid();
622
+
623
+ // 构建图生图的 sceneOptions(不包含 benefitCount 以避免扣积分)
624
+ // 注意:sceneOptions 需要是对象,在 metrics_extra 中会被 JSON.stringify
625
+ const sceneOption = {
626
+ type: "image",
627
+ scene: "ImageBasicGenerate",
628
+ modelReqKey: _model,
629
+ resolutionType,
630
+ abilityList: uploadedImageIds.map(() => ({
631
+ abilityName: "byte_edit",
632
+ strength: sampleStrength,
633
+ source: {
634
+ imageUrl: `blob:https://jimeng.jianying.com/${util.uuid()}`
635
+ }
636
+ })),
637
+ reportParams: {
638
+ enterSource: "generate",
639
+ vipSource: "generate",
640
+ extraVipFunctionKey: `${_model}-${resolutionType}`,
641
+ useVipFunctionDetailsReporterHoc: true,
642
+ },
643
+ };
644
+
645
+ const { aigc_data } = await request(
646
+ "post",
647
+ "/mweb/v1/aigc_draft/generate",
648
+ refreshToken,
649
+ {
650
+ data: {
651
+ extend: {
652
+ root_model: model,
653
+ },
654
+ submit_id: submitId,
655
+ metrics_extra: JSON.stringify({
656
+ promptSource: "custom",
657
+ generateCount: 1,
658
+ enterFrom: "click",
659
+ sceneOptions: JSON.stringify([sceneOption]),
660
+ generateId: submitId,
661
+ isRegenerate: false
662
+ }),
663
+ draft_content: JSON.stringify({
664
+ type: "draft",
665
+ id: util.uuid(),
666
+ min_version: "3.2.9",
667
+ min_features: [],
668
+ is_from_tsn: true,
669
+ version: "3.2.9",
670
+ main_component_id: componentId,
671
+ component_list: [
672
+ {
673
+ type: "image_base_component",
674
+ id: componentId,
675
+ min_version: "3.0.2",
676
+ aigc_mode: "workbench",
677
+ metadata: {
678
+ type: "",
679
+ id: util.uuid(),
680
+ created_platform: 3,
681
+ created_platform_version: "",
682
+ created_time_in_ms: Date.now().toString(),
683
+ created_did: "",
684
+ },
685
+ generate_type: "blend",
686
+ abilities: {
687
+ type: "",
688
+ id: util.uuid(),
689
+ blend: {
690
+ type: "",
691
+ id: util.uuid(),
692
+ min_version: "3.2.9",
693
+ min_features: [],
694
+ core_param: {
695
+ type: "",
696
+ id: util.uuid(),
697
+ model,
698
+ prompt: `${'#'.repeat(imageCount * 2)}${prompt}`,
699
+ sample_strength: sampleStrength,
700
+ image_ratio: imageRatio,
701
+ large_image_info: {
702
+ type: "",
703
+ id: util.uuid(),
704
+ height,
705
+ width,
706
+ resolution_type: resolutionType
707
+ },
708
+ intelligent_ratio: intelligentRatio,
709
+ },
710
+ ability_list: uploadedImageIds.map((imageId) => ({
711
+ type: "",
712
+ id: util.uuid(),
713
+ name: "byte_edit",
714
+ image_uri_list: [imageId],
715
+ image_list: [{
716
+ type: "image",
717
+ id: util.uuid(),
718
+ source_from: "upload",
719
+ platform_type: 1,
720
+ name: "",
721
+ image_uri: imageId,
722
+ width: 0,
723
+ height: 0,
724
+ format: "",
725
+ uri: imageId
726
+ }],
727
+ strength: 0.5
728
+ })),
729
+ prompt_placeholder_info_list: uploadedImageIds.map((_, index) => ({
730
+ type: "",
731
+ id: util.uuid(),
732
+ ability_index: index
733
+ })),
734
+ postedit_param: {
735
+ type: "",
736
+ id: util.uuid(),
737
+ generate_type: 0
738
+ }
739
+ },
740
+ },
741
+ },
742
+ ],
743
+ }),
744
+ http_common_info: {
745
+ aid: DEFAULT_ASSISTANT_ID,
746
+ },
747
+ },
748
+ }
749
+ );
750
+
751
+ const historyId = aigc_data?.history_record_id;
752
+ if (!historyId)
753
+ throw new APIException(EX.API_IMAGE_GENERATION_FAILED, "记录ID不存在");
754
+
755
+ logger.info(`图生图任务已提交,history_id: ${historyId},等待生成完成...`);
756
+
757
+ let status = 20, failCode, item_list = [];
758
+ let pollCount = 0;
759
+ const maxPollCount = 600; // 最多轮询10分钟
760
+
761
+ while (pollCount < maxPollCount) {
762
+ await new Promise((resolve) => setTimeout(resolve, 1000));
763
+ pollCount++;
764
+
765
+ if (pollCount % 30 === 0) {
766
+ logger.info(`图生图进度: 第 ${pollCount} 次轮询 (history_id: ${historyId}),当前状态: ${status},已生成: ${item_list.length} 张图片...`);
767
+ }
768
+
769
+ const result = await request("post", "/mweb/v1/get_history_by_ids", refreshToken, {
770
+ data: {
771
+ history_ids: [historyId],
772
+ image_info: {
773
+ width: 2048,
774
+ height: 2048,
775
+ format: "webp",
776
+ image_scene_list: [
777
+ {
778
+ scene: "smart_crop",
779
+ width: 360,
780
+ height: 360,
781
+ uniq_key: "smart_crop-w:360-h:360",
782
+ format: "webp",
783
+ },
784
+ {
785
+ scene: "smart_crop",
786
+ width: 480,
787
+ height: 480,
788
+ uniq_key: "smart_crop-w:480-h:480",
789
+ format: "webp",
790
+ },
791
+ {
792
+ scene: "smart_crop",
793
+ width: 720,
794
+ height: 720,
795
+ uniq_key: "smart_crop-w:720-h:720",
796
+ format: "webp",
797
+ },
798
+ {
799
+ scene: "smart_crop",
800
+ width: 720,
801
+ height: 480,
802
+ uniq_key: "smart_crop-w:720-h:480",
803
+ format: "webp",
804
+ },
805
+ {
806
+ scene: "normal",
807
+ width: 2400,
808
+ height: 2400,
809
+ uniq_key: "2400",
810
+ format: "webp",
811
+ },
812
+ {
813
+ scene: "normal",
814
+ width: 1080,
815
+ height: 1080,
816
+ uniq_key: "1080",
817
+ format: "webp",
818
+ },
819
+ {
820
+ scene: "normal",
821
+ width: 720,
822
+ height: 720,
823
+ uniq_key: "720",
824
+ format: "webp",
825
+ },
826
+ {
827
+ scene: "normal",
828
+ width: 480,
829
+ height: 480,
830
+ uniq_key: "480",
831
+ format: "webp",
832
+ },
833
+ {
834
+ scene: "normal",
835
+ width: 360,
836
+ height: 360,
837
+ uniq_key: "360",
838
+ format: "webp",
839
+ },
840
+ ],
841
+ },
842
+ http_common_info: {
843
+ aid: DEFAULT_ASSISTANT_ID,
844
+ },
845
+ },
846
+ });
847
+
848
+ if (!result[historyId])
849
+ throw new APIException(EX.API_IMAGE_GENERATION_FAILED, "记录不存在");
850
+
851
+ status = result[historyId].status;
852
+ failCode = result[historyId].fail_code;
853
+ item_list = result[historyId].item_list || [];
854
+
855
+ // 检查是否已生成图片
856
+ if (item_list.length > 0) {
857
+ logger.info(`图生图完成: 状态=${status}, 已生成 ${item_list.length} 张图片`);
858
+ break;
859
+ }
860
+
861
+ // 记录详细状态
862
+ if (pollCount % 60 === 0) {
863
+ logger.info(`图生图详细状态: status=${status}, item_list.length=${item_list.length}, failCode=${failCode || 'none'}`);
864
+ }
865
+
866
+ // 如果状态是完成但图片数量为0,记录并继续等待
867
+ if (status === 10 && item_list.length === 0 && pollCount % 30 === 0) {
868
+ logger.info(`图生图状态已完成但无图片生成: 状态=${status}, 继续等待...`);
869
+ }
870
+ }
871
+
872
+ if (pollCount >= maxPollCount) {
873
+ logger.warn(`图生图超时: 轮询了 ${pollCount} 次,��前状态: ${status},已生成图片数: ${item_list.length}`);
874
+ }
875
+
876
+ if (status === 30) {
877
+ if (failCode === '2038')
878
+ throw new APIException(EX.API_CONTENT_FILTERED);
879
+ else
880
+ throw new APIException(EX.API_IMAGE_GENERATION_FAILED, `图生图失败,错误代码: ${failCode}`);
881
+ }
882
+
883
+ const resultImageUrls = item_list.map((item) => {
884
+ if(!item?.image?.large_images?.[0]?.image_url)
885
+ return item?.common_attr?.cover_url || null;
886
+ return item.image.large_images[0].image_url;
887
+ }).filter(url => url !== null);
888
+
889
+ logger.info(`图生图结果: 成功生成 ${resultImageUrls.length} 张图片`);
890
+ return resultImageUrls;
891
+ }
892
+
893
+ // 多图生成函数(支持jimeng-4.0及以上版本)
894
+ async function generateMultiImages(
895
+ _model: string,
896
+ prompt: string,
897
+ {
898
+ ratio = "1:1",
899
+ resolution = "2k",
900
+ sampleStrength = 0.5,
901
+ negativePrompt = "",
902
+ intelligentRatio = false,
903
+ }: {
904
+ ratio?: string;
905
+ resolution?: string;
906
+ sampleStrength?: number;
907
+ negativePrompt?: string;
908
+ intelligentRatio?: boolean;
909
+ },
910
+ refreshToken: string
911
+ ) {
912
+ const model = getModel(_model);
913
+
914
+ // 解析分辨率
915
+ const resolutionResult = resolveResolution(resolution, ratio);
916
+ const { width, height, imageRatio, resolutionType } = resolutionResult;
917
+
918
+ // 从prompt中提取图片数量,默认为4张
919
+ const targetImageCount = prompt.match(/(\d+)张/) ? parseInt(prompt.match(/(\d+)张/)[1]) : 4;
920
+
921
+ logger.info(`使用 ${_model} 多图生成: ${targetImageCount}张图片 ${width}x${height} (${ratio}@${resolution}) 精细度: ${sampleStrength}`);
922
+
923
+ const componentId = util.uuid();
924
+ const submitId = util.uuid();
925
+
926
+ // 构建多图模式的 sceneOptions(不包含 benefitCount 以避免扣积分)
927
+ const sceneOption = {
928
+ type: "image",
929
+ scene: "ImageMultiGenerate",
930
+ modelReqKey: _model,
931
+ resolutionType,
932
+ abilityList: [],
933
+ reportParams: {
934
+ enterSource: "generate",
935
+ vipSource: "generate",
936
+ extraVipFunctionKey: `${_model}-${resolutionType}`,
937
+ useVipFunctionDetailsReporterHoc: true,
938
+ },
939
+ };
940
+
941
+ const { aigc_data } = await request(
942
+ "post",
943
+ "/mweb/v1/aigc_draft/generate",
944
+ refreshToken,
945
+ {
946
+ data: {
947
+ extend: {
948
+ root_model: model,
949
+ },
950
+ submit_id: submitId,
951
+ metrics_extra: JSON.stringify({
952
+ promptSource: "custom",
953
+ generateCount: 1,
954
+ enterFrom: "click",
955
+ sceneOptions: JSON.stringify([sceneOption]),
956
+ generateId: submitId,
957
+ isRegenerate: false,
958
+ templateId: "",
959
+ templateSource: "",
960
+ lastRequestId: "",
961
+ originRequestId: "",
962
+ }),
963
+ draft_content: JSON.stringify({
964
+ type: "draft",
965
+ id: util.uuid(),
966
+ min_version: DRAFT_MIN_VERSION,
967
+ min_features: [],
968
+ is_from_tsn: true,
969
+ version: DRAFT_VERSION,
970
+ main_component_id: componentId,
971
+ component_list: [
972
+ {
973
+ type: "image_base_component",
974
+ id: componentId,
975
+ min_version: DRAFT_MIN_VERSION,
976
+ aigc_mode: "workbench",
977
+ metadata: {
978
+ type: "",
979
+ id: util.uuid(),
980
+ created_platform: 3,
981
+ created_platform_version: "",
982
+ created_time_in_ms: Date.now().toString(),
983
+ created_did: "",
984
+ },
985
+ generate_type: "generate",
986
+ abilities: {
987
+ type: "",
988
+ id: util.uuid(),
989
+ generate: {
990
+ type: "",
991
+ id: util.uuid(),
992
+ core_param: {
993
+ type: "",
994
+ id: util.uuid(),
995
+ model,
996
+ prompt,
997
+ negative_prompt: negativePrompt,
998
+ seed: Math.floor(Math.random() * 100000000) + 2500000000,
999
+ sample_strength: sampleStrength,
1000
+ image_ratio: imageRatio,
1001
+ large_image_info: {
1002
+ type: "",
1003
+ id: util.uuid(),
1004
+ min_version: DRAFT_MIN_VERSION,
1005
+ height,
1006
+ width,
1007
+ resolution_type: resolutionType,
1008
+ },
1009
+ intelligent_ratio: intelligentRatio,
1010
+ },
1011
+ gen_option: {
1012
+ type: "",
1013
+ id: util.uuid(),
1014
+ generate_all: false,
1015
+ },
1016
+ },
1017
+ },
1018
+ },
1019
+ ],
1020
+ }),
1021
+ http_common_info: {
1022
+ aid: DEFAULT_ASSISTANT_ID,
1023
+ },
1024
+ },
1025
+ }
1026
+ );
1027
+
1028
+ const historyId = aigc_data?.history_record_id;
1029
+ if (!historyId)
1030
+ throw new APIException(EX.API_IMAGE_GENERATION_FAILED, "记录ID不存在");
1031
+
1032
+ logger.info(`多图生成任务已提交,submit_id: ${submitId}, history_id: ${historyId},等待生成 ${targetImageCount} 张图片...`);
1033
+
1034
+ // 直接使用 history_id 轮询生成结果(增加轮询时间)
1035
+ let status = 20, failCode, item_list = [];
1036
+ let pollCount = 0;
1037
+ const maxPollCount = 600; // 最多轮询10分钟(600次 * 1秒)
1038
+
1039
+ while (pollCount < maxPollCount) {
1040
+ await new Promise((resolve) => setTimeout(resolve, 1000)); // 每1秒轮询一次
1041
+ pollCount++;
1042
+
1043
+ if (pollCount % 30 === 0) {
1044
+ logger.info(`多图生成进度: 第 ${pollCount} 次轮询 (history_id: ${historyId}),当前状态: ${status},已生成: ${item_list.length}/${targetImageCount} 张图片...`);
1045
+ }
1046
+
1047
+ const result = await request("post", "/mweb/v1/get_history_by_ids", refreshToken, {
1048
+ data: {
1049
+ history_ids: [historyId],
1050
+ image_info: {
1051
+ width: 2048,
1052
+ height: 2048,
1053
+ format: "webp",
1054
+ image_scene_list: [
1055
+ {
1056
+ scene: "smart_crop",
1057
+ width: 360,
1058
+ height: 360,
1059
+ uniq_key: "smart_crop-w:360-h:360",
1060
+ format: "webp",
1061
+ },
1062
+ {
1063
+ scene: "smart_crop",
1064
+ width: 480,
1065
+ height: 480,
1066
+ uniq_key: "smart_crop-w:480-h:480",
1067
+ format: "webp",
1068
+ },
1069
+ {
1070
+ scene: "smart_crop",
1071
+ width: 720,
1072
+ height: 720,
1073
+ uniq_key: "smart_crop-w:720-h:720",
1074
+ format: "webp",
1075
+ },
1076
+ {
1077
+ scene: "smart_crop",
1078
+ width: 720,
1079
+ height: 480,
1080
+ uniq_key: "smart_crop-w:720-h:480",
1081
+ format: "webp",
1082
+ },
1083
+ {
1084
+ scene: "normal",
1085
+ width: 2400,
1086
+ height: 2400,
1087
+ uniq_key: "2400",
1088
+ format: "webp",
1089
+ },
1090
+ {
1091
+ scene: "normal",
1092
+ width: 1080,
1093
+ height: 1080,
1094
+ uniq_key: "1080",
1095
+ format: "webp",
1096
+ },
1097
+ {
1098
+ scene: "normal",
1099
+ width: 720,
1100
+ height: 720,
1101
+ uniq_key: "720",
1102
+ format: "webp",
1103
+ },
1104
+ {
1105
+ scene: "normal",
1106
+ width: 480,
1107
+ height: 480,
1108
+ uniq_key: "480",
1109
+ format: "webp",
1110
+ },
1111
+ {
1112
+ scene: "normal",
1113
+ width: 360,
1114
+ height: 360,
1115
+ uniq_key: "360",
1116
+ format: "webp",
1117
+ },
1118
+ ],
1119
+ },
1120
+ http_common_info: {
1121
+ aid: DEFAULT_ASSISTANT_ID,
1122
+ },
1123
+ },
1124
+ });
1125
+
1126
+ if (!result[historyId])
1127
+ throw new APIException(EX.API_IMAGE_GENERATION_FAILED, "记录不存在");
1128
+
1129
+ status = result[historyId].status;
1130
+ failCode = result[historyId].fail_code;
1131
+ item_list = result[historyId].item_list || [];
1132
+
1133
+ // 检查是否已生成足够的图片
1134
+ if (item_list.length >= targetImageCount) {
1135
+ logger.info(`多图生成完成: 状态=${status}, 已生成 ${item_list.length} 张图片`);
1136
+ break;
1137
+ }
1138
+
1139
+ // 记录详细状态
1140
+ if (pollCount % 60 === 0) {
1141
+ logger.info(`jimeng-4.0 详细状态: status=${status}, item_list.length=${item_list.length}, failCode=${failCode || 'none'}`);
1142
+ }
1143
+
1144
+ // 如果状态是完成但图片数量不够,记录并继续等待
1145
+ if (status === 10 && item_list.length < targetImageCount && pollCount % 30 === 0) {
1146
+ logger.info(`jimeng-4.0 状态已完成但图片数量不足: 状态=${status}, 已生成 ${item_list.length}/${targetImageCount} 张图片,继续等待...`);
1147
+ }
1148
+ }
1149
+
1150
+ if (pollCount >= maxPollCount) {
1151
+ logger.warn(`多图生成超时: 轮询了 ${pollCount} 次,当前状态: ${status},已生成图片数: ${item_list.length}`);
1152
+ }
1153
+
1154
+ if (status === 30) {
1155
+ if (failCode === '2038')
1156
+ throw new APIException(EX.API_CONTENT_FILTERED);
1157
+ else
1158
+ throw new APIException(EX.API_IMAGE_GENERATION_FAILED, `生成失败,错误代码: ${failCode}`);
1159
+ }
1160
+
1161
+ const imageUrls = item_list.map((item) => {
1162
+ if(!item?.image?.large_images?.[0]?.image_url)
1163
+ return item?.common_attr?.cover_url || null;
1164
+ return item.image.large_images[0].image_url;
1165
+ }).filter(url => url !== null);
1166
+
1167
+ logger.info(`多图生成结果: 成功生成 ${imageUrls.length} 张图片`);
1168
+ return imageUrls;
1169
+ }
1170
+
1171
+ export async function generateImages(
1172
+ _model: string,
1173
+ prompt: string,
1174
+ {
1175
+ ratio = "1:1",
1176
+ resolution = "2k",
1177
+ sampleStrength = 0.5,
1178
+ negativePrompt = "",
1179
+ intelligentRatio = false,
1180
+ }: {
1181
+ ratio?: string;
1182
+ resolution?: string;
1183
+ sampleStrength?: number;
1184
+ negativePrompt?: string;
1185
+ intelligentRatio?: boolean;
1186
+ },
1187
+ refreshToken: string
1188
+ ) {
1189
+ const model = getModel(_model);
1190
+
1191
+ // 解析分辨率
1192
+ const resolutionResult = resolveResolution(resolution, ratio);
1193
+ const { width, height, imageRatio, resolutionType } = resolutionResult;
1194
+
1195
+ logger.info(`使用模型: ${_model} 映射模型: ${model} ${width}x${height} (${ratio}@${resolution}) 精细度: ${sampleStrength}`);
1196
+
1197
+
1198
+ const { totalCredit } = await getCredit(refreshToken);
1199
+ if (totalCredit <= 0)
1200
+ await receiveCredit(refreshToken);
1201
+
1202
+ // 检测是否为多图生成请求
1203
+ const isMultiImageRequest = (/jimeng-[45]\.[0-9]/.test(_model)) && (
1204
+ prompt.includes("连续") ||
1205
+ prompt.includes("绘本") ||
1206
+ prompt.includes("故事") ||
1207
+ /\d+张/.test(prompt)
1208
+ );
1209
+
1210
+ // 如果是多图请求,使用专门的处理逻辑
1211
+ if (isMultiImageRequest) {
1212
+ return await generateMultiImages(_model, prompt, { ratio, resolution, sampleStrength, negativePrompt, intelligentRatio }, refreshToken);
1213
+ }
1214
+
1215
+ const componentId = util.uuid();
1216
+ const submitId = util.uuid();
1217
+
1218
+ // 构建 sceneOptions 用于 metrics_extra(不包含 benefitCount 以避免扣积分)
1219
+ const sceneOption = {
1220
+ type: "image",
1221
+ scene: "ImageBasicGenerate",
1222
+ modelReqKey: _model,
1223
+ resolutionType,
1224
+ abilityList: [],
1225
+ reportParams: {
1226
+ enterSource: "generate",
1227
+ vipSource: "generate",
1228
+ extraVipFunctionKey: `${_model}-${resolutionType}`,
1229
+ useVipFunctionDetailsReporterHoc: true,
1230
+ },
1231
+ };
1232
+
1233
+ const { aigc_data } = await request(
1234
+ "post",
1235
+ "/mweb/v1/aigc_draft/generate",
1236
+ refreshToken,
1237
+ {
1238
+ data: {
1239
+ extend: {
1240
+ root_model: model,
1241
+ },
1242
+ submit_id: submitId,
1243
+ metrics_extra: JSON.stringify({
1244
+ promptSource: "custom",
1245
+ generateCount: 1,
1246
+ enterFrom: "click",
1247
+ sceneOptions: JSON.stringify([sceneOption]),
1248
+ generateId: submitId,
1249
+ isRegenerate: false,
1250
+ }),
1251
+ draft_content: JSON.stringify({
1252
+ type: "draft",
1253
+ id: util.uuid(),
1254
+ min_version: DRAFT_MIN_VERSION,
1255
+ min_features: [],
1256
+ is_from_tsn: true,
1257
+ version: DRAFT_VERSION,
1258
+ main_component_id: componentId,
1259
+ component_list: [
1260
+ {
1261
+ type: "image_base_component",
1262
+ id: componentId,
1263
+ min_version: DRAFT_MIN_VERSION,
1264
+ aigc_mode: "workbench",
1265
+ metadata: {
1266
+ type: "",
1267
+ id: util.uuid(),
1268
+ created_platform: 3,
1269
+ created_platform_version: "",
1270
+ created_time_in_ms: Date.now().toString(),
1271
+ created_did: "",
1272
+ },
1273
+ generate_type: "generate",
1274
+ abilities: {
1275
+ type: "",
1276
+ id: util.uuid(),
1277
+ generate: {
1278
+ type: "",
1279
+ id: util.uuid(),
1280
+ core_param: {
1281
+ type: "",
1282
+ id: util.uuid(),
1283
+ model,
1284
+ prompt,
1285
+ negative_prompt: negativePrompt,
1286
+ seed: Math.floor(Math.random() * 100000000) + 2500000000,
1287
+ sample_strength: sampleStrength,
1288
+ image_ratio: imageRatio,
1289
+ large_image_info: {
1290
+ type: "",
1291
+ id: util.uuid(),
1292
+ min_version: DRAFT_MIN_VERSION,
1293
+ height,
1294
+ width,
1295
+ resolution_type: resolutionType,
1296
+ },
1297
+ intelligent_ratio: intelligentRatio,
1298
+ },
1299
+ gen_option: {
1300
+ type: "",
1301
+ id: util.uuid(),
1302
+ generate_all: false,
1303
+ },
1304
+ },
1305
+ },
1306
+ },
1307
+ ],
1308
+ }),
1309
+ http_common_info: {
1310
+ aid: DEFAULT_ASSISTANT_ID,
1311
+ },
1312
+ },
1313
+ }
1314
+ );
1315
+ const historyId = aigc_data.history_record_id;
1316
+ if (!historyId)
1317
+ throw new APIException(EX.API_IMAGE_GENERATION_FAILED, "记录ID不存在");
1318
+
1319
+ logger.info(`文生图任务已提交,submit_id: ${submitId}, history_id: ${historyId},等待生成完成...`);
1320
+
1321
+ let status = 20, failCode, item_list = [];
1322
+ let pollCount = 0;
1323
+ const maxPollCount = 600; // 最多轮询10分钟
1324
+
1325
+ while (pollCount < maxPollCount) {
1326
+ await new Promise((resolve) => setTimeout(resolve, 1000));
1327
+ pollCount++;
1328
+
1329
+ if (pollCount % 30 === 0) {
1330
+ logger.info(`文生图进度: 第 ${pollCount} 次轮询 (history_id: ${historyId}),当前状态: ${status},已生成: ${item_list.length} 张图片...`);
1331
+ }
1332
+
1333
+ const result = await request("post", "/mweb/v1/get_history_by_ids", refreshToken, {
1334
+ data: {
1335
+ history_ids: [historyId],
1336
+ image_info: {
1337
+ width: 2048,
1338
+ height: 2048,
1339
+ format: "webp",
1340
+ image_scene_list: [
1341
+ {
1342
+ scene: "smart_crop",
1343
+ width: 360,
1344
+ height: 360,
1345
+ uniq_key: "smart_crop-w:360-h:360",
1346
+ format: "webp",
1347
+ },
1348
+ {
1349
+ scene: "smart_crop",
1350
+ width: 480,
1351
+ height: 480,
1352
+ uniq_key: "smart_crop-w:480-h:480",
1353
+ format: "webp",
1354
+ },
1355
+ {
1356
+ scene: "smart_crop",
1357
+ width: 720,
1358
+ height: 720,
1359
+ uniq_key: "smart_crop-w:720-h:720",
1360
+ format: "webp",
1361
+ },
1362
+ {
1363
+ scene: "smart_crop",
1364
+ width: 720,
1365
+ height: 480,
1366
+ uniq_key: "smart_crop-w:720-h:480",
1367
+ format: "webp",
1368
+ },
1369
+ {
1370
+ scene: "smart_crop",
1371
+ width: 360,
1372
+ height: 240,
1373
+ uniq_key: "smart_crop-w:360-h:240",
1374
+ format: "webp",
1375
+ },
1376
+ {
1377
+ scene: "smart_crop",
1378
+ width: 240,
1379
+ height: 320,
1380
+ uniq_key: "smart_crop-w:240-h:320",
1381
+ format: "webp",
1382
+ },
1383
+ {
1384
+ scene: "smart_crop",
1385
+ width: 480,
1386
+ height: 640,
1387
+ uniq_key: "smart_crop-w:480-h:640",
1388
+ format: "webp",
1389
+ },
1390
+ {
1391
+ scene: "normal",
1392
+ width: 2400,
1393
+ height: 2400,
1394
+ uniq_key: "2400",
1395
+ format: "webp",
1396
+ },
1397
+ {
1398
+ scene: "normal",
1399
+ width: 1080,
1400
+ height: 1080,
1401
+ uniq_key: "1080",
1402
+ format: "webp",
1403
+ },
1404
+ {
1405
+ scene: "normal",
1406
+ width: 720,
1407
+ height: 720,
1408
+ uniq_key: "720",
1409
+ format: "webp",
1410
+ },
1411
+ {
1412
+ scene: "normal",
1413
+ width: 480,
1414
+ height: 480,
1415
+ uniq_key: "480",
1416
+ format: "webp",
1417
+ },
1418
+ {
1419
+ scene: "normal",
1420
+ width: 360,
1421
+ height: 360,
1422
+ uniq_key: "360",
1423
+ format: "webp",
1424
+ },
1425
+ ],
1426
+ },
1427
+ http_common_info: {
1428
+ aid: DEFAULT_ASSISTANT_ID,
1429
+ },
1430
+ },
1431
+ });
1432
+ if (!result[historyId])
1433
+ throw new APIException(EX.API_IMAGE_GENERATION_FAILED, "记录不存在");
1434
+
1435
+ status = result[historyId].status;
1436
+ failCode = result[historyId].fail_code;
1437
+ item_list = result[historyId].item_list || [];
1438
+
1439
+ // 检查是否已生成图片
1440
+ if (item_list.length > 0) {
1441
+ logger.info(`文生图完成: 状态=${status}, 已生成 ${item_list.length} 张图片`);
1442
+ break;
1443
+ }
1444
+
1445
+ // 记录详细状态
1446
+ if (pollCount % 60 === 0) {
1447
+ logger.info(`文生图详细状态: status=${status}, item_list.length=${item_list.length}, failCode=${failCode || 'none'}`);
1448
+ }
1449
+
1450
+ // 如果状态是完成但图片数量为0,记录并继续等待
1451
+ if (status === 10 && item_list.length === 0 && pollCount % 30 === 0) {
1452
+ logger.info(`文生图状态已完成但无图片生成: 状态=${status}, 继续等待...`);
1453
+ }
1454
+ }
1455
+
1456
+ if (pollCount >= maxPollCount) {
1457
+ logger.warn(`文生图超时: 轮询了 ${pollCount} 次,当前状态: ${status},已生成图片数: ${item_list.length}`);
1458
+ }
1459
+
1460
+ if (status === 30) {
1461
+ if (failCode === '2038')
1462
+ throw new APIException(EX.API_CONTENT_FILTERED);
1463
+ else
1464
+ throw new APIException(EX.API_IMAGE_GENERATION_FAILED);
1465
+ }
1466
+
1467
+ const imageUrls = item_list.map((item) => {
1468
+ if(!item?.image?.large_images?.[0]?.image_url)
1469
+ return item?.common_attr?.cover_url || null;
1470
+ return item.image.large_images[0].image_url;
1471
+ }).filter(url => url !== null);
1472
+
1473
+ logger.info(`文生图结果: 成功生成 ${imageUrls.length} 张图片`);
1474
+ return imageUrls;
1475
+ }
1476
+
1477
+ export default {
1478
+ generateImages,
1479
+ generateImageComposition,
1480
+ };
src/api/controllers/videos.ts ADDED
@@ -0,0 +1,1570 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import _ from "lodash";
2
+ import crypto from "crypto";
3
+ import fs from "fs";
4
+
5
+ import APIException from "@/lib/exceptions/APIException.ts";
6
+ import EX from "@/api/consts/exceptions.ts";
7
+ import util from "@/lib/util.ts";
8
+ import { getCredit, receiveCredit, request } from "./core.ts";
9
+ import logger from "@/lib/logger.ts";
10
+
11
+ const DEFAULT_ASSISTANT_ID = 513695;
12
+ export const DEFAULT_MODEL = "jimeng-video-3.0";
13
+ const DEFAULT_DRAFT_VERSION = "3.2.8";
14
+
15
+ const MODEL_DRAFT_VERSIONS: { [key: string]: string } = {
16
+ "jimeng-video-3.5-pro": "3.3.4",
17
+ "jimeng-video-3.0-pro": "3.2.8",
18
+ "jimeng-video-3.0": "3.2.8",
19
+ "jimeng-video-2.0": "3.2.8",
20
+ "jimeng-video-2.0-pro": "3.2.8",
21
+ // Seedance 模型
22
+ "seedance-2.0": "3.3.9",
23
+ "seedance-2.0-pro": "3.3.9",
24
+ };
25
+
26
+ const MODEL_MAP = {
27
+ "jimeng-video-3.5-pro": "dreamina_ic_generate_video_model_vgfm_3.5_pro",
28
+ "jimeng-video-3.0-pro": "dreamina_ic_generate_video_model_vgfm_3.0_pro",
29
+ "jimeng-video-3.0": "dreamina_ic_generate_video_model_vgfm_3.0",
30
+ "jimeng-video-2.0": "dreamina_ic_generate_video_model_vgfm_lite",
31
+ "jimeng-video-2.0-pro": "dreamina_ic_generate_video_model_vgfm1.0",
32
+ // Seedance 多图智能视频生成模型
33
+ "seedance-2.0": "dreamina_seedance_40_pro",
34
+ "seedance-2.0-pro": "dreamina_seedance_40_pro",
35
+ };
36
+
37
+ // Seedance 模型的 benefit_type 映射
38
+ const SEEDANCE_BENEFIT_TYPE_MAP: { [key: string]: string } = {
39
+ "seedance-2.0": "dreamina_video_seedance_20_pro",
40
+ "seedance-2.0-pro": "dreamina_video_seedance_20_pro",
41
+ };
42
+
43
+ // 判断是否为 Seedance 模型
44
+ export function isSeedanceModel(model: string): boolean {
45
+ return model.startsWith("seedance-");
46
+ }
47
+
48
+ // 视频支持的分辨率和比例配置
49
+ const VIDEO_RESOLUTION_OPTIONS: {
50
+ [resolution: string]: {
51
+ [ratio: string]: { width: number; height: number };
52
+ };
53
+ } = {
54
+ "480p": {
55
+ "1:1": { width: 480, height: 480 },
56
+ "4:3": { width: 640, height: 480 },
57
+ "3:4": { width: 480, height: 640 },
58
+ "16:9": { width: 854, height: 480 },
59
+ "9:16": { width: 480, height: 854 },
60
+ },
61
+ "720p": {
62
+ "1:1": { width: 720, height: 720 },
63
+ "4:3": { width: 960, height: 720 },
64
+ "3:4": { width: 720, height: 960 },
65
+ "16:9": { width: 1280, height: 720 },
66
+ "9:16": { width: 720, height: 1280 },
67
+ },
68
+ "1080p": {
69
+ "1:1": { width: 1080, height: 1080 },
70
+ "4:3": { width: 1440, height: 1080 },
71
+ "3:4": { width: 1080, height: 1440 },
72
+ "16:9": { width: 1920, height: 1080 },
73
+ "9:16": { width: 1080, height: 1920 },
74
+ },
75
+ };
76
+
77
+ // 解析视频分辨率参数
78
+ function resolveVideoResolution(
79
+ resolution: string = "720p",
80
+ ratio: string = "1:1"
81
+ ): { width: number; height: number } {
82
+ const resolutionGroup = VIDEO_RESOLUTION_OPTIONS[resolution];
83
+ if (!resolutionGroup) {
84
+ const supportedResolutions = Object.keys(VIDEO_RESOLUTION_OPTIONS).join(", ");
85
+ throw new Error(`不支持的视频分辨率 "${resolution}"。支持的分辨率: ${supportedResolutions}`);
86
+ }
87
+
88
+ const ratioConfig = resolutionGroup[ratio];
89
+ if (!ratioConfig) {
90
+ const supportedRatios = Object.keys(resolutionGroup).join(", ");
91
+ throw new Error(`在 "${resolution}" 分辨率下,不支持的比例 "${ratio}"。支持的比例: ${supportedRatios}`);
92
+ }
93
+
94
+ return {
95
+ width: ratioConfig.width,
96
+ height: ratioConfig.height,
97
+ };
98
+ }
99
+
100
+ export function getModel(model: string) {
101
+ return MODEL_MAP[model] || MODEL_MAP[DEFAULT_MODEL];
102
+ }
103
+
104
+ // AWS4-HMAC-SHA256 签名生成函数(从 images.ts 复制)
105
+ function createSignature(
106
+ method: string,
107
+ url: string,
108
+ headers: { [key: string]: string },
109
+ accessKeyId: string,
110
+ secretAccessKey: string,
111
+ sessionToken?: string,
112
+ payload: string = ''
113
+ ) {
114
+ const urlObj = new URL(url);
115
+ const pathname = urlObj.pathname || '/';
116
+ const search = urlObj.search;
117
+
118
+ // 创建规范请求
119
+ const timestamp = headers['x-amz-date'];
120
+ const date = timestamp.substr(0, 8);
121
+ const region = 'cn-north-1';
122
+ const service = 'imagex';
123
+
124
+ // 规范化查询参数
125
+ const queryParams: Array<[string, string]> = [];
126
+ const searchParams = new URLSearchParams(search);
127
+ searchParams.forEach((value, key) => {
128
+ queryParams.push([key, value]);
129
+ });
130
+
131
+ // 按键名排序
132
+ queryParams.sort(([a], [b]) => {
133
+ if (a < b) return -1;
134
+ if (a > b) return 1;
135
+ return 0;
136
+ });
137
+
138
+ const canonicalQueryString = queryParams
139
+ .map(([key, value]) => `${key}=${value}`)
140
+ .join('&');
141
+
142
+ // 规范化头部
143
+ const headersToSign: { [key: string]: string } = {
144
+ 'x-amz-date': timestamp
145
+ };
146
+
147
+ if (sessionToken) {
148
+ headersToSign['x-amz-security-token'] = sessionToken;
149
+ }
150
+
151
+ let payloadHash = crypto.createHash('sha256').update('').digest('hex');
152
+ if (method.toUpperCase() === 'POST' && payload) {
153
+ payloadHash = crypto.createHash('sha256').update(payload, 'utf8').digest('hex');
154
+ headersToSign['x-amz-content-sha256'] = payloadHash;
155
+ }
156
+
157
+ const signedHeaders = Object.keys(headersToSign)
158
+ .map(key => key.toLowerCase())
159
+ .sort()
160
+ .join(';');
161
+
162
+ const canonicalHeaders = Object.keys(headersToSign)
163
+ .sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()))
164
+ .map(key => `${key.toLowerCase()}:${headersToSign[key].trim()}\n`)
165
+ .join('');
166
+
167
+ const canonicalRequest = [
168
+ method.toUpperCase(),
169
+ pathname,
170
+ canonicalQueryString,
171
+ canonicalHeaders,
172
+ signedHeaders,
173
+ payloadHash
174
+ ].join('\n');
175
+
176
+ // 创建待签名字符串
177
+ const credentialScope = `${date}/${region}/${service}/aws4_request`;
178
+ const stringToSign = [
179
+ 'AWS4-HMAC-SHA256',
180
+ timestamp,
181
+ credentialScope,
182
+ crypto.createHash('sha256').update(canonicalRequest, 'utf8').digest('hex')
183
+ ].join('\n');
184
+
185
+ // 生成签名
186
+ const kDate = crypto.createHmac('sha256', `AWS4${secretAccessKey}`).update(date).digest();
187
+ const kRegion = crypto.createHmac('sha256', kDate).update(region).digest();
188
+ const kService = crypto.createHmac('sha256', kRegion).update(service).digest();
189
+ const kSigning = crypto.createHmac('sha256', kService).update('aws4_request').digest();
190
+ const signature = crypto.createHmac('sha256', kSigning).update(stringToSign, 'utf8').digest('hex');
191
+
192
+ return `AWS4-HMAC-SHA256 Credential=${accessKeyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;
193
+ }
194
+
195
+ // 计算文件的CRC32值(从 images.ts 复制)
196
+ function calculateCRC32(buffer: ArrayBuffer): string {
197
+ const crcTable = [];
198
+ for (let i = 0; i < 256; i++) {
199
+ let crc = i;
200
+ for (let j = 0; j < 8; j++) {
201
+ crc = (crc & 1) ? (0xEDB88320 ^ (crc >>> 1)) : (crc >>> 1);
202
+ }
203
+ crcTable[i] = crc;
204
+ }
205
+
206
+ let crc = 0 ^ (-1);
207
+ const bytes = new Uint8Array(buffer);
208
+ for (let i = 0; i < bytes.length; i++) {
209
+ crc = (crc >>> 8) ^ crcTable[(crc ^ bytes[i]) & 0xFF];
210
+ }
211
+ return ((crc ^ (-1)) >>> 0).toString(16).padStart(8, '0');
212
+ }
213
+
214
+ // 视频专用图片上传功能(基于 images.ts 的 uploadImageFromUrl)
215
+ async function uploadImageForVideo(imageUrl: string, refreshToken: string): Promise<string> {
216
+ try {
217
+ logger.info(`开始上传视频图片: ${imageUrl}`);
218
+
219
+ // 第一步:获取上传令牌
220
+ const tokenResult = await request("post", "/mweb/v1/get_upload_token", refreshToken, {
221
+ data: {
222
+ scene: 2, // AIGC 图片上传场景
223
+ },
224
+ });
225
+
226
+ const { access_key_id, secret_access_key, session_token, service_id } = tokenResult;
227
+ if (!access_key_id || !secret_access_key || !session_token) {
228
+ throw new Error("获取上传令牌失败");
229
+ }
230
+
231
+ const actualServiceId = service_id || "tb4s082cfz";
232
+ logger.info(`获取上传令牌成功: service_id=${actualServiceId}`);
233
+
234
+ // 下载图片数据
235
+ const imageResponse = await fetch(imageUrl);
236
+ if (!imageResponse.ok) {
237
+ throw new Error(`下载图片失败: ${imageResponse.status}`);
238
+ }
239
+
240
+ const imageBuffer = await imageResponse.arrayBuffer();
241
+ const fileSize = imageBuffer.byteLength;
242
+ const crc32 = calculateCRC32(imageBuffer);
243
+
244
+ logger.info(`图片下载完成: 大小=${fileSize}字节, CRC32=${crc32}`);
245
+
246
+ // 第二步:申请图片上传权限
247
+ const now = new Date();
248
+ const timestamp = now.toISOString().replace(/[:\-]/g, '').replace(/\.\d{3}Z$/, 'Z');
249
+
250
+ const randomStr = Math.random().toString(36).substring(2, 12);
251
+ const applyUrl = `https://imagex.bytedanceapi.com/?Action=ApplyImageUpload&Version=2018-08-01&ServiceId=${actualServiceId}&FileSize=${fileSize}&s=${randomStr}`;
252
+
253
+ const requestHeaders = {
254
+ 'x-amz-date': timestamp,
255
+ 'x-amz-security-token': session_token
256
+ };
257
+
258
+ const authorization = createSignature('GET', applyUrl, requestHeaders, access_key_id, secret_access_key, session_token);
259
+
260
+ logger.info(`申请上传权限: ${applyUrl}`);
261
+
262
+ const applyResponse = await fetch(applyUrl, {
263
+ method: 'GET',
264
+ headers: {
265
+ 'accept': '*/*',
266
+ 'accept-language': 'zh-CN,zh;q=0.9',
267
+ 'authorization': authorization,
268
+ 'origin': 'https://jimeng.jianying.com',
269
+ 'referer': 'https://jimeng.jianying.com/ai-tool/video/generate',
270
+ 'sec-ch-ua': '"Not A(Brand";v="8", "Chromium";v="132", "Google Chrome";v="132"',
271
+ 'sec-ch-ua-mobile': '?0',
272
+ 'sec-ch-ua-platform': '"Windows"',
273
+ 'sec-fetch-dest': 'empty',
274
+ 'sec-fetch-mode': 'cors',
275
+ 'sec-fetch-site': 'cross-site',
276
+ 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36',
277
+ 'x-amz-date': timestamp,
278
+ 'x-amz-security-token': session_token,
279
+ },
280
+ });
281
+
282
+ if (!applyResponse.ok) {
283
+ const errorText = await applyResponse.text();
284
+ throw new Error(`申请上传权限失败: ${applyResponse.status} - ${errorText}`);
285
+ }
286
+
287
+ const applyResult = await applyResponse.json();
288
+
289
+ if (applyResult?.ResponseMetadata?.Error) {
290
+ throw new Error(`申请上传权限失败: ${JSON.stringify(applyResult.ResponseMetadata.Error)}`);
291
+ }
292
+
293
+ logger.info(`申请上传权限成功`);
294
+
295
+ // 解析上传信息
296
+ const uploadAddress = applyResult?.Result?.UploadAddress;
297
+ if (!uploadAddress || !uploadAddress.StoreInfos || !uploadAddress.UploadHosts) {
298
+ throw new Error(`获取上传地址失败: ${JSON.stringify(applyResult)}`);
299
+ }
300
+
301
+ const storeInfo = uploadAddress.StoreInfos[0];
302
+ const uploadHost = uploadAddress.UploadHosts[0];
303
+ const auth = storeInfo.Auth;
304
+
305
+ const uploadUrl = `https://${uploadHost}/upload/v1/${storeInfo.StoreUri}`;
306
+ const imageId = storeInfo.StoreUri.split('/').pop();
307
+
308
+ logger.info(`准备上传图片: imageId=${imageId}, uploadUrl=${uploadUrl}`);
309
+
310
+ // 第三步:上传图片文件
311
+ const uploadResponse = await fetch(uploadUrl, {
312
+ method: 'POST',
313
+ headers: {
314
+ 'Accept': '*/*',
315
+ 'Accept-Language': 'zh-CN,zh;q=0.9',
316
+ 'Authorization': auth,
317
+ 'Connection': 'keep-alive',
318
+ 'Content-CRC32': crc32,
319
+ 'Content-Disposition': 'attachment; filename="undefined"',
320
+ 'Content-Type': 'application/octet-stream',
321
+ 'Origin': 'https://jimeng.jianying.com',
322
+ 'Referer': 'https://jimeng.jianying.com/ai-tool/video/generate',
323
+ 'Sec-Fetch-Dest': 'empty',
324
+ 'Sec-Fetch-Mode': 'cors',
325
+ 'Sec-Fetch-Site': 'cross-site',
326
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36',
327
+ 'X-Storage-U': '704135154117550',
328
+ },
329
+ body: imageBuffer,
330
+ });
331
+
332
+ if (!uploadResponse.ok) {
333
+ const errorText = await uploadResponse.text();
334
+ throw new Error(`图片上传失败: ${uploadResponse.status} - ${errorText}`);
335
+ }
336
+
337
+ logger.info(`图片文件上传成功`);
338
+
339
+ // 第四步:提交上传
340
+ const commitUrl = `https://imagex.bytedanceapi.com/?Action=CommitImageUpload&Version=2018-08-01&ServiceId=${actualServiceId}`;
341
+
342
+ const commitTimestamp = new Date().toISOString().replace(/[:\-]/g, '').replace(/\.\d{3}Z$/, 'Z');
343
+ const commitPayload = JSON.stringify({
344
+ SessionKey: uploadAddress.SessionKey,
345
+ SuccessActionStatus: "200"
346
+ });
347
+
348
+ const payloadHash = crypto.createHash('sha256').update(commitPayload, 'utf8').digest('hex');
349
+
350
+ const commitRequestHeaders = {
351
+ 'x-amz-date': commitTimestamp,
352
+ 'x-amz-security-token': session_token,
353
+ 'x-amz-content-sha256': payloadHash
354
+ };
355
+
356
+ const commitAuthorization = createSignature('POST', commitUrl, commitRequestHeaders, access_key_id, secret_access_key, session_token, commitPayload);
357
+
358
+ const commitResponse = await fetch(commitUrl, {
359
+ method: 'POST',
360
+ headers: {
361
+ 'accept': '*/*',
362
+ 'accept-language': 'zh-CN,zh;q=0.9',
363
+ 'authorization': commitAuthorization,
364
+ 'content-type': 'application/json',
365
+ 'origin': 'https://jimeng.jianying.com',
366
+ 'referer': 'https://jimeng.jianying.com/ai-tool/video/generate',
367
+ 'sec-ch-ua': '"Not A(Brand";v="8", "Chromium";v="132", "Google Chrome";v="132"',
368
+ 'sec-ch-ua-mobile': '?0',
369
+ 'sec-ch-ua-platform': '"Windows"',
370
+ 'sec-fetch-dest': 'empty',
371
+ 'sec-fetch-mode': 'cors',
372
+ 'sec-fetch-site': 'cross-site',
373
+ 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36',
374
+ 'x-amz-date': commitTimestamp,
375
+ 'x-amz-security-token': session_token,
376
+ 'x-amz-content-sha256': payloadHash,
377
+ },
378
+ body: commitPayload,
379
+ });
380
+
381
+ if (!commitResponse.ok) {
382
+ const errorText = await commitResponse.text();
383
+ throw new Error(`提交上传失败: ${commitResponse.status} - ${errorText}`);
384
+ }
385
+
386
+ const commitResult = await commitResponse.json();
387
+
388
+ if (commitResult?.ResponseMetadata?.Error) {
389
+ throw new Error(`提交上传失败: ${JSON.stringify(commitResult.ResponseMetadata.Error)}`);
390
+ }
391
+
392
+ if (!commitResult?.Result?.Results || commitResult.Result.Results.length === 0) {
393
+ throw new Error(`提交上传响应缺少结果: ${JSON.stringify(commitResult)}`);
394
+ }
395
+
396
+ const uploadResult = commitResult.Result.Results[0];
397
+ if (uploadResult.UriStatus !== 2000) {
398
+ throw new Error(`图片上传状态异常: UriStatus=${uploadResult.UriStatus}`);
399
+ }
400
+
401
+ const fullImageUri = uploadResult.Uri;
402
+
403
+ // 验证图片信息
404
+ const pluginResult = commitResult.Result?.PluginResult?.[0];
405
+ if (pluginResult && pluginResult.ImageUri) {
406
+ logger.info(`视频图片上传完成: ${pluginResult.ImageUri}`);
407
+ return pluginResult.ImageUri;
408
+ }
409
+
410
+ logger.info(`视频图片上传完成: ${fullImageUri}`);
411
+ return fullImageUri;
412
+
413
+ } catch (error) {
414
+ logger.error(`视频图片上传失败: ${error.message}`);
415
+ throw error;
416
+ }
417
+ }
418
+
419
+ // 从Buffer上传视频图片
420
+ async function uploadImageBufferForVideo(buffer: Buffer, refreshToken: string): Promise<string> {
421
+ try {
422
+ logger.info(`开始从Buffer上传视频图片,大小: ${buffer.length}字节`);
423
+
424
+ // 第一步:获取上传令牌
425
+ const tokenResult = await request("post", "/mweb/v1/get_upload_token", refreshToken, {
426
+ data: {
427
+ scene: 2,
428
+ },
429
+ });
430
+
431
+ const { access_key_id, secret_access_key, session_token, service_id } = tokenResult;
432
+ if (!access_key_id || !secret_access_key || !session_token) {
433
+ throw new Error("获取上传令牌失败");
434
+ }
435
+
436
+ const actualServiceId = service_id || "tb4s082cfz";
437
+ logger.info(`获取上传令牌成功: service_id=${actualServiceId}`);
438
+
439
+ const fileSize = buffer.length;
440
+ const crc32 = calculateCRC32(buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength));
441
+
442
+ logger.info(`Buffer大小: ${fileSize}字节, CRC32=${crc32}`);
443
+
444
+ // 第二步:申请图片上传权限
445
+ const now = new Date();
446
+ const timestamp = now.toISOString().replace(/[:\-]/g, '').replace(/\.\d{3}Z$/, 'Z');
447
+
448
+ const randomStr = Math.random().toString(36).substring(2, 12);
449
+ const applyUrl = `https://imagex.bytedanceapi.com/?Action=ApplyImageUpload&Version=2018-08-01&ServiceId=${actualServiceId}&FileSize=${fileSize}&s=${randomStr}`;
450
+
451
+ const requestHeaders = {
452
+ 'x-amz-date': timestamp,
453
+ 'x-amz-security-token': session_token
454
+ };
455
+
456
+ const authorization = createSignature('GET', applyUrl, requestHeaders, access_key_id, secret_access_key, session_token);
457
+
458
+ const applyResponse = await fetch(applyUrl, {
459
+ method: 'GET',
460
+ headers: {
461
+ 'accept': '*/*',
462
+ 'accept-language': 'zh-CN,zh;q=0.9',
463
+ 'authorization': authorization,
464
+ 'origin': 'https://jimeng.jianying.com',
465
+ 'referer': 'https://jimeng.jianying.com/ai-tool/video/generate',
466
+ 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36',
467
+ 'x-amz-date': timestamp,
468
+ 'x-amz-security-token': session_token,
469
+ },
470
+ });
471
+
472
+ if (!applyResponse.ok) {
473
+ const errorText = await applyResponse.text();
474
+ throw new Error(`申请上传权限失败: ${applyResponse.status} - ${errorText}`);
475
+ }
476
+
477
+ const applyResult = await applyResponse.json();
478
+
479
+ if (applyResult?.ResponseMetadata?.Error) {
480
+ throw new Error(`申请上传权限失败: ${JSON.stringify(applyResult.ResponseMetadata.Error)}`);
481
+ }
482
+
483
+ const uploadAddress = applyResult?.Result?.UploadAddress;
484
+ if (!uploadAddress || !uploadAddress.StoreInfos || !uploadAddress.UploadHosts) {
485
+ throw new Error(`获取上传地址失败: ${JSON.stringify(applyResult)}`);
486
+ }
487
+
488
+ const storeInfo = uploadAddress.StoreInfos[0];
489
+ const uploadHost = uploadAddress.UploadHosts[0];
490
+ const auth = storeInfo.Auth;
491
+
492
+ const uploadUrl = `https://${uploadHost}/upload/v1/${storeInfo.StoreUri}`;
493
+
494
+ // 第三步:上传图片文件
495
+ const uploadResponse = await fetch(uploadUrl, {
496
+ method: 'POST',
497
+ headers: {
498
+ 'Accept': '*/*',
499
+ 'Authorization': auth,
500
+ 'Content-CRC32': crc32,
501
+ 'Content-Disposition': 'attachment; filename="undefined"',
502
+ 'Content-Type': 'application/octet-stream',
503
+ 'Origin': 'https://jimeng.jianying.com',
504
+ 'Referer': 'https://jimeng.jianying.com/ai-tool/video/generate',
505
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36',
506
+ },
507
+ body: buffer,
508
+ });
509
+
510
+ if (!uploadResponse.ok) {
511
+ const errorText = await uploadResponse.text();
512
+ throw new Error(`图片上传失败: ${uploadResponse.status} - ${errorText}`);
513
+ }
514
+
515
+ logger.info(`Buffer图片文件上传成功`);
516
+
517
+ // 第四步:提交上传
518
+ const commitUrl = `https://imagex.bytedanceapi.com/?Action=CommitImageUpload&Version=2018-08-01&ServiceId=${actualServiceId}`;
519
+
520
+ const commitTimestamp = new Date().toISOString().replace(/[:\-]/g, '').replace(/\.\d{3}Z$/, 'Z');
521
+ const commitPayload = JSON.stringify({
522
+ SessionKey: uploadAddress.SessionKey,
523
+ SuccessActionStatus: "200"
524
+ });
525
+
526
+ const payloadHash = crypto.createHash('sha256').update(commitPayload, 'utf8').digest('hex');
527
+
528
+ const commitRequestHeaders = {
529
+ 'x-amz-date': commitTimestamp,
530
+ 'x-amz-security-token': session_token,
531
+ 'x-amz-content-sha256': payloadHash
532
+ };
533
+
534
+ const commitAuthorization = createSignature('POST', commitUrl, commitRequestHeaders, access_key_id, secret_access_key, session_token, commitPayload);
535
+
536
+ const commitResponse = await fetch(commitUrl, {
537
+ method: 'POST',
538
+ headers: {
539
+ 'accept': '*/*',
540
+ 'authorization': commitAuthorization,
541
+ 'content-type': 'application/json',
542
+ 'origin': 'https://jimeng.jianying.com',
543
+ 'referer': 'https://jimeng.jianying.com/ai-tool/video/generate',
544
+ 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36',
545
+ 'x-amz-date': commitTimestamp,
546
+ 'x-amz-security-token': session_token,
547
+ 'x-amz-content-sha256': payloadHash,
548
+ },
549
+ body: commitPayload,
550
+ });
551
+
552
+ if (!commitResponse.ok) {
553
+ const errorText = await commitResponse.text();
554
+ throw new Error(`提交上传失败: ${commitResponse.status} - ${errorText}`);
555
+ }
556
+
557
+ const commitResult = await commitResponse.json();
558
+
559
+ if (commitResult?.ResponseMetadata?.Error) {
560
+ throw new Error(`提交上传失败: ${JSON.stringify(commitResult.ResponseMetadata.Error)}`);
561
+ }
562
+
563
+ if (!commitResult?.Result?.Results || commitResult.Result.Results.length === 0) {
564
+ throw new Error(`提交上传响应缺少结果: ${JSON.stringify(commitResult)}`);
565
+ }
566
+
567
+ const uploadResult = commitResult.Result.Results[0];
568
+ if (uploadResult.UriStatus !== 2000) {
569
+ throw new Error(`图片上传状态异常: UriStatus=${uploadResult.UriStatus}`);
570
+ }
571
+
572
+ const fullImageUri = uploadResult.Uri;
573
+
574
+ const pluginResult = commitResult.Result?.PluginResult?.[0];
575
+ if (pluginResult && pluginResult.ImageUri) {
576
+ logger.info(`Buffer视频图片上传完成: ${pluginResult.ImageUri}`);
577
+ return pluginResult.ImageUri;
578
+ }
579
+
580
+ logger.info(`Buffer视频图片上传完成: ${fullImageUri}`);
581
+ return fullImageUri;
582
+
583
+ } catch (error) {
584
+ logger.error(`Buffer视频图片上传失败: ${error.message}`);
585
+ throw error;
586
+ }
587
+ }
588
+
589
+ /**
590
+ * 通过 get_local_item_list API 获取高质量视频下载URL
591
+ * 浏览器下载视频时使用此API获取高码率版本(~6297 vs 预览版 ~1152)
592
+ *
593
+ * @param itemId 视频项目ID
594
+ * @param refreshToken 刷新令牌
595
+ * @returns 高质量视频URL,失败时返回 null
596
+ */
597
+ async function fetchHighQualityVideoUrl(itemId: string, refreshToken: string): Promise<string | null> {
598
+ try {
599
+ logger.info(`尝试获取高质量视频下载URL,item_id: ${itemId}`);
600
+
601
+ const result = await request("post", "/mweb/v1/get_local_item_list", refreshToken, {
602
+ data: {
603
+ item_id_list: [itemId],
604
+ pack_item_opt: {
605
+ scene: 1,
606
+ need_data_integrity: true,
607
+ },
608
+ is_for_video_download: true,
609
+ },
610
+ });
611
+
612
+ const responseStr = JSON.stringify(result);
613
+ logger.info(`get_local_item_list 响应大小: ${responseStr.length} 字符`);
614
+
615
+ // 策略1: 从结构化字段中提取视频URL
616
+ const itemList = result.item_list || result.local_item_list || [];
617
+ if (itemList.length > 0) {
618
+ const item = itemList[0];
619
+ const videoUrl =
620
+ item?.video?.transcoded_video?.origin?.video_url ||
621
+ item?.video?.download_url ||
622
+ item?.video?.play_url ||
623
+ item?.video?.url;
624
+
625
+ if (videoUrl) {
626
+ logger.info(`从get_local_item_list结构化字段获取到高清视频URL: ${videoUrl}`);
627
+ return videoUrl;
628
+ }
629
+ }
630
+
631
+ // 策略2: 正则匹配 dreamnia.jimeng.com 高质量URL
632
+ const hqUrlMatch = responseStr.match(/https:\/\/v[0-9]+-dreamnia\.jimeng\.com\/[^"\s\\]+/);
633
+ if (hqUrlMatch && hqUrlMatch[0]) {
634
+ logger.info(`正则提取到高质量视频URL (dreamnia): ${hqUrlMatch[0]}`);
635
+ return hqUrlMatch[0];
636
+ }
637
+
638
+ // 策略3: 匹配任何 jimeng.com 域名的视频URL
639
+ const jimengUrlMatch = responseStr.match(/https:\/\/v[0-9]+-[^"\\]*\.jimeng\.com\/[^"\s\\]+/);
640
+ if (jimengUrlMatch && jimengUrlMatch[0]) {
641
+ logger.info(`正则提取到jimeng视频URL: ${jimengUrlMatch[0]}`);
642
+ return jimengUrlMatch[0];
643
+ }
644
+
645
+ // 策略4: 匹配任何视频URL(兜底)
646
+ const anyVideoUrlMatch = responseStr.match(/https:\/\/v[0-9]+-[^"\\]*\.(vlabvod|jimeng)\.com\/[^"\s\\]+/);
647
+ if (anyVideoUrlMatch && anyVideoUrlMatch[0]) {
648
+ logger.info(`从get_local_item_list提取到视频URL: ${anyVideoUrlMatch[0]}`);
649
+ return anyVideoUrlMatch[0];
650
+ }
651
+
652
+ logger.warn(`未能从get_local_item_list响应中提取到视频URL`);
653
+ return null;
654
+ } catch (error) {
655
+ logger.warn(`获取高质量视频下载URL失败: ${error.message}`);
656
+ return null;
657
+ }
658
+ }
659
+
660
+ /**
661
+ * 生成视频
662
+ *
663
+ * @param _model 模型名称
664
+ * @param prompt 提示词
665
+ * @param options 选项
666
+ * @param refreshToken 刷新令牌
667
+ * @returns 视频URL
668
+ */
669
+ export async function generateVideo(
670
+ _model: string,
671
+ prompt: string,
672
+ {
673
+ ratio = "1:1",
674
+ resolution = "720p",
675
+ duration = 5,
676
+ filePaths = [],
677
+ files = [],
678
+ }: {
679
+ ratio?: string;
680
+ resolution?: string;
681
+ duration?: number;
682
+ filePaths?: string[];
683
+ files?: any[];
684
+ },
685
+ refreshToken: string
686
+ ) {
687
+ const model = getModel(_model);
688
+
689
+ // 解析分辨率参数获取实际的宽高
690
+ const { width, height } = resolveVideoResolution(resolution, ratio);
691
+
692
+ logger.info(`使用模型: ${_model} 映射模型: ${model} ${width}x${height} (${ratio}@${resolution}) 时长: ${duration}秒`);
693
+
694
+ // 检查积分
695
+ const { totalCredit } = await getCredit(refreshToken);
696
+ if (totalCredit <= 0)
697
+ await receiveCredit(refreshToken);
698
+
699
+ // 处理首帧和尾帧图片
700
+ let first_frame_image = undefined;
701
+ let end_frame_image = undefined;
702
+
703
+ // 处理上传的文件(multipart/form-data)
704
+ if (files && files.length > 0) {
705
+ let uploadIDs: string[] = [];
706
+ logger.info(`开始处理 ${files.length} 个上传文件用于视频生成`);
707
+
708
+ for (let i = 0; i < files.length; i++) {
709
+ const file = files[i];
710
+ if (!file || !file.filepath) {
711
+ logger.warn(`第 ${i + 1} 个文件无效,跳过`);
712
+ continue;
713
+ }
714
+
715
+ try {
716
+ logger.info(`开始上传第 ${i + 1} 个文件: ${file.originalFilename || file.filepath}`);
717
+
718
+ // 读取文件内容并上传
719
+ const buffer = fs.readFileSync(file.filepath);
720
+ const imageUri = await uploadImageBufferForVideo(buffer, refreshToken);
721
+
722
+ if (imageUri) {
723
+ uploadIDs.push(imageUri);
724
+ logger.info(`第 ${i + 1} 个文件上传成功: ${imageUri}`);
725
+ } else {
726
+ logger.error(`第 ${i + 1} 个文件上传失败: 未获取到 image_uri`);
727
+ }
728
+ } catch (error) {
729
+ logger.error(`第 ${i + 1} 个文件上传失败: ${error.message}`);
730
+
731
+ if (i === 0) {
732
+ logger.error(`首帧文件上传失败,停止视频生成以避免浪费积分`);
733
+ throw new APIException(EX.API_REQUEST_FAILED, `首帧文件上传失败: ${error.message}`);
734
+ } else {
735
+ logger.warn(`第 ${i + 1} 个文件上传失败,将跳过此文件继续处理`);
736
+ }
737
+ }
738
+ }
739
+
740
+ logger.info(`文件上传完成,成功上传 ${uploadIDs.length} 个文件`);
741
+
742
+ if (uploadIDs.length === 0) {
743
+ logger.error(`所有文件上传失败,停止视频生成以避免浪费积分`);
744
+ throw new APIException(EX.API_REQUEST_FAILED, '所有文件上传失败,请检查文件是否有效');
745
+ }
746
+
747
+ // 构建首帧图片对象
748
+ if (uploadIDs[0]) {
749
+ first_frame_image = {
750
+ format: "",
751
+ height: height,
752
+ id: util.uuid(),
753
+ image_uri: uploadIDs[0],
754
+ name: "",
755
+ platform_type: 1,
756
+ source_from: "upload",
757
+ type: "image",
758
+ uri: uploadIDs[0],
759
+ width: width,
760
+ };
761
+ logger.info(`设置首帧图片: ${uploadIDs[0]}`);
762
+ }
763
+
764
+ // 构建尾帧图片对象
765
+ if (uploadIDs[1]) {
766
+ end_frame_image = {
767
+ format: "",
768
+ height: height,
769
+ id: util.uuid(),
770
+ image_uri: uploadIDs[1],
771
+ name: "",
772
+ platform_type: 1,
773
+ source_from: "upload",
774
+ type: "image",
775
+ uri: uploadIDs[1],
776
+ width: width,
777
+ };
778
+ logger.info(`设置尾帧图片: ${uploadIDs[1]}`);
779
+ }
780
+ } else if (filePaths && filePaths.length > 0) {
781
+ let uploadIDs: string[] = [];
782
+ logger.info(`开始上传 ${filePaths.length} 张图片用于视频生成`);
783
+
784
+ for (let i = 0; i < filePaths.length; i++) {
785
+ const filePath = filePaths[i];
786
+ if (!filePath) {
787
+ logger.warn(`第 ${i + 1} 张图片路径为空,跳过`);
788
+ continue;
789
+ }
790
+
791
+ try {
792
+ logger.info(`开始上传第 ${i + 1} 张图片: ${filePath}`);
793
+
794
+ // 使用Amazon S3上传方式
795
+ const imageUri = await uploadImageForVideo(filePath, refreshToken);
796
+
797
+ if (imageUri) {
798
+ uploadIDs.push(imageUri);
799
+ logger.info(`第 ${i + 1} 张图片上传成功: ${imageUri}`);
800
+ } else {
801
+ logger.error(`第 ${i + 1} 张图片上传失败: 未获取到 image_uri`);
802
+ }
803
+ } catch (error) {
804
+ logger.error(`第 ${i + 1} 张图片上传失败: ${error.message}`);
805
+
806
+ // 图片上传失败时,停止视频生成避免浪费积分
807
+ if (i === 0) {
808
+ logger.error(`首帧图片上传失败,停止视频生成以避免浪费积分`);
809
+ throw new APIException(EX.API_REQUEST_FAILED, `首帧图片上传失败: ${error.message}`);
810
+ } else {
811
+ logger.warn(`第 ${i + 1} 张图片上传失败,将跳过此图片继续处理`);
812
+ }
813
+ }
814
+ }
815
+
816
+ logger.info(`图片上传完成,成功上传 ${uploadIDs.length} 张图片`);
817
+
818
+ // 如果没有成功上传任何图片,停止视频生成
819
+ if (uploadIDs.length === 0) {
820
+ logger.error(`所有图片上传失败,停止视频生成以避免浪费积分`);
821
+ throw new APIException(EX.API_REQUEST_FAILED, '所有图片上传失败,请检查图片URL是否有效');
822
+ }
823
+
824
+ // 构建首帧图片对象
825
+ if (uploadIDs[0]) {
826
+ first_frame_image = {
827
+ format: "",
828
+ height: height,
829
+ id: util.uuid(),
830
+ image_uri: uploadIDs[0],
831
+ name: "",
832
+ platform_type: 1,
833
+ source_from: "upload",
834
+ type: "image",
835
+ uri: uploadIDs[0],
836
+ width: width,
837
+ };
838
+ logger.info(`设置首帧图片: ${uploadIDs[0]}`);
839
+ }
840
+
841
+ // 构建尾帧图片对象
842
+ if (uploadIDs[1]) {
843
+ end_frame_image = {
844
+ format: "",
845
+ height: height,
846
+ id: util.uuid(),
847
+ image_uri: uploadIDs[1],
848
+ name: "",
849
+ platform_type: 1,
850
+ source_from: "upload",
851
+ type: "image",
852
+ uri: uploadIDs[1],
853
+ width: width,
854
+ };
855
+ logger.info(`设置尾帧图片: ${uploadIDs[1]}`);
856
+ } else if (filePaths.length > 1) {
857
+ logger.warn(`第二张图片上传失败或未提供,将仅使用首帧图片`);
858
+ }
859
+ } else {
860
+ logger.info(`未提供图片文件,将进行纯文本视频生成`);
861
+ }
862
+
863
+ const componentId = util.uuid();
864
+ const metricsExtra = JSON.stringify({
865
+ "enterFrom": "click",
866
+ "isDefaultSeed": 1,
867
+ "promptSource": "custom",
868
+ "isRegenerate": false,
869
+ "originSubmitId": util.uuid(),
870
+ });
871
+
872
+ // 获取当前模型的 draft 版本
873
+ const draftVersion = MODEL_DRAFT_VERSIONS[_model] || DEFAULT_DRAFT_VERSION;
874
+
875
+ // 计算视频宽高比
876
+ const gcd = (a: number, b: number): number => b === 0 ? a : gcd(b, a % b);
877
+ const divisor = gcd(width, height);
878
+ const aspectRatio = `${width / divisor}:${height / divisor}`;
879
+
880
+ // 构建请求参数
881
+ const { aigc_data } = await request(
882
+ "post",
883
+ "/mweb/v1/aigc_draft/generate",
884
+ refreshToken,
885
+ {
886
+ params: {
887
+ aigc_features: "app_lip_sync",
888
+ web_version: "6.6.0",
889
+ da_version: draftVersion,
890
+ },
891
+ data: {
892
+ "extend": {
893
+ "root_model": end_frame_image ? MODEL_MAP['jimeng-video-3.0'] : model,
894
+ "m_video_commerce_info": {
895
+ benefit_type: "basic_video_operation_vgfm_v_three",
896
+ resource_id: "generate_video",
897
+ resource_id_type: "str",
898
+ resource_sub_type: "aigc"
899
+ },
900
+ "m_video_commerce_info_list": [{
901
+ benefit_type: "basic_video_operation_vgfm_v_three",
902
+ resource_id: "generate_video",
903
+ resource_id_type: "str",
904
+ resource_sub_type: "aigc"
905
+ }]
906
+ },
907
+ "submit_id": util.uuid(),
908
+ "metrics_extra": metricsExtra,
909
+ "draft_content": JSON.stringify({
910
+ "type": "draft",
911
+ "id": util.uuid(),
912
+ "min_version": "3.0.5",
913
+ "is_from_tsn": true,
914
+ "version": draftVersion,
915
+ "main_component_id": componentId,
916
+ "component_list": [{
917
+ "type": "video_base_component",
918
+ "id": componentId,
919
+ "min_version": "1.0.0",
920
+ "metadata": {
921
+ "type": "",
922
+ "id": util.uuid(),
923
+ "created_platform": 3,
924
+ "created_platform_version": "",
925
+ "created_time_in_ms": Date.now(),
926
+ "created_did": ""
927
+ },
928
+ "generate_type": "gen_video",
929
+ "aigc_mode": "workbench",
930
+ "abilities": {
931
+ "type": "",
932
+ "id": util.uuid(),
933
+ "gen_video": {
934
+ "id": util.uuid(),
935
+ "type": "",
936
+ "text_to_video_params": {
937
+ "type": "",
938
+ "id": util.uuid(),
939
+ "model_req_key": model,
940
+ "priority": 0,
941
+ "seed": Math.floor(Math.random() * 100000000) + 2500000000,
942
+ "video_aspect_ratio": aspectRatio,
943
+ "video_gen_inputs": [{
944
+ duration_ms: duration * 1000,
945
+ first_frame_image: first_frame_image,
946
+ end_frame_image: end_frame_image,
947
+ fps: 24,
948
+ id: util.uuid(),
949
+ min_version: "3.0.5",
950
+ prompt: prompt,
951
+ resolution: resolution,
952
+ type: "",
953
+ video_mode: 2
954
+ }]
955
+ },
956
+ "video_task_extra": metricsExtra,
957
+ }
958
+ }
959
+ }],
960
+ }),
961
+ http_common_info: {
962
+ aid: DEFAULT_ASSISTANT_ID,
963
+ },
964
+ },
965
+ }
966
+ );
967
+
968
+ const historyId = aigc_data.history_record_id;
969
+ if (!historyId)
970
+ throw new APIException(EX.API_IMAGE_GENERATION_FAILED, "记录ID不存在");
971
+
972
+ // 轮询获取结果
973
+ let status = 20, failCode, item_list = [];
974
+ let retryCount = 0;
975
+ const maxRetries = 60; // 增加重试次数,支持约20分钟的总重试时间
976
+
977
+ // 首次查询前等待更长时间,让服务器有时间处理请求
978
+ await new Promise((resolve) => setTimeout(resolve, 5000));
979
+
980
+ logger.info(`开始轮询视频生成结果,历史ID: ${historyId},最大重试次数: ${maxRetries}`);
981
+ logger.info(`即梦官网API地址: https://jimeng.jianying.com/mweb/v1/get_history_by_ids`);
982
+ logger.info(`视频生成请求已发送,请同时在即梦官网查看: https://jimeng.jianying.com/ai-tool/video/generate`);
983
+
984
+ while (status === 20 && retryCount < maxRetries) {
985
+ try {
986
+ // 构建请求URL和参数
987
+ const requestUrl = "/mweb/v1/get_history_by_ids";
988
+ const requestData = {
989
+ history_ids: [historyId],
990
+ };
991
+
992
+ // 尝试两种不同的API请求方式
993
+ let result;
994
+ let useAlternativeApi = retryCount > 10 && retryCount % 2 === 0; // 在重试10次后,每隔一次尝试备用API
995
+
996
+ if (useAlternativeApi) {
997
+ // 备用API请求方式
998
+ logger.info(`尝试备用API请求方式,URL: ${requestUrl}, 历史ID: ${historyId}, 重试次数: ${retryCount + 1}/${maxRetries}`);
999
+ const alternativeRequestData = {
1000
+ history_record_ids: [historyId],
1001
+ };
1002
+ result = await request("post", "/mweb/v1/get_history_records", refreshToken, {
1003
+ data: alternativeRequestData,
1004
+ });
1005
+ logger.info(`备用API响应摘要: ${JSON.stringify(result).substring(0, 500)}...`);
1006
+ } else {
1007
+ // 标准API请求方式
1008
+ logger.info(`发送请求获取视频生成结果,URL: ${requestUrl}, 历史ID: ${historyId}, 重试次数: ${retryCount + 1}/${maxRetries}`);
1009
+ result = await request("post", requestUrl, refreshToken, {
1010
+ data: requestData,
1011
+ });
1012
+ const responseStr = JSON.stringify(result);
1013
+ logger.info(`标准API响应摘要: ${responseStr.substring(0, 300)}...`);
1014
+ }
1015
+
1016
+
1017
+ // 检查结果是否有效
1018
+ let historyData;
1019
+
1020
+ if (useAlternativeApi && result.history_records && result.history_records.length > 0) {
1021
+ // 处理备用API返回的数据格式
1022
+ historyData = result.history_records[0];
1023
+ logger.info(`从备用API获取到历史记录`);
1024
+ } else if (result.history_list && result.history_list.length > 0) {
1025
+ // 处理标准API返回的数据格式
1026
+ historyData = result.history_list[0];
1027
+ logger.info(`从标准API获取到历史记录`);
1028
+ } else if (result[historyId]) {
1029
+ // get_history_by_ids 返回数据以 historyId 为键(如 result["8918159809292"])
1030
+ historyData = result[historyId];
1031
+ logger.info(`从historyId键获取到历史记录`);
1032
+ } else {
1033
+ // 所有API都没有返回有效数据
1034
+ logger.warn(`历史记录不存在,重试中 (${retryCount + 1}/${maxRetries})... 历史ID: ${historyId}`);
1035
+ logger.info(`请同时在即梦官网检查视频是否已生成: https://jimeng.jianying.com/ai-tool/video/generate`);
1036
+
1037
+ retryCount++;
1038
+ // 增加重试间隔时间,但设置上限为30秒
1039
+ const waitTime = Math.min(2000 * (retryCount + 1), 30000);
1040
+ logger.info(`等待 ${waitTime}ms 后进行第 ${retryCount + 1} 次重试`);
1041
+ await new Promise((resolve) => setTimeout(resolve, waitTime));
1042
+ continue;
1043
+ }
1044
+
1045
+ // 记录获取到的结果详情
1046
+ logger.info(`获取到历史记录结果: ${JSON.stringify(historyData)}`);
1047
+
1048
+
1049
+ // 从历史数据中提取状态和结果
1050
+ status = historyData.status;
1051
+ failCode = historyData.fail_code;
1052
+ item_list = historyData.item_list || [];
1053
+
1054
+ logger.info(`视频生成状态: ${status}, 失败代码: ${failCode || '无'}, 项目列表长度: ${item_list.length}`);
1055
+
1056
+ // 如果有视频URL,提前记录
1057
+ let tempVideoUrl = item_list?.[0]?.video?.transcoded_video?.origin?.video_url;
1058
+ if (!tempVideoUrl) {
1059
+ // 尝试从其他可能的路径获取
1060
+ tempVideoUrl = item_list?.[0]?.video?.play_url ||
1061
+ item_list?.[0]?.video?.download_url ||
1062
+ item_list?.[0]?.video?.url;
1063
+ }
1064
+
1065
+ if (tempVideoUrl) {
1066
+ logger.info(`检测到视频URL: ${tempVideoUrl}`);
1067
+ }
1068
+
1069
+ if (status === 30) {
1070
+ const error = failCode === 2038
1071
+ ? new APIException(EX.API_CONTENT_FILTERED, "内容被过滤")
1072
+ : new APIException(EX.API_IMAGE_GENERATION_FAILED, `生成失败,错误码: ${failCode}`);
1073
+ // 添加历史ID到错误对象,以便在chat.ts中显示
1074
+ error.historyId = historyId;
1075
+ throw error;
1076
+ }
1077
+
1078
+ // 如果状态仍在处理中,等待后继续
1079
+ if (status === 20) {
1080
+ const waitTime = 2000 * (Math.min(retryCount + 1, 5)); // 随着重试次数增加等待时间,但最多10秒
1081
+ logger.info(`视频生成中,状态码: ${status},等待 ${waitTime}ms 后继续查询`);
1082
+ await new Promise((resolve) => setTimeout(resolve, waitTime));
1083
+ }
1084
+ } catch (error) {
1085
+ logger.error(`轮询视频生成结果出错: ${error.message}`);
1086
+ retryCount++;
1087
+ await new Promise((resolve) => setTimeout(resolve, 2000 * (retryCount + 1)));
1088
+ }
1089
+ }
1090
+
1091
+ // 如果达到最大重试次数仍未成功
1092
+ if (retryCount >= maxRetries && status === 20) {
1093
+ logger.error(`视频生成超时,已尝试 ${retryCount} 次,总耗时约 ${Math.floor(retryCount * 2000 / 1000 / 60)} 分钟`);
1094
+ const error = new APIException(EX.API_IMAGE_GENERATION_FAILED, "获取视频生成结果超时,请稍后在即梦官网查看您的视频");
1095
+ // 添加历史ID到错误对象,以便在chat.ts中显示
1096
+ error.historyId = historyId;
1097
+ throw error;
1098
+ }
1099
+
1100
+ // 尝试通过 get_local_item_list 获取高质量视频下载URL
1101
+ const itemId = item_list?.[0]?.item_id
1102
+ || item_list?.[0]?.id
1103
+ || item_list?.[0]?.local_item_id
1104
+ || item_list?.[0]?.common_attr?.id;
1105
+
1106
+ if (itemId) {
1107
+ try {
1108
+ const hqVideoUrl = await fetchHighQualityVideoUrl(String(itemId), refreshToken);
1109
+ if (hqVideoUrl) {
1110
+ logger.info(`视频生成成功(高质量),URL: ${hqVideoUrl}`);
1111
+ return hqVideoUrl;
1112
+ }
1113
+ } catch (error) {
1114
+ logger.warn(`获取高质量视频URL失败,将使用预览URL作为回退: ${error.message}`);
1115
+ }
1116
+ } else {
1117
+ logger.warn(`未能从item_list中提取item_id,将使用预览URL。item_list[0]键: ${item_list?.[0] ? Object.keys(item_list[0]).join(', ') : '无'}`);
1118
+ }
1119
+
1120
+ // 回退:提取预览视频URL
1121
+ let videoUrl = item_list?.[0]?.video?.transcoded_video?.origin?.video_url;
1122
+
1123
+ // 如果通过常规路径无法获取视频URL,尝试其他可能的路径
1124
+ if (!videoUrl) {
1125
+ // 尝试从item_list中的其他可能位置获取
1126
+ if (item_list?.[0]?.video?.play_url) {
1127
+ videoUrl = item_list[0].video.play_url;
1128
+ logger.info(`从play_url获取到视频URL: ${videoUrl}`);
1129
+ } else if (item_list?.[0]?.video?.download_url) {
1130
+ videoUrl = item_list[0].video.download_url;
1131
+ logger.info(`从download_url获取到视频URL: ${videoUrl}`);
1132
+ } else if (item_list?.[0]?.video?.url) {
1133
+ videoUrl = item_list[0].video.url;
1134
+ logger.info(`从url获取到视频URL: ${videoUrl}`);
1135
+ } else {
1136
+ // 如果仍然找不到,记录错误并抛出异常
1137
+ logger.error(`未能获取视频URL,item_list: ${JSON.stringify(item_list)}`);
1138
+ const error = new APIException(EX.API_IMAGE_GENERATION_FAILED, "未能获取视频URL,请稍后在即梦官网查看");
1139
+ // 添加历史ID到错误对象,以便在chat.ts中显示
1140
+ error.historyId = historyId;
1141
+ throw error;
1142
+ }
1143
+ }
1144
+
1145
+ logger.info(`视频生成成功,URL: ${videoUrl}`);
1146
+ return videoUrl;
1147
+ }
1148
+
1149
+ /**
1150
+ * Seedance 2.0 多图智能视频生成
1151
+ * 支持多张图片与文本混合生成视频
1152
+ *
1153
+ * @param _model 模型名称
1154
+ * @param prompt 提示词(支持 @1 @2 等引用图片占位符)
1155
+ * @param options 选项
1156
+ * @param refreshToken 刷新令牌
1157
+ * @returns 视频URL
1158
+ */
1159
+ export async function generateSeedanceVideo(
1160
+ _model: string,
1161
+ prompt: string,
1162
+ {
1163
+ ratio = "4:3",
1164
+ resolution = "720p",
1165
+ duration = 4,
1166
+ filePaths = [],
1167
+ files = [],
1168
+ }: {
1169
+ ratio?: string;
1170
+ resolution?: string;
1171
+ duration?: number;
1172
+ filePaths?: string[];
1173
+ files?: any[];
1174
+ },
1175
+ refreshToken: string
1176
+ ) {
1177
+ const model = getModel(_model);
1178
+ const benefitType = SEEDANCE_BENEFIT_TYPE_MAP[_model] || "dreamina_video_seedance_20_pro";
1179
+
1180
+ // Seedance 2.0 默认时长为4秒
1181
+ const actualDuration = duration || 4;
1182
+
1183
+ // 解析分辨率参数获取实际的宽高
1184
+ const { width, height } = resolveVideoResolution(resolution, ratio);
1185
+
1186
+ logger.info(`Seedance 2.0 生成: 模型=${_model} 映射=${model} ${width}x${height} (${ratio}@${resolution}) 时长=${actualDuration}秒`);
1187
+
1188
+ // 检查积分
1189
+ const { totalCredit } = await getCredit(refreshToken);
1190
+ if (totalCredit <= 0)
1191
+ await receiveCredit(refreshToken);
1192
+
1193
+ // 上传所有图片
1194
+ let uploadedImages: Array<{uri: string, width: number, height: number}> = [];
1195
+
1196
+ // 处理上传的文件(multipart/form-data)
1197
+ if (files && files.length > 0) {
1198
+ logger.info(`Seedance: 开始处理 ${files.length} 个上传文件`);
1199
+
1200
+ for (let i = 0; i < files.length; i++) {
1201
+ const file = files[i];
1202
+ if (!file || !file.filepath) {
1203
+ logger.warn(`Seedance: 第 ${i + 1} 个文件无效,跳过`);
1204
+ continue;
1205
+ }
1206
+
1207
+ try {
1208
+ logger.info(`Seedance: 开始上传第 ${i + 1} 个文件: ${file.originalFilename || file.filepath}`);
1209
+ const buffer = fs.readFileSync(file.filepath);
1210
+ const imageUri = await uploadImageBufferForVideo(buffer, refreshToken);
1211
+
1212
+ if (imageUri) {
1213
+ uploadedImages.push({ uri: imageUri, width, height });
1214
+ logger.info(`Seedance: 第 ${i + 1} 个文件上传成功: ${imageUri}`);
1215
+ }
1216
+ } catch (error) {
1217
+ logger.error(`Seedance: 第 ${i + 1} 个文件上传失败: ${error.message}`);
1218
+ if (i === 0) {
1219
+ throw new APIException(EX.API_REQUEST_FAILED, `首张图片上传失败: ${error.message}`);
1220
+ }
1221
+ }
1222
+ }
1223
+ } else if (filePaths && filePaths.length > 0) {
1224
+ logger.info(`Seedance: 开始上传 ${filePaths.length} 张图片`);
1225
+
1226
+ for (let i = 0; i < filePaths.length; i++) {
1227
+ const filePath = filePaths[i];
1228
+ if (!filePath) continue;
1229
+
1230
+ try {
1231
+ logger.info(`Seedance: 开始上传第 ${i + 1} 张图片: ${filePath}`);
1232
+ const imageUri = await uploadImageForVideo(filePath, refreshToken);
1233
+
1234
+ if (imageUri) {
1235
+ uploadedImages.push({ uri: imageUri, width, height });
1236
+ logger.info(`Seedance: 第 ${i + 1} 张图片上传成功: ${imageUri}`);
1237
+ }
1238
+ } catch (error) {
1239
+ logger.error(`Seedance: 第 ${i + 1} 张图片上传失败: ${error.message}`);
1240
+ if (i === 0) {
1241
+ throw new APIException(EX.API_REQUEST_FAILED, `首张图片上传失败: ${error.message}`);
1242
+ }
1243
+ }
1244
+ }
1245
+ }
1246
+
1247
+ if (uploadedImages.length === 0) {
1248
+ throw new APIException(EX.API_REQUEST_FAILED, 'Seedance 2.0 需要至少一张图片');
1249
+ }
1250
+
1251
+ logger.info(`Seedance: 成功上传 ${uploadedImages.length} 张图片`);
1252
+
1253
+ // 构建 material_list(所有图片)
1254
+ const materialList = uploadedImages.map((img, index) => ({
1255
+ type: "",
1256
+ id: util.uuid(),
1257
+ material_type: "image",
1258
+ image_info: {
1259
+ type: "image",
1260
+ id: util.uuid(),
1261
+ source_from: "upload",
1262
+ platform_type: 1,
1263
+ name: "",
1264
+ image_uri: img.uri,
1265
+ width: img.width,
1266
+ height: img.height,
1267
+ format: "",
1268
+ uri: img.uri,
1269
+ }
1270
+ }));
1271
+
1272
+ // 解析 prompt 中的图片占位符(@1, @2 等)并构建 meta_list
1273
+ const metaList = buildMetaListFromPrompt(prompt, uploadedImages.length);
1274
+
1275
+ const componentId = util.uuid();
1276
+ const submitId = util.uuid();
1277
+ const draftVersion = MODEL_DRAFT_VERSIONS[_model] || "3.3.9";
1278
+
1279
+ // 计算视频宽高比
1280
+ const gcd = (a: number, b: number): number => b === 0 ? a : gcd(b, a % b);
1281
+ const divisor = gcd(width, height);
1282
+ const aspectRatio = `${width / divisor}:${height / divisor}`;
1283
+
1284
+ const metricsExtra = JSON.stringify({
1285
+ isDefaultSeed: 1,
1286
+ originSubmitId: submitId,
1287
+ isRegenerate: false,
1288
+ enterFrom: "click",
1289
+ position: "page_bottom_box",
1290
+ functionMode: "omni_reference",
1291
+ sceneOptions: JSON.stringify([{
1292
+ type: "video",
1293
+ scene: "BasicVideoGenerateButton",
1294
+ modelReqKey: model,
1295
+ videoDuration: actualDuration,
1296
+ reportParams: {
1297
+ enterSource: "generate",
1298
+ vipSource: "generate",
1299
+ extraVipFunctionKey: model,
1300
+ useVipFunctionDetailsReporterHoc: true
1301
+ },
1302
+ materialTypes: [1]
1303
+ }])
1304
+ });
1305
+
1306
+ // 构建 Seedance 2.0 专用请求
1307
+ const { aigc_data } = await request(
1308
+ "post",
1309
+ "/mweb/v1/aigc_draft/generate",
1310
+ refreshToken,
1311
+ {
1312
+ params: {
1313
+ aigc_features: "app_lip_sync",
1314
+ web_version: "7.5.0",
1315
+ da_version: draftVersion,
1316
+ },
1317
+ data: {
1318
+ extend: {
1319
+ root_model: model,
1320
+ m_video_commerce_info: {
1321
+ benefit_type: benefitType,
1322
+ resource_id: "generate_video",
1323
+ resource_id_type: "str",
1324
+ resource_sub_type: "aigc"
1325
+ },
1326
+ m_video_commerce_info_list: [{
1327
+ benefit_type: benefitType,
1328
+ resource_id: "generate_video",
1329
+ resource_id_type: "str",
1330
+ resource_sub_type: "aigc"
1331
+ }]
1332
+ },
1333
+ submit_id: submitId,
1334
+ metrics_extra: metricsExtra,
1335
+ draft_content: JSON.stringify({
1336
+ type: "draft",
1337
+ id: util.uuid(),
1338
+ min_version: draftVersion,
1339
+ min_features: ["AIGC_Video_UnifiedEdit"],
1340
+ is_from_tsn: true,
1341
+ version: draftVersion,
1342
+ main_component_id: componentId,
1343
+ component_list: [{
1344
+ type: "video_base_component",
1345
+ id: componentId,
1346
+ min_version: "1.0.0",
1347
+ aigc_mode: "workbench",
1348
+ metadata: {
1349
+ type: "",
1350
+ id: util.uuid(),
1351
+ created_platform: 3,
1352
+ created_platform_version: "",
1353
+ created_time_in_ms: String(Date.now()),
1354
+ created_did: ""
1355
+ },
1356
+ generate_type: "gen_video",
1357
+ abilities: {
1358
+ type: "",
1359
+ id: util.uuid(),
1360
+ gen_video: {
1361
+ type: "",
1362
+ id: util.uuid(),
1363
+ text_to_video_params: {
1364
+ type: "",
1365
+ id: util.uuid(),
1366
+ video_gen_inputs: [{
1367
+ type: "",
1368
+ id: util.uuid(),
1369
+ min_version: draftVersion,
1370
+ prompt: "", // Seedance 2.0 prompt 在 meta_list 中
1371
+ video_mode: 2,
1372
+ fps: 24,
1373
+ duration_ms: actualDuration * 1000,
1374
+ idip_meta_list: [],
1375
+ unified_edit_input: {
1376
+ type: "",
1377
+ id: util.uuid(),
1378
+ material_list: materialList,
1379
+ meta_list: metaList
1380
+ }
1381
+ }],
1382
+ video_aspect_ratio: aspectRatio,
1383
+ seed: Math.floor(Math.random() * 1000000000),
1384
+ model_req_key: model,
1385
+ priority: 0
1386
+ },
1387
+ video_task_extra: metricsExtra
1388
+ }
1389
+ },
1390
+ process_type: 1
1391
+ }]
1392
+ }),
1393
+ http_common_info: {
1394
+ aid: DEFAULT_ASSISTANT_ID,
1395
+ },
1396
+ },
1397
+ }
1398
+ );
1399
+
1400
+ const historyId = aigc_data.history_record_id;
1401
+ if (!historyId)
1402
+ throw new APIException(EX.API_IMAGE_GENERATION_FAILED, "记录ID不存在");
1403
+
1404
+ // 轮询获取结果(与普通视频相同的逻辑)
1405
+ let status = 20, failCode, item_list = [];
1406
+ let retryCount = 0;
1407
+ const maxRetries = 60;
1408
+
1409
+ await new Promise((resolve) => setTimeout(resolve, 5000));
1410
+
1411
+ logger.info(`Seedance: 开始轮询视频生成结果,历史ID: ${historyId}`);
1412
+
1413
+ while (status === 20 && retryCount < maxRetries) {
1414
+ try {
1415
+ const result = await request("post", "/mweb/v1/get_history_by_ids", refreshToken, {
1416
+ data: { history_ids: [historyId] },
1417
+ });
1418
+
1419
+ const responseStr = JSON.stringify(result);
1420
+ logger.info(`Seedance: 轮询响应摘要: ${responseStr.substring(0, 300)}...`);
1421
+
1422
+ // get_history_by_ids 返回的数据可能以 historyId 为键(如 result["8918159809292"]),
1423
+ // 也可能在 result.history_list 数组中
1424
+ let historyData = result.history_list?.[0] || result[historyId];
1425
+
1426
+ if (!historyData) {
1427
+ retryCount++;
1428
+ const waitTime = Math.min(2000 * (retryCount + 1), 30000);
1429
+ await new Promise((resolve) => setTimeout(resolve, waitTime));
1430
+ continue;
1431
+ }
1432
+ status = historyData.status;
1433
+ failCode = historyData.fail_code;
1434
+ item_list = historyData.item_list || [];
1435
+
1436
+ logger.info(`Seedance: 状态=${status}, 失败码=${failCode || '无'}`);
1437
+
1438
+ if (status === 30) {
1439
+ const error = failCode === 2038
1440
+ ? new APIException(EX.API_CONTENT_FILTERED, "内容被过滤")
1441
+ : new APIException(EX.API_IMAGE_GENERATION_FAILED, `生成失败,错误码: ${failCode}`);
1442
+ error.historyId = historyId;
1443
+ throw error;
1444
+ }
1445
+
1446
+ if (status === 20) {
1447
+ const waitTime = 2000 * Math.min(retryCount + 1, 5);
1448
+ await new Promise((resolve) => setTimeout(resolve, waitTime));
1449
+ }
1450
+
1451
+ retryCount++;
1452
+ } catch (error) {
1453
+ if (error instanceof APIException) throw error;
1454
+ logger.error(`Seedance: 轮询出错: ${error.message}`);
1455
+ retryCount++;
1456
+ await new Promise((resolve) => setTimeout(resolve, 2000 * (retryCount + 1)));
1457
+ }
1458
+ }
1459
+
1460
+ if (retryCount >= maxRetries && status === 20) {
1461
+ const error = new APIException(EX.API_IMAGE_GENERATION_FAILED, "视频生成超时");
1462
+ error.historyId = historyId;
1463
+ throw error;
1464
+ }
1465
+
1466
+ // 尝试通过 get_local_item_list 获取高质量视频下载URL
1467
+ const seedanceItemId = item_list?.[0]?.item_id
1468
+ || item_list?.[0]?.id
1469
+ || item_list?.[0]?.local_item_id
1470
+ || item_list?.[0]?.common_attr?.id;
1471
+
1472
+ if (seedanceItemId) {
1473
+ try {
1474
+ const hqVideoUrl = await fetchHighQualityVideoUrl(String(seedanceItemId), refreshToken);
1475
+ if (hqVideoUrl) {
1476
+ logger.info(`Seedance: 视频生成成功(高质量),URL: ${hqVideoUrl}`);
1477
+ return hqVideoUrl;
1478
+ }
1479
+ } catch (error) {
1480
+ logger.warn(`Seedance: 获取高质量视频URL失败,将使用预览URL作为回退: ${error.message}`);
1481
+ }
1482
+ } else {
1483
+ logger.warn(`Seedance: 未能从item_list中提取item_id,将使用预览URL。item_list[0]键: ${item_list?.[0] ? Object.keys(item_list[0]).join(', ') : '无'}`);
1484
+ }
1485
+
1486
+ // 回退:提取预览视频URL
1487
+ let videoUrl = item_list?.[0]?.video?.transcoded_video?.origin?.video_url
1488
+ || item_list?.[0]?.video?.play_url
1489
+ || item_list?.[0]?.video?.download_url
1490
+ || item_list?.[0]?.video?.url;
1491
+
1492
+ if (!videoUrl) {
1493
+ const error = new APIException(EX.API_IMAGE_GENERATION_FAILED, "未能获取视频URL");
1494
+ error.historyId = historyId;
1495
+ throw error;
1496
+ }
1497
+
1498
+ logger.info(`Seedance: 视频生成成功,URL: ${videoUrl}`);
1499
+ return videoUrl;
1500
+ }
1501
+
1502
+ /**
1503
+ * 解析 prompt 中的图片占位符并构建 meta_list
1504
+ * 支持格式: "使用 @1 图片,@2 图片做动画" -> [text, image(0), text, image(1), text]
1505
+ */
1506
+ function buildMetaListFromPrompt(prompt: string, imageCount: number): Array<{meta_type: string, text?: string, material_ref?: {material_idx: number}}> {
1507
+ const metaList: Array<{meta_type: string, text?: string, material_ref?: {material_idx: number}}> = [];
1508
+
1509
+ // 匹配 @1, @2, @图1, @图2, @image1 等格式
1510
+ const placeholderRegex = /@(?:图|image)?(\d+)/gi;
1511
+
1512
+ let lastIndex = 0;
1513
+ let match;
1514
+
1515
+ while ((match = placeholderRegex.exec(prompt)) !== null) {
1516
+ // 添加占位符前的文本
1517
+ if (match.index > lastIndex) {
1518
+ const textBefore = prompt.substring(lastIndex, match.index);
1519
+ if (textBefore.trim()) {
1520
+ metaList.push({ meta_type: "text", text: textBefore });
1521
+ }
1522
+ }
1523
+
1524
+ // 添加图片引用
1525
+ const imageIndex = parseInt(match[1]) - 1; // @1 对应 index 0
1526
+ if (imageIndex >= 0 && imageIndex < imageCount) {
1527
+ metaList.push({
1528
+ meta_type: "image",
1529
+ text: "",
1530
+ material_ref: { material_idx: imageIndex }
1531
+ });
1532
+ }
1533
+
1534
+ lastIndex = match.index + match[0].length;
1535
+ }
1536
+
1537
+ // 添加剩余的文本
1538
+ if (lastIndex < prompt.length) {
1539
+ const remainingText = prompt.substring(lastIndex);
1540
+ if (remainingText.trim()) {
1541
+ metaList.push({ meta_type: "text", text: remainingText });
1542
+ }
1543
+ }
1544
+
1545
+ // 如果没有找到任何占位符,默认使用所有图片并附加整个prompt作为文本
1546
+ if (metaList.length === 0) {
1547
+ // 先添加所有图片引用
1548
+ for (let i = 0; i < imageCount; i++) {
1549
+ if (i === 0) {
1550
+ metaList.push({ meta_type: "text", text: "使用" });
1551
+ }
1552
+ metaList.push({
1553
+ meta_type: "image",
1554
+ text: "",
1555
+ material_ref: { material_idx: i }
1556
+ });
1557
+ if (i < imageCount - 1) {
1558
+ metaList.push({ meta_type: "text", text: "和" });
1559
+ }
1560
+ }
1561
+ // 添加描述文本
1562
+ if (prompt && prompt.trim()) {
1563
+ metaList.push({ meta_type: "text", text: `图片,${prompt}` });
1564
+ } else {
1565
+ metaList.push({ meta_type: "text", text: "图片生成视频" });
1566
+ }
1567
+ }
1568
+
1569
+ return metaList;
1570
+ }
src/api/routes/chat.ts ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import _ from 'lodash';
2
+
3
+ import Request from '@/lib/request/Request.ts';
4
+ import Response from '@/lib/response/Response.ts';
5
+ import { tokenSplit } from '@/api/controllers/core.ts';
6
+ import { createCompletion, createCompletionStream } from '@/api/controllers/chat.ts';
7
+
8
+ export default {
9
+
10
+ prefix: '/v1/chat',
11
+
12
+ post: {
13
+
14
+ '/completions': async (request: Request) => {
15
+ request
16
+ .validate('body.model', v => _.isUndefined(v) || _.isString(v))
17
+ .validate('body.messages', _.isArray)
18
+ .validate('headers.authorization', _.isString)
19
+ // refresh_token切分
20
+ const tokens = tokenSplit(request.headers.authorization);
21
+ // 随机挑选一个refresh_token
22
+ const token = _.sample(tokens);
23
+ const { model, messages, stream } = request.body;
24
+ if (stream) {
25
+ const stream = await createCompletionStream(messages, token, model);
26
+ return new Response(stream, {
27
+ type: "text/event-stream"
28
+ });
29
+ }
30
+ else
31
+ return await createCompletion(messages, token, model);
32
+ }
33
+
34
+ }
35
+
36
+ }
src/api/routes/images.ts ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fs from "fs";
2
+ import _ from "lodash";
3
+
4
+ import Request from "@/lib/request/Request.ts";
5
+ import { generateImages, generateImageComposition } from "@/api/controllers/images.ts";
6
+ import { tokenSplit } from "@/api/controllers/core.ts";
7
+ import util from "@/lib/util.ts";
8
+
9
+ export default {
10
+ prefix: "/v1/images",
11
+
12
+ post: {
13
+ "/generations": async (request: Request) => {
14
+ // 检查是否使用了不支持的参数
15
+ const unsupportedParams = ['size', 'width', 'height'];
16
+ const bodyKeys = Object.keys(request.body);
17
+ const foundUnsupported = unsupportedParams.filter(param => bodyKeys.includes(param));
18
+
19
+ if (foundUnsupported.length > 0) {
20
+ throw new Error(`不支持的参数: ${foundUnsupported.join(', ')}。请使用 ratio 和 resolution 参数控制图像尺寸。`);
21
+ }
22
+
23
+ request
24
+ .validate("body.model", v => _.isUndefined(v) || _.isString(v))
25
+ .validate("body.prompt", _.isString)
26
+ .validate("body.negative_prompt", v => _.isUndefined(v) || _.isString(v))
27
+ .validate("body.ratio", v => _.isUndefined(v) || _.isString(v))
28
+ .validate("body.resolution", v => _.isUndefined(v) || _.isString(v))
29
+ .validate("body.intelligent_ratio", v => _.isUndefined(v) || _.isBoolean(v))
30
+ .validate("body.sample_strength", v => _.isUndefined(v) || _.isFinite(v))
31
+ .validate("body.response_format", v => _.isUndefined(v) || _.isString(v))
32
+ .validate("headers.authorization", _.isString);
33
+
34
+ // refresh_token切分
35
+ const tokens = tokenSplit(request.headers.authorization);
36
+ // 随机挑选一个refresh_token
37
+ const token = _.sample(tokens);
38
+ const {
39
+ model,
40
+ prompt,
41
+ negative_prompt: negativePrompt,
42
+ ratio,
43
+ resolution,
44
+ intelligent_ratio: intelligentRatio,
45
+ sample_strength: sampleStrength,
46
+ response_format,
47
+ } = request.body;
48
+
49
+ const responseFormat = _.defaultTo(response_format, "url");
50
+ const imageUrls = await generateImages(model, prompt, {
51
+ ratio,
52
+ resolution,
53
+ sampleStrength,
54
+ negativePrompt,
55
+ intelligentRatio,
56
+ }, token);
57
+
58
+ let data = [];
59
+ if (responseFormat == "b64_json") {
60
+ data = (
61
+ await Promise.all(imageUrls.map((url) => util.fetchFileBASE64(url)))
62
+ ).map((b64) => ({ b64_json: b64 }));
63
+ } else {
64
+ data = imageUrls.map((url) => ({
65
+ url,
66
+ }));
67
+ }
68
+ return {
69
+ created: util.unixTimestamp(),
70
+ data,
71
+ };
72
+ },
73
+
74
+ // 图片合成路由(图生图)
75
+ "/compositions": async (request: Request) => {
76
+ // 检查是否使用了不支持的参数
77
+ const unsupportedParams = ['size', 'width', 'height'];
78
+ const bodyKeys = Object.keys(request.body);
79
+ const foundUnsupported = unsupportedParams.filter(param => bodyKeys.includes(param));
80
+
81
+ if (foundUnsupported.length > 0) {
82
+ throw new Error(`不支持的参数: ${foundUnsupported.join(', ')}。请使用 ratio 和 resolution 参数控制图像尺寸。`);
83
+ }
84
+
85
+ const contentType = request.headers['content-type'] || '';
86
+ const isMultiPart = contentType.startsWith('multipart/form-data');
87
+
88
+ if (isMultiPart) {
89
+ request
90
+ .validate("body.model", v => _.isUndefined(v) || _.isString(v))
91
+ .validate("body.prompt", _.isString)
92
+ .validate("body.negative_prompt", v => _.isUndefined(v) || _.isString(v))
93
+ .validate("body.ratio", v => _.isUndefined(v) || _.isString(v))
94
+ .validate("body.resolution", v => _.isUndefined(v) || _.isString(v))
95
+ .validate("body.intelligent_ratio", v => _.isUndefined(v) || (typeof v === 'string' && (v === 'true' || v === 'false')) || _.isBoolean(v))
96
+ .validate("body.sample_strength", v => _.isUndefined(v) || (typeof v === 'string' && !isNaN(parseFloat(v))) || _.isFinite(v))
97
+ .validate("body.response_format", v => _.isUndefined(v) || _.isString(v))
98
+ .validate("headers.authorization", _.isString);
99
+ } else {
100
+ request
101
+ .validate("body.model", v => _.isUndefined(v) || _.isString(v))
102
+ .validate("body.prompt", _.isString)
103
+ .validate("body.images", _.isArray)
104
+ .validate("body.negative_prompt", v => _.isUndefined(v) || _.isString(v))
105
+ .validate("body.ratio", v => _.isUndefined(v) || _.isString(v))
106
+ .validate("body.resolution", v => _.isUndefined(v) || _.isString(v))
107
+ .validate("body.intelligent_ratio", v => _.isUndefined(v) || _.isBoolean(v))
108
+ .validate("body.sample_strength", v => _.isUndefined(v) || _.isFinite(v))
109
+ .validate("body.response_format", v => _.isUndefined(v) || _.isString(v))
110
+ .validate("headers.authorization", _.isString);
111
+ }
112
+
113
+ let images: (string | Buffer)[] = [];
114
+ if (isMultiPart) {
115
+ const files = request.files?.images;
116
+ if (!files) {
117
+ throw new Error("在form-data��缺少 'images' 字段");
118
+ }
119
+ const imageFiles = Array.isArray(files) ? files : [files];
120
+ if (imageFiles.length === 0) {
121
+ throw new Error("至少需要提供1张输入图片");
122
+ }
123
+ if (imageFiles.length > 10) {
124
+ throw new Error("最多支持10张输入图片");
125
+ }
126
+ images = imageFiles.map(file => fs.readFileSync(file.filepath));
127
+ } else {
128
+ const bodyImages = request.body.images;
129
+ if (!bodyImages || bodyImages.length === 0) {
130
+ throw new Error("至少需要提供1张输入图片");
131
+ }
132
+ if (bodyImages.length > 10) {
133
+ throw new Error("最多支持10张输入图片");
134
+ }
135
+ bodyImages.forEach((image: any, index: number) => {
136
+ if (!_.isString(image) && !_.isObject(image)) {
137
+ throw new Error(`图片 ${index + 1} 格式不正确:应为URL字符串或包含url字段的对象`);
138
+ }
139
+ if (_.isObject(image) && !image.url) {
140
+ throw new Error(`图片 ${index + 1} 缺少url字段`);
141
+ }
142
+ });
143
+ images = bodyImages.map((image: any) => _.isString(image) ? image : image.url);
144
+ }
145
+
146
+ // refresh_token切分
147
+ const tokens = tokenSplit(request.headers.authorization);
148
+ // 随机挑选一个refresh_token
149
+ const token = _.sample(tokens);
150
+
151
+ const {
152
+ model,
153
+ prompt,
154
+ negative_prompt: negativePrompt,
155
+ ratio,
156
+ resolution,
157
+ intelligent_ratio: intelligentRatio,
158
+ sample_strength: sampleStrength,
159
+ response_format,
160
+ } = request.body;
161
+
162
+ // 如果是 multipart/form-data,需要将字符串转换为数字和布尔值
163
+ const finalSampleStrength = isMultiPart && typeof sampleStrength === 'string'
164
+ ? parseFloat(sampleStrength)
165
+ : sampleStrength;
166
+
167
+ const finalIntelligentRatio = isMultiPart && typeof intelligentRatio === 'string'
168
+ ? intelligentRatio === 'true'
169
+ : intelligentRatio;
170
+
171
+ const responseFormat = _.defaultTo(response_format, "url");
172
+ const resultUrls = await generateImageComposition(model, prompt, images, {
173
+ ratio,
174
+ resolution,
175
+ sampleStrength: finalSampleStrength,
176
+ negativePrompt,
177
+ intelligentRatio: finalIntelligentRatio,
178
+ }, token);
179
+
180
+ let data = [];
181
+ if (responseFormat == "b64_json") {
182
+ data = (
183
+ await Promise.all(resultUrls.map((url) => util.fetchFileBASE64(url)))
184
+ ).map((b64) => ({ b64_json: b64 }));
185
+ } else {
186
+ data = resultUrls.map((url) => ({
187
+ url,
188
+ }));
189
+ }
190
+
191
+ return {
192
+ created: util.unixTimestamp(),
193
+ data,
194
+ input_images: images.length,
195
+ composition_type: "multi_image_synthesis",
196
+ };
197
+ },
198
+ },
199
+ };
src/api/routes/index.ts ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fs from 'fs-extra';
2
+
3
+ import Response from '@/lib/response/Response.ts';
4
+ import images from "./images.ts";
5
+ import chat from "./chat.ts";
6
+ import ping from "./ping.ts";
7
+ import token from './token.js';
8
+ import models from './models.ts';
9
+ import videos from './videos.ts';
10
+ import video from './video.ts';
11
+
12
+ export default [
13
+ {
14
+ get: {
15
+ '/': async () => {
16
+ const content = await fs.readFile('public/welcome.html');
17
+ return new Response(content, {
18
+ type: 'html',
19
+ headers: {
20
+ Expires: '-1'
21
+ }
22
+ });
23
+ }
24
+ }
25
+ },
26
+ images,
27
+ chat,
28
+ ping,
29
+ token,
30
+ models,
31
+ videos,
32
+ video
33
+ ];
src/api/routes/models.ts ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import _ from 'lodash';
2
+
3
+ export default {
4
+
5
+ prefix: '/v1',
6
+
7
+ get: {
8
+ '/models': async () => {
9
+ return {
10
+ "data": [
11
+ {
12
+ "id": "jimeng",
13
+ "object": "model",
14
+ "owned_by": "jimeng-free-api"
15
+ },
16
+ {
17
+ "id": "jimeng-5.0-preview",
18
+ "object": "model",
19
+ "owned_by": "jimeng-free-api",
20
+ "description": "即梦AI图像生成模型 5.0 Preview 版本(最新)"
21
+ },
22
+ {
23
+ "id": "jimeng-4.6",
24
+ "object": "model",
25
+ "owned_by": "jimeng-free-api",
26
+ "description": "即梦AI图像生成模型 4.6 版本(最新)"
27
+ },
28
+ {
29
+ "id": "jimeng-4.5",
30
+ "object": "model",
31
+ "owned_by": "jimeng-free-api",
32
+ "description": "即梦AI图像生成模型 4.5 版本"
33
+ },
34
+ {
35
+ "id": "jimeng-4.1",
36
+ "object": "model",
37
+ "owned_by": "jimeng-free-api",
38
+ "description": "即梦AI图像生成模型 4.1 版本"
39
+ },
40
+ {
41
+ "id": "jimeng-4.0",
42
+ "object": "model",
43
+ "owned_by": "jimeng-free-api",
44
+ "description": "即梦AI图像生成模型 4.0 版本"
45
+ },
46
+ {
47
+ "id": "jimeng-3.1",
48
+ "object": "model",
49
+ "owned_by": "jimeng-free-api",
50
+ "description": "即梦AI图像生成模型 3.1 版本"
51
+ },
52
+ {
53
+ "id": "jimeng-3.0",
54
+ "object": "model",
55
+ "owned_by": "jimeng-free-api",
56
+ "description": "即梦AI图像生成模型 3.0 版本"
57
+ },
58
+ {
59
+ "id": "jimeng-2.1",
60
+ "object": "model",
61
+ "owned_by": "jimeng-free-api",
62
+ "description": "即梦AI图像生成模型 2.1 版本"
63
+ },
64
+ {
65
+ "id": "jimeng-2.0-pro",
66
+ "object": "model",
67
+ "owned_by": "jimeng-free-api",
68
+ "description": "即梦AI图像生成模型 2.0 专业版"
69
+ },
70
+ {
71
+ "id": "jimeng-2.0",
72
+ "object": "model",
73
+ "owned_by": "jimeng-free-api",
74
+ "description": "即梦AI图像生成模型 2.0 版本"
75
+ },
76
+ {
77
+ "id": "jimeng-1.4",
78
+ "object": "model",
79
+ "owned_by": "jimeng-free-api",
80
+ "description": "即梦AI图像生成模型 1.4 版本"
81
+ },
82
+ {
83
+ "id": "jimeng-xl-pro",
84
+ "object": "model",
85
+ "owned_by": "jimeng-free-api",
86
+ "description": "即梦AI图像生成模型 XL Pro 版本"
87
+ },
88
+ {
89
+ "id": "jimeng-video-3.5-pro",
90
+ "object": "model",
91
+ "owned_by": "jimeng-free-api",
92
+ "description": "即梦AI视频生成模型 3.5 专业版"
93
+ },
94
+ {
95
+ "id": "jimeng-video-3.0",
96
+ "object": "model",
97
+ "owned_by": "jimeng-free-api",
98
+ "description": "即梦AI视频生成模型 3.0 版本"
99
+ },
100
+ {
101
+ "id": "jimeng-video-3.0-pro",
102
+ "object": "model",
103
+ "owned_by": "jimeng-free-api",
104
+ "description": "即梦AI视频生成模型 3.0 专业版"
105
+ },
106
+ {
107
+ "id": "jimeng-video-2.0",
108
+ "object": "model",
109
+ "owned_by": "jimeng-free-api",
110
+ "description": "即梦AI视频生成模型 2.0 版本"
111
+ },
112
+ {
113
+ "id": "jimeng-video-2.0-pro",
114
+ "object": "model",
115
+ "owned_by": "jimeng-free-api",
116
+ "description": "即梦AI视频生成模型 2.0 专业版"
117
+ },
118
+ {
119
+ "id": "seedance-2.0",
120
+ "object": "model",
121
+ "owned_by": "jimeng-free-api",
122
+ "description": "Seedance 2.0 多图智能视频生成模型(支持多张图片混合生成视频)"
123
+ },
124
+ {
125
+ "id": "seedance-2.0-pro",
126
+ "object": "model",
127
+ "owned_by": "jimeng-free-api",
128
+ "description": "Seedance 2.0 Pro 多图智能视频生成模型(支持多张图片混合生成视频,专业版)"
129
+ }
130
+ ]
131
+ };
132
+ }
133
+
134
+ }
135
+ }
src/api/routes/ping.ts ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ export default {
2
+ prefix: '/ping',
3
+ get: {
4
+ '': async () => "pong"
5
+ }
6
+ }
src/api/routes/token.ts ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import _ from 'lodash';
2
+
3
+ import Request from '@/lib/request/Request.ts';
4
+ import Response from '@/lib/response/Response.ts';
5
+ import { getTokenLiveStatus, getCredit, tokenSplit } from '@/api/controllers/core.ts';
6
+ import logger from '@/lib/logger.ts';
7
+
8
+ export default {
9
+
10
+ prefix: '/token',
11
+
12
+ post: {
13
+
14
+ '/check': async (request: Request) => {
15
+ request
16
+ .validate('body.token', _.isString)
17
+ const live = await getTokenLiveStatus(request.body.token);
18
+ return {
19
+ live
20
+ }
21
+ },
22
+
23
+ '/points': async (request: Request) => {
24
+ request
25
+ .validate('headers.authorization', _.isString)
26
+ // refresh_token切分
27
+ const tokens = tokenSplit(request.headers.authorization);
28
+ const points = await Promise.all(tokens.map(async (token) => {
29
+ return {
30
+ token,
31
+ points: await getCredit(token)
32
+ }
33
+ }))
34
+ return points;
35
+ }
36
+
37
+ }
38
+
39
+ }
src/api/routes/video.ts ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ import videos from './videos.ts';
2
+
3
+ export default {
4
+ ...videos,
5
+ prefix: '/v1/video'
6
+ };
src/api/routes/videos.ts ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import _ from 'lodash';
2
+
3
+ import Request from '@/lib/request/Request.ts';
4
+ import Response from '@/lib/response/Response.ts';
5
+ import { tokenSplit } from '@/api/controllers/core.ts';
6
+ import { generateVideo, generateSeedanceVideo, isSeedanceModel, DEFAULT_MODEL } from '@/api/controllers/videos.ts';
7
+ import util from '@/lib/util.ts';
8
+
9
+ export default {
10
+
11
+ prefix: '/v1/videos',
12
+
13
+ post: {
14
+
15
+ '/generations': async (request: Request) => {
16
+ // 检查是否使用了不支持的参数
17
+ const unsupportedParams = ['size', 'width', 'height'];
18
+ const bodyKeys = Object.keys(request.body);
19
+ const foundUnsupported = unsupportedParams.filter(param => bodyKeys.includes(param));
20
+
21
+ if (foundUnsupported.length > 0) {
22
+ throw new Error(`不支持的参数: ${foundUnsupported.join(', ')}。请使用 ratio 和 resolution 参数控制视频尺寸。`);
23
+ }
24
+
25
+ const contentType = request.headers['content-type'] || '';
26
+ const isMultiPart = contentType.startsWith('multipart/form-data');
27
+
28
+ request
29
+ .validate('body.model', v => _.isUndefined(v) || _.isString(v))
30
+ .validate('body.prompt', v => _.isUndefined(v) || _.isString(v))
31
+ .validate('body.ratio', v => _.isUndefined(v) || _.isString(v))
32
+ .validate('body.resolution', v => _.isUndefined(v) || _.isString(v))
33
+ .validate('body.duration', v => {
34
+ if (_.isUndefined(v)) return true;
35
+ // 对于 multipart/form-data,允许字符串类型的数字
36
+ if (isMultiPart && typeof v === 'string') {
37
+ const num = parseInt(v);
38
+ // Seedance 支持 4 秒,普通视频支持 5 或 10 秒
39
+ return num === 4 || num === 5 || num === 10;
40
+ }
41
+ // 对于 JSON,要求数字类型
42
+ // Seedance 支持 4 秒,普通视频支持 5 或 10 秒
43
+ return _.isFinite(v) && (v === 4 || v === 5 || v === 10);
44
+ })
45
+ .validate('body.file_paths', v => _.isUndefined(v) || _.isArray(v))
46
+ .validate('body.filePaths', v => _.isUndefined(v) || _.isArray(v))
47
+ .validate('body.response_format', v => _.isUndefined(v) || _.isString(v))
48
+ .validate('headers.authorization', _.isString);
49
+
50
+ // refresh_token切分
51
+ const tokens = tokenSplit(request.headers.authorization);
52
+ // 随机挑选一个refresh_token
53
+ const token = _.sample(tokens);
54
+
55
+ const {
56
+ model = DEFAULT_MODEL,
57
+ prompt,
58
+ ratio = "1:1",
59
+ resolution = "720p",
60
+ duration = 5,
61
+ file_paths = [],
62
+ filePaths = [],
63
+ response_format = "url"
64
+ } = request.body;
65
+
66
+ // 如果是 multipart/form-data,需要将字符串转换为数字
67
+ const finalDuration = isMultiPart && typeof duration === 'string'
68
+ ? parseInt(duration)
69
+ : duration;
70
+
71
+ // 兼容两种参数名格式:file_paths 和 filePaths
72
+ const finalFilePaths = filePaths.length > 0 ? filePaths : file_paths;
73
+
74
+ // 根据模型类型选择不同的生成函数
75
+ let videoUrl: string;
76
+ if (isSeedanceModel(model)) {
77
+ // Seedance 2.0 多图智能视频生成
78
+ // Seedance 默认时长为 4 秒,默认比例为 4:3
79
+ const seedanceDuration = finalDuration === 5 ? 4 : finalDuration; // 如果是默认的5秒,转为4秒
80
+ const seedanceRatio = ratio === "1:1" ? "4:3" : ratio; // 如果是默认的1:1,转为4:3
81
+
82
+ videoUrl = await generateSeedanceVideo(
83
+ model,
84
+ prompt,
85
+ {
86
+ ratio: seedanceRatio,
87
+ resolution,
88
+ duration: seedanceDuration,
89
+ filePaths: finalFilePaths,
90
+ files: request.files,
91
+ },
92
+ token
93
+ );
94
+ } else {
95
+ // 普通视频生成
96
+ videoUrl = await generateVideo(
97
+ model,
98
+ prompt,
99
+ {
100
+ ratio,
101
+ resolution,
102
+ duration: finalDuration,
103
+ filePaths: finalFilePaths,
104
+ files: request.files,
105
+ },
106
+ token
107
+ );
108
+ }
109
+
110
+ // 根据response_format返回不同格式的结果
111
+ if (response_format === "b64_json") {
112
+ // 获取视频内容并转换为BASE64
113
+ const videoBase64 = await util.fetchFileBASE64(videoUrl);
114
+ return {
115
+ created: util.unixTimestamp(),
116
+ data: [{
117
+ b64_json: videoBase64,
118
+ revised_prompt: prompt
119
+ }]
120
+ };
121
+ } else {
122
+ // 默认返回URL
123
+ return {
124
+ created: util.unixTimestamp(),
125
+ data: [{
126
+ url: videoUrl,
127
+ revised_prompt: prompt
128
+ }]
129
+ };
130
+ }
131
+ }
132
+
133
+ }
134
+
135
+ }
src/daemon.ts ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * 守护进程
3
+ */
4
+
5
+ import process from 'process';
6
+ import path from 'path';
7
+ import { spawn } from 'child_process';
8
+
9
+ import fs from 'fs-extra';
10
+ import { format as dateFormat } from 'date-fns';
11
+ import 'colors';
12
+
13
+ const CRASH_RESTART_LIMIT = 600; //进程崩溃重启次数限制
14
+ const CRASH_RESTART_DELAY = 5000; //进程崩溃重启延迟
15
+ const LOG_PATH = path.resolve("./logs/daemon.log"); //守护进程日志路径
16
+ let crashCount = 0; //进程崩溃次数
17
+ let currentProcess; //当前运行进程
18
+
19
+ /**
20
+ * 写入守护进程日志
21
+ */
22
+ function daemonLog(value, color?: string) {
23
+ try {
24
+ const head = `[daemon][${dateFormat(new Date(), "yyyy-MM-dd HH:mm:ss.SSS")}] `;
25
+ value = head + value;
26
+ console.log(color ? value[color] : value);
27
+ fs.ensureDirSync(path.dirname(LOG_PATH));
28
+ fs.appendFileSync(LOG_PATH, value + "\n");
29
+ }
30
+ catch(err) {
31
+ console.error("daemon log write error:", err);
32
+ }
33
+ }
34
+
35
+ daemonLog(`daemon pid: ${process.pid}`);
36
+
37
+ function createProcess() {
38
+ const childProcess = spawn("node", ["index.js", ...process.argv.slice(2)]); //启动子进程
39
+ childProcess.stdout.pipe(process.stdout, { end: false }); //将子进程输出管道到当前进程输出
40
+ childProcess.stderr.pipe(process.stderr, { end: false }); //将子进程错误输出管道到当前进程输出
41
+ currentProcess = childProcess; //更新当前进程
42
+ daemonLog(`process(${childProcess.pid}) has started`);
43
+ childProcess.on("error", err => daemonLog(`process(${childProcess.pid}) error: ${err.stack}`, "red"));
44
+ childProcess.on("close", code => {
45
+ if(code === 0) //进程正常退出
46
+ daemonLog(`process(${childProcess.pid}) has exited`);
47
+ else if(code === 2) //进程已被杀死
48
+ daemonLog(`process(${childProcess.pid}) has been killed!`, "bgYellow");
49
+ else if(code === 3) { //进程主动重启
50
+ daemonLog(`process(${childProcess.pid}) has restart`, "yellow");
51
+ createProcess(); //重新创建进程
52
+ }
53
+ else { //进程发生崩溃
54
+ if(crashCount++ < CRASH_RESTART_LIMIT) { //进程崩溃次数未达重启次数上限前尝试重启
55
+ daemonLog(`process(${childProcess.pid}) has crashed! delay ${CRASH_RESTART_DELAY}ms try restarting...(${crashCount})`, "bgRed");
56
+ setTimeout(() => createProcess(), CRASH_RESTART_DELAY); //延迟指定时长后再重启
57
+ }
58
+ else //进程已崩溃,且无法重启
59
+ daemonLog(`process(${childProcess.pid}) has crashed! unable to restart`, "bgRed");
60
+ }
61
+ }); //子进程关闭监听
62
+ }
63
+
64
+ process.on("exit", code => {
65
+ if(code === 0)
66
+ daemonLog("daemon process exited");
67
+ else if(code === 2)
68
+ daemonLog("daemon process has been killed!");
69
+ }); //守护进程退出事件
70
+
71
+ process.on("SIGTERM", () => {
72
+ daemonLog("received kill signal", "yellow");
73
+ currentProcess && currentProcess.kill("SIGINT");
74
+ process.exit(2);
75
+ }); //kill退出守护进程
76
+
77
+ process.on("SIGINT", () => {
78
+ currentProcess && currentProcess.kill("SIGINT");
79
+ process.exit(0);
80
+ }); //主动退出守护进程
81
+
82
+ createProcess(); //创建进程
src/index.ts ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use strict";
2
+
3
+ import environment from "@/lib/environment.ts";
4
+ import config from "@/lib/config.ts";
5
+ import "@/lib/initialize.ts";
6
+ import server from "@/lib/server.ts";
7
+ import routes from "@/api/routes/index.ts";
8
+ import logger from "@/lib/logger.ts";
9
+
10
+ const startupTime = performance.now();
11
+
12
+ (async () => {
13
+ logger.header();
14
+
15
+ logger.info("<<<< jimeng free server >>>>");
16
+ logger.info("Version:", environment.package.version);
17
+ logger.info("Process id:", process.pid);
18
+ logger.info("Environment:", environment.env);
19
+ logger.info("Service name:", config.service.name);
20
+
21
+ server.attachRoutes(routes);
22
+ await server.listen();
23
+
24
+ config.service.bindAddress &&
25
+ logger.success("Service bind address:", config.service.bindAddress);
26
+ })()
27
+ .then(() =>
28
+ logger.success(
29
+ `Service startup completed (${Math.floor(performance.now() - startupTime)}ms)`
30
+ )
31
+ )
32
+ .catch((err) => console.error(err));
src/lib/config.ts ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import serviceConfig from "./configs/service-config.ts";
2
+ import systemConfig from "./configs/system-config.ts";
3
+
4
+ class Config {
5
+
6
+ /** 服务配置 */
7
+ service = serviceConfig;
8
+
9
+ /** 系统配置 */
10
+ system = systemConfig;
11
+
12
+ }
13
+
14
+ export default new Config();
src/lib/configs/model-config.ts ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * 模型配置文件
3
+ * 定义不同模型的特定参数和配置
4
+ */
5
+
6
+ export interface ModelConfig {
7
+ // 模型内部名称
8
+ internalModel: string;
9
+ // draft版本
10
+ draftVersion: string;
11
+ // 支持的功能
12
+ features: {
13
+ // 是否支持多图生成
14
+ multiImage: boolean;
15
+ // 是否支持图生图
16
+ imageToImage: boolean;
17
+ // 是否支持视频生成
18
+ videoGeneration: boolean;
19
+ };
20
+ // 默认参数
21
+ defaultParams: {
22
+ // 默认宽度
23
+ width: number;
24
+ // 默认高度
25
+ height: number;
26
+ // 支持的分辨率列表
27
+ resolutions: Array<{ width: number; height: number }>;
28
+ // 采样强度范围
29
+ sampleStrengthRange: [number, number];
30
+ };
31
+ // 特殊配置
32
+ specialConfig?: {
33
+ // 是否需要特定的头部信息
34
+ specialHeaders?: Record<string, string>;
35
+ // 是否有特殊的参数要求
36
+ extraParams?: Record<string, any>;
37
+ };
38
+ }
39
+
40
+ // 模型配置映射
41
+ export const MODEL_CONFIGS: Record<string, ModelConfig> = {
42
+ "jimeng-5.0-preview": {
43
+ internalModel: "high_aes_general_v50",
44
+ draftVersion: "3.3.9",
45
+ features: {
46
+ multiImage: true,
47
+ imageToImage: true,
48
+ videoGeneration: false,
49
+ },
50
+ defaultParams: {
51
+ width: 2048,
52
+ height: 2048,
53
+ resolutions: [
54
+ { width: 1024, height: 1024 },
55
+ { width: 768, height: 1024 },
56
+ { width: 1024, height: 768 },
57
+ { width: 1024, height: 576 },
58
+ { width: 576, height: 1024 },
59
+ { width: 1024, height: 682 },
60
+ { width: 682, height: 1024 },
61
+ { width: 1195, height: 512 },
62
+ { width: 2048, height: 2048 },
63
+ { width: 2304, height: 1728 },
64
+ { width: 1728, height: 2304 },
65
+ { width: 2560, height: 1440 },
66
+ { width: 1440, height: 2560 },
67
+ { width: 2496, height: 1664 },
68
+ { width: 1664, height: 2496 },
69
+ { width: 3024, height: 1296 },
70
+ ],
71
+ sampleStrengthRange: [0.1, 1.0],
72
+ },
73
+ },
74
+ "jimeng-4.6": {
75
+ internalModel: "high_aes_general_v42",
76
+ draftVersion: "3.3.9",
77
+ features: {
78
+ multiImage: true,
79
+ imageToImage: true,
80
+ videoGeneration: false,
81
+ },
82
+ defaultParams: {
83
+ width: 2048,
84
+ height: 2048,
85
+ resolutions: [
86
+ { width: 1024, height: 1024 },
87
+ { width: 768, height: 1024 },
88
+ { width: 1024, height: 768 },
89
+ { width: 1024, height: 576 },
90
+ { width: 576, height: 1024 },
91
+ { width: 1024, height: 682 },
92
+ { width: 682, height: 1024 },
93
+ { width: 1195, height: 512 },
94
+ { width: 2048, height: 2048 },
95
+ { width: 2304, height: 1728 },
96
+ { width: 1728, height: 2304 },
97
+ { width: 2560, height: 1440 },
98
+ { width: 1440, height: 2560 },
99
+ { width: 2496, height: 1664 },
100
+ { width: 1664, height: 2496 },
101
+ { width: 3024, height: 1296 },
102
+ ],
103
+ sampleStrengthRange: [0.1, 1.0],
104
+ },
105
+ },
106
+ "jimeng-video-3.5-pro": {
107
+ internalModel: "dreamina_ic_generate_video_model_vgfm_3.5_pro",
108
+ draftVersion: "3.3.4",
109
+ features: {
110
+ multiImage: false,
111
+ imageToImage: true,
112
+ videoGeneration: true,
113
+ },
114
+ defaultParams: {
115
+ width: 1280,
116
+ height: 720,
117
+ resolutions: [
118
+ { width: 1280, height: 720 },
119
+ { width: 720, height: 1280 },
120
+ { width: 1080, height: 1080 },
121
+ { width: 1920, height: 1080 },
122
+ { width: 1080, height: 1920 },
123
+ ],
124
+ sampleStrengthRange: [0.1, 1.0],
125
+ },
126
+ },
127
+ "jimeng-4.5": {
128
+ internalModel: "high_aes_general_v40l",
129
+ draftVersion: "3.3.4",
130
+ features: {
131
+ multiImage: true,
132
+ imageToImage: true,
133
+ videoGeneration: false,
134
+ },
135
+ defaultParams: {
136
+ width: 2048,
137
+ height: 2048,
138
+ resolutions: [
139
+ { width: 1024, height: 1024 },
140
+ { width: 768, height: 1024 },
141
+ { width: 1024, height: 768 },
142
+ { width: 1024, height: 576 },
143
+ { width: 576, height: 1024 },
144
+ { width: 1024, height: 682 },
145
+ { width: 682, height: 1024 },
146
+ { width: 1195, height: 512 },
147
+ { width: 2048, height: 2048 },
148
+ { width: 2304, height: 1728 },
149
+ { width: 1728, height: 2304 },
150
+ { width: 2560, height: 1440 },
151
+ { width: 1440, height: 2560 },
152
+ { width: 2496, height: 1664 },
153
+ { width: 1664, height: 2496 },
154
+ { width: 3024, height: 1296 },
155
+ ],
156
+ sampleStrengthRange: [0.1, 1.0],
157
+ },
158
+ },
159
+ "jimeng-4.1": {
160
+ internalModel: "high_aes_general_v41",
161
+ draftVersion: "3.3.4",
162
+ features: {
163
+ multiImage: true,
164
+ imageToImage: true,
165
+ videoGeneration: false,
166
+ },
167
+ defaultParams: {
168
+ width: 2048,
169
+ height: 2048,
170
+ resolutions: [
171
+ { width: 1024, height: 1024 },
172
+ { width: 768, height: 1024 },
173
+ { width: 1024, height: 768 },
174
+ { width: 1024, height: 576 },
175
+ { width: 576, height: 1024 },
176
+ { width: 1024, height: 682 },
177
+ { width: 682, height: 1024 },
178
+ { width: 1195, height: 512 },
179
+ { width: 2048, height: 2048 },
180
+ { width: 2304, height: 1728 },
181
+ { width: 1728, height: 2304 },
182
+ { width: 2560, height: 1440 },
183
+ { width: 1440, height: 2560 },
184
+ { width: 2496, height: 1664 },
185
+ { width: 1664, height: 2496 },
186
+ { width: 3024, height: 1296 },
187
+ ],
188
+ sampleStrengthRange: [0.1, 1.0],
189
+ },
190
+ },
191
+ "jimeng-4.0": {
192
+ internalModel: "high_aes_general_v40",
193
+ draftVersion: "3.3.4",
194
+ features: {
195
+ multiImage: true,
196
+ imageToImage: true,
197
+ videoGeneration: false,
198
+ },
199
+ defaultParams: {
200
+ width: 2048,
201
+ height: 2048,
202
+ resolutions: [
203
+ { width: 1024, height: 1024 },
204
+ { width: 768, height: 1024 },
205
+ { width: 1024, height: 768 },
206
+ { width: 1024, height: 576 },
207
+ { width: 576, height: 1024 },
208
+ { width: 1024, height: 682 },
209
+ { width: 682, height: 1024 },
210
+ { width: 1195, height: 512 },
211
+ { width: 2048, height: 2048 },
212
+ { width: 2304, height: 1728 },
213
+ { width: 1728, height: 2304 },
214
+ { width: 2560, height: 1440 },
215
+ { width: 1440, height: 2560 },
216
+ { width: 2496, height: 1664 },
217
+ { width: 1664, height: 2496 },
218
+ { width: 3024, height: 1296 },
219
+ ],
220
+ sampleStrengthRange: [0.1, 1.0],
221
+ },
222
+ },
223
+ "jimeng-3.1": {
224
+ internalModel: "high_aes_general_v30l_art_fangzhou:general_v3.0_18b",
225
+ draftVersion: "3.0.2",
226
+ features: {
227
+ multiImage: false,
228
+ imageToImage: true,
229
+ videoGeneration: false,
230
+ },
231
+ defaultParams: {
232
+ width: 1024,
233
+ height: 1024,
234
+ resolutions: [
235
+ { width: 512, height: 512 },
236
+ { width: 768, height: 768 },
237
+ { width: 1024, height: 1024 },
238
+ ],
239
+ sampleStrengthRange: [0.1, 0.8],
240
+ },
241
+ },
242
+ "jimeng-3.0": {
243
+ internalModel: "high_aes_general_v30l:general_v3.0_18b",
244
+ draftVersion: "3.0.2",
245
+ features: {
246
+ multiImage: false,
247
+ imageToImage: true,
248
+ videoGeneration: false,
249
+ },
250
+ defaultParams: {
251
+ width: 1024,
252
+ height: 1024,
253
+ resolutions: [
254
+ { width: 512, height: 512 },
255
+ { width: 768, height: 768 },
256
+ { width: 1024, height: 1024 },
257
+ ],
258
+ sampleStrengthRange: [0.1, 0.8],
259
+ },
260
+ },
261
+ "jimeng-2.1": {
262
+ internalModel: "high_aes_general_v21_L:general_v2.1_L",
263
+ draftVersion: "3.0.2",
264
+ features: {
265
+ multiImage: false,
266
+ imageToImage: true,
267
+ videoGeneration: false,
268
+ },
269
+ defaultParams: {
270
+ width: 512,
271
+ height: 512,
272
+ resolutions: [
273
+ { width: 512, height: 512 },
274
+ { width: 768, height: 768 },
275
+ ],
276
+ sampleStrengthRange: [0.1, 0.7],
277
+ },
278
+ },
279
+ "jimeng-2.0-pro": {
280
+ internalModel: "high_aes_general_v20_L:general_v2.0_L",
281
+ draftVersion: "3.0.2",
282
+ features: {
283
+ multiImage: false,
284
+ imageToImage: true,
285
+ videoGeneration: false,
286
+ },
287
+ defaultParams: {
288
+ width: 512,
289
+ height: 512,
290
+ resolutions: [
291
+ { width: 512, height: 512 },
292
+ { width: 768, height: 768 },
293
+ ],
294
+ sampleStrengthRange: [0.1, 0.7],
295
+ },
296
+ },
297
+ "jimeng-2.0": {
298
+ internalModel: "high_aes_general_v20",
299
+ draftVersion: "3.0.2",
300
+ features: {
301
+ multiImage: false,
302
+ imageToImage: true,
303
+ videoGeneration: false,
304
+ },
305
+ defaultParams: {
306
+ width: 512,
307
+ height: 512,
308
+ resolutions: [
309
+ { width: 512, height: 512 },
310
+ { width: 768, height: 768 },
311
+ ],
312
+ sampleStrengthRange: [0.1, 0.7],
313
+ },
314
+ },
315
+ "jimeng-1.4": {
316
+ internalModel: "high_aes_general_v14:general_v1.4",
317
+ draftVersion: "3.0.2",
318
+ features: {
319
+ multiImage: false,
320
+ imageToImage: true,
321
+ videoGeneration: false,
322
+ },
323
+ defaultParams: {
324
+ width: 512,
325
+ height: 512,
326
+ resolutions: [
327
+ { width: 512, height: 512 },
328
+ { width: 768, height: 768 },
329
+ ],
330
+ sampleStrengthRange: [0.1, 0.6],
331
+ },
332
+ },
333
+ "jimeng-xl-pro": {
334
+ internalModel: "text2img_xl_sft",
335
+ draftVersion: "3.0.2",
336
+ features: {
337
+ multiImage: false,
338
+ imageToImage: true,
339
+ videoGeneration: false,
340
+ },
341
+ defaultParams: {
342
+ width: 1024,
343
+ height: 1024,
344
+ resolutions: [
345
+ { width: 1024, height: 1024 },
346
+ { width: 1280, height: 720 },
347
+ { width: 720, height: 1280 },
348
+ ],
349
+ sampleStrengthRange: [0.1, 0.8],
350
+ },
351
+ },
352
+ };
353
+
354
+ // 获取模型配置
355
+ export function getModelConfig(modelName: string): ModelConfig {
356
+ const config = MODEL_CONFIGS[modelName];
357
+ if (!config) {
358
+ throw new Error(`Unsupported model: ${modelName}`);
359
+ }
360
+ return config;
361
+ }
362
+
363
+ // 获取所有支持的图像生成模型
364
+ export function getSupportedImageModels(): string[] {
365
+ return Object.keys(MODEL_CONFIGS);
366
+ }
367
+
368
+ // 检查模型是否支持特定功能
369
+ export function doesModelSupport(modelName: string, feature: keyof ModelConfig['features']): boolean {
370
+ const config = getModelConfig(modelName);
371
+ return config.features[feature];
372
+ }
373
+
374
+ // 验证参数是否在模型支持的范围内
375
+ export function validateModelParams(modelName: string, params: {
376
+ width?: number;
377
+ height?: number;
378
+ sampleStrength?: number;
379
+ }): { isValid: boolean; errors: string[] } {
380
+ const config = getModelConfig(modelName);
381
+ const errors: string[] = [];
382
+
383
+ // 验证分辨率
384
+ if (params.width && params.height) {
385
+ const isValidResolution = config.defaultParams.resolutions.some(
386
+ res => res.width === params.width && res.height === params.height
387
+ );
388
+ if (!isValidResolution) {
389
+ errors.push(
390
+ `Unsupported resolution ${params.width}x${params.height}. Supported resolutions: ${config.defaultParams.resolutions.map(r => `${r.width}x${r.height}`).join(', ')}`
391
+ );
392
+ }
393
+ }
394
+
395
+ // 验证采样强度
396
+ if (params.sampleStrength !== undefined) {
397
+ const [min, max] = config.defaultParams.sampleStrengthRange;
398
+ if (params.sampleStrength < min || params.sampleStrength > max) {
399
+ errors.push(`Sample strength must be between ${min} and ${max}`);
400
+ }
401
+ }
402
+
403
+ return {
404
+ isValid: errors.length === 0,
405
+ errors
406
+ };
407
+ }
src/lib/configs/service-config.ts ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import path from 'path';
2
+
3
+ import fs from 'fs-extra';
4
+ import yaml from 'yaml';
5
+ import _ from 'lodash';
6
+
7
+ import environment from '../environment.ts';
8
+ import util from '../util.ts';
9
+
10
+ const CONFIG_PATH = path.join(path.resolve(), 'configs/', environment.env, "/service.yml");
11
+
12
+ /**
13
+ * 服务配置
14
+ */
15
+ export class ServiceConfig {
16
+
17
+ /** 服务名称 */
18
+ name: string;
19
+ /** @type {string} 服务绑定主机地址 */
20
+ host;
21
+ /** @type {number} 服务绑定端口 */
22
+ port;
23
+ /** @type {string} 服务路由前缀 */
24
+ urlPrefix;
25
+ /** @type {string} 服务绑定地址(外部访问地址) */
26
+ bindAddress;
27
+
28
+ constructor(options?: any) {
29
+ const { name, host, port, urlPrefix, bindAddress } = options || {};
30
+ this.name = _.defaultTo(name, 'jimeng-free-api');
31
+ this.host = _.defaultTo(host, '0.0.0.0');
32
+ this.port = _.defaultTo(port, 5566);
33
+ this.urlPrefix = _.defaultTo(urlPrefix, '');
34
+ this.bindAddress = bindAddress;
35
+ }
36
+
37
+ get addressHost() {
38
+ if(this.bindAddress) return this.bindAddress;
39
+ const ipAddresses = util.getIPAddressesByIPv4();
40
+ for(let ipAddress of ipAddresses) {
41
+ if(ipAddress === this.host)
42
+ return ipAddress;
43
+ }
44
+ return ipAddresses[0] || "127.0.0.1";
45
+ }
46
+
47
+ get address() {
48
+ return `${this.addressHost}:${this.port}`;
49
+ }
50
+
51
+ get pageDirUrl() {
52
+ return `http://127.0.0.1:${this.port}/page`;
53
+ }
54
+
55
+ get publicDirUrl() {
56
+ return `http://127.0.0.1:${this.port}/public`;
57
+ }
58
+
59
+ static load() {
60
+ const external = _.pickBy(environment, (v, k) => ["name", "host", "port"].includes(k) && !_.isUndefined(v));
61
+ if(!fs.pathExistsSync(CONFIG_PATH)) return new ServiceConfig(external);
62
+ const data = yaml.parse(fs.readFileSync(CONFIG_PATH).toString());
63
+ return new ServiceConfig({ ...data, ...external });
64
+ }
65
+
66
+ }
67
+
68
+ export default ServiceConfig.load();
src/lib/configs/system-config.ts ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import path from 'path';
2
+
3
+ import fs from 'fs-extra';
4
+ import yaml from 'yaml';
5
+ import _ from 'lodash';
6
+
7
+ import environment from '../environment.ts';
8
+
9
+ const CONFIG_PATH = path.join(path.resolve(), 'configs/', environment.env, "/system.yml");
10
+
11
+ /**
12
+ * 系统配置
13
+ */
14
+ export class SystemConfig {
15
+
16
+ /** 是否开启请求日志 */
17
+ requestLog: boolean;
18
+ /** 临时目录路径 */
19
+ tmpDir: string;
20
+ /** 日志目录路径 */
21
+ logDir: string;
22
+ /** 日志写入间隔(毫秒) */
23
+ logWriteInterval: number;
24
+ /** 日志文件有效期(毫秒) */
25
+ logFileExpires: number;
26
+ /** 公共目录路径 */
27
+ publicDir: string;
28
+ /** 临时文件有效期(毫秒) */
29
+ tmpFileExpires: number;
30
+ /** 请求体配置 */
31
+ requestBody: any;
32
+ /** 是否调试模式 */
33
+ debug: boolean;
34
+
35
+ constructor(options?: any) {
36
+ const { requestLog, tmpDir, logDir, logWriteInterval, logFileExpires, publicDir, tmpFileExpires, requestBody, debug } = options || {};
37
+ this.requestLog = _.defaultTo(requestLog, false);
38
+ this.tmpDir = _.defaultTo(tmpDir, './tmp');
39
+ this.logDir = _.defaultTo(logDir, './logs');
40
+ this.logWriteInterval = _.defaultTo(logWriteInterval, 200);
41
+ this.logFileExpires = _.defaultTo(logFileExpires, 2626560000);
42
+ this.publicDir = _.defaultTo(publicDir, './public');
43
+ this.tmpFileExpires = _.defaultTo(tmpFileExpires, 86400000);
44
+ this.requestBody = Object.assign(requestBody || {}, {
45
+ enableTypes: ['form', 'text', 'xml'], // 移除 json,由自定义中间件处理
46
+ encoding: 'utf-8',
47
+ formLimit: '100mb',
48
+ jsonLimit: '100mb',
49
+ textLimit: '100mb',
50
+ xmlLimit: '100mb',
51
+ formidable: {
52
+ maxFileSize: '100mb'
53
+ },
54
+ multipart: true,
55
+ parsedMethods: ['POST', 'PUT', 'PATCH']
56
+ });
57
+ this.debug = _.defaultTo(debug, true);
58
+ }
59
+
60
+ get rootDirPath() {
61
+ return path.resolve();
62
+ }
63
+
64
+ get tmpDirPath() {
65
+ return path.resolve(this.tmpDir);
66
+ }
67
+
68
+ get logDirPath() {
69
+ return path.resolve(this.logDir);
70
+ }
71
+
72
+ get publicDirPath() {
73
+ return path.resolve(this.publicDir);
74
+ }
75
+
76
+ static load() {
77
+ if (!fs.pathExistsSync(CONFIG_PATH)) return new SystemConfig();
78
+ const data = yaml.parse(fs.readFileSync(CONFIG_PATH).toString());
79
+ return new SystemConfig(data);
80
+ }
81
+
82
+ }
83
+
84
+ export default SystemConfig.load();
src/lib/consts/exceptions.ts ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ export default {
2
+ SYSTEM_ERROR: [-1000, '系统异常'],
3
+ SYSTEM_REQUEST_VALIDATION_ERROR: [-1001, '请求参数校验错误'],
4
+ SYSTEM_NOT_ROUTE_MATCHING: [-1002, '无匹配的路由']
5
+ } as Record<string, [number, string]>
src/lib/environment.ts ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import path from 'path';
2
+
3
+ import fs from 'fs-extra';
4
+ import minimist from 'minimist';
5
+ import _ from 'lodash';
6
+
7
+ const cmdArgs = minimist(process.argv.slice(2)); //获取命令行参数
8
+ const envVars = process.env; //获取环境变量
9
+
10
+ class Environment {
11
+
12
+ /** 命令行参数 */
13
+ cmdArgs: any;
14
+ /** 环境变量 */
15
+ envVars: any;
16
+ /** 环境名称 */
17
+ env?: string;
18
+ /** 服务名称 */
19
+ name?: string;
20
+ /** 服务地址 */
21
+ host?: string;
22
+ /** 服务端口 */
23
+ port?: number;
24
+ /** 包参数 */
25
+ package: any;
26
+
27
+ constructor(options: any = {}) {
28
+ const { cmdArgs, envVars, package: _package } = options;
29
+ this.cmdArgs = cmdArgs;
30
+ this.envVars = envVars;
31
+ this.env = _.defaultTo(cmdArgs.env || envVars.SERVER_ENV, 'dev');
32
+ this.name = cmdArgs.name || envVars.SERVER_NAME || undefined;
33
+ this.host = cmdArgs.host || envVars.SERVER_HOST || undefined;
34
+ this.port = Number(cmdArgs.port || envVars.SERVER_PORT) ? Number(cmdArgs.port || envVars.SERVER_PORT) : undefined;
35
+ this.package = _package;
36
+ }
37
+
38
+ }
39
+
40
+ export default new Environment({
41
+ cmdArgs,
42
+ envVars,
43
+ package: JSON.parse(fs.readFileSync(path.join(path.resolve(), "package.json")).toString())
44
+ });
src/lib/exceptions/APIException.ts ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Exception from './Exception.js';
2
+
3
+ export default class APIException extends Exception {
4
+
5
+ /**
6
+ * 构造异常
7
+ *
8
+ * @param {[number, string]} exception 异常
9
+ */
10
+ constructor(exception: (string | number)[], errmsg?: string) {
11
+ super(exception, errmsg);
12
+ }
13
+
14
+ }
src/lib/exceptions/Exception.ts ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import assert from 'assert';
2
+
3
+ import _ from 'lodash';
4
+
5
+ export default class Exception extends Error {
6
+
7
+ /** 错误码 */
8
+ errcode: number;
9
+ /** 错误消息 */
10
+ errmsg: string;
11
+ /** 数据 */
12
+ data: any;
13
+ /** HTTP状态码 */
14
+ httpStatusCode: number;
15
+
16
+ /**
17
+ * 构造异常
18
+ *
19
+ * @param exception 异常
20
+ * @param _errmsg 异常消息
21
+ */
22
+ constructor(exception: (string | number)[], _errmsg?: string) {
23
+ assert(_.isArray(exception), 'Exception must be Array');
24
+ const [errcode, errmsg] = exception as [number, string];
25
+ assert(_.isFinite(errcode), 'Exception errcode invalid');
26
+ assert(_.isString(errmsg), 'Exception errmsg invalid');
27
+ super(_errmsg || errmsg);
28
+ this.errcode = errcode;
29
+ this.errmsg = _errmsg || errmsg;
30
+ }
31
+
32
+ compare(exception: (string | number)[]) {
33
+ const [errcode] = exception as [number, string];
34
+ return this.errcode == errcode;
35
+ }
36
+
37
+ setHTTPStatusCode(value: number) {
38
+ this.httpStatusCode = value;
39
+ return this;
40
+ }
41
+
42
+ setData(value: any) {
43
+ this.data = _.defaultTo(value, null);
44
+ return this;
45
+ }
46
+
47
+ }
src/lib/http-status-codes.ts ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export default {
2
+
3
+ CONTINUE: 100, //客户端应当继续发送请求。这个临时响应是用来通知客户端它的部分请求已经被服务器接收,且仍未被拒绝。客户端应当继续发送请求的剩余部分,或者如果请求已经完成,忽略这个响应。服务器必须在请求完成后向客户端发送一个最终响应
4
+ SWITCHING_PROTOCOLS: 101, //服务器已经理解了客户端的请求,并将通过Upgrade 消息头通知客户端采用不同的协议来完成这个请求。在发送完这个响应最后的空行后,服务器将会切换到在Upgrade 消息头中定义的那些协议。只有在切换新的协议更有好处的时候才应该采取类似措施。例如,切换到新的HTTP 版本比旧版本更有优势,或者切换到一个实时且同步的协议以传送利用此类特性的资源
5
+ PROCESSING: 102, //处理将被继续执行
6
+
7
+ OK: 200, //请求已成功,请求所希望的响应头或数据体将随此响应返回
8
+ CREATED: 201, //请求已经被实现,而且有一个新的资源已经依据请求的需要而建立,且其 URI 已经随Location 头信息返回。假如需要的资源无法及时建立的话,应当返回 '202 Accepted'
9
+ ACCEPTED: 202, //服务器已接受请求,但尚未处理。正如它可能被拒绝一样,最终该请求可能会也可能不会被执行。在异步操作的场合下,没有比发送这个状态码更方便的做法了。返回202状态码的响应的目的是允许服务器接受其他过程的请求(例如某个每天只执行一次的基于批处理的操作),而不必让客户端一直保持与服务器的连接直到批处理操作全部完成。在接受请求处理并返回202状态码的响应应当在返回的实体中包含一些指示处理当前状态的信息,以及指向处理状态监视器或状态预测的指针,以便用户能够估计操作是否已经完成
10
+ NON_AUTHORITATIVE_INFO: 203, //服务器已成功处理了请求,但返回的实体头部元信息不是在原始服务器上有效的确定集合,而是来自本地或者第三方的拷贝。当前的信息可能是原始版本的子集或者超集。例如,包含资源的元数据可能导致原始服务器知道元信息的超级。使用此状态码不是必须的,而且只有在响应不使用此状态码便会返回200 OK的情况下才是合适的
11
+ NO_CONTENT: 204, //服务器成功处理了请求,但不需要返回任何实体内容,并且希望返回更新了的元信息。响应可能通过实体头部的形式,返回新的或更新后的元信息。如果存在这些头部信息,则应当与所请求的变量相呼应。如果客户端是浏览器的话,那么用户浏览器应保留发送了该请求的页面,而不产生任何文档视图上的变化,即使按照规范新的或更新后的元信息应当被应用到用户浏览器活动视图中的文档。由于204响应被禁止包含任何消息体,因此它始终以消息头后的第一个空行结尾
12
+ RESET_CONTENT: 205, //服务器成功处理了请求,且没有返回任何内容。但是与204响应不同,返回此状态码的响应要求请求者重置文档视图。该响应主要是被用于接受用户输入后,立即重置表单,以便用户能够轻松地开始另一次输入。与204响应一样,该响应也被禁止包含任何消息体,且以消息头后的第一个空行结束
13
+ PARTIAL_CONTENT: 206, //服务器已经成功处理了部分 GET 请求。类似于FlashGet或者迅雷这类的HTTP下载工具都是使用此类响应实现断点续传或者将一个大文档分解为多个下载段同时下载。该请求必须包含 Range 头信息来指示客户端希望得到的内容范围,并且可能包含 If-Range 来作为请求条件。响应必须包含如下的头部域:Content-Range 用以指示本次响应中返回的内容的范围;如果是Content-Type为multipart/byteranges的多段下载,则每一段multipart中都应包含Content-Range域用以指示本段的内容范围。假如响应中包含Content-Length,那么它的数值必须匹配它返回的内容范围的真实字节数。Date和ETag或Content-Location,假如同样的请求本应该返回200响应。Expires, Cache-Control,和/或 Vary,假如其值可能与之前相同变量的其他响应对应的值不同的话。假如本响应请求使用了 If-Range 强缓存验证,那么本次响应不应该包含其他实体头;假如本响应的请求使用了 If-Range 弱缓存验证,那么本次响应禁止包含其他实体头;这避免了缓存的实体内容和更新了的实体头信息之间的不一致。否则,本响应就应当包含所有本应该返回200响应中应当返回的所有实体头部域。假如 ETag 或 Latest-Modified 头部不能精确匹配的话,则客户端缓存应禁止将206响应返回的内容与之前任何缓存过的内容组合在一起。任何不支持 Range 以及 Content-Range 头的缓存都禁止缓存206响应返���的内容
14
+ MULTIPLE_STATUS: 207, //代表之后的消息体将是一个XML消息,并且可能依照之前子请求数量的不同,包含一系列独立的响应代码
15
+
16
+ MULTIPLE_CHOICES: 300, //被请求的资源有一系列可供选择的回馈信息,每个都有自己特定的地址和浏览器驱动的商议信息。用户或浏览器能够自行选择一个首选的地址进行重定向。除非这是一个HEAD请求,否则该响应应当包括一个资源特性及地址的列表的实体,以便用户或浏览器从中选择最合适的重定向地址。这个实体的格式由Content-Type定义的格式所决定。浏览器可能根据响应的格式以及浏览器自身能力,自动作出最合适的选择。当然,RFC 2616规范并没有规定这样的自动选择该如何进行。如果服务器本身已经有了首选的回馈选择,那么在Location中应当指明这个回馈的 URI;浏览器可能会将这个 Location 值作为自动重定向的地址。此外,除非额外指定,否则这个响应也是可缓存的
17
+ MOVED_PERMANENTLY: 301, //被请求的资源已永久移动到新位置,并且将来任何对此资源的引用都应该使用本响应返回的若干个URI之一。如果可能,拥有链接编辑功能的客户端应当自动把请求的地址修改为从服务器反馈回来的地址。除非额外指定,否则这个响应也是可缓存的。新的永久性的URI应当在响应的Location域中返回。除非这是一个HEAD请求,否则响应的实体中应当包含指向新的URI的超链接及简短说明。如果这不是一个GET或者HEAD请求,因此浏览器禁止自动进行重定向,除非得到用户的确认,因为请求的条件可能因此发生变化。注意:对于某些使用 HTTP/1.0 协议的浏览器,当它们发送的POST请求得到了一个301响应的话,接下来的重定向请求将会变成GET方式
18
+ FOUND: 302, //请求的资源现在临时从不同的URI响应请求。由于这样的重定向是临时的,客户端应当继续向原有地址发送以后的请求。只有在Cache-Control或Expires中进行了指定的情况下,这个响应才是可缓存的。新的临时性的URI应当在响应的 Location 域中返回。除非这是一个HEAD请求,否则响应的实体中应当包含指向新的URI的超链接及简短说明。如果这不是一个GET或者HEAD请求,那么浏览器禁止自动进行重定向,除非得到用户的确认,因为请求的条件可能因此发生变化。注意:虽然RFC 1945和RFC 2068规范不允许客户端在重定向时改变请求的方法,但是很多现存的浏览器将302响应视作为303响应,并且使用GET方式访问在Location中规定的URI,而无视原先请求的方法。状态码303和307被添加了进来,用以明确服务器期待客户端进行何种反应
19
+ SEE_OTHER: 303, //对应当前请求的响应可以在另一个URI上被找到,而且客户端应当采用 GET 的方式访问那个资源。这个方法的存在主要是为了允许由脚本激活的POST请求输出重定向到一个新的资源。这个新的 URI 不是原始资源的替代引用。同时,303响应禁止被缓存。当然,第二个请求(重定向)可能被缓存。新的 URI 应当在响应的Location域中返回。除非这是一个HEAD请求,否则响应的实体中应当包含指向新的URI的超链接及简短说明。注意:许多 HTTP/1.1 版以前的浏览器不能正确理解303状态。如果需要考虑与这些浏览器之间的互动,302状态码应该可以胜任,因为大多数的浏览器处理302响应时的方式恰恰就是上述规范要求客户端处理303响应时应当做的
20
+ NOT_MODIFIED: 304, //如果客户端发送了一个带条件的GET请求且该请求已被允许,而文档的内容(自上次访问以来或者根据请求的条件)并没有改变,则服务器应当返回这个状态码。304响应禁止包含消息体,因此始终以消息头后的第一个空行结尾。该响应必须包含以下的头信息:Date,除非这个服务器没有时钟。假如没有时钟的服务器也遵守这些规则,那么代理服务器以及客户端可以自行将Date字段添加到接收到的响应头中去(正如RFC 2068中规定的一样),缓存机制将会正常工作。ETag或 Content-Location,假如同样的请求本应返回200响应。Expires, Cache-Control,和/或Vary,假如其值可能与之前相同变量的其他响应对应的值不同的话。假如本响应请求使用了强缓存验证,那么本次响应不应该包含其他实体头;否则(例如,某个带条件的 GET 请求使用了弱缓存验证),本次响应禁止包含其他实体头;这避免了缓存了的实体内容和更新了的实体头信息之间的不一致。假如某个304响应指明了当前某个实体没有缓存,那么缓存系统必须忽视这个响应,并且重复发送不包含限制条件的请求。假如接收到一个要求更新某个缓存条目的304响应,那么缓存系统必须更新整个条目以反映所有在响应中被更新的字段的值
21
+ USE_PROXY: 305, //被请求的资源必须通过指定的代理才能被访问。Location域中将给出指定的代理所在的URI信息,接收者需要重复发送一个单独的请求,通过这个代理才能访问相应资源。只有原始服务器才能建立305响应。注意:RFC 2068中没有明确305响应是为了重定向一个单独的请求,而且只能被原始服务器建立。忽视这些限制可能导致严重的安全后果
22
+ UNUSED: 306, //在最新版的规范中,306状态码已经不再被使用
23
+ TEMPORARY_REDIRECT: 307, //请求的资源现在临时从不同的URI 响应请求。由于这样的重定向是临时的,客户端应当继续向原有地址发送以后的请求。只有在Cache-Control或Expires中进行了指定的情况下,这个响应才是可缓存的。新的临时性的URI 应当在响应的Location域中返回。除非这是一个HEAD请求,否则响应的实体中应当包含指向新的URI 的超链接及简短说明。因为部分浏览器不能识别307响应,因此需要添加上述必要信息以便用户能够理解并向新的 URI 发出访问请求。如果这不是一个GET或者HEAD请求,那么浏览器禁止自动进行重定向,除非得到用户的确认,因为请求的条件可能因此发生变化
24
+
25
+ BAD_REQUEST: 400, //1.语义有误,当前请求无法被服务器理解。除非进行修改,否则客户端不应该重复提交这个请求 2.请求参数有误
26
+ UNAUTHORIZED: 401, //当前请求需要用户验证。该响应必须包含一个适用于被请求资源的 WWW-Authenticate 信息头用以询问用户信息。客户端可以重复提交一个包含恰当的 Authorization 头信息的请求。如果当前请求已经包含了 Authorization 证书,那么401响应代表着服务器验证已经拒绝了那些证书。如果401响应包含了与前一个响应相同的身份验证询问,且浏览器已经至少尝试了一次验证,那么浏览器应当向用户展示响应中包含的实体信息,因为这个实体信息中可能包含了相关诊断信息。参见RFC 2617
27
+ PAYMENT_REQUIRED: 402, //该状态码是为了将来可能的需求而预留的
28
+ FORBIDDEN: 403, //服务器已经理解请求,但是拒绝执行它。与401响应不同的是,身份验证并不能提供任何帮助,而且这个请求也不应该被重复提交。如果这不是一个HEAD请求,而且服务器希望能够讲清楚为何请求不能被执行,那么就应该在实体内描述拒绝的原因。当然服务器也可以返回一个404响应,假如它不希望让客户端获得任何信息
29
+ NOT_FOUND: 404, //请求失败,请求所希望得到的资源未被在服务器上发现。没有信息能够告诉用户这个状况到底是暂时的还是永久的。假如服务器知道情况的话,应当使用410状态码来告知旧资源因为某些内部的配置机制问题,已经永久的不可用,而且没有任何可以跳转的地址。404这个状态码被广泛应用于当服务器不想揭示到底为何请求被拒绝或者没有其他适合的响应可用的情况下
30
+ METHOD_NOT_ALLOWED: 405, //请求行中指定的请求方法不能被用于请求相应的资源。该响应必须返回一个Allow 头信息用以表示出当前资源能够接受的请求方法的列表。鉴于PUT,DELETE方法会对服务器上的资源进行写操作,因而绝大部分的网页服务器都不支持或者在默认配置下不允许上述请求方法,对于此类请求均会返回405错误
31
+ NO_ACCEPTABLE: 406, //请求的资源的内容特性无法满足请求头中的条件,因而无法生成响应实体。除非这是一个 HEAD 请求,否则该响应就应当返回一个包含可以让用户或者浏览器从中选择最合适的实体特性以及地址列表的实体。实体的格式由Content-Type头中定义的媒体类型决定。浏览器可以根据格式及自身能力自行作出最佳选择。但是,规范中并没有定义任何作出此类自动选择的标准
32
+ PROXY_AUTHENTICATION_REQUIRED: 407, //与401响应类似,只不过客户端必须在代理服务器上进行身份验证。代理服务器必须返回一个Proxy-Authenticate用以进行身份询问。客户端可以返回一个Proxy-Authorization信息头用以验证。参见RFC 2617
33
+ REQUEST_TIMEOUT: 408, //请求超时。客户端没有在服务器预备等待的时间内完成一个请求的发送。客户端可以随时再次提交这一请求而无需进行任何更改
34
+ CONFLICT: 409, //由于和被请求的资源的当前状态之间存在冲突,请求无法完成。这个代码只允许用在这样的情况下才能被使用:用户被认为能够解决冲突,并且会重新提交新的请求。该响应应当包含足够的信息以便用户发现冲突的源头。冲突通常发生于对PUT请求的处理中。例如,在采用版本检查的环境下,某次PUT提交的对特定资源���修改请求所附带的版本信息与之前的某个(第三方)请求向冲突,那么此时服务器就应该返回一个409错误,告知用户请求无法完成。此时,响应实体中很可能会包含两个冲突版本之间的差异比较,以便用户重新提交归并以后的新版本
35
+ GONE: 410, //被请求的资源在服务器上已经不再可用,而且没有任何已知的转发地址。这样的状况应当被认为是永久性的。如果可能,拥有链接编辑功能的客户端应当在获得用户许可后删除所有指向这个地址的引用。如果服务器不知道或者无法确定这个状况是否是永久的,那么就应该使用404状态码。除非额外说明,否则这个响应是可缓存的。410响应的目的主要是帮助网站管理员维护网站,通知用户该资源已经不再可用,并且服务器拥有者希望所有指向这个资源的远端连接也被删除。这类事件在限时、增值服务中很普遍。同样,410响应也被用于通知客户端在当前服务器站点上,原本属于某个个人的资源已经不再可用。当然,是否需要把所有永久不可用的资源标记为'410 Gone',以及是否需要保持此标记多长时间,完全取决于服务器拥有者
36
+ LENGTH_REQUIRED: 411, //服务器拒绝在没有定义Content-Length头的情况下接受请求。在添加了表明请求消息体长度的有效Content-Length头之后,客户端可以再次提交该请求
37
+ PRECONDITION_FAILED: 412, //服务器在验证在请求的头字段中给出先决条件时,没能满足其中的一个或多个。这个状态码允许客户端在获取资源时在请求的元信息(请求头字段数据)中设置先决条件,以此避免该请求方法被应用到其希望的内容以外的资源上
38
+ REQUEST_ENTITY_TOO_LARGE: 413, //服务器拒绝处理当前请求,因为该请求提交的实体数据大小超过了服务器愿意或者能够处理的范围。此种情况下,服务器可以关闭连接以免客户端继续发送此请求。如果这个状况是临时的,服务器应当返回一个 Retry-After 的响应头,以告知客户端可以在多少时间以后重新尝试
39
+ REQUEST_URI_TOO_LONG: 414, //请求的URI长度超过了服务器能够解释的长度,因此服务器拒绝对该请求提供服务。这比较少见,通常的情况包括:本应使用POST方法的表单提交变成了GET方法,导致查询字符串(Query String)过长。重定向URI “黑洞”,例如每次重定向把旧的URI作为新的URI的一部分,导致在若干次重定向后URI超长。客户端正在尝试利用某些服务器中存在的安全漏洞攻击服务器。这类服务器使用固定长度的缓冲读取或操作请求的URI,当GET后的参数超过某个数值后,可能会产生缓冲区溢出,导致任意代码被执行[1]。没有此类漏洞的服务器,应当返回414状态码
40
+ UNSUPPORTED_MEDIA_TYPE: 415, //对于当前请求的方法和所请求的资源,请求中提交的实体并不是服务器中所支持的格式,因此请求被拒绝
41
+ REQUESTED_RANGE_NOT_SATISFIABLE: 416, //如果请求中包含了Range请求头,并且Range中指定的任何数据范围都与当前资源的可用范围不重合,同时请求中又没有定义If-Range请求头,那么服务器就应当返回416状态码。假如Range使用的是字节范围,那么这种情况就是指请求指定的所有数据范围的首字节位置都超过了当前资源的长度。服务器也应当在返回416状态码的同时,包含一个Content-Range实体头,用以指明当前资源的长度。这个响应也被禁止使用multipart/byteranges作为其 Content-Type
42
+ EXPECTION_FAILED: 417, //在请求头Expect中指定的预期内容无法被服务器满足,或者这个服务器是一个代理服务器,它有明显的证据证明在当前路由的下一个节点上,Expect的内容无法被满足
43
+ TOO_MANY_CONNECTIONS: 421, //从当前客户端所在的IP地址到服务器的连接数超过了服务器许可的最大范围。通常,这里的IP地址指的是从服务器上看到的客户端地址(比如用户的网关或者代理服务器地址)。在这种情况下,连接数的计算可能涉及到不止一个终端用户
44
+ UNPROCESSABLE_ENTITY: 422, //请求格式正确,但是由于含有语义错误,无法响应
45
+ FAILED_DEPENDENCY: 424, //由于之前的某个请求发生的错误,导致当前请求失败,例如PROPPATCH
46
+ UNORDERED_COLLECTION: 425, //在WebDav Advanced Collections 草案中定义,但是未出现在《WebDAV 顺序集协议》(RFC 3658)中
47
+ UPGRADE_REQUIRED: 426, //客户端应当切换到TLS/1.0
48
+ RETRY_WITH: 449, //由微软扩展,代表请求应当在执行完适当的操作后进行重试
49
+
50
+ INTERNAL_SERVER_ERROR: 500, //服务器遇到了一个未曾预料的状况,导致了它无法完成对请求的处理。一般来说,这个问题都会在服务器的程序码出错时出现
51
+ NOT_IMPLEMENTED: 501, //服务器不支持当前请求所需要的某个功能。当服务器无法识别请求的方法,并且无法支持其对任何资源的请求
52
+ BAD_GATEWAY: 502, //作为网关或者代理工作的服务器尝试执行请求时,从上游服务器接收到无效的响应
53
+ SERVICE_UNAVAILABLE: 503, //由于临时的服务器维护或者过载,服务器当前无法处理请求。这个状况是临时的,并且将在一段时间以后恢复。如果能够预计延迟时间,那么响应中可以包含一个 Retry-After 头用以标明这个延迟时间。如果没有给出这个 Retry-After 信息,那么客户端应当以处理500响应的方式处理它。注意:503状态码的存在并不意味着服务器在过载的时候必须使用它。某些服务器只不过是希望拒绝客户端的连接
54
+ GATEWAY_TIMEOUT: 504, //作为网关或者代理工作的服务器尝试执行请求时,未能及时从上游服务器(URI标识出的服务器,例如HTTP、FTP、LDAP)或者辅助服务器(例如DNS)收到响应。注意:某些代理服务器在DNS查询超时时会返回400或者500错误
55
+ HTTP_VERSION_NOT_SUPPORTED: 505, //服务器不支持,或者拒绝支持在请求中使用的HTTP版本。这暗示着服务器不能或不愿使用与客户端相同的版本。响应中应当包含一个描述了为何版本不被支持以及服务器支持哪些协议的实体
56
+ VARIANT_ALSO_NEGOTIATES: 506, //服务器存在内部配置错误:被请求的协商变元资源被配置为在透明内容协商中使用自己,因此在一个协商处理中不是一个合适的重点
57
+ INSUFFICIENT_STORAGE: 507, //服务器无法存储完成请求所必须的内容。这个状况被认为是临时的
58
+ BANDWIDTH_LIMIT_EXCEEDED: 509, //服务器达到带宽限制。这不是一个官方的状态码,但是仍被广泛使用
59
+ NOT_EXTENDED: 510 //获取资源所需要的策略并没有没满足
60
+
61
+ };
src/lib/initialize.ts ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logger from './logger.js';
2
+
3
+ // 允许无限量的监听器
4
+ process.setMaxListeners(Infinity);
5
+ // 输出未捕获异常
6
+ process.on("uncaughtException", (err, origin) => {
7
+ logger.error(`An unhandled error occurred: ${origin}`, err);
8
+ });
9
+ // 输出未处理的Promise.reject
10
+ process.on("unhandledRejection", (_, promise) => {
11
+ promise.catch(err => logger.error("An unhandled rejection occurred:", err));
12
+ });
13
+ // 输出系统警告信息
14
+ process.on("warning", warning => logger.warn("System warning: ", warning));
15
+ // 进程退出监听
16
+ process.on("exit", () => {
17
+ logger.info("Service exit");
18
+ logger.footer();
19
+ });
20
+ // 进程被kill
21
+ process.on("SIGTERM", () => {
22
+ logger.warn("received kill signal");
23
+ process.exit(2);
24
+ });
25
+ // Ctrl-C进程退出
26
+ process.on("SIGINT", () => {
27
+ process.exit(0);
28
+ });
src/lib/interfaces/ICompletionMessage.ts ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ export default interface ICompletionMessage {
2
+ role: 'system' | 'assistant' | 'user' | 'function';
3
+ content: string;
4
+ }
src/lib/logger.ts ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import path from 'path';
2
+ import _util from 'util';
3
+
4
+ import 'colors';
5
+ import _ from 'lodash';
6
+ import fs from 'fs-extra';
7
+ import { format as dateFormat } from 'date-fns';
8
+
9
+ import config from './config.ts';
10
+ import util from './util.ts';
11
+
12
+ const isVercelEnv = process.env.VERCEL;
13
+
14
+ class LogWriter {
15
+
16
+ #buffers = [];
17
+
18
+ constructor() {
19
+ !isVercelEnv && fs.ensureDirSync(config.system.logDirPath);
20
+ !isVercelEnv && this.work();
21
+ }
22
+
23
+ push(content) {
24
+ const buffer = Buffer.from(content);
25
+ this.#buffers.push(buffer);
26
+ }
27
+
28
+ writeSync(buffer) {
29
+ !isVercelEnv && fs.appendFileSync(path.join(config.system.logDirPath, `/${util.getDateString()}.log`), buffer);
30
+ }
31
+
32
+ async write(buffer) {
33
+ !isVercelEnv && await fs.appendFile(path.join(config.system.logDirPath, `/${util.getDateString()}.log`), buffer);
34
+ }
35
+
36
+ flush() {
37
+ if(!this.#buffers.length) return;
38
+ !isVercelEnv && fs.appendFileSync(path.join(config.system.logDirPath, `/${util.getDateString()}.log`), Buffer.concat(this.#buffers));
39
+ }
40
+
41
+ work() {
42
+ if (!this.#buffers.length) return setTimeout(this.work.bind(this), config.system.logWriteInterval);
43
+ const buffer = Buffer.concat(this.#buffers);
44
+ this.#buffers = [];
45
+ this.write(buffer)
46
+ .finally(() => setTimeout(this.work.bind(this), config.system.logWriteInterval))
47
+ .catch(err => console.error("Log write error:", err));
48
+ }
49
+
50
+ }
51
+
52
+ class LogText {
53
+
54
+ /** @type {string} 日志级别 */
55
+ level;
56
+ /** @type {string} 日志文本 */
57
+ text;
58
+ /** @type {string} 日志来源 */
59
+ source;
60
+ /** @type {Date} 日志发生时间 */
61
+ time = new Date();
62
+
63
+ constructor(level, ...params) {
64
+ this.level = level;
65
+ this.text = _util.format.apply(null, params);
66
+ this.source = this.#getStackTopCodeInfo();
67
+ }
68
+
69
+ #getStackTopCodeInfo() {
70
+ const unknownInfo = { name: "unknown", codeLine: 0, codeColumn: 0 };
71
+ const stackArray = new Error().stack.split("\n");
72
+ const text = stackArray[4];
73
+ if (!text)
74
+ return unknownInfo;
75
+ const match = text.match(/at (.+) \((.+)\)/) || text.match(/at (.+)/);
76
+ if (!match || !_.isString(match[2] || match[1]))
77
+ return unknownInfo;
78
+ const temp = match[2] || match[1];
79
+ const _match = temp.match(/([a-zA-Z0-9_\-\.]+)\:(\d+)\:(\d+)$/);
80
+ if (!_match)
81
+ return unknownInfo;
82
+ const [, scriptPath, codeLine, codeColumn] = _match as any;
83
+ return {
84
+ name: scriptPath ? scriptPath.replace(/.js$/, "") : "unknown",
85
+ path: scriptPath || null,
86
+ codeLine: parseInt(codeLine || 0),
87
+ codeColumn: parseInt(codeColumn || 0)
88
+ };
89
+ }
90
+
91
+ toString() {
92
+ return `[${dateFormat(this.time, "yyyy-MM-dd HH:mm:ss.SSS")}][${this.level}][${this.source.name}<${this.source.codeLine},${this.source.codeColumn}>] ${this.text}`;
93
+ }
94
+
95
+ }
96
+
97
+ class Logger {
98
+
99
+ /** @type {Object} 系统配置 */
100
+ config = {};
101
+ /** @type {Object} 日志级别映射 */
102
+ static Level = {
103
+ Success: "success",
104
+ Info: "info",
105
+ Log: "log",
106
+ Debug: "debug",
107
+ Warning: "warning",
108
+ Error: "error",
109
+ Fatal: "fatal"
110
+ };
111
+ /** @type {Object} 日志级别文本颜色樱色 */
112
+ static LevelColor = {
113
+ [Logger.Level.Success]: "green",
114
+ [Logger.Level.Info]: "brightCyan",
115
+ [Logger.Level.Debug]: "white",
116
+ [Logger.Level.Warning]: "brightYellow",
117
+ [Logger.Level.Error]: "brightRed",
118
+ [Logger.Level.Fatal]: "red"
119
+ };
120
+ #writer;
121
+
122
+ constructor() {
123
+ this.#writer = new LogWriter();
124
+ }
125
+
126
+ header() {
127
+ this.#writer.writeSync(Buffer.from(`\n\n===================== LOG START ${dateFormat(new Date(), "yyyy-MM-dd HH:mm:ss.SSS")} =====================\n\n`));
128
+ }
129
+
130
+ footer() {
131
+ this.#writer.flush(); //将未写入文件的日志缓存写入
132
+ this.#writer.writeSync(Buffer.from(`\n\n===================== LOG END ${dateFormat(new Date(), "yyyy-MM-dd HH:mm:ss.SSS")} =====================\n\n`));
133
+ }
134
+
135
+ success(...params) {
136
+ const content = new LogText(Logger.Level.Success, ...params).toString();
137
+ console.info(content[Logger.LevelColor[Logger.Level.Success]]);
138
+ this.#writer.push(content + "\n");
139
+ }
140
+
141
+ info(...params) {
142
+ const content = new LogText(Logger.Level.Info, ...params).toString();
143
+ console.info(content[Logger.LevelColor[Logger.Level.Info]]);
144
+ this.#writer.push(content + "\n");
145
+ }
146
+
147
+ log(...params) {
148
+ const content = new LogText(Logger.Level.Log, ...params).toString();
149
+ console.log(content[Logger.LevelColor[Logger.Level.Log]]);
150
+ this.#writer.push(content + "\n");
151
+ }
152
+
153
+ debug(...params) {
154
+ if(!config.system.debug) return; //非调试模式忽略debug
155
+ const content = new LogText(Logger.Level.Debug, ...params).toString();
156
+ console.debug(content[Logger.LevelColor[Logger.Level.Debug]]);
157
+ this.#writer.push(content + "\n");
158
+ }
159
+
160
+ warn(...params) {
161
+ const content = new LogText(Logger.Level.Warning, ...params).toString();
162
+ console.warn(content[Logger.LevelColor[Logger.Level.Warning]]);
163
+ this.#writer.push(content + "\n");
164
+ }
165
+
166
+ error(...params) {
167
+ const content = new LogText(Logger.Level.Error, ...params).toString();
168
+ console.error(content[Logger.LevelColor[Logger.Level.Error]]);
169
+ this.#writer.push(content);
170
+ }
171
+
172
+ fatal(...params) {
173
+ const content = new LogText(Logger.Level.Fatal, ...params).toString();
174
+ console.error(content[Logger.LevelColor[Logger.Level.Fatal]]);
175
+ this.#writer.push(content);
176
+ }
177
+
178
+ destory() {
179
+ this.#writer.destory();
180
+ }
181
+
182
+ }
183
+
184
+ export default new Logger();
src/lib/request/Request.ts ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import _ from 'lodash';
2
+
3
+ import APIException from '@/lib/exceptions/APIException.ts';
4
+ import EX from '@/api/consts/exceptions.ts';
5
+ import logger from '@/lib/logger.ts';
6
+ import util from '@/lib/util.ts';
7
+
8
+ export interface RequestOptions {
9
+ time?: number;
10
+ }
11
+
12
+ export default class Request {
13
+
14
+ /** 请求方法 */
15
+ method: string;
16
+ /** 请求URL */
17
+ url: string;
18
+ /** 请求路径 */
19
+ path: string;
20
+ /** 请求载荷类型 */
21
+ type: string;
22
+ /** 请求headers */
23
+ headers: any;
24
+ /** 请求原始查询字符串 */
25
+ search: string;
26
+ /** 请求查询参数 */
27
+ query: any;
28
+ /** 请求URL参数 */
29
+ params: any;
30
+ /** 请求载荷 */
31
+ body: any;
32
+ /** 上传的文件 */
33
+ files: any[];
34
+ /** 客户端IP地址 */
35
+ remoteIP: string | null;
36
+ /** 请求接受时间戳(毫秒) */
37
+ time: number;
38
+
39
+ constructor(ctx, options: RequestOptions = {}) {
40
+ const { time } = options;
41
+ this.method = ctx.request.method;
42
+ this.url = ctx.request.url;
43
+ this.path = ctx.request.path;
44
+ this.type = ctx.request.type;
45
+ this.headers = ctx.request.headers || {};
46
+ this.search = ctx.request.search;
47
+ this.query = ctx.query || {};
48
+ this.params = ctx.params || {};
49
+ this.body = ctx.request.body || {};
50
+ // koa-body 的 files 可能是对象 { files: [File, File] } 或 { files: File }
51
+ // 需要统一转换为数组格式
52
+ const rawFiles = ctx.request.files;
53
+ if (rawFiles) {
54
+ if (Array.isArray(rawFiles)) {
55
+ this.files = rawFiles;
56
+ } else if (typeof rawFiles === 'object') {
57
+ // 遍历对象,提取所有文件
58
+ const filesArray: any[] = [];
59
+ for (const key in rawFiles) {
60
+ const fileOrFiles = rawFiles[key];
61
+ if (Array.isArray(fileOrFiles)) {
62
+ filesArray.push(...fileOrFiles);
63
+ } else if (fileOrFiles) {
64
+ filesArray.push(fileOrFiles);
65
+ }
66
+ }
67
+ this.files = filesArray;
68
+ } else {
69
+ this.files = [];
70
+ }
71
+ } else {
72
+ this.files = [];
73
+ }
74
+ this.remoteIP = this.headers["X-Real-IP"] || this.headers["x-real-ip"] || this.headers["X-Forwarded-For"] || this.headers["x-forwarded-for"] || ctx.ip || null;
75
+ this.time = Number(_.defaultTo(time, util.timestamp()));
76
+ }
77
+
78
+ validate(key: string, fn?: Function, message?: string) {
79
+ try {
80
+ const value = _.get(this, key);
81
+ if (fn) {
82
+ if (fn(value) === false)
83
+ throw `[Mismatch] -> ${fn}`;
84
+ }
85
+ else if (_.isUndefined(value))
86
+ throw '[Undefined]';
87
+ }
88
+ catch (err) {
89
+ logger.warn(`Params ${key} invalid:`, err);
90
+ throw new APIException(EX.API_REQUEST_PARAMS_INVALID, message || `Params ${key} invalid`);
91
+ }
92
+ return this;
93
+ }
94
+
95
+ }
src/lib/response/Body.ts ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import _ from 'lodash';
2
+
3
+ export interface BodyOptions {
4
+ code?: number;
5
+ message?: string;
6
+ data?: any;
7
+ statusCode?: number;
8
+ }
9
+
10
+ export default class Body {
11
+
12
+ /** 状态码 */
13
+ code: number;
14
+ /** 状态消息 */
15
+ message: string;
16
+ /** 载荷 */
17
+ data: any;
18
+ /** HTTP状态码 */
19
+ statusCode: number;
20
+
21
+ constructor(options: BodyOptions = {}) {
22
+ const { code, message, data, statusCode } = options;
23
+ this.code = Number(_.defaultTo(code, 0));
24
+ this.message = _.defaultTo(message, 'OK');
25
+ this.data = _.defaultTo(data, null);
26
+ this.statusCode = Number(_.defaultTo(statusCode, 200));
27
+ }
28
+
29
+ toObject() {
30
+ return {
31
+ code: this.code,
32
+ message: this.message,
33
+ data: this.data
34
+ };
35
+ }
36
+
37
+ static isInstance(value) {
38
+ return value instanceof Body;
39
+ }
40
+
41
+ }
src/lib/response/FailureBody.ts ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import _ from 'lodash';
2
+
3
+ import Body from './Body.ts';
4
+ import Exception from '../exceptions/Exception.ts';
5
+ import APIException from '../exceptions/APIException.ts';
6
+ import EX from '../consts/exceptions.ts';
7
+ import HTTP_STATUS_CODES from '../http-status-codes.ts';
8
+
9
+ export default class FailureBody extends Body {
10
+
11
+ constructor(error: APIException | Exception | Error, _data?: any) {
12
+ let errcode, errmsg, data = _data, httpStatusCode = HTTP_STATUS_CODES.OK;;
13
+ if(_.isString(error))
14
+ error = new Exception(EX.SYSTEM_ERROR, error);
15
+ else if(error instanceof APIException || error instanceof Exception)
16
+ ({ errcode, errmsg, data, httpStatusCode } = error);
17
+ else if(_.isError(error))
18
+ ({ errcode, errmsg, data, httpStatusCode } = new Exception(EX.SYSTEM_ERROR, error.message));
19
+ super({
20
+ code: errcode || -1,
21
+ message: errmsg || 'Internal error',
22
+ data,
23
+ statusCode: httpStatusCode
24
+ });
25
+ }
26
+
27
+ static isInstance(value) {
28
+ return value instanceof FailureBody;
29
+ }
30
+
31
+ }
src/lib/response/Response.ts ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mime from 'mime';
2
+ import _ from 'lodash';
3
+
4
+ import Body from './Body.ts';
5
+ import util from '../util.ts';
6
+
7
+ export interface ResponseOptions {
8
+ statusCode?: number;
9
+ type?: string;
10
+ headers?: Record<string, any>;
11
+ redirect?: string;
12
+ body?: any;
13
+ size?: number;
14
+ time?: number;
15
+ }
16
+
17
+ export default class Response {
18
+
19
+ /** 响应HTTP状态码 */
20
+ statusCode: number;
21
+ /** 响应内容类型 */
22
+ type: string;
23
+ /** 响应headers */
24
+ headers: Record<string, any>;
25
+ /** 重定向目标 */
26
+ redirect: string;
27
+ /** 响应载荷 */
28
+ body: any;
29
+ /** 响应载荷大小 */
30
+ size: number;
31
+ /** 响应时间戳 */
32
+ time: number;
33
+
34
+ constructor(body: any, options: ResponseOptions = {}) {
35
+ const { statusCode, type, headers, redirect, size, time } = options;
36
+ this.statusCode = Number(_.defaultTo(statusCode, Body.isInstance(body) ? body.statusCode : undefined))
37
+ this.type = type;
38
+ this.headers = headers;
39
+ this.redirect = redirect;
40
+ this.size = size;
41
+ this.time = Number(_.defaultTo(time, util.timestamp()));
42
+ this.body = body;
43
+ }
44
+
45
+ injectTo(ctx) {
46
+ this.redirect && ctx.redirect(this.redirect);
47
+ this.statusCode && (ctx.status = this.statusCode);
48
+ this.type && (ctx.type = mime.getType(this.type) || this.type);
49
+ const headers = this.headers || {};
50
+ if(this.size && !headers["Content-Length"] && !headers["content-length"])
51
+ headers["Content-Length"] = this.size;
52
+ ctx.set(headers);
53
+ if(Body.isInstance(this.body))
54
+ ctx.body = this.body.toObject();
55
+ else
56
+ ctx.body = this.body;
57
+ }
58
+
59
+ static isInstance(value) {
60
+ return value instanceof Response;
61
+ }
62
+
63
+ }
src/lib/response/SuccessfulBody.ts ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import _ from 'lodash';
2
+
3
+ import Body from './Body.ts';
4
+
5
+ export default class SuccessfulBody extends Body {
6
+
7
+ constructor(data: any, message?: string) {
8
+ super({
9
+ code: 0,
10
+ message: _.defaultTo(message, "OK"),
11
+ data
12
+ });
13
+ }
14
+
15
+ static isInstance(value) {
16
+ return value instanceof SuccessfulBody;
17
+ }
18
+
19
+ }
src/lib/server.ts ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Koa from 'koa';
2
+ import KoaRouter from 'koa-router';
3
+ import koaRange from 'koa-range';
4
+ import koaCors from "koa2-cors";
5
+ import koaBody from 'koa-body';
6
+ import _ from 'lodash';
7
+
8
+ import Exception from './exceptions/Exception.ts';
9
+ import Request from './request/Request.ts';
10
+ import Response from './response/Response.js';
11
+ import FailureBody from './response/FailureBody.ts';
12
+ import EX from './consts/exceptions.ts';
13
+ import logger from './logger.ts';
14
+ import config from './config.ts';
15
+
16
+ class Server {
17
+
18
+ app;
19
+ router;
20
+ koaBodyMiddleware;
21
+
22
+ constructor() {
23
+ this.app = new Koa();
24
+ this.app.use(koaCors());
25
+ // 范围请求支持
26
+ this.app.use(koaRange);
27
+ this.router = new KoaRouter({ prefix: config.service.urlPrefix });
28
+
29
+ // 预先创建 koa-body 中间件,支持 multipart 文件上传
30
+ this.koaBodyMiddleware = koaBody({
31
+ multipart: true,
32
+ formidable: {
33
+ maxFileSize: 100 * 1024 * 1024, // 100MB
34
+ keepExtensions: true,
35
+ },
36
+ formLimit: '100mb',
37
+ jsonLimit: '100mb',
38
+ textLimit: '100mb',
39
+ parsedMethods: ['POST', 'PUT', 'PATCH'],
40
+ });
41
+
42
+ // 前置处理异常拦截
43
+ this.app.use(async (ctx: any, next: Function) => {
44
+ if(ctx.request.type === "application/xml" || ctx.request.type === "application/ssml+xml")
45
+ ctx.req.headers["content-type"] = "text/xml";
46
+ try { await next() }
47
+ catch (err) {
48
+ logger.error(err);
49
+ const failureBody = new FailureBody(err);
50
+ new Response(failureBody).injectTo(ctx);
51
+ }
52
+ });
53
+ // 自定义 JSON 解析中间件
54
+ this.app.use(async (ctx: any, next: Function) => {
55
+ // 跳过 multipart 请求,让 koa-body 处理
56
+ if (ctx.is('multipart')) {
57
+ await next();
58
+ return;
59
+ }
60
+ if (ctx.is('application/json') && ['POST', 'PUT', 'PATCH'].includes(ctx.method)) {
61
+ logger.debug('开始自定义 JSON 解析');
62
+ const chunks: Buffer[] = [];
63
+
64
+ await new Promise((resolve, reject) => {
65
+ ctx.req.on('data', (chunk: Buffer) => {
66
+ chunks.push(chunk);
67
+ });
68
+
69
+ ctx.req.on('end', () => {
70
+ resolve(null);
71
+ });
72
+
73
+ ctx.req.on('error', reject);
74
+ });
75
+
76
+ const body = Buffer.concat(chunks).toString('utf8');
77
+
78
+ // 清理问题字符
79
+ let cleanedBody = body
80
+ .replace(/\r\n/g, '\n')
81
+ .replace(/\r/g, '\n')
82
+ .replace(/\u00A0/g, ' ')
83
+ .replace(/[\u2000-\u200B]/g, ' ')
84
+ .replace(/\uFEFF/g, '')
85
+ .trim();
86
+
87
+ const parsedBody = JSON.parse(cleanedBody);
88
+
89
+ logger.debug('JSON 解析成功,跳过 koa-body');
90
+
91
+ ctx.request.body = parsedBody;
92
+ ctx.request.rawBody = cleanedBody;
93
+
94
+ // 标记已处理,避免 koa-body 再次处理
95
+ ctx._jsonProcessed = true;
96
+ }
97
+ await next();
98
+ });
99
+
100
+ // 载荷解析器支持(只处理未被自定义解析器处理的请求)
101
+ this.app.use(async (ctx: any, next: Function) => {
102
+ if (!ctx._jsonProcessed) {
103
+ await this.koaBodyMiddleware(ctx, next);
104
+ } else {
105
+ await next();
106
+ }
107
+ });
108
+ this.app.on("error", (err: any) => {
109
+ // 忽略连接重试、中断、管道、取消错误
110
+ if (["ECONNRESET", "ECONNABORTED", "EPIPE", "ECANCELED"].includes(err.code)) return;
111
+ logger.error(err);
112
+ });
113
+ logger.success("Server initialized");
114
+ }
115
+
116
+ /**
117
+ * 附加路由
118
+ *
119
+ * @param routes 路由列表
120
+ */
121
+ attachRoutes(routes: any[]) {
122
+ routes.forEach((route: any) => {
123
+ const prefix = route.prefix || "";
124
+ for (let method in route) {
125
+ if(method === "prefix") continue;
126
+ if (!_.isObject(route[method])) {
127
+ logger.warn(`Router ${prefix} ${method} invalid`);
128
+ continue;
129
+ }
130
+ for (let uri in route[method]) {
131
+ this.router[method](`${prefix}${uri}`, async ctx => {
132
+ const { request, response } = await this.#requestProcessing(ctx, route[method][uri]);
133
+ if(response != null && config.system.requestLog)
134
+ logger.info(`<- ${request.method} ${request.url} ${response.time - request.time}ms`);
135
+ });
136
+ }
137
+ }
138
+ logger.info(`Route ${config.service.urlPrefix || ""}${prefix} attached`);
139
+ });
140
+ this.app.use(this.router.routes());
141
+ this.app.use((ctx: any) => {
142
+ const request = new Request(ctx);
143
+ logger.debug(`-> ${ctx.request.method} ${ctx.request.url} request is not supported - ${request.remoteIP || "unknown"}`);
144
+ // const failureBody = new FailureBody(new Exception(EX.SYSTEM_NOT_ROUTE_MATCHING, "Request is not supported"));
145
+ // const response = new Response(failureBody);
146
+ const message = `[请求有误]: 正确请求为 POST -> /v1/chat/completions,当前请求为 ${ctx.request.method} -> ${ctx.request.url} 请纠正`;
147
+ logger.warn(message);
148
+ const failureBody = new FailureBody(new Error(message));
149
+ const response = new Response(failureBody);
150
+ response.injectTo(ctx);
151
+ if(config.system.requestLog)
152
+ logger.info(`<- ${request.method} ${request.url} ${response.time - request.time}ms`);
153
+ });
154
+ }
155
+
156
+ /**
157
+ * 请求处理
158
+ *
159
+ * @param ctx 上下文
160
+ * @param routeFn 路由方法
161
+ */
162
+ #requestProcessing(ctx: any, routeFn: Function): Promise<any> {
163
+ return new Promise(resolve => {
164
+ const request = new Request(ctx);
165
+ try {
166
+ if(config.system.requestLog)
167
+ logger.info(`-> ${request.method} ${request.url}`);
168
+ routeFn(request)
169
+ .then(response => {
170
+ try {
171
+ if(!Response.isInstance(response)) {
172
+ const _response = new Response(response);
173
+ _response.injectTo(ctx);
174
+ return resolve({ request, response: _response });
175
+ }
176
+ response.injectTo(ctx);
177
+ resolve({ request, response });
178
+ }
179
+ catch(err) {
180
+ logger.error(err);
181
+ const failureBody = new FailureBody(err);
182
+ const response = new Response(failureBody);
183
+ response.injectTo(ctx);
184
+ resolve({ request, response });
185
+ }
186
+ })
187
+ .catch(err => {
188
+ try {
189
+ logger.error(err);
190
+ const failureBody = new FailureBody(err);
191
+ const response = new Response(failureBody);
192
+ response.injectTo(ctx);
193
+ resolve({ request, response });
194
+ }
195
+ catch(err) {
196
+ logger.error(err);
197
+ const failureBody = new FailureBody(err);
198
+ const response = new Response(failureBody);
199
+ response.injectTo(ctx);
200
+ resolve({ request, response });
201
+ }
202
+ });
203
+ }
204
+ catch(err) {
205
+ logger.error(err);
206
+ const failureBody = new FailureBody(err);
207
+ const response = new Response(failureBody);
208
+ response.injectTo(ctx);
209
+ resolve({ request, response });
210
+ }
211
+ });
212
+ }
213
+
214
+ /**
215
+ * 监听端口
216
+ */
217
+ async listen() {
218
+ const host = config.service.host;
219
+ const port = config.service.port;
220
+ await Promise.all([
221
+ new Promise((resolve, reject) => {
222
+ if(host === "0.0.0.0" || host === "localhost" || host === "127.0.0.1")
223
+ return resolve(null);
224
+ this.app.listen(port, "localhost", err => {
225
+ if(err) return reject(err);
226
+ resolve(null);
227
+ });
228
+ }),
229
+ new Promise((resolve, reject) => {
230
+ this.app.listen(port, host, err => {
231
+ if(err) return reject(err);
232
+ resolve(null);
233
+ });
234
+ })
235
+ ]);
236
+ logger.success(`Server listening on port ${port} (${host})`);
237
+ }
238
+
239
+ }
240
+
241
+ export default new Server();
src/lib/util.ts ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os from "os";
2
+ import path from "path";
3
+ import crypto from "crypto";
4
+ import { Readable, Writable } from "stream";
5
+
6
+ import "colors";
7
+ import mime from "mime";
8
+ import axios from "axios";
9
+ import fs from "fs-extra";
10
+ import { v1 as uuid } from "uuid";
11
+ import { format as dateFormat } from "date-fns";
12
+ import CRC32 from "crc-32";
13
+ import randomstring from "randomstring";
14
+ import _ from "lodash";
15
+ import { CronJob } from "cron";
16
+
17
+ import HTTP_STATUS_CODE from "./http-status-codes.ts";
18
+
19
+ const autoIdMap = new Map();
20
+
21
+ const util = {
22
+ is2DArrays(value: any) {
23
+ return (
24
+ _.isArray(value) &&
25
+ (!value[0] || (_.isArray(value[0]) && _.isArray(value[value.length - 1])))
26
+ );
27
+ },
28
+
29
+ uuid: (separator = true) => (separator ? uuid() : uuid().replace(/\-/g, "")),
30
+
31
+ autoId: (prefix = "") => {
32
+ let index = autoIdMap.get(prefix);
33
+ if (index > 999999) index = 0; //超过最大数字则重置为0
34
+ autoIdMap.set(prefix, (index || 0) + 1);
35
+ return `${prefix}${index || 1}`;
36
+ },
37
+
38
+ ignoreJSONParse(value: string) {
39
+ const result = _.attempt(() => JSON.parse(value));
40
+ if (_.isError(result)) return null;
41
+ return result;
42
+ },
43
+
44
+ generateRandomString(options: any): string {
45
+ return randomstring.generate(options);
46
+ },
47
+
48
+ getResponseContentType(value: any): string | null {
49
+ return value.headers
50
+ ? value.headers["content-type"] || value.headers["Content-Type"]
51
+ : null;
52
+ },
53
+
54
+ mimeToExtension(value: string) {
55
+ let extension = mime.getExtension(value);
56
+ if (extension == "mpga") return "mp3";
57
+ return extension;
58
+ },
59
+
60
+ extractURLExtension(value: string) {
61
+ const extname = path.extname(new URL(value).pathname);
62
+ return extname.substring(1).toLowerCase();
63
+ },
64
+
65
+ createCronJob(cronPatterns: any, callback?: Function) {
66
+ if (!_.isFunction(callback))
67
+ throw new Error("callback must be an Function");
68
+ return new CronJob(
69
+ cronPatterns,
70
+ () => callback(),
71
+ null,
72
+ false,
73
+ "Asia/Shanghai"
74
+ );
75
+ },
76
+
77
+ getDateString(format = "yyyy-MM-dd", date = new Date()) {
78
+ return dateFormat(date, format);
79
+ },
80
+
81
+ getIPAddressesByIPv4(): string[] {
82
+ const interfaces = os.networkInterfaces();
83
+ const addresses = [];
84
+ for (let name in interfaces) {
85
+ const networks = interfaces[name];
86
+ const results = networks.filter(
87
+ (network) =>
88
+ network.family === "IPv4" &&
89
+ network.address !== "127.0.0.1" &&
90
+ !network.internal
91
+ );
92
+ if (results[0] && results[0].address) addresses.push(results[0].address);
93
+ }
94
+ return addresses;
95
+ },
96
+
97
+ getMACAddressesByIPv4(): string[] {
98
+ const interfaces = os.networkInterfaces();
99
+ const addresses = [];
100
+ for (let name in interfaces) {
101
+ const networks = interfaces[name];
102
+ const results = networks.filter(
103
+ (network) =>
104
+ network.family === "IPv4" &&
105
+ network.address !== "127.0.0.1" &&
106
+ !network.internal
107
+ );
108
+ if (results[0] && results[0].mac) addresses.push(results[0].mac);
109
+ }
110
+ return addresses;
111
+ },
112
+
113
+ generateSSEData(event?: string, data?: string, retry?: number) {
114
+ return `event: ${event || "message"}\ndata: ${(data || "")
115
+ .replace(/\n/g, "\\n")
116
+ .replace(/\s/g, "\\s")}\nretry: ${retry || 3000}\n\n`;
117
+ },
118
+
119
+ buildDataBASE64(type, ext, buffer) {
120
+ return `data:${type}/${ext.replace("jpg", "jpeg")};base64,${buffer.toString(
121
+ "base64"
122
+ )}`;
123
+ },
124
+
125
+ isLinux() {
126
+ return os.platform() !== "win32";
127
+ },
128
+
129
+ isIPAddress(value) {
130
+ return (
131
+ _.isString(value) &&
132
+ (/^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$/.test(
133
+ value
134
+ ) ||
135
+ /\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*/.test(
136
+ value
137
+ ))
138
+ );
139
+ },
140
+
141
+ isPort(value) {
142
+ return _.isNumber(value) && value > 0 && value < 65536;
143
+ },
144
+
145
+ isReadStream(value): boolean {
146
+ return (
147
+ value &&
148
+ (value instanceof Readable || "readable" in value || value.readable)
149
+ );
150
+ },
151
+
152
+ isWriteStream(value): boolean {
153
+ return (
154
+ value &&
155
+ (value instanceof Writable || "writable" in value || value.writable)
156
+ );
157
+ },
158
+
159
+ isHttpStatusCode(value) {
160
+ return _.isNumber(value) && Object.values(HTTP_STATUS_CODE).includes(value);
161
+ },
162
+
163
+ isURL(value) {
164
+ return !_.isUndefined(value) && /^(http|https)/.test(value);
165
+ },
166
+
167
+ isSrc(value) {
168
+ return !_.isUndefined(value) && /^\/.+\.[0-9a-zA-Z]+(\?.+)?$/.test(value);
169
+ },
170
+
171
+ isBASE64(value) {
172
+ return !_.isUndefined(value) && /^[a-zA-Z0-9\/\+]+(=?)+$/.test(value);
173
+ },
174
+
175
+ isBASE64Data(value) {
176
+ return /^data:/.test(value);
177
+ },
178
+
179
+ extractBASE64DataFormat(value): string | null {
180
+ const match = value.trim().match(/^data:(.+);base64,/);
181
+ if (!match) return null;
182
+ return match[1];
183
+ },
184
+
185
+ removeBASE64DataHeader(value): string {
186
+ return value.replace(/^data:(.+);base64,/, "");
187
+ },
188
+
189
+ isDataString(value): boolean {
190
+ return /^(base64|json):/.test(value);
191
+ },
192
+
193
+ isStringNumber(value) {
194
+ return _.isFinite(Number(value));
195
+ },
196
+
197
+ isUnixTimestamp(value) {
198
+ return /^[0-9]{10}$/.test(`${value}`);
199
+ },
200
+
201
+ isTimestamp(value) {
202
+ return /^[0-9]{13}$/.test(`${value}`);
203
+ },
204
+
205
+ isEmail(value) {
206
+ return /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test(
207
+ value
208
+ );
209
+ },
210
+
211
+ isAsyncFunction(value) {
212
+ return Object.prototype.toString.call(value) === "[object AsyncFunction]";
213
+ },
214
+
215
+ async isAPNG(filePath) {
216
+ let head;
217
+ const readStream = fs.createReadStream(filePath, { start: 37, end: 40 });
218
+ const readPromise = new Promise((resolve, reject) => {
219
+ readStream.once("end", resolve);
220
+ readStream.once("error", reject);
221
+ });
222
+ readStream.once("data", (data) => (head = data));
223
+ await readPromise;
224
+ return head.compare(Buffer.from([0x61, 0x63, 0x54, 0x4c])) === 0;
225
+ },
226
+
227
+ unixTimestamp() {
228
+ return parseInt(`${Date.now() / 1000}`);
229
+ },
230
+
231
+ timestamp() {
232
+ return Date.now();
233
+ },
234
+
235
+ urlJoin(...values) {
236
+ let url = "";
237
+ for (let i = 0; i < values.length; i++)
238
+ url += `${i > 0 ? "/" : ""}${values[i]
239
+ .replace(/^\/*/, "")
240
+ .replace(/\/*$/, "")}`;
241
+ return url;
242
+ },
243
+
244
+ millisecondsToHmss(milliseconds) {
245
+ if (_.isString(milliseconds)) return milliseconds;
246
+ milliseconds = parseInt(milliseconds);
247
+ const sec = Math.floor(milliseconds / 1000);
248
+ const hours = Math.floor(sec / 3600);
249
+ const minutes = Math.floor((sec - hours * 3600) / 60);
250
+ const seconds = sec - hours * 3600 - minutes * 60;
251
+ const ms = (milliseconds % 60000) - seconds * 1000;
252
+ return `${hours > 9 ? hours : "0" + hours}:${
253
+ minutes > 9 ? minutes : "0" + minutes
254
+ }:${seconds > 9 ? seconds : "0" + seconds}.${ms}`;
255
+ },
256
+
257
+ millisecondsToTimeString(milliseconds) {
258
+ if (milliseconds < 1000) return `${milliseconds}ms`;
259
+ if (milliseconds < 60000)
260
+ return `${parseFloat((milliseconds / 1000).toFixed(2))}s`;
261
+ return `${Math.floor(milliseconds / 1000 / 60)}m${Math.floor(
262
+ (milliseconds / 1000) % 60
263
+ )}s`;
264
+ },
265
+
266
+ rgbToHex(r, g, b): string {
267
+ return ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
268
+ },
269
+
270
+ hexToRgb(hex) {
271
+ const value = parseInt(hex.replace(/^#/, ""), 16);
272
+ return [(value >> 16) & 255, (value >> 8) & 255, value & 255];
273
+ },
274
+
275
+ md5(value) {
276
+ return crypto.createHash("md5").update(value).digest("hex");
277
+ },
278
+
279
+ crc32(value) {
280
+ return _.isBuffer(value) ? CRC32.buf(value) : CRC32.str(value);
281
+ },
282
+
283
+ arrayParse(value): any[] {
284
+ return _.isArray(value) ? value : [value];
285
+ },
286
+
287
+ booleanParse(value) {
288
+ return value === "true" || value === true ? true : false;
289
+ },
290
+
291
+ encodeBASE64(value) {
292
+ return Buffer.from(value).toString("base64");
293
+ },
294
+
295
+ decodeBASE64(value) {
296
+ return Buffer.from(value, "base64").toString();
297
+ },
298
+
299
+ async fetchFileBASE64(url: string) {
300
+ const result = await axios.get(url, {
301
+ responseType: "arraybuffer",
302
+ });
303
+ return result.data.toString("base64");
304
+ },
305
+ };
306
+
307
+ export default util;
tsconfig.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compilerOptions": {
3
+ "baseUrl": ".",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "allowImportingTsExtensions": true,
7
+ "allowSyntheticDefaultImports": true,
8
+ "noEmit": true,
9
+ "paths": {
10
+ "@/*": ["src/*"]
11
+ },
12
+ "outDir": "./dist"
13
+ },
14
+ "include": ["src/**/*", "libs.d.ts"],
15
+ "exclude": ["node_modules", "dist"]
16
+ }
vercel.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "builds": [
3
+ {
4
+ "src": "./dist/*.html",
5
+ "use": "@vercel/static"
6
+ },
7
+ {
8
+ "src": "./dist/index.js",
9
+ "use": "@vercel/node"
10
+ }
11
+ ],
12
+ "routes": [
13
+ {
14
+ "src": "/",
15
+ "dest": "/dist/welcome.html"
16
+ },
17
+ {
18
+ "src": "/(.*)",
19
+ "dest": "/dist",
20
+ "headers": {
21
+ "Access-Control-Allow-Credentials": "true",
22
+ "Access-Control-Allow-Methods": "GET,OPTIONS,PATCH,DELETE,POST,PUT",
23
+ "Access-Control-Allow-Headers": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, Content-Type, Authorization"
24
+ }
25
+ }
26
+ ]
27
+ }
yarn.lock ADDED
@@ -0,0 +1,1419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
2
+ # yarn lockfile v1
3
+
4
+
5
+ "@esbuild/linux-x64@0.27.3":
6
+ version "0.27.3"
7
+ resolved "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.3.tgz"
8
+ integrity sha512-Czi8yzXUWIQYAtL/2y6vogER8pvcsOsk5cpwL4Gk5nJqH5UZiVByIY8Eorm5R13gq+DQKYg0+JyQoytLQas4dA==
9
+
10
+ "@hapi/bourne@^3.0.0":
11
+ version "3.0.0"
12
+ resolved "https://registry.npmjs.org/@hapi/bourne/-/bourne-3.0.0.tgz"
13
+ integrity sha512-Waj1cwPXJDucOib4a3bAISsKJVb15MKi9IvmTI/7ssVEm6sywXGjVJDhl6/umt1pK1ZS7PacXU3A1PmFKHEZ2w==
14
+
15
+ "@isaacs/cliui@^8.0.2":
16
+ version "8.0.2"
17
+ resolved "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz"
18
+ integrity sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==
19
+ dependencies:
20
+ string-width "^5.1.2"
21
+ string-width-cjs "npm:string-width@^4.2.0"
22
+ strip-ansi "^7.0.1"
23
+ strip-ansi-cjs "npm:strip-ansi@^6.0.1"
24
+ wrap-ansi "^8.1.0"
25
+ wrap-ansi-cjs "npm:wrap-ansi@^7.0.0"
26
+
27
+ "@jridgewell/gen-mapping@^0.3.2":
28
+ version "0.3.5"
29
+ resolved "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.5.tgz"
30
+ integrity sha512-IzL8ZoEDIBRWEzlCcRhOaCupYyN5gdIK+Q6fbFdPDg6HqX6jpkItn7DFIpW9LQzXG6Df9sA7+OKnq0qlz/GaQg==
31
+ dependencies:
32
+ "@jridgewell/set-array" "^1.2.1"
33
+ "@jridgewell/sourcemap-codec" "^1.4.10"
34
+ "@jridgewell/trace-mapping" "^0.3.24"
35
+
36
+ "@jridgewell/resolve-uri@^3.1.0":
37
+ version "3.1.2"
38
+ resolved "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz"
39
+ integrity sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==
40
+
41
+ "@jridgewell/set-array@^1.2.1":
42
+ version "1.2.1"
43
+ resolved "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.2.1.tgz"
44
+ integrity sha512-R8gLRTZeyp03ymzP/6Lil/28tGeGEzhx1q2k703KGWRAI1VdvPIXdG70VJc2pAMw3NA6JKL5hhFu1sJX0Mnn/A==
45
+
46
+ "@jridgewell/sourcemap-codec@^1.4.10", "@jridgewell/sourcemap-codec@^1.4.14", "@jridgewell/sourcemap-codec@^1.5.5":
47
+ version "1.5.5"
48
+ resolved "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz"
49
+ integrity sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==
50
+
51
+ "@jridgewell/trace-mapping@^0.3.24":
52
+ version "0.3.25"
53
+ resolved "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz"
54
+ integrity sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==
55
+ dependencies:
56
+ "@jridgewell/resolve-uri" "^3.1.0"
57
+ "@jridgewell/sourcemap-codec" "^1.4.14"
58
+
59
+ "@noble/hashes@^1.1.5":
60
+ version "1.8.0"
61
+ resolved "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz"
62
+ integrity sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==
63
+
64
+ "@paralleldrive/cuid2@^2.2.2":
65
+ version "2.3.1"
66
+ resolved "https://registry.npmjs.org/@paralleldrive/cuid2/-/cuid2-2.3.1.tgz"
67
+ integrity sha512-XO7cAxhnTZl0Yggq6jOgjiOHhbgcO4NqFqwSmQpjK3b6TEE6Uj/jfSk6wzYyemh3+I0sHirKSetjQwn5cZktFw==
68
+ dependencies:
69
+ "@noble/hashes" "^1.1.5"
70
+
71
+ "@pkgjs/parseargs@^0.11.0":
72
+ version "0.11.0"
73
+ resolved "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz"
74
+ integrity sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==
75
+
76
+ "@rollup/rollup-linux-x64-gnu@4.57.1":
77
+ version "4.57.1"
78
+ resolved "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.57.1.tgz"
79
+ integrity sha512-ABca4ceT4N+Tv/GtotnWAeXZUZuM/9AQyCyKYyKnpk4yoA7QIAuBt6Hkgpw8kActYlew2mvckXkvx0FfoInnLg==
80
+
81
+ "@rollup/rollup-linux-x64-musl@4.57.1":
82
+ version "4.57.1"
83
+ resolved "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.57.1.tgz"
84
+ integrity sha512-HFps0JeGtuOR2convgRRkHCekD7j+gdAuXM+/i6kGzQtFhlCtQkpwtNzkNj6QhCDp7DRJ7+qC/1Vg2jt5iSOFw==
85
+
86
+ "@types/estree@1.0.8":
87
+ version "1.0.8"
88
+ resolved "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz"
89
+ integrity sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==
90
+
91
+ "@types/formidable@^2.0.4":
92
+ version "2.0.6"
93
+ resolved "https://registry.npmjs.org/@types/formidable/-/formidable-2.0.6.tgz"
94
+ integrity sha512-L4HcrA05IgQyNYJj6kItuIkXrInJvsXTPC5B1i64FggWKKqSL+4hgt7asiSNva75AoLQjq29oPxFfU4GAQ6Z2w==
95
+ dependencies:
96
+ "@types/node" "*"
97
+
98
+ "@types/lodash@^4.14.202":
99
+ version "4.17.7"
100
+ resolved "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.7.tgz"
101
+ integrity sha512-8wTvZawATi/lsmNu10/j2hk1KEP0IvjubqPE3cu1Xz7xfXXt5oCq3SNUz4fMIP4XGF9Ky+Ue2tBA3hcS7LSBlA==
102
+
103
+ "@types/luxon@~3.4.0":
104
+ version "3.4.2"
105
+ resolved "https://registry.npmjs.org/@types/luxon/-/luxon-3.4.2.tgz"
106
+ integrity sha512-TifLZlFudklWlMBfhubvgqTXRzLDI5pCbGa4P8a3wPyUQSW+1xQ5eDsreP9DWHX3tjq1ke96uYG/nwundroWcA==
107
+
108
+ "@types/mime@^3.0.4":
109
+ version "3.0.4"
110
+ resolved "https://registry.npmjs.org/@types/mime/-/mime-3.0.4.tgz"
111
+ integrity sha512-iJt33IQnVRkqeqC7PzBHPTC6fDlRNRW8vjrgqtScAhrmMwe8c4Eo7+fUGTa+XdWrpEgpyKWMYmi2dIwMAYRzPw==
112
+
113
+ "@types/node@*":
114
+ version "20.14.12"
115
+ resolved "https://registry.npmjs.org/@types/node/-/node-20.14.12.tgz"
116
+ integrity sha512-r7wNXakLeSsGT0H1AU863vS2wa5wBOK4bWMjZz2wj+8nBx+m5PeIn0k8AloSLpRuiwdRQZwarZqHE4FNArPuJQ==
117
+ dependencies:
118
+ undici-types "~5.26.4"
119
+
120
+ accepts@^1.3.5:
121
+ version "1.3.8"
122
+ resolved "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz"
123
+ integrity sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==
124
+ dependencies:
125
+ mime-types "~2.1.34"
126
+ negotiator "0.6.3"
127
+
128
+ acorn@^8.15.0:
129
+ version "8.15.0"
130
+ resolved "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz"
131
+ integrity sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==
132
+
133
+ ansi-regex@^5.0.1:
134
+ version "5.0.1"
135
+ resolved "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz"
136
+ integrity sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==
137
+
138
+ ansi-regex@^6.0.1:
139
+ version "6.0.1"
140
+ resolved "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.0.1.tgz"
141
+ integrity sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA==
142
+
143
+ ansi-styles@^4.0.0:
144
+ version "4.3.0"
145
+ resolved "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz"
146
+ integrity sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==
147
+ dependencies:
148
+ color-convert "^2.0.1"
149
+
150
+ ansi-styles@^6.1.0:
151
+ version "6.2.1"
152
+ resolved "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz"
153
+ integrity sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==
154
+
155
+ any-promise@^1.0.0:
156
+ version "1.3.0"
157
+ resolved "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz"
158
+ integrity sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==
159
+
160
+ asap@^2.0.0:
161
+ version "2.0.6"
162
+ resolved "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz"
163
+ integrity sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==
164
+
165
+ asynckit@^0.4.0:
166
+ version "0.4.0"
167
+ resolved "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz"
168
+ integrity sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==
169
+
170
+ axios@^1.6.7:
171
+ version "1.13.4"
172
+ resolved "https://registry.npmjs.org/axios/-/axios-1.13.4.tgz"
173
+ integrity sha512-1wVkUaAO6WyaYtCkcYCOx12ZgpGf9Zif+qXa4n+oYzK558YryKqiL6UWwd5DqiH3VRW0GYhTZQ/vlgJrCoNQlg==
174
+ dependencies:
175
+ follow-redirects "^1.15.6"
176
+ form-data "^4.0.4"
177
+ proxy-from-env "^1.1.0"
178
+
179
+ balanced-match@^1.0.0:
180
+ version "1.0.2"
181
+ resolved "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz"
182
+ integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==
183
+
184
+ brace-expansion@^2.0.1:
185
+ version "2.0.2"
186
+ resolved "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz"
187
+ integrity sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==
188
+ dependencies:
189
+ balanced-match "^1.0.0"
190
+
191
+ bundle-require@^5.1.0:
192
+ version "5.1.0"
193
+ resolved "https://registry.npmjs.org/bundle-require/-/bundle-require-5.1.0.tgz"
194
+ integrity sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==
195
+ dependencies:
196
+ load-tsconfig "^0.2.3"
197
+
198
+ bytes@3.1.2:
199
+ version "3.1.2"
200
+ resolved "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz"
201
+ integrity sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==
202
+
203
+ cac@^6.7.14:
204
+ version "6.7.14"
205
+ resolved "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz"
206
+ integrity sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==
207
+
208
+ cache-content-type@^1.0.0:
209
+ version "1.0.1"
210
+ resolved "https://registry.npmjs.org/cache-content-type/-/cache-content-type-1.0.1.tgz"
211
+ integrity sha512-IKufZ1o4Ut42YUrZSo8+qnMTrFuKkvyoLXUywKz9GJ5BrhOFGhLdkx9sG4KAnVvbY6kEcSFjLQul+DVmBm2bgA==
212
+ dependencies:
213
+ mime-types "^2.1.18"
214
+ ylru "^1.2.0"
215
+
216
+ call-bind-apply-helpers@^1.0.1, call-bind-apply-helpers@^1.0.2:
217
+ version "1.0.2"
218
+ resolved "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz"
219
+ integrity sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==
220
+ dependencies:
221
+ es-errors "^1.3.0"
222
+ function-bind "^1.1.2"
223
+
224
+ call-bound@^1.0.2:
225
+ version "1.0.4"
226
+ resolved "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz"
227
+ integrity sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==
228
+ dependencies:
229
+ call-bind-apply-helpers "^1.0.2"
230
+ get-intrinsic "^1.3.0"
231
+
232
+ chokidar@^4.0.3:
233
+ version "4.0.3"
234
+ resolved "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz"
235
+ integrity sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==
236
+ dependencies:
237
+ readdirp "^4.0.1"
238
+
239
+ co-body@^5.1.1:
240
+ version "5.2.0"
241
+ resolved "https://registry.npmjs.org/co-body/-/co-body-5.2.0.tgz"
242
+ integrity sha512-sX/LQ7LqUhgyaxzbe7IqwPeTr2yfpfUIQ/dgpKo6ZI4y4lpQA0YxAomWIY+7I7rHWcG02PG+OuPREzMW/5tszQ==
243
+ dependencies:
244
+ inflation "^2.0.0"
245
+ qs "^6.4.0"
246
+ raw-body "^2.2.0"
247
+ type-is "^1.6.14"
248
+
249
+ co-body@^6.0.0:
250
+ version "6.2.0"
251
+ resolved "https://registry.npmjs.org/co-body/-/co-body-6.2.0.tgz"
252
+ integrity sha512-Kbpv2Yd1NdL1V/V4cwLVxraHDV6K8ayohr2rmH0J87Er8+zJjcTa6dAn9QMPC9CRgU8+aNajKbSf1TzDB1yKPA==
253
+ dependencies:
254
+ "@hapi/bourne" "^3.0.0"
255
+ inflation "^2.0.0"
256
+ qs "^6.5.2"
257
+ raw-body "^2.3.3"
258
+ type-is "^1.6.16"
259
+
260
+ co@^4.6.0:
261
+ version "4.6.0"
262
+ resolved "https://registry.npmjs.org/co/-/co-4.6.0.tgz"
263
+ integrity sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==
264
+
265
+ color-convert@^2.0.1:
266
+ version "2.0.1"
267
+ resolved "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz"
268
+ integrity sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==
269
+ dependencies:
270
+ color-name "~1.1.4"
271
+
272
+ color-name@~1.1.4:
273
+ version "1.1.4"
274
+ resolved "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz"
275
+ integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==
276
+
277
+ colors@^1.4.0:
278
+ version "1.4.0"
279
+ resolved "https://registry.npmjs.org/colors/-/colors-1.4.0.tgz"
280
+ integrity sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==
281
+
282
+ combined-stream@^1.0.8:
283
+ version "1.0.8"
284
+ resolved "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz"
285
+ integrity sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==
286
+ dependencies:
287
+ delayed-stream "~1.0.0"
288
+
289
+ commander@^4.0.0:
290
+ version "4.1.1"
291
+ resolved "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz"
292
+ integrity sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==
293
+
294
+ confbox@^0.1.8:
295
+ version "0.1.8"
296
+ resolved "https://registry.npmjs.org/confbox/-/confbox-0.1.8.tgz"
297
+ integrity sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==
298
+
299
+ consola@^3.4.0:
300
+ version "3.4.2"
301
+ resolved "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz"
302
+ integrity sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==
303
+
304
+ content-disposition@~0.5.2:
305
+ version "0.5.4"
306
+ resolved "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz"
307
+ integrity sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==
308
+ dependencies:
309
+ safe-buffer "5.2.1"
310
+
311
+ content-type@^1.0.4:
312
+ version "1.0.5"
313
+ resolved "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz"
314
+ integrity sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==
315
+
316
+ cookies@~0.9.0:
317
+ version "0.9.1"
318
+ resolved "https://registry.npmjs.org/cookies/-/cookies-0.9.1.tgz"
319
+ integrity sha512-TG2hpqe4ELx54QER/S3HQ9SRVnQnGBtKUz5bLQWtYAQ+o6GpgMs6sYUvaiJjVxb+UXwhRhAEP3m7LbsIZ77Hmw==
320
+ dependencies:
321
+ depd "~2.0.0"
322
+ keygrip "~1.1.0"
323
+
324
+ copy-to@^2.0.1:
325
+ version "2.0.1"
326
+ resolved "https://registry.npmjs.org/copy-to/-/copy-to-2.0.1.tgz"
327
+ integrity sha512-3DdaFaU/Zf1AnpLiFDeNCD4TOWe3Zl2RZaTzUvWiIk5ERzcCodOE20Vqq4fzCbNoHURFHT4/us/Lfq+S2zyY4w==
328
+
329
+ crc-32@^1.2.2:
330
+ version "1.2.2"
331
+ resolved "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz"
332
+ integrity sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==
333
+
334
+ cron@^3.1.6:
335
+ version "3.1.7"
336
+ resolved "https://registry.npmjs.org/cron/-/cron-3.1.7.tgz"
337
+ integrity sha512-tlBg7ARsAMQLzgwqVxy8AZl/qlTc5nibqYwtNGoCrd+cV+ugI+tvZC1oT/8dFH8W455YrywGykx/KMmAqOr7Jw==
338
+ dependencies:
339
+ "@types/luxon" "~3.4.0"
340
+ luxon "~3.4.0"
341
+
342
+ cross-spawn@^7.0.0:
343
+ version "7.0.6"
344
+ resolved "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz"
345
+ integrity sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==
346
+ dependencies:
347
+ path-key "^3.1.0"
348
+ shebang-command "^2.0.0"
349
+ which "^2.0.1"
350
+
351
+ date-fns@^3.3.1:
352
+ version "3.6.0"
353
+ resolved "https://registry.npmjs.org/date-fns/-/date-fns-3.6.0.tgz"
354
+ integrity sha512-fRHTG8g/Gif+kSh50gaGEdToemgfj74aRX3swtiouboip5JDLAyDE9F11nHMIcvOaXeOC6D7SpNhi7uFyB7Uww==
355
+
356
+ debug@^4.3.2, debug@^4.3.4, debug@^4.4.0:
357
+ version "4.4.3"
358
+ resolved "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz"
359
+ integrity sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==
360
+ dependencies:
361
+ ms "^2.1.3"
362
+
363
+ deep-equal@~1.0.1:
364
+ version "1.0.1"
365
+ resolved "https://registry.npmjs.org/deep-equal/-/deep-equal-1.0.1.tgz"
366
+ integrity sha512-bHtC0iYvWhyaTzvV3CZgPeZQqCOBGyGsVV7v4eevpdkLHfiSrXUdBG+qAuSz4RI70sszvjQ1QSZ98An1yNwpSw==
367
+
368
+ delayed-stream@~1.0.0:
369
+ version "1.0.0"
370
+ resolved "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz"
371
+ integrity sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==
372
+
373
+ delegates@^1.0.0:
374
+ version "1.0.0"
375
+ resolved "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz"
376
+ integrity sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ==
377
+
378
+ depd@^2.0.0, depd@~2.0.0, depd@2.0.0:
379
+ version "2.0.0"
380
+ resolved "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz"
381
+ integrity sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==
382
+
383
+ depd@~1.1.2:
384
+ version "1.1.2"
385
+ resolved "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz"
386
+ integrity sha512-7emPTl6Dpo6JRXOXjLRxck+FlLRX5847cLKEn00PLAgc3g2hTZZgr+e4c2v6QpSmLeFP3n5yUo7ft6avBK/5jQ==
387
+
388
+ destroy@^1.0.4:
389
+ version "1.2.0"
390
+ resolved "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz"
391
+ integrity sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==
392
+
393
+ dezalgo@^1.0.4:
394
+ version "1.0.4"
395
+ resolved "https://registry.npmjs.org/dezalgo/-/dezalgo-1.0.4.tgz"
396
+ integrity sha512-rXSP0bf+5n0Qonsb+SVVfNfIsimO4HEtmnIpPHY8Q1UCzKlQrDMfdobr8nJOOsRgWCyMRqeSBQzmWUMq7zvVig==
397
+ dependencies:
398
+ asap "^2.0.0"
399
+ wrappy "1"
400
+
401
+ dunder-proto@^1.0.1:
402
+ version "1.0.1"
403
+ resolved "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz"
404
+ integrity sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==
405
+ dependencies:
406
+ call-bind-apply-helpers "^1.0.1"
407
+ es-errors "^1.3.0"
408
+ gopd "^1.2.0"
409
+
410
+ eastasianwidth@^0.2.0:
411
+ version "0.2.0"
412
+ resolved "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz"
413
+ integrity sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==
414
+
415
+ ee-first@1.1.1:
416
+ version "1.1.1"
417
+ resolved "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz"
418
+ integrity sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==
419
+
420
+ emoji-regex@^8.0.0:
421
+ version "8.0.0"
422
+ resolved "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz"
423
+ integrity sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==
424
+
425
+ emoji-regex@^9.2.2:
426
+ version "9.2.2"
427
+ resolved "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz"
428
+ integrity sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==
429
+
430
+ encodeurl@^1.0.2:
431
+ version "1.0.2"
432
+ resolved "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz"
433
+ integrity sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==
434
+
435
+ es-define-property@^1.0.1:
436
+ version "1.0.1"
437
+ resolved "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz"
438
+ integrity sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==
439
+
440
+ es-errors@^1.3.0:
441
+ version "1.3.0"
442
+ resolved "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz"
443
+ integrity sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==
444
+
445
+ es-object-atoms@^1.0.0, es-object-atoms@^1.1.1:
446
+ version "1.1.1"
447
+ resolved "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz"
448
+ integrity sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==
449
+ dependencies:
450
+ es-errors "^1.3.0"
451
+
452
+ es-set-tostringtag@^2.1.0:
453
+ version "2.1.0"
454
+ resolved "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz"
455
+ integrity sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==
456
+ dependencies:
457
+ es-errors "^1.3.0"
458
+ get-intrinsic "^1.2.6"
459
+ has-tostringtag "^1.0.2"
460
+ hasown "^2.0.2"
461
+
462
+ esbuild@^0.27.0, esbuild@>=0.18:
463
+ version "0.27.3"
464
+ resolved "https://registry.npmjs.org/esbuild/-/esbuild-0.27.3.tgz"
465
+ integrity sha512-8VwMnyGCONIs6cWue2IdpHxHnAjzxnw2Zr7MkVxB2vjmQ2ivqGFb4LEG3SMnv0Gb2F/G/2yA8zUaiL1gywDCCg==
466
+ optionalDependencies:
467
+ "@esbuild/aix-ppc64" "0.27.3"
468
+ "@esbuild/android-arm" "0.27.3"
469
+ "@esbuild/android-arm64" "0.27.3"
470
+ "@esbuild/android-x64" "0.27.3"
471
+ "@esbuild/darwin-arm64" "0.27.3"
472
+ "@esbuild/darwin-x64" "0.27.3"
473
+ "@esbuild/freebsd-arm64" "0.27.3"
474
+ "@esbuild/freebsd-x64" "0.27.3"
475
+ "@esbuild/linux-arm" "0.27.3"
476
+ "@esbuild/linux-arm64" "0.27.3"
477
+ "@esbuild/linux-ia32" "0.27.3"
478
+ "@esbuild/linux-loong64" "0.27.3"
479
+ "@esbuild/linux-mips64el" "0.27.3"
480
+ "@esbuild/linux-ppc64" "0.27.3"
481
+ "@esbuild/linux-riscv64" "0.27.3"
482
+ "@esbuild/linux-s390x" "0.27.3"
483
+ "@esbuild/linux-x64" "0.27.3"
484
+ "@esbuild/netbsd-arm64" "0.27.3"
485
+ "@esbuild/netbsd-x64" "0.27.3"
486
+ "@esbuild/openbsd-arm64" "0.27.3"
487
+ "@esbuild/openbsd-x64" "0.27.3"
488
+ "@esbuild/openharmony-arm64" "0.27.3"
489
+ "@esbuild/sunos-x64" "0.27.3"
490
+ "@esbuild/win32-arm64" "0.27.3"
491
+ "@esbuild/win32-ia32" "0.27.3"
492
+ "@esbuild/win32-x64" "0.27.3"
493
+
494
+ escape-html@^1.0.3:
495
+ version "1.0.3"
496
+ resolved "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz"
497
+ integrity sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==
498
+
499
+ eventsource-parser@^1.1.2:
500
+ version "1.1.2"
501
+ resolved "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-1.1.2.tgz"
502
+ integrity sha512-v0eOBUbiaFojBu2s2NPBfYUoRR9GjcDNvCXVaqEf5vVfpIAh9f8RCo4vXTP8c63QRKCFwoLpMpTdPwwhEKVgzA==
503
+
504
+ fdir@^6.5.0:
505
+ version "6.5.0"
506
+ resolved "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz"
507
+ integrity sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==
508
+
509
+ fix-dts-default-cjs-exports@^1.0.0:
510
+ version "1.0.1"
511
+ resolved "https://registry.npmjs.org/fix-dts-default-cjs-exports/-/fix-dts-default-cjs-exports-1.0.1.tgz"
512
+ integrity sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg==
513
+ dependencies:
514
+ magic-string "^0.30.17"
515
+ mlly "^1.7.4"
516
+ rollup "^4.34.8"
517
+
518
+ follow-redirects@^1.15.6:
519
+ version "1.15.6"
520
+ resolved "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.6.tgz"
521
+ integrity sha512-wWN62YITEaOpSK584EZXJafH1AGpO8RVgElfkuXbTOrPX4fIfOyEpW/CsiNd8JdYrAoOvafRTOEnvsO++qCqFA==
522
+
523
+ foreground-child@^3.1.0:
524
+ version "3.2.1"
525
+ resolved "https://registry.npmjs.org/foreground-child/-/foreground-child-3.2.1.tgz"
526
+ integrity sha512-PXUUyLqrR2XCWICfv6ukppP96sdFwWbNEnfEMt7jNsISjMsvaLNinAHNDYyvkyU+SZG2BTSbT5NjG+vZslfGTA==
527
+ dependencies:
528
+ cross-spawn "^7.0.0"
529
+ signal-exit "^4.0.1"
530
+
531
+ form-data@^4.0.0, form-data@^4.0.4:
532
+ version "4.0.5"
533
+ resolved "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz"
534
+ integrity sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==
535
+ dependencies:
536
+ asynckit "^0.4.0"
537
+ combined-stream "^1.0.8"
538
+ es-set-tostringtag "^2.1.0"
539
+ hasown "^2.0.2"
540
+ mime-types "^2.1.12"
541
+
542
+ formidable@^2.0.1:
543
+ version "2.1.5"
544
+ resolved "https://registry.npmjs.org/formidable/-/formidable-2.1.5.tgz"
545
+ integrity sha512-Oz5Hwvwak/DCaXVVUtPn4oLMLLy1CdclLKO1LFgU7XzDpVMUU5UjlSLpGMocyQNNk8F6IJW9M/YdooSn2MRI+Q==
546
+ dependencies:
547
+ "@paralleldrive/cuid2" "^2.2.2"
548
+ dezalgo "^1.0.4"
549
+ once "^1.4.0"
550
+ qs "^6.11.0"
551
+
552
+ fresh@~0.5.2:
553
+ version "0.5.2"
554
+ resolved "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz"
555
+ integrity sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==
556
+
557
+ fs-extra@^11.2.0:
558
+ version "11.2.0"
559
+ resolved "https://registry.npmjs.org/fs-extra/-/fs-extra-11.2.0.tgz"
560
+ integrity sha512-PmDi3uwK5nFuXh7XDTlVnS17xJS7vW36is2+w3xcv8SVxiB4NyATf4ctkVY5bkSjX0Y4nbvZCq1/EjtEyr9ktw==
561
+ dependencies:
562
+ graceful-fs "^4.2.0"
563
+ jsonfile "^6.0.1"
564
+ universalify "^2.0.0"
565
+
566
+ function-bind@^1.1.2:
567
+ version "1.1.2"
568
+ resolved "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz"
569
+ integrity sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==
570
+
571
+ get-intrinsic@^1.2.5, get-intrinsic@^1.2.6, get-intrinsic@^1.3.0:
572
+ version "1.3.0"
573
+ resolved "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz"
574
+ integrity sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==
575
+ dependencies:
576
+ call-bind-apply-helpers "^1.0.2"
577
+ es-define-property "^1.0.1"
578
+ es-errors "^1.3.0"
579
+ es-object-atoms "^1.1.1"
580
+ function-bind "^1.1.2"
581
+ get-proto "^1.0.1"
582
+ gopd "^1.2.0"
583
+ has-symbols "^1.1.0"
584
+ hasown "^2.0.2"
585
+ math-intrinsics "^1.1.0"
586
+
587
+ get-proto@^1.0.1:
588
+ version "1.0.1"
589
+ resolved "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz"
590
+ integrity sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==
591
+ dependencies:
592
+ dunder-proto "^1.0.1"
593
+ es-object-atoms "^1.0.0"
594
+
595
+ glob@^10.3.10:
596
+ version "10.5.0"
597
+ resolved "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz"
598
+ integrity sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==
599
+ dependencies:
600
+ foreground-child "^3.1.0"
601
+ jackspeak "^3.1.2"
602
+ minimatch "^9.0.4"
603
+ minipass "^7.1.2"
604
+ package-json-from-dist "^1.0.0"
605
+ path-scurry "^1.11.1"
606
+
607
+ gopd@^1.2.0:
608
+ version "1.2.0"
609
+ resolved "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz"
610
+ integrity sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==
611
+
612
+ graceful-fs@^4.1.6, graceful-fs@^4.2.0:
613
+ version "4.2.11"
614
+ resolved "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz"
615
+ integrity sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==
616
+
617
+ has-symbols@^1.0.3, has-symbols@^1.1.0:
618
+ version "1.1.0"
619
+ resolved "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz"
620
+ integrity sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==
621
+
622
+ has-tostringtag@^1.0.0, has-tostringtag@^1.0.2:
623
+ version "1.0.2"
624
+ resolved "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz"
625
+ integrity sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==
626
+ dependencies:
627
+ has-symbols "^1.0.3"
628
+
629
+ hasown@^2.0.2:
630
+ version "2.0.2"
631
+ resolved "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz"
632
+ integrity sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==
633
+ dependencies:
634
+ function-bind "^1.1.2"
635
+
636
+ http-assert@^1.3.0:
637
+ version "1.5.0"
638
+ resolved "https://registry.npmjs.org/http-assert/-/http-assert-1.5.0.tgz"
639
+ integrity sha512-uPpH7OKX4H25hBmU6G1jWNaqJGpTXxey+YOUizJUAgu0AjLUeC8D73hTrhvDS5D+GJN1DN1+hhc/eF/wpxtp0w==
640
+ dependencies:
641
+ deep-equal "~1.0.1"
642
+ http-errors "~1.8.0"
643
+
644
+ http-errors@^1.6.3, http-errors@~1.8.0:
645
+ version "1.8.1"
646
+ resolved "https://registry.npmjs.org/http-errors/-/http-errors-1.8.1.tgz"
647
+ integrity sha512-Kpk9Sm7NmI+RHhnj6OIWDI1d6fIoFAtFt9RLaTMRlg/8w49juAStsrBgp0Dp4OdxdVbRIeKhtCUvoi/RuAhO4g==
648
+ dependencies:
649
+ depd "~1.1.2"
650
+ inherits "2.0.4"
651
+ setprototypeof "1.2.0"
652
+ statuses ">= 1.5.0 < 2"
653
+ toidentifier "1.0.1"
654
+
655
+ http-errors@^2.0.0:
656
+ version "2.0.0"
657
+ resolved "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz"
658
+ integrity sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==
659
+ dependencies:
660
+ depd "2.0.0"
661
+ inherits "2.0.4"
662
+ setprototypeof "1.2.0"
663
+ statuses "2.0.1"
664
+ toidentifier "1.0.1"
665
+
666
+ http-errors@2.0.0:
667
+ version "2.0.0"
668
+ resolved "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz"
669
+ integrity sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==
670
+ dependencies:
671
+ depd "2.0.0"
672
+ inherits "2.0.4"
673
+ setprototypeof "1.2.0"
674
+ statuses "2.0.1"
675
+ toidentifier "1.0.1"
676
+
677
+ iconv-lite@0.4.24:
678
+ version "0.4.24"
679
+ resolved "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz"
680
+ integrity sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==
681
+ dependencies:
682
+ safer-buffer ">= 2.1.2 < 3"
683
+
684
+ inflation@^2.0.0:
685
+ version "2.1.0"
686
+ resolved "https://registry.npmjs.org/inflation/-/inflation-2.1.0.tgz"
687
+ integrity sha512-t54PPJHG1Pp7VQvxyVCJ9mBbjG3Hqryges9bXoOO6GExCPa+//i/d5GSuFtpx3ALLd7lgIAur6zrIlBQyJuMlQ==
688
+
689
+ inherits@2.0.4:
690
+ version "2.0.4"
691
+ resolved "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz"
692
+ integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==
693
+
694
+ is-fullwidth-code-point@^3.0.0:
695
+ version "3.0.0"
696
+ resolved "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz"
697
+ integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==
698
+
699
+ is-generator-function@^1.0.7:
700
+ version "1.0.10"
701
+ resolved "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.0.10.tgz"
702
+ integrity sha512-jsEjy9l3yiXEQ+PsXdmBwEPcOxaXWLspKdplFUVI9vq1iZgIekeC0L167qeu86czQaxed3q/Uzuw0swL0irL8A==
703
+ dependencies:
704
+ has-tostringtag "^1.0.0"
705
+
706
+ isexe@^2.0.0:
707
+ version "2.0.0"
708
+ resolved "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz"
709
+ integrity sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==
710
+
711
+ jackspeak@^3.1.2:
712
+ version "3.4.3"
713
+ resolved "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz"
714
+ integrity sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==
715
+ dependencies:
716
+ "@isaacs/cliui" "^8.0.2"
717
+ optionalDependencies:
718
+ "@pkgjs/parseargs" "^0.11.0"
719
+
720
+ joycon@^3.1.1:
721
+ version "3.1.1"
722
+ resolved "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz"
723
+ integrity sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==
724
+
725
+ jsonfile@^6.0.1:
726
+ version "6.1.0"
727
+ resolved "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz"
728
+ integrity sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==
729
+ dependencies:
730
+ universalify "^2.0.0"
731
+ optionalDependencies:
732
+ graceful-fs "^4.1.6"
733
+
734
+ keygrip@~1.1.0:
735
+ version "1.1.0"
736
+ resolved "https://registry.npmjs.org/keygrip/-/keygrip-1.1.0.tgz"
737
+ integrity sha512-iYSchDJ+liQ8iwbSI2QqsQOvqv58eJCEanyJPJi+Khyu8smkcKSFUCbPwzFcL7YVtZ6eONjqRX/38caJ7QjRAQ==
738
+ dependencies:
739
+ tsscmp "1.0.6"
740
+
741
+ koa-body@^5.0.0:
742
+ version "5.0.0"
743
+ resolved "https://registry.npmjs.org/koa-body/-/koa-body-5.0.0.tgz"
744
+ integrity sha512-nHwEODrQGiyKBILCWO8QSS40C87cKr2cp3y/Cw8u9Z8w5t0CdSkGm3+y9WK5BIAlPpo9tTw5RtSbxpVyG79vmw==
745
+ dependencies:
746
+ "@types/formidable" "^2.0.4"
747
+ co-body "^5.1.1"
748
+ formidable "^2.0.1"
749
+
750
+ koa-bodyparser@^4.4.1:
751
+ version "4.4.1"
752
+ resolved "https://registry.npmjs.org/koa-bodyparser/-/koa-bodyparser-4.4.1.tgz"
753
+ integrity sha512-kBH3IYPMb+iAXnrxIhXnW+gXV8OTzCu8VPDqvcDHW9SQrbkHmqPQtiZwrltNmSq6/lpipHnT7k7PsjlVD7kK0w==
754
+ dependencies:
755
+ co-body "^6.0.0"
756
+ copy-to "^2.0.1"
757
+ type-is "^1.6.18"
758
+
759
+ koa-compose@^4.1.0:
760
+ version "4.1.0"
761
+ resolved "https://registry.npmjs.org/koa-compose/-/koa-compose-4.1.0.tgz"
762
+ integrity sha512-8ODW8TrDuMYvXRwra/Kh7/rJo9BtOfPc6qO8eAfC80CnCvSjSl0bkRM24X6/XBBEyj0v1nRUQ1LyOy3dbqOWXw==
763
+
764
+ koa-convert@^2.0.0:
765
+ version "2.0.0"
766
+ resolved "https://registry.npmjs.org/koa-convert/-/koa-convert-2.0.0.tgz"
767
+ integrity sha512-asOvN6bFlSnxewce2e/DK3p4tltyfC4VM7ZwuTuepI7dEQVcvpyFuBcEARu1+Hxg8DIwytce2n7jrZtRlPrARA==
768
+ dependencies:
769
+ co "^4.6.0"
770
+ koa-compose "^4.1.0"
771
+
772
+ koa-range@^0.3.0:
773
+ version "0.3.0"
774
+ resolved "https://registry.npmjs.org/koa-range/-/koa-range-0.3.0.tgz"
775
+ integrity sha512-Ich3pCz6RhtbajYXRWjIl6O5wtrLs6kE3nkXc9XmaWe+MysJyZO7K4L3oce1Jpg/iMgCbj+5UCiMm/rqVtcDIg==
776
+ dependencies:
777
+ stream-slice "^0.1.2"
778
+
779
+ koa-router@^12.0.1:
780
+ version "12.0.1"
781
+ resolved "https://registry.npmjs.org/koa-router/-/koa-router-12.0.1.tgz"
782
+ integrity sha512-gaDdj3GtzoLoeosacd50kBBTnnh3B9AYxDThQUo4sfUyXdOhY6ku1qyZKW88tQCRgc3Sw6ChXYXWZwwgjOxE0w==
783
+ dependencies:
784
+ debug "^4.3.4"
785
+ http-errors "^2.0.0"
786
+ koa-compose "^4.1.0"
787
+ methods "^1.1.2"
788
+ path-to-regexp "^6.2.1"
789
+
790
+ koa@^2.15.0:
791
+ version "2.16.3"
792
+ resolved "https://registry.npmjs.org/koa/-/koa-2.16.3.tgz"
793
+ integrity sha512-zPPuIt+ku1iCpFBRwseMcPYQ1cJL8l60rSmKeOuGfOXyE6YnTBmf2aEFNL2HQGrD0cPcLO/t+v9RTgC+fwEh/g==
794
+ dependencies:
795
+ accepts "^1.3.5"
796
+ cache-content-type "^1.0.0"
797
+ content-disposition "~0.5.2"
798
+ content-type "^1.0.4"
799
+ cookies "~0.9.0"
800
+ debug "^4.3.2"
801
+ delegates "^1.0.0"
802
+ depd "^2.0.0"
803
+ destroy "^1.0.4"
804
+ encodeurl "^1.0.2"
805
+ escape-html "^1.0.3"
806
+ fresh "~0.5.2"
807
+ http-assert "^1.3.0"
808
+ http-errors "^1.6.3"
809
+ is-generator-function "^1.0.7"
810
+ koa-compose "^4.1.0"
811
+ koa-convert "^2.0.0"
812
+ on-finished "^2.3.0"
813
+ only "~0.0.2"
814
+ parseurl "^1.3.2"
815
+ statuses "^1.5.0"
816
+ type-is "^1.6.16"
817
+ vary "^1.1.2"
818
+
819
+ koa2-cors@^2.0.6:
820
+ version "2.0.6"
821
+ resolved "https://registry.npmjs.org/koa2-cors/-/koa2-cors-2.0.6.tgz"
822
+ integrity sha512-JRCcSM4lamM+8kvKGDKlesYk2ASrmSTczDtGUnIadqMgnHU4Ct5Gw7Bxt3w3m6d6dy3WN0PU4oMP43HbddDEWg==
823
+
824
+ lilconfig@^3.1.1:
825
+ version "3.1.2"
826
+ resolved "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.2.tgz"
827
+ integrity sha512-eop+wDAvpItUys0FWkHIKeC9ybYrTGbU41U5K7+bttZZeohvnY7M9dZ5kB21GNWiFT2q1OoPTvncPCgSOVO5ow==
828
+
829
+ lines-and-columns@^1.1.6:
830
+ version "1.2.4"
831
+ resolved "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz"
832
+ integrity sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==
833
+
834
+ load-tsconfig@^0.2.3:
835
+ version "0.2.5"
836
+ resolved "https://registry.npmjs.org/load-tsconfig/-/load-tsconfig-0.2.5.tgz"
837
+ integrity sha512-IXO6OCs9yg8tMKzfPZ1YmheJbZCiEsnBdcB03l0OcfK9prKnJb96siuHCr5Fl37/yo9DnKU+TLpxzTUspw9shg==
838
+
839
+ lodash@^4.17.21:
840
+ version "4.17.23"
841
+ resolved "https://registry.npmjs.org/lodash/-/lodash-4.17.23.tgz"
842
+ integrity sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==
843
+
844
+ lru-cache@^10.2.0:
845
+ version "10.4.3"
846
+ resolved "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz"
847
+ integrity sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==
848
+
849
+ luxon@~3.4.0:
850
+ version "3.4.4"
851
+ resolved "https://registry.npmjs.org/luxon/-/luxon-3.4.4.tgz"
852
+ integrity sha512-zobTr7akeGHnv7eBOXcRgMeCP6+uyYsczwmeRCauvpvaAltgNyTbLH/+VaEAPUeWBT+1GuNmz4wC/6jtQzbbVA==
853
+
854
+ magic-string@^0.30.17:
855
+ version "0.30.21"
856
+ resolved "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz"
857
+ integrity sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==
858
+ dependencies:
859
+ "@jridgewell/sourcemap-codec" "^1.5.5"
860
+
861
+ math-intrinsics@^1.1.0:
862
+ version "1.1.0"
863
+ resolved "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz"
864
+ integrity sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==
865
+
866
+ media-typer@0.3.0:
867
+ version "0.3.0"
868
+ resolved "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz"
869
+ integrity sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==
870
+
871
+ methods@^1.1.2:
872
+ version "1.1.2"
873
+ resolved "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz"
874
+ integrity sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==
875
+
876
+ mime-db@1.52.0:
877
+ version "1.52.0"
878
+ resolved "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz"
879
+ integrity sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==
880
+
881
+ mime-types@^2.1.12, mime-types@^2.1.18, mime-types@~2.1.24, mime-types@~2.1.34:
882
+ version "2.1.35"
883
+ resolved "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz"
884
+ integrity sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==
885
+ dependencies:
886
+ mime-db "1.52.0"
887
+
888
+ mime@^4.0.1:
889
+ version "4.0.4"
890
+ resolved "https://registry.npmjs.org/mime/-/mime-4.0.4.tgz"
891
+ integrity sha512-v8yqInVjhXyqP6+Kw4fV3ZzeMRqEW6FotRsKXjRS5VMTNIuXsdRoAvklpoRgSqXm6o9VNH4/C0mgedko9DdLsQ==
892
+
893
+ minimatch@^9.0.4:
894
+ version "9.0.5"
895
+ resolved "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz"
896
+ integrity sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==
897
+ dependencies:
898
+ brace-expansion "^2.0.1"
899
+
900
+ minimist@^1.2.8:
901
+ version "1.2.8"
902
+ resolved "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz"
903
+ integrity sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==
904
+
905
+ "minipass@^5.0.0 || ^6.0.2 || ^7.0.0", minipass@^7.1.2:
906
+ version "7.1.2"
907
+ resolved "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz"
908
+ integrity sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==
909
+
910
+ mlly@^1.7.4:
911
+ version "1.8.0"
912
+ resolved "https://registry.npmjs.org/mlly/-/mlly-1.8.0.tgz"
913
+ integrity sha512-l8D9ODSRWLe2KHJSifWGwBqpTZXIXTeo8mlKjY+E2HAakaTeNpqAyBZ8GSqLzHgw4XmHmC8whvpjJNMbFZN7/g==
914
+ dependencies:
915
+ acorn "^8.15.0"
916
+ pathe "^2.0.3"
917
+ pkg-types "^1.3.1"
918
+ ufo "^1.6.1"
919
+
920
+ ms@^2.1.3:
921
+ version "2.1.3"
922
+ resolved "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz"
923
+ integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==
924
+
925
+ mz@^2.7.0:
926
+ version "2.7.0"
927
+ resolved "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz"
928
+ integrity sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==
929
+ dependencies:
930
+ any-promise "^1.0.0"
931
+ object-assign "^4.0.1"
932
+ thenify-all "^1.0.0"
933
+
934
+ negotiator@0.6.3:
935
+ version "0.6.3"
936
+ resolved "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz"
937
+ integrity sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==
938
+
939
+ object-assign@^4.0.1:
940
+ version "4.1.1"
941
+ resolved "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz"
942
+ integrity sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==
943
+
944
+ object-inspect@^1.13.3:
945
+ version "1.13.4"
946
+ resolved "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz"
947
+ integrity sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==
948
+
949
+ on-finished@^2.3.0:
950
+ version "2.4.1"
951
+ resolved "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz"
952
+ integrity sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==
953
+ dependencies:
954
+ ee-first "1.1.1"
955
+
956
+ once@^1.4.0:
957
+ version "1.4.0"
958
+ resolved "https://registry.npmjs.org/once/-/once-1.4.0.tgz"
959
+ integrity sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==
960
+ dependencies:
961
+ wrappy "1"
962
+
963
+ only@~0.0.2:
964
+ version "0.0.2"
965
+ resolved "https://registry.npmjs.org/only/-/only-0.0.2.tgz"
966
+ integrity sha512-Fvw+Jemq5fjjyWz6CpKx6w9s7xxqo3+JCyM0WXWeCSOboZ8ABkyvP8ID4CZuChA/wxSx+XSJmdOm8rGVyJ1hdQ==
967
+
968
+ package-json-from-dist@^1.0.0:
969
+ version "1.0.0"
970
+ resolved "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.0.tgz"
971
+ integrity sha512-dATvCeZN/8wQsGywez1mzHtTlP22H8OEfPrVMLNr4/eGa+ijtLn/6M5f0dY8UKNrC2O9UCU6SSoG3qRKnt7STw==
972
+
973
+ parseurl@^1.3.2:
974
+ version "1.3.3"
975
+ resolved "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz"
976
+ integrity sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==
977
+
978
+ path-key@^3.1.0:
979
+ version "3.1.1"
980
+ resolved "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz"
981
+ integrity sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==
982
+
983
+ path-scurry@^1.11.1:
984
+ version "1.11.1"
985
+ resolved "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz"
986
+ integrity sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==
987
+ dependencies:
988
+ lru-cache "^10.2.0"
989
+ minipass "^5.0.0 || ^6.0.2 || ^7.0.0"
990
+
991
+ path-to-regexp@^6.2.1:
992
+ version "6.3.0"
993
+ resolved "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-6.3.0.tgz"
994
+ integrity sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==
995
+
996
+ pathe@^2.0.1, pathe@^2.0.3:
997
+ version "2.0.3"
998
+ resolved "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz"
999
+ integrity sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==
1000
+
1001
+ picocolors@^1.1.1:
1002
+ version "1.1.1"
1003
+ resolved "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz"
1004
+ integrity sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==
1005
+
1006
+ "picomatch@^3 || ^4", picomatch@^4.0.3:
1007
+ version "4.0.3"
1008
+ resolved "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz"
1009
+ integrity sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==
1010
+
1011
+ pirates@^4.0.1:
1012
+ version "4.0.6"
1013
+ resolved "https://registry.npmjs.org/pirates/-/pirates-4.0.6.tgz"
1014
+ integrity sha512-saLsH7WeYYPiD25LDuLRRY/i+6HaPYr6G1OUlN39otzkSTxKnubR9RTxS3/Kk50s1g2JTgFwWQDQyplC5/SHZg==
1015
+
1016
+ pkg-types@^1.3.1:
1017
+ version "1.3.1"
1018
+ resolved "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz"
1019
+ integrity sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==
1020
+ dependencies:
1021
+ confbox "^0.1.8"
1022
+ mlly "^1.7.4"
1023
+ pathe "^2.0.1"
1024
+
1025
+ postcss-load-config@^6.0.1:
1026
+ version "6.0.1"
1027
+ resolved "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-6.0.1.tgz"
1028
+ integrity sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==
1029
+ dependencies:
1030
+ lilconfig "^3.1.1"
1031
+
1032
+ proxy-from-env@^1.1.0:
1033
+ version "1.1.0"
1034
+ resolved "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz"
1035
+ integrity sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==
1036
+
1037
+ qs@^6.11.0, qs@^6.4.0, qs@^6.5.2:
1038
+ version "6.14.1"
1039
+ resolved "https://registry.npmjs.org/qs/-/qs-6.14.1.tgz"
1040
+ integrity sha512-4EK3+xJl8Ts67nLYNwqw/dsFVnCf+qR7RgXSK9jEEm9unao3njwMDdmsdvoKBKHzxd7tCYz5e5M+SnMjdtXGQQ==
1041
+ dependencies:
1042
+ side-channel "^1.1.0"
1043
+
1044
+ randombytes@2.0.3:
1045
+ version "2.0.3"
1046
+ resolved "https://registry.npmjs.org/randombytes/-/randombytes-2.0.3.tgz"
1047
+ integrity sha512-lDVjxQQFoCG1jcrP06LNo2lbWp4QTShEXnhActFBwYuHprllQV6VUpwreApsYqCgD+N1mHoqJ/BI/4eV4R2GYg==
1048
+
1049
+ randomstring@^1.3.0:
1050
+ version "1.3.0"
1051
+ resolved "https://registry.npmjs.org/randomstring/-/randomstring-1.3.0.tgz"
1052
+ integrity sha512-gY7aQ4i1BgwZ8I1Op4YseITAyiDiajeZOPQUbIq9TPGPhUm5FX59izIaOpmKbME1nmnEiABf28d9K2VSii6BBg==
1053
+ dependencies:
1054
+ randombytes "2.0.3"
1055
+
1056
+ raw-body@^2.2.0, raw-body@^2.3.3:
1057
+ version "2.5.2"
1058
+ resolved "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz"
1059
+ integrity sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==
1060
+ dependencies:
1061
+ bytes "3.1.2"
1062
+ http-errors "2.0.0"
1063
+ iconv-lite "0.4.24"
1064
+ unpipe "1.0.0"
1065
+
1066
+ readdirp@^4.0.1:
1067
+ version "4.1.2"
1068
+ resolved "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz"
1069
+ integrity sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==
1070
+
1071
+ resolve-from@^5.0.0:
1072
+ version "5.0.0"
1073
+ resolved "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz"
1074
+ integrity sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==
1075
+
1076
+ rollup@^4.34.8:
1077
+ version "4.57.1"
1078
+ resolved "https://registry.npmjs.org/rollup/-/rollup-4.57.1.tgz"
1079
+ integrity sha512-oQL6lgK3e2QZeQ7gcgIkS2YZPg5slw37hYufJ3edKlfQSGGm8ICoxswK15ntSzF/a8+h7ekRy7k7oWc3BQ7y8A==
1080
+ dependencies:
1081
+ "@types/estree" "1.0.8"
1082
+ optionalDependencies:
1083
+ "@rollup/rollup-android-arm-eabi" "4.57.1"
1084
+ "@rollup/rollup-android-arm64" "4.57.1"
1085
+ "@rollup/rollup-darwin-arm64" "4.57.1"
1086
+ "@rollup/rollup-darwin-x64" "4.57.1"
1087
+ "@rollup/rollup-freebsd-arm64" "4.57.1"
1088
+ "@rollup/rollup-freebsd-x64" "4.57.1"
1089
+ "@rollup/rollup-linux-arm-gnueabihf" "4.57.1"
1090
+ "@rollup/rollup-linux-arm-musleabihf" "4.57.1"
1091
+ "@rollup/rollup-linux-arm64-gnu" "4.57.1"
1092
+ "@rollup/rollup-linux-arm64-musl" "4.57.1"
1093
+ "@rollup/rollup-linux-loong64-gnu" "4.57.1"
1094
+ "@rollup/rollup-linux-loong64-musl" "4.57.1"
1095
+ "@rollup/rollup-linux-ppc64-gnu" "4.57.1"
1096
+ "@rollup/rollup-linux-ppc64-musl" "4.57.1"
1097
+ "@rollup/rollup-linux-riscv64-gnu" "4.57.1"
1098
+ "@rollup/rollup-linux-riscv64-musl" "4.57.1"
1099
+ "@rollup/rollup-linux-s390x-gnu" "4.57.1"
1100
+ "@rollup/rollup-linux-x64-gnu" "4.57.1"
1101
+ "@rollup/rollup-linux-x64-musl" "4.57.1"
1102
+ "@rollup/rollup-openbsd-x64" "4.57.1"
1103
+ "@rollup/rollup-openharmony-arm64" "4.57.1"
1104
+ "@rollup/rollup-win32-arm64-msvc" "4.57.1"
1105
+ "@rollup/rollup-win32-ia32-msvc" "4.57.1"
1106
+ "@rollup/rollup-win32-x64-gnu" "4.57.1"
1107
+ "@rollup/rollup-win32-x64-msvc" "4.57.1"
1108
+ fsevents "~2.3.2"
1109
+
1110
+ safe-buffer@5.2.1:
1111
+ version "5.2.1"
1112
+ resolved "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz"
1113
+ integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==
1114
+
1115
+ "safer-buffer@>= 2.1.2 < 3":
1116
+ version "2.1.2"
1117
+ resolved "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz"
1118
+ integrity sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==
1119
+
1120
+ semver@^7.7.2:
1121
+ version "7.7.2"
1122
+ resolved "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz"
1123
+ integrity sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==
1124
+
1125
+ setprototypeof@1.2.0:
1126
+ version "1.2.0"
1127
+ resolved "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz"
1128
+ integrity sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==
1129
+
1130
+ shebang-command@^2.0.0:
1131
+ version "2.0.0"
1132
+ resolved "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz"
1133
+ integrity sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==
1134
+ dependencies:
1135
+ shebang-regex "^3.0.0"
1136
+
1137
+ shebang-regex@^3.0.0:
1138
+ version "3.0.0"
1139
+ resolved "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz"
1140
+ integrity sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==
1141
+
1142
+ side-channel-list@^1.0.0:
1143
+ version "1.0.0"
1144
+ resolved "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz"
1145
+ integrity sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==
1146
+ dependencies:
1147
+ es-errors "^1.3.0"
1148
+ object-inspect "^1.13.3"
1149
+
1150
+ side-channel-map@^1.0.1:
1151
+ version "1.0.1"
1152
+ resolved "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz"
1153
+ integrity sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==
1154
+ dependencies:
1155
+ call-bound "^1.0.2"
1156
+ es-errors "^1.3.0"
1157
+ get-intrinsic "^1.2.5"
1158
+ object-inspect "^1.13.3"
1159
+
1160
+ side-channel-weakmap@^1.0.2:
1161
+ version "1.0.2"
1162
+ resolved "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz"
1163
+ integrity sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==
1164
+ dependencies:
1165
+ call-bound "^1.0.2"
1166
+ es-errors "^1.3.0"
1167
+ get-intrinsic "^1.2.5"
1168
+ object-inspect "^1.13.3"
1169
+ side-channel-map "^1.0.1"
1170
+
1171
+ side-channel@^1.1.0:
1172
+ version "1.1.0"
1173
+ resolved "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz"
1174
+ integrity sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==
1175
+ dependencies:
1176
+ es-errors "^1.3.0"
1177
+ object-inspect "^1.13.3"
1178
+ side-channel-list "^1.0.0"
1179
+ side-channel-map "^1.0.1"
1180
+ side-channel-weakmap "^1.0.2"
1181
+
1182
+ signal-exit@^4.0.1:
1183
+ version "4.1.0"
1184
+ resolved "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz"
1185
+ integrity sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==
1186
+
1187
+ source-map@^0.7.6:
1188
+ version "0.7.6"
1189
+ resolved "https://registry.npmjs.org/source-map/-/source-map-0.7.6.tgz"
1190
+ integrity sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==
1191
+
1192
+ statuses@^1.5.0, "statuses@>= 1.5.0 < 2":
1193
+ version "1.5.0"
1194
+ resolved "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz"
1195
+ integrity sha512-OpZ3zP+jT1PI7I8nemJX4AKmAX070ZkYPVWV/AaKTJl+tXCTGyVdC1a4SL8RUQYEwk/f34ZX8UTykN68FwrqAA==
1196
+
1197
+ statuses@2.0.1:
1198
+ version "2.0.1"
1199
+ resolved "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz"
1200
+ integrity sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==
1201
+
1202
+ stream-slice@^0.1.2:
1203
+ version "0.1.2"
1204
+ resolved "https://registry.npmjs.org/stream-slice/-/stream-slice-0.1.2.tgz"
1205
+ integrity sha512-QzQxpoacatkreL6jsxnVb7X5R/pGw9OUv2qWTYWnmLpg4NdN31snPy/f3TdQE1ZUXaThRvj1Zw4/OGg0ZkaLMA==
1206
+
1207
+ "string-width-cjs@npm:string-width@^4.2.0":
1208
+ version "4.2.3"
1209
+ resolved "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz"
1210
+ integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==
1211
+ dependencies:
1212
+ emoji-regex "^8.0.0"
1213
+ is-fullwidth-code-point "^3.0.0"
1214
+ strip-ansi "^6.0.1"
1215
+
1216
+ string-width@^4.1.0:
1217
+ version "4.2.3"
1218
+ resolved "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz"
1219
+ integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==
1220
+ dependencies:
1221
+ emoji-regex "^8.0.0"
1222
+ is-fullwidth-code-point "^3.0.0"
1223
+ strip-ansi "^6.0.1"
1224
+
1225
+ string-width@^5.0.1, string-width@^5.1.2:
1226
+ version "5.1.2"
1227
+ resolved "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz"
1228
+ integrity sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==
1229
+ dependencies:
1230
+ eastasianwidth "^0.2.0"
1231
+ emoji-regex "^9.2.2"
1232
+ strip-ansi "^7.0.1"
1233
+
1234
+ "strip-ansi-cjs@npm:strip-ansi@^6.0.1":
1235
+ version "6.0.1"
1236
+ resolved "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz"
1237
+ integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==
1238
+ dependencies:
1239
+ ansi-regex "^5.0.1"
1240
+
1241
+ strip-ansi@^6.0.0, strip-ansi@^6.0.1:
1242
+ version "6.0.1"
1243
+ resolved "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz"
1244
+ integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==
1245
+ dependencies:
1246
+ ansi-regex "^5.0.1"
1247
+
1248
+ strip-ansi@^7.0.1:
1249
+ version "7.1.0"
1250
+ resolved "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz"
1251
+ integrity sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==
1252
+ dependencies:
1253
+ ansi-regex "^6.0.1"
1254
+
1255
+ sucrase@^3.35.0:
1256
+ version "3.35.0"
1257
+ resolved "https://registry.npmjs.org/sucrase/-/sucrase-3.35.0.tgz"
1258
+ integrity sha512-8EbVDiu9iN/nESwxeSxDKe0dunta1GOlHufmSSXxMD2z2/tMZpDMpvXQGsc+ajGo8y2uYUmixaSRUc/QPoQ0GA==
1259
+ dependencies:
1260
+ "@jridgewell/gen-mapping" "^0.3.2"
1261
+ commander "^4.0.0"
1262
+ glob "^10.3.10"
1263
+ lines-and-columns "^1.1.6"
1264
+ mz "^2.7.0"
1265
+ pirates "^4.0.1"
1266
+ ts-interface-checker "^0.1.9"
1267
+
1268
+ thenify-all@^1.0.0:
1269
+ version "1.6.0"
1270
+ resolved "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz"
1271
+ integrity sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==
1272
+ dependencies:
1273
+ thenify ">= 3.1.0 < 4"
1274
+
1275
+ "thenify@>= 3.1.0 < 4":
1276
+ version "3.3.1"
1277
+ resolved "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz"
1278
+ integrity sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==
1279
+ dependencies:
1280
+ any-promise "^1.0.0"
1281
+
1282
+ tinyexec@^0.3.2:
1283
+ version "0.3.2"
1284
+ resolved "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz"
1285
+ integrity sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==
1286
+
1287
+ tinyglobby@^0.2.11:
1288
+ version "0.2.15"
1289
+ resolved "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz"
1290
+ integrity sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==
1291
+ dependencies:
1292
+ fdir "^6.5.0"
1293
+ picomatch "^4.0.3"
1294
+
1295
+ toidentifier@1.0.1:
1296
+ version "1.0.1"
1297
+ resolved "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz"
1298
+ integrity sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==
1299
+
1300
+ tree-kill@^1.2.2:
1301
+ version "1.2.2"
1302
+ resolved "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz"
1303
+ integrity sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==
1304
+
1305
+ ts-interface-checker@^0.1.9:
1306
+ version "0.1.13"
1307
+ resolved "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz"
1308
+ integrity sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==
1309
+
1310
+ tsscmp@1.0.6:
1311
+ version "1.0.6"
1312
+ resolved "https://registry.npmjs.org/tsscmp/-/tsscmp-1.0.6.tgz"
1313
+ integrity sha512-LxhtAkPDTkVCMQjt2h6eBVY28KCjikZqZfMcC15YBeNjkgUpdCfBu5HoiOTDu86v6smE8yOjyEktJ8hlbANHQA==
1314
+
1315
+ tsup@^8.0.2:
1316
+ version "8.5.1"
1317
+ resolved "https://registry.npmjs.org/tsup/-/tsup-8.5.1.tgz"
1318
+ integrity sha512-xtgkqwdhpKWr3tKPmCkvYmS9xnQK3m3XgxZHwSUjvfTjp7YfXe5tT3GgWi0F2N+ZSMsOeWeZFh7ZZFg5iPhing==
1319
+ dependencies:
1320
+ bundle-require "^5.1.0"
1321
+ cac "^6.7.14"
1322
+ chokidar "^4.0.3"
1323
+ consola "^3.4.0"
1324
+ debug "^4.4.0"
1325
+ esbuild "^0.27.0"
1326
+ fix-dts-default-cjs-exports "^1.0.0"
1327
+ joycon "^3.1.1"
1328
+ picocolors "^1.1.1"
1329
+ postcss-load-config "^6.0.1"
1330
+ resolve-from "^5.0.0"
1331
+ rollup "^4.34.8"
1332
+ source-map "^0.7.6"
1333
+ sucrase "^3.35.0"
1334
+ tinyexec "^0.3.2"
1335
+ tinyglobby "^0.2.11"
1336
+ tree-kill "^1.2.2"
1337
+
1338
+ type-is@^1.6.14, type-is@^1.6.16, type-is@^1.6.18:
1339
+ version "1.6.18"
1340
+ resolved "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz"
1341
+ integrity sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==
1342
+ dependencies:
1343
+ media-typer "0.3.0"
1344
+ mime-types "~2.1.24"
1345
+
1346
+ typescript@^5.3.3, typescript@>=4.5.0:
1347
+ version "5.5.4"
1348
+ resolved "https://registry.npmjs.org/typescript/-/typescript-5.5.4.tgz"
1349
+ integrity sha512-Mtq29sKDAEYP7aljRgtPOpTvOfbwRWlS6dPRzwjdE+C0R4brX/GUyhHSecbHMFLNBLcJIPt9nl9yG5TZ1weH+Q==
1350
+
1351
+ ufo@^1.6.1:
1352
+ version "1.6.3"
1353
+ resolved "https://registry.npmjs.org/ufo/-/ufo-1.6.3.tgz"
1354
+ integrity sha512-yDJTmhydvl5lJzBmy/hyOAA0d+aqCBuwl818haVdYCRrWV84o7YyeVm4QlVHStqNrrJSTb6jKuFAVqAFsr+K3Q==
1355
+
1356
+ undici-types@~5.26.4:
1357
+ version "5.26.5"
1358
+ resolved "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz"
1359
+ integrity sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==
1360
+
1361
+ universalify@^2.0.0:
1362
+ version "2.0.1"
1363
+ resolved "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz"
1364
+ integrity sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==
1365
+
1366
+ unpipe@1.0.0:
1367
+ version "1.0.0"
1368
+ resolved "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz"
1369
+ integrity sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==
1370
+
1371
+ uuid@^9.0.1:
1372
+ version "9.0.1"
1373
+ resolved "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz"
1374
+ integrity sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==
1375
+
1376
+ vary@^1.1.2:
1377
+ version "1.1.2"
1378
+ resolved "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz"
1379
+ integrity sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==
1380
+
1381
+ which@^2.0.1:
1382
+ version "2.0.2"
1383
+ resolved "https://registry.npmjs.org/which/-/which-2.0.2.tgz"
1384
+ integrity sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==
1385
+ dependencies:
1386
+ isexe "^2.0.0"
1387
+
1388
+ "wrap-ansi-cjs@npm:wrap-ansi@^7.0.0":
1389
+ version "7.0.0"
1390
+ resolved "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz"
1391
+ integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==
1392
+ dependencies:
1393
+ ansi-styles "^4.0.0"
1394
+ string-width "^4.1.0"
1395
+ strip-ansi "^6.0.0"
1396
+
1397
+ wrap-ansi@^8.1.0:
1398
+ version "8.1.0"
1399
+ resolved "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz"
1400
+ integrity sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==
1401
+ dependencies:
1402
+ ansi-styles "^6.1.0"
1403
+ string-width "^5.0.1"
1404
+ strip-ansi "^7.0.1"
1405
+
1406
+ wrappy@1:
1407
+ version "1.0.2"
1408
+ resolved "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz"
1409
+ integrity sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==
1410
+
1411
+ yaml@^2.3.4, yaml@^2.4.2:
1412
+ version "2.5.0"
1413
+ resolved "https://registry.npmjs.org/yaml/-/yaml-2.5.0.tgz"
1414
+ integrity sha512-2wWLbGbYDiSqqIKoPjar3MPgB94ErzCtrNE1FdqGuaO0pi2JGjmE8aW8TDZwzU7vuxcGRdL/4gPQwQ7hD5AMSw==
1415
+
1416
+ ylru@^1.2.0:
1417
+ version "1.4.0"
1418
+ resolved "https://registry.npmjs.org/ylru/-/ylru-1.4.0.tgz"
1419
+ integrity sha512-2OQsPNEmBCvXuFlIni/a+Rn+R2pHW9INm0BxXJ4hVDA8TirqMj+J/Rp9ItLatT/5pZqWwefVrTQcHpixsxnVlA==