@plume-canvas/cloud-server 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,490 @@
1
+ /**
2
+ * web2api · 视频生成(provider,自包含单文件)
3
+ *
4
+ * 与 web2api-image.js 同一套 HTTP 协议(POST /api/tasks 下单、GET 查进度、cancel 取消)。
5
+ * 单独成文件的原因:图片与视频的轮询节奏、超时预算差得远(视频 30~45 分钟),
6
+ * 拆开后改一边不会影响另一边。公共逻辑按「不能相对 import」的规矩各自复制一份。
7
+ *
8
+ * 环境变量:WEB2API_BASE / WEB2API_API_KEY(见 web2api-image.js 说明)。
9
+ */
10
+
11
+ /**
12
+ * 服务地址与密钥:优先「平台管理」页存的配置(__mcProviderConfig,装载时注入),
13
+ * 回落环境变量(老部署兼容)。多账号:submit 按选中的账号 id 取对应那套值。
14
+ */
15
+ function injected() {
16
+ return typeof __mcProviderConfig === 'undefined' ? { accounts: [], values: {}, byId: {} } : __mcProviderConfig
17
+ }
18
+ function accountValues(values) {
19
+ const inj = injected()
20
+ const preferred = values && typeof values.__accountId === 'string' ? values.__accountId : ''
21
+ if (preferred && inj.byId && inj.byId[preferred]) return inj.byId[preferred]
22
+ const accounts = inj.accounts || []
23
+ if (accounts.length > 0) return accounts[0].values || {}
24
+ return inj.values || {}
25
+ }
26
+ function baseOf(values) {
27
+ const b = values && typeof values.baseUrl === 'string' && values.baseUrl.trim()
28
+ ? values.baseUrl.trim()
29
+ : (process.env.WEB2API_BASE || 'http://localhost:8033')
30
+ return String(b).replace(/\/+$/, '')
31
+ }
32
+ const BASE = baseOf(injected().values || {})
33
+
34
+ async function api(path, init = {}, timeoutMs = 60000, values) {
35
+ const ac = new AbortController()
36
+ const timer = setTimeout(() => ac.abort(), timeoutMs)
37
+ try {
38
+ const headers = { 'Content-Type': 'application/json', Accept: 'application/json', ...(init.headers || {}) }
39
+ const key = values && values.apiKey ? values.apiKey : process.env.WEB2API_API_KEY
40
+ if (key) headers.Authorization = 'Bearer ' + key
41
+ const res = await fetch(baseOf(values) + path, { ...init, headers, signal: ac.signal })
42
+ const text = await res.text()
43
+ let body
44
+ try {
45
+ body = text ? JSON.parse(text) : {}
46
+ } catch {
47
+ throw new Error('web2api 返回的不是 JSON(HTTP ' + res.status + ')')
48
+ }
49
+ if (body && typeof body.code === 'number' && body.code !== 0) {
50
+ throw new Error(body.message || 'web2api 错误 ' + body.code)
51
+ }
52
+ if (!res.ok) throw new Error(body?.message || 'web2api HTTP ' + res.status)
53
+ return body
54
+ } catch (err) {
55
+ const msg = err instanceof Error ? err.message : String(err)
56
+ if (err instanceof Error && err.name === 'AbortError') {
57
+ throw new Error('web2api 请求超时(' + baseOf(values) + ')')
58
+ }
59
+ if (/fetch failed|ECONNREFUSED|Failed to fetch|NetworkError/i.test(msg)) {
60
+ throw new Error('连不上 web2api(' + baseOf(values) + ')。请先启动它,或在「平台」页配置服务地址')
61
+ }
62
+ throw new Error(msg || 'web2api 调用失败')
63
+ } finally {
64
+ clearTimeout(timer)
65
+ }
66
+ }
67
+
68
+ function cleanValues(values) {
69
+ const out = {}
70
+ for (const [k, v] of Object.entries(values || {})) {
71
+ if (v === undefined || v === null || v === '') continue
72
+ out[k] = v
73
+ }
74
+ return out
75
+ }
76
+
77
+ function literalOf(value) {
78
+ if (value === undefined || value === null || value === '') return undefined
79
+ if (typeof value === 'number') return Number.isFinite(value) ? String(value) : undefined
80
+ if (typeof value === 'boolean') return String(value)
81
+ const s = String(value).trim()
82
+ return s === '' ? undefined : '"' + s.replace(/"/g, '') + '"'
83
+ }
84
+
85
+ function numericOf(value) {
86
+ if (typeof value === 'number') return value
87
+ if (typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value))) return Number(value)
88
+ return value
89
+ }
90
+
91
+ /** /video(model:"Seedance 2.0 Fast", ratio:"16:9", durationSec:10) 正文 */
92
+ function buildChatAutoPrompt(model, values, body) {
93
+ const parts = []
94
+ const modelLit = literalOf(model)
95
+ if (modelLit !== undefined) parts.push('model:' + modelLit)
96
+ const ratioLit = literalOf(values.ratio)
97
+ if (ratioLit !== undefined) parts.push('ratio:' + ratioLit)
98
+ const durLit = literalOf(numericOf(values.durationSec))
99
+ if (durLit !== undefined) parts.push('durationSec:' + durLit)
100
+ const styleLit = literalOf(values.style)
101
+ if (styleLit !== undefined) parts.push('style:' + styleLit)
102
+ const head = '/video' + (parts.length > 0 ? '(' + parts.join(', ') + ')' : '')
103
+ const text = String(body || '').trim()
104
+ return text ? head + ' ' + text : head
105
+ }
106
+
107
+ /**
108
+ * 资源在数组里的位置就是它的引用索引(从 1 开始)。
109
+ *
110
+ * 平台只认「第几个图 / 第几个视频」,不认画布上的节点名字:
111
+ * 名字是给人看的,resources 数组的顺序才是和模型对齐的唯一凭据。
112
+ */
113
+ function refLabel(resource, index) {
114
+ const kind = resource && typeof resource.kind === 'string' ? resource.kind : ''
115
+ const prefix =
116
+ kind === 'image' ? '图片'
117
+ : kind === 'video' ? '视频'
118
+ : kind === 'audio' ? '音频'
119
+ : kind === 'text' ? '文本'
120
+ : '资源'
121
+ return prefix + (index + 1)
122
+ }
123
+
124
+ function textBlocks(input) {
125
+ const out = []
126
+ const resources = input.resources || []
127
+ resources.forEach((r, i) => {
128
+ if (!r || r.kind !== 'text') return
129
+ const value = typeof r.value === 'string' ? r.value : ''
130
+ out.push('<text name="' + refLabel(r, i) + '">\n' + value + '\n</text>')
131
+ })
132
+ return out
133
+ }
134
+
135
+ /** 提示词分段 → 平台要的一段文字(标签按资源在数组里的「类型+序号」展开) */
136
+ function promptText(input) {
137
+ const labels = new Map()
138
+ const resources = input.resources || []
139
+ resources.forEach((r, i) => {
140
+ if (r && typeof r.id === 'string' && r.id) labels.set(r.id, refLabel(r, i))
141
+ })
142
+ let out = ''
143
+ for (const seg of input.prompts || []) {
144
+ if (!seg || typeof seg.value !== 'string') continue
145
+ if (seg.type === 'tag') {
146
+ out += '@' + (labels.get(seg.value) || seg.value)
147
+ } else {
148
+ out += seg.value
149
+ }
150
+ }
151
+ return out
152
+ }
153
+
154
+ /**
155
+ * 参考素材 -> 参数(按动作声明的 refFields 分发)。
156
+ *
157
+ * ⚠️ web2api 目前**没有视频参考字段**(所有 meta.ts 的 acceptance 只有 image / audio)。
158
+ * 所以视频节点连进来时:跳过 + 打日志说明,而不是像以前那样混进 referenceImages
159
+ * (那会让 web2api 把一个 mp4 当图片解析,报「图片不存在」或生成出垃圾)。
160
+ */
161
+ function attachRefs(action, input, params) {
162
+ const map = action.refFields || {}
163
+ const buckets = {}
164
+ const skipped = []
165
+ for (const r of input.resources || []) {
166
+ if (r.kind === 'text') continue
167
+ const field = map[r.kind]
168
+ if (!field || typeof r.url !== 'string' || !r.url) {
169
+ if (r.kind) skipped.push(r.kind)
170
+ continue
171
+ }
172
+ if (!buckets[field]) buckets[field] = []
173
+ buckets[field].push(r.url)
174
+ }
175
+ for (const [field, urls] of Object.entries(buckets)) {
176
+ const limit = field === 'referenceAudios' ? 3 : 16
177
+ if (urls.length > limit) {
178
+ console.warn('[web2api-video] ' + action.id + ' 的 ' + field + ' 最多 ' + limit + ' 个,已截断')
179
+ }
180
+ params[field] = urls.slice(0, limit)
181
+ }
182
+ if (skipped.length > 0) {
183
+ console.warn(
184
+ '[web2api-video] ' + action.id + ' 不收这些素材,已忽略:' + [...new Set(skipped)].join('、') +
185
+ '(当前平台只收:' + (Object.keys(map).join('、') || '无') + ')',
186
+ )
187
+ }
188
+ return params
189
+ }
190
+
191
+ function buildParams(action, input) {
192
+ const values = (input.values || {})
193
+ const body = [promptText(input), ...textBlocks(input)].filter((s) => String(s).trim() !== '').join('\n')
194
+
195
+ if (action.promptMode === 'chat-auto') {
196
+ const params = { prompt: buildChatAutoPrompt(action.model, values, body) }
197
+ return attachRefs(action, input, params)
198
+ }
199
+
200
+ const params = cleanValues(values)
201
+ if (action.model !== undefined && action.model !== '') params.model = action.model
202
+ params.prompt = body
203
+ return attachRefs(action, input, params)
204
+ }
205
+
206
+ function collectUrls(result) {
207
+ const out = []
208
+ const push = (v) => {
209
+ if (typeof v === 'string') {
210
+ if (/^(https?:|data:|\/)/i.test(v)) out.push(v)
211
+ } else if (Array.isArray(v)) {
212
+ for (const item of v) push(item)
213
+ } else if (v && typeof v === 'object') {
214
+ push(v.url)
215
+ push(v.uri)
216
+ push(v.src)
217
+ push(v.urls)
218
+ push(v.downloadUrl)
219
+ push(v.resource)
220
+ push(v.videoUrl)
221
+ }
222
+ }
223
+ push(result)
224
+ return [...new Set(out)]
225
+ }
226
+
227
+ function absolutize(u) {
228
+ const s = String(u || '').trim()
229
+ if (!s) return ''
230
+ if (/^(https?:|data:|blob:)/i.test(s)) return s
231
+ return BASE + (s.startsWith('/') ? s : '/' + s)
232
+ }
233
+
234
+ async function submitTask(action, input) {
235
+ const values = accountValues(input.values)
236
+ const body = await api('/api/tasks', {
237
+ method: 'POST',
238
+ body: JSON.stringify({ platform: action.platform, operation: action.operation, params: buildParams(action, input) }),
239
+ }, 60000, values)
240
+ const task = body && body.data
241
+ if (!task || typeof task.id !== 'string' || !task.id) throw new Error('web2api 没有返回任务 id')
242
+ return task.id
243
+ }
244
+
245
+ async function pollTask(taskId) {
246
+ const body = await api('/api/tasks/' + encodeURIComponent(taskId), {}, 60000, accountValues())
247
+ const t = body && body.data
248
+ if (!t || typeof t !== 'object') return { status: 'running', message: '任务查询返回空', taskId }
249
+ const status = String(t.status || '')
250
+
251
+ if (status === 'completed' || status === 'success' || status === 'done') {
252
+ const urls = collectUrls(t.result).map(absolutize).filter(Boolean)
253
+ if (urls.length === 0) return { status: 'error', error: '任务完成但没有产出资源', taskId }
254
+ return { status: 'done', urls, taskId }
255
+ }
256
+ if (status === 'failed') return { status: 'error', error: t.message || '任务执行失败', taskId }
257
+ if (status === 'cancelled') return { status: 'error', error: t.message || '任务已取消', taskId }
258
+
259
+ const waiting = status === 'paused' || status === 'retrying' || status === 'pending'
260
+ return {
261
+ status: 'running',
262
+ message: t.message || '生成中…',
263
+ ...(typeof t.progress === 'number' ? { progress: t.progress } : {}),
264
+ taskId,
265
+ ...(waiting ? { waiting: true } : {}),
266
+ }
267
+ }
268
+
269
+ async function cancelTask(taskId) {
270
+ try {
271
+ await api('/api/tasks/' + encodeURIComponent(taskId) + '/cancel', { method: 'POST' }, 15000, accountValues())
272
+ } catch {
273
+ /* 已是终态:本机已取消,不算错 */
274
+ }
275
+ }
276
+
277
+
278
+ const ratio_doubao = {
279
+ key: 'ratio', kind: 'ratio', label: '比例', type: 'select', default: '16:9',
280
+ options: [
281
+ { label: '1:1', value: '1:1' },
282
+ { label: '3:4', value: '3:4' },
283
+ { label: '4:3', value: '4:3' },
284
+ { label: '9:16', value: '9:16' },
285
+ { label: '16:9', value: '16:9' },
286
+ { label: '21:9', value: '21:9' },
287
+ ],
288
+ }
289
+
290
+ const duration_doubao_auto = {
291
+ key: 'durationSec', label: '时长', type: 'number',
292
+ min: 4, max: 10, step: 1, default: 5, unit: '秒',
293
+ }
294
+
295
+ /** dola 只有 5 / 10 两档:number + options 会自动画成按钮网格(不用再写 kind) */
296
+ const duration_dola_auto = {
297
+ key: 'durationSec', label: '时长', type: 'number', default: 5,
298
+ options: [{ label: '5秒', value: '5' }, { label: '10秒', value: '10' }],
299
+ }
300
+
301
+ const duration_doubao_api = {
302
+ key: 'duration', label: '时长', type: 'number',
303
+ min: 4, max: 15, step: 1, default: 10, unit: '秒',
304
+ }
305
+
306
+ const duration_seedance = {
307
+ key: 'duration', label: '时长', type: 'number',
308
+ min: 4, max: 180, step: 1, default: 5, unit: '秒',
309
+ }
310
+
311
+ const ratio_seedance = {
312
+ key: 'ratio', kind: 'ratio', label: '比例', type: 'select', default: '16:9',
313
+ options: [{ label: '16:9', value: '16:9' }, { label: '9:16', value: '9:16' }],
314
+ }
315
+
316
+ const camera_doubao = {
317
+ key: 'cameraMovement', label: '运镜', type: 'grid',
318
+ options: [
319
+ { label: '固定镜头', value: '固定镜头' },
320
+ { label: '镜头环绕', value: '镜头环绕拍摄' },
321
+ { label: '镜头移动', value: '镜头移动' },
322
+ { label: '镜头聚焦', value: '镜头聚焦' },
323
+ ],
324
+ }
325
+
326
+ const provider = {
327
+ id: 'web2api-video',
328
+ // 平台展示信息(管理页显示;icon 也作为该平台模型的兜底图标)
329
+ title: 'Web2API · 视频',
330
+ description: '豆包 Seedance / MiniMax 视频生成',
331
+ icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><defs><linearGradient id="wcVid" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#a78bfa"/><stop offset="1" stop-color="#7c3aed"/></linearGradient></defs><rect width="32" height="32" rx="9" fill="url(#wcVid)"/><path d="M12 10.5 22 16l-10 5.5V10.5z" fill="#fff"/></svg>',
332
+ // 平台管理页据此渲染配置表单(与 web2api-image 同一套;多账号每套一份)
333
+ config: [
334
+ { key: 'baseUrl', label: '服务地址', type: 'string', default: 'http://localhost:8033',
335
+ placeholder: 'http://localhost:8033', description: 'web2api 服务的根地址。留空 = 用默认地址。' },
336
+ { key: 'apiKey', label: 'API Key', type: 'secret', description: 'web2api 开了 API_KEY 校验时才需要。留空 = 不带鉴权头。' },
337
+ ],
338
+ actions: [
339
+ {
340
+ id: 'web2api:doubao-video-fast',
341
+ title: '豆包 Seedance 2.0 Fast',
342
+ description: '豆包网页 UI 自动化生视频:比例 / 时长 4-10 秒',
343
+ group: 'web2api · 视频',
344
+ nodeTypes: ['video'],
345
+ needsPrompt: true,
346
+ order: 10,
347
+ platform: 'doubao', operation: 'chat-auto',
348
+ promptMode: 'chat-auto', mediaMode: 'video', model: 'Seedance 2.0 Fast',
349
+ fields: [ratio_doubao, duration_doubao_auto],
350
+ refFields: { image: 'referenceImages' },
351
+ pollIntervalMs: 4000, pollTimeoutMs: 1800000,
352
+ },
353
+ {
354
+ id: 'web2api:doubao-video-mini',
355
+ title: '豆包 Seedance 2.0 Mini',
356
+ description: '豆包网页 UI 自动化生视频(Seedance 2.0 Mini):比例 / 时长 4-10 秒',
357
+ group: 'web2api · 视频',
358
+ nodeTypes: ['video'],
359
+ needsPrompt: true,
360
+ order: 11,
361
+ platform: 'doubao', operation: 'chat-auto',
362
+ promptMode: 'chat-auto', mediaMode: 'video', model: 'Seedance 2.0 Mini',
363
+ fields: [ratio_doubao, duration_doubao_auto],
364
+ refFields: { image: 'referenceImages' },
365
+ pollIntervalMs: 4000, pollTimeoutMs: 1800000,
366
+ },
367
+ {
368
+ id: 'web2api:dola-video-seedance25',
369
+ title: 'Dola Seedance 2.5',
370
+ description: 'Dola 网页 UI 自动化生视频:时长只有 5 / 10 秒;需海外网络',
371
+ group: 'web2api · 视频',
372
+ nodeTypes: ['video'],
373
+ needsPrompt: true,
374
+ order: 12,
375
+ platform: 'dola', operation: 'chat-auto',
376
+ promptMode: 'chat-auto', mediaMode: 'video', model: 'Seedance 2.5',
377
+ fields: [ratio_doubao, duration_dola_auto],
378
+ refFields: { image: 'referenceImages' },
379
+ pollIntervalMs: 4000, pollTimeoutMs: 1800000,
380
+ },
381
+ {
382
+ id: 'web2api:dola-video-seedance20',
383
+ title: 'Dola Seedance 2.0',
384
+ description: 'Dola 网页 UI 自动化生视频:时长只有 5 / 10 秒;需海外网络',
385
+ group: 'web2api · 视频',
386
+ nodeTypes: ['video'],
387
+ needsPrompt: true,
388
+ order: 13,
389
+ platform: 'dola', operation: 'chat-auto',
390
+ promptMode: 'chat-auto', mediaMode: 'video', model: 'Seedance 2.0',
391
+ fields: [ratio_doubao, duration_dola_auto],
392
+ refFields: { image: 'referenceImages' },
393
+ pollIntervalMs: 4000, pollTimeoutMs: 1800000,
394
+ },
395
+ {
396
+ id: 'web2api:dola-video-seedance10',
397
+ title: 'Dola Seedance 1.0',
398
+ description: 'Dola 网页 UI 自动化生视频:时长只有 5 / 10 秒;需海外网络',
399
+ group: 'web2api · 视频',
400
+ nodeTypes: ['video'],
401
+ needsPrompt: true,
402
+ order: 14,
403
+ platform: 'dola', operation: 'chat-auto',
404
+ promptMode: 'chat-auto', mediaMode: 'video', model: 'Seedance 1.0',
405
+ fields: [ratio_doubao, duration_dola_auto],
406
+ refFields: { image: 'referenceImages' },
407
+ pollIntervalMs: 4000, pollTimeoutMs: 1800000,
408
+ },
409
+ {
410
+ id: 'web2api:doubao-video-api-mini',
411
+ title: '豆包 Seedance 2.0 Mini(接口)',
412
+ description: '豆包接口式文生视频(异步轮询):比例 / 时长 / 运镜',
413
+ group: 'web2api · 视频',
414
+ nodeTypes: ['video'],
415
+ needsPrompt: true,
416
+ order: 15,
417
+ platform: 'doubao', operation: 'generate-video',
418
+ promptMode: 'plain', model: 'seedance_v2.0_mini',
419
+ fields: [ratio_doubao, duration_doubao_api, camera_doubao],
420
+ refFields: { image: 'referenceImages' },
421
+ pollIntervalMs: 10000, pollTimeoutMs: 2700000,
422
+ },
423
+ {
424
+ id: 'web2api:doubao-video-api-fast',
425
+ title: '豆包 Seedance 2.0 Fast(接口)',
426
+ description: '豆包接口式文生视频(异步轮询):比例 / 时长 / 运镜',
427
+ group: 'web2api · 视频',
428
+ nodeTypes: ['video'],
429
+ needsPrompt: true,
430
+ order: 16,
431
+ platform: 'doubao', operation: 'generate-video',
432
+ promptMode: 'plain', model: 'seedance_v2.0',
433
+ fields: [ratio_doubao, duration_doubao_api, camera_doubao],
434
+ refFields: { image: 'referenceImages' },
435
+ pollIntervalMs: 10000, pollTimeoutMs: 2700000,
436
+ },
437
+ {
438
+ id: 'web2api:seedance-video-fast',
439
+ title: 'Seedance Fast',
440
+ description: 'Seedance 平台接口式文生视频:时长最长 180 秒',
441
+ group: 'web2api · 视频',
442
+ nodeTypes: ['video'],
443
+ needsPrompt: true,
444
+ order: 17,
445
+ platform: 'seedance', operation: 'generate-video',
446
+ promptMode: 'plain', model: 'fast',
447
+ fields: [ratio_seedance, duration_seedance],
448
+ refFields: { image: 'referenceImages' },
449
+ pollIntervalMs: 10000, pollTimeoutMs: 2700000,
450
+ },
451
+ {
452
+ id: 'web2api:seedance-video-20',
453
+ title: 'Seedance 2.0',
454
+ description: 'Seedance 平台接口式文生视频:时长最长 180 秒',
455
+ group: 'web2api · 视频',
456
+ nodeTypes: ['video'],
457
+ needsPrompt: true,
458
+ order: 18,
459
+ platform: 'seedance', operation: 'generate-video',
460
+ promptMode: 'plain', model: '2.0',
461
+ fields: [ratio_seedance, duration_seedance],
462
+ refFields: { image: 'referenceImages' },
463
+ pollIntervalMs: 10000, pollTimeoutMs: 2700000,
464
+ },
465
+ ],
466
+
467
+ async submit(action, input) {
468
+ try {
469
+ return { taskId: await submitTask(action, input) }
470
+ } catch (err) {
471
+ return { error: err instanceof Error ? err.message : String(err) }
472
+ }
473
+ },
474
+
475
+ async poll(taskId) {
476
+ try {
477
+ return await pollTask(taskId)
478
+ } catch (err) {
479
+ return { status: 'running', message: err instanceof Error ? err.message : '任务查询失败', taskId }
480
+ }
481
+ },
482
+
483
+ async cancel(taskId) {
484
+ await cancelTask(taskId)
485
+ },
486
+ }
487
+
488
+ export default provider
489
+
490
+
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.