@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 363 lines 11.4 KB
Raw
1 import { withRequestOptions } from "@distilled.cloud/stripe";
2 import {
3 GetEntitlementsFeatures,
4 GetEntitlementsFeature,
5 CreateEntitlementsFeature,
6 UpdateEntitlementsFeature,
7 type EntitlementsFeature as StripeEntitlementsFeature,
8 } from "@distilled.cloud/stripe/stripe";
9 import { Unowned } from "alchemy/AdoptPolicy";
10 import { isResolved } from "alchemy/Diff";
11 import { createPhysicalName } from "alchemy/PhysicalName";
12 import * as Provider from "alchemy/Provider";
13 import { Resource } from "alchemy/Resource";
14 import { tagRecord } from "alchemy/Tags";
15 import * as Effect from "effect/Effect";
16 import {
17 alchemyMetadataKeys,
18 createInternalMetadata,
19 diffMetadata,
20 hasAlchemyMetadata,
21 stripInternalMetadata,
22 toMetadata,
23 } from "./Metadata.ts";
24 import { isMissingStripeResource } from "./missing.ts";
25 import type { Providers } from "./Providers.ts";
26
27 const NAME_MAX_LENGTH = 80;
28 const LOOKUP_KEY_MAX_LENGTH = 80;
29 const LIST_PAGE_SIZE = 100;
30 const LIST_MAX_PAGES = 100;
31
32 export interface EntitlementsFeatureProps {
33 /**
34 * Unique system identifier for this feature (max 80 characters). If
35 * omitted, a unique key is generated from the stack, stage, and logical
36 * id. Create-only — changing it replaces the feature.
37 */
38 lookupKey?: string;
39 /**
40 * Feature name for your own purpose, not shown to customers (max 80
41 * characters). If omitted, a unique name is generated from the stack,
42 * stage, and logical id. Mutable.
43 */
44 name?: string;
45 /**
46 * Whether the feature can be attached to new products. Inactive
47 * (archived) features are omitted from the default list endpoint.
48 * @default true
49 */
50 active?: boolean;
51 /**
52 * User-defined metadata. Alchemy ownership keys (`alchemy_stack` /
53 * `alchemy_stage` / `alchemy_id`) are merged in automatically. Keys may
54 * not contain `:`. Mutable.
55 */
56 metadata?: Record<string, string>;
57 }
58
59 export type EntitlementsFeature = Resource<
60 "Stripe.EntitlementsFeature",
61 EntitlementsFeatureProps,
62 {
63 /** Stripe feature id (`feat_…`). */
64 id: string;
65 /** Unique system identifier for this feature. */
66 lookupKey: string;
67 /** Feature name for your own purpose, not shown to customers. */
68 name: string;
69 /** Whether the feature can be attached to new products. */
70 active: boolean;
71 /** User-defined metadata (Alchemy ownership keys stripped). */
72 metadata: Record<string, string>;
73 /** Whether the feature exists in live mode. */
74 livemode: boolean;
75 },
76 never,
77 Providers
78 >;
79
80 /**
81 * A Stripe Entitlements Feature — a monetizable ability you attach to
82 * Products. When a customer purchases a product with this feature, Stripe
83 * creates an entitlement for them. `lookup_key` is unique among active
84 * features and immutable (changing it replaces the feature). Name and
85 * metadata update in place.
86 *
87 * Stripe does not hard-delete features; destroying this resource
88 * deactivates it (`active: false`). Archived features cannot be edited
89 * or unarchived. An archived lookup key can be reused — a later create
90 * with the same key provisions a new feature.
91 *
92 * @see https://docs.stripe.com/api/entitlements/feature
93 *
94 * ### Creating a Feature
95 * **Example:** Generated lookup key
96 * ```typescript
97 * const seats = yield* Stripe.EntitlementsFeature("seats");
98 * ```
99 *
100 * **Example:** Named feature with lookup key
101 * ```typescript
102 * const seats = yield* Stripe.EntitlementsFeature("seats", {
103 * lookupKey: "seats",
104 * name: "Seat licenses",
105 * });
106 * ```
107 *
108 * ### Updating a Feature
109 * **Example:** Rename and retag
110 * ```typescript
111 * const seats = yield* Stripe.EntitlementsFeature("seats", {
112 * lookupKey: "seats",
113 * name: "Seat licenses (updated)",
114 * metadata: { plan: "pro" },
115 * });
116 * ```
117 *
118 * ### Deactivating a Feature
119 * **Example:** Destroy deactivates rather than deleting
120 * ```typescript
121 * // stack.destroy() / resource removal sets active: false
122 * const seats = yield* Stripe.EntitlementsFeature("seats", {
123 * lookupKey: "seats",
124 * name: "Seat licenses",
125 * });
126 * ```
127 *
128 * @resource
129 * @product Entitlements
130 */
131 export const EntitlementsFeature = Resource<EntitlementsFeature>("Stripe.EntitlementsFeature");
132
133 type EntitlementsFeatureAttributes = EntitlementsFeature["Attributes"];
134
135 const userMetadata = (
136 metadata: Record<string, string | undefined> | null | undefined,
137 ): Record<string, string> => stripInternalMetadata(tagRecord(metadata));
138
139 const toName = (id: string, name: string | undefined, existing?: string) =>
140 Effect.gen(function* () {
141 return name ?? existing ?? (yield* createPhysicalName({ id, maxLength: NAME_MAX_LENGTH }));
142 });
143
144 const toLookupKey = (id: string, lookupKey: string | undefined, existing?: string) =>
145 Effect.gen(function* () {
146 return (
147 lookupKey ??
148 existing ??
149 (yield* createPhysicalName({
150 id,
151 maxLength: LOOKUP_KEY_MAX_LENGTH,
152 lowercase: true,
153 }))
154 );
155 });
156
157 const toAttrs = (feature: StripeEntitlementsFeature): EntitlementsFeatureAttributes => ({
158 id: feature.id,
159 lookupKey: feature.lookup_key,
160 name: feature.name,
161 active: feature.active,
162 metadata: userMetadata(feature.metadata),
163 livemode: feature.livemode,
164 });
165
166 const isMissingFeature = isMissingStripeResource;
167
168 const getById = (id: string) =>
169 GetEntitlementsFeature({ id }).pipe(Effect.catchIf(isMissingFeature, () => Effect.undefined));
170
171 const listByArchived = Effect.fn(function* (archived: boolean) {
172 const features: StripeEntitlementsFeature[] = [];
173 let startingAfter: string | undefined;
174 for (let page = 0; page < LIST_MAX_PAGES; page++) {
175 const response = yield* GetEntitlementsFeatures({
176 archived,
177 limit: LIST_PAGE_SIZE,
178 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
179 });
180 features.push(...response.data);
181 if (!response.has_more || response.data.length === 0) {
182 break;
183 }
184 startingAfter = response.data[response.data.length - 1]?.id;
185 if (startingAfter === undefined) {
186 break;
187 }
188 }
189 return features;
190 });
191
192 const findByLookupKey = Effect.fn(function* (lookupKey: string) {
193 // Archived features cannot be updated or unarchived. Their lookup keys
194 // are reusable, so observation must ignore them and let ensure create.
195 const active = yield* GetEntitlementsFeatures({
196 lookup_key: lookupKey,
197 archived: false,
198 limit: LIST_PAGE_SIZE,
199 });
200 return active.data[0];
201 });
202
203 const findByAlchemyId = Effect.fn(function* (id: string) {
204 const features = yield* listByArchived(false);
205 const matches: StripeEntitlementsFeature[] = [];
206 for (const feature of features) {
207 if (yield* hasAlchemyMetadata(id, tagRecord(feature.metadata))) {
208 matches.push(feature);
209 }
210 }
211 matches.sort((a, b) => (a.id < b.id ? 1 : a.id > b.id ? -1 : 0));
212 return matches[0];
213 });
214
215 const observe = Effect.fn(function* (input: {
216 id?: string;
217 logicalId: string;
218 lookupKey?: string;
219 }) {
220 if (input.id !== undefined) {
221 const byId = yield* getById(input.id);
222 if (byId !== undefined) return byId;
223 }
224 if (input.lookupKey !== undefined) {
225 const byKey = yield* findByLookupKey(input.lookupKey);
226 if (
227 byKey !== undefined &&
228 (yield* hasAlchemyMetadata(input.logicalId, tagRecord(byKey.metadata)))
229 ) {
230 return byKey;
231 }
232 }
233 return yield* findByAlchemyId(input.logicalId);
234 });
235
236 const desiredMetadata = Effect.fn(function* (
237 id: string,
238 metadata: Record<string, string> | undefined,
239 ) {
240 return {
241 ...toMetadata(metadata),
242 ...(yield* createInternalMetadata(id)),
243 };
244 });
245
246 const shouldReplace = (
247 news: EntitlementsFeatureProps,
248 output: EntitlementsFeatureAttributes | undefined,
249 ): boolean => {
250 if (output === undefined) return false;
251 if (news.lookupKey !== undefined && news.lookupKey !== output.lookupKey) {
252 return true;
253 }
254 return false;
255 };
256
257 export const EntitlementsFeatureProvider = () =>
258 Provider.succeed(EntitlementsFeature, {
259 stables: ["id", "lookupKey", "livemode"],
260
261 diff: Effect.fn(function* ({ news, output }) {
262 if (!isResolved(news)) return undefined;
263 if (shouldReplace(news, output)) {
264 return { action: "replace" } as const;
265 }
266 return undefined;
267 }),
268
269 read: Effect.fn(function* ({ id, output }) {
270 const existing = yield* observe({
271 id: output?.id,
272 logicalId: id,
273 lookupKey: output?.lookupKey,
274 });
275 if (existing === undefined) return undefined;
276 const attrs = toAttrs(existing);
277 return (yield* hasAlchemyMetadata(id, tagRecord(existing.metadata))) ? attrs : Unowned(attrs);
278 }),
279
280 list: Effect.fn(function* () {
281 // Default list API is active features; archived (deactivated) rows
282 // stay in Stripe but must not re-enter nuke. Filter to alchemy_stack
283 // so account-wide teardown only touches our rows.
284 const features = yield* listByArchived(false);
285 return features
286 .filter((feature) => {
287 const metadata = tagRecord(feature.metadata);
288 return metadata[alchemyMetadataKeys.stack] !== undefined;
289 })
290 .map(toAttrs);
291 }),
292
293 reconcile: Effect.fn(function* ({ id, news, output, instanceId }) {
294 const lookupKey = yield* toLookupKey(id, news.lookupKey, output?.lookupKey);
295 const name = yield* toName(id, news.name, output?.name);
296 const metadata = yield* desiredMetadata(id, news.metadata);
297 const desiredActive = news.active ?? true;
298
299 let current: StripeEntitlementsFeature | undefined = yield* observe({
300 id: output?.id,
301 logicalId: id,
302 lookupKey,
303 });
304 if (current !== undefined && shouldReplace(news, toAttrs(current))) {
305 current = undefined;
306 }
307 // Stripe rejects updates to archived features and cannot unarchive
308 // them. Treat inactive rows as missing so ensure creates a new one
309 // (lookup keys become reusable once archived).
310 if (current !== undefined && current.active === false) {
311 if (desiredActive === false) {
312 return toAttrs(current);
313 }
314 current = undefined;
315 }
316
317 if (current === undefined) {
318 current = yield* CreateEntitlementsFeature({
319 lookup_key: lookupKey,
320 name,
321 metadata,
322 }).pipe(
323 withRequestOptions({
324 idempotencyKey: `alchemy-entitlements-feature-${instanceId}`,
325 }),
326 );
327 }
328
329 const observedMetadata = tagRecord(current.metadata);
330 const { upsert, removed } = diffMetadata(observedMetadata, metadata);
331 const metadataChanged = upsert.length > 0 || removed.length > 0;
332 const nameChanged = current.name !== name;
333 const activeChanged = current.active !== desiredActive;
334
335 if (!nameChanged && !activeChanged && !metadataChanged) {
336 return toAttrs(current);
337 }
338
339 const updated = yield* UpdateEntitlementsFeature({
340 id: current.id,
341 ...(nameChanged ? { name } : {}),
342 ...(activeChanged ? { active: desiredActive } : {}),
343 ...(metadataChanged
344 ? {
345 metadata: {
346 ...Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value])),
347 ...Object.fromEntries(removed.map((key) => [key, ""])),
348 },
349 }
350 : {}),
351 });
352 return toAttrs(updated);
353 }),
354
355 delete: Effect.fn(function* ({ output }) {
356 const existing = yield* getById(output.id);
357 if (existing === undefined || !existing.active) return;
358 yield* UpdateEntitlementsFeature({
359 id: existing.id,
360 active: false,
361 }).pipe(Effect.catchIf(isMissingFeature, () => Effect.void));
362 }),
363 });