@volter/twin-stripe 0.1.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) hide show
  1. package/README.md +64 -27
  2. package/client/dashboard-api.ts +286 -0
  3. package/client/stripe-mirror.css +272 -159
  4. package/client/stripe-mirror.tsx +1384 -541
  5. package/dist/client/dashboard-api.d.ts +107 -0
  6. package/dist/client/dashboard-api.js +238 -0
  7. package/dist/client/dashboard-api.ts +286 -0
  8. package/dist/client/stripe-mirror.bundle.js +236 -0
  9. package/dist/client/stripe-mirror.css +275 -0
  10. package/dist/client/stripe-mirror.d.ts +134 -0
  11. package/dist/client/stripe-mirror.js +823 -0
  12. package/dist/client/stripe-mirror.tsx +1534 -0
  13. package/dist/src/cli.d.ts +2 -0
  14. package/dist/src/cli.js +39 -0
  15. package/dist/src/generated/events.gen.json +1 -0
  16. package/dist/src/generated/surface.gen.json +1 -0
  17. package/dist/src/generated/ui.gen.json +1 -0
  18. package/dist/src/index.d.ts +14 -0
  19. package/dist/src/index.js +73 -0
  20. package/dist/src/manifest.d.ts +2 -0
  21. package/dist/src/manifest.js +1065 -0
  22. package/dist/src/screens/checkout.d.ts +31 -0
  23. package/dist/src/screens/checkout.js +241 -0
  24. package/dist/src/screens/consent-skin.d.ts +4 -0
  25. package/dist/src/screens/consent-skin.js +18 -0
  26. package/dist/src/screens/financial-connections.d.ts +5 -0
  27. package/dist/src/screens/financial-connections.js +90 -0
  28. package/dist/src/screens/identity.d.ts +5 -0
  29. package/dist/src/screens/identity.js +86 -0
  30. package/dist/src/screens/industries.d.ts +1 -0
  31. package/dist/src/screens/industries.js +267 -0
  32. package/dist/src/screens/onboarding.d.ts +13 -0
  33. package/dist/src/screens/onboarding.js +225 -0
  34. package/dist/src/screens/portal.d.ts +5 -0
  35. package/dist/src/screens/portal.js +214 -0
  36. package/dist/src/screens/public-details.d.ts +5 -0
  37. package/dist/src/screens/public-details.js +90 -0
  38. package/dist/src/semantics/after-payment.d.ts +22 -0
  39. package/dist/src/semantics/after-payment.js +93 -0
  40. package/dist/src/semantics/apps-secrets.d.ts +2 -0
  41. package/dist/src/semantics/apps-secrets.js +54 -0
  42. package/dist/src/semantics/balance.d.ts +11 -0
  43. package/dist/src/semantics/balance.js +195 -0
  44. package/dist/src/semantics/billing.d.ts +2 -0
  45. package/dist/src/semantics/billing.js +220 -0
  46. package/dist/src/semantics/charges.d.ts +28 -0
  47. package/dist/src/semantics/charges.js +201 -0
  48. package/dist/src/semantics/checkout.d.ts +15 -0
  49. package/dist/src/semantics/checkout.js +303 -0
  50. package/dist/src/semantics/connect.d.ts +5 -0
  51. package/dist/src/semantics/connect.js +476 -0
  52. package/dist/src/semantics/coupons.d.ts +6 -0
  53. package/dist/src/semantics/coupons.js +92 -0
  54. package/dist/src/semantics/credit-notes.d.ts +2 -0
  55. package/dist/src/semantics/credit-notes.js +172 -0
  56. package/dist/src/semantics/customers.d.ts +6 -0
  57. package/dist/src/semantics/customers.js +429 -0
  58. package/dist/src/semantics/disputes.d.ts +2 -0
  59. package/dist/src/semantics/disputes.js +51 -0
  60. package/dist/src/semantics/entitlements.d.ts +2 -0
  61. package/dist/src/semantics/entitlements.js +95 -0
  62. package/dist/src/semantics/ephemeral-keys.d.ts +2 -0
  63. package/dist/src/semantics/ephemeral-keys.js +34 -0
  64. package/dist/src/semantics/files.d.ts +2 -0
  65. package/dist/src/semantics/files.js +125 -0
  66. package/dist/src/semantics/invoices.d.ts +18 -0
  67. package/dist/src/semantics/invoices.js +541 -0
  68. package/dist/src/semantics/issuing.d.ts +13 -0
  69. package/dist/src/semantics/issuing.js +570 -0
  70. package/dist/src/semantics/ledger.d.ts +54 -0
  71. package/dist/src/semantics/ledger.js +181 -0
  72. package/dist/src/semantics/payment-intents.d.ts +18 -0
  73. package/dist/src/semantics/payment-intents.js +404 -0
  74. package/dist/src/semantics/payment-links.d.ts +2 -0
  75. package/dist/src/semantics/payment-links.js +133 -0
  76. package/dist/src/semantics/payment-methods.d.ts +20 -0
  77. package/dist/src/semantics/payment-methods.js +138 -0
  78. package/dist/src/semantics/plans.d.ts +5 -0
  79. package/dist/src/semantics/plans.js +121 -0
  80. package/dist/src/semantics/platform.d.ts +9 -0
  81. package/dist/src/semantics/platform.js +206 -0
  82. package/dist/src/semantics/products.d.ts +2 -0
  83. package/dist/src/semantics/products.js +140 -0
  84. package/dist/src/semantics/radar.d.ts +2 -0
  85. package/dist/src/semantics/radar.js +83 -0
  86. package/dist/src/semantics/refunds.d.ts +9 -0
  87. package/dist/src/semantics/refunds.js +195 -0
  88. package/dist/src/semantics/renewals.d.ts +47 -0
  89. package/dist/src/semantics/renewals.js +251 -0
  90. package/dist/src/semantics/setup-intents.d.ts +2 -0
  91. package/dist/src/semantics/setup-intents.js +84 -0
  92. package/dist/src/semantics/shared.d.ts +78 -0
  93. package/dist/src/semantics/shared.js +192 -0
  94. package/dist/src/semantics/subscription-schedules.d.ts +2 -0
  95. package/dist/src/semantics/subscription-schedules.js +119 -0
  96. package/dist/src/semantics/subscriptions.d.ts +11 -0
  97. package/dist/src/semantics/subscriptions.js +605 -0
  98. package/dist/src/semantics/tax.d.ts +2 -0
  99. package/dist/src/semantics/tax.js +197 -0
  100. package/dist/src/semantics/terminal.d.ts +5 -0
  101. package/dist/src/semantics/terminal.js +182 -0
  102. package/dist/src/semantics/test-clocks.d.ts +6 -0
  103. package/dist/src/semantics/test-clocks.js +73 -0
  104. package/dist/src/semantics/tokens.d.ts +4 -0
  105. package/dist/src/semantics/tokens.js +44 -0
  106. package/dist/src/semantics/transfers.d.ts +2 -0
  107. package/dist/src/semantics/transfers.js +154 -0
  108. package/dist/src/semantics/treasury.d.ts +2 -0
  109. package/dist/src/semantics/treasury.js +377 -0
  110. package/dist/src/semantics/webhook-endpoints.d.ts +3 -0
  111. package/dist/src/semantics/webhook-endpoints.js +85 -0
  112. package/dist/src/stripe-budget.d.ts +55 -0
  113. package/dist/src/stripe-budget.js +155 -0
  114. package/dist/src/stripe-capabilities.d.ts +3 -0
  115. package/dist/src/stripe-capabilities.js +5052 -0
  116. package/dist/src/stripe-conformance.d.ts +41 -0
  117. package/dist/src/stripe-conformance.js +96 -0
  118. package/dist/src/stripe-connector.d.ts +161 -0
  119. package/dist/src/stripe-connector.js +414 -0
  120. package/dist/src/stripe-emit.d.ts +2 -0
  121. package/dist/src/stripe-emit.js +145 -0
  122. package/dist/src/stripe-events.d.ts +93 -0
  123. package/dist/src/stripe-events.js +388 -0
  124. package/dist/src/stripe-js.d.ts +4 -0
  125. package/dist/src/stripe-js.js +70 -0
  126. package/dist/src/stripe-mirror-ui.d.ts +15 -0
  127. package/dist/src/stripe-mirror-ui.js +87 -0
  128. package/dist/src/stripe-params.d.ts +3 -0
  129. package/dist/src/stripe-params.js +43 -0
  130. package/dist/src/stripe-perform-harness.d.ts +9 -0
  131. package/dist/src/stripe-perform-harness.js +26 -0
  132. package/dist/src/stripe-server.d.ts +33 -0
  133. package/dist/src/stripe-server.js +326 -0
  134. package/dist/src/stripe-shared.d.ts +106 -0
  135. package/dist/src/stripe-shared.js +273 -0
  136. package/dist/src/stripe-twin.d.ts +155 -0
  137. package/dist/src/stripe-twin.js +1226 -0
  138. package/dist/src/stripe-ui-conformance.d.ts +5 -0
  139. package/dist/src/stripe-ui-conformance.js +79 -0
  140. package/dist/src/stripe-ui-structure.d.ts +3 -0
  141. package/dist/src/stripe-ui-structure.js +168 -0
  142. package/dist/src/stripe-version.d.ts +10 -0
  143. package/dist/src/stripe-version.js +285 -0
  144. package/dist/test-fixtures/stripe-known-deviations.json +105 -0
  145. package/dist/test-fixtures/stripe-openapi-operations.SOURCE.md +14 -0
  146. package/dist/test-fixtures/stripe-openapi-operations.json +4717 -0
  147. package/dist/test-fixtures/stripe-schemas.SOURCE.md +35 -0
  148. package/dist/test-fixtures/stripe-schemas.json +3740 -0
  149. package/package.json +18 -10
  150. package/src/cli.ts +7 -7
  151. package/src/generated/events.gen.json +1 -0
  152. package/src/generated/surface.gen.json +1 -0
  153. package/src/generated/ui.gen.json +1 -0
  154. package/src/index.ts +31 -9
  155. package/src/manifest.ts +1097 -0
  156. package/src/screens/checkout.tsx +252 -0
  157. package/src/screens/consent-skin.ts +20 -0
  158. package/src/screens/financial-connections.tsx +101 -0
  159. package/src/screens/identity.tsx +96 -0
  160. package/src/screens/industries.ts +267 -0
  161. package/src/screens/onboarding.tsx +243 -0
  162. package/src/screens/portal.tsx +218 -0
  163. package/src/screens/public-details.tsx +105 -0
  164. package/src/semantics/after-payment.ts +113 -0
  165. package/src/semantics/apps-secrets.ts +58 -0
  166. package/src/semantics/balance.ts +209 -0
  167. package/src/semantics/billing.ts +216 -0
  168. package/src/semantics/charges.ts +211 -0
  169. package/src/semantics/checkout.ts +297 -0
  170. package/src/semantics/connect.ts +471 -0
  171. package/src/semantics/coupons.ts +97 -0
  172. package/src/semantics/credit-notes.ts +168 -0
  173. package/src/semantics/customers.ts +432 -0
  174. package/src/semantics/disputes.ts +62 -0
  175. package/src/semantics/entitlements.ts +94 -0
  176. package/src/semantics/ephemeral-keys.ts +34 -0
  177. package/src/semantics/files.ts +143 -0
  178. package/src/semantics/invoices.ts +541 -0
  179. package/src/semantics/issuing.ts +585 -0
  180. package/src/semantics/ledger.ts +216 -0
  181. package/src/semantics/payment-intents.ts +420 -0
  182. package/src/semantics/payment-links.ts +148 -0
  183. package/src/semantics/payment-methods.ts +143 -0
  184. package/src/semantics/plans.ts +131 -0
  185. package/src/semantics/platform.ts +220 -0
  186. package/src/semantics/products.ts +154 -0
  187. package/src/semantics/radar.ts +85 -0
  188. package/src/semantics/refunds.ts +218 -0
  189. package/src/semantics/renewals.ts +274 -0
  190. package/src/semantics/setup-intents.ts +87 -0
  191. package/src/semantics/shared.ts +215 -0
  192. package/src/semantics/subscription-schedules.ts +129 -0
  193. package/src/semantics/subscriptions.ts +610 -0
  194. package/src/semantics/tax.ts +220 -0
  195. package/src/semantics/terminal.ts +195 -0
  196. package/src/semantics/test-clocks.ts +77 -0
  197. package/src/semantics/tokens.ts +52 -0
  198. package/src/semantics/transfers.ts +174 -0
  199. package/src/semantics/treasury.ts +383 -0
  200. package/src/semantics/webhook-endpoints.ts +87 -0
  201. package/src/stripe-budget.ts +4 -4
  202. package/src/stripe-capabilities.ts +1456 -222
  203. package/src/stripe-conformance.ts +6 -5
  204. package/src/stripe-connector.ts +68 -40
  205. package/src/stripe-emit.ts +14 -7
  206. package/src/stripe-events.ts +94 -36
  207. package/src/stripe-js.ts +70 -0
  208. package/src/stripe-mirror-ui.ts +28 -298
  209. package/src/stripe-params.ts +44 -0
  210. package/src/stripe-perform-harness.ts +29 -0
  211. package/src/stripe-server.ts +263 -38
  212. package/src/stripe-shared.ts +294 -0
  213. package/src/stripe-twin.ts +429 -5325
  214. package/src/stripe-ui-conformance.ts +70 -107
  215. package/src/stripe-ui-structure.ts +124 -348
  216. package/src/stripe-version.ts +278 -0
  217. package/test-fixtures/stripe-known-deviations.json +2 -7
  218. package/test-fixtures/stripe-openapi-operations.json +1188 -2855
  219. package/src/stripe-form.ts +0 -35
