328 lines · 12.8 KB
import { beforeEach, describe, expect, mock, test } from "bun:test";
import Stripe from "stripe";
import { fakeD1 } from "../metering/fake-d1.test-helper";

let d1 = fakeD1();
const kv = new Map<string, string>();
const SECRET = "whsec_test_secret";
const fakeEnv: Record<string, unknown> = {
  get DB() {
    return d1.binding;
  },
  KV: {
    get: async (key: string) => kv.get(key) ?? null,
    put: async (key: string, value: string) => void kv.set(key, value),
    delete: async (key: string) => void kv.delete(key),
  },
  METERING_PLANS: "",
  PUBLIC_URL: "https://forge.test",
  STRIPE_SECRET_KEY: "sk_test_unit",
  STRIPE_WEBHOOK_SECRET: SECRET,
  STRIPE_PRICE_PRO: "price_pro",
  STRIPE_TOPUP_PRICES: JSON.stringify({
    compute_10h: "price_c",
    tokens_10m: { price: "price_t" },
    tokens_50m: "nope",
    unknown_pack: "price_x",
  }),
};
mock.module("cloudflare:workers", () => ({ env: fakeEnv, waitUntil: () => undefined }));

const { handleStripeWebhook, processStripeEvent } = await import("./webhook");
const { topupPacks } = await import("./config");
const { creditBalance } = await import("../metering/credits");

const signer = new Stripe("sk_test_unit");
const crypto = Stripe.createSubtleCryptoProvider();
let sequence = 0;

function event(type: string, object: Record<string, unknown>, created = 1_700_000_000 + sequence): Stripe.Event {
  sequence += 1;