@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/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,295 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.14.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 458c34c: 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
|
+
- e009dc3: 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
|
+
|
|
70
|
+
- 67e0b78: Make `nostr`, `feishu_lark`, `synology_chat`, `tlon_urbit` and `twitch` first-party platforms.
|
|
71
|
+
|
|
72
|
+
`@theokit/gateway` gains the five keys in `PlatformEventRegistry`, the `NostrMessageEvent`,
|
|
73
|
+
`FeishuLarkMessageEvent`, `SynologyChatMessageEvent`, `TlonUrbitMessageEvent` and
|
|
74
|
+
`TwitchMessageEvent` types, and a `channelRendering` row for each (`plain`, markers removed).
|
|
75
|
+
`PlatformName` grows by five members. Code that lists every platform in a
|
|
76
|
+
`Record<PlatformName, …>` or in a switch with a `never` default must add the five, and a package
|
|
77
|
+
that registered one of these keys through module augmentation now collides with the first-party
|
|
78
|
+
one (TS2717) and should drop it. The ten event types added since 0.11.0 are now declared in one
|
|
79
|
+
module beside the registry; every name is still exported from the package entry as before.
|
|
80
|
+
|
|
81
|
+
- 3f1788d: Send an image from a gateway handler, and refuse it wherever a platform cannot show one.
|
|
82
|
+
|
|
83
|
+
`@theokit/gateway` exports `OutboundAttachment` (`kind: "image"`, `mediaType`, `data`, optional
|
|
84
|
+
`filename`). `OutboundMessage` gains an optional `attachments` list, `ctx.reply(text, { attachments })`
|
|
85
|
+
carries it to the adapter (an empty list is left out), and `BasePlatformAdapter` declares
|
|
86
|
+
`supportsAttachments`, `false` by default. `DeliveryRouter.send` takes the same `attachments`
|
|
87
|
+
field. The runner and the router refuse an outbound carrying attachments as
|
|
88
|
+
`attachments_unsupported`, with no `sendMessage` call, when the adapter does not declare
|
|
89
|
+
`supportsAttachments`.
|
|
90
|
+
|
|
91
|
+
`@theokit/gateway-telegram` reports `supportsAttachments: true` and sends each image through
|
|
92
|
+
`sendPhoto`, the text as the first photo's caption up to 1024 UTF-16 units and after the photos
|
|
93
|
+
when longer. A non-image kind is refused as `attachments_unsupported`; a missing image, more
|
|
94
|
+
than 10 images or an image over 10 MiB as `invalid_attachment`; all with no request.
|
|
95
|
+
|
|
96
|
+
Every other adapter, and every adapter's `editMessage`, refuses an outbound carrying attachments
|
|
97
|
+
with `attachments_unsupported` and makes no platform call, instead of sending the text and
|
|
98
|
+
dropping the image.
|
|
99
|
+
|
|
100
|
+
The runner's auto-reply to a blocking `pre_inbound` hook no longer discards a `sendMessage` that
|
|
101
|
+
throws: the error reaches the `on_error` hooks with the event and is written to stderr, redacted,
|
|
102
|
+
as a handler error is. Dispatch still does not throw.
|
|
103
|
+
|
|
104
|
+
- 782e448: Carry voice in both directions. The inbound event gains an optional `audio` field, an
|
|
105
|
+
`InboundAudio` with the voice note's bytes, media type and duration in seconds, and
|
|
106
|
+
`OutboundAttachment` gains an `audio` member beside `image`. The Telegram adapter reads a polled
|
|
107
|
+
voice note through `getFile` and a download bounded at 20 MiB and 30 seconds, delivering the
|
|
108
|
+
message without `audio` and one stderr line when it cannot, and sends an audio attachment through
|
|
109
|
+
`sendVoice` with the reply text as its caption. Every other adapter refuses audio as it refuses an
|
|
110
|
+
image. Code that switches exhaustively on `OutboundAttachment["kind"]` gains a case.
|
|
111
|
+
- 48b1b04: Make `buzz` a first-party platform.
|
|
112
|
+
|
|
113
|
+
`@theokit/gateway` gains the `buzz` key in `PlatformEventRegistry`, the `BuzzMessageEvent`
|
|
114
|
+
type and a `channelRendering` row (`plain`, markers removed). `PlatformName` grows by one member.
|
|
115
|
+
Code that lists every platform in a `Record<PlatformName, …>` or in a switch with a `never` default
|
|
116
|
+
must add it.
|
|
117
|
+
|
|
118
|
+
- 1b27d5d: Make `clickclack` a first-party platform.
|
|
119
|
+
|
|
120
|
+
`@theokit/gateway` gains the `clickclack` key in `PlatformEventRegistry`, the `ClickClackMessageEvent`
|
|
121
|
+
type and a `channelRendering` row (`plain`, markers removed). `PlatformName` grows by one member.
|
|
122
|
+
Code that lists every platform in a `Record<PlatformName, …>` or in a switch with a `never` default
|
|
123
|
+
must add it.
|
|
124
|
+
|
|
125
|
+
- baadf93: Make `zalo_personal` a first-party platform.
|
|
126
|
+
|
|
127
|
+
`@theokit/gateway` gains the `zalo_personal` key in `PlatformEventRegistry`, the
|
|
128
|
+
`ZaloPersonalMessageEvent` type and a `channelRendering` row (`plain`, markers removed).
|
|
129
|
+
`PlatformName` grows by one member. Code that lists every platform in a `Record<PlatformName, …>`
|
|
130
|
+
or in a switch with a `never` default must add it.
|
|
131
|
+
|
|
132
|
+
- e980fb8: `@theokit/gateway` exports `SeenIds` (a bounded set of delivered ids) and `splitKeepingRows` (a
|
|
133
|
+
grapheme-safe split that keeps Markdown table rows whole). The SMS and LINE adapters import
|
|
134
|
+
`splitKeepingRows` instead of carrying copies; their peer floor is now `>=0.13.0`.
|
|
135
|
+
- 17c0713: Keep Markdown table rows whole when Discord, Slack, Teams, Telegram, WhatsApp and Mattermost split a long reply. A cut that fell inside a table row now moves back to the start of that row when the row fits in a part, so each row reaches the platform byte-identical. `chunkText` gains the opt-in `keepTableRows` option; text with no table row splits into the same chunks as before.
|
|
136
|
+
|
|
137
|
+
### Patch Changes
|
|
138
|
+
|
|
139
|
+
- e9be726: Keep Markdown table rows intact through translation and splitting.
|
|
140
|
+
|
|
141
|
+
`channelRendering(platform).translate` and `toDialect` now rewrite a table row (a line whose first
|
|
142
|
+
non-blank character is `|`) one cell at a time. Before, an emphasis span could open in one cell
|
|
143
|
+
and close in the next, so `| 2 x *a | b* y |` lost both stars on the ten platforms that rewrite
|
|
144
|
+
markers. Text where no span crosses a row's pipe translates exactly as before. A lone `\r` counts
|
|
145
|
+
as a line ending, as in GFM. Inline code that holds an unescaped pipe inside a row is split at
|
|
146
|
+
that pipe, as GFM splits the cell, so its backticks no longer pair and the platforms that strip
|
|
147
|
+
markers now keep them.
|
|
148
|
+
|
|
149
|
+
`splitForLine` and `splitForSMS` no longer cut a table row in two at a part
|
|
150
|
+
boundary. When a cut would fall inside a row that fits in one part, the part ends before that row
|
|
151
|
+
and the row starts the next part. A row longer than a part is still cut by length. Every
|
|
152
|
+
character is kept, and every part stays within its limit (with the `(i/N) ` prefix counted on
|
|
153
|
+
SMS, whose numbering follows the new part count) except a single grapheme longer than the limit,
|
|
154
|
+
which is emitted whole as its own part, as before. Text with no table row splits exactly as
|
|
155
|
+
before. Two rows that each fill a part exactly arrive as three parts, the second holding only the
|
|
156
|
+
line ending between them.
|
|
157
|
+
|
|
158
|
+
No export, signature, dependency or peer range changes.
|
|
159
|
+
|
|
160
|
+
## 0.12.0
|
|
161
|
+
|
|
162
|
+
### Minor Changes
|
|
163
|
+
|
|
164
|
+
- 05e7fdd: Edit a message an adapter sent, so a reply can stream as a preview that the final text replaces.
|
|
165
|
+
|
|
166
|
+
`BasePlatformAdapter` gains `supportsEdit` (`false` by default) and
|
|
167
|
+
`editMessage(messageId, out)`, whose default refuses with `edit_unsupported`, makes no platform
|
|
168
|
+
call and never throws. A third-party subclass that already declares a member with either name and
|
|
169
|
+
a different type no longer compiles against this release, and under `noImplicitOverride` one
|
|
170
|
+
that declares it without `override` does not either.
|
|
171
|
+
|
|
172
|
+
Telegram (`editMessageText`), Discord (one REST `PATCH` of the message, without fetching the
|
|
173
|
+
channel), Slack (`chat.update`), Mattermost (`patchPost`), Matrix (an `m.replace` event) and Teams
|
|
174
|
+
(`updateActivity`, or `activities(conversationId).update` on `@microsoft/teams.api` below 2.0.14)
|
|
175
|
+
set `supportsEdit` to `true` and replace the text of a message they sent, honouring `format` as
|
|
176
|
+
`sendMessage` does (Slack's `chat.update` takes no `mrkdwn` argument, so its edit sends the text
|
|
177
|
+
as it is for every format), and return `{ ok: true, messageId }` with the same id. E-mail, SMS, LINE and
|
|
178
|
+
WhatsApp keep the default.
|
|
179
|
+
|
|
180
|
+
An edit is refused with no request as `edit_too_long` when the text would need more than one
|
|
181
|
+
platform message (Matrix has no length check), as `invalid_message_id` for an empty id (and on
|
|
182
|
+
Telegram one that is not a safe positive integer), and as `empty_text` and `not_connected` where
|
|
183
|
+
`sendMessage` answers those. Telegram answers its "message is not modified" refusal as a success.
|
|
184
|
+
On Discord an unknown channel is answered by the platform, as `discord_10003`. On Matrix a
|
|
185
|
+
`#alias` the adapter never resolved costs one lookup before the edit. Teams and Matrix do not
|
|
186
|
+
retry a refused markup as plain text on an edit, as they do on a send.
|
|
187
|
+
|
|
188
|
+
The six adapters keep `>=0.9.0` as their peer range on `@theokit/gateway` in this release. At run
|
|
189
|
+
time they work against any core in that range, since no adapter calls the base `editMessage`. Their
|
|
190
|
+
sources declare both members with `override`, so building them against a core older than this one
|
|
191
|
+
reports TS4113. The floor rises to this core in the next release, once it is on npm
|
|
192
|
+
(`docs/adr/0008-edit-capable-adapters-raise-their-core-floor-after-the-core-ships.md`). A
|
|
193
|
+
consumer's own typecheck reads the published declarations, which carry no `override`, and passes
|
|
194
|
+
on an older core.
|
|
195
|
+
|
|
196
|
+
- e646038: Make `google_chat` a first-party platform.
|
|
197
|
+
|
|
198
|
+
`@theokit/gateway` gains the `google_chat` key in `PlatformEventRegistry`, the
|
|
199
|
+
`GoogleChatMessageEvent` type, and a `channelRendering("google_chat")` row. `PlatformName` grows by
|
|
200
|
+
one member. Code that lists every platform in a `Record<PlatformName, …>` or in a switch with a
|
|
201
|
+
`never` default must add a `google_chat` entry, and a package that registered its own `google_chat`
|
|
202
|
+
key through module augmentation now collides with the first-party one (TS2717) and should drop it.
|
|
203
|
+
|
|
204
|
+
- e646038: Make `imessage` a first-party platform.
|
|
205
|
+
|
|
206
|
+
`@theokit/gateway` gains the `imessage` key in `PlatformEventRegistry`, the `IMessageMessageEvent`
|
|
207
|
+
type, and a `channelRendering("imessage")` row (`plain`, markers removed). `PlatformName` grows by
|
|
208
|
+
one member. Code that lists every platform in a `Record<PlatformName, …>` or in a switch with a
|
|
209
|
+
`never` default must add an `imessage` entry, and a package that registered its own `imessage` key
|
|
210
|
+
through module augmentation now collides with the first-party one (TS2717) and should drop it.
|
|
211
|
+
|
|
212
|
+
- e646038: Make `irc` a first-party platform.
|
|
213
|
+
|
|
214
|
+
`@theokit/gateway` gains the `irc` key in `PlatformEventRegistry`, the `IrcMessageEvent` type,
|
|
215
|
+
and a `channelRendering("irc")` row (`plain`, markers removed). `PlatformName` grows by one
|
|
216
|
+
member. Code that lists every platform in a `Record<PlatformName, …>` or in a switch with a
|
|
217
|
+
`never` default must add an `irc` entry, and a package that registered its own `irc` key through
|
|
218
|
+
module augmentation now collides with the first-party one (TS2717) and should drop it.
|
|
219
|
+
|
|
220
|
+
- e646038: Make `nextcloud_talk` a first-party platform.
|
|
221
|
+
|
|
222
|
+
`@theokit/gateway` gains the `nextcloud_talk` key in `PlatformEventRegistry`, the
|
|
223
|
+
`NextcloudTalkMessageEvent` type, and a `channelRendering("nextcloud_talk")` row (`markdown`,
|
|
224
|
+
passed through). `PlatformName` grows by one member. Code that lists every platform in a
|
|
225
|
+
`Record<PlatformName, …>` or in a switch with a `never` default must add a `nextcloud_talk`
|
|
226
|
+
entry, and a package that registered its own `nextcloud_talk` key through module augmentation now
|
|
227
|
+
collides with the first-party one (TS2717) and should drop it.
|
|
228
|
+
|
|
229
|
+
- e646038: Make `signal` a first-party platform.
|
|
230
|
+
|
|
231
|
+
`@theokit/gateway` gains the `signal` key in `PlatformEventRegistry`, the `SignalMessageEvent`
|
|
232
|
+
type, and a `channelRendering("signal")` row (`markdown`, text unchanged). `PlatformName` grows by
|
|
233
|
+
one member. Code that lists every platform in a `Record<PlatformName, …>` or in a switch with a
|
|
234
|
+
`never` default must add a `signal` entry, and a package that registered its own `signal` key
|
|
235
|
+
through module augmentation now collides with the first-party one (TS2717) and should drop it.
|
|
236
|
+
|
|
237
|
+
- b0b29d3: `rawBodyCapture(tag, { maxBytes })` refuses a body larger than `maxBytes` bytes before holding it.
|
|
238
|
+
A declared `content-length` over the limit is refused before any byte is kept; a streamed body is
|
|
239
|
+
refused once it passes the limit. Either way the rest of the stream is dropped, and when it ends
|
|
240
|
+
the middleware answers 413 with the JSON body `{ "error": "request body too large" }` and one
|
|
241
|
+
stderr line naming the router. `next` is not called, so no error reaches Express's final handler,
|
|
242
|
+
which would answer with an HTML page carrying the stack outside production. The middleware
|
|
243
|
+
answers once: data, the end of the stream or a stream error after a refusal do nothing. A
|
|
244
|
+
`maxBytes` that is not a finite number of zero or more throws a `RangeError` when the middleware is
|
|
245
|
+
built. Without the option the middleware keeps no limit, as before. `RawBodyCaptureOptions` is
|
|
246
|
+
exported.
|
|
247
|
+
|
|
248
|
+
### Patch Changes
|
|
249
|
+
|
|
250
|
+
- d3f359a: `createChannels` builds one adapter per platform. In 0.11.0 it built every entry, so two entries
|
|
251
|
+
for one platform gave a `GatewayRunner` two adapters of that platform: the runner sent the first
|
|
252
|
+
one's replies through the second and never disconnected the first. A later entry for a platform
|
|
253
|
+
it already built is now rejected with a `GatewayConfigurationError` coded `duplicate_channel`, and
|
|
254
|
+
its `create` is not called. If your app lists two entries for one platform, the second one now
|
|
255
|
+
lands in `rejected` instead of being built. The first entry built for a platform wins, and an
|
|
256
|
+
entry rejected for its configuration does not claim its platform.
|
|
257
|
+
|
|
258
|
+
An entry whose `create` returns an adapter reporting another platform than its descriptor declares
|
|
259
|
+
is rejected with the code `platform_mismatch`, and the adapter it built is dropped unconnected.
|
|
260
|
+
The runner keys adapters by the adapter's own platform, so such an adapter would otherwise reach
|
|
261
|
+
it as a second adapter for a platform the duplicate check never saw.
|
|
262
|
+
|
|
263
|
+
- 7bea3d4: Two overlapping `start()` calls on one `GatewayRunner` now share one connect. A call made while
|
|
264
|
+
the first is still connecting no longer connects every adapter again; both calls resolve the same
|
|
265
|
+
`StartResult`, or reject with the same error. A start that rejects is not remembered, so a later
|
|
266
|
+
`start()` connects again.
|
|
267
|
+
|
|
268
|
+
A `stop()` during an in-flight `start()` no longer leaves an adapter connected on a stopped runner.
|
|
269
|
+
The start disconnects what connected, wires no inbound dispatch, and resolves
|
|
270
|
+
`{ connected: [], failed }` instead of naming the platforms it connected. Under `"rollback"`, a
|
|
271
|
+
connect that fails still rejects it.
|
|
272
|
+
|
|
273
|
+
Under the default `connectFailure: "rollback"`, the rollback waits for every connect to settle, so
|
|
274
|
+
an adapter that connects after another refused is disconnected as well. The rejection therefore
|
|
275
|
+
comes only once the slowest connect settles. With one adapter refusing and another whose connect
|
|
276
|
+
hangs, `start()` used to reject at once and now stays pending, as a successful rollback start and
|
|
277
|
+
an `"isolate"` start already did.
|
|
278
|
+
|
|
279
|
+
When `stop()`, a rollback, or a start that `stop()` overtook disconnects an adapter and that
|
|
280
|
+
`disconnect()` fails, the runner now writes one line to stderr naming the platform, with any
|
|
281
|
+
credential in the error redacted. The failure used to be discarded, so an adapter that might still
|
|
282
|
+
hold its platform session left no trace. How `start()` and `stop()` resolve or reject is unchanged.
|
|
283
|
+
|
|
284
|
+
- 9a8b81b: `listenerLifecycle(...).start()` rejects with the bind error when the port is taken, instead of
|
|
285
|
+
resolving over no listener. Under Express 5 the error reached the `listen` callback, which ignored
|
|
286
|
+
it, so a second server on a port another one held reported itself started and answered nothing;
|
|
287
|
+
under Express 4 the error was emitted on the server with no listener attached. The
|
|
288
|
+
`createWebhookServer` of `@theokit/gateway-line` and `@theokit/gateway-sms` returns this lifecycle,
|
|
289
|
+
so their `start()` now rejects with `EADDRINUSE` in that case, and a later `start()` tries again.
|
|
290
|
+
`ListenableApp.listen` declares the error argument Express 5 passes, and `ListenerLike` the
|
|
291
|
+
optional `once("error")` Express 4's server has.
|
|
292
|
+
|
|
3
293
|
## 0.11.0
|
|
4
294
|
|
|
5
295
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -16,8 +16,8 @@ pnpm add @theokit/gateway-discord discord.js
|
|
|
16
16
|
|
|
17
17
|
## How each adapter treats `OutboundMessage.format`
|
|
18
18
|
|
|
19
|
-
**
|
|
20
|
-
to read
|
|
19
|
+
**Every adapter honours it** — each reads the field and lets it decide what the platform receives. What they can DO with it differs by platform, and a consumer should not have
|
|
20
|
+
to read every package to learn which — so the classes are stated here.
|
|
21
21
|
|
|
22
22
|
| Platform | What it does with `format` |
|
|
23
23
|
|---|---|
|
|
@@ -73,8 +73,8 @@ presenter per turn; it keeps state between `present()` calls.
|
|
|
73
73
|
|---|---|---|
|
|
74
74
|
| whatsapp | `**b**` to `*b*`, `*i*` or `_i_` to `_i_`, `~~s~~` to `~s~`, `` `c` `` to ` ```c``` ` | `plain` |
|
|
75
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` |
|
|
76
|
+
| discord, mattermost, teams, signal, nextcloud_talk | unchanged | `markdown` |
|
|
77
|
+
| telegram, matrix, email, line, sms, imessage, google_chat, irc, nostr, feishu_lark, synology_chat, tlon_urbit, twitch | the markers removed, their content kept | `plain` |
|
|
78
78
|
|
|
79
79
|
- Only the four inline markers are translated: bold, italic, strikethrough and inline code.
|
|
80
80
|
Headings, links, lists and block quotes reach every platform unchanged.
|
|
@@ -93,6 +93,135 @@ presenter per turn; it keeps state between `present()` calls.
|
|
|
93
93
|
- `@theokit/presenter` is your dependency, not this package's: `@theokit/gateway` does not depend
|
|
94
94
|
on it.
|
|
95
95
|
|
|
96
|
+
## Sending an image
|
|
97
|
+
|
|
98
|
+
`ctx.reply` takes an optional `attachments` list of images, each an `OutboundAttachment`: its
|
|
99
|
+
bytes (`data`, a `Uint8Array`), their `mediaType`, and an optional `filename`. The runner carries
|
|
100
|
+
the list to the adapter's `sendMessage` as `OutboundMessage.attachments`, by reference, and leaves
|
|
101
|
+
an empty list out. `post_outbound` hooks see the same outbound, image bytes included. Do not change
|
|
102
|
+
the bytes or the list until the reply's promise settles: Telegram reads each image only when its
|
|
103
|
+
turn comes. `DeliveryRouter.send` takes the same `attachments` field for a scheduled delivery.
|
|
104
|
+
|
|
105
|
+
Only Telegram sends images today. Code that holds the adapter reads `supportsAttachments` before
|
|
106
|
+
attaching: every other adapter reports `false` and refuses an outbound carrying attachments with
|
|
107
|
+
`attachments_unsupported`, making no platform call, so an image is never dropped in silence. An
|
|
108
|
+
edit carrying attachments is refused the same way on every adapter, Telegram included.
|
|
109
|
+
`BasePlatformAdapter`, `OutboundAttachment` and `SendResult` come from `@theokit/gateway`.
|
|
110
|
+
|
|
111
|
+
```typescript
|
|
112
|
+
async function sendChart(
|
|
113
|
+
adapter: BasePlatformAdapter,
|
|
114
|
+
channel: OutboundMessage["channel"],
|
|
115
|
+
chart: OutboundAttachment,
|
|
116
|
+
): Promise<SendResult> {
|
|
117
|
+
// No image send on this platform: say so in text instead.
|
|
118
|
+
if (!adapter.supportsAttachments) {
|
|
119
|
+
const text = "The chart is ready, but this chat cannot show images.";
|
|
120
|
+
return adapter.sendMessage({ channel, text });
|
|
121
|
+
}
|
|
122
|
+
return adapter.sendMessage({ channel, text: "Here is the chart.", attachments: [chart] });
|
|
123
|
+
}
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
The runner and the router answer `attachments_unsupported` themselves, with no `sendMessage` call,
|
|
127
|
+
when the adapter does not declare `supportsAttachments`, so an adapter that ignores the field
|
|
128
|
+
cannot drop the image and report success. A handler, which receives no adapter, branches on that
|
|
129
|
+
code:
|
|
130
|
+
|
|
131
|
+
```typescript
|
|
132
|
+
const sent = await ctx.reply("Here is the chart.", { attachments: [chart] });
|
|
133
|
+
if (sent.error?.code === "attachments_unsupported") {
|
|
134
|
+
await ctx.reply("The chart is ready, but this chat cannot show images.");
|
|
135
|
+
}
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
| Code | When |
|
|
139
|
+
|---|---|
|
|
140
|
+
| `attachments_unsupported` | the adapter cannot send attachments, the outbound is an edit, or (Telegram) an attachment's `kind` is neither `image` nor `audio` |
|
|
141
|
+
| `invalid_attachment` | Telegram only: `attachments` is not a list, holds more than 10 attachments, an entry has no bytes, an image is over 10 MiB, or an audio clip is over 50 MiB or its `mediaType` is not `audio/*` |
|
|
142
|
+
|
|
143
|
+
## Voice notes and spoken replies
|
|
144
|
+
|
|
145
|
+
An inbound event may carry `audio`, an `InboundAudio`: the voice note's bytes (`data`, a
|
|
146
|
+
`Uint8Array`), their `mediaType` (such as `audio/ogg`) and `durationSeconds`, a whole number the
|
|
147
|
+
platform reported (0 when it reported none). The field is optional and absent on every message
|
|
148
|
+
without a voice note. Only the Telegram adapter fills it today, and only for updates it polls: a
|
|
149
|
+
voice arriving through a webhook is not read. A voice the adapter could not read leaves `audio`
|
|
150
|
+
absent and writes one stderr line naming the reason, so an empty `text` with no `audio` can mean
|
|
151
|
+
either; the message is delivered in both cases. The bytes reach `post_inbound` hooks by reference.
|
|
152
|
+
|
|
153
|
+
To answer with speech, attach an audio clip: `{ kind: "audio", mediaType: "audio/ogg", data }`.
|
|
154
|
+
`OutboundAttachment` is a union of the image and the audio member, told apart by `kind`; code
|
|
155
|
+
that switches on `kind` exhaustively gains a case. Every adapter but Telegram refuses an audio
|
|
156
|
+
attachment as it refuses an image, with `attachments_unsupported` and no platform call.
|
|
157
|
+
|
|
158
|
+
```typescript
|
|
159
|
+
const runner = new GatewayRunner({
|
|
160
|
+
adapters: [adapter],
|
|
161
|
+
handler: async (event, ctx) => {
|
|
162
|
+
if (event.audio === undefined) return;
|
|
163
|
+
const text = await transcribe(event.audio.data, event.audio.mediaType);
|
|
164
|
+
const speech = await synthesize(await answer(text));
|
|
165
|
+
await ctx.reply(text, { attachments: [{ kind: "audio", mediaType: "audio/ogg", data: speech }] });
|
|
166
|
+
},
|
|
167
|
+
});
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
## Editing a sent message
|
|
171
|
+
|
|
172
|
+
Six adapters can replace the text of a message they sent, keeping its id: Telegram, Discord,
|
|
173
|
+
Slack, Mattermost, Matrix and Teams. E-mail, SMS, LINE and WhatsApp cannot, because their
|
|
174
|
+
platforms have no edit call. A caller that wants a reply to appear as a preview and then become
|
|
175
|
+
the final text reads `supportsEdit` before it starts, and falls back to `sendMessage` whenever an
|
|
176
|
+
edit is refused. `BasePlatformAdapter`, `OutboundMessage` and `SendResult` come from
|
|
177
|
+
`@theokit/gateway`.
|
|
178
|
+
|
|
179
|
+
```typescript
|
|
180
|
+
async function sendWithPreview(
|
|
181
|
+
adapter: BasePlatformAdapter,
|
|
182
|
+
out: OutboundMessage,
|
|
183
|
+
preview: string,
|
|
184
|
+
): Promise<SendResult> {
|
|
185
|
+
// No edit call on this platform: send the final text once.
|
|
186
|
+
if (!adapter.supportsEdit) return adapter.sendMessage(out);
|
|
187
|
+
const sent = await adapter.sendMessage({ ...out, text: preview });
|
|
188
|
+
if (!sent.ok || sent.messageId === undefined) return adapter.sendMessage(out);
|
|
189
|
+
// The preview must fit one message; edit_too_long and every other refusal fall back to a send.
|
|
190
|
+
const edited = await adapter.editMessage(sent.messageId, out);
|
|
191
|
+
return edited.ok ? edited : adapter.sendMessage(out);
|
|
192
|
+
}
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
`supportsEdit` is set at construction and does not change with `connect()`. `editMessage` never
|
|
196
|
+
throws on a platform error; it answers with a `SendResult`, and these refusals make no edit
|
|
197
|
+
request:
|
|
198
|
+
|
|
199
|
+
| Code | When |
|
|
200
|
+
|---|---|
|
|
201
|
+
| `edit_unsupported` | the adapter cannot edit (the four above), or a Matrix client injected without `sendMessage` |
|
|
202
|
+
| `edit_too_long` | the text would need more than one platform message, counted after a `plain` text is escaped as a send escapes it; an edit replaces one message and is never split. Matrix has no length check |
|
|
203
|
+
| `invalid_message_id` | the id is empty, or on Telegram not a positive integer |
|
|
204
|
+
| `empty_text` | the text is empty, or on Teams only whitespace |
|
|
205
|
+
| `not_connected` | the adapter is not connected, where its `sendMessage` checks that too (all but Telegram and Discord) |
|
|
206
|
+
| `invalid_channel` | Telegram only: the channel id is not numeric, as on a send |
|
|
207
|
+
| `encrypted_room_unsupported` | Matrix only: the room is encrypted, as on a send |
|
|
208
|
+
|
|
209
|
+
Any other refusal comes from the platform, mapped as `sendMessage` maps it. Keep the preview
|
|
210
|
+
within one message, and edit only a message this adapter sent: on Matrix an edit is an
|
|
211
|
+
`m.replace` event, and clients apply it only to an event from the same sender. An edit whose
|
|
212
|
+
markup the platform refuses is not retried as plain text. When an edit is refused, the sample
|
|
213
|
+
sends the final text as a new message, so the preview stays above it.
|
|
214
|
+
|
|
215
|
+
`supportsEdit` says that the adapter has an edit call, not that every edit is accepted. Treat
|
|
216
|
+
`edit_unsupported` from an adapter that reports `true` as "stop previewing", like any other
|
|
217
|
+
refusal. Where an adapter checks the connection, `not_connected` is answered before
|
|
218
|
+
`invalid_message_id`.
|
|
219
|
+
|
|
220
|
+
The adapters do not order edits. Two edits of the same message that are in flight at once can
|
|
221
|
+
reach the platform in either order, and the one that lands last stays on screen; on Matrix each
|
|
222
|
+
edit is a separate event and clients show the newest. Await each edit before sending the next,
|
|
223
|
+
or keep one in flight and send only the latest text when it settles.
|
|
224
|
+
|
|
96
225
|
## Architecture (5 pieces)
|
|
97
226
|
|
|
98
227
|
| Module | Responsibility |
|
|
@@ -172,17 +301,24 @@ for (const { platform, reason } of failed) console.error(`${platform} did not co
|
|
|
172
301
|
`GatewayConfigurationError` coded `missing_required_config` that names the keys, and reports a
|
|
173
302
|
configuration error thrown by `create` the same way. Any other error propagates. It performs no
|
|
174
303
|
network call.
|
|
304
|
+
- `createChannels` also returns `channels`: each built adapter paired with the descriptor that built it, in the order of `adapters`.
|
|
175
305
|
- `connectFailure` defaults to `"rollback"`: one failed connect disconnects the adapters that did
|
|
176
306
|
connect and rejects `start()`, as before. Under `"isolate"`, `start()` resolves even when every
|
|
177
307
|
adapter failed, so check `connected` before you rely on the runner.
|
|
178
308
|
- `start()` resolves a `StartResult` (`{ connected, failed }`) under both values. Code that awaits
|
|
179
309
|
it and ignores the value is unaffected; a type or subclass that declares
|
|
180
310
|
`start(): Promise<void>` needs to change.
|
|
181
|
-
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
311
|
+
- A runner holds one channel per platform: it routes replies and `stop()` by platform.
|
|
312
|
+
`createChannels` enforces this. The first entry built for a platform wins, and a later entry for
|
|
313
|
+
it is rejected with a `GatewayConfigurationError` coded `duplicate_channel` and never built. An
|
|
314
|
+
entry whose `create` returns an adapter reporting another platform than its descriptor is
|
|
315
|
+
rejected with the code `platform_mismatch`, and that adapter is dropped unconnected. A
|
|
316
|
+
runner you build from adapters you constructed yourself is not checked, so give it one adapter
|
|
317
|
+
per platform: with two of one platform the later one sends the earlier one's replies, and the
|
|
318
|
+
earlier one is connected but never disconnected.
|
|
319
|
+
- `start()` waits for every connect under both `connectFailure` modes, so a connect that never
|
|
320
|
+
settles blocks it. Under `"rollback"` that holds after a failure too: a failing start rejects
|
|
321
|
+
only once its slowest connect settles.
|
|
186
322
|
- A webhook channel's request reaches your HTTP route; route it by platform to the descriptor's
|
|
187
323
|
`webhook.verify(adapter, { rawBody, headers })`, then parse the body and pass it to
|
|
188
324
|
`webhook.ingest(adapter, payload)`, which answers `"delivered"`, `"malformed"` or
|
|
@@ -228,19 +364,32 @@ here). Both halves exist now, and the wiring needs three things that are easy to
|
|
|
228
364
|
import { handleChannelWebhook } from "theokit/server/agent";
|
|
229
365
|
import { route } from "theokit/server/define";
|
|
230
366
|
import { whatsapp, whatsappSubscribe } from "theokit/server/webhook";
|
|
231
|
-
import {
|
|
367
|
+
import { parseWebhookPayload, WhatsAppAdapter } from "@theokit/gateway-whatsapp";
|
|
368
|
+
|
|
369
|
+
// The adapter applies the sender allowlist and the group rule, and drops a message addressed to
|
|
370
|
+
// another phone number of the same Meta app. `normalizeInboundMessages` alone applies none of them.
|
|
371
|
+
const adapter = WhatsAppAdapter.fromCloud(
|
|
372
|
+
{
|
|
373
|
+
accessToken: process.env.WHATSAPP_ACCESS_TOKEN!,
|
|
374
|
+
phoneNumberId: process.env.WHATSAPP_PHONE_NUMBER_ID!,
|
|
375
|
+
appSecret: process.env.META_APP_SECRET!,
|
|
376
|
+
},
|
|
377
|
+
{ allowedSenders: process.env.WHATSAPP_ALLOWED },
|
|
378
|
+
);
|
|
379
|
+
|
|
380
|
+
async function onMessage({ payload }: { payload: unknown }): Promise<void> {
|
|
381
|
+
const envelope = parseWebhookPayload(payload);
|
|
382
|
+
if (envelope === null) return; // not a shape we know — answer normally
|
|
383
|
+
for (const event of adapter.toDeliverableEvents(envelope)) {
|
|
384
|
+
console.log(`${event.from}: ${event.text}`);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
232
387
|
|
|
233
388
|
const handle = ({ request }: { request: Request }) =>
|
|
234
389
|
handleChannelWebhook(request, new URL(request.url).pathname, {
|
|
235
390
|
validators: { whatsapp: whatsapp({ appSecret: process.env.META_APP_SECRET! }) },
|
|
236
391
|
subscribe: { whatsapp: whatsappSubscribe({ verifyToken: process.env.META_VERIFY_TOKEN! }) },
|
|
237
|
-
onMessage
|
|
238
|
-
const envelope = parseWebhookPayload(payload);
|
|
239
|
-
if (envelope === null) return; // not a shape we know — answer normally
|
|
240
|
-
for (const event of normalizeInboundMessages(envelope)) {
|
|
241
|
-
console.log(`${event.from}: ${event.text}`);
|
|
242
|
-
}
|
|
243
|
-
},
|
|
392
|
+
onMessage,
|
|
244
393
|
});
|
|
245
394
|
|
|
246
395
|
// BOTH verbs, and `.csrf(false)` on each.
|
|
@@ -279,7 +428,7 @@ the raw body, the headers and the URL, and `ChannelMessage` provides none of the
|
|
|
279
428
|
own `createWebhookServer` rather than this seam.
|
|
280
429
|
Every other adapter exports its translation under its own name — `gateway-line` has
|
|
281
430
|
`lineEventToMessageEvent`, `gateway-whatsapp` composes `parseWebhookPayload` with
|
|
282
|
-
`
|
|
431
|
+
`WhatsAppAdapter.toDeliverableEvents` — each with its own signature: read the one you are using rather than
|
|
283
432
|
assuming this one's.
|
|
284
433
|
|
|
285
434
|
Adapters whose transport is a long-lived connection rather than a webhook own that transport and do
|