@theokit/gateway 0.14.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +51 -0
- package/README.md +6 -0
- package/dist/index.cjs +589 -248
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +256 -25
- package/dist/index.d.ts +256 -25
- package/dist/index.js +588 -249
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,216 @@
|
|
|
1
1
|
import { Security } from '@theokit/sdk';
|
|
2
2
|
|
|
3
|
+
// src/text/fence.ts
|
|
4
|
+
var MAY_FENCE = /^ {0,3}(?:`{3}|~{3})/m;
|
|
5
|
+
var OPENING = /^ {0,3}(`{3,}|~{3,})(.*)$/;
|
|
6
|
+
var CLOSING = /^ {0,3}(`{3,}|~{3,})[ \t]*$/;
|
|
7
|
+
function lineEndAt(text, from) {
|
|
8
|
+
let end = from;
|
|
9
|
+
while (end < text.length && text[end] !== "\n" && text[end] !== "\r") end += 1;
|
|
10
|
+
let next = end;
|
|
11
|
+
if (text[next] === "\r" && text[next + 1] === "\n") next += 2;
|
|
12
|
+
else if (next < text.length) next += 1;
|
|
13
|
+
return { end, next };
|
|
14
|
+
}
|
|
15
|
+
function findClose(text, from, run) {
|
|
16
|
+
for (let scan = from; scan < text.length; ) {
|
|
17
|
+
const line = lineEndAt(text, scan);
|
|
18
|
+
const found = CLOSING.exec(text.slice(scan, line.end))?.[1];
|
|
19
|
+
if (found !== void 0 && found[0] === run[0] && found.length >= run.length) return line;
|
|
20
|
+
scan = line.next;
|
|
21
|
+
}
|
|
22
|
+
return void 0;
|
|
23
|
+
}
|
|
24
|
+
function scanFences(text) {
|
|
25
|
+
if (!MAY_FENCE.test(text)) return [];
|
|
26
|
+
const regions = [];
|
|
27
|
+
let pos = 0;
|
|
28
|
+
while (pos < text.length) {
|
|
29
|
+
const start = pos;
|
|
30
|
+
const line = lineEndAt(text, start);
|
|
31
|
+
const open = OPENING.exec(text.slice(start, line.end));
|
|
32
|
+
const run = open?.[1];
|
|
33
|
+
if (run === void 0 || run.startsWith("`") && (open?.[2] ?? "").includes("`")) {
|
|
34
|
+
pos = line.next;
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
const close = findClose(text, line.next, run);
|
|
38
|
+
pos = close?.next ?? text.length;
|
|
39
|
+
const end = close?.end ?? text.length;
|
|
40
|
+
const closed = close !== void 0;
|
|
41
|
+
regions.push({
|
|
42
|
+
start,
|
|
43
|
+
openerEnd: line.end,
|
|
44
|
+
contentStart: line.next,
|
|
45
|
+
end,
|
|
46
|
+
opener: text.slice(start, line.end),
|
|
47
|
+
closer: run,
|
|
48
|
+
closed
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
return regions;
|
|
52
|
+
}
|
|
53
|
+
function fenceAt(regions, offset) {
|
|
54
|
+
return regions.find((r) => r.start < offset && offset < r.end);
|
|
55
|
+
}
|
|
56
|
+
function openerEol(text, region) {
|
|
57
|
+
if (text.startsWith("\r\n", region.openerEnd)) return "\r\n";
|
|
58
|
+
return text[region.openerEnd] === "\r" ? "\r" : "\n";
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// src/text/dialect.ts
|
|
62
|
+
var DIALECTS = {
|
|
63
|
+
// WhatsApp emphasis is inline and single-character: *bold*, _italic_, ~strike~, ```mono```.
|
|
64
|
+
whatsapp: { bold: "*", italic: "_", strike: "~", code: "```" },
|
|
65
|
+
// LINE text messages carry no rich text at all — decoration is emoji-only. Markers are dropped.
|
|
66
|
+
line: {},
|
|
67
|
+
// SMS is plain text by definition of the medium.
|
|
68
|
+
sms: {}
|
|
69
|
+
};
|
|
70
|
+
var PATTERN = /\*\*(?<bold>.+?)\*\*|~~(?<strike>.+?)~~|(?<![*\w])\*(?!\s)(?<italicStar>.+?)(?<!\s)\*(?!\*)|(?<![_\w])_(?!\s)(?<italicUnderscore>.+?)(?<!\s)_(?!\w)|`(?<code>.+?)`/gu;
|
|
71
|
+
var GROUP_MARKERS = [
|
|
72
|
+
["bold", "bold"],
|
|
73
|
+
["strike", "strike"],
|
|
74
|
+
["italicStar", "italic"],
|
|
75
|
+
["italicUnderscore", "italic"],
|
|
76
|
+
["code", "code"]
|
|
77
|
+
];
|
|
78
|
+
function toDialect(text, platform) {
|
|
79
|
+
const dialect = DIALECTS[platform];
|
|
80
|
+
if (dialect === void 0) return text;
|
|
81
|
+
return rewriteMarkers(text, dialect);
|
|
82
|
+
}
|
|
83
|
+
function markerFor(matched, groups, dialect) {
|
|
84
|
+
if (groups === void 0) return matched;
|
|
85
|
+
for (const [group, marker] of GROUP_MARKERS) {
|
|
86
|
+
const content = groups[group];
|
|
87
|
+
if (content === void 0) continue;
|
|
88
|
+
const wrap = dialect[marker];
|
|
89
|
+
return wrap === void 0 ? content : `${wrap}${content}${wrap}`;
|
|
90
|
+
}
|
|
91
|
+
return matched;
|
|
92
|
+
}
|
|
93
|
+
function rewriteMatch(matched, args, dialect) {
|
|
94
|
+
return markerFor(matched, args.at(-1), dialect);
|
|
95
|
+
}
|
|
96
|
+
function replaceMarkers(text, dialect) {
|
|
97
|
+
return text.replace(PATTERN, (matched, ...args) => rewriteMatch(matched, args, dialect));
|
|
98
|
+
}
|
|
99
|
+
var ROW_START = /[^\S\r\n]*\|/y;
|
|
100
|
+
var LINE_ENDING = /(\r\n|\r|\n)/;
|
|
101
|
+
var MARKER_CHARACTER = /[*_~\x60]/;
|
|
102
|
+
var PIPE = 124;
|
|
103
|
+
var BACKSLASH = 92;
|
|
104
|
+
var LF = 10;
|
|
105
|
+
var CR = 13;
|
|
106
|
+
function rowLocator(text) {
|
|
107
|
+
const rowStart = new RegExp(ROW_START);
|
|
108
|
+
let lineStart = 0;
|
|
109
|
+
let scanned = 0;
|
|
110
|
+
return (offset) => {
|
|
111
|
+
for (; scanned < offset; scanned += 1) {
|
|
112
|
+
const code = text.charCodeAt(scanned);
|
|
113
|
+
if (code === LF || code === CR) lineStart = scanned + 1;
|
|
114
|
+
}
|
|
115
|
+
rowStart.lastIndex = lineStart;
|
|
116
|
+
return rowStart.test(text);
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
function rewriteTableRow(row, dialect) {
|
|
120
|
+
let out = "";
|
|
121
|
+
let from = 0;
|
|
122
|
+
let backslashes = 0;
|
|
123
|
+
for (let i = 0; i < row.length; i += 1) {
|
|
124
|
+
const code = row.charCodeAt(i);
|
|
125
|
+
if (code === BACKSLASH) {
|
|
126
|
+
backslashes += 1;
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
if (code === PIPE && backslashes % 2 === 0) {
|
|
130
|
+
out += `${replaceMarkers(row.slice(from, i), dialect)}|`;
|
|
131
|
+
from = i + 1;
|
|
132
|
+
}
|
|
133
|
+
backslashes = 0;
|
|
134
|
+
}
|
|
135
|
+
return out + replaceMarkers(row.slice(from), dialect);
|
|
136
|
+
}
|
|
137
|
+
function rewriteLine(line, dialect, rowStart) {
|
|
138
|
+
rowStart.lastIndex = 0;
|
|
139
|
+
if (!rowStart.test(line)) return replaceMarkers(line, dialect);
|
|
140
|
+
return MARKER_CHARACTER.test(line) ? rewriteTableRow(line, dialect) : line;
|
|
141
|
+
}
|
|
142
|
+
function rewriteByLine(text, dialect) {
|
|
143
|
+
const rowStart = new RegExp(ROW_START);
|
|
144
|
+
return text.split(LINE_ENDING).map((piece) => rewriteLine(piece, dialect, rowStart)).join("");
|
|
145
|
+
}
|
|
146
|
+
function rewriteMarkers(text, dialect) {
|
|
147
|
+
const regions = scanFences(text);
|
|
148
|
+
if (regions.length === 0) return rewriteUnfenced(text, dialect);
|
|
149
|
+
let out = "";
|
|
150
|
+
let from = 0;
|
|
151
|
+
for (const region of regions) {
|
|
152
|
+
out += rewriteUnfenced(text.slice(from, region.start), dialect) + text.slice(region.start, region.end);
|
|
153
|
+
from = region.end;
|
|
154
|
+
}
|
|
155
|
+
return out + rewriteUnfenced(text.slice(from), dialect);
|
|
156
|
+
}
|
|
157
|
+
function rewriteUnfenced(text, dialect) {
|
|
158
|
+
const onTableRow = rowLocator(text);
|
|
159
|
+
let crossesRowPipe = false;
|
|
160
|
+
const rewritten = text.replace(PATTERN, (matched, ...args) => {
|
|
161
|
+
if (!crossesRowPipe && matched.includes("|")) {
|
|
162
|
+
crossesRowPipe = onTableRow(args.at(-3));
|
|
163
|
+
}
|
|
164
|
+
return rewriteMatch(matched, args, dialect);
|
|
165
|
+
});
|
|
166
|
+
return crossesRowPipe ? rewriteByLine(text, dialect) : rewritten;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// src/text/channel-rendering.ts
|
|
170
|
+
var SLACK = { bold: "*", italic: "_", strike: "~", code: "`" };
|
|
171
|
+
var STRIP = {};
|
|
172
|
+
var identity = (text) => text;
|
|
173
|
+
var translateWith = (dialect) => (text) => rewriteMarkers(text, dialect);
|
|
174
|
+
var RENDERINGS = {
|
|
175
|
+
whatsapp: { format: "plain", translate: translateWith(DIALECTS.whatsapp) },
|
|
176
|
+
slack: { format: "markdown", translate: translateWith(SLACK) },
|
|
177
|
+
discord: { format: "markdown", translate: identity },
|
|
178
|
+
mattermost: { format: "markdown", translate: identity },
|
|
179
|
+
teams: { format: "markdown", translate: identity },
|
|
180
|
+
signal: { format: "markdown", translate: identity },
|
|
181
|
+
line: { format: "plain", translate: translateWith(DIALECTS.line) },
|
|
182
|
+
sms: { format: "plain", translate: translateWith(DIALECTS.sms) },
|
|
183
|
+
telegram: { format: "plain", translate: translateWith(STRIP) },
|
|
184
|
+
matrix: { format: "plain", translate: translateWith(STRIP) },
|
|
185
|
+
email: { format: "plain", translate: translateWith(STRIP) },
|
|
186
|
+
imessage: { format: "plain", translate: translateWith(STRIP) },
|
|
187
|
+
google_chat: { format: "plain", translate: translateWith(STRIP) },
|
|
188
|
+
irc: { format: "plain", translate: translateWith(STRIP) },
|
|
189
|
+
nextcloud_talk: { format: "markdown", translate: identity },
|
|
190
|
+
nostr: { format: "plain", translate: translateWith(STRIP) },
|
|
191
|
+
feishu_lark: { format: "plain", translate: translateWith(STRIP) },
|
|
192
|
+
synology_chat: { format: "plain", translate: translateWith(STRIP) },
|
|
193
|
+
tlon_urbit: { format: "plain", translate: translateWith(STRIP) },
|
|
194
|
+
twitch: { format: "plain", translate: translateWith(STRIP) },
|
|
195
|
+
buzz: { format: "plain", translate: translateWith(STRIP) },
|
|
196
|
+
clickclack: { format: "plain", translate: translateWith(STRIP) },
|
|
197
|
+
zalo_personal: { format: "plain", translate: translateWith(STRIP) },
|
|
198
|
+
zalo: { format: "plain", translate: translateWith(STRIP) },
|
|
199
|
+
wechat: { format: "plain", translate: translateWith(STRIP) },
|
|
200
|
+
wecom: { format: "plain", translate: translateWith(STRIP) },
|
|
201
|
+
yuanbao: { format: "plain", translate: translateWith(STRIP) },
|
|
202
|
+
raft: { format: "plain", translate: translateWith(STRIP) }
|
|
203
|
+
};
|
|
204
|
+
function channelRendering(platform) {
|
|
205
|
+
const rendering = Object.hasOwn(RENDERINGS, platform) ? RENDERINGS[platform] : void 0;
|
|
206
|
+
if (rendering === void 0) {
|
|
207
|
+
throw new RangeError(
|
|
208
|
+
`channelRendering: unknown platform "${String(platform)}"; expected one of ${Object.keys(RENDERINGS).join(", ")}`
|
|
209
|
+
);
|
|
210
|
+
}
|
|
211
|
+
return rendering;
|
|
212
|
+
}
|
|
213
|
+
|
|
3
214
|
// src/adapter/base.ts
|
|
4
215
|
var BasePlatformAdapter = class {
|
|
5
216
|
/**
|
|
@@ -26,6 +237,56 @@ var BasePlatformAdapter = class {
|
|
|
26
237
|
}
|
|
27
238
|
return "ok";
|
|
28
239
|
}
|
|
240
|
+
/** The handler {@link subscribe} holds; `undefined` while nobody is subscribed. */
|
|
241
|
+
subscribedHandler;
|
|
242
|
+
/** The body of {@link onInbound}: replace the handler, and unsubscribe only if it is still the one held. */
|
|
243
|
+
subscribe(handler) {
|
|
244
|
+
this.subscribedHandler = handler;
|
|
245
|
+
return () => {
|
|
246
|
+
if (this.subscribedHandler === handler) this.subscribedHandler = void 0;
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
/** The body of {@link deliver} for an adapter that subscribed through {@link subscribe}. */
|
|
250
|
+
deliverInbound(event) {
|
|
251
|
+
return this.runHandler(this.subscribedHandler, event);
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Dispatch a webhook event once: `duplicate` when `seen` holds its id, `no_handler` when nobody
|
|
255
|
+
* subscribed (the id is then NOT remembered, so a redelivery is handled), otherwise remember the
|
|
256
|
+
* id and run the handler. A handler's throw is also logged under `label`.
|
|
257
|
+
*/
|
|
258
|
+
async dispatchOnce(seen, event, label) {
|
|
259
|
+
if (seen.has(event.id)) return "duplicate";
|
|
260
|
+
if (this.subscribedHandler === void 0) return "no_handler";
|
|
261
|
+
seen.add(event.id);
|
|
262
|
+
const outcome = await this.runHandler(this.subscribedHandler, event);
|
|
263
|
+
if (outcome === "handler_threw") process.stderr.write(`[${label}] handler threw
|
|
264
|
+
`);
|
|
265
|
+
return outcome;
|
|
266
|
+
}
|
|
267
|
+
/** `out.text`, translated to the platform's markup when `out.format` is `markdown`. */
|
|
268
|
+
outboundText(out) {
|
|
269
|
+
return out.format === "markdown" ? channelRendering(this.platform).translate(out.text) : out.text;
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* The local checks every text-only `sendMessage` makes before a request, in this order:
|
|
273
|
+
* `empty_text`, `not_connected`, then `invalid_channel` when `channel.valid` rejects the id.
|
|
274
|
+
* Returns the refusal, or `undefined` when the message may be sent.
|
|
275
|
+
*/
|
|
276
|
+
refuseUnsendable(out, check) {
|
|
277
|
+
const refuse = (code, message) => ({
|
|
278
|
+
ok: false,
|
|
279
|
+
error: { code, message }
|
|
280
|
+
});
|
|
281
|
+
if (out.text.length === 0) return refuse("empty_text", "outbound text is empty");
|
|
282
|
+
if (!check.connected) {
|
|
283
|
+
return refuse("not_connected", `${check.className}.connect() has not succeeded`);
|
|
284
|
+
}
|
|
285
|
+
if (check.channel !== void 0 && !check.channel.valid(out.channel.id)) {
|
|
286
|
+
return refuse("invalid_channel", check.channel.message);
|
|
287
|
+
}
|
|
288
|
+
return void 0;
|
|
289
|
+
}
|
|
29
290
|
/**
|
|
30
291
|
* Whether {@link editMessage} can replace the text of a message this adapter sent.
|
|
31
292
|
*
|
|
@@ -63,6 +324,25 @@ var BasePlatformAdapter = class {
|
|
|
63
324
|
}
|
|
64
325
|
};
|
|
65
326
|
}
|
|
327
|
+
/**
|
|
328
|
+
* React to an inbound message with an emoji (for example 👀 as an acknowledgement).
|
|
329
|
+
*
|
|
330
|
+
* Returns `{ ok: true, messageId }` on success and a `SendResult` error otherwise; it never
|
|
331
|
+
* throws on platform errors. `channelId` is the channel the message is in and `messageId` the
|
|
332
|
+
* id the inbound event carried.
|
|
333
|
+
*
|
|
334
|
+
* Default: resolves `{ ok: false, error: { code: "react_unsupported" } }` and makes no
|
|
335
|
+
* platform call.
|
|
336
|
+
*/
|
|
337
|
+
async react(_channelId, _messageId, _emoji) {
|
|
338
|
+
return {
|
|
339
|
+
ok: false,
|
|
340
|
+
error: {
|
|
341
|
+
code: "react_unsupported",
|
|
342
|
+
message: `${this.platform} adapter cannot react to a message`
|
|
343
|
+
}
|
|
344
|
+
};
|
|
345
|
+
}
|
|
66
346
|
/** Lifecycle: emit a typing indicator. Default: noop. */
|
|
67
347
|
async startTyping(_channelId) {
|
|
68
348
|
}
|
|
@@ -71,6 +351,184 @@ var BasePlatformAdapter = class {
|
|
|
71
351
|
}
|
|
72
352
|
};
|
|
73
353
|
|
|
354
|
+
// src/text/seen-ids.ts
|
|
355
|
+
var DEFAULT_LIMIT = 1e3;
|
|
356
|
+
var SeenIds = class {
|
|
357
|
+
/** @param limit the most ids held at once; the oldest is forgotten when one more arrives */
|
|
358
|
+
constructor(limit = DEFAULT_LIMIT) {
|
|
359
|
+
this.limit = limit;
|
|
360
|
+
}
|
|
361
|
+
limit;
|
|
362
|
+
ids = /* @__PURE__ */ new Set();
|
|
363
|
+
/**
|
|
364
|
+
* Record `id`.
|
|
365
|
+
*
|
|
366
|
+
* @returns `true` when the id was new, `false` when it was already held
|
|
367
|
+
*/
|
|
368
|
+
add(id) {
|
|
369
|
+
if (this.ids.has(id)) return false;
|
|
370
|
+
this.ids.add(id);
|
|
371
|
+
if (this.ids.size > this.limit) {
|
|
372
|
+
const oldest = this.ids.values().next().value;
|
|
373
|
+
if (oldest !== void 0) this.ids.delete(oldest);
|
|
374
|
+
}
|
|
375
|
+
return true;
|
|
376
|
+
}
|
|
377
|
+
/** Whether `id` is held. */
|
|
378
|
+
has(id) {
|
|
379
|
+
return this.ids.has(id);
|
|
380
|
+
}
|
|
381
|
+
/** How many ids are held. */
|
|
382
|
+
get size() {
|
|
383
|
+
return this.ids.size;
|
|
384
|
+
}
|
|
385
|
+
};
|
|
386
|
+
|
|
387
|
+
// src/adapter/weixin-xml.ts
|
|
388
|
+
function parseFlatXml(xml) {
|
|
389
|
+
const out = {};
|
|
390
|
+
const tag = /<([A-Za-z][A-Za-z0-9]*)>(?:<!\[CDATA\[([\s\S]*?)\]\]>|([^<]*))<\/\1>/g;
|
|
391
|
+
for (const m of xml.matchAll(tag)) {
|
|
392
|
+
const name = m[1];
|
|
393
|
+
if (name !== void 0 && name !== "xml") out[name] = m[2] ?? decodeEntities(m[3] ?? "");
|
|
394
|
+
}
|
|
395
|
+
return out;
|
|
396
|
+
}
|
|
397
|
+
function decodeEntities(s) {
|
|
398
|
+
return s.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, "&");
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
// src/adapter/weixin-base.ts
|
|
402
|
+
var REQUEST_TIMEOUT_MS = 3e4;
|
|
403
|
+
var TOKEN_MARGIN_MS = 6e4;
|
|
404
|
+
var defaultFetch = async (url, init) => {
|
|
405
|
+
const res = await fetch(url, { ...init, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
|
|
406
|
+
return { status: res.status, text: () => res.text() };
|
|
407
|
+
};
|
|
408
|
+
function weixinMessageOf(err) {
|
|
409
|
+
return err instanceof Error ? err.message : String(err);
|
|
410
|
+
}
|
|
411
|
+
function weixinAck(reason) {
|
|
412
|
+
return { status: 200, body: "success", reason };
|
|
413
|
+
}
|
|
414
|
+
var WeixinAdapterBase = class extends BasePlatformAdapter {
|
|
415
|
+
cfg;
|
|
416
|
+
doFetch;
|
|
417
|
+
connected = false;
|
|
418
|
+
accessToken;
|
|
419
|
+
seen = new SeenIds();
|
|
420
|
+
constructor(cfg) {
|
|
421
|
+
super();
|
|
422
|
+
this.cfg = cfg;
|
|
423
|
+
this.doFetch = cfg.fetch ?? defaultFetch;
|
|
424
|
+
}
|
|
425
|
+
async connect() {
|
|
426
|
+
if (this.connected) return true;
|
|
427
|
+
try {
|
|
428
|
+
await this.token(true);
|
|
429
|
+
this.connected = true;
|
|
430
|
+
return true;
|
|
431
|
+
} catch (err) {
|
|
432
|
+
process.stderr.write(`[${this.cfg.label}] connect failed: ${weixinMessageOf(err)}
|
|
433
|
+
`);
|
|
434
|
+
return false;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
async disconnect() {
|
|
438
|
+
this.connected = false;
|
|
439
|
+
this.accessToken = void 0;
|
|
440
|
+
}
|
|
441
|
+
/** Send text only; a subclass's `sendMessage` refuses attachments first, then calls this. */
|
|
442
|
+
async sendText(out) {
|
|
443
|
+
if (out.text.length === 0) {
|
|
444
|
+
return { ok: false, error: { code: "empty_text", message: "outbound text is empty" } };
|
|
445
|
+
}
|
|
446
|
+
if (!this.connected) {
|
|
447
|
+
return {
|
|
448
|
+
ok: false,
|
|
449
|
+
error: {
|
|
450
|
+
code: "not_connected",
|
|
451
|
+
message: `${this.cfg.className}.connect() has not succeeded`
|
|
452
|
+
}
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
if (out.channel.id === "") {
|
|
456
|
+
return {
|
|
457
|
+
ok: false,
|
|
458
|
+
error: { code: "invalid_channel", message: `channel.id must be ${this.cfg.userNoun}` }
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
return this.sendParts(out);
|
|
462
|
+
}
|
|
463
|
+
async sendParts(out) {
|
|
464
|
+
const failed = `${this.platform}_send_failed`;
|
|
465
|
+
try {
|
|
466
|
+
for (const content of this.split(this.outboundText(out))) {
|
|
467
|
+
const token = await this.token(false);
|
|
468
|
+
const req = this.sendRequest(token, out.channel.id, content);
|
|
469
|
+
const body = await this.call("POST", req.path, req.payload);
|
|
470
|
+
if (body.errcode !== 0) {
|
|
471
|
+
return {
|
|
472
|
+
ok: false,
|
|
473
|
+
error: {
|
|
474
|
+
code: failed,
|
|
475
|
+
message: `${this.cfg.brand} error ${String(body.errcode)}: ${String(body.errmsg)}`
|
|
476
|
+
}
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
} catch (err) {
|
|
481
|
+
return { ok: false, error: { code: failed, message: weixinMessageOf(err) } };
|
|
482
|
+
}
|
|
483
|
+
return { ok: true, messageId: "" };
|
|
484
|
+
}
|
|
485
|
+
onInbound(handler) {
|
|
486
|
+
return this.subscribe(handler);
|
|
487
|
+
}
|
|
488
|
+
/** Deliver an event that arrived out of band, through `runHandler`. */
|
|
489
|
+
async deliver(event) {
|
|
490
|
+
return this.deliverInbound(event);
|
|
491
|
+
}
|
|
492
|
+
/** Turn a plain (decrypted) XML body into one event, dispatch it and answer the webhook. */
|
|
493
|
+
async handleMessage(xml) {
|
|
494
|
+
const event = this.toEvent(parseFlatXml(xml));
|
|
495
|
+
if (event === "skip") return weixinAck("not a text message");
|
|
496
|
+
if (event === void 0) return { status: 400, body: "", reason: "incomplete" };
|
|
497
|
+
const outcome = await this.dispatchOnce(this.seen, event, this.cfg.label);
|
|
498
|
+
if (outcome === "no_handler") return { status: 503, body: "", reason: "no handler subscribed" };
|
|
499
|
+
return weixinAck(outcome);
|
|
500
|
+
}
|
|
501
|
+
async token(force) {
|
|
502
|
+
const cached = this.accessToken;
|
|
503
|
+
if (!force && cached !== void 0 && cached.expiresAt - TOKEN_MARGIN_MS > Date.now()) {
|
|
504
|
+
return cached.value;
|
|
505
|
+
}
|
|
506
|
+
const body = await this.call("GET", this.tokenPath());
|
|
507
|
+
if (body.errcode !== void 0 && body.errcode !== 0) {
|
|
508
|
+
throw new Error(`token answered error ${String(body.errcode)}: ${String(body.errmsg)}`);
|
|
509
|
+
}
|
|
510
|
+
if (!body.access_token) throw new Error("token answer has no access_token");
|
|
511
|
+
this.accessToken = {
|
|
512
|
+
value: body.access_token,
|
|
513
|
+
expiresAt: Date.now() + (body.expires_in ?? 7200) * 1e3
|
|
514
|
+
};
|
|
515
|
+
return body.access_token;
|
|
516
|
+
}
|
|
517
|
+
async call(method, path, payload) {
|
|
518
|
+
const res = await this.doFetch((this.cfg.apiBase ?? this.cfg.defaultBase) + path, {
|
|
519
|
+
method,
|
|
520
|
+
headers: { "Content-Type": "application/json" },
|
|
521
|
+
...payload === void 0 ? {} : { body: JSON.stringify(payload) }
|
|
522
|
+
});
|
|
523
|
+
const text = await res.text();
|
|
524
|
+
try {
|
|
525
|
+
return JSON.parse(text);
|
|
526
|
+
} catch {
|
|
527
|
+
throw new Error(`${this.cfg.brand} answered HTTP ${res.status} with a non-JSON body`);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
};
|
|
531
|
+
|
|
74
532
|
// src/errors/config-error.ts
|
|
75
533
|
var GatewayConfigurationError = class extends Error {
|
|
76
534
|
name = "GatewayConfigurationError";
|
|
@@ -257,6 +715,22 @@ var CREDENTIAL_SHAPES = {
|
|
|
257
715
|
field: "gateway-clickclack `token`",
|
|
258
716
|
why: "a ClickClack bot token (`ccb_` prefix) or session token with no fixed shape for the latter. It travels only in Authorization headers, which the adapter never logs."
|
|
259
717
|
},
|
|
718
|
+
{
|
|
719
|
+
field: "gateway-zalo `accessToken`, `oaSecretKey`",
|
|
720
|
+
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."
|
|
721
|
+
},
|
|
722
|
+
{
|
|
723
|
+
field: "gateway-wechat `appSecret`, `token`",
|
|
724
|
+
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."
|
|
725
|
+
},
|
|
726
|
+
{
|
|
727
|
+
field: "gateway-wecom `corpSecret`, `token`, `encodingAesKey`",
|
|
728
|
+
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."
|
|
729
|
+
},
|
|
730
|
+
{
|
|
731
|
+
field: "gateway-yuanbao `appSecret`, `callbackSecret`",
|
|
732
|
+
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."
|
|
733
|
+
},
|
|
260
734
|
{
|
|
261
735
|
field: "gateway-zalo-personal `credentials`",
|
|
262
736
|
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."
|
|
@@ -427,12 +901,36 @@ var HookExecutor = class {
|
|
|
427
901
|
|
|
428
902
|
// src/runner/gateway-runner.ts
|
|
429
903
|
var DEFAULT_DRAIN_MS = 1e4;
|
|
904
|
+
var TYPING_RENEW_MS = 4e3;
|
|
905
|
+
function keepTyping(adapter, channelId) {
|
|
906
|
+
const swallow = (p) => p.catch(() => void 0);
|
|
907
|
+
const start = () => swallow(Promise.resolve().then(() => adapter.startTyping(channelId)));
|
|
908
|
+
void start();
|
|
909
|
+
const timer = setInterval(() => void start(), TYPING_RENEW_MS);
|
|
910
|
+
timer.unref();
|
|
911
|
+
return async () => {
|
|
912
|
+
clearInterval(timer);
|
|
913
|
+
await swallow(Promise.resolve().then(() => adapter.stopTyping(channelId)));
|
|
914
|
+
};
|
|
915
|
+
}
|
|
430
916
|
var DEFAULT_COMMAND_PREFIXES = ["/"];
|
|
431
917
|
function connectFailureReason(outcome) {
|
|
432
918
|
if (outcome.status === "fulfilled") return "connect returned false";
|
|
433
919
|
const message = outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason);
|
|
434
920
|
return redactSecrets(message);
|
|
435
921
|
}
|
|
922
|
+
function isTerminalConnectError(err) {
|
|
923
|
+
if (typeof err !== "object" || err === null) return false;
|
|
924
|
+
const e = err;
|
|
925
|
+
for (const key of ["status", "statusCode", "httpStatus"]) {
|
|
926
|
+
if (e[key] === 401 || e[key] === 403) return true;
|
|
927
|
+
}
|
|
928
|
+
if (e.errcode === "M_UNKNOWN_TOKEN" || e.errcode === "M_FORBIDDEN") return true;
|
|
929
|
+
const message = typeof e.message === "string" ? e.message : "";
|
|
930
|
+
return /\b(?:http|status(?: code)?)\s*:?\s*(?:401|403)\b|unauthori[sz]ed|forbidden/i.test(
|
|
931
|
+
message
|
|
932
|
+
);
|
|
933
|
+
}
|
|
436
934
|
async function releaseAdapters(adapters, during) {
|
|
437
935
|
await Promise.all(
|
|
438
936
|
adapters.map(async (a) => {
|
|
@@ -463,6 +961,7 @@ var GatewayRunner = class {
|
|
|
463
961
|
/** The start that has not settled yet, shared by every overlapping `start()` call. */
|
|
464
962
|
startInFlight;
|
|
465
963
|
stopped = false;
|
|
964
|
+
retryTimers = /* @__PURE__ */ new Set();
|
|
466
965
|
/**
|
|
467
966
|
* Register a slash command. Match rule (EC-A): text === "/" + name
|
|
468
967
|
* OR text.startsWith("/" + name + " ") OR text.startsWith("/" + name + "@").
|
|
@@ -521,12 +1020,80 @@ var GatewayRunner = class {
|
|
|
521
1020
|
this.startResult = { connected: [], failed: result.failed };
|
|
522
1021
|
return this.startResult;
|
|
523
1022
|
}
|
|
524
|
-
this.wireInbound(result.connected);
|
|
525
|
-
this.startResult = {
|
|
526
|
-
connected: result.connected.map((a) => a.platform),
|
|
527
|
-
failed: result.failed
|
|
528
|
-
};
|
|
529
|
-
|
|
1023
|
+
this.wireInbound(result.connected);
|
|
1024
|
+
this.startResult = {
|
|
1025
|
+
connected: result.connected.map((a) => a.platform),
|
|
1026
|
+
failed: result.failed
|
|
1027
|
+
};
|
|
1028
|
+
for (const adapter of result.retryable) this.scheduleReconnect(adapter, 1);
|
|
1029
|
+
return this.startResult;
|
|
1030
|
+
}
|
|
1031
|
+
/** Retry one adapter after its backoff delay; reschedules itself until it connects or gives up. */
|
|
1032
|
+
scheduleReconnect(adapter, attempt) {
|
|
1033
|
+
const policy = this.opts.reconnect;
|
|
1034
|
+
if (policy === void 0 || this.stopped) return;
|
|
1035
|
+
if (policy.maxAttempts !== void 0 && attempt > policy.maxAttempts) {
|
|
1036
|
+
process.stderr.write(
|
|
1037
|
+
`[gateway] adapter "${adapter.platform}" gave up reconnecting after ${policy.maxAttempts} attempts
|
|
1038
|
+
`
|
|
1039
|
+
);
|
|
1040
|
+
return;
|
|
1041
|
+
}
|
|
1042
|
+
const delay = Math.min(
|
|
1043
|
+
(policy.initialDelayMs ?? 1e3) * (policy.factor ?? 2) ** (attempt - 1),
|
|
1044
|
+
policy.maxDelayMs ?? 6e4
|
|
1045
|
+
);
|
|
1046
|
+
const timer = setTimeout(() => {
|
|
1047
|
+
this.retryTimers.delete(timer);
|
|
1048
|
+
void this.reconnectOnce(adapter, attempt);
|
|
1049
|
+
}, delay);
|
|
1050
|
+
timer.unref();
|
|
1051
|
+
this.retryTimers.add(timer);
|
|
1052
|
+
process.stderr.write(
|
|
1053
|
+
`[gateway] adapter "${adapter.platform}" reconnect attempt ${attempt} in ${delay}ms
|
|
1054
|
+
`
|
|
1055
|
+
);
|
|
1056
|
+
}
|
|
1057
|
+
async reconnectOnce(adapter, attempt) {
|
|
1058
|
+
if (this.stopped) return;
|
|
1059
|
+
try {
|
|
1060
|
+
if (await adapter.connect()) {
|
|
1061
|
+
if (this.stopped) {
|
|
1062
|
+
await releaseAdapters([adapter], "releasing a reconnect that stop() overtook");
|
|
1063
|
+
return;
|
|
1064
|
+
}
|
|
1065
|
+
this.wireInbound([adapter]);
|
|
1066
|
+
const prev = this.startResult ?? { connected: [], failed: [] };
|
|
1067
|
+
this.startResult = {
|
|
1068
|
+
connected: [...prev.connected, adapter.platform],
|
|
1069
|
+
failed: prev.failed.filter((f) => f.platform !== adapter.platform)
|
|
1070
|
+
};
|
|
1071
|
+
process.stderr.write(
|
|
1072
|
+
`[gateway] adapter "${adapter.platform}" connected on attempt ${attempt}
|
|
1073
|
+
`
|
|
1074
|
+
);
|
|
1075
|
+
return;
|
|
1076
|
+
}
|
|
1077
|
+
process.stderr.write(
|
|
1078
|
+
`[gateway] adapter "${adapter.platform}" refused to connect; not retrying
|
|
1079
|
+
`
|
|
1080
|
+
);
|
|
1081
|
+
return;
|
|
1082
|
+
} catch (err) {
|
|
1083
|
+
const reason = connectFailureReason({ status: "rejected", reason: err });
|
|
1084
|
+
if (isTerminalConnectError(err)) {
|
|
1085
|
+
process.stderr.write(
|
|
1086
|
+
`[gateway] adapter "${adapter.platform}" credentials rejected: ${reason}; not retrying
|
|
1087
|
+
`
|
|
1088
|
+
);
|
|
1089
|
+
return;
|
|
1090
|
+
}
|
|
1091
|
+
process.stderr.write(
|
|
1092
|
+
`[gateway] adapter "${adapter.platform}" reconnect attempt ${attempt} failed: ${reason}
|
|
1093
|
+
`
|
|
1094
|
+
);
|
|
1095
|
+
}
|
|
1096
|
+
this.scheduleReconnect(adapter, attempt + 1);
|
|
530
1097
|
}
|
|
531
1098
|
/**
|
|
532
1099
|
* All or nothing: when any connect fails, disconnect the adapters that did connect, then rethrow
|
|
@@ -557,7 +1124,7 @@ var GatewayRunner = class {
|
|
|
557
1124
|
await releaseAdapters(connected, "rolling back a failed start");
|
|
558
1125
|
throw failures[0];
|
|
559
1126
|
}
|
|
560
|
-
return { connected: [...adapters], failed: [] };
|
|
1127
|
+
return { connected: [...adapters], failed: [], retryable: [] };
|
|
561
1128
|
}
|
|
562
1129
|
/**
|
|
563
1130
|
* Connect every adapter and keep the ones that connected. The `async` wrapper turns a
|
|
@@ -569,12 +1136,18 @@ var GatewayRunner = class {
|
|
|
569
1136
|
const settled = await Promise.allSettled(adapters.map(async (a) => a.connect()));
|
|
570
1137
|
const connected = [];
|
|
571
1138
|
const failed = [];
|
|
1139
|
+
const retryable = [];
|
|
572
1140
|
settled.forEach((outcome, i) => {
|
|
573
1141
|
const adapter = adapters[i];
|
|
574
1142
|
if (outcome.status === "fulfilled" && outcome.value) connected.push(adapter);
|
|
575
|
-
else
|
|
1143
|
+
else {
|
|
1144
|
+
failed.push({ platform: adapter.platform, reason: connectFailureReason(outcome) });
|
|
1145
|
+
if (outcome.status === "rejected" && !isTerminalConnectError(outcome.reason)) {
|
|
1146
|
+
retryable.push(adapter);
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
576
1149
|
});
|
|
577
|
-
return { connected, failed };
|
|
1150
|
+
return { connected, failed, retryable };
|
|
578
1151
|
}
|
|
579
1152
|
wireInbound(adapters) {
|
|
580
1153
|
for (const a of adapters) {
|
|
@@ -605,6 +1178,8 @@ var GatewayRunner = class {
|
|
|
605
1178
|
}
|
|
606
1179
|
}
|
|
607
1180
|
this.unsubs.length = 0;
|
|
1181
|
+
for (const t of this.retryTimers) clearTimeout(t);
|
|
1182
|
+
this.retryTimers.clear();
|
|
608
1183
|
const drainMs = this.opts.drainTimeoutMs ?? DEFAULT_DRAIN_MS;
|
|
609
1184
|
if (this.inflight.size > 0) {
|
|
610
1185
|
let timer;
|
|
@@ -648,12 +1223,15 @@ var GatewayRunner = class {
|
|
|
648
1223
|
const slashHandler = this.matchSlashCommand(event);
|
|
649
1224
|
const handler = slashHandler ?? this.opts.handler;
|
|
650
1225
|
const work = (async () => {
|
|
1226
|
+
const stopTyping = keepTyping(adapter, event.channel.id);
|
|
651
1227
|
try {
|
|
652
1228
|
await handler(event, ctx);
|
|
653
1229
|
} catch (err) {
|
|
654
1230
|
await this.hookExecutor.fireOnError({ event, error: err });
|
|
655
1231
|
process.stderr.write(`[gateway] handler error: ${redactSecrets(err.message)}
|
|
656
1232
|
`);
|
|
1233
|
+
} finally {
|
|
1234
|
+
await stopTyping();
|
|
657
1235
|
}
|
|
658
1236
|
})();
|
|
659
1237
|
this.inflight.add(work);
|
|
@@ -754,212 +1332,6 @@ var SessionRouter = class {
|
|
|
754
1332
|
}
|
|
755
1333
|
};
|
|
756
1334
|
|
|
757
|
-
// src/text/fence.ts
|
|
758
|
-
var MAY_FENCE = /^ {0,3}(?:`{3}|~{3})/m;
|
|
759
|
-
var OPENING = /^ {0,3}(`{3,}|~{3,})(.*)$/;
|
|
760
|
-
var CLOSING = /^ {0,3}(`{3,}|~{3,})[ \t]*$/;
|
|
761
|
-
function lineEndAt(text, from) {
|
|
762
|
-
let end = from;
|
|
763
|
-
while (end < text.length && text[end] !== "\n" && text[end] !== "\r") end += 1;
|
|
764
|
-
let next = end;
|
|
765
|
-
if (text[next] === "\r" && text[next + 1] === "\n") next += 2;
|
|
766
|
-
else if (next < text.length) next += 1;
|
|
767
|
-
return { end, next };
|
|
768
|
-
}
|
|
769
|
-
function findClose(text, from, run) {
|
|
770
|
-
for (let scan = from; scan < text.length; ) {
|
|
771
|
-
const line = lineEndAt(text, scan);
|
|
772
|
-
const found = CLOSING.exec(text.slice(scan, line.end))?.[1];
|
|
773
|
-
if (found !== void 0 && found[0] === run[0] && found.length >= run.length) return line;
|
|
774
|
-
scan = line.next;
|
|
775
|
-
}
|
|
776
|
-
return void 0;
|
|
777
|
-
}
|
|
778
|
-
function scanFences(text) {
|
|
779
|
-
if (!MAY_FENCE.test(text)) return [];
|
|
780
|
-
const regions = [];
|
|
781
|
-
let pos = 0;
|
|
782
|
-
while (pos < text.length) {
|
|
783
|
-
const start = pos;
|
|
784
|
-
const line = lineEndAt(text, start);
|
|
785
|
-
const open = OPENING.exec(text.slice(start, line.end));
|
|
786
|
-
const run = open?.[1];
|
|
787
|
-
if (run === void 0 || run.startsWith("`") && (open?.[2] ?? "").includes("`")) {
|
|
788
|
-
pos = line.next;
|
|
789
|
-
continue;
|
|
790
|
-
}
|
|
791
|
-
const close = findClose(text, line.next, run);
|
|
792
|
-
pos = close?.next ?? text.length;
|
|
793
|
-
const end = close?.end ?? text.length;
|
|
794
|
-
const closed = close !== void 0;
|
|
795
|
-
regions.push({
|
|
796
|
-
start,
|
|
797
|
-
openerEnd: line.end,
|
|
798
|
-
contentStart: line.next,
|
|
799
|
-
end,
|
|
800
|
-
opener: text.slice(start, line.end),
|
|
801
|
-
closer: run,
|
|
802
|
-
closed
|
|
803
|
-
});
|
|
804
|
-
}
|
|
805
|
-
return regions;
|
|
806
|
-
}
|
|
807
|
-
function fenceAt(regions, offset) {
|
|
808
|
-
return regions.find((r) => r.start < offset && offset < r.end);
|
|
809
|
-
}
|
|
810
|
-
function openerEol(text, region) {
|
|
811
|
-
if (text.startsWith("\r\n", region.openerEnd)) return "\r\n";
|
|
812
|
-
return text[region.openerEnd] === "\r" ? "\r" : "\n";
|
|
813
|
-
}
|
|
814
|
-
|
|
815
|
-
// src/text/dialect.ts
|
|
816
|
-
var DIALECTS = {
|
|
817
|
-
// WhatsApp emphasis is inline and single-character: *bold*, _italic_, ~strike~, ```mono```.
|
|
818
|
-
whatsapp: { bold: "*", italic: "_", strike: "~", code: "```" },
|
|
819
|
-
// LINE text messages carry no rich text at all — decoration is emoji-only. Markers are dropped.
|
|
820
|
-
line: {},
|
|
821
|
-
// SMS is plain text by definition of the medium.
|
|
822
|
-
sms: {}
|
|
823
|
-
};
|
|
824
|
-
var PATTERN = /\*\*(?<bold>.+?)\*\*|~~(?<strike>.+?)~~|(?<![*\w])\*(?!\s)(?<italicStar>.+?)(?<!\s)\*(?!\*)|(?<![_\w])_(?!\s)(?<italicUnderscore>.+?)(?<!\s)_(?!\w)|`(?<code>.+?)`/gu;
|
|
825
|
-
var GROUP_MARKERS = [
|
|
826
|
-
["bold", "bold"],
|
|
827
|
-
["strike", "strike"],
|
|
828
|
-
["italicStar", "italic"],
|
|
829
|
-
["italicUnderscore", "italic"],
|
|
830
|
-
["code", "code"]
|
|
831
|
-
];
|
|
832
|
-
function toDialect(text, platform) {
|
|
833
|
-
const dialect = DIALECTS[platform];
|
|
834
|
-
if (dialect === void 0) return text;
|
|
835
|
-
return rewriteMarkers(text, dialect);
|
|
836
|
-
}
|
|
837
|
-
function markerFor(matched, groups, dialect) {
|
|
838
|
-
if (groups === void 0) return matched;
|
|
839
|
-
for (const [group, marker] of GROUP_MARKERS) {
|
|
840
|
-
const content = groups[group];
|
|
841
|
-
if (content === void 0) continue;
|
|
842
|
-
const wrap = dialect[marker];
|
|
843
|
-
return wrap === void 0 ? content : `${wrap}${content}${wrap}`;
|
|
844
|
-
}
|
|
845
|
-
return matched;
|
|
846
|
-
}
|
|
847
|
-
function rewriteMatch(matched, args, dialect) {
|
|
848
|
-
return markerFor(matched, args.at(-1), dialect);
|
|
849
|
-
}
|
|
850
|
-
function replaceMarkers(text, dialect) {
|
|
851
|
-
return text.replace(PATTERN, (matched, ...args) => rewriteMatch(matched, args, dialect));
|
|
852
|
-
}
|
|
853
|
-
var ROW_START = /[^\S\r\n]*\|/y;
|
|
854
|
-
var LINE_ENDING = /(\r\n|\r|\n)/;
|
|
855
|
-
var MARKER_CHARACTER = /[*_~\x60]/;
|
|
856
|
-
var PIPE = 124;
|
|
857
|
-
var BACKSLASH = 92;
|
|
858
|
-
var LF = 10;
|
|
859
|
-
var CR = 13;
|
|
860
|
-
function rowLocator(text) {
|
|
861
|
-
const rowStart = new RegExp(ROW_START);
|
|
862
|
-
let lineStart = 0;
|
|
863
|
-
let scanned = 0;
|
|
864
|
-
return (offset) => {
|
|
865
|
-
for (; scanned < offset; scanned += 1) {
|
|
866
|
-
const code = text.charCodeAt(scanned);
|
|
867
|
-
if (code === LF || code === CR) lineStart = scanned + 1;
|
|
868
|
-
}
|
|
869
|
-
rowStart.lastIndex = lineStart;
|
|
870
|
-
return rowStart.test(text);
|
|
871
|
-
};
|
|
872
|
-
}
|
|
873
|
-
function rewriteTableRow(row, dialect) {
|
|
874
|
-
let out = "";
|
|
875
|
-
let from = 0;
|
|
876
|
-
let backslashes = 0;
|
|
877
|
-
for (let i = 0; i < row.length; i += 1) {
|
|
878
|
-
const code = row.charCodeAt(i);
|
|
879
|
-
if (code === BACKSLASH) {
|
|
880
|
-
backslashes += 1;
|
|
881
|
-
continue;
|
|
882
|
-
}
|
|
883
|
-
if (code === PIPE && backslashes % 2 === 0) {
|
|
884
|
-
out += `${replaceMarkers(row.slice(from, i), dialect)}|`;
|
|
885
|
-
from = i + 1;
|
|
886
|
-
}
|
|
887
|
-
backslashes = 0;
|
|
888
|
-
}
|
|
889
|
-
return out + replaceMarkers(row.slice(from), dialect);
|
|
890
|
-
}
|
|
891
|
-
function rewriteLine(line, dialect, rowStart) {
|
|
892
|
-
rowStart.lastIndex = 0;
|
|
893
|
-
if (!rowStart.test(line)) return replaceMarkers(line, dialect);
|
|
894
|
-
return MARKER_CHARACTER.test(line) ? rewriteTableRow(line, dialect) : line;
|
|
895
|
-
}
|
|
896
|
-
function rewriteByLine(text, dialect) {
|
|
897
|
-
const rowStart = new RegExp(ROW_START);
|
|
898
|
-
return text.split(LINE_ENDING).map((piece) => rewriteLine(piece, dialect, rowStart)).join("");
|
|
899
|
-
}
|
|
900
|
-
function rewriteMarkers(text, dialect) {
|
|
901
|
-
const regions = scanFences(text);
|
|
902
|
-
if (regions.length === 0) return rewriteUnfenced(text, dialect);
|
|
903
|
-
let out = "";
|
|
904
|
-
let from = 0;
|
|
905
|
-
for (const region of regions) {
|
|
906
|
-
out += rewriteUnfenced(text.slice(from, region.start), dialect) + text.slice(region.start, region.end);
|
|
907
|
-
from = region.end;
|
|
908
|
-
}
|
|
909
|
-
return out + rewriteUnfenced(text.slice(from), dialect);
|
|
910
|
-
}
|
|
911
|
-
function rewriteUnfenced(text, dialect) {
|
|
912
|
-
const onTableRow = rowLocator(text);
|
|
913
|
-
let crossesRowPipe = false;
|
|
914
|
-
const rewritten = text.replace(PATTERN, (matched, ...args) => {
|
|
915
|
-
if (!crossesRowPipe && matched.includes("|")) {
|
|
916
|
-
crossesRowPipe = onTableRow(args.at(-3));
|
|
917
|
-
}
|
|
918
|
-
return rewriteMatch(matched, args, dialect);
|
|
919
|
-
});
|
|
920
|
-
return crossesRowPipe ? rewriteByLine(text, dialect) : rewritten;
|
|
921
|
-
}
|
|
922
|
-
|
|
923
|
-
// src/text/channel-rendering.ts
|
|
924
|
-
var SLACK = { bold: "*", italic: "_", strike: "~", code: "`" };
|
|
925
|
-
var STRIP = {};
|
|
926
|
-
var identity = (text) => text;
|
|
927
|
-
var translateWith = (dialect) => (text) => rewriteMarkers(text, dialect);
|
|
928
|
-
var RENDERINGS = {
|
|
929
|
-
whatsapp: { format: "plain", translate: translateWith(DIALECTS.whatsapp) },
|
|
930
|
-
slack: { format: "markdown", translate: translateWith(SLACK) },
|
|
931
|
-
discord: { format: "markdown", translate: identity },
|
|
932
|
-
mattermost: { format: "markdown", translate: identity },
|
|
933
|
-
teams: { format: "markdown", translate: identity },
|
|
934
|
-
signal: { format: "markdown", translate: identity },
|
|
935
|
-
line: { format: "plain", translate: translateWith(DIALECTS.line) },
|
|
936
|
-
sms: { format: "plain", translate: translateWith(DIALECTS.sms) },
|
|
937
|
-
telegram: { format: "plain", translate: translateWith(STRIP) },
|
|
938
|
-
matrix: { format: "plain", translate: translateWith(STRIP) },
|
|
939
|
-
email: { format: "plain", translate: translateWith(STRIP) },
|
|
940
|
-
imessage: { format: "plain", translate: translateWith(STRIP) },
|
|
941
|
-
google_chat: { format: "plain", translate: translateWith(STRIP) },
|
|
942
|
-
irc: { format: "plain", translate: translateWith(STRIP) },
|
|
943
|
-
nextcloud_talk: { format: "markdown", translate: identity },
|
|
944
|
-
nostr: { format: "plain", translate: translateWith(STRIP) },
|
|
945
|
-
feishu_lark: { format: "plain", translate: translateWith(STRIP) },
|
|
946
|
-
synology_chat: { format: "plain", translate: translateWith(STRIP) },
|
|
947
|
-
tlon_urbit: { format: "plain", translate: translateWith(STRIP) },
|
|
948
|
-
twitch: { format: "plain", translate: translateWith(STRIP) },
|
|
949
|
-
buzz: { format: "plain", translate: translateWith(STRIP) },
|
|
950
|
-
clickclack: { format: "plain", translate: translateWith(STRIP) },
|
|
951
|
-
zalo_personal: { format: "plain", translate: translateWith(STRIP) }
|
|
952
|
-
};
|
|
953
|
-
function channelRendering(platform) {
|
|
954
|
-
const rendering = Object.hasOwn(RENDERINGS, platform) ? RENDERINGS[platform] : void 0;
|
|
955
|
-
if (rendering === void 0) {
|
|
956
|
-
throw new RangeError(
|
|
957
|
-
`channelRendering: unknown platform "${String(platform)}"; expected one of ${Object.keys(RENDERINGS).join(", ")}`
|
|
958
|
-
);
|
|
959
|
-
}
|
|
960
|
-
return rendering;
|
|
961
|
-
}
|
|
962
|
-
|
|
963
1335
|
// src/text/chunk.ts
|
|
964
1336
|
function searchBoundary(remaining, window, boundaries) {
|
|
965
1337
|
let cut = window;
|
|
@@ -1145,39 +1517,6 @@ function fenceGraphemeCut(text, region, pos, plain, room, boundaryUpTo) {
|
|
|
1145
1517
|
return { cut: at, suffix: (closes ? "" : eol) + region.closer, reopen: region.opener + eol };
|
|
1146
1518
|
}
|
|
1147
1519
|
|
|
1148
|
-
// src/text/seen-ids.ts
|
|
1149
|
-
var DEFAULT_LIMIT = 1e3;
|
|
1150
|
-
var SeenIds = class {
|
|
1151
|
-
/** @param limit the most ids held at once; the oldest is forgotten when one more arrives */
|
|
1152
|
-
constructor(limit = DEFAULT_LIMIT) {
|
|
1153
|
-
this.limit = limit;
|
|
1154
|
-
}
|
|
1155
|
-
limit;
|
|
1156
|
-
ids = /* @__PURE__ */ new Set();
|
|
1157
|
-
/**
|
|
1158
|
-
* Record `id`.
|
|
1159
|
-
*
|
|
1160
|
-
* @returns `true` when the id was new, `false` when it was already held
|
|
1161
|
-
*/
|
|
1162
|
-
add(id) {
|
|
1163
|
-
if (this.ids.has(id)) return false;
|
|
1164
|
-
this.ids.add(id);
|
|
1165
|
-
if (this.ids.size > this.limit) {
|
|
1166
|
-
const oldest = this.ids.values().next().value;
|
|
1167
|
-
if (oldest !== void 0) this.ids.delete(oldest);
|
|
1168
|
-
}
|
|
1169
|
-
return true;
|
|
1170
|
-
}
|
|
1171
|
-
/** Whether `id` is held. */
|
|
1172
|
-
has(id) {
|
|
1173
|
-
return this.ids.has(id);
|
|
1174
|
-
}
|
|
1175
|
-
/** How many ids are held. */
|
|
1176
|
-
get size() {
|
|
1177
|
-
return this.ids.size;
|
|
1178
|
-
}
|
|
1179
|
-
};
|
|
1180
|
-
|
|
1181
1520
|
// src/text/split-rows.ts
|
|
1182
1521
|
var ROW_BLANK = /^[^\S\r\n]$/;
|
|
1183
1522
|
function isLineEnd2(character) {
|
|
@@ -1336,6 +1675,6 @@ function listenerLifecycle(opts) {
|
|
|
1336
1675
|
};
|
|
1337
1676
|
}
|
|
1338
1677
|
|
|
1339
|
-
export { BasePlatformAdapter, CREDENTIAL_SHAPES, DeliveryRouter, GatewayConfigurationError, GatewayLifecycleError, GatewayRunner, HookExecutor, SeenIds, SessionRouter, channelRendering, chunkByGrapheme, chunkText, createChannels, defaultStrategy, listenerLifecycle, loadPeer, maskShapes, rawBodyCapture, redactSecrets, scanFences, splitKeepingRows, toDialect };
|
|
1678
|
+
export { BasePlatformAdapter, CREDENTIAL_SHAPES, DeliveryRouter, GatewayConfigurationError, GatewayLifecycleError, GatewayRunner, HookExecutor, SeenIds, SessionRouter, WeixinAdapterBase, channelRendering, chunkByGrapheme, chunkText, createChannels, defaultStrategy, listenerLifecycle, loadPeer, maskShapes, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, splitKeepingRows, toDialect };
|
|
1340
1679
|
//# sourceMappingURL=index.js.map
|
|
1341
1680
|
//# sourceMappingURL=index.js.map
|