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

main
ts 324 lines 9.85 KB
Raw
1 import { withRequestOptions } from "@distilled.cloud/stripe";
2 import {
3 DeleteProduct,
4 GetProducts,
5 GetProduct,
6 CreateProduct,
7 UpdateProduct,
8 type Product as StripeProduct,
9 } from "@distilled.cloud/stripe/stripe";
10 import { Unowned } from "alchemy/AdoptPolicy";
11 import { isResolved } from "alchemy/Diff";
12 import { createPhysicalName } from "alchemy/PhysicalName";
13 import * as Provider from "alchemy/Provider";
14 import { Resource } from "alchemy/Resource";
15 import { tagRecord } from "alchemy/Tags";
16 import { arrayEquals } from "alchemy/Util/equal";
17 import * as Effect from "effect/Effect";
18 import {
19 alchemyMetadataKeys,
20 createInternalMetadata,
21 diffMetadata,
22 hasAlchemyMetadata,
23 stripInternalMetadata,
24 toMetadata,
25 } from "./Metadata.ts";
26 import { isMissingStripeResource } from "./missing.ts";
27 import type { Providers } from "./Providers.ts";
28
29 const NAME_MAX_LENGTH = 250;
30 const LIST_PAGE_SIZE = 100;
31 const LIST_MAX_PAGES = 100;
32
33 export interface ProductProps {
34 /**
35 * Display name of the product. If omitted, a unique name is generated
36 * from the stack, stage, and logical id.
37 */
38 name?: string;
39 /**
40 * Description meant to be displayable to the customer.
41 */
42 description?: string;
43 /**
44 * Whether the product is available for purchase.
45 * @default true
46 */
47 active?: boolean;
48 /**
49 * Up to 8 image URLs meant to be displayable to the customer.
50 */
51 images?: string[];
52 /**
53 * User-defined metadata. Alchemy ownership keys (`alchemy_stack` /
54 * `alchemy_stage` / `alchemy_id`) are merged in automatically. Keys may
55 * not contain `:`.
56 */
57 metadata?: Record<string, string>;
58 }
59
60 export type Product = Resource<
61 "Stripe.Product",
62 ProductProps,
63 {
64 /** Stripe product id (`prod_…`). */
65 id: string;
66 /** Display name of the product. */
67 name: string;
68 /** Description meant to be displayable to the customer. */
69 description: string | undefined;
70 /** Whether the product is available for purchase. */
71 active: boolean;
72 /** Image URLs meant to be displayable to the customer. */
73 images: string[];
74 /** User-defined metadata (Alchemy ownership keys stripped). */
75 metadata: Record<string, string>;
76 /** Unix timestamp when the product was created. */
77 created: number;
78 /** Whether the product exists in live mode. */
79 livemode: boolean;
80 },
81 never,
82 Providers
83 >;
84
85 /**
86 * A Stripe Product — the catalog item that Prices, invoices, and Checkout
87 * attach to. Name, description, active, images, and metadata are updated
88 * in place. Deleting a product is only possible when it has no Prices.
89 *
90 * @see https://docs.stripe.com/api/products
91 *
92 * ### Creating a Product
93 * **Example:** Generated name
94 * ```typescript
95 * const product = yield* Stripe.Product("pro-plan");
96 * ```
97 *
98 * **Example:** Named product with description
99 * ```typescript
100 * const product = yield* Stripe.Product("pro-plan", {
101 * name: "Pro Plan",
102 * description: "Billed monthly",
103 * });
104 * ```
105 *
106 * ### Catalog details
107 * **Example:** Images, metadata, and inactive product
108 * ```typescript
109 * const product = yield* Stripe.Product("pro-plan", {
110 * name: "Pro Plan",
111 * description: "Billed monthly",
112 * active: false,
113 * images: ["https://example.com/pro.png"],
114 * metadata: { tier: "pro" },
115 * });
116 * ```
117 *
118 * ### Destroying a Product
119 * **Example:** Delete when it has no prices
120 * ```typescript
121 * // alchemy destroy deletes the Product. If prices remain, Stripe
122 * // rejects the delete and Alchemy archives it (`active: false`).
123 * ```
124 *
125 * @resource
126 * @product Product
127 */
128 export const Product = Resource<Product>("Stripe.Product");
129
130 const userMetadata = (
131 metadata: Record<string, string | undefined> | null | undefined,
132 ): Record<string, string> => stripInternalMetadata(tagRecord(metadata));
133
134 const toName = (id: string, name: string | undefined, existing?: string) =>
135 Effect.gen(function* () {
136 return name ?? existing ?? (yield* createPhysicalName({ id, maxLength: NAME_MAX_LENGTH }));
137 });
138
139 const toAttrs = (product: StripeProduct) => ({
140 id: product.id,
141 name: product.name,
142 description: product.description ?? undefined,
143 active: product.active,
144 images: product.images,
145 metadata: userMetadata(product.metadata),
146 created: product.created,
147 livemode: product.livemode,
148 });
149
150 const isMissingProduct = isMissingStripeResource;
151
152 const getById = (id: string) =>
153 GetProduct({ id }).pipe(Effect.catchIf(isMissingProduct, () => Effect.undefined));
154
155 const listByActive = Effect.fn(function* (active: boolean) {
156 const products: StripeProduct[] = [];
157 let startingAfter: string | undefined;
158 for (let page = 0; page < LIST_MAX_PAGES; page++) {
159 const response = yield* GetProducts({
160 active,
161 limit: LIST_PAGE_SIZE,
162 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
163 });
164 products.push(...response.data);
165 if (!response.has_more || response.data.length === 0) {
166 break;
167 }
168 startingAfter = response.data[response.data.length - 1]?.id;
169 if (startingAfter === undefined) {
170 break;
171 }
172 }
173 return products;
174 });
175
176 const listAllProducts = Effect.fn(function* () {
177 const [active, inactive] = yield* Effect.all([listByActive(true), listByActive(false)], {
178 concurrency: 2,
179 });
180 const seen = new Set<string>();
181 const products: StripeProduct[] = [];
182 for (const product of [...active, ...inactive]) {
183 if (seen.has(product.id)) continue;
184 seen.add(product.id);
185 products.push(product);
186 }
187 return products;
188 });
189
190 const findByAlchemyId = Effect.fn(function* (id: string) {
191 const products = yield* listAllProducts();
192 const matches: StripeProduct[] = [];
193 for (const product of products) {
194 if (yield* hasAlchemyMetadata(id, tagRecord(product.metadata))) {
195 matches.push(product);
196 }
197 }
198 matches.sort((a, b) => b.created - a.created);
199 return matches[0];
200 });
201
202 const observe = Effect.fn(function* (input: { id?: string; logicalId: string }) {
203 if (input.id !== undefined) {
204 const byId = yield* getById(input.id);
205 if (byId !== undefined) return byId;
206 }
207 return yield* findByAlchemyId(input.logicalId);
208 });
209
210 const desiredMetadata = Effect.fn(function* (
211 id: string,
212 metadata: Record<string, string> | undefined,
213 ) {
214 return {
215 ...toMetadata(metadata),
216 ...(yield* createInternalMetadata(id)),
217 };
218 });
219
220 export const ProductProvider = () =>
221 Provider.succeed(Product, {
222 stables: ["id", "created", "livemode"],
223
224 diff: Effect.fn(function* ({ news }) {
225 if (!isResolved(news)) return undefined;
226 return undefined;
227 }),
228
229 read: Effect.fn(function* ({ id, output }) {
230 const existing = yield* observe({
231 id: output?.id,
232 logicalId: id,
233 });
234 if (existing === undefined) return undefined;
235 const attrs = toAttrs(existing);
236 return (yield* hasAlchemyMetadata(id, tagRecord(existing.metadata))) ? attrs : Unowned(attrs);
237 }),
238
239 list: Effect.fn(function* () {
240 // Stripe cannot hard-delete a product that has prices; delete archives
241 // it (active: false). Archived rows are effectively deleted and must
242 // not re-enter nuke, so enumerate active products only.
243 const products = yield* listByActive(true);
244 return products
245 .filter((product) => {
246 const metadata = tagRecord(product.metadata);
247 return metadata[alchemyMetadataKeys.stack] !== undefined;
248 })
249 .map(toAttrs);
250 }),
251
252 reconcile: Effect.fn(function* ({ id, news, output, instanceId }) {
253 const name = yield* toName(id, news.name, output?.name);
254 const metadata = yield* desiredMetadata(id, news.metadata);
255 const desiredActive = news.active ?? true;
256 const desiredDescription = news.description ?? "";
257 const desiredImages = news.images ?? [];
258
259 let current = yield* observe({
260 id: output?.id,
261 logicalId: id,
262 });
263
264 if (current === undefined) {
265 current = yield* CreateProduct({
266 name,
267 active: desiredActive,
268 ...(desiredDescription.length > 0 ? { description: desiredDescription } : {}),
269 ...(desiredImages.length > 0 ? { images: desiredImages } : {}),
270 metadata,
271 }).pipe(
272 withRequestOptions({
273 idempotencyKey: `alchemy-product-${instanceId}`,
274 }),
275 );
276 }
277
278 const observedMetadata = tagRecord(current.metadata);
279 const { upsert, removed } = diffMetadata(observedMetadata, metadata);
280 const metadataChanged = upsert.length > 0 || removed.length > 0;
281 const nameChanged = current.name !== name;
282 const activeChanged = current.active !== desiredActive;
283 const descriptionChanged = (current.description ?? "") !== desiredDescription;
284 const imagesChanged = !arrayEquals(current.images, desiredImages);
285
286 if (
287 !nameChanged &&
288 !activeChanged &&
289 !descriptionChanged &&
290 !imagesChanged &&
291 !metadataChanged
292 ) {
293 return toAttrs(current);
294 }
295
296 const updated = yield* UpdateProduct({
297 id: current.id,
298 ...(nameChanged ? { name } : {}),
299 ...(activeChanged ? { active: desiredActive } : {}),
300 ...(descriptionChanged ? { description: desiredDescription } : {}),
301 ...(imagesChanged ? { images: desiredImages.length > 0 ? desiredImages : "" } : {}),
302 ...(metadataChanged
303 ? {
304 metadata: {
305 ...Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value])),
306 ...Object.fromEntries(removed.map((key) => [key, ""])),
307 },
308 }
309 : {}),
310 });
311 return toAttrs(updated);
312 }),
313
314 delete: Effect.fn(function* ({ output }) {
315 yield* DeleteProduct({ id: output.id }).pipe(
316 Effect.catchTag("ProductHasPrices", () =>
317 UpdateProduct({ id: output.id, active: false }).pipe(
318 Effect.catchIf(isMissingProduct, () => Effect.void),
319 ),
320 ),
321 Effect.catchIf(isMissingProduct, () => Effect.void),
322 );
323 }),
324 });