@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.
- package/LICENSE +21 -0
- package/README.md +477 -0
- package/dist/client.d.ts +50 -0
- package/dist/client.js +551 -0
- package/dist/embedded.d.ts +68 -0
- package/dist/embedded.js +196 -0
- package/dist/errors.d.ts +91 -0
- package/dist/errors.js +103 -0
- package/dist/form.d.ts +55 -0
- package/dist/form.js +135 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +14 -0
- package/dist/popup.d.ts +168 -0
- package/dist/popup.js +260 -0
- package/dist/types.d.ts +358 -0
- package/dist/types.js +1 -0
- package/package.json +50 -0
package/dist/embedded.js
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
/** The three messages vpay's checkout page sends its framer (D8). */
|
|
2
|
+
const MESSAGE_TYPES = {
|
|
3
|
+
resize: "vpay:resize",
|
|
4
|
+
complete: "vpay:complete",
|
|
5
|
+
redirect: "vpay:redirect",
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* What the frame is allowed to do.
|
|
9
|
+
*
|
|
10
|
+
* `allow-same-origin` is required, not a relaxation: without it the frame
|
|
11
|
+
* runs in an opaque origin, its `/v1/browser` requests carry `Origin: null`
|
|
12
|
+
* and vpay's CORS layer refuses them. What the list *withholds* is the
|
|
13
|
+
* point — `allow-top-navigation` is absent, so the page physically cannot
|
|
14
|
+
* navigate the merchant's tab, which is why the redirect rail's hand-off is
|
|
15
|
+
* a `vpay:redirect` message the parent acts on rather than something the
|
|
16
|
+
* frame does itself.
|
|
17
|
+
*/
|
|
18
|
+
const FRAME_SANDBOX = "allow-scripts allow-same-origin allow-forms";
|
|
19
|
+
/**
|
|
20
|
+
* True only for an absolute `http:`/`https:` URL.
|
|
21
|
+
*
|
|
22
|
+
* Duplicated in spirit from `client.ts`'s `isSafeRedirectUrl` and applied
|
|
23
|
+
* for a stronger reason: a `vpay:redirect` message asks the *parent* to
|
|
24
|
+
* navigate, so a `javascript:` URL would execute in the **merchant's**
|
|
25
|
+
* origin, on the merchant's own document, with the merchant's cookies. The
|
|
26
|
+
* origin check above should already make that unreachable; this is the
|
|
27
|
+
* second lock on the same door.
|
|
28
|
+
*/
|
|
29
|
+
function isSafeTopLevelUrl(url) {
|
|
30
|
+
let parsed;
|
|
31
|
+
try {
|
|
32
|
+
parsed = new URL(url);
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
return parsed.protocol === "http:" || parsed.protocol === "https:";
|
|
38
|
+
}
|
|
39
|
+
/** The `origin` half of a URL — what `event.origin` is compared against. */
|
|
40
|
+
export function originOf(url) {
|
|
41
|
+
return new URL(url).origin;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Builds the frame's `src`: `{checkoutBaseUrl}/e/{cs_id}?key={pk}#{secret}`.
|
|
45
|
+
*
|
|
46
|
+
* The id is percent-encoded (it is interpolated into a path, and
|
|
47
|
+
* `client.ts` encodes an intent id for the same reason); the key is
|
|
48
|
+
* percent-encoded; the fragment is **verbatim**, because it is the exact
|
|
49
|
+
* byte string the page hands back to `/v1/browser` and an encoding this
|
|
50
|
+
* package applied would have to be undone by an agreement nobody wrote
|
|
51
|
+
* down.
|
|
52
|
+
*/
|
|
53
|
+
export function embeddedFrameSrc(config) {
|
|
54
|
+
const path = `${config.checkoutBaseUrl}/e/${encodeURIComponent(config.sessionId)}`;
|
|
55
|
+
const query = `key=${encodeURIComponent(config.publishableKey)}`;
|
|
56
|
+
return `${path}?${query}#${config.clientSecret}`;
|
|
57
|
+
}
|
|
58
|
+
/** Reads a `vpay:complete` payload, or `undefined` if it is not one. */
|
|
59
|
+
function parseCompleteEvent(data) {
|
|
60
|
+
const session = data["session"];
|
|
61
|
+
const status = data["status"];
|
|
62
|
+
if (typeof session !== "string" || typeof status !== "string") {
|
|
63
|
+
return undefined;
|
|
64
|
+
}
|
|
65
|
+
return { session, status };
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* The `document` and `window` this handle drives, or a `TypeError`.
|
|
69
|
+
*
|
|
70
|
+
* `@vaam-apps/vpay-stripe-js` runs under Node in its own tests and in SSR frameworks
|
|
71
|
+
* at a merchant, where neither binding exists. An embedded checkout with no
|
|
72
|
+
* DOM cannot be silently degraded into anything useful, so it is refused
|
|
73
|
+
* with the same shape as `loadStripe`'s argument checks.
|
|
74
|
+
*/
|
|
75
|
+
function requireBrowser() {
|
|
76
|
+
const win = typeof window === "undefined" ? undefined : window;
|
|
77
|
+
if (win === undefined || typeof win.document !== "object") {
|
|
78
|
+
throw new TypeError("initEmbeddedCheckout: there is no browser window to mount into");
|
|
79
|
+
}
|
|
80
|
+
return { win, doc: win.document };
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Builds one embedded-checkout handle: an `<iframe>`, a `message`
|
|
84
|
+
* listener pinned to the checkout origin, and the three-verb lifecycle
|
|
85
|
+
* `@stripe/stripe-js`'s `StripeEmbeddedCheckout` defines.
|
|
86
|
+
*
|
|
87
|
+
* The listener is attached here rather than in `mount`, so a page that
|
|
88
|
+
* posts a `vpay:complete` between two `mount` calls is not lost, and it is
|
|
89
|
+
* detached in `destroy` and nowhere else — `unmount` leaves the handle
|
|
90
|
+
* usable, which is Stripe's own semantics.
|
|
91
|
+
*/
|
|
92
|
+
export function createEmbeddedCheckout(config) {
|
|
93
|
+
const { win, doc } = requireBrowser();
|
|
94
|
+
const allowedOrigin = originOf(config.checkoutBaseUrl);
|
|
95
|
+
const frame = doc.createElement("iframe");
|
|
96
|
+
frame.setAttribute("src", embeddedFrameSrc(config));
|
|
97
|
+
// Named, because a frame with no accessible name is announced as
|
|
98
|
+
// "frame" and a payer using a screen reader cannot tell it from the
|
|
99
|
+
// merchant's own chrome.
|
|
100
|
+
frame.setAttribute("title", "Checkout");
|
|
101
|
+
frame.setAttribute("sandbox", FRAME_SANDBOX);
|
|
102
|
+
frame.style.border = "0";
|
|
103
|
+
frame.style.width = "100%";
|
|
104
|
+
frame.style.display = "block";
|
|
105
|
+
// Zero until the page says otherwise. The page owns its own height — it
|
|
106
|
+
// is the only side that knows how tall its content is — and sends
|
|
107
|
+
// `vpay:resize` on every layout change. A page that never sends one
|
|
108
|
+
// renders nothing, deliberately: an iframe silently stuck at a height
|
|
109
|
+
// this package guessed would be a worse failure to diagnose.
|
|
110
|
+
frame.style.height = "0px";
|
|
111
|
+
let mounted = false;
|
|
112
|
+
let destroyed = false;
|
|
113
|
+
const onMessage = (event) => {
|
|
114
|
+
// Rule 2. Everything below this line trusts the sender.
|
|
115
|
+
if (event.origin !== allowedOrigin) {
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
// …and trusts *this* frame, not merely something else served from the
|
|
119
|
+
// same checkout origin: two embedded checkouts on one merchant page
|
|
120
|
+
// would otherwise resize and complete each other.
|
|
121
|
+
if (event.source !== frame.contentWindow) {
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
const data = event.data;
|
|
125
|
+
if (typeof data !== "object" || data === null) {
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
const message = data;
|
|
129
|
+
switch (message["type"]) {
|
|
130
|
+
case MESSAGE_TYPES.resize: {
|
|
131
|
+
const height = message["height"];
|
|
132
|
+
if (typeof height === "number" &&
|
|
133
|
+
Number.isFinite(height) &&
|
|
134
|
+
height >= 0) {
|
|
135
|
+
frame.style.height = `${height}px`;
|
|
136
|
+
}
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
case MESSAGE_TYPES.complete: {
|
|
140
|
+
const payload = parseCompleteEvent(message);
|
|
141
|
+
if (payload !== undefined) {
|
|
142
|
+
config.onComplete?.(payload);
|
|
143
|
+
}
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
case MESSAGE_TYPES.redirect: {
|
|
147
|
+
const url = message["url"];
|
|
148
|
+
if (typeof url !== "string" || !isSafeTopLevelUrl(url)) {
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
// The parent navigates, because the frame may not (see
|
|
152
|
+
// `FRAME_SANDBOX`). `window.top` rather than `window`: a merchant
|
|
153
|
+
// may itself be framed, and sending only its own frame to the
|
|
154
|
+
// rail's page would put Orange's page inside two frames, which its
|
|
155
|
+
// own `frame-ancestors` refuses.
|
|
156
|
+
win.top?.location.assign(url);
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
default:
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
win.addEventListener("message", onMessage);
|
|
164
|
+
return {
|
|
165
|
+
mount(location) {
|
|
166
|
+
if (destroyed) {
|
|
167
|
+
throw new TypeError("EmbeddedCheckout.mount: this checkout has been destroyed; create a new one");
|
|
168
|
+
}
|
|
169
|
+
if (mounted) {
|
|
170
|
+
throw new TypeError("EmbeddedCheckout.mount: this checkout is already mounted; call unmount() first");
|
|
171
|
+
}
|
|
172
|
+
const target = typeof location === "string" ? doc.querySelector(location) : location;
|
|
173
|
+
if (target === null) {
|
|
174
|
+
throw new TypeError("EmbeddedCheckout.mount: no element matches the given selector");
|
|
175
|
+
}
|
|
176
|
+
target.appendChild(frame);
|
|
177
|
+
mounted = true;
|
|
178
|
+
},
|
|
179
|
+
unmount() {
|
|
180
|
+
// Idempotent on purpose, and legal after `destroy`: a merchant's
|
|
181
|
+
// cleanup path (a React effect teardown, say) should not have to
|
|
182
|
+
// know which of the two already ran.
|
|
183
|
+
frame.remove();
|
|
184
|
+
mounted = false;
|
|
185
|
+
},
|
|
186
|
+
destroy() {
|
|
187
|
+
if (destroyed) {
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
destroyed = true;
|
|
191
|
+
frame.remove();
|
|
192
|
+
mounted = false;
|
|
193
|
+
win.removeEventListener("message", onMessage);
|
|
194
|
+
},
|
|
195
|
+
};
|
|
196
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The error half of `@vaam-apps/vpay-stripe-js`.
|
|
3
|
+
*
|
|
4
|
+
* Two rules hold everywhere in this package and are what this module exists
|
|
5
|
+
* to enforce in one place:
|
|
6
|
+
*
|
|
7
|
+
* 1. **Nothing rejects.** Every method on {@link import('./types.js').Stripe}
|
|
8
|
+
* resolves with a `PaymentIntentResult`, so a merchant's `await` never
|
|
9
|
+
* needs a `try`/`catch`. That is Stripe.js's own contract and it is the
|
|
10
|
+
* reason a payer never sees an unhandled rejection in the console.
|
|
11
|
+
* 2. **No error message ever carries a credential.** The request URL holds
|
|
12
|
+
* both `key` and `client_secret` in its query string, so a message built
|
|
13
|
+
* from a `fetch` failure (`err.message`, `String(err)`, `err.cause`) can
|
|
14
|
+
* leak the secret into a console line, a Sentry breadcrumb or a
|
|
15
|
+
* `window.onerror` report. Every message below is a **fixed string** —
|
|
16
|
+
* never interpolated from a thrown value or a URL.
|
|
17
|
+
*
|
|
18
|
+
* The `type`/`code` vocabulary is vpay's server vocabulary, not an invented
|
|
19
|
+
* one: `invalid_request_error` + `invalid_request` is what
|
|
20
|
+
* `vpay_core::Category::InvalidRequest` renders, and `resource_missing` is
|
|
21
|
+
* what `Category::NotFound` renders. Codes the *client* originates (there
|
|
22
|
+
* are three) are the ones the server can never send, so a merchant reading
|
|
23
|
+
* `error.code` can always tell which side produced the failure.
|
|
24
|
+
*/
|
|
25
|
+
/**
|
|
26
|
+
* Stripe.js's `StripeError`, narrowed to the members vpay can populate.
|
|
27
|
+
*
|
|
28
|
+
* `type` is `string` rather than Stripe's closed `StripeErrorType` union so
|
|
29
|
+
* that a `type` a future vpay version introduces still deserialises here
|
|
30
|
+
* instead of being a compile error at the merchant. See `src/compat.test.ts`
|
|
31
|
+
* for what that costs in assignability, pinned at the type level.
|
|
32
|
+
*
|
|
33
|
+
* Every optional member is written `?: T | undefined`, not `?: T`, so a
|
|
34
|
+
* consumer compiling with `exactOptionalPropertyTypes` (as this repo does)
|
|
35
|
+
* can pass through a value that is legitimately `undefined`.
|
|
36
|
+
*/
|
|
37
|
+
export interface StripeError {
|
|
38
|
+
/** e.g. `invalid_request_error`, `api_error`, `api_connection_error`. */
|
|
39
|
+
type: string;
|
|
40
|
+
/** Machine-readable code, e.g. `resource_missing`. */
|
|
41
|
+
code?: string | undefined;
|
|
42
|
+
/** Human-readable detail. Never contains a `client_secret` or a publishable key. */
|
|
43
|
+
message?: string | undefined;
|
|
44
|
+
/** The offending request parameter, when one can be named. */
|
|
45
|
+
param?: string | undefined;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The four codes this package originates rather than reads off the wire.
|
|
49
|
+
*
|
|
50
|
+
* vpay's server has no such codes, so `error.code` alone distinguishes "the
|
|
51
|
+
* browser could not finish" from "the API refused".
|
|
52
|
+
*/
|
|
53
|
+
export declare const CLIENT_ERROR_CODES: {
|
|
54
|
+
/** {@link import('./types.js').Stripe.waitForPaymentIntent} ran out of time. */
|
|
55
|
+
readonly pollingTimeout: "polling_timeout";
|
|
56
|
+
/** A redirect was required but there is no `window` to navigate. */
|
|
57
|
+
readonly redirectUnavailable: "redirect_unavailable";
|
|
58
|
+
/** A response that is not the documented envelope — a proxy's HTML 502, say. */
|
|
59
|
+
readonly unexpectedResponse: "unexpected_response";
|
|
60
|
+
/**
|
|
61
|
+
* `next_action.redirect_to_url.url` was not an absolute `http:`/`https:`
|
|
62
|
+
* URL, so it was refused rather than handed to `location.assign`.
|
|
63
|
+
*/
|
|
64
|
+
readonly invalidRedirect: "invalid_redirect";
|
|
65
|
+
};
|
|
66
|
+
/** Builds a `{ error }` result body. Not exported from the package. */
|
|
67
|
+
export declare function stripeError(type: string, code: string | undefined, message: string, param?: string): StripeError;
|
|
68
|
+
/**
|
|
69
|
+
* A `fetch` that never reached the API: DNS, TLS, connection refused, CORS,
|
|
70
|
+
* an aborted navigation.
|
|
71
|
+
*
|
|
72
|
+
* Deliberately carries no `code` and a fixed message. The thrown value is
|
|
73
|
+
* *not* interpolated: in a browser a `fetch` rejection is
|
|
74
|
+
* `TypeError: Failed to fetch`, but its `cause` and some engines' messages
|
|
75
|
+
* include the request URL — which is exactly the string holding the
|
|
76
|
+
* `client_secret`.
|
|
77
|
+
*/
|
|
78
|
+
export declare function connectionError(): StripeError;
|
|
79
|
+
/** A response that is not vpay's documented error envelope. Carries the status, never the body. */
|
|
80
|
+
export declare function unexpectedResponseError(status: number): StripeError;
|
|
81
|
+
/**
|
|
82
|
+
* Reads `{ "error": { "type", "code", "message", "param" } }` —
|
|
83
|
+
* `vpay_api::error_envelope_with_param` — out of a parsed response body.
|
|
84
|
+
*
|
|
85
|
+
* `type` is the only member the renderer always writes that this parser
|
|
86
|
+
* insists on; `code` is always written too, but a version skew that dropped
|
|
87
|
+
* it should surface as a typed error rather than as
|
|
88
|
+
* `unexpected_response`. Returns `undefined` for anything else, which the
|
|
89
|
+
* caller turns into {@link unexpectedResponseError}.
|
|
90
|
+
*/
|
|
91
|
+
export declare function parseErrorEnvelope(body: unknown): StripeError | undefined;
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The error half of `@vaam-apps/vpay-stripe-js`.
|
|
3
|
+
*
|
|
4
|
+
* Two rules hold everywhere in this package and are what this module exists
|
|
5
|
+
* to enforce in one place:
|
|
6
|
+
*
|
|
7
|
+
* 1. **Nothing rejects.** Every method on {@link import('./types.js').Stripe}
|
|
8
|
+
* resolves with a `PaymentIntentResult`, so a merchant's `await` never
|
|
9
|
+
* needs a `try`/`catch`. That is Stripe.js's own contract and it is the
|
|
10
|
+
* reason a payer never sees an unhandled rejection in the console.
|
|
11
|
+
* 2. **No error message ever carries a credential.** The request URL holds
|
|
12
|
+
* both `key` and `client_secret` in its query string, so a message built
|
|
13
|
+
* from a `fetch` failure (`err.message`, `String(err)`, `err.cause`) can
|
|
14
|
+
* leak the secret into a console line, a Sentry breadcrumb or a
|
|
15
|
+
* `window.onerror` report. Every message below is a **fixed string** —
|
|
16
|
+
* never interpolated from a thrown value or a URL.
|
|
17
|
+
*
|
|
18
|
+
* The `type`/`code` vocabulary is vpay's server vocabulary, not an invented
|
|
19
|
+
* one: `invalid_request_error` + `invalid_request` is what
|
|
20
|
+
* `vpay_core::Category::InvalidRequest` renders, and `resource_missing` is
|
|
21
|
+
* what `Category::NotFound` renders. Codes the *client* originates (there
|
|
22
|
+
* are three) are the ones the server can never send, so a merchant reading
|
|
23
|
+
* `error.code` can always tell which side produced the failure.
|
|
24
|
+
*/
|
|
25
|
+
/**
|
|
26
|
+
* The four codes this package originates rather than reads off the wire.
|
|
27
|
+
*
|
|
28
|
+
* vpay's server has no such codes, so `error.code` alone distinguishes "the
|
|
29
|
+
* browser could not finish" from "the API refused".
|
|
30
|
+
*/
|
|
31
|
+
export const CLIENT_ERROR_CODES = {
|
|
32
|
+
/** {@link import('./types.js').Stripe.waitForPaymentIntent} ran out of time. */
|
|
33
|
+
pollingTimeout: "polling_timeout",
|
|
34
|
+
/** A redirect was required but there is no `window` to navigate. */
|
|
35
|
+
redirectUnavailable: "redirect_unavailable",
|
|
36
|
+
/** A response that is not the documented envelope — a proxy's HTML 502, say. */
|
|
37
|
+
unexpectedResponse: "unexpected_response",
|
|
38
|
+
/**
|
|
39
|
+
* `next_action.redirect_to_url.url` was not an absolute `http:`/`https:`
|
|
40
|
+
* URL, so it was refused rather than handed to `location.assign`.
|
|
41
|
+
*/
|
|
42
|
+
invalidRedirect: "invalid_redirect",
|
|
43
|
+
};
|
|
44
|
+
/** Builds a `{ error }` result body. Not exported from the package. */
|
|
45
|
+
export function stripeError(type, code, message, param) {
|
|
46
|
+
const error = { type, message };
|
|
47
|
+
if (code !== undefined) {
|
|
48
|
+
error.code = code;
|
|
49
|
+
}
|
|
50
|
+
if (param !== undefined) {
|
|
51
|
+
error.param = param;
|
|
52
|
+
}
|
|
53
|
+
return error;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* A `fetch` that never reached the API: DNS, TLS, connection refused, CORS,
|
|
57
|
+
* an aborted navigation.
|
|
58
|
+
*
|
|
59
|
+
* Deliberately carries no `code` and a fixed message. The thrown value is
|
|
60
|
+
* *not* interpolated: in a browser a `fetch` rejection is
|
|
61
|
+
* `TypeError: Failed to fetch`, but its `cause` and some engines' messages
|
|
62
|
+
* include the request URL — which is exactly the string holding the
|
|
63
|
+
* `client_secret`.
|
|
64
|
+
*/
|
|
65
|
+
export function connectionError() {
|
|
66
|
+
return stripeError("api_connection_error", undefined, "Could not reach the vpay API.");
|
|
67
|
+
}
|
|
68
|
+
/** A response that is not vpay's documented error envelope. Carries the status, never the body. */
|
|
69
|
+
export function unexpectedResponseError(status) {
|
|
70
|
+
return stripeError("api_error", CLIENT_ERROR_CODES.unexpectedResponse, `The vpay API returned an unexpected response (HTTP ${status}).`);
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Reads `{ "error": { "type", "code", "message", "param" } }` —
|
|
74
|
+
* `vpay_api::error_envelope_with_param` — out of a parsed response body.
|
|
75
|
+
*
|
|
76
|
+
* `type` is the only member the renderer always writes that this parser
|
|
77
|
+
* insists on; `code` is always written too, but a version skew that dropped
|
|
78
|
+
* it should surface as a typed error rather than as
|
|
79
|
+
* `unexpected_response`. Returns `undefined` for anything else, which the
|
|
80
|
+
* caller turns into {@link unexpectedResponseError}.
|
|
81
|
+
*/
|
|
82
|
+
export function parseErrorEnvelope(body) {
|
|
83
|
+
if (typeof body !== "object" || body === null || !("error" in body)) {
|
|
84
|
+
return undefined;
|
|
85
|
+
}
|
|
86
|
+
const raw = body.error;
|
|
87
|
+
if (typeof raw !== "object" || raw === null) {
|
|
88
|
+
return undefined;
|
|
89
|
+
}
|
|
90
|
+
const fields = raw;
|
|
91
|
+
const type = fields["type"];
|
|
92
|
+
if (typeof type !== "string") {
|
|
93
|
+
return undefined;
|
|
94
|
+
}
|
|
95
|
+
const error = { type };
|
|
96
|
+
for (const key of ["code", "message", "param"]) {
|
|
97
|
+
const value = fields[key];
|
|
98
|
+
if (typeof value === "string") {
|
|
99
|
+
error[key] = value;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return error;
|
|
103
|
+
}
|
package/dist/form.d.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stripe's bracket-nested `application/x-www-form-urlencoded` encoding —
|
|
3
|
+
* the same one `@vaam-apps/vpay-sdk`'s `src/form.ts` implements for `/v1`, because
|
|
4
|
+
* `/v1/browser` is served by the same axum form extractor.
|
|
5
|
+
*
|
|
6
|
+
* | Shape | Wire form |
|
|
7
|
+
* |---|---|
|
|
8
|
+
* | scalar | `key=pk_test_x` |
|
|
9
|
+
* | nested object | `payment_method_data[mtn_momo][msisdn]=237690000000` |
|
|
10
|
+
* | array | `a[0]=x&a[1]=y` (indexed) |
|
|
11
|
+
* | boolean | `true` / `false` |
|
|
12
|
+
* | `undefined` / `null` | omitted entirely |
|
|
13
|
+
*
|
|
14
|
+
* A key is carried through the flattener as an **array of path segments**
|
|
15
|
+
* and only assembled into wire syntax at the end, so the brackets a nested
|
|
16
|
+
* key is written with are structural while every segment — including one a
|
|
17
|
+
* merchant supplied containing `[` or `]` — is percent-encoded. Assembling
|
|
18
|
+
* first and re-parsing with a bracket regex is what silently corrupted
|
|
19
|
+
* `{ "a[b]": "x" }` into `a[b]=x`-meaning-something-else in the Node SDK
|
|
20
|
+
* before that bug was fixed; this is the fixed version.
|
|
21
|
+
*
|
|
22
|
+
* The browser package differs from the Node one in a single respect: it is
|
|
23
|
+
* fed `payment_method_data` typed `Record<string, unknown>`, i.e. whatever a
|
|
24
|
+
* merchant's page passed. Anything the wire format cannot carry exactly
|
|
25
|
+
* ({@link FormEncodingError}) is refused here so that
|
|
26
|
+
* {@link import('./client.js').VpayStripe.confirmPayment} can answer with a
|
|
27
|
+
* typed `invalid_request_error` naming the parameter, rather than sending an
|
|
28
|
+
* approximation of what the caller wrote to a payment API.
|
|
29
|
+
*/
|
|
30
|
+
/** A value the form encoder can flatten. `null` is treated like `undefined`: omitted. */
|
|
31
|
+
export type FormValue = string | number | boolean | undefined | null | readonly FormValue[] | {
|
|
32
|
+
[key: string]: FormValue;
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* A value that cannot be encoded exactly. Thrown only by
|
|
36
|
+
* {@link encodeForm}, and only ever caught — never surfaced to a merchant as
|
|
37
|
+
* a rejection.
|
|
38
|
+
*/
|
|
39
|
+
export declare class FormEncodingError extends Error {
|
|
40
|
+
/** The offending path in bracket syntax, e.g. `payment_method_data[mtn_momo]`. */
|
|
41
|
+
readonly path: string;
|
|
42
|
+
constructor(path: string, detail: string);
|
|
43
|
+
}
|
|
44
|
+
/** Flattens a params object into ordered `[path segments, value]` pairs. */
|
|
45
|
+
export declare function flattenForm(params: Record<string, FormValue>): Array<[readonly string[], string]>;
|
|
46
|
+
/**
|
|
47
|
+
* Encodes `params` as an `application/x-www-form-urlencoded` body — or,
|
|
48
|
+
* identically, as a query string.
|
|
49
|
+
*
|
|
50
|
+
* `encodeURIComponent` and not `URLSearchParams`: the latter encodes a space
|
|
51
|
+
* as `+` and leaves `!'()*~` alone, so two encoders in one codebase would
|
|
52
|
+
* put different bytes on the wire for the same MSISDN-bearing body. This is
|
|
53
|
+
* byte-for-byte what `@vaam-apps/vpay-sdk` sends.
|
|
54
|
+
*/
|
|
55
|
+
export declare function encodeForm(params: Record<string, FormValue>): string;
|
package/dist/form.js
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stripe's bracket-nested `application/x-www-form-urlencoded` encoding —
|
|
3
|
+
* the same one `@vaam-apps/vpay-sdk`'s `src/form.ts` implements for `/v1`, because
|
|
4
|
+
* `/v1/browser` is served by the same axum form extractor.
|
|
5
|
+
*
|
|
6
|
+
* | Shape | Wire form |
|
|
7
|
+
* |---|---|
|
|
8
|
+
* | scalar | `key=pk_test_x` |
|
|
9
|
+
* | nested object | `payment_method_data[mtn_momo][msisdn]=237690000000` |
|
|
10
|
+
* | array | `a[0]=x&a[1]=y` (indexed) |
|
|
11
|
+
* | boolean | `true` / `false` |
|
|
12
|
+
* | `undefined` / `null` | omitted entirely |
|
|
13
|
+
*
|
|
14
|
+
* A key is carried through the flattener as an **array of path segments**
|
|
15
|
+
* and only assembled into wire syntax at the end, so the brackets a nested
|
|
16
|
+
* key is written with are structural while every segment — including one a
|
|
17
|
+
* merchant supplied containing `[` or `]` — is percent-encoded. Assembling
|
|
18
|
+
* first and re-parsing with a bracket regex is what silently corrupted
|
|
19
|
+
* `{ "a[b]": "x" }` into `a[b]=x`-meaning-something-else in the Node SDK
|
|
20
|
+
* before that bug was fixed; this is the fixed version.
|
|
21
|
+
*
|
|
22
|
+
* The browser package differs from the Node one in a single respect: it is
|
|
23
|
+
* fed `payment_method_data` typed `Record<string, unknown>`, i.e. whatever a
|
|
24
|
+
* merchant's page passed. Anything the wire format cannot carry exactly
|
|
25
|
+
* ({@link FormEncodingError}) is refused here so that
|
|
26
|
+
* {@link import('./client.js').VpayStripe.confirmPayment} can answer with a
|
|
27
|
+
* typed `invalid_request_error` naming the parameter, rather than sending an
|
|
28
|
+
* approximation of what the caller wrote to a payment API.
|
|
29
|
+
*/
|
|
30
|
+
/**
|
|
31
|
+
* A value that cannot be encoded exactly. Thrown only by
|
|
32
|
+
* {@link encodeForm}, and only ever caught — never surfaced to a merchant as
|
|
33
|
+
* a rejection.
|
|
34
|
+
*/
|
|
35
|
+
export class FormEncodingError extends Error {
|
|
36
|
+
constructor(path, detail) {
|
|
37
|
+
super(`${path} ${detail}`);
|
|
38
|
+
this.name = "FormEncodingError";
|
|
39
|
+
this.path = path;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/** Renders a path back into bracket syntax, for error messages only. */
|
|
43
|
+
function describePath(path) {
|
|
44
|
+
const [head, ...rest] = path;
|
|
45
|
+
return `${head ?? ""}${rest.map((segment) => `[${segment}]`).join("")}`;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* True only for `{}`-shaped values: an object literal, or one created with a
|
|
49
|
+
* null prototype. A `Date`, `Map`, `URL` or class instance is not one — and
|
|
50
|
+
* must not be, because `Object.entries` on it yields no own enumerable keys,
|
|
51
|
+
* so it would vanish from the request body entirely rather than fail.
|
|
52
|
+
*/
|
|
53
|
+
function isPlainObject(value) {
|
|
54
|
+
const prototype = Object.getPrototypeOf(value);
|
|
55
|
+
return prototype === Object.prototype || prototype === null;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Renders a number, refusing anything that is not an exact decimal integer.
|
|
59
|
+
*
|
|
60
|
+
* vpay's wire format is decimal integers with no separators
|
|
61
|
+
* (`docs/flows/money.md` bans floating point in the money path outright), so
|
|
62
|
+
* a float, a `NaN`, or a value past `Number.MAX_SAFE_INTEGER` is a bug in the
|
|
63
|
+
* caller rather than a value to transmit approximately.
|
|
64
|
+
*/
|
|
65
|
+
function encodeNumber(value, path) {
|
|
66
|
+
if (!Number.isSafeInteger(value)) {
|
|
67
|
+
throw new FormEncodingError(describePath(path), `must be a safe integer, got ${value}`);
|
|
68
|
+
}
|
|
69
|
+
return String(value);
|
|
70
|
+
}
|
|
71
|
+
function flattenValue(path, value, out) {
|
|
72
|
+
if (value === undefined || value === null) {
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
if (Array.isArray(value)) {
|
|
76
|
+
value.forEach((item, index) => flattenValue([...path, String(index)], item, out));
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
if (typeof value === "object") {
|
|
80
|
+
if (!isPlainObject(value)) {
|
|
81
|
+
throw new FormEncodingError(describePath(path), "must be a plain object, array or scalar");
|
|
82
|
+
}
|
|
83
|
+
for (const [childKey, childValue] of Object.entries(value)) {
|
|
84
|
+
flattenValue([...path, childKey], childValue, out);
|
|
85
|
+
}
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
if (typeof value === "boolean") {
|
|
89
|
+
out.push([path, value ? "true" : "false"]);
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
if (typeof value === "number") {
|
|
93
|
+
out.push([path, encodeNumber(value, path)]);
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
if (typeof value !== "string") {
|
|
97
|
+
// Reachable only from an `unknown` a merchant passed through
|
|
98
|
+
// `payment_method_data` — a `symbol`, a `bigint`, a function.
|
|
99
|
+
throw new FormEncodingError(describePath(path), `must be a string, number, boolean, array or plain object, got ${typeof value}`);
|
|
100
|
+
}
|
|
101
|
+
out.push([path, value]);
|
|
102
|
+
}
|
|
103
|
+
/** Flattens a params object into ordered `[path segments, value]` pairs. */
|
|
104
|
+
export function flattenForm(params) {
|
|
105
|
+
const out = [];
|
|
106
|
+
for (const [key, value] of Object.entries(params)) {
|
|
107
|
+
flattenValue([key], value, out);
|
|
108
|
+
}
|
|
109
|
+
return out;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Assembles one flattened path into wire syntax: every segment
|
|
113
|
+
* percent-encoded, the brackets between them literal.
|
|
114
|
+
*/
|
|
115
|
+
function encodePath(path) {
|
|
116
|
+
const [head, ...rest] = path;
|
|
117
|
+
const encodedRest = rest
|
|
118
|
+
.map((segment) => `[${encodeURIComponent(segment)}]`)
|
|
119
|
+
.join("");
|
|
120
|
+
return `${encodeURIComponent(head ?? "")}${encodedRest}`;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Encodes `params` as an `application/x-www-form-urlencoded` body — or,
|
|
124
|
+
* identically, as a query string.
|
|
125
|
+
*
|
|
126
|
+
* `encodeURIComponent` and not `URLSearchParams`: the latter encodes a space
|
|
127
|
+
* as `+` and leaves `!'()*~` alone, so two encoders in one codebase would
|
|
128
|
+
* put different bytes on the wire for the same MSISDN-bearing body. This is
|
|
129
|
+
* byte-for-byte what `@vaam-apps/vpay-sdk` sends.
|
|
130
|
+
*/
|
|
131
|
+
export function encodeForm(params) {
|
|
132
|
+
return flattenForm(params)
|
|
133
|
+
.map(([path, value]) => `${encodePath(path)}=${encodeURIComponent(value)}`)
|
|
134
|
+
.join("&");
|
|
135
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@vaam-apps/vpay-stripe-js` — a Stripe.js-shaped browser client for vpay's payer
|
|
3
|
+
* surface.
|
|
4
|
+
*
|
|
5
|
+
* Drop-in for the *payment-intent* half of Stripe.js, plus vpay's own
|
|
6
|
+
* Checkout Session surface (`retrieveCheckoutSession`,
|
|
7
|
+
* `initEmbeddedCheckout`), and nothing else. See README.md for the
|
|
8
|
+
* compatible surface, the list of Stripe features that are not compatible
|
|
9
|
+
* and never will be, and this package's own Status section (as of this
|
|
10
|
+
* commit the server routes it speaks to are being built in the same step
|
|
11
|
+
* and nothing here has run against them).
|
|
12
|
+
*/
|
|
13
|
+
export { loadStripe } from "./client.js";
|
|
14
|
+
export { CheckoutPopupBlockedError, notifyCheckoutOpener } from "./popup.js";
|
|
15
|
+
export type { StripeError } from "./errors.js";
|
|
16
|
+
export type { CheckoutPopup, NotifyCheckoutOpenerOptions, OpenCheckoutPopupOptions, } from "./popup.js";
|
|
17
|
+
export type { Stripe, CheckoutSession, CheckoutSessionResult, CheckoutSessionStatus, CheckoutSessionUiMode, CheckoutPaymentStatus, EmbeddedCheckout, EmbeddedCheckoutCompleteEvent, InitEmbeddedCheckoutOptions, PaymentIntent, PaymentIntentResult, PaymentIntentStatus, NextAction, LastPaymentError, FailureCode, VpayStripeOptions, ConfirmPaymentOptions, WaitForPaymentIntentOptions, MobileMoneyData, } from "./types.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@vaam-apps/vpay-stripe-js` — a Stripe.js-shaped browser client for vpay's payer
|
|
3
|
+
* surface.
|
|
4
|
+
*
|
|
5
|
+
* Drop-in for the *payment-intent* half of Stripe.js, plus vpay's own
|
|
6
|
+
* Checkout Session surface (`retrieveCheckoutSession`,
|
|
7
|
+
* `initEmbeddedCheckout`), and nothing else. See README.md for the
|
|
8
|
+
* compatible surface, the list of Stripe features that are not compatible
|
|
9
|
+
* and never will be, and this package's own Status section (as of this
|
|
10
|
+
* commit the server routes it speaks to are being built in the same step
|
|
11
|
+
* and nothing here has run against them).
|
|
12
|
+
*/
|
|
13
|
+
export { loadStripe } from "./client.js";
|
|
14
|
+
export { CheckoutPopupBlockedError, notifyCheckoutOpener } from "./popup.js";
|