@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/dist/index.js CHANGED
@@ -34,6 +34,14 @@ var BasePlatformAdapter = class {
34
34
  * edit-capable adapter can override it with `true`.
35
35
  */
36
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;
37
45
  /**
38
46
  * Replace the text of a message this adapter sent, keeping its id.
39
47
  *
@@ -132,6 +140,7 @@ function createAdapter(entry, values) {
132
140
  }
133
141
  function createChannels(entries) {
134
142
  const adapters = [];
143
+ const channels = [];
135
144
  const rejected = [];
136
145
  const builtPlatforms = /* @__PURE__ */ new Set();
137
146
  for (const entry of entries) {
@@ -142,9 +151,28 @@ function createChannels(entries) {
142
151
  continue;
143
152
  }
144
153
  adapters.push(outcome.adapter);
154
+ channels.push({ descriptor: entry.descriptor, adapter: outcome.adapter });
145
155
  builtPlatforms.add(entry.descriptor.platform);
146
156
  }
147
- return { adapters, rejected };
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;
168
+ }
169
+ return {
170
+ ok: false,
171
+ error: {
172
+ code: "attachments_unsupported",
173
+ message: `${adapter.platform} adapter cannot send attachments`
174
+ }
175
+ };
148
176
  }
149
177
 
150
178
  // src/delivery/router.ts
@@ -161,12 +189,14 @@ var DeliveryRouter = class {
161
189
  error: { code: "no_adapter", message: `no adapter for platform "${req.platform}"` }
162
190
  };
163
191
  }
164
- return adapter.sendMessage({
192
+ const outbound = {
165
193
  channel: req.channel,
166
194
  text: req.text,
167
195
  ...req.format !== void 0 ? { format: req.format } : {},
168
- ...req.replyTo !== void 0 ? { replyTo: req.replyTo } : {}
169
- });
196
+ ...req.replyTo !== void 0 ? { replyTo: req.replyTo } : {},
197
+ ...attachmentsOf(req.attachments)
198
+ };
199
+ return refuseUnsupportedAttachments(adapter, outbound) ?? adapter.sendMessage(outbound);
170
200
  }
171
201
  };
172
202
 
@@ -211,9 +241,46 @@ var CREDENTIAL_SHAPES = {
211
241
  field: "gateway-teams `clientSecret`",
212
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,
213
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"
214
249
  }
215
250
  ],
