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

main
ts 329 lines 10.9 KB
Raw
1 import { withRequestOptions } from "@distilled.cloud/stripe";
2 import {
3 GetPaymentMethodDomains,
4 GetPaymentMethodDomain,
5 CreatePaymentMethodDomain,
6 UpdatePaymentMethodDomain,
7 type PaymentMethodDomain as StripePaymentMethodDomain,
8 type PaymentMethodDomainResourcePaymentMethodStatus,
9 } from "@distilled.cloud/stripe/stripe";
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 * as Data from "effect/Data";
15 import * as Effect from "effect/Effect";
16 import { isMissingStripeResource } from "./missing.ts";
17 import type { Providers } from "./Providers.ts";
18
19 const DOMAIN_SUFFIX = ".example.com";
20 const DOMAIN_LABEL_MAX_LENGTH = 63;
21 const LIST_PAGE_SIZE = 100;
22 const LIST_MAX_PAGES = 100;
23
24 /** The status of a payment method on a registered domain. */
25 export type PaymentMethodDomainStatus = "active" | "inactive";
26
27 export interface PaymentMethodDomainPaymentMethodStatus {
28 /**
29 * Whether the payment method is active on this domain.
30 */
31 status: PaymentMethodDomainStatus;
32 /**
33 * Extra details when the payment method is inactive, including the
34 * error message from Stripe.
35 */
36 statusDetails?: {
37 /** Error message associated with the inactive status. */
38 errorMessage: string;
39 };
40 }
41
42 export interface PaymentMethodDomainProps {
43 /**
44 * Domain name this payment method domain represents (e.g.
45 * `"checkout.example.com"`). If omitted, a unique hostname is generated
46 * from the stack, stage, and logical id under `.example.com`. Create-only
47 * — changing it replaces the domain. Stripe domain names are unique per
48 * account, including disabled domains.
49 */
50 domainName?: string;
51 /**
52 * Whether this payment method domain is enabled. If disabled, payment
53 * methods that require a registered domain do not appear in Elements or
54 * Embedded Checkout. Destroy sets this to `false`.
55 * @default true
56 */
57 enabled?: boolean;
58 }
59
60 export type PaymentMethodDomain = Resource<
61 "Stripe.PaymentMethodDomain",
62 PaymentMethodDomainProps,
63 {
64 /** Stripe payment method domain id (`pmd_…`). */
65 id: string;
66 /** Domain name this object represents. */
67 domainName: string;
68 /** Whether this payment method domain is enabled. */
69 enabled: boolean;
70 /** Amazon Pay eligibility on this domain. */
71 amazonPay: PaymentMethodDomainPaymentMethodStatus;
72 /** Apple Pay eligibility on this domain. */
73 applePay: PaymentMethodDomainPaymentMethodStatus;
74 /** Google Pay eligibility on this domain. */
75 googlePay: PaymentMethodDomainPaymentMethodStatus;
76 /** Klarna eligibility on this domain. */
77 klarna: PaymentMethodDomainPaymentMethodStatus;
78 /** Link eligibility on this domain. */
79 link: PaymentMethodDomainPaymentMethodStatus;
80 /** PayPal eligibility on this domain. */
81 paypal: PaymentMethodDomainPaymentMethodStatus;
82 /** Unix timestamp when the domain was created. */
83 created: number;
84 /** Whether the domain exists in live mode. */
85 livemode: boolean;
86 },
87 never,
88 Providers
89 >;
90
91 /**
92 * A Stripe Payment Method Domain — a web domain registered so Stripe
93 * Elements and Embedded Checkout can show domain-gated payment methods
94 * (Apple Pay, Google Pay, Link, PayPal, Klarna, Amazon Pay). `enabled`
95 * updates in place. `domainName` is create-only and changing it replaces
96 * the domain.
97 *
98 * Payment method domains have no metadata field and cannot be
99 * hard-deleted. Destroying this resource disables it (`enabled: false`).
100 * Disabled domains still occupy their `domainName`, so a later deploy
101 * with the same name re-enables the existing domain.
102 *
103 * @see https://docs.stripe.com/api/payment_method_domains
104 *
105 * ### Creating a Domain
106 * **Example:** Generated domain name
107 * ```typescript
108 * const domain = yield* Stripe.PaymentMethodDomain("checkout");
109 * ```
110 *
111 * **Example:** Named domain
112 * ```typescript
113 * const domain = yield* Stripe.PaymentMethodDomain("checkout", {
114 * domainName: "checkout.example.com",
115 * });
116 * ```
117 *
118 * ### Updating a Domain
119 * **Example:** Disable without replacing
120 * ```typescript
121 * const domain = yield* Stripe.PaymentMethodDomain("checkout", {
122 * domainName: "checkout.example.com",
123 * enabled: false,
124 * });
125 * ```
126 *
127 * ### Deactivating a Domain
128 * **Example:** Destroy disables rather than deleting
129 * ```typescript
130 * // stack.destroy() / resource removal sets enabled: false
131 * const domain = yield* Stripe.PaymentMethodDomain("checkout", {
132 * domainName: "checkout.example.com",
133 * });
134 * ```
135 *
136 * @resource
137 * @product Payment Methods
138 */
139 export const PaymentMethodDomain = Resource<PaymentMethodDomain>("Stripe.PaymentMethodDomain");
140
141 export class PaymentMethodDomainNotResolved extends Data.TaggedError(
142 "Stripe.PaymentMethodDomainNotResolved",
143 )<{
144 domainName: string;
145 }> {}
146
147 type PaymentMethodDomainAttributes = PaymentMethodDomain["Attributes"];
148
149 const toDomainName = (id: string, domainName: string | undefined, existing?: string) =>
150 Effect.gen(function* () {
151 return (
152 domainName ??
153 existing ??
154 `${yield* createPhysicalName({
155 id,
156 maxLength: DOMAIN_LABEL_MAX_LENGTH,
157 lowercase: true,
158 })}${DOMAIN_SUFFIX}`
159 );
160 });
161
162 const toPaymentMethodStatus = (
163 value: PaymentMethodDomainResourcePaymentMethodStatus,
164 ): PaymentMethodDomainPaymentMethodStatus => ({
165 status: value.status,
166 statusDetails:
167 value.status_details === undefined
168 ? undefined
169 : { errorMessage: value.status_details.error_message },
170 });
171
172 const toAttrs = (domain: StripePaymentMethodDomain): PaymentMethodDomainAttributes => ({
173 id: domain.id,
174 domainName: domain.domain_name,
175 enabled: domain.enabled,
176 amazonPay: toPaymentMethodStatus(domain.amazon_pay),
177 applePay: toPaymentMethodStatus(domain.apple_pay),
178 googlePay: toPaymentMethodStatus(domain.google_pay),
179 klarna: toPaymentMethodStatus(domain.klarna),
180 link: toPaymentMethodStatus(domain.link),
181 paypal: toPaymentMethodStatus(domain.paypal),
182 created: domain.created,
183 livemode: domain.livemode,
184 });
185
186 const isMissingDomain = isMissingStripeResource;
187
188 /** Stripe-hosted domains (`buy.stripe.com`, …) Stripe registers itself. */
189 const isStripeManagedDomain = (domainName: string) =>
190 domainName === "stripe.com" || domainName.endsWith(".stripe.com");
191
192 const getById = (paymentMethodDomain: string) =>
193 GetPaymentMethodDomain({
194 payment_method_domain: paymentMethodDomain,
195 }).pipe(Effect.catchIf(isMissingDomain, () => Effect.undefined));
196
197 const listByEnabled = Effect.fn(function* (enabled: boolean, domainName?: string) {
198 const domains: StripePaymentMethodDomain[] = [];
199 let startingAfter: string | undefined;
200 for (let page = 0; page < LIST_MAX_PAGES; page++) {
201 const response = yield* GetPaymentMethodDomains({
202 enabled,
203 limit: LIST_PAGE_SIZE,
204 ...(domainName !== undefined ? { domain_name: domainName } : {}),
205 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
206 });
207 domains.push(...response.data);
208 if (!response.has_more || response.data.length === 0) {
209 break;
210 }
211 startingAfter = response.data[response.data.length - 1]?.id;
212 if (startingAfter === undefined) {
213 break;
214 }
215 }
216 return domains;
217 });
218
219 const findByDomainName = Effect.fn(function* (domainName: string) {
220 const [enabled, disabled] = yield* Effect.all(
221 [listByEnabled(true, domainName), listByEnabled(false, domainName)],
222 { concurrency: 2 },
223 );
224 const matches = [...enabled, ...disabled].filter((domain) => domain.domain_name === domainName);
225 return matches.find((domain) => domain.enabled) ?? matches[0];
226 });
227
228 const observe = Effect.fn(function* (input: { id?: string; domainName?: string }) {
229 if (input.id !== undefined) {
230 const byId = yield* getById(input.id);
231 if (byId !== undefined) return byId;
232 }
233 if (input.domainName !== undefined) {
234 return yield* findByDomainName(input.domainName);
235 }
236 return undefined;
237 });
238
239 const shouldReplace = (
240 news: PaymentMethodDomainProps,
241 output: PaymentMethodDomainAttributes | undefined,
242 ): boolean => {
243 if (output === undefined) return false;
244 if (news.domainName !== undefined && news.domainName !== output.domainName) {
245 return true;
246 }
247 return false;
248 };
249
250 export const PaymentMethodDomainProvider = () =>
251 Provider.succeed(PaymentMethodDomain, {
252 stables: ["id", "domainName", "created", "livemode"],
253
254 diff: Effect.fn(function* ({ news, output }) {
255 if (!isResolved(news)) return undefined;
256 if (shouldReplace(news, output)) {
257 return { action: "replace" } as const;
258 }
259 return undefined;
260 }),
261
262 read: Effect.fn(function* ({ output }) {
263 const existing = yield* observe({
264 id: output?.id,
265 domainName: output?.domainName,
266 });
267 if (existing === undefined) return undefined;
268 // Payment method domains have no metadata. Identity is the Stripe
269 // id and the unique domain_name; a match is treated as owned.
270 return toAttrs(existing);
271 }),
272
273 list: Effect.fn(function* () {
274 // No metadata on this resource. Default list is enabled domains;
275 // disabled rows stay in Stripe (domain_name remains reserved) but
276 // must not re-enter nuke. Stripe auto-registers its own hosted
277 // domains (e.g. `buy.stripe.com` for Payment Links) on the account;
278 // those are Stripe-managed, never ours, and are skipped.
279 const domains = yield* listByEnabled(true);
280 return domains.filter((domain) => !isStripeManagedDomain(domain.domain_name)).map(toAttrs);
281 }),
282
283 reconcile: Effect.fn(function* ({ id, news, output, instanceId }) {
284 const domainName = yield* toDomainName(id, news.domainName, output?.domainName);
285 const desiredEnabled = news.enabled ?? true;
286
287 let current = yield* observe({
288 id: output?.id,
289 domainName,
290 });
291 if (current !== undefined && shouldReplace(news, toAttrs(current))) {
292 current = undefined;
293 }
294
295 if (current === undefined) {
296 current = yield* CreatePaymentMethodDomain({
297 domain_name: domainName,
298 enabled: desiredEnabled,
299 }).pipe(
300 withRequestOptions({
301 idempotencyKey: `alchemy-payment-method-domain-${instanceId}`,
302 }),
303 );
304 }
305
306 if (current === undefined) {
307 return yield* new PaymentMethodDomainNotResolved({ domainName });
308 }
309
310 if (current.enabled === desiredEnabled) {
311 return toAttrs(current);
312 }
313
314 const updated = yield* UpdatePaymentMethodDomain({
315 payment_method_domain: current.id,
316 enabled: desiredEnabled,
317 });
318 return toAttrs(updated);
319 }),
320
321 delete: Effect.fn(function* ({ output }) {
322 const existing = yield* getById(output.id);
323 if (existing === undefined || !existing.enabled) return;
324 yield* UpdatePaymentMethodDomain({
325 payment_method_domain: existing.id,
326 enabled: false,
327 }).pipe(Effect.catchIf(isMissingDomain, () => Effect.void));
328 }),
329 });