dsh-remote-web 0.7.11-beta.3 → 0.7.12-beta.2

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,372 @@
1
+ /**
2
+ * im-format — **通道感知的消息格式化**(2026-11-08 业主反馈「企微/飞书推回来的表格都是乱的」)。
3
+ *
4
+ * 背景
5
+ * -----------------------------------------------------------------
6
+ * agent 的最终回答常带 Markdown 表格(`| a | b |`)、标题、引用、任务列表…… 而企业微信 / 钉钉的
7
+ * markdown **不支持表格**:原样发出去就是一堆竖线,用户看到的就是「乱」。不同 IM 通道的能力也不同
8
+ * (企微/钉钉支持 markdown 子集;飞书 markdown 能力弱、卡片强;个人微信机器人有自己的一套特殊格式),
9
+ * 所以"发之前按通道能力适配一次"应该是一个**独立的、可单测的纯函数模块**,而不是散在 wecom-bot 里。
10
+ *
11
+ * 用法
12
+ * -----------------------------------------------------------------
13
+ * ```js
14
+ * import { formatForChannel, CHANNEL_CAPS } from "./im-format.mjs";
15
+ * const text = formatForChannel("wecom", { title: "", text: agentAnswer });
16
+ * ```
17
+ * 规则(确定性、可测,见 formatForChannel 注释):
18
+ * · 表格 → 「• 列1:值1 · 列2:值2」多行(列多/超宽时按「• 记录 N」+ 每列一行拆开)
19
+ * · `#` 标题 → 加粗(markdown 通道)/ 纯文本
20
+ * · `---` 分隔线 → 空行;`>` 引用 → `› `;`- [ ]` / `- [x]` → `☐` / `☑`;嵌套列表压平一层
21
+ * · 代码块**原样保留**;inline code / bold / 链接不动(企微 markdown 支持)
22
+ * · wecom 默认按 **4096 字节(UTF-8)** 截断,优先在段落/行边界,附「…(已截断,完整内容看电脑)」
23
+ * · `wechat` 走现有特殊格式(本模块只做 **plain 兜底**,不重复实现微信那套富文本)
24
+ * · 未知通道 → `plain`(fail-safe:宁可少用格式,也不发坏的 markdown)
25
+ */
26
+
27
+ /** 各通道能力(钉钉/飞书实现时直接复用;wechat = 现有特殊格式,不经本模块排版)。 */
28
+ export const CHANNEL_CAPS = Object.freeze({
29
+ wecom: Object.freeze({ markdown: true, tables: false, card: true }),
30
+ dingtalk: Object.freeze({ markdown: true, tables: false, card: true }),
31
+ feishu: Object.freeze({ markdown: false, tables: false, card: true }),
32
+ wechat: Object.freeze({ markdown: false, special: true }),
33
+ plain: Object.freeze({ markdown: false })
34
+ });
35
+
36
+ /** 截断提示(与 wecom-bot 的 ANSWER_TRUNCATED_NOTE 同文,便于去重)。 */
37
+ export const TRUNCATED_NOTE = "…(已截断,完整内容看电脑)";
38
+
39
+ /** 各通道默认字节上限(wecom 官方 4096;其它先给宽松值,留 maxBytes 覆盖)。 */
40
+ const DEFAULT_MAX_BYTES = Object.freeze({
41
+ wecom: 4096,
42
+ dingtalk: 4096,
43
+ feishu: 8192,
44
+ wechat: Infinity,
45
+ plain: Infinity
46
+ });
47
+
48
+ /** UTF-8 字节数(中文 3 字节;emoji 4 字节)。 */
49
+ export function utf8Bytes(value) {
50
+ try {
51
+ return Buffer.byteLength(String(value == null ? "" : value), "utf8");
52
+ } catch {
53
+ return String(value == null ? "" : value).length * 3;
54
+ }
55
+ }
56
+
57
+ /** 终端/聊天窗口的显示宽度(CJK 与 emoji 记 2 列;只用于"这行会不会太宽"的确定性判断)。 */
58
+ export function displayWidth(value) {
59
+ let width = 0;
60
+ for (const ch of String(value == null ? "" : value)) {
61
+ const cp = ch.codePointAt(0) || 0;
62
+ const wide = cp === 0x2329 || cp === 0x232a
63
+ || (cp >= 0x1100 && cp <= 0x115f)
64
+ || (cp >= 0x2e80 && cp <= 0xa4cf)
65
+ || (cp >= 0xac00 && cp <= 0xd7a3)
66
+ || (cp >= 0xf900 && cp <= 0xfaff)
67
+ || (cp >= 0xfe30 && cp <= 0xfe4f)
68
+ || (cp >= 0xff00 && cp <= 0xff60)
69
+ || (cp >= 0xffe0 && cp <= 0xffe6)
70
+ || (cp >= 0x1f300 && cp <= 0x1f64f)
71
+ || (cp >= 0x1f900 && cp <= 0x1f9ff)
72
+ || (cp >= 0x20000 && cp <= 0x3fffd);
73
+ width += wide ? 2 : 1;
74
+ }
75
+ return width;
76
+ }
77
+
78
+ /** 通道名规范化:未知/空 → `plain`(fail-safe)。 */
79
+ export function normalizeChannelName(channel) {
80
+ const name = String(channel || "").trim().toLowerCase();
81
+ if (Object.prototype.hasOwnProperty.call(CHANNEL_CAPS, name)) return name;
82
+ // 常见别名(调用方拼错/叫法不同时不至于掉进 markdown 分支)
83
+ if (name === "weixin" || name === "wx" || name === "wechat-bot" || name === "personal") return "wechat";
84
+ if (name === "workbench" || name === "wxwork" || name === "qywx" || name === "wecom-bot") return "wecom";
85
+ if (name === "ding" || name === "dingding") return "dingtalk";
86
+ if (name === "lark") return "feishu";
87
+ return "plain";
88
+ }
89
+
90
+ // ---------- Markdown 表格解析(确定性:只按未转义的 `|` 切) ----------
91
+
92
+ /** 是否是表格行(以 `|` 开头且至少 2 个竖线)。 */
93
+ function isTableLine(line) {
94
+ const t = String(line || "").trim();
95
+ if (!t.startsWith("|")) return false;
96
+ const count = (t.match(/\|/g) || []).length;
97
+ return count >= 2;
98
+ }
99
+
100
+ /** 把一行表格拆成单元格(支持 `\|` 转义;不会把转义竖线当分隔符)。 */
101
+ export function splitTableRow(line) {
102
+ let s = String(line || "").trim();
103
+ if (s.startsWith("|")) s = s.slice(1);
104
+ // 结尾的竖线是边框(`\|` 结尾不算)
105
+ if (s.endsWith("|") && !s.endsWith("\\|")) s = s.slice(0, -1);
106
+ const cells = [];
107
+ let cur = "";
108
+ for (let i = 0; i < s.length; i += 1) {
109
+ const ch = s[i];
110
+ if (ch === "\\" && s[i + 1] === "|") { cur += "|"; i += 1; continue; }
111
+ if (ch === "|") { cells.push(cur.trim()); cur = ""; continue; }
112
+ cur += ch;
113
+ }
114
+ cells.push(cur.trim());
115
+ return cells;
116
+ }
117
+
118
+ /** 分隔行(`|---|---|` / `|:--|--:|`)。 */
119
+ function isSeparatorRow(cells) {
120
+ return Array.isArray(cells) && cells.length > 0 && cells.every((c) => /^:?-{1,}:?$/.test(String(c || "").trim()));
121
+ }
122
+
123
+ /**
124
+ * 表格 → 可读文本。
125
+ *
126
+ * 规则(写死,便于单测):
127
+ * · 每条数据行 = 「• 列1:值1 · 列2:值2 …」;
128
+ * · 列数 ≤3 且整行显示宽度 ≤60 → 单行;否则拆成「• 记录 N」+ 每列一行(避免超宽/被客户端折行成乱码);
129
+ * · 表头作为**列名**逐行带上(不是另起一行表格头——用户要的是"看得懂哪列是什么")。
130
+ * @param {string[]} lines 连续的表格行
131
+ * @returns {string[]} 转换后的行(不含 `|---`)
132
+ */
133
+ export function convertMarkdownTable(lines) {
134
+ const rows = (Array.isArray(lines) ? lines : []).map(splitTableRow);
135
+ if (!rows.length) return [];
136
+ let header = null;
137
+ let dataRows = rows;
138
+ if (rows.length >= 2 && isSeparatorRow(rows[1])) { header = rows[0]; dataRows = rows.slice(2); }
139
+ else if (rows.length >= 1 && isSeparatorRow(rows[0])) { dataRows = rows.slice(1); }
140
+ else { header = rows[0]; dataRows = rows.slice(1); }
141
+ const colCount = Math.max(
142
+ header ? header.length : 0,
143
+ ...dataRows.map((r) => r.length),
144
+ 0
145
+ );
146
+ const out = [];
147
+ let index = 0;
148
+ for (const row of dataRows) {
149
+ if (!row || isSeparatorRow(row)) continue;
150
+ index += 1;
151
+ const cells = [];
152
+ for (let c = 0; c < colCount; c += 1) {
153
+ const rawName = header && header[c] ? String(header[c]).trim() : "";
154
+ const name = rawName || `列${c + 1}`;
155
+ const val = row[c] == null ? "" : String(row[c]).trim();
156
+ if (!val) continue;
157
+ cells.push({ name, val });
158
+ }
159
+ if (!cells.length) continue;
160
+ const oneLine = cells.map((c) => `${c.name}:${c.val}`).join(" · ");
161
+ if (cells.length <= 3 && displayWidth(oneLine) <= 60) {
162
+ out.push(`• ${oneLine}`);
163
+ continue;
164
+ }
165
+ out.push(`• 记录 ${index}`);
166
+ for (const c of cells) out.push(` ${c.name}:${c.val}`);
167
+ }
168
+ return out;
169
+ }
170
+
171
+ // ---------- 行级转换 ----------
172
+
173
+ const RE_FENCE = /^\s{0,3}(```|~~~)/;
174
+ const RE_HEADING = /^\s{0,3}(#{1,6})\s+(.*?)\s*#*\s*$/;
175
+ const RE_HR = /^\s{0,3}([-*_])(?:\s*\1){2,}\s*$/;
176
+ const RE_QUOTE = /^\s{0,3}>\s?(.*)$/;
177
+ const RE_TASK = /^(\s*)([-*+]|\d+\.)\s+\[( |x|X)\]\s+(.*)$/;
178
+ const RE_NESTED_LIST = /^(\s{2,})([-*+]|\d+\.)\s+(.*)$/;
179
+ const RE_BULLET = /^(\s*)([-*+])\s+(.*)$/;
180
+
181
+ /** 把一段"非代码块"文本按行转换(markdown 通道保留 inline 语法;非 markdown 通道降级)。 */
182
+ function convertLines(lines, markdown) {
183
+ const out = [];
184
+ let table = [];
185
+ const flushTable = () => {
186
+ if (!table.length) return;
187
+ const converted = convertMarkdownTable(table);
188
+ if (converted.length) {
189
+ out.push("", ...converted, "");
190
+ }
191
+ table = [];
192
+ };
193
+ for (const rawLine of lines) {
194
+ const line = String(rawLine == null ? "" : rawLine);
195
+ if (isTableLine(line)) { table.push(line); continue; }
196
+ flushTable();
197
+ // 标题
198
+ const heading = RE_HEADING.exec(line);
199
+ if (heading) {
200
+ const text = heading[2].trim();
201
+ out.push(markdown ? `**${text}**` : text);
202
+ continue;
203
+ }
204
+ // 分隔线 → 空行
205
+ if (RE_HR.test(line)) { out.push(""); continue; }
206
+ // 引用
207
+ const quote = RE_QUOTE.exec(line);
208
+ if (quote) { out.push(`› ${quote[1].trim()}`); continue; }
209
+ // 任务列表(☐/☑,不再保留 `- [ ]`)
210
+ const task = RE_TASK.exec(line);
211
+ if (task) {
212
+ const done = String(task[3]).toLowerCase() === "x";
213
+ const box = done ? "☑" : "☐";
214
+ out.push(markdown ? `- ${box} ${task[4].trim()}` : `${box} ${task[4].trim()}`);
215
+ continue;
216
+ }
217
+ // 嵌套列表:压平一层(更深缩进统一成 2 空格 + `·`,不再出现多层缩进)
218
+ const nested = RE_NESTED_LIST.exec(line);
219
+ if (nested) { out.push(` · ${nested[3].trim()}`); continue; }
220
+ // 普通列表:非 markdown 通道把 `-` 换成 `•`(markdown 通道保持)
221
+ const bullet = RE_BULLET.exec(line);
222
+ if (bullet && !markdown) { out.push(`${bullet[1]}• ${bullet[3].trim()}`); continue; }
223
+ out.push(markdown ? line : line.replace(/\*\*(.+?)\*\*/g, "$1").replace(/`([^`]+)`/g, "$1"));
224
+ }
225
+ flushTable();
226
+ return out;
227
+ }
228
+
229
+ /** 整段 Markdown → 目标通道文本(代码块原样保留)。 */
230
+ function convertMarkdownLike(input, markdown) {
231
+ const text = String(input == null ? "" : input);
232
+ if (!text.trim()) return "";
233
+ const lines = text.split("\n");
234
+ const out = [];
235
+ let code = [];
236
+ let inCode = false;
237
+ const flushCode = () => {
238
+ if (!code.length) return;
239
+ if (markdown) out.push(...code);
240
+ else {
241
+ // 非 markdown 通道:去掉围栏,内容缩进两格(保持"是代码"的观感,不出现 ```)
242
+ for (const line of code) {
243
+ if (RE_FENCE.test(line)) continue;
244
+ out.push(line ? ` ${line}` : "");
245
+ }
246
+ }
247
+ code = [];
248
+ };
249
+ let plainBuffer = [];
250
+ const flushPlain = () => {
251
+ if (!plainBuffer.length) return;
252
+ out.push(...convertLines(plainBuffer, markdown));
253
+ plainBuffer = [];
254
+ };
255
+ for (const line of lines) {
256
+ if (RE_FENCE.test(line)) {
257
+ if (!inCode) { flushPlain(); inCode = true; code = [line]; continue; }
258
+ code.push(line); flushCode(); inCode = false; continue;
259
+ }
260
+ if (inCode) { code.push(line); continue; }
261
+ plainBuffer.push(line);
262
+ }
263
+ if (inCode) flushCode(); // 未闭合的代码块也原样保留(不吞内容)
264
+ flushPlain();
265
+ // 收尾清理:行尾空格 / 连续空行压成一个 / 首尾空行去掉
266
+ const cleaned = [];
267
+ for (const line of out) {
268
+ const trimmedRight = String(line).replace(/[ \t]+$/, "");
269
+ if (trimmedRight === "" && (cleaned.length === 0 || cleaned[cleaned.length - 1] === "")) continue;
270
+ cleaned.push(trimmedRight);
271
+ }
272
+ while (cleaned.length && cleaned[cleaned.length - 1] === "") cleaned.pop();
273
+ return cleaned.join("\n");
274
+ }
275
+
276
+ // ---------- 截断(按 UTF-8 字节 / 字符,优先段落边界) ----------
277
+
278
+ function fitsBoth(value, maxBytes, maxChars) {
279
+ if (utf8Bytes(value) > maxBytes) return false;
280
+ if (maxChars !== Infinity && [...String(value)].length > maxChars) return false;
281
+ return true;
282
+ }
283
+
284
+ /**
285
+ * 安全截断:优先整段 → 整行 → 逐码点;绝不切在 UTF-8 中间(用 `for...of` 按码点累加)。
286
+ * 结果末尾附 `suffix`(调用方保证 suffix 也计入上限)。
287
+ * @returns {string}
288
+ */
289
+ export function truncateUtf8Safe(text, { maxBytes = Infinity, maxChars = Infinity, suffix = TRUNCATED_NOTE } = {}) {
290
+ const body = String(text == null ? "" : text);
291
+ if (fitsBoth(body, maxBytes, maxChars)) return body;
292
+ const tail = `\n${suffix}`;
293
+ const budgetBytes = maxBytes - utf8Bytes(tail);
294
+ const budgetChars = maxChars === Infinity ? Infinity : maxChars - [...tail].length;
295
+ if (budgetBytes <= 0 || (budgetChars !== Infinity && budgetChars <= 0)) return suffix;
296
+ // ① 段落
297
+ let out = "";
298
+ for (const para of body.split(/\n{2,}/)) {
299
+ const cand = out ? `${out}\n\n${para}` : para;
300
+ if (!fitsBoth(cand, budgetBytes, budgetChars)) break;
301
+ out = cand;
302
+ }
303
+ // ② 行
304
+ if (!out) {
305
+ for (const line of body.split("\n")) {
306
+ const cand = out ? `${out}\n${line}` : line;
307
+ if (!fitsBoth(cand, budgetBytes, budgetChars)) break;
308
+ out = cand;
309
+ }
310
+ }
311
+ // ③ 逐码点(不会切坏代理对/中文)
312
+ if (!out) {
313
+ for (const ch of body) {
314
+ const cand = out + ch;
315
+ if (!fitsBoth(cand, budgetBytes, budgetChars)) break;
316
+ out = cand;
317
+ }
318
+ }
319
+ return `${out.replace(/[ \t]+$/, "")}${tail}`;
320
+ }
321
+
322
+ // ---------- 对外主函数 ----------
323
+
324
+ /**
325
+ * 按通道能力格式化消息。
326
+ *
327
+ * 支持的选项:
328
+ * · `text` 正文(Markdown 源码)
329
+ * · `title` 可选标题(会作为加粗/纯文本首行;正文里的 `#` 标题也会各自转换)
330
+ * · `kind` 预留:目前不影响输出(钉钉/飞书将来可按 kind 分样式)
331
+ * · `maxChars` 字符上限(可选)
332
+ * · `maxBytes` 字节上限(默认按通道:wecom/dingtalk 4096;feishu 8192;plain/wechat 不限)
333
+ *
334
+ * @param {"wecom"|"dingtalk"|"feishu"|"wechat"|"plain"|string} channel
335
+ * @param {{title?:string, text?:string, kind?:string, maxChars?:number, maxBytes?:number}} [options]
336
+ * @returns {string}
337
+ */
338
+ export function formatForChannel(channel, options = {}) {
339
+ const name = normalizeChannelName(channel);
340
+ const caps = CHANNEL_CAPS[name] || CHANNEL_CAPS.plain;
341
+ const markdown = caps.markdown === true;
342
+ const rawText = String(options.text == null ? "" : options.text);
343
+ const maxBytes = Number.isFinite(Number(options.maxBytes)) && Number(options.maxBytes) > 0
344
+ ? Number(options.maxBytes) : DEFAULT_MAX_BYTES[name];
345
+ const maxChars = Number.isFinite(Number(options.maxChars)) && Number(options.maxChars) > 0
346
+ ? Number(options.maxChars) : Infinity;
347
+
348
+ // 调用方可能已经自己截断过并附了 suffix(wecom-bot 的回答回传会先按字符截 1500):
349
+ // 先摘掉,统一由本模块决定是否需要再按字节截,避免出现两个「已截断」。
350
+ let preTruncated = false;
351
+ let bodyText = rawText;
352
+ if (bodyText.endsWith(TRUNCATED_NOTE)) {
353
+ preTruncated = true;
354
+ bodyText = bodyText.slice(0, -TRUNCATED_NOTE.length);
355
+ }
356
+
357
+ let body = convertMarkdownLike(bodyText, markdown);
358
+ const title = String(options.title == null ? "" : options.title).trim();
359
+ if (title) {
360
+ const titleLine = markdown ? `**${title}**` : title;
361
+ body = body ? `${titleLine}\n\n${body}` : titleLine;
362
+ }
363
+ // 微信通道有其自己的特殊格式(wechat-runtime 负责):这里只做 plain 兜底,且不截断(由微信侧管)。
364
+ if (name === "wechat") return body;
365
+
366
+ const fitted = truncateUtf8Safe(body, { maxBytes, maxChars, suffix: TRUNCATED_NOTE });
367
+ if (fitted === body) {
368
+ // 原本就在上限内:如果调用方已标过截断,保留它的提示(不要悄悄丢掉;保持原样拼接)
369
+ return preTruncated ? `${body}${TRUNCATED_NOTE}` : body;
370
+ }
371
+ return fitted;
372
+ }
@@ -10,10 +10,15 @@
10
10
  * 1. **绝不打扰用户**:不改 DOM、不加 UI、不阻塞渲染;任何异常都在内部吞掉。