216
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
+ },
217
284
  {
218
285
  field: "gateway-sms `authToken` (Twilio), gateway-line `channelSecret`",
219
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."
@@ -384,11 +451,9 @@ async function releaseAdapters(adapters, during) {
384
451
  var GatewayRunner = class {
385
452
  constructor(opts) {
386
453
  this.opts = opts;
387
- for (const a of opts.adapters) this.adaptersByPlatform.set(a.platform, a);
388
454
  this.hookExecutor = new HookExecutor(opts.hooks ?? []);
389
455
  }
390
456
  opts;
391
- adaptersByPlatform = /* @__PURE__ */ new Map();
392
457
  hookExecutor;
393
458
  inflight = /* @__PURE__ */ new Set();
394
459
  unsubs = [];
@@ -514,7 +579,7 @@ var GatewayRunner = class {
514
579
  wireInbound(adapters) {
515
580
  for (const a of adapters) {
516
581
  const unsub = a.onInbound(async (event) => {
517
- const p = this.dispatch(event);
582
+ const p = this.dispatch(event, a);
518
583
  this.inflight.add(p);
519
584
  p.finally(() => this.inflight.delete(p));
520
585
  });
@@ -554,7 +619,7 @@ var GatewayRunner = class {
554
619
  if (timer !== void 0) clearTimeout(timer);
555
620
  }
556
621
  }
557
- await releaseAdapters([...this.adaptersByPlatform.values()], "stopping the runner");
622
+ await releaseAdapters([...new Set(this.opts.adapters)], "stopping the runner");
558
623
  }
559
624
  /**
560
625
  * @internal Test seam, following `EmailAdapter._threadStoreSize`. The drain set must SHRINK: a
@@ -566,12 +631,17 @@ var GatewayRunner = class {
566
631
  return this.inflight.size;
567
632
  }
568
633
  /** @internal */
569
- async dispatch(event) {
570
- const ctx = this.buildContext(event);
634
+ async dispatch(event, adapter) {
635
+ const ctx = this.buildContext(event, adapter);
571
636
  const decision = await this.hookExecutor.firePreInbound({ event });
572
637
  if (decision.block === true) {
573
638
  if (decision.message !== void 0 && decision.message.length > 0) {
574
- await ctx.reply(decision.message).catch(() => void 0);
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
+ });
575
645
  }
576
646
  return;
577
647
  }
@@ -616,13 +686,14 @@ var GatewayRunner = class {
616
686
  return void 0;
617
687
  }
618
688
  /** EC-G: per-event ctx whose reply routes to the matching adapter. */
619
- buildContext(event) {
689
+ buildContext(event, adapter) {
620
690
  return {
621
691
  event,
622
- reply: async (text, opts) => this.deliver(event, {
692
+ reply: async (text, opts) => this.deliver(event, adapter, {
623
693
  channel: event.channel,
624
694
  text,
625
- ...opts?.format !== void 0 ? { format: opts.format } : {}
695
+ ...opts?.format !== void 0 ? { format: opts.format } : {},
696
+ ...attachmentsOf(opts?.attachments)
626
697
  })
627
698
  };
628
699
  }
@@ -634,6 +705,10 @@ var GatewayRunner = class {
634
705
  * adapter for the platform. An audit hook that counted only the deliveries
635
706
  * which reached a transport would omit precisely the ones that went nowhere.
636
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
+ *
637
712
  * `post_outbound` observes; it does not intercept. The adapter's `SendResult`
638
713
  * is returned to the caller unchanged, and `HookExecutor` already contains a
639
714
  * throwing hook, so a broken observer cannot turn a delivered reply into a
@@ -641,9 +716,9 @@ var GatewayRunner = class {
641
716
  *
642
717
  * @internal
643
718
  */
644
- async deliver(event, outbound) {
645
- const adapter = this.adaptersByPlatform.get(event.platform);
646
- const result = adapter === void 0 ? { ok: false, error: { code: "no_adapter", message: `no adapter for ${event.platform}` } } : await adapter.sendMessage(outbound);
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);
647
722
  await this.hookExecutor.firePostOutbound({ event, outbound, result });
648
723
  return result;
649
724
  }
@@ -679,6 +754,64 @@ var SessionRouter = class {
679
754
  }
680
755
  };
681
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
+
682
815
  // src/text/dialect.ts
683
816
  var DIALECTS = {
684
817
  // WhatsApp emphasis is inline and single-character: *bold*, _italic_, ~strike~, ```mono```.
@@ -701,18 +834,90 @@ function toDialect(text, platform) {
701
834
  if (dialect === void 0) return text;
702
835
  return rewriteMarkers(text, dialect);
703
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
+ }
704
900
  function rewriteMarkers(text, dialect) {
705
- return text.replace(PATTERN, (matched, ...args) => {
706
- const groups = args.at(-1);
707
- if (groups === void 0) return matched;
708
- for (const [group, marker] of GROUP_MARKERS) {
709
- const content = groups[group];
710
- if (content === void 0) continue;
711
- const wrap = dialect[marker];
712
- return wrap === void 0 ? content : `${wrap}${content}${wrap}`;
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));
713
917
  }
714
- return matched;
918
+ return rewriteMatch(matched, args, dialect);
715
919
  });
920
+ return crossesRowPipe ? rewriteByLine(text, dialect) : rewritten;
716
921
  }
717
922
 
718
923
  // src/text/channel-rendering.ts
@@ -735,7 +940,15 @@ var RENDERINGS = {
735
940
  imessage: { format: "plain", translate: translateWith(STRIP) },
736
941
  google_chat: { format: "plain", translate: translateWith(STRIP) },
737
942
  irc: { format: "plain", translate: translateWith(STRIP) },
738
- nextcloud_talk: { format: "markdown", translate: identity }
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) }
739
952
  };
740
953
  function channelRendering(platform) {
741
954
  const rendering = Object.hasOwn(RENDERINGS, platform) ? RENDERINGS[platform] : void 0;
@@ -774,6 +987,63 @@ function findCut(remaining, window, boundaries, lastResort, surrogateGuard) {
774
987
  if (surrogateGuard) cut = guardSurrogate(remaining, cut);
775
988
  return cut <= 0 ? window : cut;
776
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
+ }
777
1047
  function chunkText(text, options) {
778
1048
  const {
779
1049
  limit,
@@ -782,7 +1052,8 @@ function chunkText(text, options) {
782
1052
  lastResort = "window",
783
1053
  surrogateGuard = false,
784
1054
  stripLeading = /^\n+/,
785
- trimParts = false
1055
+ trimParts = false,
1056
+ keepTableRows = false
786
1057
  } = options;
787
1058
  assertPositiveInt("chunkText: limit", limit);
788
1059
  assertPositiveInt("chunkText: safeLimit", safeLimit);
@@ -794,11 +1065,16 @@ function chunkText(text, options) {
794
1065
  return finalize([text]);
795
1066
  }
796
1067
  const parts = [];
1068
+ const hasFence = scanFences(text).length > 0;
797
1069
  let remaining = text;
798
1070
  while (remaining.length > safeLimit) {
799
1071
  const cut = findCut(remaining, safeLimit, boundaries, lastResort, surrogateGuard);
800
- parts.push(remaining.slice(0, cut));
801
- remaining = remaining.slice(cut).replace(stripLeading, "");
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;
802
1078
  }
803
1079
  if (remaining.length > 0) parts.push(remaining);
804
1080
  return finalize(parts);
@@ -809,6 +1085,8 @@ function chunkByGrapheme(text, options) {
809
1085
  assertPositiveInt("chunkByGrapheme: partLimit", partLimit);
810
1086
  if (text.length === 0) return [""];
811
1087
  if (text.length <= limit) return [text];
1088
+ const regions = scanFences(text);
1089
+ if (regions.length > 0) return chunkFencedByGrapheme(text, partLimit, regions);
812
1090
  const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
813
1091
  const parts = [];
814
1092
  let buf = "";
@@ -822,6 +1100,132 @@ function chunkByGrapheme(text, options) {
822
1100
  if (buf.length > 0) parts.push(buf);
823
1101
  return parts;
824
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
+ }
825
1229
 
826
1230
  // src/webhook/express-server.ts
827
1231
  async function loadPeer(load, onMissing) {
@@ -932,6 +1336,6 @@ function listenerLifecycle(opts) {
932
1336
  };
933
1337
  }
934
1338
 
935
- 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 };
936
1340
  //# sourceMappingURL=index.js.map
937
1341
  //# sourceMappingURL=index.js.map