@zhin.js/adapter-douyin-live 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,235 @@
1
+ /**
2
+ * 抖音直播弹幕 Endpoint(Experimental,非官方协议)。
3
+ *
4
+ * - 入站:web_rid → 内部 room_id → 连弹幕 WebSocket(轻量 WSS,不起浏览器 / CDP);10 秒 `hb` 心跳,
5
+ * `needAck` 时回 ack;每条 `WebcastChatMessage` 进一条 canonical 消息,其余类型(礼物 / 进场 / 点赞 / 关注)忽略。
6
+ * Adapter 声明 `liveDanmaku`,Agent 按 ADR 0038 §5 把弹幕收进窗口、一窗只回一次、只用只读工具。
7
+ * - 断线走 `createEndpointLifecycle` 退避重连,每次重连重新解析 room_id、重建签名地址。
8
+ * - 出站(sendMode α):默认 `off` 只听不说;`direct` 尚无稳定可测的发送接口,明确返回 `not_implemented`。
9
+ * - 不落盘:所有状态都在内存里,且有上限。
10
+ */
11
+ import WebSocket from 'ws';
12
+ import { EndpointDeliveryError } from '@zhin.js/im-contract';
13
+ import { createEndpointSpecification, endpointSpec, createEndpointLifecycle, } from 'zhin.js/adapter';
14
+ import { formatCompact, getAdapterLogger } from '@zhin.js/logger';
15
+ import { DOUYIN_LIVE_USER_AGENT, DouyinLiveClient } from './client.js';
16
+ import { DOUYIN_LIVE_HEARTBEAT_MS, decodeWebcastFrame, encodeAck, encodeHeartbeat, formatOutboundDanmaku, parseChatMessage, splitDanmaku, } from './protocol.js';
17
+ /** 去重窗口:最近这么多条弹幕 id。 */
18
+ const SEEN_CAPACITY = 500;
19
+ /** 握手等待上限。 */
20
+ const OPEN_TIMEOUT_MS = 15_000;
21
+ const defaultSocket = (url, headers) => new WebSocket(url, { headers: { ...headers } });
22
+ export class DouyinLiveEndpoint extends DouyinLiveClient {
23
+ [endpointSpec];
24
+ #options;
25
+ #logger;
26
+ #lifecycle;
27
+ #seen = new Set();
28
+ #internalRoomId;
29
+ #socket;
30
+ #open = false;
31
+ #sequence = 0;
32
+ #warnedUnsigned = false;
33
+ constructor(options) {
34
+ super(options.config, options.fetch ?? globalThis.fetch, {
35
+ ...(options.now ? { now: options.now } : {}),
36
+ ...(options.signal ? { signal: options.signal } : {}),
37
+ ...(options.sign ? { sign: options.sign } : {}),
38
+ ...(options.userUniqueId ? { userUniqueId: options.userUniqueId } : {}),
39
+ });
40
+ this.#options = options;
41
+ const readTransportState = () => this.#transportState;
42
+ this[endpointSpec] = createEndpointSpecification(this, {
43
+ name: options.config.id,
44
+ start: () => this.#start(), open: () => this.#openEndpoint(),
45
+ close: () => this.#close(), stop: () => this.#stop(),
46
+ send: request => this.#send(request),
47
+ get transportState() { return readTransportState(); },
48
+ });
49
+ this.#logger = getAdapterLogger('douyin-live', options.config.id);
50
+ this.#lifecycle = createEndpointLifecycle({
51
+ name: `douyin-live:${options.config.id}`,
52
+ heartbeat: { intervalMs: DOUYIN_LIVE_HEARTBEAT_MS, watchdogMisses: 3 },
53
+ });
54
+ }
55
+ get #transportState() {
56
+ return this.#lifecycle.state;
57
+ }
58
+ /** web_rid(会话 id,与配置 `roomId` 一致)。 */
59
+ get webRid() {
60
+ return this.config.roomId;
61
+ }
62
+ /** 平台内部 room_id(连上之后可用)。 */
63
+ get internalRoomId() {
64
+ return this.#internalRoomId;
65
+ }
66
+ async #start() {
67
+ await this.#lifecycle.start((handle) => this.#connect(handle));
68
+ if (this.config.sendMode === 'direct') {
69
+ this.#logger.warn(formatCompact({
70
+ op: 'douyin_live_send_not_implemented',
71
+ hint: 'sendMode: direct 尚未实现,回复不会发出(返回 not_implemented);请改用 sendMode: off',
72
+ }));
73
+ }
74
+ }
75
+ #openEndpoint() {
76
+ this.#open = true;
77
+ }
78
+ #close() {
79
+ this.#open = false;
80
+ }
81
+ async #stop() {
82
+ this.#open = false;
83
+ await this.#lifecycle.stop();
84
+ this.#socket = undefined;
85
+ this.#seen.clear();
86
+ }
87
+ /** 每次(重)连都重新解析 room_id、重新生成签名地址。 */
88
+ async #connect(handle) {
89
+ const { roomId } = await this.resolveRoom();
90
+ this.#internalRoomId = roomId;
91
+ if (!this.canSign && !this.#warnedUnsigned) {
92
+ this.#warnedUnsigned = true;
93
+ this.#logger.warn(formatCompact({
94
+ op: 'douyin_live_unsigned',
95
+ hint: '未配置 signerUrl:WebSocket 不带 signature 连接,平台可能拒绝握手',
96
+ }));
97
+ }
98
+ const url = await this.buildPushUrl(roomId);
99
+ const factory = this.#options.socket ?? defaultSocket;
100
+ const socket = factory(url, { cookie: this.cookieHeader(), 'user-agent': DOUYIN_LIVE_USER_AGENT });
101
+ socket.binaryType = 'arraybuffer';
102
+ this.#socket = socket;
103
+ handle.onForceClose(() => {
104
+ try {
105
+ socket.close();
106
+ }
107
+ catch { /* ignore */ }
108
+ });
109
+ await new Promise((resolve, reject) => {
110
+ let settled = false;
111
+ const settle = (error) => {
112
+ if (settled)
113
+ return;
114
+ settled = true;
115
+ clearTimeout(timer);
116
+ if (error)
117
+ reject(error);
118
+ else
119
+ resolve();
120
+ };
121
+ const timer = setTimeout(() => {
122
+ settle(new Error('douyin live socket open timed out'));
123
+ try {
124
+ socket.close();
125
+ }
126
+ catch { /* ignore */ }
127
+ }, OPEN_TIMEOUT_MS);
128
+ socket.addEventListener('open', () => {
129
+ if (this.#socket !== socket || !this.#lifecycle.started)
130
+ return;
131
+ this.#lifecycle.startHeartbeat(() => socket.send(encodeHeartbeat()));
132
+ socket.send(encodeHeartbeat());
133
+ this.#logger.info(formatCompact({ op: 'douyin_live_connected', room: this.webRid }));
134
+ settle();
135
+ });
136
+ socket.addEventListener('message', (event) => {
137
+ if (this.#socket !== socket || !this.#lifecycle.started)
138
+ return;
139
+ this.#lifecycle.notifyHeartbeatAck();
140
+ const bytes = toBytes(event.data);
141
+ if (!bytes)
142
+ return;
143
+ const decoded = decodeWebcastFrame(bytes);
144
+ const response = decoded?.response;
145
+ if (!decoded || !response)
146
+ return;
147
+ if (response.needAck) {
148
+ try {
149
+ socket.send(encodeAck(decoded.frame.logId, response.internalExt));
150
+ }
151
+ catch { /* closing */ }
152
+ }
153
+ for (const message of response.messages) {
154
+ const chat = parseChatMessage(message, this.now);
155
+ if (!chat)
156
+ continue;
157
+ void this[endpointSpec].events.run(() => this.#admit(roomId, chat)).catch((error) => this.#logger.debug(formatCompact({
158
+ op: 'douyin_live_dispatch_failed', error: error instanceof Error ? error.message : String(error),
159
+ })));
160
+ }
161
+ });
162
+ socket.addEventListener('close', (event) => {
163
+ if (this.#socket === socket)
164
+ this.#socket = undefined;
165
+ handle.notifyClosed(new Error(`douyin live socket closed (${event.code ?? 'unknown'})`));
166
+ settle(new Error(`douyin live socket closed before open (${event.code ?? 'unknown'})`));
167
+ });
168
+ socket.addEventListener('error', () => {
169
+ settle(new Error('douyin live socket error'));
170
+ });
171
+ });
172
+ }
173
+ #conversation() {
174
+ return {
175
+ endpoint: this[endpointSpec].identity,
176
+ kind: 'channel',
177
+ id: this.webRid,
178
+ };
179
+ }
180
+ async #admit(roomId, chat) {
181
+ if (!this.#open)
182
+ return;
183
+ this.#sequence += 1;
184
+ const id = chat.id ?? `${chat.timestamp}-${chat.uid}-${this.#sequence}`;
185
+ // 只有平台 id 可去重;兜底 id 含序号、永不重复,不占去重窗口。
186
+ if (chat.id) {
187
+ if (this.#seen.has(chat.id))
188
+ return;
189
+ this.#seen.add(chat.id);
190
+ if (this.#seen.size > SEEN_CAPACITY) {
191
+ const oldest = this.#seen.values().next().value;
192
+ if (oldest !== undefined)
193
+ this.#seen.delete(oldest);
194
+ }
195
+ }
196
+ // 取不到 uid 时按昵称区分观众,避免所有人被当成同一个人。
197
+ const senderId = chat.uid && chat.uid !== '0' ? chat.uid : `anon:${chat.nickname}`;
198
+ const conversation = this.#conversation();
199
+ void this[endpointSpec].events.platform('danmaku', chat).catch(() => undefined);
200
+ await this[endpointSpec].events.message({
201
+ event: chat,
202
+ platformSentAt: chat.timestamp,
203
+ conversation,
204
+ message: { conversation, id },
205
+ content: chat.text,
206
+ sender: { id: senderId, name: chat.nickname },
207
+ endpointId: this.#options.config.id,
208
+ metadata: Object.freeze({ roomId: chat.roomId ?? roomId, liveDanmaku: true }),
209
+ });
210
+ }
211
+ /**
212
+ * 出站(sendMode α):默认 `off` 只听不说;`direct` 在有稳定可测的 HTTP 发送接口之前明确返回
213
+ * `not_implemented`(不尝试任何平台写接口)。校验顺序与将来的真实发送一致:模式 → 房间 → 内容。
214
+ */
215
+ async #send({ conversation, payload }) {
216
+ const config = this.config;
217
+ if (config.sendMode === 'off') {
218
+ throw new EndpointDeliveryError('send_disabled', 'Douyin live sendMode is off', 'not_sent');
219
+ }
220
+ if (conversation.id !== this.webRid) {
221
+ throw new EndpointDeliveryError('invalid_recipient', `Douyin live can only post to its own room ${this.webRid}, got "${conversation.id}"`, 'not_sent');
222
+ }
223
+ const chunks = splitDanmaku(formatOutboundDanmaku(payload), config.maxLength, config.maxChunks);
224
+ if (chunks.length === 0)
225
+ throw new EndpointDeliveryError('invalid_payload', 'Danmaku is empty', 'not_sent');
226
+ throw new EndpointDeliveryError('not_implemented', 'Douyin live direct sending is not implemented yet (no stable, testable send API); use sendMode: off', 'not_sent');
227
+ }
228
+ }
229
+ function toBytes(data) {
230
+ if (data instanceof ArrayBuffer)
231
+ return new Uint8Array(data);
232
+ if (ArrayBuffer.isView(data))
233
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
234
+ return undefined;
235
+ }
package/lib/index.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ export * from './protocol.js';
2
+ export { DouyinLiveApiError, DouyinLiveClient, type DouyinLiveClientEventMap, type DouyinLiveFetch, type DouyinLiveSigner, type DouyinLiveRoomInfo, buildSignatureStub, } from './client.js';
3
+ export { DouyinLiveEndpoint, type DouyinLiveEndpointOptions, type LiveSocket, type LiveSocketFactory, } from './endpoint.js';
4
+ export { DouyinLiveAdapter } from './adapter.js';
package/lib/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from './protocol.js';
2
+ export { DouyinLiveApiError, DouyinLiveClient, buildSignatureStub, } from './client.js';
3
+ export { DouyinLiveEndpoint, } from './endpoint.js';
4
+ export { DouyinLiveAdapter } from './adapter.js';
@@ -0,0 +1,117 @@
1
+ import type { EndpointProfileConfiguration } from 'zhin.js/adapter';
2
+ export type DouyinLiveSendMode = 'direct' | 'off';
3
+ export declare const DOUYIN_LIVE_DEFAULT_MAX_LENGTH = 50;
4
+ export declare const DOUYIN_LIVE_DEFAULT_MAX_CHUNKS = 2;
5
+ export declare const DOUYIN_LIVE_DEFAULT_SEND_INTERVAL_SEC = 5;
6
+ export declare const DOUYIN_LIVE_MIN_SEND_INTERVAL_SEC = 2;
7
+ /** 心跳间隔:网页端约 10 秒一次 `hb` 帧。 */
8
+ export declare const DOUYIN_LIVE_HEARTBEAT_MS = 10000;
9
+ /** 唯一解析的消息类型。 */
10
+ export declare const DOUYIN_CHAT_METHOD = "WebcastChatMessage";
11
+ /** One endpoint config after AdapterIndex expands `<instanceKey>.endpoints`. */
12
+ export interface DouyinLiveEndpointConfig extends EndpointProfileConfiguration {
13
+ readonly id: string;
14
+ /** 直播间 web_rid(`https://live.douyin.com/<web_rid>` 里的数字)。只填你自己的直播间。 */
15
+ readonly roomId?: string | number;
16
+ /** 浏览器 Cookie 整串(请用 ${DOUYIN_LIVE_COOKIE} 注入,切勿写进仓库)。不填时启动时向平台申请游客 `ttwid`。 */
17
+ readonly cookie?: string;
18
+ /** 出站模式:`off`(默认,只听不说)/ `direct`(尚未实现,发送返回 `not_implemented`)。 */
19
+ readonly sendMode?: DouyinLiveSendMode;
20
+ /** 单条弹幕最多字符数,默认 50(为后续 direct 发送预留)。 */
21
+ readonly maxLength?: number;
22
+ /** 一次回复最多拆成几条弹幕,默认 2。 */
23
+ readonly maxChunks?: number;
24
+ /** 两次回复的最小间隔秒数(默认 5,最小 2)。 */
25
+ readonly minSendIntervalSec?: number;
26
+ /**
27
+ * 可选:外部签名服务地址。WebSocket 的 `signature` 参数由平台混淆脚本生成,本包不内置;
28
+ * 配置后以 `GET <signerUrl>?stub=<X-MS-STUB>` 取签名(返回纯文本或 `{ signature }`)。
29
+ */
30
+ readonly signerUrl?: string;
31
+ }
32
+ export interface ResolvedDouyinLiveConfig {
33
+ readonly context: 'douyin-live';
34
+ readonly id: string;
35
+ /** web_rid。 */
36
+ readonly roomId: string;
37
+ readonly cookie?: string;
38
+ readonly sendMode: DouyinLiveSendMode;
39
+ readonly maxLength: number;
40
+ readonly maxChunks: number;
41
+ readonly minSendIntervalMs: number;
42
+ readonly signerUrl?: string;
43
+ }
44
+ export declare function resolveDouyinLiveConfig(raw: unknown): ResolvedDouyinLiveConfig;
45
+ type ProtoValue = bigint | Uint8Array;
46
+ interface ProtoField {
47
+ readonly field: number;
48
+ readonly value: ProtoValue;
49
+ }
50
+ /** 解出一层 message 的所有字段(varint / fixed / length-delimited)。格式错误抛错。 */
51
+ export declare function readProtoFields(bytes: Uint8Array): ProtoField[];
52
+ /** `PushFrame`(WebSocket 外层帧)。字段号:seqId 1 / logId 2 / payloadEncoding 6 / payloadType 7 / payload 8。 */
53
+ export interface PushFrame {
54
+ readonly seqId: string;
55
+ readonly logId: string;
56
+ readonly payloadEncoding: string;
57
+ readonly payloadType: string;
58
+ readonly payload: Uint8Array;
59
+ }
60
+ export declare function decodePushFrame(bytes: Uint8Array): PushFrame | undefined;
61
+ export declare function encodePushFrame(frame: {
62
+ readonly logId?: string;
63
+ readonly payloadType: string;
64
+ readonly payloadEncoding?: string;
65
+ readonly payload?: Uint8Array;
66
+ }): Uint8Array;
67
+ /** 心跳帧:`PushFrame { payloadType: 'hb' }`。 */
68
+ export declare function encodeHeartbeat(): Uint8Array;
69
+ /** 确认帧:`Response.needAck` 时回 `PushFrame { logId, payloadType: 'ack', payload: internalExt }`。 */
70
+ export declare function encodeAck(logId: string, internalExt: string): Uint8Array;
71
+ /** `Message`:method 1 / payload 2 / msgId 3。 */
72
+ export interface WebcastMessage {
73
+ readonly method: string;
74
+ readonly payload: Uint8Array;
75
+ readonly msgId: string;
76
+ }
77
+ /** `Response`:messagesList 1 / internalExt 5 / heartbeatDuration 8 / needAck 9。 */
78
+ export interface WebcastResponse {
79
+ readonly messages: readonly WebcastMessage[];
80
+ readonly internalExt: string;
81
+ readonly needAck: boolean;
82
+ readonly heartbeatDurationMs: number;
83
+ }
84
+ /**
85
+ * 解一帧:PushFrame → (gzip)→ Response。不是消息帧(如心跳回包)或坏帧返回 undefined,不抛错:
86
+ * 平台改版时宁可漏几条弹幕,也不让连接崩溃重连刷屏。
87
+ */
88
+ export declare function decodeWebcastFrame(bytes: Uint8Array): {
89
+ readonly frame: PushFrame;
90
+ readonly response?: WebcastResponse;
91
+ } | undefined;
92
+ /** 一条抖音直播聊天弹幕(`WebcastChatMessage`)。 */
93
+ export interface DouyinLiveChat {
94
+ /** 平台消息 id(`common.msgId`,或外层 `Message.msgId`);取不到时为空。 */
95
+ readonly id?: string;
96
+ readonly text: string;
97
+ /** 发送者 user id;取不到时为 `'0'`。 */
98
+ readonly uid: string;
99
+ readonly nickname: string;
100
+ /** 平台内部 room_id(`common.roomId`),取不到时为空。 */
101
+ readonly roomId?: string;
102
+ /** 毫秒时间戳。 */
103
+ readonly timestamp: number;
104
+ }
105
+ /**
106
+ * 解 `ChatMessage`:common 1(method 1 / msgId 2 / roomId 3 / createTime 4)、
107
+ * user 2(id 1 / nickName 3 / idStr 1028)、content 3、eventTime 15。
108
+ */
109
+ export declare function parseChatMessage(message: WebcastMessage, now?: () => number): DouyinLiveChat | undefined;
110
+ /** 出站:弹幕只支持纯文本;抖音弹幕没有「回复」字段,mention 折叠进正文 ` @昵称 `(前后留空格,避免与相邻文本粘连)。 */
111
+ export declare function formatOutboundDanmaku(payload: unknown): string;
112
+ /**
113
+ * 把回复切成至多 `maxChunks` 条弹幕,每条至多 `maxLength` 字符(按码点算)。
114
+ * 放不下的部分截掉,最后一条以「…」结尾。
115
+ */
116
+ export declare function splitDanmaku(text: string, maxLength: number, maxChunks: number): string[];
117
+ export {};
@@ -0,0 +1,292 @@
1
+ /**
2
+ * 抖音直播弹幕协议(Experimental,非官方 Web 协议)。
3
+ *
4
+ * - 一个直播间 = 一个 conversation:`{ kind: 'channel', id: <web_rid> }`(与配置 `roomId` 一致);
5
+ * 平台内部 room_id 放在 `metadata.roomId`。
6
+ * - WebSocket 帧是 protobuf `PushFrame`;`payload` 通常 gzip 压缩,内层是 `Response`,
7
+ * `Response.messagesList` 里每条 `Message` 按 `method` 区分类型。本包只解 `WebcastChatMessage`(聊天弹幕)。
8
+ * - 只维护最小 proto:帧外壳 + ChatMessage 用到的字段,手写解码,不引第三方 protobuf 运行时。
9
+ */
10
+ import { gunzipSync } from 'node:zlib';
11
+ export const DOUYIN_LIVE_DEFAULT_MAX_LENGTH = 50;
12
+ export const DOUYIN_LIVE_DEFAULT_MAX_CHUNKS = 2;
13
+ export const DOUYIN_LIVE_DEFAULT_SEND_INTERVAL_SEC = 5;
14
+ export const DOUYIN_LIVE_MIN_SEND_INTERVAL_SEC = 2;
15
+ /** 心跳间隔:网页端约 10 秒一次 `hb` 帧。 */
16
+ export const DOUYIN_LIVE_HEARTBEAT_MS = 10_000;
17
+ /** 唯一解析的消息类型。 */
18
+ export const DOUYIN_CHAT_METHOD = 'WebcastChatMessage';
19
+ /** 单帧 / 解压后的大小上限:超过视为坏帧,整帧丢弃。 */
20
+ const MAX_FRAME_BYTES = 4 * 1024 * 1024;
21
+ function intInRange(value, fallback, min, max) {
22
+ const n = typeof value === 'number' ? value : typeof value === 'string' && value.trim() ? Number(value) : NaN;
23
+ if (!Number.isFinite(n))
24
+ return fallback;
25
+ return Math.min(max, Math.max(min, Math.floor(n)));
26
+ }
27
+ function optionalString(value) {
28
+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;
29
+ }
30
+ export function resolveDouyinLiveConfig(raw) {
31
+ const config = (raw && typeof raw === 'object' ? raw : {});
32
+ const id = optionalString(config.id);
33
+ if (!id)
34
+ throw new Error('douyin-live endpoint requires an id');
35
+ const roomId = String(config.roomId ?? '').trim();
36
+ // 未加引号的超大整数会被 YAML/JS 解析器静默取整,指向别的直播间:数字形式只收安全整数。
37
+ const unsafeNumber = typeof config.roomId === 'number' && !Number.isSafeInteger(config.roomId);
38
+ if (unsafeNumber || !/^[1-9]\d*$/.test(roomId)) {
39
+ throw new Error(`douyin-live endpoint "${id}" requires a numeric roomId (web_rid)`);
40
+ }
41
+ const cookie = optionalString(config.cookie);
42
+ const signerUrl = optionalString(config.signerUrl);
43
+ if (signerUrl && !/^https?:\/\//i.test(signerUrl)) {
44
+ throw new Error(`douyin-live endpoint "${id}" signerUrl must be an http(s) URL`);
45
+ }
46
+ return Object.freeze({
47
+ context: 'douyin-live',
48
+ id,
49
+ roomId,
50
+ ...(cookie ? { cookie } : {}),
51
+ // α:默认只听不说;只有显式写 direct 才进入(尚未实现的)发送路径。
52
+ sendMode: config.sendMode === 'direct' ? 'direct' : 'off',
53
+ maxLength: intInRange(config.maxLength, DOUYIN_LIVE_DEFAULT_MAX_LENGTH, 10, 100),
54
+ maxChunks: intInRange(config.maxChunks, DOUYIN_LIVE_DEFAULT_MAX_CHUNKS, 1, 5),
55
+ minSendIntervalMs: intInRange(config.minSendIntervalSec, DOUYIN_LIVE_DEFAULT_SEND_INTERVAL_SEC, DOUYIN_LIVE_MIN_SEND_INTERVAL_SEC, 3600) * 1000,
56
+ ...(signerUrl ? { signerUrl } : {}),
57
+ });
58
+ }
59
+ /** 解出一层 message 的所有字段(varint / fixed / length-delimited)。格式错误抛错。 */
60
+ export function readProtoFields(bytes) {
61
+ const fields = [];
62
+ let pos = 0;
63
+ const varint = () => {
64
+ let result = 0n;
65
+ let shift = 0n;
66
+ for (let i = 0; i < 10; i++) {
67
+ if (pos >= bytes.length)
68
+ throw new Error('truncated varint');
69
+ const byte = bytes[pos++];
70
+ result |= BigInt(byte & 0x7f) << shift;
71
+ if ((byte & 0x80) === 0)
72
+ return result;
73
+ shift += 7n;
74
+ }
75
+ throw new Error('varint too long');
76
+ };
77
+ while (pos < bytes.length) {
78
+ const key = varint();
79
+ const field = Number(key >> 3n);
80
+ const wire = Number(key & 7n);
81
+ if (field <= 0)
82
+ throw new Error('invalid field number');
83
+ if (wire === 0) {
84
+ fields.push({ field, value: varint() });
85
+ }
86
+ else if (wire === 2) {
87
+ const length = Number(varint());
88
+ if (length < 0 || pos + length > bytes.length)
89
+ throw new Error('truncated bytes');
90
+ fields.push({ field, value: bytes.subarray(pos, pos + length) });
91
+ pos += length;
92
+ }
93
+ else if (wire === 1 || wire === 5) {
94
+ const size = wire === 1 ? 8 : 4;
95
+ if (pos + size > bytes.length)
96
+ throw new Error('truncated fixed');
97
+ let value = 0n;
98
+ for (let i = size - 1; i >= 0; i--)
99
+ value = (value << 8n) | BigInt(bytes[pos + i]);
100
+ fields.push({ field, value });
101
+ pos += size;
102
+ }
103
+ else {
104
+ throw new Error(`unsupported wire type ${wire}`);
105
+ }
106
+ }
107
+ return fields;
108
+ }
109
+ const utf8 = new TextDecoder('utf-8');
110
+ const first = (fields, field) => fields.find((item) => item.field === field)?.value;
111
+ const asBytes = (value) => (value instanceof Uint8Array ? value : undefined);
112
+ const asString = (value) => (value instanceof Uint8Array ? utf8.decode(value) : '');
113
+ const asUint = (value) => (typeof value === 'bigint' ? value : 0n);
114
+ function writeVarint(out, value) {
115
+ let v = BigInt.asUintN(64, value);
116
+ while (v >= 0x80n) {
117
+ out.push(Number((v & 0x7fn) | 0x80n));
118
+ v >>= 7n;
119
+ }
120
+ out.push(Number(v));
121
+ }
122
+ function writeBytesField(out, field, bytes) {
123
+ writeVarint(out, BigInt((field << 3) | 2));
124
+ writeVarint(out, BigInt(bytes.length));
125
+ for (const byte of bytes)
126
+ out.push(byte);
127
+ }
128
+ export function decodePushFrame(bytes) {
129
+ if (bytes.byteLength > MAX_FRAME_BYTES)
130
+ return undefined;
131
+ try {
132
+ const fields = readProtoFields(bytes);
133
+ return Object.freeze({
134
+ seqId: asUint(first(fields, 1)).toString(),
135
+ logId: asUint(first(fields, 2)).toString(),
136
+ payloadEncoding: asString(first(fields, 6)),
137
+ payloadType: asString(first(fields, 7)),
138
+ payload: asBytes(first(fields, 8)) ?? new Uint8Array(),
139
+ });
140
+ }
141
+ catch {
142
+ return undefined;
143
+ }
144
+ }
145
+ export function encodePushFrame(frame) {
146
+ const out = [];
147
+ if (frame.logId && frame.logId !== '0') {
148
+ writeVarint(out, 2n << 3n);
149
+ writeVarint(out, BigInt(frame.logId));
150
+ }
151
+ if (frame.payloadEncoding)
152
+ writeBytesField(out, 6, Buffer.from(frame.payloadEncoding, 'utf8'));
153
+ writeBytesField(out, 7, Buffer.from(frame.payloadType, 'utf8'));
154
+ if (frame.payload && frame.payload.length > 0)
155
+ writeBytesField(out, 8, frame.payload);
156
+ return Uint8Array.from(out);
157
+ }
158
+ /** 心跳帧:`PushFrame { payloadType: 'hb' }`。 */
159
+ export function encodeHeartbeat() {
160
+ return encodePushFrame({ payloadType: 'hb' });
161
+ }
162
+ /** 确认帧:`Response.needAck` 时回 `PushFrame { logId, payloadType: 'ack', payload: internalExt }`。 */
163
+ export function encodeAck(logId, internalExt) {
164
+ return encodePushFrame({ logId, payloadType: 'ack', payload: Buffer.from(internalExt, 'utf8') });
165
+ }
166
+ /**
167
+ * 解一帧:PushFrame → (gzip)→ Response。不是消息帧(如心跳回包)或坏帧返回 undefined,不抛错:
168
+ * 平台改版时宁可漏几条弹幕,也不让连接崩溃重连刷屏。
169
+ */
170
+ export function decodeWebcastFrame(bytes) {
171
+ const frame = decodePushFrame(bytes);
172
+ if (!frame)
173
+ return undefined;
174
+ if (frame.payloadType && frame.payloadType !== 'msg')
175
+ return { frame };
176
+ if (frame.payload.length === 0)
177
+ return { frame };
178
+ try {
179
+ const gzipped = frame.payloadEncoding === 'gzip' || (frame.payload[0] === 0x1f && frame.payload[1] === 0x8b);
180
+ const raw = gzipped ? gunzipSync(frame.payload, { maxOutputLength: MAX_FRAME_BYTES }) : frame.payload;
181
+ const fields = readProtoFields(raw);
182
+ const messages = [];
183
+ for (const item of fields) {
184
+ if (item.field !== 1 || !(item.value instanceof Uint8Array))
185
+ continue;
186
+ try {
187
+ const msg = readProtoFields(item.value);
188
+ messages.push(Object.freeze({
189
+ method: asString(first(msg, 1)),
190
+ payload: asBytes(first(msg, 2)) ?? new Uint8Array(),
191
+ msgId: asUint(first(msg, 3)).toString(),
192
+ }));
193
+ }
194
+ catch {
195
+ // 单条坏消息:跳过。
196
+ }
197
+ }
198
+ return {
199
+ frame,
200
+ response: Object.freeze({
201
+ messages: Object.freeze(messages),
202
+ internalExt: asString(first(fields, 5)),
203
+ heartbeatDurationMs: Number(asUint(first(fields, 8))),
204
+ needAck: asUint(first(fields, 9)) !== 0n,
205
+ }),
206
+ };
207
+ }
208
+ catch {
209
+ return { frame };
210
+ }
211
+ }
212
+ /**
213
+ * 解 `ChatMessage`:common 1(method 1 / msgId 2 / roomId 3 / createTime 4)、
214
+ * user 2(id 1 / nickName 3 / idStr 1028)、content 3、eventTime 15。
215
+ */
216
+ export function parseChatMessage(message, now = Date.now) {
217
+ if (message.method !== DOUYIN_CHAT_METHOD)
218
+ return undefined;
219
+ try {
220
+ const chat = readProtoFields(message.payload);
221
+ const text = asString(first(chat, 3)).trim();
222
+ if (!text)
223
+ return undefined;
224
+ const commonBytes = asBytes(first(chat, 1));
225
+ const common = commonBytes ? readProtoFields(commonBytes) : [];
226
+ const userBytes = asBytes(first(chat, 2));
227
+ const user = userBytes ? readProtoFields(userBytes) : [];
228
+ const idStr = asString(first(user, 1028)).trim();
229
+ const numericId = asUint(first(user, 1));
230
+ const uid = /^\d+$/.test(idStr) && !/^0+$/.test(idStr) ? idStr : numericId.toString();
231
+ const nickname = asString(first(user, 3)).trim() || uid;
232
+ const commonMsgId = asUint(first(common, 2));
233
+ const msgId = commonMsgId !== 0n ? commonMsgId.toString() : message.msgId !== '0' ? message.msgId : undefined;
234
+ const roomId = asUint(first(common, 3));
235
+ const createTime = Number(asUint(first(common, 4)));
236
+ const eventTime = Number(asUint(first(chat, 15)));
237
+ const raw = createTime > 0 ? createTime : eventTime;
238
+ // createTime 为毫秒,eventTime 为秒;按量级区分。
239
+ const timestamp = raw <= 0 ? now() : raw < 1e12 ? raw * 1000 : raw;
240
+ return Object.freeze({
241
+ ...(msgId ? { id: msgId } : {}),
242
+ text,
243
+ uid,
244
+ nickname,
245
+ ...(roomId !== 0n ? { roomId: roomId.toString() } : {}),
246
+ timestamp,
247
+ });
248
+ }
249
+ catch {
250
+ return undefined;
251
+ }
252
+ }
253
+ /** 出站:弹幕只支持纯文本;抖音弹幕没有「回复」字段,mention 折叠进正文 ` @昵称 `(前后留空格,避免与相邻文本粘连)。 */
254
+ export function formatOutboundDanmaku(payload) {
255
+ if (typeof payload === 'string')
256
+ return payload.replace(/\s+/g, ' ').trim();
257
+ if (payload == null)
258
+ return '';
259
+ const items = Array.isArray(payload) ? payload : [payload];
260
+ return items.map((item) => {
261
+ if (typeof item === 'string')
262
+ return item;
263
+ if (!item || typeof item !== 'object')
264
+ return '';
265
+ const seg = item;
266
+ if (seg.type === 'text')
267
+ return String(seg.data?.text ?? '');
268
+ if (seg.type === 'mention' || seg.type === 'at') {
269
+ const name = String(seg.data?.name ?? seg.data?.id ?? seg.data?.user_id ?? '').trim();
270
+ return name ? ` @${name} ` : '';
271
+ }
272
+ return '';
273
+ }).join('').replace(/\s+/g, ' ').trim();
274
+ }
275
+ /**
276
+ * 把回复切成至多 `maxChunks` 条弹幕,每条至多 `maxLength` 字符(按码点算)。
277
+ * 放不下的部分截掉,最后一条以「…」结尾。
278
+ */
279
+ export function splitDanmaku(text, maxLength, maxChunks) {
280
+ const chars = [...text.trim()];
281
+ if (chars.length === 0)
282
+ return [];
283
+ const chunks = [];
284
+ for (let start = 0; start < chars.length && chunks.length < maxChunks; start += maxLength) {
285
+ chunks.push(chars.slice(start, start + maxLength).join(''));
286
+ }
287
+ if (chars.length > maxLength * maxChunks) {
288
+ const last = [...chunks[chunks.length - 1]];
289
+ chunks[chunks.length - 1] = `${last.slice(0, maxLength - 1).join('')}…`;
290
+ }
291
+ return chunks;
292
+ }