@theokit/gateway 0.14.0 → 0.15.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.cjs CHANGED
@@ -2,6 +2,217 @@
2
2
 
3
3
  var sdk = require('@theokit/sdk');
4
4
 
5
+ // src/text/fence.ts
6
+ var MAY_FENCE = /^ {0,3}(?:`{3}|~{3})/m;
7
+ var OPENING = /^ {0,3}(`{3,}|~{3,})(.*)$/;
8
+ var CLOSING = /^ {0,3}(`{3,}|~{3,})[ \t]*$/;
9
+ function lineEndAt(text, from) {
10
+ let end = from;
11
+ while (end < text.length && text[end] !== "\n" && text[end] !== "\r") end += 1;
12
+ let next = end;
13
+ if (text[next] === "\r" && text[next + 1] === "\n") next += 2;
14
+ else if (next < text.length) next += 1;
15
+ return { end, next };
16
+ }
17
+ function findClose(text, from, run) {
18
+ for (let scan = from; scan < text.length; ) {
19
+ const line = lineEndAt(text, scan);
20
+ const found = CLOSING.exec(text.slice(scan, line.end))?.[1];
21
+ if (found !== void 0 && found[0] === run[0] && found.length >= run.length) return line;
22
+ scan = line.next;
23
+ }
24
+ return void 0;
25
+ }
26
+ function scanFences(text) {
27
+ if (!MAY_FENCE.test(text)) return [];
28
+ const regions = [];
29
+ let pos = 0;
30
+ while (pos < text.length) {
31
+ const start = pos;
32
+ const line = lineEndAt(text, start);
33
+ const open = OPENING.exec(text.slice(start, line.end));
34
+ const run = open?.[1];
35
+ if (run === void 0 || run.startsWith("`") && (open?.[2] ?? "").includes("`")) {
36
+ pos = line.next;
37
+ continue;
38
+ }
39
+ const close = findClose(text, line.next, run);
40
+ pos = close?.next ?? text.length;
41
+ const end = close?.end ?? text.length;
42
+ const closed = close !== void 0;
43
+ regions.push({
44
+ start,
45
+ openerEnd: line.end,
46
+ contentStart: line.next,
47
+ end,
48
+ opener: text.slice(start, line.end),
49
+ closer: run,
50
+ closed
51
+ });
52
+ }
53
+ return regions;
54
+ }
55
+ function fenceAt(regions, offset) {
56
+ return regions.find((r) => r.start < offset && offset < r.end);
57
+ }
58
+ function openerEol(text, region) {
59
+ if (text.startsWith("\r\n", region.openerEnd)) return "\r\n";
60
+ return text[region.openerEnd] === "\r" ? "\r" : "\n";
61
+ }
62
+
63
+ // src/text/dialect.ts
64
+ var DIALECTS = {
65
+ // WhatsApp emphasis is inline and single-character: *bold*, _italic_, ~strike~, ```mono```.
66
+ whatsapp: { bold: "*", italic: "_", strike: "~", code: "```" },
67
+ // LINE text messages carry no rich text at all — decoration is emoji-only. Markers are dropped.
68
+ line: {},
69
+ // SMS is plain text by definition of the medium.
70
+ sms: {}
71
+ };
72
+ var PATTERN = /\*\*(?<bold>.+?)\*\*|~~(?<strike>.+?)~~|(?<![*\w])\*(?!\s)(?<italicStar>.+?)(?<!\s)\*(?!\*)|(?<![_\w])_(?!\s)(?<italicUnderscore>.+?)(?<!\s)_(?!\w)|`(?<code>.+?)`/gu;
73
+ var GROUP_MARKERS = [
74
+ ["bold", "bold"],
75
+ ["strike", "strike"],
76
+ ["italicStar", "italic"],
77
+ ["italicUnderscore", "italic"],
78
+ ["code", "code"]
79
+ ];
80
+ function toDialect(text, platform) {
81
+ const dialect = DIALECTS[platform];
82
+ if (dialect === void 0) return text;
83
+ return rewriteMarkers(text, dialect);
84
+ }
85
+ function markerFor(matched, groups, dialect) {
86
+ if (groups === void 0) return matched;
87
+ for (const [group, marker] of GROUP_MARKERS) {
88
+ const content = groups[group];
89
+ if (content === void 0) continue;
90
+ const wrap = dialect[marker];
91
+ return wrap === void 0 ? content : `${wrap}${content}${wrap}`;
92
+ }
93
+ return matched;
94
+ }
95
+ function rewriteMatch(matched, args, dialect) {
96
+ return markerFor(matched, args.at(-1), dialect);
97
+ }
98
+ function replaceMarkers(text, dialect) {
99
+ return text.replace(PATTERN, (matched, ...args) => rewriteMatch(matched, args, dialect));
100
+ }
101
+ var ROW_START = /[^\S\r\n]*\|/y;
102
+ var LINE_ENDING = /(\r\n|\r|\n)/;
103
+ var MARKER_CHARACTER = /[*_~\x60]/;
104
+ var PIPE = 124;
105
+ var BACKSLASH = 92;
106
+ var LF = 10;
107
+ var CR = 13;
108
+ function rowLocator(text) {
109
+ const rowStart = new RegExp(ROW_START);
110
+ let lineStart = 0;
111
+ let scanned = 0;
112
+ return (offset) => {
113
+ for (; scanned < offset; scanned += 1) {
114
+ const code = text.charCodeAt(scanned);
115
+ if (code === LF || code === CR) lineStart = scanned + 1;
116
+ }
117
+ rowStart.lastIndex = lineStart;
118
+ return rowStart.test(text);
119
+ };
120
+ }
121
+ function rewriteTableRow(row, dialect) {
122
+ let out = "";
123
+ let from = 0;
124
+ let backslashes = 0;
125
+ for (let i = 0; i < row.length; i += 1) {
126
+ const code = row.charCodeAt(i);
127
+ if (code === BACKSLASH) {
128
+ backslashes += 1;
129
+ continue;
130
+ }
131
+ if (code === PIPE && backslashes % 2 === 0) {
132
+ out += `${replaceMarkers(row.slice(from, i), dialect)}|`;
133
+ from = i + 1;
134
+ }
135
+ backslashes = 0;
136
+ }
137
+ return out + replaceMarkers(row.slice(from), dialect);
138
+ }
139
+ function rewriteLine(line, dialect, rowStart) {
140
+ rowStart.lastIndex = 0;
141
+ if (!rowStart.test(line)) return replaceMarkers(line, dialect);
142
+ return MARKER_CHARACTER.test(line) ? rewriteTableRow(line, dialect) : line;
143
+ }
144
+ function rewriteByLine(text, dialect) {
145
+ const rowStart = new RegExp(ROW_START);
146
+ return text.split(LINE_ENDING).map((piece) => rewriteLine(piece, dialect, rowStart)).join("");
147
+ }
148
+ function rewriteMarkers(text, dialect) {
149
+ const regions = scanFences(text);
150
+ if (regions.length === 0) return rewriteUnfenced(text, dialect);
151
+ let out = "";
152
+ let from = 0;
153
+ for (const region of regions) {
154
+ out += rewriteUnfenced(text.slice(from, region.start), dialect) + text.slice(region.start, region.end);
155
+ from = region.end;
156
+ }
157
+ return out + rewriteUnfenced(text.slice(from), dialect);
158
+ }
159
+ function rewriteUnfenced(text, dialect) {
160
+ const onTableRow = rowLocator(text);
161
+ let crossesRowPipe = false;
162
+ const rewritten = text.replace(PATTERN, (matched, ...args) => {
163
+ if (!crossesRowPipe && matched.includes("|")) {
164
+ crossesRowPipe = onTableRow(args.at(-3));
165
+ }
166
+ return rewriteMatch(matched, args, dialect);
167
+ });
168
+ return crossesRowPipe ? rewriteByLine(text, dialect) : rewritten;
169
+ }
170
+
171
+ // src/text/channel-rendering.ts
172
+ var SLACK = { bold: "*", italic: "_", strike: "~", code: "`" };
173
+ var STRIP = {};
174
+ var identity = (text) => text;
175
+ var translateWith = (dialect) => (text) => rewriteMarkers(text, dialect);
176
+ var RENDERINGS = {
177
+ whatsapp: { format: "plain", translate: translateWith(DIALECTS.whatsapp) },
178
+ slack: { format: "markdown", translate: translateWith(SLACK) },
179
+ discord: { format: "markdown", translate: identity },
180
+ mattermost: { format: "markdown", translate: identity },
181
+ teams: { format: "markdown", translate: identity },
182
+ signal: { format: "markdown", translate: identity },
183
+ line: { format: "plain", translate: translateWith(DIALECTS.line) },
184
+ sms: { format: "plain", translate: translateWith(DIALECTS.sms) },
185
+ telegram: { format: "plain", translate: translateWith(STRIP) },
186
+ matrix: { format: "plain", translate: translateWith(STRIP) },
187
+ email: { format: "plain", translate: translateWith(STRIP) },
188
+ imessage: { format: "plain", translate: translateWith(STRIP) },
189
+ google_chat: { format: "plain", translate: translateWith(STRIP) },
190
+ irc: { format: "plain", translate: translateWith(STRIP) },
191
+ nextcloud_talk: { format: "markdown", translate: identity },
192
+ nostr: { format: "plain", translate: translateWith(STRIP) },
193
+ feishu_lark: { format: "plain", translate: translateWith(STRIP) },
194
+ synology_chat: { format: "plain", translate: translateWith(STRIP) },
195
+ tlon_urbit: { format: "plain", translate: translateWith(STRIP) },
196
+ twitch: { format: "plain", translate: translateWith(STRIP) },
197
+ buzz: { format: "plain", translate: translateWith(STRIP) },
198
+ clickclack: { format: "plain", translate: translateWith(STRIP) },
199
+ zalo_personal: { format: "plain", translate: translateWith(STRIP) },
200
+ zalo: { format: "plain", translate: translateWith(STRIP) },
201
+ wechat: { format: "plain", translate: translateWith(STRIP) },
202
+ wecom: { format: "plain", translate: translateWith(STRIP) },
203
+ yuanbao: { 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
+
5
216
  // src/adapter/base.ts
6
217
  var BasePlatformAdapter = class {
7
218
  /**
@@ -28,6 +239,56 @@ var BasePlatformAdapter = class {
28
239
  }
29
240
  return "ok";
30
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
+ }
31
292
  /**
32
293
  * Whether {@link editMessage} can replace the text of a message this adapter sent.
33
294
  *
@@ -65,6 +326,25 @@ var BasePlatformAdapter = class {
65
326
  }
66
327
  };
67
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
+ }
68
348
  /** Lifecycle: emit a typing indicator. Default: noop. */
69
349
  async startTyping(_channelId) {
70
350
  }
@@ -73,6 +353,184 @@ var BasePlatformAdapter = class {
73
353
  }
74
354
  };
75
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
+
76
534
  // src/errors/config-error.ts
77
535
  var GatewayConfigurationError = class extends Error {
78
536
  name = "GatewayConfigurationError";
@@ -259,6 +717,22 @@ var CREDENTIAL_SHAPES = {
259
717
  field: "gateway-clickclack `token`",
260
718
  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."
261
719
  },
720
+ {
721
+ field: "gateway-zalo `accessToken`, `oaSecretKey`",
722
+ why: "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."
723
+ },
724
+ {
725
+ field: "gateway-wechat `appSecret`, `token`",
726
+ why: "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."
727
+ },
728
+ {
729
+ field: "gateway-wecom `corpSecret`, `token`, `encodingAesKey`",
730
+ why: "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."
731
+ },
732
+ {
733
+ field: "gateway-yuanbao `appSecret`, `callbackSecret`",
734
+ why: "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."
735
+ },
262
736
  {
263
737
  field: "gateway-zalo-personal `credentials`",
264
738
  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."
@@ -429,12 +903,36 @@ var HookExecutor = class {
429
903
 
430
904
  // src/runner/gateway-runner.ts
431
905
  var DEFAULT_DRAIN_MS = 1e4;
906
+ var TYPING_RENEW_MS = 4e3;
907
+ function keepTyping(adapter, channelId) {
908
+ const swallow = (p) => p.catch(() => void 0);
909
+ const start = () => swallow(Promise.resolve().then(() => adapter.startTyping(channelId)));
910
+ void start();
911
+ const timer = setInterval(() => void start(), TYPING_RENEW_MS);
912
+ timer.unref();
913
+ return async () => {
914
+ clearInterval(timer);
915
+ await swallow(Promise.resolve().then(() => adapter.stopTyping(channelId)));
916
+ };
917
+ }
432
918
  var DEFAULT_COMMAND_PREFIXES = ["/"];
433
919
  function connectFailureReason(outcome) {
434
920
  if (outcome.status === "fulfilled") return "connect returned false";
435
921
  const message = outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason);
436
922
  return redactSecrets(message);
437
923
  }
924
+ function isTerminalConnectError(err) {
925
+ if (typeof err !== "object" || err === null) return false;
926
+ const e = err;
927
+ for (const key of ["status", "statusCode", "httpStatus"]) {
928
+ if (e[key] === 401 || e[key] === 403) return true;
929
+ }
930
+ if (e.errcode === "M_UNKNOWN_TOKEN" || e.errcode === "M_FORBIDDEN") return true;
931
+ const message = typeof e.message === "string" ? e.message : "";
932
+ return /\b(?:http|status(?: code)?)\s*:?\s*(?:401|403)\b|unauthori[sz]ed|forbidden/i.test(
933
+ message
934
+ );
935
+ }
438
936
  async function releaseAdapters(adapters, during) {
439
937
  await Promise.all(
440
938
  adapters.map(async (a) => {
@@ -465,6 +963,7 @@ var GatewayRunner = class {
465
963
  /** The start that has not settled yet, shared by every overlapping `start()` call. */
466
964
  startInFlight;
467
965
  stopped = false;
966
+ retryTimers = /* @__PURE__ */ new Set();
468
967
  /**
469
968
  * Register a slash command. Match rule (EC-A): text === "/" + name
470
969
  * OR text.startsWith("/" + name + " ") OR text.startsWith("/" + name + "@").
@@ -523,12 +1022,80 @@ var GatewayRunner = class {
523
1022
  this.startResult = { connected: [], failed: result.failed };
524
1023
  return this.startResult;
525
1024
  }
526
- this.wireInbound(result.connected);
527
- this.startResult = {
528
- connected: result.connected.map((a) => a.platform),
529
- failed: result.failed
530
- };
531
- return this.startResult;
1025
+ this.wireInbound(result.connected);
1026
+ this.startResult = {
1027
+ connected: result.connected.map((a) => a.platform),
1028
+ failed: result.failed
1029
+ };
1030
+ for (const adapter of result.retryable) this.scheduleReconnect(adapter, 1);
1031
+ return this.startResult;
1032
+ }
1033
+ /** Retry one adapter after its backoff delay; reschedules itself until it connects or gives up. */
1034
+ scheduleReconnect(adapter, attempt) {
1035
+ const policy = this.opts.reconnect;
1036
+ if (policy === void 0 || this.stopped) return;
1037
+ if (policy.maxAttempts !== void 0 && attempt > policy.maxAttempts) {
1038
+ process.stderr.write(
1039
+ `[gateway] adapter "${adapter.platform}" gave up reconnecting after ${policy.maxAttempts} attempts
1040
+ `
1041
+ );
1042
+ return;
1043
+ }
1044
+ const delay = Math.min(
1045
+ (policy.initialDelayMs ?? 1e3) * (policy.factor ?? 2) ** (attempt - 1),
1046
+ policy.maxDelayMs ?? 6e4
1047
+ );
1048
+ const timer = setTimeout(() => {
1049
+ this.retryTimers.delete(timer);
1050
+ void this.reconnectOnce(adapter, attempt);
1051
+ }, delay);
1052
+ timer.unref();
1053
+ this.retryTimers.add(timer);
1054
+ process.stderr.write(
1055
+ `[gateway] adapter "${adapter.platform}" reconnect attempt ${attempt} in ${delay}ms
1056
+ `
1057
+ );
1058
+ }
1059
+ async reconnectOnce(adapter, attempt) {
1060
+ if (this.stopped) return;
1061
+ try {
1062
+ if (await adapter.connect()) {
1063
+ if (this.stopped) {
1064
+ await releaseAdapters([adapter], "releasing a reconnect that stop() overtook");
1065
+ return;
1066
+ }
1067
+ this.wireInbound([adapter]);
1068
+ const prev = this.startResult ?? { connected: [], failed: [] };
1069
+ this.startResult = {
1070
+ connected: [...prev.connected, adapter.platform],
1071
+ failed: prev.failed.filter((f) => f.platform !== adapter.platform)
1072
+ };
1073
+ process.stderr.write(
1074
+ `[gateway] adapter "${adapter.platform}" connected on attempt ${attempt}
1075
+ `
1076
+ );
1077
+ return;
1078
+ }
1079
+ process.stderr.write(
1080
+ `[gateway] adapter "${adapter.platform}" refused to connect; not retrying
1081
+ `
1082
+ );
1083
+ return;
1084
+ } catch (err) {
1085
+ const reason = connectFailureReason({ status: "rejected", reason: err });
1086
+ if (isTerminalConnectError(err)) {
1087
+ process.stderr.write(
1088
+ `[gateway] adapter "${adapter.platform}" credentials rejected: ${reason}; not retrying
1089
+ `
1090
+ );
1091
+ return;
1092
+ }
1093
+ process.stderr.write(
1094
+ `[gateway] adapter "${adapter.platform}" reconnect attempt ${attempt} failed: ${reason}
1095
+ `
1096
+ );
1097
+ }
1098
+ this.scheduleReconnect(adapter, attempt + 1);
532
1099
  }
533
1100
  /**
534
1101
  * All or nothing: when any connect fails, disconnect the adapters that did connect, then rethrow
@@ -559,7 +1126,7 @@ var GatewayRunner = class {
559
1126
  await releaseAdapters(connected, "rolling back a failed start");
560
1127
  throw failures[0];
561
1128
  }
562
- return { connected: [...adapters], failed: [] };
1129
+ return { connected: [...adapters], failed: [], retryable: [] };
563
1130
  }
564
1131
  /**
565
1132
  * Connect every adapter and keep the ones that connected. The `async` wrapper turns a
@@ -571,12 +1138,18 @@ var GatewayRunner = class {
571
1138
  const settled = await Promise.allSettled(adapters.map(async (a) => a.connect()));
572
1139
  const connected = [];
573
1140
  const failed = [];
1141
+ const retryable = [];
574
1142
  settled.forEach((outcome, i) => {
575
1143
  const adapter = adapters[i];
576
1144
  if (outcome.status === "fulfilled" && outcome.value) connected.push(adapter);
577
- else failed.push({ platform: adapter.platform, reason: connectFailureReason(outcome) });
1145
+ else {
1146
+ failed.push({ platform: adapter.platform, reason: connectFailureReason(outcome) });
1147
+ if (outcome.status === "rejected" && !isTerminalConnectError(outcome.reason)) {
1148
+ retryable.push(adapter);
1149
+ }
1150
+ }
578
1151
  });
579
- return { connected, failed };
1152
+ return { connected, failed, retryable };
580
1153
  }
581
1154
  wireInbound(adapters) {
582
1155
  for (const a of adapters) {
@@ -607,6 +1180,8 @@ var GatewayRunner = class {
607
1180
  }
608
1181
  }
609
1182
  this.unsubs.length = 0;
1183
+ for (const t of this.retryTimers) clearTimeout(t);
1184
+ this.retryTimers.clear();
610
1185
  const drainMs = this.opts.drainTimeoutMs ?? DEFAULT_DRAIN_MS;
611
1186
  if (this.inflight.size > 0) {
612
1187
  let timer;
@@ -650,12 +1225,15 @@ var GatewayRunner = class {
650
1225
  const slashHandler = this.matchSlashCommand(event);
651
1226
  const handler = slashHandler ?? this.opts.handler;
652
1227
  const work = (async () => {
1228
+ const stopTyping = keepTyping(adapter, event.channel.id);
653
1229
  try {
654
1230
  await handler(event, ctx);
655
1231
  } catch (err) {
656
1232
  await this.hookExecutor.fireOnError({ event, error: err });
657
1233
  process.stderr.write(`[gateway] handler error: ${redactSecrets(err.message)}
658
1234
  `);
1235
+ } finally {
1236
+ await stopTyping();
659
1237
  }
660
1238
  })();
661
1239
  this.inflight.add(work);
@@ -756,212 +1334,6 @@ var SessionRouter = class {
756
1334
  }
757
1335
  };
758
1336
 
759
- // src/text/fence.ts
760
- var MAY_FENCE = /^ {0,3}(?:`{3}|~{3})/m;
761
- var OPENING = /^ {0,3}(`{3,}|~{3,})(.*)$/;
762
- var CLOSING = /^ {0,3}(`{3,}|~{3,})[ \t]*$/;
763
- function lineEndAt(text, from) {
764
- let end = from;
765
- while (end < text.length && text[end] !== "\n" && text[end] !== "\r") end += 1;
766
- let next = end;
767
- if (text[next] === "\r" && text[next + 1] === "\n") next += 2;
768
- else if (next < text.length) next += 1;
769
- return { end, next };
770
- }
771
- function findClose(text, from, run) {
772
- for (let scan = from; scan < text.length; ) {
773
- const line = lineEndAt(text, scan);
774
- const found = CLOSING.exec(text.slice(scan, line.end))?.[1];
775
- if (found !== void 0 && found[0] === run[0] && found.length >= run.length) return line;
776
- scan = line.next;
777
- }
778
- return void 0;
779
- }
780
- function scanFences(text) {
781
- if (!MAY_FENCE.test(text)) return [];
782
- const regions = [];
783
- let pos = 0;
784
- while (pos < text.length) {
785
- const start = pos;
786
- const line = lineEndAt(text, start);
787
- const open = OPENING.exec(text.slice(start, line.end));
788
- const run = open?.[1];
789
- if (run === void 0 || run.startsWith("`") && (open?.[2] ?? "").includes("`")) {
790
- pos = line.next;
791
- continue;
792
- }
793
- const close = findClose(text, line.next, run);
794
- pos = close?.next ?? text.length;
795
- const end = close?.end ?? text.length;
796
- const closed = close !== void 0;
797
- regions.push({
798
- start,
799
- openerEnd: line.end,
800
- contentStart: line.next,
801
- end,
802
- opener: text.slice(start, line.end),
803
- closer: run,
804
- closed
805
- });
806
- }
807
- return regions;
808
- }
809
- function fenceAt(regions, offset) {
810
- return regions.find((r) => r.start < offset && offset < r.end);
811
- }
812
- function openerEol(text, region) {
813
- if (text.startsWith("\r\n", region.openerEnd)) return "\r\n";
814
- return text[region.openerEnd] === "\r" ? "\r" : "\n";
815
- }
816
-
817
- // src/text/dialect.ts
818
- var DIALECTS = {
819
- // WhatsApp emphasis is inline and single-character: *bold*, _italic_, ~strike~, ```mono```.
820
- whatsapp: { bold: "*", italic: "_", strike: "~", code: "```" },
821
- // LINE text messages carry no rich text at all — decoration is emoji-only. Markers are dropped.
822
- line: {},
823
- // SMS is plain text by definition of the medium.
824
- sms: {}
825
- };
826
- var PATTERN = /\*\*(?<bold>.+?)\*\*|~~(?<strike>.+?)~~|(?<![*\w])\*(?!\s)(?<italicStar>.+?)(?<!\s)\*(?!\*)|(?<![_\w])_(?!\s)(?<italicUnderscore>.+?)(?<!\s)_(?!\w)|`(?<code>.+?)`/gu;
827
- var GROUP_MARKERS = [
828
- ["bold", "bold"],
829
- ["strike", "strike"],
830
- ["italicStar", "italic"],
831
- ["italicUnderscore", "italic"],
832
- ["code", "code"]
833
- ];
834
- function toDialect(text, platform) {
835
- const dialect = DIALECTS[platform];
836
- if (dialect === void 0) return text;
837
- return rewriteMarkers(text, dialect);
838
- }
839
- function markerFor(matched, groups, dialect) {
840
- if (groups === void 0) return matched;
841
- for (const [group, marker] of GROUP_MARKERS) {
842
- const content = groups[group];
843
- if (content === void 0) continue;
844
- const wrap = dialect[marker];
845
- return wrap === void 0 ? content : `${wrap}${content}${wrap}`;
846
- }
847
- return matched;
848
- }
849
- function rewriteMatch(matched, args, dialect) {
850
- return markerFor(matched, args.at(-1), dialect);
851
- }
852
- function replaceMarkers(text, dialect) {
853
- return text.replace(PATTERN, (matched, ...args) => rewriteMatch(matched, args, dialect));
854
- }
855
- var ROW_START = /[^\S\r\n]*\|/y;
856
- var LINE_ENDING = /(\r\n|\r|\n)/;
857
- var MARKER_CHARACTER = /[*_~\x60]/;
858
- var PIPE = 124;
859
- var BACKSLASH = 92;
860
- var LF = 10;
861
- var CR = 13;
862
- function rowLocator(text) {
863
- const rowStart = new RegExp(ROW_START);
864
- let lineStart = 0;
865
- let scanned = 0;
866
- return (offset) => {
867
- for (; scanned < offset; scanned += 1) {
868
- const code = text.charCodeAt(scanned);
869
- if (code === LF || code === CR) lineStart = scanned + 1;
870
- }
871
- rowStart.lastIndex = lineStart;
872
- return rowStart.test(text);
873
- };
874
- }
875
- function rewriteTableRow(row, dialect) {
876
- let out = "";
877
- let from = 0;
878
- let backslashes = 0;
879
- for (let i = 0; i < row.length; i += 1) {
880
- const code = row.charCodeAt(i);
881
- if (code === BACKSLASH) {
882
- backslashes += 1;
883
- continue;
884
- }
885
- if (code === PIPE && backslashes % 2 === 0) {
886
- out += `${replaceMarkers(row.slice(from, i), dialect)}|`;
887
- from = i + 1;
888
- }
889
- backslashes = 0;
890
- }
891
- return out + replaceMarkers(row.slice(from), dialect);
892
- }
893
- function rewriteLine(line, dialect, rowStart) {
894
- rowStart.lastIndex = 0;
895
- if (!rowStart.test(line)) return replaceMarkers(line, dialect);
896
- return MARKER_CHARACTER.test(line) ? rewriteTableRow(line, dialect) : line;
897
- }
898
- function rewriteByLine(text, dialect) {
899
- const rowStart = new RegExp(ROW_START);
900
- return text.split(LINE_ENDING).map((piece) => rewriteLine(piece, dialect, rowStart)).join("");
901
- }
902
- function rewriteMarkers(text, dialect) {
903
- const regions = scanFences(text);
904
- if (regions.length === 0) return rewriteUnfenced(text, dialect);
905
- let out = "";
906
- let from = 0;
907
- for (const region of regions) {
908
- out += rewriteUnfenced(text.slice(from, region.start), dialect) + text.slice(region.start, region.end);
909
- from = region.end;
910
- }
911
- return out + rewriteUnfenced(text.slice(from), dialect);
912
- }
913
- function rewriteUnfenced(text, dialect) {
914
- const onTableRow = rowLocator(text);
915
- let crossesRowPipe = false;
916
- const rewritten = text.replace(PATTERN, (matched, ...args) => {
917
- if (!crossesRowPipe && matched.includes("|")) {
918
- crossesRowPipe = onTableRow(args.at(-3));
919
- }
920
- return rewriteMatch(matched, args, dialect);
921
- });
922
- return crossesRowPipe ? rewriteByLine(text, dialect) : rewritten;
923
- }
924
-
925
- // src/text/channel-rendering.ts
926
- var SLACK = { bold: "*", italic: "_", strike: "~", code: "`" };
927
- var STRIP = {};
928
- var identity = (text) => text;
929
- var translateWith = (dialect) => (text) => rewriteMarkers(text, dialect);
930
- var RENDERINGS = {
931
- whatsapp: { format: "plain", translate: translateWith(DIALECTS.whatsapp) },
932
- slack: { format: "markdown", translate: translateWith(SLACK) },
933
- discord: { format: "markdown", translate: identity },
934
- mattermost: { format: "markdown", translate: identity },
935
- teams: { format: "markdown", translate: identity },
936
- signal: { format: "markdown", translate: identity },
937
- line: { format: "plain", translate: translateWith(DIALECTS.line) },
938
- sms: { format: "plain", translate: translateWith(DIALECTS.sms) },
939
- telegram: { format: "plain", translate: translateWith(STRIP) },
940
- matrix: { format: "plain", translate: translateWith(STRIP) },
941
- email: { format: "plain", translate: translateWith(STRIP) },
942
- imessage: { format: "plain", translate: translateWith(STRIP) },
943
- google_chat: { format: "plain", translate: translateWith(STRIP) },
944
- irc: { format: "plain", translate: translateWith(STRIP) },
945
- nextcloud_talk: { format: "markdown", translate: identity },
946
- nostr: { format: "plain", translate: translateWith(STRIP) },
947
- feishu_lark: { format: "plain", translate: translateWith(STRIP) },
948
- synology_chat: { format: "plain", translate: translateWith(STRIP) },
949
- tlon_urbit: { format: "plain", translate: translateWith(STRIP) },
950
- twitch: { format: "plain", translate: translateWith(STRIP) },
951
- buzz: { format: "plain", translate: translateWith(STRIP) },
952
- clickclack: { format: "plain", translate: translateWith(STRIP) },
953
- zalo_personal: { format: "plain", translate: translateWith(STRIP) }
954
- };
955
- function channelRendering(platform) {
956
- const rendering = Object.hasOwn(RENDERINGS, platform) ? RENDERINGS[platform] : void 0;
957
- if (rendering === void 0) {
958
- throw new RangeError(
959
- `channelRendering: unknown platform "${String(platform)}"; expected one of ${Object.keys(RENDERINGS).join(", ")}`
960
- );
961
- }
962
- return rendering;
963
- }
964
-
965
1337
  // src/text/chunk.ts
966
1338
  function searchBoundary(remaining, window, boundaries) {
967
1339
  let cut = window;
@@ -1147,39 +1519,6 @@ function fenceGraphemeCut(text, region, pos, plain, room, boundaryUpTo) {
1147
1519
  return { cut: at, suffix: (closes ? "" : eol) + region.closer, reopen: region.opener + eol };
1148
1520
  }
1149
1521
 
1150
- // src/text/seen-ids.ts
1151
- var DEFAULT_LIMIT = 1e3;
1152
- var SeenIds = class {
1153
- /** @param limit the most ids held at once; the oldest is forgotten when one more arrives */
1154
- constructor(limit = DEFAULT_LIMIT) {
1155
- this.limit = limit;
1156
- }
1157
- limit;
1158
- ids = /* @__PURE__ */ new Set();
1159
- /**
1160
- * Record `id`.
1161
- *
1162
- * @returns `true` when the id was new, `false` when it was already held
1163
- */
1164
- add(id) {
1165
- if (this.ids.has(id)) return false;
1166
- this.ids.add(id);
1167
- if (this.ids.size > this.limit) {
1168
- const oldest = this.ids.values().next().value;
1169
- if (oldest !== void 0) this.ids.delete(oldest);
1170
- }
1171
- return true;
1172
- }
1173
- /** Whether `id` is held. */
1174
- has(id) {
1175
- return this.ids.has(id);
1176
- }
1177
- /** How many ids are held. */
1178
- get size() {
1179
- return this.ids.size;
1180
- }
1181
- };
1182
-
1183
1522
  // src/text/split-rows.ts
1184
1523
  var ROW_BLANK = /^[^\S\r\n]$/;
1185
1524
  function isLineEnd2(character) {
@@ -1347,6 +1686,7 @@ exports.GatewayRunner = GatewayRunner;
1347
1686
  exports.HookExecutor = HookExecutor;
1348
1687
  exports.SeenIds = SeenIds;
1349
1688
  exports.SessionRouter = SessionRouter;
1689
+ exports.WeixinAdapterBase = WeixinAdapterBase;
1350
1690
  exports.channelRendering = channelRendering;
1351
1691
  exports.chunkByGrapheme = chunkByGrapheme;
1352
1692
  exports.chunkText = chunkText;
@@ -1355,6 +1695,7 @@ exports.defaultStrategy = defaultStrategy;
1355
1695
  exports.listenerLifecycle = listenerLifecycle;
1356
1696
  exports.loadPeer = loadPeer;
1357
1697
  exports.maskShapes = maskShapes;
1698
+ exports.parseFlatXml = parseFlatXml;
1358
1699
  exports.rawBodyCapture = rawBodyCapture;
1359
1700
  exports.redactSecrets = redactSecrets;
1360
1701
  exports.scanFences = scanFences;