import { describe, it, expect } from "bun:test";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { recordedSubscriptionScope } from "../routes/stripe-webhook";
type Leaf = { kind: "str" | "col" | "param"; value: string };
function leaves(node: unknown, out: Leaf[] = []): Leaf[] {
if (!node) return out;
if (Array.isArray(node)) {
for (const n of node) leaves(n, out);
return out;
}
const anyNode = node as any;
const kind = anyNode?.constructor?.name;
if (kind === "SQL") return leaves(anyNode.queryChunks, out);
if (kind === "StringChunk") {
out.push({ kind: "str", value: String(anyNode.value ?? "") });
return out;
}
if (kind === "Param") {
out.push({ kind: "param", value: String(anyNode.value) });
return out;
}
if (anyNode?.name && anyNode?.table) {
out.push({ kind: "col", value: String(anyNode.name) });
}
return out;
}
const text = (ls: Leaf[]) =>
ls
.filter((l) => l.kind === "str")
.map((l) => l.value)
.join(" ");
describe("recordedSubscriptionScope", () => {
it("returns no constraint when the event names no subscription", () => {
expect(recordedSubscriptionScope("")).toBeUndefined();
});
it("constrains on the subscription id the event carries", () => {
const ls = leaves(recordedSubscriptionScope("sub_ABC"));
expect(ls.some((l) => l.kind === "col" && l.value === "stripe_subscription_id")).toBe(true);
expect(ls.some((l) => l.kind === "param" && l.value === "sub_ABC")).toBe(true);
});
it("does not bind some other subscription's id", () => {
const ls = leaves(recordedSubscriptionScope("sub_NEW"));
expect(ls.some((l) => l.kind === "param" && l.value === "sub_OLD")).toBe(false);
});
it("also matches a row whose subscription id was never recorded", () => {
const sql = text(leaves(recordedSubscriptionScope("sub_ABC")));
expect(sql).toContain(" or ");
expect(sql.toLowerCase()).toContain("is null");
});
it("never references the customer column — that is the caller's job", () => {
const ls = leaves(recordedSubscriptionScope("sub_ABC"));
expect(ls.some((l) => l.kind === "col" && l.value === "stripe_customer_id")).toBe(false);
});
});
describe("stripe-webhook applies the scope everywhere it mutates a plan", () => {
const src = (() => {
const raw = readFileSync(
join(import.meta.dir, "..", "routes", "stripe-webhook.ts"),
"utf8"
);
const stripped = raw
.split("\n")
.filter((l) => !l.trim().startsWith("//") && !l.trim().startsWith("*"))
.join("\n");
expect(stripped.length).toBeGreaterThan(0);
return stripped;
})();
function slice(startAnchor: string, endAnchor: string): string {
const start = src.indexOf(startAnchor);
expect(start).toBeGreaterThan(-1);
const end = src.indexOf(endAnchor, start + startAnchor.length);
expect(end).toBeGreaterThan(start);
const body = src.slice(start, end);
expect(body.length).toBeGreaterThan(0);
return body;
}
it("subscription.deleted scopes the downgrade", () => {
const body = slice(
`case "customer.subscription.deleted"`,
`case "invoice.payment_failed"`
);
expect(body).toContain('planSlug: "free"');
expect(body).toContain("recordedSubscriptionScope");
expect(body.indexOf("recordedSubscriptionScope")).toBeGreaterThan(
body.indexOf("stripeCustomerId, customerId")
);
});
it("invoice.payment_failed scopes the past_due flag", () => {
const body = slice(`case "invoice.payment_failed"`, "default:");
expect(body).toContain('stripeSubscriptionStatus: "past_due"');
expect(body).toContain("recordedSubscriptionScope");
});
it("reconcileSubscription scopes its non-active write", () => {
const body = slice("async function reconcileSubscription", "if (!slug)");
expect(body).toContain("stripeSubscriptionId: sub.id");
expect(body).toContain("recordedSubscriptionScope");
});
it("leaves exactly one unscoped update — the active-upgrade path", () => {
const unscoped =
src.match(/\.where\(\s*eq\(userQuotas\.stripeCustomerId/g) ?? [];
expect(unscoped.length).toBe(1);
const at = src.search(/\.where\(\s*eq\(userQuotas\.stripeCustomerId/);
const block = src.slice(Math.max(0, at - 400), at);
expect(block.length).toBeGreaterThan(0);
expect(block).toContain("planSlug: slug");
expect(block).not.toContain('planSlug: "free"');
expect(block).not.toContain('"past_due"');
});
});
|