dsh-game-material-master 0.7.0 → 0.9.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.
package/lib/comfy.js ADDED
@@ -0,0 +1,769 @@
1
+ /**
2
+ * 本地 ComfyUI 后端(生成视频)。
3
+ *
4
+ * 与 Ark / MiniMax 的区别:这里没有「远端 API 契约」,只有一份**用户自己的 API 格式工作流**。
5
+ * 于是插件负责三件事:
6
+ * 1. 把提示词 / 首帧图 / 尺寸 / 时长 / 种子**注入**到工作流的对应输入(自动探测,可手工覆盖成 `节点ID.输入名`);
7
+ * 2. `POST /prompt` 提交,之后轮询 `/history/<promptId>`(还没进 history 时看 `/queue` 区分排队与执行);
8
+ * 3. 从 history 的 outputs 里挑出视频文件,拼出 `/view` 地址,交给既有的下载 → 抽帧 → 抠像流水线。
9
+ *
10
+ * 注入点是**探测**出来的,不写死节点 id:换一份工作流(Wan / Hunyuan / Flux…)只要输入名符合常见约定就能直接用。
11
+ */
12
+ import { randomUUID } from "node:crypto";
13
+ export class ComfyError extends Error {
14
+ status;
15
+ constructor(message, status) {
16
+ super(message);
17
+ this.name = "ComfyError";
18
+ this.status = status;
19
+ }
20
+ }
21
+ const PROMPT_KEYS = ["text", "prompt", "positive", "positive_prompt", "caption"];
22
+ const FIRST_KEYS = ["first", "first_frame", "first_image", "start_image", "init_image", "image"];
23
+ const LAST_KEYS = ["last", "last_frame", "last_image", "end_image"];
24
+ const WIDTH_KEYS = ["width"];
25
+ const HEIGHT_KEYS = ["height"];
26
+ const SECONDS_KEYS = ["seconds", "duration", "video_length", "length"];
27
+ const SEED_KEYS = ["seed", "noise_seed", "rand_seed"];
28
+ export function normalizeComfyBaseUrl(value) {
29
+ const trimmed = (value ?? "").trim();
30
+ if (trimmed === "")
31
+ return "http://127.0.0.1:8188";
32
+ return trimmed.replace(/\/+$/, "");
33
+ }
34
+ /**
35
+ * 归一化 `Cookie` 请求头原文。
36
+ *
37
+ * 用户多半直接从浏览器的开发者工具里复制:那里可能带 `Cookie: ` 前缀,整段
38
+ * 「Copy request headers」还夹着 Accept 之类的别的头,长 cookie 也可能折成几行。
39
+ * 这里统一收成一行 `a=1; b=2`:只认 Cookie 那一行(加它的续行)、剥掉前缀、
40
+ * 去掉每段末尾多余的分号。空串(或只有空白)= 不带这个头。
41
+ */
42
+ export function normalizeComfyCookies(value) {
43
+ const trimmed = (value ?? "").trim();
44
+ if (trimmed === "")
45
+ return "";
46
+ const lines = trimmed
47
+ .split(/[\r\n]+/)
48
+ .map((line) => line.trim())
49
+ .filter((line) => line !== "");
50
+ // 整块粘贴时只认 Cookie:它那一行,加上后面不以「名字:」开头的续行。
51
+ const start = lines.findIndex((line) => /^cookie\s*:/i.test(line));
52
+ const picked = start < 0 ? lines : [lines[start], ...lines.slice(start + 1).filter((line) => !/^[A-Za-z0-9_-]+\s*:/.test(line))];
53
+ return picked
54
+ // 每段先去掉自己的尾分号,再拼起来——不然 `a=1;` + `b=2` 会拼出 `a=1;; b=2`。
55
+ .map((line) => line.replace(/[;\s]+$/, ""))
56
+ .join("; ")
57
+ .replace(/^cookie\s*:/i, " ")
58
+ .replace(/[;\s]+$/, "")
59
+ .trim();
60
+ }
61
+ export function formatBinding(binding) {
62
+ return binding === undefined ? "" : binding.node + "." + binding.input;
63
+ }
64
+ /** 解析 `节点ID.输入名`。节点 id 里可能带点,所以按**最后一个**点切分。 */
65
+ export function parseBinding(text) {
66
+ const trimmed = (text ?? "").trim();
67
+ if (trimmed === "")
68
+ return undefined;
69
+ const dot = trimmed.lastIndexOf(".");
70
+ if (dot <= 0 || dot === trimmed.length - 1)
71
+ return undefined;
72
+ return { node: trimmed.slice(0, dot), input: trimmed.slice(dot + 1) };
73
+ }
74
+ /** 界面格式里 seed / 步数这类控件后面跟的那个控制项,它不是节点输入。 */
75
+ const UI_CONTROL_WORDS = new Set(["fixed", "increment", "decrement", "randomize"]);
76
+ /** 界面格式的连线表:链接 id → 来源节点 + 槽位。旧版是数组,新版是对象,两种都读。 */
77
+ function uiLinkTable(record) {
78
+ const table = new Map();
79
+ if (!Array.isArray(record.links))
80
+ return table;
81
+ for (const item of record.links) {
82
+ if (Array.isArray(item)) {
83
+ const id = Number(item[0]);
84
+ if (!Number.isFinite(id))
85
+ continue;
86
+ table.set(id, { originId: String(item[1] ?? ""), originSlot: Number(item[2] ?? 0) || 0 });
87
+ continue;
88
+ }
89
+ if (item !== null && typeof item === "object") {
90
+ const entry = item;
91
+ const id = Number(entry.id);
92
+ if (!Number.isFinite(id))
93
+ continue;
94
+ table.set(id, { originId: String(entry.origin_id ?? ""), originSlot: Number(entry.origin_slot ?? 0) || 0 });
95
+ }
96
+ }
97
+ return table;
98
+ }
99
+ /**
100
+ * ComfyUI **界面格式** → API 格式。
101
+ *
102
+ * 官方示例工作流(FlashML-org/FreeVideo 的 example_workflows/FreeVideo-All-in-One.json)就是界面格式,
103
+ * 而 ComfyUI 的「Save (API Format)」藏得比较深,所以这里直接替用户转一遍:
104
+ * - 有 link 的输入 → 查连线表,写成 [来源节点 id, 来源槽位];
105
+ * - 带 widget 的输入 → 按顺序从 widgets_values 取(值后面那个 fixed / randomize 是控件,要跳过)。
106
+ */
107
+ function convertUiWorkflow(record) {
108
+ const rawNodes = record.nodes;
109
+ if (!Array.isArray(rawNodes))
110
+ return { ok: false, error: "没有 nodes 数组" };
111
+ const links = uiLinkTable(record);
112
+ const workflow = {};
113
+ // 老版 ComfyUI 导出的界面格式里,widget(不是可连线输入的那些框)不出现在 inputs 数组里,
114
+ // 只能靠 widgets_values 的顺序猜名字——猜不到就只报个数,让人改用 Save (API Format)。
115
+ let droppedWidgets = 0;
116
+ for (const item of rawNodes) {
117
+ if (item === null || typeof item !== "object" || Array.isArray(item))
118
+ continue;
119
+ const node = item;
120
+ const id = node.id;
121
+ if (id === undefined || id === null || String(id) === "")
122
+ continue;
123
+ const classType = typeof node.type === "string" ? node.type.trim() : "";
124
+ // 便签(Note / MarkdownNote)不是节点;mode 2 / 4 是画布上的「静音」「旁路」。
125
+ if (classType === "" || classType === "Note" || classType === "MarkdownNote")
126
+ continue;
127
+ const mode = Number(node.mode);
128
+ if (mode === 2 || mode === 4)
129
+ continue;
130
+ const widgets = Array.isArray(node.widgets_values) ? [...node.widgets_values] : [];
131
+ let widgetIndex = 0;
132
+ const inputs = {};
133
+ const declared = Array.isArray(node.inputs) ? node.inputs : [];
134
+ for (const slot of declared) {
135
+ if (slot === null || typeof slot !== "object" || Array.isArray(slot))
136
+ continue;
137
+ const spec = slot;
138
+ const name = typeof spec.name === "string" ? spec.name : "";
139
+ if (name === "")
140
+ continue;
141
+ const link = spec.link;
142
+ if (link !== null && link !== undefined) {
143
+ const end = links.get(Number(link));
144
+ if (end !== undefined) {
145
+ inputs[name] = [end.originId, end.originSlot];
146
+ continue;
147
+ }
148
+ }
149
+ if (spec.widget === undefined)
150
+ continue;
151
+ if (widgetIndex >= widgets.length)
152
+ continue;
153
+ inputs[name] = widgets[widgetIndex];
154
+ widgetIndex += 1;
155
+ if (UI_CONTROL_WORDS.has(String(widgets[widgetIndex])))
156
+ widgetIndex += 1;
157
+ }
158
+ droppedWidgets += Math.max(0, widgets.length - widgetIndex);
159
+ const entry = { class_type: classType, inputs };
160
+ if (typeof node.title === "string" && node.title !== "")
161
+ entry._meta = { title: node.title };
162
+ workflow[String(id)] = entry;
163
+ }
164
+ const uiIds = Object.keys(workflow);
165
+ if (uiIds.length === 0)
166
+ return { ok: false, error: "里面没有任何可用节点(便签与静音 / 旁路节点不算)" };
167
+ return { ok: true, workflow, nodes: uiIds.length, droppedWidgets };
168
+ }
169
+ export function parseComfyWorkflow(text) {
170
+ const trimmed = (text ?? "").trim();
171
+ if (trimmed === "")
172
+ return { ok: false, error: "工作流是空的" };
173
+ let parsed;
174
+ try {
175
+ parsed = JSON.parse(trimmed);
176
+ }
177
+ catch (error) {
178
+ const reason = error instanceof Error ? error.message : String(error);
179
+ return { ok: false, error: "不是合法 JSON:" + reason };
180
+ }
181
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
182
+ return { ok: false, error: "顶层必须是「节点 id → 节点」的对象" };
183
+ }
184
+ const record = parsed;
185
+ if (Array.isArray(record.nodes)) {
186
+ // 界面格式(nodes + links)。官方示例工作流就是这个格式,直接转一遍比让用户去找
187
+ // 藏得很深的「Save (API Format)」友好得多。
188
+ const converted = convertUiWorkflow(record);
189
+ if (converted.ok === true)
190
+ return {
191
+ ok: true,
192
+ workflow: converted.workflow,
193
+ nodes: converted.nodes,
194
+ converted: true,
195
+ droppedWidgets: converted.droppedWidgets
196
+ };
197
+ return { ok: false, error: "看起来是 ComfyUI 界面导出的工作流,但转换失败:" + converted.error };
198
+ }
199
+ const ids = Object.keys(record);
200
+ if (ids.length === 0)
201
+ return { ok: false, error: "工作流里没有任何节点" };
202
+ for (const id of ids) {
203
+ const node = record[id];
204
+ if (node === null || typeof node !== "object" || Array.isArray(node))
205
+ return { ok: false, error: "节点 " + id + " 不是对象" };
206
+ const classType = node.class_type;
207
+ if (typeof classType !== "string" || classType.trim() === "")
208
+ return { ok: false, error: "节点 " + id + " 缺少 class_type" };
209
+ }
210
+ return { ok: true, workflow: record, nodes: ids.length };
211
+ }
212
+ /** 只有界面预览与报错信息用:把工作流里的一批候选输入列出来。 */
213
+ function nodeOrder(workflow) {
214
+ return Object.keys(workflow).sort((a, b) => {
215
+ const na = Number(a);
216
+ const nb = Number(b);
217
+ const fa = Number.isFinite(na);
218
+ const fb = Number.isFinite(nb);
219
+ if (fa && fb)
220
+ return na - nb;
221
+ if (fa !== fb)
222
+ return fa ? -1 : 1;
223
+ return a.localeCompare(b);
224
+ });
225
+ }
226
+ function candidates(workflow, keys, want) {
227
+ const found = [];
228
+ for (const id of nodeOrder(workflow)) {
229
+ const node = workflow[id];
230
+ const inputs = node?.inputs;
231
+ if (inputs === undefined)
232
+ continue;
233
+ for (const key of keys) {
234
+ const value = inputs[key];
235
+ if (value === undefined)
236
+ continue;
237
+ if (want === "string" && typeof value !== "string")
238
+ continue;
239
+ if (want === "number" && typeof value !== "number")
240
+ continue;
241
+ const meta = node?._meta;
242
+ const title = meta !== undefined && typeof meta.title === "string" ? meta.title : (node?.class_type ?? "");
243
+ found.push({ binding: { node: id, input: key }, title });
244
+ }
245
+ }
246
+ return found;
247
+ }
248
+ /**
249
+ * 按节点类型查 ComfyUI 的节点定义。
250
+ *
251
+ * 为什么要查:**工作流里没写的输入,在 JSON 里根本看不见**。FreeVideo 的
252
+ * `FreeVideoMedia.first` 就是这种 optional IMAGE 输入——用户在界面里没连首帧图,
253
+ * 导出的工作流里就没有这个键,只靠「扫工作流里已存在的输入」永远找不到它。
254
+ * 拿到节点定义才知道「这个节点接得下 IMAGE,键名叫 first」,于是能自动补上连线。
255
+ *
256
+ * 查不到(ComfyUI 没启动 / 类型不存在)只跳过不抛错:调用方按「没有额外信息」继续。
257
+ */
258
+ export async function fetchComfyObjectInfo(request, classTypes) {
259
+ const out = {};
260
+ const unique = Array.from(new Set(classTypes.filter((item) => typeof item === "string" && item.trim() !== "")));
261
+ await Promise.all(unique.map(async (classType) => {
262
+ try {
263
+ const response = await comfyFetch(request, "/object_info/" + encodeURIComponent(classType));
264
+ if (response.ok !== true)
265
+ return;
266
+ const data = (await response.json());
267
+ const spec = data[classType];
268
+ if (spec !== undefined)
269
+ out[classType] = spec;
270
+ }
271
+ catch {
272
+ // 单个类型查不到不影响其它类型,也不影响「没有额外信息」这条兜底。
273
+ }
274
+ }));
275
+ return out;
276
+ }
277
+ /** 这个节点定义里哪些输入吃 IMAGE(optional 在前:required 的 IMAGE 输入通常必须自己连)。 */
278
+ function imageInputNames(spec) {
279
+ if (spec === undefined)
280
+ return [];
281
+ const group = spec.input ?? spec;
282
+ const names = [];
283
+ for (const part of [group.optional ?? {}, group.required ?? {}]) {
284
+ for (const [key, value] of Object.entries(part)) {
285
+ if (Array.isArray(value) && value[0] === "IMAGE")
286
+ names.push(key);
287
+ }
288
+ }
289
+ return names;
290
+ }
291
+ /**
292
+ * 在工作流里找一个**接得下 IMAGE 且名字符合候选**的输入,用于自动补首帧 / 尾帧连线。
293
+ * 名字不在候选里的 IMAGE 输入(reference / mask 之类)一律不猜——接错比不接更坏。
294
+ */
295
+ function findImageInput(workflow, info, keys) {
296
+ const wanted = keys.map((key) => key.toLowerCase());
297
+ for (const id of nodeOrder(workflow)) {
298
+ const node = workflow[id];
299
+ if (node === undefined)
300
+ continue;
301
+ for (const name of imageInputNames(info[node.class_type ?? ""])) {
302
+ if (!wanted.includes(name.toLowerCase()))
303
+ continue;
304
+ if (Array.isArray(node.inputs?.[name]))
305
+ continue; // 已被别的连线占用
306
+ return { node: id, input: name };
307
+ }
308
+ }
309
+ return undefined;
310
+ }
311
+ /**
312
+ * 探测注入点。显式覆盖优先;否则按上面的候选名列表,节点按数字 id 升序取第一个。
313
+ * 覆盖写错(节点或输入不存在)时只记一条 note 并回退到自动探测,不抛错——这样设置页的预览也能用。
314
+ */
315
+ export function detectComfyBindings(workflow, overrides = {}, info) {
316
+ const notes = [];
317
+ // 一个 LoadImage 只装一张图:首帧用第一个;尾帧只在真有第二个时才走「替换文件名」这条路。
318
+ // 只有一个 LoadImage 还把尾帧也指过去,注入尾帧时会静默顶掉首帧的图 —— 这种错在界面上看不出来。
319
+ const loadImageIds = nodeOrder(workflow).filter((id) => workflow[id]?.class_type === "LoadImage");
320
+ /** 用户显式填的 `节点ID.输入名`:只有真能写进去才采用,否则记一条 note 并回退。 */
321
+ const overrideBinding = (label, override) => {
322
+ if (override === undefined || override.trim() === "")
323
+ return undefined;
324
+ const binding = parseBinding(override);
325
+ if (binding === undefined) {
326
+ notes.push(label + "覆盖「" + override + "」不是 节点ID.输入名 的写法,已忽略。");
327
+ }
328
+ else if (workflow[binding.node] === undefined) {
329
+ notes.push(label + "覆盖指向的节点 " + binding.node + " 不存在,已忽略。");
330
+ }
331
+ else if (workflow[binding.node].inputs?.[binding.input] === undefined) {
332
+ notes.push(label + "覆盖指向的输入 " + override + " 不存在,已忽略。");
333
+ }
334
+ else {
335
+ return binding;
336
+ }
337
+ return undefined;
338
+ };
339
+ const autoBinding = (label, keys, want) => {
340
+ const list = candidates(workflow, keys, want);
341
+ if (list.length > 1) {
342
+ notes.push(label + "有 " + list.length + " 个候选(" + list.map((item) => item.binding.node + "." + item.binding.input + (item.title === "" ? "" : " " + item.title)).join("、") + "),当前用第一个。");
343
+ }
344
+ return list[0]?.binding;
345
+ };
346
+ const pick = (label, override, keys, want) => overrideBinding(label, override) ?? autoBinding(label, keys, want);
347
+ /**
348
+ * 图像断点分四级找:显式覆盖 → 工作流自带的 LoadImage(替换它的 image 文件名,连线不动)
349
+ * → 工作流里已经写着的 first 类输入 → **节点定义里的 optional IMAGE 输入**(工作流里没写的那种,补连线)。
350
+ * 前两级命中时不再往下扫,免得对着一个用不上的候选报「有多个候选」。
351
+ */
352
+ const locateImage = (label, override, keys, loadImageId) => {
353
+ const explicit = overrideBinding(label, override);
354
+ if (explicit !== undefined)
355
+ return { binding: explicit, source: "override" };
356
+ if (loadImageId !== undefined)
357
+ return { binding: { node: loadImageId, input: "image" }, source: "loadImage" };
358
+ const existing = autoBinding(label, keys, "string");
359
+ if (existing !== undefined)
360
+ return { binding: existing, source: "input" };
361
+ if (info !== undefined) {
362
+ const declared = findImageInput(workflow, info, keys);
363
+ if (declared !== undefined)
364
+ return { binding: declared, source: "declared" };
365
+ }
366
+ return { binding: undefined, source: "none" };
367
+ };
368
+ const first = locateImage("首帧", overrides.first, FIRST_KEYS, loadImageIds[0]);
369
+ // 尾帧拿第二个 LoadImage(没有就交给「已存在的 last 类输入 / 节点定义里的 optional IMAGE」)。
370
+ const last = locateImage("尾帧", overrides.last, LAST_KEYS, loadImageIds[1]);
371
+ const bindings = {
372
+ prompt: pick("提示词", overrides.prompt, PROMPT_KEYS, "string"),
373
+ width: pick("宽度", overrides.width, WIDTH_KEYS, "number"),
374
+ height: pick("高度", overrides.height, HEIGHT_KEYS, "number"),
375
+ seconds: pick("时长", overrides.seconds, SECONDS_KEYS, "number"),
376
+ seed: pick("种子", overrides.seed, SEED_KEYS, "number"),
377
+ first: first.binding,
378
+ last: last.binding
379
+ };
380
+ if (loadImageIds.length > 0)
381
+ bindings.loadImage = loadImageIds[0];
382
+ if (first.source === "loadImage") {
383
+ notes.push("工作流里已有 LoadImage 节点(id=" + (first.binding?.node ?? "") + "),首帧图会直接替换它的 image 文件名。");
384
+ }
385
+ else if (first.source === "declared") {
386
+ notes.push("工作流里没有连首帧图,但按节点定义 " + formatBinding(first.binding) + " 接得下 IMAGE——提交时会插入一个 LoadImage 节点连过去。");
387
+ }
388
+ else if (first.source === "none") {
389
+ notes.push("没有找到首帧图的注入点(既没有 LoadImage 节点,也没有 first 之类的 IMAGE 输入)——图生视频会在提交时报错。");
390
+ }
391
+ if (last.source === "declared") {
392
+ notes.push("尾帧图会接到 " + formatBinding(last.binding) + "(工作流里原本没连这个 IMAGE 输入)。");
393
+ }
394
+ return { bindings, notes };
395
+ }
396
+ function cloneWorkflow(workflow) {
397
+ return JSON.parse(JSON.stringify(workflow));
398
+ }
399
+ function nextNodeId(workflow) {
400
+ let max = 0;
401
+ for (const id of Object.keys(workflow)) {
402
+ const value = Number(id);
403
+ if (Number.isFinite(value) && value > max)
404
+ max = Math.floor(value);
405
+ }
406
+ let candidate = String(max + 1);
407
+ while (Object.prototype.hasOwnProperty.call(workflow, candidate))
408
+ candidate = String(Number(candidate) + 1);
409
+ return candidate;
410
+ }
411
+ function injectImage(workflow, bindings, name, which, notes) {
412
+ const target = which === "first" ? bindings.first : bindings.last;
413
+ const label = which === "first" ? "首帧" : "尾帧";
414
+ if (target === undefined) {
415
+ if (which === "first") {
416
+ throw new ComfyError("工作流里没有可以接收首帧图的位置:请在工作流里放一个 LoadImage 节点(把它的 IMAGE 输出连给视频节点)," +
417
+ "或在设置页把「首帧图注入点」填成 节点ID.输入名(例如 2.first)。" +
418
+ "如果这个节点确实有 IMAGE 输入却仍报这一条,多半是 ComfyUI 没在配置的地址上跑,读不到它的节点定义。");
419
+ }
420
+ notes.push("工作流里没有尾帧输入,尾帧图已忽略。");
421
+ return;
422
+ }
423
+ const node = workflow[target.node];
424
+ if (node === undefined)
425
+ throw new ComfyError("首帧目标 " + formatBinding(target) + " 指向的节点不存在。");
426
+ if (node.class_type === "LoadImage" && target.input === "image") {
427
+ node.inputs = { ...(node.inputs ?? {}), image: name };
428
+ notes.push("已把" + label + "图替换为 " + name + "(工作流自带的 LoadImage 节点 " + target.node + ")。");
429
+ return;
430
+ }
431
+ const newId = nextNodeId(workflow);
432
+ workflow[newId] = { class_type: "LoadImage", inputs: { image: name }, _meta: { title: "游戏素材大师 · " + label + "图" } };
433
+ node.inputs = { ...(node.inputs ?? {}) };
434
+ node.inputs[target.input] = [newId, 0];
435
+ notes.push("已插入 LoadImage 节点 " + newId + ",把 " + name + " 接到 " + formatBinding(target) + "。");
436
+ }
437
+ export function applyComfyInputs(workflow, bindings, input) {
438
+ const next = cloneWorkflow(workflow);
439
+ const notes = [];
440
+ const writeLiteral = (binding, value, label) => {
441
+ if (binding === undefined)
442
+ return false;
443
+ const node = next[binding.node];
444
+ if (node === undefined)
445
+ return false;
446
+ const inputs = node.inputs ?? {};
447
+ if (Array.isArray(inputs[binding.input])) {
448
+ notes.push(label + "目标 " + formatBinding(binding) + " 现在是连线,已跳过注入(要在 ComfyUI 里先断开这条连线)。");
449
+ return false;
450
+ }
451
+ node.inputs = { ...inputs, [binding.input]: value };
452
+ return true;
453
+ };
454
+ if (typeof input.prompt === "string" && input.prompt !== "") {
455
+ if (bindings.prompt === undefined) {
456
+ throw new ComfyError("工作流里找不到可以写入提示词的文本输入:请放一个提示词节点,或在设置页把「提示词目标」填成 节点ID.输入名。");
457
+ }
458
+ writeLiteral(bindings.prompt, input.prompt, "提示词");
459
+ }
460
+ if (typeof input.width === "number" && input.width > 0)
461
+ writeLiteral(bindings.width, Math.round(input.width), "宽度");
462
+ if (typeof input.height === "number" && input.height > 0)
463
+ writeLiteral(bindings.height, Math.round(input.height), "高度");
464
+ if (typeof input.seconds === "number" && input.seconds > 0)
465
+ writeLiteral(bindings.seconds, Math.round(input.seconds * 100) / 100, "时长");
466
+ if (typeof input.seed === "number" && Number.isFinite(input.seed))
467
+ writeLiteral(bindings.seed, Math.max(0, Math.floor(input.seed)), "种子");
468
+ if (typeof input.firstImageName === "string" && input.firstImageName !== "") {
469
+ injectImage(next, bindings, input.firstImageName, "first", notes);
470
+ // FreeVideo 这类节点有「首帧参考」开关,注入首帧后必须打开它,否则图不参与。
471
+ for (const id of Object.keys(next)) {
472
+ const node = next[id];
473
+ if (node !== undefined && node.inputs !== undefined && node.inputs.first_frame_reference === false) {
474
+ node.inputs = { ...node.inputs, first_frame_reference: true };
475
+ notes.push("已把 " + id + ".first_frame_reference 置为 true,让注入的首帧真正参与生成。");
476
+ }
477
+ }
478
+ }
479
+ if (typeof input.lastImageName === "string" && input.lastImageName !== "") {
480
+ injectImage(next, bindings, input.lastImageName, "last", notes);
481
+ }
482
+ return { workflow: next, bindings, notes };
483
+ }
484
+ /**
485
+ * 内置默认工作流:FreeVideo(本机装了这个扩展就能直接跑)。
486
+ *
487
+ * 结构对照 FreeVideo 节点在 `/object_info` 里的定义:
488
+ * - `FreeVideoGenerate.text` 是提示词(required STRING),尺寸 / 时长 / 种子都在这一个节点上;
489
+ * - `FreeVideoGenerate.first_frame_reference` 是「首帧参考」开关,注入首帧后必须为 true;
490
+ * - `FreeVideoGenerate.media` 连 `FreeVideoMedia` 的输出;
491
+ * - 首帧图接 `FreeVideoGenerate.first`——官方示例 FreeVideo-All-in-One 就是这么接的。
492
+ *
493
+ * 所以模板自带一个空的 LoadImage(节点 3)并连到 `FreeVideoGenerate.first`:插件把上传后的文件名写进它的
494
+ * `image`,连线不动——比「提交时现插一个节点」稳,也省得用户自己接一遍。
495
+ */
496
+ export const DEFAULT_COMFY_WORKFLOW_TEXT = JSON.stringify({
497
+ "1": {
498
+ inputs: {
499
+ text: "在这里写提示词(插件会用项目里的提示词自动替换这一项)",
500
+ width: 512,
501
+ height: 512,
502
+ seconds: 4,
503
+ seed: 0,
504
+ two_pass: true,
505
+ base_steps: 8,
506
+ refine_steps: 3,
507
+ force_regenerate: false,
508
+ preview: false,
509
+ refine_from: "",
510
+ continue_from: "",
511
+ frames: 0,
512
+ first_frame_reference: true,
513
+ first: ["3", 0],
514
+ media: ["2", 0]
515
+ },
516
+ class_type: "FreeVideoGenerate",
517
+ _meta: { title: "FreeVideo" }
518
+ },
519
+ "2": {
520
+ inputs: { assets: "[]" },
521
+ class_type: "FreeVideoMedia",
522
+ _meta: { title: "FreeVideo 素材" }
523
+ },
524
+ "3": {
525
+ inputs: { image: "" },
526
+ class_type: "LoadImage",
527
+ _meta: { title: "游戏素材大师 · 首帧图" }
528
+ }
529
+ }, null, 2);
530
+ function newClientId() {
531
+ try {
532
+ return "gmm-" + randomUUID();
533
+ }
534
+ catch {
535
+ return "gmm-" + Date.now() + "-" + Math.random().toString(16).slice(2);
536
+ }
537
+ }
538
+ async function comfyFetch(request, path, init) {
539
+ const base = normalizeComfyBaseUrl(request.baseUrl);
540
+ const timeoutMs = Math.max(5000, Math.round(request.timeoutMs));
541
+ const timeout = AbortSignal.timeout(timeoutMs);
542
+ // 鉴权反代后面:所有请求(状态、上传、提交、查询)都带上同一份 Cookie。
543
+ const cookies = normalizeComfyCookies(request.cookies);
544
+ const headers = new Headers(init?.headers ?? undefined);
545
+ if (cookies !== "")
546
+ headers.set("Cookie", cookies);
547
+ try {
548
+ return await fetch(base + path, { ...(init ?? {}), headers, signal: timeout });
549
+ }
550
+ catch (error) {
551
+ const reason = error instanceof Error ? error.message : String(error);
552
+ if (timeout.aborted === true)
553
+ throw new ComfyError("本地 ComfyUI 请求超时(" + Math.round(timeoutMs / 1000) + " 秒):" + path);
554
+ throw new ComfyError("无法连接本地 ComfyUI(" + base + "):" + reason + "。请确认 ComfyUI 正在运行。");
555
+ }
556
+ }
557
+ async function comfyJson(request, path, init) {
558
+ const response = await comfyFetch(request, path, init);
559
+ const text = await response.text().catch(() => "");
560
+ if (response.ok !== true) {
561
+ throw new ComfyError("ComfyUI " + path + " 返回 HTTP " + response.status + ":" + (text.slice(0, 400) === "" ? response.statusText : text.slice(0, 400)), response.status);
562
+ }
563
+ const trimmed = text.trim();
564
+ if (trimmed === "")
565
+ return undefined;
566
+ try {
567
+ return JSON.parse(trimmed);
568
+ }
569
+ catch {
570
+ throw new ComfyError("ComfyUI " + path + " 返回的不是 JSON:" + trimmed.slice(0, 200));
571
+ }
572
+ }
573
+ /** 连通性自检:读 /system_stats 与 /queue。 */
574
+ export async function testComfy(request) {
575
+ const stats = await comfyJson(request, "/system_stats");
576
+ const version = typeof stats?.system?.comfyui_version === "string" ? stats.system.comfyui_version : "未知";
577
+ const device = Array.isArray(stats?.devices) && typeof stats.devices[0]?.name === "string" ? stats.devices[0].name : undefined;
578
+ const queue = await comfyJson(request, "/queue").catch(() => undefined);
579
+ const running = Array.isArray(queue?.queue_running) ? queue.queue_running.length : 0;
580
+ const pending = Array.isArray(queue?.queue_pending) ? queue.queue_pending.length : 0;
581
+ return { ok: true, version, device, queueRunning: running, queuePending: pending };
582
+ }
583
+ export async function submitComfyVideo(request) {
584
+ const payload = await comfyJson(request, "/prompt", {
585
+ method: "POST",
586
+ headers: { "Content-Type": "application/json" },
587
+ body: JSON.stringify({ prompt: request.workflow, client_id: newClientId() })
588
+ });
589
+ const nodeErrors = payload?.node_errors;
590
+ if (nodeErrors !== undefined && nodeErrors !== null && typeof nodeErrors === "object" && Object.keys(nodeErrors).length > 0) {
591
+ throw new ComfyError("ComfyUI 拒绝了这个工作流:" + JSON.stringify(nodeErrors).slice(0, 500));
592
+ }
593
+ if (payload?.error !== undefined && payload.error !== null) {
594
+ throw new ComfyError("ComfyUI 提交失败:" + JSON.stringify(payload.error).slice(0, 400));
595
+ }
596
+ const promptId = payload?.prompt_id;
597
+ if (typeof promptId !== "string" || promptId === "") {
598
+ throw new ComfyError("ComfyUI 没有返回 prompt_id:" + JSON.stringify(payload).slice(0, 300));
599
+ }
600
+ return promptId;
601
+ }
602
+ export function comfyViewUrl(baseUrl, file) {
603
+ const params = new URLSearchParams();
604
+ params.set("filename", file.filename);
605
+ if (file.subfolder !== undefined && file.subfolder !== "")
606
+ params.set("subfolder", file.subfolder);
607
+ params.set("type", file.type === undefined || file.type === "" ? "output" : file.type);
608
+ return normalizeComfyBaseUrl(baseUrl) + "/view?" + params.toString();
609
+ }
610
+ function scoreOutput(item, filename) {
611
+ const metadata = item.metadata;
612
+ const kind = metadata !== null && typeof metadata === "object" ? metadata.kind : undefined;
613
+ const ext = filename.slice(filename.lastIndexOf(".") + 1).toLowerCase();
614
+ const isImage = ext === "png" || ext === "jpg" || ext === "jpeg" || ext === "webp" || ext === "bmp";
615
+ const isAudio = ext === "flac" || ext === "wav" || ext === "mp3" || ext === "ogg";
616
+ let score = 0;
617
+ if (kind === "video")
618
+ score += 5;
619
+ else if (typeof kind === "string" && kind !== "")
620
+ score -= 3;
621
+ if (ext === "mp4" || ext === "webm" || ext === "mkv" || ext === "mov")
622
+ score += 4;
623
+ else if (ext === "gif")
624
+ score += 2;
625
+ else if (isImage)
626
+ score -= 5;
627
+ else if (isAudio)
628
+ score -= 4;
629
+ else
630
+ score += 1;
631
+ return score;
632
+ }
633
+ function pickVideoFile(outputs, baseUrl) {
634
+ if (outputs === null || typeof outputs !== "object")
635
+ return undefined;
636
+ let best;
637
+ for (const nodeId of Object.keys(outputs)) {
638
+ const nodeOut = outputs[nodeId];
639
+ if (nodeOut === null || typeof nodeOut !== "object")
640
+ continue;
641
+ for (const key of Object.keys(nodeOut)) {
642
+ const list = nodeOut[key];
643
+ if (!Array.isArray(list))
644
+ continue;
645
+ for (const raw of list) {
646
+ if (raw === null || typeof raw !== "object")
647
+ continue;
648
+ const item = raw;
649
+ const filename = typeof item.filename === "string" ? item.filename : "";
650
+ if (filename === "")
651
+ continue;
652
+ const score = scoreOutput(item, filename);
653
+ if (score <= 0)
654
+ continue;
655
+ if (best === undefined || score > best.score) {
656
+ const subfolder = typeof item.subfolder === "string" ? item.subfolder : "";
657
+ const type = typeof item.type === "string" ? item.type : "output";
658
+ best = { score, file: { filename, subfolder, type, url: comfyViewUrl(baseUrl, { filename, subfolder, type }) } };
659
+ }
660
+ }
661
+ }
662
+ }
663
+ return best?.file;
664
+ }
665
+ function extractHistoryError(entry) {
666
+ const messages = entry?.status?.messages;
667
+ if (Array.isArray(messages)) {
668
+ for (const message of messages) {
669
+ if (Array.isArray(message) && message[0] === "execution_error" && message[1] !== null && typeof message[1] === "object") {
670
+ const info = message[1];
671
+ const parts = [info.node_type, info.exception_type, info.exception_message].filter((value) => typeof value === "string" && value !== "");
672
+ if (parts.length > 0)
673
+ return "ComfyUI 执行失败:" + parts.join(" / ");
674
+ }
675
+ }
676
+ }
677
+ return "ComfyUI 执行失败(history 里没有更详细的信息)";
678
+ }
679
+ export async function queryComfyVideo(request) {
680
+ const history = await comfyJson(request, "/history/" + encodeURIComponent(request.promptId));
681
+ const entry = history === null || typeof history !== "object" ? undefined : history[request.promptId];
682
+ if (entry !== undefined && entry !== null && typeof entry === "object") {
683
+ const record = entry;
684
+ const statusStr = typeof record?.status?.status_str === "string" ? record.status.status_str : "";
685
+ if (statusStr === "error")
686
+ return { status: "failed", remoteStatus: "error", error: extractHistoryError(record), raw: record };
687
+ if (record?.status?.completed === true || statusStr === "success") {
688
+ const file = pickVideoFile(record?.outputs, request.baseUrl);
689
+ if (file === undefined) {
690
+ return { status: "failed", remoteStatus: "empty", error: "ComfyUI 执行完成,但输出里没有视频文件(检查工作流的终点节点是不是视频节点)。", raw: record };
691
+ }
692
+ return { status: "succeeded", remoteStatus: "success", file, videoUrl: file.url, raw: record };
693
+ }
694
+ return { status: "running", remoteStatus: statusStr === "" ? "running" : statusStr, raw: record };
695
+ }
696
+ const queue = await comfyJson(request, "/queue").catch(() => undefined);
697
+ const running = Array.isArray(queue?.queue_running) ? queue.queue_running : [];
698
+ const pending = Array.isArray(queue?.queue_pending) ? queue.queue_pending : [];
699
+ const inRunning = running.some((item) => Array.isArray(item) && item[1] === request.promptId);
700
+ if (inRunning)
701
+ return { status: "running", remoteStatus: "running" };
702
+ const index = pending.findIndex((item) => Array.isArray(item) && item[1] === request.promptId);
703
+ if (index >= 0)
704
+ return { status: "pending", remoteStatus: "排队中(前面还有 " + index + " 个任务)" };
705
+ return { status: "pending", remoteStatus: "等待 ComfyUI 接收" };
706
+ }
707
+ function extForMime(mime) {
708
+ const lower = mime.toLowerCase();
709
+ if (lower === "image/jpeg" || lower === "image/jpg")
710
+ return "jpg";
711
+ if (lower === "image/webp")
712
+ return "webp";
713
+ if (lower === "image/bmp")
714
+ return "bmp";
715
+ return "png";
716
+ }
717
+ /** 把 data URI(或裸 base64)解码成字节。 */
718
+ export function decodeDataUri(value) {
719
+ const trimmed = (value ?? "").trim();
720
+ if (trimmed === "")
721
+ throw new ComfyError("参考图数据是空的");
722
+ const match = /^data:([^;,]*)(;base64)?,(.*)$/s.exec(trimmed);
723
+ if (match !== null) {
724
+ const mime = match[1] !== undefined && match[1] !== "" ? match[1] : "image/png";
725
+ const payload = match[2] === undefined ? decodeURIComponent(match[3]) : Buffer.from(match[3], "base64");
726
+ const bytes = Buffer.isBuffer(payload) ? payload : Buffer.from(payload, "utf8");
727
+ if (bytes.length === 0)
728
+ throw new ComfyError("参考图数据是空的");
729
+ return { bytes, mime, ext: extForMime(mime) };
730
+ }
731
+ if (/^https?:/i.test(trimmed)) {
732
+ throw new ComfyError("本地 ComfyUI 只接收本机图片字节,不接受 http(s) 图片地址。");
733
+ }
734
+ const bytes = Buffer.from(trimmed, "base64");
735
+ if (bytes.length === 0)
736
+ throw new ComfyError("参考图数据是空的");
737
+ return { bytes, mime: "image/png", ext: "png" };
738
+ }
739
+ /** 上传一张参考图到 ComfyUI 的 input 目录,返回 LoadImage 能用的文件名。 */
740
+ export async function uploadComfyImage(request, dataUri, prefix = "gmm") {
741
+ const decoded = decodeDataUri(dataUri);
742
+ const name = prefix + "_" + Date.now().toString(36) + "_" + Math.random().toString(36).slice(2, 8) + "." + decoded.ext;
743
+ const form = new FormData();
744
+ form.append("image", new Blob([new Uint8Array(decoded.bytes)], { type: decoded.mime }), name);
745
+ form.append("overwrite", "true");
746
+ form.append("type", "input");
747
+ const response = await comfyFetch(request, "/upload/image", { method: "POST", body: form });
748
+ const text = await response.text().catch(() => "");
749
+ if (response.ok !== true) {
750
+ throw new ComfyError("上传参考图到 ComfyUI 失败(HTTP " + response.status + "):" + text.slice(0, 300), response.status);
751
+ }
752
+ let payload;
753
+ try {
754
+ payload = JSON.parse(text);
755
+ }
756
+ catch {
757
+ throw new ComfyError("上传参考图返回的不是 JSON:" + text.slice(0, 200));
758
+ }
759
+ const fileName = typeof payload?.name === "string" ? payload.name : "";
760
+ if (fileName === "")
761
+ throw new ComfyError("上传参考图失败:" + text.slice(0, 200));
762
+ const subfolder = typeof payload?.subfolder === "string" ? payload.subfolder : "";
763
+ return subfolder === "" ? fileName : subfolder + "/" + fileName;
764
+ }
765
+ export function prepareComfyWorkflow(input) {
766
+ const detected = detectComfyBindings(input.workflow, input.overrides ?? {}, input.info);
767
+ const applied = applyComfyInputs(input.workflow, detected.bindings, input);
768
+ return { workflow: applied.workflow, bindings: applied.bindings, notes: [...detected.notes, ...applied.notes] };
769
+ }