11
11
  * 2. **只在出错时上报**:没有失败资源/脚本错误 → 一个字节都不发(零流量)。
12
12
  * 3. **不泄密**:只上报**路径**(剥掉 query/hash)、状态码、耗时、字节数、错误消息前 500 字;
13
- * 不上报页面内容、请求体、cookie、token、用户信息。
13
+ * 不上报页面内容、请求体、cookie、token、用户信息。`page_id` 是**本页随机串**,
14
+ * 不含设备号/账号/时间派生信息,只用于把同一页的多批上报关联起来。
14
15
  * 4. **可关**:`?mirror_diag=0` 或 bridge 环境变量 `DSH_MIRROR_DIAG=0` → 完全不注入。
15
16
  * 5. **慢请求也记**:`/plugins/`、`/assets/` 加载超过 8s 记一条(这正是"插件聚合包被
16
17
  * 限速拖死 → 浏览器 499"的现场)。
18
+ * 6. **追加批(2026-11-08)**:同一页面最多 3 批、批间 ≥3s。此前 `sent` 一置位后
19
+ * `add()` 直接丢弃 —— 首屏失败后自动重试 2 次的**后续**失败明细全部丢失
20
+ * (生产现场:4 项首屏资源失败、2 次重试,服务端只拿到第一批)。现在按批上报,
21
+ * 每批 ≤20 项(服务端上限);成功页仍然**一个字节都不发**。
17
22
  *
18
23
  * 上报地址:`/relay-api/api/mirror-diag`(企业端,需登录态;token 从 localStorage.dsh_token 取)。
19
24
  */
@@ -22,13 +27,22 @@
22
27
  var W = window, D = document;
23
28
  var VERSION = 1;
24
29
  var SLOW_MS = 8000;
30
+ /** 每批最多 20 项:服务端 `POST /api/mirror-diag` 的上限就是 20,多了会被截断。 */
25
31
  var MAX_ITEMS = 20;
26
32
  var FLUSH_DELAY = 2500;
33
+ /** 同一页面最多上报批数(服务端还有每 (user,page) 每日 3 行的硬约束)。 */
34
+ var MAX_FLUSHES = 3;
35
+ /** 批间最小间隔:防止重试风暴把 3 批在几毫秒内打光。 */
36
+ var FLUSH_GAP_MS = 3000;
27
37
  var ENDPOINT = "/relay-api/api/mirror-diag";
28
38
  var items = [];
29
39
  var bootFailed = [];
30
- var sent = false;
40
+ var flushCount = 0;
41
+ var lastFlushAt = 0;
31
42
  var timer = null;
43
+ /** 本页随机 id:只用 Date.now/random,不引 crypto(老 Safari 可能没有 randomUUID),
44
+ * 不含设备/账号信息,仅用于把同一页的 2~3 批关联(服务端按 (user,page) 限流也够用)。 */
45
+ var pageId = "p" + Date.now().toString(36) + "-" + Math.random().toString(36).slice(2, 10);
32
46
 
33
47
  function now() { return Date.now(); }
34
48
  function clip(s, n) { s = String(s == null ? "" : s); return s.length > n ? s.slice(0, n) : s; }
@@ -40,10 +54,14 @@
40
54
  return clip(x.pathname, 300);
41
55
  } catch (e) { return null; }
