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

main
ts 249 lines 7.36 KB
Raw
1 import { withRequestOptions } from "@distilled.cloud/stripe";
2 import {
3 DeleteApplePayDomain,
4 GetApplePayDomains,
5 GetApplePayDomain,
6 CreateApplePayDomain,
7 type ApplePayDomain as StripeApplePayDomain,
8 } from "@distilled.cloud/stripe/stripe";
9 import { isResolved } from "alchemy/Diff";
10 import * as Provider from "alchemy/Provider";
11 import { Resource } from "alchemy/Resource";
12 import * as Data from "effect/Data";
13 import * as Effect from "effect/Effect";
14 import { isMissingStripeResource } from "./missing.ts";
15 import type { Providers } from "./Providers.ts";
16
17 const LIST_PAGE_SIZE = 100;
18 const LIST_MAX_PAGES = 100;
19
20 export interface ApplePayDomainProps {
21 /**
22 * Fully-qualified hostname to register with Apple Pay (e.g.
23 * `"pay.example.com"`). Changing it replaces the domain. Stripe does
24 * not support metadata on Apple Pay domains.
25 */
26 domainName: string;
27 }
28
29 export type ApplePayDomain = Resource<
30 "Stripe.ApplePayDomain",
31 ApplePayDomainProps,
32 {
33 /** Stripe Apple Pay domain id (`apwc_…`). */
34 id: string;
35 /** Fully-qualified hostname registered with Apple Pay. */
36 domainName: string;
37 /** Unix timestamp when the domain was registered. */
38 created: number;
39 /** Whether the domain exists in live mode. */
40 livemode: boolean;
41 },
42 never,
43 Providers
44 >;
45
46 /**
47 * A Stripe Apple Pay Domain — a hostname registered so Apple Pay can be
48 * offered on that origin. Existence-only: there is nothing to update in
49 * place; changing `domainName` replaces the registration. Destroy deletes
50 * it.
51 *
52 * Apple Pay domains have no metadata. Account-wide `list()` (nuke)
53 * enumerates every domain on the account.
54 *
55 * In test mode, Stripe does not require the Apple domain-association
56 * file. Live mode requires
57 * `/.well-known/apple-developer-merchantid-domain-association` on the
58 * hostname before registration succeeds.
59 *
60 * @see https://docs.stripe.com/apple-pay
61 *
62 * ### Registering a Domain
63 * **Example:** Basic domain
64 * ```typescript
65 * const pay = yield* Stripe.ApplePayDomain("checkout", {
66 * domainName: "pay.example.com",
67 * });
68 * ```
69 *
70 * ### Replacing a Domain
71 * **Example:** Point at a different hostname
72 * ```typescript
73 * const pay = yield* Stripe.ApplePayDomain("checkout", {
74 * domainName: "checkout.example.com",
75 * });
76 * ```
77 *
78 * ### Deleting a Domain
79 * **Example:** Destroy deletes the registration
80 * ```typescript
81 * // stack.destroy() / resource removal deletes the Apple Pay domain
82 * const pay = yield* Stripe.ApplePayDomain("checkout", {
83 * domainName: "pay.example.com",
84 * });
85 * ```
86 *
87 * @resource
88 * @product Payment Methods
89 */
90 export const ApplePayDomain = Resource<ApplePayDomain>("Stripe.ApplePayDomain");
91
92 export class ApplePayDomainNotResolved extends Data.TaggedError(
93 "Stripe.ApplePayDomainNotResolved",
94 )<{
95 domainName: string;
96 }> {}
97
98 type ApplePayDomainAttributes = ApplePayDomain["Attributes"];
99
100 const toAttrs = (domain: StripeApplePayDomain): ApplePayDomainAttributes => ({
101 id: domain.id,
102 domainName: domain.domain_name,
103 created: domain.created,
104 livemode: domain.livemode,
105 });
106
107 const isMissing = isMissingStripeResource;
108
109 const getById = (domain: string) =>
110 GetApplePayDomain({ domain }).pipe(Effect.catchIf(isMissing, () => Effect.undefined));
111
112 const listAllApplePayDomains = Effect.fn(function* () {
113 const domains: StripeApplePayDomain[] = [];
114 let startingAfter: string | undefined;
115 for (let page = 0; page < LIST_MAX_PAGES; page++) {
116 const response = yield* GetApplePayDomains({
117 limit: LIST_PAGE_SIZE,
118 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
119 });
120 domains.push(...response.data);
121 if (!response.has_more || response.data.length === 0) {
122 break;
123 }
124 startingAfter = response.data[response.data.length - 1]?.id;
125 if (startingAfter === undefined) {
126 break;
127 }
128 }
129 return domains;
130 });
131
132 const findByDomainName = Effect.fn(function* (domainName: string) {
133 const matches: StripeApplePayDomain[] = [];
134 let startingAfter: string | undefined;
135 for (let page = 0; page < LIST_MAX_PAGES; page++) {
136 const response = yield* GetApplePayDomains({
137 domain_name: domainName,
138 limit: LIST_PAGE_SIZE,
139 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
140 });
141 for (const domain of response.data) {
142 if (domain.domain_name === domainName) {
143 matches.push(domain);
144 }
145 }
146 if (!response.has_more || response.data.length === 0) {
147 break;
148 }
149 startingAfter = response.data[response.data.length - 1]?.id;
150 if (startingAfter === undefined) {
151 break;
152 }
153 }
154 matches.sort((a, b) => b.created - a.created);
155 return matches[0];
156 });
157
158 const observe = Effect.fn(function* (input: { id?: string; domainName?: string }) {
159 if (input.id !== undefined) {
160 const byId = yield* getById(input.id);
161 if (byId !== undefined) return byId;
162 }
163 if (input.domainName !== undefined) {
164 return yield* findByDomainName(input.domainName);
165 }
166 return undefined;
167 });
168
169 const shouldReplace = (
170 news: ApplePayDomainProps,
171 output: ApplePayDomainAttributes | undefined,
172 ): boolean => {
173 if (output === undefined) return false;
174 return news.domainName !== output.domainName;
175 };
176
177 export const ApplePayDomainProvider = () =>
178 Provider.succeed(ApplePayDomain, {
179 stables: ["id", "domainName", "created", "livemode"],
180
181 diff: Effect.fn(function* ({ news, output }) {
182 if (!isResolved(news)) return undefined;
183 if (shouldReplace(news, output)) {
184 return { action: "replace" } as const;
185 }
186 return undefined;
187 }),
188
189 read: Effect.fn(function* ({ output, olds }) {
190 const domainName =
191 output?.domainName ?? (typeof olds?.domainName === "string" ? olds.domainName : undefined);
192 const existing = yield* observe({
193 id: output?.id,
194 domainName,
195 });
196 if (existing === undefined) return undefined;
197 return toAttrs(existing);
198 }),
199
200 list: Effect.fn(function* () {
201 // Apple Pay domains have no metadata. Account-wide list so nuke can
202 // tear down leaked registrations.
203 const domains = yield* listAllApplePayDomains();
204 return domains.map(toAttrs);
205 }),
206
207 reconcile: Effect.fn(function* ({ news, output, instanceId }) {
208 let current = yield* observe({
209 id: output?.id,
210 domainName: news.domainName,
211 });
212 if (current !== undefined && shouldReplace(news, toAttrs(current))) {
213 current = undefined;
214 }
215
216 if (current === undefined) {
217 current = yield* CreateApplePayDomain({
218 domain_name: news.domainName,
219 }).pipe(
220 withRequestOptions({
221 idempotencyKey: `alchemy-apple-pay-domain-${instanceId}`,
222 }),
223 Effect.catchIf(
224 (e) => e._tag === "InvalidRequestError" || e._tag === "Conflict",
225 (e) =>
226 observe({ domainName: news.domainName }).pipe(
227 Effect.flatMap((found) =>
228 found !== undefined ? Effect.succeed(found) : Effect.fail(e),
229 ),
230 ),
231 ),
232 );
233 }
234
235 if (current === undefined) {
236 return yield* new ApplePayDomainNotResolved({
237 domainName: news.domainName,
238 });
239 }
240
241 return toAttrs(current);
242 }),
243
244 delete: Effect.fn(function* ({ output }) {
245 yield* DeleteApplePayDomain({ domain: output.id }).pipe(
246 Effect.catchIf(isMissing, () => Effect.void),
247 );
248 }),
249 });