@theokit/gateway 0.12.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
  *
@@ -36,6 +297,14 @@ var BasePlatformAdapter = class {
36
297
  * edit-capable adapter can override it with `true`.
37
298
  */
38
299
  supportsEdit = false;
300
+ /**
301
+ * Whether {@link sendMessage} can send the images of `out.attachments` (B-674).
302
+ *
303
+ * Read it before attaching: on `false`, the adapter refuses a non-empty list with
304
+ * `attachments_unsupported`. Set at construction, never changed by `connect()`. Annotated as
305
+ * `boolean` so that an adapter that sends images can override it with `true`.
306
+ */
307
+ supportsAttachments = false;
39
308
  /**
40
309
  * Replace the text of a message this adapter sent, keeping its id.
41
310
  *
@@ -57,6 +326,25 @@ var BasePlatformAdapter = class {
57
326
  }
58
327
  };
59
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
+ }
60
348
  /** Lifecycle: emit a typing indicator. Default: noop. */
61
349
  async startTyping(_channelId) {
62
350
  }
@@ -65,6 +353,184 @@ var BasePlatformAdapter = class {
65
353
  }
66
354
  };
67
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
+
68
534
  // src/errors/config-error.ts
69
535
  var GatewayConfigurationError = class extends Error {
70
536
  name = "GatewayConfigurationError";
@@ -134,6 +600,7 @@ function createAdapter(entry, values) {
134
600
  }
135
601
  function createChannels(entries) {
136
602
  const adapters = [];
603
+ const channels = [];
137
604
  const rejected = [];
138
605
  const builtPlatforms = /* @__PURE__ */ new Set();
139
606
  for (const entry of entries) {
@@ -144,9 +611,28 @@ function createChannels(entries) {
144
611
  continue;
145
612
  }
146
613
  adapters.push(outcome.adapter);
614
+ channels.push({ descriptor: entry.descriptor, adapter: outcome.adapter });
147
615
  builtPlatforms.add(entry.descriptor.platform);
148
616
  }
149
- return { adapters, rejected };
617
+ return { adapters, channels, rejected };
618
+ }
619
+
620
+ // src/delivery/attachments.ts
621
+ function attachmentsOf(attachments) {
622
+ return attachments != null && attachments.length !== 0 ? { attachments } : {};
623
+ }
624
+ function refuseUnsupportedAttachments(adapter, outbound) {
625
+ const { attachments } = outbound;
626
+ if (adapter.supportsAttachments || attachments == null || attachments.length === 0) {
627
+ return void 0;
628
+ }
629
+ return {
630
+ ok: false,
631
+ error: {
632
+ code: "attachments_unsupported",
633
+ message: `${adapter.platform} adapter cannot send attachments`
634
+ }
635
+ };
150
636
  }
151
637
 
152
638
  // src/delivery/router.ts
@@ -163,12 +649,14 @@ var DeliveryRouter = class {
163
649
  error: { code: "no_adapter", message: `no adapter for platform "${req.platform}"` }
164
650
  };
165
651
  }
166
- return adapter.sendMessage({
652
+ const outbound = {
167
653
  channel: req.channel,
168
654
  text: req.text,
169
655
  ...req.format !== void 0 ? { format: req.format } : {},
170
- ...req.replyTo !== void 0 ? { replyTo: req.replyTo } : {}
171
- });
656
+ ...req.replyTo !== void 0 ? { replyTo: req.replyTo } : {},
657
+ ...attachmentsOf(req.attachments)
658
+ };
659
+ return refuseUnsupportedAttachments(adapter, outbound) ?? adapter.sendMessage(outbound);
172
660
  }
173
661
  };
174
662
 
