@aomex/logger-telegram-transport 4.15.0 → 4.16.1

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/CHANGELOG.md CHANGED
@@ -3,6 +3,21 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ ## [4.16.1](https://github.com/aomex/aomex/compare/v4.16.0...v4.16.1) (2026-12-04)
7
+
8
+ **Note:** Version bump only for package @aomex/logger-telegram-transport
9
+
10
+
11
+
12
+
13
+
14
+ # [4.16.0](https://github.com/aomex/aomex/compare/v4.15.0...v4.16.0) (2026-12-04)
15
+
16
+ ### Features
17
+
18
+ * **logger-telegram-transport:** 优化 dedupe 合并策略 ([c214e72](https://github.com/aomex/aomex/commit/c214e72d743bae4c58fb4f8a9c6b78ed47eabf47))
19
+
20
+
6
21
  # [4.15.0](https://github.com/aomex/aomex/compare/v4.14.0...v4.15.0) (2026-12-04)
7
22
 
8
23
  **Note:** Version bump only for package @aomex/logger-telegram-transport
package/dist/index.d.ts CHANGED
@@ -5,8 +5,8 @@ export declare const TELEGRAM_MESSAGE_MAX_LENGTH = 4096;
5
5
  type TelegramDedupeBindingKeys = 'all' | readonly string[];
6
6
  interface TelegramDedupeOptions {
7
7
  /**
8
- * 合并间隔(毫秒)。默认 `30_000`。
9
- * 间隔内相同指纹只发一条,正文带 `(×N)`。
8
+ * 合并间隔(毫秒)。默认 `60_000`。
9
+ * 间隔内相同指纹合并为一条:首条完整正文,第 2 条起在下方追加时间与 bindings。
10
10
  */
11
11
  interval?: number;
12
12
  /**
@@ -14,7 +14,10 @@ interface TelegramDedupeOptions {
14
14
  * 避免业务侧关联字段拆散合并;需要时自行传 `'all'` 或键名白名单。
15
15
  */
16
16
  bindingKeys?: TelegramDedupeBindingKeys;
17
- /** 自定义指纹;默认走 `fingerprintLog` */
17
+ /**
18
+ * 自定义合并指纹。不传时按 `level` + `message` + `exception` 生成;
19
+ * 是否纳入 bindings 由 `bindingKeys` 决定。
20
+ */
18
21
  fingerprint?: (log: LogRecord) => string;
19
22
  }
20
23
  interface TelegramTransportOptions {
@@ -26,11 +29,13 @@ interface TelegramTransportOptions {
26
29
  * 请求总超时(毫秒,含 auto-retry 等待)。默认 `120_000`。
27
30
  */
28
31
  timeout?: number;
29
- /** 自定义消息正文;默认 `formatTelegramMessage` */
32
+ /**
33
+ * 自定义消息正文。不传时为:`[level] 时间`、message、可选 bindings / exception。
34
+ */
30
35
  format?: (log: LogRecord) => string;
31
36
  /**
32
- * 间隔内相同指纹合并为一条后再发送。默认开启(间隔 30s,指纹不含 bindings)。
33
- * 传 `false` 则每条立即发送。
37
+ * 间隔内相同指纹合并为一条后再发送。默认关闭(每条立即发送)。
38
+ * 传 `true` 时默认间隔 60s,指纹不含 bindings;也可传选项对象细调。
34
39
  */
35
40
  dedupe?: boolean | TelegramDedupeOptions;
36
41
  }
@@ -40,8 +45,7 @@ type TelegramDedupeConfig = {
40
45
  fingerprint?: (log: LogRecord) => string;
41
46
  };
42
47
  type DedupeBufferEntry = {
43
- log: LogRecord;
44
- count: number;
48
+ logs: LogRecord[];
45
49
  timer: ReturnType<typeof setTimeout>;
46
50
  };
47
51
  /**
@@ -71,7 +75,13 @@ export declare class TelegramTransport extends Transport {
71
75
  protected formatMessage(log: LogRecord): string;
72
76
  /** 默认消息模板;子类可 override */
73
77
  protected formatTelegramMessage(log: LogRecord): string;
74
- protected formatBufferedMessage(log: LogRecord, count: number): string;
78
+ /**
79
+ * 合并窗口产出的正文:首条走 `formatMessage`;
80
+ * 其后每条追加一行时间(ISO)与 bindings(若有)。
81
+ */
82
+ protected formatBufferedMessage(logs: LogRecord[]): string;
83
+ /** 合并窗口内第 2 条及之后:`时间` + 可选 `bindings` JSON */
84
+ protected formatDedupeRepeat(log: LogRecord): string;
75
85
  /** 解析最终指纹(自定义 `fingerprint` 优先) */
76
86
  protected fingerprint(log: LogRecord): string;
77
87
  /**
package/dist/index.js CHANGED
@@ -62,10 +62,10 @@ var TelegramTransport = class extends Transport {
62
62
  await Promise.all([...this.pending]);
63
63
  }
64
64
  resolveDedupe(dedupe) {
65
- if (dedupe === false) return false;
66
- const opts = dedupe === true || dedupe == null ? {} : dedupe;
65
+ if (dedupe == null || dedupe === false) return false;
66
+ const opts = dedupe === true ? {} : dedupe;
67
67
  return {
68
- interval: opts.interval ?? 3e4,
68
+ interval: opts.interval ?? 6e4,
69
69
  bindingKeys: opts.bindingKeys,
70
70
  fingerprint: opts.fingerprint
71
71
  };
@@ -83,12 +83,23 @@ var TelegramTransport = class extends Transport {
83
83
  if (text.length <= 4096) return text;
84
84
  return `${text.slice(0, 4095)}…`;
85
85
  }
86
- formatBufferedMessage(log, count) {
87
- let text = this.formatMessage(log);
88
- if (count > 1) text += `\n(×${count})`;
86
+ /**
87
+ * 合并窗口产出的正文:首条走 `formatMessage`;
88
+ * 其后每条追加一行时间(ISO)与 bindings(若有)。
89
+ */
90
+ formatBufferedMessage(logs) {
91
+ const [first, ...rest] = logs;
92
+ let text = this.formatMessage(first);
93
+ if (rest.length > 0) text += `\n\n\n${rest.map((log) => this.formatDedupeRepeat(log)).join("\n")}`;
89
94
  if (text.length <= 4096) return text;
90
95
  return `${text.slice(0, 4095)}…`;
91
96
  }
97
+ /** 合并窗口内第 2 条及之后:`时间` + 可选 `bindings` JSON */
98
+ formatDedupeRepeat(log) {
99
+ let line = log.timestamp.toISOString();
100
+ if (log.bindings) line += ` ${JSON.stringify(log.bindings)}`;
101
+ return line;
102
+ }
92
103
  /** 解析最终指纹(自定义 `fingerprint` 优先) */
93
104
  fingerprint(log) {
94
105
  const dedupe = this.dedupe;
@@ -129,7 +140,7 @@ var TelegramTransport = class extends Transport {
129
140
  const fp = this.fingerprint(log);
130
141
  const existing = this.buffer.get(fp);
131
142
  if (existing) {
132
- existing.count += 1;
143
+ existing.logs.push(log);
133
144
  return;
134
145
  }
135
146
  const timer = setTimeout(() => {
@@ -140,8 +151,7 @@ var TelegramTransport = class extends Transport {
140
151
  }, dedupe.interval);
141
152
  timer.unref?.();
142
153
  this.buffer.set(fp, {
143
- log,
144
- count: 1,
154
+ logs: [log],
145
155
  timer
146
156
  });
147
157
  }
@@ -154,7 +164,7 @@ var TelegramTransport = class extends Transport {
154
164
  if (!entry) return;
155
165
  clearTimeout(entry.timer);
156
166
  this.buffer.delete(fp);
157
- const task = this.sendText(this.formatBufferedMessage(entry.log, entry.count)).finally(() => {
167
+ const task = this.sendText(this.formatBufferedMessage(entry.logs)).finally(() => {
158
168
  this.pending.delete(task);
159
169
  });
160
170
  this.pending.add(task);
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/i18n/locales/zh-cn.ts","../src/i18n/locales/en-us.ts","../src/i18n/index.ts","../src/telegram-transport.ts"],"sourcesContent":["import { I18n } from '@aomex/common';\n\nexport const zh = I18n.define({\n send_message_timed_out: 'Telegram 发送消息超时',\n});\n","import { I18n } from '@aomex/common';\nimport { zh } from './zh-cn';\n\nexport const en = I18n.satisfies(zh).define({\n send_message_timed_out: 'Telegram message send timed out',\n});\n","import { createI18n } from '@aomex/common';\nimport { zh } from './locales/zh-cn';\nimport { en } from './locales/en-us';\n\nexport const i18n = createI18n({\n zh,\n en,\n load: (file) => import(new URL(`./locales/${file}.js`, import.meta.url).href),\n});\n","import { Api } from 'grammy';\nimport { autoRetry } from '@grammyjs/auto-retry';\nimport { Transport, type LogRecord, type SerializedError } from '@aomex/logger';\nimport { i18n } from './i18n';\n\nexport const TELEGRAM_MESSAGE_MAX_LENGTH = 4096;\n\n/** 指纹中如何纳入 `bindings`:默认不纳入;`'all'` 为全部;数组为白名单键 */\nexport type TelegramDedupeBindingKeys = 'all' | readonly string[];\n\nexport interface TelegramDedupeOptions {\n /**\n * 合并间隔(毫秒)。默认 `30_000`。\n * 间隔内相同指纹只发一条,正文带 `(×N)`。\n */\n interval?: number;\n /**\n * 纳入指纹的 bindings。默认不纳入(只按 `level` / `message` / `exception`),\n * 避免业务侧关联字段拆散合并;需要时自行传 `'all'` 或键名白名单。\n */\n bindingKeys?: TelegramDedupeBindingKeys;\n /** 自定义指纹;默认走 `fingerprintLog` */\n fingerprint?: (log: LogRecord) => string;\n}\n\nexport interface TelegramTransportOptions {\n /** Bot token(来自 @BotFather) */\n botToken: string;\n /** 目标 chat / 群 / 频道 id */\n chatId: string | number;\n /**\n * 请求总超时(毫秒,含 auto-retry 等待)。默认 `120_000`。\n */\n timeout?: number;\n /** 自定义消息正文;默认 `formatTelegramMessage` */\n format?: (log: LogRecord) => string;\n /**\n * 间隔内相同指纹合并为一条后再发送。默认开启(间隔 30s,指纹不含 bindings)。\n * 传 `false` 则每条立即发送。\n */\n dedupe?: boolean | TelegramDedupeOptions;\n}\n\ntype TelegramDedupeConfig = {\n interval: number;\n bindingKeys?: TelegramDedupeBindingKeys;\n fingerprint?: (log: LogRecord) => string;\n};\n\ntype DedupeBufferEntry = {\n log: LogRecord;\n count: number;\n timer: ReturnType<typeof setTimeout>;\n};\n\n/**\n * 通过 [grammy](https://grammy.dev) `Api.sendMessage` 推送日志,\n * 固定启用 [`@grammyjs/auto-retry`](https://grammy.dev/plugins/auto-retry)。\n *\n * ```typescript\n * new TelegramTransport({\n * botToken: process.env.TELEGRAM_BOT_TOKEN!,\n * chatId: process.env.TELEGRAM_CHAT_ID!,\n * })\n * ```\n */\nexport class TelegramTransport extends Transport {\n protected readonly chatId: string | number;\n protected readonly timeout: number;\n protected readonly api: Api;\n protected readonly customFormat?: (log: LogRecord) => string;\n protected readonly dedupe: TelegramDedupeConfig | false;\n protected readonly pending = new Set<Promise<void>>();\n protected readonly buffer = new Map<string, DedupeBufferEntry>();\n\n constructor(opts: TelegramTransportOptions) {\n super();\n this.chatId = opts.chatId;\n this.timeout = opts.timeout ?? 120_000;\n this.customFormat = opts.format;\n this.dedupe = this.resolveDedupe(opts.dedupe);\n\n const api = new Api(opts.botToken);\n api.config.use(autoRetry({ maxRetryAttempts: 3, maxDelaySeconds: 60 }));\n this.api = api;\n }\n\n override async consume(log: LogRecord): Promise<void> {\n if (this.dedupe) {\n this.enqueue(log);\n return;\n }\n const task = this.sendText(this.formatMessage(log)).finally(() => {\n this.pending.delete(task);\n });\n this.pending.add(task);\n await task;\n }\n\n override async flush(): Promise<void> {\n await this.flushBuffer();\n await Promise.all([...this.pending]);\n }\n\n protected resolveDedupe(\n dedupe: boolean | TelegramDedupeOptions | undefined,\n ): TelegramDedupeConfig | false {\n if (dedupe === false) return false;\n const opts = dedupe === true || dedupe == null ? {} : dedupe;\n return {\n interval: opts.interval ?? 30_000,\n bindingKeys: opts.bindingKeys,\n fingerprint: opts.fingerprint,\n };\n }\n\n /** 组装待发送正文(自定义 `format` 优先) */\n protected formatMessage(log: LogRecord): string {\n return this.customFormat?.(log) ?? this.formatTelegramMessage(log);\n }\n\n /** 默认消息模板;子类可 override */\n protected formatTelegramMessage(log: LogRecord): string {\n let text = `[${log.level}] ${log.timestamp.toISOString()}\\n${log.message}`;\n if (log.bindings) {\n text += `\\n${JSON.stringify(log.bindings)}`;\n }\n if (log.exception?.stack) {\n text += `\\n\\n${log.exception.stack}`;\n } else if (log.exception) {\n text += `\\n\\n${log.exception.type}: ${log.exception.message}`;\n }\n if (text.length <= TELEGRAM_MESSAGE_MAX_LENGTH) return text;\n return `${text.slice(0, TELEGRAM_MESSAGE_MAX_LENGTH - 1)}…`;\n }\n\n protected formatBufferedMessage(log: LogRecord, count: number): string {\n let text = this.formatMessage(log);\n if (count > 1) {\n text += `\\n(×${count})`;\n }\n if (text.length <= TELEGRAM_MESSAGE_MAX_LENGTH) return text;\n return `${text.slice(0, TELEGRAM_MESSAGE_MAX_LENGTH - 1)}…`;\n }\n\n /** 解析最终指纹(自定义 `fingerprint` 优先) */\n protected fingerprint(log: LogRecord): string {\n const dedupe = this.dedupe;\n if (!dedupe) {\n return this.fingerprintLog(log);\n }\n return dedupe.fingerprint?.(log) ?? this.fingerprintLog(log, dedupe.bindingKeys);\n }\n\n /**\n * 默认指纹:`level` + `message` + `exception`;\n * 传入 `bindingKeys` 时再附加对应 bindings。\n */\n protected fingerprintLog(\n log: LogRecord,\n bindingKeys?: TelegramDedupeBindingKeys,\n ): string {\n const parts: unknown[] = [log.level, log.message];\n if (log.exception) {\n parts.push(this.fingerprintException(log.exception));\n }\n if (log.bindings) {\n const picked = this.pickBindingsForFingerprint(log.bindings, bindingKeys);\n if (picked) {\n parts.push(picked);\n }\n }\n return JSON.stringify(parts);\n }\n\n protected fingerprintException(exception: SerializedError): unknown {\n return {\n type: exception.type,\n message: exception.message,\n stack: exception.stack,\n ...(exception.cause ? { cause: this.fingerprintException(exception.cause) } : {}),\n };\n }\n\n protected pickBindingsForFingerprint(\n bindings: Record<string, unknown>,\n bindingKeys: TelegramDedupeBindingKeys | undefined,\n ): Record<string, unknown> | undefined {\n if (bindingKeys == null) return undefined;\n const filtered: Record<string, unknown> = {};\n if (bindingKeys === 'all') {\n for (const key of Object.keys(bindings).sort()) {\n filtered[key] = bindings[key];\n }\n } else {\n for (const key of [...bindingKeys].sort()) {\n if (Object.hasOwn(bindings, key)) {\n filtered[key] = bindings[key];\n }\n }\n }\n return Object.keys(filtered).length > 0 ? filtered : undefined;\n }\n\n protected enqueue(log: LogRecord): void {\n const dedupe = this.dedupe;\n if (!dedupe) return;\n\n const fp = this.fingerprint(log);\n const existing = this.buffer.get(fp);\n if (existing) {\n existing.count += 1;\n return;\n }\n\n const timer = setTimeout(() => {\n void this.flushFingerprint(fp).catch((err) => {\n const detail = Error.isError(err) ? (err.stack ?? err.message) : String(err);\n console.error(`[aomex/logger-telegram-transport] dedupe flush failed: ${detail}`);\n });\n }, dedupe.interval);\n timer.unref?.();\n this.buffer.set(fp, { log, count: 1, timer });\n }\n\n protected async flushBuffer(): Promise<void> {\n const fingerprints = [...this.buffer.keys()];\n await Promise.all(fingerprints.map((fp) => this.flushFingerprint(fp)));\n }\n\n protected async flushFingerprint(fp: string): Promise<void> {\n const entry = this.buffer.get(fp);\n if (!entry) return;\n clearTimeout(entry.timer);\n this.buffer.delete(fp);\n\n const task = this.sendText(\n this.formatBufferedMessage(entry.log, entry.count),\n ).finally(() => {\n this.pending.delete(task);\n });\n this.pending.add(task);\n await task;\n }\n\n protected async sendText(text: string): Promise<void> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeout);\n try {\n await this.api.sendMessage(\n this.chatId,\n text,\n { link_preview_options: { is_disabled: true } },\n // grammy 使用独立 AbortSignal 类型\n controller.signal as Parameters<Api['sendMessage']>[3],\n );\n } catch (err) {\n if (Error.isError(err) && err.name === 'AbortError') {\n throw new Error(i18n.t('send_message_timed_out'));\n }\n throw err;\n } finally {\n clearTimeout(timer);\n }\n }\n}\n"],"mappings":";;;;;AAEA,MAAa,KAAK,KAAK,OAAO,EAC5B,wBAAwB,kBAC1B,CAAC;;ACDD,MAAa,KAAK,KAAK,UAAU,EAAE,CAAC,CAAC,OAAO,EAC1C,wBAAwB,kCAC1B,CAAC;;ACDD,MAAa,OAAO,WAAW;CAC7B;CACA;CACA,OAAO,SAAS,OAAO,IAAI,IAAI,aAAa,KAAK,MAAM,YAAY,GAAG,CAAC,CAAC;AAC1E,CAAC;;ACHD,MAAa,8BAA8B;;;;;;;;;;;;AA6D3C,IAAa,oBAAb,cAAuC,UAAU;CAC/C;CACA;CACA;CACA;CACA;CACA,0BAA6B,IAAI,IAAmB;CACpD,yBAA4B,IAAI,IAA+B;CAE/D,YAAY,MAAgC;EAC1C,MAAM;EACN,KAAK,SAAS,KAAK;EACnB,KAAK,UAAU,KAAK,WAAW;EAC/B,KAAK,eAAe,KAAK;EACzB,KAAK,SAAS,KAAK,cAAc,KAAK,MAAM;EAE5C,MAAM,MAAM,IAAI,IAAI,KAAK,QAAQ;EACjC,IAAI,OAAO,IAAI,UAAU;GAAE,kBAAkB;GAAG,iBAAiB;EAAG,CAAC,CAAC;EACtE,KAAK,MAAM;CACb;CAEA,MAAe,QAAQ,KAA+B;EAC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i18n/locales/en-us.ts","../src/i18n/index.ts","../src/telegram-transport.ts"],"sourcesContent":["import { I18n } from '@aomex/common';\n\nexport const zh = I18n.define({\n send_message_timed_out: 'Telegram 发送消息超时',\n});\n","import { I18n } from '@aomex/common';\nimport { zh } from './zh-cn';\n\nexport const en = I18n.satisfies(zh).define({\n send_message_timed_out: 'Telegram message send timed out',\n});\n","import { createI18n } from '@aomex/common';\nimport { zh } from './locales/zh-cn';\nimport { en } from './locales/en-us';\n\nexport const i18n = createI18n({\n zh,\n en,\n load: (file) => import(new URL(`./locales/${file}.js`, import.meta.url).href),\n});\n","import { Api } from 'grammy';\nimport { autoRetry } from '@grammyjs/auto-retry';\nimport { Transport, type LogRecord, type SerializedError } from '@aomex/logger';\nimport { i18n } from './i18n';\n\nexport const TELEGRAM_MESSAGE_MAX_LENGTH = 4096;\n\n/** 指纹中如何纳入 `bindings`:默认不纳入;`'all'` 为全部;数组为白名单键 */\nexport type TelegramDedupeBindingKeys = 'all' | readonly string[];\n\nexport interface TelegramDedupeOptions {\n /**\n * 合并间隔(毫秒)。默认 `60_000`。\n * 间隔内相同指纹合并为一条:首条完整正文,第 2 条起在下方追加时间与 bindings。\n */\n interval?: number;\n /**\n * 纳入指纹的 bindings。默认不纳入(只按 `level` / `message` / `exception`),\n * 避免业务侧关联字段拆散合并;需要时自行传 `'all'` 或键名白名单。\n */\n bindingKeys?: TelegramDedupeBindingKeys;\n /**\n * 自定义合并指纹。不传时按 `level` + `message` + `exception` 生成;\n * 是否纳入 bindings 由 `bindingKeys` 决定。\n */\n fingerprint?: (log: LogRecord) => string;\n}\n\nexport interface TelegramTransportOptions {\n /** Bot token(来自 @BotFather) */\n botToken: string;\n /** 目标 chat / 群 / 频道 id */\n chatId: string | number;\n /**\n * 请求总超时(毫秒,含 auto-retry 等待)。默认 `120_000`。\n */\n timeout?: number;\n /**\n * 自定义消息正文。不传时为:`[level] 时间`、message、可选 bindings / exception。\n */\n format?: (log: LogRecord) => string;\n /**\n * 间隔内相同指纹合并为一条后再发送。默认关闭(每条立即发送)。\n * 传 `true` 时默认间隔 60s,指纹不含 bindings;也可传选项对象细调。\n */\n dedupe?: boolean | TelegramDedupeOptions;\n}\n\ntype TelegramDedupeConfig = {\n interval: number;\n bindingKeys?: TelegramDedupeBindingKeys;\n fingerprint?: (log: LogRecord) => string;\n};\n\ntype DedupeBufferEntry = {\n logs: LogRecord[];\n timer: ReturnType<typeof setTimeout>;\n};\n\n/**\n * 通过 [grammy](https://grammy.dev) `Api.sendMessage` 推送日志,\n * 固定启用 [`@grammyjs/auto-retry`](https://grammy.dev/plugins/auto-retry)。\n *\n * ```typescript\n * new TelegramTransport({\n * botToken: process.env.TELEGRAM_BOT_TOKEN!,\n * chatId: process.env.TELEGRAM_CHAT_ID!,\n * })\n * ```\n */\nexport class TelegramTransport extends Transport {\n protected readonly chatId: string | number;\n protected readonly timeout: number;\n protected readonly api: Api;\n protected readonly customFormat?: (log: LogRecord) => string;\n protected readonly dedupe: TelegramDedupeConfig | false;\n protected readonly pending = new Set<Promise<void>>();\n protected readonly buffer = new Map<string, DedupeBufferEntry>();\n\n constructor(opts: TelegramTransportOptions) {\n super();\n this.chatId = opts.chatId;\n this.timeout = opts.timeout ?? 120_000;\n this.customFormat = opts.format;\n this.dedupe = this.resolveDedupe(opts.dedupe);\n\n const api = new Api(opts.botToken);\n api.config.use(autoRetry({ maxRetryAttempts: 3, maxDelaySeconds: 60 }));\n this.api = api;\n }\n\n override async consume(log: LogRecord): Promise<void> {\n if (this.dedupe) {\n this.enqueue(log);\n return;\n }\n const task = this.sendText(this.formatMessage(log)).finally(() => {\n this.pending.delete(task);\n });\n this.pending.add(task);\n await task;\n }\n\n override async flush(): Promise<void> {\n await this.flushBuffer();\n await Promise.all([...this.pending]);\n }\n\n protected resolveDedupe(\n dedupe: boolean | TelegramDedupeOptions | undefined,\n ): TelegramDedupeConfig | false {\n if (dedupe == null || dedupe === false) return false;\n const opts = dedupe === true ? {} : dedupe;\n return {\n interval: opts.interval ?? 60_000,\n bindingKeys: opts.bindingKeys,\n fingerprint: opts.fingerprint,\n };\n }\n\n /** 组装待发送正文(自定义 `format` 优先) */\n protected formatMessage(log: LogRecord): string {\n return this.customFormat?.(log) ?? this.formatTelegramMessage(log);\n }\n\n /** 默认消息模板;子类可 override */\n protected formatTelegramMessage(log: LogRecord): string {\n let text = `[${log.level}] ${log.timestamp.toISOString()}\\n${log.message}`;\n if (log.bindings) {\n text += `\\n${JSON.stringify(log.bindings)}`;\n }\n if (log.exception?.stack) {\n text += `\\n\\n${log.exception.stack}`;\n } else if (log.exception) {\n text += `\\n\\n${log.exception.type}: ${log.exception.message}`;\n }\n if (text.length <= TELEGRAM_MESSAGE_MAX_LENGTH) return text;\n return `${text.slice(0, TELEGRAM_MESSAGE_MAX_LENGTH - 1)}…`;\n }\n\n /**\n * 合并窗口产出的正文:首条走 `formatMessage`;\n * 其后每条追加一行时间(ISO)与 bindings(若有)。\n */\n protected formatBufferedMessage(logs: LogRecord[]): string {\n const [first, ...rest] = logs;\n let text = this.formatMessage(first!);\n if (rest.length > 0) {\n // 与首条之间空两行\n text += `\\n\\n\\n${rest.map((log) => this.formatDedupeRepeat(log)).join('\\n')}`;\n }\n if (text.length <= TELEGRAM_MESSAGE_MAX_LENGTH) return text;\n return `${text.slice(0, TELEGRAM_MESSAGE_MAX_LENGTH - 1)}…`;\n }\n\n /** 合并窗口内第 2 条及之后:`时间` + 可选 `bindings` JSON */\n protected formatDedupeRepeat(log: LogRecord): string {\n let line = log.timestamp.toISOString();\n if (log.bindings) {\n line += ` ${JSON.stringify(log.bindings)}`;\n }\n return line;\n }\n\n /** 解析最终指纹(自定义 `fingerprint` 优先) */\n protected fingerprint(log: LogRecord): string {\n const dedupe = this.dedupe;\n if (!dedupe) {\n return this.fingerprintLog(log);\n }\n return dedupe.fingerprint?.(log) ?? this.fingerprintLog(log, dedupe.bindingKeys);\n }\n\n /**\n * 默认指纹:`level` + `message` + `exception`;\n * 传入 `bindingKeys` 时再附加对应 bindings。\n */\n protected fingerprintLog(\n log: LogRecord,\n bindingKeys?: TelegramDedupeBindingKeys,\n ): string {\n const parts: unknown[] = [log.level, log.message];\n if (log.exception) {\n parts.push(this.fingerprintException(log.exception));\n }\n if (log.bindings) {\n const picked = this.pickBindingsForFingerprint(log.bindings, bindingKeys);\n if (picked) {\n parts.push(picked);\n }\n }\n return JSON.stringify(parts);\n }\n\n protected fingerprintException(exception: SerializedError): unknown {\n return {\n type: exception.type,\n message: exception.message,\n stack: exception.stack,\n ...(exception.cause ? { cause: this.fingerprintException(exception.cause) } : {}),\n };\n }\n\n protected pickBindingsForFingerprint(\n bindings: Record<string, unknown>,\n bindingKeys: TelegramDedupeBindingKeys | undefined,\n ): Record<string, unknown> | undefined {\n if (bindingKeys == null) return undefined;\n const filtered: Record<string, unknown> = {};\n if (bindingKeys === 'all') {\n for (const key of Object.keys(bindings).sort()) {\n filtered[key] = bindings[key];\n }\n } else {\n for (const key of [...bindingKeys].sort()) {\n if (Object.hasOwn(bindings, key)) {\n filtered[key] = bindings[key];\n }\n }\n }\n return Object.keys(filtered).length > 0 ? filtered : undefined;\n }\n\n protected enqueue(log: LogRecord): void {\n const dedupe = this.dedupe;\n if (!dedupe) return;\n\n const fp = this.fingerprint(log);\n const existing = this.buffer.get(fp);\n if (existing) {\n existing.logs.push(log);\n return;\n }\n\n const timer = setTimeout(() => {\n void this.flushFingerprint(fp).catch((err) => {\n const detail = Error.isError(err) ? (err.stack ?? err.message) : String(err);\n console.error(`[aomex/logger-telegram-transport] dedupe flush failed: ${detail}`);\n });\n }, dedupe.interval);\n timer.unref?.();\n this.buffer.set(fp, { logs: [log], timer });\n }\n\n protected async flushBuffer(): Promise<void> {\n const fingerprints = [...this.buffer.keys()];\n await Promise.all(fingerprints.map((fp) => this.flushFingerprint(fp)));\n }\n\n protected async flushFingerprint(fp: string): Promise<void> {\n const entry = this.buffer.get(fp);\n if (!entry) return;\n clearTimeout(entry.timer);\n this.buffer.delete(fp);\n\n const task = this.sendText(this.formatBufferedMessage(entry.logs)).finally(() => {\n this.pending.delete(task);\n });\n this.pending.add(task);\n await task;\n }\n\n protected async sendText(text: string): Promise<void> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeout);\n try {\n await this.api.sendMessage(\n this.chatId,\n text,\n { link_preview_options: { is_disabled: true } },\n // grammy 使用独立 AbortSignal 类型\n controller.signal as Parameters<Api['sendMessage']>[3],\n );\n } catch (err) {\n if (Error.isError(err) && err.name === 'AbortError') {\n throw new Error(i18n.t('send_message_timed_out'));\n }\n throw err;\n } finally {\n clearTimeout(timer);\n }\n }\n}\n"],"mappings":";;;;;AAEA,MAAa,KAAK,KAAK,OAAO,EAC5B,wBAAwB,kBAC1B,CAAC;;ACDD,MAAa,KAAK,KAAK,UAAU,EAAE,CAAC,CAAC,OAAO,EAC1C,wBAAwB,kCAC1B,CAAC;;ACDD,MAAa,OAAO,WAAW;CAC7B;CACA;CACA,OAAO,SAAS,OAAO,IAAI,IAAI,aAAa,KAAK,MAAM,YAAY,GAAG,CAAC,CAAC;AAC1E,CAAC;;ACHD,MAAa,8BAA8B;;;;;;;;;;;;AAiE3C,IAAa,oBAAb,cAAuC,UAAU;CAC/C;CACA;CACA;CACA;CACA;CACA,0BAA6B,IAAI,IAAmB;CACpD,yBAA4B,IAAI,IAA+B;CAE/D,YAAY,MAAgC;EAC1C,MAAM;EACN,KAAK,SAAS,KAAK;EACnB,KAAK,UAAU,KAAK,WAAW;EAC/B,KAAK,eAAe,KAAK;EACzB,KAAK,SAAS,KAAK,cAAc,KAAK,MAAM;EAE5C,MAAM,MAAM,IAAI,IAAI,KAAK,QAAQ;EACjC,IAAI,OAAO,IAAI,UAAU;GAAE,kBAAkB;GAAG,iBAAiB;EAAG,CAAC,CAAC;EACtE,KAAK,MAAM;CACb;CAEA,MAAe,QAAQ,KAA+B;EACpD,IAAI,KAAK,QAAQ;GACf,KAAK,QAAQ,GAAG;GAChB;EACF;EACA,MAAM,OAAO,KAA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,SAAS,cACrC,MAAM,IAAI,MAAM,KAAK,EAAE,wBAAwB,CAAC;GAElD,MAAM;EACR,UAAU;GACR,aAAa,KAAK;EACpB;CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aomex/logger-telegram-transport",
3
- "version": "4.15.0",
3
+ "version": "4.16.1",
4
4
  "description": "aomex logger Telegram Bot transport (grammy)",
5
5
  "repository": {
6
6
  "type": "git",
@@ -36,8 +36,8 @@
36
36
  "grammy": "^1.48.0"
37
37
  },
38
38
  "devDependencies": {
39
- "@aomex/common": "4.15.0",
40
- "@aomex/logger": "4.15.0"
39
+ "@aomex/common": "4.16.1",
40
+ "@aomex/logger": "4.16.1"
41
41
  },
42
42
  "scripts": {}
43
43
  }