@duke-dsh-plugins/dsh-remote-control 0.0.0-stage → 1.1.3
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/LICENSE +21 -0
- package/README.md +88 -3
- package/client.js +747 -0
- package/cordis.patch.yml +12 -0
- package/icon.svg +20 -0
- package/index.js +731 -0
- package/lib/config.mjs +270 -0
- package/lib/host-bridge.mjs +2848 -0
- package/lib/images.mjs +458 -0
- package/lib/pairing.mjs +266 -0
- package/lib/protocol.mjs +390 -0
- package/lib/push.mjs +229 -0
- package/lib/qr.mjs +439 -0
- package/lib/relay-client.mjs +741 -0
- package/lib/relay-supervisor.mjs +798 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +75 -6
- package/typert.host.js +243 -0
- package/vendor/relay/server.js +777 -0
package/lib/images.mjs
ADDED
|
@@ -0,0 +1,458 @@
|
|
|
1
|
+
// lib/images.mjs —— 会话消息里的图片处理(契约 §5.10「会话消息里的图片(v1.0.9)」
|
|
2
|
+
// 与 §5.1 的 `image.fetch` 行)。
|
|
3
|
+
//
|
|
4
|
+
// 背景(宿主实证):DSH 会话消息的 content 块里图片是**附件引用**,不是内联 base64:
|
|
5
|
+
// { type:'image', attachment:{ attachmentId, mediaType, bytes, width, height, name? } }
|
|
6
|
+
// 附件服务在 Cordis ctx 里叫 `attachments`(本地后端 dsh-attachment-local 实现),
|
|
7
|
+
// 有 imageHostPath(ref)(宿主文件系统绝对路径)与 readImage(ref, signal)(原始字节)。
|
|
8
|
+
//
|
|
9
|
+
// 中继单帧上限 **1MiB**(密文帧),原图直传必然超限,故走契约的两段式:
|
|
10
|
+
// ① 缩略图**内联**(长边 ≤480、JPEG q75、base64 ≤96KB)——事件/历史里立刻能显示;
|
|
11
|
+
// ② 大图按需 `image.fetch` 拉取(等比缩放 + JPEG q85、base64 ≤1MiB 预算)。
|
|
12
|
+
//
|
|
13
|
+
// 本模块只做「图片 ↔ data URI」的纯加工;**读附件字节**在 host-bridge(那里才有 ctx)。
|
|
14
|
+
//
|
|
15
|
+
// sharp 不在插件自己的 node_modules 里(插件是 link 安装,依赖解析走真实路径),
|
|
16
|
+
// 故用 createRequire 从 **DSH 部署目录**动态解析;解析不到就**降级**(只发元数据、
|
|
17
|
+
// thumb 留空),绝不抛异常崩掉插件。
|
|
18
|
+
import { createRequire } from "node:module";
|
|
19
|
+
import { homedir } from "node:os";
|
|
20
|
+
import { dirname, join } from "node:path";
|
|
21
|
+
|
|
22
|
+
/** 宿主接受的图片类型(dsh-attachment 的 ImageMediaType)。 */
|
|
23
|
+
export const IMAGE_MEDIA_TYPES = Object.freeze(["image/png", "image/jpeg", "image/webp", "image/gif"]);
|
|
24
|
+
|
|
25
|
+
/** 缩略图长边上限(契约 §5.10:长边 ≤ 480、JPEG q75)。 */
|
|
26
|
+
export const THUMB_MAX_EDGE = 480;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* 按文件扩展名猜媒体类型(**不读文件**,纯字符串判断)。
|
|
30
|
+
*
|
|
31
|
+
* 用途:宿主 `present` 工具投递的文件(deliverables/presented 事件)只有路径,
|
|
32
|
+
* 没有附件元数据;插件要把它当图片转发给手机端,就得自己认类型。
|
|
33
|
+
* 非图片(.md/.zip/…)返回 '' —— 留给别的通道(文件卡片)处理。
|
|
34
|
+
* @param {string} path 文件路径
|
|
35
|
+
* @returns {string} 媒体类型或 ''
|
|
36
|
+
*/
|
|
37
|
+
export function mediaTypeOfPath(path) {
|
|
38
|
+
if (typeof path !== "string") return "";
|
|
39
|
+
const m = /\.(png|jpe?g|gif|webp)$/i.exec(path.trim());
|
|
40
|
+
if (!m) return "";
|
|
41
|
+
const ext = m[1].toLowerCase();
|
|
42
|
+
if (ext === "png") return "image/png";
|
|
43
|
+
if (ext === "jpg" || ext === "jpeg") return "image/jpeg";
|
|
44
|
+
if (ext === "gif") return "image/gif";
|
|
45
|
+
if (ext === "webp") return "image/webp";
|
|
46
|
+
return "";
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* 读图片原始尺寸(sharp 不可用 → {width:0,height:0},**绝不抛**)。
|
|
51
|
+
*
|
|
52
|
+
* 宿主附件自带 width/height,但 present 出来的文件没有 → 插件自己量。
|
|
53
|
+
* @param {Buffer|Uint8Array|ArrayBuffer} buffer 原始字节
|
|
54
|
+
* @returns {Promise<{width:number,height:number}>}
|
|
55
|
+
*/
|
|
56
|
+
export async function imageMetaOf(buffer) {
|
|
57
|
+
const input = toBytes(buffer);
|
|
58
|
+
if (input === null || input.length === 0) return { width: 0, height: 0 };
|
|
59
|
+
const sharp = loadSharp();
|
|
60
|
+
if (!sharp) return { width: 0, height: 0 };
|
|
61
|
+
try {
|
|
62
|
+
const meta = await sharp(input, { animated: false }).metadata();
|
|
63
|
+
return { width: Number(meta?.width) || 0, height: Number(meta?.height) || 0 };
|
|
64
|
+
} catch {
|
|
65
|
+
return { width: 0, height: 0 };
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** 缩略图 base64 字节上限(契约 §5.10:必须压缩到 ≤ 96KB base64)。 */
|
|
70
|
+
export const THUMB_MAX_BASE64 = 96 * 1024;
|
|
71
|
+
|
|
72
|
+
/** 大图缺省长边(契约 §5.1 image.fetch:maxEdge 缺省 1600)。 */
|
|
73
|
+
export const LARGE_DEFAULT_MAX_EDGE = 1600;
|
|
74
|
+
|
|
75
|
+
/** 大图长边上限(契约 §5.1 image.fetch:上限 4096)。 */
|
|
76
|
+
export const LARGE_MAX_EDGE = 4096;
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* 大图 base64 字节上限。
|
|
80
|
+
*
|
|
81
|
+
* 契约写的是「单张回包 ≤ 1MiB(中继硬上限)」,但中继的 1MiB 限制落在 **密文帧**上
|
|
82
|
+
* (relay/server.js 的 RELAY_MAX_PAYLOAD=1048576,ws maxPayload,收发两个方向都算),
|
|
83
|
+
* 而密文帧 = base64url(iv+ct+tag),明文 JSON 会被放大约 4/3 倍。
|
|
84
|
+
* 这里给 base64 留 600KB 预算:600KB base64 → 明文 ≈600KB → 密文 ≈600KB →
|
|
85
|
+
* base64url ≈800KB < 1MiB(余量留给信封/sid/seq 与 JSON 转义),**绝不会**把中继连接顶爆。
|
|
86
|
+
* 取 600KB 也满足契约「≤1MiB」(更保守)。
|
|
87
|
+
*/
|
|
88
|
+
export const LARGE_MAX_BASE64 = 600 * 1024;
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* 中继单帧上限(relay/server.js RELAY_MAX_PAYLOAD = 1MiB,ws maxPayload)。
|
|
92
|
+
* 超了 ws 直接**断开连接**(1009),不是「丢一帧」——所以回包必须自己守住。
|
|
93
|
+
*/
|
|
94
|
+
export const RELAY_MAX_FRAME_BYTES = 1024 * 1024;
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* 回包明文 JSON 预算(帧预算守卫用)。
|
|
98
|
+
*
|
|
99
|
+
* 帧里装的是 base64url(iv||密文||tag),密文长度 = 明文长度 → 帧 ≈ 明文 × 4/3。
|
|
100
|
+
* 640KB 明文 → 帧 ≈ 853KB < 1MiB(留 18% 余量给信封/sid/seq 与 JSON 转义)。
|
|
101
|
+
*/
|
|
102
|
+
export const REPLY_PLAIN_MAX_BYTES = 640 * 1024;
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* 一页历史里**所有缩略图**的总预算(base64 字节)。
|
|
106
|
+
*
|
|
107
|
+
* 页里几十张图 × 96KB 会把回包顶到中继上限之外 → 整条链路被 ws 断开。
|
|
108
|
+
* 故缩略图总量单独设预算(512KB),超出的图片只发元数据(thumb 留空)。
|
|
109
|
+
*/
|
|
110
|
+
export const THUMB_PAGE_BUDGET = 512 * 1024;
|
|
111
|
+
|
|
112
|
+
/** 缩略图 data URI 前缀(缩略图统一转 JPEG)。 */
|
|
113
|
+
export const THUMB_DATA_URI_PREFIX = "data:image/jpeg;base64,";
|
|
114
|
+
|
|
115
|
+
/** 缩略图质量阶梯(契约 §5.10:超限时「降质重压」)。 */
|
|
116
|
+
export const THUMB_LADDER = Object.freeze([
|
|
117
|
+
{ edge: THUMB_MAX_EDGE, quality: 75 },
|
|
118
|
+
{ edge: THUMB_MAX_EDGE, quality: 60 },
|
|
119
|
+
{ edge: 400, quality: 55 },
|
|
120
|
+
{ edge: 320, quality: 50 },
|
|
121
|
+
{ edge: 240, quality: 45 },
|
|
122
|
+
{ edge: 160, quality: 40 },
|
|
123
|
+
]);
|
|
124
|
+
|
|
125
|
+
/** 大图质量阶梯(先降质再降尺寸;每一步都保长边 ≤ maxEdge)。 */
|
|
126
|
+
export const LARGE_LADDER = Object.freeze([
|
|
127
|
+
{ scale: 1, quality: 85 },
|
|
128
|
+
{ scale: 1, quality: 70 },
|
|
129
|
+
{ scale: 0.8, quality: 70 },
|
|
130
|
+
{ scale: 0.8, quality: 60 },
|
|
131
|
+
{ scale: 0.6, quality: 60 },
|
|
132
|
+
{ scale: 0.45, quality: 55 },
|
|
133
|
+
{ scale: 0.3, quality: 50 },
|
|
134
|
+
{ scale: 0.2, quality: 45 },
|
|
135
|
+
{ scale: 0.12, quality: 40 },
|
|
136
|
+
]);
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* 隐藏的附件引用槽位。
|
|
140
|
+
*
|
|
141
|
+
* ImageRef 走 wire(JSON.stringify)时不能带宿主引用对象(attachmentId 之外的字段
|
|
142
|
+
* 是宿主内部结构,且可能很大)——所以用**不可枚举**的 symbol 挂上去:
|
|
143
|
+
* 既能在插件内部拿到原始引用(读字节、缩略图),又绝不会进 JSON。
|
|
144
|
+
*/
|
|
145
|
+
const REF = Symbol("dshrc.attachmentRef");
|
|
146
|
+
|
|
147
|
+
/** sharp 解析器(默认按部署目录解析;可被单测替换)。null = 尚未尝试。 */
|
|
148
|
+
let sharpCache = null;
|
|
149
|
+
|
|
150
|
+
/** 单测注入点(生产代码不调用):替换 sharp 解析器。传 null 恢复默认解析。 */
|
|
151
|
+
let sharpResolver = null;
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* 注入 sharp 解析器(**仅供单测**)。
|
|
155
|
+
* @param {(() => any)|null} provider 返回 sharp 模块;返回 null/抛错 = 视为不可用
|
|
156
|
+
*/
|
|
157
|
+
export function setSharpResolver(provider) {
|
|
158
|
+
sharpResolver = typeof provider === "function" ? provider : null;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** DSH 部署目录候选(sharp 就装在 <deploy>/node_modules/sharp)。 */
|
|
162
|
+
function deployRoots() {
|
|
163
|
+
const roots = [];
|
|
164
|
+
const env = process.env ?? {};
|
|
165
|
+
if (typeof env.DSH_DEPLOY_DIR === "string" && env.DSH_DEPLOY_DIR !== "") roots.push(env.DSH_DEPLOY_DIR);
|
|
166
|
+
// ① 宿主包位置反推:<deploy>/node_modules/@deepseek-ai/dsh/package.json → <deploy>
|
|
167
|
+
try {
|
|
168
|
+
const req = createRequire(import.meta.url);
|
|
169
|
+
const pkg = req.resolve("@deepseek-ai/dsh/package.json");
|
|
170
|
+
roots.push(dirname(dirname(dirname(pkg))));
|
|
171
|
+
} catch {
|
|
172
|
+
/* 宿主包不可见(插件单独跑时) */
|
|
173
|
+
}
|
|
174
|
+
// ② 宿主进程入口反推:<deploy>/node_modules/@deepseek-ai/dsh/lib/bin.js → <deploy>
|
|
175
|
+
if (typeof process.argv?.[1] === "string" && process.argv[1] !== "") {
|
|
176
|
+
const entry = process.argv[1];
|
|
177
|
+
roots.push(dirname(entry));
|
|
178
|
+
roots.push(dirname(dirname(dirname(entry))));
|
|
179
|
+
}
|
|
180
|
+
const appdata = typeof env.APPDATA === "string" ? env.APPDATA : "";
|
|
181
|
+
if (appdata !== "") roots.push(join(appdata, "DeepSeek Harness Desktop", "dsh"));
|
|
182
|
+
// 同一台机器上的其它常见部署路径(Windows / Linux / macOS)
|
|
183
|
+
roots.push(join(homedir(), "AppData", "Roaming", "DeepSeek Harness Desktop", "dsh"));
|
|
184
|
+
roots.push(join(homedir(), ".local", "share", "DeepSeek Harness Desktop", "dsh"));
|
|
185
|
+
roots.push(join(homedir(), "Library", "Application Support", "DeepSeek Harness Desktop", "dsh"));
|
|
186
|
+
return roots;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* 解析 sharp 模块(尽力而为,**不抛**)。
|
|
191
|
+
*
|
|
192
|
+
* 插件自己的 node_modules 里没有 sharp(link 安装 + 依赖不打包),只能从 DSH 部署
|
|
193
|
+
* 目录动态解析;解析不到时调用方必须降级(只发元数据),不能崩。
|
|
194
|
+
* @returns {any|null} sharp 模块或 null
|
|
195
|
+
*/
|
|
196
|
+
export function loadSharp() {
|
|
197
|
+
if (sharpResolver !== null) {
|
|
198
|
+
try {
|
|
199
|
+
return sharpResolver() ?? null;
|
|
200
|
+
} catch {
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
if (sharpCache !== null) return sharpCache;
|
|
205
|
+
// ① 插件自身依赖(万一以后把它列进 dependencies)
|
|
206
|
+
try {
|
|
207
|
+
sharpCache = createRequire(import.meta.url)("sharp");
|
|
208
|
+
return sharpCache;
|
|
209
|
+
} catch {
|
|
210
|
+
/* 继续找部署目录 */
|
|
211
|
+
}
|
|
212
|
+
// ② DSH 部署目录
|
|
213
|
+
for (const root of deployRoots()) {
|
|
214
|
+
try {
|
|
215
|
+
const req = createRequire(join(root, "package.json"));
|
|
216
|
+
sharpCache = req("sharp");
|
|
217
|
+
if (sharpCache) return sharpCache;
|
|
218
|
+
} catch {
|
|
219
|
+
/* 换下一个候选 */
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
sharpCache = null;
|
|
223
|
+
return null;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** 各种字节形态 → Buffer(认 Buffer / Uint8Array / ArrayBuffer / {data})。 */
|
|
227
|
+
function toBytes(input) {
|
|
228
|
+
if (input === null || input === undefined) return null;
|
|
229
|
+
if (Buffer.isBuffer(input)) return input;
|
|
230
|
+
if (input instanceof Uint8Array) return Buffer.from(input.buffer, input.byteOffset, input.byteLength);
|
|
231
|
+
if (input instanceof ArrayBuffer) return Buffer.from(input);
|
|
232
|
+
if (typeof input === "object" && input.data !== undefined && input.data !== null) return toBytes(input.data);
|
|
233
|
+
return null;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* 内容块数组 → 图片附件引用数组(契约 §5.10 的 `type:'image'` 块)。
|
|
238
|
+
*
|
|
239
|
+
* 只取带 `attachment` 的 image 块;结构不认识的一律跳过(绝不抛)。
|
|
240
|
+
* @param {unknown} content ContentBlock[]
|
|
241
|
+
* @returns {object[]} 附件引用(宿主 ImageAttachmentRef 原样)
|
|
242
|
+
*/
|
|
243
|
+
export function imageBlocksOf(content) {
|
|
244
|
+
if (!Array.isArray(content)) return [];
|
|
245
|
+
const out = [];
|
|
246
|
+
for (const block of content) {
|
|
247
|
+
if (!block || typeof block !== "object") continue;
|
|
248
|
+
if (block.type !== "image") continue;
|
|
249
|
+
const ref = block.attachment;
|
|
250
|
+
if (!ref || typeof ref !== "object") continue;
|
|
251
|
+
out.push(ref);
|
|
252
|
+
}
|
|
253
|
+
return out;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* 附件引用 → wire ImageRef(契约 §5.10)。
|
|
258
|
+
*
|
|
259
|
+
* 只带**元数据**(imageId=宿主 attachmentId、mediaType、width、height、bytes),
|
|
260
|
+
* thumb 留空——缩略图要读字节压缩,纯函数里做不了(见 host-bridge 的 attachThumbs)。
|
|
261
|
+
* 原始附件引用挂在**不可枚举**的 symbol 上(不进 JSON)。
|
|
262
|
+
* @param {any} ref 宿主附件引用
|
|
263
|
+
* @returns {{imageId:string,mediaType:string,width:number,height:number,bytes:number,thumb:string}}
|
|
264
|
+
*/
|
|
265
|
+
export function imageRefMeta(ref) {
|
|
266
|
+
const meta = {
|
|
267
|
+
imageId: typeof ref?.attachmentId === "string" ? ref.attachmentId : "",
|
|
268
|
+
mediaType: typeof ref?.mediaType === "string" ? ref.mediaType : "",
|
|
269
|
+
width: Number.isSafeInteger(ref?.width) ? ref.width : 0,
|
|
270
|
+
height: Number.isSafeInteger(ref?.height) ? ref.height : 0,
|
|
271
|
+
bytes: Number.isSafeInteger(ref?.bytes) ? ref.bytes : 0,
|
|
272
|
+
thumb: "",
|
|
273
|
+
};
|
|
274
|
+
try {
|
|
275
|
+
Object.defineProperty(meta, REF, { value: ref, enumerable: false, configurable: true });
|
|
276
|
+
} catch {
|
|
277
|
+
/* 定义失败也不影响元数据本身 */
|
|
278
|
+
}
|
|
279
|
+
return meta;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* 取回 ImageRef 挂着的宿主附件引用(没有则 null)。
|
|
284
|
+
* @param {any} imageRef
|
|
285
|
+
* @returns {any|null}
|
|
286
|
+
*/
|
|
287
|
+
export function attachmentRefOf(imageRef) {
|
|
288
|
+
if (!imageRef || typeof imageRef !== "object") return null;
|
|
289
|
+
const ref = imageRef[REF];
|
|
290
|
+
return ref && typeof ref === "object" ? ref : null;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* 渲染一档 JPEG(等比缩放 + 质量)。失败返回 null(不抛)。
|
|
295
|
+
* @param {any} sharp sharp 模块
|
|
296
|
+
* @param {Buffer} input 原始字节
|
|
297
|
+
* @param {number} edge 长边上限
|
|
298
|
+
* @param {number} quality JPEG 质量
|
|
299
|
+
* @returns {Promise<{base64:string,width:number,height:number,bytes:number}|null>}
|
|
300
|
+
*/
|
|
301
|
+
async function renderJpeg(sharp, input, edge, quality) {
|
|
302
|
+
try {
|
|
303
|
+
// animated:false —— GIF 动图**只取首帧**(契约允许:缩略图/大图都是静态 JPEG)。
|
|
304
|
+
// rotate() —— 按 EXIF 自动摆正(宿主归一化时已摆正,重复调用是幂等的)。
|
|
305
|
+
const { data, info } = await sharp(input, { animated: false })
|
|
306
|
+
.rotate()
|
|
307
|
+
.resize({ width: edge, height: edge, fit: "inside", withoutEnlargement: true })
|
|
308
|
+
.jpeg({ quality })
|
|
309
|
+
.toBuffer({ resolveWithObject: true });
|
|
310
|
+
return {
|
|
311
|
+
base64: data.toString("base64"),
|
|
312
|
+
width: Number(info?.width) || 0,
|
|
313
|
+
height: Number(info?.height) || 0,
|
|
314
|
+
bytes: data.length,
|
|
315
|
+
};
|
|
316
|
+
} catch {
|
|
317
|
+
return null;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* 缩略图(契约 §5.10):长边 ≤480、JPEG q75,输出 `data:image/jpeg;base64,…`。
|
|
323
|
+
*
|
|
324
|
+
* 超 96KB base64 就沿阶梯降质/降尺寸重压;仍超限则返回 **''**(调用方只发元数据,
|
|
325
|
+
* 客户端显示占位框)。sharp 不可用时同样返回 ''(**绝不抛**)。
|
|
326
|
+
* @param {Buffer|Uint8Array|ArrayBuffer} buffer 原始字节
|
|
327
|
+
* @param {string} [mediaType] 原图类型(只用于诊断,不影响输出——统一转 JPEG)
|
|
328
|
+
* @returns {Promise<string>} data URI 或 ''
|
|
329
|
+
*/
|
|
330
|
+
export async function makeThumb(buffer, mediaType) {
|
|
331
|
+
void mediaType;
|
|
332
|
+
const input = toBytes(buffer);
|
|
333
|
+
if (input === null || input.length === 0) return "";
|
|
334
|
+
const sharp = loadSharp();
|
|
335
|
+
if (!sharp) return "";
|
|
336
|
+
for (const step of THUMB_LADDER) {
|
|
337
|
+
const out = await renderJpeg(sharp, input, step.edge, step.quality);
|
|
338
|
+
if (out === null) continue;
|
|
339
|
+
if (out.base64.length <= THUMB_MAX_BASE64) return THUMB_DATA_URI_PREFIX + out.base64;
|
|
340
|
+
}
|
|
341
|
+
// 压到最小一档还超限 → 只发元数据(契约允许 thumb 留空)
|
|
342
|
+
return "";
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* 大图(契约 §5.1 image.fetch):等比缩到长边 ≤ maxEdge、JPEG q85,输出 data URI。
|
|
347
|
+
*
|
|
348
|
+
* maxEdge 缺省 1600、上限 4096。base64 必须 ≤ LARGE_MAX_BASE64(1MiB 预算内);
|
|
349
|
+
* 超了就沿阶梯降质/降尺寸;实在压不进去**抛错**(由上层回 error,客户端提示
|
|
350
|
+
* 「原图过大,仅可看缩略图」)。
|
|
351
|
+
* @param {Buffer|Uint8Array|ArrayBuffer} buffer 原始字节
|
|
352
|
+
* @param {string} [mediaType] 原图类型(统一输出 JPEG)
|
|
353
|
+
* @param {number} [maxEdge] 长边上限
|
|
354
|
+
* @returns {Promise<{data:string,mediaType:string,width:number,height:number,bytes:number}>}
|
|
355
|
+
*/
|
|
356
|
+
export async function makeLarge(buffer, mediaType, maxEdge) {
|
|
357
|
+
void mediaType;
|
|
358
|
+
const input = toBytes(buffer);
|
|
359
|
+
if (input === null || input.length === 0) throw new Error("empty image buffer");
|
|
360
|
+
const sharp = loadSharp();
|
|
361
|
+
if (!sharp) throw new Error("sharp unavailable; cannot build large image");
|
|
362
|
+
const edge = clampMaxEdge(maxEdge);
|
|
363
|
+
for (const step of LARGE_LADDER) {
|
|
364
|
+
const target = Math.max(1, Math.round(edge * step.scale));
|
|
365
|
+
const out = await renderJpeg(sharp, input, target, step.quality);
|
|
366
|
+
if (out === null) continue;
|
|
367
|
+
if (out.base64.length <= LARGE_MAX_BASE64) {
|
|
368
|
+
return {
|
|
369
|
+
data: "data:image/jpeg;base64," + out.base64,
|
|
370
|
+
mediaType: "image/jpeg",
|
|
371
|
+
width: out.width,
|
|
372
|
+
height: out.height,
|
|
373
|
+
bytes: out.bytes,
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
throw new Error("image too large to fit the relay frame budget");
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* maxEdge 归一化(契约 §5.1:缺省 1600、上限 4096)。
|
|
382
|
+
* @param {unknown} value
|
|
383
|
+
* @returns {number}
|
|
384
|
+
*/
|
|
385
|
+
export function clampMaxEdge(value) {
|
|
386
|
+
const n = Number(value);
|
|
387
|
+
if (!Number.isFinite(n)) return LARGE_DEFAULT_MAX_EDGE;
|
|
388
|
+
const i = Math.round(n);
|
|
389
|
+
if (i <= 0) return LARGE_DEFAULT_MAX_EDGE;
|
|
390
|
+
return Math.min(LARGE_MAX_EDGE, i);
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* 回包**帧预算守卫**(纯函数,就地修改 value)。
|
|
395
|
+
*
|
|
396
|
+
* 中继的 1MiB 限制是 **ws 单帧**上限:超了 ws 直接断开连接(1009),
|
|
397
|
+
* 不是「丢一帧」——所以回包必须自己守住,否则一页多图历史就能把整条链路顶死。
|
|
398
|
+
*
|
|
399
|
+
* 降级顺序(先丢像素、后丢条目,尽量保住信息):
|
|
400
|
+
* 1. 明文 JSON 超过预算 → 按 thumb 从大到小**剥掉缩略图**(保留元数据:imageId/尺寸);
|
|
401
|
+
* 2. 还超 → 整条 `images[]` **丢掉**(客户端按无图消息处理);
|
|
402
|
+
* 3. 还超(只剩文字就超了)→ 返回 overflow=true,由调用方回 error
|
|
403
|
+
* (宁可这一页失败,也不能发一帧把链路顶爆)。
|
|
404
|
+
*
|
|
405
|
+
* @param {any} value 回包 value(会被就地修改)
|
|
406
|
+
* @param {number} [maxPlainBytes] 明文 JSON 预算
|
|
407
|
+
* @returns {{value:any,bytes:number,strippedThumbs:number,strippedImages:number,overflow:boolean}}
|
|
408
|
+
*/
|
|
409
|
+
export function fitReplyBudget(value, maxPlainBytes = REPLY_PLAIN_MAX_BYTES) {
|
|
410
|
+
const limit =
|
|
411
|
+
Number.isSafeInteger(maxPlainBytes) && maxPlainBytes > 0 ? maxPlainBytes : REPLY_PLAIN_MAX_BYTES;
|
|
412
|
+
const size = () => {
|
|
413
|
+
try {
|
|
414
|
+
return JSON.stringify(value)?.length ?? 0;
|
|
415
|
+
} catch {
|
|
416
|
+
return 0;
|
|
417
|
+
}
|
|
418
|
+
};
|
|
419
|
+
const done = (strippedThumbs, strippedImages) => ({
|
|
420
|
+
value,
|
|
421
|
+
bytes: size(),
|
|
422
|
+
strippedThumbs,
|
|
423
|
+
strippedImages,
|
|
424
|
+
overflow: size() > limit,
|
|
425
|
+
});
|
|
426
|
+
if (size() <= limit) return done(0, 0);
|
|
427
|
+
|
|
428
|
+
// 1) 剥缩略图(大 → 小)
|
|
429
|
+
const messages = Array.isArray(value?.messages) ? value.messages : [];
|
|
430
|
+
/** @type {any[]} */
|
|
431
|
+
const withThumb = [];
|
|
432
|
+
for (const message of messages) {
|
|
433
|
+
const images = Array.isArray(message?.images) ? message.images : [];
|
|
434
|
+
for (const image of images) {
|
|
435
|
+
if (image && typeof image === "object" && typeof image.thumb === "string" && image.thumb !== "") {
|
|
436
|
+
withThumb.push(image);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
withThumb.sort((a, b) => b.thumb.length - a.thumb.length);
|
|
441
|
+
let strippedThumbs = 0;
|
|
442
|
+
for (const image of withThumb) {
|
|
443
|
+
image.thumb = "";
|
|
444
|
+
strippedThumbs += 1;
|
|
445
|
+
if (size() <= limit) return done(strippedThumbs, 0);
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
// 2) 丢整条 images[]
|
|
449
|
+
let strippedImages = 0;
|
|
450
|
+
for (const message of messages) {
|
|
451
|
+
if (Array.isArray(message?.images) && message.images.length > 0) {
|
|
452
|
+
strippedImages += message.images.length;
|
|
453
|
+
delete message.images;
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
if (size() <= limit) return done(strippedThumbs, strippedImages);
|
|
457
|
+
return done(strippedThumbs, strippedImages);
|
|
458
|
+
}
|