Functional Weave
Code in Rust

subscriptions.stripe-state@1.0.0

impl/typescript.ts

7,430 bytes · the TypeScript implementation · view raw

import type { StripeSubscriptionStatus, SubscriptionState } from "./subscriptions_stripe_state_types.ts";

const STATUSES: readonly string[] = ["incomplete", "incomplete_expired", "trialing", "active", "past_due", "canceled", "unpaid", "paused"];
const SUBSCRIPTION_EVENTS: readonly string[] = [
  "customer.subscription.created",
  "customer.subscription.updated",
  "customer.subscription.deleted",
  "customer.subscription.paused",
  "customer.subscription.resumed",
  "customer.subscription.trial_will_end",
];
const PAID_EVENTS: readonly string[] = ["invoice.paid", "invoice.payment_succeeded"];
const FAILED_EVENT = "invoice.payment_failed";

type Obj = Readonly<Record<string, unknown>>;

function isObj(v: unknown): v is Obj {
  return typeof v === "object" && v !== null && !Array.isArray(v);
}

function field(o: unknown, key: string): unknown {
  return isObj(o) ? o[key] : undefined;
}

// An id Stripe sends either as a string or, when expanded, as an object with one.
function idOf(v: unknown): string | null {
  if (typeof v === "string" && v !== "") return v;
  const id = field(v, "id");
  return typeof id === "string" && id !== "" ? id : null;
}

function optInt(o: Obj, key: string): number | null {
  const v = o[key];
  if (v === undefined || v === null) return null;
  if (typeof v !== "number" || !Number.isInteger(v)) throw new Error(`subscription field ${key} must be a whole number or null`);
  return v;
}

function entitledFor(status: string): boolean {
  return status === "active" || status === "trialing" || status === "past_due";
}

// Where an invoice event happened after this snapshot was taken, the snapshot
// does not know about the payment yet: keep the invoice's effect on top of it.
function withInvoiceEffect(status: string, paymentFailed: boolean): string {
  if (!paymentFailed && (status === "incomplete" || status === "past_due" || status === "unpaid")) return "active";
  if (paymentFailed && status === "active") return "past_due";
  return status;
}

function invoiceSubscription(invoice: Obj): string | null {
  const direct = idOf(invoice.subscription);
  if (direct !== null) return direct;
  // API versions from 2025 move it under parent.subscription_details.
  return idOf(field(field(invoice.parent, "subscription_details"), "subscription"));
}

/**
 * Folds one verified Stripe webhook event into the stored state of one
 * subscription. Stripe does not promise delivery order or delivery once, so
 * subscription snapshots and invoice events each keep their own clock and an
 * older one is ignored, a redelivered event changes nothing, and a cancelled
 * subscription stays cancelled.
 */
export function applyStripeEvent(state: SubscriptionState | null, event: unknown): SubscriptionState | null {
  if (!isObj(event)) throw new Error("event must be a JSON object");
  if (typeof event.id !== "string" || event.id === "") throw new Error("event id must be a non-empty string");
  if (typeof event.type !== "string" || event.type === "") throw new Error("event type must be a non-empty string");
  if (typeof event.created !== "number" || !Number.isInteger(event.created) || event.created < 0) {
    throw new Error("event created must be a whole number of seconds");
  }
  if (!isObj(event.object)) throw new Error("event object must be a JSON object");
  if (state !== null && event.id === state.lastEventId) return state;
  const obj = event.object;

  if (SUBSCRIPTION_EVENTS.includes(event.type)) {
    const id = idOf(obj.id);
    const customer = idOf(obj.customer);
    const rawStatus = obj.status;
    if (id === null || customer === null || typeof rawStatus !== "string") {
      throw new Error("subscription object needs id, customer and status");
    }
    if (!STATUSES.includes(rawStatus)) throw new Error(`unknown subscription status "${rawStatus}"`);
    if (state !== null && id !== state.subscriptionId) throw new Error(`event is for subscription ${id}, not ${state.subscriptionId}`);
    const snapshotStatus = event.type === "customer.subscription.deleted" ? "canceled" : rawStatus;
    // Cancelled is final in Stripe: a late snapshot never revives it, though a
    // later cancelled one (the deletion after the update) may fill in endedAt.
    if (state !== null && state.status === "canceled" && snapshotStatus !== "canceled") return state;
    if (state !== null && event.created < state.subscriptionEventAt) return state;
    const items = field(obj.items, "data");
    const item: Obj = Array.isArray(items) && isObj(items[0]) ? items[0] : {};
    const quantity = optInt(item, "quantity") ?? 1;
    const periodStart = optInt(obj, "current_period_start") ?? optInt(item, "current_period_start");
    const periodEnd = optInt(obj, "current_period_end") ?? optInt(item, "current_period_end");
    const cape = obj.cancel_at_period_end;
    if (cape !== undefined && cape !== null && typeof cape !== "boolean") throw new Error("subscription field cancel_at_period_end must be true or false");
    const paymentFailed = state?.paymentFailed ?? false;
    const invoiceEventAt = state?.invoiceEventAt ?? 0;
    let status: string = snapshotStatus;
    if (invoiceEventAt > event.created) status = withInvoiceEffect(status, paymentFailed);
    return {
      subscriptionId: id,
      customerId: customer,
      status: status as StripeSubscriptionStatus,
      priceId: idOf(field(item, "price")),
      quantity,
      currentPeriodStart: periodStart,
      currentPeriodEnd: periodEnd,
      cancelAtPeriodEnd: cape === true,
      cancelAt: optInt(obj, "cancel_at"),
      canceledAt: optInt(obj, "canceled_at"),
      endedAt: optInt(obj, "ended_at"),
      trialEnd: optInt(obj, "trial_end"),
      latestInvoiceId: idOf(obj.latest_invoice) ?? state?.latestInvoiceId ?? null,
      paymentFailed,
      entitled: entitledFor(status),
      subscriptionEventAt: event.created,
      invoiceEventAt,
      lastEventId: event.id,
    };
  }

  const paid = PAID_EVENTS.includes(event.type);
  if (paid || event.type === FAILED_EVENT) {
    const sub = invoiceSubscription(obj);
    if (sub === null) return state;
    const invoiceId = idOf(obj.id);
    if (state === null) {
      const customer = idOf(obj.customer);
      if (customer === null) throw new Error("invoice object needs customer");
      const status = paid ? "active" : "incomplete";
      return {
        subscriptionId: sub,
        customerId: customer,
        status,
        priceId: null,
        quantity: 1,
        currentPeriodStart: null,
        currentPeriodEnd: null,
        cancelAtPeriodEnd: false,
        cancelAt: null,
        canceledAt: null,
        endedAt: null,
        trialEnd: null,
        latestInvoiceId: invoiceId,
        paymentFailed: !paid,
        entitled: entitledFor(status),
        subscriptionEventAt: 0,
        invoiceEventAt: event.created,
        lastEventId: event.id,
      };
    }
    if (sub !== state.subscriptionId) throw new Error(`event is for subscription ${sub}, not ${state.subscriptionId}`);
    if (event.created < state.invoiceEventAt) return state;
    const status = withInvoiceEffect(state.status, !paid);
    return {
      ...state,
      status: status as StripeSubscriptionStatus,
      latestInvoiceId: invoiceId ?? state.latestInvoiceId,
      paymentFailed: !paid,
      entitled: entitledFor(status),
      invoiceEventAt: event.created,
      lastEventId: event.id,
    };
  }

  return state;
}