The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { withRequestOptions } from "@distilled.cloud/stripe"; |
| 2 | import { |
| 3 | DeleteAccount, |
| 4 | GetAccounts, |
| 5 | GetAccountByAccount, |
| 6 | CreateAccount, |
| 7 | UpdateAccount, |
| 8 | type Account as StripeAccount, |
| 9 | type AccountBusinessType as StripeAccountBusinessType, |
| 10 | type AccountType as StripeAccountType, |
| 11 | type CreateAccountRequestBusinessProfile, |
| 12 | type CreateAccountRequestCapabilities, |
| 13 | type CreateAccountRequestCompany, |
| 14 | type CreateAccountRequestController, |
| 15 | type CreateAccountRequestIndividual, |
| 16 | type CreateAccountRequestSettings, |
| 17 | type CreateAccountRequestTosAcceptance, |
| 18 | } from "@distilled.cloud/stripe/stripe"; |
| 19 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 20 | import { deepEqual, isResolved } from "alchemy/Diff"; |
| 21 | import * as Provider from "alchemy/Provider"; |
| 22 | import { Resource } from "alchemy/Resource"; |
| 23 | import { tagRecord } from "alchemy/Tags"; |
| 24 | import * as Effect from "effect/Effect"; |
| 25 | import { |
| 26 | alchemyMetadataKeys, |
| 27 | createInternalMetadata, |
| 28 | diffMetadata, |
| 29 | hasAlchemyMetadata, |
| 30 | stripInternalMetadata, |
| 31 | toMetadata, |
| 32 | } from "./Metadata.ts"; |
| 33 | import { isMissingStripeResource } from "./missing.ts"; |
| 34 | import type { Providers } from "./Providers.ts"; |
| 35 | |
| 36 | const LIST_PAGE_SIZE = 100; |
| 37 | const LIST_MAX_PAGES = 100; |
| 38 | |
| 39 | /** Connected-account kinds accepted by `POST /v1/accounts`. */ |
| 40 | export type AccountKind = "custom" | "express" | "standard"; |
| 41 | |
| 42 | /** Legal structure of the account holder. */ |
| 43 | export type AccountBusinessType = StripeAccountBusinessType; |
| 44 | |
| 45 | /** Stripe-reported account type, including `none` for controller-created accounts. */ |
| 46 | export type AccountType = StripeAccountType; |
| 47 | |
| 48 | export interface AccountBusinessProfile { |
| 49 | /** |
| 50 | * Customer-facing business name. |
| 51 | */ |
| 52 | name?: string; |
| 53 | /** |
| 54 | * Public website of the business. |
| 55 | */ |
| 56 | url?: string; |
| 57 | /** |
| 58 | * Merchant category code (MCC). |
| 59 | */ |
| 60 | mcc?: string; |
| 61 | /** |
| 62 | * Internal description of the product or service. Used by Stripe for |
| 63 | * underwriting. |
| 64 | */ |
| 65 | productDescription?: string; |
| 66 | /** |
| 67 | * Public support email. |
| 68 | */ |
| 69 | supportEmail?: string; |
| 70 | /** |
| 71 | * Public support phone. |
| 72 | */ |
| 73 | supportPhone?: string; |
| 74 | /** |
| 75 | * Public support URL. |
| 76 | */ |
| 77 | supportUrl?: string; |
| 78 | } |
| 79 | |
| 80 | export interface AccountControllerFees { |
| 81 | /** |
| 82 | * Who pays Stripe fees on this account. |
| 83 | * @default "account" |
| 84 | */ |
| 85 | payer?: "account" | "application"; |
| 86 | } |
| 87 | |
| 88 | export interface AccountControllerLosses { |
| 89 | /** |
| 90 | * Who is liable for negative balances. |
| 91 | * @default "stripe" |
| 92 | */ |
| 93 | payments?: "application" | "stripe"; |
| 94 | } |
| 95 | |
| 96 | export interface AccountControllerDashboard { |
| 97 | /** |
| 98 | * Stripe-hosted dashboard access: full Dashboard, Express, or none. |
| 99 | * @default "full" |
| 100 | */ |
| 101 | type?: "express" | "full" | "none"; |
| 102 | } |
| 103 | |
| 104 | export interface AccountController { |
| 105 | /** |
| 106 | * Who pays Stripe fees for product usage on this account. |
| 107 | */ |
| 108 | fees?: AccountControllerFees; |
| 109 | /** |
| 110 | * Who is liable for negative balances on this account. |
| 111 | */ |
| 112 | losses?: AccountControllerLosses; |
| 113 | /** |
| 114 | * Who collects updated information when requirements are due. |
| 115 | * @default "stripe" |
| 116 | */ |
| 117 | requirementCollection?: "application" | "stripe"; |
| 118 | /** |
| 119 | * Stripe-hosted dashboard access. |
| 120 | */ |
| 121 | stripeDashboard?: AccountControllerDashboard; |
| 122 | } |
| 123 | |
| 124 | export interface AccountTosAcceptance { |
| 125 | /** |
| 126 | * Unix timestamp when the account representative accepted the service |
| 127 | * agreement. |
| 128 | */ |
| 129 | date?: number; |
| 130 | /** |
| 131 | * IP address from which the representative accepted the agreement. |
| 132 | */ |
| 133 | ip?: string; |
| 134 | /** |
| 135 | * User agent of the browser that accepted the agreement. |
| 136 | */ |
| 137 | userAgent?: string; |
| 138 | /** |
| 139 | * Service agreement type. |
| 140 | */ |
| 141 | serviceAgreement?: string; |
| 142 | } |
| 143 | |
| 144 | export interface AccountProps { |
| 145 | /** |
| 146 | * Kind of connected account to create — `standard`, `express`, or |
| 147 | * `custom`. Create-only — changing it replaces the account. |
| 148 | * |
| 149 | * Mutually exclusive with {@link AccountProps.controller}. Omitting both |
| 150 | * makes Stripe default to a Standard account. |
| 151 | */ |
| 152 | type?: AccountKind; |
| 153 | /** |
| 154 | * Two-letter ISO country code of the account holder (e.g. `"US"`). |
| 155 | * Create-only — changing it replaces the account. When omitted, Stripe |
| 156 | * defaults to the platform's country. |
| 157 | */ |
| 158 | country?: string; |
| 159 | /** |
| 160 | * Email address of the account holder. Used to identify the account; |
| 161 | * Stripe does not market to it. Mutable. |
| 162 | */ |
| 163 | email?: string; |
| 164 | /** |
| 165 | * Legal structure of the account holder. Mutable until Connect |
| 166 | * onboarding starts on Standard and Express accounts. |
| 167 | */ |
| 168 | businessType?: AccountBusinessType; |
| 169 | /** |
| 170 | * Public-facing business information (name, URL, support contacts, MCC). |
| 171 | * Mutable. |
| 172 | */ |
| 173 | businessProfile?: AccountBusinessProfile; |
| 174 | /** |
| 175 | * Capabilities to request, keyed by Stripe capability name |
| 176 | * (`card_payments`, `transfers`, …) with `{ requested: boolean }`. |
| 177 | * Mutable — requesting a capability does not activate it; Stripe |
| 178 | * activates it once requirements are met. |
| 179 | * |
| 180 | * Nested fields use Stripe's wire names. |
| 181 | */ |
| 182 | capabilities?: CreateAccountRequestCapabilities; |
| 183 | /** |
| 184 | * Account behaviour settings (branding, payouts, card payments, …). |
| 185 | * Mutable. Nested fields use Stripe's wire names. |
| 186 | */ |
| 187 | settings?: CreateAccountRequestSettings; |
| 188 | /** |
| 189 | * Three-letter ISO currency code used as the account's default currency. |
| 190 | * Must be a currency Stripe supports in the account's country. Mutable. |
| 191 | */ |
| 192 | defaultCurrency?: string; |
| 193 | /** |
| 194 | * Company or business details. Available for any `businessType`. Mutable |
| 195 | * while `controller.requirement_collection` is `application` (Custom). |
| 196 | * Nested fields use Stripe's wire names. |
| 197 | */ |
| 198 | company?: CreateAccountRequestCompany; |
| 199 | /** |
| 200 | * Individual represented by the account. Only meaningful when |
| 201 | * `businessType` is `individual`. Nested fields use Stripe's wire names. |
| 202 | */ |
| 203 | individual?: CreateAccountRequestIndividual; |
| 204 | /** |
| 205 | * Record of the account holder accepting the Stripe Services Agreement. |
| 206 | * Only settable for Custom accounts. |
| 207 | */ |
| 208 | tosAcceptance?: AccountTosAcceptance; |
| 209 | /** |
| 210 | * Who is responsible for fees, losses, requirement collection, and |
| 211 | * dashboard access. Create-only — changing it replaces the account. |
| 212 | * |
| 213 | * Mutually exclusive with {@link AccountProps.type}. |
| 214 | */ |
| 215 | controller?: AccountController; |
| 216 | /** |
| 217 | * User-defined metadata. Alchemy ownership keys (`alchemy_stack` / |
| 218 | * `alchemy_stage` / `alchemy_id`) are merged in automatically. Keys may |
| 219 | * not contain `:`. |
| 220 | */ |
| 221 | metadata?: Record<string, string>; |
| 222 | } |
| 223 | |
| 224 | export type Account = Resource< |
| 225 | "Stripe.Account", |
| 226 | AccountProps, |
| 227 | { |
| 228 | /** Stripe account id (`acct_…`). */ |
| 229 | id: string; |
| 230 | /** |
| 231 | * Stripe account type — `standard`, `express`, `custom`, or `none` |
| 232 | * for accounts created with an explicit `controller`. |
| 233 | */ |
| 234 | type: AccountType | undefined; |
| 235 | /** Two-letter ISO country code the account is registered in. */ |
| 236 | country: string | undefined; |
| 237 | /** Email address associated with the account. */ |
| 238 | email: string | undefined; |
| 239 | /** Legal structure of the account holder, once known. */ |
| 240 | businessType: AccountBusinessType | undefined; |
| 241 | /** Three-letter ISO code of the account's default currency. */ |
| 242 | defaultCurrency: string | undefined; |
| 243 | /** Customer-facing business name, if set. */ |
| 244 | businessProfileName: string | undefined; |
| 245 | /** Public website of the business, if set. */ |
| 246 | businessProfileUrl: string | undefined; |
| 247 | /** Whether the account can currently process charges. */ |
| 248 | chargesEnabled: boolean; |
| 249 | /** Whether funds in the account can currently be paid out. */ |
| 250 | payoutsEnabled: boolean; |
| 251 | /** |
| 252 | * Whether the account has finished submitting its details. Accounts |
| 253 | * with Dashboard access cannot receive payouts until this is `true`. |
| 254 | */ |
| 255 | detailsSubmitted: boolean; |
| 256 | /** |
| 257 | * Capability name → status (`active`, `pending`, `inactive`) for every |
| 258 | * capability Stripe reports on the account. |
| 259 | */ |
| 260 | capabilities: Record<string, string>; |
| 261 | /** |
| 262 | * Fields Stripe needs before the account's capabilities stay enabled. |
| 263 | */ |
| 264 | requirementsCurrentlyDue: string[]; |
| 265 | /** Why the account is currently disabled, if it is. */ |
| 266 | requirementsDisabledReason: string | undefined; |
| 267 | /** Unix timestamp when the account was connected. */ |
| 268 | created: number | undefined; |
| 269 | /** User-defined metadata (Alchemy ownership keys stripped). */ |
| 270 | metadata: Record<string, string>; |
| 271 | }, |
| 272 | never, |
| 273 | Providers |
| 274 | >; |
| 275 | |
| 276 | /** |
| 277 | * A Stripe Connect connected account — a Standard, Express, or Custom |
| 278 | * account created by your platform on behalf of a user. |
| 279 | * |
| 280 | * Creating an account is only the first step of onboarding: Stripe |
| 281 | * activates requested capabilities once the account satisfies their |
| 282 | * requirements, so a freshly created account normally reports |
| 283 | * `chargesEnabled: false` and a non-empty `requirementsCurrentlyDue`. |
| 284 | * Account Links are one-shot URLs and are not modeled as resources. |
| 285 | * |
| 286 | * `type`, `country`, and `controller` are fixed at creation. Email, |
| 287 | * business profile, capabilities, settings, and metadata update in |
| 288 | * place. Deleting the resource deletes the connected account. |
| 289 | * |
| 290 | * @see https://docs.stripe.com/api/accounts |
| 291 | * |
| 292 | * ### Creating an Account |
| 293 | * **Example:** A Standard connected account |
| 294 | * ```typescript |
| 295 | * const account = yield* Stripe.Account("Merchant", { |
| 296 | * type: "standard", |
| 297 | * country: "US", |
| 298 | * email: "merchant@example.com", |
| 299 | * }); |
| 300 | * ``` |
| 301 | * |
| 302 | * **Example:** An Express account requesting payment capabilities |
| 303 | * ```typescript |
| 304 | * const account = yield* Stripe.Account("Merchant", { |
| 305 | * type: "express", |
| 306 | * country: "US", |
| 307 | * email: "merchant@example.com", |
| 308 | * capabilities: { |
| 309 | * card_payments: { requested: true }, |
| 310 | * transfers: { requested: true }, |
| 311 | * }, |
| 312 | * }); |
| 313 | * ``` |
| 314 | * |
| 315 | * ### Fully configuring an Account |
| 316 | * **Example:** Business profile, payouts, and metadata |
| 317 | * ```typescript |
| 318 | * const account = yield* Stripe.Account("Merchant", { |
| 319 | * type: "express", |
| 320 | * country: "US", |
| 321 | * email: "merchant@example.com", |
| 322 | * businessType: "company", |
| 323 | * defaultCurrency: "usd", |
| 324 | * businessProfile: { |
| 325 | * name: "Example Merchant", |
| 326 | * url: "https://example.com", |
| 327 | * mcc: "5734", |
| 328 | * supportEmail: "support@example.com", |
| 329 | * }, |
| 330 | * capabilities: { |
| 331 | * card_payments: { requested: true }, |
| 332 | * transfers: { requested: true }, |
| 333 | * }, |
| 334 | * settings: { |
| 335 | * payouts: { schedule: { interval: "manual" } }, |
| 336 | * }, |
| 337 | * metadata: { tier: "gold" }, |
| 338 | * }); |
| 339 | * ``` |
| 340 | * |
| 341 | * ### Controller instead of type |
| 342 | * **Example:** Custom responsibilities without `type` |
| 343 | * ```typescript |
| 344 | * const account = yield* Stripe.Account("Merchant", { |
| 345 | * country: "US", |
| 346 | * controller: { |
| 347 | * losses: { payments: "application" }, |
| 348 | * fees: { payer: "application" }, |
| 349 | * requirementCollection: "application", |
| 350 | * stripeDashboard: { type: "none" }, |
| 351 | * }, |
| 352 | * }); |
| 353 | * ``` |
| 354 | * |
| 355 | * @resource |
| 356 | * @product Account |
| 357 | */ |
| 358 | export const Account = Resource<Account>("Stripe.Account"); |
| 359 | |
| 360 | const userMetadata = ( |
| 361 | metadata: Record<string, string | undefined> | null | undefined, |
| 362 | ): Record<string, string> => stripInternalMetadata(tagRecord(metadata)); |
| 363 | |
| 364 | const capabilityStatuses = (capabilities: StripeAccount["capabilities"]): Record<string, string> => |
| 365 | Object.fromEntries( |
| 366 | Object.entries(capabilities ?? {}).filter( |
| 367 | (entry): entry is [string, string] => typeof entry[1] === "string", |
| 368 | ), |
| 369 | ); |
| 370 | |
| 371 | const toWireBusinessProfile = ( |
| 372 | profile: AccountBusinessProfile, |
| 373 | ): CreateAccountRequestBusinessProfile => ({ |
| 374 | ...(profile.name !== undefined ? { name: profile.name } : {}), |
| 375 | ...(profile.url !== undefined ? { url: profile.url } : {}), |
| 376 | ...(profile.mcc !== undefined ? { mcc: profile.mcc } : {}), |
| 377 | ...(profile.productDescription !== undefined |
| 378 | ? { product_description: profile.productDescription } |
| 379 | : {}), |
| 380 | ...(profile.supportEmail !== undefined ? { support_email: profile.supportEmail } : {}), |
| 381 | ...(profile.supportPhone !== undefined ? { support_phone: profile.supportPhone } : {}), |
| 382 | ...(profile.supportUrl !== undefined ? { support_url: profile.supportUrl } : {}), |
| 383 | }); |
| 384 | |
| 385 | const toWireController = (controller: AccountController): CreateAccountRequestController => ({ |
| 386 | ...(controller.fees !== undefined |
| 387 | ? { |
| 388 | fees: controller.fees.payer !== undefined ? { payer: controller.fees.payer } : {}, |
| 389 | } |
| 390 | : {}), |
| 391 | ...(controller.losses !== undefined |
| 392 | ? { |
| 393 | losses: |
| 394 | controller.losses.payments !== undefined ? { payments: controller.losses.payments } : {}, |
| 395 | } |
| 396 | : {}), |
| 397 | ...(controller.requirementCollection !== undefined |
| 398 | ? { requirement_collection: controller.requirementCollection } |
| 399 | : {}), |
| 400 | ...(controller.stripeDashboard !== undefined |
| 401 | ? { |
| 402 | stripe_dashboard: |
| 403 | controller.stripeDashboard.type !== undefined |
| 404 | ? { type: controller.stripeDashboard.type } |
| 405 | : {}, |
| 406 | } |
| 407 | : {}), |
| 408 | }); |
| 409 | |
| 410 | const toWireTosAcceptance = (tos: AccountTosAcceptance): CreateAccountRequestTosAcceptance => ({ |
| 411 | ...(tos.date !== undefined ? { date: tos.date } : {}), |
| 412 | ...(tos.ip !== undefined ? { ip: tos.ip } : {}), |
| 413 | ...(tos.userAgent !== undefined ? { user_agent: tos.userAgent } : {}), |
| 414 | ...(tos.serviceAgreement !== undefined ? { service_agreement: tos.serviceAgreement } : {}), |
| 415 | }); |
| 416 | |
| 417 | const toAttrs = (account: StripeAccount) => ({ |
| 418 | id: account.id, |
| 419 | type: account.type, |
| 420 | country: account.country, |
| 421 | email: account.email ?? undefined, |
| 422 | businessType: account.business_type ?? undefined, |
| 423 | defaultCurrency: account.default_currency, |
| 424 | businessProfileName: account.business_profile?.name ?? undefined, |
| 425 | businessProfileUrl: account.business_profile?.url ?? undefined, |
| 426 | chargesEnabled: account.charges_enabled ?? false, |
| 427 | payoutsEnabled: account.payouts_enabled ?? false, |
| 428 | detailsSubmitted: account.details_submitted ?? false, |
| 429 | capabilities: capabilityStatuses(account.capabilities), |
| 430 | requirementsCurrentlyDue: [...(account.requirements?.currently_due ?? [])], |
| 431 | requirementsDisabledReason: account.requirements?.disabled_reason ?? undefined, |
| 432 | created: account.created, |
| 433 | metadata: userMetadata(account.metadata), |
| 434 | }); |
| 435 | |
| 436 | const isMissingAccount = isMissingStripeResource; |
| 437 | |
| 438 | const getById = (account: string) => |
| 439 | GetAccountByAccount({ account }).pipe(Effect.catchIf(isMissingAccount, () => Effect.undefined)); |
| 440 | |
| 441 | const listAllAccounts = Effect.fn(function* () { |
| 442 | const accounts: StripeAccount[] = []; |
| 443 | let startingAfter: string | undefined; |
| 444 | for (let page = 0; page < LIST_MAX_PAGES; page++) { |
| 445 | const response = yield* GetAccounts({ |
| 446 | limit: LIST_PAGE_SIZE, |
| 447 | ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}), |
| 448 | }); |
| 449 | accounts.push(...response.data); |
| 450 | if (!response.has_more || response.data.length === 0) { |
| 451 | break; |
| 452 | } |
| 453 | startingAfter = response.data[response.data.length - 1]?.id; |
| 454 | if (startingAfter === undefined) { |
| 455 | break; |
| 456 | } |
| 457 | } |
| 458 | return accounts; |
| 459 | }); |
| 460 | |
| 461 | const findByAlchemyId = Effect.fn(function* (id: string) { |
| 462 | const accounts = yield* listAllAccounts(); |
| 463 | const matches: StripeAccount[] = []; |
| 464 | for (const account of accounts) { |
| 465 | if (yield* hasAlchemyMetadata(id, tagRecord(account.metadata))) { |
| 466 | matches.push(account); |
| 467 | } |
| 468 | } |
| 469 | matches.sort((a, b) => (b.created ?? 0) - (a.created ?? 0)); |
| 470 | return matches[0]; |
| 471 | }); |
| 472 | |
| 473 | const observe = Effect.fn(function* (input: { id?: string; logicalId: string }) { |
| 474 | if (input.id !== undefined) { |
| 475 | const byId = yield* getById(input.id); |
| 476 | if (byId !== undefined) return byId; |
| 477 | } |
| 478 | return yield* findByAlchemyId(input.logicalId); |
| 479 | }); |
| 480 | |
| 481 | const desiredMetadata = Effect.fn(function* ( |
| 482 | id: string, |
| 483 | metadata: Record<string, string> | undefined, |
| 484 | ) { |
| 485 | return { |
| 486 | ...toMetadata(metadata), |
| 487 | ...(yield* createInternalMetadata(id)), |
| 488 | }; |
| 489 | }); |
| 490 | |
| 491 | const businessProfileChanged = ( |
| 492 | desired: AccountBusinessProfile | undefined, |
| 493 | observed: StripeAccount["business_profile"], |
| 494 | ): boolean => { |
| 495 | if (desired === undefined) return false; |
| 496 | if (desired.name !== undefined && desired.name !== (observed?.name ?? undefined)) { |
| 497 | return true; |
| 498 | } |
| 499 | if (desired.url !== undefined && desired.url !== (observed?.url ?? undefined)) { |
| 500 | return true; |
| 501 | } |
| 502 | if (desired.mcc !== undefined && desired.mcc !== (observed?.mcc ?? undefined)) { |
| 503 | return true; |
| 504 | } |
| 505 | if ( |
| 506 | desired.productDescription !== undefined && |
| 507 | desired.productDescription !== (observed?.product_description ?? undefined) |
| 508 | ) { |
| 509 | return true; |
| 510 | } |
| 511 | if ( |
| 512 | desired.supportEmail !== undefined && |
| 513 | desired.supportEmail !== (observed?.support_email ?? undefined) |
| 514 | ) { |
| 515 | return true; |
| 516 | } |
| 517 | if ( |
| 518 | desired.supportPhone !== undefined && |
| 519 | desired.supportPhone !== (observed?.support_phone ?? undefined) |
| 520 | ) { |
| 521 | return true; |
| 522 | } |
| 523 | if ( |
| 524 | desired.supportUrl !== undefined && |
| 525 | desired.supportUrl !== (observed?.support_url ?? undefined) |
| 526 | ) { |
| 527 | return true; |
| 528 | } |
| 529 | return false; |
| 530 | }; |
| 531 | |
| 532 | const capabilitiesDiverge = ( |
| 533 | desired: CreateAccountRequestCapabilities | undefined, |
| 534 | observed: Record<string, string>, |
| 535 | ): boolean => { |
| 536 | if (desired === undefined) return false; |
| 537 | return Object.entries(desired).some(([name, value]) => { |
| 538 | const requested = value?.requested; |
| 539 | if (requested === undefined) return false; |
| 540 | const status = observed[name]; |
| 541 | const onFile = status === "active" || status === "pending"; |
| 542 | return requested !== onFile; |
| 543 | }); |
| 544 | }; |
| 545 | |
| 546 | const shouldReplace = ( |
| 547 | news: AccountProps, |
| 548 | olds: AccountProps | undefined, |
| 549 | output: Account["Attributes"] | undefined, |
| 550 | ): boolean => { |
| 551 | if (news.type !== undefined && output?.type !== undefined && news.type !== output.type) { |
| 552 | return true; |
| 553 | } |
| 554 | if ( |
| 555 | news.country !== undefined && |
| 556 | output?.country !== undefined && |
| 557 | news.country !== output.country |
| 558 | ) { |
| 559 | return true; |
| 560 | } |
| 561 | if ( |
| 562 | olds !== undefined && |
| 563 | news.controller !== undefined && |
| 564 | !deepEqual(news.controller, olds.controller, { stripNullish: true }) |
| 565 | ) { |
| 566 | return true; |
| 567 | } |
| 568 | return false; |
| 569 | }; |
| 570 | |
| 571 | export const AccountProvider = () => |
| 572 | Provider.succeed(Account, { |
| 573 | stables: ["id", "type", "country", "created"], |
| 574 | |
| 575 | diff: Effect.fn(function* ({ olds, news, output }) { |
| 576 | if (!isResolved(news)) return undefined; |
| 577 | if (shouldReplace(news, olds, output)) { |
| 578 | return { action: "replace" as const }; |
| 579 | } |
| 580 | return undefined; |
| 581 | }), |
| 582 | |
| 583 | read: Effect.fn(function* ({ id, output }) { |
| 584 | const existing = yield* observe({ |
| 585 | id: output?.id, |
| 586 | logicalId: id, |
| 587 | }); |
| 588 | if (existing === undefined) return undefined; |
| 589 | const attrs = toAttrs(existing); |
| 590 | return (yield* hasAlchemyMetadata(id, tagRecord(existing.metadata))) ? attrs : Unowned(attrs); |
| 591 | }), |
| 592 | |
| 593 | list: Effect.fn(function* () { |
| 594 | const accounts = yield* listAllAccounts(); |
| 595 | return accounts |
| 596 | .filter((account) => { |
| 597 | const metadata = tagRecord(account.metadata); |
| 598 | return metadata[alchemyMetadataKeys.stack] !== undefined; |
| 599 | }) |
| 600 | .map(toAttrs); |
| 601 | }), |
| 602 | |
| 603 | reconcile: Effect.fn(function* ({ id, news, olds, output, instanceId }) { |
| 604 | const metadata = yield* desiredMetadata(id, news.metadata); |
| 605 | const businessProfile = |
| 606 | news.businessProfile !== undefined |
| 607 | ? toWireBusinessProfile(news.businessProfile) |
| 608 | : undefined; |
| 609 | const controller = |
| 610 | news.controller !== undefined ? toWireController(news.controller) : undefined; |
| 611 | const tosAcceptance = |
| 612 | news.tosAcceptance !== undefined ? toWireTosAcceptance(news.tosAcceptance) : undefined; |
| 613 | |
| 614 | let current = yield* observe({ |
| 615 | id: output?.id, |
| 616 | logicalId: id, |
| 617 | }); |
| 618 | let createdThisPass = false; |
| 619 | |
| 620 | if (current === undefined) { |
| 621 | current = yield* CreateAccount({ |
| 622 | ...(news.type !== undefined ? { type: news.type } : {}), |
| 623 | ...(news.country !== undefined ? { country: news.country } : {}), |
| 624 | ...(controller !== undefined ? { controller } : {}), |
| 625 | ...(news.email !== undefined ? { email: news.email } : {}), |
| 626 | ...(news.businessType !== undefined ? { business_type: news.businessType } : {}), |
| 627 | ...(businessProfile !== undefined ? { business_profile: businessProfile } : {}), |
| 628 | ...(news.capabilities !== undefined ? { capabilities: news.capabilities } : {}), |
| 629 | ...(news.settings !== undefined ? { settings: news.settings } : {}), |
| 630 | ...(news.defaultCurrency !== undefined ? { default_currency: news.defaultCurrency } : {}), |
| 631 | ...(news.company !== undefined ? { company: news.company } : {}), |
| 632 | ...(news.individual !== undefined ? { individual: news.individual } : {}), |
| 633 | ...(tosAcceptance !== undefined ? { tos_acceptance: tosAcceptance } : {}), |
| 634 | metadata, |
| 635 | }).pipe( |
| 636 | withRequestOptions({ |
| 637 | idempotencyKey: `alchemy-account-${instanceId}`, |
| 638 | }), |
| 639 | ); |
| 640 | createdThisPass = true; |
| 641 | } |
| 642 | |
| 643 | const observedMetadata = tagRecord(current.metadata); |
| 644 | const { upsert, removed } = diffMetadata(observedMetadata, metadata); |
| 645 | const metadataChanged = upsert.length > 0 || removed.length > 0; |
| 646 | const emailChanged = news.email !== undefined && (current.email ?? undefined) !== news.email; |
| 647 | const businessTypeChanged = |
| 648 | news.businessType !== undefined && |
| 649 | (current.business_type ?? undefined) !== news.businessType; |
| 650 | const defaultCurrencyChanged = |
| 651 | news.defaultCurrency !== undefined && current.default_currency !== news.defaultCurrency; |
| 652 | const profileChanged = businessProfileChanged(news.businessProfile, current.business_profile); |
| 653 | const capsChanged = capabilitiesDiverge( |
| 654 | news.capabilities, |
| 655 | capabilityStatuses(current.capabilities), |
| 656 | ); |
| 657 | const writeOnlyChanged = |
| 658 | !createdThisPass && |
| 659 | ((news.settings !== undefined && |
| 660 | (olds === undefined || |
| 661 | !deepEqual(news.settings, olds.settings, { |
| 662 | stripNullish: true, |
| 663 | }))) || |
| 664 | (news.company !== undefined && |
| 665 | (olds === undefined || |
| 666 | !deepEqual(news.company, olds.company, { |
| 667 | stripNullish: true, |
| 668 | }))) || |
| 669 | (news.individual !== undefined && |
| 670 | (olds === undefined || |
| 671 | !deepEqual(news.individual, olds.individual, { |
| 672 | stripNullish: true, |
| 673 | }))) || |
| 674 | (news.tosAcceptance !== undefined && |
| 675 | (olds === undefined || |
| 676 | !deepEqual(news.tosAcceptance, olds.tosAcceptance, { |
| 677 | stripNullish: true, |
| 678 | })))); |
| 679 | |
| 680 | if ( |
| 681 | !emailChanged && |
| 682 | !businessTypeChanged && |
| 683 | !defaultCurrencyChanged && |
| 684 | !profileChanged && |
| 685 | !capsChanged && |
| 686 | !writeOnlyChanged && |
| 687 | !metadataChanged |
| 688 | ) { |
| 689 | return toAttrs(current); |
| 690 | } |
| 691 | |
| 692 | const updated = yield* UpdateAccount({ |
| 693 | account: current.id, |
| 694 | ...(emailChanged ? { email: news.email } : {}), |
| 695 | ...(businessTypeChanged ? { business_type: news.businessType } : {}), |
| 696 | ...(defaultCurrencyChanged ? { default_currency: news.defaultCurrency } : {}), |
| 697 | ...(profileChanged ? { business_profile: businessProfile } : {}), |
| 698 | ...(capsChanged ? { capabilities: news.capabilities } : {}), |
| 699 | ...(writeOnlyChanged && news.settings !== undefined ? { settings: news.settings } : {}), |
| 700 | ...(writeOnlyChanged && news.company !== undefined ? { company: news.company } : {}), |
| 701 | ...(writeOnlyChanged && news.individual !== undefined |
| 702 | ? { individual: news.individual } |
| 703 | : {}), |
| 704 | ...(writeOnlyChanged && tosAcceptance !== undefined |
| 705 | ? { tos_acceptance: tosAcceptance } |
| 706 | : {}), |
| 707 | ...(metadataChanged |
| 708 | ? { |
| 709 | metadata: { |
| 710 | ...Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value])), |
| 711 | ...Object.fromEntries(removed.map((key) => [key, ""])), |
| 712 | }, |
| 713 | } |
| 714 | : {}), |
| 715 | }); |
| 716 | return toAttrs(updated); |
| 717 | }), |
| 718 | |
| 719 | delete: Effect.fn(function* ({ output }) { |
| 720 | yield* DeleteAccount({ account: output.id }).pipe( |
| 721 | Effect.catchIf(isMissingAccount, () => Effect.void), |
| 722 | ); |
| 723 | }), |
| 724 | }); |