@theokit/gateway-sms 0.3.1 → 0.3.3

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,63 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.3
4
+
5
+ ### Patch Changes
6
+
7
+ - 6329554: The LINE and SMS webhook routes answer 413 to a request body over 1 MiB instead of buffering it without limit before the signature check.
8
+ - bca7cfd: Raise the `@theokit/gateway` peer floor to the core version that ships the APIs this adapter imports, so npm no longer installs it next to a core it cannot load.
9
+
10
+ ## 0.3.2
11
+
12
+ ### Patch Changes
13
+
14
+ - 3f1788d: Send an image from a gateway handler, and refuse it wherever a platform cannot show one.
15
+
16
+ `@theokit/gateway` exports `OutboundAttachment` (`kind: "image"`, `mediaType`, `data`, optional
17
+ `filename`). `OutboundMessage` gains an optional `attachments` list, `ctx.reply(text, { attachments })`
18
+ carries it to the adapter (an empty list is left out), and `BasePlatformAdapter` declares
19
+ `supportsAttachments`, `false` by default. `DeliveryRouter.send` takes the same `attachments`
20
+ field. The runner and the router refuse an outbound carrying attachments as
21
+ `attachments_unsupported`, with no `sendMessage` call, when the adapter does not declare
22
+ `supportsAttachments`.
23
+
24
+ `@theokit/gateway-telegram` reports `supportsAttachments: true` and sends each image through
25
+ `sendPhoto`, the text as the first photo's caption up to 1024 UTF-16 units and after the photos
26
+ when longer. A non-image kind is refused as `attachments_unsupported`; a missing image, more
27
+ than 10 images or an image over 10 MiB as `invalid_attachment`; all with no request.
28
+
29
+ Every other adapter, and every adapter's `editMessage`, refuses an outbound carrying attachments
30
+ with `attachments_unsupported` and makes no platform call, instead of sending the text and
31
+ dropping the image.
32
+
33
+ The runner's auto-reply to a blocking `pre_inbound` hook no longer discards a `sendMessage` that
34
+ throws: the error reaches the `on_error` hooks with the event and is written to stderr, redacted,
35
+ as a handler error is. Dispatch still does not throw.
36
+
37
+ - e980fb8: `@theokit/gateway` exports `SeenIds` (a bounded set of delivered ids) and `splitKeepingRows` (a
38
+ grapheme-safe split that keeps Markdown table rows whole). The SMS and LINE adapters import
39
+ `splitKeepingRows` instead of carrying copies; their peer floor is now `>=0.13.0`.
40
+ - e9be726: Keep Markdown table rows intact through translation and splitting.
41
+
42
+ `channelRendering(platform).translate` and `toDialect` now rewrite a table row (a line whose first
43
+ non-blank character is `|`) one cell at a time. Before, an emphasis span could open in one cell
44
+ and close in the next, so `| 2 x *a | b* y |` lost both stars on the ten platforms that rewrite
45
+ markers. Text where no span crosses a row's pipe translates exactly as before. A lone `\r` counts
46
+ as a line ending, as in GFM. Inline code that holds an unescaped pipe inside a row is split at
47
+ that pipe, as GFM splits the cell, so its backticks no longer pair and the platforms that strip
48
+ markers now keep them.
49
+
50
+ `splitForLine` and `splitForSMS` no longer cut a table row in two at a part
51
+ boundary. When a cut would fall inside a row that fits in one part, the part ends before that row
52
+ and the row starts the next part. A row longer than a part is still cut by length. Every
53
+ character is kept, and every part stays within its limit (with the `(i/N) ` prefix counted on
54
+ SMS, whose numbering follows the new part count) except a single grapheme longer than the limit,
55
+ which is emitted whole as its own part, as before. Text with no table row splits exactly as
56
+ before. Two rows that each fill a part exactly arrive as three parts, the second holding only the
57
+ line ending between them.
58
+
59
+ No export, signature, dependency or peer range changes.
60
+
3
61
  ## 0.3.1
4
62
 
5
63
  ### Patch Changes
package/dist/index.cjs CHANGED
@@ -390,9 +390,23 @@ function inboundToMessageEvent(inbound, backend) {
390
390
  }
391
391
  };
392
392
  }
393
+
394
+ // src/refuse-attachments.ts
395
+ function refuseAttachments(out) {
396
+ if (out.attachments == null || out.attachments.length === 0) return void 0;
397
+ return {
398
+ ok: false,
399
+ error: { code: "attachments_unsupported", message: "sms adapter cannot send attachments" }
400
+ };
401
+ }
393
402
  function prefixWidthFor(total) {
394
403
  return 2 * String(total).length + 4;
395
404
  }
405
+ function partsFor(text, limit, partLimit) {
406
+ if (text.length <= limit) return gateway.chunkByGrapheme(text, { limit, partLimit });
407
+ gateway.chunkByGrapheme("", { limit, partLimit });
408
+ return gateway.splitKeepingRows(text, partLimit);
409
+ }
396
410
  function splitForSMS(text, limit = 1600) {
397
411
  let reserved = prefixWidthFor(1);
398
412
  for (let pass = 0; pass < 8; pass += 1) {
@@ -402,7 +416,7 @@ function splitForSMS(text, limit = 1600) {
402
416
  `limit ${limit} is too small to carry an SMS part: the "(i/N) " prefix alone needs ${reserved} chars`
403
417
  );
404
418
  }
405
- const parts = gateway.chunkByGrapheme(text, { limit, partLimit });
419
+ const parts = partsFor(text, limit, partLimit);
406
420
  if (parts.length <= 1) return parts;
407
421
  const needed = prefixWidthFor(parts.length);
408
422
  if (needed <= reserved) {
@@ -488,6 +502,9 @@ var SMSAdapter = class extends gateway.BasePlatformAdapter {
488
502
  this.inboundHandler = void 0;
489
503
  }
490
504
  async sendMessage(out) {
505
+ return refuseAttachments(out) ?? this.sendText(out);
506
+ }
507
+ async sendText(out) {
491
508
  if (out.text.length === 0) {
492
509
  return { ok: false, error: { code: "empty_text", message: "outbound text is empty" } };
493
510
  }
@@ -679,7 +696,11 @@ async function createWebhookServer(opts) {
679
696
  });
680
697
  res.status(204).end();
681
698
  };
682
- app.post(`${prefix}/${backend}`, gateway.rawBodyCapture("gateway-sms"), handler);
699
+ app.post(
700
+ `${prefix}/${backend}`,
701
+ gateway.rawBodyCapture("gateway-sms", { maxBytes: gateway.DEFAULT_WEBHOOK_MAX_BYTES }),
702
+ handler
703
+ );
683
704
  return gateway.listenerLifecycle({ app, port: opts.port ?? 3e3, injected: opts.app !== void 0 });
684
705
  }
