@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, 04:45 UTC

main
ts 670 lines 21.6 KB
Raw
1 import { withRequestOptions } from "@distilled.cloud/stripe";
2 import type { StripeOpError } from "@distilled.cloud/stripe";
3 import {
4 GetIssuingCards,
5 GetIssuingCard,
6 CreateIssuingCard,
7 UpdateIssuingCard,
8 type IssuingCard as StripeIssuingCard,
9 type CreateIssuingCardRequestSpendingControls,
10 } from "@distilled.cloud/stripe/stripe";
11 import { Unowned } from "alchemy/AdoptPolicy";
12 import { deepEqual, isResolved } from "alchemy/Diff";
13 import * as Provider from "alchemy/Provider";
14 import { Resource } from "alchemy/Resource";
15 import { tagRecord } from "alchemy/Tags";
16 import * as Data from "effect/Data";
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 LIST_PAGE_SIZE = 100;
30 const LIST_MAX_PAGES = 100;
31
32 /** Whether authorizations can be approved on this card. */
33 export type IssuingCardStatus = "active" | "canceled" | "inactive";
34
35 /** The type of Issuing card. Create-only — changing it replaces the card. */
36 export type IssuingCardType = "physical" | "virtual";
37
38 /** Why a previous card is being replaced. Create-only. */
39 export type IssuingCardReplacementReason = "damaged" | "expired" | "lost" | "stolen";
40
41 /** Card-present vs card-not-present authorization presence. */
42 export type IssuingCardPresence = "not_present" | "present";
43
44 /** Interval (or event) a spending limit applies to. */
45 export type IssuingCardSpendingLimitInterval =
46 | "all_time"
47 | "daily"
48 | "monthly"
49 | "per_authorization"
50 | "weekly"
51 | "yearly";
52
53 export interface IssuingCardSpendingLimit {
54 /**
55 * Maximum amount allowed to spend per interval, in the card's currency
56 * minor units.
57 */
58 amount: number;
59 /**
60 * Interval (or event) to which the amount applies.
61 */
62 interval: IssuingCardSpendingLimitInterval;
63 /**
64 * Merchant categories this limit applies to. Omit to apply to all
65 * categories.
66 */
67 categories?: string[];
68 }
69
70 export interface IssuingCardSpendingControls {
71 /**
72 * Card-presence statuses from which authorizations are allowed. Cannot
73 * be set with `blockedCardPresences`.
74 */
75 allowedCardPresences?: IssuingCardPresence[];
76 /**
77 * Merchant categories to allow. All other categories are blocked.
78 * Cannot be set with `blockedCategories`.
79 */
80 allowedCategories?: string[];
81 /**
82 * ISO 3166 alpha-2 countries from which authorizations are allowed.
83 * Cannot be set with `blockedMerchantCountries`.
84 */
85 allowedMerchantCountries?: string[];
86 /**
87 * Card-presence statuses from which authorizations are declined. Cannot
88 * be set with `allowedCardPresences`.
89 */
90 blockedCardPresences?: IssuingCardPresence[];
91 /**
92 * Merchant categories to decline. All other categories are allowed.
93 * Cannot be set with `allowedCategories`.
94 */
95 blockedCategories?: string[];
96 /**
97 * ISO 3166 alpha-2 countries from which authorizations are declined.
98 * Cannot be set with `allowedMerchantCountries`.
99 */
100 blockedMerchantCountries?: string[];
101 /**
102 * Amount-based spending limits that apply across this card and any
103 * cards it replaced.
104 */
105 spendingLimits?: IssuingCardSpendingLimit[];
106 }
107
108 export interface IssuingCardProps {
109 /**
110 * Id of the Issuing Cardholder this card is issued to (`ich_…`).
111 * Create-only — changing it replaces the card.
112 */
113 cardholder: string;
114 /**
115 * Three-letter ISO currency code, lowercase. Supported currencies are
116 * `usd` (US), `eur` (EU), and `gbp` (UK). Create-only — changing it
117 * replaces the card.
118 */
119 currency: string;
120 /**
121 * The type of card to issue.
122 * @default "virtual"
123 */
124 type?: IssuingCardType;
125 /**
126 * Whether authorizations can be approved on this card. Stripe defaults
127 * new cards to `inactive`. Destroying this resource cancels the card
128 * (`canceled`); canceled cards cannot be reactivated.
129 * @default "inactive"
130 */
131 status?: "active" | "inactive";
132 /**
133 * Second line printed on the card (max 24 characters). Create-only —
134 * changing it replaces the card.
135 */
136 secondLine?: string;
137 /**
138 * Desired expiration month (1–12) when specifying a custom expiration
139 * date. Create-only.
140 */
141 expMonth?: number;
142 /**
143 * Desired 4-digit expiration year when specifying a custom expiration
144 * date. Create-only.
145 */
146 expYear?: number;
147 /**
148 * Financial account id this card is attached to. Create-only —
149 * changing it replaces the card.
150 */
151 financialAccount?: string;
152 /**
153 * Personalization design id belonging to this card. Mutable.
154 */
155 personalizationDesign?: string;
156 /**
157 * Card this one replaces, if any. Create-only.
158 */
159 replacementFor?: string;
160 /**
161 * Why `replacementFor` is being replaced. Create-only.
162 */
163 replacementReason?: IssuingCardReplacementReason;
164 /**
165 * Rules that control spending for this card. Mutable.
166 */
167 spendingControls?: IssuingCardSpendingControls;
168 /**
169 * User-defined metadata. Alchemy ownership keys (`alchemy_stack` /
170 * `alchemy_stage` / `alchemy_id`) are merged in automatically. Keys may
171 * not contain `:`. Mutable.
172 */
173 metadata?: Record<string, string>;
174 }
175
176 export type IssuingCard = Resource<
177 "Stripe.IssuingCard",
178 IssuingCardProps,
179 {
180 /** Stripe Issuing card id (`ic_…`). */
181 id: string;
182 /** Id of the cardholder this card belongs to (`ich_…`). */
183 cardholder: string;
184 /** Three-letter ISO currency code. */
185 currency: string;
186 /** `virtual` or `physical`. */
187 type: IssuingCardType;
188 /** Whether authorizations can be approved on this card. */
189 status: IssuingCardStatus;
190 /** Card brand (e.g. `Visa`). */
191 brand: string;
192 /** Last 4 digits of the card number. */
193 last4: string;
194 /** Expiration month. */
195 expMonth: number;
196 /** Expiration year. */
197 expYear: number;
198 /** Second line printed on the card, if set. */
199 secondLine: string | undefined;
200 /** Financial account id, if attached. */
201 financialAccount: string | undefined;
202 /** Personalization design id, if set. */
203 personalizationDesign: string | undefined;
204 /** Card this one replaces, if any. */
205 replacementFor: string | undefined;
206 /** Why the previous card was replaced, if this is a replacement. */
207 replacementReason: IssuingCardReplacementReason | undefined;
208 /** Why the card was canceled, if canceled. */
209 cancellationReason: string | undefined;
210 /** Spending controls currently applied to this card. */
211 spendingControls: IssuingCardSpendingControls | undefined;
212 /** User-defined metadata (Alchemy ownership keys stripped). */
213 metadata: Record<string, string>;
214 /** Unix timestamp when the card was created. */
215 created: number;
216 /** Whether the card exists in live mode. */
217 livemode: boolean;
218 },
219 never,
220 Providers
221 >;
222
223 /**
224 * A Stripe Issuing Card — a virtual or physical card issued to a
225 * Cardholder. `cardholder`, `currency`, `type`, `secondLine`, and
226 * custom expiration are immutable (changing them replaces the card).
227 * Status, spending controls, personalization design, and metadata
228 * update in place.
229 *
230 * Cards cannot be hard-deleted; destroying this resource cancels the
231 * card (`status: canceled`). Canceled cards cannot be reactivated — a
232 * later create with the same logical id provisions a new card.
233 *
234 * Issuing must be enabled on the Stripe account.
235 *
236 * @see https://docs.stripe.com/api/issuing/cards
237 *
238 * ### Creating a Card
239 * **Example:** Virtual card
240 * ```typescript
241 * const card = yield* Stripe.IssuingCard("expense-card", {
242 * cardholder: cardholder.id,
243 * currency: "usd",
244 * type: "virtual",
245 * status: "inactive",
246 * });
247 * ```
248 *
249 * **Example:** Spending limits and metadata
250 * ```typescript
251 * const card = yield* Stripe.IssuingCard("expense-card", {
252 * cardholder: cardholder.id,
253 * currency: "usd",
254 * type: "virtual",
255 * status: "active",
256 * spendingControls: {
257 * spendingLimits: [{ amount: 50_000, interval: "monthly" }],
258 * },
259 * metadata: { team: "ops" },
260 * });
261 * ```
262 *
263 * ### Updating a Card
264 * **Example:** Freeze and retag
265 * ```typescript
266 * const card = yield* Stripe.IssuingCard("expense-card", {
267 * cardholder: cardholder.id,
268 * currency: "usd",
269 * type: "virtual",
270 * status: "inactive",
271 * metadata: { team: "ops", frozen: "true" },
272 * });
273 * ```
274 *
275 * ### Replacing a Card
276 * **Example:** Changing type replaces the card
277 * ```typescript
278 * const card = yield* Stripe.IssuingCard("expense-card", {
279 * cardholder: cardholder.id,
280 * currency: "usd",
281 * type: "physical",
282 * });
283 * ```
284 *
285 * @resource
286 * @product Issuing
287 */
288 export const IssuingCard = Resource<IssuingCard>("Stripe.IssuingCard");
289
290 export class IssuingCardNotResolved extends Data.TaggedError("Stripe.IssuingCardNotResolved")<{
291 cardholder: string;
292 currency: string;
293 }> {}
294
295 type IssuingCardAttributes = IssuingCard["Attributes"];
296
297 const userMetadata = (
298 metadata: Record<string, string | undefined> | null | undefined,
299 ): Record<string, string> => stripInternalMetadata(tagRecord(metadata));
300
301 const expandedId = (
302 value: string | { readonly id: string } | null | undefined,
303 ): string | undefined => {
304 if (value == null) return undefined;
305 if (typeof value === "string") return value;
306 return value.id;
307 };
308
309 const toSpendingControls = (
310 controls: StripeIssuingCard["spending_controls"] | null | undefined,
311 ): IssuingCardSpendingControls | undefined => {
312 if (controls == null) return undefined;
313 const spendingLimits = (controls.spending_limits ?? []).map((limit) => ({
314 amount: limit.amount,
315 interval: limit.interval as IssuingCardSpendingLimitInterval,
316 ...(limit.categories != null && limit.categories.length > 0
317 ? { categories: [...limit.categories] }
318 : {}),
319 }));
320 const result: IssuingCardSpendingControls = {
321 ...(controls.allowed_card_presences != null
322 ? {
323 allowedCardPresences: [...controls.allowed_card_presences] as IssuingCardPresence[],
324 }
325 : {}),
326 ...(controls.allowed_categories != null
327 ? { allowedCategories: [...controls.allowed_categories] }
328 : {}),
329 ...(controls.allowed_merchant_countries != null
330 ? { allowedMerchantCountries: [...controls.allowed_merchant_countries] }
331 : {}),
332 ...(controls.blocked_card_presences != null
333 ? {
334 blockedCardPresences: [...controls.blocked_card_presences] as IssuingCardPresence[],
335 }
336 : {}),
337 ...(controls.blocked_categories != null
338 ? { blockedCategories: [...controls.blocked_categories] }
339 : {}),
340 ...(controls.blocked_merchant_countries != null
341 ? { blockedMerchantCountries: [...controls.blocked_merchant_countries] }
342 : {}),
343 ...(spendingLimits.length > 0 ? { spendingLimits } : {}),
344 };
345 if (
346 result.allowedCardPresences === undefined &&
347 result.allowedCategories === undefined &&
348 result.allowedMerchantCountries === undefined &&
349 result.blockedCardPresences === undefined &&
350 result.blockedCategories === undefined &&
351 result.blockedMerchantCountries === undefined &&
352 result.spendingLimits === undefined
353 ) {
354 return undefined;
355 }
356 return result;
357 };
358
359 const toWireSpendingControls = (
360 controls: IssuingCardSpendingControls,
361 ): CreateIssuingCardRequestSpendingControls => ({
362 ...(controls.allowedCardPresences !== undefined
363 ? { allowed_card_presences: controls.allowedCardPresences }
364 : {}),
365 ...(controls.allowedCategories !== undefined
366 ? { allowed_categories: controls.allowedCategories }
367 : {}),
368 ...(controls.allowedMerchantCountries !== undefined
369 ? { allowed_merchant_countries: controls.allowedMerchantCountries }
370 : {}),
371 ...(controls.blockedCardPresences !== undefined
372 ? { blocked_card_presences: controls.blockedCardPresences }
373 : {}),
374 ...(controls.blockedCategories !== undefined
375 ? { blocked_categories: controls.blockedCategories }
376 : {}),
377 ...(controls.blockedMerchantCountries !== undefined
378 ? { blocked_merchant_countries: controls.blockedMerchantCountries }
379 : {}),
380 ...(controls.spendingLimits !== undefined
381 ? {
382 spending_limits: controls.spendingLimits.map((limit) => ({
383 amount: limit.amount,
384 interval: limit.interval,
385 ...(limit.categories !== undefined ? { categories: limit.categories } : {}),
386 })),
387 }
388 : {}),
389 });
390
391 const toAttrs = (card: StripeIssuingCard): IssuingCardAttributes => ({
392 id: card.id,
393 cardholder: card.cardholder.id,
394 currency: card.currency,
395 type: card.type,
396 status: card.status,
397 brand: card.brand,
398 last4: card.last4,
399 expMonth: card.exp_month,
400 expYear: card.exp_year,
401 secondLine: card.second_line ?? undefined,
402 financialAccount: card.financial_account ?? undefined,
403 personalizationDesign: expandedId(card.personalization_design),
404 replacementFor: expandedId(card.replacement_for),
405 replacementReason: (card.replacement_reason as IssuingCardReplacementReason | null) ?? undefined,
406 cancellationReason: card.cancellation_reason ?? undefined,
407 spendingControls: toSpendingControls(card.spending_controls),
408 metadata: userMetadata(card.metadata),
409 created: card.created,
410 livemode: card.livemode,
411 });
412
413 const isMissingCard = isMissingStripeResource;
414
415 const isIssuingUnavailable = (error: StripeOpError): boolean =>
416 error._tag === "InvalidRequestError" || error._tag === "Forbidden";
417
418 const getById = (card: string) =>
419 GetIssuingCard({ card }).pipe(
420 Effect.map((live) => (live.status === "canceled" ? undefined : live)),
421 Effect.catchIf(isMissingCard, () => Effect.undefined),
422 );
423
424 const getByIdAny = (card: string) =>
425 GetIssuingCard({ card }).pipe(Effect.catchIf(isMissingCard, () => Effect.undefined));
426
427 const listByStatus = Effect.fn(function* (status: "active" | "inactive") {
428 const cards: StripeIssuingCard[] = [];
429 let startingAfter: string | undefined;
430 for (let page = 0; page < LIST_MAX_PAGES; page++) {
431 const response = yield* GetIssuingCards({
432 status,
433 limit: LIST_PAGE_SIZE,
434 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
435 });
436 cards.push(...response.data);
437 if (!response.has_more || response.data.length === 0) {
438 break;
439 }
440 startingAfter = response.data[response.data.length - 1]?.id;
441 if (startingAfter === undefined) {
442 break;
443 }
444 }
445 return cards;
446 });
447
448 const listLiveCards = Effect.fn(function* () {
449 const listed = yield* Effect.all([listByStatus("active"), listByStatus("inactive")], {
450 concurrency: 2,
451 }).pipe(
452 Effect.catchIf(isIssuingUnavailable, () =>
453 Effect.succeed([[], []] as [StripeIssuingCard[], StripeIssuingCard[]]),
454 ),
455 );
456 const seen = new Set<string>();
457 const cards: StripeIssuingCard[] = [];
458 for (const card of [...listed[0], ...listed[1]]) {
459 if (seen.has(card.id)) continue;
460 seen.add(card.id);
461 cards.push(card);
462 }
463 return cards;
464 });
465
466 const findByAlchemyId = Effect.fn(function* (id: string) {
467 const cards = yield* listLiveCards();
468 const matches: StripeIssuingCard[] = [];
469 for (const card of cards) {
470 if (yield* hasAlchemyMetadata(id, tagRecord(card.metadata))) {
471 matches.push(card);
472 }
473 }
474 matches.sort((a, b) => b.created - a.created);
475 return matches[0];
476 });
477
478 const observe = Effect.fn(function* (input: { id?: string; logicalId: string }) {
479 if (input.id !== undefined) {
480 const byId = yield* getById(input.id);
481 if (byId !== undefined) return byId;
482 }
483 return yield* findByAlchemyId(input.logicalId);
484 });
485
486 const desiredMetadata = Effect.fn(function* (
487 id: string,
488 metadata: Record<string, string> | undefined,
489 ) {
490 return {
491 ...toMetadata(metadata),
492 ...(yield* createInternalMetadata(id)),
493 };
494 });
495
496 const shouldReplace = (
497 news: IssuingCardProps,
498 output: IssuingCardAttributes | undefined,
499 ): boolean => {
500 if (output === undefined) return false;
501 if (news.cardholder !== output.cardholder) return true;
502 if (news.currency !== output.currency) return true;
503 if ((news.type ?? "virtual") !== output.type) return true;
504 if (news.secondLine !== undefined && news.secondLine !== (output.secondLine ?? undefined)) {
505 return true;
506 }
507 if (news.expMonth !== undefined && news.expMonth !== output.expMonth) {
508 return true;
509 }
510 if (news.expYear !== undefined && news.expYear !== output.expYear) {
511 return true;
512 }
513 if (
514 news.financialAccount !== undefined &&
515 news.financialAccount !== (output.financialAccount ?? undefined)
516 ) {
517 return true;
518 }
519 if (
520 news.replacementFor !== undefined &&
521 news.replacementFor !== (output.replacementFor ?? undefined)
522 ) {
523 return true;
524 }
525 return false;
526 };
527
528 export const IssuingCardProvider = () =>
529 Provider.succeed(IssuingCard, {
530 stables: [
531 "id",
532 "cardholder",
533 "currency",
534 "type",
535 "brand",
536 "last4",
537 "expMonth",
538 "expYear",
539 "created",
540 "livemode",
541 ],
542
543 diff: Effect.fn(function* ({ news, output }) {
544 if (!isResolved(news)) return undefined;
545 if (shouldReplace(news, output)) {
546 return { action: "replace" } as const;
547 }
548 return undefined;
549 }),
550
551 read: Effect.fn(function* ({ id, output }) {
552 const existing = yield* observe({
553 id: output?.id,
554 logicalId: id,
555 });
556 if (existing === undefined) return undefined;
557 const attrs = toAttrs(existing);
558 return (yield* hasAlchemyMetadata(id, tagRecord(existing.metadata))) ? attrs : Unowned(attrs);
559 }),
560
561 list: Effect.fn(function* () {
562 // Canceled cards stay in Stripe but must not re-enter nuke. Filter
563 // to alchemy_stack so account-wide teardown only touches our rows.
564 const cards = yield* listLiveCards();
565 return cards
566 .filter((card) => {
567 const metadata = tagRecord(card.metadata);
568 return metadata[alchemyMetadataKeys.stack] !== undefined;
569 })
570 .map(toAttrs);
571 }),
572
573 reconcile: Effect.fn(function* ({ id, news, output, instanceId }) {
574 const metadata = yield* desiredMetadata(id, news.metadata);
575 const desiredType = news.type ?? "virtual";
576 const desiredStatus = news.status ?? "inactive";
577 const spendingControls =
578 news.spendingControls !== undefined
579 ? toWireSpendingControls(news.spendingControls)
580 : undefined;
581
582 let current: StripeIssuingCard | undefined = yield* observe({
583 id: output?.id,
584 logicalId: id,
585 });
586 // A previous generation (same logical id, different immutable
587 // fields) must not be reused — Stripe cards cannot change
588 // cardholder, currency, type, or printed second line.
589 if (current !== undefined && shouldReplace(news, toAttrs(current))) {
590 current = undefined;
591 }
592
593 if (current === undefined) {
594 current = yield* CreateIssuingCard({
595 cardholder: news.cardholder,
596 currency: news.currency,
597 type: desiredType,
598 status: desiredStatus,
599 metadata,
600 ...(news.secondLine !== undefined ? { second_line: news.secondLine } : {}),
601 ...(news.expMonth !== undefined ? { exp_month: news.expMonth } : {}),
602 ...(news.expYear !== undefined ? { exp_year: news.expYear } : {}),
603 ...(news.financialAccount !== undefined
604 ? { financial_account: news.financialAccount }
605 : {}),
606 ...(news.personalizationDesign !== undefined
607 ? { personalization_design: news.personalizationDesign }
608 : {}),
609 ...(news.replacementFor !== undefined ? { replacement_for: news.replacementFor } : {}),
610 ...(news.replacementReason !== undefined
611 ? { replacement_reason: news.replacementReason }
612 : {}),
613 ...(spendingControls !== undefined ? { spending_controls: spendingControls } : {}),
614 }).pipe(
615 withRequestOptions({
616 idempotencyKey: `alchemy-issuing-card-${instanceId}`,
617 }),
618 );
619 }
620
621 if (current === undefined) {
622 return yield* new IssuingCardNotResolved({
623 cardholder: news.cardholder,
624 currency: news.currency,
625 });
626 }
627
628 const observedMetadata = tagRecord(current.metadata);
629 const { upsert, removed } = diffMetadata(observedMetadata, metadata);
630 const metadataChanged = upsert.length > 0 || removed.length > 0;
631 const statusChanged = current.status !== desiredStatus;
632 const personalizationChanged =
633 news.personalizationDesign !== undefined &&
634 expandedId(current.personalization_design) !== news.personalizationDesign;
635 const spendingChanged =
636 news.spendingControls !== undefined &&
637 !deepEqual(news.spendingControls, toSpendingControls(current.spending_controls), {
638 stripNullish: true,
639 });
640
641 if (!statusChanged && !personalizationChanged && !spendingChanged && !metadataChanged) {
642 return toAttrs(current);
643 }
644
645 const updated = yield* UpdateIssuingCard({
646 card: current.id,
647 ...(statusChanged ? { status: desiredStatus } : {}),
648 ...(personalizationChanged ? { personalization_design: news.personalizationDesign } : {}),
649 ...(spendingChanged ? { spending_controls: spendingControls } : {}),
650 ...(metadataChanged
651 ? {
652 metadata: {
653 ...Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value])),
654 ...Object.fromEntries(removed.map((key) => [key, ""])),
655 },
656 }
657 : {}),
658 });
659 return toAttrs(updated);
660 }),
661
662 delete: Effect.fn(function* ({ output }) {
663 const existing = yield* getByIdAny(output.id);
664 if (existing === undefined || existing.status === "canceled") return;
665 yield* UpdateIssuingCard({
666 card: existing.id,
667 status: "canceled",
668 }).pipe(Effect.catchIf(isMissingCard, () => Effect.void));
669 }),
670 });