@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,26 @@
1
+ // A MINIATURE OF THE HEAD, for this pack's own claims and suites (protocol 2). The kernel's loop
2
+ // (`performEntries`) needs a bound root and a sealed credential a unit test does not have; this is the same
3
+ // shape without one — the same `deployableEntries`, the pack's own push, the same `confirmAction`. Not on
4
+ // the serve path, not exported from the pack.
5
+ import { confirmAction, deployableEntries, worldNow } from '@volter/world-core';
6
+ import { INTERNAL_SUBJECT_TYPES, isPushable, pushStripeAction } from "./stripe-connector.js";
7
+ export async function performPending(execute, opts) {
8
+ const confirmed = [];
9
+ const externalIds = {};
10
+ for (const entry of deployableEntries('stripe', opts.root)) {
11
+ const op = entry.operation ?? `${entry.subject.type}.update`;
12
+ // the twin's own records — the recorded event envelopes and the idempotency bookkeeping — are local
13
+ // state and are never sent
14
+ if (INTERNAL_SUBJECT_TYPES.has(entry.subject.type) || !isPushable(op))
15
+ continue;
16
+ const { externalId } = await pushStripeAction(execute, { operation: op, subject: entry.subject, fields: entry.fields ?? {} });
17
+ confirmAction({
18
+ service: 'stripe', actionId: entry.id, subject: entry.subject, fields: entry.fields ?? {},
19
+ occurredAt: opts.occurredAt ?? worldNow(), vendorSubjectId: externalId, receipt: { status: 'deployed' },
20
+ ...(opts.root !== undefined ? { root: opts.root } : {}),
21
+ });
22
+ confirmed.push(entry.id);
23
+ externalIds[entry.id] = externalId;
24
+ }
25
+ return { pushed: confirmed.length, confirmed, externalIds };
26
+ }
@@ -0,0 +1,33 @@
1
+ import { type DerivedFetch } from '@volter/world-core';
2
+ /** Options shared by the fetch handler and the Bun.serve wrapper around it. `port` is a
3
+ * BIND concern the fetch ignores; it stays in one shape so a caller configures the twin
4
+ * once whichever way it is mounted. */
5
+ export type StripeTwinOptions = {
6
+ root?: string;
7
+ port?: number;
8
+ readOnly?: boolean; /** the World instant, when a caller pins it */
9
+ clock?: () => string;
10
+ };
11
+ /**
12
+ * The whole Stripe serve path as a plain `(Request) => Response` — the `/twin` manifest
13
+ * door, the header threading (idempotency key, pinned API version, Connect account) and
14
+ * the derived dispatch over the hand-written routes. NOTHING about it is port-bound.
15
+ *
16
+ * Why this is the factory and `createStripeTwinServer` is a wrapper (runtime contract R12,
17
+ * the Cloudflare ruling): a Durable Object / Worker entry has no loopback ports — it mounts
18
+ * pack fetches IN-PROCESS behind one router. Handing that entry `Bun.serve` is not an
19
+ * option, so the vendor HTTP adaptation has to be a value it can call. Keeping the server a
20
+ * thin `Bun.serve(fetch)` also means the local and hosted lanes execute the SAME bytes of
21
+ * serving code — the parity claim (R9) is about one code path, not two that resemble each
22
+ * other.
23
+ *
24
+ * SCOPING THE STORES AROUND IT: this fetch is ASYNC, so install the world store with
25
+ * `setActiveWorldStore(store)` in a try/finally — **not** `withWorldStore(store, fn)`, whose
26
+ * `finally` fires when `fn` RETURNS, i.e. at the first `await`, restoring the previous store
27
+ * under the rest of the request.
28
+ */
29
+ export declare function createStripeTwinFetch(options: StripeTwinOptions): DerivedFetch;
30
+ export declare function createStripeTwinServer(options: StripeTwinOptions): Promise<{
31
+ port: number;
32
+ stop: () => void;
33
+ }>;
@@ -0,0 +1,326 @@
1
+ // Stripe twin HTTP server — serve the full Stripe twin handler over HTTP so the
2
+ // real `stripe` SDK ({host,port,protocol}) works unmodified (R1), or route the QA
3
+ // backend sandbox's api.stripe.com interception at it. Form-encoded bodies (what
4
+ // the SDK sends) pass through to the handler. Writable by default (the local stack
5
+ // uses the twin as its authoritative Stripe); pass readOnly to reject writes (R4).
6
+ //
7
+ // The surface is a plain `fetch` (`createStripeTwinFetch`) and the SERVER is one line of
8
+ // `Bun.serve` around it — see that factory's docstring for why (a serverless entry has no
9
+ // port to bind, so it mounts the fetch in-process).
10
+ import { bindSemantics, coreFor, createDerivedFetch, crossCutting, readParams, semanticsContext, serveHttp, vendorError } from '@volter/world-core';
11
+ import { stripeCheckoutFlow } from "./screens/checkout.js";
12
+ import { stripeJs } from "./stripe-js.js";
13
+ import { stripeFinancialConnectionsFlow } from "./screens/financial-connections.js";
14
+ import { stripeIdentityFlow } from "./screens/identity.js";
15
+ import { stripeOnboardingFlow } from "./screens/onboarding.js";
16
+ import { stripePortalFlow } from "./screens/portal.js";
17
+ import { stripePublicDetailsFlow } from "./screens/public-details.js";
18
+ import surface from './generated/surface.gen.json' with { type: 'json' };
19
+ import { manifest } from "./manifest.js";
20
+ import { appsSecrets } from "./semantics/apps-secrets.js";
21
+ import { balances } from "./semantics/balance.js";
22
+ import { billing } from "./semantics/billing.js";
23
+ import { charges } from "./semantics/charges.js";
24
+ import { checkout } from "./semantics/checkout.js";
25
+ import { connect } from "./semantics/connect.js";
26
+ import { coupons } from "./semantics/coupons.js";
27
+ import { creditNotes } from "./semantics/credit-notes.js";
28
+ import { customers } from "./semantics/customers.js";
29
+ import { disputes } from "./semantics/disputes.js";
30
+ import { entitlements } from "./semantics/entitlements.js";
31
+ import { ephemeralKeys } from "./semantics/ephemeral-keys.js";
32
+ import { files } from "./semantics/files.js";
33
+ import { invoices } from "./semantics/invoices.js";
34
+ import { issuing, lapseRealtimeRequests } from "./semantics/issuing.js";
35
+ import { paymentIntents } from "./semantics/payment-intents.js";
36
+ import { paymentLinks } from "./semantics/payment-links.js";
37
+ import { paymentMethods } from "./semantics/payment-methods.js";
38
+ import { platform } from "./semantics/platform.js";
39
+ import { plans } from "./semantics/plans.js";
40
+ import { products } from "./semantics/products.js";
41
+ import { radar } from "./semantics/radar.js";
42
+ import { refunds } from "./semantics/refunds.js";
43
+ import { setupIntents } from "./semantics/setup-intents.js";
44
+ import { subscriptionSchedules } from "./semantics/subscription-schedules.js";
45
+ import { subscriptions } from "./semantics/subscriptions.js";
46
+ import { tax } from "./semantics/tax.js";
47
+ import { terminal } from "./semantics/terminal.js";
48
+ import { testClocks } from "./semantics/test-clocks.js";
49
+ import { ledger } from "./semantics/ledger.js";
50
+ import { tokens } from "./semantics/tokens.js";
51
+ import { transfers } from "./semantics/transfers.js";
52
+ import { treasury } from "./semantics/treasury.js";
53
+ import { webhookEndpoints } from "./semantics/webhook-endpoints.js";
54
+ import { advancePayouts, balanceBody, payDuePayouts } from "./semantics/balance.js";
55
+ import { settleDueEntries } from "./semantics/ledger.js";
56
+ import { settleHeldRefunds } from "./semantics/refunds.js";
57
+ import { settleBankDebits } from "./semantics/payment-intents.js";
58
+ import { lapseCoupons } from "./semantics/coupons.js";
59
+ import { finishClockAdvances } from "./semantics/test-clocks.js";
60
+ import { settleTopups } from "./semantics/terminal.js";
61
+ import { finishReportRuns } from "./semantics/platform.js";
62
+ import { advanceBilling } from "./semantics/renewals.js";
63
+ import { refuseParameters } from "./stripe-params.js";
64
+ import { afterStripeWrite, handleStripeDoor, PLATFORM_ACCOUNT_ID } from "./stripe-twin.js";
65
+ import { worldNow, statefulTwinManifest } from '@volter/world-core';
66
+ import { expandOf, render, servesCurrent, withoutEndpointSecret } from "./stripe-version.js";
67
+ // ── what a publishable key may call ──
68
+ // "Publishable API key pk_... | Safe to expose: Yes | API key for Stripe.js, Elements, and mobile SDKs. It can identify
69
+ // your account and create tokens or PaymentMethods from payment details, but it can't perform sensitive operations such
70
+ // as creating charges or reading account data" (docs.stripe.com/keys). The served spec names the calls a publishable key
71
+ // makes with an object's client secret: "You can retrieve a PaymentIntent client-side using a publishable key when the
72
+ // client_secret is provided in the query string" (GET /v1/payment_intents/{intent}), "Client-side retrieval using a
73
+ // publishable key is allowed when the client_secret is provided" (GET /v1/setup_intents/{intent}), "Required if a
74
+ // publishable key is used to retrieve the source" (GET /v1/sources/{source}), and the confirm and verify_microdeposits
75
+ // calls that take "The client secret of the PaymentIntent" (or SetupIntent). Anything else is refused with Stripe's
76
+ // code: "secret_key_required | The API key provided is a publishable key, but a secret key is required"
77
+ // (docs.stripe.com/error-codes), as 403, "The API key doesn't have permissions to perform the request"
78
+ // (docs.stripe.com/api/errors).
79
+ // Where the documentation stops and the twin decides: the list above is the whole of what a publishable key may call
80
+ // (Stripe publishes no complete list); a client-secret call without the secret answers parameter_missing, and one with a
81
+ // secret that is not the object's answers the object's 404, as though the key could not see it.
82
+ const PUBLISHABLE_CREATES = new Set(['PostTokens', 'PostPaymentMethods']);
83
+ const BY_CLIENT_SECRET = {
84
+ GetPaymentIntentsIntent: { type: 'payment_intent', param: 'intent' },
85
+ PostPaymentIntentsIntentConfirm: { type: 'payment_intent', param: 'intent' },
86
+ PostPaymentIntentsIntentVerifyMicrodeposits: { type: 'payment_intent', param: 'intent' },
87
+ GetSetupIntentsIntent: { type: 'setup_intent', param: 'intent' },
88
+ PostSetupIntentsIntentConfirm: { type: 'setup_intent', param: 'intent' },
89
+ PostSetupIntentsIntentVerifyMicrodeposits: { type: 'setup_intent', param: 'intent' },
90
+ GetSourcesSource: { type: 'source', param: 'source' },
91
+ };
92
+ /** Stripe's refusal of a call a publishable key may not make, or undefined when the key may make it. */
93
+ async function publishableKeyRefused(call, scope) {
94
+ const key = /^bearer\s+(\S+)/i.exec(call.request.headers.get('authorization') ?? '')?.[1] ?? '';
95
+ if (!key.startsWith('pk_'))
96
+ return undefined;
97
+ if (PUBLISHABLE_CREATES.has(call.operation.id))
98
+ return undefined;
99
+ const scoped = BY_CLIENT_SECRET[call.operation.id];
100
+ if (!scoped)
101
+ return vendorError(manifest, { status: 403, code: 'secret_key_required', message: 'The API key provided is a publishable key, but a secret key is required.' });
102
+ const params = await readParams(manifest, call.request.clone(), call.operation);
103
+ const secret = typeof params.client_secret === 'string' ? params.client_secret : '';
104
+ if (!secret)
105
+ return vendorError(manifest, { status: 400, code: 'parameter_missing', param: 'client_secret', message: 'Missing required param: client_secret.' });
106
+ const id = call.params[scoped.param] ?? '';
107
+ // the context reads a body of its own, so the handler after this still has the request's
108
+ const ctx = await semanticsContext(manifest, call.request.clone(), call.operation, scope);
109
+ return ctx.get(scoped.type, id)?.client_secret === secret ? undefined : wrongClientSecret(scoped, id);
110
+ }
111
+ /** A client-secret call whose secret is not the object's: answered as though the key could not see it (the twin's
112
+ * decision, above). */
113
+ function wrongClientSecret(scoped, id) {
114
+ return vendorError(manifest, { status: 404, code: 'resource_missing', param: scoped.param, message: `No such ${scoped.type}: '${id}'` });
115
+ }
116
+ /**
117
+ * The whole Stripe serve path as a plain `(Request) => Response` — the `/twin` manifest
118
+ * door, the header threading (idempotency key, pinned API version, Connect account) and
119
+ * the derived dispatch over the hand-written routes. NOTHING about it is port-bound.
120
+ *
121
+ * Why this is the factory and `createStripeTwinServer` is a wrapper (runtime contract R12,
122
+ * the Cloudflare ruling): a Durable Object / Worker entry has no loopback ports — it mounts
123
+ * pack fetches IN-PROCESS behind one router. Handing that entry `Bun.serve` is not an
124
+ * option, so the vendor HTTP adaptation has to be a value it can call. Keeping the server a
125
+ * thin `Bun.serve(fetch)` also means the local and hosted lanes execute the SAME bytes of
126
+ * serving code — the parity claim (R9) is about one code path, not two that resemble each
127
+ * other.
128
+ *
129
+ * SCOPING THE STORES AROUND IT: this fetch is ASYNC, so install the world store with
130
+ * `setActiveWorldStore(store)` in a try/finally — **not** `withWorldStore(store, fn)`, whose
131
+ * `finally` fires when `fn` RETURNS, i.e. at the first `await`, restoring the previous store
132
+ * under the rest of the request.
133
+ */
134
+ export function createStripeTwinFetch(options) {
135
+ const readOnly = options.readOnly ?? false;
136
+ const scope = { ...(options.root !== undefined ? { root: options.root } : {}), ...(options.clock ? { clock: options.clock } : {}) };
137
+ // The derived dispatch owns the API: an operation with a semantics handler is served by it, one on a
138
+ // resource the manifest declares by the derived core, and one neither models answers Stripe's
139
+ // unrecognized-URL 404.
140
+ const guard = crossCutting(manifest, { readOnly, ...scope });
141
+ const handlerMap = { ...billing, ...paymentIntents, ...customers, ...products, ...plans, ...charges, ...refunds, ...setupIntents, ...paymentMethods, ...subscriptions, ...invoices, ...checkout, ...ephemeralKeys, ...disputes, ...balances, ...coupons, ...creditNotes, ...subscriptionSchedules, ...entitlements, ...testClocks, ...webhookEndpoints, ...connect, ...transfers, ...appsSecrets, ...tokens, ...files, ...tax, ...paymentLinks, ...radar, ...issuing, ...terminal, ...treasury, ...platform, ...ledger };
142
+ const core = coreFor(manifest, scope);
143
+ const derived = createDerivedFetch({
144
+ surface,
145
+ handlers: bindSemantics(manifest, handlerMap, scope),
146
+ core,
147
+ // after the credential and the version, a publishable key is held to the client-side calls, then a request's
148
+ // parameters are checked against the operation's (stripe-params.ts)
149
+ around: (call, next) => guard(call, async () => (await publishableKeyRefused(call, scope)) ?? (await refuseParameters(call)) ?? next()),
150
+ gap: (request) => vendorError(manifest, { status: 404, message: `Unrecognized request URL (${request.method}: ${new URL(request.url).pathname}).` }),
151
+ });
152
+ // the hosted flows sit beside the API: checkout.stripe.com's payment page, billing.stripe.com's customer portal,
153
+ // connect.stripe.com's onboarding, verify.stripe.com's identity check and the bank-linking flow Stripe.js opens, and
154
+ // the Dashboard's Public details page (dashboard.stripe.com/settings/public, the platform's customer-facing name);
155
+ // a read-only twin takes no payments and moves nothing
156
+ const flows = [stripeCheckoutFlow(scope), stripePortalFlow(scope), stripeOnboardingFlow(scope), stripeIdentityFlow(scope), stripeFinancialConnectionsFlow(scope), stripePublicDetailsFlow(scope)];
157
+ // the twin's own doors sit in front of the API: discovery, and what stands in for an act Stripe's API
158
+ // does not have (stripe-twin.ts)
159
+ // GET /twin: what this twin is (not Stripe's; a host reads it)
160
+ function discovery() {
161
+ return Response.json(statefulTwinManifest({ vendor: 'stripe', twinOf: 'the Stripe REST API', stores: 'customers, payment objects, checkout sessions, products/prices and webhook endpoints (signed events)' }));
162
+ }
163
+ // /_twin/…: a door's body is read as the API's is: a form, or JSON
164
+ const twinDoor = async (request, url) => {
165
+ const answer = await handleStripeDoor({
166
+ method: request.method, path: url.pathname, readOnly,
167
+ occurredAt: options.clock ? options.clock() : worldNow(),
168
+ ...(options.root !== undefined ? { root: options.root } : {}),
169
+ }, await readParams(manifest, request));
170
+ return answer && Response.json(answer.body, { status: answer.status, headers: { 'request-id': 'req_twin' } });
171
+ };
172
+ const door = async (request) => {
173
+ const url = new URL(request.url);
174
+ if (request.method === 'GET' && url.pathname.replace(/\/+$/, '') === '/twin')
175
+ return discovery();
176
+ return url.pathname.startsWith('/_twin/') ? twinDoor(request, url) : undefined;
177
+ };
178
+ // time's moves Stripe makes on its own (a subscription renewing at its period's end, its renewal charged an hour
179
+ // later: semantics/renewals.ts; each account's automatic payouts: semantics/balance.ts) are caught up to the World's clock before anything is answered, so every door
180
+ // (the API, the hosted pages) reads the account as it stands now
181
+ const billingClock = surface.operations.find((o) => o.id === 'GetSubscriptions');
182
+ const catchUp = async (request) => {
183
+ if (readOnly)
184
+ return;
185
+ const ctx = await semanticsContext(manifest, new Request(request.url), billingClock, scope);
186
+ // a test clock advanced by the last request has reached its time (semantics/test-clocks.ts)
187
+ await finishClockAdvances(ctx);
188
+ await advanceBilling(ctx);
189
+ // a submitted bank debit settles (in test mode at once) before anything is answered (semantics/payment-intents.ts)
190
+ await settleBankDebits(ctx);
191
+ // a coupon past its redeem_by is no longer valid (semantics/coupons.ts)
192
+ await lapseCoupons(ctx);
193
+ // a top-up's funds arrive five days after it is made (semantics/terminal.ts)
194
+ await settleTopups(ctx);
195
+ // a report run completes (semantics/platform.ts)
196
+ await finishReportRuns(ctx);
197
+ // a real-time authorization request no one answered is decided when its window ends (semantics/issuing.ts)
198
+ await lapseRealtimeRequests(ctx);
199
+ // a refund held for want of balance is made when funds cover it, before any payout takes them (semantics/refunds.ts)
200
+ await settleHeldRefunds(ctx);
201
+ await advancePayouts(ctx);
202
+ };
203
+ // Time's EVENTS, sent on the vendor's clock through a twin-only drain door, as the qstash and vercel twins send
204
+ // theirs (a caller — a runner's drainer — drives each move). POST /_twin/drain catches time up as every request
205
+ // does, then writes what time settled on each account: payouts whose arrival date came (pending → paid, sent as
206
+ // payout.paid) and funds that came due (pending → available), for which the account is sent one balance.available
207
+ // ("Occurs whenever your Stripe balance has been updated (e.g., when a charge is available to be paid out)",
208
+ // docs.stripe.com/api/events/types) carrying its Balance, when an entry that settled adds to it ("This event is not
209
+ // fired for negative transactions", the same page); a connected account's events go to Connect endpoints.
210
+ // A read already sees these moves; the drain is what makes Stripe's events about them arrive. Answers what it sent.
211
+ const drain = async (request) => {
212
+ if (readOnly)
213
+ return Response.json({ error: 'twin is read-only; omit readOnly to accept writes' }, { status: 405 });
214
+ await catchUp(request);
215
+ const at = (account) => semanticsContext(manifest, new Request(request.url, account ? { headers: { 'stripe-account': account } } : {}), billingClock, scope);
216
+ const platformCtx = await at();
217
+ const accounts = [undefined, ...platformCtx.rows('account').map((a) => String(a.id)).filter((id) => id !== PLATFORM_ACCOUNT_ID)];
218
+ const delivered = [];
219
+ for (const account of accounts) {
220
+ const ctx = account ? await at(account) : platformCtx;
221
+ for (const id of await payDuePayouts(ctx))
222
+ delivered.push({ type: 'payout.paid', id, ...(account ? { account } : {}) });
223
+ if ((await settleDueEntries(ctx)).some((t) => Number(t.net) > 0)) {
224
+ await afterStripeWrite('balance', 'balance.available', balanceBody(ctx), options.root, ctx.occurredAt, undefined, account);
225
+ delivered.push({ type: 'balance.available', ...(account ? { account } : {}) });
226
+ }
227
+ }
228
+ return Response.json({ delivered });
229
+ };
230
+ const served = async (request) => {
231
+ if (request.method === 'POST' && new URL(request.url).pathname.replace(/\/+$/, '') === '/_twin/drain')
232
+ return drain(request);
233
+ const opened = await door(request);
234
+ if (opened)
235
+ return opened;
236
+ // the client library an application's page loads from js.stripe.com (stripe-js.ts); it moves nothing, so a
237
+ // read-only twin serves it too
238
+ const library = stripeJs(request);
239
+ if (library)
240
+ return library;
241
+ await catchUp(request);
242
+ if (!readOnly)
243
+ for (const flow of flows) {
244
+ const page = await flow(request);
245
+ if (page)
246
+ return page;
247
+ }
248
+ // an update's metadata is merged into what the object holds before the handler or the core serves it (mergeMetadata)
249
+ return derived(readOnly ? request : await mergeMetadata(request, (op) => !(op.id in handlerMap) && core.owns(op), scope));
250
+ };
251
+ // every answer in the shape of the API version the caller is served (stripe-version.ts)
252
+ const rendered = async (request) => {
253
+ const expand = expandOf(request.clone());
254
+ const creates = request.method === 'POST' && new URL(request.url).pathname.replace(/\/+$/, '') === '/v1/webhook_endpoints';
255
+ const res = await served(request);
256
+ const pinned = request.headers.get('stripe-version');
257
+ if (!(res.headers.get('content-type') ?? '').includes('json'))
258
+ return res;
259
+ if (!servesCurrent(pinned) && creates)
260
+ return res;
261
+ const body = await res.json();
262
+ // a webhook endpoint's `secret` is "Only returned at creation" (docs.stripe.com/api/webhook_endpoints/object)
263
+ const answered = creates ? body : withoutEndpointSecret(body);
264
+ return new Response(JSON.stringify(servesCurrent(pinned) ? render(answered, pinned, await expand) : answered), { status: res.status, statusText: res.statusText, headers: res.headers });
265
+ };
266
+ return Object.assign(rendered, { owners: derived.owners });
267
+ }
268
+ export async function createStripeTwinServer(options) {
269
+ const server = await serveHttp({
270
+ port: options.port ?? 0,
271
+ idleTimeout: 60,
272
+ fetch: createStripeTwinFetch(options),
273
+ });
274
+ return { port: server.port ?? options.port ?? 0, stop: () => server.stop(true) };
275
+ }
276
+ // the update operations, by their path as a pattern, for mergeMetadata
277
+ const UPDATES = surface.operations.filter((o) => o.class === 'update' && o.method.toUpperCase() === 'POST')
278
+ .map((op) => ({ op, re: new RegExp(`^${op.path.replace(/[.*+?^$()|[\]\\]/g, '\\$&').replace(/\\\{[^}]+\\\}|\{[^}]+\}/g, '([^/]+)')}/?$`) }));
279
+ /** An update's `metadata`, merged into what the object holds before anything serves the update. "This parameter uses a
280
+ * merge mechanism, which allows you to add new key-value pairs to an object in an update call without affecting any
281
+ * existing metadata"; "Pass in the key with an empty string as the value to remove the key from the metadata"; "Pass an
282
+ * empty string as the value for the metadata attribute to delete all of the keys simultaneously"
283
+ * (docs.stripe.com/metadata). The derived core already merges a nested hash where the manifest leaves `update` at
284
+ * `merge` (dropping keys set to ""), so only a clear-all is rewritten for it; where a handler or a `replace` update
285
+ * stores the request's metadata whole, the request is rewritten to carry the merged hash, so every door stores the same
286
+ * answer. The request is rewritten as JSON (readParams reads either). */
287
+ async function mergeMetadata(request, coreMerges, scope) {
288
+ if (request.method !== 'POST' || (request.headers.get('content-type') ?? '').includes('multipart'))
289
+ return request;
290
+ const path = new URL(request.url).pathname;
291
+ let op;
292
+ let id = '';
293
+ for (const u of UPDATES) {
294
+ const m = u.re.exec(path);
295
+ if (m) {
296
+ op = u.op;
297
+ id = decodeURIComponent(m.at(-1) ?? '');
298
+ break;
299
+ }
300
+ }
301
+ if (!op?.resource)
302
+ return request;
303
+ const params = await readParams(manifest, request.clone(), op);
304
+ if (!('metadata' in params))
305
+ return request;
306
+ const given = params.metadata;
307
+ // a plan is kept as the recurring price it is (semantics/plans.ts)
308
+ const resource = op.resource === 'plan' ? 'price' : op.resource;
309
+ const ctx = await semanticsContext(manifest, request.clone(), op, scope);
310
+ const held = ctx.get(resource, id)?.metadata;
311
+ const prior = held && typeof held === 'object' ? held : {};
312
+ const merges = coreMerges(op) && manifest.resources[resource]?.update !== 'replace';
313
+ let metadata;
314
+ if (given === '')
315
+ metadata = merges ? Object.fromEntries(Object.keys(prior).map((k) => [k, ''])) : {};
316
+ else if (given && typeof given === 'object' && !Array.isArray(given)) {
317
+ if (merges)
318
+ return request;
319
+ metadata = Object.fromEntries(Object.entries({ ...prior, ...given }).filter(([, v]) => v !== ''));
320
+ }
321
+ else
322
+ return request;
323
+ const headers = new Headers(request.headers);
324
+ headers.set('content-type', 'application/json');
325
+ return new Request(request.url, { method: request.method, headers, body: JSON.stringify({ ...params, metadata }) });
326
+ }
@@ -0,0 +1,106 @@
1
+ export type StripeRow = Record<string, any>;
2
+ /** The name an account shows its customers (Checkout, the customer portal): its public business name,
3
+ * `business_profile.name` ("The customer-facing business name", docs.stripe.com/api/accounts/object), which the
4
+ * operator sets on the Dashboard ("You can change a Checkout page's name by modifying the Business name field",
5
+ * docs.stripe.com/payments/checkout/customization/appearance). Where the documentation stops and the twin decides:
6
+ * with none set it falls back to the Dashboard's account name, `settings.dashboard.display_name` ("used on the Stripe
7
+ * Dashboard to differentiate between accounts", the same object page), and with neither to "Twin Inc.", the name the
8
+ * Dashboard mirror has always given the World's own account. */
9
+ export declare const PLATFORM_DEFAULT_NAME = "Twin Inc.";
10
+ export declare function publicBusinessName(account: StripeRow | undefined): string;
11
+ /**
12
+ * Format a Stripe minor-unit amount (cents) as a localized currency string.
13
+ * Honors zero-decimal currencies (¥4200 not ¥42.00). Non-numbers → an em dash.
14
+ */
15
+ export declare function formatStripeAmount(value: unknown, currency?: string): string;
16
+ /**
17
+ * Render a Stripe price's `recurring` block as a short interval label, e.g.
18
+ * "every month", "every 3 months". Returns '' when it isn't a recurring price.
19
+ */
20
+ export declare function formatRecurring(recurring: unknown): string;
21
+ /**
22
+ * Render a saved payment method as a short human label, e.g. "Visa •••• 4242"
23
+ * for a card, or the bare `type` ("us_bank_account") for non-card methods.
24
+ */
25
+ export declare function formatPaymentMethod(pm: unknown): string;
26
+ /**
27
+ * Extract the HTTP(S) image URLs from a product's `images` field (Stripe stores an
28
+ * array of URL strings) so the mirror can render them as <img> thumbnails instead
29
+ * of plain text. Non-arrays / non-URL entries are dropped. Order is preserved.
30
+ */
31
+ export declare function productImageUrls(images: unknown): string[];
32
+ /**
33
+ * Render a payment_intent / charge `last_payment_error` (the test-card decline state)
34
+ * as a single human-readable line, e.g. "card_declined (insufficient_funds): Your card
35
+ * has insufficient funds." Returns '' when there is no error object. This is the
36
+ * vendor-faithful decline reason the twin populates on a declined confirm.
37
+ */
38
+ export declare function formatPaymentError(error: unknown): string;
39
+ /**
40
+ * Summarize a synthesized Stripe `balance` object (available/pending arrays, one entry
41
+ * per currency) into short per-bucket lines, e.g. ["available: $42.00", "pending: $0.00"].
42
+ * The balance is not a list collection, so the mirror renders this summary directly.
43
+ */
44
+ export declare function formatBalanceSummary(balance: unknown): Array<{
45
+ bucket: string;
46
+ text: string;
47
+ }>;
48
+ /**
49
+ * Summarize a Connect connected `account` object's enablement state into the three
50
+ * boolean capability flags a real Stripe Connect dashboard shows up front:
51
+ * charges_enabled, payouts_enabled, details_submitted. Each is rendered as a tone-
52
+ * carrying flag (true → ok, false → warn) so an un-onboarded account reads as such.
53
+ */
54
+ export type AccountFlag = {
55
+ key: string;
56
+ label: string;
57
+ enabled: boolean;
58
+ };
59
+ export declare function formatAccountFlags(account: unknown): AccountFlag[];
60
+ /**
61
+ * Extract a Connect account's outstanding onboarding requirements (the
62
+ * `requirements.currently_due` list real Stripe shows as "needs attention"). Returns
63
+ * an ordered list of the still-due field paths; empty when nothing is due.
64
+ */
65
+ export declare function accountCurrentlyDue(account: unknown): string[];
66
+ /** Tone for a status pill: 'ok' (green), 'warn' (amber), 'bad' (red), '' (neutral). */
67
+ export type PillTone = 'ok' | 'warn' | 'bad' | '';
68
+ export declare function statusTone(value: unknown): PillTone;
69
+ /** True when a key names a field whose value is a Stripe object id we can link. */
70
+ export declare function isReferenceKey(key: string): boolean;
71
+ /** The collection a reference field points at, or undefined if not a reference. */
72
+ export declare function referenceCollection(key: string): string | undefined;
73
+ /** A single line in the flattened, human-readable view of a nested value. */
74
+ export type FlatLine = {
75
+ depth: number;
76
+ label: string;
77
+ value: string;
78
+ ref?: string;
79
+ };
80
+ /**
81
+ * Flatten an arbitrary nested Stripe value (object / array / scalar) into ordered,
82
+ * indented label/value lines suitable for a readable detail view — instead of the
83
+ * old "[object Object]". Stripe "list" wrappers ({object:'list',data:[...]}) are
84
+ * unwrapped to their `data`. Amount-ish fields are currency-formatted.
85
+ */
86
+ export declare function flattenStripeValue(value: unknown, opts?: {
87
+ label?: string;
88
+ depth?: number;
89
+ currency?: string;
90
+ }): FlatLine[];
91
+ /**
92
+ * Resolve the cross-references for a row: the rows in other collections that this
93
+ * row points AT (outgoing, e.g. invoice→customer) and the rows that point BACK at
94
+ * it (incoming, e.g. customer←subscriptions). Resolved purely from already-fetched
95
+ * collection data, so the UI can render clickable links without extra requests.
96
+ */
97
+ export type RefLink = {
98
+ collection: string;
99
+ id: string;
100
+ label: string;
101
+ };
102
+ export type CrossRefs = {
103
+ outgoing: RefLink[];
104
+ incoming: RefLink[];
105
+ };
106
+ export declare function resolveCrossRefs(collection: string, row: StripeRow, data: Record<string, StripeRow[]>): CrossRefs;