@kalangu/ussd 0.0.0-stage → 0.1.0-alpha.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Abdoullah Ndao
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,38 @@
1
- # Temporary Holding Version
1
+ # @kalangu/ussd
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Africa's Talking USSD adapter for [Kalangu](https://github.com/utachicodes/kalangu)
4
+ agents.
5
+
6
+ > Alpha. The API may change before 1.0.
7
+
8
+ ```sh
9
+ pnpm add @kalangu/core @kalangu/ussd
10
+ ```
11
+
12
+ ```ts
13
+ import { createAgent } from "@kalangu/core";
14
+ import { africasTalkingUssd } from "@kalangu/ussd";
15
+
16
+ const agent = createAgent({
17
+ start,
18
+ channels: [africasTalkingUssd({ code: "*384*1#", path: "/ussd" })],
19
+ });
20
+
21
+ // Mount agent.requestHandler (standard Request -> Response) at your callback URL.
22
+ ```
23
+
24
+ - Parses the gateway's form callback and always answers `200 text/plain`
25
+ with `CON `/`END `, including on errors, so the user's session is never
26
+ dropped by a malformed reply.
27
+ - Dial strings with choices (`*384*1*2#`) are replayed from the start menu.
28
+ - Options: `maxScreenChars` (default 160; Airtel Kenya allows 184), `more`
29
+ (default `98`), `unsafeChars` (`"strip"` or `"throw"`), `hopMetadata`,
30
+ and a session-end notification route (`endPath`, default `/ussd/end`).
31
+
32
+ Callbacks from the gateway are not signed. Use a hard-to-guess path and,
33
+ where you can, allow only the gateway's IP addresses.
34
+
35
+ A `*` typed inside free text splits the answer; the gateway gives no way
36
+ to tell it apart from a separator. Numeric input is unaffected.
37
+
38
+ MIT licensed.
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Africa's Talking USSD adapter (docs/design.md §7.1).
3
+ *
4
+ * The gateway POSTs form fields on every dial and every reply, and expects
5
+ * `200 text/plain` starting `CON ` (continue) or `END ` (finish). Anything
6
+ * else ends the user's session, so every path here answers with a valid
7
+ * body, including errors.
8
+ *
9
+ * Callbacks are not signed. Treat them as untrusted input: use a hard-to-
10
+ * guess path and, where you can, allow only the gateway's IP addresses.
11
+ */
12
+ import { type Channel, type Outcome, type RouteAgent } from "@kalangu/core";
13
+ export interface AfricasTalkingUssdOptions {
14
+ /** Channel id. Default "ussd". */
15
+ id?: string;
16
+ /** Your service code, e.g. "*384*1#". Requests for another code are logged. */
17
+ code?: string;
18
+ /** Callback path. Default "/ussd". */
19
+ path?: string;
20
+ /** Session-end notification path, or false for none. Default "/ussd/end". */
21
+ endPath?: string | false;
22
+ /** Characters per screen. Default 160 (Safaricom KE, Nigeria); Airtel KE allows 184. */
23
+ maxScreenChars?: number;
24
+ /** The number for "More". Default "98". */
25
+ more?: string;
26
+ /** Characters with no safe form: strip with a warning (default) or throw. */
27
+ unsafeChars?: "strip" | "throw";
28
+ /**
29
+ * Send the step id in the `at-ussd-hop-metadata` header for journey
30
+ * tracking in the gateway dashboard. Contains no personal data. Default off.
31
+ */
32
+ hopMetadata?: boolean;
33
+ /** Called with each session-end notification after it is logged. */
34
+ onSessionEnd?: (notification: SessionEndNotification) => void | Promise<void>;
35
+ }
36
+ export interface UssdRequest {
37
+ sessionId: string;
38
+ phoneNumber: string;
39
+ networkCode: string;
40
+ serviceCode: string;
41
+ /** Everything typed this session, `*`-joined; empty on the first request. */
42
+ text: string;
43
+ }
44
+ export interface SessionEndNotification {
45
+ sessionId: string;
46
+ phoneNumber: string;
47
+ networkCode: string;
48
+ serviceCode: string;
49
+ date: string;
50
+ status: "Incomplete" | "Success" | "Failed" | (string & {});
51
+ cost: string;
52
+ durationInMillis: number | null;
53
+ hopsCount: number | null;
54
+ hopsMetadata: string[];
55
+ input: string;
56
+ lastAppResponse: string;
57
+ errorMessage?: string;
58
+ }
59
+ export type AfricasTalkingUssdChannel = Channel & {
60
+ /** This channel's callback handler, for mounting it yourself. */
61
+ handler(agent: RouteAgent): (req: Request) => Promise<Response>;
62
+ };
63
+ export declare function africasTalkingUssd(options?: AfricasTalkingUssdOptions): AfricasTalkingUssdChannel;
64
+ /** Reads the gateway's form fields. Missing fields become empty strings. */
65
+ export declare function parseUssdRequest(form: FormData | URLSearchParams): UssdRequest;
66
+ /**
67
+ * The inputs typed so far, oldest first. A `*` typed inside free text also
68
+ * splits here; the gateway sends no way to tell the two apart.
69
+ */
70
+ export declare function ussdInputs(text: string): string[];
71
+ /** `CON body` or `END body`, with the trailing space the official SDK sends. */
72
+ export declare function ussdBody(outcome: Pick<Outcome, "text" | "end">): string;
73
+ /** Reads a session-end notification's form fields. */
74
+ export declare function parseSessionEnd(form: FormData | URLSearchParams): SessionEndNotification;
75
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../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G,IAAI,CAAC;IAChC,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,YAAY,EAAE,MAAM,EAAE,CAAC;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,eAAe,EAAE,MAAM,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,MAAM,yBAAyB,GAAG,OAAO,GAAG;IAChD,iEAAiE;IACjE,OAAO,CAAC,KAAK,EAAE,UAAU,GAAG,CAAC,GAAG,EAAE,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;CACjE,CAAC;AAIF,wBAAgB,kBAAkB,CAAC,OAAO,GAAE,yBAA8B,GAAG,yBAAyB,CAyBrG;AAED,4EAA4E;AAC5E,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,QAAQ,GAAG,eAAe,GAAG,WAAW,CAY9E;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAEjD;AAED,gFAAgF;AAChF,wBAAgB,QAAQ,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,KAAK,CAAC,GAAG,MAAM,CAEvE;AAoED,sDAAsD;AACtD,wBAAgB,eAAe,CAAC,IAAI,EAAE,QAAQ,GAAG,eAAe,GAAG,sBAAsB,CA2BxF"}
package/dist/index.js ADDED
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Africa's Talking USSD adapter (docs/design.md §7.1).
3
+ *
4
+ * The gateway POSTs form fields on every dial and every reply, and expects
5
+ * `200 text/plain` starting `CON ` (continue) or `END ` (finish). Anything
6
+ * else ends the user's session, so every path here answers with a valid
7
+ * body, including errors.
8
+ *
9
+ * Callbacks are not signed. Treat them as untrusted input: use a hard-to-
10
+ * guess path and, where you can, allow only the gateway's IP addresses.
11
+ */
12
+ import { ussdChannel } from "@kalangu/core";
13
+ const HOP_HEADER = "at-ussd-hop-metadata";
14
+ export function africasTalkingUssd(options = {}) {
15
+ const path = options.path ?? "/ussd";
16
+ const endPath = options.endPath === undefined ? "/ussd/end" : options.endPath;
17
+ const callback = {
18
+ path,
19
+ handle: (req, agent) => handleCallback(req, agent, channel.id, options),
20
+ };
21
+ const routes = [callback];
22
+ if (endPath)
23
+ routes.push({ path: endPath, handle: (req, agent) => handleSessionEnd(req, agent, options) });
24
+ const base = ussdChannel({
25
+ id: options.id ?? "ussd",
26
+ budget: {
27
+ ...(options.maxScreenChars !== undefined ? { maxChars: options.maxScreenChars } : {}),
28
+ ...(options.more !== undefined ? { more: options.more } : {}),
29
+ ...(options.unsafeChars !== undefined ? { unsafeChars: options.unsafeChars } : {}),
30
+ },
31
+ routes,
32
+ });
33
+ const channel = {
34
+ ...base,
35
+ handler: (agent) => (req) => callback.handle(req, agent),
36
+ };
37
+ return channel;
38
+ }
39
+ /** Reads the gateway's form fields. Missing fields become empty strings. */
40
+ export function parseUssdRequest(form) {
41
+ const field = (name) => {
42
+ const value = form.get(name);
43
+ return typeof value === "string" ? value : "";
44
+ };
45
+ return {
46
+ sessionId: field("sessionId"),
47
+ phoneNumber: field("phoneNumber"),
48
+ networkCode: field("networkCode"),
49
+ serviceCode: field("serviceCode"),
50
+ text: field("text"),
51
+ };
52
+ }
53
+ /**
54
+ * The inputs typed so far, oldest first. A `*` typed inside free text also
55
+ * splits here; the gateway sends no way to tell the two apart.
56
+ */
57
+ export function ussdInputs(text) {
58
+ return text === "" ? [] : text.split("*");
59
+ }
60
+ /** `CON body` or `END body`, with the trailing space the official SDK sends. */
61
+ export function ussdBody(outcome) {
62
+ return `${outcome.end ? "END" : "CON"} ${outcome.text}`;
63
+ }
64
+ async function handleCallback(req, agent, channelId, options) {
65
+ if (req.method !== "POST")
66
+ return methodNotAllowed();
67
+ let request;
68
+ try {
69
+ request = parseUssdRequest(await req.formData());
70
+ }
71
+ catch (err) {
72
+ agent.logger.warn("Unreadable USSD callback body", { error: String(err) });
73
+ return reply({ text: agent.errorText(), end: true, stepId: null, deferred: false }, false);
74
+ }
75
+ if (!request.phoneNumber) {
76
+ agent.logger.warn("USSD callback without a phone number", { sessionId: request.sessionId });
77
+ return reply({ text: agent.errorText(), end: true, stepId: null, deferred: false }, false);
78
+ }
79
+ if (options.code && request.serviceCode && request.serviceCode !== options.code) {
80
+ agent.logger.warn("USSD callback for an unexpected service code", {
81
+ expected: options.code,
82
+ received: request.serviceCode,
83
+ });
84
+ }
85
+ const inputs = ussdInputs(request.text);
86
+ try {
87
+ const outcome = await agent.handle({
88
+ channel: channelId,
89
+ phone: request.phoneNumber,
90
+ input: inputs.at(-1) ?? "",
91
+ inputs,
92
+ newSession: request.text === "",
93
+ ...(request.sessionId ? { gatewaySessionId: request.sessionId } : {}),
94
+ });
95
+ return reply(outcome, options.hopMetadata ?? false);
96
+ }
97
+ catch (err) {
98
+ agent.logger.error("USSD turn failed", { phone: agent.mask(request.phoneNumber), error: String(err) });
99
+ return reply({ text: agent.errorText(), end: true, stepId: null, deferred: false }, false);
100
+ }
101
+ }
102
+ async function handleSessionEnd(req, agent, options) {
103
+ if (req.method !== "POST")
104
+ return methodNotAllowed();
105
+ try {
106
+ const notification = parseSessionEnd(await req.formData());
107
+ agent.logger.info("USSD session ended", {
108
+ phone: agent.mask(notification.phoneNumber),
109
+ status: notification.status,
110
+ durationInMillis: notification.durationInMillis,
111
+ hopsCount: notification.hopsCount,
112
+ ...(notification.errorMessage ? { errorMessage: notification.errorMessage } : {}),
113
+ });
114
+ await options.onSessionEnd?.(notification);
115
+ }
116
+ catch (err) {
117
+ agent.logger.error("Session-end notification failed", { error: String(err) });
118
+ }
119
+ return new Response("OK", { status: 200, headers: { "content-type": "text/plain" } });
120
+ }
121
+ /** Reads a session-end notification's form fields. */
122
+ export function parseSessionEnd(form) {
123
+ const field = (name) => {
124
+ const value = form.get(name);
125
+ return typeof value === "string" ? value : "";
126
+ };
127
+ const number = (name) => {
128
+ const value = field(name);
129
+ const n = Number(value);
130
+ return value !== "" && Number.isFinite(n) ? n : null;
131
+ };
132
+ const notification = {
133
+ sessionId: field("sessionId"),
134
+ phoneNumber: field("phoneNumber"),
135
+ networkCode: field("networkCode"),
136
+ serviceCode: field("serviceCode"),
137
+ date: field("date"),
138
+ status: field("status"),
139
+ cost: field("cost"),
140
+ durationInMillis: number("durationInMillis"),
141
+ hopsCount: number("hopsCount"),
142
+ hopsMetadata: field("hopsMetadata") === "" ? [] : field("hopsMetadata").split("|"),
143
+ input: field("input"),
144
+ lastAppResponse: field("lastAppResponse"),
145
+ };
146
+ const errorMessage = field("errorMessage");
147
+ if (errorMessage)
148
+ notification.errorMessage = errorMessage;
149
+ return notification;
150
+ }
151
+ function reply(outcome, hopMetadata) {
152
+ const headers = new Headers({ "content-type": "text/plain; charset=utf-8" });
153
+ if (hopMetadata && outcome.stepId) {
154
+ headers.set(HOP_HEADER, outcome.stepId.replace(/\|/g, "/").slice(0, 99));
155
+ }
156
+ return new Response(ussdBody(outcome), { status: 200, headers });
157
+ }
158
+ function methodNotAllowed() {
159
+ return new Response("Method not allowed", { status: 405, headers: { allow: "POST", "content-type": "text/plain" } });
160
+ }
161
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,WAAW,EAA2D,MAAM,eAAe,CAAC;AAwDrG,MAAM,UAAU,GAAG,sBAAsB,CAAC;AAE1C,MAAM,UAAU,kBAAkB,CAAC,OAAO,GAA8B,EAAE;IACxE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,OAAO,CAAC;IACrC,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC;IAE9E,MAAM,QAAQ,GAAU;QACtB,IAAI;QACJ,MAAM,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,CAAC,cAAc,CAAC,GAA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C;QAC9B,YAAY,EAAE,KAAK,CAAC,cAAc,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC;QAClF,KAAK,EAAE,KAAK,CAAC,OAAO,CAAC;QACrB,eAAe,EAAE,KAAK,CAAC,iBAAiB,CAAC;KAC1C,CAAC;IACF,MAAM,YAAY,GAAG,KAAK,CAAC,cAAc,CAAC,CAAC;IAC3C,IAAI,YAAY;QAAE,YAAY,CAAC,YAAY,GAAG,YAAY,CAAC;IAC3D,OAAO,YAAY,CAAC;AACtB,CAAC;AAED,SAAS,KAAK,CAAC,OAAgB,EAAE,WAAoB;IACnD,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,EAAE,cAAc,EAAE,2BAA2B,EAAE,CAAC,CAAC;IAC7E,IAAI,WAAW,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;QAClC,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;IAC3E,CAAC;IACD,OAAO,IAAI,QAAQ,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,EAAE,CAAC,CAAC;AACnE,CAAC;AAED,SAAS,gBAAgB;IACvB,OAAO,IAAI,QAAQ,CAAC,oBAAoB,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,cAAc,EAAE,YAAY,EAAE,EAAE,CAAC,CAAC;AACvH,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "@kalangu/ussd",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0-alpha.1",
4
+ "description": "Africa's Talking USSD adapter for Kalangu agents.",
5
+ "keywords": [
6
+ "ussd",
7
+ "africastalking",
8
+ "africas-talking",
9
+ "agents",
10
+ "ai",
11
+ "africa"
12
+ ],
13
+ "license": "MIT",
14
+ "author": "Abdoullah Ndao",
15
+ "homepage": "https://github.com/utachicodes/kalangu/tree/main/packages/ussd#readme",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/utachicodes/kalangu.git",
19
+ "directory": "packages/ussd"
20
+ },
21
+ "bugs": {
22
+ "url": "https://github.com/utachicodes/kalangu/issues"
23
+ },
24
+ "type": "module",
25
+ "sideEffects": false,
26
+ "engines": {
27
+ "node": ">=20"
28
+ },
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "default": "./dist/index.js"
33
+ }
34
+ },
35
+ "types": "./dist/index.d.ts",
36
+ "files": [
37
+ "dist",
38
+ "src",
39
+ "README.md",
40
+ "LICENSE"
41
+ ],
42
+ "publishConfig": {
43
+ "access": "public",
44
+ "tag": "alpha"
45
+ },
46
+ "dependencies": {
47
+ "@kalangu/core": "0.1.0-alpha.1"
48
+ },
49
+ "scripts": {
50
+ "build": "tsc -p tsconfig.build.json",
51
+ "typecheck": "tsc -p tsconfig.json --noEmit",
52
+ "test": "vitest run"
53
+ }
6
54
  }