@@ -0,0 +1,1097 @@
1
+ // Stripe's manifest: the vendor facts its published spec does not carry, and the resources the
2
+ // derived core serves (docs/contributing/architecture.md, "Protocol 3"). The surface itself is
3
+ // generated (./generated/surface.gen.json, from ../spec by scripts/derive-pack.ts).
4
+ import type { DerivedManifest, StateField, Transition } from '@volter/world-core';
5
+ import { afterStripeWrite, embedIssuingAuthorizationCard, isValidApiVersion, view } from './stripe-twin.ts';
6
+
7
+ const unexpected = (verb: string, allowed: string) => ({
8
+ status: 400,
9
+ code: 'payment_intent_unexpected_state',
10
+ message: `This PaymentIntent could not be ${verb} because it has a status of {from}. ${allowed}`,
11
+ });
12
+ const OPEN = ['requires_payment_method', 'requires_confirmation', 'requires_action', 'requires_capture', 'processing'];
13
+
14
+ /** A move no API call makes: Stripe's own (`vendor`), the clock's (`time`), or the person on a
15
+ * Stripe-hosted page (`external`: Checkout, the billing portal, a hosted invoice or 3DS page). */
16
+ const by = (actor: 'vendor' | 'time' | 'external', from: string[], to: string, source: string): Transition => ({ actor, from, to, source });
17
+ /** A bank account's `status` as a payout or payment destination. Stripe validates its routing number,
18
+ * verifies it (micro-deposits, or instantly) and marks it errored when a payout or debit to it fails
19
+ * (the page each machine cites); no call the twin serves does any of that (the customer-source verify is
20
+ * a gap), so no move of it is the twin's. */
21
+ const bankAccountStatus = (_doc: string): StateField => ({ initial: 'new', transitions: [] });
22
+
23
+ /** A flag an update sets either way. */
24
+ const flag = (operation: string, source: string): Transition[] => ['true', 'false'].map((to) => ({ operation, from: '*' as const, to, source }));
25
+
26
+ /** A PaymentIntent's `status`: which operation may move it from where, and what Stripe answers otherwise. */
27
+ const paymentIntentStatus: StateField = {
28
+ // "After you create the PaymentIntent, its status is `requires_payment_method` until you attach a payment method"
29
+ // (docs.stripe.com/payments/paymentintents/lifecycle)
30
+ initial: 'requires_payment_method',
31
+ transitions: [
32
+ // created with its payment method, it "enters the `requires_confirmation` status and is ready to confirm" (the same page)
33
+ { operation: 'PostPaymentIntents', from: ['requires_payment_method'], to: 'requires_confirmation', source: 'https://docs.stripe.com/payments/paymentintents/lifecycle' },
34
+ // confirm lands on one of its outcomes, decided by the payment method and the capture method
35
+ ...['requires_payment_method', 'requires_action', 'requires_capture', 'succeeded'].map((to) => ({
36
+ operation: 'PostPaymentIntentsIntentConfirm',
37
+ from: ['requires_payment_method', 'requires_confirmation', 'requires_action'],
38
+ to,
39
+ refusal: { status: 400, code: 'payment_intent_unexpected_state', message: 'You cannot confirm this PaymentIntent because it has a status of {from}.' },
40
+ source: 'https://docs.stripe.com/api/payment_intents/confirm',
41
+ })),
42
+ // a bank debit confirmed (created with `confirm`, confirmed, or verified by micro-deposits) is submitted and
43
+ // processes: "The PaymentIntent you create initially has a status of `processing`"; "When the bank account is
44
+ // successfully verified, Stripe returns the PaymentIntent object with a status of `processing`"
45
+ ...['PostPaymentIntents', 'PostPaymentIntentsIntentConfirm'].map((operation) => ({
46
+ operation, from: ['requires_payment_method', 'requires_confirmation', 'requires_action'], to: 'processing',
47
+ source: 'https://docs.stripe.com/payments/ach-direct-debit/accept-a-payment?payment-ui=direct-api',
48
+ })),
49
+ // and succeeds: "After the payment has succeeded, the PaymentIntent status is updated from `processing`
50
+ // to `succeeded`" (semantics/payment-intents.ts settleBankDebits)
51
+ by('vendor', ['processing'], 'succeeded', 'https://docs.stripe.com/payments/ach-direct-debit/accept-a-payment?payment-ui=direct-api'),
52
+ // creating one with `confirm` confirms it at once, landing where a confirm lands
53
+ ...['requires_payment_method', 'requires_action', 'requires_capture', 'succeeded'].map((to) => ({
54
+ operation: 'PostPaymentIntents',
55
+ from: ['requires_payment_method', 'requires_confirmation'],
56
+ to,
57
+ source: 'spec:PostPaymentIntents "Set to `true` to attempt to [confirm this PaymentIntent](https://docs.stripe.com/api/payment_intents/confirm) immediately."',
58
+ })),
59
+ {
60
+ operation: 'PostPaymentIntentsIntentCapture',
61
+ from: ['requires_capture'],
62
+ to: 'succeeded',
63
+ refusal: unexpected('captured', 'Only a PaymentIntent with one of the following statuses may be captured: requires_capture.'),
64
+ source: 'https://docs.stripe.com/api/payment_intents/capture',
65
+ },
66
+ {
67
+ operation: 'PostPaymentIntentsIntentIncrementAuthorization',
68
+ from: ['requires_capture'],
69
+ to: 'requires_capture',
70
+ refusal: unexpected('incremented', 'Only a PaymentIntent with a status of requires_capture may be incremented.'),
71
+ source: 'https://docs.stripe.com/api/payment_intents/increment_authorization',
72
+ },
73
+ {
74
+ operation: 'PostPaymentIntentsIntentCancel',
75
+ from: OPEN,
76
+ to: 'canceled',
77
+ refusal: unexpected('canceled', 'Only a PaymentIntent with one of the following statuses may be canceled: requires_payment_method, requires_capture, requires_confirmation, requires_action, processing.'),
78
+ source: 'https://docs.stripe.com/api/payment_intents/cancel',
79
+ },
80
+ {
81
+ operation: 'PostPaymentIntentsIntentVerifyMicrodeposits',
82
+ from: ['requires_action'],
83
+ to: 'processing',
84
+ refusal: { status: 400, code: 'payment_intent_unexpected_state', message: 'This PaymentIntent could not be verified because it has a status of {from}.' },
85
+ source: 'https://docs.stripe.com/payments/ach-direct-debit/accept-a-payment?payment-ui=direct-api',
86
+ },
87
+ {
88
+ // paying the invoice an intent collects for settles the intent
89
+ operation: 'PostInvoicesInvoicePay',
90
+ from: OPEN,
91
+ to: 'succeeded',
92
+ source: 'https://docs.stripe.com/api/invoices/pay',
93
+ },
94
+ ...['succeeded', 'requires_action'].map((to) => ({
95
+ operation: 'PostPaymentIntentsIntentApplyCustomerBalance',
96
+ from: OPEN,
97
+ to,
98
+ refusal: { status: 400, code: 'payment_intent_unexpected_state', message: 'This PaymentIntent could not be updated because it has a status of {from}.' },
99
+ source: 'https://docs.stripe.com/api/payment_intents/apply_customer_balance',
100
+ })),
101
+ // a card presented to the Terminal reader processing an intent pays it (held, under manual capture)
102
+ ...['succeeded', 'requires_capture'].map((to) => ({
103
+ operation: 'PostTestHelpersTerminalReadersReaderPresentPaymentMethod', from: ['requires_payment_method', 'requires_confirmation'], to,
104
+ source: 'https://docs.stripe.com/api/terminal/readers/present_payment_method',
105
+ })),
106
+ // the customer pays, in the billing portal, the invoice an intent collects for after its charge was declined
107
+ by('external', ['requires_payment_method'], 'succeeded', 'https://docs.stripe.com/customer-management'),
108
+ // Stripe also fails a bank debit back to needing a payment method, completes 3-D Secure on the bank's page and
109
+ // cancels a hold left uncaptured; the twin's bank debits succeed unless their test account stays processing, it has no 3-D Secure page, and it keeps
110
+ // holds until they are captured or canceled
111
+ ],
112
+ };
113
+
114
+ /** A charge's `captured`: an authorization (capture=false) is captured once. */
115
+ const chargeCaptured: StateField = {
116
+ initial: true,
117
+ transitions: [
118
+ {
119
+ operation: 'PostChargesChargeCapture',
120
+ from: ['false'],
121
+ to: 'true',
122
+ refusal: { status: 400, code: 'charge_already_captured', message: 'Charge ch_xxx has already been captured.' },
123
+ source: 'https://docs.stripe.com/api/charges/capture',
124
+ },
125
+ // a manual-capture intent's capture captures the charge its confirm authorized
126
+ { operation: 'PostPaymentIntentsIntentCapture', from: ['false'], to: 'true', source: 'https://docs.stripe.com/api/payment_intents/capture' },
127
+ ],
128
+ };
129
+
130
+ /** A charge's `refunded`: true once refunds take its whole amount, false again when a refund that made it so is
131
+ * canceled. A capture or a cancel never makes it so: "`refunded` will no longer be `true` for payment cancellation
132
+ * flows", and a partial capture makes no Refund (docs.stripe.com/changelog/basil/2025-03-31/remove-refund-from-partial-
133
+ * capture-and-payment-cancellation-flow). */
134
+ const chargeRefunded: StateField = {
135
+ initial: false,
136
+ transitions: [
137
+ ...['PostRefunds', 'PostChargesChargeRefunds', 'PostCreditNotes'].map((operation) => ({ operation, from: ['false'], to: 'true', source: 'https://docs.stripe.com/api/charges/object#charge_object-refunded' })),
138
+ { operation: 'PostRefundsRefundCancel', from: ['true'], to: 'false', source: 'https://docs.stripe.com/api/refunds/cancel' },
139
+ // (an authorization left uncaptured is canceled after seven days, "Uncaptured PaymentIntents are cancelled a set
140
+ // number of days (7 by default) after their creation", docs.stripe.com/api/payment_intents/capture; the twin keeps it)
141
+ ],
142
+ };
143
+
144
+ /** A charge's `status`: the twin settles a charge when it is made (a declined one is never
145
+ * stored); an asynchronous one settles later, on the network's word. */
146
+ const chargeStatus: StateField = {
147
+ initial: 'succeeded',
148
+ transitions: [
149
+ // (an asynchronous charge is pending at Stripe until it settles or fails; the twin's settle when made)
150
+ ],
151
+ };
152
+
153
+ /** A charge's `paid`: true once it succeeded or was authorized; a pending one becomes paid when it settles. */
154
+ const chargePaid: StateField = {
155
+ initial: true,
156
+ // (a charge is paid when it settles; the twin's settle when made)
157
+ transitions: [],
158
+ };
159
+
160
+ /** A refund's `status`: only one waiting on the customer (requires_action) may be canceled; the
161
+ * rest is the network's. */
162
+ const refundStatus: StateField = {
163
+ initial: 'succeeded',
164
+ transitions: [
165
+ {
166
+ operation: 'PostRefundsRefundCancel',
167
+ from: ['requires_action'],
168
+ to: 'canceled',
169
+ refusal: { status: 400, code: 'refund_status_invalid', message: 'Refund {id} cannot be canceled because its status is {from}.' },
170
+ source: 'https://docs.stripe.com/api/refunds/cancel',
171
+ },
172
+ // a card refund the available balance does not cover is held pending, and made once the balance covers it: "Stripe
173
+ // holds the refund as pending for card transactions ... until your Stripe balance becomes sufficient"
174
+ // (docs.stripe.com/refunds; semantics/refunds.ts)
175
+ // (a paid invoice's credit note makes its refund as a refund call does: "Refunds: create a new refund (using
176
+ // refund_amount)", docs.stripe.com/api/credit_notes/create)
177
+ ...['PostRefunds', 'PostChargesChargeRefunds', 'PostCreditNotes'].map((operation) => ({ operation, from: ['succeeded'], to: 'pending', source: 'https://docs.stripe.com/refunds' })),
178
+ by('vendor', ['pending'], 'succeeded', 'https://docs.stripe.com/refunds'),
179
+ // a bank-transfer payment's refund waits in requires_action for the customer's bank details, and is made so
180
+ // (semantics/refunds.ts); (Stripe also fails some refunds; the twin's do not fail)
181
+ ],
182
+ };
183
+
184
+ const SETUP_OPEN = ['requires_payment_method', 'requires_confirmation', 'requires_action'];
185
+ const setupUnexpected = (verb: string) => ({ status: 400, code: 'setup_intent_unexpected_state', message: `You cannot ${verb} this SetupIntent because it has a status of {from}.` });
186
+
187
+ /** A SetupIntent's `status`: confirm settles it (or leaves a bank account awaiting micro-deposits),
188
+ * cancel ends an open one, and verification completes the micro-deposit wait. */
189
+ const setupIntentStatus: StateField = {
190
+ // "After you create the SetupIntent, it has a status of `requires_payment_method` until you attach a payment method"
191
+ // (docs.stripe.com/payments/paymentintents/lifecycle)
192
+ initial: 'requires_payment_method',
193
+ transitions: [
194
+ // created with its payment method, it "enters the `requires_confirmation` status and is ready to confirm" (the same page)
195
+ { operation: 'PostSetupIntents', from: ['requires_payment_method'], to: 'requires_confirmation', source: 'https://docs.stripe.com/payments/paymentintents/lifecycle' },
196
+ ...['requires_action', 'succeeded'].map((to) => ({
197
+ operation: 'PostSetupIntentsIntentConfirm',
198
+ from: SETUP_OPEN,
199
+ to,
200
+ refusal: setupUnexpected('confirm'),
201
+ source: 'https://docs.stripe.com/api/setup_intents/confirm',
202
+ })),
203
+ {
204
+ operation: 'PostSetupIntentsIntentCancel',
205
+ from: SETUP_OPEN,
206
+ to: 'canceled',
207
+ refusal: setupUnexpected('cancel'),
208
+ source: 'https://docs.stripe.com/api/setup_intents/cancel',
209
+ },
210
+ {
211
+ operation: 'PostSetupIntentsIntentVerifyMicrodeposits',
212
+ from: ['requires_action'],
213
+ to: 'succeeded',
214
+ refusal: { status: 400, code: 'setup_intent_unexpected_state', message: 'This SetupIntent could not be verified because it has a status of {from}.' },
215
+ source: 'https://docs.stripe.com/api/setup_intents/verify_microdeposits',
216
+ },
217
+ // (Stripe completes 3-D Secure on the bank's page and settles an asynchronous method from processing; the
218
+ // twin has no such page and settles every method at once)
219
+ ],
220
+ };
221
+
222
+ const invoiceRefusal = (message: string) => ({ status: 400, code: 'invoice_not_editable', message });
223
+
224
+ /** An invoice's `status`: a draft is finalized (or sent, which finalizes it) into open, an open one
225
+ * is paid, written off or voided. Sending leaves any other status where it is. */
226
+ const invoiceStatus: StateField = {
227
+ initial: 'draft',
228
+ transitions: [
229
+ {
230
+ operation: 'PostInvoicesInvoiceFinalize',
231
+ from: ['draft'],
232
+ to: 'open',
233
+ refusal: invoiceRefusal('This invoice cannot be finalized because it has status {from}.'),
234
+ source: 'https://docs.stripe.com/api/invoices/finalize',
235
+ },
236
+ // docs.stripe.com/invoicing/integration: "To finalize a draft invoice, use the Dashboard, send it to the customer, or pay it."
237
+ { operation: 'PostInvoicesInvoiceSend', from: ['draft'], to: 'open', source: 'https://docs.stripe.com/invoicing/integration' },
238
+ { operation: 'PostInvoicesInvoiceSend', from: ['open', 'paid', 'uncollectible', 'void'], source: 'https://docs.stripe.com/api/invoices/send' },
239
+ {
240
+ operation: 'PostInvoicesInvoicePay',
241
+ from: ['open', 'uncollectible'],
242
+ to: 'paid',
243
+ refusal: invoiceRefusal('This invoice cannot be paid because it has status {from}.'),
244
+ refusals: { paid: { status: 400, code: 'invoice_payment_intent_requires_action', message: 'This invoice has already been paid.' } },
245
+ source: 'https://docs.stripe.com/api/invoices/pay',
246
+ },
247
+ {
248
+ operation: 'PostInvoicesInvoiceMarkUncollectible',
249
+ from: ['open'],
250
+ to: 'uncollectible',
251
+ refusal: invoiceRefusal('Only open invoices can be marked uncollectible (this one is {from}).'),
252
+ source: 'https://docs.stripe.com/api/invoices/mark_uncollectible',
253
+ },
254
+ {
255
+ // only a finalized invoice is voided; a draft is deleted
256
+ operation: 'PostInvoicesInvoiceVoid',
257
+ from: ['open', 'uncollectible'],
258
+ to: 'void',
259
+ refusal: invoiceRefusal('This invoice cannot be voided because it has status {from}.'),
260
+ source: 'https://docs.stripe.com/api/invoices/void',
261
+ },
262
+ // confirming or capturing the PaymentIntent an invoice collects through pays the invoice
263
+ ...['PostPaymentIntentsIntentConfirm', 'PostPaymentIntentsIntentCapture'].map((operation) => ({
264
+ operation, from: ['draft', 'open', 'uncollectible'], to: 'paid', source: 'https://docs.stripe.com/billing/subscriptions/build-subscriptions',
265
+ })),
266
+ // as does its bank debit succeeding once submitted (semantics/payment-intents.ts settleBankDebits)
267
+ by('vendor', ['draft', 'open', 'uncollectible'], 'paid', 'https://docs.stripe.com/billing/subscriptions/build-subscriptions'),
268
+ // a bank transfer that arrives in the customer's cash balance pays an open invoice that takes transfers
269
+ // (automatic reconciliation; in test mode the funding helper stands in for the transfer)
270
+ { operation: 'PostTestHelpersCustomersCustomerFundCashBalance', from: ['open'], to: 'paid', source: 'https://docs.stripe.com/payments/customer-balance/reconciliation' },
271
+ // a subscription's first invoice is paid on the Checkout page that started it
272
+ by('external', ['draft'], 'paid', 'https://docs.stripe.com/payments/checkout/how-checkout-works'),
273
+ // a subscription's renewal, drafted at its period's end, is finalized about an hour later and charged: paid, or
274
+ // open when the charge is declined (semantics/renewals.ts)
275
+ by('time', ['draft'], 'paid', 'https://docs.stripe.com/invoicing/integration/workflow-transitions#finalized'),
276
+ by('time', ['draft'], 'open', 'https://docs.stripe.com/billing/subscriptions/overview#payment-status'),
277
+ // an update that ends a subscription's trial invoices its new period and attempts payment at once: paid, or open
278
+ // when the charge is declined or not attempted (semantics/subscriptions.ts applyTrialEnd)
279
+ { operation: 'PostSubscriptionsSubscriptionExposedId', from: ['draft'], to: 'paid', source: 'https://docs.stripe.com/billing/subscriptions/upgrade-downgrade#immediate-payment' },
280
+ // a trialing subscription's first invoice, for nothing, is paid as it is made ("An immediate invoice is still
281
+ // created, but the amount is 0", docs.stripe.com/billing/subscriptions/trials/free-trials)
282
+ { operation: 'PostSubscriptions', from: ['draft'], to: 'paid', source: 'https://docs.stripe.com/billing/subscriptions/trials/free-trials' },
283
+ { operation: 'PostSubscriptionsSubscriptionExposedId', from: ['draft'], to: 'open', source: 'https://docs.stripe.com/billing/subscriptions/upgrade-downgrade#immediate-payment' },
284
+ // the customer pays an open invoice in the billing portal
285
+ by('external', ['open'], 'paid', 'https://docs.stripe.com/customer-management'),
286
+ // (Stripe also finalizes any other auto-advancing draft after an hour, retries an open invoice on its schedule
287
+ // and, retries exhausted, may write it off, and takes payment on the hosted invoice page; the twin's other
288
+ // invoices move only by the calls above)
289
+ ],
290
+ };
291
+
292
+ /** A subscription's `status` as the twin's own operations move it; canceling ends any subscription. */
293
+ const subscriptionStatus: StateField = {
294
+ initial: 'active',
295
+ transitions: [
296
+ { operation: 'DeleteSubscriptionsSubscriptionExposedId', from: '*', to: 'canceled', source: 'https://docs.stripe.com/api/subscriptions/cancel' },
297
+ // (a test clock's advance moves no subscription itself: when the clock reaches its target, a trial that ended there
298
+ // ends by time's move below, on the next request; semantics/test-clocks.ts finishClockAdvances)
299
+ // "Deleting the simulation also deletes the test customers associated with the clock and cancels their
300
+ // subscriptions" (docs.stripe.com/billing/testing/test-clocks/api-advanced-usage)
301
+ { operation: 'DeleteTestHelpersTestClocksTestClock', from: '*', to: 'canceled', source: 'https://docs.stripe.com/billing/testing/test-clocks/api-advanced-usage' },
302
+ // "Cancels a subscription schedule and its associated subscription immediately" (docs.stripe.com/api/subscription_schedules/cancel)
303
+ { operation: 'PostSubscriptionSchedulesScheduleCancel', from: ['active', 'trialing', 'past_due', 'incomplete'], to: 'canceled', source: 'https://docs.stripe.com/api/subscription_schedules/cancel' },
304
+ // confirming or capturing the first invoice's PaymentIntent, or paying the invoice itself, pays it and
305
+ // activates the subscription
306
+ ...['PostPaymentIntentsIntentConfirm', 'PostPaymentIntentsIntentCapture'].map((operation) => ({
307
+ operation, from: ['incomplete'], to: 'active', source: 'https://docs.stripe.com/billing/subscriptions/build-subscriptions',
308
+ })),
309
+ // or when its bank debit succeeds once submitted (semantics/payment-intents.ts settleBankDebits)
310
+ by('vendor', ['incomplete'], 'active', 'https://docs.stripe.com/billing/subscriptions/build-subscriptions'),
311
+ // paying the invoice a subscription waits on (its first, or a renewal that failed) makes it active
312
+ { operation: 'PostInvoicesInvoicePay', from: ['incomplete', 'past_due'], to: 'active', source: 'https://docs.stripe.com/billing/subscriptions/overview#payment-status' },
313
+ // an update's `trial_end`: `now` ends a trial at once and charges the new period, active when paid and past_due when
314
+ // not; a future timestamp starts a trial on a subscription out of one (semantics/subscriptions.ts applyTrialEnd)
315
+ { operation: 'PostSubscriptionsSubscriptionExposedId', from: ['trialing'], to: 'active', source: 'https://docs.stripe.com/api/subscriptions/update#update_subscription-trial_end' },
316
+ { operation: 'PostSubscriptionsSubscriptionExposedId', from: ['trialing'], to: 'past_due', source: 'https://docs.stripe.com/billing/subscriptions/upgrade-downgrade#immediate-payment' },
317
+ {
318
+ operation: 'PostSubscriptionsSubscriptionExposedId', from: ['active', 'past_due'], to: 'trialing',
319
+ // (Where the documentation stops and the twin decides: the wording of the refusal for a subscription neither
320
+ // active nor past_due; a canceled one answers what Stripe answers any update of a canceled subscription.)
321
+ refusal: { status: 400, message: 'A trial can only be added to an active or past_due subscription; this one is {from}.' },
322
+ refusals: { canceled: { status: 400, message: 'A canceled subscription can only update its cancellation_details and metadata.' } },
323
+ source: 'https://docs.stripe.com/billing/subscriptions/trials/free-trials#adding-a-new-trial-to-a-subscription-previously-in-a-trial',
324
+ },
325
+ // a trial ends on its own clock (Stripe pauses one that ends with no payment method to bill; the twin's
326
+ // trials end active), and a renewal whose charge is declined leaves the subscription past_due
327
+ // (semantics/renewals.ts)
328
+ by('time', ['trialing'], 'active', 'https://docs.stripe.com/billing/subscriptions/trials'),
329
+ by('time', ['active'], 'past_due', 'https://docs.stripe.com/billing/subscriptions/overview#payment-status'),
330
+ // one set to cancel at its period's end is canceled when the period ends
331
+ by('time', ['active', 'trialing', 'past_due'], 'canceled', 'https://docs.stripe.com/billing/subscriptions/cancel#cancel-at-end-of-cycle'),
332
+ // the customer pays the invoice it waits on in the billing portal
333
+ by('external', ['past_due'], 'active', 'https://docs.stripe.com/customer-management'),
334
+ // (Stripe also expires an incomplete subscription after 23 hours, and retries a failed renewal on its schedule,
335
+ // the settings ending the retries unpaid or canceled; the twin makes no retry)
336
+ // the customer cancels in the billing portal
337
+ by('external', ['active', 'trialing', 'past_due', 'unpaid', 'paused'], 'canceled', 'spec:/components/schemas/portal_subscription_cancel "Whether to cancel subscriptions immediately or at the end of the billing period."'),
338
+ ],
339
+ };
340
+
341
+ const notOpen = (verb: string) => ({ status: 400, code: 'checkout_session_not_open', message: `You may only ${verb} a Checkout Session that is currently in the \`open\` state.` });
342
+
343
+ /** A Checkout Session's `status`: an open session expires (asked to, or 24 hours on), or completes
344
+ * when the customer pays on the hosted page. Completion is the external actor's move, the one the
345
+ * hosted Checkout page (src/screens/checkout.tsx) performs. */
346
+ const checkoutStatus: StateField = {
347
+ initial: 'open',
348
+ transitions: [
349
+ { operation: 'PostCheckoutSessionsSessionExpire', from: ['open'], to: 'expired', refusal: notOpen('expire'), source: 'https://docs.stripe.com/api/checkout/sessions/expire' },
350
+ { actor: 'external', from: ['open'], to: 'complete', refusal: notOpen('complete'), source: 'https://docs.stripe.com/api/checkout/sessions/object#checkout_session_object-status' },
351
+ // (Stripe expires an open session at expires_at; the twin keeps it open until asked)
352
+ ],
353
+ };
354
+
355
+ /** A Checkout Session's `payment_status`: the customer completing a payment or subscription session
356
+ * pays it; a delayed payment method settles later. */
357
+ const checkoutPaymentStatus: StateField = {
358
+ initial: 'unpaid',
359
+ transitions: [
360
+ { actor: 'external', from: '*', to: 'paid', source: 'https://docs.stripe.com/api/checkout/sessions/object#checkout_session_object-payment_status' },
361
+ // (a delayed method settles a session later at Stripe; the twin's settle on the page)
362
+ ],
363
+ };
364
+
365
+ /** A dispute's `status`: closing concedes it; the bank decides the rest, and an unanswered one is
366
+ * lost when its evidence is due. */
367
+ const disputeStatus: StateField = {
368
+ initial: 'warning_needs_response',
369
+ transitions: [
370
+ { operation: 'PostDisputesDisputeClose', from: '*', to: 'lost', source: 'https://docs.stripe.com/api/disputes/close' },
371
+ // submitting evidence puts a dispute (or an inquiry) under review; in test mode the evidence decides it
372
+ { operation: 'PostDisputesDispute', from: ['needs_response'], to: 'under_review', source: 'https://docs.stripe.com/api/disputes/update#update_dispute-submit' },
373
+ { operation: 'PostDisputesDispute', from: ['warning_needs_response'], to: 'warning_under_review', source: 'https://docs.stripe.com/api/disputes/update#update_dispute-submit' },
374
+ by('vendor', ['under_review'], 'won', 'https://docs.stripe.com/testing#evidence'),
375
+ by('vendor', ['under_review'], 'lost', 'https://docs.stripe.com/testing#evidence'),
376
+ // (the bank decides a dispute under review, escalates an inquiry and loses one left unanswered; the twin
377
+ // decides none)
378
+ // Stripe also closes an inquiry the bank drops (warning_closed); no inquiry the twin holds is dropped
379
+ ],
380
+ };
381
+
382
+ /** A payout's `status`: cancel ends it; reversing cancels it and pays a reversal, never twice. */
383
+ const payoutStatus: StateField = {
384
+ initial: 'pending',
385
+ transitions: [
386
+ // only a pending payout can be canceled (docs.stripe.com/api/payouts/cancel); reversing a paid one makes a new
387
+ // payout and leaves the original paid (semantics/balance.ts)
388
+ { operation: 'PostPayoutsPayoutCancel', from: ['pending'], to: 'canceled', source: 'https://docs.stripe.com/api/payouts/cancel' },
389
+ // it arrives in the bank on its arrival date
390
+ by('time', ['pending'], 'paid', 'https://docs.stripe.com/payouts#payout-statuses'),
391
+ // (a bank may fail a payout at Stripe; the twin's arrive)
392
+ ],
393
+ };
394
+
395
+ /** A credit note's `status`: issued, then voided once. */
396
+ const creditNoteStatus: StateField = {
397
+ initial: 'issued',
398
+ transitions: [
399
+ {
400
+ operation: 'PostCreditNotesIdVoid',
401
+ from: ['issued'],
402
+ to: 'void',
403
+ refusal: { status: 400, code: 'credit_note_already_voided', message: 'This credit note has already been voided.' },
404
+ source: 'https://docs.stripe.com/api/credit_notes/void',
405
+ },
406
+ ],
407
+ };
408
+
409
+ const scheduleEnded = (verb: string) => ({ status: 400, code: 'subscription_schedule_status_invalid', message: `This subscription schedule has status {from} and cannot be ${verb}.` });
410
+
411
+ /** A subscription schedule's `status`: canceling or releasing ends it; an ended one refuses both. */
412
+ const scheduleStatus: StateField = {
413
+ initial: 'active',
414
+ transitions: [
415
+ // "A subscription schedule can only be canceled if its status is not_started or active"; "A schedule can only be
416
+ // released if its status is not_started or active" (the cancel and release pages)
417
+ { operation: 'PostSubscriptionSchedulesScheduleCancel', from: ['active', 'not_started'], to: 'canceled', refusal: scheduleEnded('canceled'), source: 'https://docs.stripe.com/api/subscription_schedules/cancel' },
418
+ { operation: 'PostSubscriptionSchedulesScheduleRelease', from: ['active', 'not_started'], to: 'released', refusal: scheduleEnded('released'), source: 'https://docs.stripe.com/api/subscription_schedules/release' },
419
+ // its phases run on the clock: it starts at its start date and ends with its last phase
420
+ // (a schedule whose end_behavior is cancel completes at its end at Stripe; the twin's release)
421
+ // (Stripe starts a schedule at its start date and ends it with its last phase; the twin's start at once
422
+ // and end when canceled or released)
423
+ ],
424
+ };
425
+
426
+ const quoteRefusal = (verb: string) => ({ status: 400, code: 'quote_invalid_status', message: `This quote cannot be ${verb} because it has status {from}.` });
427
+
428
+ /** A quote's `status`: a draft is finalized into open, an open one accepted, and either canceled. */
429
+ const quoteStatus: StateField = {
430
+ initial: 'draft',
431
+ transitions: [
432
+ { operation: 'PostQuotesQuoteFinalize', from: ['draft'], to: 'open', refusal: quoteRefusal('finalized'), source: 'https://docs.stripe.com/api/quotes/finalize' },
433
+ { operation: 'PostQuotesQuoteAccept', from: ['open'], to: 'accepted', refusal: quoteRefusal('accepted'), source: 'https://docs.stripe.com/api/quotes/accept' },
434
+ { operation: 'PostQuotesQuoteCancel', from: ['draft', 'open'], to: 'canceled', refusal: quoteRefusal('canceled'), source: 'https://docs.stripe.com/api/quotes/cancel' },
435
+ // an open quote not accepted by its expires_at is canceled
436
+ // (Stripe cancels an open quote at its expires_at; the twin keeps it open)
437
+ ],
438
+ };
439
+
440
+ const setBy = (operation: string, values: string[], source: string): Transition[] => values.map((to) => ({ operation, from: '*' as const, to, source }));
441
+
442
+ /** An Issuing authorization's `status`: approve and decline close a pending one, once; a capture
443
+ * closes it, or leaves it pending when told not to close. */
444
+ const issuingAuthorizationStatus: StateField = {
445
+ initial: 'pending',
446
+ transitions: [
447
+ // approving keeps it pending (approved) until the merchant captures; declining closes it
448
+ { operation: 'PostIssuingAuthorizationsAuthorizationApprove', from: ['pending'], refusal: { status: 400, code: 'authorization_already_finalized', message: 'This authorization has already been finalized (status {from}).' }, source: 'https://docs.stripe.com/issuing/purchases/authorizations' },
449
+ { operation: 'PostIssuingAuthorizationsAuthorizationDecline', from: ['pending'], to: 'closed', refusal: { status: 400, code: 'authorization_already_finalized', message: 'This authorization has already been finalized (status {from}).' }, source: 'https://docs.stripe.com/api/issuing/authorizations/decline' },
450
+ { operation: 'PostTestHelpersIssuingAuthorizationsAuthorizationCapture', from: ['pending'], to: 'closed', source: 'https://docs.stripe.com/api/issuing/authorizations/test_mode_capture' },
451
+ { operation: 'PostTestHelpersIssuingAuthorizationsAuthorizationCapture', from: ['pending'], source: 'https://docs.stripe.com/api/issuing/authorizations/test_mode_capture' },
452
+ // a real-time request no one answered is decided when its window ends: "If Stripe doesn't receive your approve or
453
+ // decline response within 2 seconds, the Authorization is automatically approved or declined based on your timeout
454
+ // settings" (semantics/issuing.ts lapseRealtimeRequests)
455
+ by('time', ['pending'], 'closed', 'https://docs.stripe.com/issuing/controls/real-time-authorizations'),
456
+ // (Stripe also closes, reverses and expires one as the merchant and the clock act; in test mode the
457
+ // capture helper above closes it, and the twin serves no other)
458
+ ],
459
+ };
460
+
461
+ /** A Treasury flow's `status` as the twin's own operations move it: only a processing flow cancels. */
462
+ const flowCancel = (operation: string, code: string, name: string, network: Transition[]): StateField => ({
463
+ initial: 'processing',
464
+ transitions: [
465
+ { operation, from: ['processing'], to: 'canceled', refusal: { status: 400, code, message: `This ${name} cannot be canceled because it is no longer processing.` }, source: 'https://docs.stripe.com/api/treasury' },
466
+ ...network,
467
+ ],
468
+ });
469
+ /** An outbound flow on the network: Stripe posts or fails it and a posted one may come back returned (in
470
+ * test mode by test helpers the twin does not serve), so none of those moves is the twin's. */
471
+ const outbound = (_doc: string): Transition[] => [];
472
+
473
+ export const manifest: DerivedManifest = {
474
+ vendor: 'stripe',
475
+ service: 'stripe',
476
+ body: { form: { coerce: true } },
477
+ ids: { template: '{prefix}_twin_{n}', acceptProvided: true },
478
+ // on declared resources, but never served by the twin: Stripe's unknown-URL answer
479
+ unmodeled: [
480
+ 'DeleteAccountsAccountBankAccountsId',
481
+ 'DeleteAccountsAccountPeoplePerson',
482
+ 'DeleteCustomersCustomerSubscriptionsSubscriptionExposedId',
483
+ 'DeleteTaxIdsId',
484
+ 'GetAccountsAccountBankAccountsId',
485
+ 'GetAccountsAccountPeople',
486
+ 'GetAccountsAccountPeoplePerson',
487
+ 'GetApplicationFeesFeeRefundsId',
488
+ 'GetBalanceHistory',
489
+ 'GetBalanceHistoryId',
490
+ 'GetChargesChargeDispute',
491
+ 'GetCustomersCustomerSubscriptions',
492
+ 'GetCustomersCustomerSubscriptionsSubscriptionExposedId',
493
+ 'GetFileLinks',
494
+ 'GetFileLinksLink',
495
+ 'GetFinancialConnectionsTransactionsTransaction',
496
+ 'GetIdentityVerificationSessions',
497
+ 'GetLinkAccountSessionsSession',
498
+ 'GetLinkedAccounts',
499
+ 'GetLinkedAccountsAccount',
500
+ 'GetTaxIdsId',
501
+ 'GetTransfersTransferReversalsId',
502
+ 'PostAccountsAccountBankAccounts',
503
+ 'PostAccountsAccountBankAccountsId',
504
+ 'PostAccountsAccountExternalAccountsId',
505
+ 'PostAccountsAccountPeople',
506
+ 'PostAccountsAccountPeoplePerson',
507
+ 'PostApplicationFeesFeeRefundsId',
508
+ 'PostBillingMetersId',
509
+ 'PostCustomersCustomerBalanceTransactionsTransaction',
510
+ 'PostCustomersCustomerSubscriptions',
511
+ 'PostCustomersCustomerSubscriptionsSubscriptionExposedId',
512
+ 'PostFileLinksLink',
513
+ 'PostIdentityVerificationSessionsSession',
514
+ 'PostInvoicesInvoice',
515
+ 'PostLinkAccountSessions',
516
+ 'PostPaymentMethodsPaymentMethod',
517
+ 'PostPayoutsPayout',
518
+ 'PostQuotesQuote',
519
+ 'PostTaxRegistrationsId',
520
+ 'PostTransfersTransferReversalsId',
521
+ ],
522
+ time: 'unix',
523
+ error: { error: { type: '{kind}', message: '{message}', code: '{code}', param: '{param}' } },
524
+ errorOmitsAbsent: true,
525
+ defaultKind: 'invalid_request_error',
526
+ readOnly: { status: 405, kind: 'invalid_request_error', message: 'twin is read-only; omit readOnly to accept writes' },
527
+ version: {
528
+ header: 'stripe-version',
529
+ pattern: '^\\d{4}-\\d{2}-\\d{2}(\\.[a-z_]+)?$',
530
+ error: { status: 400, kind: 'invalid_request_error', code: 'invalid_api_version', message: 'Invalid Stripe version: {value}. Check the API version reference: https://stripe.com/docs/api/versioning' },
531
+ },
532
+ notFound: { status: 404, kind: 'invalid_request_error', code: 'resource_missing', message: "No such {object}: '{id}'" },
533
+ list: {
534
+ style: 'envelope',
535
+ envelope: { object: 'list', url: '{url}', has_more: '{has_more}', data: '{data}' },
536
+ limit: { param: 'limit', default: 10, max: 100 },
537
+ after: 'starting_after',
538
+ before: 'ending_before',
539
+ },
540
+ deleted: { id: '{id}', object: '{object}', deleted: true },
541
+ expandParam: 'expand',
542
+ idempotency: {
543
+ header: 'idempotency-key',
544
+ storedAs: '_idempotency',
545
+ conflict: {
546
+ status: 400,
547
+ kind: 'idempotency_error',
548
+ message: 'Keys for idempotent requests can only be used with the same parameters they were originally used with. Provide a new idempotency key, or use the original parameters that were used with this key.',
549
+ },
550
+ },
551
+ // The screens applications and people reach (docs/contributing/architecture.md, "Screens"). Demand is the
552
+ // ladder's 85 applications: the code that sends a customer to the page.
553
+ screens: [
554
+ {
555
+ id: 'checkout', kind: 'flow', host: 'checkout.stripe.com', path: '/c/pay/{session}', status: 'done',
556
+ demand: '16 of 85 applications send customers to Checkout',
557
+ controls: ['email', 'cardNumber', 'cardExpiry', 'cardCvc', 'billingName', 'billingCountry', 'billingPostalCode', 'Pay', '← Back'],
558
+ source: 'https://docs.stripe.com/payments/checkout/how-checkout-works',
559
+ },
560
+ {
561
+ id: 'billing-portal', kind: 'flow', host: 'billing.stripe.com', path: '/p/session/{session}', status: 'done',
562
+ demand: '15 of 85 applications send customers to the billing portal', controls: ['Cancel plan', 'Renew plan', '← Return to {business name}'],
563
+ source: 'https://docs.stripe.com/customer-management',
564
+ },
565
+ {
566
+ id: 'connect-onboarding', kind: 'flow', host: 'connect.stripe.com', path: '/setup/{account_link} → /setup/s/{session}', status: 'done',
567
+ demand: '3 of 85 applications onboard connected accounts with Account Links', controls: ['Agree and submit', '← Return to platform'],
568
+ source: 'https://docs.stripe.com/connect/hosted-onboarding',
569
+ },
570
+ {
571
+ id: 'identity-verification', kind: 'flow', host: 'verify.stripe.com', path: '/start/{verification_session}', status: 'done',
572
+ demand: 'a verification report is written only when a person completes this page', controls: ['Verify', 'Fail verification'],
573
+ source: 'https://docs.stripe.com/identity/how-sessions-work',
574
+ },
575
+ {
576
+ id: 'financial-connections', kind: 'flow', host: 'js.stripe.com', path: '/v3/financial-connections/{client_secret}', status: 'done',
577
+ demand: 'a linked bank account exists only once its holder links it here', controls: ['Link accounts', 'Cancel'],
578
+ source: 'https://docs.stripe.com/js/financial_connections/collect_financial_connections_accounts',
579
+ },
580
+ {
581
+ id: 'dashboard', kind: 'workspace', host: 'dashboard.stripe.com', path: '/test/{section}; /settings/public', status: 'done',
582
+ demand: 'testers and agents inspect payments, customers and subscriptions; an operator sets the business name Checkout shows (Public details)',
583
+ controls: ['Business name', 'Save'], source: 'https://docs.stripe.com/dashboard/basics',
584
+ },
585
+ ],
586
+ resources: {
587
+ 'billing.meter': {
588
+ storedAs: 'billing_meter', idPrefix: 'mtr', notFound: "No such meter: '{id}'",
589
+ notState: ['event_time_window'], filters: ['status'],
590
+ state: { status: { initial: 'active', transitions: [
591
+ { operation: 'PostBillingMetersIdDeactivate', from: '*', to: 'inactive', source: 'https://docs.stripe.com/api/billing/meter/deactivate' },
592
+ { operation: 'PostBillingMetersIdReactivate', from: '*', to: 'active', source: 'https://docs.stripe.com/api/billing/meter/reactivate' },
593
+ ] } },
594
+ },
595
+ 'billing.meter_event': { storedAs: 'billing_meter_event', idPrefix: 'mtr_evt' },
596
+ 'billing.credit_grant': { storedAs: 'credit_grant', idPrefix: 'credgr', notState: ['category'], filters: ['customer'], notFound: "No such credit grant: '{id}'" },
597
+ 'billing.alert': {
598
+ storedAs: 'billing_alert', idPrefix: 'alert', notFound: "No such alert: '{id}'",
599
+ state: { status: { initial: 'active', transitions: [
600
+ { operation: 'PostBillingAlertsIdActivate', from: '*', to: 'active', source: 'https://docs.stripe.com/api/billing/alert/activate' },
601
+ { operation: 'PostBillingAlertsIdDeactivate', from: '*', to: 'inactive', source: 'https://docs.stripe.com/api/billing/alert/deactivate' },
602
+ { operation: 'PostBillingAlertsIdArchive', from: '*', to: 'archived', source: 'https://docs.stripe.com/api/billing/alert/archive' },
603
+ ] } },
604
+ },
605
+ payment_intent: {
606
+ idPrefix: 'pi',
607
+ state: { status: paymentIntentStatus },
608
+ notState: ['cancellation_reason', 'capture_method', 'confirmation_method', 'setup_future_usage'],
609
+ embeds: { customer: 'customer', latest_charge: 'charge', payment_method: 'payment_method', invoice: 'invoice' },
610
+ filters: ['customer'],
611
+ },
612
+ // an update stores what it is given, nested objects whole, as the twin always has (Stripe merges
613
+ // metadata keys; `update: 'replace'` keeps the twin's answer)
614
+ customer: { idPrefix: 'cus', update: 'replace', notState: ['tax_exempt'], filters: ['email'] },
615
+ tax_id: { idPrefix: 'txi', notState: ['type'], filters: ['customer'] },
616
+ customer_balance_transaction: { idPrefix: 'cbtxn', notState: ['type'] },
617
+ customer_cash_balance_transaction: { storedAs: 'cash_balance_transaction', idPrefix: 'ccsbtxn', notState: ['type'] },
618
+ // a card is chargeable at once; any other source waits for its owner to authorize it through its
619
+ // flow, and is used up (single-use) or lapses
620
+ // what a customer's sources list answers (a card, a bank account, a Source, an account) as one
621
+ // resource over the stored sources; the card fields and an account's type/business_type are
622
+ // attributes. A customer's bank account verifies as a payout account does.
623
+ payment_source: {
624
+ storedAs: 'source',
625
+ idPrefix: 'src',
626
+ state: { status: bankAccountStatus('https://docs.stripe.com/api/customer_bank_accounts/object#customer_bank_account_object-status') },
627
+ notState: ['allow_redisplay', 'business_type', 'regulated_status', 'type'],
628
+ },
629
+ source: {
630
+ idPrefix: 'src',
631
+ state: {
632
+ status: {
633
+ initial: 'chargeable',
634
+ transitions: [
635
+ // (Stripe makes a redirect source chargeable when the customer authorizes it on the bank's page;
636
+ // the twin has no such page, so a non-card source stays pending)
637
+ // Stripe also fails a source the customer abandons, consumes a single-use one once charged and
638
+ // cancels one left unused; the twin's sources stay chargeable
639
+ ],
640
+ },
641
+ },
642
+ notState: ['allow_redisplay', 'type'],
643
+ },
644
+ charge: {
645
+ idPrefix: 'ch',
646
+ state: { status: chargeStatus, captured: chargeCaptured, paid: chargePaid, refunded: chargeRefunded },
647
+ embeds: { customer: 'customer', payment_intent: 'payment_intent', invoice: 'invoice', balance_transaction: 'balance_transaction' },
648
+ filters: ['customer', 'payment_intent'],
649
+ },
650
+ refund: {
651
+ idPrefix: 're',
652
+ update: 'replace',
653
+ state: { status: refundStatus },
654
+ notState: ['pending_reason', 'reason'],
655
+ embeds: { charge: 'charge', payment_intent: 'payment_intent', balance_transaction: 'balance_transaction' },
656
+ filters: ['charge', 'payment_intent'],
657
+ },
658
+ setup_intent: {
659
+ idPrefix: 'seti',
660
+ update: 'replace',
661
+ state: { status: setupIntentStatus },
662
+ notState: ['cancellation_reason'],
663
+ embeds: { customer: 'customer', payment_method: 'payment_method' },
664
+ filters: ['customer', 'payment_method'],
665
+ },
666
+ payment_method: { idPrefix: 'pm', notState: ['allow_redisplay', 'type'], embeds: { customer: 'customer' }, filters: ['customer', 'type'] },
667
+ subscription: {
668
+ idPrefix: 'sub',
669
+ state: { status: subscriptionStatus },
670
+ notState: ['collection_method'],
671
+ embeds: { customer: 'customer', latest_invoice: 'invoice', default_payment_method: 'payment_method', schedule: 'subscription_schedule' },
672
+ filters: ['customer'],
673
+ },
674
+ subscription_item: { idPrefix: 'si' },
675
+ invoice: {
676
+ idPrefix: 'in',
677
+ state: { status: invoiceStatus },
678
+ notState: ['billing_reason', 'collection_method', 'customer_tax_exempt'],
679
+ embeds: { customer: 'customer', subscription: 'subscription', charge: 'charge', payment_intent: 'payment_intent' },
680
+ filters: ['customer', 'status', 'subscription'],
681
+ },
682
+ invoiceitem: { idPrefix: 'ii', embeds: { customer: 'customer', price: 'price' }, filters: ['customer', 'invoice'], order: { field: 'date', direction: 'desc' } },
683
+ 'checkout.session': {
684
+ storedAs: 'checkout_session',
685
+ idPrefix: 'cs',
686
+ state: { status: checkoutStatus, payment_status: checkoutPaymentStatus },
687
+ notState: ['billing_address_collection', 'customer_creation', 'locale', 'mode', 'origin_context', 'payment_method_collection', 'redirect_on_completion', 'submit_type', 'ui_mode'],
688
+ filters: ['customer', 'payment_intent', 'subscription', 'status'],
689
+ // the objects a session links to, as its x-expandableFields name them
690
+ embeds: { customer: 'customer', invoice: 'invoice', payment_intent: 'payment_intent', payment_link: 'payment_link', setup_intent: 'setup_intent', subscription: 'subscription' },
691
+ },
692
+ ephemeral_key: { idPrefix: 'ephkey' },
693
+ // a mandate's status is the network's to move; nothing here moves it
694
+ mandate: {
695
+ idPrefix: 'mandate',
696
+ state: {
697
+ status: {
698
+ initial: 'active',
699
+ transitions: [
700
+ // a single-use mandate is spent by its payment: inactive "The mandate was rejected, revoked, or previously
701
+ // used, and may not be used to initiate future payments" (semantics/payment-intents.ts settleBankDebits)
702
+ by('vendor', ['active'], 'inactive', 'https://docs.stripe.com/api/mandates/object'),
703
+ // (Stripe also activates a pending mandate and deactivates one revoked; the twin's are active when made)
704
+ ],
705
+ },
706
+ },
707
+ notState: ['type'],
708
+ },
709
+ dispute: { idPrefix: 'dp', update: 'replace', state: { status: disputeStatus }, notState: ['is_charge_refundable'], embeds: { charge: 'charge', payment_intent: 'payment_intent' }, filters: ['charge', 'payment_intent'] },
710
+ payout: { idPrefix: 'po', state: { status: payoutStatus }, notState: ['reconciliation_status', 'type'], embeds: { balance_transaction: 'balance_transaction', destination: 'account' } },
711
+ // the twin's ledger is seeded available; Stripe holds funds pending until their available_on
712
+ balance_transaction: {
713
+ idPrefix: 'txn',
714
+ state: { status: { initial: 'available', vendorInitial: 'pending', transitions: [by('time', ['pending'], 'available', 'https://docs.stripe.com/api/balance_transactions/object#balance_transaction_object-status')] } },
715
+ notState: ['balance_type', 'type'],
716
+ filters: ['type', 'currency'],
717
+ },
718
+ // a coupon lapses at its redeem_by: "Date after which the coupon can no longer be redeemed", and `valid` is
719
+ // "Taking account of the above properties, whether this coupon can still be applied to a customer" (the served
720
+ // spec's coupon); the twin keeps no redemption count, so max_redemptions never lapses one
721
+ coupon: {
722
+ idPrefix: 'coupon', update: 'replace', notState: ['duration'],
723
+ state: { valid: { initial: true, transitions: [by('time', ['true'], 'false', 'spec:/components/schemas/coupon/properties/redeem_by "Date after which the coupon can no longer be redeemed."')] } },
724
+ },
725
+ // switched on and off by an update (Stripe also lapses one at expires_at or when fully redeemed; the
726
+ // twin keeps no redemption count or expiry)
727
+ promotion_code: {
728
+ idPrefix: 'promo',
729
+ update: 'replace',
730
+ notFound: "No such promotion code: '{id}'",
731
+ state: {
732
+ active: {
733
+ initial: true,
734
+ transitions: [
735
+ ...flag('PostPromotionCodesPromotionCode', 'https://docs.stripe.com/api/promotion_codes/update'),
736
+ ],
737
+ },
738
+ },
739
+ },
740
+ credit_note: { idPrefix: 'cn', state: { status: creditNoteStatus }, notState: ['reason', 'type'], embeds: { customer: 'customer', invoice: 'invoice' }, filters: ['invoice', 'customer'] },
741
+ subscription_schedule: {
742
+ idPrefix: 'sub_sched',
743
+ update: 'replace',
744
+ state: { status: scheduleStatus },
745
+ notState: ['end_behavior'],
746
+ embeds: { customer: 'customer', subscription: 'subscription' },
747
+ filters: ['customer', 'subscription'],
748
+ },
749
+ 'entitlements.feature': {
750
+ storedAs: 'entitlements_feature', idPrefix: 'feat', notFound: "No such feature: '{id}'",
751
+ state: { active: { initial: true, transitions: flag('PostEntitlementsFeaturesId', 'spec:PostEntitlementsFeaturesId "Update a feature’s metadata or permanently deactivate it."') } },
752
+ },
753
+ // an advance answers advancing and the clock is ready once it has reached the time (semantics/test-clocks.ts)
754
+ 'test_helpers.test_clock': {
755
+ storedAs: 'test_clock',
756
+ idPrefix: 'clock',
757
+ notFound: "No such test clock: '{id}'",
758
+ state: {
759
+ status: {
760
+ initial: 'ready',
761
+ transitions: [
762
+ // "advancing: The clock has started to advance but hasn't reached the specified time"; "ready: The clock has
763
+ // completed advancing to the specified time" (docs.stripe.com/billing/testing/test-clocks/api-advanced-usage)
764
+ { operation: 'PostTestHelpersTestClocksTestClockAdvance', from: ['ready'], to: 'advancing', refusal: { status: 400, code: 'test_clock_not_ready', message: 'This test clock is still advancing.' }, source: 'https://docs.stripe.com/api/test_clocks/advance' },
765
+ by('vendor', ['advancing'], 'ready', 'https://docs.stripe.com/billing/testing/test-clocks/api-advanced-usage'),
766
+ // (Stripe may also end an advance in internal_failure; the twin's advances complete)
767
+ ],
768
+ },
769
+ },
770
+ },
771
+ event: { idPrefix: 'evt', filters: ['type'] },
772
+ // disabled and re-enabled by an update's `disabled` (Stripe also disables one that keeps failing; the
773
+ // twin counts no failures)
774
+ webhook_endpoint: {
775
+ idPrefix: 'we',
776
+ notFound: "No such webhook endpoint: '{id}'",
777
+ state: {
778
+ status: {
779
+ initial: 'enabled',
780
+ transitions: [
781
+ ...['enabled', 'disabled'].map((to) => ({ operation: 'PostWebhookEndpointsWebhookEndpoint', from: '*' as const, to, source: 'https://docs.stripe.com/api/webhook_endpoints/update#update_webhook_endpoint-disabled' })),
782
+ ],
783
+ },
784
+ },
785
+ },
786
+ account: { idPrefix: 'acct', notState: ['business_type', 'type'] },
787
+ person: { idPrefix: 'person', notState: ['political_exposure'], parent: { param: 'account', field: 'account', resource: 'account' } },
788
+ // a capability lives in its account's capability map; requesting one leaves it pending, withdrawing it inactive
789
+ capability: {
790
+ idPrefix: 'cap',
791
+ state: {
792
+ status: {
793
+ initial: 'unrequested',
794
+ transitions: [
795
+ ...['pending', 'inactive'].map((to) => ({ operation: 'PostAccountsAccountCapabilitiesCapability', from: '*' as const, to, source: 'https://docs.stripe.com/api/capabilities/update' })),
796
+ // Stripe reviews the account's requirements
797
+ by('vendor', ['pending', 'inactive'], 'active', 'https://docs.stripe.com/connect/account-capabilities#capability-status'),
798
+ by('vendor', ['active', 'pending'], 'inactive', 'https://docs.stripe.com/connect/account-capabilities#capability-status'),
799
+ ],
800
+ },
801
+ },
802
+ },
803
+ // allow_redisplay and regulated_status belong to a card destination: consent and the issuer's
804
+ // regulation, set when it is added, not a lifecycle
805
+ external_account: {
806
+ idPrefix: 'ba',
807
+ state: { status: bankAccountStatus('https://docs.stripe.com/api/external_account_bank_accounts/object#account_bank_account_object-status') },
808
+ notState: ['allow_redisplay', 'regulated_status'],
809
+ },
810
+ account_link: { idPrefix: 'acctlink' },
811
+ account_session: { idPrefix: 'accts' },
812
+ transfer: { idPrefix: 'tr', update: 'replace', filters: ['destination'] },
813
+ transfer_reversal: { idPrefix: 'trr' },
814
+ // refunded once fee refunds take its whole amount
815
+ application_fee: {
816
+ idPrefix: 'fee', notFound: "No such application fee: '{id}'", filters: ['charge'],
817
+ state: { refunded: { initial: false, transitions: [
818
+ { operation: 'PostApplicationFeesIdRefunds', from: ['false'], to: 'true', source: 'https://docs.stripe.com/api/fee_refunds/create' },
819
+ // a refund of its charge with refund_application_fee refunds it in proportion
820
+ ...['PostRefunds', 'PostChargesChargeRefunds'].map((operation) => ({ operation, from: ['false'], to: 'true', source: 'https://docs.stripe.com/api/refunds/create#create_refund-refund_application_fee' })),
821
+ ] } },
822
+ },
823
+ fee_refund: { idPrefix: 'fr' },
824
+ 'apps.secret': { storedAs: 'apps_secret', idPrefix: 'apmc' },
825
+ token: { idPrefix: 'tok' },
826
+ file: { idPrefix: 'file', notState: ['purpose'], filters: ['purpose'] },
827
+ file_link: { idPrefix: 'link' },
828
+ // the user submits on Stripe's hosted verification page and Stripe checks it (the twin's own helper
829
+ // outside Stripe's surface, POST …/verify, stands in for both at once)
830
+ 'identity.verification_session': {
831
+ storedAs: 'verification_session',
832
+ idPrefix: 'vs',
833
+ notFound: "No such VerificationSession: '{id}'",
834
+ state: {
835
+ status: {
836
+ initial: 'requires_input',
837
+ transitions: [
838
+ by('external', ['requires_input'], 'processing', 'https://docs.stripe.com/identity/how-sessions-work'),
839
+ by('vendor', ['processing'], 'verified', 'https://docs.stripe.com/identity/how-sessions-work'),
840
+ by('vendor', ['processing'], 'requires_input', 'https://docs.stripe.com/identity/how-sessions-work'),
841
+ ],
842
+ },
843
+ },
844
+ notState: ['type'],
845
+ },
846
+ 'identity.verification_report': { storedAs: 'verification_report', idPrefix: 'vr', notFound: "No such verification report: '{id}'", notState: ['type'], filters: ['verification_session', 'type'] },
847
+ 'billing_portal.session': { storedAs: 'billing_portal_session', idPrefix: 'bps', notState: ['locale'] },
848
+ // is_default is Stripe's: the configuration the dashboard made first
849
+ 'billing_portal.configuration': {
850
+ storedAs: 'billing_portal_configuration', idPrefix: 'bpc', notFound: "No such configuration: '{id}'",
851
+ state: { active: { initial: true, transitions: flag('PostBillingPortalConfigurationsConfiguration', 'https://docs.stripe.com/api/customer_portal/configurations/update') } },
852
+ notState: ['is_default'],
853
+ },
854
+ // `state` is a US state code, not a lifecycle
855
+ tax_rate: {
856
+ idPrefix: 'txr', notFound: "No such tax rate: '{id}'",
857
+ state: { active: { initial: true, transitions: flag('PostTaxRatesTaxRate', 'https://docs.stripe.com/api/tax_rates/update') } },
858
+ notState: ['jurisdiction_level', 'rate_type', 'state', 'tax_type'],
859
+ },
860
+ // its status is derived on every read from whether a head office is set; nothing stores it
861
+ 'tax.settings': { storedAs: 'tax_settings', idPrefix: 'taxset', notState: ['status'] },
862
+ 'tax.calculation': { storedAs: 'tax_calculation', idPrefix: 'taxcalc', notFound: "No such tax calculation: '{id}'" },
863
+ // a registration is active from creation here; its dates move it on the clock
864
+ 'tax.registration': {
865
+ storedAs: 'tax_registration', idPrefix: 'taxreg', notFound: "No such tax registration: '{id}'", filters: ['status'],
866
+ state: {
867
+ // Stripe schedules a registration with a future active_from and expires one at expires_at; the twin's
868
+ // are active from the start and never expire
869
+ status: { initial: 'active', transitions: [] },
870
+ },
871
+ },
872
+ 'tax.transaction': { storedAs: 'tax_transaction', idPrefix: 'tax', notFound: "No such tax transaction: '{id}'", notState: ['type'] },
873
+ payment_link: {
874
+ idPrefix: 'plink',
875
+ update: 'replace', notFound: "No such payment link: '{id}'",
876
+ state: { active: { initial: true, transitions: flag('PostPaymentLinksPaymentLink', 'https://docs.stripe.com/api/payment_links/payment_links/update') } },
877
+ notState: ['billing_address_collection', 'customer_creation', 'payment_method_collection', 'submit_type'],
878
+ },
879
+ quote: { idPrefix: 'qt', state: { status: quoteStatus }, notState: ['collection_method'], filters: ['customer', 'status'] },
880
+ // a review is open until it is closed; approving closes it, once
881
+ review: {
882
+ storedAs: 'radar_review',
883
+ idPrefix: 'prv',
884
+ state: {
885
+ open: {
886
+ initial: true,
887
+ transitions: [
888
+ // (Stripe also closes one when the payment is refunded or disputed; the twin's close only on approval)
889
+ { operation: 'PostReviewsReviewApprove', from: ['true'], to: 'false', refusal: { status: 400, code: 'review_already_closed', message: 'This review has already been closed.' }, source: 'https://docs.stripe.com/api/radar/reviews/approve' },
890
+ ],
891
+ },
892
+ },
893
+ notState: ['closed_reason', 'opened_reason'],
894
+ },
895
+ 'radar.value_list': { storedAs: 'radar_value_list', idPrefix: 'rsl', notFound: "No such radar value list: '{id}'", notState: ['item_type'], filters: ['alias'] },
896
+ 'radar.value_list_item': { storedAs: 'radar_value_list_item', idPrefix: 'rsli', notFound: "No such radar value list item: '{id}'" },
897
+ 'issuing.cardholder': {
898
+ storedAs: 'issuing_cardholder',
899
+ idPrefix: 'ich',
900
+ notFound: "No such cardholder: '{id}'",
901
+ state: { status: { initial: 'active', transitions: setBy('PostIssuingCardholdersCardholder', ['active', 'inactive', 'blocked'], 'https://docs.stripe.com/api/issuing/cardholders/update') } },
902
+ notState: ['type'],
903
+ filters: ['status', 'type', 'email'],
904
+ },
905
+ 'issuing.card': {
906
+ storedAs: 'issuing_card',
907
+ idPrefix: 'ic',
908
+ notFound: "No such card: '{id}'",
909
+ state: { status: { initial: 'active', transitions: setBy('PostIssuingCardsCard', ['active', 'inactive', 'canceled'], 'https://docs.stripe.com/api/issuing/cards/update') } },
910
+ notState: ['cancellation_reason', 'replacement_reason', 'type'],
911
+ filters: ['cardholder', 'status', 'type'],
912
+ },
913
+ 'issuing.authorization': { storedAs: 'issuing_authorization', idPrefix: 'iauth', state: { status: issuingAuthorizationStatus }, notState: ['authorization_method', 'card_presence'] },
914
+ 'issuing.transaction': { storedAs: 'issuing_transaction', idPrefix: 'ipi', notFound: "No such transaction: '{id}'", notState: ['type', 'wallet'], filters: ['card', 'cardholder'] },
915
+ 'issuing.dispute': {
916
+ storedAs: 'issuing_dispute',
917
+ idPrefix: 'idp',
918
+ notFound: "No such dispute: '{id}'",
919
+ state: {
920
+ status: {
921
+ initial: 'unsubmitted',
922
+ transitions: [
923
+ { operation: 'PostIssuingDisputesDisputeSubmit', from: ['unsubmitted'], to: 'submitted', refusal: { status: 400, code: 'dispute_unsubmitted_required', message: 'This dispute has already been submitted (status {from}).' }, source: 'spec:PostIssuingDisputesDisputeSubmit "Submits an Issuing <code>Dispute</code> to the card network."' },
924
+ // (Stripe decides a submitted dispute won or lost and expires one never submitted; the twin decides none)
925
+ ],
926
+ },
927
+ },
928
+ notState: ['loss_reason'],
929
+ filters: ['status', 'transaction'],
930
+ },
931
+ 'issuing.token': {
932
+ storedAs: 'issuing_token',
933
+ idPrefix: 'iss_tok',
934
+ notFound: "No such issuing token: '{id}'",
935
+ state: { status: { initial: 'active', transitions: [...setBy('PostIssuingTokensToken', ['active', 'deleted', 'suspended'], 'https://docs.stripe.com/api/issuing/tokens/update')] } },
936
+ notState: ['network', 'wallet_provider'],
937
+ filters: ['card', 'status'],
938
+ },
939
+ // a design waits in review (inactive) until the review test helpers decide it
940
+ 'issuing.personalization_design': {
941
+ storedAs: 'personalization_design',
942
+ idPrefix: 'pd',
943
+ notFound: "No such personalization design: '{id}'",
944
+ state: {
945
+ status: {
946
+ // a new design waits on Stripe's review (docs.stripe.com/issuing/cards/physical/personalization-design)
947
+ initial: 'review',
948
+ transitions: [
949
+ ...setBy('PostTestHelpersIssuingPersonalizationDesignsPersonalizationDesignActivate', ['active'], 'spec:PostTestHelpersIssuingPersonalizationDesignsPersonalizationDesignActivate "to <code>active</code>"'),
950
+ ...setBy('PostTestHelpersIssuingPersonalizationDesignsPersonalizationDesignDeactivate', ['inactive'], 'spec:PostTestHelpersIssuingPersonalizationDesignsPersonalizationDesignDeactivate "to <code>inactive</code>"'),
951
+ ...setBy('PostTestHelpersIssuingPersonalizationDesignsPersonalizationDesignReject', ['rejected'], 'spec:PostTestHelpersIssuingPersonalizationDesignsPersonalizationDesignReject "to <code>rejected</code>"'),
952
+ // (outside test mode Stripe's review decides it; the twin is test mode, where these helpers do)
953
+ ],
954
+ },
955
+ },
956
+ },
957
+ 'terminal.location': { storedAs: 'terminal_location', idPrefix: 'tml', notFound: "No such location: '{id}'" },
958
+ // a simulated reader is online from registration; a real one drops off and comes back
959
+ 'terminal.reader': {
960
+ storedAs: 'terminal_reader', idPrefix: 'tmr', notFound: "No such reader: '{id}'", notState: ['device_type'], filters: ['location', 'status'],
961
+ // (a real reader goes offline and back; the twin's simulated readers stay online)
962
+ state: { status: { initial: 'online', transitions: [] } },
963
+ },
964
+ 'terminal.configuration': { storedAs: 'terminal_configuration', idPrefix: 'tmc', notFound: "No such configuration: '{id}'", notState: ['is_account_default'] },
965
+ topup: {
966
+ idPrefix: 'tu',
967
+ state: {
968
+ status: {
969
+ // a top-up starts pending (the create page's example answers "status": "pending") and its funds arrive days
970
+ // later: "USA (USD) ACH Debit Transfer 5 days" (docs.stripe.com/connect/top-ups; semantics/terminal.ts)
971
+ initial: 'pending',
972
+ transitions: [
973
+ { operation: 'PostTopupsTopupCancel', from: ['pending'], to: 'canceled', refusal: { status: 400, code: 'topup_unexpected_state', message: 'This top-up cannot be canceled because it has a status of {from}.' }, source: 'https://docs.stripe.com/api/topups/cancel' },
974
+ // to the Issuing balance alike: "Your top-ups can take up to 5 business days to become available"
975
+ // (docs.stripe.com/issuing/funding/balance)
976
+ by('vendor', ['pending'], 'succeeded', 'https://docs.stripe.com/connect/top-ups'),
977
+ // (Stripe also fails a top-up or reverses a settled one; the twin's top-ups do neither)
978
+ ],
979
+ },
980
+ },
981
+ notState: ['initiated_by'],
982
+ filters: ['status'],
983
+ },
984
+ // closing an account (POST …/close) is not modeled here; is_default is Stripe's
985
+ 'treasury.financial_account': { storedAs: 'financial_account', idPrefix: 'fa', notFound: "No such financial account: '{id}'", state: { status: { initial: 'open', transitions: [] } }, notState: ['is_default'], filters: ['status'] },
986
+ 'treasury.outbound_payment': {
987
+ storedAs: 'outbound_payment',
988
+ idPrefix: 'obp',
989
+ notFound: "No such outbound payment: '{id}'",
990
+ state: { status: flowCancel('PostTreasuryOutboundPaymentsIdCancel', 'outbound_payment_not_cancelable', 'OutboundPayment', outbound('https://docs.stripe.com/treasury/moving-money/financial-accounts/out-of/outbound-payments')) },
991
+ filters: ['financial_account', 'status'],
992
+ },
993
+ 'treasury.outbound_transfer': {
994
+ storedAs: 'outbound_transfer',
995
+ idPrefix: 'obt',
996
+ notFound: "No such outbound transfer: '{id}'",
997
+ state: { status: flowCancel('PostTreasuryOutboundTransfersOutboundTransferCancel', 'outbound_transfer_not_cancelable', 'OutboundTransfer', outbound('https://docs.stripe.com/treasury/moving-money/financial-accounts/out-of/outbound-transfers')) },
998
+ filters: ['financial_account', 'status'],
999
+ },
1000
+ 'treasury.inbound_transfer': {
1001
+ storedAs: 'inbound_transfer',
1002
+ idPrefix: 'ibt',
1003
+ notFound: "No such inbound transfer: '{id}'",
1004
+ // "An InboundTransfer is processing if it is created and pending. The status changes to succeeded once the funds have
1005
+ // been "confirmed""; in test mode the succeed helper confirms them (docs.stripe.com/api/treasury/inbound_transfers)
1006
+ state: { status: flowCancel('PostTreasuryInboundTransfersInboundTransferCancel', 'inbound_transfer_not_cancelable', 'InboundTransfer', [
1007
+ { operation: 'PostTestHelpersTreasuryInboundTransfersIdSucceed', from: ['processing'], to: 'succeeded', refusal: { status: 400, code: 'inbound_transfer_not_processing', message: 'This InboundTransfer cannot succeed because it is no longer processing.' }, source: 'https://docs.stripe.com/api/treasury/inbound_transfers' },
1008
+ ]) },
1009
+ filters: ['financial_account', 'status'],
1010
+ },
1011
+ // received credits and debits are materialized by the network (test helpers the twin does not serve)
1012
+ 'treasury.received_credit': { storedAs: 'received_credit', idPrefix: 'rc', notFound: "No such received credit: '{id}'", state: { status: { initial: 'succeeded', transitions: [] } }, notState: ['failure_code', 'network'], filters: ['financial_account', 'status'] },
1013
+ 'treasury.received_debit': { storedAs: 'received_debit', idPrefix: 'rd', notFound: "No such received debit: '{id}'", state: { status: { initial: 'succeeded', transitions: [] } }, notState: ['failure_code', 'network'], filters: ['financial_account', 'status'] },
1014
+ // a ledger transaction is posted or left open by the flow that writes it; the network settles an open one
1015
+ 'treasury.transaction': {
1016
+ storedAs: 'treasury_transaction', idPrefix: 'trxn', notFound: "No such treasury transaction: '{id}'", notState: ['flow_type'],
1017
+ // void: "The Transaction never impacted the balance. For example, a Transaction would enter this state if an
1018
+ // OutboundPayment was initiated but then canceled" (docs.stripe.com/api/treasury/transactions/object); canceling an
1019
+ // outbound flow voids its open transaction (semantics/treasury.ts). (Stripe also posts an open transaction as its
1020
+ // flow settles; the twin's outbound flows stay processing)
1021
+ state: { status: { initial: 'open', transitions: [
1022
+ ...['PostTreasuryOutboundPaymentsIdCancel', 'PostTreasuryOutboundTransfersOutboundTransferCancel', 'PostTreasuryInboundTransfersInboundTransferCancel'].map((operation) => ({ operation, from: ['open'], to: 'void', source: 'https://docs.stripe.com/api/treasury/transactions/object' })),
1023
+ // an inbound transfer's transaction posts when it succeeds ("a transaction is created and posted")
1024
+ { operation: 'PostTestHelpersTreasuryInboundTransfersIdSucceed', from: ['open'], to: 'posted', source: 'https://docs.stripe.com/api/treasury/inbound_transfers' },
1025
+ ] } },
1026
+ },
1027
+ 'treasury.transaction_entry': { storedAs: 'treasury_transaction_entry', idPrefix: 'trxne', notFound: "No such transaction entry: '{id}'", notState: ['flow_type', 'type'] },
1028
+ 'climate.order': {
1029
+ storedAs: 'climate_order',
1030
+ idPrefix: 'climorder',
1031
+ notFound: "No such order: '{id}'",
1032
+ state: {
1033
+ status: {
1034
+ // an order is created confirmed: the create page's example answers "status": "confirmed" with confirmed_at set
1035
+ // (docs.stripe.com/api/climate/order/create)
1036
+ initial: 'confirmed',
1037
+ transitions: [
1038
+ { operation: 'PostClimateOrdersOrderCancel', from: ['awaiting_funds', 'confirmed', 'open'], to: 'canceled', refusal: { status: 400, code: 'climate_order_not_cancelable', message: 'This order can no longer be canceled because it is {from}.' }, source: 'https://docs.stripe.com/api/climate/order/cancel' },
1039
+ // funded, confirmed by the supplier, then delivered
1040
+ // (Stripe funds, confirms and delivers an order over months; the twin's orders stay where they are made)
1041
+ ],
1042
+ },
1043
+ },
1044
+ notState: ['cancellation_reason'],
1045
+ },
1046
+ 'financial_connections.session': { storedAs: 'fc_session', idPrefix: 'fcsess' },
1047
+ 'financial_connections.account': {
1048
+ storedAs: 'fc_account',
1049
+ idPrefix: 'fca',
1050
+ notFound: "No such account: '{id}'",
1051
+ state: {
1052
+ status: {
1053
+ initial: 'active',
1054
+ transitions: [
1055
+ { operation: 'PostFinancialConnectionsAccountsAccountDisconnect', from: '*', to: 'disconnected', source: 'https://docs.stripe.com/api/financial_connections/accounts/disconnect' },
1056
+ // (Stripe marks an account inactive when the bank link breaks, and active again; the twin's links hold)
1057
+ ],
1058
+ },
1059
+ },
1060
+ notState: ['category', 'subcategory'],
1061
+ },
1062
+ // a linked account's transactions arrive posted here; the bank settles a pending one
1063
+ 'financial_connections.transaction': {
1064
+ storedAs: 'fc_transaction', idPrefix: 'fctxn',
1065
+ // (a bank's pending transaction posts or is voided at Stripe; the twin's arrive posted)
1066
+ state: { status: { initial: 'posted', transitions: [] } },
1067
+ },
1068
+ 'forwarding.request': { storedAs: 'forwarding_request', idPrefix: 'fwdr', notFound: "No such forwarding request: '{id}'" },
1069
+ // the twin runs a report at once; Stripe runs it in the background
1070
+ 'reporting.report_run': {
1071
+ storedAs: 'report_run', idPrefix: 'frr', notFound: "No such report run: '{id}'",
1072
+ // "When first created, the object appears with status="pending""; "When the run completes, Stripe updates the
1073
+ // object, and it has a status of succeeded" (docs.stripe.com/reports/api; semantics/platform.ts finishReportRuns).
1074
+ // (Stripe may also fail a run; the twin's runs succeed)
1075
+ state: { status: { initial: 'pending', transitions: [by('vendor', ['pending'], 'succeeded', 'https://docs.stripe.com/reports/api')] } },
1076
+ },
1077
+ // archived (active=false) and restored by an update
1078
+ product: { idPrefix: 'prod', update: 'replace', state: { active: { initial: true, transitions: flag('PostProductsId', 'https://docs.stripe.com/api/products/update#update_product-active') } } },
1079
+ product_feature: { idPrefix: 'prodft' },
1080
+ price: {
1081
+ idPrefix: 'price',
1082
+ update: 'replace', notState: ['billing_scheme', 'tax_behavior', 'tiers_mode', 'type'], embeds: { product: 'product' },
1083
+ // deleting a plan leaves its price for its subscribers, inactive: "Deleting plans means new subscribers can’t be added.
1084
+ // Existing subscribers aren’t affected." (docs.stripe.com/api/plans/delete; semantics/plans.ts)
1085
+ state: { active: { initial: true, transitions: [...flag('PostPricesPrice', 'https://docs.stripe.com/api/prices/update#update_price-active'), { operation: 'DeletePlansPlan', from: ['true'], to: 'false', source: 'https://docs.stripe.com/api/plans/delete' }] } },
1086
+ },
1087
+ },
1088
+ view: (storedType, row) => view(storedType, row),
1089
+ onWrite: async ({ operation, storedType, body, root, occurredAt, request }) => {
1090
+ const version = request.headers.get('stripe-version') ?? undefined;
1091
+ // an Issuing authorization carries its full card in every egress, webhooks included; the write
1092
+ // hook is where the root is known, and the body it embeds into is the one the handler answers
1093
+ if (storedType === 'issuing_authorization') embedIssuingAuthorizationCard(body, root);
1094
+ await afterStripeWrite(storedType, operation, body, root, occurredAt, version && isValidApiVersion(version) ? version : undefined, request.headers.get('stripe-account') ?? undefined);
1095
+ },
1096
+ };
1097
+