@binopartner/pay-sdk 0.0.0-stage → 0.1.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.
package/README.md CHANGED
@@ -1,3 +1,198 @@
1
- # Temporary Holding Version
1
+ # @binopartner/pay-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Embed the Binodex deposit and withdrawal widget in a broker site. The SDK gives you a root component and composable parts for React, and a `mount()` function for any other stack. The payment form itself runs inside an iframe on the Binodex origin, so the SDK never handles payment providers, requisites or user data.
4
+
5
+ - `Root` holds one widget session and renders nothing until every required part is present.
6
+ - Parts (`Frame`, `Trigger`, `Close`, `Loader`, `Status`) are placed anywhere inside `Root`, inside your own layout.
7
+ - Messages between your page and the widget are checked by window, origin and a per-instance channel.
8
+ - Works with every `/embed/pay` build: frames that predate the channel fall back to the legacy handshake.
9
+
10
+ ## Install
11
+
12
+ The package is on the public npm registry, no token is needed:
13
+
14
+ ```sh
15
+ npm install @binopartner/pay-sdk
16
+ ```
17
+
18
+ React 18 or newer is an optional peer dependency; `mount()` needs no framework.
19
+
20
+ Inside this repository the package is an npm workspace (`packages/pay-sdk`) and is linked already:
21
+
22
+ ```sh
23
+ npm install
24
+ npm run build -w @binopartner/pay-sdk
25
+ ```
26
+
27
+ Releases are published from CI, see [PUBLISHING.md](PUBLISHING.md).
28
+
29
+ ## Your backend: the session endpoint
30
+
31
+ Your server creates a one-time widget session with the Broker API and returns the response unchanged. The SDK needs nothing else: no client secret and no Broker API token in the browser.
32
+
33
+ ```ts
34
+ // POST /api/widget-session body: { mode: "deposit" | "withdraw" }
35
+ const response = await fetch("https://api.binodex.app/v1/broker/widget-sessions", {
36
+ method: "POST",
37
+ headers: {
38
+ Authorization: `Bearer ${userAccessToken}`,
39
+ "Content-Type": "application/json",
40
+ },
41
+ body: JSON.stringify({ origin: "https://broker.example", mode, user_ip: clientIp }),
42
+ });
43
+ return Response.json(await response.json(), { status: response.status });
44
+ // { session: "wss_…", expires_in: 60, widget_url?: "https://…/embed/pay?…", widget_origin?: "https://…" }
45
+ ```
46
+
47
+ The SDK calls this endpoint with `POST { mode }` (same-origin cookies included) whenever it needs a session: once to open the widget and again when the widget asks for re-authentication. On a non-2xx answer it shows `error.message` from the JSON body.
48
+
49
+ ## React
50
+
51
+ ```tsx
52
+ "use client";
53
+ import * as PayWidget from "@binopartner/pay-sdk/react";
54
+
55
+ export function DepositPanel({ onDone }: { onDone: () => void }) {
56
+ return (
57
+ <PayWidget.Root
58
+ mode="deposit"
59
+ sessionEndpoint="/api/widget-session"
60
+ clientId={clientId}
61
+ platformUrl="https://binodex.app"
62
+ onOpenChange={(open) => !open && onDone()}
63
+ onCredited={({ amount, asset }) => refreshBalance()}
64
+ >
65
+ <PayWidget.Loader>Opening the payment form…</PayWidget.Loader>
66
+ <PayWidget.Status />
67
+ <PayWidget.Frame title="Deposit" />
68
+ </PayWidget.Root>
69
+ );
70
+ }
71
+ ```
72
+
73
+ `clientId` and `platformUrl` are only used when the session response carries no `widget_url`.
74
+
75
+ ### Open on demand
76
+
77
+ ```tsx
78
+ <PayWidget.Root mode="withdraw" sessionEndpoint="/api/widget-session" defaultOpen={false}>
79
+ <PayWidget.Trigger>Withdraw</PayWidget.Trigger>
80
+ <div className="sheet">
81
+ <PayWidget.Close>Done</PayWidget.Close>
82
+ <PayWidget.Frame />
83
+ </div>
84
+ </PayWidget.Root>
85
+ ```
86
+
87
+ A session is created only when the widget opens and is dropped when it closes. Use `open` and `onOpenChange` to control it yourself, and `usePayWidget()` inside `Root` to read `{ open, setOpen, status, error }` for a custom shell.
88
+
89
+ ### `Root` props
90
+
91
+ | Prop | Type | Default | Notes |
92
+ | --- | --- | --- | --- |
93
+ | `mode` | `"deposit" \| "withdraw"` | required | Changing it restarts the widget with a new session. |
94
+ | `sessionEndpoint` | `string` | | Your endpoint described above. Pass this or `createSession`. |
95
+ | `createSession` | `({ mode, signal }) => Promise<WidgetSession>` | | Full control over how the session is fetched. |
96
+ | `clientId`, `platformUrl` | `string` | | Fallback URL `${platformUrl}/embed/pay?mode=…&client_id=…`. |
97
+ | `lang` | `string` | | For example `ru` or `ru-RU`. |
98
+ | `theme` | `"light" \| "dark"` | | Overrides the theme set in the partner cabinet. |
99
+ | `open`, `defaultOpen`, `onOpenChange` | | `defaultOpen = true` | Controlled or uncontrolled open state. |
100
+ | `onCredited` | `({ amount, asset }) => void` | | A deposit was credited. UI signal only, see Security. |
101
+ | `onStatusChange`, `onError` | | | See Status. |
102
+ | `requireChannel` | `boolean` | `false` | Refuse frames that do not prove the channel (no legacy fallback). |
103
+ | `required` | `PayPart[]` | `[]` | Extra parts that must be present, on top of `frame`. |
104
+
105
+ ## Parts
106
+
107
+ | Part | Required | Renders | Notes |
108
+ | --- | --- | --- | --- |
109
+ | `Frame` | yes | while open | Slot for the iframe. Props: `title`, `initialHeight` (720), `minHeight` (520), `maxHeight` (900; pass `Infinity` to lift it). |
110
+ | `Trigger` | no | always | `<button>` that opens the widget; sets `aria-expanded` and `aria-controls`. |
111
+ | `Close` | no | while open | `<button>` that closes the widget. Labelled "Close" when it has no children. |
112
+ | `Loader` | no | while the session or the frame document is loading | `role="status"`. |
113
+ | `Status` | no | on error | `role="alert"`. Children may be a function `(error) => ReactNode`. |
114
+
115
+ Required parts must be rendered unconditionally inside `Root`. If one is missing, `Root` renders nothing at all: no markup, no session request, no iframe. During development it also logs a warning; production builds stay silent. A `Root` that lost a required part stays empty until it is mounted again. On the server `Root` renders nothing; it appears after hydration.
116
+
117
+ Every part carries `data-binodex-pay="<part>"`; `Frame` and `Loader` also carry `data-status`, `Frame` and `Trigger` carry `data-state="open|closed"`, `Status` carries `data-error="<code>"`.
118
+
119
+ ## Without a framework
120
+
121
+ `mount()` needs no React, but the package is an ES module meant for a bundler (Vite, webpack, esbuild): a browser cannot resolve the bare `@binopartner/pay-sdk` import by itself. Put the script below into your bundled code, or map the specifier with an import map.
122
+
123
+ ```html
124
+ <div id="pay">
125
+ <button data-binodex-pay="trigger">Deposit</button>
126
+ <button data-binodex-pay="close">Close</button>
127
+ <div data-binodex-pay="loader">Opening…</div>
128
+ <div data-binodex-pay="status"></div>
129
+ <div data-binodex-pay="frame"></div>
130
+ </div>
131
+ <script type="module">
132
+ import { mount } from "@binopartner/pay-sdk";
133
+
134
+ const widget = mount(document.getElementById("pay"), {
135
+ mode: "deposit",
136
+ sessionEndpoint: "/api/widget-session",
137
+ open: false,
138
+ onCredited: ({ amount, asset }) => console.log("credited", amount, asset),
139
+ });
140
+ // widget.open(), widget.close(), widget.getState(), widget.destroy()
141
+ </script>
142
+ ```
143
+
144
+ `mount()` takes the same options as `Root` plus the `Frame` height options. When a required part is missing it returns `null`, sets `hidden` on the root element and warns in development. An empty `status` element is filled with the error message.
145
+
146
+ ## Status and errors
147
+
148
+ `idle` → `session` (creating the session) → `loading` (frame document loading) → `handshake` (frame loaded, session handed over) → `ready` (form shown). `error` comes with `{ code, message, reason? }`:
149
+
150
+ | `code` | When |
151
+ | --- | --- |
152
+ | `session_failed` | The session endpoint failed or returned no valid `session`. `message` is the server's `error.message` when present. |
153
+ | `invalid_widget_url` | No usable widget URL: not https (plain http is allowed for `localhost`), embedded credentials, or `widget_url` disagrees with `widget_origin`. |
154
+ | `widget_error` | The widget reported an error; `reason` is its code, for example `widget_auth_error`. |
155
+
156
+ ## Protocol
157
+
158
+ The widget page is `/embed/pay` on the Binodex origin. The SDK adds a random 128-bit channel to the iframe URL fragment (`#channel=…`). Fragments are never sent to servers or in `Referer`.
159
+
160
+ | Direction | Message | Notes |
161
+ | --- | --- | --- |
162
+ | widget → page | `binodex-embed:ready` | The widget waits for a session. |
163
+ | page → widget | `binodex-embed:init { session }` | Sent only to the widget origin. |
164
+ | widget → page | `binodex-embed:resize { height }` | Content height; the SDK clamps it. |
165
+ | widget → page | `binodex-embed:credited { amount, asset }` | |
166
+ | widget → page | `binodex-embed:close` | The user closed the form inside the widget. |
167
+ | widget → page | `binodex-embed:error { message }` | `message` is a code. |
168
+ | widget → page | `binodex-embed:reauth-required` | The SDK fetches a fresh session and sends `init` again. |
169
+
170
+ A widget that understands channels adds `channel` to every message, and expects `channel` in `init`. The SDK picks the dialect from the first `ready`: with the channel it answers with a channel-bound `init` and from then on drops every message without the channel; without it (an older widget) it speaks the legacy handshake, unless `requireChannel` is set. Integrations that never set the fragment see exactly the legacy messages.
171
+
172
+ ## Security
173
+
174
+ What stays in the iframe: payment providers, card and bank requisites, wallet addresses and user data are rendered inside the iframe on the Binodex origin. The browser's same-origin policy keeps other origins from reading the iframe's content, and the SDK has no API that asks for that data. The only data the widget posts to your page is the list above.
175
+
176
+ What is checked:
177
+
178
+ - Your page → widget: `init` is posted with an exact target origin, never `*`, so a widget frame navigated elsewhere never receives the session. The widget accepts `init` only from its parent window, only from an origin registered for your client, only with the exact expected fields and, with a channel, only with its own channel.
179
+ - Widget → your page: the SDK accepts a message only when it comes from its own iframe window, from the widget origin, has a known type with valid fields and, once the widget proved the channel, carries that channel. Another iframe, a popup or a second widget instance on the page cannot drive yours.
180
+ - Secrets: the SDK only ever hands the widget the one-time `wss_` session (single use, valid for 60 seconds, bound to the user, client and mode). The widget exchanges it for a short-lived token inside the iframe.
181
+ - `widget_url` must be https (plain http only on loopback hosts), must not carry credentials and must match `widget_origin`. Take it from the Broker API response only, never from user input.
182
+ - The iframe is created with `referrerpolicy="origin"`: the widget learns your origin to verify it, never your page path.
183
+
184
+ Out of scope, and how to handle it:
185
+
186
+ - Events are UI hints. A user can fake `onCredited` in their own browser. Never credit, ship or unlock anything because of a widget event; confirm with the Broker API or webhooks.
187
+ - Script running on your page (your code, a compromised dependency, an XSS) acts as your page, with everything your page can do, widget sessions included. The SDK cannot protect you from it: keep a strict CSP, add `frame-src` for the Binodex origin, and guard your session route like any authenticated endpoint.
188
+ - Clickjacking by the embedding page itself is not something an iframe can prevent.
189
+
190
+ ## Development
191
+
192
+ ```sh
193
+ npm run build -w @binopartner/pay-sdk # ESM + .d.ts into dist/
194
+ npm run typecheck -w @binopartner/pay-sdk
195
+ npm test -w @binopartner/pay-sdk # vitest + jsdom
196
+ ```
197
+
198
+ Releases go out through the `Publish pay-sdk` GitHub Actions workflow, see [PUBLISHING.md](PUBLISHING.md).
@@ -0,0 +1 @@
1
+ export declare const createChannel: () => string;
@@ -0,0 +1,13 @@
1
+ const CHANNEL_BYTES = 16;
2
+ export const createChannel = () => {
3
+ const bytes = new Uint8Array(CHANNEL_BYTES);
4
+ globalThis.crypto.getRandomValues(bytes);
5
+ let binary = "";
6
+ bytes.forEach((byte) => {
7
+ binary += String.fromCharCode(byte);
8
+ });
9
+ return btoa(binary)
10
+ .replace(/\+/g, "-")
11
+ .replace(/\//g, "_")
12
+ .replace(/=+$/, "");
13
+ };
package/dist/dev.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import type { PayPart } from "./types.js";
2
+ export declare const warnMissingParts: (owner: string, missing: readonly PayPart[]) => void;
package/dist/dev.js ADDED
@@ -0,0 +1,16 @@
1
+ const isProduction = () => {
2
+ try {
3
+ return process.env.NODE_ENV === "production";
4
+ }
5
+ catch {
6
+ return false;
7
+ }
8
+ };
9
+ export const warnMissingParts = (owner, missing) => {
10
+ if (isProduction())
11
+ return;
12
+ const names = missing.map((part) => `"${part}"`).join(", ");
13
+ const noun = missing.length === 1 ? "part" : "parts";
14
+ console.warn(`[@binopartner/pay-sdk] ${owner} rendered nothing: missing required ${noun} ${names}. ` +
15
+ "Render every required part unconditionally inside the root.");
16
+ };
@@ -0,0 +1,7 @@
1
+ import type { PayError, PayErrorCode } from "./types.js";
2
+ export declare class PaySdkError extends Error {
3
+ readonly code: PayErrorCode;
4
+ constructor(code: PayErrorCode, message: string);
5
+ }
6
+ export declare const SESSION_FAILED_MESSAGE = "Could not create widget session";
7
+ export declare const toPayError: (error: unknown) => PayError;
package/dist/errors.js ADDED
@@ -0,0 +1,11 @@
1
+ export class PaySdkError extends Error {
2
+ constructor(code, message) {
3
+ super(message);
4
+ this.name = "PaySdkError";
5
+ this.code = code;
6
+ }
7
+ }
8
+ export const SESSION_FAILED_MESSAGE = "Could not create widget session";
9
+ export const toPayError = (error) => error instanceof PaySdkError
10
+ ? { code: error.code, message: error.message }
11
+ : { code: "session_failed", message: SESSION_FAILED_MESSAGE };
@@ -0,0 +1,14 @@
1
+ import type { CreditedEvent, FrameOptions, PayError, PayStatus, PayWidgetOptions } from "./types.js";
2
+ export interface FrameEvents {
3
+ status: (status: PayStatus, error: PayError | null) => void;
4
+ height: (height: number) => void;
5
+ credited: (event: CreditedEvent) => void;
6
+ close: () => void;
7
+ }
8
+ export interface HeightBounds {
9
+ initial: number;
10
+ min: number;
11
+ max: number;
12
+ }
13
+ export declare const heightBounds: (options: FrameOptions) => HeightBounds;
14
+ export declare const runPayFrame: (container: HTMLElement, options: PayWidgetOptions & FrameOptions, events: FrameEvents) => (() => void);
package/dist/frame.js ADDED
@@ -0,0 +1,181 @@
1
+ import { createChannel } from "./channel.js";
2
+ import { PaySdkError, toPayError } from "./errors.js";
3
+ import { initMessage, readWidgetMessage, } from "./protocol.js";
4
+ import { holdSession, requestSession } from "./session.js";
5
+ import { resolveWidgetLocation } from "./widget-url.js";
6
+ const DEFAULT_HEIGHTS = { initial: 720, min: 520, max: 900 };
7
+ const FRAME_PERMISSIONS = "payment *; clipboard-write *";
8
+ const finiteSize = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0
9
+ ? value
10
+ : null;
11
+ const fit = (value, min, max) => Math.min(max, Math.max(min, Math.ceil(value)));
12
+ export const heightBounds = (options) => {
13
+ const min = finiteSize(options.minHeight) ?? DEFAULT_HEIGHTS.min;
14
+ const max = Math.max(min, options.maxHeight === Infinity
15
+ ? Infinity
16
+ : (finiteSize(options.maxHeight) ?? DEFAULT_HEIGHTS.max));
17
+ const initial = fit(finiteSize(options.initialHeight) ?? DEFAULT_HEIGHTS.initial, min, max);
18
+ return { initial, min, max };
19
+ };
20
+ const createFrame = (src, title, height) => {
21
+ const frame = document.createElement("iframe");
22
+ frame.setAttribute("title", title);
23
+ frame.setAttribute("allow", FRAME_PERMISSIONS);
24
+ frame.setAttribute("referrerpolicy", "origin");
25
+ frame.style.display = "block";
26
+ frame.style.width = "100%";
27
+ frame.style.height = `${height}px`;
28
+ frame.style.border = "0";
29
+ frame.style.background = "transparent";
30
+ frame.setAttribute("src", src);
31
+ return frame;
32
+ };
33
+ export const runPayFrame = (container, options, events) => {
34
+ const abort = new AbortController();
35
+ const channel = createChannel();
36
+ const bounds = heightBounds(options);
37
+ let stopped = false;
38
+ let frame = null;
39
+ let widgetOrigin = "";
40
+ let protocol = null;
41
+ let held = null;
42
+ let initInFlight = false;
43
+ let shown = false;
44
+ let status = "idle";
45
+ const setStatus = (next, error = null) => {
46
+ if (stopped || (next === status && next !== "error"))
47
+ return;
48
+ status = next;
49
+ events.status(next, error);
50
+ };
51
+ const fail = (error) => {
52
+ if (stopped || abort.signal.aborted)
53
+ return;
54
+ setStatus("error", toPayError(error));
55
+ };
56
+ const sendInit = async (reuse) => {
57
+ if (initInFlight)
58
+ return;
59
+ initInFlight = true;
60
+ try {
61
+ const candidate = held;
62
+ held = null;
63
+ const session = reuse && candidate && candidate.reusableUntil > Date.now()
64
+ ? candidate.session
65
+ : (await requestSession(options, abort.signal)).session;
66
+ const target = frame?.contentWindow;
67
+ if (stopped || !target)
68
+ return;
69
+ target.postMessage(initMessage(session, protocol === 2 ? channel : null), widgetOrigin);
70
+ }
71
+ catch (error) {
72
+ fail(error);
73
+ }
74
+ finally {
75
+ initInFlight = false;
76
+ }
77
+ };
78
+ const handle = (event) => {
79
+ switch (event.type) {
80
+ case "ready":
81
+ shown = false;
82
+ setStatus("handshake");
83
+ void sendInit(true);
84
+ return;
85
+ case "reauth-required":
86
+ shown = false;
87
+ setStatus("handshake");
88
+ void sendInit(false);
89
+ return;
90
+ case "resize": {
91
+ const height = fit(event.height, bounds.min, bounds.max);
92
+ if (frame)
93
+ frame.style.height = `${height}px`;
94
+ events.height(height);
95
+ if (!shown) {
96
+ shown = true;
97
+ setStatus("ready");
98
+ }
99
+ return;
100
+ }
101
+ case "credited":
102
+ events.credited({ amount: event.amount, asset: event.asset });
103
+ return;
104
+ case "close":
105
+ events.close();
106
+ return;
107
+ case "error":
108
+ setStatus("error", {
109
+ code: "widget_error",
110
+ message: "Payment form is unavailable",
111
+ reason: event.reason,
112
+ });
113
+ }
114
+ };
115
+ const onMessage = (event) => {
116
+ if (stopped || !frame)
117
+ return;
118
+ if (event.source !== frame.contentWindow || event.origin !== widgetOrigin) {
119
+ return;
120
+ }
121
+ const envelope = readWidgetMessage(event.data);
122
+ if (!envelope)
123
+ return;
124
+ if (envelope.channel !== null) {
125
+ if (envelope.channel !== channel)
126
+ return;
127
+ protocol = 2;
128
+ }
129
+ else if (protocol === 2 || options.requireChannel) {
130
+ return;
131
+ }
132
+ else {
133
+ protocol = 1;
134
+ }
135
+ handle(envelope.event);
136
+ };
137
+ const onLoad = () => {
138
+ if (status === "loading")
139
+ setStatus("handshake");
140
+ };
141
+ events.height(bounds.initial);
142
+ setStatus("session");
143
+ requestSession(options, abort.signal)
144
+ .then((session) => {
145
+ if (stopped)
146
+ return;
147
+ const location = resolveWidgetLocation({
148
+ session,
149
+ channel,
150
+ mode: options.mode,
151
+ clientId: options.clientId,
152
+ platformUrl: options.platformUrl,
153
+ lang: options.lang,
154
+ theme: options.theme,
155
+ });
156
+ if (!location) {
157
+ throw new PaySdkError("invalid_widget_url", "The widget session has no usable widget URL");
158
+ }
159
+ held = holdSession(session, Date.now());
160
+ widgetOrigin = location.origin;
161
+ frame = createFrame(location.src, options.title || (options.mode === "withdraw" ? "Withdraw" : "Deposit"), bounds.initial);
162
+ frame.addEventListener("load", onLoad);
163
+ window.addEventListener("message", onMessage);
164
+ setStatus("loading");
165
+ container.appendChild(frame);
166
+ })
167
+ .catch(fail);
168
+ return () => {
169
+ if (stopped)
170
+ return;
171
+ stopped = true;
172
+ abort.abort();
173
+ window.removeEventListener("message", onMessage);
174
+ if (frame) {
175
+ frame.removeEventListener("load", onLoad);
176
+ frame.remove();
177
+ frame = null;
178
+ }
179
+ held = null;
180
+ };
181
+ };
@@ -0,0 +1,3 @@
1
+ export { mount } from "./mount.js";
2
+ export type { MountOptions, PayWidget, PayWidgetState } from "./mount.js";
3
+ export type { CreateSession, CreateSessionContext, CreditedEvent, FrameOptions, PayError, PayErrorCode, PayMode, PayPart, PayStatus, PayTheme, PayWidgetOptions, WidgetSession, } from "./types.js";
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { mount } from "./mount.js";
@@ -0,0 +1,21 @@
1
+ import type { CreditedEvent, FrameOptions, PayError, PayPart, PayStatus, PayWidgetOptions } from "./types.js";
2
+ export type MountOptions = PayWidgetOptions & FrameOptions & {
3
+ open?: boolean;
4
+ required?: readonly PayPart[];
5
+ onOpenChange?: (open: boolean) => void;
6
+ onCredited?: (event: CreditedEvent) => void;
7
+ onError?: (error: PayError) => void;
8
+ onStatusChange?: (status: PayStatus) => void;
9
+ };
10
+ export interface PayWidgetState {
11
+ open: boolean;
12
+ status: PayStatus;
13
+ error: PayError | null;
14
+ }
15
+ export interface PayWidget {
16
+ open: () => void;
17
+ close: () => void;
18
+ destroy: () => void;
19
+ getState: () => PayWidgetState;
20
+ }
21
+ export declare const mount: (root: HTMLElement, options: MountOptions) => PayWidget | null;
package/dist/mount.js ADDED
@@ -0,0 +1,119 @@
1
+ import { warnMissingParts } from "./dev.js";
2
+ import { runPayFrame } from "./frame.js";
3
+ import { PART_ATTRIBUTE, isLoadingStatus, isPayPart, missingParts, } from "./parts.js";
4
+ const collectParts = (root) => {
5
+ const parts = new Map();
6
+ root
7
+ .querySelectorAll(`[${PART_ATTRIBUTE}]`)
8
+ .forEach((element) => {
9
+ const name = element.getAttribute(PART_ATTRIBUTE);
10
+ if (!isPayPart(name))
11
+ return;
12
+ parts.set(name, [...(parts.get(name) ?? []), element]);
13
+ });
14
+ return parts;
15
+ };
16
+ export const mount = (root, options) => {
17
+ const parts = collectParts(root);
18
+ const missing = missingParts((part) => parts.has(part), options.required);
19
+ const [frameElement] = parts.get("frame") ?? [];
20
+ if (missing.length > 0 || !frameElement) {
21
+ warnMissingParts("mount()", missing);
22
+ root.hidden = true;
23
+ return null;
24
+ }
25
+ const triggers = parts.get("trigger") ?? [];
26
+ const closers = parts.get("close") ?? [];
27
+ const loaders = parts.get("loader") ?? [];
28
+ const statuses = parts.get("status") ?? [];
29
+ const fillsStatusText = new Map(statuses.map((element) => [element, element.childNodes.length === 0]));
30
+ if (!frameElement.id) {
31
+ frameElement.id = `binodex-pay-${Math.random().toString(36).slice(2, 10)}`;
32
+ }
33
+ let open = options.open ?? true;
34
+ let status = "idle";
35
+ let error = null;
36
+ let stop = null;
37
+ let destroyed = false;
38
+ const render = () => {
39
+ const state = open ? "open" : "closed";
40
+ root.setAttribute("data-state", state);
41
+ root.setAttribute("data-status", status);
42
+ frameElement.hidden = !open;
43
+ frameElement.setAttribute("data-state", state);
44
+ frameElement.setAttribute("data-status", status);
45
+ triggers.forEach((element) => {
46
+ element.setAttribute("aria-expanded", String(open));
47
+ element.setAttribute("aria-controls", frameElement.id);
48
+ });
49
+ closers.forEach((element) => {
50
+ element.hidden = !open;
51
+ });
52
+ loaders.forEach((element) => {
53
+ element.hidden = !(open && isLoadingStatus(status));
54
+ });
55
+ statuses.forEach((element) => {
56
+ element.hidden = !(open && status === "error");
57
+ if (fillsStatusText.get(element)) {
58
+ element.textContent = status === "error" && error ? error.message : "";
59
+ }
60
+ });
61
+ };
62
+ const halt = () => {
63
+ stop?.();
64
+ stop = null;
65
+ status = "idle";
66
+ error = null;
67
+ frameElement.style.minHeight = "";
68
+ };
69
+ const setOpen = (next) => {
70
+ if (destroyed || next === open)
71
+ return;
72
+ open = next;
73
+ if (open)
74
+ start();
75
+ else
76
+ halt();
77
+ render();
78
+ options.onOpenChange?.(open);
79
+ };
80
+ function start() {
81
+ if (stop || destroyed)
82
+ return;
83
+ stop = runPayFrame(frameElement, options, {
84
+ status: (next, nextError) => {
85
+ status = next;
86
+ error = nextError;
87
+ render();
88
+ options.onStatusChange?.(next);
89
+ if (nextError)
90
+ options.onError?.(nextError);
91
+ },
92
+ height: (height) => {
93
+ frameElement.style.minHeight = `${height}px`;
94
+ },
95
+ credited: (event) => options.onCredited?.(event),
96
+ close: () => setOpen(false),
97
+ });
98
+ }
99
+ const onTrigger = () => setOpen(true);
100
+ const onClose = () => setOpen(false);
101
+ triggers.forEach((element) => element.addEventListener("click", onTrigger));
102
+ closers.forEach((element) => element.addEventListener("click", onClose));
103
+ render();
104
+ if (open)
105
+ start();
106
+ return {
107
+ open: () => setOpen(true),
108
+ close: () => setOpen(false),
109
+ destroy: () => {
110
+ if (destroyed)
111
+ return;
112
+ halt();
113
+ destroyed = true;
114
+ triggers.forEach((element) => element.removeEventListener("click", onTrigger));
115
+ closers.forEach((element) => element.removeEventListener("click", onClose));
116
+ },
117
+ getState: () => ({ open, status, error }),
118
+ };
119
+ };
@@ -0,0 +1,6 @@
1
+ import type { PayPart, PayStatus } from "./types.js";
2
+ export declare const PART_ATTRIBUTE = "data-binodex-pay";
3
+ export declare const REQUIRED_PARTS: readonly PayPart[];
4
+ export declare const isPayPart: (value: unknown) => value is PayPart;
5
+ export declare const isLoadingStatus: (status: PayStatus) => boolean;
6
+ export declare const missingParts: (isPresent: (part: PayPart) => boolean, required?: readonly PayPart[]) => PayPart[];
package/dist/parts.js ADDED
@@ -0,0 +1,17 @@
1
+ export const PART_ATTRIBUTE = "data-binodex-pay";
2
+ export const REQUIRED_PARTS = ["frame"];
3
+ const PART_NAMES = new Set([
4
+ "frame",
5
+ "trigger",
6
+ "close",
7
+ "loader",
8
+ "status",
9
+ ]);
10
+ const LOADING_STATUSES = new Set([
11
+ "idle",
12
+ "session",
13
+ "loading",
14
+ ]);
15
+ export const isPayPart = (value) => typeof value === "string" && PART_NAMES.has(value);
16
+ export const isLoadingStatus = (status) => LOADING_STATUSES.has(status);
17
+ export const missingParts = (isPresent, required = []) => Array.from(new Set([...REQUIRED_PARTS, ...required])).filter((part) => !isPresent(part));
@@ -0,0 +1,31 @@
1
+ export type WidgetEvent = {
2
+ type: "ready";
3
+ } | {
4
+ type: "reauth-required";
5
+ } | {
6
+ type: "close";
7
+ } | {
8
+ type: "credited";
9
+ amount: number;
10
+ asset: string;
11
+ } | {
12
+ type: "error";
13
+ reason: string;
14
+ } | {
15
+ type: "resize";
16
+ height: number;
17
+ };
18
+ export interface WidgetEnvelope {
19
+ event: WidgetEvent;
20
+ channel: string | null;
21
+ }
22
+ export type InitMessage = {
23
+ type: "binodex-embed:init";
24
+ session: string;
25
+ } | {
26
+ type: "binodex-embed:init";
27
+ session: string;
28
+ channel: string;
29
+ };
30
+ export declare const readWidgetMessage: (data: unknown) => WidgetEnvelope | null;
31
+ export declare const initMessage: (session: string, channel: string | null) => InitMessage;
@@ -0,0 +1,53 @@
1
+ const PREFIX = "binodex-embed:";
2
+ const REASON_PATTERN = /^[a-z0-9_]{1,64}$/;
3
+ const ASSET_PATTERN = /^[A-Z0-9]{2,16}$/;
4
+ const isPlainObject = (value) => {
5
+ if (Object.prototype.toString.call(value) !== "[object Object]")
6
+ return false;
7
+ const prototype = Object.getPrototypeOf(value);
8
+ return prototype === null || prototype === Object.prototype;
9
+ };
10
+ const isPositiveNumber = (value) => typeof value === "number" && Number.isFinite(value) && value > 0;
11
+ const readEvent = (name, data) => {
12
+ switch (name) {
13
+ case "ready":
14
+ case "reauth-required":
15
+ case "close":
16
+ return { type: name };
17
+ case "resize":
18
+ return isPositiveNumber(data.height)
19
+ ? { type: "resize", height: data.height }
20
+ : null;
21
+ case "credited":
22
+ return isPositiveNumber(data.amount) &&
23
+ typeof data.asset === "string" &&
24
+ ASSET_PATTERN.test(data.asset)
25
+ ? { type: "credited", amount: data.amount, asset: data.asset }
26
+ : null;
27
+ case "error":
28
+ return {
29
+ type: "error",
30
+ reason: typeof data.message === "string" && REASON_PATTERN.test(data.message)
31
+ ? data.message
32
+ : "unknown",
33
+ };
34
+ default:
35
+ return null;
36
+ }
37
+ };
38
+ export const readWidgetMessage = (data) => {
39
+ if (!isPlainObject(data))
40
+ return null;
41
+ const { type, channel } = data;
42
+ if (typeof type !== "string" || !type.startsWith(PREFIX))
43
+ return null;
44
+ if (channel !== undefined && typeof channel !== "string")
45
+ return null;
46
+ const event = readEvent(type.slice(PREFIX.length), data);
47
+ if (!event)
48
+ return null;
49
+ return { event, channel: typeof channel === "string" ? channel : null };
50
+ };
51
+ export const initMessage = (session, channel) => channel
52
+ ? { type: "binodex-embed:init", session, channel }
53
+ : { type: "binodex-embed:init", session };
@@ -0,0 +1,35 @@
1
+ import { type ButtonHTMLAttributes, type HTMLAttributes, type ReactNode } from "react";
2
+ import type { CreditedEvent, FrameOptions, PayError, PayPart, PayStatus, PayWidgetOptions } from "./types.js";
3
+ export type { CreateSession, CreateSessionContext, CreditedEvent, FrameOptions, PayError, PayErrorCode, PayMode, PayPart, PayStatus, PayTheme, PayWidgetOptions, WidgetSession, } from "./types.js";
4
+ export type RootProps = PayWidgetOptions & {
5
+ children?: ReactNode;
6
+ open?: boolean;
7
+ defaultOpen?: boolean;
8
+ onOpenChange?: (open: boolean) => void;
9
+ onCredited?: (event: CreditedEvent) => void;
10
+ onError?: (error: PayError) => void;
11
+ onStatusChange?: (status: PayStatus) => void;
12
+ required?: readonly PayPart[];
13
+ };
14
+ export declare function Root(props: RootProps): import("react").JSX.Element | null;
15
+ export type FrameProps = Omit<HTMLAttributes<HTMLDivElement>, "children"> & FrameOptions;
16
+ export declare const Frame: import("react").ForwardRefExoticComponent<Omit<HTMLAttributes<HTMLDivElement>, "children"> & FrameOptions & import("react").RefAttributes<HTMLDivElement>>;
17
+ export type TriggerProps = ButtonHTMLAttributes<HTMLButtonElement>;
18
+ export declare const Trigger: import("react").ForwardRefExoticComponent<TriggerProps & import("react").RefAttributes<HTMLButtonElement>>;
19
+ export type CloseProps = ButtonHTMLAttributes<HTMLButtonElement>;
20
+ export declare const Close: import("react").ForwardRefExoticComponent<CloseProps & import("react").RefAttributes<HTMLButtonElement>>;
21
+ export type LoaderProps = HTMLAttributes<HTMLDivElement>;
22
+ export declare const Loader: import("react").ForwardRefExoticComponent<LoaderProps & import("react").RefAttributes<HTMLDivElement>>;
23
+ export type StatusProps = Omit<HTMLAttributes<HTMLDivElement>, "children"> & {
24
+ children?: ReactNode | ((error: PayError) => ReactNode);
25
+ };
26
+ export declare const Status: import("react").ForwardRefExoticComponent<Omit<HTMLAttributes<HTMLDivElement>, "children"> & {
27
+ children?: ReactNode | ((error: PayError) => ReactNode);
28
+ } & import("react").RefAttributes<HTMLDivElement>>;
29
+ export interface UsePayWidgetResult {
30
+ open: boolean;
31
+ setOpen: (open: boolean) => void;
32
+ status: PayStatus;
33
+ error: PayError | null;
34
+ }
35
+ export declare function usePayWidget(): UsePayWidgetResult;
package/dist/react.js ADDED
@@ -0,0 +1,188 @@
1
+ "use client";
2
+ import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { createContext, forwardRef, useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore, } from "react";
4
+ import { warnMissingParts } from "./dev.js";
5
+ import { heightBounds, runPayFrame } from "./frame.js";
6
+ import { isLoadingStatus, missingParts } from "./parts.js";
7
+ const useIsomorphicLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;
8
+ const subscribeToNothing = () => () => undefined;
9
+ const IDLE = { status: "idle", error: null, height: null };
10
+ const PayContext = createContext(null);
11
+ const usePayContext = (owner) => {
12
+ const context = useContext(PayContext);
13
+ if (!context) {
14
+ throw new Error(`${owner} must be used inside <Root> from @binopartner/pay-sdk/react`);
15
+ }
16
+ return context;
17
+ };
18
+ const usePart = (owner, part) => {
19
+ const context = usePayContext(owner);
20
+ const { register } = context;
21
+ useIsomorphicLayoutEffect(() => register(part), [register, part]);
22
+ return context;
23
+ };
24
+ const assignRef = (ref, value) => {
25
+ if (typeof ref === "function")
26
+ ref(value);
27
+ else if (ref)
28
+ ref.current = value;
29
+ };
30
+ export function Root(props) {
31
+ const { children, open: openProp, defaultOpen = true, required } = props;
32
+ const latest = useRef(props);
33
+ useIsomorphicLayoutEffect(() => {
34
+ latest.current = props;
35
+ });
36
+ const isClient = useSyncExternalStore(subscribeToNothing, () => true, () => false);
37
+ const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen);
38
+ const open = openProp ?? uncontrolledOpen;
39
+ const [runState, setRunState] = useState(IDLE);
40
+ const counts = useRef(new Map());
41
+ const [partsVersion, bumpParts] = useReducer((value) => value + 1, 0);
42
+ const [verdict, setVerdict] = useState("probe");
43
+ const frameId = useId();
44
+ const requiredKey = (required ?? []).join(" ");
45
+ const setOpen = useCallback((next) => {
46
+ if (latest.current.open === undefined)
47
+ setUncontrolledOpen(next);
48
+ latest.current.onOpenChange?.(next);
49
+ }, []);
50
+ const register = useCallback((part) => {
51
+ counts.current.set(part, (counts.current.get(part) ?? 0) + 1);
52
+ bumpParts();
53
+ return () => {
54
+ counts.current.set(part, (counts.current.get(part) ?? 1) - 1);
55
+ bumpParts();
56
+ };
57
+ }, []);
58
+ useIsomorphicLayoutEffect(() => {
59
+ if (!isClient)
60
+ return;
61
+ const extra = requiredKey ? requiredKey.split(" ") : [];
62
+ const missing = missingParts((part) => (counts.current.get(part) ?? 0) > 0, extra);
63
+ if (missing.length === 0) {
64
+ setVerdict("valid");
65
+ return;
66
+ }
67
+ if (verdict !== "invalid")
68
+ warnMissingParts("<Root>", missing);
69
+ setVerdict("invalid");
70
+ }, [isClient, partsVersion, requiredKey, verdict]);
71
+ const createSession = useCallback((context) => {
72
+ const source = latest.current.createSession;
73
+ return source
74
+ ? source(context)
75
+ : Promise.reject(new Error("createSession is no longer provided"));
76
+ }, []);
77
+ const { mode, lang, theme } = props;
78
+ const run = useCallback((container, frame) => {
79
+ const current = latest.current;
80
+ const source = current.createSession
81
+ ? { createSession }
82
+ : { sessionEndpoint: current.sessionEndpoint ?? "" };
83
+ const stop = runPayFrame(container, {
84
+ ...source,
85
+ mode,
86
+ lang,
87
+ theme,
88
+ clientId: current.clientId,
89
+ platformUrl: current.platformUrl,
90
+ requireChannel: current.requireChannel,
91
+ ...frame,
92
+ }, {
93
+ status: (status, error) => {
94
+ setRunState((previous) => ({ ...previous, status, error }));
95
+ latest.current.onStatusChange?.(status);
96
+ if (error)
97
+ latest.current.onError?.(error);
98
+ },
99
+ height: (height) => setRunState((previous) => ({ ...previous, height })),
100
+ credited: (event) => latest.current.onCredited?.(event),
101
+ close: () => setOpen(false),
102
+ });
103
+ return () => {
104
+ stop();
105
+ setRunState(IDLE);
106
+ };
107
+ }, [createSession, mode, lang, theme, setOpen]);
108
+ const value = useMemo(() => ({
109
+ armed: verdict === "valid",
110
+ open,
111
+ status: runState.status,
112
+ error: runState.error,
113
+ height: runState.height,
114
+ frameId,
115
+ setOpen,
116
+ register,
117
+ run,
118
+ }), [verdict, open, runState, frameId, setOpen, register, run]);
119
+ if (!isClient || verdict === "invalid")
120
+ return null;
121
+ return _jsx(PayContext.Provider, { value: value, children: children });
122
+ }
123
+ export const Frame = forwardRef(function Frame({ title, initialHeight, minHeight, maxHeight, style, ...rest }, forwardedRef) {
124
+ const context = usePart("<Frame>", "frame");
125
+ const { armed, open, run } = context;
126
+ const active = armed && open;
127
+ const container = useRef(null);
128
+ const frameOptions = useRef({});
129
+ useIsomorphicLayoutEffect(() => {
130
+ frameOptions.current = { title, initialHeight, minHeight, maxHeight };
131
+ });
132
+ useEffect(() => {
133
+ const element = container.current;
134
+ if (!active || !element)
135
+ return;
136
+ return run(element, frameOptions.current);
137
+ }, [active, run]);
138
+ const setContainer = useCallback((element) => {
139
+ container.current = element;
140
+ assignRef(forwardedRef, element);
141
+ }, [forwardedRef]);
142
+ if (!active)
143
+ return null;
144
+ const reserved = context.height ??
145
+ heightBounds({ initialHeight, minHeight, maxHeight }).initial;
146
+ return (_jsx("div", { ...rest, ref: setContainer, id: context.frameId, "data-binodex-pay": "frame", "data-state": "open", "data-status": context.status, style: { minHeight: reserved, ...style } }));
147
+ });
148
+ export const Trigger = forwardRef(function Trigger({ onClick, type = "button", ...rest }, ref) {
149
+ const context = usePart("<Trigger>", "trigger");
150
+ if (!context.armed)
151
+ return null;
152
+ return (_jsx("button", { type: type, "aria-expanded": context.open, "aria-controls": context.open ? context.frameId : undefined, ...rest, ref: ref, "data-binodex-pay": "trigger", "data-state": context.open ? "open" : "closed", onClick: (event) => {
153
+ onClick?.(event);
154
+ if (!event.defaultPrevented)
155
+ context.setOpen(true);
156
+ } }));
157
+ });
158
+ export const Close = forwardRef(function Close({ onClick, type = "button", children, ...rest }, ref) {
159
+ const context = usePart("<Close>", "close");
160
+ if (!context.armed || !context.open)
161
+ return null;
162
+ return (_jsx("button", { type: type, "aria-label": children ? undefined : "Close", ...rest, ref: ref, "data-binodex-pay": "close", onClick: (event) => {
163
+ onClick?.(event);
164
+ if (!event.defaultPrevented)
165
+ context.setOpen(false);
166
+ }, children: children }));
167
+ });
168
+ export const Loader = forwardRef(function Loader({ children, ...rest }, ref) {
169
+ const context = usePart("<Loader>", "loader");
170
+ if (!context.armed || !context.open || !isLoadingStatus(context.status)) {
171
+ return null;
172
+ }
173
+ return (_jsx("div", { role: "status", "aria-live": "polite", ...rest, ref: ref, "data-binodex-pay": "loader", "data-status": context.status, children: children ?? "Loading payment form…" }));
174
+ });
175
+ export const Status = forwardRef(function Status({ children, ...rest }, ref) {
176
+ const context = usePart("<Status>", "status");
177
+ const { error } = context;
178
+ if (!context.armed || !context.open || context.status !== "error" || !error) {
179
+ return null;
180
+ }
181
+ return (_jsx("div", { role: "alert", ...rest, ref: ref, "data-binodex-pay": "status", "data-error": error.code, children: typeof children === "function"
182
+ ? children(error)
183
+ : (children ?? error.message) }));
184
+ });
185
+ export function usePayWidget() {
186
+ const { open, setOpen, status, error } = usePayContext("usePayWidget()");
187
+ return { open, setOpen, status, error };
188
+ }
@@ -0,0 +1,13 @@
1
+ import type { CreateSession, PayMode, WidgetSession } from "./types.js";
2
+ export interface SessionSource {
3
+ mode: PayMode;
4
+ sessionEndpoint?: string;
5
+ createSession?: CreateSession;
6
+ }
7
+ export interface HeldSession {
8
+ session: string;
9
+ reusableUntil: number;
10
+ }
11
+ export declare const isWidgetSession: (value: unknown) => value is WidgetSession;
12
+ export declare const requestSession: (source: SessionSource, signal: AbortSignal) => Promise<WidgetSession>;
13
+ export declare const holdSession: (session: WidgetSession, now: number) => HeldSession;
@@ -0,0 +1,91 @@
1
+ import { PaySdkError, SESSION_FAILED_MESSAGE } from "./errors.js";
2
+ const SESSION_PATTERN = /^[\x21-\x7e]{1,1024}$/;
3
+ const REUSE_LIMIT_MS = 45000;
4
+ const REUSE_HEADROOM_MS = 15000;
5
+ export const isWidgetSession = (value) => {
6
+ if (!value || typeof value !== "object")
7
+ return false;
8
+ const { session, expires_in, widget_url, widget_origin } = value;
9
+ return (typeof session === "string" &&
10
+ SESSION_PATTERN.test(session) &&
11
+ (expires_in === undefined || typeof expires_in === "number") &&
12
+ (widget_url === undefined ||
13
+ widget_url === null ||
14
+ typeof widget_url === "string") &&
15
+ (widget_origin === undefined ||
16
+ widget_origin === null ||
17
+ typeof widget_origin === "string"));
18
+ };
19
+ const readServerMessage = (data) => {
20
+ if (!data || typeof data !== "object")
21
+ return null;
22
+ const { error, message } = data;
23
+ const nested = error && typeof error === "object"
24
+ ? error.message
25
+ : error;
26
+ const text = typeof nested === "string"
27
+ ? nested
28
+ : typeof message === "string"
29
+ ? message
30
+ : "";
31
+ return text ? text.slice(0, 300) : null;
32
+ };
33
+ const postSessionEndpoint = async (endpoint, mode, signal) => {
34
+ let response;
35
+ try {
36
+ response = await fetch(endpoint, {
37
+ method: "POST",
38
+ credentials: "same-origin",
39
+ headers: {
40
+ Accept: "application/json",
41
+ "Content-Type": "application/json",
42
+ },
43
+ body: JSON.stringify({ mode }),
44
+ signal,
45
+ });
46
+ }
47
+ catch (error) {
48
+ if (signal.aborted)
49
+ throw error;
50
+ throw new PaySdkError("session_failed", SESSION_FAILED_MESSAGE);
51
+ }
52
+ const data = await response.json().catch(() => null);
53
+ if (!response.ok) {
54
+ throw new PaySdkError("session_failed", readServerMessage(data) ?? SESSION_FAILED_MESSAGE);
55
+ }
56
+ return data;
57
+ };
58
+ export const requestSession = async (source, signal) => {
59
+ let data;
60
+ try {
61
+ if (source.createSession) {
62
+ data = await source.createSession({ mode: source.mode, signal });
63
+ }
64
+ else if (source.sessionEndpoint) {
65
+ data = await postSessionEndpoint(source.sessionEndpoint, source.mode, signal);
66
+ }
67
+ else {
68
+ throw new PaySdkError("session_failed", "Pass sessionEndpoint or createSession");
69
+ }
70
+ }
71
+ catch (error) {
72
+ if (error instanceof PaySdkError || signal.aborted)
73
+ throw error;
74
+ throw new PaySdkError("session_failed", error instanceof Error && error.message
75
+ ? error.message
76
+ : SESSION_FAILED_MESSAGE);
77
+ }
78
+ if (!isWidgetSession(data)) {
79
+ throw new PaySdkError("session_failed", readServerMessage(data) ?? SESSION_FAILED_MESSAGE);
80
+ }
81
+ return data;
82
+ };
83
+ export const holdSession = (session, now) => {
84
+ const ttl = typeof session.expires_in === "number" && session.expires_in > 0
85
+ ? session.expires_in * 1000 - REUSE_HEADROOM_MS
86
+ : REUSE_LIMIT_MS;
87
+ return {
88
+ session: session.session,
89
+ reusableUntil: now + Math.max(0, Math.min(REUSE_LIMIT_MS, ttl)),
90
+ };
91
+ };
@@ -0,0 +1,48 @@
1
+ export type PayMode = "deposit" | "withdraw";
2
+ export type PayTheme = "light" | "dark";
3
+ export type PayStatus = "idle" | "session" | "loading" | "handshake" | "ready" | "error";
4
+ export type PayErrorCode = "session_failed" | "invalid_widget_url" | "widget_error";
5
+ export interface PayError {
6
+ code: PayErrorCode;
7
+ message: string;
8
+ reason?: string;
9
+ }
10
+ export interface CreditedEvent {
11
+ amount: number;
12
+ asset: string;
13
+ }
14
+ export interface WidgetSession {
15
+ session: string;
16
+ expires_in?: number;
17
+ widget_url?: string;
18
+ widget_origin?: string;
19
+ region?: string;
20
+ }
21
+ export interface CreateSessionContext {
22
+ mode: PayMode;
23
+ signal: AbortSignal;
24
+ }
25
+ export type CreateSession = (context: CreateSessionContext) => Promise<WidgetSession>;
26
+ export type PayPart = "frame" | "trigger" | "close" | "loader" | "status";
27
+ interface PayWidgetBaseOptions {
28
+ mode: PayMode;
29
+ clientId?: string;
30
+ platformUrl?: string;
31
+ lang?: string;
32
+ theme?: PayTheme;
33
+ requireChannel?: boolean;
34
+ }
35
+ export type PayWidgetOptions = PayWidgetBaseOptions & ({
36
+ sessionEndpoint: string;
37
+ createSession?: undefined;
38
+ } | {
39
+ createSession: CreateSession;
40
+ sessionEndpoint?: undefined;
41
+ });
42
+ export interface FrameOptions {
43
+ title?: string;
44
+ initialHeight?: number;
45
+ minHeight?: number;
46
+ maxHeight?: number;
47
+ }
48
+ export {};
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,15 @@
1
+ import type { PayMode, PayTheme, WidgetSession } from "./types.js";
2
+ export interface WidgetLocation {
3
+ src: string;
4
+ origin: string;
5
+ }
6
+ export interface WidgetLocationInput {
7
+ session: WidgetSession;
8
+ mode: PayMode;
9
+ channel: string;
10
+ clientId?: string;
11
+ platformUrl?: string;
12
+ lang?: string;
13
+ theme?: PayTheme;
14
+ }
15
+ export declare const resolveWidgetLocation: (input: WidgetLocationInput) => WidgetLocation | null;
@@ -0,0 +1,36 @@
1
+ const LOOPBACK_HOST = /^(?:localhost|127\.0\.0\.1|\[::1\])$|\.localhost$/;
2
+ const LANG_PATTERN = /^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/;
3
+ const fallbackUrl = ({ mode, clientId, platformUrl, }) => {
4
+ if (!clientId || !platformUrl)
5
+ return null;
6
+ const url = new URL(`${platformUrl.replace(/\/+$/, "")}/embed/pay`);
7
+ url.searchParams.set("mode", mode);
8
+ url.searchParams.set("client_id", clientId);
9
+ return url.toString();
10
+ };
11
+ const isTransportAllowed = (url) => url.protocol === "https:" ||
12
+ (url.protocol === "http:" && LOOPBACK_HOST.test(url.hostname));
13
+ export const resolveWidgetLocation = (input) => {
14
+ try {
15
+ const base = input.session.widget_url || fallbackUrl(input);
16
+ if (!base)
17
+ return null;
18
+ const url = new URL(base);
19
+ if (!isTransportAllowed(url) || url.username || url.password)
20
+ return null;
21
+ const declaredOrigin = input.session.widget_origin;
22
+ if (declaredOrigin && declaredOrigin !== url.origin)
23
+ return null;
24
+ if (input.lang && LANG_PATTERN.test(input.lang)) {
25
+ url.searchParams.set("lang", input.lang);
26
+ }
27
+ if (input.theme === "light" || input.theme === "dark") {
28
+ url.searchParams.set("theme", input.theme);
29
+ }
30
+ url.hash = new URLSearchParams({ channel: input.channel }).toString();
31
+ return { src: url.toString(), origin: url.origin };
32
+ }
33
+ catch {
34
+ return null;
35
+ }
36
+ };
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@binopartner/pay-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "license": "UNLICENSED",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/binodex/broker-web.git",
8
+ "directory": "packages/pay-sdk"
9
+ },
10
+ "homepage": "https://github.com/binodex/broker-web/tree/main/packages/pay-sdk#readme",
11
+ "description": "Embed the Binodex deposit and withdrawal widget: a root component, composable parts and a hardened iframe channel.",
12
+ "type": "module",
13
+ "sideEffects": false,
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "import": "./dist/index.js",
18
+ "default": "./dist/index.js"
19
+ },
20
+ "./react": {
21
+ "types": "./dist/react.d.ts",
22
+ "import": "./dist/react.js",
23
+ "default": "./dist/react.js"
24
+ },
25
+ "./package.json": "./package.json"
26
+ },
27
+ "files": [
28
+ "dist",
29
+ "README.md"
30
+ ],
31
+ "scripts": {
32
+ "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json",
33
+ "typecheck": "tsc -p tsconfig.json",
34
+ "test": "vitest run"
35
+ },
36
+ "peerDependencies": {
37
+ "react": ">=18"
38
+ },
39
+ "peerDependenciesMeta": {
40
+ "react": {
41
+ "optional": true
42
+ }
43
+ },
44
+ "devDependencies": {
45
+ "@types/react": "^19.2.18",
46
+ "jsdom": "^27.4.0",
47
+ "react": "^19.2.8",
48
+ "react-dom": "^19.2.8",
49
+ "typescript": "^5",
50
+ "vite": "^7.3.7",
51
+ "vitest": "^4.1.10"
52
+ },
53
+ "publishConfig": {
54
+ "access": "public"
55
+ }
56
+ }