package/src/index.ts ADDED
@@ -0,0 +1,232 @@
1
+ /**
2
+ * Africa's Talking USSD adapter (docs/design.md §7.1).
3
+ *
4
+ * The gateway POSTs form fields on every dial and every reply, and expects
5
+ * `200 text/plain` starting `CON ` (continue) or `END ` (finish). Anything
6
+ * else ends the user's session, so every path here answers with a valid
7
+ * body, including errors.
8
+ *
9
+ * Callbacks are not signed. Treat them as untrusted input: use a hard-to-
10
+ * guess path and, where you can, allow only the gateway's IP addresses.
11
+ */
12
+
13
+ import { ussdChannel, type Channel, type Outcome, type Route, type RouteAgent } from "@kalangu/core";
14
+
15
+ export interface AfricasTalkingUssdOptions {
16
+ /** Channel id. Default "ussd". */
17
+ id?: string;
18
+ /** Your service code, e.g. "*384*1#". Requests for another code are logged. */
19
+ code?: string;
20
+ /** Callback path. Default "/ussd". */
21
+ path?: string;
22
+ /** Session-end notification path, or false for none. Default "/ussd/end". */
23
+ endPath?: string | false;
24
+ /** Characters per screen. Default 160 (Safaricom KE, Nigeria); Airtel KE allows 184. */
25
+ maxScreenChars?: number;
26
+ /** The number for "More". Default "98". */
27
+ more?: string;
28
+ /** Characters with no safe form: strip with a warning (default) or throw. */
29
+ unsafeChars?: "strip" | "throw";
30
+ /**
31
+ * Send the step id in the `at-ussd-hop-metadata` header for journey
32
+ * tracking in the gateway dashboard. Contains no personal data. Default off.
33
+ */
34
+ hopMetadata?: boolean;
35
+ /** Called with each session-end notification after it is logged. */
36
+ onSessionEnd?: (notification: SessionEndNotification) => void | Promise<void>;
37
+ }
38
+
39
+ export interface UssdRequest {
40
+ sessionId: string;
41
+ phoneNumber: string;
42
+ networkCode: string;
43
+ serviceCode: string;
44
+ /** Everything typed this session, `*`-joined; empty on the first request. */
45
+ text: string;
46
+ }
47
+
48
+ export interface SessionEndNotification {
49
+ sessionId: string;
50
+ phoneNumber: string;
51
+ networkCode: string;
52
+ serviceCode: string;
53
+ date: string;
54
+ status: "Incomplete" | "Success" | "Failed" | (string & {});
55
+ cost: string;
56
+ durationInMillis: number | null;
57
+ hopsCount: number | null;
58
+ hopsMetadata: string[];
59
+ input: string;
60
+ lastAppResponse: string;
61
+ errorMessage?: string;
62
+ }
63
+
64
+ export type AfricasTalkingUssdChannel = Channel & {
65
+ /** This channel's callback handler, for mounting it yourself. */
66
+ handler(agent: RouteAgent): (req: Request) => Promise<Response>;
67
+ };
68
+
69
+ const HOP_HEADER = "at-ussd-hop-metadata";
70
+
71
+ export function africasTalkingUssd(options: AfricasTalkingUssdOptions = {}): AfricasTalkingUssdChannel {
72
+ const path = options.path ?? "/ussd";
73
+ const endPath = options.endPath === undefined ? "/ussd/end" : options.endPath;
74
+
75
+ const callback: Route = {
76
+ path,
77
+ handle: (req, agent) => handleCallback(req, agent, channel.id, options),
78
+ };
79
+ const routes: Route[] = [callback];
80
+ if (endPath) routes.push({ path: endPath, handle: (req, agent) => handleSessionEnd(req, agent, options) });
81
+
82
+ const base = ussdChannel({
83
+ id: options.id ?? "ussd",
84
+ budget: {
85
+ ...(options.maxScreenChars !== undefined ? { maxChars: options.maxScreenChars } : {}),
86
+ ...(options.more !== undefined ? { more: options.more } : {}),
87
+ ...(options.unsafeChars !== undefined ? { unsafeChars: options.unsafeChars } : {}),
88
+ },
89
+ routes,
90
+ });
91
+ const channel: AfricasTalkingUssdChannel = {
92
+ ...base,
93
+ handler: (agent) => (req) => callback.handle(req, agent),
94
+ };
95
+ return channel;
96
+ }
97
+
98
+ /** Reads the gateway's form fields. Missing fields become empty strings. */
99
+ export function parseUssdRequest(form: FormData | URLSearchParams): UssdRequest {
100
+ const field = (name: string) => {
101
+ const value = form.get(name);
102
+ return typeof value === "string" ? value : "";
103
+ };
104
+ return {
105
+ sessionId: field("sessionId"),
106
+ phoneNumber: field("phoneNumber"),
107
+ networkCode: field("networkCode"),
108
+ serviceCode: field("serviceCode"),
109
+ text: field("text"),
110
+ };
111
+ }
112
+
113
+ /**
114
+ * The inputs typed so far, oldest first. A `*` typed inside free text also
115
+ * splits here; the gateway sends no way to tell the two apart.
116
+ */
117
+ export function ussdInputs(text: string): string[] {
118
+ return text === "" ? [] : text.split("*");
119
+ }
120
+
121
+ /** `CON body` or `END body`, with the trailing space the official SDK sends. */
122
+ export function ussdBody(outcome: Pick<Outcome, "text" | "end">): string {
123
+ return `${outcome.end ? "END" : "CON"} ${outcome.text}`;
124
+ }
125
+
126
+ async function handleCallback(
127
+ req: Request,
128
+ agent: RouteAgent,
129
+ channelId: string,
130
+ options: AfricasTalkingUssdOptions,
131
+ ): Promise<Response> {
132
+ if (req.method !== "POST") return methodNotAllowed();
133
+
134
+ let request: UssdRequest;
135
+ try {
136
+ request = parseUssdRequest(await req.formData());
137
+ } catch (err) {
138
+ agent.logger.warn("Unreadable USSD callback body", { error: String(err) });
139
+ return reply({ text: agent.errorText(), end: true, stepId: null, deferred: false }, false);
140
+ }
141
+
142
+ if (!request.phoneNumber) {
143
+ agent.logger.warn("USSD callback without a phone number", { sessionId: request.sessionId });
144
+ return reply({ text: agent.errorText(), end: true, stepId: null, deferred: false }, false);
145
+ }
146
+ if (options.code && request.serviceCode && request.serviceCode !== options.code) {
147
+ agent.logger.warn("USSD callback for an unexpected service code", {
148
+ expected: options.code,
149
+ received: request.serviceCode,
150
+ });
151
+ }
152
+
153
+ const inputs = ussdInputs(request.text);
154
+ try {
155
+ const outcome = await agent.handle({
156
+ channel: channelId,
157
+ phone: request.phoneNumber,
158
+ input: inputs.at(-1) ?? "",
159
+ inputs,
160
+ newSession: request.text === "",
161
+ ...(request.sessionId ? { gatewaySessionId: request.sessionId } : {}),
162
+ });
163
+ return reply(outcome, options.hopMetadata ?? false);
164
+ } catch (err) {
165
+ agent.logger.error("USSD turn failed", { phone: agent.mask(request.phoneNumber), error: String(err) });
166
+ return reply({ text: agent.errorText(), end: true, stepId: null, deferred: false }, false);
167
+ }
168
+ }
169
+
170
+ async function handleSessionEnd(
171
+ req: Request,
172
+ agent: RouteAgent,
173
+ options: AfricasTalkingUssdOptions,
174
+ ): Promise<Response> {
175
+ if (req.method !== "POST") return methodNotAllowed();
176
+ try {
177
+ const notification = parseSessionEnd(await req.formData());
178
+ agent.logger.info("USSD session ended", {
179
+ phone: agent.mask(notification.phoneNumber),
180
+ status: notification.status,
181
+ durationInMillis: notification.durationInMillis,
182
+ hopsCount: notification.hopsCount,
183
+ ...(notification.errorMessage ? { errorMessage: notification.errorMessage } : {}),
184
+ });
185
+ await options.onSessionEnd?.(notification);
186
+ } catch (err) {
187
+ agent.logger.error("Session-end notification failed", { error: String(err) });
188
+ }
189
+ return new Response("OK", { status: 200, headers: { "content-type": "text/plain" } });
190
+ }
191
+
192
+ /** Reads a session-end notification's form fields. */
193
+ export function parseSessionEnd(form: FormData | URLSearchParams): SessionEndNotification {
194
+ const field = (name: string) => {
195
+ const value = form.get(name);
196
+ return typeof value === "string" ? value : "";
197
+ };
198
+ const number = (name: string) => {
199
+ const value = field(name);
200
+ const n = Number(value);
201
+ return value !== "" && Number.isFinite(n) ? n : null;
202
+ };
203
+ const notification: SessionEndNotification = {
204
+ sessionId: field("sessionId"),
205
+ phoneNumber: field("phoneNumber"),
206
+ networkCode: field("networkCode"),
207
+ serviceCode: field("serviceCode"),
208
+ date: field("date"),
209
+ status: field("status"),
210
+ cost: field("cost"),
211
+ durationInMillis: number("durationInMillis"),
212
+ hopsCount: number("hopsCount"),
213
+ hopsMetadata: field("hopsMetadata") === "" ? [] : field("hopsMetadata").split("|"),
214
+ input: field("input"),
215
+ lastAppResponse: field("lastAppResponse"),
216
+ };
217
+ const errorMessage = field("errorMessage");
218
+ if (errorMessage) notification.errorMessage = errorMessage;
219
+ return notification;
220
+ }
221
+
222
+ function reply(outcome: Outcome, hopMetadata: boolean): Response {
223
+ const headers = new Headers({ "content-type": "text/plain; charset=utf-8" });
224
+ if (hopMetadata && outcome.stepId) {
225
+ headers.set(HOP_HEADER, outcome.stepId.replace(/\|/g, "/").slice(0, 99));
226
+ }
227
+ return new Response(ussdBody(outcome), { status: 200, headers });
228
+ }
229
+
230
+ function methodNotAllowed(): Response {
231
+ return new Response("Method not allowed", { status: 405, headers: { allow: "POST", "content-type": "text/plain" } });
232
+ }