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

main
ts 490 lines 15.6 KB
Raw
1 import { withRequestOptions } from "@distilled.cloud/stripe";
2 import {
3 GetPrices,
4 GetPrice,
5 CreatePrice,
6 UpdatePrice,
7 type Price as StripePrice,
8 type PriceProduct,
9 } from "@distilled.cloud/stripe/stripe";
10 import { Unowned } from "alchemy/AdoptPolicy";
11 import { isResolved } from "alchemy/Diff";
12 import * as Provider from "alchemy/Provider";
13 import { Resource } from "alchemy/Resource";
14 import { tagRecord } from "alchemy/Tags";
15 import * as Data from "effect/Data";
16 import * as Effect from "effect/Effect";
17 import {
18 alchemyMetadataKeys,
19 createInternalMetadata,
20 diffMetadata,
21 hasAlchemyMetadata,
22 stripInternalMetadata,
23 toMetadata,
24 } from "./Metadata.ts";
25 import { isMissingStripeResource } from "./missing.ts";
26 import type { Product } from "./Product.ts";
27 import type { Providers } from "./Providers.ts";
28
29 const LIST_PAGE_SIZE = 100;
30 const LIST_MAX_PAGES = 100;
31
32 export type PriceInterval = "day" | "month" | "week" | "year";
33 export type PriceUsageType = "licensed" | "metered";
34 export type PriceType = "one_time" | "recurring";
35
36 export interface PriceRecurring {
37 /**
38 * Billing frequency. Create-only — changing it replaces the price.
39 */
40 interval: PriceInterval;
41 /**
42 * Number of intervals between billings. Maximum of three years
43 * (`3` years, `36` months, or `156` weeks).
44 * @default 1
45 */
46 intervalCount?: number;
47 /**
48 * How quantity per period is determined. `licensed` bills the
49 * subscription quantity; `metered` aggregates usage records.
50 * @default "licensed"
51 */
52 usageType?: PriceUsageType;
53 /**
54 * Meter that tracks usage for a metered price. Create-only.
55 */
56 meter?: string;
57 /**
58 * Default trial length (days) when subscribing with
59 * `trial_from_plan=true`. Create-only.
60 */
61 trialPeriodDays?: number;
62 }
63
64 export interface PriceProps {
65 /**
66 * Stripe Product this price belongs to — the resource, or a `prod_…`
67 * id. Create-only — changing it replaces the price.
68 */
69 product: string | Product;
70 /**
71 * Three-letter ISO currency code, lowercase (e.g. `"usd"`). Create-only
72 * — changing it replaces the price.
73 */
74 currency: string;
75 /**
76 * Amount in the currency's minor units (e.g. cents). Required unless
77 * `unitAmountDecimal` is set or the price is tiered. Create-only —
78 * changing it replaces the price.
79 */
80 unitAmount?: number;
81 /**
82 * Decimal amount in the currency's minor units, at most 12 decimal
83 * places. Mutually exclusive with `unitAmount`. Create-only.
84 */
85 unitAmountDecimal?: string;
86 /**
87 * Recurring billing configuration. Omit for a one-time price.
88 * Create-only — changing it replaces the price.
89 */
90 recurring?: PriceRecurring;
91 /**
92 * Brief description of the price, hidden from customers.
93 */
94 nickname?: string;
95 /**
96 * Whether the price can be used for new purchases.
97 * @default true
98 */
99 active?: boolean;
100 /**
101 * Lookup key used to retrieve this price from a static string (max 200
102 * characters).
103 */
104 lookupKey?: string;
105 /**
106 * User-defined metadata. Alchemy ownership keys (`alchemy_stack` /
107 * `alchemy_stage` / `alchemy_id`) are merged in automatically. Keys may
108 * not contain `:`.
109 */
110 metadata?: Record<string, string>;
111 }
112
113 export type Price = Resource<
114 "Stripe.Price",
115 PriceProps,
116 {
117 /** Stripe price id (`price_…`). */
118 id: string;
119 /** Id of the product this price belongs to. */
120 product: string;
121 /** Three-letter ISO currency code. */
122 currency: string;
123 /** Amount in the currency's minor units, or `undefined` when unset. */
124 unitAmount: number | undefined;
125 /** Decimal amount in the currency's minor units, or `undefined`. */
126 unitAmountDecimal: string | undefined;
127 /** Whether the price can be used for new purchases. */
128 active: boolean;
129 /** Brief description of the price, hidden from customers. */
130 nickname: string | undefined;
131 /** Lookup key, if set. */
132 lookupKey: string | undefined;
133 /** `one_time` or `recurring`. */
134 type: PriceType;
135 /** Recurring billing configuration, if this is a recurring price. */
136 recurring: PriceRecurring | undefined;
137 /** User-defined metadata (Alchemy ownership keys stripped). */
138 metadata: Record<string, string>;
139 /** Unix timestamp when the price was created. */
140 created: number;
141 /** Whether the price exists in live mode. */
142 livemode: boolean;
143 },
144 never,
145 Providers
146 >;
147
148 /**
149 * A Stripe Price — the unit cost attached to a Product. Currency, amount,
150 * product, and recurring interval are immutable (changing them replaces
151 * the price). Nickname, metadata, lookup key, and `active` update in
152 * place. Prices cannot be deleted; destroy deactivates them
153 * (`active=false`).
154 *
155 * @see https://docs.stripe.com/api/prices
156 *
157 * ### Creating a Price
158 * **Example:** One-time price
159 * ```typescript
160 * const product = yield* Stripe.Product("pro-plan", { name: "Pro Plan" });
161 * const price = yield* Stripe.Price("pro-once", {
162 * product,
163 * currency: "usd",
164 * unitAmount: 2000,
165 * });
166 * ```
167 *
168 * **Example:** Recurring monthly price
169 * ```typescript
170 * const price = yield* Stripe.Price("pro-monthly", {
171 * product,
172 * currency: "usd",
173 * unitAmount: 1500,
174 * recurring: { interval: "month" },
175 * nickname: "Pro monthly",
176 * });
177 * ```
178 *
179 * ### Updating a Price
180 * **Example:** Nickname, metadata, and deactivate
181 * ```typescript
182 * const price = yield* Stripe.Price("pro-monthly", {
183 * product,
184 * currency: "usd",
185 * unitAmount: 1500,
186 * recurring: { interval: "month" },
187 * nickname: "Pro monthly (paused)",
188 * active: false,
189 * metadata: { tier: "pro" },
190 * });
191 * ```
192 *
193 * ### Destroying a Price
194 * **Example:** Deactivate instead of delete
195 * ```typescript
196 * // Stripe cannot delete a used price. `alchemy destroy` sets
197 * // `active: false`.
198 * ```
199 *
200 * @resource
201 * @product Product
202 */
203 export const Price = Resource<Price>("Stripe.Price");
204
205 export class PriceNotResolved extends Data.TaggedError("Stripe.PriceNotResolved")<{
206 product: string;
207 currency: string;
208 }> {}
209
210 const userMetadata = (
211 metadata: Record<string, string | undefined> | null | undefined,
212 ): Record<string, string> => stripInternalMetadata(tagRecord(metadata));
213
214 const productIdOf = (product: PriceProduct): string => {
215 if (typeof product === "string") return product;
216 return product.id;
217 };
218
219 const alchemyProductId = (product: string | Product): string => {
220 if (typeof product === "string") return product;
221 const id = product.id as unknown;
222 if (typeof id === "string") return id;
223 return String(id);
224 };
225
226 const toRecurring = (recurring: StripePrice["recurring"]): PriceRecurring | undefined => {
227 if (recurring == null) return undefined;
228 return {
229 interval: recurring.interval as PriceInterval,
230 intervalCount: recurring.interval_count,
231 usageType: recurring.usage_type as PriceUsageType,
232 ...(recurring.meter != null ? { meter: recurring.meter } : {}),
233 ...(recurring.trial_period_days != null
234 ? { trialPeriodDays: recurring.trial_period_days }
235 : {}),
236 };
237 };
238
239 const toAttrs = (price: StripePrice) => ({
240 id: price.id,
241 product: productIdOf(price.product),
242 currency: price.currency,
243 unitAmount: price.unit_amount ?? undefined,
244 unitAmountDecimal: price.unit_amount_decimal ?? undefined,
245 active: price.active,
246 nickname: price.nickname ?? undefined,
247 lookupKey: price.lookup_key ?? undefined,
248 type: price.type as PriceType,
249 recurring: toRecurring(price.recurring),
250 metadata: userMetadata(price.metadata),
251 created: price.created,
252 livemode: price.livemode,
253 });
254
255 const isMissingPrice = isMissingStripeResource;
256
257 const getById = (price: string) =>
258 GetPrice({ price }).pipe(Effect.catchIf(isMissingPrice, () => Effect.undefined));
259
260 const listByActive = Effect.fn(function* (active: boolean) {
261 const prices: StripePrice[] = [];
262 let startingAfter: string | undefined;
263 for (let page = 0; page < LIST_MAX_PAGES; page++) {
264 const response = yield* GetPrices({
265 active,
266 limit: LIST_PAGE_SIZE,
267 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
268 });
269 prices.push(...response.data);
270 if (!response.has_more || response.data.length === 0) {
271 break;
272 }
273 startingAfter = response.data[response.data.length - 1]?.id;
274 if (startingAfter === undefined) {
275 break;
276 }
277 }
278 return prices;
279 });
280
281 const listAllPrices = Effect.fn(function* () {
282 const [active, inactive] = yield* Effect.all([listByActive(true), listByActive(false)], {
283 concurrency: 2,
284 });
285 const seen = new Set<string>();
286 const prices: StripePrice[] = [];
287 for (const price of [...active, ...inactive]) {
288 if (seen.has(price.id)) continue;
289 seen.add(price.id);
290 prices.push(price);
291 }
292 return prices;
293 });
294
295 const findByAlchemyId = Effect.fn(function* (id: string) {
296 const prices = yield* listAllPrices();
297 const matches: StripePrice[] = [];
298 for (const price of prices) {
299 if (yield* hasAlchemyMetadata(id, tagRecord(price.metadata))) {
300 matches.push(price);
301 }
302 }
303 matches.sort((a, b) => b.created - a.created);
304 return matches[0];
305 });
306
307 const observe = Effect.fn(function* (input: { id?: string; logicalId: string }) {
308 if (input.id !== undefined) {
309 const byId = yield* getById(input.id);
310 if (byId !== undefined) return byId;
311 }
312 return yield* findByAlchemyId(input.logicalId);
313 });
314
315 const desiredMetadata = Effect.fn(function* (
316 id: string,
317 metadata: Record<string, string> | undefined,
318 ) {
319 return {
320 ...toMetadata(metadata),
321 ...(yield* createInternalMetadata(id)),
322 };
323 });
324
325 const recurringEqual = (
326 news: PriceRecurring | undefined,
327 observed: PriceRecurring | undefined,
328 ): boolean => {
329 if (news === undefined) return true;
330 if (observed === undefined) return false;
331 if (news.interval !== observed.interval) return false;
332 if ((news.intervalCount ?? 1) !== (observed.intervalCount ?? 1)) return false;
333 if ((news.usageType ?? "licensed") !== (observed.usageType ?? "licensed")) {
334 return false;
335 }
336 if ((news.meter ?? undefined) !== (observed.meter ?? undefined)) return false;
337 if ((news.trialPeriodDays ?? undefined) !== (observed.trialPeriodDays ?? undefined)) {
338 return false;
339 }
340 return true;
341 };
342
343 const shouldReplace = (news: PriceProps, output: Price["Attributes"] | undefined) => {
344 if (output === undefined) return false;
345 if (alchemyProductId(news.product) !== output.product) return true;
346 if (news.currency !== output.currency) return true;
347 if (news.unitAmount !== undefined && news.unitAmount !== output.unitAmount) {
348 return true;
349 }
350 if (news.unitAmountDecimal !== undefined && news.unitAmountDecimal !== output.unitAmountDecimal) {
351 return true;
352 }
353 if (!recurringEqual(news.recurring, output.recurring)) return true;
354 return false;
355 };
356
357 export const PriceProvider = () =>
358 Provider.succeed(Price, {
359 stables: ["id", "product", "currency", "type", "created", "livemode"],
360
361 diff: Effect.fn(function* ({ news, output }) {
362 if (!isResolved(news)) return undefined;
363 if (shouldReplace(news, output)) {
364 return { action: "replace" } as const;
365 }
366 return undefined;
367 }),
368
369 read: Effect.fn(function* ({ id, output }) {
370 const existing = yield* observe({
371 id: output?.id,
372 logicalId: id,
373 });
374 if (existing === undefined) return undefined;
375 const attrs = toAttrs(existing);
376 return (yield* hasAlchemyMetadata(id, tagRecord(existing.metadata))) ? attrs : Unowned(attrs);
377 }),
378
379 list: Effect.fn(function* () {
380 // Default list API is active prices; inactive (deactivated) rows
381 // stay in Stripe but must not re-enter nuke. Filter to alchemy_stack
382 // so account-wide teardown only touches our rows.
383 const prices = yield* listByActive(true);
384 return prices
385 .filter((price) => {
386 const metadata = tagRecord(price.metadata);
387 return metadata[alchemyMetadataKeys.stack] !== undefined;
388 })
389 .map(toAttrs);
390 }),
391
392 reconcile: Effect.fn(function* ({ id, news, output, instanceId }) {
393 const metadata = yield* desiredMetadata(id, news.metadata);
394 const desiredActive = news.active ?? true;
395 const desiredNickname = news.nickname ?? "";
396 const desiredLookupKey = news.lookupKey ?? "";
397
398 let current: StripePrice | undefined = yield* observe({
399 id: output?.id,
400 logicalId: id,
401 });
402 // A previous generation (same logical id, different immutable
403 // fields) must not be reused — Stripe prices cannot change amount,
404 // currency, product, or recurring interval.
405 if (current !== undefined && shouldReplace(news, toAttrs(current))) {
406 current = undefined;
407 }
408
409 if (current === undefined) {
410 current = yield* CreatePrice({
411 product: alchemyProductId(news.product),
412 currency: news.currency,
413 active: desiredActive,
414 metadata,
415 ...(news.unitAmount !== undefined ? { unit_amount: news.unitAmount } : {}),
416 ...(news.unitAmountDecimal !== undefined
417 ? { unit_amount_decimal: news.unitAmountDecimal }
418 : {}),
419 ...(news.recurring !== undefined
420 ? {
421 recurring: {
422 interval: news.recurring.interval,
423 ...(news.recurring.intervalCount !== undefined
424 ? { interval_count: news.recurring.intervalCount }
425 : {}),
426 ...(news.recurring.usageType !== undefined
427 ? { usage_type: news.recurring.usageType }
428 : {}),
429 ...(news.recurring.meter !== undefined ? { meter: news.recurring.meter } : {}),
430 ...(news.recurring.trialPeriodDays !== undefined
431 ? { trial_period_days: news.recurring.trialPeriodDays }
432 : {}),
433 },
434 }
435 : {}),
436 ...(desiredNickname.length > 0 ? { nickname: desiredNickname } : {}),
437 ...(desiredLookupKey.length > 0
438 ? { lookup_key: desiredLookupKey, transfer_lookup_key: true }
439 : {}),
440 }).pipe(
441 withRequestOptions({
442 idempotencyKey: `alchemy-price-${instanceId}`,
443 }),
444 );
445 }
446
447 if (current === undefined) {
448 return yield* new PriceNotResolved({
449 product: alchemyProductId(news.product),
450 currency: news.currency,
451 });
452 }
453
454 const observedMetadata = tagRecord(current.metadata);
455 const { upsert, removed } = diffMetadata(observedMetadata, metadata);
456 const metadataChanged = upsert.length > 0 || removed.length > 0;
457 const activeChanged = current.active !== desiredActive;
458 const nicknameChanged = (current.nickname ?? "") !== desiredNickname;
459 const lookupKeyChanged = (current.lookup_key ?? "") !== desiredLookupKey;
460
461 if (!activeChanged && !nicknameChanged && !lookupKeyChanged && !metadataChanged) {
462 return toAttrs(current);
463 }
464
465 const updated = yield* UpdatePrice({
466 price: current.id,
467 ...(activeChanged ? { active: desiredActive } : {}),
468 ...(nicknameChanged ? { nickname: desiredNickname } : {}),
469 ...(lookupKeyChanged ? { lookup_key: desiredLookupKey, transfer_lookup_key: true } : {}),
470 ...(metadataChanged
471 ? {
472 metadata: {
473 ...Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value])),
474 ...Object.fromEntries(removed.map((key) => [key, ""])),
475 },
476 }
477 : {}),
478 });
479 return toAttrs(updated);
480 }),
481
482 delete: Effect.fn(function* ({ output }) {
483 const existing = yield* getById(output.id);
484 if (existing === undefined || !existing.active) return;
485 yield* UpdatePrice({
486 price: existing.id,
487 active: false,
488 }).pipe(Effect.catchIf(isMissingPrice, () => Effect.void));
489 }),
490 });