@@ -213,9 +701,62 @@ var CREDENTIAL_SHAPES = {
213
701
  field: "gateway-teams `clientSecret`",
214
702
  pattern: /(?<![A-Za-z0-9~])[A-Za-z0-9]{3}\d[A-Za-z0-9]?~[A-Za-z0-9._~-]{30,}(?![A-Za-z0-9._~-])/g,
215
703
  alsoMatches: "an Entra-style secret is the only common value with a tilde in that position"
704
+ },
705
+ {
706
+ field: "gateway-nostr `secretKey` (nsec1 form)",
707
+ pattern: /(?<![a-z0-9])nsec1[02-9ac-hj-np-z]{58}(?![a-z0-9])/g,
708
+ alsoMatches: "nothing plausible \u2014 `nsec1` is NIP-19's prefix for a secret key"
216
709
  }
217
710
  ],
218
711
  uncovered: [
712
+ {
713
+ field: "gateway-buzz `token`",
714
+ why: "a Buzz bot token with no fixed shape this package could confirm. It travels only in Authorization headers, which the adapter never logs."
715
+ },
716
+ {
717
+ field: "gateway-clickclack `token`",
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."
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
+ },
736
+ {
737
+ field: "gateway-zalo-personal `credentials`",
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."
739
+ },
740
+ {
741
+ field: "gateway-twitch `accessToken`",
742
+ 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."
743
+ },
744
+ {
745
+ field: "gateway-tlon-urbit `code`",
746
+ 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."
747
+ },
748
+ {
749
+ field: "gateway-synology-chat `botToken` and `incomingUrl`",
750
+ 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."
751
+ },
752
+ {
753
+ field: "gateway-feishu-lark `appSecret`",
754
+ 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."
755
+ },
756
+ {
757
+ field: "gateway-nostr `secretKey` (64-hex form)",
758
+ 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."
759
+ },
219
760
  {
220
761
  field: "gateway-sms `authToken` (Twilio), gateway-line `channelSecret`",
221
762
  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."
@@ -362,12 +903,36 @@ var HookExecutor = class {
362
903
 
363
904
  // src/runner/gateway-runner.ts
364
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
+ }
365
918
  var DEFAULT_COMMAND_PREFIXES = ["/"];
366
919
  function connectFailureReason(outcome) {
367
920
  if (outcome.status === "fulfilled") return "connect returned false";
368
921
  const message = outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason);
369
922
  return redactSecrets(message);
370
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
+ }
371
936
  async function releaseAdapters(adapters, during) {
372
937
  await Promise.all(
373
938
  adapters.map(async (a) => {
@@ -386,11 +951,9 @@ async function releaseAdapters(adapters, during) {
386
951
  var GatewayRunner = class {
387
952
  constructor(opts) {
388
953
  this.opts = opts;
389
- for (const a of opts.adapters) this.adaptersByPlatform.set(a.platform, a);
390
954
  this.hookExecutor = new HookExecutor(opts.hooks ?? []);
391
955
  }
392
956
  opts;
393
- adaptersByPlatform = /* @__PURE__ */ new Map();
394
957
  hookExecutor;
395
958
  inflight = /* @__PURE__ */ new Set();
396
959
  unsubs = [];
@@ -400,6 +963,7 @@ var GatewayRunner = class {
400
963
  /** The start that has not settled yet, shared by every overlapping `start()` call. */
401
964
  startInFlight;
402
965
  stopped = false;
966
+ retryTimers = /* @__PURE__ */ new Set();
403
967
  /**
404
968
  * Register a slash command. Match rule (EC-A): text === "/" + name
405
969
  * OR text.startsWith("/" + name + " ") OR text.startsWith("/" + name + "@").
@@ -463,8 +1027,76 @@ var GatewayRunner = class {
463
1027
  connected: result.connected.map((a) => a.platform),
464
1028
  failed: result.failed
465
1029
  };
1030
+ for (const adapter of result.retryable) this.scheduleReconnect(adapter, 1);
466
1031
  return this.startResult;
467
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);
1099
+ }
468
1100
  /**
469
1101
  * All or nothing: when any connect fails, disconnect the adapters that did connect, then rethrow
470
1102
  * the first failure. Every connect settles before the rollback: rolling back while one is still
@@ -494,7 +1126,7 @@ var GatewayRunner = class {
494
1126
  await releaseAdapters(connected, "rolling back a failed start");
495
1127
  throw failures[0];
496
1128
  }
497
- return { connected: [...adapters], failed: [] };
1129
+ return { connected: [...adapters], failed: [], retryable: [] };
498
1130
  }
499
1131
  /**
500
1132
  * Connect every adapter and keep the ones that connected. The `async` wrapper turns a
@@ -506,17 +1138,23 @@ var GatewayRunner = class {
506
1138
  const settled = await Promise.allSettled(adapters.map(async (a) => a.connect()));
507
1139
  const connected = [];
508
1140
  const failed = [];
1141
+ const retryable = [];
509
1142
  settled.forEach((outcome, i) => {
510
1143
  const adapter = adapters[i];
511
1144
  if (outcome.status === "fulfilled" && outcome.value) connected.push(adapter);
512
- 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
+ }
513
1151
  });
514
- return { connected, failed };
1152
+ return { connected, failed, retryable };
515
1153
  }
516
1154
  wireInbound(adapters) {
517
1155
  for (const a of adapters) {
518
1156
  const unsub = a.onInbound(async (event) => {
519
- const p = this.dispatch(event);
1157
+ const p = this.dispatch(event, a);
520
1158
  this.inflight.add(p);
521
1159
  p.finally(() => this.inflight.delete(p));
522
1160
  });
@@ -542,6 +1180,8 @@ var GatewayRunner = class {
542
1180
  }
543
1181
  }
544
1182
  this.unsubs.length = 0;
1183
+ for (const t of this.retryTimers) clearTimeout(t);
1184
+ this.retryTimers.clear();
545
1185
  const drainMs = this.opts.drainTimeoutMs ?? DEFAULT_DRAIN_MS;
546
1186
  if (this.inflight.size > 0) {
547
1187
  let timer;
@@ -556,7 +1196,7 @@ var GatewayRunner = class {
556
1196
  if (timer !== void 0) clearTimeout(timer);
557
1197
  }
558
1198
  }
559
- await releaseAdapters([...this.adaptersByPlatform.values()], "stopping the runner");
1199
+ await releaseAdapters([...new Set(this.opts.adapters)], "stopping the runner");
560
1200
  }
561
1201
  /**
562
1202
  * @internal Test seam, following `EmailAdapter._threadStoreSize`. The drain set must SHRINK: a
@@ -568,24 +1208,32 @@ var GatewayRunner = class {
568
1208
  return this.inflight.size;
569
1209
  }
570
1210
  /** @internal */
571
- async dispatch(event) {
572
- const ctx = this.buildContext(event);
1211
+ async dispatch(event, adapter) {
1212
+ const ctx = this.buildContext(event, adapter);
573
1213
  const decision = await this.hookExecutor.firePreInbound({ event });
574
1214
  if (decision.block === true) {
575
1215
  if (decision.message !== void 0 && decision.message.length > 0) {
576
- await ctx.reply(decision.message).catch(() => void 0);
1216
+ await ctx.reply(decision.message).catch(async (err) => {
1217
+ const error = err;
1218
+ await this.hookExecutor.fireOnError({ event, error });
1219
+ process.stderr.write(`[gateway] auto-reply error: ${redactSecrets(error.message)}
1220
+ `);
1221
+ });
577
1222
  }
578
1223
  return;
579
1224
  }
580
1225
  const slashHandler = this.matchSlashCommand(event);
581
1226
  const handler = slashHandler ?? this.opts.handler;
582
1227
  const work = (async () => {
1228
+ const stopTyping = keepTyping(adapter, event.channel.id);
583
1229
  try {
584
1230
  await handler(event, ctx);
585
1231
  } catch (err) {
586
1232
  await this.hookExecutor.fireOnError({ event, error: err });
587
1233
  process.stderr.write(`[gateway] handler error: ${redactSecrets(err.message)}
588
1234
  `);
1235
+ } finally {
1236
+ await stopTyping();
589
1237
  }
590
1238
  })();
591
1239
  this.inflight.add(work);
@@ -618,13 +1266,14 @@ var GatewayRunner = class {
618
1266
  return void 0;
619
1267
  }
620
1268
  /** EC-G: per-event ctx whose reply routes to the matching adapter. */
621
- buildContext(event) {
1269
+ buildContext(event, adapter) {
622
1270
  return {
623
1271
  event,
624
- reply: async (text, opts) => this.deliver(event, {
1272
+ reply: async (text, opts) => this.deliver(event, adapter, {
625
1273
  channel: event.channel,
626
1274
  text,
627
- ...opts?.format !== void 0 ? { format: opts.format } : {}
1275
+ ...opts?.format !== void 0 ? { format: opts.format } : {},
1276
+ ...attachmentsOf(opts?.attachments)
628
1277
  })
629
1278
  };
630
1279
  }
@@ -636,6 +1285,10 @@ var GatewayRunner = class {
636
1285
  * adapter for the platform. An audit hook that counted only the deliveries
637
1286
  * which reached a transport would omit precisely the ones that went nowhere.
638
1287
  *
1288
+ * An outbound with attachments for an adapter that does not declare `supportsAttachments` is
1289
+ * refused here as `attachments_unsupported`, with no `sendMessage` call, so an adapter that
1290
+ * ignores the field cannot drop the image and report success (B-674).
1291
+ *
639
1292
  * `post_outbound` observes; it does not intercept. The adapter's `SendResult`
640
1293
  * is returned to the caller unchanged, and `HookExecutor` already contains a
641
1294
  * throwing hook, so a broken observer cannot turn a delivered reply into a
@@ -643,9 +1296,9 @@ var GatewayRunner = class {
643
1296
  *
644
1297
  * @internal
645
1298
  */
646
- async deliver(event, outbound) {
647
- const adapter = this.adaptersByPlatform.get(event.platform);
648
- const result = adapter === void 0 ? { ok: false, error: { code: "no_adapter", message: `no adapter for ${event.platform}` } } : await adapter.sendMessage(outbound);
1299
+ async deliver(event, adapter, outbound) {
1300
+ const target = adapter?.platform === event.platform ? adapter : void 0;
1301
+ const result = target === void 0 ? { ok: false, error: { code: "no_adapter", message: `no adapter for ${event.platform}` } } : refuseUnsupportedAttachments(target, outbound) ?? await target.sendMessage(outbound);
649
1302
  await this.hookExecutor.firePostOutbound({ event, outbound, result });
650
1303
  return result;
651
1304
  }
@@ -681,74 +1334,6 @@ var SessionRouter = class {
681
1334
  }
682
1335
  };
683
1336
 
684
- // src/text/dialect.ts
685
- var DIALECTS = {
686
- // WhatsApp emphasis is inline and single-character: *bold*, _italic_, ~strike~, ```mono```.
687
- whatsapp: { bold: "*", italic: "_", strike: "~", code: "```" },
688
- // LINE text messages carry no rich text at all — decoration is emoji-only. Markers are dropped.
689
- line: {},
690
- // SMS is plain text by definition of the medium.
691
- sms: {}
692
- };
693
- var PATTERN = /\*\*(?<bold>.+?)\*\*|~~(?<strike>.+?)~~|(?<![*\w])\*(?!\s)(?<italicStar>.+?)(?<!\s)\*(?!\*)|(?<![_\w])_(?!\s)(?<italicUnderscore>.+?)(?<!\s)_(?!\w)|`(?<code>.+?)`/gu;
694
- var GROUP_MARKERS = [
695
- ["bold", "bold"],
696
- ["strike", "strike"],
697
- ["italicStar", "italic"],
698
- ["italicUnderscore", "italic"],
699
- ["code", "code"]
700
- ];
701
- function toDialect(text, platform) {
702
- const dialect = DIALECTS[platform];
703
- if (dialect === void 0) return text;
704
- return rewriteMarkers(text, dialect);
705
- }
706
- function rewriteMarkers(text, dialect) {
707
- return text.replace(PATTERN, (matched, ...args) => {
708
- const groups = args.at(-1);
709
- if (groups === void 0) return matched;
710
- for (const [group, marker] of GROUP_MARKERS) {
711
- const content = groups[group];
712
- if (content === void 0) continue;
713
- const wrap = dialect[marker];
714
- return wrap === void 0 ? content : `${wrap}${content}${wrap}`;
715
- }
716
- return matched;
717
- });
718
- }
719
-
720
- // src/text/channel-rendering.ts
721
- var SLACK = { bold: "*", italic: "_", strike: "~", code: "`" };
722
- var STRIP = {};
723
- var identity = (text) => text;
724
- var translateWith = (dialect) => (text) => rewriteMarkers(text, dialect);
725
- var RENDERINGS = {
726
- whatsapp: { format: "plain", translate: translateWith(DIALECTS.whatsapp) },
727
- slack: { format: "markdown", translate: translateWith(SLACK) },
728
- discord: { format: "markdown", translate: identity },
729
- mattermost: { format: "markdown", translate: identity },
730
- teams: { format: "markdown", translate: identity },
731
- signal: { format: "markdown", translate: identity },
732
- line: { format: "plain", translate: translateWith(DIALECTS.line) },
733
- sms: { format: "plain", translate: translateWith(DIALECTS.sms) },
734
- telegram: { format: "plain", translate: translateWith(STRIP) },
735
- matrix: { format: "plain", translate: translateWith(STRIP) },
736
- email: { format: "plain", translate: translateWith(STRIP) },
737
- imessage: { format: "plain", translate: translateWith(STRIP) },
738
- google_chat: { format: "plain", translate: translateWith(STRIP) },
739
- irc: { format: "plain", translate: translateWith(STRIP) },
740
- nextcloud_talk: { format: "markdown", translate: identity }
741
- };
742
- function channelRendering(platform) {
743
- const rendering = Object.hasOwn(RENDERINGS, platform) ? RENDERINGS[platform] : void 0;
744
- if (rendering === void 0) {
745
- throw new RangeError(
746
- `channelRendering: unknown platform "${String(platform)}"; expected one of ${Object.keys(RENDERINGS).join(", ")}`
747
- );
748
- }
749
- return rendering;
750
- }
751
-
752
1337
  // src/text/chunk.ts
753
1338
  function searchBoundary(remaining, window, boundaries) {
754
1339
  let cut = window;
@@ -776,6 +1361,63 @@ function findCut(remaining, window, boundaries, lastResort, surrogateGuard) {
776
1361
  if (surrogateGuard) cut = guardSurrogate(remaining, cut);
777
1362
  return cut <= 0 ? window : cut;
778
1363
  }
1364
+ var isLineEnd = (ch) => ch === "\n" || ch === "\r";
1365
+ function startsTableRow(text, from) {
1366
+ let at = from;
1367
+ while (at < text.length && /^[^\S\r\n]$/.test(text[at] ?? "")) at += 1;
1368
+ return text[at] === "|";
1369
+ }
1370
+ function rowSafeCut(text, cut, window) {
1371
+ const start = tableRowStart(text, cut);
1372
+ if (start === void 0 || rowLength(text, start, cut, window) > window) return void 0;
1373
+ let end = start;
1374
+ while (end > 0 && isLineEnd(text[end - 1])) end -= 1;
1375
+ return end > 0 ? { end, start } : void 0;
1376
+ }
1377
+ function tableRowStart(text, cut) {
1378
+ if (cut >= text.length || isLineEnd(text[cut])) return void 0;
1379
+ let start = cut;
1380
+ while (start > 0 && !isLineEnd(text[start - 1])) start -= 1;
1381
+ return start > 0 && startsTableRow(text, start) ? start : void 0;
1382
+ }
1383
+ function rowLength(text, start, cut, window) {
1384
+ let rowEnd = cut;
1385
+ while (rowEnd < text.length && rowEnd - start <= window && !isLineEnd(text[rowEnd])) rowEnd += 1;
1386
+ return rowEnd - start;
1387
+ }
1388
+ function rowStep(remaining, cut, window) {
1389
+ const moved = rowSafeCut(remaining, cut, window);
1390
+ if (moved === void 0) return void 0;
1391
+ return { chunk: remaining.slice(0, moved.end), remaining: remaining.slice(moved.start) };
1392
+ }
1393
+ function stepBeforeFence(remaining, region) {
1394
+ let end = region.start;
1395
+ while (end > 0 && isLineEnd(remaining[end - 1])) end -= 1;
1396
+ if (end === 0) return void 0;
1397
+ return { chunk: remaining.slice(0, end), remaining: remaining.slice(region.start) };
1398
+ }
1399
+ function stepThroughFence(remaining, region, window, surrogateGuard) {
1400
+ const eol = openerEol(remaining, region);
1401
+ const room = window - region.closer.length - eol.length;
1402
+ if (room <= region.contentStart) return void 0;
1403
+ let at = remaining.lastIndexOf("\n", room);
1404
+ let rest = at + 1;
1405
+ if (at < region.contentStart) {
1406
+ at = surrogateGuard ? guardSurrogate(remaining, room) : room;
1407
+ rest = at;
1408
+ } else if (remaining[at - 1] === "\r") {
1409
+ at -= 1;
1410
+ }
1411
+ return {
1412
+ chunk: `${remaining.slice(0, at)}${eol}${region.closer}`,
1413
+ remaining: `${region.opener}${eol}${remaining.slice(rest)}`
1414
+ };
1415
+ }
1416
+ function fenceStep(remaining, cut, window, surrogateGuard) {
1417
+ const region = fenceAt(scanFences(remaining), cut);
1418
+ if (region === void 0) return void 0;
1419
+ return cut <= region.openerEnd ? stepBeforeFence(remaining, region) : stepThroughFence(remaining, region, window, surrogateGuard);
1420
+ }
779
1421
  function chunkText(text, options) {
780
1422
  const {
781
1423
  limit,
@@ -784,7 +1426,8 @@ function chunkText(text, options) {
784
1426
  lastResort = "window",
785
1427
  surrogateGuard = false,
786
1428
  stripLeading = /^\n+/,
787
- trimParts = false
1429
+ trimParts = false,
1430
+ keepTableRows = false
788
1431
  } = options;
789
1432
  assertPositiveInt("chunkText: limit", limit);
790
1433
  assertPositiveInt("chunkText: safeLimit", safeLimit);
@@ -796,11 +1439,16 @@ function chunkText(text, options) {
796
1439
  return finalize([text]);
797
1440
  }
798
1441
  const parts = [];
1442
+ const hasFence = scanFences(text).length > 0;
799
1443
  let remaining = text;
800
1444
  while (remaining.length > safeLimit) {
801
1445
  const cut = findCut(remaining, safeLimit, boundaries, lastResort, surrogateGuard);
802
- parts.push(remaining.slice(0, cut));
803
- remaining = remaining.slice(cut).replace(stripLeading, "");
1446
+ const step = (hasFence ? fenceStep(remaining, cut, safeLimit, surrogateGuard) : void 0) ?? (keepTableRows ? rowStep(remaining, cut, safeLimit) : void 0) ?? {
1447
+ chunk: remaining.slice(0, cut),
1448
+ remaining: remaining.slice(cut).replace(stripLeading, "")
1449
+ };
1450
+ parts.push(step.chunk);
1451
+ remaining = step.remaining;
804
1452
  }
805
1453
  if (remaining.length > 0) parts.push(remaining);
806
1454
  return finalize(parts);
@@ -811,6 +1459,8 @@ function chunkByGrapheme(text, options) {
811
1459
  assertPositiveInt("chunkByGrapheme: partLimit", partLimit);
812
1460
  if (text.length === 0) return [""];
813
1461
  if (text.length <= limit) return [text];
1462
+ const regions = scanFences(text);
1463
+ if (regions.length > 0) return chunkFencedByGrapheme(text, partLimit, regions);
814
1464
  const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
815
1465
  const parts = [];
816
1466
  let buf = "";
@@ -824,6 +1474,99 @@ function chunkByGrapheme(text, options) {
824
1474
  if (buf.length > 0) parts.push(buf);
825
1475
  return parts;
826
1476
  }
1477
+ function graphemeBoundaries(text) {
1478
+ const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
1479
+ const starts = Array.from(segmenter.segment(text), (s) => s.index);
1480
+ starts.push(text.length);
1481
+ return (pos, max) => {
1482
+ const after = starts.filter((b) => b > pos);
1483
+ const within = after.filter((b) => b <= max);
1484
+ return within.at(-1) ?? after[0] ?? text.length;
1485
+ };
1486
+ }
1487
+ function chunkFencedByGrapheme(text, partLimit, regions) {
1488
+ const boundaryUpTo = graphemeBoundaries(text);
1489
+ const parts = [];
1490
+ let pos = 0;
1491
+ let prefix = "";
1492
+ while (prefix.length + (text.length - pos) > partLimit) {
1493
+ const room = partLimit - prefix.length;
1494
+ const plain = boundaryUpTo(pos, pos + room);
1495
+ const region = fenceAt(regions, plain);
1496
+ const next = region === void 0 ? { cut: plain, suffix: "", reopen: "" } : fenceGraphemeCut(text, region, pos, plain, room, boundaryUpTo);
1497
+ parts.push(prefix + text.slice(pos, next.cut) + next.suffix);
1498
+ pos = next.cut;
1499
+ prefix = next.reopen;
1500
+ }
1501
+ parts.push(prefix + text.slice(pos));
1502
+ return parts;
1503
+ }
1504
+ function fenceGraphemeCut(text, region, pos, plain, room, boundaryUpTo) {
1505
+ const none = { cut: plain, suffix: "", reopen: "" };
1506
+ if (plain <= region.openerEnd) {
1507
+ return region.start > pos ? { ...none, cut: region.start } : none;
1508
+ }
1509
+ const eol = openerEol(text, region);
1510
+ const max = pos + room - region.closer.length - eol.length;
1511
+ const floor = Math.max(pos, region.contentStart);
1512
+ if (max <= floor) return none;
1513
+ let at = boundaryUpTo(pos, max);
1514
+ const nl = text.lastIndexOf("\n", at - 1);
1515
+ if (nl >= floor - 1 && nl + 1 > pos) at = nl + 1;
1516
+ if (at <= pos || at > max) return none;
1517
+ if (fenceAt([region], at) === void 0) return { ...none, cut: at };
1518
+ const closes = isLineEnd(text[at - 1]);
1519
+ return { cut: at, suffix: (closes ? "" : eol) + region.closer, reopen: region.opener + eol };
1520
+ }
1521
+
1522
+ // src/text/split-rows.ts
1523
+ var ROW_BLANK = /^[^\S\r\n]$/;
1524
+ function isLineEnd2(character) {
1525
+ return character === "\n" || character === "\r";
1526
+ }
1527
+ function startsTableRow2(text, from) {
1528
+ let at = from;
1529
+ while (at < text.length && ROW_BLANK.test(text[at] ?? "")) at += 1;
1530
+ return text[at] === "|";
1531
+ }
1532
+ function lineStartBefore(text, cut, partStart) {
1533
+ let at = cut;
1534
+ while (at > partStart && !isLineEnd2(text[at - 1])) at -= 1;
1535
+ return at;
1536
+ }
1537
+ function lineEndFrom(text, cut, bound) {
1538
+ let at = cut;
1539
+ while (at < text.length && at <= bound && !isLineEnd2(text[at])) at += 1;
1540
+ return at;
1541
+ }
1542
+ function rowSafeCut2(text, partStart, cut, partLimit) {
1543
+ const lineStart = lineStartBefore(text, cut, partStart);
1544
+ if (lineStart <= partStart || lineStart === cut) return cut;
1545
+ if (isLineEnd2(text[cut]) || !startsTableRow2(text, lineStart)) return cut;
1546
+ const lineEnd = lineEndFrom(text, cut, lineStart + partLimit);
1547
+ return lineEnd - lineStart <= partLimit ? lineStart : cut;
1548
+ }
1549
+ function graphemeCut(segments, start, partLimit) {
1550
+ const cut = start + partLimit;
1551
+ const segment = segments.containing(cut);
1552
+ if (segment === void 0 || segment.index >= cut) return cut;
1553
+ return segment.index > start ? segment.index : segment.index + segment.segment.length;
1554
+ }
1555
+ function splitKeepingRows(text, partLimit) {
1556
+ const segments = new Intl.Segmenter(void 0, { granularity: "grapheme" }).segment(text);
1557
+ const parts = [];
1558
+ let start = 0;
1559
+ while (text.length - start > partLimit) {
1560
+ const cut = rowSafeCut2(text, start, graphemeCut(segments, start, partLimit), partLimit);
1561
+ if (cut <= start) {
1562
+ throw new RangeError(`splitKeepingRows: no progress at offset ${start} of ${text.length}`);
1563
+ }
1564
+ parts.push(text.slice(start, cut));
1565
+ start = cut;
1566
+ }
1567
+ if (start < text.length) parts.push(text.slice(start));
1568
+ return parts;
1569
+ }
827
1570
 
828
1571
  // src/webhook/express-server.ts
829
1572
  async function loadPeer(load, onMissing) {
@@ -941,7 +1684,9 @@ exports.GatewayConfigurationError = GatewayConfigurationError;
941
1684
  exports.GatewayLifecycleError = GatewayLifecycleError;
942
1685
  exports.GatewayRunner = GatewayRunner;
943
1686
  exports.HookExecutor = HookExecutor;
1687
+ exports.SeenIds = SeenIds;
944
1688
  exports.SessionRouter = SessionRouter;
1689
+ exports.WeixinAdapterBase = WeixinAdapterBase;
945
1690
  exports.channelRendering = channelRendering;
946
1691
  exports.chunkByGrapheme = chunkByGrapheme;
947
1692
  exports.chunkText = chunkText;
@@ -950,8 +1695,11 @@ exports.defaultStrategy = defaultStrategy;
950
1695
  exports.listenerLifecycle = listenerLifecycle;
951
1696
  exports.loadPeer = loadPeer;
952
1697
  exports.maskShapes = maskShapes;
1698
+ exports.parseFlatXml = parseFlatXml;
953
1699
  exports.rawBodyCapture = rawBodyCapture;
954
1700
  exports.redactSecrets = redactSecrets;
1701
+ exports.scanFences = scanFences;
1702
+ exports.splitKeepingRows = splitKeepingRows;
955
1703
  exports.toDialect = toDialect;
956
1704
  //# sourceMappingURL=index.cjs.map
957
1705
  //# sourceMappingURL=index.cjs.map