@theokit/gateway 0.14.0 → 0.16.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.
package/dist/index.js CHANGED
@@ -1,5 +1,218 @@
1
1
  import { Security } from '@theokit/sdk';
2
2
 
3
+ // src/text/fence.ts
4
+ var MAY_FENCE = /^ {0,3}(?:`{3}|~{3})/m;
5
+ var OPENING = /^ {0,3}(`{3,}|~{3,})(.*)$/;
6
+ var CLOSING = /^ {0,3}(`{3,}|~{3,})[ \t]*$/;
7
+ function lineEndAt(text, from) {
8
+ let end = from;
9
+ while (end < text.length && text[end] !== "\n" && text[end] !== "\r") end += 1;
10
+ let next = end;
11
+ if (text[next] === "\r" && text[next + 1] === "\n") next += 2;
12
+ else if (next < text.length) next += 1;
13
+ return { end, next };
14
+ }
15
+ function findClose(text, from, run) {
16
+ for (let scan = from; scan < text.length; ) {
17
+ const line = lineEndAt(text, scan);
18
+ const found = CLOSING.exec(text.slice(scan, line.end))?.[1];
19
+ if (found !== void 0 && found[0] === run[0] && found.length >= run.length) return line;
20
+ scan = line.next;
21
+ }
22
+ return void 0;
23
+ }
24
+ function scanFences(text) {
25
+ if (!MAY_FENCE.test(text)) return [];
26
+ const regions = [];
27
+ let pos = 0;
28
+ while (pos < text.length) {
29
+ const start = pos;
30
+ const line = lineEndAt(text, start);
31
+ const open = OPENING.exec(text.slice(start, line.end));
32
+ const run = open?.[1];
33
+ if (run === void 0 || run.startsWith("`") && (open?.[2] ?? "").includes("`")) {
34
+ pos = line.next;
35
+ continue;
36
+ }
37
+ const close = findClose(text, line.next, run);
38
+ pos = close?.next ?? text.length;
39
+ const end = close?.end ?? text.length;
40
+ const closed = close !== void 0;
41
+ regions.push({
42
+ start,
43
+ openerEnd: line.end,
44
+ contentStart: line.next,
45
+ end,
46
+ opener: text.slice(start, line.end),
47
+ closer: run,
48
+ closed
49
+ });
50
+ }
51
+ return regions;
52
+ }
53
+ function fenceAt(regions, offset) {
54
+ return regions.find((r) => r.start < offset && offset < r.end);
55
+ }
56
+ function openerEol(text, region) {
57
+ if (text.startsWith("\r\n", region.openerEnd)) return "\r\n";
58
+ return text[region.openerEnd] === "\r" ? "\r" : "\n";
59
+ }
60
+
61
+ // src/text/dialect.ts
62
+ var DIALECTS = {
63
+ // WhatsApp emphasis is inline and single-character: *bold*, _italic_, ~strike~, ```mono```.
64
+ whatsapp: { bold: "*", italic: "_", strike: "~", code: "```" },
65
+ // LINE text messages carry no rich text at all — decoration is emoji-only. Markers are dropped.
66
+ line: {},
67
+ // SMS is plain text by definition of the medium.
68
+ sms: {}
69
+ };
70
+ var PATTERN = /\*\*(?<bold>.+?)\*\*|~~(?<strike>.+?)~~|(?<![*\w])\*(?!\s)(?<italicStar>.+?)(?<!\s)\*(?!\*)|(?<![_\w])_(?!\s)(?<italicUnderscore>.+?)(?<!\s)_(?!\w)|`(?<code>.+?)`/gu;
71
+ var GROUP_MARKERS = [
72
+ ["bold", "bold"],
73
+ ["strike", "strike"],
74
+ ["italicStar", "italic"],
75
+ ["italicUnderscore", "italic"],
76
+ ["code", "code"]
77
+ ];
78
+ function toDialect(text, platform) {
79
+ const dialect = DIALECTS[platform];
80
+ if (dialect === void 0) return text;
81
+ return rewriteMarkers(text, dialect);
82
+ }
83
+ function markerFor(matched, groups, dialect) {
84
+ if (groups === void 0) return matched;
85
+ for (const [group, marker] of GROUP_MARKERS) {
86
+ const content = groups[group];
87
+ if (content === void 0) continue;
88
+ const wrap = dialect[marker];
89
+ return wrap === void 0 ? content : `${wrap}${content}${wrap}`;
90
+ }
91
+ return matched;
92
+ }
93
+ function rewriteMatch(matched, args, dialect) {
94
+ return markerFor(matched, args.at(-1), dialect);
95
+ }
96
+ function replaceMarkers(text, dialect) {
97
+ return text.replace(PATTERN, (matched, ...args) => rewriteMatch(matched, args, dialect));
98
+ }
99
+ var ROW_START = /[^\S\r\n]*\|/y;
100
+ var LINE_ENDING = /(\r\n|\r|\n)/;
101
+ var MARKER_CHARACTER = /[*_~\x60]/;
102
+ var PIPE = 124;
103
+ var BACKSLASH = 92;
104
+ var LF = 10;
105
+ var CR = 13;
106
+ function rowLocator(text) {
107
+ const rowStart = new RegExp(ROW_START);
108
+ let lineStart = 0;
109
+ let scanned = 0;
110
+ return (offset) => {
111
+ for (; scanned < offset; scanned += 1) {
112
+ const code = text.charCodeAt(scanned);
113
+ if (code === LF || code === CR) lineStart = scanned + 1;
114
+ }
115
+ rowStart.lastIndex = lineStart;
116
+ return rowStart.test(text);
117
+ };
118
+ }
119
+ function rewriteTableRow(row, dialect) {
120
+ let out = "";
121
+ let from = 0;
122
+ let backslashes = 0;
123
+ for (let i = 0; i < row.length; i += 1) {
124
+ const code = row.charCodeAt(i);
125
+ if (code === BACKSLASH) {
126
+ backslashes += 1;
127
+ continue;
128
+ }
129
+ if (code === PIPE && backslashes % 2 === 0) {
130
+ out += `${replaceMarkers(row.slice(from, i), dialect)}|`;
131
+ from = i + 1;
132
+ }
133
+ backslashes = 0;
134
+ }
135
+ return out + replaceMarkers(row.slice(from), dialect);
136
+ }
137
+ function rewriteLine(line, dialect, rowStart) {
138
+ rowStart.lastIndex = 0;
139
+ if (!rowStart.test(line)) return replaceMarkers(line, dialect);
140
+ return MARKER_CHARACTER.test(line) ? rewriteTableRow(line, dialect) : line;
141
+ }
142
+ function rewriteByLine(text, dialect) {
143
+ const rowStart = new RegExp(ROW_START);
144
+ return text.split(LINE_ENDING).map((piece) => rewriteLine(piece, dialect, rowStart)).join("");
145
+ }
146
+ function rewriteMarkers(text, dialect) {
147
+ const regions = scanFences(text);
148
+ if (regions.length === 0) return rewriteUnfenced(text, dialect);
149
+ let out = "";
150
+ let from = 0;
151
+ for (const region of regions) {
152
+ out += rewriteUnfenced(text.slice(from, region.start), dialect) + text.slice(region.start, region.end);
153
+ from = region.end;
154
+ }
155
+ return out + rewriteUnfenced(text.slice(from), dialect);
156
+ }
157
+ function rewriteUnfenced(text, dialect) {
158
+ const onTableRow = rowLocator(text);
159
+ let crossesRowPipe = false;
160
+ const rewritten = text.replace(PATTERN, (matched, ...args) => {
161
+ if (!crossesRowPipe && matched.includes("|")) {
162
+ crossesRowPipe = onTableRow(args.at(-3));
163
+ }
164
+ return rewriteMatch(matched, args, dialect);
165
+ });
166
+ return crossesRowPipe ? rewriteByLine(text, dialect) : rewritten;
167
+ }
168
+
169
+ // src/text/channel-rendering.ts
170
+ var SLACK = { bold: "*", italic: "_", strike: "~", code: "`" };
171
+ var STRIP = {};
172
+ var identity = (text) => text;
173
+ var translateWith = (dialect) => (text) => rewriteMarkers(text, dialect);
174
+ var RENDERINGS = {
175
+ whatsapp: { format: "plain", translate: translateWith(DIALECTS.whatsapp) },
176
+ slack: { format: "markdown", translate: translateWith(SLACK) },
177
+ discord: { format: "markdown", translate: identity },
178
+ mattermost: { format: "markdown", translate: identity },
179
+ teams: { format: "markdown", translate: identity },
180
+ signal: { format: "markdown", translate: identity },
181
+ line: { format: "plain", translate: translateWith(DIALECTS.line) },
182
+ sms: { format: "plain", translate: translateWith(DIALECTS.sms) },
183
+ telegram: { format: "plain", translate: translateWith(STRIP) },
184
+ matrix: { format: "plain", translate: translateWith(STRIP) },
185
+ email: { format: "plain", translate: translateWith(STRIP) },
186
+ imessage: { format: "plain", translate: translateWith(STRIP) },
187
+ google_chat: { format: "plain", translate: translateWith(STRIP) },
188
+ irc: { format: "plain", translate: translateWith(STRIP) },
189
+ nextcloud_talk: { format: "markdown", translate: identity },
190
+ nostr: { format: "plain", translate: translateWith(STRIP) },
191
+ feishu_lark: { format: "plain", translate: translateWith(STRIP) },
192
+ synology_chat: { format: "plain", translate: translateWith(STRIP) },
193
+ tlon_urbit: { format: "plain", translate: translateWith(STRIP) },
194
+ twitch: { format: "plain", translate: translateWith(STRIP) },
195
+ buzz: { format: "plain", translate: translateWith(STRIP) },
196
+ clickclack: { format: "plain", translate: translateWith(STRIP) },
197
+ zalo_personal: { format: "plain", translate: translateWith(STRIP) },
198
+ zalo: { format: "plain", translate: translateWith(STRIP) },
199
+ wechat: { format: "plain", translate: translateWith(STRIP) },
200
+ wecom: { format: "plain", translate: translateWith(STRIP) },
201
+ yuanbao: { format: "plain", translate: translateWith(STRIP) },
202
+ qq: { format: "plain", translate: translateWith(STRIP) },
203
+ x: { format: "plain", translate: translateWith(STRIP) },
204
+ raft: { format: "plain", translate: translateWith(STRIP) }
205
+ };
206
+ function channelRendering(platform) {
207
+ const rendering = Object.hasOwn(RENDERINGS, platform) ? RENDERINGS[platform] : void 0;
208
+ if (rendering === void 0) {
209
+ throw new RangeError(
210
+ `channelRendering: unknown platform "${String(platform)}"; expected one of ${Object.keys(RENDERINGS).join(", ")}`
211
+ );
212
+ }
213
+ return rendering;
214
+ }
215
+
3
216
  // src/adapter/base.ts
