refactor: normalize delivery context

Co-authored-by: adam91holt <adam91holt@users.noreply.github.com>
This commit is contained in:
Peter Steinberger
2026-01-17 04:24:42 +00:00
parent 8ebfa2950d
commit 4f37f66264
4 changed files with 47 additions and 21 deletions

View File

@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import {
deliveryContextKey,
deliveryContextFromSession,
mergeDeliveryContext,
normalizeDeliveryContext,
} from "./delivery-context.js";
@@ -42,4 +43,19 @@ describe("delivery context helpers", () => {
);
expect(deliveryContextKey({ channel: "whatsapp" })).toBeUndefined();
});
it("derives delivery context from a session entry", () => {
expect(
deliveryContextFromSession({
channel: "webchat",
lastChannel: " whatsapp ",
lastTo: " +1777 ",
lastAccountId: " acct-9 ",
}),
).toEqual({
channel: "whatsapp",
to: "+1777",
accountId: "acct-9",
});
});
});

View File

@@ -6,6 +6,13 @@ export type DeliveryContext = {
accountId?: string;
};
type DeliveryContextSessionSource = {
channel?: string;
lastChannel?: string;
lastTo?: string;
lastAccountId?: string;
};
export function normalizeDeliveryContext(context?: DeliveryContext): DeliveryContext | undefined {
if (!context) return undefined;
const channel = typeof context.channel === "string" ? context.channel.trim() : undefined;
@@ -19,6 +26,17 @@ export function normalizeDeliveryContext(context?: DeliveryContext): DeliveryCon
};
}
export function deliveryContextFromSession(
entry?: DeliveryContextSessionSource,
): DeliveryContext | undefined {
if (!entry) return undefined;
return normalizeDeliveryContext({
channel: entry.lastChannel ?? entry.channel,
to: entry.lastTo,
accountId: entry.lastAccountId,
});
}
export function mergeDeliveryContext(
primary?: DeliveryContext,
fallback?: DeliveryContext,