@theokit/gateway 0.18.0 → 0.19.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
@@ -214,7 +214,7 @@ function channelRendering(platform) {
214
214
  }
215
215
 
216
216
  // src/adapter/base.ts
217
- var BasePlatformAdapter = class {
217
+ var BasePlatformAdapter = class _BasePlatformAdapter {
218
218
  /**
219
219
  * Run a subscribed handler and contain its failure. The body of {@link deliver}, written once.
220
220
  *
@@ -305,6 +305,27 @@ var BasePlatformAdapter = class {
305
305
  * `boolean` so that an adapter that sends images can override it with `true`.
306
306
  */
307
307
  supportsAttachments = false;
308
+ /**
309
+ * The attachment kinds {@link sendMessage} can send. `undefined` means "not declared": the
310
+ * `capabilities` getter then reports `["image"]` when `supportsAttachments` is `true`, else `[]`.
311
+ */
312
+ attachmentKinds = void 0;
313
+ /**
314
+ * What this adapter can do, for an app that renders differently per channel.
315
+ *
316
+ * Derived from the members above and from which lifecycle methods the subclass overrides; an
317
+ * adapter overrides the getter only for what derivation cannot know. Read it at call time.
318
+ */
319
+ get capabilities() {
320
+ const proto = _BasePlatformAdapter.prototype;
321
+ return {
322
+ edit: this.supportsEdit,
323
+ attachments: this.attachmentKinds ?? (this.supportsAttachments ? ["image"] : []),
324
+ typing: this.startTyping !== proto.startTyping,
325
+ reactions: this.react !== proto.react,
326
+ threads: false
327
+ };
328
+ }
308
329
  /**
309
330
  * Replace the text of a message this adapter sent, keeping its id.
310
331
  *
@@ -531,6 +552,11 @@ var WeixinAdapterBase = class extends BasePlatformAdapter {
531
552
  }
532
553
  };
533
554
 
555
+ // src/channel/channel-descriptor.ts
556
+ function isAuthenticatedSender(descriptor) {
557
+ return descriptor.senderIdentity === "authenticated";
558
+ }
559
+
534
560
  // src/errors/config-error.ts
535
561
  var GatewayConfigurationError = class extends Error {
536
562
  name = "GatewayConfigurationError";
@@ -670,6 +696,72 @@ var GatewayLifecycleError = class extends Error {
670
696
  this.code = opts.code;
671
697
  }
672
698
  };
699
+
700
+ // src/hooks/chat-command.ts
701
+ var LEADING_MENTION = /^(?:<@[^>]+>|@\S+)\s+/;
702
+ var DEFAULT_PREFIXES = ["/"];
703
+ function matchPrefix(text, prefixes) {
704
+ let best;
705
+ for (const p of prefixes) {
706
+ if (p.length > 0 && text.startsWith(p) && (best === void 0 || p.length > best.length)) {
707
+ best = p;
708
+ }
709
+ }
710
+ return best;
711
+ }
712
+ function parseChatCommand(text, options) {
713
+ const body = text.trim().replace(LEADING_MENTION, "");
714
+ const prefix = matchPrefix(body, options?.prefixes ?? DEFAULT_PREFIXES);
715
+ if (prefix === void 0) return void 0;
716
+ const rest = body.slice(prefix.length);
717
+ const m = /^([^\s@]+)(?:@\S+)?(?:\s+([\s\S]*))?$/.exec(rest);
718
+ if (!m?.[1]) return void 0;
719
+ return { name: m[1].toLowerCase(), arg: (m[2] ?? "").trim() };
720
+ }
721
+ function usageOf(c) {
722
+ return c.usage ?? `/${c.name}`;
723
+ }
724
+ function helpText(commands) {
725
+ return commands.map((c) => `${usageOf(c)} - ${c.description}`).join("\n");
726
+ }
727
+ function assertUnique(names) {
728
+ const seen = /* @__PURE__ */ new Set();
729
+ for (const raw of names) {
730
+ const name = raw.toLowerCase();
731
+ if (seen.has(name)) {
732
+ throw new GatewayConfigurationError("gateway", {
733
+ code: "duplicate_command",
734
+ message: `gateway: duplicate_command: ${raw}`,
735
+ detail: raw
736
+ });
737
+ }
738
+ seen.add(name);
739
+ }
740
+ }
741
+ function badArity(c, arg) {
742
+ const mode = c.arg ?? "optional";
743
+ return mode === "none" && arg !== "" || mode === "required" && arg === "";
744
+ }
745
+ function commandHook(commands, options) {
746
+ const helpName = options?.helpCommand === void 0 ? "help" : options.helpCommand;
747
+ assertUnique([...commands.map((c) => c.name), ...helpName === false ? [] : [helpName]]);
748
+ const byName = new Map(commands.map((c) => [c.name.toLowerCase(), c]));
749
+ const help = helpText(commands);
750
+ return {
751
+ name: options?.name ?? "chat-commands",
752
+ async pre_inbound({ event }) {
753
+ const parsed = parseChatCommand(event.text);
754
+ if (!parsed) return void 0;
755
+ if (helpName !== false && parsed.name === helpName.toLowerCase()) {
756
+ return { block: true, message: help };
757
+ }
758
+ const command = byName.get(parsed.name);
759
+ if (!command) return void 0;
760
+ if (badArity(command, parsed.arg)) return { block: true, message: usageOf(command) };
761
+ return command.run(event, parsed.arg);
762
+ }
763
+ };
764
+ }
673
765
  var UNCOVERED_TABLE = `gateway-qq \`appSecret\` :: a QQ Bot AppSecret, an opaque 32-character string with no prefix or fixed shape. It travels only to the access-token endpoint and into the webhook signature derivation; the adapter never logs it.
674
766
  gateway-x \`clientSecret\`, \`refreshToken\`, \`bearerToken\` :: an X OAuth 2.0 client secret, a rotating refresh token and an app bearer token, opaque strings with no fixed prefix. They travel only to the X API in Authorization headers and the token request body, which the adapter never logs.
675
767
  gateway-buzz \`token\` :: a Buzz bot token with no fixed shape this package could confirm. It travels only in Authorization headers, which the adapter never logs.
@@ -747,6 +839,12 @@ function maskShapes(text) {
747
839
  function redactSecrets(value) {
748
840
  return Security.redact(maskShapes(typeof value === "string" ? value : String(value)));
749
841
  }
842
+ function maskSecrets(text, secrets) {
843
+ const ordered = [...new Set(secrets)].filter((s) => s.length > 0).sort((a, b) => b.length - a.length);
844
+ let out = text;
845
+ for (const secret of ordered) out = out.split(secret).join("[redacted]");
846
+ return out;
847
+ }
750
848
 
751
849
  // src/hooks/executor.ts
752
850
  var HOOK_PHASES = ["pre_inbound", "post_outbound", "on_error"];
@@ -860,10 +958,10 @@ function keepTyping(adapter, channelId) {
860
958
  };
861
959
  }
862
960
  var DEFAULT_COMMAND_PREFIXES = ["/"];
863
- function connectFailureReason(outcome) {
961
+ function connectFailureReason(outcome, redact) {
864
962
  if (outcome.status === "fulfilled") return "connect returned false";
865
963
  const message = outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason);
866
- return redactSecrets(message);
964
+ return redact(message);
867
965
  }
868
966
  function isTerminalConnectError(err) {
869
967
  if (typeof err !== "object" || err === null) return false;
@@ -877,7 +975,7 @@ function isTerminalConnectError(err) {
877
975
  message
878
976
  );
879
977
  }
880
- async function releaseAdapters(adapters, during) {
978
+ async function releaseAdapters(adapters, during, redact = redactSecrets) {
881
979
  await Promise.all(
882
980
  adapters.map(async (a) => {
883
981
  try {
@@ -885,7 +983,7 @@ async function releaseAdapters(adapters, during) {
885
983
  } catch (err) {
886
984
  const message = err instanceof Error ? err.message : String(err);
887
985
  process.stderr.write(
888
- `[gateway] adapter "${a.platform}" disconnect failed while ${during}: ${redactSecrets(message)}
986
+ `[gateway] adapter "${a.platform}" disconnect failed while ${during}: ${redact(message)}
889
987
  `
890
988
  );