42
56
  }
57
+ function schedule(delayMs) {
58
+ if (timer !== null) return;
59
+ timer = setTimeout(function () { flush(false); }, delayMs);
60
+ }
43
61
  function add(item) {
44
- if (!item || items.length >= MAX_ITEMS || sent) return;
62
+ if (!item || items.length >= MAX_ITEMS || flushCount >= MAX_FLUSHES) return;
45
63
  items.push(item);
46
- if (timer === null) timer = setTimeout(flush, FLUSH_DELAY);
64
+ schedule(FLUSH_DELAY);
47
65
  }
48
66
  function interesting(p) {
49
67
  return !!p && (p.indexOf("/plugins/") === 0 || p.indexOf("/assets/") === 0
@@ -105,7 +123,7 @@
105
123
  }
106
124
  }
107
125
  if (bootFailed.length === 0) bootFailed.push("Failed to load plugins(无明细文本)");
108
- if (timer === null) timer = setTimeout(flush, 300);
126
+ schedule(300);
109
127
  } catch (x) {}
110
128
  }
111
129
  try {
@@ -141,19 +159,39 @@
141
159
  } catch (e) { return undefined; }
142
160
  }
143
161
 
144
- function flush() {
162
+ /**
163
+ * 发送一批。
164
+ * @param {boolean} force true = pagehide 兜底:跳过批间隔等待,但仍受 MAX_FLUSHES 限制。
165
+ * 每批只发**尚未发出**的条目(发完即从数组头部移除),所以第 2/3 批带的是重试后的新失败。
166
+ */
167
+ function flush(force) {
145
168
  timer = null;
146
- if (sent || (items.length === 0 && bootFailed.length === 0)) return;
147
- sent = true;
169
+ if (items.length === 0 && bootFailed.length === 0) return;
170
+ if (flushCount >= MAX_FLUSHES) return;
171
+ var t = now();
172
+ // 批间节流:不足间隔就再等一会儿(pagehide 兜底不等,页面要走了)
173
+ if (!force && flushCount > 0) {
174
+ var wait = FLUSH_GAP_MS - (t - lastFlushAt);
175
+ if (wait > 0) { timer = setTimeout(function () { flush(false); }, wait); return; }
176
+ }
177
+ var batchItems = items.slice(0, MAX_ITEMS);
178
+ var batchBoot = bootFailed.slice(0, 10);
179
+ items = items.slice(batchItems.length);
180
+ bootFailed = bootFailed.slice(batchBoot.length);
181
+ flushCount += 1;
182
+ lastFlushAt = t;
148
183
  var tk = token();
149
184
  var payload = {
150
185
  v: VERSION,
151
- kind: bootFailed.length ? "boot" : "runtime",
186
+ kind: batchBoot.length ? "boot" : "runtime",
152
187
  page: clip(W.location.pathname, 200),
153
188
  ua: clip(W.navigator && W.navigator.userAgent, 300),
154
- items: items.slice(0, MAX_ITEMS),
155
- boot_failed: bootFailed.slice(0, 10),
156
- at: now()
189
+ // 追加批标记:b = 第几批(1 起),page_id = 本页随机串。老服务端不认识就无视(payload 是 JSON)。
190
+ b: flushCount,
191
+ page_id: pageId,
192
+ items: batchItems,
193
+ boot_failed: batchBoot,
194
+ at: t
157
195
  };
158
196
  var ui = uiDiag();
159
197
  if (ui) payload.ui = ui; // 可选字段:老服务端无视即可
@@ -168,6 +206,7 @@
168
206
  } catch (e) { /* ignore */ }
169
207
  }
170
208
 
171
- // 页面卸载前兜底发一次(keepalive 允许在卸载后继续)
172
- W.addEventListener("pagehide", function () { try { if (!sent) flush(); } catch (x) {} });
209
+ // 页面卸载前兜底发一次(keepalive 允许在卸载后继续);多批模式下即使已发过首批也要把
210
+ // 尚未发出的条目带走 —— 这正是"重试后的失败明细"最容易被丢掉的时刻。
211
+ W.addEventListener("pagehide", function () { try { flush(true); } catch (x) {} });
173
212
  })();