685
706
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/phone.ts","../src/backend/plivo.ts","../src/backend/twilio.ts","../src/backend/vonage.ts","../src/backend/index.ts","../src/normalize.ts","../src/split.ts","../src/adapter.ts","../src/parse-inbound.ts","../src/webhook-server.ts","../src/webhook-verifier.ts"],"names":["GatewayConfigurationError","parsePhoneNumberFromString","parseFormUrlEncoded","chunkByGrapheme","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GACX,EAAE,EAAA,EAAI,KAAA,EAAO,MAAA,EAAQ,oBAAA,EAAqB;AAAA,EAChD,CAAA;AACF","file":"index.cjs","sourcesContent":["/**\n * Typed errors for `@theokit/gateway-sms` (D389-D396).\n *\n * - `ConfigurationError` — programmer error at construction time\n * (missing signing secret, missing backend SDK install, malformed\n * phone number on outbound). Thrown synchronously.\n * - `BackendNotInstalledError` — peer-dep optional backend (twilio /\n * plivo / @vonage/server-sdk) was selected but the npm package is\n * not installed. Carries actionable install hint.\n *\n * `ConfigurationError` extends the shared core `GatewayConfigurationError`\n * base (roadmap M2); the SDK still consumes structured errors via\n * `metadata.code`. Behavior byte-identical (pinned by `tests/errors.test.ts`).\n *\n * @internal — re-exported by `src/index.ts`.\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;\n\n/**\n * Misconfiguration of this adapter, raised before any network call.\n *\n * Extends the shared core base so every gateway package reports configuration faults in one shape:\n * a structured `code` the caller can branch on, tagged with `\"gateway-sms\"` as the origin. A\n * missing credential or an unsupported option is a programmer error, not a transient failure —\n * these are never retried.\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-sms\", opts);\n }\n}\n\n/**\n * The provider SDK for the selected backend is not installed.\n *\n * `gateway-sms` speaks to Twilio, Plivo or Vonage, and declares all three as optional peers — a\n * project installs only the one it uses. Selecting a backend whose SDK is absent is caught here, at\n * connect time, with the package name and the command that installs it.\n */\nexport class BackendNotInstalledError extends ConfigurationError {\n constructor(backend: \"twilio\" | \"plivo\" | \"vonage\", pkgName: string) {\n super({\n code: \"backend_not_installed\",\n message: `gateway-sms: peer-dep \"${pkgName}\" not installed but backend=\"${backend}\" was selected. Run: pnpm add ${pkgName}`,\n detail: pkgName,\n });\n }\n}\n","/**\n * E.164 phone normalization (D391, EC-6).\n *\n * Wraps `libphonenumber-js` (full — accepts mobile + toll-free; the\n * `/mobile` sub-bundle was inadequate because it rejects toll-free\n * US 1-800 numbers).\n *\n * @internal\n */\n\nimport { parsePhoneNumberFromString } from \"libphonenumber-js\";\n\nimport { ConfigurationError } from \"./errors.js\";\n\n/**\n * Normalize a free-form phone number to canonical E.164 (`+5511999999999`).\n *\n * Accepts:\n * - International with `+`: `\"+5511999999999\"` → unchanged.\n * - National without `+` when `defaultCountry` is provided: `(\"11999999999\", \"BR\")` → `\"+5511999999999\"`.\n * - Toll-free US (EC-6): `\"+18001234567\"` → unchanged.\n *\n * Throws `ConfigurationError({ code: \"invalid_phone_number\" })` on any\n * input that cannot be parsed to a valid number.\n */\nexport function normalizeE164(input: string, defaultCountry?: string): string {\n if (input.length === 0) {\n throw new ConfigurationError({\n code: \"invalid_phone_number\",\n message: \"gateway-sms: phone number is empty\",\n detail: \"<empty>\",\n });\n }\n const parsed = parsePhoneNumberFromString(\n input,\n defaultCountry as Parameters<typeof parsePhoneNumberFromString>[1],\n );\n if (parsed === undefined || !parsed.isValid()) {\n throw new ConfigurationError({\n code: \"invalid_phone_number\",\n message: `gateway-sms: invalid phone number ${JSON.stringify(input)}`,\n detail: input,\n });\n }\n return parsed.format(\"E.164\");\n}\n","/**\n * Plivo backend impl.\n *\n * - SDK: `plivo` (peer-dep, optional).\n * - Signature: `X-Plivo-Signature-V3` is HMAC-SHA256 of the request URL\n * + nonce + body. `validateV3Signature` is exposed by the SDK; we\n * delegate to avoid reimplementation.\n *\n * @internal\n */\n\nimport type { SendResult } from \"@theokit/gateway\";\nimport type { SignatureContext, SMSBackend, SMSInbound } from \"../backend-types.js\";\nimport { BackendNotInstalledError } from \"../errors.js\";\nimport { normalizeE164 } from \"../phone.js\";\nimport type { PlivoOptions } from \"../types.js\";\n\ninterface PlivoCreateResponse {\n apiId?: string;\n messageUuid?: string[];\n message_uuid?: string[];\n}\n\ninterface PlivoClient {\n messages: {\n // The actual SDK uses positional args: create(src, dst, text, ...).\n create(src: string, dst: string, text: string): Promise<PlivoCreateResponse>;\n };\n}\n\ninterface PlivoModule {\n Client: new (authId?: string, authToken?: string) => PlivoClient;\n // Real SDK signature: validateV3Signature(method, uri, nonce, authToken, v3Signature)\n validateV3Signature?: (\n method: string,\n uri: string,\n nonce: string,\n authToken: string,\n signature: string,\n ) => boolean;\n}\n\nasync function loadPlivo(): Promise<PlivoModule> {\n try {\n // Plivo's published types are stricter (positional args) than our\n // generic mock; we narrow at call sites and pass through unknown.\n const mod = (await import(\"plivo\")) as unknown as PlivoModule;\n return mod;\n } catch {\n throw new BackendNotInstalledError(\"plivo\", \"plivo\");\n }\n}\n\nexport class PlivoBackend implements SMSBackend {\n readonly kind = \"plivo\" as const;\n private mod: PlivoModule | undefined;\n private client: PlivoClient | undefined;\n\n constructor(private readonly opts: PlivoOptions) {}\n\n async connect(): Promise<boolean> {\n if (this.client !== undefined) return true;\n this.mod = await loadPlivo();\n this.client = new this.mod.Client(this.opts.authId, this.opts.authToken);\n return true;\n }\n\n async disconnect(): Promise<void> {\n this.client = undefined;\n }\n\n verifySignature(ctx: SignatureContext): boolean {\n if (this.mod?.validateV3Signature === undefined) return false;\n const signature = ctx.headers[\"x-plivo-signature-v3\"];\n const nonce = ctx.headers[\"x-plivo-signature-v3-nonce\"];\n if (signature === undefined || nonce === undefined) return false;\n try {\n return this.mod.validateV3Signature(\"POST\", ctx.url, nonce, this.opts.authToken, signature);\n } catch {\n return false;\n }\n }\n\n parseInbound(ctx: SignatureContext): SMSInbound {\n let params: Record<string, string> = {};\n // Plivo posts JSON or form-encoded depending on application config.\n if ((ctx.headers[\"content-type\"] ?? \"\").includes(\"application/json\")) {\n try {\n params = JSON.parse(ctx.rawBody) as Record<string, string>;\n } catch {\n params = {};\n }\n } else {\n params = parseFormUrlEncoded(ctx.rawBody);\n }\n return {\n from: normalizeE164(params.From ?? \"\", this.opts.defaultCountry),\n to: normalizeE164(params.To ?? \"\", this.opts.defaultCountry),\n body: params.Text ?? params.text ?? \"\",\n messageId: params.MessageUUID ?? params.message_uuid ?? \"\",\n receivedAt: Date.now(),\n raw: params,\n };\n }\n\n async sendMessage(to: string, body: string): Promise<SendResult> {\n if (this.client === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"PlivoBackend.connect() not called\" },\n };\n }\n try {\n const resp = await this.client.messages.create(this.opts.fromNumber, to, body);\n const id = resp.messageUuid?.[0] ?? resp.message_uuid?.[0] ?? resp.apiId ?? \"\";\n return { ok: true, messageId: id };\n } catch (err) {\n return mapPlivoError(err);\n }\n }\n}\n\nfunction parseFormUrlEncoded(body: string): Record<string, string> {\n const params: Record<string, string> = {};\n for (const pair of body.split(\"&\")) {\n if (pair.length === 0) continue;\n const eqIdx = pair.indexOf(\"=\");\n const k = eqIdx < 0 ? pair : pair.slice(0, eqIdx);\n const v = eqIdx < 0 ? \"\" : pair.slice(eqIdx + 1);\n params[decodeURIComponent(k.replace(/\\+/g, \" \"))] = decodeURIComponent(v.replace(/\\+/g, \" \"));\n }\n return params;\n}\n\ninterface PlivoRestError {\n statusCode?: number;\n status?: number;\n message?: string;\n}\n\nfunction mapPlivoError(err: unknown): SendResult {\n const e = err as PlivoRestError;\n const status = e.statusCode ?? e.status ?? 0;\n if (status === 429)\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"Plivo rate limit\" } };\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"Plivo auth error\" },\n };\n }\n if (status === 400) {\n return {\n ok: false,\n error: { code: \"invalid_request\", message: e.message ?? \"Plivo rejected request\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\n}\n","/**\n * Twilio backend impl.\n *\n * - SDK: `twilio` (peer-dep, optional). Loaded lazily so packages\n * that pick other backends don't pay the cost.\n * - Signature: `X-Twilio-Signature` is HMAC-SHA1 of `(fullUrl + sortedParams)`.\n * We delegate to `twilio.validateRequest` so we don't reimplement.\n *\n * @internal\n */\n\nimport type { SendResult } from \"@theokit/gateway\";\nimport type { SignatureContext, SMSBackend, SMSInbound } from \"../backend-types.js\";\nimport { BackendNotInstalledError } from \"../errors.js\";\nimport { normalizeE164 } from \"../phone.js\";\nimport type { TwilioOptions } from \"../types.js\";\n\ninterface TwilioCreateArgs {\n from: string;\n to: string;\n body: string;\n}\n\ninterface TwilioMessageInstance {\n sid: string;\n status?: string;\n}\n\ninterface TwilioClientInstance {\n messages: {\n create(args: TwilioCreateArgs): Promise<TwilioMessageInstance>;\n };\n}\n\ninterface TwilioFactory {\n (accountSid: string, authToken: string): TwilioClientInstance;\n validateRequest(\n authToken: string,\n signature: string,\n url: string,\n params: Record<string, string>,\n ): boolean;\n}\n\nasync function loadTwilio(): Promise<TwilioFactory> {\n try {\n const mod = await import(\"twilio\");\n // ESM ships { default: factory }; CJS ships factory.\n const candidate =\n (mod as { default?: TwilioFactory }).default ?? (mod as unknown as TwilioFactory);\n return candidate;\n } catch {\n throw new BackendNotInstalledError(\"twilio\", \"twilio\");\n }\n}\n\nexport class TwilioBackend implements SMSBackend {\n readonly kind = \"twilio\" as const;\n private client: TwilioClientInstance | undefined;\n private twilio: TwilioFactory | undefined;\n\n constructor(private readonly opts: TwilioOptions) {}\n\n async connect(): Promise<boolean> {\n if (this.client !== undefined) return true;\n this.twilio = await loadTwilio();\n this.client = this.twilio(this.opts.accountSid, this.opts.authToken);\n return true;\n }\n\n async disconnect(): Promise<void> {\n // No persistent connection — REST client is GC'd on dereference.\n this.client = undefined;\n }\n\n verifySignature(ctx: SignatureContext): boolean {\n if (this.twilio === undefined) return false;\n const signature = ctx.headers[\"x-twilio-signature\"];\n if (signature === undefined) return false;\n const params = parseFormUrlEncoded(ctx.rawBody);\n try {\n return this.twilio.validateRequest(this.opts.authToken, signature, ctx.url, params);\n } catch {\n return false;\n }\n }\n\n parseInbound(ctx: SignatureContext): SMSInbound {\n const params = parseFormUrlEncoded(ctx.rawBody);\n return {\n from: normalizeE164(params.From ?? \"\", this.opts.defaultCountry),\n to: normalizeE164(params.To ?? \"\", this.opts.defaultCountry),\n body: params.Body ?? \"\",\n messageId: params.MessageSid ?? params.SmsMessageSid ?? \"\",\n receivedAt: Date.now(),\n raw: params,\n };\n }\n\n async sendMessage(to: string, body: string): Promise<SendResult> {\n if (this.client === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"TwilioBackend.connect() not called\" },\n };\n }\n try {\n const msg = await this.client.messages.create({ from: this.opts.fromNumber, to, body });\n return { ok: true, messageId: msg.sid };\n } catch (err) {\n return mapTwilioError(err);\n }\n }\n}\n\n/**\n * Parse `application/x-www-form-urlencoded` request body to a flat\n * `Record<string, string>`. Twilio POSTs in this format.\n *\n * @internal\n */\nfunction parseFormUrlEncoded(body: string): Record<string, string> {\n const params: Record<string, string> = {};\n for (const pair of body.split(\"&\")) {\n if (pair.length === 0) continue;\n const eqIdx = pair.indexOf(\"=\");\n const k = eqIdx < 0 ? pair : pair.slice(0, eqIdx);\n const v = eqIdx < 0 ? \"\" : pair.slice(eqIdx + 1);\n params[decodeURIComponent(k.replace(/\\+/g, \" \"))] = decodeURIComponent(v.replace(/\\+/g, \" \"));\n }\n return params;\n}\n\ninterface TwilioRestError {\n status?: number;\n code?: number | string;\n message?: string;\n}\n\nfunction mapTwilioError(err: unknown): SendResult {\n const e = err as TwilioRestError;\n const status = e.status ?? 0;\n if (status === 429) {\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"Twilio rate limit\" } };\n }\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"Twilio auth error\" },\n };\n }\n if (status === 400) {\n return {\n ok: false,\n error: { code: \"invalid_request\", message: e.message ?? \"Twilio rejected request\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\n}\n","/**\n * Vonage backend impl.\n *\n * - SDK: `@vonage/server-sdk` (peer-dep, optional).\n * - Signature: `Authorization: Bearer <JWT>` signed with the Signature\n * Secret (NOT the API secret). The SDK exposes `Auth.verifySignature`\n * for this purpose.\n *\n * @internal\n */\n\nimport type { SendResult } from \"@theokit/gateway\";\nimport type { SignatureContext, SMSBackend, SMSInbound } from \"../backend-types.js\";\nimport { BackendNotInstalledError } from \"../errors.js\";\nimport { normalizeE164 } from \"../phone.js\";\nimport type { VonageOptions } from \"../types.js\";\n\ninterface VonageSmsClient {\n send(args: { to: string; from: string; text: string }): Promise<{\n messages?: Array<{ \"message-id\"?: string; messageId?: string; status?: string }>;\n }>;\n}\n\ninterface VonageInstance {\n sms: VonageSmsClient;\n}\n\ninterface VonageModule {\n Vonage: new (creds: {\n apiKey: string;\n apiSecret: string;\n signatureSecret?: string;\n }) => VonageInstance;\n Auth?: {\n verifySignature?: (token: string, secret: string) => boolean;\n };\n}\n\nasync function loadVonage(): Promise<VonageModule> {\n try {\n // SDK ships ESM/CJS variants; we narrow at call sites and pass through.\n const raw = await import(\"@vonage/server-sdk\");\n return raw as unknown as VonageModule;\n } catch {\n throw new BackendNotInstalledError(\"vonage\", \"@vonage/server-sdk\");\n }\n}\n\nexport class VonageBackend implements SMSBackend {\n readonly kind = \"vonage\" as const;\n private mod: VonageModule | undefined;\n private vonage: VonageInstance | undefined;\n\n constructor(private readonly opts: VonageOptions) {}\n\n async connect(): Promise<boolean> {\n if (this.vonage !== undefined) return true;\n this.mod = await loadVonage();\n this.vonage = new this.mod.Vonage({\n apiKey: this.opts.apiKey,\n apiSecret: this.opts.apiSecret,\n signatureSecret: this.opts.signatureSecret,\n });\n return true;\n }\n\n async disconnect(): Promise<void> {\n this.vonage = undefined;\n }\n\n verifySignature(ctx: SignatureContext): boolean {\n const auth = ctx.headers.authorization;\n if (auth === undefined) return false;\n const m = auth.match(/^Bearer\\s+(.+)$/i);\n if (m === null) return false;\n const token = m[1] ?? \"\";\n if (token.length === 0) return false;\n if (this.mod?.Auth?.verifySignature === undefined) return false;\n try {\n return this.mod.Auth.verifySignature(token, this.opts.signatureSecret);\n } catch {\n return false;\n }\n }\n\n parseInbound(ctx: SignatureContext): SMSInbound {\n let payload: Record<string, string> = {};\n try {\n payload = JSON.parse(ctx.rawBody) as Record<string, string>;\n } catch {\n payload = {};\n }\n return {\n from: normalizeE164(payload.msisdn ?? payload.from ?? \"\", this.opts.defaultCountry),\n to: normalizeE164(payload.to ?? \"\", this.opts.defaultCountry),\n body: payload.text ?? \"\",\n messageId: payload.messageId ?? payload[\"message-id\"] ?? \"\",\n receivedAt: Date.now(),\n raw: payload,\n };\n }\n\n async sendMessage(to: string, body: string): Promise<SendResult> {\n if (this.vonage === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"VonageBackend.connect() not called\" },\n };\n }\n try {\n const resp = await this.vonage.sms.send({ from: this.opts.fromNumber, to, text: body });\n const msg = resp.messages?.[0];\n const id = msg?.[\"message-id\"] ?? msg?.messageId ?? \"\";\n if (msg?.status !== undefined && msg.status !== \"0\") {\n return {\n ok: false,\n error: { code: \"send_failed\", message: `Vonage returned status=${msg.status}` },\n };\n }\n return { ok: true, messageId: id };\n } catch (err) {\n return mapVonageError(err);\n }\n }\n}\n\ninterface VonageRestError {\n status?: number;\n response?: { status?: number };\n message?: string;\n}\n\nfunction mapVonageError(err: unknown): SendResult {\n const e = err as VonageRestError;\n const status = e.status ?? e.response?.status ?? 0;\n if (status === 429)\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"Vonage rate limit\" } };\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"Vonage auth error\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\n}\n","/**\n * Backend factory — picks the right impl from `opts.backend`.\n *\n * @internal\n */\n\nimport type { SMSBackend } from \"../backend-types.js\";\nimport type { SMSAdapterOptions } from \"../types.js\";\nimport { PlivoBackend } from \"./plivo.js\";\nimport { TwilioBackend } from \"./twilio.js\";\nimport { VonageBackend } from \"./vonage.js\";\n\nexport function createBackend(opts: SMSAdapterOptions): SMSBackend {\n switch (opts.backend) {\n case \"twilio\":\n return new TwilioBackend(opts);\n case \"plivo\":\n return new PlivoBackend(opts);\n case \"vonage\":\n return new VonageBackend(opts);\n default: {\n const _exhaustive: never = opts;\n throw new Error(`unknown backend: ${JSON.stringify(_exhaustive)}`);\n }\n }\n}\n","/**\n * Inbound normalization: `SMSInbound` → `SMSMessageEvent`.\n *\n * `from` and `to` are already E.164 (backend.parseInbound enforces this).\n * `channel.id` is `from` because SMS conversations are flat per-pair\n * (D394 — no threading).\n *\n * @internal\n */\n\nimport type { SMSMessageEvent } from \"@theokit/gateway\";\n\nimport type { SMSInbound } from \"./backend-types.js\";\n\nexport function inboundToMessageEvent(\n inbound: SMSInbound,\n backend: \"twilio\" | \"plivo\" | \"vonage\",\n): SMSMessageEvent {\n return {\n id: inbound.messageId,\n platform: \"sms\",\n sender: { id: inbound.from },\n channel: { id: inbound.from, type: \"dm\" },\n text: inbound.body,\n receivedAt: inbound.receivedAt,\n sms: {\n backend,\n messageId: inbound.messageId,\n from: inbound.from,\n to: inbound.to,\n raw: inbound.raw,\n },\n };\n}\n","/**\n * `splitForSMS` — grapheme-cluster-safe multipart segmentation (D393, EC-7).\n *\n * Concatenated SMS (UDH) on modern carriers reassemble at the recipient,\n * but each TCP/IP-layer chunk is one billed message. We segment at\n * 1600 chars (default) so the API call doesn't reject and each part is\n * prefixed with `(i/N) ` to allow manual reordering when carriers\n * deliver out of sequence (EC-7).\n *\n * Thin wrapper over core `chunkByGrapheme` (roadmap M1) — single-sources the\n * `Intl.Segmenter` grapheme walk so emoji (🇧🇷) and combining sequences are\n * never severed. The `(i/N) ` prefix (and its reserved width) stays here since\n * it is SMS-specific. Output is byte-identical to the previous implementation\n * (pinned by `tests/split.test.ts`).\n *\n * @internal\n */\n\nimport { chunkByGrapheme } from \"@theokit/gateway\";\n\n/**\n * Width of `\"(i/total) \"` when `i` has as many digits as `total` — the widest\n * the prefix can get for a given part count. `(99/99) ` is 8, `(100/126) ` is\n * 10, `(1000/1234) ` is 12.\n *\n * This used to be the constant 8, commented `\"(99/99) \" worst case`. It is the\n * worst case only below 100 parts; from the hundredth part on, every prefix\n * overflowed its reservation and each part exceeded the caller's declared cap\n * by 2 chars, which the provider rejects.\n */\nfunction prefixWidthFor(total: number): number {\n return 2 * String(total).length + 4;\n}\n\nexport function splitForSMS(text: string, limit = 1600): string[] {\n // Chicken and egg: the reservation depends on the part count, and the part\n // count depends on the reservation. Widening the prefix shrinks the payload,\n // which can push the count into another digit — so iterate to a fixed point.\n // It converges fast because the width grows with the LOGARITHM of the count;\n // the bound is a backstop against a pathological input, not the expected path.\n let reserved = prefixWidthFor(1);\n for (let pass = 0; pass < 8; pass += 1) {\n const partLimit = limit - reserved;\n if (partLimit <= 0) {\n throw new RangeError(\n `limit ${limit} is too small to carry an SMS part: the \"(i/N) \" prefix alone needs ${reserved} chars`,\n );\n }\n const parts = chunkByGrapheme(text, { limit, partLimit });\n if (parts.length <= 1) return parts; // short-circuit / single part: skip prefix\n const needed = prefixWidthFor(parts.length);\n if (needed <= reserved) {\n const total = parts.length;\n return parts.map((p, i) => `(${i + 1}/${total}) ${p}`);\n }\n reserved = needed;\n }\n /* c8 ignore next 3 -- unreachable: 8 passes cover part counts up to 10^8. */\n throw new RangeError(\n `could not settle the \"(i/N) \" prefix width for a ${text.length}-char message at limit ${limit}`,\n );\n}\n","/**\n * `SMSAdapter` — implements `BasePlatformAdapter` over a backend\n * (twilio / plivo / vonage). ADRs D389-D396.\n *\n * Lifecycle:\n * - `connect()` initializes the chosen backend (lazy peer-dep import).\n * - `disconnect()` releases the backend; idempotent.\n * - `sendMessage()` splits multipart (D393) and sends each part via backend.\n * - `onInbound(handler)` replaces previous handler (EC-H, mirror D276).\n *\n * Inbound dispatch is driven by the webhook server (`webhook-server.ts`)\n * which calls `adapter.dispatchInbound(ctx)` after signature verification.\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\nimport { createBackend } from \"./backend/index.js\";\nimport type { SignatureContext, SMSBackend } from \"./backend-types.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { inboundToMessageEvent } from \"./normalize.js\";\nimport { normalizeE164 } from \"./phone.js\";\nimport { splitForSMS } from \"./split.js\";\nimport type { SMSAdapterOptions } from \"./types.js\";\n\nexport class SMSAdapter extends BasePlatformAdapter {\n /**\n * Whether the \"this medium carries no formatting\" warning has already been emitted.\n *\n * Once per adapter, not once per message: a gateway answering a busy channel would turn a\n * useful diagnostic into a log flood, and a flooded log is one nobody reads — the same\n * reason the group-mention and allowlist drops elsewhere in this family log once.\n */\n private warnedAboutFormat = false;\n\n /**\n * Say, once, that a declared format is being dropped.\n *\n * `OutboundMessage.format` is the caller stating intent, and this medium has nowhere to put\n * it: no flag, no markup, no alternative part. Discarding it in silence is the swallowed-\n * error shape `rules/error-handling.md` refuses — nothing fails, and the caller learns their\n * formatting never arrived from a user, weeks later.\n *\n * @internal\n */\n private warnFormatUnsupported(format: string | undefined): void {\n // The \"is there anything to say\" question lives here rather than at the call site: a\n // `sendMessage` already at its complexity limit should ask one thing, not three.\n if (format === undefined || format === \"plain\") return;\n if (this.warnedAboutFormat) return;\n this.warnedAboutFormat = true;\n process.stderr.write(\n `[gateway-sms] format=\"${format}\" was declared, and SMS cannot carry it — ` +\n \"the medium is plain text. Sending unformatted; this is logged once.\\n\",\n );\n }\n\n readonly platform = \"sms\" as const;\n\n /**\n * The URL the provider POSTs inbound to, as the provider sees it.\n *\n * Required by all three backend option shapes and documented there as \"used by signature\n * verifier\" — and, measured 2026-08-31, read by nothing: it appeared only in the type and in test\n * fixtures. Twilio SIGNS this URL, so the value matters most in exactly the case where the\n * request cannot supply it: behind a proxy or a tunnel, the request's own URL is the internal one\n * and will not match what was signed.\n *\n * Exposed so {@link smsWebhookVerifier} can use it, which is what makes the option true.\n */\n readonly publicUrl: string;\n\n private readonly backend: SMSBackend;\n private inboundHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private connected = false;\n private readonly defaultCountry: string | undefined;\n\n constructor(opts: SMSAdapterOptions) {\n super();\n // EC-1: refuse to operate without signing secret.\n const secret = secretFromOpts(opts);\n if (secret.length === 0) {\n throw new ConfigurationError({\n code: \"signing_secret_required\",\n message: `gateway-sms: backend=\"${opts.backend}\" requires a signing secret (would accept unsigned webhooks)`,\n });\n }\n this.defaultCountry = opts.defaultCountry;\n this.publicUrl = opts.publicUrl;\n this.backend = createBackend(opts);\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n const ok = await this.backend.connect();\n this.connected = ok;\n return ok;\n }\n\n async disconnect(): Promise<void> {\n if (!this.connected) return;\n await this.backend.disconnect();\n this.connected = false;\n this.inboundHandler = undefined;\n }\n\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"outbound text is empty\" } };\n }\n let toE164: string;\n try {\n toE164 = normalizeE164(out.channel.id, this.defaultCountry);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return { ok: false, error: { code: \"invalid_phone_number\", message: msg } };\n }\n const parts = splitForSMS(out.text);\n // Send sequentially so the recipient sees them in order; concurrent\n // submit would still cost the same but breaks ordering at carriers.\n let lastResult: SendResult | undefined;\n // SMS is plain text by definition. Reading the field is not ceremony: it is what turns a\n // silent discard into a stated one.\n this.warnFormatUnsupported(out.format);\n\n for (const part of parts) {\n lastResult = await this.backend.sendMessage(toE164, part);\n if (lastResult.ok !== true) {\n return {\n ok: false,\n error: {\n code: lastResult.error?.code ?? \"partial_send_failure\",\n message: `partial send failed after ${parts.indexOf(part)}/${parts.length}: ${lastResult.error?.message ?? \"unknown\"}`,\n },\n };\n }\n }\n return lastResult ?? { ok: false, error: { code: \"send_failed\", message: \"no parts sent\" } };\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace, not stack.\n this.inboundHandler = handler;\n return () => {\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n /**\n * Webhook hook — called by `createWebhookServer` AFTER signature\n * verification + parseInbound. Returns dispatch outcome (used for\n * 200/204 vs 500 by the webhook handler).\n *\n * @internal\n */\n async dispatchInbound(ctx: SignatureContext): Promise<\"ok\" | \"no_handler\" | \"parse_failed\"> {\n if (!this.backend.verifySignature(ctx)) {\n // Caller (webhook-server) inspects this via verifySignature directly,\n // but we re-check defensively if anyone calls dispatch directly.\n return \"parse_failed\";\n }\n let inbound: ReturnType<SMSBackend[\"parseInbound\"]>;\n try {\n inbound = this.backend.parseInbound(ctx);\n } catch {\n return \"parse_failed\";\n }\n if (this.inboundHandler === undefined) return \"no_handler\";\n const event = inboundToMessageEvent(inbound, this.backend.kind);\n try {\n await this.inboundHandler(event);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-sms] handler threw: ${msg}\\n`);\n }\n return \"ok\";\n }\n\n /**\n * Direct signature check — used by the webhook server to respond\n * `401` BEFORE dispatch when signature is invalid.\n *\n * @internal\n */\n verifySignature(ctx: SignatureContext): boolean {\n return this.backend.verifySignature(ctx);\n }\n\n /**\n * Direct parse — used by the webhook server when signature was already\n * validated upstream. Returns the normalized `SMSMessageEvent` to be\n * dispatched.\n *\n * @internal\n */\n buildEventFromCtx(ctx: SignatureContext): GatewayMessageEvent {\n const inbound = this.backend.parseInbound(ctx);\n return inboundToMessageEvent(inbound, this.backend.kind);\n }\n\n /**\n * Dispatch a pre-built event (used by webhook server after manual\n * signature + parse). Honors EC-H replace semantics and isolates\n * handler exceptions per `gateway-runner` contract.\n *\n * @internal\n */\n async dispatchEvent(event: GatewayMessageEvent): Promise<\"ok\" | \"no_handler\"> {\n if (this.inboundHandler === undefined) return \"no_handler\";\n try {\n await this.inboundHandler(event);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-sms] handler threw: ${msg}\\n`);\n }\n return \"ok\";\n }\n\n /** Backend kind (escape hatch for callers needing to introspect). */\n getBackendKind(): \"twilio\" | \"plivo\" | \"vonage\" {\n return this.backend.kind;\n }\n\n /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.runHandler(this.inboundHandler, event);\n }\n}\n\nfunction secretFromOpts(opts: SMSAdapterOptions): string {\n switch (opts.backend) {\n case \"twilio\":\n return opts.authToken;\n case \"plivo\":\n return opts.authToken;\n case \"vonage\":\n return opts.signatureSecret;\n default: {\n const _exhaustive: never = opts;\n void _exhaustive;\n return \"\";\n }\n }\n}\n","/**\n * Translating a raw provider webhook into the canonical event.\n *\n * **This does NOT go through TheoKit's `handleChannelWebhook`.** Signature verification here needs\n * the RAW body, the headers and the exact URL — `ChannelMessage` carries none of the three, so the\n * check cannot be performed from inside `onMessage` whatever the provider sends. Twilio adds a\n * second obstacle: it posts `application/x-www-form-urlencoded`, and that seam reads the body with\n * `request.json()` and answers 400 when it is not JSON. (Plivo accepts either encoding and Vonage\n * posts JSON, so only the first reason applies to them.)\n *\n * For an Express app, `createWebhookServer` is the whole path and you never call this — it builds\n * the {@link SignatureContext}, verifies the signature and goes through the adapter. This export is\n * for a route you host yourself: build the context from a request whose body you have not parsed,\n * then call this. It composes two functions that\n * already existed and were both private: each backend's `parseInbound`, which turns a provider's\n * raw body into the provider-agnostic {@link SMSInbound}, and `inboundToMessageEvent`, which turns\n * that into the canonical event. Neither is duplicated here — per ADR D426 the mapping stays in one\n * place, and this is composition, not a second translator.\n *\n * **Why it takes the adapter's options.** Parsing is provider-specific (`Twilio` posts\n * `MessageSid`, Plivo posts `MessageUUID`) and, for Twilio, country-dependent: a number that is not\n * already in E.164 is normalised against `defaultCountry`. Both live in the options an app already\n * holds, because it constructed the adapter with them. `createBackend` only stores them — it opens\n * no connection and loads no SDK, so this stays a pure function over its inputs.\n */\n\nimport type { SMSMessageEvent } from \"@theokit/gateway\";\n\nimport { createBackend } from \"./backend/index.js\";\nimport type { SignatureContext, SMSInbound } from \"./backend-types.js\";\nimport { inboundToMessageEvent } from \"./normalize.js\";\nimport type { SMSAdapterOptions } from \"./types.js\";\n\n/**\n * Translate one raw provider webhook into an {@link SMSMessageEvent}.\n *\n * Returns `null` — never throws — when the body is not one this provider recognises. The caller is\n * whatever holds the {@link SignatureContext}: `createWebhookServer` here, or your own route. It\n * returns `null` rather than throwing because a throw out of a webhook handler becomes a failed\n * request, and the provider then sees a delivery failure for a body that was merely unrecognised\n * (ADR D428, whose original rationale — \"runs after the 200\" — was measured false on 2026-08-24).\n *\n * `null` here means \"this body is not a parseable inbound message\".\n *\n * **One class of configuration error is not distinguishable from a bad body, and is not pretended\n * to be.** `defaultCountry` is read while parsing the body's own numbers, and `normalizeE164`\n * raises the same `ConfigurationError` for a bad configured country as for a bad number in the\n * body. An invalid `defaultCountry` therefore degrades to `null` rather than throwing.\n *\n * An earlier version tried to separate them by validating `options.fromNumber` up front. That was\n * wrong twice: `fromNumber` is passed raw to the provider SDK everywhere else in this package and\n * validated nowhere, and the invented rule rejected four documented, valid configurations — a\n * Vonage alphanumeric sender ID (`\"ACME\"`), a Twilio short code (`\"12345\"`), a Messaging Service\n * SID (`\"MG…\"`), and a national number with `defaultCountry` set. Each one threw out of\n * `onMessage`, turning a message the provider delivered into a failed request — precisely the\n * failure the check was written to prevent.\n * Inventing a validation stricter than the package's own is how that happened.\n *\n * @public\n */\nexport function parseInbound(\n options: SMSAdapterOptions,\n ctx: SignatureContext,\n): SMSMessageEvent | null {\n // `createBackend` is the CONFIGURATION step and sits outside the try on purpose: an unsupported\n // `backend` is a programmer error and must surface, not become the same `null` a malformed body\n // produces.\n const backend = createBackend(options);\n\n let inbound: SMSInbound;\n try {\n inbound = backend.parseInbound(ctx);\n } catch {\n // Everything from here is body-dependent, so any error means the body was unreadable. Caught\n // whatever its type: `decodeURIComponent` raises `URIError` on a malformed percent-escape\n // (`From=%zz`) and `normalizeE164` raises `ConfigurationError` on a number the body carried.\n // Both are bad requests, and returning `null` is what keeps them from failing the request:\n // measured against `theokit@0.48.14`, `handleChannelWebhook` awaits `onMessage` BEFORE\n // building the 200 and catches nothing around it, so a throw here escapes it entirely and\n // the 200 is never built (ADR D428, whose original rationale — \"runs after the 200\" — was\n // measured false on 2026-08-24).\n return null;\n }\n\n // A body the provider posted that carries no message id.\n //\n // Deliberately does NOT also check `inbound.from === \"\"`: all three backends build `from` with\n // `normalizeE164(x ?? \"\")`, which throws on an empty string, so the branch was unreachable and a\n // mutation deleting it survived the suite.\n if (inbound.messageId === \"\") return null;\n\n return inboundToMessageEvent(inbound, options.backend);\n}\n","/**\n * `createWebhookServer` — Express helper for inbound SMS webhooks.\n *\n * Registers per-backend routes (`/sms/twilio`, `/sms/plivo`, `/sms/vonage`)\n * each with the matching parser middleware. All three:\n *\n * 1. Read the raw body verbatim (signature verification depends on the\n * exact bytes — even one extra `\\r\\n` invalidates the HMAC).\n * 2. Call `adapter.verifySignature(ctx)` → 401 if false.\n * 3. Call `adapter.buildEventFromCtx(ctx)` → `dispatchEvent(event)`.\n * 4. Return 204 No Content.\n *\n * Caller can pass an existing Express app (`opts.app`) or let the helper\n * create one. `start()` / `stop()` are idempotent.\n *\n * @public\n */\n\nimport { listenerLifecycle, loadPeer, rawBodyCapture } from \"@theokit/gateway\";\nimport type { Express, Request, Response } from \"express\";\nimport type { SMSAdapter } from \"./adapter.js\";\nimport type { SignatureContext } from \"./backend-types.js\";\n\nimport { ConfigurationError } from \"./errors.js\";\n\nexport interface WebhookServerOptions {\n readonly adapter: SMSAdapter;\n /** Mount path prefix; default `\"/sms\"`. The full path is `${path}/${backend}`. */\n readonly path?: string;\n /** Listen port. Ignored when `app` is provided. Default `3000`. */\n readonly port?: number;\n /** Inject an existing Express app instead of creating one. */\n readonly app?: Express;\n}\n\n/** A started HTTP listener, with the handle needed to shut it down again. */\nexport interface WebhookServer {\n start(): Promise<void>;\n stop(): Promise<void>;\n}\n\nasync function loadExpress(): Promise<() => Express> {\n return loadPeer<() => Express>(\n async () => import(\"express\"),\n () => {\n throw new ConfigurationError({\n code: \"express_not_installed\",\n message: 'gateway-sms: peer-dep \"express\" not installed. Run: pnpm add express',\n });\n },\n );\n}\n\n/**\n * The URL the provider signed.\n *\n * `publicUrl` wins when it is configured, because it is the only value that survives a proxy. The\n * provider verifies against the address IT posted to, and behind a tunnel, an ingress, or a load\n * balancer terminating TLS the reconstruction below yields the internal one — so a correct\n * signature fails, on every delivery, with nothing in the log naming the cause.\n *\n * The header reconstruction stays as the fallback: an app served directly has nothing to configure\n * and the headers are the truth. Measured 2026-08-31 — `publicUrl` is required by all three backend\n * option shapes and documented as \"used by signature verifier\", and until this commit no source\n * file read it.\n */\nfunction signedUrl(\n req: Request,\n headers: Readonly<Record<string, string>>,\n publicUrl?: string,\n): string {\n if (publicUrl !== undefined && publicUrl !== \"\") return publicUrl;\n const protoHeader = headers[\"x-forwarded-proto\"];\n const proto = protoHeader ?? (req.secure ? \"https\" : \"http\");\n const host = req.get(\"host\") ?? \"localhost\";\n return `${proto}://${host}${req.originalUrl}`;\n}\n\nfunction buildSignatureContext(req: Request, publicUrl?: string): SignatureContext {\n const rawBody = (req as Request & { rawBody?: string }).rawBody ?? \"\";\n const headers: Record<string, string> = {};\n for (const [k, v] of Object.entries(req.headers)) {\n headers[k.toLowerCase()] = Array.isArray(v) ? v.join(\",\") : (v ?? \"\");\n }\n return { headers, rawBody, url: signedUrl(req, headers, publicUrl) };\n}\n\n/**\n * Build the HTTP listener that receives the provider's inbound-SMS callbacks.\n *\n * The provider dials in, so this endpoint must be reachable over public HTTPS and registered in the\n * provider console — inbound cannot work behind a firewall. `express` is loaded lazily, so a project\n * that only sends messages never pays for it.\n */\nexport async function createWebhookServer(opts: WebhookServerOptions): Promise<WebhookServer> {\n const createApp = await loadExpress();\n const app: Express = opts.app ?? createApp();\n const prefix = opts.path ?? \"/sms\";\n const backend = opts.adapter.getBackendKind();\n\n const handler = (req: Request, res: Response): void => {\n const ctx = buildSignatureContext(req, opts.adapter.publicUrl);\n if (!opts.adapter.verifySignature(ctx)) {\n res.status(401).type(\"text/plain\").send(\"invalid signature\");\n return;\n }\n let event: ReturnType<typeof opts.adapter.buildEventFromCtx>;\n try {\n event = opts.adapter.buildEventFromCtx(ctx);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n res.status(400).type(\"text/plain\").send(`parse failed: ${msg}`);\n return;\n }\n // Same contract as the LINE server: the provider is answered before the handler runs, so a\n // slow handler cannot become a provider retry. That makes the dispatch floated, and a floated\n // rejection ends the process — so it is caught here rather than left to the runtime (#41).\n void opts.adapter.dispatchEvent(event).catch((err: unknown) => {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-sms] webhook dispatch failed: ${message}\\n`);\n });\n // Twilio expects either TwiML or 204; 204 keeps things simple\n // and avoids accidentally double-replying.\n res.status(204).end();\n };\n\n app.post(`${prefix}/${backend}`, rawBodyCapture(\"gateway-sms\"), handler);\n\n // The lifecycle lives in `@theokit/gateway`, written once. It was duplicated here and in\n // gateway-line, and the same write-once latch bug had to be fixed in both files by one commit —\n // which is what turned the duplication from a style question into a defect (#89).\n return listenerLifecycle({ app, port: opts.port ?? 3000, injected: opts.app !== undefined });\n}\n","/**\n * The SMS half of a channel webhook, in the shape a framework webhook seam expects.\n *\n * `theokit/server/webhook` ships validators for the platforms whose signature is a plain HMAC it\n * can compute itself. SMS is not one of them: Twilio signs the URL plus the sorted POST parameters,\n * Plivo signs a different string again, and Vonage uses a JWT. Those three schemes already exist in\n * this package, correctly, with their own tests — reimplementing them one repository over would put\n * security-critical code in two places and guarantee they drift.\n *\n * So the direction is inverted. The framework declares the SHAPE; the package that owns the\n * platform provides the implementation. The shape is structural, so nothing here imports the\n * framework and this package gains no dependency:\n *\n * ```ts\n * await handleChannelWebhook(request, pathname, {\n * validators: { sms: smsWebhookVerifier(adapter) },\n * })\n * ```\n *\n * @public\n */\n\nimport type { SMSAdapter } from \"./adapter.js\";\nimport type { SignatureContext } from \"./backend-types.js\";\n\n/**\n * What a verifier answers. Structurally identical to the framework's `VerifyResult`, declared here\n * so this package does not depend on the framework to describe its own return value.\n *\n * @public\n */\nexport type WebhookVerifyResult =\n | { readonly ok: true }\n | { readonly ok: false; readonly reason: string };\n\n/** Options for {@link smsWebhookVerifier}. @public */\nexport interface SMSWebhookVerifierOptions {\n /**\n * The URL the provider POSTs to, as the provider sees it.\n *\n * Twilio signs the URL, so verification compares against whatever string is passed here — and\n * behind a proxy or a tunnel the request's own URL is the INTERNAL one, which will not match.\n * Defaults to the adapter's configured `publicUrl` when it has one, and to the request URL\n * otherwise.\n */\n readonly publicUrl?: string;\n}\n\n/**\n * The subset of the adapter this verifier reads. Stated as an interface so the parameter is honest\n * about its requirements, and so a test can supply the two members without a live provider SDK.\n */\ninterface VerifiableAdapter {\n verifySignature(ctx: SignatureContext): boolean;\n readonly publicUrl?: string;\n}\n\n/**\n * The lowercased header map {@link SignatureContext} promises its consumers.\n *\n * No `toLowerCase()` here, and that is the point rather than an omission: the Fetch `Headers` object\n * normalises names on the way in, so iterating it already yields `x-twilio-signature` however the\n * sender wrote it. Lowercasing again was in the first version and mutation testing showed it dead —\n * removing it changed no test, because the platform had already done the work.\n */\nfunction headersOf(request: Request): Record<string, string> {\n const out: Record<string, string> = {};\n request.headers.forEach((value, key) => {\n out[key] = value;\n });\n return out;\n}\n\n/**\n * Build a verifier for one configured SMS adapter.\n *\n * The request is READ, so pass a clone if the body is needed afterwards — a framework seam that\n * hands validators a `clone()` already does this. Reading it raw is not optional: every provider\n * signs the exact bytes, and a body that was parsed and re-serialised hashes differently.\n *\n * **Connect the adapter first.** Each backend loads its provider SDK during `connect()`, and until\n * it has, `verifySignature` answers `false` for everything — so a verifier wired before connect\n * refuses every genuine delivery as a bad signature. The two are NOT distinguishable here: the\n * backend contract returns a boolean, and inventing a reason this function cannot actually observe\n * would be worse than the ambiguity. The behaviour is pinned by a test rather than papered over,\n * and telling them apart needs a readiness signal the adapter does not expose today.\n *\n * @public\n */\nexport function smsWebhookVerifier(\n adapter: SMSAdapter | VerifiableAdapter,\n opts: SMSWebhookVerifierOptions = {},\n): (request: Request) => Promise<WebhookVerifyResult> {\n return async (request: Request): Promise<WebhookVerifyResult> => {\n const rawBody = await request.text();\n const ctx: SignatureContext = {\n headers: headersOf(request),\n rawBody,\n url: opts.publicUrl ?? adapter.publicUrl ?? request.url,\n };\n return adapter.verifySignature(ctx)\n ? { ok: true }\n : { ok: false, reason: \"signature mismatch\" };\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/phone.ts","../src/backend/plivo.ts","../src/backend/twilio.ts","../src/backend/vonage.ts","../src/backend/index.ts","../src/normalize.ts","../src/refuse-attachments.ts","../src/split.ts","../src/adapter.ts","../src/parse-inbound.ts","../src/webhook-server.ts","../src/webhook-verifier.ts"],"names":["GatewayConfigurationError","parsePhoneNumberFromString","parseFormUrlEncoded","chunkByGrapheme","splitKeepingRows","BasePlatformAdapter","loadPeer","rawBodyCapture","DEFAULT_WEBHOOK_MAX_BYTES","listenerLifecycle"],"mappings":";;;;;;AA8BO,IAAM,kBAAA,GAAN,cAAiCA,iCAAA,CAA0B;AAAA,EAC9C,IAAA,GAAO,oBAAA;AAAA,EACzB,YAAY,IAAA,EAAiC;AAC3C,IAAA,KAAA,CAAM,eAAe,IAAI,CAAA;AAAA,EAC3B;AACF;AASO,IAAM,wBAAA,GAAN,cAAuC,kBAAA,CAAmB;AAAA,EAC/D,WAAA,CAAY,SAAwC,OAAA,EAAiB;AACnE,IAAA,KAAA,CAAM;AAAA,MACJ,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,IAAA,GAAkC,EAAC,EACiB;AACpD,EAAA,OAAO,OAAO,OAAA,KAAmD;AAC/D,IAAA,MAAM,OAAA,GAAU,MAAM,OAAA,CAAQ,IAAA,EAAK;AACnC,IAAA,MAAM,GAAA,GAAwB;AAAA,MAC5B,OAAA,EAAS,UAAU,OAAO,CAAA;AAAA,MAC1B,OAAA;AAAA,MACA,GAAA,EAAK,IAAA,CAAK,SAAA,IAAa,OAAA,CAAQ,aAAa,OAAA,CAAQ;AAAA,KACtD;AACA,IAAA,OAAO,OAAA,CAAQ,eAAA,CAAgB,GAAG,CAAA,GAC9B,EAAE,EAAA,EAAI,IAAA,EAAK,GACX,EAAE,EAAA,EAAI,KAAA,EAAO,MAAA,EAAQ,oBAAA,EAAqB;AAAA,EAChD,CAAA;AACF","file":"index.cjs","sourcesContent":["/**\n * Typed errors for `@theokit/gateway-sms` (D389-D396).\n *\n * - `ConfigurationError` — programmer error at construction time\n * (missing signing secret, missing backend SDK install, malformed\n * phone number on outbound). Thrown synchronously.\n * - `BackendNotInstalledError` — peer-dep optional backend (twilio /\n * plivo / @vonage/server-sdk) was selected but the npm package is\n * not installed. Carries actionable install hint.\n *\n * `ConfigurationError` extends the shared core `GatewayConfigurationError`\n * base (roadmap M2); the SDK still consumes structured errors via\n * `metadata.code`. Behavior byte-identical (pinned by `tests/errors.test.ts`).\n *\n * @internal — re-exported by `src/index.ts`.\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;\n\n/**\n * Misconfiguration of this adapter, raised before any network call.\n *\n * Extends the shared core base so every gateway package reports configuration faults in one shape:\n * a structured `code` the caller can branch on, tagged with `\"gateway-sms\"` as the origin. A\n * missing credential or an unsupported option is a programmer error, not a transient failure —\n * these are never retried.\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-sms\", opts);\n }\n}\n\n/**\n * The provider SDK for the selected backend is not installed.\n *\n * `gateway-sms` speaks to Twilio, Plivo or Vonage, and declares all three as optional peers — a\n * project installs only the one it uses. Selecting a backend whose SDK is absent is caught here, at\n * connect time, with the package name and the command that installs it.\n */\nexport class BackendNotInstalledError extends ConfigurationError {\n constructor(backend: \"twilio\" | \"plivo\" | \"vonage\", pkgName: string) {\n super({\n code: \"backend_not_installed\",\n message: `gateway-sms: peer-dep \"${pkgName}\" not installed but backend=\"${backend}\" was selected. Run: pnpm add ${pkgName}`,\n detail: pkgName,\n });\n }\n}\n","/**\n * E.164 phone normalization (D391, EC-6).\n *\n * Wraps `libphonenumber-js` (full — accepts mobile + toll-free; the\n * `/mobile` sub-bundle was inadequate because it rejects toll-free\n * US 1-800 numbers).\n *\n * @internal\n */\n\nimport { parsePhoneNumberFromString } from \"libphonenumber-js\";\n\nimport { ConfigurationError } from \"./errors.js\";\n\n/**\n * Normalize a free-form phone number to canonical E.164 (`+5511999999999`).\n *\n * Accepts:\n * - International with `+`: `\"+5511999999999\"` → unchanged.\n * - National without `+` when `defaultCountry` is provided: `(\"11999999999\", \"BR\")` → `\"+5511999999999\"`.\n * - Toll-free US (EC-6): `\"+18001234567\"` → unchanged.\n *\n * Throws `ConfigurationError({ code: \"invalid_phone_number\" })` on any\n * input that cannot be parsed to a valid number.\n */\nexport function normalizeE164(input: string, defaultCountry?: string): string {\n if (input.length === 0) {\n throw new ConfigurationError({\n code: \"invalid_phone_number\",\n message: \"gateway-sms: phone number is empty\",\n detail: \"<empty>\",\n });\n }\n const parsed = parsePhoneNumberFromString(\n input,\n defaultCountry as Parameters<typeof parsePhoneNumberFromString>[1],\n );\n if (parsed === undefined || !parsed.isValid()) {\n throw new ConfigurationError({\n code: \"invalid_phone_number\",\n message: `gateway-sms: invalid phone number ${JSON.stringify(input)}`,\n detail: input,\n });\n }\n return parsed.format(\"E.164\");\n}\n","/**\n * Plivo backend impl.\n *\n * - SDK: `plivo` (peer-dep, optional).\n * - Signature: `X-Plivo-Signature-V3` is HMAC-SHA256 of the request URL\n * + nonce + body. `validateV3Signature` is exposed by the SDK; we\n * delegate to avoid reimplementation.\n *\n * @internal\n */\n\nimport type { SendResult } from \"@theokit/gateway\";\nimport type { SignatureContext, SMSBackend, SMSInbound } from \"../backend-types.js\";\nimport { BackendNotInstalledError } from \"../errors.js\";\nimport { normalizeE164 } from \"../phone.js\";\nimport type { PlivoOptions } from \"../types.js\";\n\ninterface PlivoCreateResponse {\n apiId?: string;\n messageUuid?: string[];\n message_uuid?: string[];\n}\n\ninterface PlivoClient {\n messages: {\n // The actual SDK uses positional args: create(src, dst, text, ...).\n create(src: string, dst: string, text: string): Promise<PlivoCreateResponse>;\n };\n}\n\ninterface PlivoModule {\n Client: new (authId?: string, authToken?: string) => PlivoClient;\n // Real SDK signature: validateV3Signature(method, uri, nonce, authToken, v3Signature)\n validateV3Signature?: (\n method: string,\n uri: string,\n nonce: string,\n authToken: string,\n signature: string,\n ) => boolean;\n}\n\nasync function loadPlivo(): Promise<PlivoModule> {\n try {\n // Plivo's published types are stricter (positional args) than our\n // generic mock; we narrow at call sites and pass through unknown.\n const mod = (await import(\"plivo\")) as unknown as PlivoModule;\n return mod;\n } catch {\n throw new BackendNotInstalledError(\"plivo\", \"plivo\");\n }\n}\n\nexport class PlivoBackend implements SMSBackend {\n readonly kind = \"plivo\" as const;\n private mod: PlivoModule | undefined;\n private client: PlivoClient | undefined;\n\n constructor(private readonly opts: PlivoOptions) {}\n\n async connect(): Promise<boolean> {\n if (this.client !== undefined) return true;\n this.mod = await loadPlivo();\n this.client = new this.mod.Client(this.opts.authId, this.opts.authToken);\n return true;\n }\n\n async disconnect(): Promise<void> {\n this.client = undefined;\n }\n\n verifySignature(ctx: SignatureContext): boolean {\n if (this.mod?.validateV3Signature === undefined) return false;\n const signature = ctx.headers[\"x-plivo-signature-v3\"];\n const nonce = ctx.headers[\"x-plivo-signature-v3-nonce\"];\n if (signature === undefined || nonce === undefined) return false;\n try {\n return this.mod.validateV3Signature(\"POST\", ctx.url, nonce, this.opts.authToken, signature);\n } catch {\n return false;\n }\n }\n\n parseInbound(ctx: SignatureContext): SMSInbound {\n let params: Record<string, string> = {};\n // Plivo posts JSON or form-encoded depending on application config.\n if ((ctx.headers[\"content-type\"] ?? \"\").includes(\"application/json\")) {\n try {\n params = JSON.parse(ctx.rawBody) as Record<string, string>;\n } catch {\n params = {};\n }\n } else {\n params = parseFormUrlEncoded(ctx.rawBody);\n }\n return {\n from: normalizeE164(params.From ?? \"\", this.opts.defaultCountry),\n to: normalizeE164(params.To ?? \"\", this.opts.defaultCountry),\n body: params.Text ?? params.text ?? \"\",\n messageId: params.MessageUUID ?? params.message_uuid ?? \"\",\n receivedAt: Date.now(),\n raw: params,\n };\n }\n\n async sendMessage(to: string, body: string): Promise<SendResult> {\n if (this.client === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"PlivoBackend.connect() not called\" },\n };\n }\n try {\n const resp = await this.client.messages.create(this.opts.fromNumber, to, body);\n const id = resp.messageUuid?.[0] ?? resp.message_uuid?.[0] ?? resp.apiId ?? \"\";\n return { ok: true, messageId: id };\n } catch (err) {\n return mapPlivoError(err);\n }\n }\n}\n\nfunction parseFormUrlEncoded(body: string): Record<string, string> {\n const params: Record<string, string> = {};\n for (const pair of body.split(\"&\")) {\n if (pair.length === 0) continue;\n const eqIdx = pair.indexOf(\"=\");\n const k = eqIdx < 0 ? pair : pair.slice(0, eqIdx);\n const v = eqIdx < 0 ? \"\" : pair.slice(eqIdx + 1);\n params[decodeURIComponent(k.replace(/\\+/g, \" \"))] = decodeURIComponent(v.replace(/\\+/g, \" \"));\n }\n return params;\n}\n\ninterface PlivoRestError {\n statusCode?: number;\n status?: number;\n message?: string;\n}\n\nfunction mapPlivoError(err: unknown): SendResult {\n const e = err as PlivoRestError;\n const status = e.statusCode ?? e.status ?? 0;\n if (status === 429)\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"Plivo rate limit\" } };\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"Plivo auth error\" },\n };\n }\n if (status === 400) {\n return {\n ok: false,\n error: { code: \"invalid_request\", message: e.message ?? \"Plivo rejected request\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\n}\n","/**\n * Twilio backend impl.\n *\n * - SDK: `twilio` (peer-dep, optional). Loaded lazily so packages\n * that pick other backends don't pay the cost.\n * - Signature: `X-Twilio-Signature` is HMAC-SHA1 of `(fullUrl + sortedParams)`.\n * We delegate to `twilio.validateRequest` so we don't reimplement.\n *\n * @internal\n */\n\nimport type { SendResult } from \"@theokit/gateway\";\nimport type { SignatureContext, SMSBackend, SMSInbound } from \"../backend-types.js\";\nimport { BackendNotInstalledError } from \"../errors.js\";\nimport { normalizeE164 } from \"../phone.js\";\nimport type { TwilioOptions } from \"../types.js\";\n\ninterface TwilioCreateArgs {\n from: string;\n to: string;\n body: string;\n}\n\ninterface TwilioMessageInstance {\n sid: string;\n status?: string;\n}\n\ninterface TwilioClientInstance {\n messages: {\n create(args: TwilioCreateArgs): Promise<TwilioMessageInstance>;\n };\n}\n\ninterface TwilioFactory {\n (accountSid: string, authToken: string): TwilioClientInstance;\n validateRequest(\n authToken: string,\n signature: string,\n url: string,\n params: Record<string, string>,\n ): boolean;\n}\n\nasync function loadTwilio(): Promise<TwilioFactory> {\n try {\n const mod = await import(\"twilio\");\n // ESM ships { default: factory }; CJS ships factory.\n const candidate =\n (mod as { default?: TwilioFactory }).default ?? (mod as unknown as TwilioFactory);\n return candidate;\n } catch {\n throw new BackendNotInstalledError(\"twilio\", \"twilio\");\n }\n}\n\nexport class TwilioBackend implements SMSBackend {\n readonly kind = \"twilio\" as const;\n private client: TwilioClientInstance | undefined;\n private twilio: TwilioFactory | undefined;\n\n constructor(private readonly opts: TwilioOptions) {}\n\n async connect(): Promise<boolean> {\n if (this.client !== undefined) return true;\n this.twilio = await loadTwilio();\n this.client = this.twilio(this.opts.accountSid, this.opts.authToken);\n return true;\n }\n\n async disconnect(): Promise<void> {\n // No persistent connection — REST client is GC'd on dereference.\n this.client = undefined;\n }\n\n verifySignature(ctx: SignatureContext): boolean {\n if (this.twilio === undefined) return false;\n const signature = ctx.headers[\"x-twilio-signature\"];\n if (signature === undefined) return false;\n const params = parseFormUrlEncoded(ctx.rawBody);\n try {\n return this.twilio.validateRequest(this.opts.authToken, signature, ctx.url, params);\n } catch {\n return false;\n }\n }\n\n parseInbound(ctx: SignatureContext): SMSInbound {\n const params = parseFormUrlEncoded(ctx.rawBody);\n return {\n from: normalizeE164(params.From ?? \"\", this.opts.defaultCountry),\n to: normalizeE164(params.To ?? \"\", this.opts.defaultCountry),\n body: params.Body ?? \"\",\n messageId: params.MessageSid ?? params.SmsMessageSid ?? \"\",\n receivedAt: Date.now(),\n raw: params,\n };\n }\n\n async sendMessage(to: string, body: string): Promise<SendResult> {\n if (this.client === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"TwilioBackend.connect() not called\" },\n };\n }\n try {\n const msg = await this.client.messages.create({ from: this.opts.fromNumber, to, body });\n return { ok: true, messageId: msg.sid };\n } catch (err) {\n return mapTwilioError(err);\n }\n }\n}\n\n/**\n * Parse `application/x-www-form-urlencoded` request body to a flat\n * `Record<string, string>`. Twilio POSTs in this format.\n *\n * @internal\n */\nfunction parseFormUrlEncoded(body: string): Record<string, string> {\n const params: Record<string, string> = {};\n for (const pair of body.split(\"&\")) {\n if (pair.length === 0) continue;\n const eqIdx = pair.indexOf(\"=\");\n const k = eqIdx < 0 ? pair : pair.slice(0, eqIdx);\n const v = eqIdx < 0 ? \"\" : pair.slice(eqIdx + 1);\n params[decodeURIComponent(k.replace(/\\+/g, \" \"))] = decodeURIComponent(v.replace(/\\+/g, \" \"));\n }\n return params;\n}\n\ninterface TwilioRestError {\n status?: number;\n code?: number | string;\n message?: string;\n}\n\nfunction mapTwilioError(err: unknown): SendResult {\n const e = err as TwilioRestError;\n const status = e.status ?? 0;\n if (status === 429) {\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"Twilio rate limit\" } };\n }\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"Twilio auth error\" },\n };\n }\n if (status === 400) {\n return {\n ok: false,\n error: { code: \"invalid_request\", message: e.message ?? \"Twilio rejected request\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\n}\n","/**\n * Vonage backend impl.\n *\n * - SDK: `@vonage/server-sdk` (peer-dep, optional).\n * - Signature: `Authorization: Bearer <JWT>` signed with the Signature\n * Secret (NOT the API secret). The SDK exposes `Auth.verifySignature`\n * for this purpose.\n *\n * @internal\n */\n\nimport type { SendResult } from \"@theokit/gateway\";\nimport type { SignatureContext, SMSBackend, SMSInbound } from \"../backend-types.js\";\nimport { BackendNotInstalledError } from \"../errors.js\";\nimport { normalizeE164 } from \"../phone.js\";\nimport type { VonageOptions } from \"../types.js\";\n\ninterface VonageSmsClient {\n send(args: { to: string; from: string; text: string }): Promise<{\n messages?: Array<{ \"message-id\"?: string; messageId?: string; status?: string }>;\n }>;\n}\n\ninterface VonageInstance {\n sms: VonageSmsClient;\n}\n\ninterface VonageModule {\n Vonage: new (creds: {\n apiKey: string;\n apiSecret: string;\n signatureSecret?: string;\n }) => VonageInstance;\n Auth?: {\n verifySignature?: (token: string, secret: string) => boolean;\n };\n}\n\nasync function loadVonage(): Promise<VonageModule> {\n try {\n // SDK ships ESM/CJS variants; we narrow at call sites and pass through.\n const raw = await import(\"@vonage/server-sdk\");\n return raw as unknown as VonageModule;\n } catch {\n throw new BackendNotInstalledError(\"vonage\", \"@vonage/server-sdk\");\n }\n}\n\nexport class VonageBackend implements SMSBackend {\n readonly kind = \"vonage\" as const;\n private mod: VonageModule | undefined;\n private vonage: VonageInstance | undefined;\n\n constructor(private readonly opts: VonageOptions) {}\n\n async connect(): Promise<boolean> {\n if (this.vonage !== undefined) return true;\n this.mod = await loadVonage();\n this.vonage = new this.mod.Vonage({\n apiKey: this.opts.apiKey,\n apiSecret: this.opts.apiSecret,\n signatureSecret: this.opts.signatureSecret,\n });\n return true;\n }\n\n async disconnect(): Promise<void> {\n this.vonage = undefined;\n }\n\n verifySignature(ctx: SignatureContext): boolean {\n const auth = ctx.headers.authorization;\n if (auth === undefined) return false;\n const m = auth.match(/^Bearer\\s+(.+)$/i);\n if (m === null) return false;\n const token = m[1] ?? \"\";\n if (token.length === 0) return false;\n if (this.mod?.Auth?.verifySignature === undefined) return false;\n try {\n return this.mod.Auth.verifySignature(token, this.opts.signatureSecret);\n } catch {\n return false;\n }\n }\n\n parseInbound(ctx: SignatureContext): SMSInbound {\n let payload: Record<string, string> = {};\n try {\n payload = JSON.parse(ctx.rawBody) as Record<string, string>;\n } catch {\n payload = {};\n }\n return {\n from: normalizeE164(payload.msisdn ?? payload.from ?? \"\", this.opts.defaultCountry),\n to: normalizeE164(payload.to ?? \"\", this.opts.defaultCountry),\n body: payload.text ?? \"\",\n messageId: payload.messageId ?? payload[\"message-id\"] ?? \"\",\n receivedAt: Date.now(),\n raw: payload,\n };\n }\n\n async sendMessage(to: string, body: string): Promise<SendResult> {\n if (this.vonage === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"VonageBackend.connect() not called\" },\n };\n }\n try {\n const resp = await this.vonage.sms.send({ from: this.opts.fromNumber, to, text: body });\n const msg = resp.messages?.[0];\n const id = msg?.[\"message-id\"] ?? msg?.messageId ?? \"\";\n if (msg?.status !== undefined && msg.status !== \"0\") {\n return {\n ok: false,\n error: { code: \"send_failed\", message: `Vonage returned status=${msg.status}` },\n };\n }\n return { ok: true, messageId: id };\n } catch (err) {\n return mapVonageError(err);\n }\n }\n}\n\ninterface VonageRestError {\n status?: number;\n response?: { status?: number };\n message?: string;\n}\n\nfunction mapVonageError(err: unknown): SendResult {\n const e = err as VonageRestError;\n const status = e.status ?? e.response?.status ?? 0;\n if (status === 429)\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"Vonage rate limit\" } };\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"Vonage auth error\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\n}\n","/**\n * Backend factory — picks the right impl from `opts.backend`.\n *\n * @internal\n */\n\nimport type { SMSBackend } from \"../backend-types.js\";\nimport type { SMSAdapterOptions } from \"../types.js\";\nimport { PlivoBackend } from \"./plivo.js\";\nimport { TwilioBackend } from \"./twilio.js\";\nimport { VonageBackend } from \"./vonage.js\";\n\nexport function createBackend(opts: SMSAdapterOptions): SMSBackend {\n switch (opts.backend) {\n case \"twilio\":\n return new TwilioBackend(opts);\n case \"plivo\":\n return new PlivoBackend(opts);\n case \"vonage\":\n return new VonageBackend(opts);\n default: {\n const _exhaustive: never = opts;\n throw new Error(`unknown backend: ${JSON.stringify(_exhaustive)}`);\n }\n }\n}\n","/**\n * Inbound normalization: `SMSInbound` → `SMSMessageEvent`.\n *\n * `from` and `to` are already E.164 (backend.parseInbound enforces this).\n * `channel.id` is `from` because SMS conversations are flat per-pair\n * (D394 — no threading).\n *\n * @internal\n */\n\nimport type { SMSMessageEvent } from \"@theokit/gateway\";\n\nimport type { SMSInbound } from \"./backend-types.js\";\n\nexport function inboundToMessageEvent(\n inbound: SMSInbound,\n backend: \"twilio\" | \"plivo\" | \"vonage\",\n): SMSMessageEvent {\n return {\n id: inbound.messageId,\n platform: \"sms\",\n sender: { id: inbound.from },\n channel: { id: inbound.from, type: \"dm\" },\n text: inbound.body,\n receivedAt: inbound.receivedAt,\n sms: {\n backend,\n messageId: inbound.messageId,\n from: inbound.from,\n to: inbound.to,\n raw: inbound.raw,\n },\n };\n}\n","/**\n * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * This adapter sends text only, so an outbound carrying attachments is refused rather than sent without its images.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `@theokit/gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"@theokit/gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: { code: \"attachments_unsupported\", message: \"sms adapter cannot send attachments\" },\n };\n}\n","/**\n * `splitForSMS` — grapheme-cluster-safe multipart segmentation (D393, EC-7), keeping table rows\n * whole.\n *\n * Concatenated SMS (UDH) on modern carriers reassemble at the recipient,\n * but each TCP/IP-layer chunk is one billed message. We segment at\n * 1600 chars (default) so the API call doesn't reject and each part is\n * prefixed with `(i/N) ` to allow manual reordering when carriers\n * deliver out of sequence (EC-7).\n *\n * A text within the limit goes through core `chunkByGrapheme` as before. A longer one is cut at\n * the last grapheme boundary within each part, which is where `chunkByGrapheme`'s greedy walk\n * ends a part, so emoji (🇧🇷) and combining sequences are never severed and text with no table\n * row splits exactly as it did (pinned by `tests/split-no-table-baseline.test.ts` and the\n * equivalence test in `tests/split-tables.test.ts`). A cut that falls inside a Markdown table row\n * which fits in a part moves back to the start of that row (B-556). The rule is core\n * `splitKeepingRows`, shared with gateway-line. The `(i/N) ` prefix (and its reserved width) stays here since it is SMS-specific.\n *\n * @internal\n */\n\nimport { chunkByGrapheme, splitKeepingRows } from \"@theokit/gateway\";\n\n/**\n * Width of `\"(i/total) \"` when `i` has as many digits as `total` — the widest\n * the prefix can get for a given part count. `(99/99) ` is 8, `(100/126) ` is\n * 10, `(1000/1234) ` is 12.\n *\n * This used to be the constant 8, commented `\"(99/99) \" worst case`. It is the\n * worst case only below 100 parts; from the hundredth part on, every prefix\n * overflowed its reservation and each part exceeded the caller's declared cap\n * by 2 chars, which the provider rejects.\n */\nfunction prefixWidthFor(total: number): number {\n return 2 * String(total).length + 4;\n}\n\n/** One fixed-point pass: the parts of `text` with `partLimit` left beside the prefix. */\nfunction partsFor(text: string, limit: number, partLimit: number): string[] {\n if (text.length <= limit) return chunkByGrapheme(text, { limit, partLimit });\n // The core's RangeError for a limit of 0, 1.5 or NaN, with the message it had before.\n chunkByGrapheme(\"\", { limit, partLimit });\n return splitKeepingRows(text, partLimit);\n}\n\nexport function splitForSMS(text: string, limit = 1600): string[] {\n // Chicken and egg: the reservation depends on the part count, and the part\n // count depends on the reservation. Widening the prefix shrinks the payload,\n // which can push the count into another digit — so iterate to a fixed point.\n // It converges fast because the width grows with the LOGARITHM of the count;\n // the bound is a backstop against a pathological input, not the expected path.\n let reserved = prefixWidthFor(1);\n for (let pass = 0; pass < 8; pass += 1) {\n const partLimit = limit - reserved;\n if (partLimit <= 0) {\n throw new RangeError(\n `limit ${limit} is too small to carry an SMS part: the \"(i/N) \" prefix alone needs ${reserved} chars`,\n );\n }\n const parts = partsFor(text, limit, partLimit);\n if (parts.length <= 1) return parts; // short-circuit / single part: skip prefix\n const needed = prefixWidthFor(parts.length);\n if (needed <= reserved) {\n const total = parts.length;\n return parts.map((p, i) => `(${i + 1}/${total}) ${p}`);\n }\n reserved = needed;\n }\n /* c8 ignore next 3 -- unreachable: 8 passes cover part counts up to 10^8. */\n throw new RangeError(\n `could not settle the \"(i/N) \" prefix width for a ${text.length}-char message at limit ${limit}`,\n );\n}\n","/**\n * `SMSAdapter` — implements `BasePlatformAdapter` over a backend\n * (twilio / plivo / vonage). ADRs D389-D396.\n *\n * Lifecycle:\n * - `connect()` initializes the chosen backend (lazy peer-dep import).\n * - `disconnect()` releases the backend; idempotent.\n * - `sendMessage()` splits multipart (D393) and sends each part via backend.\n * - `onInbound(handler)` replaces previous handler (EC-H, mirror D276).\n *\n * Inbound dispatch is driven by the webhook server (`webhook-server.ts`)\n * which calls `adapter.dispatchInbound(ctx)` after signature verification.\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\nimport { createBackend } from \"./backend/index.js\";\nimport type { SignatureContext, SMSBackend } from \"./backend-types.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { inboundToMessageEvent } from \"./normalize.js\";\nimport { normalizeE164 } from \"./phone.js\";\nimport { refuseAttachments } from \"./refuse-attachments.js\";\nimport { splitForSMS } from \"./split.js\";\nimport type { SMSAdapterOptions } from \"./types.js\";\n\nexport class SMSAdapter extends BasePlatformAdapter {\n /**\n * Whether the \"this medium carries no formatting\" warning has already been emitted.\n *\n * Once per adapter, not once per message: a gateway answering a busy channel would turn a\n * useful diagnostic into a log flood, and a flooded log is one nobody reads — the same\n * reason the group-mention and allowlist drops elsewhere in this family log once.\n */\n private warnedAboutFormat = false;\n\n /**\n * Say, once, that a declared format is being dropped.\n *\n * `OutboundMessage.format` is the caller stating intent, and this medium has nowhere to put\n * it: no flag, no markup, no alternative part. Discarding it in silence is the swallowed-\n * error shape `rules/error-handling.md` refuses — nothing fails, and the caller learns their\n * formatting never arrived from a user, weeks later.\n *\n * @internal\n */\n private warnFormatUnsupported(format: string | undefined): void {\n // The \"is there anything to say\" question lives here rather than at the call site: a\n // `sendMessage` already at its complexity limit should ask one thing, not three.\n if (format === undefined || format === \"plain\") return;\n if (this.warnedAboutFormat) return;\n this.warnedAboutFormat = true;\n process.stderr.write(\n `[gateway-sms] format=\"${format}\" was declared, and SMS cannot carry it — ` +\n \"the medium is plain text. Sending unformatted; this is logged once.\\n\",\n );\n }\n\n readonly platform = \"sms\" as const;\n\n /**\n * The URL the provider POSTs inbound to, as the provider sees it.\n *\n * Required by all three backend option shapes and documented there as \"used by signature\n * verifier\" — and, measured 2026-08-31, read by nothing: it appeared only in the type and in test\n * fixtures. Twilio SIGNS this URL, so the value matters most in exactly the case where the\n * request cannot supply it: behind a proxy or a tunnel, the request's own URL is the internal one\n * and will not match what was signed.\n *\n * Exposed so {@link smsWebhookVerifier} can use it, which is what makes the option true.\n */\n readonly publicUrl: string;\n\n private readonly backend: SMSBackend;\n private inboundHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private connected = false;\n private readonly defaultCountry: string | undefined;\n\n constructor(opts: SMSAdapterOptions) {\n super();\n // EC-1: refuse to operate without signing secret.\n const secret = secretFromOpts(opts);\n if (secret.length === 0) {\n throw new ConfigurationError({\n code: \"signing_secret_required\",\n message: `gateway-sms: backend=\"${opts.backend}\" requires a signing secret (would accept unsigned webhooks)`,\n });\n }\n this.defaultCountry = opts.defaultCountry;\n this.publicUrl = opts.publicUrl;\n this.backend = createBackend(opts);\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n const ok = await this.backend.connect();\n this.connected = ok;\n return ok;\n }\n\n async disconnect(): Promise<void> {\n if (!this.connected) return;\n await this.backend.disconnect();\n this.connected = false;\n this.inboundHandler = undefined;\n }\n\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.sendText(out);\n }\n\n private async sendText(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"outbound text is empty\" } };\n }\n let toE164: string;\n try {\n toE164 = normalizeE164(out.channel.id, this.defaultCountry);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return { ok: false, error: { code: \"invalid_phone_number\", message: msg } };\n }\n const parts = splitForSMS(out.text);\n // Send sequentially so the recipient sees them in order; concurrent\n // submit would still cost the same but breaks ordering at carriers.\n let lastResult: SendResult | undefined;\n // SMS is plain text by definition. Reading the field is not ceremony: it is what turns a\n // silent discard into a stated one.\n this.warnFormatUnsupported(out.format);\n\n for (const part of parts) {\n lastResult = await this.backend.sendMessage(toE164, part);\n if (lastResult.ok !== true) {\n return {\n ok: false,\n error: {\n code: lastResult.error?.code ?? \"partial_send_failure\",\n message: `partial send failed after ${parts.indexOf(part)}/${parts.length}: ${lastResult.error?.message ?? \"unknown\"}`,\n },\n };\n }\n }\n return lastResult ?? { ok: false, error: { code: \"send_failed\", message: \"no parts sent\" } };\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace, not stack.\n this.inboundHandler = handler;\n return () => {\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n /**\n * Webhook hook — called by `createWebhookServer` AFTER signature\n * verification + parseInbound. Returns dispatch outcome (used for\n * 200/204 vs 500 by the webhook handler).\n *\n * @internal\n */\n async dispatchInbound(ctx: SignatureContext): Promise<\"ok\" | \"no_handler\" | \"parse_failed\"> {\n if (!this.backend.verifySignature(ctx)) {\n // Caller (webhook-server) inspects this via verifySignature directly,\n // but we re-check defensively if anyone calls dispatch directly.\n return \"parse_failed\";\n }\n let inbound: ReturnType<SMSBackend[\"parseInbound\"]>;\n try {\n inbound = this.backend.parseInbound(ctx);\n } catch {\n return \"parse_failed\";\n }\n if (this.inboundHandler === undefined) return \"no_handler\";\n const event = inboundToMessageEvent(inbound, this.backend.kind);\n try {\n await this.inboundHandler(event);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-sms] handler threw: ${msg}\\n`);\n }\n return \"ok\";\n }\n\n /**\n * Direct signature check — used by the webhook server to respond\n * `401` BEFORE dispatch when signature is invalid.\n *\n * @internal\n */\n verifySignature(ctx: SignatureContext): boolean {\n return this.backend.verifySignature(ctx);\n }\n\n /**\n * Direct parse — used by the webhook server when signature was already\n * validated upstream. Returns the normalized `SMSMessageEvent` to be\n * dispatched.\n *\n * @internal\n */\n buildEventFromCtx(ctx: SignatureContext): GatewayMessageEvent {\n const inbound = this.backend.parseInbound(ctx);\n return inboundToMessageEvent(inbound, this.backend.kind);\n }\n\n /**\n * Dispatch a pre-built event (used by webhook server after manual\n * signature + parse). Honors EC-H replace semantics and isolates\n * handler exceptions per `gateway-runner` contract.\n *\n * @internal\n */\n async dispatchEvent(event: GatewayMessageEvent): Promise<\"ok\" | \"no_handler\"> {\n if (this.inboundHandler === undefined) return \"no_handler\";\n try {\n await this.inboundHandler(event);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-sms] handler threw: ${msg}\\n`);\n }\n return \"ok\";\n }\n\n /** Backend kind (escape hatch for callers needing to introspect). */\n getBackendKind(): \"twilio\" | \"plivo\" | \"vonage\" {\n return this.backend.kind;\n }\n\n /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.runHandler(this.inboundHandler, event);\n }\n}\n\nfunction secretFromOpts(opts: SMSAdapterOptions): string {\n switch (opts.backend) {\n case \"twilio\":\n return opts.authToken;\n case \"plivo\":\n return opts.authToken;\n case \"vonage\":\n return opts.signatureSecret;\n default: {\n const _exhaustive: never = opts;\n void _exhaustive;\n return \"\";\n }\n }\n}\n","/**\n * Translating a raw provider webhook into the canonical event.\n *\n * **This does NOT go through TheoKit's `handleChannelWebhook`.** Signature verification here needs\n * the RAW body, the headers and the exact URL — `ChannelMessage` carries none of the three, so the\n * check cannot be performed from inside `onMessage` whatever the provider sends. Twilio adds a\n * second obstacle: it posts `application/x-www-form-urlencoded`, and that seam reads the body with\n * `request.json()` and answers 400 when it is not JSON. (Plivo accepts either encoding and Vonage\n * posts JSON, so only the first reason applies to them.)\n *\n * For an Express app, `createWebhookServer` is the whole path and you never call this — it builds\n * the {@link SignatureContext}, verifies the signature and goes through the adapter. This export is\n * for a route you host yourself: build the context from a request whose body you have not parsed,\n * then call this. It composes two functions that\n * already existed and were both private: each backend's `parseInbound`, which turns a provider's\n * raw body into the provider-agnostic {@link SMSInbound}, and `inboundToMessageEvent`, which turns\n * that into the canonical event. Neither is duplicated here — per ADR D426 the mapping stays in one\n * place, and this is composition, not a second translator.\n *\n * **Why it takes the adapter's options.** Parsing is provider-specific (`Twilio` posts\n * `MessageSid`, Plivo posts `MessageUUID`) and, for Twilio, country-dependent: a number that is not\n * already in E.164 is normalised against `defaultCountry`. Both live in the options an app already\n * holds, because it constructed the adapter with them. `createBackend` only stores them — it opens\n * no connection and loads no SDK, so this stays a pure function over its inputs.\n */\n\nimport type { SMSMessageEvent } from \"@theokit/gateway\";\n\nimport { createBackend } from \"./backend/index.js\";\nimport type { SignatureContext, SMSInbound } from \"./backend-types.js\";\nimport { inboundToMessageEvent } from \"./normalize.js\";\nimport type { SMSAdapterOptions } from \"./types.js\";\n\n/**\n * Translate one raw provider webhook into an {@link SMSMessageEvent}.\n *\n * Returns `null` — never throws — when the body is not one this provider recognises. The caller is\n * whatever holds the {@link SignatureContext}: `createWebhookServer` here, or your own route. It\n * returns `null` rather than throwing because a throw out of a webhook handler becomes a failed\n * request, and the provider then sees a delivery failure for a body that was merely unrecognised\n * (ADR D428, whose original rationale — \"runs after the 200\" — was measured false on 2026-08-24).\n *\n * `null` here means \"this body is not a parseable inbound message\".\n *\n * **One class of configuration error is not distinguishable from a bad body, and is not pretended\n * to be.** `defaultCountry` is read while parsing the body's own numbers, and `normalizeE164`\n * raises the same `ConfigurationError` for a bad configured country as for a bad number in the\n * body. An invalid `defaultCountry` therefore degrades to `null` rather than throwing.\n *\n * An earlier version tried to separate them by validating `options.fromNumber` up front. That was\n * wrong twice: `fromNumber` is passed raw to the provider SDK everywhere else in this package and\n * validated nowhere, and the invented rule rejected four documented, valid configurations — a\n * Vonage alphanumeric sender ID (`\"ACME\"`), a Twilio short code (`\"12345\"`), a Messaging Service\n * SID (`\"MG…\"`), and a national number with `defaultCountry` set. Each one threw out of\n * `onMessage`, turning a message the provider delivered into a failed request — precisely the\n * failure the check was written to prevent.\n * Inventing a validation stricter than the package's own is how that happened.\n *\n * @public\n */\nexport function parseInbound(\n options: SMSAdapterOptions,\n ctx: SignatureContext,\n): SMSMessageEvent | null {\n // `createBackend` is the CONFIGURATION step and sits outside the try on purpose: an unsupported\n // `backend` is a programmer error and must surface, not become the same `null` a malformed body\n // produces.\n const backend = createBackend(options);\n\n let inbound: SMSInbound;\n try {\n inbound = backend.parseInbound(ctx);\n } catch {\n // Everything from here is body-dependent, so any error means the body was unreadable. Caught\n // whatever its type: `decodeURIComponent` raises `URIError` on a malformed percent-escape\n // (`From=%zz`) and `normalizeE164` raises `ConfigurationError` on a number the body carried.\n // Both are bad requests, and returning `null` is what keeps them from failing the request:\n // measured against `theokit@0.48.14`, `handleChannelWebhook` awaits `onMessage` BEFORE\n // building the 200 and catches nothing around it, so a throw here escapes it entirely and\n // the 200 is never built (ADR D428, whose original rationale — \"runs after the 200\" — was\n // measured false on 2026-08-24).\n return null;\n }\n\n // A body the provider posted that carries no message id.\n //\n // Deliberately does NOT also check `inbound.from === \"\"`: all three backends build `from` with\n // `normalizeE164(x ?? \"\")`, which throws on an empty string, so the branch was unreachable and a\n // mutation deleting it survived the suite.\n if (inbound.messageId === \"\") return null;\n\n return inboundToMessageEvent(inbound, options.backend);\n}\n","/**\n * `createWebhookServer` — Express helper for inbound SMS webhooks.\n *\n * Registers per-backend routes (`/sms/twilio`, `/sms/plivo`, `/sms/vonage`)\n * each with the matching parser middleware. All three:\n *\n * 1. Read the raw body verbatim (signature verification depends on the\n * exact bytes — even one extra `\\r\\n` invalidates the HMAC).\n * 2. Call `adapter.verifySignature(ctx)` → 401 if false.\n * 3. Call `adapter.buildEventFromCtx(ctx)` → `dispatchEvent(event)`.\n * 4. Return 204 No Content.\n *\n * Caller can pass an existing Express app (`opts.app`) or let the helper\n * create one. `start()` / `stop()` are idempotent.\n *\n * @public\n */\n\nimport {\n DEFAULT_WEBHOOK_MAX_BYTES,\n listenerLifecycle,\n loadPeer,\n rawBodyCapture,\n} from \"@theokit/gateway\";\nimport type { Express, Request, Response } from \"express\";\nimport type { SMSAdapter } from \"./adapter.js\";\nimport type { SignatureContext } from \"./backend-types.js\";\n\nimport { ConfigurationError } from \"./errors.js\";\n\nexport interface WebhookServerOptions {\n readonly adapter: SMSAdapter;\n /** Mount path prefix; default `\"/sms\"`. The full path is `${path}/${backend}`. */\n readonly path?: string;\n /** Listen port. Ignored when `app` is provided. Default `3000`. */\n readonly port?: number;\n /** Inject an existing Express app instead of creating one. */\n readonly app?: Express;\n}\n\n/** A started HTTP listener, with the handle needed to shut it down again. */\nexport interface WebhookServer {\n start(): Promise<void>;\n stop(): Promise<void>;\n}\n\nasync function loadExpress(): Promise<() => Express> {\n return loadPeer<() => Express>(\n async () => import(\"express\"),\n () => {\n throw new ConfigurationError({\n code: \"express_not_installed\",\n message: 'gateway-sms: peer-dep \"express\" not installed. Run: pnpm add express',\n });\n },\n );\n}\n\n/**\n * The URL the provider signed.\n *\n * `publicUrl` wins when it is configured, because it is the only value that survives a proxy. The\n * provider verifies against the address IT posted to, and behind a tunnel, an ingress, or a load\n * balancer terminating TLS the reconstruction below yields the internal one — so a correct\n * signature fails, on every delivery, with nothing in the log naming the cause.\n *\n * The header reconstruction stays as the fallback: an app served directly has nothing to configure\n * and the headers are the truth. Measured 2026-08-31 — `publicUrl` is required by all three backend\n * option shapes and documented as \"used by signature verifier\", and until this commit no source\n * file read it.\n */\nfunction signedUrl(\n req: Request,\n headers: Readonly<Record<string, string>>,\n publicUrl?: string,\n): string {\n if (publicUrl !== undefined && publicUrl !== \"\") return publicUrl;\n const protoHeader = headers[\"x-forwarded-proto\"];\n const proto = protoHeader ?? (req.secure ? \"https\" : \"http\");\n const host = req.get(\"host\") ?? \"localhost\";\n return `${proto}://${host}${req.originalUrl}`;\n}\n\nfunction buildSignatureContext(req: Request, publicUrl?: string): SignatureContext {\n const rawBody = (req as Request & { rawBody?: string }).rawBody ?? \"\";\n const headers: Record<string, string> = {};\n for (const [k, v] of Object.entries(req.headers)) {\n headers[k.toLowerCase()] = Array.isArray(v) ? v.join(\",\") : (v ?? \"\");\n }\n return { headers, rawBody, url: signedUrl(req, headers, publicUrl) };\n}\n\n/**\n * Build the HTTP listener that receives the provider's inbound-SMS callbacks.\n *\n * The provider dials in, so this endpoint must be reachable over public HTTPS and registered in the\n * provider console — inbound cannot work behind a firewall. `express` is loaded lazily, so a project\n * that only sends messages never pays for it.\n */\nexport async function createWebhookServer(opts: WebhookServerOptions): Promise<WebhookServer> {\n const createApp = await loadExpress();\n const app: Express = opts.app ?? createApp();\n const prefix = opts.path ?? \"/sms\";\n const backend = opts.adapter.getBackendKind();\n\n const handler = (req: Request, res: Response): void => {\n const ctx = buildSignatureContext(req, opts.adapter.publicUrl);\n if (!opts.adapter.verifySignature(ctx)) {\n res.status(401).type(\"text/plain\").send(\"invalid signature\");\n return;\n }\n let event: ReturnType<typeof opts.adapter.buildEventFromCtx>;\n try {\n event = opts.adapter.buildEventFromCtx(ctx);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n res.status(400).type(\"text/plain\").send(`parse failed: ${msg}`);\n return;\n }\n // Same contract as the LINE server: the provider is answered before the handler runs, so a\n // slow handler cannot become a provider retry. That makes the dispatch floated, and a floated\n // rejection ends the process — so it is caught here rather than left to the runtime (#41).\n void opts.adapter.dispatchEvent(event).catch((err: unknown) => {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-sms] webhook dispatch failed: ${message}\\n`);\n });\n // Twilio expects either TwiML or 204; 204 keeps things simple\n // and avoids accidentally double-replying.\n res.status(204).end();\n };\n\n app.post(\n `${prefix}/${backend}`,\n rawBodyCapture(\"gateway-sms\", { maxBytes: DEFAULT_WEBHOOK_MAX_BYTES }),\n handler,\n );\n\n // The lifecycle lives in `@theokit/gateway`, written once. It was duplicated here and in\n // gateway-line, and the same write-once latch bug had to be fixed in both files by one commit —\n // which is what turned the duplication from a style question into a defect (#89).\n return listenerLifecycle({ app, port: opts.port ?? 3000, injected: opts.app !== undefined });\n}\n","/**\n * The SMS half of a channel webhook, in the shape a framework webhook seam expects.\n *\n * `theokit/server/webhook` ships validators for the platforms whose signature is a plain HMAC it\n * can compute itself. SMS is not one of them: Twilio signs the URL plus the sorted POST parameters,\n * Plivo signs a different string again, and Vonage uses a JWT. Those three schemes already exist in\n * this package, correctly, with their own tests — reimplementing them one repository over would put\n * security-critical code in two places and guarantee they drift.\n *\n * So the direction is inverted. The framework declares the SHAPE; the package that owns the\n * platform provides the implementation. The shape is structural, so nothing here imports the\n * framework and this package gains no dependency:\n *\n * ```ts\n * await handleChannelWebhook(request, pathname, {\n * validators: { sms: smsWebhookVerifier(adapter) },\n * })\n * ```\n *\n * @public\n */\n\nimport type { SMSAdapter } from \"./adapter.js\";\nimport type { SignatureContext } from \"./backend-types.js\";\n\n/**\n * What a verifier answers. Structurally identical to the framework's `VerifyResult`, declared here\n * so this package does not depend on the framework to describe its own return value.\n *\n * @public\n */\nexport type WebhookVerifyResult =\n | { readonly ok: true }\n | { readonly ok: false; readonly reason: string };\n\n/** Options for {@link smsWebhookVerifier}. @public */\nexport interface SMSWebhookVerifierOptions {\n /**\n * The URL the provider POSTs to, as the provider sees it.\n *\n * Twilio signs the URL, so verification compares against whatever string is passed here — and\n * behind a proxy or a tunnel the request's own URL is the INTERNAL one, which will not match.\n * Defaults to the adapter's configured `publicUrl` when it has one, and to the request URL\n * otherwise.\n */\n readonly publicUrl?: string;\n}\n\n/**\n * The subset of the adapter this verifier reads. Stated as an interface so the parameter is honest\n * about its requirements, and so a test can supply the two members without a live provider SDK.\n */\ninterface VerifiableAdapter {\n verifySignature(ctx: SignatureContext): boolean;\n readonly publicUrl?: string;\n}\n\n/**\n * The lowercased header map {@link SignatureContext} promises its consumers.\n *\n * No `toLowerCase()` here, and that is the point rather than an omission: the Fetch `Headers` object\n * normalises names on the way in, so iterating it already yields `x-twilio-signature` however the\n * sender wrote it. Lowercasing again was in the first version and mutation testing showed it dead —\n * removing it changed no test, because the platform had already done the work.\n */\nfunction headersOf(request: Request): Record<string, string> {\n const out: Record<string, string> = {};\n request.headers.forEach((value, key) => {\n out[key] = value;\n });\n return out;\n}\n\n/**\n * Build a verifier for one configured SMS adapter.\n *\n * The request is READ, so pass a clone if the body is needed afterwards — a framework seam that\n * hands validators a `clone()` already does this. Reading it raw is not optional: every provider\n * signs the exact bytes, and a body that was parsed and re-serialised hashes differently.\n *\n * **Connect the adapter first.** Each backend loads its provider SDK during `connect()`, and until\n * it has, `verifySignature` answers `false` for everything — so a verifier wired before connect\n * refuses every genuine delivery as a bad signature. The two are NOT distinguishable here: the\n * backend contract returns a boolean, and inventing a reason this function cannot actually observe\n * would be worse than the ambiguity. The behaviour is pinned by a test rather than papered over,\n * and telling them apart needs a readiness signal the adapter does not expose today.\n *\n * @public\n */\nexport function smsWebhookVerifier(\n adapter: SMSAdapter | VerifiableAdapter,\n opts: SMSWebhookVerifierOptions = {},\n): (request: Request) => Promise<WebhookVerifyResult> {\n return async (request: Request): Promise<WebhookVerifyResult> => {\n const rawBody = await request.text();\n const ctx: SignatureContext = {\n headers: headersOf(request),\n rawBody,\n url: opts.publicUrl ?? adapter.publicUrl ?? request.url,\n };\n return adapter.verifySignature(ctx)\n ? { ok: true }\n : { ok: false, reason: \"signature mismatch\" };\n };\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -27,7 +27,11 @@ interface TwilioOptions {
27
27
  readonly authToken: string;
28
28
  /** Bot's own E.164 number (used as `from` in outbound). */
29
29
  readonly fromNumber: string;
30
- /** Public URL where Twilio posts inbound — used by signature verifier. */
30
+ /**
31
+ * Public URL the provider posts inbound to. This configured value is the
32
+ * URL the signature is checked against, used before `x-forwarded-proto`
33
+ * and the `host` header.
34
+ */
31
35
  readonly publicUrl: string;
32
36
  /** Default country for unprefixed inbound `from` numbers. Optional. */
33
37
  readonly defaultCountry?: string;
@@ -39,6 +43,11 @@ interface PlivoOptions {
39
43
  /** Auth token used for V3 signature verification — REQUIRED (D392, EC-1). */
40
44
  readonly authToken: string;
41
45
  readonly fromNumber: string;
46
+ /**
47
+ * Public URL the provider posts inbound to. This configured value is the
48
+ * URL the signature is checked against, used before `x-forwarded-proto`
49
+ * and the `host` header.
50
+ */
42
51
  readonly publicUrl: string;
43
52
  readonly defaultCountry?: string;
44
53
  }
@@ -64,6 +73,11 @@ interface VonageOptions {
64
73
  */
65
74
  readonly signatureSecret: string;
66
75
  readonly fromNumber: string;
76
+ /**
77
+ * Public URL the provider posts inbound to. This configured value is the
78
+ * URL the signature is checked against, used before `x-forwarded-proto`
79
+ * and the `host` header.
80
+ */
67
81
  readonly publicUrl: string;
68
82
  readonly defaultCountry?: string;
69
83
  }
@@ -121,6 +135,7 @@ declare class SMSAdapter extends BasePlatformAdapter {
121
135
  connect(): Promise<boolean>;
122
136
  disconnect(): Promise<void>;
123
137
  sendMessage(out: OutboundMessage): Promise<SendResult>;
138
+ private sendText;
124
139
  onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
125
140
  /** Backend kind (escape hatch for callers needing to introspect). */
126
141
  getBackendKind(): "twilio" | "plivo" | "vonage";
@@ -262,7 +277,8 @@ declare function parseInbound(options: SMSAdapterOptions, ctx: SignatureContext)
262
277
  declare function normalizeE164(input: string, defaultCountry?: string): string;
263
278
 
264
279
  /**
265
- * `splitForSMS` — grapheme-cluster-safe multipart segmentation (D393, EC-7).
280
+ * `splitForSMS` — grapheme-cluster-safe multipart segmentation (D393, EC-7), keeping table rows
281
+ * whole.
266
282
  *
267
283
  * Concatenated SMS (UDH) on modern carriers reassemble at the recipient,
268
284
  * but each TCP/IP-layer chunk is one billed message. We segment at
@@ -270,11 +286,13 @@ declare function normalizeE164(input: string, defaultCountry?: string): string;
270
286
  * prefixed with `(i/N) ` to allow manual reordering when carriers
271
287
  * deliver out of sequence (EC-7).
272
288
  *
273
- * Thin wrapper over core `chunkByGrapheme` (roadmap M1) — single-sources the
274
- * `Intl.Segmenter` grapheme walk so emoji (🇧🇷) and combining sequences are
275
- * never severed. The `(i/N) ` prefix (and its reserved width) stays here since
276
- * it is SMS-specific. Output is byte-identical to the previous implementation
277
- * (pinned by `tests/split.test.ts`).
289
+ * A text within the limit goes through core `chunkByGrapheme` as before. A longer one is cut at
290
+ * the last grapheme boundary within each part, which is where `chunkByGrapheme`'s greedy walk
291
+ * ends a part, so emoji (🇧🇷) and combining sequences are never severed and text with no table
292
+ * row splits exactly as it did (pinned by `tests/split-no-table-baseline.test.ts` and the
293
+ * equivalence test in `tests/split-tables.test.ts`). A cut that falls inside a Markdown table row
294
+ * which fits in a part moves back to the start of that row (B-556). The rule is core
295
+ * `splitKeepingRows`, shared with gateway-line. The `(i/N) ` prefix (and its reserved width) stays here since it is SMS-specific.
278
296
  *
279
297
  * @internal
280
298
  */
package/dist/index.d.ts CHANGED
@@ -27,7 +27,11 @@ interface TwilioOptions {
27
27
  readonly authToken: string;
28
28
  /** Bot's own E.164 number (used as `from` in outbound). */
29
29
  readonly fromNumber: string;
30
- /** Public URL where Twilio posts inbound — used by signature verifier. */
30
+ /**
31
+ * Public URL the provider posts inbound to. This configured value is the
32
+ * URL the signature is checked against, used before `x-forwarded-proto`
33
+ * and the `host` header.
34
+ */
31
35
  readonly publicUrl: string;
32
36
  /** Default country for unprefixed inbound `from` numbers. Optional. */
33
37
  readonly defaultCountry?: string;
@@ -39,6 +43,11 @@ interface PlivoOptions {
39
43
  /** Auth token used for V3 signature verification — REQUIRED (D392, EC-1). */
40
44
  readonly authToken: string;
41
45
  readonly fromNumber: string;
46
+ /**
47
+ * Public URL the provider posts inbound to. This configured value is the
48
+ * URL the signature is checked against, used before `x-forwarded-proto`
49
+ * and the `host` header.
50
+ */
42
51
  readonly publicUrl: string;
43
52
  readonly defaultCountry?: string;
44
53
  }
@@ -64,6 +73,11 @@ interface VonageOptions {
64
73
  */
65
74
  readonly signatureSecret: string;
66
75
  readonly fromNumber: string;
76
+ /**
77
+ * Public URL the provider posts inbound to. This configured value is the
78
+ * URL the signature is checked against, used before `x-forwarded-proto`
79
+ * and the `host` header.
80
+ */
67
81
  readonly publicUrl: string;
68
82
  readonly defaultCountry?: string;
69
83
  }
@@ -121,6 +135,7 @@ declare class SMSAdapter extends BasePlatformAdapter {
121
135
  connect(): Promise<boolean>;
122
136
  disconnect(): Promise<void>;
123
137
  sendMessage(out: OutboundMessage): Promise<SendResult>;
138
+ private sendText;
124
139
  onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
125
140
  /** Backend kind (escape hatch for callers needing to introspect). */
126
141
  getBackendKind(): "twilio" | "plivo" | "vonage";
@@ -262,7 +277,8 @@ declare function parseInbound(options: SMSAdapterOptions, ctx: SignatureContext)
262
277
  declare function normalizeE164(input: string, defaultCountry?: string): string;
263
278
 
264
279
  /**
265
- * `splitForSMS` — grapheme-cluster-safe multipart segmentation (D393, EC-7).
280
+ * `splitForSMS` — grapheme-cluster-safe multipart segmentation (D393, EC-7), keeping table rows
281
+ * whole.
266
282
  *
267
283
  * Concatenated SMS (UDH) on modern carriers reassemble at the recipient,
268
284
  * but each TCP/IP-layer chunk is one billed message. We segment at
@@ -270,11 +286,13 @@ declare function normalizeE164(input: string, defaultCountry?: string): string;
270
286
  * prefixed with `(i/N) ` to allow manual reordering when carriers
271
287
  * deliver out of sequence (EC-7).
272
288
  *
273
- * Thin wrapper over core `chunkByGrapheme` (roadmap M1) — single-sources the
274
- * `Intl.Segmenter` grapheme walk so emoji (🇧🇷) and combining sequences are
275
- * never severed. The `(i/N) ` prefix (and its reserved width) stays here since
276
- * it is SMS-specific. Output is byte-identical to the previous implementation
277
- * (pinned by `tests/split.test.ts`).
289
+ * A text within the limit goes through core `chunkByGrapheme` as before. A longer one is cut at
290
+ * the last grapheme boundary within each part, which is where `chunkByGrapheme`'s greedy walk
291
+ * ends a part, so emoji (🇧🇷) and combining sequences are never severed and text with no table
292
+ * row splits exactly as it did (pinned by `tests/split-no-table-baseline.test.ts` and the
293
+ * equivalence test in `tests/split-tables.test.ts`). A cut that falls inside a Markdown table row
294
+ * which fits in a part moves back to the start of that row (B-556). The rule is core
295
+ * `splitKeepingRows`, shared with gateway-line. The `(i/N) ` prefix (and its reserved width) stays here since it is SMS-specific.
278
296
  *
279
297
  * @internal
280
298
  */
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { GatewayConfigurationError, chunkByGrapheme, BasePlatformAdapter, rawBodyCapture, listenerLifecycle, loadPeer } from '@theokit/gateway';
1
+ import { GatewayConfigurationError, BasePlatformAdapter, rawBodyCapture, DEFAULT_WEBHOOK_MAX_BYTES, listenerLifecycle, chunkByGrapheme, splitKeepingRows, loadPeer } from '@theokit/gateway';
2
2
  import { parsePhoneNumberFromString } from 'libphonenumber-js';
3
3
 
4
4
  // src/adapter.ts
@@ -388,9 +388,23 @@ function inboundToMessageEvent(inbound, backend) {
388
388
  }
389
389
  };
390
390
  }
391
+
392
+ // src/refuse-attachments.ts
393
+ function refuseAttachments(out) {
394
+ if (out.attachments == null || out.attachments.length === 0) return void 0;
395
+ return {
396
+ ok: false,
397
+ error: { code: "attachments_unsupported", message: "sms adapter cannot send attachments" }
398
+ };
399
+ }
391
400
  function prefixWidthFor(total) {
392
401
  return 2 * String(total).length + 4;
393
402
  }
403
+ function partsFor(text, limit, partLimit) {
404
+ if (text.length <= limit) return chunkByGrapheme(text, { limit, partLimit });
405
+ chunkByGrapheme("", { limit, partLimit });
406
+ return splitKeepingRows(text, partLimit);
407
+ }
394
408
  function splitForSMS(text, limit = 1600) {
395
409
  let reserved = prefixWidthFor(1);
396
410
  for (let pass = 0; pass < 8; pass += 1) {
@@ -400,7 +414,7 @@ function splitForSMS(text, limit = 1600) {
400
414
  `limit ${limit} is too small to carry an SMS part: the "(i/N) " prefix alone needs ${reserved} chars`
401
415
  );
402
416
  }
403
- const parts = chunkByGrapheme(text, { limit, partLimit });
417
+ const parts = partsFor(text, limit, partLimit);
404
418
  if (parts.length <= 1) return parts;
405
419
  const needed = prefixWidthFor(parts.length);
406
420
  if (needed <= reserved) {
@@ -486,6 +500,9 @@ var SMSAdapter = class extends BasePlatformAdapter {
486
500
  this.inboundHandler = void 0;
487
501
  }
488
502
  async sendMessage(out) {
503
+ return refuseAttachments(out) ?? this.sendText(out);
504
+ }
505
+ async sendText(out) {
489
506
  if (out.text.length === 0) {
490
507
  return { ok: false, error: { code: "empty_text", message: "outbound text is empty" } };
491
508
  }
@@ -677,7 +694,11 @@ async function createWebhookServer(opts) {
677
694
  });
678
695
  res.status(204).end();
679
696
  };
680
- app.post(`${prefix}/${backend}`, rawBodyCapture("gateway-sms"), handler);
697
+ app.post(
698
+ `${prefix}/${backend}`,
699
+ rawBodyCapture("gateway-sms", { maxBytes: DEFAULT_WEBHOOK_MAX_BYTES }),
700
+ handler
701
+ );
681
702
  return listenerLifecycle({ app, port: opts.port ?? 3e3, injected: opts.app !== void 0 });
682
703
  }
683
704
 
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/phone.ts","../src/backend/plivo.ts","../src/backend/twilio.ts","../src/backend/vonage.ts","../src/backend/index.ts","../src/normalize.ts","../src/split.ts","../src/adapter.ts","../src/parse-inbound.ts","../src/webhook-server.ts","../src/webhook-verifier.ts"],"names":["parseFormUrlEncoded"],"mappings":";;;;AA8BO,IAAM,kBAAA,GAAN,cAAiC,yBAAA,CAA0B;AAAA,EAC9C,IAAA,GAAO,oBAAA;AAAA,EACzB,YAAY,IAAA,EAAiC;AAC3C,IAAA,KAAA,CAAM,eAAe,IAAI,CAAA;AAAA,EAC3B;AACF;AASO,IAAM,wBAAA,GAAN,cAAuC,kBAAA,CAAmB;AAAA,EAC/D,WAAA,CAAY,SAAwC,OAAA,EAAiB;AACnE,IAAA,KAAA,CAAM;AAAA,MACJ,IAAA,EAAM,uBAAA;AAAA,MACN,SAAS,CAAA,uBAAA,EAA0B,OAAO,CAAA,6BAAA,EAAgC,OAAO,iCAAiC,OAAO,CAAA,CAAA;AAAA,MACzH,MAAA,EAA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,GAAA,KAAQ,MAAA,EAAW,CAAA;AAC7F;;;ACnEA,SAAS,UAAU,OAAA,EAA0C;AAC3D,EAAA,MAAM,MAA8B,EAAC;AACrC,EAAA,OAAA,CAAQ,OAAA,CAAQ,OAAA,CAAQ,CAAC,KAAA,EAAO,GAAA,KAAQ;AACtC,IAAA,GAAA,CAAI,GAAG,CAAA,GAAI,KAAA;AAAA,EACb,CAAC,CAAA;AACD,EAAA,OAAO,GAAA;AACT;AAkBO,SAAS,kBAAA,CACd,OAAA,EACA,IAAA,GAAkC,EAAC,EACiB;AACpD,EAAA,OAAO,OAAO,OAAA,KAAmD;AAC/D,IAAA,MAAM,OAAA,GAAU,MAAM,OAAA,CAAQ,IAAA,EAAK;AACnC,IAAA,MAAM,GAAA,GAAwB;AAAA,MAC5B,OAAA,EAAS,UAAU,OAAO,CAAA;AAAA,MAC1B,OAAA;AAAA,MACA,GAAA,EAAK,IAAA,CAAK,SAAA,IAAa,OAAA,CAAQ,aAAa,OAAA,CAAQ;AAAA,KACtD;AACA,IAAA,OAAO,OAAA,CAAQ,eAAA,CAAgB,GAAG,CAAA,GAC9B,EAAE,EAAA,EAAI,IAAA,EAAK,GACX,EAAE,EAAA,EAAI,KAAA,EAAO,MAAA,EAAQ,oBAAA,EAAqB;AAAA,EAChD,CAAA;AACF","file":"index.js","sourcesContent":["/**\n * Typed errors for `@theokit/gateway-sms` (D389-D396).\n *\n * - `ConfigurationError` — programmer error at construction time\n * (missing signing secret, missing backend SDK install, malformed\n * phone number on outbound). Thrown synchronously.\n * - `BackendNotInstalledError` — peer-dep optional backend (twilio /\n * plivo / @vonage/server-sdk) was selected but the npm package is\n * not installed. Carries actionable install hint.\n *\n * `ConfigurationError` extends the shared core `GatewayConfigurationError`\n * base (roadmap M2); the SDK still consumes structured errors via\n * `metadata.code`. Behavior byte-identical (pinned by `tests/errors.test.ts`).\n *\n * @internal — re-exported by `src/index.ts`.\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;\n\n/**\n * Misconfiguration of this adapter, raised before any network call.\n *\n * Extends the shared core base so every gateway package reports configuration faults in one shape:\n * a structured `code` the caller can branch on, tagged with `\"gateway-sms\"` as the origin. A\n * missing credential or an unsupported option is a programmer error, not a transient failure —\n * these are never retried.\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-sms\", opts);\n }\n}\n\n/**\n * The provider SDK for the selected backend is not installed.\n *\n * `gateway-sms` speaks to Twilio, Plivo or Vonage, and declares all three as optional peers — a\n * project installs only the one it uses. Selecting a backend whose SDK is absent is caught here, at\n * connect time, with the package name and the command that installs it.\n */\nexport class BackendNotInstalledError extends ConfigurationError {\n constructor(backend: \"twilio\" | \"plivo\" | \"vonage\", pkgName: string) {\n super({\n code: \"backend_not_installed\",\n message: `gateway-sms: peer-dep \"${pkgName}\" not installed but backend=\"${backend}\" was selected. Run: pnpm add ${pkgName}`,\n detail: pkgName,\n });\n }\n}\n","/**\n * E.164 phone normalization (D391, EC-6).\n *\n * Wraps `libphonenumber-js` (full — accepts mobile + toll-free; the\n * `/mobile` sub-bundle was inadequate because it rejects toll-free\n * US 1-800 numbers).\n *\n * @internal\n */\n\nimport { parsePhoneNumberFromString } from \"libphonenumber-js\";\n\nimport { ConfigurationError } from \"./errors.js\";\n\n/**\n * Normalize a free-form phone number to canonical E.164 (`+5511999999999`).\n *\n * Accepts:\n * - International with `+`: `\"+5511999999999\"` → unchanged.\n * - National without `+` when `defaultCountry` is provided: `(\"11999999999\", \"BR\")` → `\"+5511999999999\"`.\n * - Toll-free US (EC-6): `\"+18001234567\"` → unchanged.\n *\n * Throws `ConfigurationError({ code: \"invalid_phone_number\" })` on any\n * input that cannot be parsed to a valid number.\n */\nexport function normalizeE164(input: string, defaultCountry?: string): string {\n if (input.length === 0) {\n throw new ConfigurationError({\n code: \"invalid_phone_number\",\n message: \"gateway-sms: phone number is empty\",\n detail: \"<empty>\",\n });\n }\n const parsed = parsePhoneNumberFromString(\n input,\n defaultCountry as Parameters<typeof parsePhoneNumberFromString>[1],\n );\n if (parsed === undefined || !parsed.isValid()) {\n throw new ConfigurationError({\n code: \"invalid_phone_number\",\n message: `gateway-sms: invalid phone number ${JSON.stringify(input)}`,\n detail: input,\n });\n }\n return parsed.format(\"E.164\");\n}\n","/**\n * Plivo backend impl.\n *\n * - SDK: `plivo` (peer-dep, optional).\n * - Signature: `X-Plivo-Signature-V3` is HMAC-SHA256 of the request URL\n * + nonce + body. `validateV3Signature` is exposed by the SDK; we\n * delegate to avoid reimplementation.\n *\n * @internal\n */\n\nimport type { SendResult } from \"@theokit/gateway\";\nimport type { SignatureContext, SMSBackend, SMSInbound } from \"../backend-types.js\";\nimport { BackendNotInstalledError } from \"../errors.js\";\nimport { normalizeE164 } from \"../phone.js\";\nimport type { PlivoOptions } from \"../types.js\";\n\ninterface PlivoCreateResponse {\n apiId?: string;\n messageUuid?: string[];\n message_uuid?: string[];\n}\n\ninterface PlivoClient {\n messages: {\n // The actual SDK uses positional args: create(src, dst, text, ...).\n create(src: string, dst: string, text: string): Promise<PlivoCreateResponse>;\n };\n}\n\ninterface PlivoModule {\n Client: new (authId?: string, authToken?: string) => PlivoClient;\n // Real SDK signature: validateV3Signature(method, uri, nonce, authToken, v3Signature)\n validateV3Signature?: (\n method: string,\n uri: string,\n nonce: string,\n authToken: string,\n signature: string,\n ) => boolean;\n}\n\nasync function loadPlivo(): Promise<PlivoModule> {\n try {\n // Plivo's published types are stricter (positional args) than our\n // generic mock; we narrow at call sites and pass through unknown.\n const mod = (await import(\"plivo\")) as unknown as PlivoModule;\n return mod;\n } catch {\n throw new BackendNotInstalledError(\"plivo\", \"plivo\");\n }\n}\n\nexport class PlivoBackend implements SMSBackend {\n readonly kind = \"plivo\" as const;\n private mod: PlivoModule | undefined;\n private client: PlivoClient | undefined;\n\n constructor(private readonly opts: PlivoOptions) {}\n\n async connect(): Promise<boolean> {\n if (this.client !== undefined) return true;\n this.mod = await loadPlivo();\n this.client = new this.mod.Client(this.opts.authId, this.opts.authToken);\n return true;\n }\n\n async disconnect(): Promise<void> {\n this.client = undefined;\n }\n\n verifySignature(ctx: SignatureContext): boolean {\n if (this.mod?.validateV3Signature === undefined) return false;\n const signature = ctx.headers[\"x-plivo-signature-v3\"];\n const nonce = ctx.headers[\"x-plivo-signature-v3-nonce\"];\n if (signature === undefined || nonce === undefined) return false;\n try {\n return this.mod.validateV3Signature(\"POST\", ctx.url, nonce, this.opts.authToken, signature);\n } catch {\n return false;\n }\n }\n\n parseInbound(ctx: SignatureContext): SMSInbound {\n let params: Record<string, string> = {};\n // Plivo posts JSON or form-encoded depending on application config.\n if ((ctx.headers[\"content-type\"] ?? \"\").includes(\"application/json\")) {\n try {\n params = JSON.parse(ctx.rawBody) as Record<string, string>;\n } catch {\n params = {};\n }\n } else {\n params = parseFormUrlEncoded(ctx.rawBody);\n }\n return {\n from: normalizeE164(params.From ?? \"\", this.opts.defaultCountry),\n to: normalizeE164(params.To ?? \"\", this.opts.defaultCountry),\n body: params.Text ?? params.text ?? \"\",\n messageId: params.MessageUUID ?? params.message_uuid ?? \"\",\n receivedAt: Date.now(),\n raw: params,\n };\n }\n\n async sendMessage(to: string, body: string): Promise<SendResult> {\n if (this.client === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"PlivoBackend.connect() not called\" },\n };\n }\n try {\n const resp = await this.client.messages.create(this.opts.fromNumber, to, body);\n const id = resp.messageUuid?.[0] ?? resp.message_uuid?.[0] ?? resp.apiId ?? \"\";\n return { ok: true, messageId: id };\n } catch (err) {\n return mapPlivoError(err);\n }\n }\n}\n\nfunction parseFormUrlEncoded(body: string): Record<string, string> {\n const params: Record<string, string> = {};\n for (const pair of body.split(\"&\")) {\n if (pair.length === 0) continue;\n const eqIdx = pair.indexOf(\"=\");\n const k = eqIdx < 0 ? pair : pair.slice(0, eqIdx);\n const v = eqIdx < 0 ? \"\" : pair.slice(eqIdx + 1);\n params[decodeURIComponent(k.replace(/\\+/g, \" \"))] = decodeURIComponent(v.replace(/\\+/g, \" \"));\n }\n return params;\n}\n\ninterface PlivoRestError {\n statusCode?: number;\n status?: number;\n message?: string;\n}\n\nfunction mapPlivoError(err: unknown): SendResult {\n const e = err as PlivoRestError;\n const status = e.statusCode ?? e.status ?? 0;\n if (status === 429)\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"Plivo rate limit\" } };\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"Plivo auth error\" },\n };\n }\n if (status === 400) {\n return {\n ok: false,\n error: { code: \"invalid_request\", message: e.message ?? \"Plivo rejected request\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\n}\n","/**\n * Twilio backend impl.\n *\n * - SDK: `twilio` (peer-dep, optional). Loaded lazily so packages\n * that pick other backends don't pay the cost.\n * - Signature: `X-Twilio-Signature` is HMAC-SHA1 of `(fullUrl + sortedParams)`.\n * We delegate to `twilio.validateRequest` so we don't reimplement.\n *\n * @internal\n */\n\nimport type { SendResult } from \"@theokit/gateway\";\nimport type { SignatureContext, SMSBackend, SMSInbound } from \"../backend-types.js\";\nimport { BackendNotInstalledError } from \"../errors.js\";\nimport { normalizeE164 } from \"../phone.js\";\nimport type { TwilioOptions } from \"../types.js\";\n\ninterface TwilioCreateArgs {\n from: string;\n to: string;\n body: string;\n}\n\ninterface TwilioMessageInstance {\n sid: string;\n status?: string;\n}\n\ninterface TwilioClientInstance {\n messages: {\n create(args: TwilioCreateArgs): Promise<TwilioMessageInstance>;\n };\n}\n\ninterface TwilioFactory {\n (accountSid: string, authToken: string): TwilioClientInstance;\n validateRequest(\n authToken: string,\n signature: string,\n url: string,\n params: Record<string, string>,\n ): boolean;\n}\n\nasync function loadTwilio(): Promise<TwilioFactory> {\n try {\n const mod = await import(\"twilio\");\n // ESM ships { default: factory }; CJS ships factory.\n const candidate =\n (mod as { default?: TwilioFactory }).default ?? (mod as unknown as TwilioFactory);\n return candidate;\n } catch {\n throw new BackendNotInstalledError(\"twilio\", \"twilio\");\n }\n}\n\nexport class TwilioBackend implements SMSBackend {\n readonly kind = \"twilio\" as const;\n private client: TwilioClientInstance | undefined;\n private twilio: TwilioFactory | undefined;\n\n constructor(private readonly opts: TwilioOptions) {}\n\n async connect(): Promise<boolean> {\n if (this.client !== undefined) return true;\n this.twilio = await loadTwilio();\n this.client = this.twilio(this.opts.accountSid, this.opts.authToken);\n return true;\n }\n\n async disconnect(): Promise<void> {\n // No persistent connection — REST client is GC'd on dereference.\n this.client = undefined;\n }\n\n verifySignature(ctx: SignatureContext): boolean {\n if (this.twilio === undefined) return false;\n const signature = ctx.headers[\"x-twilio-signature\"];\n if (signature === undefined) return false;\n const params = parseFormUrlEncoded(ctx.rawBody);\n try {\n return this.twilio.validateRequest(this.opts.authToken, signature, ctx.url, params);\n } catch {\n return false;\n }\n }\n\n parseInbound(ctx: SignatureContext): SMSInbound {\n const params = parseFormUrlEncoded(ctx.rawBody);\n return {\n from: normalizeE164(params.From ?? \"\", this.opts.defaultCountry),\n to: normalizeE164(params.To ?? \"\", this.opts.defaultCountry),\n body: params.Body ?? \"\",\n messageId: params.MessageSid ?? params.SmsMessageSid ?? \"\",\n receivedAt: Date.now(),\n raw: params,\n };\n }\n\n async sendMessage(to: string, body: string): Promise<SendResult> {\n if (this.client === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"TwilioBackend.connect() not called\" },\n };\n }\n try {\n const msg = await this.client.messages.create({ from: this.opts.fromNumber, to, body });\n return { ok: true, messageId: msg.sid };\n } catch (err) {\n return mapTwilioError(err);\n }\n }\n}\n\n/**\n * Parse `application/x-www-form-urlencoded` request body to a flat\n * `Record<string, string>`. Twilio POSTs in this format.\n *\n * @internal\n */\nfunction parseFormUrlEncoded(body: string): Record<string, string> {\n const params: Record<string, string> = {};\n for (const pair of body.split(\"&\")) {\n if (pair.length === 0) continue;\n const eqIdx = pair.indexOf(\"=\");\n const k = eqIdx < 0 ? pair : pair.slice(0, eqIdx);\n const v = eqIdx < 0 ? \"\" : pair.slice(eqIdx + 1);\n params[decodeURIComponent(k.replace(/\\+/g, \" \"))] = decodeURIComponent(v.replace(/\\+/g, \" \"));\n }\n return params;\n}\n\ninterface TwilioRestError {\n status?: number;\n code?: number | string;\n message?: string;\n}\n\nfunction mapTwilioError(err: unknown): SendResult {\n const e = err as TwilioRestError;\n const status = e.status ?? 0;\n if (status === 429) {\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"Twilio rate limit\" } };\n }\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"Twilio auth error\" },\n };\n }\n if (status === 400) {\n return {\n ok: false,\n error: { code: \"invalid_request\", message: e.message ?? \"Twilio rejected request\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\n}\n","/**\n * Vonage backend impl.\n *\n * - SDK: `@vonage/server-sdk` (peer-dep, optional).\n * - Signature: `Authorization: Bearer <JWT>` signed with the Signature\n * Secret (NOT the API secret). The SDK exposes `Auth.verifySignature`\n * for this purpose.\n *\n * @internal\n */\n\nimport type { SendResult } from \"@theokit/gateway\";\nimport type { SignatureContext, SMSBackend, SMSInbound } from \"../backend-types.js\";\nimport { BackendNotInstalledError } from \"../errors.js\";\nimport { normalizeE164 } from \"../phone.js\";\nimport type { VonageOptions } from \"../types.js\";\n\ninterface VonageSmsClient {\n send(args: { to: string; from: string; text: string }): Promise<{\n messages?: Array<{ \"message-id\"?: string; messageId?: string; status?: string }>;\n }>;\n}\n\ninterface VonageInstance {\n sms: VonageSmsClient;\n}\n\ninterface VonageModule {\n Vonage: new (creds: {\n apiKey: string;\n apiSecret: string;\n signatureSecret?: string;\n }) => VonageInstance;\n Auth?: {\n verifySignature?: (token: string, secret: string) => boolean;\n };\n}\n\nasync function loadVonage(): Promise<VonageModule> {\n try {\n // SDK ships ESM/CJS variants; we narrow at call sites and pass through.\n const raw = await import(\"@vonage/server-sdk\");\n return raw as unknown as VonageModule;\n } catch {\n throw new BackendNotInstalledError(\"vonage\", \"@vonage/server-sdk\");\n }\n}\n\nexport class VonageBackend implements SMSBackend {\n readonly kind = \"vonage\" as const;\n private mod: VonageModule | undefined;\n private vonage: VonageInstance | undefined;\n\n constructor(private readonly opts: VonageOptions) {}\n\n async connect(): Promise<boolean> {\n if (this.vonage !== undefined) return true;\n this.mod = await loadVonage();\n this.vonage = new this.mod.Vonage({\n apiKey: this.opts.apiKey,\n apiSecret: this.opts.apiSecret,\n signatureSecret: this.opts.signatureSecret,\n });\n return true;\n }\n\n async disconnect(): Promise<void> {\n this.vonage = undefined;\n }\n\n verifySignature(ctx: SignatureContext): boolean {\n const auth = ctx.headers.authorization;\n if (auth === undefined) return false;\n const m = auth.match(/^Bearer\\s+(.+)$/i);\n if (m === null) return false;\n const token = m[1] ?? \"\";\n if (token.length === 0) return false;\n if (this.mod?.Auth?.verifySignature === undefined) return false;\n try {\n return this.mod.Auth.verifySignature(token, this.opts.signatureSecret);\n } catch {\n return false;\n }\n }\n\n parseInbound(ctx: SignatureContext): SMSInbound {\n let payload: Record<string, string> = {};\n try {\n payload = JSON.parse(ctx.rawBody) as Record<string, string>;\n } catch {\n payload = {};\n }\n return {\n from: normalizeE164(payload.msisdn ?? payload.from ?? \"\", this.opts.defaultCountry),\n to: normalizeE164(payload.to ?? \"\", this.opts.defaultCountry),\n body: payload.text ?? \"\",\n messageId: payload.messageId ?? payload[\"message-id\"] ?? \"\",\n receivedAt: Date.now(),\n raw: payload,\n };\n }\n\n async sendMessage(to: string, body: string): Promise<SendResult> {\n if (this.vonage === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"VonageBackend.connect() not called\" },\n };\n }\n try {\n const resp = await this.vonage.sms.send({ from: this.opts.fromNumber, to, text: body });\n const msg = resp.messages?.[0];\n const id = msg?.[\"message-id\"] ?? msg?.messageId ?? \"\";\n if (msg?.status !== undefined && msg.status !== \"0\") {\n return {\n ok: false,\n error: { code: \"send_failed\", message: `Vonage returned status=${msg.status}` },\n };\n }\n return { ok: true, messageId: id };\n } catch (err) {\n return mapVonageError(err);\n }\n }\n}\n\ninterface VonageRestError {\n status?: number;\n response?: { status?: number };\n message?: string;\n}\n\nfunction mapVonageError(err: unknown): SendResult {\n const e = err as VonageRestError;\n const status = e.status ?? e.response?.status ?? 0;\n if (status === 429)\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"Vonage rate limit\" } };\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"Vonage auth error\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\n}\n","/**\n * Backend factory — picks the right impl from `opts.backend`.\n *\n * @internal\n */\n\nimport type { SMSBackend } from \"../backend-types.js\";\nimport type { SMSAdapterOptions } from \"../types.js\";\nimport { PlivoBackend } from \"./plivo.js\";\nimport { TwilioBackend } from \"./twilio.js\";\nimport { VonageBackend } from \"./vonage.js\";\n\nexport function createBackend(opts: SMSAdapterOptions): SMSBackend {\n switch (opts.backend) {\n case \"twilio\":\n return new TwilioBackend(opts);\n case \"plivo\":\n return new PlivoBackend(opts);\n case \"vonage\":\n return new VonageBackend(opts);\n default: {\n const _exhaustive: never = opts;\n throw new Error(`unknown backend: ${JSON.stringify(_exhaustive)}`);\n }\n }\n}\n","/**\n * Inbound normalization: `SMSInbound` → `SMSMessageEvent`.\n *\n * `from` and `to` are already E.164 (backend.parseInbound enforces this).\n * `channel.id` is `from` because SMS conversations are flat per-pair\n * (D394 — no threading).\n *\n * @internal\n */\n\nimport type { SMSMessageEvent } from \"@theokit/gateway\";\n\nimport type { SMSInbound } from \"./backend-types.js\";\n\nexport function inboundToMessageEvent(\n inbound: SMSInbound,\n backend: \"twilio\" | \"plivo\" | \"vonage\",\n): SMSMessageEvent {\n return {\n id: inbound.messageId,\n platform: \"sms\",\n sender: { id: inbound.from },\n channel: { id: inbound.from, type: \"dm\" },\n text: inbound.body,\n receivedAt: inbound.receivedAt,\n sms: {\n backend,\n messageId: inbound.messageId,\n from: inbound.from,\n to: inbound.to,\n raw: inbound.raw,\n },\n };\n}\n","/**\n * `splitForSMS` — grapheme-cluster-safe multipart segmentation (D393, EC-7).\n *\n * Concatenated SMS (UDH) on modern carriers reassemble at the recipient,\n * but each TCP/IP-layer chunk is one billed message. We segment at\n * 1600 chars (default) so the API call doesn't reject and each part is\n * prefixed with `(i/N) ` to allow manual reordering when carriers\n * deliver out of sequence (EC-7).\n *\n * Thin wrapper over core `chunkByGrapheme` (roadmap M1) — single-sources the\n * `Intl.Segmenter` grapheme walk so emoji (🇧🇷) and combining sequences are\n * never severed. The `(i/N) ` prefix (and its reserved width) stays here since\n * it is SMS-specific. Output is byte-identical to the previous implementation\n * (pinned by `tests/split.test.ts`).\n *\n * @internal\n */\n\nimport { chunkByGrapheme } from \"@theokit/gateway\";\n\n/**\n * Width of `\"(i/total) \"` when `i` has as many digits as `total` — the widest\n * the prefix can get for a given part count. `(99/99) ` is 8, `(100/126) ` is\n * 10, `(1000/1234) ` is 12.\n *\n * This used to be the constant 8, commented `\"(99/99) \" worst case`. It is the\n * worst case only below 100 parts; from the hundredth part on, every prefix\n * overflowed its reservation and each part exceeded the caller's declared cap\n * by 2 chars, which the provider rejects.\n */\nfunction prefixWidthFor(total: number): number {\n return 2 * String(total).length + 4;\n}\n\nexport function splitForSMS(text: string, limit = 1600): string[] {\n // Chicken and egg: the reservation depends on the part count, and the part\n // count depends on the reservation. Widening the prefix shrinks the payload,\n // which can push the count into another digit — so iterate to a fixed point.\n // It converges fast because the width grows with the LOGARITHM of the count;\n // the bound is a backstop against a pathological input, not the expected path.\n let reserved = prefixWidthFor(1);\n for (let pass = 0; pass < 8; pass += 1) {\n const partLimit = limit - reserved;\n if (partLimit <= 0) {\n throw new RangeError(\n `limit ${limit} is too small to carry an SMS part: the \"(i/N) \" prefix alone needs ${reserved} chars`,\n );\n }\n const parts = chunkByGrapheme(text, { limit, partLimit });\n if (parts.length <= 1) return parts; // short-circuit / single part: skip prefix\n const needed = prefixWidthFor(parts.length);\n if (needed <= reserved) {\n const total = parts.length;\n return parts.map((p, i) => `(${i + 1}/${total}) ${p}`);\n }\n reserved = needed;\n }\n /* c8 ignore next 3 -- unreachable: 8 passes cover part counts up to 10^8. */\n throw new RangeError(\n `could not settle the \"(i/N) \" prefix width for a ${text.length}-char message at limit ${limit}`,\n );\n}\n","/**\n * `SMSAdapter` — implements `BasePlatformAdapter` over a backend\n * (twilio / plivo / vonage). ADRs D389-D396.\n *\n * Lifecycle:\n * - `connect()` initializes the chosen backend (lazy peer-dep import).\n * - `disconnect()` releases the backend; idempotent.\n * - `sendMessage()` splits multipart (D393) and sends each part via backend.\n * - `onInbound(handler)` replaces previous handler (EC-H, mirror D276).\n *\n * Inbound dispatch is driven by the webhook server (`webhook-server.ts`)\n * which calls `adapter.dispatchInbound(ctx)` after signature verification.\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\nimport { createBackend } from \"./backend/index.js\";\nimport type { SignatureContext, SMSBackend } from \"./backend-types.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { inboundToMessageEvent } from \"./normalize.js\";\nimport { normalizeE164 } from \"./phone.js\";\nimport { splitForSMS } from \"./split.js\";\nimport type { SMSAdapterOptions } from \"./types.js\";\n\nexport class SMSAdapter extends BasePlatformAdapter {\n /**\n * Whether the \"this medium carries no formatting\" warning has already been emitted.\n *\n * Once per adapter, not once per message: a gateway answering a busy channel would turn a\n * useful diagnostic into a log flood, and a flooded log is one nobody reads — the same\n * reason the group-mention and allowlist drops elsewhere in this family log once.\n */\n private warnedAboutFormat = false;\n\n /**\n * Say, once, that a declared format is being dropped.\n *\n * `OutboundMessage.format` is the caller stating intent, and this medium has nowhere to put\n * it: no flag, no markup, no alternative part. Discarding it in silence is the swallowed-\n * error shape `rules/error-handling.md` refuses — nothing fails, and the caller learns their\n * formatting never arrived from a user, weeks later.\n *\n * @internal\n */\n private warnFormatUnsupported(format: string | undefined): void {\n // The \"is there anything to say\" question lives here rather than at the call site: a\n // `sendMessage` already at its complexity limit should ask one thing, not three.\n if (format === undefined || format === \"plain\") return;\n if (this.warnedAboutFormat) return;\n this.warnedAboutFormat = true;\n process.stderr.write(\n `[gateway-sms] format=\"${format}\" was declared, and SMS cannot carry it — ` +\n \"the medium is plain text. Sending unformatted; this is logged once.\\n\",\n );\n }\n\n readonly platform = \"sms\" as const;\n\n /**\n * The URL the provider POSTs inbound to, as the provider sees it.\n *\n * Required by all three backend option shapes and documented there as \"used by signature\n * verifier\" — and, measured 2026-08-31, read by nothing: it appeared only in the type and in test\n * fixtures. Twilio SIGNS this URL, so the value matters most in exactly the case where the\n * request cannot supply it: behind a proxy or a tunnel, the request's own URL is the internal one\n * and will not match what was signed.\n *\n * Exposed so {@link smsWebhookVerifier} can use it, which is what makes the option true.\n */\n readonly publicUrl: string;\n\n private readonly backend: SMSBackend;\n private inboundHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private connected = false;\n private readonly defaultCountry: string | undefined;\n\n constructor(opts: SMSAdapterOptions) {\n super();\n // EC-1: refuse to operate without signing secret.\n const secret = secretFromOpts(opts);\n if (secret.length === 0) {\n throw new ConfigurationError({\n code: \"signing_secret_required\",\n message: `gateway-sms: backend=\"${opts.backend}\" requires a signing secret (would accept unsigned webhooks)`,\n });\n }\n this.defaultCountry = opts.defaultCountry;\n this.publicUrl = opts.publicUrl;\n this.backend = createBackend(opts);\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n const ok = await this.backend.connect();\n this.connected = ok;\n return ok;\n }\n\n async disconnect(): Promise<void> {\n if (!this.connected) return;\n await this.backend.disconnect();\n this.connected = false;\n this.inboundHandler = undefined;\n }\n\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"outbound text is empty\" } };\n }\n let toE164: string;\n try {\n toE164 = normalizeE164(out.channel.id, this.defaultCountry);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return { ok: false, error: { code: \"invalid_phone_number\", message: msg } };\n }\n const parts = splitForSMS(out.text);\n // Send sequentially so the recipient sees them in order; concurrent\n // submit would still cost the same but breaks ordering at carriers.\n let lastResult: SendResult | undefined;\n // SMS is plain text by definition. Reading the field is not ceremony: it is what turns a\n // silent discard into a stated one.\n this.warnFormatUnsupported(out.format);\n\n for (const part of parts) {\n lastResult = await this.backend.sendMessage(toE164, part);\n if (lastResult.ok !== true) {\n return {\n ok: false,\n error: {\n code: lastResult.error?.code ?? \"partial_send_failure\",\n message: `partial send failed after ${parts.indexOf(part)}/${parts.length}: ${lastResult.error?.message ?? \"unknown\"}`,\n },\n };\n }\n }\n return lastResult ?? { ok: false, error: { code: \"send_failed\", message: \"no parts sent\" } };\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace, not stack.\n this.inboundHandler = handler;\n return () => {\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n /**\n * Webhook hook — called by `createWebhookServer` AFTER signature\n * verification + parseInbound. Returns dispatch outcome (used for\n * 200/204 vs 500 by the webhook handler).\n *\n * @internal\n */\n async dispatchInbound(ctx: SignatureContext): Promise<\"ok\" | \"no_handler\" | \"parse_failed\"> {\n if (!this.backend.verifySignature(ctx)) {\n // Caller (webhook-server) inspects this via verifySignature directly,\n // but we re-check defensively if anyone calls dispatch directly.\n return \"parse_failed\";\n }\n let inbound: ReturnType<SMSBackend[\"parseInbound\"]>;\n try {\n inbound = this.backend.parseInbound(ctx);\n } catch {\n return \"parse_failed\";\n }\n if (this.inboundHandler === undefined) return \"no_handler\";\n const event = inboundToMessageEvent(inbound, this.backend.kind);\n try {\n await this.inboundHandler(event);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-sms] handler threw: ${msg}\\n`);\n }\n return \"ok\";\n }\n\n /**\n * Direct signature check — used by the webhook server to respond\n * `401` BEFORE dispatch when signature is invalid.\n *\n * @internal\n */\n verifySignature(ctx: SignatureContext): boolean {\n return this.backend.verifySignature(ctx);\n }\n\n /**\n * Direct parse — used by the webhook server when signature was already\n * validated upstream. Returns the normalized `SMSMessageEvent` to be\n * dispatched.\n *\n * @internal\n */\n buildEventFromCtx(ctx: SignatureContext): GatewayMessageEvent {\n const inbound = this.backend.parseInbound(ctx);\n return inboundToMessageEvent(inbound, this.backend.kind);\n }\n\n /**\n * Dispatch a pre-built event (used by webhook server after manual\n * signature + parse). Honors EC-H replace semantics and isolates\n * handler exceptions per `gateway-runner` contract.\n *\n * @internal\n */\n async dispatchEvent(event: GatewayMessageEvent): Promise<\"ok\" | \"no_handler\"> {\n if (this.inboundHandler === undefined) return \"no_handler\";\n try {\n await this.inboundHandler(event);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-sms] handler threw: ${msg}\\n`);\n }\n return \"ok\";\n }\n\n /** Backend kind (escape hatch for callers needing to introspect). */\n getBackendKind(): \"twilio\" | \"plivo\" | \"vonage\" {\n return this.backend.kind;\n }\n\n /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.runHandler(this.inboundHandler, event);\n }\n}\n\nfunction secretFromOpts(opts: SMSAdapterOptions): string {\n switch (opts.backend) {\n case \"twilio\":\n return opts.authToken;\n case \"plivo\":\n return opts.authToken;\n case \"vonage\":\n return opts.signatureSecret;\n default: {\n const _exhaustive: never = opts;\n void _exhaustive;\n return \"\";\n }\n }\n}\n","/**\n * Translating a raw provider webhook into the canonical event.\n *\n * **This does NOT go through TheoKit's `handleChannelWebhook`.** Signature verification here needs\n * the RAW body, the headers and the exact URL — `ChannelMessage` carries none of the three, so the\n * check cannot be performed from inside `onMessage` whatever the provider sends. Twilio adds a\n * second obstacle: it posts `application/x-www-form-urlencoded`, and that seam reads the body with\n * `request.json()` and answers 400 when it is not JSON. (Plivo accepts either encoding and Vonage\n * posts JSON, so only the first reason applies to them.)\n *\n * For an Express app, `createWebhookServer` is the whole path and you never call this — it builds\n * the {@link SignatureContext}, verifies the signature and goes through the adapter. This export is\n * for a route you host yourself: build the context from a request whose body you have not parsed,\n * then call this. It composes two functions that\n * already existed and were both private: each backend's `parseInbound`, which turns a provider's\n * raw body into the provider-agnostic {@link SMSInbound}, and `inboundToMessageEvent`, which turns\n * that into the canonical event. Neither is duplicated here — per ADR D426 the mapping stays in one\n * place, and this is composition, not a second translator.\n *\n * **Why it takes the adapter's options.** Parsing is provider-specific (`Twilio` posts\n * `MessageSid`, Plivo posts `MessageUUID`) and, for Twilio, country-dependent: a number that is not\n * already in E.164 is normalised against `defaultCountry`. Both live in the options an app already\n * holds, because it constructed the adapter with them. `createBackend` only stores them — it opens\n * no connection and loads no SDK, so this stays a pure function over its inputs.\n */\n\nimport type { SMSMessageEvent } from \"@theokit/gateway\";\n\nimport { createBackend } from \"./backend/index.js\";\nimport type { SignatureContext, SMSInbound } from \"./backend-types.js\";\nimport { inboundToMessageEvent } from \"./normalize.js\";\nimport type { SMSAdapterOptions } from \"./types.js\";\n\n/**\n * Translate one raw provider webhook into an {@link SMSMessageEvent}.\n *\n * Returns `null` — never throws — when the body is not one this provider recognises. The caller is\n * whatever holds the {@link SignatureContext}: `createWebhookServer` here, or your own route. It\n * returns `null` rather than throwing because a throw out of a webhook handler becomes a failed\n * request, and the provider then sees a delivery failure for a body that was merely unrecognised\n * (ADR D428, whose original rationale — \"runs after the 200\" — was measured false on 2026-08-24).\n *\n * `null` here means \"this body is not a parseable inbound message\".\n *\n * **One class of configuration error is not distinguishable from a bad body, and is not pretended\n * to be.** `defaultCountry` is read while parsing the body's own numbers, and `normalizeE164`\n * raises the same `ConfigurationError` for a bad configured country as for a bad number in the\n * body. An invalid `defaultCountry` therefore degrades to `null` rather than throwing.\n *\n * An earlier version tried to separate them by validating `options.fromNumber` up front. That was\n * wrong twice: `fromNumber` is passed raw to the provider SDK everywhere else in this package and\n * validated nowhere, and the invented rule rejected four documented, valid configurations — a\n * Vonage alphanumeric sender ID (`\"ACME\"`), a Twilio short code (`\"12345\"`), a Messaging Service\n * SID (`\"MG…\"`), and a national number with `defaultCountry` set. Each one threw out of\n * `onMessage`, turning a message the provider delivered into a failed request — precisely the\n * failure the check was written to prevent.\n * Inventing a validation stricter than the package's own is how that happened.\n *\n * @public\n */\nexport function parseInbound(\n options: SMSAdapterOptions,\n ctx: SignatureContext,\n): SMSMessageEvent | null {\n // `createBackend` is the CONFIGURATION step and sits outside the try on purpose: an unsupported\n // `backend` is a programmer error and must surface, not become the same `null` a malformed body\n // produces.\n const backend = createBackend(options);\n\n let inbound: SMSInbound;\n try {\n inbound = backend.parseInbound(ctx);\n } catch {\n // Everything from here is body-dependent, so any error means the body was unreadable. Caught\n // whatever its type: `decodeURIComponent` raises `URIError` on a malformed percent-escape\n // (`From=%zz`) and `normalizeE164` raises `ConfigurationError` on a number the body carried.\n // Both are bad requests, and returning `null` is what keeps them from failing the request:\n // measured against `theokit@0.48.14`, `handleChannelWebhook` awaits `onMessage` BEFORE\n // building the 200 and catches nothing around it, so a throw here escapes it entirely and\n // the 200 is never built (ADR D428, whose original rationale — \"runs after the 200\" — was\n // measured false on 2026-08-24).\n return null;\n }\n\n // A body the provider posted that carries no message id.\n //\n // Deliberately does NOT also check `inbound.from === \"\"`: all three backends build `from` with\n // `normalizeE164(x ?? \"\")`, which throws on an empty string, so the branch was unreachable and a\n // mutation deleting it survived the suite.\n if (inbound.messageId === \"\") return null;\n\n return inboundToMessageEvent(inbound, options.backend);\n}\n","/**\n * `createWebhookServer` — Express helper for inbound SMS webhooks.\n *\n * Registers per-backend routes (`/sms/twilio`, `/sms/plivo`, `/sms/vonage`)\n * each with the matching parser middleware. All three:\n *\n * 1. Read the raw body verbatim (signature verification depends on the\n * exact bytes — even one extra `\\r\\n` invalidates the HMAC).\n * 2. Call `adapter.verifySignature(ctx)` → 401 if false.\n * 3. Call `adapter.buildEventFromCtx(ctx)` → `dispatchEvent(event)`.\n * 4. Return 204 No Content.\n *\n * Caller can pass an existing Express app (`opts.app`) or let the helper\n * create one. `start()` / `stop()` are idempotent.\n *\n * @public\n */\n\nimport { listenerLifecycle, loadPeer, rawBodyCapture } from \"@theokit/gateway\";\nimport type { Express, Request, Response } from \"express\";\nimport type { SMSAdapter } from \"./adapter.js\";\nimport type { SignatureContext } from \"./backend-types.js\";\n\nimport { ConfigurationError } from \"./errors.js\";\n\nexport interface WebhookServerOptions {\n readonly adapter: SMSAdapter;\n /** Mount path prefix; default `\"/sms\"`. The full path is `${path}/${backend}`. */\n readonly path?: string;\n /** Listen port. Ignored when `app` is provided. Default `3000`. */\n readonly port?: number;\n /** Inject an existing Express app instead of creating one. */\n readonly app?: Express;\n}\n\n/** A started HTTP listener, with the handle needed to shut it down again. */\nexport interface WebhookServer {\n start(): Promise<void>;\n stop(): Promise<void>;\n}\n\nasync function loadExpress(): Promise<() => Express> {\n return loadPeer<() => Express>(\n async () => import(\"express\"),\n () => {\n throw new ConfigurationError({\n code: \"express_not_installed\",\n message: 'gateway-sms: peer-dep \"express\" not installed. Run: pnpm add express',\n });\n },\n );\n}\n\n/**\n * The URL the provider signed.\n *\n * `publicUrl` wins when it is configured, because it is the only value that survives a proxy. The\n * provider verifies against the address IT posted to, and behind a tunnel, an ingress, or a load\n * balancer terminating TLS the reconstruction below yields the internal one — so a correct\n * signature fails, on every delivery, with nothing in the log naming the cause.\n *\n * The header reconstruction stays as the fallback: an app served directly has nothing to configure\n * and the headers are the truth. Measured 2026-08-31 — `publicUrl` is required by all three backend\n * option shapes and documented as \"used by signature verifier\", and until this commit no source\n * file read it.\n */\nfunction signedUrl(\n req: Request,\n headers: Readonly<Record<string, string>>,\n publicUrl?: string,\n): string {\n if (publicUrl !== undefined && publicUrl !== \"\") return publicUrl;\n const protoHeader = headers[\"x-forwarded-proto\"];\n const proto = protoHeader ?? (req.secure ? \"https\" : \"http\");\n const host = req.get(\"host\") ?? \"localhost\";\n return `${proto}://${host}${req.originalUrl}`;\n}\n\nfunction buildSignatureContext(req: Request, publicUrl?: string): SignatureContext {\n const rawBody = (req as Request & { rawBody?: string }).rawBody ?? \"\";\n const headers: Record<string, string> = {};\n for (const [k, v] of Object.entries(req.headers)) {\n headers[k.toLowerCase()] = Array.isArray(v) ? v.join(\",\") : (v ?? \"\");\n }\n return { headers, rawBody, url: signedUrl(req, headers, publicUrl) };\n}\n\n/**\n * Build the HTTP listener that receives the provider's inbound-SMS callbacks.\n *\n * The provider dials in, so this endpoint must be reachable over public HTTPS and registered in the\n * provider console — inbound cannot work behind a firewall. `express` is loaded lazily, so a project\n * that only sends messages never pays for it.\n */\nexport async function createWebhookServer(opts: WebhookServerOptions): Promise<WebhookServer> {\n const createApp = await loadExpress();\n const app: Express = opts.app ?? createApp();\n const prefix = opts.path ?? \"/sms\";\n const backend = opts.adapter.getBackendKind();\n\n const handler = (req: Request, res: Response): void => {\n const ctx = buildSignatureContext(req, opts.adapter.publicUrl);\n if (!opts.adapter.verifySignature(ctx)) {\n res.status(401).type(\"text/plain\").send(\"invalid signature\");\n return;\n }\n let event: ReturnType<typeof opts.adapter.buildEventFromCtx>;\n try {\n event = opts.adapter.buildEventFromCtx(ctx);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n res.status(400).type(\"text/plain\").send(`parse failed: ${msg}`);\n return;\n }\n // Same contract as the LINE server: the provider is answered before the handler runs, so a\n // slow handler cannot become a provider retry. That makes the dispatch floated, and a floated\n // rejection ends the process — so it is caught here rather than left to the runtime (#41).\n void opts.adapter.dispatchEvent(event).catch((err: unknown) => {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-sms] webhook dispatch failed: ${message}\\n`);\n });\n // Twilio expects either TwiML or 204; 204 keeps things simple\n // and avoids accidentally double-replying.\n res.status(204).end();\n };\n\n app.post(`${prefix}/${backend}`, rawBodyCapture(\"gateway-sms\"), handler);\n\n // The lifecycle lives in `@theokit/gateway`, written once. It was duplicated here and in\n // gateway-line, and the same write-once latch bug had to be fixed in both files by one commit —\n // which is what turned the duplication from a style question into a defect (#89).\n return listenerLifecycle({ app, port: opts.port ?? 3000, injected: opts.app !== undefined });\n}\n","/**\n * The SMS half of a channel webhook, in the shape a framework webhook seam expects.\n *\n * `theokit/server/webhook` ships validators for the platforms whose signature is a plain HMAC it\n * can compute itself. SMS is not one of them: Twilio signs the URL plus the sorted POST parameters,\n * Plivo signs a different string again, and Vonage uses a JWT. Those three schemes already exist in\n * this package, correctly, with their own tests — reimplementing them one repository over would put\n * security-critical code in two places and guarantee they drift.\n *\n * So the direction is inverted. The framework declares the SHAPE; the package that owns the\n * platform provides the implementation. The shape is structural, so nothing here imports the\n * framework and this package gains no dependency:\n *\n * ```ts\n * await handleChannelWebhook(request, pathname, {\n * validators: { sms: smsWebhookVerifier(adapter) },\n * })\n * ```\n *\n * @public\n */\n\nimport type { SMSAdapter } from \"./adapter.js\";\nimport type { SignatureContext } from \"./backend-types.js\";\n\n/**\n * What a verifier answers. Structurally identical to the framework's `VerifyResult`, declared here\n * so this package does not depend on the framework to describe its own return value.\n *\n * @public\n */\nexport type WebhookVerifyResult =\n | { readonly ok: true }\n | { readonly ok: false; readonly reason: string };\n\n/** Options for {@link smsWebhookVerifier}. @public */\nexport interface SMSWebhookVerifierOptions {\n /**\n * The URL the provider POSTs to, as the provider sees it.\n *\n * Twilio signs the URL, so verification compares against whatever string is passed here — and\n * behind a proxy or a tunnel the request's own URL is the INTERNAL one, which will not match.\n * Defaults to the adapter's configured `publicUrl` when it has one, and to the request URL\n * otherwise.\n */\n readonly publicUrl?: string;\n}\n\n/**\n * The subset of the adapter this verifier reads. Stated as an interface so the parameter is honest\n * about its requirements, and so a test can supply the two members without a live provider SDK.\n */\ninterface VerifiableAdapter {\n verifySignature(ctx: SignatureContext): boolean;\n readonly publicUrl?: string;\n}\n\n/**\n * The lowercased header map {@link SignatureContext} promises its consumers.\n *\n * No `toLowerCase()` here, and that is the point rather than an omission: the Fetch `Headers` object\n * normalises names on the way in, so iterating it already yields `x-twilio-signature` however the\n * sender wrote it. Lowercasing again was in the first version and mutation testing showed it dead —\n * removing it changed no test, because the platform had already done the work.\n */\nfunction headersOf(request: Request): Record<string, string> {\n const out: Record<string, string> = {};\n request.headers.forEach((value, key) => {\n out[key] = value;\n });\n return out;\n}\n\n/**\n * Build a verifier for one configured SMS adapter.\n *\n * The request is READ, so pass a clone if the body is needed afterwards — a framework seam that\n * hands validators a `clone()` already does this. Reading it raw is not optional: every provider\n * signs the exact bytes, and a body that was parsed and re-serialised hashes differently.\n *\n * **Connect the adapter first.** Each backend loads its provider SDK during `connect()`, and until\n * it has, `verifySignature` answers `false` for everything — so a verifier wired before connect\n * refuses every genuine delivery as a bad signature. The two are NOT distinguishable here: the\n * backend contract returns a boolean, and inventing a reason this function cannot actually observe\n * would be worse than the ambiguity. The behaviour is pinned by a test rather than papered over,\n * and telling them apart needs a readiness signal the adapter does not expose today.\n *\n * @public\n */\nexport function smsWebhookVerifier(\n adapter: SMSAdapter | VerifiableAdapter,\n opts: SMSWebhookVerifierOptions = {},\n): (request: Request) => Promise<WebhookVerifyResult> {\n return async (request: Request): Promise<WebhookVerifyResult> => {\n const rawBody = await request.text();\n const ctx: SignatureContext = {\n headers: headersOf(request),\n rawBody,\n url: opts.publicUrl ?? adapter.publicUrl ?? request.url,\n };\n return adapter.verifySignature(ctx)\n ? { ok: true }\n : { ok: false, reason: \"signature mismatch\" };\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/phone.ts","../src/backend/plivo.ts","../src/backend/twilio.ts","../src/backend/vonage.ts","../src/backend/index.ts","../src/normalize.ts","../src/refuse-attachments.ts","../src/split.ts","../src/adapter.ts","../src/parse-inbound.ts","../src/webhook-server.ts","../src/webhook-verifier.ts"],"names":["parseFormUrlEncoded"],"mappings":";;;;AA8BO,IAAM,kBAAA,GAAN,cAAiC,yBAAA,CAA0B;AAAA,EAC9C,IAAA,GAAO,oBAAA;AAAA,EACzB,YAAY,IAAA,EAAiC;AAC3C,IAAA,KAAA,CAAM,eAAe,IAAI,CAAA;AAAA,EAC3B;AACF;AASO,IAAM,wBAAA,GAAN,cAAuC,kBAAA,CAAmB;AAAA,EAC/D,WAAA,CAAY,SAAwC,OAAA,EAAiB;AACnE,IAAA,KAAA,CAAM;AAAA,MACJ,IAAA,EAAM,uBAAA;AAAA,MACN,SAAS,CAAA,uBAAA,EAA0B,OAAO,CAAA,6BAAA,EAAgC,OAAO,iCAAiC,OAAO,CAAA,CAAA;AAAA,MACzH,MAAA,EAAQ;AAAA,KACT,CAAA;AAAA,EACH;AACF;AC3BO,SAAS,aAAA,CAAc,OAAe,cAAA,EAAiC;AAC5E,EAAA,IAAI,KAAA,CAAM,WAAW,CAAA,EAAG;AACtB,IAAA,MAAM,IAAI,kBAAA,CAAmB;AAAA,MAC3B,IAAA,EAAM,sBAAA;AAAA,MACN,OAAA,EAAS,oCAAA;AAAA,MACT,MAAA,EAAQ;AAAA,KACT,CAAA;AAAA,EACH;AACA,EAAA,MAAM,MAAA,GAAS,0BAAA;AAAA,IACb,KAAA;AAAA,IACA;AAAA,GACF;AACA,EAAA,IAAI,MAAA,KAAW,MAAA,IAAa,CAAC,MAAA,CAAO,SAAQ,EAAG;AAC7C,IAAA,MAAM,IAAI,kBAAA,CAAmB;AAAA,MAC3B,IAAA,EAAM,s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EAAG,MAAM,CAAA,CAAA,EAAI,OAAO,CAAA,CAAA;AAAA,IACpB,cAAA,CAAe,aAAA,EAAe,EAAE,QAAA,EAAU,2BAA2B,CAAA;AAAA,IACrE;AAAA,GACF;AAKA,EAAA,OAAO,iBAAA,CAAkB,EAAE,GAAA,EAAK,IAAA,EAAM,IAAA,CAAK,IAAA,IAAQ,GAAA,EAAM,QAAA,EAAU,IAAA,CAAK,GAAA,KAAQ,MAAA,EAAW,CAAA;AAC7F;;;AC5EA,SAAS,UAAU,OAAA,EAA0C;AAC3D,EAAA,MAAM,MAA8B,EAAC;AACrC,EAAA,OAAA,CAAQ,OAAA,CAAQ,OAAA,CAAQ,CAAC,KAAA,EAAO,GAAA,KAAQ;AACtC,IAAA,GAAA,CAAI,GAAG,CAAA,GAAI,KAAA;AAAA,EACb,CAAC,CAAA;AACD,EAAA,OAAO,GAAA;AACT;AAkBO,SAAS,kBAAA,CACd,OAAA,EACA,IAAA,GAAkC,EAAC,EACiB;AACpD,EAAA,OAAO,OAAO,OAAA,KAAmD;AAC/D,IAAA,MAAM,OAAA,GAAU,MAAM,OAAA,CAAQ,IAAA,EAAK;AACnC,IAAA,MAAM,GAAA,GAAwB;AAAA,MAC5B,OAAA,EAAS,UAAU,OAAO,CAAA;AAAA,MAC1B,OAAA;AAAA,MACA,GAAA,EAAK,IAAA,CAAK,SAAA,IAAa,OAAA,CAAQ,aAAa,OAAA,CAAQ;AAAA,KACtD;AACA,IAAA,OAAO,OAAA,CAAQ,eAAA,CAAgB,GAAG,CAAA,GAC9B,EAAE,EAAA,EAAI,IAAA,EAAK,GACX,EAAE,EAAA,EAAI,KAAA,EAAO,MAAA,EAAQ,oBAAA,EAAqB;AAAA,EAChD,CAAA;AACF","file":"index.js","sourcesContent":["/**\n * Typed errors for `@theokit/gateway-sms` (D389-D396).\n *\n * - `ConfigurationError` — programmer error at construction time\n * (missing signing secret, missing backend SDK install, malformed\n * phone number on outbound). Thrown synchronously.\n * - `BackendNotInstalledError` — peer-dep optional backend (twilio /\n * plivo / @vonage/server-sdk) was selected but the npm package is\n * not installed. Carries actionable install hint.\n *\n * `ConfigurationError` extends the shared core `GatewayConfigurationError`\n * base (roadmap M2); the SDK still consumes structured errors via\n * `metadata.code`. Behavior byte-identical (pinned by `tests/errors.test.ts`).\n *\n * @internal — re-exported by `src/index.ts`.\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;\n\n/**\n * Misconfiguration of this adapter, raised before any network call.\n *\n * Extends the shared core base so every gateway package reports configuration faults in one shape:\n * a structured `code` the caller can branch on, tagged with `\"gateway-sms\"` as the origin. A\n * missing credential or an unsupported option is a programmer error, not a transient failure —\n * these are never retried.\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-sms\", opts);\n }\n}\n\n/**\n * The provider SDK for the selected backend is not installed.\n *\n * `gateway-sms` speaks to Twilio, Plivo or Vonage, and declares all three as optional peers — a\n * project installs only the one it uses. Selecting a backend whose SDK is absent is caught here, at\n * connect time, with the package name and the command that installs it.\n */\nexport class BackendNotInstalledError extends ConfigurationError {\n constructor(backend: \"twilio\" | \"plivo\" | \"vonage\", pkgName: string) {\n super({\n code: \"backend_not_installed\",\n message: `gateway-sms: peer-dep \"${pkgName}\" not installed but backend=\"${backend}\" was selected. Run: pnpm add ${pkgName}`,\n detail: pkgName,\n });\n }\n}\n","/**\n * E.164 phone normalization (D391, EC-6).\n *\n * Wraps `libphonenumber-js` (full — accepts mobile + toll-free; the\n * `/mobile` sub-bundle was inadequate because it rejects toll-free\n * US 1-800 numbers).\n *\n * @internal\n */\n\nimport { parsePhoneNumberFromString } from \"libphonenumber-js\";\n\nimport { ConfigurationError } from \"./errors.js\";\n\n/**\n * Normalize a free-form phone number to canonical E.164 (`+5511999999999`).\n *\n * Accepts:\n * - International with `+`: `\"+5511999999999\"` → unchanged.\n * - National without `+` when `defaultCountry` is provided: `(\"11999999999\", \"BR\")` → `\"+5511999999999\"`.\n * - Toll-free US (EC-6): `\"+18001234567\"` → unchanged.\n *\n * Throws `ConfigurationError({ code: \"invalid_phone_number\" })` on any\n * input that cannot be parsed to a valid number.\n */\nexport function normalizeE164(input: string, defaultCountry?: string): string {\n if (input.length === 0) {\n throw new ConfigurationError({\n code: \"invalid_phone_number\",\n message: \"gateway-sms: phone number is empty\",\n detail: \"<empty>\",\n });\n }\n const parsed = parsePhoneNumberFromString(\n input,\n defaultCountry as Parameters<typeof parsePhoneNumberFromString>[1],\n );\n if (parsed === undefined || !parsed.isValid()) {\n throw new ConfigurationError({\n code: \"invalid_phone_number\",\n message: `gateway-sms: invalid phone number ${JSON.stringify(input)}`,\n detail: input,\n });\n }\n return parsed.format(\"E.164\");\n}\n","/**\n * Plivo backend impl.\n *\n * - SDK: `plivo` (peer-dep, optional).\n * - Signature: `X-Plivo-Signature-V3` is HMAC-SHA256 of the request URL\n * + nonce + body. `validateV3Signature` is exposed by the SDK; we\n * delegate to avoid reimplementation.\n *\n * @internal\n */\n\nimport type { SendResult } from \"@theokit/gateway\";\nimport type { SignatureContext, SMSBackend, SMSInbound } from \"../backend-types.js\";\nimport { BackendNotInstalledError } from \"../errors.js\";\nimport { normalizeE164 } from \"../phone.js\";\nimport type { PlivoOptions } from \"../types.js\";\n\ninterface PlivoCreateResponse {\n apiId?: string;\n messageUuid?: string[];\n message_uuid?: string[];\n}\n\ninterface PlivoClient {\n messages: {\n // The actual SDK uses positional args: create(src, dst, text, ...).\n create(src: string, dst: string, text: string): Promise<PlivoCreateResponse>;\n };\n}\n\ninterface PlivoModule {\n Client: new (authId?: string, authToken?: string) => PlivoClient;\n // Real SDK signature: validateV3Signature(method, uri, nonce, authToken, v3Signature)\n validateV3Signature?: (\n method: string,\n uri: string,\n nonce: string,\n authToken: string,\n signature: string,\n ) => boolean;\n}\n\nasync function loadPlivo(): Promise<PlivoModule> {\n try {\n // Plivo's published types are stricter (positional args) than our\n // generic mock; we narrow at call sites and pass through unknown.\n const mod = (await import(\"plivo\")) as unknown as PlivoModule;\n return mod;\n } catch {\n throw new BackendNotInstalledError(\"plivo\", \"plivo\");\n }\n}\n\nexport class PlivoBackend implements SMSBackend {\n readonly kind = \"plivo\" as const;\n private mod: PlivoModule | undefined;\n private client: PlivoClient | undefined;\n\n constructor(private readonly opts: PlivoOptions) {}\n\n async connect(): Promise<boolean> {\n if (this.client !== undefined) return true;\n this.mod = await loadPlivo();\n this.client = new this.mod.Client(this.opts.authId, this.opts.authToken);\n return true;\n }\n\n async disconnect(): Promise<void> {\n this.client = undefined;\n }\n\n verifySignature(ctx: SignatureContext): boolean {\n if (this.mod?.validateV3Signature === undefined) return false;\n const signature = ctx.headers[\"x-plivo-signature-v3\"];\n const nonce = ctx.headers[\"x-plivo-signature-v3-nonce\"];\n if (signature === undefined || nonce === undefined) return false;\n try {\n return this.mod.validateV3Signature(\"POST\", ctx.url, nonce, this.opts.authToken, signature);\n } catch {\n return false;\n }\n }\n\n parseInbound(ctx: SignatureContext): SMSInbound {\n let params: Record<string, string> = {};\n // Plivo posts JSON or form-encoded depending on application config.\n if ((ctx.headers[\"content-type\"] ?? \"\").includes(\"application/json\")) {\n try {\n params = JSON.parse(ctx.rawBody) as Record<string, string>;\n } catch {\n params = {};\n }\n } else {\n params = parseFormUrlEncoded(ctx.rawBody);\n }\n return {\n from: normalizeE164(params.From ?? \"\", this.opts.defaultCountry),\n to: normalizeE164(params.To ?? \"\", this.opts.defaultCountry),\n body: params.Text ?? params.text ?? \"\",\n messageId: params.MessageUUID ?? params.message_uuid ?? \"\",\n receivedAt: Date.now(),\n raw: params,\n };\n }\n\n async sendMessage(to: string, body: string): Promise<SendResult> {\n if (this.client === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"PlivoBackend.connect() not called\" },\n };\n }\n try {\n const resp = await this.client.messages.create(this.opts.fromNumber, to, body);\n const id = resp.messageUuid?.[0] ?? resp.message_uuid?.[0] ?? resp.apiId ?? \"\";\n return { ok: true, messageId: id };\n } catch (err) {\n return mapPlivoError(err);\n }\n }\n}\n\nfunction parseFormUrlEncoded(body: string): Record<string, string> {\n const params: Record<string, string> = {};\n for (const pair of body.split(\"&\")) {\n if (pair.length === 0) continue;\n const eqIdx = pair.indexOf(\"=\");\n const k = eqIdx < 0 ? pair : pair.slice(0, eqIdx);\n const v = eqIdx < 0 ? \"\" : pair.slice(eqIdx + 1);\n params[decodeURIComponent(k.replace(/\\+/g, \" \"))] = decodeURIComponent(v.replace(/\\+/g, \" \"));\n }\n return params;\n}\n\ninterface PlivoRestError {\n statusCode?: number;\n status?: number;\n message?: string;\n}\n\nfunction mapPlivoError(err: unknown): SendResult {\n const e = err as PlivoRestError;\n const status = e.statusCode ?? e.status ?? 0;\n if (status === 429)\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"Plivo rate limit\" } };\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"Plivo auth error\" },\n };\n }\n if (status === 400) {\n return {\n ok: false,\n error: { code: \"invalid_request\", message: e.message ?? \"Plivo rejected request\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\n}\n","/**\n * Twilio backend impl.\n *\n * - SDK: `twilio` (peer-dep, optional). Loaded lazily so packages\n * that pick other backends don't pay the cost.\n * - Signature: `X-Twilio-Signature` is HMAC-SHA1 of `(fullUrl + sortedParams)`.\n * We delegate to `twilio.validateRequest` so we don't reimplement.\n *\n * @internal\n */\n\nimport type { SendResult } from \"@theokit/gateway\";\nimport type { SignatureContext, SMSBackend, SMSInbound } from \"../backend-types.js\";\nimport { BackendNotInstalledError } from \"../errors.js\";\nimport { normalizeE164 } from \"../phone.js\";\nimport type { TwilioOptions } from \"../types.js\";\n\ninterface TwilioCreateArgs {\n from: string;\n to: string;\n body: string;\n}\n\ninterface TwilioMessageInstance {\n sid: string;\n status?: string;\n}\n\ninterface TwilioClientInstance {\n messages: {\n create(args: TwilioCreateArgs): Promise<TwilioMessageInstance>;\n };\n}\n\ninterface TwilioFactory {\n (accountSid: string, authToken: string): TwilioClientInstance;\n validateRequest(\n authToken: string,\n signature: string,\n url: string,\n params: Record<string, string>,\n ): boolean;\n}\n\nasync function loadTwilio(): Promise<TwilioFactory> {\n try {\n const mod = await import(\"twilio\");\n // ESM ships { default: factory }; CJS ships factory.\n const candidate =\n (mod as { default?: TwilioFactory }).default ?? (mod as unknown as TwilioFactory);\n return candidate;\n } catch {\n throw new BackendNotInstalledError(\"twilio\", \"twilio\");\n }\n}\n\nexport class TwilioBackend implements SMSBackend {\n readonly kind = \"twilio\" as const;\n private client: TwilioClientInstance | undefined;\n private twilio: TwilioFactory | undefined;\n\n constructor(private readonly opts: TwilioOptions) {}\n\n async connect(): Promise<boolean> {\n if (this.client !== undefined) return true;\n this.twilio = await loadTwilio();\n this.client = this.twilio(this.opts.accountSid, this.opts.authToken);\n return true;\n }\n\n async disconnect(): Promise<void> {\n // No persistent connection — REST client is GC'd on dereference.\n this.client = undefined;\n }\n\n verifySignature(ctx: SignatureContext): boolean {\n if (this.twilio === undefined) return false;\n const signature = ctx.headers[\"x-twilio-signature\"];\n if (signature === undefined) return false;\n const params = parseFormUrlEncoded(ctx.rawBody);\n try {\n return this.twilio.validateRequest(this.opts.authToken, signature, ctx.url, params);\n } catch {\n return false;\n }\n }\n\n parseInbound(ctx: SignatureContext): SMSInbound {\n const params = parseFormUrlEncoded(ctx.rawBody);\n return {\n from: normalizeE164(params.From ?? \"\", this.opts.defaultCountry),\n to: normalizeE164(params.To ?? \"\", this.opts.defaultCountry),\n body: params.Body ?? \"\",\n messageId: params.MessageSid ?? params.SmsMessageSid ?? \"\",\n receivedAt: Date.now(),\n raw: params,\n };\n }\n\n async sendMessage(to: string, body: string): Promise<SendResult> {\n if (this.client === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"TwilioBackend.connect() not called\" },\n };\n }\n try {\n const msg = await this.client.messages.create({ from: this.opts.fromNumber, to, body });\n return { ok: true, messageId: msg.sid };\n } catch (err) {\n return mapTwilioError(err);\n }\n }\n}\n\n/**\n * Parse `application/x-www-form-urlencoded` request body to a flat\n * `Record<string, string>`. Twilio POSTs in this format.\n *\n * @internal\n */\nfunction parseFormUrlEncoded(body: string): Record<string, string> {\n const params: Record<string, string> = {};\n for (const pair of body.split(\"&\")) {\n if (pair.length === 0) continue;\n const eqIdx = pair.indexOf(\"=\");\n const k = eqIdx < 0 ? pair : pair.slice(0, eqIdx);\n const v = eqIdx < 0 ? \"\" : pair.slice(eqIdx + 1);\n params[decodeURIComponent(k.replace(/\\+/g, \" \"))] = decodeURIComponent(v.replace(/\\+/g, \" \"));\n }\n return params;\n}\n\ninterface TwilioRestError {\n status?: number;\n code?: number | string;\n message?: string;\n}\n\nfunction mapTwilioError(err: unknown): SendResult {\n const e = err as TwilioRestError;\n const status = e.status ?? 0;\n if (status === 429) {\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"Twilio rate limit\" } };\n }\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"Twilio auth error\" },\n };\n }\n if (status === 400) {\n return {\n ok: false,\n error: { code: \"invalid_request\", message: e.message ?? \"Twilio rejected request\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\n}\n","/**\n * Vonage backend impl.\n *\n * - SDK: `@vonage/server-sdk` (peer-dep, optional).\n * - Signature: `Authorization: Bearer <JWT>` signed with the Signature\n * Secret (NOT the API secret). The SDK exposes `Auth.verifySignature`\n * for this purpose.\n *\n * @internal\n */\n\nimport type { SendResult } from \"@theokit/gateway\";\nimport type { SignatureContext, SMSBackend, SMSInbound } from \"../backend-types.js\";\nimport { BackendNotInstalledError } from \"../errors.js\";\nimport { normalizeE164 } from \"../phone.js\";\nimport type { VonageOptions } from \"../types.js\";\n\ninterface VonageSmsClient {\n send(args: { to: string; from: string; text: string }): Promise<{\n messages?: Array<{ \"message-id\"?: string; messageId?: string; status?: string }>;\n }>;\n}\n\ninterface VonageInstance {\n sms: VonageSmsClient;\n}\n\ninterface VonageModule {\n Vonage: new (creds: {\n apiKey: string;\n apiSecret: string;\n signatureSecret?: string;\n }) => VonageInstance;\n Auth?: {\n verifySignature?: (token: string, secret: string) => boolean;\n };\n}\n\nasync function loadVonage(): Promise<VonageModule> {\n try {\n // SDK ships ESM/CJS variants; we narrow at call sites and pass through.\n const raw = await import(\"@vonage/server-sdk\");\n return raw as unknown as VonageModule;\n } catch {\n throw new BackendNotInstalledError(\"vonage\", \"@vonage/server-sdk\");\n }\n}\n\nexport class VonageBackend implements SMSBackend {\n readonly kind = \"vonage\" as const;\n private mod: VonageModule | undefined;\n private vonage: VonageInstance | undefined;\n\n constructor(private readonly opts: VonageOptions) {}\n\n async connect(): Promise<boolean> {\n if (this.vonage !== undefined) return true;\n this.mod = await loadVonage();\n this.vonage = new this.mod.Vonage({\n apiKey: this.opts.apiKey,\n apiSecret: this.opts.apiSecret,\n signatureSecret: this.opts.signatureSecret,\n });\n return true;\n }\n\n async disconnect(): Promise<void> {\n this.vonage = undefined;\n }\n\n verifySignature(ctx: SignatureContext): boolean {\n const auth = ctx.headers.authorization;\n if (auth === undefined) return false;\n const m = auth.match(/^Bearer\\s+(.+)$/i);\n if (m === null) return false;\n const token = m[1] ?? \"\";\n if (token.length === 0) return false;\n if (this.mod?.Auth?.verifySignature === undefined) return false;\n try {\n return this.mod.Auth.verifySignature(token, this.opts.signatureSecret);\n } catch {\n return false;\n }\n }\n\n parseInbound(ctx: SignatureContext): SMSInbound {\n let payload: Record<string, string> = {};\n try {\n payload = JSON.parse(ctx.rawBody) as Record<string, string>;\n } catch {\n payload = {};\n }\n return {\n from: normalizeE164(payload.msisdn ?? payload.from ?? \"\", this.opts.defaultCountry),\n to: normalizeE164(payload.to ?? \"\", this.opts.defaultCountry),\n body: payload.text ?? \"\",\n messageId: payload.messageId ?? payload[\"message-id\"] ?? \"\",\n receivedAt: Date.now(),\n raw: payload,\n };\n }\n\n async sendMessage(to: string, body: string): Promise<SendResult> {\n if (this.vonage === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"VonageBackend.connect() not called\" },\n };\n }\n try {\n const resp = await this.vonage.sms.send({ from: this.opts.fromNumber, to, text: body });\n const msg = resp.messages?.[0];\n const id = msg?.[\"message-id\"] ?? msg?.messageId ?? \"\";\n if (msg?.status !== undefined && msg.status !== \"0\") {\n return {\n ok: false,\n error: { code: \"send_failed\", message: `Vonage returned status=${msg.status}` },\n };\n }\n return { ok: true, messageId: id };\n } catch (err) {\n return mapVonageError(err);\n }\n }\n}\n\ninterface VonageRestError {\n status?: number;\n response?: { status?: number };\n message?: string;\n}\n\nfunction mapVonageError(err: unknown): SendResult {\n const e = err as VonageRestError;\n const status = e.status ?? e.response?.status ?? 0;\n if (status === 429)\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"Vonage rate limit\" } };\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"Vonage auth error\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\n}\n","/**\n * Backend factory — picks the right impl from `opts.backend`.\n *\n * @internal\n */\n\nimport type { SMSBackend } from \"../backend-types.js\";\nimport type { SMSAdapterOptions } from \"../types.js\";\nimport { PlivoBackend } from \"./plivo.js\";\nimport { TwilioBackend } from \"./twilio.js\";\nimport { VonageBackend } from \"./vonage.js\";\n\nexport function createBackend(opts: SMSAdapterOptions): SMSBackend {\n switch (opts.backend) {\n case \"twilio\":\n return new TwilioBackend(opts);\n case \"plivo\":\n return new PlivoBackend(opts);\n case \"vonage\":\n return new VonageBackend(opts);\n default: {\n const _exhaustive: never = opts;\n throw new Error(`unknown backend: ${JSON.stringify(_exhaustive)}`);\n }\n }\n}\n","/**\n * Inbound normalization: `SMSInbound` → `SMSMessageEvent`.\n *\n * `from` and `to` are already E.164 (backend.parseInbound enforces this).\n * `channel.id` is `from` because SMS conversations are flat per-pair\n * (D394 — no threading).\n *\n * @internal\n */\n\nimport type { SMSMessageEvent } from \"@theokit/gateway\";\n\nimport type { SMSInbound } from \"./backend-types.js\";\n\nexport function inboundToMessageEvent(\n inbound: SMSInbound,\n backend: \"twilio\" | \"plivo\" | \"vonage\",\n): SMSMessageEvent {\n return {\n id: inbound.messageId,\n platform: \"sms\",\n sender: { id: inbound.from },\n channel: { id: inbound.from, type: \"dm\" },\n text: inbound.body,\n receivedAt: inbound.receivedAt,\n sms: {\n backend,\n messageId: inbound.messageId,\n from: inbound.from,\n to: inbound.to,\n raw: inbound.raw,\n },\n };\n}\n","/**\n * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * This adapter sends text only, so an outbound carrying attachments is refused rather than sent without its images.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `@theokit/gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"@theokit/gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: { code: \"attachments_unsupported\", message: \"sms adapter cannot send attachments\" },\n };\n}\n","/**\n * `splitForSMS` — grapheme-cluster-safe multipart segmentation (D393, EC-7), keeping table rows\n * whole.\n *\n * Concatenated SMS (UDH) on modern carriers reassemble at the recipient,\n * but each TCP/IP-layer chunk is one billed message. We segment at\n * 1600 chars (default) so the API call doesn't reject and each part is\n * prefixed with `(i/N) ` to allow manual reordering when carriers\n * deliver out of sequence (EC-7).\n *\n * A text within the limit goes through core `chunkByGrapheme` as before. A longer one is cut at\n * the last grapheme boundary within each part, which is where `chunkByGrapheme`'s greedy walk\n * ends a part, so emoji (🇧🇷) and combining sequences are never severed and text with no table\n * row splits exactly as it did (pinned by `tests/split-no-table-baseline.test.ts` and the\n * equivalence test in `tests/split-tables.test.ts`). A cut that falls inside a Markdown table row\n * which fits in a part moves back to the start of that row (B-556). The rule is core\n * `splitKeepingRows`, shared with gateway-line. The `(i/N) ` prefix (and its reserved width) stays here since it is SMS-specific.\n *\n * @internal\n */\n\nimport { chunkByGrapheme, splitKeepingRows } from \"@theokit/gateway\";\n\n/**\n * Width of `\"(i/total) \"` when `i` has as many digits as `total` — the widest\n * the prefix can get for a given part count. `(99/99) ` is 8, `(100/126) ` is\n * 10, `(1000/1234) ` is 12.\n *\n * This used to be the constant 8, commented `\"(99/99) \" worst case`. It is the\n * worst case only below 100 parts; from the hundredth part on, every prefix\n * overflowed its reservation and each part exceeded the caller's declared cap\n * by 2 chars, which the provider rejects.\n */\nfunction prefixWidthFor(total: number): number {\n return 2 * String(total).length + 4;\n}\n\n/** One fixed-point pass: the parts of `text` with `partLimit` left beside the prefix. */\nfunction partsFor(text: string, limit: number, partLimit: number): string[] {\n if (text.length <= limit) return chunkByGrapheme(text, { limit, partLimit });\n // The core's RangeError for a limit of 0, 1.5 or NaN, with the message it had before.\n chunkByGrapheme(\"\", { limit, partLimit });\n return splitKeepingRows(text, partLimit);\n}\n\nexport function splitForSMS(text: string, limit = 1600): string[] {\n // Chicken and egg: the reservation depends on the part count, and the part\n // count depends on the reservation. Widening the prefix shrinks the payload,\n // which can push the count into another digit — so iterate to a fixed point.\n // It converges fast because the width grows with the LOGARITHM of the count;\n // the bound is a backstop against a pathological input, not the expected path.\n let reserved = prefixWidthFor(1);\n for (let pass = 0; pass < 8; pass += 1) {\n const partLimit = limit - reserved;\n if (partLimit <= 0) {\n throw new RangeError(\n `limit ${limit} is too small to carry an SMS part: the \"(i/N) \" prefix alone needs ${reserved} chars`,\n );\n }\n const parts = partsFor(text, limit, partLimit);\n if (parts.length <= 1) return parts; // short-circuit / single part: skip prefix\n const needed = prefixWidthFor(parts.length);\n if (needed <= reserved) {\n const total = parts.length;\n return parts.map((p, i) => `(${i + 1}/${total}) ${p}`);\n }\n reserved = needed;\n }\n /* c8 ignore next 3 -- unreachable: 8 passes cover part counts up to 10^8. */\n throw new RangeError(\n `could not settle the \"(i/N) \" prefix width for a ${text.length}-char message at limit ${limit}`,\n );\n}\n","/**\n * `SMSAdapter` — implements `BasePlatformAdapter` over a backend\n * (twilio / plivo / vonage). ADRs D389-D396.\n *\n * Lifecycle:\n * - `connect()` initializes the chosen backend (lazy peer-dep import).\n * - `disconnect()` releases the backend; idempotent.\n * - `sendMessage()` splits multipart (D393) and sends each part via backend.\n * - `onInbound(handler)` replaces previous handler (EC-H, mirror D276).\n *\n * Inbound dispatch is driven by the webhook server (`webhook-server.ts`)\n * which calls `adapter.dispatchInbound(ctx)` after signature verification.\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\nimport { createBackend } from \"./backend/index.js\";\nimport type { SignatureContext, SMSBackend } from \"./backend-types.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { inboundToMessageEvent } from \"./normalize.js\";\nimport { normalizeE164 } from \"./phone.js\";\nimport { refuseAttachments } from \"./refuse-attachments.js\";\nimport { splitForSMS } from \"./split.js\";\nimport type { SMSAdapterOptions } from \"./types.js\";\n\nexport class SMSAdapter extends BasePlatformAdapter {\n /**\n * Whether the \"this medium carries no formatting\" warning has already been emitted.\n *\n * Once per adapter, not once per message: a gateway answering a busy channel would turn a\n * useful diagnostic into a log flood, and a flooded log is one nobody reads — the same\n * reason the group-mention and allowlist drops elsewhere in this family log once.\n */\n private warnedAboutFormat = false;\n\n /**\n * Say, once, that a declared format is being dropped.\n *\n * `OutboundMessage.format` is the caller stating intent, and this medium has nowhere to put\n * it: no flag, no markup, no alternative part. Discarding it in silence is the swallowed-\n * error shape `rules/error-handling.md` refuses — nothing fails, and the caller learns their\n * formatting never arrived from a user, weeks later.\n *\n * @internal\n */\n private warnFormatUnsupported(format: string | undefined): void {\n // The \"is there anything to say\" question lives here rather than at the call site: a\n // `sendMessage` already at its complexity limit should ask one thing, not three.\n if (format === undefined || format === \"plain\") return;\n if (this.warnedAboutFormat) return;\n this.warnedAboutFormat = true;\n process.stderr.write(\n `[gateway-sms] format=\"${format}\" was declared, and SMS cannot carry it — ` +\n \"the medium is plain text. Sending unformatted; this is logged once.\\n\",\n );\n }\n\n readonly platform = \"sms\" as const;\n\n /**\n * The URL the provider POSTs inbound to, as the provider sees it.\n *\n * Required by all three backend option shapes and documented there as \"used by signature\n * verifier\" — and, measured 2026-08-31, read by nothing: it appeared only in the type and in test\n * fixtures. Twilio SIGNS this URL, so the value matters most in exactly the case where the\n * request cannot supply it: behind a proxy or a tunnel, the request's own URL is the internal one\n * and will not match what was signed.\n *\n * Exposed so {@link smsWebhookVerifier} can use it, which is what makes the option true.\n */\n readonly publicUrl: string;\n\n private readonly backend: SMSBackend;\n private inboundHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private connected = false;\n private readonly defaultCountry: string | undefined;\n\n constructor(opts: SMSAdapterOptions) {\n super();\n // EC-1: refuse to operate without signing secret.\n const secret = secretFromOpts(opts);\n if (secret.length === 0) {\n throw new ConfigurationError({\n code: \"signing_secret_required\",\n message: `gateway-sms: backend=\"${opts.backend}\" requires a signing secret (would accept unsigned webhooks)`,\n });\n }\n this.defaultCountry = opts.defaultCountry;\n this.publicUrl = opts.publicUrl;\n this.backend = createBackend(opts);\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n const ok = await this.backend.connect();\n this.connected = ok;\n return ok;\n }\n\n async disconnect(): Promise<void> {\n if (!this.connected) return;\n await this.backend.disconnect();\n this.connected = false;\n this.inboundHandler = undefined;\n }\n\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.sendText(out);\n }\n\n private async sendText(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"outbound text is empty\" } };\n }\n let toE164: string;\n try {\n toE164 = normalizeE164(out.channel.id, this.defaultCountry);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return { ok: false, error: { code: \"invalid_phone_number\", message: msg } };\n }\n const parts = splitForSMS(out.text);\n // Send sequentially so the recipient sees them in order; concurrent\n // submit would still cost the same but breaks ordering at carriers.\n let lastResult: SendResult | undefined;\n // SMS is plain text by definition. Reading the field is not ceremony: it is what turns a\n // silent discard into a stated one.\n this.warnFormatUnsupported(out.format);\n\n for (const part of parts) {\n lastResult = await this.backend.sendMessage(toE164, part);\n if (lastResult.ok !== true) {\n return {\n ok: false,\n error: {\n code: lastResult.error?.code ?? \"partial_send_failure\",\n message: `partial send failed after ${parts.indexOf(part)}/${parts.length}: ${lastResult.error?.message ?? \"unknown\"}`,\n },\n };\n }\n }\n return lastResult ?? { ok: false, error: { code: \"send_failed\", message: \"no parts sent\" } };\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace, not stack.\n this.inboundHandler = handler;\n return () => {\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n /**\n * Webhook hook — called by `createWebhookServer` AFTER signature\n * verification + parseInbound. Returns dispatch outcome (used for\n * 200/204 vs 500 by the webhook handler).\n *\n * @internal\n */\n async dispatchInbound(ctx: SignatureContext): Promise<\"ok\" | \"no_handler\" | \"parse_failed\"> {\n if (!this.backend.verifySignature(ctx)) {\n // Caller (webhook-server) inspects this via verifySignature directly,\n // but we re-check defensively if anyone calls dispatch directly.\n return \"parse_failed\";\n }\n let inbound: ReturnType<SMSBackend[\"parseInbound\"]>;\n try {\n inbound = this.backend.parseInbound(ctx);\n } catch {\n return \"parse_failed\";\n }\n if (this.inboundHandler === undefined) return \"no_handler\";\n const event = inboundToMessageEvent(inbound, this.backend.kind);\n try {\n await this.inboundHandler(event);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-sms] handler threw: ${msg}\\n`);\n }\n return \"ok\";\n }\n\n /**\n * Direct signature check — used by the webhook server to respond\n * `401` BEFORE dispatch when signature is invalid.\n *\n * @internal\n */\n verifySignature(ctx: SignatureContext): boolean {\n return this.backend.verifySignature(ctx);\n }\n\n /**\n * Direct parse — used by the webhook server when signature was already\n * validated upstream. Returns the normalized `SMSMessageEvent` to be\n * dispatched.\n *\n * @internal\n */\n buildEventFromCtx(ctx: SignatureContext): GatewayMessageEvent {\n const inbound = this.backend.parseInbound(ctx);\n return inboundToMessageEvent(inbound, this.backend.kind);\n }\n\n /**\n * Dispatch a pre-built event (used by webhook server after manual\n * signature + parse). Honors EC-H replace semantics and isolates\n * handler exceptions per `gateway-runner` contract.\n *\n * @internal\n */\n async dispatchEvent(event: GatewayMessageEvent): Promise<\"ok\" | \"no_handler\"> {\n if (this.inboundHandler === undefined) return \"no_handler\";\n try {\n await this.inboundHandler(event);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-sms] handler threw: ${msg}\\n`);\n }\n return \"ok\";\n }\n\n /** Backend kind (escape hatch for callers needing to introspect). */\n getBackendKind(): \"twilio\" | \"plivo\" | \"vonage\" {\n return this.backend.kind;\n }\n\n /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.runHandler(this.inboundHandler, event);\n }\n}\n\nfunction secretFromOpts(opts: SMSAdapterOptions): string {\n switch (opts.backend) {\n case \"twilio\":\n return opts.authToken;\n case \"plivo\":\n return opts.authToken;\n case \"vonage\":\n return opts.signatureSecret;\n default: {\n const _exhaustive: never = opts;\n void _exhaustive;\n return \"\";\n }\n }\n}\n","/**\n * Translating a raw provider webhook into the canonical event.\n *\n * **This does NOT go through TheoKit's `handleChannelWebhook`.** Signature verification here needs\n * the RAW body, the headers and the exact URL — `ChannelMessage` carries none of the three, so the\n * check cannot be performed from inside `onMessage` whatever the provider sends. Twilio adds a\n * second obstacle: it posts `application/x-www-form-urlencoded`, and that seam reads the body with\n * `request.json()` and answers 400 when it is not JSON. (Plivo accepts either encoding and Vonage\n * posts JSON, so only the first reason applies to them.)\n *\n * For an Express app, `createWebhookServer` is the whole path and you never call this — it builds\n * the {@link SignatureContext}, verifies the signature and goes through the adapter. This export is\n * for a route you host yourself: build the context from a request whose body you have not parsed,\n * then call this. It composes two functions that\n * already existed and were both private: each backend's `parseInbound`, which turns a provider's\n * raw body into the provider-agnostic {@link SMSInbound}, and `inboundToMessageEvent`, which turns\n * that into the canonical event. Neither is duplicated here — per ADR D426 the mapping stays in one\n * place, and this is composition, not a second translator.\n *\n * **Why it takes the adapter's options.** Parsing is provider-specific (`Twilio` posts\n * `MessageSid`, Plivo posts `MessageUUID`) and, for Twilio, country-dependent: a number that is not\n * already in E.164 is normalised against `defaultCountry`. Both live in the options an app already\n * holds, because it constructed the adapter with them. `createBackend` only stores them — it opens\n * no connection and loads no SDK, so this stays a pure function over its inputs.\n */\n\nimport type { SMSMessageEvent } from \"@theokit/gateway\";\n\nimport { createBackend } from \"./backend/index.js\";\nimport type { SignatureContext, SMSInbound } from \"./backend-types.js\";\nimport { inboundToMessageEvent } from \"./normalize.js\";\nimport type { SMSAdapterOptions } from \"./types.js\";\n\n/**\n * Translate one raw provider webhook into an {@link SMSMessageEvent}.\n *\n * Returns `null` — never throws — when the body is not one this provider recognises. The caller is\n * whatever holds the {@link SignatureContext}: `createWebhookServer` here, or your own route. It\n * returns `null` rather than throwing because a throw out of a webhook handler becomes a failed\n * request, and the provider then sees a delivery failure for a body that was merely unrecognised\n * (ADR D428, whose original rationale — \"runs after the 200\" — was measured false on 2026-08-24).\n *\n * `null` here means \"this body is not a parseable inbound message\".\n *\n * **One class of configuration error is not distinguishable from a bad body, and is not pretended\n * to be.** `defaultCountry` is read while parsing the body's own numbers, and `normalizeE164`\n * raises the same `ConfigurationError` for a bad configured country as for a bad number in the\n * body. An invalid `defaultCountry` therefore degrades to `null` rather than throwing.\n *\n * An earlier version tried to separate them by validating `options.fromNumber` up front. That was\n * wrong twice: `fromNumber` is passed raw to the provider SDK everywhere else in this package and\n * validated nowhere, and the invented rule rejected four documented, valid configurations — a\n * Vonage alphanumeric sender ID (`\"ACME\"`), a Twilio short code (`\"12345\"`), a Messaging Service\n * SID (`\"MG…\"`), and a national number with `defaultCountry` set. Each one threw out of\n * `onMessage`, turning a message the provider delivered into a failed request — precisely the\n * failure the check was written to prevent.\n * Inventing a validation stricter than the package's own is how that happened.\n *\n * @public\n */\nexport function parseInbound(\n options: SMSAdapterOptions,\n ctx: SignatureContext,\n): SMSMessageEvent | null {\n // `createBackend` is the CONFIGURATION step and sits outside the try on purpose: an unsupported\n // `backend` is a programmer error and must surface, not become the same `null` a malformed body\n // produces.\n const backend = createBackend(options);\n\n let inbound: SMSInbound;\n try {\n inbound = backend.parseInbound(ctx);\n } catch {\n // Everything from here is body-dependent, so any error means the body was unreadable. Caught\n // whatever its type: `decodeURIComponent` raises `URIError` on a malformed percent-escape\n // (`From=%zz`) and `normalizeE164` raises `ConfigurationError` on a number the body carried.\n // Both are bad requests, and returning `null` is what keeps them from failing the request:\n // measured against `theokit@0.48.14`, `handleChannelWebhook` awaits `onMessage` BEFORE\n // building the 200 and catches nothing around it, so a throw here escapes it entirely and\n // the 200 is never built (ADR D428, whose original rationale — \"runs after the 200\" — was\n // measured false on 2026-08-24).\n return null;\n }\n\n // A body the provider posted that carries no message id.\n //\n // Deliberately does NOT also check `inbound.from === \"\"`: all three backends build `from` with\n // `normalizeE164(x ?? \"\")`, which throws on an empty string, so the branch was unreachable and a\n // mutation deleting it survived the suite.\n if (inbound.messageId === \"\") return null;\n\n return inboundToMessageEvent(inbound, options.backend);\n}\n","/**\n * `createWebhookServer` — Express helper for inbound SMS webhooks.\n *\n * Registers per-backend routes (`/sms/twilio`, `/sms/plivo`, `/sms/vonage`)\n * each with the matching parser middleware. All three:\n *\n * 1. Read the raw body verbatim (signature verification depends on the\n * exact bytes — even one extra `\\r\\n` invalidates the HMAC).\n * 2. Call `adapter.verifySignature(ctx)` → 401 if false.\n * 3. Call `adapter.buildEventFromCtx(ctx)` → `dispatchEvent(event)`.\n * 4. Return 204 No Content.\n *\n * Caller can pass an existing Express app (`opts.app`) or let the helper\n * create one. `start()` / `stop()` are idempotent.\n *\n * @public\n */\n\nimport {\n DEFAULT_WEBHOOK_MAX_BYTES,\n listenerLifecycle,\n loadPeer,\n rawBodyCapture,\n} from \"@theokit/gateway\";\nimport type { Express, Request, Response } from \"express\";\nimport type { SMSAdapter } from \"./adapter.js\";\nimport type { SignatureContext } from \"./backend-types.js\";\n\nimport { ConfigurationError } from \"./errors.js\";\n\nexport interface WebhookServerOptions {\n readonly adapter: SMSAdapter;\n /** Mount path prefix; default `\"/sms\"`. The full path is `${path}/${backend}`. */\n readonly path?: string;\n /** Listen port. Ignored when `app` is provided. Default `3000`. */\n readonly port?: number;\n /** Inject an existing Express app instead of creating one. */\n readonly app?: Express;\n}\n\n/** A started HTTP listener, with the handle needed to shut it down again. */\nexport interface WebhookServer {\n start(): Promise<void>;\n stop(): Promise<void>;\n}\n\nasync function loadExpress(): Promise<() => Express> {\n return loadPeer<() => Express>(\n async () => import(\"express\"),\n () => {\n throw new ConfigurationError({\n code: \"express_not_installed\",\n message: 'gateway-sms: peer-dep \"express\" not installed. Run: pnpm add express',\n });\n },\n );\n}\n\n/**\n * The URL the provider signed.\n *\n * `publicUrl` wins when it is configured, because it is the only value that survives a proxy. The\n * provider verifies against the address IT posted to, and behind a tunnel, an ingress, or a load\n * balancer terminating TLS the reconstruction below yields the internal one — so a correct\n * signature fails, on every delivery, with nothing in the log naming the cause.\n *\n * The header reconstruction stays as the fallback: an app served directly has nothing to configure\n * and the headers are the truth. Measured 2026-08-31 — `publicUrl` is required by all three backend\n * option shapes and documented as \"used by signature verifier\", and until this commit no source\n * file read it.\n */\nfunction signedUrl(\n req: Request,\n headers: Readonly<Record<string, string>>,\n publicUrl?: string,\n): string {\n if (publicUrl !== undefined && publicUrl !== \"\") return publicUrl;\n const protoHeader = headers[\"x-forwarded-proto\"];\n const proto = protoHeader ?? (req.secure ? \"https\" : \"http\");\n const host = req.get(\"host\") ?? \"localhost\";\n return `${proto}://${host}${req.originalUrl}`;\n}\n\nfunction buildSignatureContext(req: Request, publicUrl?: string): SignatureContext {\n const rawBody = (req as Request & { rawBody?: string }).rawBody ?? \"\";\n const headers: Record<string, string> = {};\n for (const [k, v] of Object.entries(req.headers)) {\n headers[k.toLowerCase()] = Array.isArray(v) ? v.join(\",\") : (v ?? \"\");\n }\n return { headers, rawBody, url: signedUrl(req, headers, publicUrl) };\n}\n\n/**\n * Build the HTTP listener that receives the provider's inbound-SMS callbacks.\n *\n * The provider dials in, so this endpoint must be reachable over public HTTPS and registered in the\n * provider console — inbound cannot work behind a firewall. `express` is loaded lazily, so a project\n * that only sends messages never pays for it.\n */\nexport async function createWebhookServer(opts: WebhookServerOptions): Promise<WebhookServer> {\n const createApp = await loadExpress();\n const app: Express = opts.app ?? createApp();\n const prefix = opts.path ?? \"/sms\";\n const backend = opts.adapter.getBackendKind();\n\n const handler = (req: Request, res: Response): void => {\n const ctx = buildSignatureContext(req, opts.adapter.publicUrl);\n if (!opts.adapter.verifySignature(ctx)) {\n res.status(401).type(\"text/plain\").send(\"invalid signature\");\n return;\n }\n let event: ReturnType<typeof opts.adapter.buildEventFromCtx>;\n try {\n event = opts.adapter.buildEventFromCtx(ctx);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n res.status(400).type(\"text/plain\").send(`parse failed: ${msg}`);\n return;\n }\n // Same contract as the LINE server: the provider is answered before the handler runs, so a\n // slow handler cannot become a provider retry. That makes the dispatch floated, and a floated\n // rejection ends the process — so it is caught here rather than left to the runtime (#41).\n void opts.adapter.dispatchEvent(event).catch((err: unknown) => {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-sms] webhook dispatch failed: ${message}\\n`);\n });\n // Twilio expects either TwiML or 204; 204 keeps things simple\n // and avoids accidentally double-replying.\n res.status(204).end();\n };\n\n app.post(\n `${prefix}/${backend}`,\n rawBodyCapture(\"gateway-sms\", { maxBytes: DEFAULT_WEBHOOK_MAX_BYTES }),\n handler,\n );\n\n // The lifecycle lives in `@theokit/gateway`, written once. It was duplicated here and in\n // gateway-line, and the same write-once latch bug had to be fixed in both files by one commit —\n // which is what turned the duplication from a style question into a defect (#89).\n return listenerLifecycle({ app, port: opts.port ?? 3000, injected: opts.app !== undefined });\n}\n","/**\n * The SMS half of a channel webhook, in the shape a framework webhook seam expects.\n *\n * `theokit/server/webhook` ships validators for the platforms whose signature is a plain HMAC it\n * can compute itself. SMS is not one of them: Twilio signs the URL plus the sorted POST parameters,\n * Plivo signs a different string again, and Vonage uses a JWT. Those three schemes already exist in\n * this package, correctly, with their own tests — reimplementing them one repository over would put\n * security-critical code in two places and guarantee they drift.\n *\n * So the direction is inverted. The framework declares the SHAPE; the package that owns the\n * platform provides the implementation. The shape is structural, so nothing here imports the\n * framework and this package gains no dependency:\n *\n * ```ts\n * await handleChannelWebhook(request, pathname, {\n * validators: { sms: smsWebhookVerifier(adapter) },\n * })\n * ```\n *\n * @public\n */\n\nimport type { SMSAdapter } from \"./adapter.js\";\nimport type { SignatureContext } from \"./backend-types.js\";\n\n/**\n * What a verifier answers. Structurally identical to the framework's `VerifyResult`, declared here\n * so this package does not depend on the framework to describe its own return value.\n *\n * @public\n */\nexport type WebhookVerifyResult =\n | { readonly ok: true }\n | { readonly ok: false; readonly reason: string };\n\n/** Options for {@link smsWebhookVerifier}. @public */\nexport interface SMSWebhookVerifierOptions {\n /**\n * The URL the provider POSTs to, as the provider sees it.\n *\n * Twilio signs the URL, so verification compares against whatever string is passed here — and\n * behind a proxy or a tunnel the request's own URL is the INTERNAL one, which will not match.\n * Defaults to the adapter's configured `publicUrl` when it has one, and to the request URL\n * otherwise.\n */\n readonly publicUrl?: string;\n}\n\n/**\n * The subset of the adapter this verifier reads. Stated as an interface so the parameter is honest\n * about its requirements, and so a test can supply the two members without a live provider SDK.\n */\ninterface VerifiableAdapter {\n verifySignature(ctx: SignatureContext): boolean;\n readonly publicUrl?: string;\n}\n\n/**\n * The lowercased header map {@link SignatureContext} promises its consumers.\n *\n * No `toLowerCase()` here, and that is the point rather than an omission: the Fetch `Headers` object\n * normalises names on the way in, so iterating it already yields `x-twilio-signature` however the\n * sender wrote it. Lowercasing again was in the first version and mutation testing showed it dead —\n * removing it changed no test, because the platform had already done the work.\n */\nfunction headersOf(request: Request): Record<string, string> {\n const out: Record<string, string> = {};\n request.headers.forEach((value, key) => {\n out[key] = value;\n });\n return out;\n}\n\n/**\n * Build a verifier for one configured SMS adapter.\n *\n * The request is READ, so pass a clone if the body is needed afterwards — a framework seam that\n * hands validators a `clone()` already does this. Reading it raw is not optional: every provider\n * signs the exact bytes, and a body that was parsed and re-serialised hashes differently.\n *\n * **Connect the adapter first.** Each backend loads its provider SDK during `connect()`, and until\n * it has, `verifySignature` answers `false` for everything — so a verifier wired before connect\n * refuses every genuine delivery as a bad signature. The two are NOT distinguishable here: the\n * backend contract returns a boolean, and inventing a reason this function cannot actually observe\n * would be worse than the ambiguity. The behaviour is pinned by a test rather than papered over,\n * and telling them apart needs a readiness signal the adapter does not expose today.\n *\n * @public\n */\nexport function smsWebhookVerifier(\n adapter: SMSAdapter | VerifiableAdapter,\n opts: SMSWebhookVerifierOptions = {},\n): (request: Request) => Promise<WebhookVerifyResult> {\n return async (request: Request): Promise<WebhookVerifyResult> => {\n const rawBody = await request.text();\n const ctx: SignatureContext = {\n headers: headersOf(request),\n rawBody,\n url: opts.publicUrl ?? adapter.publicUrl ?? request.url,\n };\n return adapter.verifySignature(ctx)\n ? { ok: true }\n : { ok: false, reason: \"signature mismatch\" };\n };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theokit/gateway-sms",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "description": "SMS platform adapter for @theokit/gateway. Multi-backend (Twilio + Plivo + Vonage). ADRs D389-D396.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -25,7 +25,8 @@
25
25
  "types": "./dist/index.d.cts",
26
26
  "default": "./dist/index.cjs"
27
27
  }
28
- }
28
+ },
29
+ "./package.json": "./package.json"
29
30
  },
