@theokit/gateway 0.12.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 CHANGED
@@ -1,5 +1,162 @@
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
+
3
160
  ## 0.12.0
4
161
 
5
162
  ### 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
- **All ten honour it** — they read the field and let it decide what the platform receives. What they can DO with it differs by platform, and a consumer should not have
20
- to read ten packages to learn which — so the classes are stated here.
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,80 @@ 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
+
96
170
  ## Editing a sent message
97
171
 
98
172
  Six adapters can replace the text of a message they sent, keeping its id: Telegram, Discord,
@@ -227,6 +301,7 @@ for (const { platform, reason } of failed) console.error(`${platform} did not co
227
301
  `GatewayConfigurationError` coded `missing_required_config` that names the keys, and reports a
228
302
  configuration error thrown by `create` the same way. Any other error propagates. It performs no
229
303
  network call.
304
+ - `createChannels` also returns `channels`: each built adapter paired with the descriptor that built it, in the order of `adapters`.
230
305
  - `connectFailure` defaults to `"rollback"`: one failed connect disconnects the adapters that did
231
306
  connect and rejects `start()`, as before. Under `"isolate"`, `start()` resolves even when every
232
307
  adapter failed, so check `connected` before you rely on the runner.
@@ -241,8 +316,9 @@ for (const { platform, reason } of failed) console.error(`${platform} did not co
241
316
  runner you build from adapters you constructed yourself is not checked, so give it one adapter
242
317
  per platform: with two of one platform the later one sends the earlier one's replies, and the
243
318
  earlier one is connected but never disconnected.
244
- - Under `"isolate"`, and under `"rollback"` until the first failure, `start()` waits for every
245
- connect, so a connect that never settles blocks it.
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.
246
322
  - A webhook channel's request reaches your HTTP route; route it by platform to the descriptor's
247
323
  `webhook.verify(adapter, { rawBody, headers })`, then parse the body and pass it to
248
324
  `webhook.ingest(adapter, payload)`, which answers `"delivered"`, `"malformed"` or
@@ -288,19 +364,32 @@ here). Both halves exist now, and the wiring needs three things that are easy to
288
364
  import { handleChannelWebhook } from "theokit/server/agent";
289
365
  import { route } from "theokit/server/define";
290
366
  import { whatsapp, whatsappSubscribe } from "theokit/server/webhook";
291
- import { normalizeInboundMessages, parseWebhookPayload } from "@theokit/gateway-whatsapp";
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
+ }
292
387
 
293
388
  const handle = ({ request }: { request: Request }) =>
294
389
  handleChannelWebhook(request, new URL(request.url).pathname, {
295
390
  validators: { whatsapp: whatsapp({ appSecret: process.env.META_APP_SECRET! }) },
296
391
  subscribe: { whatsapp: whatsappSubscribe({ verifyToken: process.env.META_VERIFY_TOKEN! }) },
297
- onMessage: async ({ payload }) => {
298
- const envelope = parseWebhookPayload(payload);
299
- if (envelope === null) return; // not a shape we know — answer normally
300
- for (const event of normalizeInboundMessages(envelope)) {
301
- console.log(`${event.from}: ${event.text}`);
302
- }
303
- },
392
+ onMessage,
304
393
  });
305
394
 
306
395
  // BOTH verbs, and `.csrf(false)` on each.
@@ -339,7 +428,7 @@ the raw body, the headers and the URL, and `ChannelMessage` provides none of the
339
428
  own `createWebhookServer` rather than this seam.
340
429
  Every other adapter exports its translation under its own name — `gateway-line` has
341
430
  `lineEventToMessageEvent`, `gateway-whatsapp` composes `parseWebhookPayload` with
342
- `normalizeInboundMessages` — each with its own signature: read the one you are using rather than
431
+ `WhatsAppAdapter.toDeliverableEvents` — each with its own signature: read the one you are using rather than
343
432
  assuming this one's.
344
433
 
345
434
  Adapters whose transport is a long-lived connection rather than a webhook own that transport and do