@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/CHANGELOG.md +73 -0
- package/README.md +6 -0
- package/dist/index.cjs +605 -318
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +298 -25
- package/dist/index.d.ts +298 -25
- package/dist/index.js +604 -319
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -2,6 +2,219 @@
|
|
|
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
|
+
qq: { format: "plain", translate: translateWith(STRIP) },
|
|
205
|
+
x: { format: "plain", translate: translateWith(STRIP) },
|
|
206
|
+
raft: { format: "plain", translate: translateWith(STRIP) }
|
|
207
|
+
};
|
|
208
|
+
function channelRendering(platform) {
|
|
209
|
+
const rendering = Object.hasOwn(RENDERINGS, platform) ? RENDERINGS[platform] : void 0;
|
|
210
|
+
if (rendering === void 0) {
|
|
211
|
+
throw new RangeError(
|
|
212
|
+
`channelRendering: unknown platform "${String(platform)}"; expected one of ${Object.keys(RENDERINGS).join(", ")}`
|
|
213
|
+
);
|
|
214
|
+
}
|
|
215
|
+
return rendering;
|
|
216
|
+
}
|
|
217
|
+
|
|
5
218
|
// src/adapter/base.ts
|
|
6
219
|
var BasePlatformAdapter = class {
|
|
7
220
|
/**
|
|
@@ -28,6 +241,56 @@ var BasePlatformAdapter = class {
|
|
|
28
241
|
}
|
|
29
242
|
return "ok";
|
|
30
243
|
}
|
|
244
|
+
/** The handler {@link subscribe} holds; `undefined` while nobody is subscribed. */
|
|
245
|
+
subscribedHandler;
|
|
246
|
+
/** The body of {@link onInbound}: replace the handler, and unsubscribe only if it is still the one held. */
|
|
247
|
+
subscribe(handler) {
|
|
248
|
+
this.subscribedHandler = handler;
|
|
249
|
+
return () => {
|
|
250
|
+
if (this.subscribedHandler === handler) this.subscribedHandler = void 0;
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
/** The body of {@link deliver} for an adapter that subscribed through {@link subscribe}. */
|
|
254
|
+
deliverInbound(event) {
|
|
255
|
+
return this.runHandler(this.subscribedHandler, event);
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Dispatch a webhook event once: `duplicate` when `seen` holds its id, `no_handler` when nobody
|
|
259
|
+
* subscribed (the id is then NOT remembered, so a redelivery is handled), otherwise remember the
|
|
260
|
+
* id and run the handler. A handler's throw is also logged under `label`.
|
|
261
|
+
*/
|
|
262
|
+
async dispatchOnce(seen, event, label) {
|
|
263
|
+
if (seen.has(event.id)) return "duplicate";
|
|
264
|
+
if (this.subscribedHandler === void 0) return "no_handler";
|
|
265
|
+
seen.add(event.id);
|
|
266
|
+
const outcome = await this.runHandler(this.subscribedHandler, event);
|
|
267
|
+
if (outcome === "handler_threw") process.stderr.write(`[${label}] handler threw
|
|
268
|
+
`);
|
|
269
|
+
return outcome;
|
|
270
|
+
}
|
|
271
|
+
/** `out.text`, translated to the platform's markup when `out.format` is `markdown`. */
|
|
272
|
+
outboundText(out) {
|
|
273
|
+
return out.format === "markdown" ? channelRendering(this.platform).translate(out.text) : out.text;
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* The local checks every text-only `sendMessage` makes before a request, in this order:
|
|
277
|
+
* `empty_text`, `not_connected`, then `invalid_channel` when `channel.valid` rejects the id.
|
|
278
|
+
* Returns the refusal, or `undefined` when the message may be sent.
|
|
279
|
+
*/
|
|
280
|
+
refuseUnsendable(out, check) {
|
|
281
|
+
const refuse = (code, message) => ({
|
|
282
|
+
ok: false,
|
|
283
|
+
error: { code, message }
|
|
284
|
+
});
|
|
285
|
+
if (out.text.length === 0) return refuse("empty_text", "outbound text is empty");
|
|
286
|
+
if (!check.connected) {
|
|
287
|
+
return refuse("not_connected", `${check.className}.connect() has not succeeded`);
|
|
288
|
+
}
|
|
289
|
+
if (check.channel !== void 0 && !check.channel.valid(out.channel.id)) {
|
|
290
|
+
return refuse("invalid_channel", check.channel.message);
|
|
291
|
+
}
|
|
292
|
+
return void 0;
|
|
293
|
+
}
|
|
31
294
|
/**
|
|
32
295
|
* Whether {@link editMessage} can replace the text of a message this adapter sent.
|
|
33
296
|
*
|
|
@@ -65,6 +328,25 @@ var BasePlatformAdapter = class {
|
|
|
65
328
|
}
|
|
66
329
|
};
|
|
67
330
|
}
|
|
331
|
+
/**
|
|
332
|
+
* React to an inbound message with an emoji (for example 👀 as an acknowledgement).
|
|
333
|
+
*
|
|
334
|
+
* Returns `{ ok: true, messageId }` on success and a `SendResult` error otherwise; it never
|
|
335
|
+
* throws on platform errors. `channelId` is the channel the message is in and `messageId` the
|
|
336
|
+
* id the inbound event carried.
|
|
337
|
+
*
|
|
338
|
+
* Default: resolves `{ ok: false, error: { code: "react_unsupported" } }` and makes no
|
|
339
|
+
* platform call.
|
|
340
|
+
*/
|
|
341
|
+
async react(_channelId, _messageId, _emoji) {
|
|
342
|
+
return {
|
|
343
|
+
ok: false,
|
|
344
|
+
error: {
|
|
345
|
+
code: "react_unsupported",
|
|
346
|
+
message: `${this.platform} adapter cannot react to a message`
|
|
347
|
+
}
|
|
348
|
+
};
|
|
349
|
+
}
|
|
68
350
|
/** Lifecycle: emit a typing indicator. Default: noop. */
|
|
69
351
|
async startTyping(_channelId) {
|
|
70
352
|
}
|
|
@@ -73,6 +355,184 @@ var BasePlatformAdapter = class {
|
|
|
73
355
|
}
|
|
74
356
|
};
|
|
75
357
|
|
|
358
|
+
// src/text/seen-ids.ts
|
|
359
|
+
var DEFAULT_LIMIT = 1e3;
|
|
360
|
+
var SeenIds = class {
|
|
361
|
+
/** @param limit the most ids held at once; the oldest is forgotten when one more arrives */
|
|
362
|
+
constructor(limit = DEFAULT_LIMIT) {
|
|
363
|
+
this.limit = limit;
|
|
364
|
+
}
|
|
365
|
+
limit;
|
|
366
|
+
ids = /* @__PURE__ */ new Set();
|
|
367
|
+
/**
|
|
368
|
+
* Record `id`.
|
|
369
|
+
*
|
|
370
|
+
* @returns `true` when the id was new, `false` when it was already held
|
|
371
|
+
*/
|
|
372
|
+
add(id) {
|
|
373
|
+
if (this.ids.has(id)) return false;
|
|
374
|
+
this.ids.add(id);
|
|
375
|
+
if (this.ids.size > this.limit) {
|
|
376
|
+
const oldest = this.ids.values().next().value;
|
|
377
|
+
if (oldest !== void 0) this.ids.delete(oldest);
|
|
378
|
+
}
|
|
379
|
+
return true;
|
|
380
|
+
}
|
|
381
|
+
/** Whether `id` is held. */
|
|
382
|
+
has(id) {
|
|
383
|
+
return this.ids.has(id);
|
|
384
|
+
}
|
|
385
|
+
/** How many ids are held. */
|
|
386
|
+
get size() {
|
|
387
|
+
return this.ids.size;
|
|
388
|
+
}
|
|
389
|
+
};
|
|
390
|
+
|
|
391
|
+
// src/adapter/weixin-xml.ts
|
|
392
|
+
function parseFlatXml(xml) {
|
|
393
|
+
const out = {};
|
|
394
|
+
const tag = /<([A-Za-z][A-Za-z0-9]*)>(?:<!\[CDATA\[([\s\S]*?)\]\]>|([^<]*))<\/\1>/g;
|
|
395
|
+
for (const m of xml.matchAll(tag)) {
|
|
396
|
+
const name = m[1];
|
|
397
|
+
if (name !== void 0 && name !== "xml") out[name] = m[2] ?? decodeEntities(m[3] ?? "");
|
|
398
|
+
}
|
|
399
|
+
return out;
|
|
400
|
+
}
|
|
401
|
+
function decodeEntities(s) {
|
|
402
|
+
return s.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, "&");
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// src/adapter/weixin-base.ts
|
|
406
|
+
var REQUEST_TIMEOUT_MS = 3e4;
|
|
407
|
+
var TOKEN_MARGIN_MS = 6e4;
|
|
408
|
+
var defaultFetch = async (url, init) => {
|
|
409
|
+
const res = await fetch(url, { ...init, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
|
|
410
|
+
return { status: res.status, text: () => res.text() };
|
|
411
|
+
};
|
|
412
|
+
function weixinMessageOf(err) {
|
|
413
|
+
return err instanceof Error ? err.message : String(err);
|
|
414
|
+
}
|
|
415
|
+
function weixinAck(reason) {
|
|
416
|
+
return { status: 200, body: "success", reason };
|
|
417
|
+
}
|
|
418
|
+
var WeixinAdapterBase = class extends BasePlatformAdapter {
|
|
419
|
+
cfg;
|
|
420
|
+
doFetch;
|
|
421
|
+
connected = false;
|
|
422
|
+
accessToken;
|
|
423
|
+
seen = new SeenIds();
|
|
424
|
+
constructor(cfg) {
|
|
425
|
+
super();
|
|
426
|
+
this.cfg = cfg;
|
|
427
|
+
this.doFetch = cfg.fetch ?? defaultFetch;
|
|
428
|
+
}
|
|
429
|
+
async connect() {
|
|
430
|
+
if (this.connected) return true;
|
|
431
|
+
try {
|
|
432
|
+
await this.token(true);
|
|
433
|
+
this.connected = true;
|
|
434
|
+
return true;
|
|
435
|
+
} catch (err) {
|
|
436
|
+
process.stderr.write(`[${this.cfg.label}] connect failed: ${weixinMessageOf(err)}
|
|
437
|
+
`);
|
|
438
|
+
return false;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
async disconnect() {
|
|
442
|
+
this.connected = false;
|
|
443
|
+
this.accessToken = void 0;
|
|
444
|
+
}
|
|
445
|
+
/** Send text only; a subclass's `sendMessage` refuses attachments first, then calls this. */
|
|
446
|
+
async sendText(out) {
|
|
447
|
+
if (out.text.length === 0) {
|
|
448
|
+
return { ok: false, error: { code: "empty_text", message: "outbound text is empty" } };
|
|
449
|
+
}
|
|
450
|
+
if (!this.connected) {
|
|
451
|
+
return {
|
|
452
|
+
ok: false,
|
|
453
|
+
error: {
|
|
454
|
+
code: "not_connected",
|
|
455
|
+
message: `${this.cfg.className}.connect() has not succeeded`
|
|
456
|
+
}
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
if (out.channel.id === "") {
|
|
460
|
+
return {
|
|
461
|
+
ok: false,
|
|
462
|
+
error: { code: "invalid_channel", message: `channel.id must be ${this.cfg.userNoun}` }
|
|
463
|
+
};
|
|
464
|
+
}
|
|
465
|
+
return this.sendParts(out);
|
|
466
|
+
}
|
|
467
|
+
async sendParts(out) {
|
|
468
|
+
const failed = `${this.platform}_send_failed`;
|
|
469
|
+
try {
|
|
470
|
+
for (const content of this.split(this.outboundText(out))) {
|
|
471
|
+
const token = await this.token(false);
|
|
472
|
+
const req = this.sendRequest(token, out.channel.id, content);
|
|
473
|
+
const body = await this.call("POST", req.path, req.payload);
|
|
474
|
+
if (body.errcode !== 0) {
|
|
475
|
+
return {
|
|
476
|
+
ok: false,
|
|
477
|
+
error: {
|
|
478
|
+
code: failed,
|
|
479
|
+
message: `${this.cfg.brand} error ${String(body.errcode)}: ${String(body.errmsg)}`
|
|
480
|
+
}
|
|
481
|
+
};
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
} catch (err) {
|
|
485
|
+
return { ok: false, error: { code: failed, message: weixinMessageOf(err) } };
|
|
486
|
+
}
|
|
487
|
+
return { ok: true, messageId: "" };
|
|
488
|
+
}
|
|
489
|
+
onInbound(handler) {
|
|
490
|
+
return this.subscribe(handler);
|
|
491
|
+
}
|
|
492
|
+
/** Deliver an event that arrived out of band, through `runHandler`. */
|
|
493
|
+
async deliver(event) {
|
|
494
|
+
return this.deliverInbound(event);
|
|
495
|
+
}
|
|
496
|
+
/** Turn a plain (decrypted) XML body into one event, dispatch it and answer the webhook. */
|
|
497
|
+
async handleMessage(xml) {
|
|
498
|
+
const event = this.toEvent(parseFlatXml(xml));
|
|
499
|
+
if (event === "skip") return weixinAck("not a text message");
|
|
500
|
+
if (event === void 0) return { status: 400, body: "", reason: "incomplete" };
|
|
501
|
+
const outcome = await this.dispatchOnce(this.seen, event, this.cfg.label);
|
|
502
|
+
if (outcome === "no_handler") return { status: 503, body: "", reason: "no handler subscribed" };
|
|
503
|
+
return weixinAck(outcome);
|
|
504
|
+
}
|
|
505
|
+
async token(force) {
|
|
506
|
+
const cached = this.accessToken;
|
|
507
|
+
if (!force && cached !== void 0 && cached.expiresAt - TOKEN_MARGIN_MS > Date.now()) {
|
|
508
|
+
return cached.value;
|
|
509
|
+
}
|
|
510
|
+
const body = await this.call("GET", this.tokenPath());
|
|
511
|
+
if (body.errcode !== void 0 && body.errcode !== 0) {
|
|
512
|
+
throw new Error(`token answered error ${String(body.errcode)}: ${String(body.errmsg)}`);
|
|
513
|
+
}
|
|
514
|
+
if (!body.access_token) throw new Error("token answer has no access_token");
|
|
515
|
+
this.accessToken = {
|
|
516
|
+
value: body.access_token,
|
|
517
|
+
expiresAt: Date.now() + (body.expires_in ?? 7200) * 1e3
|
|
518
|
+
};
|
|
519
|
+
return body.access_token;
|
|
520
|
+
}
|
|
521
|
+
async call(method, path, payload) {
|
|
522
|
+
const res = await this.doFetch((this.cfg.apiBase ?? this.cfg.defaultBase) + path, {
|
|
523
|
+
method,
|
|
524
|
+
headers: { "Content-Type": "application/json" },
|
|
525
|
+
...payload === void 0 ? {} : { body: JSON.stringify(payload) }
|
|
526
|
+
});
|
|
527
|
+
const text = await res.text();
|
|
528
|
+
try {
|
|
529
|
+
return JSON.parse(text);
|
|
530
|
+
} catch {
|
|
531
|
+
throw new Error(`${this.cfg.brand} answered HTTP ${res.status} with a non-JSON body`);
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
};
|
|
535
|
+
|
|
76
536
|
// src/errors/config-error.ts
|
|
77
537
|
var GatewayConfigurationError = class extends Error {
|
|
78
538
|
name = "GatewayConfigurationError";
|
|
@@ -212,6 +672,35 @@ var GatewayLifecycleError = class extends Error {
|
|
|
212
672
|
this.code = opts.code;
|
|
213
673
|
}
|
|
214
674
|
};
|
|
675
|
+
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.
|
|
676
|
+
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.
|
|
677
|
+
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.
|
|
678
|
+
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.
|
|
679
|
+
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.
|
|
680
|
+
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.
|
|
681
|
+
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.
|
|
682
|
+
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.
|
|
683
|
+
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.
|
|
684
|
+
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.
|
|
685
|
+
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.
|
|
686
|
+
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.
|
|
687
|
+
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.
|
|
688
|
+
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.
|
|
689
|
+
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.
|
|
690
|
+
gateway-mattermost \`accessToken\` :: 26 lowercase alphanumerics, which is exactly a lowercase ULID \u2014 the shape of most trace ids.
|
|
691
|
+
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.
|
|
692
|
+
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.
|
|
693
|
+
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.
|
|
694
|
+
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.
|
|
695
|
+
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.
|
|
696
|
+
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=...\`.
|
|
697
|
+
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.`;
|
|
698
|
+
function parseUncovered(table) {
|
|
699
|
+
return table.split("\n").map((row) => {
|
|
700
|
+
const [field = "", why = ""] = row.split(" :: ");
|
|
701
|
+
return { field, why };
|
|
702
|
+
});
|
|
703
|
+
}
|
|
215
704
|
var CREDENTIAL_SHAPES = {
|
|
216
705
|
covered: [
|
|
217
706
|
{
|
|
@@ -250,76 +739,7 @@ var CREDENTIAL_SHAPES = {
|
|
|
250
739
|
alsoMatches: "nothing plausible \u2014 `nsec1` is NIP-19's prefix for a secret key"
|
|
251
740
|
}
|
|
252
741
|
],
|
|
253
|
-
uncovered:
|
|
254
|
-
{
|
|
255
|
-
field: "gateway-buzz `token`",
|
|
256
|
-
why: "a Buzz bot token with no fixed shape this package could confirm. It travels only in Authorization headers, which the adapter never logs."
|
|
257
|
-
},
|
|
258
|
-
{
|
|
259
|
-
field: "gateway-clickclack `token`",
|
|
260
|
-
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
|
-
},
|
|
262
|
-
{
|
|
263
|
-
field: "gateway-zalo-personal `credentials`",
|
|
264
|
-
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."
|
|
265
|
-
},
|
|
266
|
-
{
|
|
267
|
-
field: "gateway-twitch `accessToken`",
|
|
268
|
-
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."
|
|
269
|
-
},
|
|
270
|
-
{
|
|
271
|
-
field: "gateway-tlon-urbit `code`",
|
|
272
|
-
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."
|
|
273
|
-
},
|
|
274
|
-
{
|
|
275
|
-
field: "gateway-synology-chat `botToken` and `incomingUrl`",
|
|
276
|
-
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."
|
|
277
|
-
},
|
|
278
|
-
{
|
|
279
|
-
field: "gateway-feishu-lark `appSecret`",
|
|
280
|
-
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."
|
|
281
|
-
},
|
|
282
|
-
{
|
|
283
|
-
field: "gateway-nostr `secretKey` (64-hex form)",
|
|
284
|
-
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."
|
|
285
|
-
},
|
|
286
|
-
{
|
|
287
|
-
field: "gateway-sms `authToken` (Twilio), gateway-line `channelSecret`",
|
|
288
|
-
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."
|
|
289
|
-
},
|
|
290
|
-
{
|
|
291
|
-
field: "gateway-mattermost `accessToken`",
|
|
292
|
-
why: "26 lowercase alphanumerics, which is exactly a lowercase ULID \u2014 the shape of most trace ids."
|
|
293
|
-
},
|
|
294
|
-
{
|
|
295
|
-
field: "gateway-email `password`, gateway-sms `apiSecret` and `signatureSecret` (Vonage)",
|
|
296
|
-
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."
|
|
297
|
-
},
|
|
298
|
-
{
|
|
299
|
-
field: "gateway-slack `botToken`",
|
|
300
|
-
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."
|
|
301
|
-
},
|
|
302
|
-
{
|
|
303
|
-
field: "gateway-whatsapp `appSecret`",
|
|
304
|
-
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."
|
|
305
|
-
},
|
|
306
|
-
{
|
|
307
|
-
field: "gateway-nextcloud-talk `secret`",
|
|
308
|
-
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."
|
|
309
|
-
},
|
|
310
|
-
{
|
|
311
|
-
field: "gateway-irc `password` and `saslPassword`",
|
|
312
|
-
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."
|
|
313
|
-
},
|
|
314
|
-
{
|
|
315
|
-
field: "gateway-google-chat `privateKey`",
|
|
316
|
-
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=...`."
|
|
317
|
-
},
|
|
318
|
-
{
|
|
319
|
-
field: "gateway-line `channelAccessToken`, gateway-sms `authToken` (Plivo)",
|
|
320
|
-
why: "long base64 runs with no prefix, indistinguishable from any encoded blob a platform library puts in an error message."
|
|
321
|
-
}
|
|
322
|
-
]
|
|
742
|
+
uncovered: parseUncovered(UNCOVERED_TABLE)
|
|
323
743
|
};
|
|
324
744
|
function maskShapes(text) {
|
|
325
745
|
let out = text;
|
|
@@ -429,12 +849,36 @@ var HookExecutor = class {
|
|
|
429
849
|
|
|
430
850
|
// src/runner/gateway-runner.ts
|
|
431
851
|
var DEFAULT_DRAIN_MS = 1e4;
|
|
852
|
+
var TYPING_RENEW_MS = 4e3;
|
|
853
|
+
function keepTyping(adapter, channelId) {
|
|
854
|
+
const swallow = (p) => p.catch(() => void 0);
|
|
855
|
+
const start = () => swallow(Promise.resolve().then(() => adapter.startTyping(channelId)));
|
|
856
|
+
void start();
|
|
857
|
+
const timer = setInterval(() => void start(), TYPING_RENEW_MS);
|
|
858
|
+
timer.unref();
|
|
859
|
+
return async () => {
|
|
860
|
+
clearInterval(timer);
|
|
861
|
+
await swallow(Promise.resolve().then(() => adapter.stopTyping(channelId)));
|
|
862
|
+
};
|
|
863
|
+
}
|
|
432
864
|
var DEFAULT_COMMAND_PREFIXES = ["/"];
|
|
433
865
|
function connectFailureReason(outcome) {
|
|
434
866
|
if (outcome.status === "fulfilled") return "connect returned false";
|
|
435
867
|
const message = outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason);
|
|
436
868
|
return redactSecrets(message);
|
|
437
869
|
}
|
|
870
|
+
function isTerminalConnectError(err) {
|
|
871
|
+
if (typeof err !== "object" || err === null) return false;
|
|
872
|
+
const e = err;
|
|
873
|
+
for (const key of ["status", "statusCode", "httpStatus"]) {
|
|
874
|
+
if (e[key] === 401 || e[key] === 403) return true;
|
|
875
|
+
}
|
|
876
|
+
if (e.errcode === "M_UNKNOWN_TOKEN" || e.errcode === "M_FORBIDDEN") return true;
|
|
877
|
+
const message = typeof e.message === "string" ? e.message : "";
|
|
878
|
+
return /\b(?:http|status(?: code)?)\s*:?\s*(?:401|403)\b|unauthori[sz]ed|forbidden/i.test(
|
|
879
|
+
message
|
|
880
|
+
);
|
|
881
|
+
}
|
|
438
882
|
async function releaseAdapters(adapters, during) {
|
|
439
883
|
await Promise.all(
|
|
440
884
|
adapters.map(async (a) => {
|
|
@@ -465,6 +909,7 @@ var GatewayRunner = class {
|
|
|
465
909
|
/** The start that has not settled yet, shared by every overlapping `start()` call. */
|
|
466
910
|
startInFlight;
|
|
467
911
|
stopped = false;
|
|
912
|
+
retryTimers = /* @__PURE__ */ new Set();
|
|
468
913
|
/**
|
|
469
914
|
* Register a slash command. Match rule (EC-A): text === "/" + name
|
|
470
915
|
* OR text.startsWith("/" + name + " ") OR text.startsWith("/" + name + "@").
|
|
@@ -523,12 +968,80 @@ var GatewayRunner = class {
|
|
|
523
968
|
this.startResult = { connected: [], failed: result.failed };
|
|
524
969
|
return this.startResult;
|
|
525
970
|
}
|
|
526
|
-
this.wireInbound(result.connected);
|
|
527
|
-
this.startResult = {
|
|
528
|
-
connected: result.connected.map((a) => a.platform),
|
|
529
|
-
failed: result.failed
|
|
530
|
-
};
|
|
531
|
-
|
|
971
|
+
this.wireInbound(result.connected);
|
|
972
|
+
this.startResult = {
|
|
973
|
+
connected: result.connected.map((a) => a.platform),
|
|
974
|
+
failed: result.failed
|
|
975
|
+
};
|
|
976
|
+
for (const adapter of result.retryable) this.scheduleReconnect(adapter, 1);
|
|
977
|
+
return this.startResult;
|
|
978
|
+
}
|
|
979
|
+
/** Retry one adapter after its backoff delay; reschedules itself until it connects or gives up. */
|
|
980
|
+
scheduleReconnect(adapter, attempt) {
|
|
981
|
+
const policy = this.opts.reconnect;
|
|
982
|
+
if (policy === void 0 || this.stopped) return;
|
|
983
|
+
if (policy.maxAttempts !== void 0 && attempt > policy.maxAttempts) {
|
|
984
|
+
process.stderr.write(
|
|
985
|
+
`[gateway] adapter "${adapter.platform}" gave up reconnecting after ${policy.maxAttempts} attempts
|
|
986
|
+
`
|
|
987
|
+
);
|
|
988
|
+
return;
|
|
989
|
+
}
|
|
990
|
+
const delay = Math.min(
|
|
991
|
+
(policy.initialDelayMs ?? 1e3) * (policy.factor ?? 2) ** (attempt - 1),
|
|
992
|
+
policy.maxDelayMs ?? 6e4
|
|
993
|
+
);
|
|
994
|
+
const timer = setTimeout(() => {
|
|
995
|
+
this.retryTimers.delete(timer);
|
|
996
|
+
void this.reconnectOnce(adapter, attempt);
|
|
997
|
+
}, delay);
|
|
998
|
+
timer.unref();
|
|
999
|
+
this.retryTimers.add(timer);
|
|
1000
|
+
process.stderr.write(
|
|
1001
|
+
`[gateway] adapter "${adapter.platform}" reconnect attempt ${attempt} in ${delay}ms
|
|
1002
|
+
`
|
|
1003
|
+
);
|
|
1004
|
+
}
|
|
1005
|
+
async reconnectOnce(adapter, attempt) {
|
|
1006
|
+
if (this.stopped) return;
|
|
1007
|
+
try {
|
|
1008
|
+
if (await adapter.connect()) {
|
|
1009
|
+
if (this.stopped) {
|
|
1010
|
+
await releaseAdapters([adapter], "releasing a reconnect that stop() overtook");
|
|
1011
|
+
return;
|
|
1012
|
+
}
|
|
1013
|
+
this.wireInbound([adapter]);
|
|
1014
|
+
const prev = this.startResult ?? { connected: [], failed: [] };
|
|
1015
|
+
this.startResult = {
|
|
1016
|
+
connected: [...prev.connected, adapter.platform],
|
|
1017
|
+
failed: prev.failed.filter((f) => f.platform !== adapter.platform)
|
|
1018
|
+
};
|
|
1019
|
+
process.stderr.write(
|
|
1020
|
+
`[gateway] adapter "${adapter.platform}" connected on attempt ${attempt}
|
|
1021
|
+
`
|
|
1022
|
+
);
|
|
1023
|
+
return;
|
|
1024
|
+
}
|
|
1025
|
+
process.stderr.write(
|
|
1026
|
+
`[gateway] adapter "${adapter.platform}" refused to connect; not retrying
|
|
1027
|
+
`
|
|
1028
|
+
);
|
|
1029
|
+
return;
|
|
1030
|
+
} catch (err) {
|
|
1031
|
+
const reason = connectFailureReason({ status: "rejected", reason: err });
|
|
1032
|
+
if (isTerminalConnectError(err)) {
|
|
1033
|
+
process.stderr.write(
|
|
1034
|
+
`[gateway] adapter "${adapter.platform}" credentials rejected: ${reason}; not retrying
|
|
1035
|
+
`
|
|
1036
|
+
);
|
|
1037
|
+
return;
|
|
1038
|
+
}
|
|
1039
|
+
process.stderr.write(
|
|
1040
|
+
`[gateway] adapter "${adapter.platform}" reconnect attempt ${attempt} failed: ${reason}
|
|
1041
|
+
`
|
|
1042
|
+
);
|
|
1043
|
+
}
|
|
1044
|
+
this.scheduleReconnect(adapter, attempt + 1);
|
|
532
1045
|
}
|
|
533
1046
|
/**
|
|
534
1047
|
* All or nothing: when any connect fails, disconnect the adapters that did connect, then rethrow
|
|
@@ -559,7 +1072,7 @@ var GatewayRunner = class {
|
|
|
559
1072
|
await releaseAdapters(connected, "rolling back a failed start");
|
|
560
1073
|
throw failures[0];
|
|
561
1074
|
}
|
|
562
|
-
return { connected: [...adapters], failed: [] };
|
|
1075
|
+
return { connected: [...adapters], failed: [], retryable: [] };
|
|
563
1076
|
}
|
|
564
1077
|
/**
|
|
565
1078
|
* Connect every adapter and keep the ones that connected. The `async` wrapper turns a
|
|
@@ -571,12 +1084,18 @@ var GatewayRunner = class {
|
|
|
571
1084
|
const settled = await Promise.allSettled(adapters.map(async (a) => a.connect()));
|
|
572
1085
|
const connected = [];
|
|
573
1086
|
const failed = [];
|
|
1087
|
+
const retryable = [];
|
|
574
1088
|
settled.forEach((outcome, i) => {
|
|
575
1089
|
const adapter = adapters[i];
|
|
576
1090
|
if (outcome.status === "fulfilled" && outcome.value) connected.push(adapter);
|
|
577
|
-
else
|
|
1091
|
+
else {
|
|
1092
|
+
failed.push({ platform: adapter.platform, reason: connectFailureReason(outcome) });
|
|
1093
|
+
if (outcome.status === "rejected" && !isTerminalConnectError(outcome.reason)) {
|
|
1094
|
+
retryable.push(adapter);
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
578
1097
|
});
|
|
579
|
-
return { connected, failed };
|
|
1098
|
+
return { connected, failed, retryable };
|
|
580
1099
|
}
|
|
581
1100
|
wireInbound(adapters) {
|
|
582
1101
|
for (const a of adapters) {
|
|
@@ -607,6 +1126,8 @@ var GatewayRunner = class {
|
|
|
607
1126
|
}
|
|
608
1127
|
}
|
|
609
1128
|
this.unsubs.length = 0;
|
|
1129
|
+
for (const t of this.retryTimers) clearTimeout(t);
|
|
1130
|
+
this.retryTimers.clear();
|
|
610
1131
|
const drainMs = this.opts.drainTimeoutMs ?? DEFAULT_DRAIN_MS;
|
|
611
1132
|
if (this.inflight.size > 0) {
|
|
612
1133
|
let timer;
|
|
@@ -650,12 +1171,15 @@ var GatewayRunner = class {
|
|
|
650
1171
|
const slashHandler = this.matchSlashCommand(event);
|
|
651
1172
|
const handler = slashHandler ?? this.opts.handler;
|
|
652
1173
|
const work = (async () => {
|
|
1174
|
+
const stopTyping = keepTyping(adapter, event.channel.id);
|
|
653
1175
|
try {
|
|
654
1176
|
await handler(event, ctx);
|
|
655
1177
|
} catch (err) {
|
|
656
1178
|
await this.hookExecutor.fireOnError({ event, error: err });
|
|
657
1179
|
process.stderr.write(`[gateway] handler error: ${redactSecrets(err.message)}
|
|
658
1180
|
`);
|
|
1181
|
+
} finally {
|
|
1182
|
+
await stopTyping();
|
|
659
1183
|
}
|
|
660
1184
|
})();
|
|
661
1185
|
this.inflight.add(work);
|
|
@@ -756,212 +1280,6 @@ var SessionRouter = class {
|
|
|
756
1280
|
}
|
|
757
1281
|
};
|
|
758
1282
|
|
|
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
1283
|
// src/text/chunk.ts
|
|
966
1284
|
function searchBoundary(remaining, window, boundaries) {
|
|
967
1285
|
let cut = window;
|
|
@@ -1147,39 +1465,6 @@ function fenceGraphemeCut(text, region, pos, plain, room, boundaryUpTo) {
|
|
|
1147
1465
|
return { cut: at, suffix: (closes ? "" : eol) + region.closer, reopen: region.opener + eol };
|
|
1148
1466
|
}
|
|
1149
1467
|
|
|
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
1468
|
// src/text/split-rows.ts
|
|
1184
1469
|
var ROW_BLANK = /^[^\S\r\n]$/;
|
|
1185
1470
|
function isLineEnd2(character) {
|
|
@@ -1347,6 +1632,7 @@ exports.GatewayRunner = GatewayRunner;
|
|
|
1347
1632
|
exports.HookExecutor = HookExecutor;
|
|
1348
1633
|
exports.SeenIds = SeenIds;
|
|
1349
1634
|
exports.SessionRouter = SessionRouter;
|
|
1635
|
+
exports.WeixinAdapterBase = WeixinAdapterBase;
|
|
1350
1636
|
exports.channelRendering = channelRendering;
|
|
1351
1637
|
exports.chunkByGrapheme = chunkByGrapheme;
|
|
1352
1638
|
exports.chunkText = chunkText;
|
|
@@ -1355,6 +1641,7 @@ exports.defaultStrategy = defaultStrategy;
|
|
|
1355
1641
|
exports.listenerLifecycle = listenerLifecycle;
|
|
1356
1642
|
exports.loadPeer = loadPeer;
|
|
1357
1643
|
exports.maskShapes = maskShapes;
|
|
1644
|
+
exports.parseFlatXml = parseFlatXml;
|
|
1358
1645
|
exports.rawBodyCapture = rawBodyCapture;
|
|
1359
1646
|
exports.redactSecrets = redactSecrets;
|
|
1360
1647
|
exports.scanFences = scanFences;
|