@vaam-apps/vpay-stripe-js 0.2.1

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.
@@ -0,0 +1,358 @@
1
+ /**
2
+ * Wire and API types for vpay's browser surface
3
+ * (`docs/plans/2026-09-03-step5c-stripejs.md` §1, `docs/api/README.md`).
4
+ *
5
+ * The object types mirror `vpay_api::model` exactly. Where a name also
6
+ * exists in `@stripe/stripe-js` the shape is Stripe's, so that a merchant
7
+ * who has integrated against Stripe reads the same field names here — see
8
+ * `src/compat.test.ts` for which of those shapes are actually assignable
9
+ * across the two packages and which are not.
10
+ */
11
+ import type { StripeError } from "./errors.js";
12
+ import type { CheckoutPopup, OpenCheckoutPopupOptions } from "./popup.js";
13
+ /**
14
+ * The five-value state machine `vpay_core::state::IntentStatus` defines
15
+ * (`docs/flows/payment-lifecycle.md`). There is deliberately no `failed`
16
+ * status — a rail failure returns the intent to `requires_payment_method`
17
+ * with {@link LastPaymentError} populated, which is why
18
+ * {@link Stripe.waitForPaymentIntent} must inspect both fields to decide it
19
+ * is finished.
20
+ */
21
+ export type PaymentIntentStatus = "requires_payment_method" | "requires_action" | "processing" | "succeeded" | "canceled";
22
+ /** Redirect-rail next step — Stripe's own `next_action.redirect_to_url` shape. */
23
+ export interface NextAction {
24
+ type: "redirect_to_url";
25
+ redirect_to_url: {
26
+ url: string;
27
+ /**
28
+ * The merchant's `return_url`, echoed back. **A label, not a
29
+ * destination**: as of Step 5c nothing in vpay redirects a payer to it
30
+ * (D4, and §0 S2 of the design). See the package README.
31
+ */
32
+ return_url: string | null;
33
+ };
34
+ }
35
+ /**
36
+ * The closed failure-code vocabulary `vpay_core::failure` owns
37
+ * (`docs/flows/failures.md`). Adapters map rail-specific error strings into
38
+ * this list, so a payer-facing message is written once per code rather than
39
+ * once per rail.
40
+ *
41
+ * **Not every rail can produce every code.** The list is the *core's*, and it
42
+ * does not shrink when a rail is added — but a merchant branching on all
43
+ * eleven should know that on the two MVP rails, MTN MoMo reaches all of them
44
+ * and Orange Money reaches three (`payer_timeout`,
45
+ * `provider_account_blocked`, `provider_error`). Orange documents five
46
+ * statuses and no sub-reason for `FAILED`, so its protocol has no way to say
47
+ * "not enough funds"; a payer who cancels on its hosted page arrives as
48
+ * `payer_timeout`, because the rail does not distinguish that from an
49
+ * abandoned page. The table, code by code with the rail reason that produces
50
+ * it and the conformance case that proves it, is
51
+ * `docs/flows/failures.md` § "Which rail can produce which code".
52
+ *
53
+ * `payer_declined` in particular was produced by **no** adapter until
54
+ * 2026-09-10 (vpay issue #59), while being typed here and given buyer copy by
55
+ * `examples/shop`. It is now MTN's `PAYMENT_NOT_APPROVED` /
56
+ * `APPROVAL_REJECTED`.
57
+ */
58
+ export type FailureCode = "insufficient_funds" | "payer_timeout" | "payer_declined" | "invalid_payer" | "payer_limit_reached" | "payer_account_blocked" | "invalid_payee" | "payee_account_blocked" | "provider_account_blocked" | "provider_unavailable" | "provider_error";
59
+ export interface LastPaymentError {
60
+ code: FailureCode;
61
+ message: string;
62
+ }
63
+ /**
64
+ * `vpay_api::model::PaymentIntentWithSecret`: the twelve keys of
65
+ * `PaymentIntentObject` — pinned server-side by
66
+ * `every_documented_key_is_present_including_the_null_ones` — plus the
67
+ * `client_secret` the browser surface flattens in alongside them (D2).
68
+ *
69
+ * `client_secret` is `string`, not Stripe's `string | null`: the browser
70
+ * routes are reachable *only* by presenting one, so a response that omitted
71
+ * it would be a server bug rather than a case to model.
72
+ */
73
+ export interface PaymentIntent {
74
+ id: string;
75
+ object: "payment_intent";
76
+ /** Integer minor units. XAF is zero-decimal: `5000` means 5,000 FCFA. */
77
+ amount: number;
78
+ /** Lowercase ISO 4217 code, e.g. `xaf`. */
79
+ currency: string;
80
+ status: PaymentIntentStatus;
81
+ payment_method_types: string[];
82
+ /** `null` on a push rail, and on an intent nobody has confirmed. */
83
+ next_action: NextAction | null;
84
+ /** Present *with* `requires_payment_method` — there is no `failed` status. */
85
+ last_payment_error: LastPaymentError | null;
86
+ metadata: Record<string, string>;
87
+ description: string | null;
88
+ /** Unix **seconds**, not milliseconds. */
89
+ created: number;
90
+ livemode: boolean;
91
+ /** `pi_…_secret_…`. Never log this. */
92
+ client_secret: string;
93
+ }
94
+ /**
95
+ * Stripe.js's `PaymentIntentResult`, member for member.
96
+ *
97
+ * The `error?: undefined` / `paymentIntent?: undefined` members are what
98
+ * make `if (result.error)` narrow `result.paymentIntent` to non-`undefined`
99
+ * — without them a merchant's Stripe-shaped code needs a non-null assertion.
100
+ */
101
+ export type PaymentIntentResult = {
102
+ paymentIntent: PaymentIntent;
103
+ error?: undefined;
104
+ } | {
105
+ paymentIntent?: undefined;
106
+ error: StripeError;
107
+ };
108
+ /** Options for {@link loadStripe}. */
109
+ export interface VpayStripeOptions {
110
+ /**
111
+ * The origin vpay is served from, e.g. `https://api.vpay.example`. The
112
+ * `/v1/browser/...` path is appended by this package; a trailing slash is
113
+ * tolerated and stripped.
114
+ */
115
+ baseUrl: string;
116
+ /**
117
+ * The origin vpay's **checkout app** is served from, e.g.
118
+ * `https://checkout.vpay.example` — the deployment's
119
+ * `checkout.public_base_url`. A different host from {@link baseUrl}: one
120
+ * serves the API, the other serves the page that goes in the iframe.
121
+ *
122
+ * Optional, and **required for {@link Stripe.initEmbeddedCheckout}**,
123
+ * which rejects without it rather than guessing. It is also the value the
124
+ * `message` listener pins `event.origin` against, so a wrong one does not
125
+ * fail open — it silently accepts nothing.
126
+ *
127
+ * Validated here when supplied: an absolute `http:`/`https:` URL, trailing
128
+ * slashes stripped.
129
+ */
130
+ checkoutBaseUrl?: string | undefined;
131
+ /**
132
+ * Injected `fetch`, for tests and for a host that wants its own
133
+ * instrumentation. Defaults to `globalThis.fetch`.
134
+ */
135
+ fetch?: typeof fetch | undefined;
136
+ }
137
+ /** `payment_method_data` for {@link Stripe.confirmMobileMoneyPayment}. */
138
+ export interface MobileMoneyData {
139
+ /** A rail code, e.g. `mtn_momo`. Encoded as `payment_method_data[type]`. */
140
+ type: string;
141
+ /** Encoded as `payment_method_data[<type>][msisdn]`. */
142
+ msisdn: string;
143
+ }
144
+ /** Options for {@link Stripe.confirmPayment}. */
145
+ export interface ConfirmPaymentOptions {
146
+ clientSecret: string;
147
+ confirmParams?: {
148
+ return_url?: string | undefined;
149
+ payment_method_data?: Record<string, unknown> | undefined;
150
+ } | undefined;
151
+ /**
152
+ * `always` (the default) navigates the browser when the rail answers with
153
+ * `next_action.redirect_to_url`, and the returned promise then never
154
+ * settles — Stripe.js's own behaviour, and the only way a caller's
155
+ * `finally` cannot fire a "payment failed" state during the unload.
156
+ * `if_required` suppresses the navigation and resolves with the intent so
157
+ * the caller can render the redirect itself.
158
+ */
159
+ redirect?: "always" | "if_required" | undefined;
160
+ }
161
+ /** Options for {@link Stripe.waitForPaymentIntent}. */
162
+ export interface WaitForPaymentIntentOptions {
163
+ /** Total budget in milliseconds. Default 180000 (three minutes). */
164
+ timeoutMs?: number | undefined;
165
+ /** Base delay between polls in milliseconds, jittered ±25%. Default 2000. */
166
+ intervalMs?: number | undefined;
167
+ }
168
+ /**
169
+ * The object {@link loadStripe} resolves to — a deliberate subset of
170
+ * Stripe.js's `Stripe`.
171
+ *
172
+ * Everything Stripe.js exposes that depends on card data, an iframe served
173
+ * from `js.stripe.com`, or a Stripe-hosted page is **absent by
174
+ * construction**, not stubbed: Elements, `confirmCardPayment`,
175
+ * `createPaymentMethod`, Checkout, Link, Payment Request. The package README
176
+ * carries the full list. A method that is missing is a compile error at the
177
+ * merchant; a method that returned a plausible-looking failure would be a
178
+ * runtime surprise on a payment page.
179
+ */
180
+ export interface Stripe {
181
+ /** `GET /v1/browser/payment_intents/{id}`. The polling endpoint. */
182
+ retrievePaymentIntent(clientSecret: string): Promise<PaymentIntentResult>;
183
+ /** `POST /v1/browser/payment_intents/{id}/confirm`, then the redirect rule above. */
184
+ confirmPayment(options: ConfirmPaymentOptions): Promise<PaymentIntentResult>;
185
+ /** Retrieves, then performs the navigation `next_action` calls for, if any. */
186
+ handleNextAction(options: {
187
+ clientSecret: string;
188
+ }): Promise<PaymentIntentResult>;
189
+ /** {@link confirmPayment} for a push rail: the two fields a payer supplies. */
190
+ confirmMobileMoneyPayment(clientSecret: string, data: MobileMoneyData): Promise<PaymentIntentResult>;
191
+ /** Polls {@link retrievePaymentIntent} until the intent stops moving. */
192
+ waitForPaymentIntent(clientSecret: string, options?: WaitForPaymentIntentOptions): Promise<PaymentIntentResult>;
193
+ /**
194
+ * `GET /v1/browser/checkout/sessions/{id}` — reads a Checkout Session by
195
+ * its own `client_secret`. Never rejects.
196
+ */
197
+ retrieveCheckoutSession(clientSecret: string): Promise<CheckoutSessionResult>;
198
+ /**
199
+ * Frames vpay's checkout page on the merchant's own page (Step 9's D8).
200
+ *
201
+ * **This one rejects**, like {@link loadStripe}: a missing
202
+ * `checkoutBaseUrl` or a `client_secret` that is not a session's is an
203
+ * integration mistake visible on the first render, not a payer-facing
204
+ * failure, and a rejection from `fetchClientSecret` is the merchant's own
205
+ * server call failing.
206
+ */
207
+ initEmbeddedCheckout(options: InitEmbeddedCheckoutOptions): Promise<EmbeddedCheckout>;
208
+ /**
209
+ * Opens vpay's **hosted** checkout page in a popup window the merchant's
210
+ * page owns, and reports completion through `window.opener` (see
211
+ * `src/popup.ts` for why the message comes from the merchant's own return
212
+ * page and not from vpay's).
213
+ *
214
+ * **This one rejects**, like {@link initEmbeddedCheckout}: with
215
+ * `CheckoutPopupBlockedError` when the browser refused the window — the
216
+ * one failure here a correct integration can still hit, and the one a
217
+ * merchant must fall back from — and with a `TypeError` for an
218
+ * integration mistake.
219
+ */
220
+ openCheckoutPopup(options: OpenCheckoutPopupOptions): Promise<CheckoutPopup>;
221
+ }
222
+ /**
223
+ * A Checkout Session's lifecycle state — Step 9's D10, and deliberately
224
+ * vpay's own three values rather than Stripe's.
225
+ *
226
+ * There is no `failed`: a session whose intent reached a terminal
227
+ * non-success state is reported `expired` with
228
+ * {@link CheckoutSession.payment_status} `failed`, the same way a
229
+ * PaymentIntent has no `failed` status either.
230
+ */
231
+ export type CheckoutSessionStatus = "open" | "complete" | "expired";
232
+ /** Whether the session's intent has been paid. D10's second axis. */
233
+ export type CheckoutPaymentStatus = "unpaid" | "paid" | "failed";
234
+ /**
235
+ * Which surface the session is rendered on: `hosted` (vpay serves a
236
+ * top-level page and returns its `url`) or `embedded` (the merchant frames
237
+ * vpay's page with {@link Stripe.initEmbeddedCheckout}).
238
+ */
239
+ export type CheckoutSessionUiMode = "hosted" | "embedded";
240
+ /**
241
+ * `checkout.session` as the **browser** surface renders it — the object in
242
+ * §"The wire contract" of `docs/plans/2026-09-04-step9-hosted-checkout.md`,
243
+ * with `payment_intent` expanded.
244
+ *
245
+ * The one place this differs from the merchant SDKs' `CheckoutSession`
246
+ * (`@vaam-apps/vpay-sdk`, `vpay_sdk`) is {@link payment_intent}, and the difference is
247
+ * deliberate rather than a skew: on `/v1` the field is the `pi_…` **id**; on
248
+ * `GET /v1/browser/checkout/sessions/{id}` it is the whole intent, because
249
+ * vpay's checkout page has to confirm and poll it through the existing
250
+ * browser routes and a second round trip to fetch it would need a credential
251
+ * the page does not have yet. Stripe's own `expand` convention, applied at
252
+ * exactly one route.
253
+ *
254
+ * **This means `retrieveCheckoutSession` hands its caller a live *confirm*
255
+ * credential** (`session.payment_intent.client_secret`), not only a
256
+ * session-read one. That is a wider exposure than the session's own secret
257
+ * and is stated here rather than buried: a merchant's outer page that only
258
+ * wants the session's status should read `status` and `payment_status` and
259
+ * leave the intent alone.
260
+ *
261
+ * `client_secret` is `string`, not `string | null`, for the same reason
262
+ * {@link PaymentIntent.client_secret} is: this route is reachable *only* by
263
+ * presenting one.
264
+ */
265
+ export interface CheckoutSession {
266
+ /** `cs_…`. */
267
+ id: string;
268
+ object: "checkout.session";
269
+ livemode: boolean;
270
+ /**
271
+ * The intent this session drives, **expanded** — every
272
+ * {@link PaymentIntent} field, `client_secret` included. A session never
273
+ * creates its intent; it references one that already exists.
274
+ *
275
+ * Typed as the object rather than `string | PaymentIntent` because this
276
+ * package calls exactly one route and that route always expands it. The
277
+ * *return* read (`…/{id}/return?t=…`) expands it too but omits the
278
+ * intent's `client_secret` — nothing here calls that route, it is vpay's
279
+ * own return page, and typing a union for a response this package never
280
+ * receives would push a needless narrowing onto every caller.
281
+ */
282
+ payment_intent: PaymentIntent;
283
+ ui_mode: CheckoutSessionUiMode;
284
+ status: CheckoutSessionStatus;
285
+ payment_status: CheckoutPaymentStatus;
286
+ /** Hosted mode only; `null` on an embedded session. May carry `{CHECKOUT_SESSION_ID}` (D5). */
287
+ success_url: string | null;
288
+ /** Hosted mode only; `null` on an embedded session. */
289
+ cancel_url: string | null;
290
+ /** Embedded mode only; `null` on a hosted session. */
291
+ return_url: string | null;
292
+ /** The page vpay serves for a hosted session, secret in the fragment (D6); `null` when embedded. */
293
+ url: string | null;
294
+ /** Unix **seconds**. 24 h from create (D10). */
295
+ expires_at: number;
296
+ /** Unix **seconds**. */
297
+ created: number;
298
+ /** `cs_…_secret_…`. Never log this. */
299
+ client_secret: string;
300
+ }
301
+ /**
302
+ * {@link Stripe.retrieveCheckoutSession}'s answer, shaped like
303
+ * {@link PaymentIntentResult} so the same `if (result.error)` narrowing
304
+ * works. It never rejects — see the package README's "Errors".
305
+ */
306
+ export type CheckoutSessionResult = {
307
+ checkoutSession: CheckoutSession;
308
+ error?: undefined;
309
+ } | {
310
+ checkoutSession?: undefined;
311
+ error: StripeError;
312
+ };
313
+ /**
314
+ * What vpay's page sends the parent when the payer is finished
315
+ * (`{type:'vpay:complete', session, status}`, D8).
316
+ *
317
+ * Both members are strings on the wire and a message whose `session` or
318
+ * `status` is anything else is **ignored**, not coerced: this crosses an
319
+ * origin boundary, and a callback fired with a half-understood payload is
320
+ * worse than one that did not fire.
321
+ */
322
+ export interface EmbeddedCheckoutCompleteEvent {
323
+ /** The `cs_…` that completed. Look the outcome up server-side; do not trust `status` alone. */
324
+ session: string;
325
+ /** The session's {@link CheckoutSessionStatus} as the page saw it. */
326
+ status: string;
327
+ }
328
+ /** Options for {@link Stripe.initEmbeddedCheckout}. */
329
+ export interface InitEmbeddedCheckoutOptions {
330
+ /**
331
+ * Returns the session's `client_secret` — the merchant's own server call
332
+ * to `POST /v1/checkout/sessions`, proxied through its page. Called once
333
+ * per {@link Stripe.initEmbeddedCheckout}; a rejection propagates.
334
+ */
335
+ fetchClientSecret: () => Promise<string>;
336
+ /**
337
+ * Called when vpay's page reports the payer is finished. **Not** proof of
338
+ * payment: it is a message from an iframe, so treat it as a cue to
339
+ * re-read the session from the merchant's own server.
340
+ */
341
+ onComplete?: ((event: EmbeddedCheckoutCompleteEvent) => void) | undefined;
342
+ }
343
+ /**
344
+ * The handle {@link Stripe.initEmbeddedCheckout} resolves to.
345
+ *
346
+ * Member for member `@stripe/stripe-js`'s own `StripeEmbeddedCheckout` —
347
+ * pinned as a compile-time assertion in `src/compat.test.ts`, in both
348
+ * directions, because this is the one part of Checkout where the two
349
+ * packages' shapes genuinely do coincide.
350
+ */
351
+ export interface EmbeddedCheckout {
352
+ /** Attaches the frame to a CSS selector or an element. */
353
+ mount(location: string | HTMLElement): void;
354
+ /** Detaches the frame. The handle stays usable — {@link mount} may be called again. */
355
+ unmount(): void;
356
+ /** Detaches the frame, drops the `message` listener, and makes the handle unusable. */
357
+ destroy(): void;
358
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@vaam-apps/vpay-stripe-js",
3
+ "version": "0.2.1",
4
+ "description": "A Stripe.js-shaped browser client for vpay's payer surface: payment intents, embedded and hosted Checkout, zero runtime dependencies.",
5
+ "license": "Apache-2.0",
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/vaam-apps/vpay.git",
12
+ "directory": "sdks/stripe-js"
13
+ },
14
+ "homepage": "https://github.com/vaam-apps/vpay/tree/master/sdks/stripe-js#readme",
15
+ "bugs": {
16
+ "url": "https://github.com/vaam-apps/vpay/issues"
17
+ },
18
+ "type": "module",
19
+ "engines": {
20
+ "node": ">=22.11.0"
21
+ },
22
+ "main": "./dist/index.js",
23
+ "types": "./dist/index.d.ts",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "default": "./dist/index.js"
28
+ }
29
+ },
30
+ "sideEffects": false,
31
+ "files": [
32
+ "dist",
33
+ "README.md"
34
+ ],
35
+ "devDependencies": {
36
+ "@stripe/stripe-js": "9.15.0",
37
+ "@types/node": "^22.10.0",
38
+ "eslint": "9.39.5",
39
+ "jsdom": "^25.0.1",
40
+ "typescript": "^5.7.0",
41
+ "vitest": "^4.1.11",
42
+ "@vpay/config": "0.0.0"
43
+ },
44
+ "scripts": {
45
+ "build": "tsc -p tsconfig.build.json",
46
+ "typecheck": "tsc -p tsconfig.json --noEmit",
47
+ "test": "vitest run",
48
+ "lint": "eslint . --max-warnings 0"
49
+ }
50
+ }