@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 234 lines 7.88 KB
Raw
1 import { expect } from "bun:test";
2 import * as Cloudflare from "@alchemy.run/cloudflare";
3 import * as Stripe from "@alchemy.run/stripe";
4 import * as Test from "@alchemy.run/test/Bun";
5 import {
6 CreatePaymentMethod,
7 CreatePaymentMethodAttach,
8 CreateSubscription,
9 DeleteCustomer,
10 DeleteSubscription,
11 GetCheckoutSession,
12 GetWebhookEndpoints,
13 } from "@distilled.cloud/stripe/stripe";
14 import * as Alchemy from "alchemy";
15 import * as Effect from "effect/Effect";
16 import * as FetchHttpClient from "effect/http/FetchHttpClient";
17 import * as HttpClient from "effect/http/HttpClient";
18 import * as HttpClientRequest from "effect/http/HttpClientRequest";
19 import * as Layer from "effect/Layer";
20 import * as Schedule from "effect/Schedule";
21 import Stack from "../alchemy.run.ts";
22
23 const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
24 providers: Layer.mergeAll(Cloudflare.providers(), Stripe.providers()),
25 state: Alchemy.localState(),
26 });
27
28 const { getWhenReady } = Test;
29
30 // Out-of-band distilled calls resolve the same stored Stripe key the deploy
31 // uses, so the test runs against the configured profile without needing
32 // STRIPE_API_KEY in the environment.
33 const StripeHttp = Layer.mergeAll(
34 Stripe.StripeAuth,
35 Stripe.fromAuthProvider(),
36 FetchHttpClient.layer,
37 );
38
39 interface Entitlement {
40 customerId: string;
41 status: "active" | "past_due" | "canceled" | "none";
42 priceId: string | null;
43 subscriptionId: string | null;
44 }
45
46 const stack = beforeAll(deploy(Stack), { timeout: 180_000 });
47
48 afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(Stack), {
49 timeout: 120_000,
50 });
51
52 const readEntitlement = (baseUrl: string, customerId: string) =>
53 Effect.gen(function* () {
54 const res = yield* HttpClient.execute(
55 HttpClientRequest.get(`${baseUrl}/subscription/${customerId}`),
56 );
57 return (yield* res.json) as unknown as Entitlement;
58 });
59
60 // Webhook delivery is asynchronous; poll until the entitlement reaches the
61 // expected status.
62 const waitForStatus = (baseUrl: string, customerId: string, status: Entitlement["status"]) =>
63 readEntitlement(baseUrl, customerId).pipe(
64 Effect.repeat({
65 schedule: Schedule.spaced("5 seconds"),
66 until: (e) => e.status === status,
67 times: 24,
68 }),
69 );
70
71 test(
72 "deploys a worker URL and provisions the webhook endpoint",
73 Effect.gen(function* () {
74 const { url } = yield* stack;
75 expect(url).toBeString();
76 const delivery = `${url.replace(/\/+$/, "")}/webhooks/stripe`;
77 const endpoints = yield* GetWebhookEndpoints({ limit: 100 }).pipe(Effect.provide(StripeHttp));
78 const endpoint = endpoints.data.find((e) => e.url.replace(/\/+$/, "") === delivery);
79 expect(endpoint).toBeDefined();
80 expect(endpoint?.enabled_events).toEqual(
81 expect.arrayContaining([
82 "checkout.session.completed",
83 "customer.subscription.created",
84 "customer.subscription.updated",
85 "customer.subscription.deleted",
86 "invoice.payment_failed",
87 ]),
88 );
89 }),
90 );
91
92 test(
93 "POST /checkout creates a customer and a hosted Checkout Session for the Pro price",
94 Effect.gen(function* () {
95 const { url } = yield* stack;
96 const baseUrl = url.replace(/\/+$/, "");
97 yield* getWhenReady(`${baseUrl}/pricing`);
98
99 const res = yield* HttpClient.execute(
100 HttpClientRequest.post(`${baseUrl}/checkout`).pipe(
101 HttpClientRequest.bodyJsonUnsafe({
102 email: "stripe-billing-checkout@example.com",
103 }),
104 ),
105 );
106 expect(res.status).toBe(201);
107 const body = (yield* res.json) as {
108 customerId: string;
109 checkoutUrl: string;
110 };
111 expect(body.customerId).toMatch(/^cus_/);
112 expect(body.checkoutUrl).toMatch(/^https:\/\/checkout\.stripe\.com\//);
113
114 // The session is a real subscription-mode Checkout for the deployed
115 // Price, bound to the customer the Worker just created.
116 const sessionId = new URL(body.checkoutUrl).pathname.split("/").filter(Boolean).at(-1)!;
117 const session = yield* GetCheckoutSession({ session: sessionId }).pipe(
118 Effect.provide(StripeHttp),
119 );
120 expect(session.mode).toEqual("subscription");
121 expect(session.status).toEqual("open");
122 expect(session.customer).toEqual(body.customerId);
123
124 // Nothing paid yet → no entitlement.
125 const before = yield* readEntitlement(baseUrl, body.customerId);
126 expect(before.status).toEqual("none");
127
128 yield* DeleteCustomer({ customer: body.customerId }).pipe(
129 Effect.catch(() => Effect.void),
130 Effect.provide(StripeHttp),
131 );
132 }),
133 { timeout: 120_000 },
134 );
135
136 test(
137 "subscription lifecycle webhooks keep the entitlement current",
138 Effect.gen(function* () {
139 const { url } = yield* stack;
140 const baseUrl = url.replace(/\/+$/, "");
141 yield* getWhenReady(`${baseUrl}/pricing`);
142
143 // Start from the Worker so the customer exists in the app's flow.
144 const checkout = yield* HttpClient.execute(
145 HttpClientRequest.post(`${baseUrl}/checkout`).pipe(
146 HttpClientRequest.bodyJsonUnsafe({
147 email: "stripe-billing-lifecycle@example.com",
148 }),
149 ),
150 );
151 const { customerId, checkoutUrl } = (yield* checkout.json) as {
152 customerId: string;
153 checkoutUrl: string;
154 };
155
156 // Hosted Checkout needs a browser. Stand in for the buyer by attaching
157 // Stripe's `tok_visa` test card and creating the same subscription
158 // directly — this fires the real `customer.subscription.*` webhooks the
159 // Worker consumes.
160 const sessionId = new URL(checkoutUrl).pathname.split("/").filter(Boolean).at(-1)!;
161 const session = yield* GetCheckoutSession({
162 session: sessionId,
163 expand: ["line_items"],
164 }).pipe(Effect.provide(StripeHttp));
165 const priceId = session.line_items?.data[0]?.price?.id;
166 expect(priceId).toMatch(/^price_/);
167
168 const paymentMethod = yield* CreatePaymentMethod({
169 type: "card",
170 card: { token: "tok_visa" },
171 }).pipe(Effect.provide(StripeHttp));
172 yield* CreatePaymentMethodAttach({
173 payment_method: paymentMethod.id,
174 customer: customerId,
175 }).pipe(Effect.provide(StripeHttp));
176 const subscription = yield* CreateSubscription({
177 customer: customerId,
178 items: [{ price: priceId! }],
179 default_payment_method: paymentMethod.id,
180 payment_behavior: "error_if_incomplete",
181 }).pipe(Effect.provide(StripeHttp));
182 expect(subscription.status).toEqual("active");
183
184 const active = yield* waitForStatus(baseUrl, customerId, "active");
185 expect(active.subscriptionId).toEqual(subscription.id);
186 expect(active.priceId).toEqual(priceId!);
187
188 yield* DeleteSubscription({
189 subscription_exposed_id: subscription.id,
190 }).pipe(Effect.provide(StripeHttp));
191
192 const canceled = yield* waitForStatus(baseUrl, customerId, "canceled");
193 expect(canceled.subscriptionId).toEqual(subscription.id);
194
195 yield* DeleteCustomer({ customer: customerId }).pipe(
196 Effect.catch(() => Effect.void),
197 Effect.provide(StripeHttp),
198 );
199 }),
200 { timeout: 300_000 },
201 );
202
203 test(
204 "POST /portal opens the Billing Portal for a customer",
205 Effect.gen(function* () {
206 const { url } = yield* stack;
207 const baseUrl = url.replace(/\/+$/, "");
208 yield* getWhenReady(`${baseUrl}/pricing`);
209
210 const checkout = yield* HttpClient.execute(
211 HttpClientRequest.post(`${baseUrl}/checkout`).pipe(
212 HttpClientRequest.bodyJsonUnsafe({
213 email: "stripe-billing-portal@example.com",
214 }),
215 ),
216 );
217 const { customerId } = (yield* checkout.json) as { customerId: string };
218
219 const res = yield* HttpClient.execute(
220 HttpClientRequest.post(`${baseUrl}/portal`).pipe(
221 HttpClientRequest.bodyJsonUnsafe({ customerId }),
222 ),
223 );
224 expect(res.status).toBe(200);
225 const body = (yield* res.json) as { portalUrl: string };
226 expect(body.portalUrl).toMatch(/^https:\/\/billing\.stripe\.com\//);
227
228 yield* DeleteCustomer({ customer: customerId }).pipe(
229 Effect.catch(() => Effect.void),
230 Effect.provide(StripeHttp),
231 );
232 }),
233 { timeout: 120_000 },
234 );