@theokit/gateway 0.10.0 → 0.11.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 +67 -0
- package/README.md +118 -1
- package/dist/index.cjs +159 -55
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +240 -66
- package/dist/index.d.ts +240 -66
- package/dist/index.js +158 -56
- package/dist/index.js.map +1 -1
- package/package.json +2 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,72 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.11.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 39d06f8: Wire channels from descriptors, and keep the channels that connect when another cannot.
|
|
8
|
+
|
|
9
|
+
`@theokit/gateway` exports `createChannels` and the types `ChannelDescriptor`,
|
|
10
|
+
`ChannelConfigField`, `ChannelWebhook`, `WebhookRequest`, `IngestResult`, `ChannelEntry`,
|
|
11
|
+
`ChannelRejection` and `CreateChannelsResult`. `createChannels(entries)` builds an adapter per
|
|
12
|
+
entry and returns `{ adapters, rejected }`: an entry whose required field is absent, `null` or
|
|
13
|
+
`""` is rejected with a `GatewayConfigurationError` coded `missing_required_config` naming the
|
|
14
|
+
keys, and a configuration error thrown by the descriptor's `create` is rejected the same way. Any
|
|
15
|
+
other error propagates. It connects nothing and makes no network call.
|
|
16
|
+
|
|
17
|
+
`GatewayRunner` accepts `connectFailure: "rollback" | "isolate"` (exported as `ConnectFailure`),
|
|
18
|
+
and `StartResult` is exported.
|
|
19
|
+
The default, `"rollback"`, is unchanged: one failed connect disconnects the adapters that did
|
|
20
|
+
connect and rejects `start()`. Under `"isolate"`, `start()` connects every adapter, wires inbound
|
|
21
|
+
only for the ones that connected, and reports the rest with a redacted reason.
|
|
22
|
+
|
|
23
|
+
`start()` now resolves a `StartResult` (`{ connected, failed }`) instead of `void`, under both
|
|
24
|
+
values. This is a type change: code that awaits `start()` and ignores the value is unaffected,
|
|
25
|
+
but a structural type declaring `start(): Promise<void>` that a `GatewayRunner` is assigned to
|
|
26
|
+
fails with TS2322, and a subclass overriding `start()` with that signature fails with TS2416.
|
|
27
|
+
|
|
28
|
+
`@theokit/gateway-telegram` exports `telegramChannel`, a socket channel whose config has a
|
|
29
|
+
required, secret `token` and an optional `allowedUsers`, and a `ConfigurationError` (a
|
|
30
|
+
`GatewayConfigurationError` with the `gateway-telegram` prefix). Called directly,
|
|
31
|
+
`telegramChannel.create` refuses a token that is not a string or is empty, and an `allowedUsers`
|
|
32
|
+
that is not an array of strings; through `createChannels`, an absent or empty token is rejected
|
|
33
|
+
first, as `missing_required_config`.
|
|
34
|
+
|
|
35
|
+
`@theokit/gateway-line` exports `lineChannel`, a webhook channel whose `webhook.verify` checks the
|
|
36
|
+
`x-line-signature` header against the raw body and whose `webhook.ingest` dispatches a verified
|
|
37
|
+
payload through `dispatchWebhookBody`, so a reply uses the cached reply token, or answers
|
|
38
|
+
`"malformed"` without dispatching. It answers `"no_handler"` (a member of `IngestResult`) when the
|
|
39
|
+
payload holds a text message for the handler and none is subscribed: before the runner started,
|
|
40
|
+
after it stopped, or when LINE's connect failed under `"isolate"`. Before, such a request answered
|
|
41
|
+
`"delivered"`, a route acknowledged it, and LINE did not redeliver the lost message.
|
|
42
|
+
`lineChannel.create` checks field types before the adapter's constructor.
|
|
43
|
+
|
|
44
|
+
`LineAdapter.dispatchWebhookBody` now resolves `"ok" | "no_handler"` instead of `void`. It answers
|
|
45
|
+
`"no_handler"`, dispatching nothing and caching no reply token, for a batch holding a text message
|
|
46
|
+
that passes the mention guard while no handler is subscribed; an empty or follow-only batch still
|
|
47
|
+
answers `"ok"`. It reads the handler once per batch, so a handler that unsubscribes while handling
|
|
48
|
+
one event still receives the rest of the batch. Code that ignores the value is unaffected; a
|
|
49
|
+
subclass overriding the method with `Promise<void>` fails with TS2416. `createWebhookServer` is
|
|
50
|
+
unchanged and still answers 200 before it dispatches.
|
|
51
|
+
|
|
52
|
+
Both descriptors are typed locally and import nothing `@theokit/gateway` 0.9.0 lacks, so the peer
|
|
53
|
+
range stays `>=0.9.0 <1.0.0`.
|
|
54
|
+
|
|
55
|
+
- e13abe8: Pair each platform with the rendering `ChatPresenter` needs.
|
|
56
|
+
|
|
57
|
+
`@theokit/gateway` exports `channelRendering(platform)` and the type `ChannelRendering`, a
|
|
58
|
+
`{ translate, format }` pair to spread into `@theokit/presenter`'s `ChatPresenter` options.
|
|
59
|
+
whatsapp and slack get single-character emphasis (`*bold*`, `_italic_`, `~strike~`), discord,
|
|
60
|
+
mattermost and teams keep markdown, and telegram, matrix, email, line and sms get the four inline
|
|
61
|
+
markers removed with `format: "plain"`. Before this, the presenter's defaults put `**bold**` on
|
|
62
|
+
the wire as characters on matrix and email, and handed telegram and slack a bold spelled for
|
|
63
|
+
another dialect.
|
|
64
|
+
|
|
65
|
+
Only bold, italic, strikethrough and inline code are translated. Headings, links, lists and block
|
|
66
|
+
quotes pass through, and fenced code blocks are not handled yet: the inline-code rule rewrites
|
|
67
|
+
their backticks. A platform the table does not know throws a `RangeError`. `toDialect` is
|
|
68
|
+
unchanged, and `@theokit/gateway` still does not depend on `@theokit/presenter`.
|
|
69
|
+
|
|
3
70
|
## 0.10.0
|
|
4
71
|
|
|
5
72
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -31,13 +31,68 @@ to read ten packages to learn which — so the classes are stated here.
|
|
|
31
31
|
|
|
32
32
|
**What none of them does is convert markdown to a platform's dialect.** `format` states the
|
|
33
33
|
caller's INTENT and lets the transport act on it; translating `**bold**` into WhatsApp's
|
|
34
|
-
`*bold*` is a presentation concern and is
|
|
34
|
+
`*bold*` is a presentation concern, and `channelRendering` (below) is where it happens.
|
|
35
35
|
|
|
36
36
|
Measured 2026-08-30: before this, two of ten read the field. An agent answered
|
|
37
37
|
`**Bom Sucesso (MG)**` and LINE and WhatsApp delivered literal asterisks, which is what a
|
|
38
38
|
declared-and-ignored field costs at the far end.
|
|
39
39
|
|
|
40
40
|
|
|
41
|
+
## Sending an agent's reply
|
|
42
|
+
|
|
43
|
+
`@theokit/presenter`'s `ChatPresenter` turns one agent turn into one chat message: it keeps the
|
|
44
|
+
answer's text, drops the model's reasoning and the tool events, and emits once, on `finish`.
|
|
45
|
+
`channelRendering(platform)` gives it the two things it needs to know about the destination, as
|
|
46
|
+
`{ translate, format }`.
|
|
47
|
+
|
|
48
|
+
```typescript
|
|
49
|
+
import { channelRendering, type MessageEvent } from "@theokit/gateway";
|
|
50
|
+
import { type AgentOutputEvent, ChatPresenter } from "@theokit/presenter";
|
|
51
|
+
import type { TelegramAdapter } from "@theokit/gateway-telegram";
|
|
52
|
+
|
|
53
|
+
async function reply(
|
|
54
|
+
adapter: TelegramAdapter,
|
|
55
|
+
event: MessageEvent,
|
|
56
|
+
turn: AsyncIterable<AgentOutputEvent>,
|
|
57
|
+
): Promise<void> {
|
|
58
|
+
const presenter = new ChatPresenter({
|
|
59
|
+
channel: event.channel,
|
|
60
|
+
...channelRendering(event.platform),
|
|
61
|
+
});
|
|
62
|
+
for await (const output of turn) {
|
|
63
|
+
for (const message of presenter.present(output)) await adapter.sendMessage(message);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
A hand-written loop that concatenates every event carrying `text` sends the reasoning too: one
|
|
69
|
+
reply reached a phone as `"TheOi! 👋"`, `"The"` being the start of the model's thinking. Build one
|
|
70
|
+
presenter per turn; it keeps state between `present()` calls.
|
|
71
|
+
|
|
72
|
+
| Platform | `translate` | `format` |
|
|
73
|
+
|---|---|---|
|
|
74
|
+
| whatsapp | `**b**` to `*b*`, `*i*` or `_i_` to `_i_`, `~~s~~` to `~s~`, `` `c` `` to ` ```c``` ` | `plain` |
|
|
75
|
+
| slack | `**b**` to `*b*`, `*i*` or `_i_` to `_i_`, `~~s~~` to `~s~`, `` `c` `` kept | `markdown` |
|
|
76
|
+
| discord, mattermost, teams | unchanged | `markdown` |
|
|
77
|
+
| telegram, matrix, email, line, sms | the markers removed, their content kept | `plain` |
|
|
78
|
+
|
|
79
|
+
- Only the four inline markers are translated: bold, italic, strikethrough and inline code.
|
|
80
|
+
Headings, links, lists and block quotes reach every platform unchanged.
|
|
81
|
+
- **Fenced code blocks are not handled yet, and they come out wrong.** The inline-code rule
|
|
82
|
+
rewrites a fence's backticks: a three-backtick fence becomes one backtick on the plain
|
|
83
|
+
platforms and seven on whatsapp. Do not send a fenced block to a platform that does not render
|
|
84
|
+
markdown.
|
|
85
|
+
- Telegram gets plain text on purpose. Its adapter maps `markdown` to legacy Markdown, which
|
|
86
|
+
refuses a reply with an unpaired `_` or `*`, and the send fails with no retry.
|
|
87
|
+
- These renderings are inferred from each platform's documented syntax and from what each adapter
|
|
88
|
+
does with `format`; none was observed on a real client.
|
|
89
|
+
- The presenter never splits. Each adapter's `sendMessage` splits a long message at its own
|
|
90
|
+
platform's limit, as it always has.
|
|
91
|
+
- `channelRendering` throws a `RangeError` for a platform it does not know, rather than letting
|
|
92
|
+
the presenter fall back to markdown.
|
|
93
|
+
- `@theokit/presenter` is your dependency, not this package's: `@theokit/gateway` does not depend
|
|
94
|
+
on it.
|
|
95
|
+
|
|
41
96
|
## Architecture (5 pieces)
|
|
42
97
|
|
|
43
98
|
| Module | Responsibility |
|
|
@@ -75,6 +130,68 @@ const runner = new GatewayRunner({
|
|
|
75
130
|
await runner.start();
|
|
76
131
|
```
|
|
77
132
|
|
|
133
|
+
## Wiring channels from descriptors
|
|
134
|
+
|
|
135
|
+
Each platform package that has one exports a descriptor: a static object listing the channel's
|
|
136
|
+
config fields (`required`, `secret`), how to build its adapter (`create`), and, for a channel that
|
|
137
|
+
receives webhooks, how to verify and ingest a request (`webhook`). `createChannels` builds every
|
|
138
|
+
channel from its descriptor without connecting anything, and `connectFailure: "isolate"` keeps the
|
|
139
|
+
channels that connect when another one cannot.
|
|
140
|
+
|
|
141
|
+
```typescript
|
|
142
|
+
import { createChannels, GatewayRunner } from "@theokit/gateway";
|
|
143
|
+
import { lineChannel } from "@theokit/gateway-line";
|
|
144
|
+
import { telegramChannel } from "@theokit/gateway-telegram";
|
|
145
|
+
|
|
146
|
+
const { adapters, rejected } = createChannels([
|
|
147
|
+
{ descriptor: telegramChannel, config: { token: process.env.TELEGRAM_BOT_TOKEN } },
|
|
148
|
+
{
|
|
149
|
+
descriptor: lineChannel,
|
|
150
|
+
config: {
|
|
151
|
+
channelSecret: process.env.LINE_CHANNEL_SECRET,
|
|
152
|
+
channelAccessToken: process.env.LINE_CHANNEL_ACCESS_TOKEN,
|
|
153
|
+
},
|
|
154
|
+
},
|
|
155
|
+
]);
|
|
156
|
+
for (const { platform, error } of rejected) console.error(`${platform}: ${error.message}`);
|
|
157
|
+
|
|
158
|
+
const runner = new GatewayRunner({
|
|
159
|
+
adapters,
|
|
160
|
+
connectFailure: "isolate",
|
|
161
|
+
handler: async (event, ctx) => {
|
|
162
|
+
await ctx.reply(`got: ${event.text}`);
|
|
163
|
+
},
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
const { connected, failed } = await runner.start();
|
|
167
|
+
if (connected.length === 0) throw new Error("no channel connected");
|
|
168
|
+
for (const { platform, reason } of failed) console.error(`${platform} did not connect: ${reason}`);
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
- `createChannels` rejects an entry whose required field is absent, `null` or `""` with a
|
|
172
|
+
`GatewayConfigurationError` coded `missing_required_config` that names the keys, and reports a
|
|
173
|
+
configuration error thrown by `create` the same way. Any other error propagates. It performs no
|
|
174
|
+
network call.
|
|
175
|
+
- `connectFailure` defaults to `"rollback"`: one failed connect disconnects the adapters that did
|
|
176
|
+
connect and rejects `start()`, as before. Under `"isolate"`, `start()` resolves even when every
|
|
177
|
+
adapter failed, so check `connected` before you rely on the runner.
|
|
178
|
+
- `start()` resolves a `StartResult` (`{ connected, failed }`) under both values. Code that awaits
|
|
179
|
+
it and ignores the value is unaffected; a type or subclass that declares
|
|
180
|
+
`start(): Promise<void>` needs to change.
|
|
181
|
+
- Give a runner one channel per platform. It routes replies and `stop()` by platform, so with two
|
|
182
|
+
channels of one platform the later one sends the earlier one's replies, and the earlier one is
|
|
183
|
+
connected but never disconnected.
|
|
184
|
+
- Under `"isolate"`, and under `"rollback"` until the first failure, `start()` waits for every
|
|
185
|
+
connect, so a connect that never settles blocks it.
|
|
186
|
+
- A webhook channel's request reaches your HTTP route; route it by platform to the descriptor's
|
|
187
|
+
`webhook.verify(adapter, { rawBody, headers })`, then parse the body and pass it to
|
|
188
|
+
`webhook.ingest(adapter, payload)`, which answers `"delivered"`, `"malformed"` or
|
|
189
|
+
`"no_handler"`. Answer the platform with a success status only for `"delivered"`.
|
|
190
|
+
`"no_handler"` means the payload held a message and no handler was subscribed: a request that
|
|
191
|
+
arrives before `start()` resolves, after `stop()`, or for a channel `start()` reported in
|
|
192
|
+
`failed` under `"isolate"`. Acknowledging it loses the message, since the platform does not
|
|
193
|
+
redeliver an acknowledged request.
|
|
194
|
+
|
|
78
195
|
## Receiving from a TheoKit app
|
|
79
196
|
|
|
80
197
|
Three repositories share this path. `theokit` owns the HTTP route and the signature check —
|
package/dist/index.cjs
CHANGED
|
@@ -36,6 +36,56 @@ var BasePlatformAdapter = class {
|
|
|
36
36
|
}
|
|
37
37
|
};
|
|
38
38
|
|
|
39
|
+
// src/errors/config-error.ts
|
|
40
|
+
var GatewayConfigurationError = class extends Error {
|
|
41
|
+
name = "GatewayConfigurationError";
|
|
42
|
+
code;
|
|
43
|
+
detail;
|
|
44
|
+
/**
|
|
45
|
+
* @param prefix Package prefix used in the default message (e.g. `"gateway-line"`).
|
|
46
|
+
* @param opts `code` (required), optional explicit `message`, optional `detail`.
|
|
47
|
+
*/
|
|
48
|
+
constructor(prefix, opts) {
|
|
49
|
+
super(opts.message ?? `${prefix}: ${opts.code}`);
|
|
50
|
+
this.code = opts.code;
|
|
51
|
+
this.detail = opts.detail;
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
// src/channel/create-channels.ts
|
|
56
|
+
function isAbsent(value) {
|
|
57
|
+
return value === void 0 || value === null || value === "";
|
|
58
|
+
}
|
|
59
|
+
function missingRequiredKeys(entry, values) {
|
|
60
|
+
return entry.descriptor.config.filter((field) => field.required && isAbsent(values[field.key])).map((field) => field.key);
|
|
61
|
+
}
|
|
62
|
+
function createChannels(entries) {
|
|
63
|
+
const adapters = [];
|
|
64
|
+
const rejected = [];
|
|
65
|
+
for (const entry of entries) {
|
|
66
|
+
const values = entry.config ?? {};
|
|
67
|
+
const platform = entry.descriptor.platform;
|
|
68
|
+
const missing = missingRequiredKeys(entry, values);
|
|
69
|
+
if (missing.length > 0) {
|
|
70
|
+
rejected.push({
|
|
71
|
+
platform,
|
|
72
|
+
error: new GatewayConfigurationError("gateway", {
|
|
73
|
+
code: "missing_required_config",
|
|
74
|
+
message: `channel ${platform}: missing required config ${missing.join(", ")}`
|
|
75
|
+
})
|
|
76
|
+
});
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
try {
|
|
80
|
+
adapters.push(entry.descriptor.create(values));
|
|
81
|
+
} catch (err) {
|
|
82
|
+
if (!(err instanceof GatewayConfigurationError)) throw err;
|
|
83
|
+
rejected.push({ platform, error: err });
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return { adapters, rejected };
|
|
87
|
+
}
|
|
88
|
+
|
|
39
89
|
// src/delivery/router.ts
|
|
40
90
|
var DeliveryRouter = class {
|
|
41
91
|
adapters = /* @__PURE__ */ new Map();
|
|
@@ -59,22 +109,6 @@ var DeliveryRouter = class {
|
|
|
59
109
|
}
|
|
60
110
|
};
|
|
61
111
|
|
|
62
|
-
// src/errors/config-error.ts
|
|
63
|
-
var GatewayConfigurationError = class extends Error {
|
|
64
|
-
name = "GatewayConfigurationError";
|
|
65
|
-
code;
|
|
66
|
-
detail;
|
|
67
|
-
/**
|
|
68
|
-
* @param prefix Package prefix used in the default message (e.g. `"gateway-line"`).
|
|
69
|
-
* @param opts `code` (required), optional explicit `message`, optional `detail`.
|
|
70
|
-
*/
|
|
71
|
-
constructor(prefix, opts) {
|
|
72
|
-
super(opts.message ?? `${prefix}: ${opts.code}`);
|
|
73
|
-
this.code = opts.code;
|
|
74
|
-
this.detail = opts.detail;
|
|
75
|
-
}
|
|
76
|
-
};
|
|
77
|
-
|
|
78
112
|
// src/errors/lifecycle-error.ts
|
|
79
113
|
var GatewayLifecycleError = class extends Error {
|
|
80
114
|
name = "GatewayLifecycleError";
|
|
@@ -254,6 +288,11 @@ var HookExecutor = class {
|
|
|
254
288
|
// src/runner/gateway-runner.ts
|
|
255
289
|
var DEFAULT_DRAIN_MS = 1e4;
|
|
256
290
|
var DEFAULT_COMMAND_PREFIXES = ["/"];
|
|
291
|
+
function connectFailureReason(outcome) {
|
|
292
|
+
if (outcome.status === "fulfilled") return "connect returned false";
|
|
293
|
+
const message = outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason);
|
|
294
|
+
return redactSecrets(message);
|
|
295
|
+
}
|
|
257
296
|
var GatewayRunner = class {
|
|
258
297
|
constructor(opts) {
|
|
259
298
|
this.opts = opts;
|
|
@@ -267,7 +306,7 @@ var GatewayRunner = class {
|
|
|
267
306
|
unsubs = [];
|
|
268
307
|
/** Slash command registry: name → handler (word-boundary match, EC-A). */
|
|
269
308
|
commands = /* @__PURE__ */ new Map();
|
|
270
|
-
|
|
309
|
+
startResult;
|
|
271
310
|
stopped = false;
|
|
272
311
|
/**
|
|
273
312
|
* Register a slash command. Match rule (EC-A): text === "/" + name
|
|
@@ -279,10 +318,15 @@ var GatewayRunner = class {
|
|
|
279
318
|
this.commands.set(name, handler);
|
|
280
319
|
}
|
|
281
320
|
/**
|
|
282
|
-
* Connect
|
|
321
|
+
* Connect the adapters and wire inbound dispatch for the ones that connected.
|
|
322
|
+
*
|
|
323
|
+
* Resolves with what connected. A second call after the first resolved returns the same result
|
|
324
|
+
* without connecting again.
|
|
283
325
|
*
|
|
284
326
|
* @throws {GatewayLifecycleError} `runner_stopped` — the runner was already
|
|
285
327
|
* stopped. A stopped runner is spent; construct a new one.
|
|
328
|
+
* @throws {Error} under the default `connectFailure: "rollback"`, the first connect failure, after the
|
|
329
|
+
* adapters that did connect were disconnected.
|
|
286
330
|
*/
|
|
287
331
|
async start() {
|
|
288
332
|
if (this.stopped) {
|
|
@@ -291,7 +335,17 @@ var GatewayRunner = class {
|
|
|
291
335
|
message: "GatewayRunner.start(): this runner has already been stopped and cannot be restarted. Construct a new GatewayRunner instead."
|
|
292
336
|
});
|
|
293
337
|
}
|
|
294
|
-
if (this.
|
|
338
|
+
if (this.startResult !== void 0) return this.startResult;
|
|
339
|
+
const result = (this.opts.connectFailure ?? "rollback") === "isolate" ? await this.connectIsolated() : await this.connectAllOrRollback();
|
|
340
|
+
this.wireInbound(result.connected);
|
|
341
|
+
this.startResult = {
|
|
342
|
+
connected: result.connected.map((a) => a.platform),
|
|
343
|
+
failed: result.failed
|
|
344
|
+
};
|
|
345
|
+
return this.startResult;
|
|
346
|
+
}
|
|
347
|
+
/** All or nothing: one failure disconnects the adapters already open, then rethrows. */
|
|
348
|
+
async connectAllOrRollback() {
|
|
295
349
|
const connected = [];
|
|
296
350
|
try {
|
|
297
351
|
await Promise.all(
|
|
@@ -305,7 +359,27 @@ var GatewayRunner = class {
|
|
|
305
359
|
await Promise.all(connected.map((a) => a.disconnect().catch(() => void 0)));
|
|
306
360
|
throw err;
|
|
307
361
|
}
|
|
308
|
-
|
|
362
|
+
return { connected: [...this.opts.adapters], failed: [] };
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* Connect every adapter and keep the ones that connected. The `async` wrapper turns a
|
|
366
|
+
* synchronous throw inside `connect()` into a rejection `allSettled` sees; a bare
|
|
367
|
+
* `a => a.connect()` would let it escape `map` and reject `start()` itself.
|
|
368
|
+
*/
|
|
369
|
+
async connectIsolated() {
|
|
370
|
+
const adapters = this.opts.adapters;
|
|
371
|
+
const settled = await Promise.allSettled(adapters.map(async (a) => a.connect()));
|
|
372
|
+
const connected = [];
|
|
373
|
+
const failed = [];
|
|
374
|
+
settled.forEach((outcome, i) => {
|
|
375
|
+
const adapter = adapters[i];
|
|
376
|
+
if (outcome.status === "fulfilled" && outcome.value) connected.push(adapter);
|
|
377
|
+
else failed.push({ platform: adapter.platform, reason: connectFailureReason(outcome) });
|
|
378
|
+
});
|
|
379
|
+
return { connected, failed };
|
|
380
|
+
}
|
|
381
|
+
wireInbound(adapters) {
|
|
382
|
+
for (const a of adapters) {
|
|
309
383
|
const unsub = a.onInbound(async (event) => {
|
|
310
384
|
const p = this.dispatch(event);
|
|
311
385
|
this.inflight.add(p);
|
|
@@ -313,7 +387,6 @@ var GatewayRunner = class {
|
|
|
313
387
|
});
|
|
314
388
|
this.unsubs.push(unsub);
|
|
315
389
|
}
|
|
316
|
-
this.connected = true;
|
|
317
390
|
}
|
|
318
391
|
/**
|
|
319
392
|
* Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,
|
|
@@ -346,7 +419,6 @@ var GatewayRunner = class {
|
|
|
346
419
|
await Promise.all(
|
|
347
420
|
[...this.adaptersByPlatform.values()].map((a) => a.disconnect().catch(() => void 0))
|
|
348
421
|
);
|
|
349
|
-
this.connected = false;
|
|
350
422
|
}
|
|
351
423
|
/**
|
|
352
424
|
* @internal Test seam, following `EmailAdapter._threadStoreSize`. The drain set must SHRINK: a
|
|
@@ -471,6 +543,69 @@ var SessionRouter = class {
|
|
|
471
543
|
}
|
|
472
544
|
};
|
|
473
545
|
|
|
546
|
+
// src/text/dialect.ts
|
|
547
|
+
var DIALECTS = {
|
|
548
|
+
// WhatsApp emphasis is inline and single-character: *bold*, _italic_, ~strike~, ```mono```.
|
|
549
|
+
whatsapp: { bold: "*", italic: "_", strike: "~", code: "```" },
|
|
550
|
+
// LINE text messages carry no rich text at all — decoration is emoji-only. Markers are dropped.
|
|
551
|
+
line: {},
|
|
552
|
+
// SMS is plain text by definition of the medium.
|
|
553
|
+
sms: {}
|
|
554
|
+
};
|
|
555
|
+
var PATTERN = /\*\*(?<bold>.+?)\*\*|~~(?<strike>.+?)~~|(?<![*\w])\*(?!\s)(?<italicStar>.+?)(?<!\s)\*(?!\*)|(?<![_\w])_(?!\s)(?<italicUnderscore>.+?)(?<!\s)_(?!\w)|`(?<code>.+?)`/gu;
|
|
556
|
+
var GROUP_MARKERS = [
|
|
557
|
+
["bold", "bold"],
|
|
558
|
+
["strike", "strike"],
|
|
559
|
+
["italicStar", "italic"],
|
|
560
|
+
["italicUnderscore", "italic"],
|
|
561
|
+
["code", "code"]
|
|
562
|
+
];
|
|
563
|
+
function toDialect(text, platform) {
|
|
564
|
+
const dialect = DIALECTS[platform];
|
|
565
|
+
if (dialect === void 0) return text;
|
|
566
|
+
return rewriteMarkers(text, dialect);
|
|
567
|
+
}
|
|
568
|
+
function rewriteMarkers(text, dialect) {
|
|
569
|
+
return text.replace(PATTERN, (matched, ...args) => {
|
|
570
|
+
const groups = args.at(-1);
|
|
571
|
+
if (groups === void 0) return matched;
|
|
572
|
+
for (const [group, marker] of GROUP_MARKERS) {
|
|
573
|
+
const content = groups[group];
|
|
574
|
+
if (content === void 0) continue;
|
|
575
|
+
const wrap = dialect[marker];
|
|
576
|
+
return wrap === void 0 ? content : `${wrap}${content}${wrap}`;
|
|
577
|
+
}
|
|
578
|
+
return matched;
|
|
579
|
+
});
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
// src/text/channel-rendering.ts
|
|
583
|
+
var SLACK = { bold: "*", italic: "_", strike: "~", code: "`" };
|
|
584
|
+
var STRIP = {};
|
|
585
|
+
var identity = (text) => text;
|
|
586
|
+
var translateWith = (dialect) => (text) => rewriteMarkers(text, dialect);
|
|
587
|
+
var RENDERINGS = {
|
|
588
|
+
whatsapp: { format: "plain", translate: translateWith(DIALECTS.whatsapp) },
|
|
589
|
+
slack: { format: "markdown", translate: translateWith(SLACK) },
|
|
590
|
+
discord: { format: "markdown", translate: identity },
|
|
591
|
+
mattermost: { format: "markdown", translate: identity },
|
|
592
|
+
teams: { format: "markdown", translate: identity },
|
|
593
|
+
line: { format: "plain", translate: translateWith(DIALECTS.line) },
|
|
594
|
+
sms: { format: "plain", translate: translateWith(DIALECTS.sms) },
|
|
595
|
+
telegram: { format: "plain", translate: translateWith(STRIP) },
|
|
596
|
+
matrix: { format: "plain", translate: translateWith(STRIP) },
|
|
597
|
+
email: { format: "plain", translate: translateWith(STRIP) }
|
|
598
|
+
};
|
|
599
|
+
function channelRendering(platform) {
|
|
600
|
+
const rendering = Object.hasOwn(RENDERINGS, platform) ? RENDERINGS[platform] : void 0;
|
|
601
|
+
if (rendering === void 0) {
|
|
602
|
+
throw new RangeError(
|
|
603
|
+
`channelRendering: unknown platform "${String(platform)}"; expected one of ${Object.keys(RENDERINGS).join(", ")}`
|
|
604
|
+
);
|
|
605
|
+
}
|
|
606
|
+
return rendering;
|
|
607
|
+
}
|
|
608
|
+
|
|
474
609
|
// src/text/chunk.ts
|
|
475
610
|
function searchBoundary(remaining, window, boundaries) {
|
|
476
611
|
let cut = window;
|
|
@@ -547,39 +682,6 @@ function chunkByGrapheme(text, options) {
|
|
|
547
682
|
return parts;
|
|
548
683
|
}
|
|
549
684
|
|
|
550
|
-
// src/text/dialect.ts
|
|
551
|
-
var DIALECTS = {
|
|
552
|
-
// WhatsApp emphasis is inline and single-character: *bold*, _italic_, ~strike~, ```mono```.
|
|
553
|
-
whatsapp: { bold: "*", italic: "_", strike: "~", code: "```" },
|
|
554
|
-
// LINE text messages carry no rich text at all — decoration is emoji-only. Markers are dropped.
|
|
555
|
-
line: {},
|
|
556
|
-
// SMS is plain text by definition of the medium.
|
|
557
|
-
sms: {}
|
|
558
|
-
};
|
|
559
|
-
var PATTERN = /\*\*(?<bold>.+?)\*\*|~~(?<strike>.+?)~~|(?<![*\w])\*(?!\s)(?<italicStar>.+?)(?<!\s)\*(?!\*)|(?<![_\w])_(?!\s)(?<italicUnderscore>.+?)(?<!\s)_(?!\w)|`(?<code>.+?)`/gu;
|
|
560
|
-
var GROUP_MARKERS = [
|
|
561
|
-
["bold", "bold"],
|
|
562
|
-
["strike", "strike"],
|
|
563
|
-
["italicStar", "italic"],
|
|
564
|
-
["italicUnderscore", "italic"],
|
|
565
|
-
["code", "code"]
|
|
566
|
-
];
|
|
567
|
-
function toDialect(text, platform) {
|
|
568
|
-
const dialect = DIALECTS[platform];
|
|
569
|
-
if (dialect === void 0) return text;
|
|
570
|
-
return text.replace(PATTERN, (matched, ...args) => {
|
|
571
|
-
const groups = args.at(-1);
|
|
572
|
-
if (groups === void 0) return matched;
|
|
573
|
-
for (const [group, marker] of GROUP_MARKERS) {
|
|
574
|
-
const content = groups[group];
|
|
575
|
-
if (content === void 0) continue;
|
|
576
|
-
const wrap = dialect[marker];
|
|
577
|
-
return wrap === void 0 ? content : `${wrap}${content}${wrap}`;
|
|
578
|
-
}
|
|
579
|
-
return matched;
|
|
580
|
-
});
|
|
581
|
-
}
|
|
582
|
-
|
|
583
685
|
// src/webhook/express-server.ts
|
|
584
686
|
async function loadPeer(load, onMissing) {
|
|
585
687
|
try {
|
|
@@ -651,8 +753,10 @@ exports.GatewayLifecycleError = GatewayLifecycleError;
|
|
|
651
753
|
exports.GatewayRunner = GatewayRunner;
|
|
652
754
|
exports.HookExecutor = HookExecutor;
|
|
653
755
|
exports.SessionRouter = SessionRouter;
|
|
756
|
+
exports.channelRendering = channelRendering;
|
|
654
757
|
exports.chunkByGrapheme = chunkByGrapheme;
|
|
655
758
|
exports.chunkText = chunkText;
|
|
759
|
+
exports.createChannels = createChannels;
|
|
656
760
|
exports.defaultStrategy = defaultStrategy;
|
|
657
761
|
exports.listenerLifecycle = listenerLifecycle;
|
|
658
762
|
exports.loadPeer = loadPeer;
|