@theokit/gateway 0.7.1 → 0.9.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.d.ts CHANGED
@@ -108,6 +108,23 @@ interface WhatsAppMessageEvent extends BaseMessageEvent {
108
108
  readonly phoneNumberId?: string;
109
109
  /** Contact's profile name when Meta provides it. */
110
110
  readonly contactName?: string;
111
+ /**
112
+ * The address this arrived on, verbatim — what a reply must be sent to.
113
+ *
114
+ * `channel.id` is normalised to digits, which is what an allowlist compares and what a session
115
+ * key is built from. The normalisation strips the DOMAIN, and the domain is what says which
116
+ * kind of identifier it is: `@s.whatsapp.net` a phone, `@g.us` a group, `@lid` an account's
117
+ * linked identity. A note-to-self arrives addressed by LID, so answering `channel.id` rebuilds
118
+ * `…@s.whatsapp.net` — an address that does not exist, and a send that reports ok and lands
119
+ * nowhere (#84).
120
+ *
121
+ * `sendMessage` accepts this verbatim: a `to` containing `@` is already an address and is
122
+ * passed through untouched.
123
+ *
124
+ * Present on the baileys backend. The cloud backend addresses recipients by phone and has no
125
+ * JID to report.
126
+ */
127
+ readonly channelJid?: string;
111
128
  /**
112
129
  * Which backend produced this event.
113
130
  *
@@ -429,6 +446,36 @@ declare abstract class BasePlatformAdapter {
429
446
  * ten to it.
430
447
  */
431
448
  abstract onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
449
+ /**
450
+ * Deliver an inbound event that arrived OUT OF BAND, and report what the handler did with it.
451
+ *
452
+ * Six adapters self-deliver once connected — long polling, a gateway socket, Socket Mode, a sync
453
+ * loop, IMAP. The webhook platforms cannot: the payload arrives on an HTTP route the application
454
+ * owns, and until this existed there was no supported call that joined the two. `onInbound` had no
455
+ * public counterpart, so `GatewayRunner` was reachable for eight platforms and not for LINE or
456
+ * WhatsApp Cloud, which every app then wired by hand beside the runner instead of through it
457
+ * (#83).
458
+ *
459
+ * The return value distinguishes the three outcomes a caller can act on, because they are not the
460
+ * same problem: nobody subscribed, the handler ran, or the handler threw. Answering a webhook 200
461
+ * for the first is wrong — the provider would stop retrying a message nothing received.
462
+ *
463
+ * Implementations should be one line over {@link runHandler}, which owns the containment.
464
+ */
465
+ abstract deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
466
+ /**
467
+ * Run a subscribed handler and contain its failure. The body of {@link deliver}, written once.
468
+ *
469
+ * A handler is USER code and may throw. An adapter must contain that throw, name it as the
470
+ * handler's failure rather than the platform's, and keep delivering — one bad message ends
471
+ * neither the process nor the connection. Two adapters once discarded the rejection with `void`,
472
+ * which under Node's default ends the process; two more reported it as a platform-client error,
473
+ * sending whoever debugged their own handler to the wrong repository (#41).
474
+ *
475
+ * Ten copies of that knowledge is ten chances to get it wrong, so it lives here. The platform tag
476
+ * is taken from `this.platform`, which is the only part that differed between them.
477
+ */
478
+ protected runHandler(handler: ((event: MessageEvent) => Promise<void>) | undefined, event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
432
479
  /** Lifecycle: emit a typing indicator. Default: noop. */
433
480
  startTyping(_channelId: string): Promise<void>;
434
481
  /** Lifecycle: stop the typing indicator. Default: noop. */
@@ -607,12 +654,6 @@ interface GatewayHook {
607
654
  * @public
608
655
  */
609
656
 
610
- /**
611
- * Runs registered hooks at the right fire points. Stateless — safe to
612
- * construct per-event if hooks need event-scoped storage.
613
- *
614
- * @public
615
- */
616
657
  declare class HookExecutor {
617
658
  private readonly hooks;
618
659
  constructor(hooks: ReadonlyArray<GatewayHook>);
@@ -647,7 +688,7 @@ declare class HookExecutor {
647
688
  * 2. If `block: true` + `message`: call `ctx.reply(message)` (EC-D), short-circuit.
648
689
  * 3. If `block: true` only: short-circuit silently.
649
690
  * 4. Otherwise: call user handler.
650
- * 5. On handler throw: fire `on_error`, log via `Security.redact` (EC-F).
691
+ * 5. On handler throw: fire `on_error`, log via `redactSecrets` (EC-F).
651
692
  *
652
693
  * Every reply — the handler's `ctx.reply` and the EC-D auto-reply alike — fires
653
694
  * `post_outbound` with the event, the outbound and the adapter's result, once
@@ -731,6 +772,55 @@ declare class GatewayRunner {
731
772
  private buildContext;
732
773
  }
733
774
 
775
+ /** A credential shape this module masks, and the cost of matching it. */
776
+ interface CoveredShape {
777
+ /** The platform and field, for the reader of the table. */
778
+ readonly field: string;
779
+ /** Anchored to the shape. */
780
+ readonly pattern: RegExp;
781
+ /** What else this matches. Every entry has one — a shape narrow enough to have none is rare. */
782
+ readonly alsoMatches: string;
783
+ }
784
+ /** A credential this repository declares and this module does not mask. */
785
+ interface UncoveredShape {
786
+ /** The platform and field. */
787
+ readonly field: string;
788
+ /** Why a pattern for it would cost more than it buys. */
789
+ readonly why: string;
790
+ }
791
+ /**
792
+ * What is masked and what is not.
793
+ *
794
+ * The uncovered list is the point of publishing this as data rather than burying it in a regex
795
+ * table: a reader can see which of their credentials this protects, and a maintainer adding an
796
+ * adapter can see the standard the new shape has to meet.
797
+ */
798
+ declare const CREDENTIAL_SHAPES: {
799
+ readonly covered: readonly CoveredShape[];
800
+ readonly uncovered: readonly UncoveredShape[];
801
+ };
802
+ /**
803
+ * Replace every covered shape with `***`.
804
+ *
805
+ * Full replacement rather than the SDK's `first6…last4`: a partial mask of a credential is still a
806
+ * disclosure, and the six leading characters of a token identify the account it belongs to.
807
+ *
808
+ * @param text
809
+ * @returns the text with covered shapes removed
810
+ */
811
+ declare function maskShapes(text: string): string;
812
+ /**
813
+ * Mask this domain's shapes, then apply the SDK's redactor.
814
+ *
815
+ * The one function the log sites call. Order matters: ours runs first so a covered shape is gone
816
+ * before the SDK's `key=value` rule can shorten it instead, and the SDK still contributes its own
817
+ * twelve patterns for everything we do not know about.
818
+ *
819
+ * @param value the value to redact — a message, an error, anything stringifiable
820
+ * @returns the redacted string
821
+ */
822
+ declare function redactSecrets(value: unknown): string;
823
+
734
824
  /**
735
825
  * `SessionRouter` — pure routing logic: `MessageEvent → agentId`
736
826
  * (T2.1, ADR D174).
@@ -857,4 +947,83 @@ interface ChunkByGraphemeOptions {
857
947
  */
858
948
  declare function chunkByGrapheme(text: string, options: ChunkByGraphemeOptions): string[];
859
949
 
860
- export { type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, type ChunkByGraphemeOptions, type ChunkTextOptions, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type EmailMessageEvent, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayLifecycleError, type GatewayLifecycleErrorOptions, GatewayRunner, type GatewayRunnerOptions, type HookDecision, HookExecutor, type HookName, type LineMessageEvent, type MatrixMessageEvent, type MattermostMessageEvent, type MessageEvent, type OnErrorContext, type OutboundMessage, type PlatformEventRegistry, type PlatformName, type PostOutboundContext, type PreInboundContext, type SMSMessageEvent, type SendResult, SessionRouter, type SlackMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type WhatsAppMessageEvent, chunkByGrapheme, chunkText, defaultStrategy };
950
+ /**
951
+ * The half of an Express webhook server that is the same for every platform.
952
+ *
953
+ * `gateway-line` and `gateway-sms` each ship one, and they shared 101 of ~170 lines: the lazy
954
+ * `express` load, the raw-body capture with the hang it documents, and the start/stop lifecycle.
955
+ * What differs is signature verification, body parsing and routing, which are genuinely
956
+ * per-platform (#89).
957
+ *
958
+ * The duplication had already been paid for. Commit `11000cc` fixed a write-once latch that made
959
+ * `start()` after `stop()` return without creating a listener — a port nothing answers on, with no
960
+ * error and no log — and it had to fix it in BOTH files, because the latch lives in the copied
961
+ * half. That is the DRY test verbatim: change it here, change it there.
962
+ *
963
+ * ## Why here, and not in a new package
964
+ *
965
+ * The core had no HTTP concern, and `express` is a peer dependency of exactly the two packages that
966
+ * duplicate this — so the obvious objection to putting it here is that it would impose express on
967
+ * all ten adapters.
968
+ *
969
+ * It does not, because nothing here imports express. Every shape below is structural: a request is
970
+ * whatever has `readableEnded` and `on`, a listener is whatever has `listen` and `close`. The
971
+ * packages that use express keep declaring it; this module never learns the name.
972
+ *
973
+ * Exported rather than internal: the two packages that consume it are separate npm packages, so
974
+ * "internal to this repository" is not a thing the module system can express.
975
+ *
976
+ * @public
977
+ */
978
+ /** What the capture middleware reads. Express's `Request` satisfies it; so does a bare stream. */
979
+ interface RawBodyRequest {
980
+ readonly readableEnded?: boolean;
981
+ readonly complete?: boolean;
982
+ setEncoding(encoding: string): unknown;
983
+ on(event: string, listener: (arg: never) => void): unknown;
984
+ }
985
+ /** What a started listener must be able to do. `http.Server` satisfies it. */
986
+ interface ListenerLike {
987
+ close(cb?: (err?: Error) => void): unknown;
988
+ }
989
+ /** What can start a listener. Express's app satisfies it. */
990
+ interface ListenableApp {
991
+ listen(port: number, cb: () => void): ListenerLike;
992
+ }
993
+ /**
994
+ * Load a peer dependency, or fail with a message that says what to install.
995
+ *
996
+ * The error is the point. A bare `Cannot find module 'express'` reaches a consumer who did not
997
+ * write the import and cannot tell whether the package is broken or a step is missing.
998
+ */
999
+ declare function loadPeer<T>(load: () => Promise<unknown>, onMissing: () => never): Promise<T>;
1000
+ /**
1001
+ * Middleware that captures the RAW request body before anything parses it.
1002
+ *
1003
+ * Every provider signs the exact bytes, so a body that was parsed and re-serialised hashes
1004
+ * differently and fails verification for a correct request. The bytes are attached as `rawBody`.
1005
+ *
1006
+ * @param tag the package name for the diagnostic, so a reader knows which router is complaining
1007
+ */
1008
+ declare function rawBodyCapture(tag: string): (rawReq: unknown, _res: unknown, next: (err?: unknown) => void) => void;
1009
+ /**
1010
+ * The start/stop pair, with the latches that make a restart a restart.
1011
+ *
1012
+ * Both flags used to be write-once, in both packages. After a `stop()`, `start()` hit `if (started)`
1013
+ * and returned without creating a listener — the server was silently dead — and the next `stop()`
1014
+ * was a no-op for the same reason, in the other direction. Anything that restarts a gateway hit it:
1015
+ * a config reload, a reconnect after a network fault, a supervisor cycling a process in-band.
1016
+ *
1017
+ * `injected` is for the case where the caller owns the app: there is no listener to open or close,
1018
+ * and `start()`/`stop()` must still be callable and idempotent.
1019
+ */
1020
+ declare function listenerLifecycle(opts: {
1021
+ readonly app: ListenableApp;
1022
+ readonly port: number;
1023
+ readonly injected: boolean;
1024
+ }): {
1025
+ start(): Promise<void>;
1026
+ stop(): Promise<void>;
1027
+ };
1028
+
1029
+ export { type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, CREDENTIAL_SHAPES, type ChunkByGraphemeOptions, type ChunkTextOptions, type CoveredShape, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type EmailMessageEvent, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayLifecycleError, type GatewayLifecycleErrorOptions, GatewayRunner, type GatewayRunnerOptions, type HookDecision, HookExecutor, type HookName, type LineMessageEvent, type ListenableApp, type ListenerLike, type MatrixMessageEvent, type MattermostMessageEvent, type MessageEvent, type OnErrorContext, type OutboundMessage, type PlatformEventRegistry, type PlatformName, type PostOutboundContext, type PreInboundContext, type RawBodyRequest, type SMSMessageEvent, type SendResult, SessionRouter, type SlackMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type UncoveredShape, type WhatsAppMessageEvent, chunkByGrapheme, chunkText, defaultStrategy, listenerLifecycle, loadPeer, maskShapes, rawBodyCapture, redactSecrets };
package/dist/index.js CHANGED
@@ -2,6 +2,30 @@ import { Security } from '@theokit/sdk';
2
2
 
3
3
  // src/adapter/base.ts
4
4
  var BasePlatformAdapter = class {
5
+ /**
6
+ * Run a subscribed handler and contain its failure. The body of {@link deliver}, written once.
7
+ *
8
+ * A handler is USER code and may throw. An adapter must contain that throw, name it as the
9
+ * handler's failure rather than the platform's, and keep delivering — one bad message ends
10
+ * neither the process nor the connection. Two adapters once discarded the rejection with `void`,
11
+ * which under Node's default ends the process; two more reported it as a platform-client error,
12
+ * sending whoever debugged their own handler to the wrong repository (#41).
13
+ *
14
+ * Ten copies of that knowledge is ten chances to get it wrong, so it lives here. The platform tag
15
+ * is taken from `this.platform`, which is the only part that differed between them.
16
+ */
17
+ async runHandler(handler, event) {
18
+ if (handler === void 0) return "no_handler";
19
+ try {
20
+ await handler(event);
21
+ } catch (err) {
22
+ const message = err instanceof Error ? err.message : String(err);
23
+ process.stderr.write(`[${this.platform}] handler threw: ${message}
24
+ `);
25
+ return "handler_threw";
26
+ }
27
+ return "ok";
28
+ }
5
29
  /** Lifecycle: emit a typing indicator. Default: noop. */
6
30
  async startTyping(_channelId) {
7
31
  }
@@ -59,9 +83,114 @@ var GatewayLifecycleError = class extends Error {
59
83
  this.code = opts.code;
60
84
  }
61
85
  };
86
+ var CREDENTIAL_SHAPES = {
87
+ covered: [
88
+ {
89
+ field: "gateway-telegram `token`",
90
+ pattern: /(?<![A-Za-z0-9])\d{8,10}:[A-Za-z0-9_-]{35}(?![A-Za-z0-9_-])/g,
91
+ alsoMatches: "an 8-10 digit number joined by a colon to exactly 35 url-safe characters \u2014 a timestamped identifier of that exact width would be masked"
92
+ },
93
+ {
94
+ field: "gateway-discord `token`",
95
+ pattern: /(?<![A-Za-z0-9_-])[A-Za-z0-9_-]{23,28}\.[A-Za-z0-9_-]{6,7}\.[A-Za-z0-9_-]{27,}(?![A-Za-z0-9_-])/g,
96
+ alsoMatches: "a three-part dotted identifier of those widths; a JWT's middle part is longer"
97
+ },
98
+ {
99
+ field: "gateway-slack `appToken`",
100
+ pattern: /(?<![A-Za-z0-9-])xapp-\d-[A-Z0-9]+-\d+-[a-f0-9]{32,}(?![a-f0-9])/g,
101
+ alsoMatches: "nothing plausible \u2014 the `xapp-` prefix and the shape are Slack's"
102
+ },
103
+ {
104
+ field: "gateway-matrix `accessToken`",
105
+ pattern: /(?<![A-Za-z0-9_])syt_[A-Za-z0-9_-]+_[A-Za-z0-9_-]+_[A-Za-z0-9]+(?![A-Za-z0-9_-])/g,
106
+ alsoMatches: "nothing plausible \u2014 `syt_` is Matrix's own prefix"
107
+ },
108
+ {
109
+ field: "gateway-whatsapp `accessToken`",
110
+ pattern: /(?<![A-Za-z0-9])EAA[A-Za-z0-9]{20,}(?![A-Za-z0-9])/g,
111
+ alsoMatches: "any identifier beginning EAA followed by 20 or more alphanumerics"
112
+ },
113
+ {
114
+ field: "gateway-teams `clientSecret`",
115
+ 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,
116
+ alsoMatches: "an Entra-style secret is the only common value with a tilde in that position"
117
+ }
118
+ ],
119
+ uncovered: [
120
+ {
121
+ field: "gateway-sms `authToken` (Twilio), gateway-line `channelSecret`",
122
+ 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."
123
+ },
124
+ {
125
+ field: "gateway-mattermost `accessToken`",
126
+ why: "26 lowercase alphanumerics, which is exactly a lowercase ULID \u2014 the shape of most trace ids."
127
+ },
128
+ {
129
+ field: "gateway-email `password`, gateway-sms `apiSecret` and `signatureSecret` (Vonage)",
130
+ why: "no format of their own; a passphrase is indistinguishable from prose. The SDK's own `key=value` rule already masks these fully wherever they appear as `field=value`, and adding a pattern here made that WORSE by claiming the value first \u2014 it was masked as first6\u2026last4 instead of removed."
131
+ },
132
+ {
133
+ field: "gateway-slack `botToken`",
134
+ why: "already masked by one of the SDK's own twelve built-in patterns \u2014 `xoxb-` is Slack's and the SDK knows it. A pattern here would be a second one doing the first's work, and the field-level gate flagged its absence, which is the gate working."
135
+ },
136
+ {
137
+ field: "gateway-whatsapp `appSecret`",
138
+ why: "32 lowercase hex, the same shape as the Twilio auth token above and as every md5 and dashless UUID. Masking it would eat the correlation ids in a log."
139
+ },
140
+ {
141
+ field: "gateway-line `channelAccessToken`, gateway-sms `authToken` (Plivo)",
142
+ why: "long base64 runs with no prefix, indistinguishable from any encoded blob a platform library puts in an error message."
143
+ }
144
+ ]
145
+ };
146
+ function maskShapes(text) {
147
+ let out = text;
148
+ for (const { pattern } of CREDENTIAL_SHAPES.covered) out = out.replace(pattern, "***");
149
+ return out;
150
+ }
151
+ function redactSecrets(value) {
152
+ return Security.redact(maskShapes(typeof value === "string" ? value : String(value)));
153
+ }
154
+
155
+ // src/hooks/executor.ts
156
+ var HOOK_PHASES = ["pre_inbound", "post_outbound", "on_error"];
157
+ function malformedHook(index, why) {
158
+ return new GatewayConfigurationError("gateway", {
159
+ code: "malformed_hook",
160
+ message: `gateway: hooks[${index}] ${why}`,
161
+ detail: `hooks[${index}]`
162
+ });
163
+ }
164
+ function assertHook(entry, index) {
165
+ if (typeof entry !== "object" || entry === null) {
166
+ throw malformedHook(index, `is ${entry === null ? "null" : typeof entry}, not a hook object`);
167
+ }
168
+ const hook = entry;
169
+ if (typeof hook.name !== "string" || hook.name.length === 0) {
170
+ throw malformedHook(
171
+ index,
172
+ "has no name \u2014 every hook is named so a log can say which one acted"
173
+ );
174
+ }
175
+ const declared = HOOK_PHASES.filter((phase) => hook[phase] !== void 0);
176
+ if (declared.length === 0) {
177
+ throw malformedHook(
178
+ index,
179
+ `("${hook.name}") declares none of ${HOOK_PHASES.join(", ")} \u2014 it would never run`
180
+ );
181
+ }
182
+ for (const phase of declared) {
183
+ if (typeof hook[phase] !== "function") {
184
+ throw malformedHook(index, `("${hook.name}") declares ${phase}, which is not callable`);
185
+ }
186
+ }
187
+ }
62
188
  var HookExecutor = class {
63
189
  constructor(hooks) {
64
190
  this.hooks = hooks;
191
+ hooks.forEach((hook, index) => {
192
+ assertHook(hook, index);
193
+ });
65
194
  }
66
195
  hooks;
67
196
  /**
@@ -76,7 +205,7 @@ var HookExecutor = class {
76
205
  decision = await h.pre_inbound(ctx);
77
206
  } catch (err) {
78
207
  process.stderr.write(
79
- `[gateway] pre_inbound hook "${h.name}" threw: ${Security.redact(err.message)}
208
+ `[gateway] pre_inbound hook "${h.name}" threw: ${redactSecrets(err.message)}
80
209
  `
81
210
  );
82
211
  return {
@@ -119,6 +248,8 @@ var HookExecutor = class {
119
248
  }
120
249
  }
121
250
  };
251
+
252
+ // src/runner/gateway-runner.ts
122
253
  var DEFAULT_DRAIN_MS = 1e4;
123
254
  var DEFAULT_COMMAND_PREFIXES = ["/"];
124
255
  var GatewayRunner = class {
@@ -215,6 +346,15 @@ var GatewayRunner = class {
215
346
  );
216
347
  this.connected = false;
217
348
  }
349
+ /**
350
+ * @internal Test seam, following `EmailAdapter._threadStoreSize`. The drain set must SHRINK: a
351
+ * settled dispatch that is never removed is a leak that grows for the life of the process, and it
352
+ * is invisible from the outside — `stop()` drains correctly either way, because settled promises
353
+ * resolve immediately whether or not anyone deleted them.
354
+ */
355
+ get _inflightSize() {
356
+ return this.inflight.size;
357
+ }
218
358
  /** @internal */
219
359
  async dispatch(event) {
220
360
  const ctx = this.buildContext(event);
@@ -232,10 +372,8 @@ var GatewayRunner = class {
232
372
  await handler(event, ctx);
233
373
  } catch (err) {
234
374
  await this.hookExecutor.fireOnError({ event, error: err });
235
- process.stderr.write(
236
- `[gateway] handler error: ${Security.redact(err.message)}
237
- `
238
- );
375
+ process.stderr.write(`[gateway] handler error: ${redactSecrets(err.message)}
376
+ `);
239
377
  }
240
378
  })();
241
379
  this.inflight.add(work);
@@ -407,6 +545,69 @@ function chunkByGrapheme(text, options) {
407
545
  return parts;
408
546
  }
409
547
 
410
- export { BasePlatformAdapter, DeliveryRouter, GatewayConfigurationError, GatewayLifecycleError, GatewayRunner, HookExecutor, SessionRouter, chunkByGrapheme, chunkText, defaultStrategy };
548
+ // src/webhook/express-server.ts
549
+ async function loadPeer(load, onMissing) {
550
+ try {
551
+ const mod = await load();
552
+ return mod.default ?? mod;
553
+ } catch {
554
+ onMissing();
555
+ }
556
+ }
557
+ function rawBodyCapture(tag) {
558
+ return (rawReq, _res, next) => {
559
+ const req = rawReq;
560
+ if (req.readableEnded === true || req.complete === true) {
561
+ process.stderr.write(
562
+ `[${tag}] raw body already consumed before signature capture \u2014 mount this router BEFORE any global body parser, or signature verification cannot see the bytes it must hash
563
+ `
564
+ );
565
+ req.rawBody = "";
566
+ next();
567
+ return;
568
+ }
569
+ let buf = "";
570
+ req.setEncoding("utf8");
571
+ req.on("data", (chunk) => {
572
+ buf += chunk;
573
+ });
574
+ req.on("end", () => {
575
+ req.rawBody = buf;
576
+ next();
577
+ });
578
+ req.on("error", (err) => next(err));
579
+ };
580
+ }
581
+ function listenerLifecycle(opts) {
582
+ let started = false;
583
+ let stopped = false;
584
+ let listener;
585
+ return {
586
+ async start() {
587
+ if (started || opts.injected) {
588
+ started = true;
589
+ return;
590
+ }
591
+ stopped = false;
592
+ await new Promise((resolve) => {
593
+ listener = opts.app.listen(opts.port, () => resolve());
594
+ });
595
+ started = true;
596
+ },
597
+ async stop() {
598
+ if (stopped) return;
599
+ stopped = true;
600
+ started = false;
601
+ const current = listener;
602
+ listener = void 0;
603
+ if (current === void 0) return;
604
+ await new Promise((resolve) => {
605
+ current.close(() => resolve());
606
+ });
607
+ }
608
+ };
609
+ }
610
+
611
+ export { BasePlatformAdapter, CREDENTIAL_SHAPES, DeliveryRouter, GatewayConfigurationError, GatewayLifecycleError, GatewayRunner, HookExecutor, SessionRouter, chunkByGrapheme, chunkText, defaultStrategy, listenerLifecycle, loadPeer, maskShapes, rawBodyCapture, redactSecrets };
411
612
  //# sourceMappingURL=index.js.map
412
613
  //# sourceMappingURL=index.js.map