@napuketto/adapter 0.20.0 → 0.21.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.
@@ -1,605 +0,0 @@
1
- import { errorMessage, kernelError } from "@napuketto/kernel";
2
- import { randomUUID } from "node:crypto";
3
- import { z } from "zod";
4
- import { AsyncLocalStorage } from "node:async_hooks";
5
- import { copyFile, lstat, mkdir, mkdtemp, open, readFile, readdir, realpath, rename, rm, rmdir, stat, unlink, writeFile } from "node:fs/promises";
6
- import { tmpdir } from "node:os";
7
- import { basename, dirname, extname, join, resolve } from "node:path";
8
- import { downloadPublicUrl, downloadUrl, encodePcmToSilk, extractVideoFrame, getVideoInfo } from "@napuketto/media";
9
- import { fileURLToPath } from "node:url";
10
- // src/internal/infra/media-cache.ts
11
- const CACHE_DIR = ".napuketto-media-v1";
12
- const ENTRY_RE = /^entry-(\d+)-[\da-f-]{36}$/;
13
- const EXTENSION_RE = /^\.[a-zA-Z0-9]+$/;
14
- const OWNED_FILE_RE = /^(?:media\.[a-zA-Z0-9]+(?:\.part-\d+-[\da-f-]{36})?|\.napuketto-[\da-f]{16}\.pcm|\.owner-next-[\da-f-]{36}\.json|\.lease-\d+-[\da-f-]{36})$/;
15
- const LEASE_RE = /^\.lease-(\d+)-[\da-f-]{36}$/;
16
- const VIDEO_DIR_RE = /^\.napuketto-video-[a-zA-Z0-9]{6}$/;
17
- const DAY = 864e5;
18
- const META = ".owner.json";
19
- const MEDIA_TEMP_ROOT = join(tmpdir(), "napuketto-adapter-media");
20
- const locks = /* @__PURE__ */ new Map();
21
- const active = /* @__PURE__ */ new Map();
22
- const scopes = new AsyncLocalStorage();
23
- async function locked(root, task) {
24
- const prior = locks.get(root) ?? Promise.resolve();
25
- let release = () => void 0;
26
- const next = new Promise((done) => {
27
- release = done;
28
- });
29
- locks.set(root, next);
30
- await prior;
31
- try {
32
- return await task();
33
- } finally {
34
- release();
35
- if (locks.get(root) === next) locks.delete(root);
36
- }
37
- }
38
- function pin(dir) {
39
- active.set(dir, (active.get(dir) ?? 0) + 1);
40
- }
41
- function unpin(dir) {
42
- const count = active.get(dir) ?? 0;
43
- if (count <= 1) active.delete(dir);
44
- else active.set(dir, count - 1);
45
- }
46
- function missing(err) {
47
- return err instanceof Error && "code" in err && err.code === "ENOENT";
48
- }
49
- function alive(pid) {
50
- try {
51
- process.kill(pid, 0);
52
- return true;
53
- } catch (err) {
54
- return !(err instanceof Error && "code" in err && err.code === "ESRCH");
55
- }
56
- }
57
- function hasLiveLease(files) {
58
- return files.some((name) => {
59
- const lease = LEASE_RE.exec(name);
60
- return lease !== null && alive(Number(lease[1]));
61
- });
62
- }
63
- function parseOwner(value) {
64
- if (typeof value !== "object" || value === null || !("version" in value) || value.version !== 1 || !("lifetime" in value) || value.lifetime !== "temporary" && value.lifetime !== "reference" || !("expires" in value) || typeof value.expires !== "number" || !Number.isFinite(value.expires)) return void 0;
65
- return {
66
- version: 1,
67
- lifetime: value.lifetime,
68
- expires: value.expires
69
- };
70
- }
71
- /** Private adapter cache. Only its marked, flat entries are candidates for deletion. */
72
- var MediaCache = class {
73
- roots = /* @__PURE__ */ new Set();
74
- timer;
75
- starting;
76
- generation = 0;
77
- ttl;
78
- orphanTtl;
79
- maxBytes;
80
- now;
81
- options;
82
- constructor(options = {}) {
83
- this.options = options;
84
- this.roots.add(resolve(MEDIA_TEMP_ROOT, CACHE_DIR));
85
- if (options.root) this.roots.add(resolve(options.root, CACHE_DIR));
86
- this.ttl = options.ttlMs ?? DAY;
87
- this.orphanTtl = options.orphanTtlMs ?? 36e5;
88
- this.maxBytes = options.maxBytes ?? 536870912;
89
- this.now = options.now ?? Date.now;
90
- }
91
- async start() {
92
- if (this.timer !== void 0) return;
93
- if (this.starting !== void 0) return await this.starting;
94
- const generation = ++this.generation;
95
- this.starting = this.sweep().then(() => {
96
- if (generation !== this.generation) return;
97
- this.timer = setInterval(() => {
98
- this.sweep().catch((err) => {
99
- this.options.logger?.warn({ error: errorMessage(err) }, "媒体缓存清理失败");
100
- });
101
- }, 6e4);
102
- this.timer.unref();
103
- });
104
- try {
105
- await this.starting;
106
- } finally {
107
- this.starting = void 0;
108
- }
109
- }
110
- stop() {
111
- this.generation++;
112
- if (this.timer !== void 0) clearInterval(this.timer);
113
- this.timer = void 0;
114
- }
115
- /** Nested action helpers reuse the lease until the outer action finishes. */
116
- async run(task) {
117
- if (scopes.getStore() !== void 0) return await task();
118
- const scope = {
119
- cache: this,
120
- owned: /* @__PURE__ */ new Map(),
121
- pinned: /* @__PURE__ */ new Map(),
122
- failed: false
123
- };
124
- return await scopes.run(scope, async () => {
125
- let result;
126
- try {
127
- result = await task();
128
- } catch (err) {
129
- await this.finish(scope, false).catch((cleanup) => {
130
- this.options.logger?.warn({ error: errorMessage(cleanup) }, "媒体动作失败后的清理失败");
131
- });
132
- throw err;
133
- }
134
- await this.finish(scope, !scope.failed);
135
- return result;
136
- });
137
- }
138
- async finish(scope, success) {
139
- const cleaned = await Promise.allSettled([...scope.owned].map(([dir, lifetime]) => locked(dirname(dir), async () => {
140
- if (success && lifetime === "reference") await this.mark(dir, "reference", this.now() + this.ttl);
141
- else await this.remove(dir);
142
- })));
143
- const released = await Promise.allSettled([...scope.pinned].map(([dir, lease]) => locked(dirname(dir), async () => {
144
- try {
145
- await this.checkRoot(dirname(dir));
146
- if ((await lstat(dir)).isSymbolicLink() || await realpath(dir) !== dir) throw kernelError("媒体缓存租约边界已改变", "INVALID_STATE");
147
- await unlink(join(dir, lease));
148
- } finally {
149
- unpin(dir);
150
- }
151
- })));
152
- for (const dir of scope.owned.keys()) unpin(dir);
153
- const failure = [...cleaned, ...released].find((result) => result.status === "rejected");
154
- if (failure?.status === "rejected") throw failure.reason;
155
- }
156
- /** Allocate before any download/write. Writer may return a renamed output in the same entry. */
157
- async create(base, extension, writer, lifetime = "temporary") {
158
- if (!EXTENSION_RE.test(extension)) throw kernelError("非法媒体缓存扩展名", "INVALID_PARAM");
159
- await mkdir(resolve(base), { recursive: true });
160
- const root = join(await realpath(resolve(base)), CACHE_DIR);
161
- this.roots.add(root);
162
- const dir = await locked(root, async () => {
163
- await mkdir(root, { recursive: true });
164
- await this.checkRoot(root);
165
- await this.collect(root);
166
- for (let attempt = 0; attempt < 8; attempt++) {
167
- const candidate = join(root, `entry-${process.pid}-${randomUUID()}`);
168
- try {
169
- await mkdir(candidate);
170
- } catch (err) {
171
- if (err instanceof Error && "code" in err && err.code === "EEXIST") continue;
172
- throw err;
173
- }
174
- pin(candidate);
175
- try {
176
- await this.mark(candidate, "temporary", this.now() + this.orphanTtl);
177
- } catch (err) {
178
- unpin(candidate);
179
- await rmdir(candidate);
180
- throw err;
181
- }
182
- return candidate;
183
- }
184
- throw kernelError("媒体缓存命名冲突", "INVALID_STATE");
185
- });
186
- const scope = scopes.getStore();
187
- try {
188
- const path = join(dir, `media${extension}`);
189
- const output = await writer(path) ?? path;
190
- const info = await lstat(output);
191
- if (dirname(resolve(output)) !== dir || !OWNED_FILE_RE.test(basename(output)) || !info.isFile() || info.isSymbolicLink()) throw kernelError("媒体缓存输出超出受控目录", "INVALID_STATE");
192
- await locked(root, async () => {
193
- if (await this.collect(root) > this.maxBytes) throw kernelError("媒体缓存容量已满(引用期限或使用中租约保护)", "INVALID_STATE");
194
- if (scope === void 0) await this.mark(dir, "reference", this.now() + this.ttl);
195
- });
196
- if (scope !== void 0) scope.owned.set(dir, lifetime);
197
- else unpin(dir);
198
- return output;
199
- } catch (err) {
200
- try {
201
- await locked(root, () => this.remove(dir));
202
- } finally {
203
- unpin(dir);
204
- }
205
- throw err;
206
- }
207
- }
208
- async sweep() {
209
- for (const configuredRoot of this.roots) {
210
- let root;
211
- try {
212
- root = join(await realpath(dirname(configuredRoot)), CACHE_DIR);
213
- } catch (err) {
214
- if (missing(err)) continue;
215
- throw err;
216
- }
217
- await locked(root, async () => {
218
- try {
219
- await this.checkRoot(root);
220
- } catch (err) {
221
- if (missing(err)) return;
222
- throw err;
223
- }
224
- await this.collect(root);
225
- });
226
- }
227
- }
228
- async checkRoot(root) {
229
- const info = await lstat(root);
230
- if (!info.isDirectory() || info.isSymbolicLink() || await realpath(root) !== root) throw kernelError("媒体缓存目录不能是符号链接", "INVALID_STATE");
231
- }
232
- async mark(dir, lifetime, expires) {
233
- await this.checkRoot(dirname(dir));
234
- const info = await lstat(dir);
235
- if (!info.isDirectory() || info.isSymbolicLink() || await realpath(dir) !== dir) throw kernelError("媒体缓存条目边界无效", "INVALID_STATE");
236
- const metadata = join(dir, META);
237
- const next = join(dir, `.owner-next-${randomUUID()}.json`);
238
- try {
239
- await writeFile(next, JSON.stringify({
240
- version: 1,
241
- lifetime,
242
- expires
243
- }), { flag: "wx" });
244
- await rename(next, metadata);
245
- } finally {
246
- await unlink(next).catch((err) => {
247
- if (!missing(err)) throw err;
248
- });
249
- }
250
- }
251
- async inspect(dir) {
252
- const match = ENTRY_RE.exec(basename(dir));
253
- if (match === null) return void 0;
254
- const info = await lstat(dir);
255
- if (!info.isDirectory() || info.isSymbolicLink()) return void 0;
256
- const files = await readdir(dir);
257
- const summary = await this.summarize(dir, files);
258
- if (summary === void 0) return void 0;
259
- if (!files.includes(META)) return void 0;
260
- const parsed = parseOwner(JSON.parse(await readFile(join(dir, META), "utf8")));
261
- if (parsed === void 0) return void 0;
262
- const pid = Number(match[1]);
263
- return {
264
- dir,
265
- owner: parsed,
266
- bytes: summary.bytes,
267
- files: summary.files,
268
- directories: summary.directories,
269
- foreignLive: pid !== process.pid && alive(pid) || hasLiveLease(files),
270
- removable: summary.removable
271
- };
272
- }
273
- async summarize(dir, files) {
274
- const out = {
275
- bytes: 0,
276
- removable: true,
277
- files: [],
278
- directories: []
279
- };
280
- for (const file of files) {
281
- const item = await this.summarizeFile(dir, file);
282
- if (item === void 0) return void 0;
283
- out.bytes += item.bytes;
284
- out.removable &&= item.removable;
285
- out.files.push(...item.files);
286
- out.directories.push(...item.directories);
287
- }
288
- return out;
289
- }
290
- async summarizeFile(dir, file) {
291
- const stat = await lstat(join(dir, file));
292
- if (stat.isDirectory() && VIDEO_DIR_RE.test(file)) {
293
- const nested = await this.videoOutput(join(dir, file));
294
- return nested === void 0 ? {
295
- bytes: Number.POSITIVE_INFINITY,
296
- removable: false,
297
- files: [],
298
- directories: []
299
- } : {
300
- bytes: nested.bytes,
301
- removable: true,
302
- files: nested.files.map((name) => join(file, name)),
303
- directories: [file]
304
- };
305
- }
306
- const regular = stat.isFile() && !stat.isSymbolicLink();
307
- if (file === META && !regular) return void 0;
308
- return {
309
- bytes: file === META ? 0 : regular ? stat.size : Number.POSITIVE_INFINITY,
310
- removable: regular && (file === META || OWNED_FILE_RE.test(file)),
311
- files: [file],
312
- directories: []
313
- };
314
- }
315
- async videoOutput(dir) {
316
- const files = await readdir(dir);
317
- if (files.length === 0) return {
318
- bytes: 0,
319
- files
320
- };
321
- if (files.length !== 1 || files[0] !== "output.mp4") return void 0;
322
- const info = await lstat(join(dir, "output.mp4"));
323
- return info.isFile() && !info.isSymbolicLink() ? {
324
- bytes: info.size,
325
- files
326
- } : void 0;
327
- }
328
- async collect(root) {
329
- let total = 0;
330
- for (const name of await readdir(root)) {
331
- const dir = join(root, name);
332
- let entry;
333
- try {
334
- entry = await this.inspect(dir);
335
- } catch (err) {
336
- if (missing(err) || err instanceof SyntaxError) continue;
337
- throw err;
338
- }
339
- if (entry === void 0) continue;
340
- if (entry.removable && !active.has(dir) && !entry.foreignLive && entry.owner.expires <= this.now()) await this.remove(dir);
341
- else total += entry.bytes;
342
- }
343
- return total;
344
- }
345
- async remove(dir) {
346
- await this.checkRoot(dirname(dir));
347
- const entry = await this.inspect(dir);
348
- if (entry === void 0 || !entry.removable || hasLiveLease(entry.files)) return;
349
- for (const file of entry.files.filter((name) => name !== META)) {
350
- await this.checkRoot(dirname(dir));
351
- if (await realpath(dir) !== dir || (await lstat(dir)).isSymbolicLink()) throw kernelError("媒体缓存条目边界已改变", "INVALID_STATE");
352
- const path = join(dir, file);
353
- if (await realpath(dirname(path)) !== dirname(path)) return;
354
- const info = await lstat(path);
355
- if (!info.isFile() || info.isSymbolicLink()) return;
356
- await unlink(path);
357
- }
358
- for (const name of entry.directories) await rmdir(join(dir, name));
359
- await unlink(join(dir, META));
360
- await rmdir(dir);
361
- }
362
- };
363
- /** Action factories also work independently of an adapter/registry. */
364
- async function withMediaScope(task) {
365
- const scope = scopes.getStore();
366
- if (scope === void 0) return await new MediaCache().run(task);
367
- try {
368
- return await task();
369
- } catch (err) {
370
- scope.failed = true;
371
- throw err;
372
- }
373
- }
374
- async function cacheMediaFile(root, extension, writer, lifetime = "temporary") {
375
- return await (scopes.getStore()?.cache ?? new MediaCache()).create(root, extension, writer, lifetime);
376
- }
377
- /** Lease a previously returned cache path; caller/QQ paths are never adopted. */
378
- async function protectMediaPath(path) {
379
- const scope = scopes.getStore();
380
- const dir = dirname(resolve(path));
381
- const root = dirname(dir);
382
- if (scope === void 0 || basename(root) !== CACHE_DIR || !ENTRY_RE.test(basename(dir)) || scope.pinned.has(dir) || scope.owned.has(dir)) return path;
383
- await locked(root, async () => {
384
- if ((await lstat(root)).isSymbolicLink() || await realpath(root) !== root || (await lstat(dir)).isSymbolicLink() || await realpath(dir) !== dir) throw kernelError("媒体缓存引用边界无效", "INVALID_STATE");
385
- const marker = join(dir, META);
386
- if ((await lstat(marker)).isSymbolicLink() || parseOwner(JSON.parse(await readFile(marker, "utf8"))) === void 0) throw kernelError("媒体缓存引用缺少所有权标记", "INVALID_STATE");
387
- const lease = `.lease-${process.pid}-${randomUUID()}`;
388
- await writeFile(join(dir, lease), "", { flag: "wx" });
389
- pin(dir);
390
- scope.pinned.set(dir, lease);
391
- });
392
- return path;
393
- }
394
- // src/internal/qq/media.ts
395
- /**
396
- * adapter core 媒体辅助:语音归一化 + 视频缩略图(media 严格解耦的协议层落点)
397
- *
398
- * 协议层(onebot11 / satori)发送媒体前统一走这里:
399
- * - `ensureSilk`:非 silk 音频转 QQ 语音格式(silk v3);
400
- * - `prepareVideoElements`:视频缺缩略图/时长/尺寸时,用 ffmpeg 抽首帧并探测元数据。
401
- * 都依赖 @napuketto/media,只发生在 adapter 层;kernel 不 import media(红线),
402
- * 只接收「文件齐全」的 canonical 元素。
403
- */
404
- /** file:// 前缀(fileURLToPath 解析失败时的裸剥离兜底)。 */
405
- const FILE_URI_PREFIX_RE = /^file:\/\//;
406
- const MEDIA_EXTENSION_RE = /^\.[a-zA-Z0-9]+$/;
407
- const MAX_AUDIO_COPY_BYTES = 33554432;
408
- /**
409
- * file:// URI → 平台路径(Windows 盘符 / 百分号编码兼容)。
410
- * fileURLToPath 解析失败时退化为裸剥离前缀(历史兜底行为,协议侧共用)。
411
- */
412
- function fileUriToPath(uri) {
413
- try {
414
- return fileURLToPath(uri);
415
- } catch {
416
- return FILE_URI_PREFIX_RE.test(uri) ? uri.replace(FILE_URI_PREFIX_RE, "") : uri;
417
- }
418
- }
419
- /** 协议动作默认走公网下载,兼容模式由受信任的装配方显式启用。 */
420
- function mediaDownloader(policy) {
421
- return policy === "compat" ? downloadUrl : downloadPublicUrl;
422
- }
423
- /** 转换有上传语义的下载失败,保留既有 SEND_FAILED 信封。 */
424
- async function downloadProtocolMedia(url, filePath, options = {}) {
425
- try {
426
- await mediaDownloader(options.outboundPolicy)(url, filePath, { headers: options.headers });
427
- } catch (err) {
428
- throw kernelError(`${options.errorLabel ?? "下载失败"}: ${errorMessage(err)}`, "SEND_FAILED", { cause: err });
429
- }
430
- }
431
- /** 读文件头 8 字节(判断 silk 魔数)。 */
432
- async function readFileHead(path) {
433
- const handle = await open(path, "r");
434
- try {
435
- const buf = Buffer.alloc(8);
436
- await handle.read(buf, 0, 8, 0);
437
- return buf.toString("utf8");
438
- } finally {
439
- await handle.close();
440
- }
441
- }
442
- /**
443
- * 语音转码:非 silk 输入(任意音频格式,经 @napuketto/media 归一化)转 silk。
444
- * 已是 silk(#!SILK_V3 头)原样返回;转码失败原样返回(由 kernel 发送时兜底),
445
- * 可选 logger 记录降级上下文。
446
- */
447
- async function ensureSilk(path, logger) {
448
- try {
449
- await protectMediaPath(path);
450
- const info = await stat(path);
451
- if (!info.isFile() || info.size > MAX_AUDIO_COPY_BYTES) throw kernelError("语音复制输入必须是 32MiB 以内的普通文件", "INVALID_PARAM");
452
- if ((await readFileHead(path)).startsWith("#!SILK")) return path;
453
- const ext = extname(path);
454
- return await cacheMediaFile(MEDIA_TEMP_ROOT, MEDIA_EXTENSION_RE.test(ext) ? ext : ".bin", async (copy) => {
455
- await copyFile(path, copy);
456
- return await encodePcmToSilk(copy);
457
- });
458
- } catch (err) {
459
- logger?.warn({
460
- path,
461
- error: errorMessage(err)
462
- }, "语音 silk 转码失败,原样透传");
463
- return path;
464
- }
465
- }
466
- /** 是否是需要补缩略图的视频元素。 */
467
- function needsVideoThumb(el) {
468
- return el.type === "video" && (el.thumbPath === void 0 || el.thumbPath === "");
469
- }
470
- /**
471
- * 视频元素补「首帧缩略图 + 时长 + 尺寸」(QQ 视频消息发送契约)。
472
- *
473
- * 为什么必须补:kernel 的 `prepareVideoElement` 只有在 `thumbPath` 存在时才写
474
- * `thumbMd5 / thumbSize / thumbPath(Map)`,缺失时 native 传输找不到缩略图,
475
- * `sendMsg` 只回 `sendStatus=0`(无错误信息);`fileTime`(秒)也取自
476
- * `durationSec`,缺省 0。Linux 原生宿主实测:只给 `file` 的 OB11 `video` 段
477
- * 必然失败,补上首帧后成功。
478
- *
479
- * 缩略图写在系统临时目录(发送时 kernel 会 copyFile 进 QQ 数据目录),
480
- * 由 `cleanup` 统一删除——不污染用户文件目录。
481
- *
482
- * 依赖系统 ffmpeg / ffprobe(@napuketto/media);缺失或抽帧失败时抛
483
- * `MediaError`,由协议动作层映射成可读错误,而不是让 native 回 `sendStatus=0`。
484
- */
485
- async function prepareVideoElements(elements) {
486
- if (!elements.some(needsVideoThumb)) return {
487
- elements: [...elements],
488
- cleanup: async () => void 0
489
- };
490
- const dir = await mkdtemp(join(tmpdir(), "napuketto-video-thumb-"));
491
- const cleanup = async () => {
492
- await rm(dir, {
493
- recursive: true,
494
- force: true
495
- });
496
- };
497
- try {
498
- const out = [];
499
- let index = 0;
500
- for (const el of elements) {
501
- if (!needsVideoThumb(el)) {
502
- out.push(el);
503
- continue;
504
- }
505
- index += 1;
506
- const thumbPath = join(dir, `thumb-${index}.png`);
507
- const info = await getVideoInfo(el.path);
508
- await extractVideoFrame(el.path, thumbPath);
509
- out.push({
510
- ...el,
511
- thumbPath,
512
- width: el.width ?? info.width,
513
- height: el.height ?? info.height,
514
- durationSec: el.durationSec ?? Math.max(1, Math.round(info.durationMs / 1e3))
515
- });
516
- }
517
- return {
518
- elements: out,
519
- cleanup
520
- };
521
- } catch (err) {
522
- await cleanup();
523
- throw err;
524
- }
525
- }
526
- // src/internal/infra/media-config.ts
527
- const protocolMediaSchema = z.object({ outboundPolicy: z.enum(["public-only", "compat"]).optional() });
528
- // src/internal/infra/log.ts
529
- /**
530
- * raw 日志截断与最小 logger 面(协议 adapter 校准日志共用,自
531
- * onebot11/milky adapter.ts 顶部内联工具收拢)。
532
- *
533
- * info/warn 级 raw 字段对运行状态无信息量(输出内容治理):
534
- * hex/base64/JSON 原文保留前缀定位 + 缺省长度标注;完整值仅在 debug 级
535
- * 与日志文件中出现。两种截断口径刻意并存——OB11 校准日志带缺省长度标注,
536
- * Milky 长文本校准日志用固定切片(无标注)。
537
- */
538
- /** info/warn 级截断缺省上限(OB11 口径)。 */
539
- const RAW_INFO_LIMIT = 64;
540
- /** 长文本截断缺省上限(debug / raw 校准日志防刷屏)。 */
541
- const RAW_DEBUG_LIMIT = 2e3;
542
- /**
543
- * raw 字段截断:超限截断 + 缺省长度标注(…(+N))。
544
- * OB11 校准日志(warn 级 64 缺省)口径。
545
- */
546
- function truncRaw(value, keep = RAW_INFO_LIMIT) {
547
- if (value === void 0) return "";
548
- return value.length <= keep ? value : `${value.slice(0, keep)}…(+${value.length - keep})`;
549
- }
550
- /** 长文本截断:固定上限切片(Milky 校准日志 2000 缺省口径,无长度标注)。 */
551
- function sliceRaw(value, max = RAW_DEBUG_LIMIT) {
552
- return value === void 0 ? "" : value.slice(0, max);
553
- }
554
- /**
555
- * 事件链翻译失败留痕(收链路异步 .catch 统一出口:单条/整批丢弃,warn 留痕
556
- * 不打断订阅;err 规范化为 message 串)。
557
- */
558
- function logEventFailure(logger, msg, err) {
559
- logger?.warn({ err: errorMessage(err) }, msg);
560
- }
561
- // src/internal/qq/gray-tip.ts
562
- /**
563
- * 消息是否含 grayTip 元素(OB11 / Milky 收链路分流判据,收拢)。
564
- * `!= null` 空值判定:Linux 原生宿主把未命中的变体字段显式置 null,
565
- * `!== undefined` 会把普通消息误判成 grayTip 消息(见 OB11 hasFileElement 注)。
566
- */
567
- function hasGrayTip(msg) {
568
- return msg.elements.some((el) => el.grayTipElement != null);
569
- }
570
- /** 非空 uid 才加入集合(Linux 原生对象未命中的字段是显式 null,不只 undefined)。 */
571
- function collectUids(uids, ...candidates) {
572
- for (const uid of candidates) if (uid != null && uid !== "") uids.add(uid);
573
- }
574
- /** 收集 grayTip 涉及的 uid(批量 uidToUin 用)。 */
575
- function collectGrayTipUids(msg) {
576
- const uids = /* @__PURE__ */ new Set();
577
- for (const el of msg.elements) {
578
- const g = el.grayTipElement;
579
- if (g == null) continue;
580
- collectUids(uids, g.revokeElement?.operatorUid, g.aioOpGrayTipElement?.peerUid);
581
- const grp = g.groupElement;
582
- if (grp == null) continue;
583
- collectUids(uids, grp.memberUid, grp.adminUid, grp.shutUp?.admin?.uid, grp.shutUp?.member?.uid);
584
- }
585
- return [...uids];
586
- }
587
- /**
588
- * 第一条「已挂载但不可翻译」的 grayTip 元素(校准日志入口)。
589
- * 与 OB11 / Milky notice 翻译共用:翻译函数返回 null 时用本函数定位元素打 raw
590
- * 日志,两协议的日志口径一致(跳过 REVOKE——撤回翻译独立成事件)。
591
- */
592
- function firstUntranslatedGrayTip(msg) {
593
- for (const el of msg.elements) {
594
- const g = el.grayTipElement;
595
- if (g != null && g.revokeElement == null) return g;
596
- }
597
- }
598
- /**
599
- * 撤回 grayTip 元素(非撤回消息返回 undefined;Milky 收链路 notice/召回
600
- * 分流判据,自 milky adapter.ts 收拢)。
601
- */
602
- function findRevokeElement(msg) {
603
- return msg.elements.find((el) => el.grayTipElement?.revokeElement != null)?.grayTipElement?.revokeElement ?? void 0;
604
- }
605
- export { withMediaScope as _, logEventFailure as a, protocolMediaSchema as c, fileUriToPath as d, mediaDownloader as f, protectMediaPath as g, cacheMediaFile as h, hasGrayTip as i, downloadProtocolMedia as l, MediaCache as m, findRevokeElement as n, sliceRaw as o, prepareVideoElements as p, firstUntranslatedGrayTip as r, truncRaw as s, collectGrayTipUids as t, ensureSilk as u };