4
217
  var BasePlatformAdapter = class {
5
218
  /**
@@ -26,6 +239,56 @@ var BasePlatformAdapter = class {
26
239
  }
27
240
  return "ok";
28
241
  }
242
+ /** The handler {@link subscribe} holds; `undefined` while nobody is subscribed. */
243
+ subscribedHandler;
244
+ /** The body of {@link onInbound}: replace the handler, and unsubscribe only if it is still the one held. */
245
+ subscribe(handler) {
246
+ this.subscribedHandler = handler;
247
+ return () => {
248
+ if (this.subscribedHandler === handler) this.subscribedHandler = void 0;
249
+ };
250
+ }
251
+ /** The body of {@link deliver} for an adapter that subscribed through {@link subscribe}. */
252
+ deliverInbound(event) {
253
+ return this.runHandler(this.subscribedHandler, event);
254
+ }
255
+ /**
256
+ * Dispatch a webhook event once: `duplicate` when `seen` holds its id, `no_handler` when nobody
257
+ * subscribed (the id is then NOT remembered, so a redelivery is handled), otherwise remember the
258
+ * id and run the handler. A handler's throw is also logged under `label`.
259
+ */
260
+ async dispatchOnce(seen, event, label) {
261
+ if (seen.has(event.id)) return "duplicate";
262
+ if (this.subscribedHandler === void 0) return "no_handler";
263
+ seen.add(event.id);
264
+ const outcome = await this.runHandler(this.subscribedHandler, event);
265
+ if (outcome === "handler_threw") process.stderr.write(`[${label}] handler threw
266
+ `);
267
+ return outcome;
268
+ }
269
+ /** `out.text`, translated to the platform's markup when `out.format` is `markdown`. */
270
+ outboundText(out) {
271
+ return out.format === "markdown" ? channelRendering(this.platform).translate(out.text) : out.text;
272
+ }
273
+ /**
274
+ * The local checks every text-only `sendMessage` makes before a request, in this order:
275
+ * `empty_text`, `not_connected`, then `invalid_channel` when `channel.valid` rejects the id.
276
+ * Returns the refusal, or `undefined` when the message may be sent.
277
+ */
278
+ refuseUnsendable(out, check) {
279
+ const refuse = (code, message) => ({
280
+ ok: false,
281
+ error: { code, message }
282
+ });
283
+ if (out.text.length === 0) return refuse("empty_text", "outbound text is empty");
284
+ if (!check.connected) {
285
+ return refuse("not_connected", `${check.className}.connect() has not succeeded`);
286
+ }
287
+ if (check.channel !== void 0 && !check.channel.valid(out.channel.id)) {
288
+ return refuse("invalid_channel", check.channel.message);
289
+ }
290
+ return void 0;
291
+ }
29
292
  /**
30
293
  * Whether {@link editMessage} can replace the text of a message this adapter sent.
31
294
  *
@@ -63,6 +326,25 @@ var BasePlatformAdapter = class {
63
326
  }
64
327
  };
65
328
  }
329
+ /**
330
+ * React to an inbound message with an emoji (for example 👀 as an acknowledgement).
331
+ *
332
+ * Returns `{ ok: true, messageId }` on success and a `SendResult` error otherwise; it never
333
+ * throws on platform errors. `channelId` is the channel the message is in and `messageId` the
334
+ * id the inbound event carried.
335
+ *
336
+ * Default: resolves `{ ok: false, error: { code: "react_unsupported" } }` and makes no
337
+ * platform call.
338
+ */
339
+ async react(_channelId, _messageId, _emoji) {
340
+ return {
341
+ ok: false,
342
+ error: {
343
+ code: "react_unsupported",
344
+ message: `${this.platform} adapter cannot react to a message`
345
+ }
346
+ };
347
+ }
66
348
  /** Lifecycle: emit a typing indicator. Default: noop. */
67
349
  async startTyping(_channelId) {
68
350
  }
@@ -71,6 +353,184 @@ var BasePlatformAdapter = class {
71
353
  }
72
354
  };