30
31
  "sideEffects": false,
31
32
  "files": [
@@ -35,7 +36,7 @@
35
36
  "CHANGELOG.md"
36
37
  ],
37
38
  "peerDependencies": {
38
- "@theokit/gateway": ">=0.9.0 <1.0.0",
39
+ "@theokit/gateway": ">=0.14.0 <1.0.0",
39
40
  "@vonage/server-sdk": "^3.0.0",
40
41
  "express": "^4.18.0 || ^5.0.0",
41
42
  "libphonenumber-js": "^1.10.0",
@@ -70,12 +71,26 @@
70
71
  "typescript": "5.9.3",
71
72
  "vitest": "^4.1.11",
72
73
  "zod": "^4.0.0",
73
- "@theokit/gateway": "0.9.0"
74
+ "@theokit/gateway": "0.17.0"
74
75
  },
75
76
  "publishConfig": {
76
77
  "access": "public",
77
78
  "provenance": true
78
79
  },
80
+ "bugs": {
81
+ "url": "https://github.com/usetheokit/theokit-gateways/issues"
82
+ },
83
+ "homepage": "https://github.com/usetheokit/theokit-gateways/tree/main/packages/gateway-sms#readme",
84
+ "keywords": [
85
+ "theokit",
86
+ "gateway",
87
+ "sms",
88
+ "platform",
89
+ "adapter",
90
+ "multi-backend",
91
+ "twilio",
92
+ "plivo"
93
+ ],
79
94
  "scripts": {
80
95
  "build": "tsup",
81
96
  "typecheck": "tsc --noEmit",