@theokit/gateway 0.11.0 → 0.14.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 +290 -0
- package/README.md +167 -18
- package/dist/index.cjs +666 -70
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +498 -19
- package/dist/index.d.ts +498 -19
- package/dist/index.js +664 -71
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -26,6 +26,43 @@ var BasePlatformAdapter = class {
|
|
|
26
26
|
}
|
|
27
27
|
return "ok";
|
|
28
28
|
}
|
|
29
|
+
/**
|
|
30
|
+
* Whether {@link editMessage} can replace the text of a message this adapter sent.
|
|
31
|
+
*
|
|
32
|
+
* Read it before starting a preview: on `false`, send the final text instead. An adapter sets
|
|
33
|
+
* it at construction and MUST NOT change it with `connect()`. Annotated as `boolean` so that an
|
|
34
|
+
* edit-capable adapter can override it with `true`.
|
|
35
|
+
*/
|
|
36
|
+
supportsEdit = false;
|
|
37
|
+
/**
|
|
38
|
+
* Whether {@link sendMessage} can send the images of `out.attachments` (B-674).
|
|
39
|
+
*
|
|
40
|
+
* Read it before attaching: on `false`, the adapter refuses a non-empty list with
|
|
41
|
+
* `attachments_unsupported`. Set at construction, never changed by `connect()`. Annotated as
|
|
42
|
+
* `boolean` so that an adapter that sends images can override it with `true`.
|
|
43
|
+
*/
|
|
44
|
+
supportsAttachments = false;
|
|
45
|
+
/**
|
|
46
|
+
* Replace the text of a message this adapter sent, keeping its id.
|
|
47
|
+
*
|
|
48
|
+
* Returns `{ ok: true, messageId }` on success and a `SendResult` error otherwise; it never
|
|
49
|
+
* throws on platform errors. An edit-capable adapter applies, with no request, the same local
|
|
50
|
+
* checks its `sendMessage` applies (such as `empty_text`, and `not_connected` where the send
|
|
51
|
+
* checks the connection), plus `invalid_message_id`, and `edit_too_long` where the adapter
|
|
52
|
+
* splits text: an edit that would need more than one platform message is refused, never split.
|
|
53
|
+
*
|
|
54
|
+
* Default: refuses with `edit_unsupported`, makes no platform call, and checks nothing else
|
|
55
|
+
* first, so capability is answered before input.
|
|
56
|
+
*/
|
|
57
|
+
async editMessage(_messageId, _out) {
|
|
58
|
+
return {
|
|
59
|
+
ok: false,
|
|
60
|
+
error: {
|
|
61
|
+
code: "edit_unsupported",
|
|
62
|
+
message: `${this.platform} adapter cannot edit a sent message`
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
}
|
|
29
66
|
/** Lifecycle: emit a typing indicator. Default: noop. */
|
|
30
67
|
async startTyping(_channelId) {
|
|
31
68
|
}
|
|
@@ -57,31 +94,85 @@ function isAbsent(value) {
|
|
|
57
94
|
function missingRequiredKeys(entry, values) {
|
|
58
95
|
return entry.descriptor.config.filter((field) => field.required && isAbsent(values[field.key])).map((field) => field.key);
|
|
59
96
|
}
|
|
97
|
+
function refused(platform, code, reason) {
|
|
98
|
+
return {
|
|
99
|
+
refusal: {
|
|
100
|
+
platform,
|
|
101
|
+
error: new GatewayConfigurationError("gateway", {
|
|
102
|
+
code,
|
|
103
|
+
message: `channel ${platform}: ${reason}`
|
|
104
|
+
})
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
function refuseBeforeCreate(entry, values, builtPlatforms) {
|
|
109
|
+
const platform = entry.descriptor.platform;
|
|
110
|
+
if (builtPlatforms.has(platform)) {
|
|
111
|
+
return refused(platform, "duplicate_channel", "a channel for this platform was already built");
|
|
112
|
+
}
|
|
113
|
+
const missing = missingRequiredKeys(entry, values);
|
|
114
|
+
if (missing.length > 0) {
|
|
115
|
+
return refused(
|
|
116
|
+
platform,
|
|
117
|
+
"missing_required_config",
|
|
118
|
+
`missing required config ${missing.join(", ")}`
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
return void 0;
|
|
122
|
+
}
|
|
123
|
+
function createAdapter(entry, values) {
|
|
124
|
+
const platform = entry.descriptor.platform;
|
|
125
|
+
let adapter;
|
|
126
|
+
try {
|
|
127
|
+
adapter = entry.descriptor.create(values);
|
|
128
|
+
} catch (err) {
|
|
129
|
+
if (!(err instanceof GatewayConfigurationError)) throw err;
|
|
130
|
+
return { refusal: { platform, error: err } };
|
|
131
|
+
}
|
|
132
|
+
if (adapter.platform !== platform) {
|
|
133
|
+
return refused(
|
|
134
|
+
platform,
|
|
135
|
+
"platform_mismatch",
|
|
136
|
+
`create returned an adapter reporting platform ${adapter.platform}`
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
return { adapter };
|
|
140
|
+
}
|
|
60
141
|
function createChannels(entries) {
|
|
61
142
|
const adapters = [];
|
|
143
|
+
const channels = [];
|
|
62
144
|
const rejected = [];
|
|
145
|
+
const builtPlatforms = /* @__PURE__ */ new Set();
|
|
63
146
|
for (const entry of entries) {
|
|
64
147
|
const values = entry.config ?? {};
|
|
65
|
-
const
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
rejected.push({
|
|
69
|
-
platform,
|
|
70
|
-
error: new GatewayConfigurationError("gateway", {
|
|
71
|
-
code: "missing_required_config",
|
|
72
|
-
message: `channel ${platform}: missing required config ${missing.join(", ")}`
|
|
73
|
-
})
|
|
74
|
-
});
|
|
148
|
+
const outcome = refuseBeforeCreate(entry, values, builtPlatforms) ?? createAdapter(entry, values);
|
|
149
|
+
if (outcome.refusal !== void 0) {
|
|
150
|
+
rejected.push(outcome.refusal);
|
|
75
151
|
continue;
|
|
76
152
|
}
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
153
|
+
adapters.push(outcome.adapter);
|
|
154
|
+
channels.push({ descriptor: entry.descriptor, adapter: outcome.adapter });
|
|
155
|
+
builtPlatforms.add(entry.descriptor.platform);
|
|
156
|
+
}
|
|
157
|
+
return { adapters, channels, rejected };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// src/delivery/attachments.ts
|
|
161
|
+
function attachmentsOf(attachments) {
|
|
162
|
+
return attachments != null && attachments.length !== 0 ? { attachments } : {};
|
|
163
|
+
}
|
|
164
|
+
function refuseUnsupportedAttachments(adapter, outbound) {
|
|
165
|
+
const { attachments } = outbound;
|
|
166
|
+
if (adapter.supportsAttachments || attachments == null || attachments.length === 0) {
|
|
167
|
+
return void 0;
|
|
83
168
|
}
|
|
84
|
-
return {
|
|
169
|
+
return {
|
|
170
|
+
ok: false,
|
|
171
|
+
error: {
|
|
172
|
+
code: "attachments_unsupported",
|
|
173
|
+
message: `${adapter.platform} adapter cannot send attachments`
|
|
174
|
+
}
|
|
175
|
+
};
|
|
85
176
|
}
|
|
86
177
|
|
|
87
178
|
// src/delivery/router.ts
|
|
@@ -98,12 +189,14 @@ var DeliveryRouter = class {
|
|
|
98
189
|
error: { code: "no_adapter", message: `no adapter for platform "${req.platform}"` }
|
|
99
190
|
};
|
|
100
191
|
}
|
|
101
|
-
|
|
192
|
+
const outbound = {
|
|
102
193
|
channel: req.channel,
|
|
103
194
|
text: req.text,
|
|
104
195
|
...req.format !== void 0 ? { format: req.format } : {},
|
|
105
|
-
...req.replyTo !== void 0 ? { replyTo: req.replyTo } : {}
|
|
106
|
-
|
|
196
|
+
...req.replyTo !== void 0 ? { replyTo: req.replyTo } : {},
|
|
197
|
+
...attachmentsOf(req.attachments)
|
|
198
|
+
};
|
|
199
|
+
return refuseUnsupportedAttachments(adapter, outbound) ?? adapter.sendMessage(outbound);
|
|
107
200
|
}
|
|
108
201
|
};
|
|
109
202
|
|
|
@@ -148,9 +241,46 @@ var CREDENTIAL_SHAPES = {
|
|
|
148
241
|
field: "gateway-teams `clientSecret`",
|
|
149
242
|
pattern: /(?<![A-Za-z0-9~])[A-Za-z0-9]{3}\d[A-Za-z0-9]?~[A-Za-z0-9._~-]{30,}(?![A-Za-z0-9._~-])/g,
|
|
150
243
|
alsoMatches: "an Entra-style secret is the only common value with a tilde in that position"
|
|
244
|
+
},
|
|
245
|
+
{
|
|
246
|
+
field: "gateway-nostr `secretKey` (nsec1 form)",
|
|
247
|
+
pattern: /(?<![a-z0-9])nsec1[02-9ac-hj-np-z]{58}(?![a-z0-9])/g,
|
|
248
|
+
alsoMatches: "nothing plausible \u2014 `nsec1` is NIP-19's prefix for a secret key"
|
|
151
249
|
}
|
|
152
250
|
],
|
|
153
251
|
uncovered: [
|
|
252
|
+
{
|
|
253
|
+
field: "gateway-buzz `token`",
|
|
254
|
+
why: "a Buzz bot token with no fixed shape this package could confirm. It travels only in Authorization headers, which the adapter never logs."
|
|
255
|
+
},
|
|
256
|
+
{
|
|
257
|
+
field: "gateway-clickclack `token`",
|
|
258
|
+
why: "a ClickClack bot token (`ccb_` prefix) or session token with no fixed shape for the latter. It travels only in Authorization headers, which the adapter never logs."
|
|
259
|
+
},
|
|
260
|
+
{
|
|
261
|
+
field: "gateway-zalo-personal `credentials`",
|
|
262
|
+
why: "a Zalo web session: a cookie jar, an IMEI-like device id and a user agent. The cookie has no prefix or fixed shape to recognise. It travels only to the Zalo library, which the adapter never logs."
|
|
263
|
+
},
|
|
264
|
+
{
|
|
265
|
+
field: "gateway-twitch `accessToken`",
|
|
266
|
+
why: "30 lowercase alphanumerics with no prefix, the shape of many ids and hashes in a log. It travels only in Authorization headers, which the adapter never logs."
|
|
267
|
+
},
|
|
268
|
+
{
|
|
269
|
+
field: "gateway-tlon-urbit `code`",
|
|
270
|
+
why: "a +code is four dash-joined phonemic syllable words, the same shape as an Urbit ship name such as ~sampel-palnet-sampel-palnet, which the logs exist to show. It travels only in the /~/login body, which the adapter never logs."
|
|
271
|
+
},
|
|
272
|
+
{
|
|
273
|
+
field: "gateway-synology-chat `botToken` and `incomingUrl`",
|
|
274
|
+
why: "a bot token is a random string the NAS generates with no prefix, and the Incoming URL carries its own token as a query parameter of an ordinary entry.cgi URL. Neither has a shape to claim without eating ordinary ids and URLs; the adapter never logs the URL, and refuses a callback token before reading it."
|
|
275
|
+
},
|
|
276
|
+
{
|
|
277
|
+
field: "gateway-feishu-lark `appSecret`",
|
|
278
|
+
why: "32 alphanumerics with no prefix, the shape of many tokens and hashes; it travels only in the body of the tenant-token request, which the adapter never logs."
|
|
279
|
+
},
|
|
280
|
+
{
|
|
281
|
+
field: "gateway-nostr `secretKey` (64-hex form)",
|
|
282
|
+
why: "64 hex characters is also every Nostr public key and event id, which the logs exist to show, and a sha256 digest. The nsec1 spelling of the same key is masked above."
|
|
283
|
+
},
|
|
154
284
|
{
|
|
155
285
|
field: "gateway-sms `authToken` (Twilio), gateway-line `channelSecret`",
|
|
156
286
|
why: "32 lowercase hex characters, which is also an md5 digest, a dashless UUID and half a git tree hash. Masking it would eat the correlation id a developer reads the log to find."
|
|
@@ -171,6 +301,18 @@ var CREDENTIAL_SHAPES = {
|
|
|
171
301
|
field: "gateway-whatsapp `appSecret`",
|
|
172
302
|
why: "32 lowercase hex, the same shape as the Twilio auth token above and as every md5 and dashless UUID. Masking it would eat the correlation ids in a log."
|
|
173
303
|
},
|
|
304
|
+
{
|
|
305
|
+
field: "gateway-nextcloud-talk `secret`",
|
|
306
|
+
why: "a Talk bot secret is a string of 40 to 128 characters the administrator chose for `occ talk:bot:install`, with no prefix or format to recognise. It never travels: both sides send only an HMAC made with it, and the adapter never logs it."
|
|
307
|
+
},
|
|
308
|
+
{
|
|
309
|
+
field: "gateway-irc `password` and `saslPassword`",
|
|
310
|
+
why: "a server password and a NickServ password are passphrases the operator chose, with no format to recognise. The SDK's `key=value` rule masks them as fields wherever they appear as `password=...`; the SASL payload on the wire is their base64, which the adapter never logs."
|
|
311
|
+
},
|
|
312
|
+
{
|
|
313
|
+
field: "gateway-google-chat `privateKey`",
|
|
314
|
+
why: "a PEM block spans lines, and in a log it usually arrives inside a JSON string with its line breaks escaped as \\n, which no single-line shape can claim whole. The SDK's `key=value` rule masks it as a field wherever it appears as `private_key=...` or `privateKey=...`."
|
|
315
|
+
},
|
|
174
316
|
{
|
|
175
317
|
field: "gateway-line `channelAccessToken`, gateway-sms `authToken` (Plivo)",
|
|
176
318
|
why: "long base64 runs with no prefix, indistinguishable from any encoded blob a platform library puts in an error message."
|
|
@@ -291,20 +433,35 @@ function connectFailureReason(outcome) {
|
|
|
291
433
|
const message = outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason);
|
|
292
434
|
return redactSecrets(message);
|
|
293
435
|
}
|
|
436
|
+
async function releaseAdapters(adapters, during) {
|
|
437
|
+
await Promise.all(
|
|
438
|
+
adapters.map(async (a) => {
|
|
439
|
+
try {
|
|
440
|
+
await a.disconnect();
|
|
441
|
+
} catch (err) {
|
|
442
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
443
|
+
process.stderr.write(
|
|
444
|
+
`[gateway] adapter "${a.platform}" disconnect failed while ${during}: ${redactSecrets(message)}
|
|
445
|
+
`
|
|
446
|
+
);
|
|
447
|
+
}
|
|
448
|
+
})
|
|
449
|
+
);
|
|
450
|
+
}
|
|
294
451
|
var GatewayRunner = class {
|
|
295
452
|
constructor(opts) {
|
|
296
453
|
this.opts = opts;
|
|
297
|
-
for (const a of opts.adapters) this.adaptersByPlatform.set(a.platform, a);
|
|
298
454
|
this.hookExecutor = new HookExecutor(opts.hooks ?? []);
|
|
299
455
|
}
|
|
300
456
|
opts;
|
|
301
|
-
adaptersByPlatform = /* @__PURE__ */ new Map();
|
|
302
457
|
hookExecutor;
|
|
303
458
|
inflight = /* @__PURE__ */ new Set();
|
|
304
459
|
unsubs = [];
|
|
305
460
|
/** Slash command registry: name → handler (word-boundary match, EC-A). */
|
|
306
461
|
commands = /* @__PURE__ */ new Map();
|
|
307
462
|
startResult;
|
|
463
|
+
/** The start that has not settled yet, shared by every overlapping `start()` call. */
|
|
464
|
+
startInFlight;
|
|
308
465
|
stopped = false;
|
|
309
466
|
/**
|
|
310
467
|
* Register a slash command. Match rule (EC-A): text === "/" + name
|
|
@@ -321,10 +478,24 @@ var GatewayRunner = class {
|
|
|
321
478
|
* Resolves with what connected. A second call after the first resolved returns the same result
|
|
322
479
|
* without connecting again.
|
|
323
480
|
*
|
|
481
|
+
* Overlapping calls share one start; a start overtaken by stop resolves with no adapter connected.
|
|
482
|
+
* A call made before `stop()` while another is still connecting connects nothing and settles
|
|
483
|
+
* with it; a call made after `stop()` throws `runner_stopped`. When `stop()` runs before the
|
|
484
|
+
* connect settles, the adapters that connected are disconnected, no inbound dispatch is wired,
|
|
485
|
+
* and the start resolves `{ connected: [], failed }`, keeping the `"isolate"` failures. Under
|
|
486
|
+
* `"rollback"`, a connect that fails still rejects the start.
|
|
487
|
+
*
|
|
488
|
+
* Under `connectFailure: "rollback"`, every connect settles before the rollback, so a failing
|
|
489
|
+
* start rejects only once its slowest connect settles, as a successful one resolves only then.
|
|
490
|
+
*
|
|
491
|
+
* An adapter whose `disconnect()` fails while a start rolls back, or while a start that `stop()`
|
|
492
|
+
* overtook gives its adapters back, is named on stderr with the error redacted; how the start
|
|
493
|
+
* settles does not change.
|
|
494
|
+
*
|
|
324
495
|
* @throws {GatewayLifecycleError} `runner_stopped` — the runner was already
|
|
325
496
|
* stopped. A stopped runner is spent; construct a new one.
|
|
326
|
-
* @throws {Error} under the default `connectFailure: "rollback"`, the first connect failure, after
|
|
327
|
-
* adapters that did connect were disconnected.
|
|
497
|
+
* @throws {Error} under the default `connectFailure: "rollback"`, the first connect failure, after
|
|
498
|
+
* every connect settled and the adapters that did connect were disconnected.
|
|
328
499
|
*/
|
|
329
500
|
async start() {
|
|
330
501
|
if (this.stopped) {
|
|
@@ -334,7 +505,22 @@ var GatewayRunner = class {
|
|
|
334
505
|
});
|
|
335
506
|
}
|
|
336
507
|
if (this.startResult !== void 0) return this.startResult;
|
|
508
|
+
if (this.startInFlight === void 0) {
|
|
509
|
+
const pending = this.runStart();
|
|
510
|
+
this.startInFlight = pending;
|
|
511
|
+
pending.catch(() => {
|
|
512
|
+
if (this.startInFlight === pending) this.startInFlight = void 0;
|
|
513
|
+
});
|
|
514
|
+
}
|
|
515
|
+
return this.startInFlight;
|
|
516
|
+
}
|
|
517
|
+
async runStart() {
|
|
337
518
|
const result = (this.opts.connectFailure ?? "rollback") === "isolate" ? await this.connectIsolated() : await this.connectAllOrRollback();
|
|
519
|
+
if (this.stopped) {
|
|
520
|
+
await releaseAdapters(result.connected, "releasing a start that stop() overtook");
|
|
521
|
+
this.startResult = { connected: [], failed: result.failed };
|
|
522
|
+
return this.startResult;
|
|
523
|
+
}
|
|
338
524
|
this.wireInbound(result.connected);
|
|
339
525
|
this.startResult = {
|
|
340
526
|
connected: result.connected.map((a) => a.platform),
|
|
@@ -342,22 +528,36 @@ var GatewayRunner = class {
|
|
|
342
528
|
};
|
|
343
529
|
return this.startResult;
|
|
344
530
|
}
|
|
345
|
-
/**
|
|
531
|
+
/**
|
|
532
|
+
* All or nothing: when any connect fails, disconnect the adapters that did connect, then rethrow
|
|
533
|
+
* the first failure. Every connect settles before the rollback: rolling back while one is still
|
|
534
|
+
* pending left that adapter live once it connected.
|
|
535
|
+
*/
|
|
346
536
|
async connectAllOrRollback() {
|
|
347
|
-
const
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
})
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
537
|
+
const adapters = this.opts.adapters;
|
|
538
|
+
const failures = [];
|
|
539
|
+
const settled = await Promise.allSettled(
|
|
540
|
+
adapters.map(async (a) => {
|
|
541
|
+
let ok;
|
|
542
|
+
try {
|
|
543
|
+
ok = await a.connect();
|
|
544
|
+
} catch (err) {
|
|
545
|
+
failures.push(err);
|
|
546
|
+
throw err;
|
|
547
|
+
}
|
|
548
|
+
if (!ok) {
|
|
549
|
+
const refusal = new Error(`adapter "${a.platform}" connect returned false`);
|
|
550
|
+
failures.push(refusal);
|
|
551
|
+
throw refusal;
|
|
552
|
+
}
|
|
553
|
+
})
|
|
554
|
+
);
|
|
555
|
+
if (failures.length > 0) {
|
|
556
|
+
const connected = adapters.filter((_, i) => settled[i]?.status === "fulfilled");
|
|
557
|
+
await releaseAdapters(connected, "rolling back a failed start");
|
|
558
|
+
throw failures[0];
|
|
359
559
|
}
|
|
360
|
-
return { connected: [...
|
|
560
|
+
return { connected: [...adapters], failed: [] };
|
|
361
561
|
}
|
|
362
562
|
/**
|
|
363
563
|
* Connect every adapter and keep the ones that connected. The `async` wrapper turns a
|
|
@@ -379,7 +579,7 @@ var GatewayRunner = class {
|
|
|
379
579
|
wireInbound(adapters) {
|
|
380
580
|
for (const a of adapters) {
|
|
381
581
|
const unsub = a.onInbound(async (event) => {
|
|
382
|
-
const p = this.dispatch(event);
|
|
582
|
+
const p = this.dispatch(event, a);
|
|
383
583
|
this.inflight.add(p);
|
|
384
584
|
p.finally(() => this.inflight.delete(p));
|
|
385
585
|
});
|
|
@@ -388,7 +588,12 @@ var GatewayRunner = class {
|
|
|
388
588
|
}
|
|
389
589
|
/**
|
|
390
590
|
* Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,
|
|
391
|
-
* then disconnects adapters. Idempotent (EC-E).
|
|
591
|
+
* then disconnects adapters. Idempotent (EC-E). A disconnect that fails does not make `stop()`
|
|
592
|
+
* reject and does not stop the other disconnects; it is written to stderr, redacted, naming the
|
|
593
|
+
* platform.
|
|
594
|
+
*
|
|
595
|
+
* An adapter still connecting under an in-flight start is released when that start settles;
|
|
596
|
+
* `stop()` does not wait for it.
|
|
392
597
|
*/
|
|
393
598
|
async stop() {
|
|
394
599
|
if (this.stopped) return;
|
|
@@ -414,9 +619,7 @@ var GatewayRunner = class {
|
|
|
414
619
|
if (timer !== void 0) clearTimeout(timer);
|
|
415
620
|
}
|
|
416
621
|
}
|
|
417
|
-
await
|
|
418
|
-
[...this.adaptersByPlatform.values()].map((a) => a.disconnect().catch(() => void 0))
|
|
419
|
-
);
|
|
622
|
+
await releaseAdapters([...new Set(this.opts.adapters)], "stopping the runner");
|
|
420
623
|
}
|
|
421
624
|
/**
|
|
422
625
|
* @internal Test seam, following `EmailAdapter._threadStoreSize`. The drain set must SHRINK: a
|
|
@@ -428,12 +631,17 @@ var GatewayRunner = class {
|
|
|
428
631
|
return this.inflight.size;
|
|
429
632
|
}
|
|
430
633
|
/** @internal */
|
|
431
|
-
async dispatch(event) {
|
|
432
|
-
const ctx = this.buildContext(event);
|
|
634
|
+
async dispatch(event, adapter) {
|
|
635
|
+
const ctx = this.buildContext(event, adapter);
|
|
433
636
|
const decision = await this.hookExecutor.firePreInbound({ event });
|
|
434
637
|
if (decision.block === true) {
|
|
435
638
|
if (decision.message !== void 0 && decision.message.length > 0) {
|
|
436
|
-
await ctx.reply(decision.message).catch(() =>
|
|
639
|
+
await ctx.reply(decision.message).catch(async (err) => {
|
|
640
|
+
const error = err;
|
|
641
|
+
await this.hookExecutor.fireOnError({ event, error });
|
|
642
|
+
process.stderr.write(`[gateway] auto-reply error: ${redactSecrets(error.message)}
|
|
643
|
+
`);
|
|
644
|
+
});
|
|
437
645
|
}
|
|
438
646
|
return;
|
|
439
647
|
}
|
|
@@ -478,13 +686,14 @@ var GatewayRunner = class {
|
|
|
478
686
|
return void 0;
|
|
479
687
|
}
|
|
480
688
|
/** EC-G: per-event ctx whose reply routes to the matching adapter. */
|
|
481
|
-
buildContext(event) {
|
|
689
|
+
buildContext(event, adapter) {
|
|
482
690
|
return {
|
|
483
691
|
event,
|
|
484
|
-
reply: async (text, opts) => this.deliver(event, {
|
|
692
|
+
reply: async (text, opts) => this.deliver(event, adapter, {
|
|
485
693
|
channel: event.channel,
|
|
486
694
|
text,
|
|
487
|
-
...opts?.format !== void 0 ? { format: opts.format } : {}
|
|
695
|
+
...opts?.format !== void 0 ? { format: opts.format } : {},
|
|
696
|
+
...attachmentsOf(opts?.attachments)
|
|
488
697
|
})
|
|
489
698
|
};
|
|
490
699
|
}
|
|
@@ -496,6 +705,10 @@ var GatewayRunner = class {
|
|
|
496
705
|
* adapter for the platform. An audit hook that counted only the deliveries
|
|
497
706
|
* which reached a transport would omit precisely the ones that went nowhere.
|
|
498
707
|
*
|
|
708
|
+
* An outbound with attachments for an adapter that does not declare `supportsAttachments` is
|
|
709
|
+
* refused here as `attachments_unsupported`, with no `sendMessage` call, so an adapter that
|
|
710
|
+
* ignores the field cannot drop the image and report success (B-674).
|
|
711
|
+
*
|
|
499
712
|
* `post_outbound` observes; it does not intercept. The adapter's `SendResult`
|
|
500
713
|
* is returned to the caller unchanged, and `HookExecutor` already contains a
|
|
501
714
|
* throwing hook, so a broken observer cannot turn a delivered reply into a
|
|
@@ -503,9 +716,9 @@ var GatewayRunner = class {
|
|
|
503
716
|
*
|
|
504
717
|
* @internal
|
|
505
718
|
*/
|
|
506
|
-
async deliver(event, outbound) {
|
|
507
|
-
const
|
|
508
|
-
const result =
|
|
719
|
+
async deliver(event, adapter, outbound) {
|
|
720
|
+
const target = adapter?.platform === event.platform ? adapter : void 0;
|
|
721
|
+
const result = target === void 0 ? { ok: false, error: { code: "no_adapter", message: `no adapter for ${event.platform}` } } : refuseUnsupportedAttachments(target, outbound) ?? await target.sendMessage(outbound);
|
|
509
722
|
await this.hookExecutor.firePostOutbound({ event, outbound, result });
|
|
510
723
|
return result;
|
|
511
724
|
}
|
|
@@ -541,6 +754,64 @@ var SessionRouter = class {
|
|
|
541
754
|
}
|
|
542
755
|
};
|
|
543
756
|
|
|
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
|
+
|
|
544
815
|
// src/text/dialect.ts
|
|
545
816
|
var DIALECTS = {
|
|
546
817
|
// WhatsApp emphasis is inline and single-character: *bold*, _italic_, ~strike~, ```mono```.
|
|
@@ -563,18 +834,90 @@ function toDialect(text, platform) {
|
|
|
563
834
|
if (dialect === void 0) return text;
|
|
564
835
|
return rewriteMarkers(text, dialect);
|
|
565
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
|
+
}
|
|
566
900
|
function rewriteMarkers(text, dialect) {
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
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));
|
|
575
917
|
}
|
|
576
|
-
return matched;
|
|
918
|
+
return rewriteMatch(matched, args, dialect);
|
|
577
919
|
});
|
|
920
|
+
return crossesRowPipe ? rewriteByLine(text, dialect) : rewritten;
|
|
578
921
|
}
|
|
579
922
|
|
|
580
923
|
// src/text/channel-rendering.ts
|
|
@@ -588,11 +931,24 @@ var RENDERINGS = {
|
|
|
588
931
|
discord: { format: "markdown", translate: identity },
|
|
589
932
|
mattermost: { format: "markdown", translate: identity },
|
|
590
933
|
teams: { format: "markdown", translate: identity },
|
|
934
|
+
signal: { format: "markdown", translate: identity },
|
|
591
935
|
line: { format: "plain", translate: translateWith(DIALECTS.line) },
|
|
592
936
|
sms: { format: "plain", translate: translateWith(DIALECTS.sms) },
|
|
593
937
|
telegram: { format: "plain", translate: translateWith(STRIP) },
|
|
594
938
|
matrix: { format: "plain", translate: translateWith(STRIP) },
|
|
595
|
-
email: { 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) }
|
|
596
952
|
};
|
|
597
953
|
function channelRendering(platform) {
|
|
598
954
|
const rendering = Object.hasOwn(RENDERINGS, platform) ? RENDERINGS[platform] : void 0;
|
|
@@ -631,6 +987,63 @@ function findCut(remaining, window, boundaries, lastResort, surrogateGuard) {
|
|
|
631
987
|
if (surrogateGuard) cut = guardSurrogate(remaining, cut);
|
|
632
988
|
return cut <= 0 ? window : cut;
|
|
633
989
|
}
|
|
990
|
+
var isLineEnd = (ch) => ch === "\n" || ch === "\r";
|
|
991
|
+
function startsTableRow(text, from) {
|
|
992
|
+
let at = from;
|
|
993
|
+
while (at < text.length && /^[^\S\r\n]$/.test(text[at] ?? "")) at += 1;
|
|
994
|
+
return text[at] === "|";
|
|
995
|
+
}
|
|
996
|
+
function rowSafeCut(text, cut, window) {
|
|
997
|
+
const start = tableRowStart(text, cut);
|
|
998
|
+
if (start === void 0 || rowLength(text, start, cut, window) > window) return void 0;
|
|
999
|
+
let end = start;
|
|
1000
|
+
while (end > 0 && isLineEnd(text[end - 1])) end -= 1;
|
|
1001
|
+
return end > 0 ? { end, start } : void 0;
|
|
1002
|
+
}
|
|
1003
|
+
function tableRowStart(text, cut) {
|
|
1004
|
+
if (cut >= text.length || isLineEnd(text[cut])) return void 0;
|
|
1005
|
+
let start = cut;
|
|
1006
|
+
while (start > 0 && !isLineEnd(text[start - 1])) start -= 1;
|
|
1007
|
+
return start > 0 && startsTableRow(text, start) ? start : void 0;
|
|
1008
|
+
}
|
|
1009
|
+
function rowLength(text, start, cut, window) {
|
|
1010
|
+
let rowEnd = cut;
|
|
1011
|
+
while (rowEnd < text.length && rowEnd - start <= window && !isLineEnd(text[rowEnd])) rowEnd += 1;
|
|
1012
|
+
return rowEnd - start;
|
|
1013
|
+
}
|
|
1014
|
+
function rowStep(remaining, cut, window) {
|
|
1015
|
+
const moved = rowSafeCut(remaining, cut, window);
|
|
1016
|
+
if (moved === void 0) return void 0;
|
|
1017
|
+
return { chunk: remaining.slice(0, moved.end), remaining: remaining.slice(moved.start) };
|
|
1018
|
+
}
|
|
1019
|
+
function stepBeforeFence(remaining, region) {
|
|
1020
|
+
let end = region.start;
|
|
1021
|
+
while (end > 0 && isLineEnd(remaining[end - 1])) end -= 1;
|
|
1022
|
+
if (end === 0) return void 0;
|
|
1023
|
+
return { chunk: remaining.slice(0, end), remaining: remaining.slice(region.start) };
|
|
1024
|
+
}
|
|
1025
|
+
function stepThroughFence(remaining, region, window, surrogateGuard) {
|
|
1026
|
+
const eol = openerEol(remaining, region);
|
|
1027
|
+
const room = window - region.closer.length - eol.length;
|
|
1028
|
+
if (room <= region.contentStart) return void 0;
|
|
1029
|
+
let at = remaining.lastIndexOf("\n", room);
|
|
1030
|
+
let rest = at + 1;
|
|
1031
|
+
if (at < region.contentStart) {
|
|
1032
|
+
at = surrogateGuard ? guardSurrogate(remaining, room) : room;
|
|
1033
|
+
rest = at;
|
|
1034
|
+
} else if (remaining[at - 1] === "\r") {
|
|
1035
|
+
at -= 1;
|
|
1036
|
+
}
|
|
1037
|
+
return {
|
|
1038
|
+
chunk: `${remaining.slice(0, at)}${eol}${region.closer}`,
|
|
1039
|
+
remaining: `${region.opener}${eol}${remaining.slice(rest)}`
|
|
1040
|
+
};
|
|
1041
|
+
}
|
|
1042
|
+
function fenceStep(remaining, cut, window, surrogateGuard) {
|
|
1043
|
+
const region = fenceAt(scanFences(remaining), cut);
|
|
1044
|
+
if (region === void 0) return void 0;
|
|
1045
|
+
return cut <= region.openerEnd ? stepBeforeFence(remaining, region) : stepThroughFence(remaining, region, window, surrogateGuard);
|
|
1046
|
+
}
|
|
634
1047
|
function chunkText(text, options) {
|
|
635
1048
|
const {
|
|
636
1049
|
limit,
|
|
@@ -639,7 +1052,8 @@ function chunkText(text, options) {
|
|
|
639
1052
|
lastResort = "window",
|
|
640
1053
|
surrogateGuard = false,
|
|
641
1054
|
stripLeading = /^\n+/,
|
|
642
|
-
trimParts = false
|
|
1055
|
+
trimParts = false,
|
|
1056
|
+
keepTableRows = false
|
|
643
1057
|
} = options;
|
|
644
1058
|
assertPositiveInt("chunkText: limit", limit);
|
|
645
1059
|
assertPositiveInt("chunkText: safeLimit", safeLimit);
|
|
@@ -651,11 +1065,16 @@ function chunkText(text, options) {
|
|
|
651
1065
|
return finalize([text]);
|
|
652
1066
|
}
|
|
653
1067
|
const parts = [];
|
|
1068
|
+
const hasFence = scanFences(text).length > 0;
|
|
654
1069
|
let remaining = text;
|
|
655
1070
|
while (remaining.length > safeLimit) {
|
|
656
1071
|
const cut = findCut(remaining, safeLimit, boundaries, lastResort, surrogateGuard);
|
|
657
|
-
|
|
658
|
-
|
|
1072
|
+
const step = (hasFence ? fenceStep(remaining, cut, safeLimit, surrogateGuard) : void 0) ?? (keepTableRows ? rowStep(remaining, cut, safeLimit) : void 0) ?? {
|
|
1073
|
+
chunk: remaining.slice(0, cut),
|
|
1074
|
+
remaining: remaining.slice(cut).replace(stripLeading, "")
|
|
1075
|
+
};
|
|
1076
|
+
parts.push(step.chunk);
|
|
1077
|
+
remaining = step.remaining;
|
|
659
1078
|
}
|
|
660
1079
|
if (remaining.length > 0) parts.push(remaining);
|
|
661
1080
|
return finalize(parts);
|
|
@@ -666,6 +1085,8 @@ function chunkByGrapheme(text, options) {
|
|
|
666
1085
|
assertPositiveInt("chunkByGrapheme: partLimit", partLimit);
|
|
667
1086
|
if (text.length === 0) return [""];
|
|
668
1087
|
if (text.length <= limit) return [text];
|
|
1088
|
+
const regions = scanFences(text);
|
|
1089
|
+
if (regions.length > 0) return chunkFencedByGrapheme(text, partLimit, regions);
|
|
669
1090
|
const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
|
|
670
1091
|
const parts = [];
|
|
671
1092
|
let buf = "";
|
|
@@ -679,6 +1100,132 @@ function chunkByGrapheme(text, options) {
|
|
|
679
1100
|
if (buf.length > 0) parts.push(buf);
|
|
680
1101
|
return parts;
|
|
681
1102
|
}
|
|
1103
|
+
function graphemeBoundaries(text) {
|
|
1104
|
+
const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
|
|
1105
|
+
const starts = Array.from(segmenter.segment(text), (s) => s.index);
|
|
1106
|
+
starts.push(text.length);
|
|
1107
|
+
return (pos, max) => {
|
|
1108
|
+
const after = starts.filter((b) => b > pos);
|
|
1109
|
+
const within = after.filter((b) => b <= max);
|
|
1110
|
+
return within.at(-1) ?? after[0] ?? text.length;
|
|
1111
|
+
};
|
|
1112
|
+
}
|
|
1113
|
+
function chunkFencedByGrapheme(text, partLimit, regions) {
|
|
1114
|
+
const boundaryUpTo = graphemeBoundaries(text);
|
|
1115
|
+
const parts = [];
|
|
1116
|
+
let pos = 0;
|
|
1117
|
+
let prefix = "";
|
|
1118
|
+
while (prefix.length + (text.length - pos) > partLimit) {
|
|
1119
|
+
const room = partLimit - prefix.length;
|
|
1120
|
+
const plain = boundaryUpTo(pos, pos + room);
|
|
1121
|
+
const region = fenceAt(regions, plain);
|
|
1122
|
+
const next = region === void 0 ? { cut: plain, suffix: "", reopen: "" } : fenceGraphemeCut(text, region, pos, plain, room, boundaryUpTo);
|
|
1123
|
+
parts.push(prefix + text.slice(pos, next.cut) + next.suffix);
|
|
1124
|
+
pos = next.cut;
|
|
1125
|
+
prefix = next.reopen;
|
|
1126
|
+
}
|
|
1127
|
+
parts.push(prefix + text.slice(pos));
|
|
1128
|
+
return parts;
|
|
1129
|
+
}
|
|
1130
|
+
function fenceGraphemeCut(text, region, pos, plain, room, boundaryUpTo) {
|
|
1131
|
+
const none = { cut: plain, suffix: "", reopen: "" };
|
|
1132
|
+
if (plain <= region.openerEnd) {
|
|
1133
|
+
return region.start > pos ? { ...none, cut: region.start } : none;
|
|
1134
|
+
}
|
|
1135
|
+
const eol = openerEol(text, region);
|
|
1136
|
+
const max = pos + room - region.closer.length - eol.length;
|
|
1137
|
+
const floor = Math.max(pos, region.contentStart);
|
|
1138
|
+
if (max <= floor) return none;
|
|
1139
|
+
let at = boundaryUpTo(pos, max);
|
|
1140
|
+
const nl = text.lastIndexOf("\n", at - 1);
|
|
1141
|
+
if (nl >= floor - 1 && nl + 1 > pos) at = nl + 1;
|
|
1142
|
+
if (at <= pos || at > max) return none;
|
|
1143
|
+
if (fenceAt([region], at) === void 0) return { ...none, cut: at };
|
|
1144
|
+
const closes = isLineEnd(text[at - 1]);
|
|
1145
|
+
return { cut: at, suffix: (closes ? "" : eol) + region.closer, reopen: region.opener + eol };
|
|
1146
|
+
}
|
|
1147
|
+
|
|
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
|
+
// src/text/split-rows.ts
|
|
1182
|
+
var ROW_BLANK = /^[^\S\r\n]$/;
|
|
1183
|
+
function isLineEnd2(character) {
|
|
1184
|
+
return character === "\n" || character === "\r";
|
|
1185
|
+
}
|
|
1186
|
+
function startsTableRow2(text, from) {
|
|
1187
|
+
let at = from;
|
|
1188
|
+
while (at < text.length && ROW_BLANK.test(text[at] ?? "")) at += 1;
|
|
1189
|
+
return text[at] === "|";
|
|
1190
|
+
}
|
|
1191
|
+
function lineStartBefore(text, cut, partStart) {
|
|
1192
|
+
let at = cut;
|
|
1193
|
+
while (at > partStart && !isLineEnd2(text[at - 1])) at -= 1;
|
|
1194
|
+
return at;
|
|
1195
|
+
}
|
|
1196
|
+
function lineEndFrom(text, cut, bound) {
|
|
1197
|
+
let at = cut;
|
|
1198
|
+
while (at < text.length && at <= bound && !isLineEnd2(text[at])) at += 1;
|
|
1199
|
+
return at;
|
|
1200
|
+
}
|
|
1201
|
+
function rowSafeCut2(text, partStart, cut, partLimit) {
|
|
1202
|
+
const lineStart = lineStartBefore(text, cut, partStart);
|
|
1203
|
+
if (lineStart <= partStart || lineStart === cut) return cut;
|
|
1204
|
+
if (isLineEnd2(text[cut]) || !startsTableRow2(text, lineStart)) return cut;
|
|
1205
|
+
const lineEnd = lineEndFrom(text, cut, lineStart + partLimit);
|
|
1206
|
+
return lineEnd - lineStart <= partLimit ? lineStart : cut;
|
|
1207
|
+
}
|
|
1208
|
+
function graphemeCut(segments, start, partLimit) {
|
|
1209
|
+
const cut = start + partLimit;
|
|
1210
|
+
const segment = segments.containing(cut);
|
|
1211
|
+
if (segment === void 0 || segment.index >= cut) return cut;
|
|
1212
|
+
return segment.index > start ? segment.index : segment.index + segment.segment.length;
|
|
1213
|
+
}
|
|
1214
|
+
function splitKeepingRows(text, partLimit) {
|
|
1215
|
+
const segments = new Intl.Segmenter(void 0, { granularity: "grapheme" }).segment(text);
|
|
1216
|
+
const parts = [];
|
|
1217
|
+
let start = 0;
|
|
1218
|
+
while (text.length - start > partLimit) {
|
|
1219
|
+
const cut = rowSafeCut2(text, start, graphemeCut(segments, start, partLimit), partLimit);
|
|
1220
|
+
if (cut <= start) {
|
|
1221
|
+
throw new RangeError(`splitKeepingRows: no progress at offset ${start} of ${text.length}`);
|
|
1222
|
+
}
|
|
1223
|
+
parts.push(text.slice(start, cut));
|
|
1224
|
+
start = cut;
|
|
1225
|
+
}
|
|
1226
|
+
if (start < text.length) parts.push(text.slice(start));
|
|
1227
|
+
return parts;
|
|
1228
|
+
}
|
|
682
1229
|
|
|
683
1230
|
// src/webhook/express-server.ts
|
|
684
1231
|
async function loadPeer(load, onMissing) {
|
|
@@ -689,8 +1236,14 @@ async function loadPeer(load, onMissing) {
|
|
|
689
1236
|
onMissing();
|
|
690
1237
|
}
|
|
691
1238
|
}
|
|
692
|
-
function rawBodyCapture(tag) {
|
|
693
|
-
|
|
1239
|
+
function rawBodyCapture(tag, options = {}) {
|
|
1240
|
+
const { maxBytes } = options;
|
|
1241
|
+
if (maxBytes !== void 0 && !(Number.isFinite(maxBytes) && maxBytes >= 0)) {
|
|
1242
|
+
throw new RangeError(
|
|
1243
|
+
`[${tag}] rawBodyCapture: maxBytes must be a finite number of zero or more, got ${maxBytes}`
|
|
1244
|
+
);
|
|
1245
|
+
}
|
|
1246
|
+
return (rawReq, rawRes, next) => {
|
|
694
1247
|
const req = rawReq;
|
|
695
1248
|
if (req.readableEnded === true || req.complete === true) {
|
|
696
1249
|
process.stderr.write(
|
|
@@ -702,17 +1255,48 @@ function rawBodyCapture(tag) {
|
|
|
702
1255
|
return;
|
|
703
1256
|
}
|
|
704
1257
|
let buf = "";
|
|
1258
|
+
let bytes = 0;
|
|
1259
|
+
let refused2 = maxBytes !== void 0 && declaredLength(req) > maxBytes;
|
|
1260
|
+
let settled = false;
|
|
705
1261
|
req.setEncoding("utf8");
|
|
706
1262
|
req.on("data", (chunk) => {
|
|
1263
|
+
if (refused2 || settled) return;
|
|
1264
|
+
bytes += Buffer.byteLength(chunk);
|
|
1265
|
+
if (maxBytes !== void 0 && bytes > maxBytes) {
|
|
1266
|
+
refused2 = true;
|
|
1267
|
+
buf = "";
|
|
1268
|
+
return;
|
|
1269
|
+
}
|
|
707
1270
|
buf += chunk;
|
|
708
1271
|
});
|
|
709
1272
|
req.on("end", () => {
|
|
1273
|
+
if (settled) return;
|
|
1274
|
+
settled = true;
|
|
1275
|
+
if (refused2) {
|
|
1276
|
+
answerTooLarge(rawRes, tag, maxBytes ?? 0);
|
|
1277
|
+
return;
|
|
1278
|
+
}
|
|
710
1279
|
req.rawBody = buf;
|
|
711
1280
|
next();
|
|
712
1281
|
});
|
|
713
|
-
req.on("error", (err) =>
|
|
1282
|
+
req.on("error", (err) => {
|
|
1283
|
+
if (settled) return;
|
|
1284
|
+
settled = true;
|
|
1285
|
+
if (refused2) return;
|
|
1286
|
+
next(err);
|
|
1287
|
+
});
|
|
714
1288
|
};
|
|
715
1289
|
}
|
|
1290
|
+
function declaredLength(req) {
|
|
1291
|
+
const value = req.headers?.["content-length"];
|
|
1292
|
+
const declared = Number(Array.isArray(value) ? value[0] : value);
|
|
1293
|
+
return Number.isFinite(declared) ? declared : 0;
|
|
1294
|
+
}
|
|
1295
|
+
function answerTooLarge(res, tag, maxBytes) {
|
|
1296
|
+
process.stderr.write(`[${tag}] refused a request (413): body larger than ${maxBytes} bytes
|
|
1297
|
+
`);
|
|
1298
|
+
res.status(413).json({ error: "request body too large" });
|
|
1299
|
+
}
|
|
716
1300
|
function listenerLifecycle(opts) {
|
|
717
1301
|
let started = false;
|
|
718
1302
|
let stopped = false;
|
|
@@ -724,8 +1308,17 @@ function listenerLifecycle(opts) {
|
|
|
724
1308
|
return;
|
|
725
1309
|
}
|
|
726
1310
|
stopped = false;
|
|
727
|
-
await new Promise((resolve) => {
|
|
728
|
-
|
|
1311
|
+
await new Promise((resolve, reject) => {
|
|
1312
|
+
const settle = (err) => {
|
|
1313
|
+
if (err === void 0) resolve();
|
|
1314
|
+
else reject(err);
|
|
1315
|
+
};
|
|
1316
|
+
const current = opts.app.listen(opts.port, settle);
|
|
1317
|
+
listener = current;
|
|
1318
|
+
current.once?.("error", settle);
|
|
1319
|
+
}).catch((err) => {
|
|
1320
|
+
listener = void 0;
|
|
1321
|
+
throw err;
|
|
729
1322
|
});
|
|
730
1323
|
started = true;
|
|
731
1324
|
},
|
|
@@ -743,6 +1336,6 @@ function listenerLifecycle(opts) {
|
|
|
743
1336
|
};
|
|
744
1337
|
}
|
|
745
1338
|
|
|
746
|
-
export { BasePlatformAdapter, CREDENTIAL_SHAPES, DeliveryRouter, GatewayConfigurationError, GatewayLifecycleError, GatewayRunner, HookExecutor, SessionRouter, channelRendering, chunkByGrapheme, chunkText, createChannels, defaultStrategy, listenerLifecycle, loadPeer, maskShapes, rawBodyCapture, redactSecrets, toDialect };
|
|
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 };
|
|
747
1340
|
//# sourceMappingURL=index.js.map
|
|
748
1341
|
//# sourceMappingURL=index.js.map
|