73
355
 
356
+ // src/text/seen-ids.ts
357
+ var DEFAULT_LIMIT = 1e3;
358
+ var SeenIds = class {
359
+ /** @param limit the most ids held at once; the oldest is forgotten when one more arrives */
360
+ constructor(limit = DEFAULT_LIMIT) {
361
+ this.limit = limit;
362
+ }
363
+ limit;
364
+ ids = /* @__PURE__ */ new Set();
365
+ /**
366
+ * Record `id`.
367
+ *
368
+ * @returns `true` when the id was new, `false` when it was already held
369
+ */
370
+ add(id) {
371
+ if (this.ids.has(id)) return false;
372
+ this.ids.add(id);
373
+ if (this.ids.size > this.limit) {
374
+ const oldest = this.ids.values().next().value;
375
+ if (oldest !== void 0) this.ids.delete(oldest);
376
+ }
377
+ return true;
378
+ }
379
+ /** Whether `id` is held. */
380
+ has(id) {
381
+ return this.ids.has(id);
382
+ }
383
+ /** How many ids are held. */
384
+ get size() {
385
+ return this.ids.size;
386
+ }
387
+ };
388
+
389
+ // src/adapter/weixin-xml.ts
390
+ function parseFlatXml(xml) {
391
+ const out = {};
392
+ const tag = /<([A-Za-z][A-Za-z0-9]*)>(?:<!\[CDATA\[([\s\S]*?)\]\]>|([^<]*))<\/\1>/g;
393
+ for (const m of xml.matchAll(tag)) {
394
+ const name = m[1];
395
+ if (name !== void 0 && name !== "xml") out[name] = m[2] ?? decodeEntities(m[3] ?? "");
396
+ }
397
+ return out;
398
+ }
399
+ function decodeEntities(s) {
400
+ return s.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/g, "&");
401
+ }
402
+
403
+ // src/adapter/weixin-base.ts
404
+ var REQUEST_TIMEOUT_MS = 3e4;
405
+ var TOKEN_MARGIN_MS = 6e4;
406
+ var defaultFetch = async (url, init) => {
407
+ const res = await fetch(url, { ...init, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
408
+ return { status: res.status, text: () => res.text() };
409
+ };
410
+ function weixinMessageOf(err) {
411
+ return err instanceof Error ? err.message : String(err);
412
+ }
413
+ function weixinAck(reason) {
414
+ return { status: 200, body: "success", reason };
415
+ }
416
+ var WeixinAdapterBase = class extends BasePlatformAdapter {
417
+ cfg;
418
+ doFetch;
419
+ connected = false;
420
+ accessToken;
421
+ seen = new SeenIds();
422
+ constructor(cfg) {
423
+ super();
424
+ this.cfg = cfg;
425
+ this.doFetch = cfg.fetch ?? defaultFetch;
426
+ }
427
+ async connect() {
428
+ if (this.connected) return true;
429
+ try {
430
+ await this.token(true);
431
+ this.connected = true;
432
+ return true;
433
+ } catch (err) {
434
+ process.stderr.write(`[${this.cfg.label}] connect failed: ${weixinMessageOf(err)}
435
+ `);
436
+ return false;
437
+ }
438
+ }
439
+ async disconnect() {
440
+ this.connected = false;
441
+ this.accessToken = void 0;
442
+ }
443
+ /** Send text only; a subclass's `sendMessage` refuses attachments first, then calls this. */
444
+ async sendText(out) {
445
+ if (out.text.length === 0) {
446
+ return { ok: false, error: { code: "empty_text", message: "outbound text is empty" } };
447
+ }
448
+ if (!this.connected) {
449
+ return {
450
+ ok: false,
451
+ error: {
452
+ code: "not_connected",
453
+ message: `${this.cfg.className}.connect() has not succeeded`
454
+ }
455
+ };
456
+ }
457
+ if (out.channel.id === "") {
458
+ return {
459
+ ok: false,
460
+ error: { code: "invalid_channel", message: `channel.id must be ${this.cfg.userNoun}` }
461
+ };
462
+ }
463
+ return this.sendParts(out);
464
+ }
465
+ async sendParts(out) {
466
+ const failed = `${this.platform}_send_failed`;
467
+ try {
468
+ for (const content of this.split(this.outboundText(out))) {
469
+ const token = await this.token(false);
470
+ const req = this.sendRequest(token, out.channel.id, content);
471
+ const body = await this.call("POST", req.path, req.payload);
472
+ if (body.errcode !== 0) {
473
+ return {
474
+ ok: false,
475
+ error: {
476
+ code: failed,
477
+ message: `${this.cfg.brand} error ${String(body.errcode)}: ${String(body.errmsg)}`
478
+ }
479
+ };
480
+ }
481
+ }
482
+ } catch (err) {
483
+ return { ok: false, error: { code: failed, message: weixinMessageOf(err) } };
484
+ }
485
+ return { ok: true, messageId: "" };
486
+ }
487
+ onInbound(handler) {
488
+ return this.subscribe(handler);
489
+ }
490
+ /** Deliver an event that arrived out of band, through `runHandler`. */
491
+ async deliver(event) {
492
+ return this.deliverInbound(event);
493
+ }
494
+ /** Turn a plain (decrypted) XML body into one event, dispatch it and answer the webhook. */
495
+ async handleMessage(xml) {
496
+ const event = this.toEvent(parseFlatXml(xml));
497
+ if (event === "skip") return weixinAck("not a text message");
498
+ if (event === void 0) return { status: 400, body: "", reason: "incomplete" };
499
+ const outcome = await this.dispatchOnce(this.seen, event, this.cfg.label);
500
+ if (outcome === "no_handler") return { status: 503, body: "", reason: "no handler subscribed" };
501
+ return weixinAck(outcome);
502
+ }
503
+ async token(force) {
504
+ const cached = this.accessToken;
505
+ if (!force && cached !== void 0 && cached.expiresAt - TOKEN_MARGIN_MS > Date.now()) {
506
+ return cached.value;
507
+ }
508
+ const body = await this.call("GET", this.tokenPath());
509
+ if (body.errcode !== void 0 && body.errcode !== 0) {
510
+ throw new Error(`token answered error ${String(body.errcode)}: ${String(body.errmsg)}`);
511
+ }
512
+ if (!body.access_token) throw new Error("token answer has no access_token");
513
+ this.accessToken = {
514
+ value: body.access_token,
515
+ expiresAt: Date.now() + (body.expires_in ?? 7200) * 1e3
516
+ };
517
+ return body.access_token;
518
+ }
519
+ async call(method, path, payload) {
520
+ const res = await this.doFetch((this.cfg.apiBase ?? this.cfg.defaultBase) + path, {
521
+ method,
522
+ headers: { "Content-Type": "application/json" },
523
+ ...payload === void 0 ? {} : { body: JSON.stringify(payload) }
524
+ });
525
+ const text = await res.text();
526
+ try {
527
+ return JSON.parse(text);
528
+ } catch {
529
+ throw new Error(`${this.cfg.brand} answered HTTP ${res.status} with a non-JSON body`);
530
+ }
531
+ }
532
+ };
533
+
74
534
  // src/errors/config-error.ts
75
535
  var GatewayConfigurationError = class extends Error {
76
536
  name = "GatewayConfigurationError";
@@ -210,6 +670,35 @@ var GatewayLifecycleError = class extends Error {
210
670
  this.code = opts.code;
211
671
  }
212
672
  };
673
+ var UNCOVERED_TABLE = `gateway-qq \`appSecret\` :: a QQ Bot AppSecret, an opaque 32-character string with no prefix or fixed shape. It travels only to the access-token endpoint and into the webhook signature derivation; the adapter never logs it.
674
+ gateway-x \`clientSecret\`, \`refreshToken\`, \`bearerToken\` :: an X OAuth 2.0 client secret, a rotating refresh token and an app bearer token, opaque strings with no fixed prefix. They travel only to the X API in Authorization headers and the token request body, which the adapter never logs.
675
+ gateway-buzz \`token\` :: a Buzz bot token with no fixed shape this package could confirm. It travels only in Authorization headers, which the adapter never logs.
676
+ gateway-clickclack \`token\` :: a ClickClack bot token (\`ccb_\` prefix) or session token with no fixed shape for the latter. It travels only in Authorization headers, which the adapter never logs.
677
+ gateway-zalo \`accessToken\`, \`oaSecretKey\` :: a Zalo Official Account access token and OA secret key: opaque strings with no prefix or fixed shape to recognise. The token travels only in an \`access_token\` header and the key only into the signature check, and the adapter never logs either.
678
+ gateway-wechat \`appSecret\`, \`token\` :: a WeChat Official Account AppSecret (32 hex characters, indistinguishable from any other hex string) and the server-URL verification token (a string the operator chooses). The secret travels only to the access-token endpoint and the token only into the signature check; the adapter never logs either.
679
+ gateway-wecom \`corpSecret\`, \`token\`, \`encodingAesKey\` :: a WeCom application Secret (43 URL-safe base64 characters, indistinguishable from other opaque strings), the callback Token (a string the operator chooses) and the EncodingAESKey (43 base64 characters). The secret travels only to the access-token endpoint, the token into the signature check and the key into the decryption; the adapter never logs any of them.
680
+ gateway-yuanbao \`appSecret\`, \`callbackSecret\` :: a Yuanbao bot AppSecret and the callback signing secret, both opaque strings with no prefix or fixed shape. The app secret travels only to the access-token endpoint and the callback secret only into the signature check; the adapter never logs either.
681
+ gateway-zalo-personal \`credentials\` :: a Zalo web session: a cookie jar, an IMEI-like device id and a user agent. The cookie has no prefix or fixed shape to recognise. It travels only to the Zalo library, which the adapter never logs.
682
+ gateway-twitch \`accessToken\` :: 30 lowercase alphanumerics with no prefix, the shape of many ids and hashes in a log. It travels only in Authorization headers, which the adapter never logs.
683
+ gateway-tlon-urbit \`code\` :: a +code is four dash-joined phonemic syllable words, the same shape as an Urbit ship name such as ~sampel-palnet-sampel-palnet, which the logs exist to show. It travels only in the /~/login body, which the adapter never logs.
684
+ gateway-synology-chat \`botToken\` and \`incomingUrl\` :: a bot token is a random string the NAS generates with no prefix, and the Incoming URL carries its own token as a query parameter of an ordinary entry.cgi URL. Neither has a shape to claim without eating ordinary ids and URLs; the adapter never logs the URL, and refuses a callback token before reading it.
685
+ gateway-feishu-lark \`appSecret\` :: 32 alphanumerics with no prefix, the shape of many tokens and hashes; it travels only in the body of the tenant-token request, which the adapter never logs.
686
+ gateway-nostr \`secretKey\` (64-hex form) :: 64 hex characters is also every Nostr public key and event id, which the logs exist to show, and a sha256 digest. The nsec1 spelling of the same key is masked above.
687
+ gateway-sms \`authToken\` (Twilio), gateway-line \`channelSecret\` :: 32 lowercase hex characters, which is also an md5 digest, a dashless UUID and half a git tree hash. Masking it would eat the correlation id a developer reads the log to find.
688
+ gateway-mattermost \`accessToken\` :: 26 lowercase alphanumerics, which is exactly a lowercase ULID \u2014 the shape of most trace ids.
689
+ gateway-email \`password\`, gateway-sms \`apiSecret\` and \`signatureSecret\` (Vonage) :: no format of their own; a passphrase is indistinguishable from prose. The SDK's own \`key=value\` rule already masks these fully wherever they appear as \`field=value\`, and adding a pattern here made that WORSE by claiming the value first \u2014 it was masked as first6\u2026last4 instead of removed.
690
+ gateway-slack \`botToken\` :: already masked by one of the SDK's own twelve built-in patterns \u2014 \`xoxb-\` is Slack's and the SDK knows it. A pattern here would be a second one doing the first's work, and the field-level gate flagged its absence, which is the gate working.
691
+ gateway-whatsapp \`appSecret\` :: 32 lowercase hex, the same shape as the Twilio auth token above and as every md5 and dashless UUID. Masking it would eat the correlation ids in a log.
692
+ gateway-nextcloud-talk \`secret\` :: a Talk bot secret is a string of 40 to 128 characters the administrator chose for \`occ talk:bot:install\`, with no prefix or format to recognise. It never travels: both sides send only an HMAC made with it, and the adapter never logs it.
693
+ gateway-irc \`password\` and \`saslPassword\` :: a server password and a NickServ password are passphrases the operator chose, with no format to recognise. The SDK's \`key=value\` rule masks them as fields wherever they appear as \`password=...\`; the SASL payload on the wire is their base64, which the adapter never logs.
694
+ gateway-google-chat \`privateKey\` :: a PEM block spans lines, and in a log it usually arrives inside a JSON string with its line breaks escaped as \\n, which no single-line shape can claim whole. The SDK's \`key=value\` rule masks it as a field wherever it appears as \`private_key=...\` or \`privateKey=...\`.
695
+ gateway-line \`channelAccessToken\`, gateway-sms \`authToken\` (Plivo) :: long base64 runs with no prefix, indistinguishable from any encoded blob a platform library puts in an error message.`;
696
+ function parseUncovered(table) {
697
+ return table.split("\n").map((row) => {
698
+ const [field = "", why = ""] = row.split(" :: ");
699
+ return { field, why };
700
+ });
701
+ }
213
702
  var CREDENTIAL_SHAPES = {
214
703
  covered: [
215
704
  {
@@ -248,76 +737,7 @@ var CREDENTIAL_SHAPES = {
248
737
  alsoMatches: "nothing plausible \u2014 `nsec1` is NIP-19's prefix for a secret key"
249
738
  }
250
739
  ],
251
- uncovered: [
252
- {
253
- field: "gateway-buzz `token`",
254
- why: "a Buzz bot token with no fixed shape this package could confirm. It travels only in Authorization headers, which the adapter never logs."
255
- },
256
- {
257
- field: "gateway-clickclack `token`",
258
- why: "a ClickClack bot token (`ccb_` prefix) or session token with no fixed shape for the latter. It travels only in Authorization headers, which the adapter never logs."
259
- },
260
- {
261
- field: "gateway-zalo-personal `credentials`",
262
- why: "a Zalo web session: a cookie jar, an IMEI-like device id and a user agent. The cookie has no prefix or fixed shape to recognise. It travels only to the Zalo library, which the adapter never logs."
263
- },
264
- {
265
- field: "gateway-twitch `accessToken`",
266
- why: "30 lowercase alphanumerics with no prefix, the shape of many ids and hashes in a log. It travels only in Authorization headers, which the adapter never logs."
267
- },
268
- {
269
- field: "gateway-tlon-urbit `code`",
270
- why: "a +code is four dash-joined phonemic syllable words, the same shape as an Urbit ship name such as ~sampel-palnet-sampel-palnet, which the logs exist to show. It travels only in the /~/login body, which the adapter never logs."
271
- },
272
- {
273
- field: "gateway-synology-chat `botToken` and `incomingUrl`",
274
- why: "a bot token is a random string the NAS generates with no prefix, and the Incoming URL carries its own token as a query parameter of an ordinary entry.cgi URL. Neither has a shape to claim without eating ordinary ids and URLs; the adapter never logs the URL, and refuses a callback token before reading it."
275
- },
276
- {
277
- field: "gateway-feishu-lark `appSecret`",
278
- why: "32 alphanumerics with no prefix, the shape of many tokens and hashes; it travels only in the body of the tenant-token request, which the adapter never logs."
279
- },
280
- {
281
- field: "gateway-nostr `secretKey` (64-hex form)",
282
- why: "64 hex characters is also every Nostr public key and event id, which the logs exist to show, and a sha256 digest. The nsec1 spelling of the same key is masked above."
283
- },
284
- {
285
- field: "gateway-sms `authToken` (Twilio), gateway-line `channelSecret`",
286
- why: "32 lowercase hex characters, which is also an md5 digest, a dashless UUID and half a git tree hash. Masking it would eat the correlation id a developer reads the log to find."
287
- },
288
- {
289
- field: "gateway-mattermost `accessToken`",
290
- why: "26 lowercase alphanumerics, which is exactly a lowercase ULID \u2014 the shape of most trace ids."
291
- },
292
- {
293
- field: "gateway-email `password`, gateway-sms `apiSecret` and `signatureSecret` (Vonage)",
294
- why: "no format of their own; a passphrase is indistinguishable from prose. The SDK's own `key=value` rule already masks these fully wherever they appear as `field=value`, and adding a pattern here made that WORSE by claiming the value first \u2014 it was masked as first6\u2026last4 instead of removed."
295
- },
296
- {
297
- field: "gateway-slack `botToken`",
298
- why: "already masked by one of the SDK's own twelve built-in patterns \u2014 `xoxb-` is Slack's and the SDK knows it. A pattern here would be a second one doing the first's work, and the field-level gate flagged its absence, which is the gate working."
299
- },
300
- {
301
- field: "gateway-whatsapp `appSecret`",
302
- why: "32 lowercase hex, the same shape as the Twilio auth token above and as every md5 and dashless UUID. Masking it would eat the correlation ids in a log."
303
- },
304
- {
305
- field: "gateway-nextcloud-talk `secret`",
306
- why: "a Talk bot secret is a string of 40 to 128 characters the administrator chose for `occ talk:bot:install`, with no prefix or format to recognise. It never travels: both sides send only an HMAC made with it, and the adapter never logs it."
307
- },
308
- {
309
- field: "gateway-irc `password` and `saslPassword`",
310
- why: "a server password and a NickServ password are passphrases the operator chose, with no format to recognise. The SDK's `key=value` rule masks them as fields wherever they appear as `password=...`; the SASL payload on the wire is their base64, which the adapter never logs."
311
- },
312
- {
313
- field: "gateway-google-chat `privateKey`",
314
- why: "a PEM block spans lines, and in a log it usually arrives inside a JSON string with its line breaks escaped as \\n, which no single-line shape can claim whole. The SDK's `key=value` rule masks it as a field wherever it appears as `private_key=...` or `privateKey=...`."
315
- },
316
- {
317
- field: "gateway-line `channelAccessToken`, gateway-sms `authToken` (Plivo)",
318
- why: "long base64 runs with no prefix, indistinguishable from any encoded blob a platform library puts in an error message."
319
- }
320
- ]
740
+ uncovered: parseUncovered(UNCOVERED_TABLE)
321
741
  };
322
742
  function maskShapes(text) {
323
743
  let out = text;
@@ -427,12 +847,36 @@ var HookExecutor = class {
427
847
 
428
848
  // src/runner/gateway-runner.ts
429
849
  var DEFAULT_DRAIN_MS = 1e4;
850
+ var TYPING_RENEW_MS = 4e3;
851
+ function keepTyping(adapter, channelId) {
852
+ const swallow = (p) => p.catch(() => void 0);
853
+ const start = () => swallow(Promise.resolve().then(() => adapter.startTyping(channelId)));
854
+ void start();
855
+ const timer = setInterval(() => void start(), TYPING_RENEW_MS);
856
+ timer.unref();
857
+ return async () => {
858
+ clearInterval(timer);
859
+ await swallow(Promise.resolve().then(() => adapter.stopTyping(channelId)));
860
+ };
861
+ }
430
862
  var DEFAULT_COMMAND_PREFIXES = ["/"];
431
863
  function connectFailureReason(outcome) {
432
864
  if (outcome.status === "fulfilled") return "connect returned false";
433
865
  const message = outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason);
434
866
  return redactSecrets(message);
435
867
  }
868
+ function isTerminalConnectError(err) {
869
+ if (typeof err !== "object" || err === null) return false;
870
+ const e = err;
871
+ for (const key of ["status", "statusCode", "httpStatus"]) {
872
+ if (e[key] === 401 || e[key] === 403) return true;
873
+ }
874
+ if (e.errcode === "M_UNKNOWN_TOKEN" || e.errcode === "M_FORBIDDEN") return true;
875
+ const message = typeof e.message === "string" ? e.message : "";
876
+ return /\b(?:http|status(?: code)?)\s*:?\s*(?:401|403)\b|unauthori[sz]ed|forbidden/i.test(
877
+ message
878
+ );
879
+ }
436
880
  async function releaseAdapters(adapters, during) {
437
881
  await Promise.all(
438
882
  adapters.map(async (a) => {
@@ -463,6 +907,7 @@ var GatewayRunner = class {
463
907
  /** The start that has not settled yet, shared by every overlapping `start()` call. */
464
908
  startInFlight;
465
909
  stopped = false;
910
+ retryTimers = /* @__PURE__ */ new Set();
466
911
  /**
467
912
  * Register a slash command. Match rule (EC-A): text === "/" + name
468
913
  * OR text.startsWith("/" + name + " ") OR text.startsWith("/" + name + "@").
@@ -521,12 +966,80 @@ var GatewayRunner = class {
521
966
  this.startResult = { connected: [], failed: result.failed };
522
967
  return this.startResult;
523
968
  }
524
- this.wireInbound(result.connected);
525
- this.startResult = {
526
- connected: result.connected.map((a) => a.platform),
527
- failed: result.failed
528
- };
529
- return this.startResult;
969
+ this.wireInbound(result.connected);
970
+ this.startResult = {
971
+ connected: result.connected.map((a) => a.platform),
972
+ failed: result.failed
973
+ };
974
+ for (const adapter of result.retryable) this.scheduleReconnect(adapter, 1);
975
+ return this.startResult;
976
+ }
977
+ /** Retry one adapter after its backoff delay; reschedules itself until it connects or gives up. */
978
+ scheduleReconnect(adapter, attempt) {
979
+ const policy = this.opts.reconnect;
980
+ if (policy === void 0 || this.stopped) return;
981
+ if (policy.maxAttempts !== void 0 && attempt > policy.maxAttempts) {
982
+ process.stderr.write(
983
+ `[gateway] adapter "${adapter.platform}" gave up reconnecting after ${policy.maxAttempts} attempts
984
+ `
985
+ );
986
+ return;
987
+ }
988
+ const delay = Math.min(
989
+ (policy.initialDelayMs ?? 1e3) * (policy.factor ?? 2) ** (attempt - 1),
990
+ policy.maxDelayMs ?? 6e4
991
+ );
992
+ const timer = setTimeout(() => {
993
+ this.retryTimers.delete(timer);
994
+ void this.reconnectOnce(adapter, attempt);
995
+ }, delay);
996
+ timer.unref();
997
+ this.retryTimers.add(timer);
998
+ process.stderr.write(
999
+ `[gateway] adapter "${adapter.platform}" reconnect attempt ${attempt} in ${delay}ms
1000
+ `
1001
+ );
1002
+ }
1003
+ async reconnectOnce(adapter, attempt) {
1004
+ if (this.stopped) return;
1005
+ try {
1006
+ if (await adapter.connect()) {
1007
+ if (this.stopped) {
1008
+ await releaseAdapters([adapter], "releasing a reconnect that stop() overtook");
1009
+ return;
1010
+ }
1011
+ this.wireInbound([adapter]);
1012
+ const prev = this.startResult ?? { connected: [], failed: [] };
1013
+ this.startResult = {
1014
+ connected: [...prev.connected, adapter.platform],
1015
+ failed: prev.failed.filter((f) => f.platform !== adapter.platform)
1016
+ };
1017
+ process.stderr.write(
1018
+ `[gateway] adapter "${adapter.platform}" connected on attempt ${attempt}
1019
+ `
1020
+ );
1021
+ return;
1022
+ }
1023
+ process.stderr.write(
1024
+ `[gateway] adapter "${adapter.platform}" refused to connect; not retrying
1025
+ `
1026
+ );
1027
+ return;
1028
+ } catch (err) {
1029
+ const reason = connectFailureReason({ status: "rejected", reason: err });
1030
+ if (isTerminalConnectError(err)) {
1031
+ process.stderr.write(
1032
+ `[gateway] adapter "${adapter.platform}" credentials rejected: ${reason}; not retrying
1033
+ `
1034
+ );
1035
+ return;
1036
+ }
1037
+ process.stderr.write(
1038
+ `[gateway] adapter "${adapter.platform}" reconnect attempt ${attempt} failed: ${reason}
1039
+ `
1040
+ );
1041
+ }
1042
+ this.scheduleReconnect(adapter, attempt + 1);
530
1043
  }
531
1044
  /**
532
1045
  * All or nothing: when any connect fails, disconnect the adapters that did connect, then rethrow
@@ -557,7 +1070,7 @@ var GatewayRunner = class {
557
1070
  await releaseAdapters(connected, "rolling back a failed start");
558
1071
  throw failures[0];
559
1072
  }
560
- return { connected: [...adapters], failed: [] };
1073
+ return { connected: [...adapters], failed: [], retryable: [] };
561
1074
  }
562
1075
  /**
563
1076
  * Connect every adapter and keep the ones that connected. The `async` wrapper turns a
@@ -569,12 +1082,18 @@ var GatewayRunner = class {
569
1082
  const settled = await Promise.allSettled(adapters.map(async (a) => a.connect()));
570
1083
  const connected = [];
571
1084
  const failed = [];
1085
+ const retryable = [];
572
1086
  settled.forEach((outcome, i) => {
573
1087
  const adapter = adapters[i];
574
1088
  if (outcome.status === "fulfilled" && outcome.value) connected.push(adapter);
575
- else failed.push({ platform: adapter.platform, reason: connectFailureReason(outcome) });
1089
+ else {
1090
+ failed.push({ platform: adapter.platform, reason: connectFailureReason(outcome) });
1091
+ if (outcome.status === "rejected" && !isTerminalConnectError(outcome.reason)) {
1092
+ retryable.push(adapter);
1093
+ }
1094
+ }
576
1095
  });
577
- return { connected, failed };
1096
+ return { connected, failed, retryable };
578
1097
  }
579
1098
  wireInbound(adapters) {
580
1099
  for (const a of adapters) {
@@ -605,6 +1124,8 @@ var GatewayRunner = class {
605
1124
  }
606
1125
  }
607
1126
  this.unsubs.length = 0;
1127
+ for (const t of this.retryTimers) clearTimeout(t);
1128
+ this.retryTimers.clear();
608
1129
  const drainMs = this.opts.drainTimeoutMs ?? DEFAULT_DRAIN_MS;
609
1130
  if (this.inflight.size > 0) {
610
1131
  let timer;
@@ -648,12 +1169,15 @@ var GatewayRunner = class {
648
1169
  const slashHandler = this.matchSlashCommand(event);
649
1170
  const handler = slashHandler ?? this.opts.handler;
650
1171
  const work = (async () => {
1172
+ const stopTyping = keepTyping(adapter, event.channel.id);
651
1173
  try {
652
1174
  await handler(event, ctx);
653
1175
  } catch (err) {
654
1176
  await this.hookExecutor.fireOnError({ event, error: err });
655
1177
  process.stderr.write(`[gateway] handler error: ${redactSecrets(err.message)}
656
1178
  `);
1179
+ } finally {
1180
+ await stopTyping();
657
1181
  }
658
1182
  })();
659
1183
  this.inflight.add(work);
@@ -754,212 +1278,6 @@ var SessionRouter = class {
754
1278
  }
755
1279
  };
756
1280
 
757
- // src/text/fence.ts
758
- var MAY_FENCE = /^ {0,3}(?:`{3}|~{3})/m;
759
- var OPENING = /^ {0,3}(`{3,}|~{3,})(.*)$/;
760
- var CLOSING = /^ {0,3}(`{3,}|~{3,})[ \t]*$/;
761
- function lineEndAt(text, from) {
762
- let end = from;
763
- while (end < text.length && text[end] !== "\n" && text[end] !== "\r") end += 1;
764
- let next = end;
765
- if (text[next] === "\r" && text[next + 1] === "\n") next += 2;
766
- else if (next < text.length) next += 1;
767
- return { end, next };
768
- }
769
- function findClose(text, from, run) {
770
- for (let scan = from; scan < text.length; ) {
771
- const line = lineEndAt(text, scan);
772
- const found = CLOSING.exec(text.slice(scan, line.end))?.[1];
773
- if (found !== void 0 && found[0] === run[0] && found.length >= run.length) return line;
774
- scan = line.next;
775
- }
776
- return void 0;
777
- }
778
- function scanFences(text) {
779
- if (!MAY_FENCE.test(text)) return [];
780
- const regions = [];
781
- let pos = 0;
782
- while (pos < text.length) {
783
- const start = pos;
784
- const line = lineEndAt(text, start);
785
- const open = OPENING.exec(text.slice(start, line.end));
786
- const run = open?.[1];
787
- if (run === void 0 || run.startsWith("`") && (open?.[2] ?? "").includes("`")) {
788
- pos = line.next;
789
- continue;
790
- }
791
- const close = findClose(text, line.next, run);
792
- pos = close?.next ?? text.length;
793
- const end = close?.end ?? text.length;
794
- const closed = close !== void 0;
795
- regions.push({
796
- start,
797
- openerEnd: line.end,
798
- contentStart: line.next,
799
- end,
800
- opener: text.slice(start, line.end),
801
- closer: run,
802
- closed
803
- });
804
- }
805
- return regions;
806
- }
807
- function fenceAt(regions, offset) {
808
- return regions.find((r) => r.start < offset && offset < r.end);
809
- }
810
- function openerEol(text, region) {
811
- if (text.startsWith("\r\n", region.openerEnd)) return "\r\n";
812
- return text[region.openerEnd] === "\r" ? "\r" : "\n";
813
- }
814
-
815
- // src/text/dialect.ts
816
- var DIALECTS = {
817
- // WhatsApp emphasis is inline and single-character: *bold*, _italic_, ~strike~, ```mono```.
818
- whatsapp: { bold: "*", italic: "_", strike: "~", code: "```" },
819
- // LINE text messages carry no rich text at all — decoration is emoji-only. Markers are dropped.
820
- line: {},
821
- // SMS is plain text by definition of the medium.
822
- sms: {}
823
- };
824
- var PATTERN = /\*\*(?<bold>.+?)\*\*|~~(?<strike>.+?)~~|(?<![*\w])\*(?!\s)(?<italicStar>.+?)(?<!\s)\*(?!\*)|(?<![_\w])_(?!\s)(?<italicUnderscore>.+?)(?<!\s)_(?!\w)|`(?<code>.+?)`/gu;
825
- var GROUP_MARKERS = [
826
- ["bold", "bold"],
827
- ["strike", "strike"],
828
- ["italicStar", "italic"],
829
- ["italicUnderscore", "italic"],
830
- ["code", "code"]
831
- ];
832
- function toDialect(text, platform) {
833
- const dialect = DIALECTS[platform];
834
- if (dialect === void 0) return text;
835
- return rewriteMarkers(text, dialect);
836
- }
837
- function markerFor(matched, groups, dialect) {
838
- if (groups === void 0) return matched;
839
- for (const [group, marker] of GROUP_MARKERS) {
840
- const content = groups[group];
841
- if (content === void 0) continue;
842
- const wrap = dialect[marker];
843
- return wrap === void 0 ? content : `${wrap}${content}${wrap}`;
844
- }
845
- return matched;
846
- }
847
- function rewriteMatch(matched, args, dialect) {
848
- return markerFor(matched, args.at(-1), dialect);
849
- }
850
- function replaceMarkers(text, dialect) {
851
- return text.replace(PATTERN, (matched, ...args) => rewriteMatch(matched, args, dialect));
852
- }
853
- var ROW_START = /[^\S\r\n]*\|/y;
854
- var LINE_ENDING = /(\r\n|\r|\n)/;
855
- var MARKER_CHARACTER = /[*_~\x60]/;
856
- var PIPE = 124;
857
- var BACKSLASH = 92;
858
- var LF = 10;
859
- var CR = 13;
860
- function rowLocator(text) {
861
- const rowStart = new RegExp(ROW_START);
862
- let lineStart = 0;
863
- let scanned = 0;
864
- return (offset) => {
865
- for (; scanned < offset; scanned += 1) {
866
- const code = text.charCodeAt(scanned);
867
- if (code === LF || code === CR) lineStart = scanned + 1;
868
- }
869
- rowStart.lastIndex = lineStart;
870
- return rowStart.test(text);
871
- };
872
- }
873
- function rewriteTableRow(row, dialect) {
874
- let out = "";
875
- let from = 0;
876
- let backslashes = 0;
877
- for (let i = 0; i < row.length; i += 1) {
878
- const code = row.charCodeAt(i);
879
- if (code === BACKSLASH) {
880
- backslashes += 1;
881
- continue;
882
- }
883
- if (code === PIPE && backslashes % 2 === 0) {
884
- out += `${replaceMarkers(row.slice(from, i), dialect)}|`;
885
- from = i + 1;
886
- }
887
- backslashes = 0;
888
- }
889
- return out + replaceMarkers(row.slice(from), dialect);
890
- }
891
- function rewriteLine(line, dialect, rowStart) {
892
- rowStart.lastIndex = 0;
893
- if (!rowStart.test(line)) return replaceMarkers(line, dialect);
894
- return MARKER_CHARACTER.test(line) ? rewriteTableRow(line, dialect) : line;
895
- }
896
- function rewriteByLine(text, dialect) {
897
- const rowStart = new RegExp(ROW_START);
898
- return text.split(LINE_ENDING).map((piece) => rewriteLine(piece, dialect, rowStart)).join("");
899
- }
900
- function rewriteMarkers(text, dialect) {
901
- const regions = scanFences(text);
902
- if (regions.length === 0) return rewriteUnfenced(text, dialect);
903
- let out = "";
904
- let from = 0;
905
- for (const region of regions) {
906
- out += rewriteUnfenced(text.slice(from, region.start), dialect) + text.slice(region.start, region.end);
907
- from = region.end;
908
- }
909
- return out + rewriteUnfenced(text.slice(from), dialect);
910
- }
911
- function rewriteUnfenced(text, dialect) {
912
- const onTableRow = rowLocator(text);
913
- let crossesRowPipe = false;
914
- const rewritten = text.replace(PATTERN, (matched, ...args) => {
915
- if (!crossesRowPipe && matched.includes("|")) {
916
- crossesRowPipe = onTableRow(args.at(-3));
917
- }
918
- return rewriteMatch(matched, args, dialect);
919
- });
920
- return crossesRowPipe ? rewriteByLine(text, dialect) : rewritten;
921
- }
922
-
923
- // src/text/channel-rendering.ts
924
- var SLACK = { bold: "*", italic: "_", strike: "~", code: "`" };
925
- var STRIP = {};
926
- var identity = (text) => text;
927
- var translateWith = (dialect) => (text) => rewriteMarkers(text, dialect);
928
- var RENDERINGS = {
929
- whatsapp: { format: "plain", translate: translateWith(DIALECTS.whatsapp) },
930
- slack: { format: "markdown", translate: translateWith(SLACK) },
931
- discord: { format: "markdown", translate: identity },
932
- mattermost: { format: "markdown", translate: identity },
933
- teams: { format: "markdown", translate: identity },
934
- signal: { format: "markdown", translate: identity },
935
- line: { format: "plain", translate: translateWith(DIALECTS.line) },
936
- sms: { format: "plain", translate: translateWith(DIALECTS.sms) },
937
- telegram: { format: "plain", translate: translateWith(STRIP) },
938
- matrix: { format: "plain", translate: translateWith(STRIP) },
939
- email: { format: "plain", translate: translateWith(STRIP) },
940
- imessage: { format: "plain", translate: translateWith(STRIP) },
941
- google_chat: { format: "plain", translate: translateWith(STRIP) },
942
- irc: { format: "plain", translate: translateWith(STRIP) },
943
- nextcloud_talk: { format: "markdown", translate: identity },
944
- nostr: { format: "plain", translate: translateWith(STRIP) },
945
- feishu_lark: { format: "plain", translate: translateWith(STRIP) },
946
- synology_chat: { format: "plain", translate: translateWith(STRIP) },
947
- tlon_urbit: { format: "plain", translate: translateWith(STRIP) },
948
- twitch: { format: "plain", translate: translateWith(STRIP) },
949
- buzz: { format: "plain", translate: translateWith(STRIP) },
950
- clickclack: { format: "plain", translate: translateWith(STRIP) },
951
- zalo_personal: { format: "plain", translate: translateWith(STRIP) }
952
- };
953
- function channelRendering(platform) {
954
- const rendering = Object.hasOwn(RENDERINGS, platform) ? RENDERINGS[platform] : void 0;
955
- if (rendering === void 0) {
956
- throw new RangeError(
957
- `channelRendering: unknown platform "${String(platform)}"; expected one of ${Object.keys(RENDERINGS).join(", ")}`
958
- );
959
- }
960
- return rendering;
961
- }
962
-
963
1281
  // src/text/chunk.ts
964
1282
  function searchBoundary(remaining, window, boundaries) {
965
1283
  let cut = window;
@@ -1145,39 +1463,6 @@ function fenceGraphemeCut(text, region, pos, plain, room, boundaryUpTo) {
1145
1463
  return { cut: at, suffix: (closes ? "" : eol) + region.closer, reopen: region.opener + eol };
1146
1464
  }
1147
1465
 
1148
- // src/text/seen-ids.ts
1149
- var DEFAULT_LIMIT = 1e3;
1150
- var SeenIds = class {
1151
- /** @param limit the most ids held at once; the oldest is forgotten when one more arrives */
1152
- constructor(limit = DEFAULT_LIMIT) {
1153
- this.limit = limit;
1154
- }
1155
- limit;
1156
- ids = /* @__PURE__ */ new Set();
1157
- /**
1158
- * Record `id`.
1159
- *
1160
- * @returns `true` when the id was new, `false` when it was already held
1161
- */
1162
- add(id) {
1163
- if (this.ids.has(id)) return false;
1164
- this.ids.add(id);
1165
- if (this.ids.size > this.limit) {
1166
- const oldest = this.ids.values().next().value;
1167
- if (oldest !== void 0) this.ids.delete(oldest);
1168
- }
1169
- return true;
1170
- }
1171
- /** Whether `id` is held. */
1172
- has(id) {
1173
- return this.ids.has(id);
1174
- }
1175
- /** How many ids are held. */
1176
- get size() {
1177
- return this.ids.size;
1178
- }
1179
- };
1180
-
1181
1466
  // src/text/split-rows.ts
1182
1467
  var ROW_BLANK = /^[^\S\r\n]$/;
1183
1468
  function isLineEnd2(character) {
@@ -1336,6 +1621,6 @@ function listenerLifecycle(opts) {
1336
1621
  };
1337
1622
  }
1338
1623
 
1339
- export { BasePlatformAdapter, CREDENTIAL_SHAPES, DeliveryRouter, GatewayConfigurationError, GatewayLifecycleError, GatewayRunner, HookExecutor, SeenIds, SessionRouter, channelRendering, chunkByGrapheme, chunkText, createChannels, defaultStrategy, listenerLifecycle, loadPeer, maskShapes, rawBodyCapture, redactSecrets, scanFences, splitKeepingRows, toDialect };
1624
+ export { BasePlatformAdapter, CREDENTIAL_SHAPES, DeliveryRouter, GatewayConfigurationError, GatewayLifecycleError, GatewayRunner, HookExecutor, SeenIds, SessionRouter, WeixinAdapterBase, channelRendering, chunkByGrapheme, chunkText, createChannels, defaultStrategy, listenerLifecycle, loadPeer, maskShapes, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, splitKeepingRows, toDialect };
1340
1625
  //# sourceMappingURL=index.js.map
1341
1626
  //# sourceMappingURL=index.js.map