891
989
  }
@@ -896,6 +994,8 @@ var GatewayRunner = class {
896
994
  constructor(opts) {
897
995
  this.opts = opts;
898
996
  this.hookExecutor = new HookExecutor(opts.hooks ?? []);
997
+ const secrets = opts.secrets ?? [];
998
+ this.redact = (text) => redactSecrets(maskSecrets(text, secrets));
899
999
  }
900
1000
  opts;
901
1001
  hookExecutor;
@@ -908,6 +1008,23 @@ var GatewayRunner = class {
908
1008
  startInFlight;
909
1009
  stopped = false;
910
1010
  retryTimers = /* @__PURE__ */ new Set();
1011
+ connectedPlatforms = /* @__PURE__ */ new Set();
1012
+ redact;
1013
+ /** The registered adapter for a platform, connected or not. */
1014
+ adapter(platform) {
1015
+ return this.opts.adapters.find((a) => a.platform === platform);
1016
+ }
1017
+ /** Platforms whose adapter is connected now; updated by connects, retries and `stop()`. */
1018
+ get connected() {
1019
+ return this.connectedPlatforms;
1020
+ }
1021
+ emitState(platform, state, reason) {
1022
+ if ((this.opts.connectFailure ?? "rollback") !== "isolate") return;
1023
+ try {
1024
+ this.opts.onAdapterState?.(platform, state, reason);
1025
+ } catch {
1026
+ }
1027
+ }
911
1028
  /**
912
1029
  * Register a slash command. Match rule (EC-A): text === "/" + name
913
1030
  * OR text.startsWith("/" + name + " ") OR text.startsWith("/" + name + "@").
@@ -962,11 +1079,17 @@ var GatewayRunner = class {
962
1079
  async runStart() {
963
1080
  const result = (this.opts.connectFailure ?? "rollback") === "isolate" ? await this.connectIsolated() : await this.connectAllOrRollback();
964
1081
  if (this.stopped) {
965
- await releaseAdapters(result.connected, "releasing a start that stop() overtook");
1082
+ await releaseAdapters(
1083
+ result.connected,
1084
+ "releasing a start that stop() overtook",
1085
+ this.redact
1086
+ );
1087
+ this.connectedPlatforms.clear();
966
1088
  this.startResult = { connected: [], failed: result.failed };
967
1089
  return this.startResult;
968
1090
  }
969
1091
  this.wireInbound(result.connected);
1092
+ for (const a of result.connected) this.connectedPlatforms.add(a.platform);
970
1093
  this.startResult = {
971
1094
  connected: result.connected.map((a) => a.platform),
972
1095
  failed: result.failed
@@ -999,16 +1122,23 @@ var GatewayRunner = class {
999
1122
  `[gateway] adapter "${adapter.platform}" reconnect attempt ${attempt} in ${delay}ms
1000
1123
  `
1001
1124
  );
1125
+ this.emitState(adapter.platform, "retrying", `reconnect attempt ${attempt} in ${delay}ms`);
1002
1126
  }
1003
1127
  async reconnectOnce(adapter, attempt) {
1004
1128
  if (this.stopped) return;
1005
1129
  try {
1006
1130
  if (await adapter.connect()) {
1007
1131
  if (this.stopped) {
1008
- await releaseAdapters([adapter], "releasing a reconnect that stop() overtook");
1132
+ await releaseAdapters(
1133
+ [adapter],
1134
+ "releasing a reconnect that stop() overtook",
1135
+ this.redact
1136
+ );
1009
1137
  return;
1010
1138
  }
1011
1139
  this.wireInbound([adapter]);
1140
+ this.connectedPlatforms.add(adapter.platform);
1141
+ this.emitState(adapter.platform, "connected");
1012
1142
  const prev = this.startResult ?? { connected: [], failed: [] };
1013
1143
  this.startResult = {
1014
1144
  connected: [...prev.connected, adapter.platform],
@@ -1026,8 +1156,9 @@ var GatewayRunner = class {
1026
1156
  );
1027
1157
  return;
1028
1158
  } catch (err) {
1029
- const reason = connectFailureReason({ status: "rejected", reason: err });
1159
+ const reason = connectFailureReason({ status: "rejected", reason: err }, this.redact);
1030
1160
  if (isTerminalConnectError(err)) {
1161
+ this.emitState(adapter.platform, "failed", reason);
1031
1162
  process.stderr.write(
1032
1163
  `[gateway] adapter "${adapter.platform}" credentials rejected: ${reason}; not retrying
1033
1164
  `
@@ -1067,7 +1198,7 @@ var GatewayRunner = class {
1067
1198
  );
1068
1199
  if (failures.length > 0) {
1069
1200
  const connected = adapters.filter((_, i) => settled[i]?.status === "fulfilled");
1070
- await releaseAdapters(connected, "rolling back a failed start");
1201
+ await releaseAdapters(connected, "rolling back a failed start", this.redact);
1071
1202
  throw failures[0];
1072
1203
  }
1073
1204
  return { connected: [...adapters], failed: [], retryable: [] };
@@ -1079,22 +1210,55 @@ var GatewayRunner = class {
1079
1210
  */
1080
1211
  async connectIsolated() {
1081
1212
  const adapters = this.opts.adapters;
1082
- const settled = await Promise.allSettled(adapters.map(async (a) => a.connect()));
1213
+ const results = await Promise.all(adapters.map((a) => this.connectOne(a)));
1083
1214
  const connected = [];
1084
1215
  const failed = [];
1085
1216
  const retryable = [];
1086
- settled.forEach((outcome, i) => {
1087
- const adapter = adapters[i];
1088
- if (outcome.status === "fulfilled" && outcome.value) connected.push(adapter);
1089
- else {
1090
- failed.push({ platform: adapter.platform, reason: connectFailureReason(outcome) });
1091
- if (outcome.status === "rejected" && !isTerminalConnectError(outcome.reason)) {
1092
- retryable.push(adapter);
1093
- }
1094
- }
1095
- });
1217
+ for (const r of results) {
1218
+ if (r.failure === void 0) connected.push(r.adapter);
1219
+ else failed.push(r.failure);
1220
+ if (r.retry) retryable.push(r.adapter);
1221
+ }
1096
1222
  return { connected, failed, retryable };
1097
1223
  }
1224
+ /** Connect one adapter, bounded by `connectTimeoutMs`, and report its state as it settles. */
1225
+ async connectOne(adapter) {
1226
+ const attempt = Promise.allSettled([(async () => adapter.connect())()]).then(
1227
+ ([r]) => r
1228
+ );
1229
+ const ms = this.opts.connectTimeoutMs;
1230
+ if (ms === void 0) return this.classify(adapter, await attempt);
1231
+ let timer;
1232
+ const first = await Promise.race([
1233
+ attempt,
1234
+ new Promise((resolve) => {
1235
+ timer = setTimeout(() => resolve("timeout"), ms);
1236
+ })
1237
+ ]);
1238
+ if (timer !== void 0) clearTimeout(timer);
1239
+ if (first !== "timeout") return this.classify(adapter, first);
1240
+ void attempt.then((late) => this.releaseLateConnect(adapter, late));
1241
+ const reason = `connect timed out after ${ms}ms`;
1242
+ this.emitState(adapter.platform, "timed_out", reason);
1243
+ return { adapter, failure: { platform: adapter.platform, reason }, retry: true };
1244
+ }
1245
+ /** A connect that finished after the runner gave up on it must not stay connected unseen. */
1246
+ releaseLateConnect(adapter, late) {
1247
+ if (late.status !== "fulfilled" || !late.value) return;
1248
+ if (this.connectedPlatforms.has(adapter.platform)) return;
1249
+ void releaseAdapters([adapter], "releasing a connect that timed out", this.redact);
1250
+ }
1251
+ classify(adapter, outcome) {
1252
+ if (outcome.status === "fulfilled" && outcome.value) {
1253
+ this.connectedPlatforms.add(adapter.platform);
1254
+ this.emitState(adapter.platform, "connected");
1255
+ return { adapter, failure: void 0, retry: false };
1256
+ }
1257
+ const reason = connectFailureReason(outcome, this.redact);
1258
+ this.emitState(adapter.platform, "failed", reason);
1259
+ const retry = outcome.status === "rejected" && !isTerminalConnectError(outcome.reason);
1260
+ return { adapter, failure: { platform: adapter.platform, reason }, retry };
1261
+ }
1098
1262
  wireInbound(adapters) {
1099
1263
  for (const a of adapters) {
1100
1264
  const unsub = a.onInbound(async (event) => {
@@ -1126,6 +1290,7 @@ var GatewayRunner = class {
1126
1290
  this.unsubs.length = 0;
1127
1291
  for (const t of this.retryTimers) clearTimeout(t);
1128
1292
  this.retryTimers.clear();
1293
+ this.connectedPlatforms.clear();
1129
1294
  const drainMs = this.opts.drainTimeoutMs ?? DEFAULT_DRAIN_MS;
1130
1295
  if (this.inflight.size > 0) {
1131
1296
  let timer;
@@ -1140,7 +1305,7 @@ var GatewayRunner = class {
1140
1305
  if (timer !== void 0) clearTimeout(timer);
1141
1306
  }
1142
1307
  }
1143
- await releaseAdapters([...new Set(this.opts.adapters)], "stopping the runner");
1308
+ await releaseAdapters([...new Set(this.opts.adapters)], "stopping the runner", this.redact);
1144
1309
  }
1145
1310
  /**
1146
1311
  * @internal Test seam, following `EmailAdapter._threadStoreSize`. The drain set must SHRINK: a
@@ -1160,7 +1325,7 @@ var GatewayRunner = class {
1160
1325
  await ctx.reply(decision.message).catch(async (err) => {
1161
1326
  const error = err;
1162
1327
  await this.hookExecutor.fireOnError({ event, error });
1163
- process.stderr.write(`[gateway] auto-reply error: ${redactSecrets(error.message)}
1328
+ process.stderr.write(`[gateway] auto-reply error: ${this.redact(error.message)}
1164
1329
  `);
1165
1330
  });
1166
1331
  }
@@ -1174,7 +1339,7 @@ var GatewayRunner = class {
1174
1339
  await handler(event, ctx);
1175
1340
  } catch (err) {
1176
1341
  await this.hookExecutor.fireOnError({ event, error: err });
1177
- process.stderr.write(`[gateway] handler error: ${redactSecrets(err.message)}
1342
+ process.stderr.write(`[gateway] handler error: ${this.redact(err.message)}
1178
1343
  `);
1179
1344
  } finally {
1180
1345
  await stopTyping();
@@ -1326,6 +1491,67 @@ var SessionRouter = class {
1326
1491
  }
1327
1492
  };
1328
1493
 
1494
+ // src/session/bindings.ts
1495
+ function unknownAgent(agent) {
1496
+ return new GatewayConfigurationError("gateway", {
1497
+ code: "unknown_agent",
1498
+ message: `gateway: unknown_agent: ${agent}`,
1499
+ detail: agent
1500
+ });
1501
+ }
1502
+ function createAgentBindings(options) {
1503
+ const known = new Set(options.agents);
1504
+ if (!known.has(options.defaultAgent)) throw unknownAgent(options.defaultAgent);
1505
+ for (const rule of options.rules) {
1506
+ if (!known.has(rule.agent)) throw unknownAgent(rule.agent);
1507
+ if (rule.platform === void 0 && rule.account === void 0 && rule.peer === void 0) {
1508
+ throw new GatewayConfigurationError("gateway", {
1509
+ code: "empty_binding_rule",
1510
+ message: `gateway: empty_binding_rule: ${rule.agent}`,
1511
+ detail: rule.agent
1512
+ });
1513
+ }
1514
+ }
1515
+ const rules = [...options.rules];
1516
+ const { accountOf } = options;
1517
+ return {
1518
+ agentFor(event) {
1519
+ const ctx = {
1520
+ platform: event.platform,
1521
+ account: accountOf?.(event),
1522
+ peer: event.channel.type === "dm" ? event.sender.id : event.channel.id
1523
+ };
1524
+ let best = options.defaultAgent;
1525
+ let bestScore = 0;
1526
+ for (const rule of rules) {
1527
+ const score = scoreRule(rule, ctx);
1528
+ if (score > bestScore) {
1529
+ best = rule.agent;
1530
+ bestScore = score;
1531
+ }
1532
+ }
1533
+ return best;
1534
+ }
1535
+ };
1536
+ }
1537
+ function scoreRule(rule, ctx) {
1538
+ const fields = [
1539
+ [rule.platform, ctx.platform, 1],
1540
+ [rule.account, ctx.account, 2],
1541
+ [rule.peer, ctx.peer, 4]
1542
+ ];
1543
+ let score = 0;
1544
+ for (const [want, got, weight] of fields) {
1545
+ if (want === void 0) continue;
1546
+ if (want !== got) return 0;
1547
+ score += weight;
1548
+ }
1549
+ return score;
1550
+ }
1551
+ function bindingStrategy(bindings, inner) {
1552
+ return (event) => `${sanitize(bindings.agentFor(event))}-${inner(event)}`;
1553
+ }
1554
+
1329
1555
  // src/text/chunk.ts
1330
1556
  function searchBoundary(remaining, window, boundaries) {
1331
1557
  let cut = window;
@@ -1483,9 +1709,9 @@ function chunkFencedByGrapheme(text, partLimit, regions) {
1483
1709
  let prefix = "";
1484
1710
  while (prefix.length + (text.length - pos) > partLimit) {
1485
1711
  const room = partLimit - prefix.length;
1486
- const plain = boundaryUpTo(pos, pos + room);
1487
- const region = fenceAt(regions, plain);
1488
- const next = region === void 0 ? { cut: plain, suffix: "", reopen: "" } : fenceGraphemeCut(text, region, pos, plain, room, boundaryUpTo);
1712
+ const plain2 = boundaryUpTo(pos, pos + room);
1713
+ const region = fenceAt(regions, plain2);
1714
+ const next = region === void 0 ? { cut: plain2, suffix: "", reopen: "" } : fenceGraphemeCut(text, region, pos, plain2, room, boundaryUpTo);
1489
1715
  parts.push(prefix + text.slice(pos, next.cut) + next.suffix);
1490
1716
  pos = next.cut;
1491
1717
  prefix = next.reopen;
@@ -1493,9 +1719,9 @@ function chunkFencedByGrapheme(text, partLimit, regions) {
1493
1719
  parts.push(prefix + text.slice(pos));
1494
1720
  return parts;
1495
1721
  }
1496
- function fenceGraphemeCut(text, region, pos, plain, room, boundaryUpTo) {
1497
- const none = { cut: plain, suffix: "", reopen: "" };
1498
- if (plain <= region.openerEnd) {
1722
+ function fenceGraphemeCut(text, region, pos, plain2, room, boundaryUpTo) {
1723
+ const none = { cut: plain2, suffix: "", reopen: "" };
1724
+ if (plain2 <= region.openerEnd) {
1499
1725
  return region.start > pos ? { ...none, cut: region.start } : none;
1500
1726
  }
1501
1727
  const eol = openerEol(text, region);
@@ -1560,6 +1786,21 @@ function splitKeepingRows(text, partLimit) {
1560
1786
  return parts;
1561
1787
  }
1562
1788
 
1789
+ // src/webhook/deliver-status.ts
1790
+ function statusForDeliver(outcomes) {
1791
+ let status = 200;
1792
+ for (const outcome of outcomes) {
1793
+ if (outcome === "handler_threw") {
1794
+ status = 500;
1795
+ } else if (outcome === "no_handler") {
1796
+ if (status === 200) status = 503;
1797
+ } else if (outcome !== "ok") {
1798
+ throw new Error(`unknown deliver outcome: ${outcome}`);
1799
+ }
1800
+ }
1801
+ return status;
1802
+ }
1803
+
1563
1804
  // src/webhook/express-server.ts
1564
1805
  async function loadPeer(load, onMissing) {
1565
1806
  try {
@@ -1670,6 +1911,126 @@ function listenerLifecycle(opts) {
1670
1911
  };
1671
1912
  }
1672
1913
 
1673
- export { BasePlatformAdapter, CREDENTIAL_SHAPES, DEFAULT_WEBHOOK_MAX_BYTES, DeliveryRouter, GatewayConfigurationError, GatewayLifecycleError, GatewayRunner, HookExecutor, SeenIds, SessionRouter, WeixinAdapterBase, channelRendering, chunkByGrapheme, chunkText, createChannels, defaultStrategy, listenerLifecycle, loadPeer, maskShapes, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, splitKeepingRows, toDialect, withMediaUnderstanding };
1914
+ // src/webhook/fetch-handler.ts
1915
+ var TOO_LARGE = /* @__PURE__ */ Symbol("too-large");
1916
+ function defaultPlatformFor(url) {
1917
+ const marker = "/webhooks/";
1918
+ const at = url.pathname.lastIndexOf(marker);
1919
+ if (at < 0) return void 0;
1920
+ const rest = url.pathname.slice(at + marker.length).replace(/\/+$/, "");
1921
+ const last = rest.split("/").pop();
1922
+ return last ? last : void 0;
1923
+ }
1924
+ function plain(status, extra) {
1925
+ return new Response(null, { status, headers: extra });
1926
+ }
1927
+ function tooLarge() {
1928
+ return plain(413, { connection: "close" });
1929
+ }
1930
+ async function readCapped(request, max) {
1931
+ const declared = request.headers.get("content-length");
1932
+ if (declared !== null && Number(declared) > max) return TOO_LARGE;
1933
+ if (request.body === null) return "";
1934
+ const reader = request.body.getReader();
1935
+ const chunks = [];
1936
+ let total = 0;
1937
+ for (; ; ) {
1938
+ const { done, value } = await reader.read();
1939
+ if (done) break;
1940
+ total += value.byteLength;
1941
+ if (total > max) {
1942
+ await reader.cancel().catch(() => void 0);
1943
+ return TOO_LARGE;
1944
+ }
1945
+ chunks.push(value);
1946
+ }
1947
+ const joined = new Uint8Array(total);
1948
+ let offset = 0;
1949
+ for (const chunk of chunks) {
1950
+ joined.set(chunk, offset);
1951
+ offset += chunk.byteLength;
1952
+ }
1953
+ return new TextDecoder().decode(joined);
1954
+ }
1955
+ function answerResponse(answer) {
1956
+ const headers = {};
1957
+ if (answer.contentType !== void 0) headers["content-type"] = answer.contentType;
1958
+ return new Response(answer.body ?? null, { status: answer.status, headers });
1959
+ }
1960
+ async function runDefault(webhook, adapter, request) {
1961
+ if (!webhook.verify(adapter, request)) return plain(401);
1962
+ let payload;
1963
+ try {
1964
+ payload = JSON.parse(request.rawBody);
1965
+ } catch {
1966
+ return plain(400);
1967
+ }
1968
+ const result = await webhook.ingest(adapter, payload);
1969
+ if (result === "delivered") return plain(200);
1970
+ return plain(result === "no_handler" ? 503 : 400);
1971
+ }
1972
+ function headersOf(request) {
1973
+ const out = {};
1974
+ request.headers.forEach((value, key) => {
1975
+ out[key] = value;
1976
+ });
1977
+ return out;
1978
+ }
1979
+ async function readBody(request, max) {
1980
+ let body;
1981
+ try {
1982
+ body = await readCapped(request, max);
1983
+ } catch {
1984
+ return plain(400);
1985
+ }
1986
+ return body === TOO_LARGE ? tooLarge() : body;
1987
+ }
1988
+ function createWebhookHandler(options) {
1989
+ const max = options.maxBodyBytes ?? DEFAULT_WEBHOOK_MAX_BYTES;
1990
+ const platformFor = options.platformFor ?? defaultPlatformFor;
1991
+ const routes = /* @__PURE__ */ new Map();
1992
+ for (const channel of options.channels) {
1993
+ if (channel.descriptor.transport === "webhook")
1994
+ routes.set(channel.descriptor.platform, channel);
1995
+ }
1996
+ const route = (url) => {
1997
+ const platform = platformFor(url);
1998
+ return platform === void 0 ? void 0 : routes.get(platform);
1999
+ };
2000
+ return async (request) => {
2001
+ const channel = route(new URL(request.url));
2002
+ if (channel === void 0) return plain(404);
2003
+ const platform = channel.descriptor.platform;
2004
+ if (!options.isStarted(platform)) return plain(503);
2005
+ const webhook = channel.descriptor.webhook;
2006
+ const refused2 = refuseMethod(webhook, request);
2007
+ if (refused2 !== void 0) return refused2;
2008
+ const rawBody = await readBody(request, max);
2009
+ if (typeof rawBody !== "string") return rawBody;
2010
+ try {
2011
+ return await dispatch(webhook, channel.adapter, {
2012
+ rawBody,
2013
+ headers: headersOf(request),
2014
+ method: request.method.toUpperCase(),
2015
+ url: request.url
2016
+ });
2017
+ } catch (error) {
2018
+ options.onError?.(platform, error);
2019
+ return plain(500);
2020
+ }
2021
+ };
2022
+ }
2023
+ function refuseMethod(webhook, request) {
2024
+ const methods = webhook.methods ?? ["POST"];
2025
+ const method = request.method.toUpperCase();
2026
+ if (methods.some((m) => m.toUpperCase() === method)) return void 0;
2027
+ return plain(405, { allow: methods.join(", ") });
2028
+ }
2029
+ async function dispatch(webhook, adapter, request) {
2030
+ if (webhook.handle !== void 0) return answerResponse(await webhook.handle(adapter, request));
2031
+ return runDefault(webhook, adapter, request);
2032
+ }
2033
+
2034
+ export { BasePlatformAdapter, CREDENTIAL_SHAPES, DEFAULT_WEBHOOK_MAX_BYTES, DeliveryRouter, GatewayConfigurationError, GatewayLifecycleError, GatewayRunner, HookExecutor, SeenIds, SessionRouter, WeixinAdapterBase, bindingStrategy, channelRendering, chunkByGrapheme, chunkText, commandHook, createAgentBindings, createChannels, createWebhookHandler, defaultStrategy, helpText, isAuthenticatedSender, listenerLifecycle, loadPeer, maskSecrets, maskShapes, parseChatCommand, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, splitKeepingRows, statusForDeliver, toDialect, withMediaUnderstanding };
1674
2035
  //# sourceMappingURL=index.js.map
1675
2036
  //# sourceMappingURL=index.js.map