@invonetwork/web-sdk 3.10.1 → 3.11.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/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { A as ApproveResult, C as ConfirmReceiptResult, M as MountCheckoutOptions, a as CheckoutMountHandle, b as ClientConfig, c as CallOptions, L as LinkDeviceResult, P as PendingCollectResult, D as DestinationsQuery, d as DestinationsResult, B as BalanceResult, E as EnrollmentBeginResult, e as EnrollmentVerifyResult, R as RecoveryBeginResult, f as RecoveryCompleteResult } from './types-CBxpXgAM.cjs';
2
- export { g as BalanceRow, h as DestinationGame, I as InvoError, i as InvoErrorInfo, j as InvoHooks, k as InvoRequestInfo, l as InvoResponseInfo, m as PendingCollectItem, n as Rail, V as VerificationMethod } from './types-CBxpXgAM.cjs';
1
+ import { A as ApproveResult, C as ConfirmReceiptResult, P as PurchaseStatusResult, a as PurchaseCredited, b as PurchaseExpired, c as PurchaseRefunded, d as PurchaseRefused, e as CheckoutClientConfig, H as Http, f as PurchaseStatusInput, g as CallOptions, W as WaitForPurchaseInput, M as MountCheckoutOptions, h as CheckoutMountHandle, i as ClientConfig, L as LinkDeviceResult, j as PendingCollectResult, D as DestinationsQuery, k as DestinationsResult, B as BalanceResult, E as EnrollmentBeginResult, l as EnrollmentVerifyResult, R as RecoveryBeginResult, m as RecoveryCompleteResult } from './types-DSLGe_0Z.cjs';
2
+ export { n as BalanceRow, o as CheckoutPurchaseStatus, p as DestinationGame, I as InvoError, q as InvoErrorInfo, r as InvoHooks, s as InvoRequestInfo, t as InvoResponseInfo, u as PendingCollectItem, v as PurchaseRefusalReason, w as Rail, V as VerificationMethod } from './types-DSLGe_0Z.cjs';
3
3
 
4
4
  /** The four device-approval flows (`begin.flow`). */
5
5
  type HostedFlow = "transfer" | "send" | "send_receipt" | "transfer_receipt";
@@ -94,6 +94,65 @@ interface ApproveHostedOptions {
94
94
  signal?: AbortSignal;
95
95
  }
96
96
 
97
+ /**
98
+ * The purchase status read: mapping and the guards that go with it.
99
+ *
100
+ * WHY THE ENDPOINT EXISTS. A hosted checkout used to be able to charge a buyer in full,
101
+ * refuse the credit, answer `200` on every route, and close the page on nothing: no coins,
102
+ * no error, no receipt. `GET /api/checkout/sessions/<id>` is INVO's fix for that silence.
103
+ * It always has something true to say, including the case where INVO has the buyer's money
104
+ * and the buyer does not have their coins.
105
+ *
106
+ * ONE RULE RUNS THROUGH THIS FILE: `terminal` is INVO's answer, never ours. It is read
107
+ * straight off the response and never recomputed from `status`, so a status a future
108
+ * backend introduces cannot make a build pinned to this release decide a purchase
109
+ * finished, or finished WELL, on its own.
110
+ */
111
+
112
+ /**
113
+ * The purchase was charged and the coins are in the balance. Show `coinsCredited`,
114
+ * `currencyName` and `newBalance` when it is not null, and close on the buyer's action
115
+ * rather than automatically.
116
+ *
117
+ * It narrows the SHAPE of a result; it is not a way to ask whether polling is over. Use
118
+ * `result.terminal` for that. A status this build does not recognise answers `false` here,
119
+ * so an unknown terminal value is never read as a success.
120
+ */
121
+ declare function isPurchaseCredited(r: PurchaseStatusResult): r is PurchaseCredited;
122
+ /**
123
+ * This purchase will not credit. Show `message` verbatim, show `orderId`, and show
124
+ * **Contact support**. Never close silently. Offer a Try again only when
125
+ * {@link nothingWasCharged} is true.
126
+ */
127
+ declare function isPurchaseRefused(r: PurchaseStatusResult): r is PurchaseRefused;
128
+ /** The money went back to the buyer (a refund, or a reversal by their bank). */
129
+ declare function isPurchaseRefunded(r: PurchaseStatusResult): r is PurchaseRefunded;
130
+ /** The checkout was never paid and can no longer be paid. Offer a new checkout. */
131
+ declare function isPurchaseExpired(r: PurchaseStatusResult): r is PurchaseExpired;
132
+ /**
133
+ * True when INVO has said, in this exact result, that no money was taken: an `expired`
134
+ * checkout, or a refusal coded `PAYMENT_DECLINED` / `PAYMENT_CANCELLED`. Those are the
135
+ * outcomes to put a **Try again** on.
136
+ *
137
+ * FALSE FOR EVERYTHING ELSE, INCLUDING A CODE THIS BUILD HAS NEVER SEEN. Every other
138
+ * refusal happened AFTER the card was charged, and inviting that buyer to pay a second
139
+ * time is the worst thing the page can do. When this is false and the purchase is refused,
140
+ * offer Contact support with the order id and nothing else.
141
+ */
142
+ declare function nothingWasCharged(r: PurchaseStatusResult): boolean;
143
+
144
+ /**
145
+ * @invonetwork/web-sdk — BROWSER entry.
146
+ *
147
+ * InvoClient holds only the short-lived, game-scoped player token (minted
148
+ * server-side by InvoServer.mintPlayerToken) and runs the passkey ceremonies:
149
+ * enroll, approve a send/transfer, and recipient self-claim. It never sees the
150
+ * game secret.
151
+ *
152
+ * Currency purchase has NO browser method — it is server-initiated; the browser
153
+ * only redirects to the checkoutUrl/paymentUrl the server returns.
154
+ */
155
+
97
156
  declare class PlatformCommerceClient {
98
157
  /**
99
158
  * Embed INVO's hosted checkout in an iframe and listen for completion.
@@ -115,6 +174,81 @@ declare class PlatformCommerceClient {
115
174
  */
116
175
  mountCheckout(el: string | HTMLElement, checkoutUrl: string, opts?: MountCheckoutOptions): CheckoutMountHandle;
117
176
  }
177
+ /**
178
+ * Reads what happened to a hosted-checkout currency purchase.
179
+ *
180
+ * Reach it as `invo.checkout` on an {@link InvoClient}, or construct it on its own for a
181
+ * page that has no player token (a return page after the redirect, for instance):
182
+ *
183
+ * ```ts
184
+ * const checkout = new CheckoutClient({ baseUrl: "https://invo.network" });
185
+ * const result = await checkout.waitForPurchase({ sessionId, sessionToken });
186
+ * ```
187
+ *
188
+ * THE CREDENTIAL IS THE SESSION TOKEN, not the player token and not the game secret, so
189
+ * this class needs neither. The session id in the path is an identifier: it says which
190
+ * purchase is being asked about and on its own reads nothing.
191
+ */
192
+ declare class CheckoutClient {
193
+ private readonly http;
194
+ constructor(config: CheckoutClientConfig);
195
+ /**
196
+ * Wrap an `Http` the owning client already built, so `invo.checkout` shares that
197
+ * client's baseUrl, timeout, retry budget and observability hooks.
198
+ *
199
+ * @internal Not part of the public API; it takes an internal type and may change.
200
+ */
201
+ static _withHttp(http: Http): CheckoutClient;
202
+ /**
203
+ * Read a purchase's status once.
204
+ *
205
+ * Answers `200` with a {@link PurchaseStatusResult} for every state of the purchase,
206
+ * including "we have your money and your coins are not there". There is no tenant gate
207
+ * on it: a partner suspended after a buyer's card was charged is exactly the case it
208
+ * exists for.
209
+ *
210
+ * Throws an {@link InvoError} on `401` (no token, bad signature, or a card-setup token:
211
+ * `err.isWrongSessionPurpose`), `403` (a valid token for a DIFFERENT session:
212
+ * `err.isCheckoutSessionMismatch`) and `410` (the token is more than 24 hours past its
213
+ * expiry: `err.isCheckoutSessionExpired`; show the buyer the order id you already have
214
+ * and a Contact support link).
215
+ *
216
+ * Storefront (in-client) purchases are keyed on the partner's own purchase reference
217
+ * rather than on a checkout session, so a read by session id finds nothing and answers
218
+ * `pending`. Do not conclude from that that such a purchase never happened.
219
+ */
220
+ getPurchaseStatus(input: PurchaseStatusInput, opts?: CallOptions): Promise<PurchaseStatusResult>;
221
+ /**
222
+ * Poll {@link getPurchaseStatus} until INVO says the purchase is finished, and return
223
+ * that final result.
224
+ *
225
+ * ```ts
226
+ * const result = await invo.checkout.waitForPurchase({
227
+ * sessionId, sessionToken,
228
+ * intervalMs: 1500,
229
+ * timeoutMs: 300_000,
230
+ * signal: controller.signal,
231
+ * onUpdate: (r) => render(r), // keep the modal open on every non-terminal read
232
+ * });
233
+ * if (isPurchaseCredited(result)) showCoins(result.coinsCredited, result.currencyName);
234
+ * else if (result.message) showMessage(result.message, result.orderId); // verbatim
235
+ * ```
236
+ *
237
+ * IT STOPS ON `result.terminal` AND ON NOTHING ELSE. `terminal` is INVO's word, read off
238
+ * the response; this loop never recomputes it from `status`, so a status a later backend
239
+ * introduces cannot end a wait here as a success. `paid_pending_credit` is deliberately
240
+ * not terminal and is never promoted to a failure by age: INVO's reconciler recovers a
241
+ * stalled credit, and telling a buyer they lost money they are about to receive would
242
+ * be a fresh lie in place of the old silence.
243
+ *
244
+ * A transient failure (network, timeout, 429, 5xx) is polled through rather than raised;
245
+ * a `401`, `403` or `410` is raised at once. On the cap it returns the LAST result it
246
+ * read, whose `terminal` is false. Nothing is guessed and nothing is thrown, so the page
247
+ * keeps showing the buyer what INVO last said. If it never got a single answer, the last
248
+ * transport failure is thrown.
249
+ */
250
+ waitForPurchase(input: WaitForPurchaseInput): Promise<PurchaseStatusResult>;
251
+ }
118
252
  declare class InvoClient {
119
253
  private readonly http;
120
254
  private auth;
@@ -129,6 +263,15 @@ declare class InvoClient {
129
263
  * {@link PlatformCommerceClient}.
130
264
  */
131
265
  readonly platformCommerce: PlatformCommerceClient;
266
+ /**
267
+ * Read what happened to a hosted-checkout currency purchase:
268
+ * `invo.checkout.getPurchaseStatus({ sessionId, sessionToken })` once, or
269
+ * `invo.checkout.waitForPurchase({ ... })` until INVO says it is finished.
270
+ *
271
+ * It authenticates with the SESSION token, not this client's player token, so a page
272
+ * that has no player token can build a {@link CheckoutClient} directly instead.
273
+ */
274
+ readonly checkout: CheckoutClient;
132
275
  constructor(config: ClientConfig);
133
276
  private assertWebAuthn;
134
277
  /**
@@ -296,4 +439,4 @@ declare class InvoClient {
296
439
  private confirmReceipt;
297
440
  }
298
441
 
299
- export { type ApproveHostedOptions, type ApproveHostedResult, ApproveResult, BalanceResult, CallOptions, CheckoutMountHandle, ClientConfig, ConfirmReceiptResult, DestinationsQuery, DestinationsResult, EnrollmentBeginResult, type EnrollmentDecision, type EnrollmentRespond, EnrollmentVerifyResult, type HostedApprovalStatus, type HostedEnrollment, type HostedEnrollmentInput, type HostedFlow, InvoClient, LinkDeviceResult, MountCheckoutOptions, PendingCollectResult, PlatformCommerceClient, RecoveryBeginResult, RecoveryCompleteResult };
442
+ export { type ApproveHostedOptions, type ApproveHostedResult, ApproveResult, BalanceResult, CallOptions, CheckoutClient, CheckoutClientConfig, CheckoutMountHandle, ClientConfig, ConfirmReceiptResult, DestinationsQuery, DestinationsResult, EnrollmentBeginResult, type EnrollmentDecision, type EnrollmentRespond, EnrollmentVerifyResult, type HostedApprovalStatus, type HostedEnrollment, type HostedEnrollmentInput, type HostedFlow, InvoClient, LinkDeviceResult, MountCheckoutOptions, PendingCollectResult, PlatformCommerceClient, PurchaseCredited, PurchaseExpired, PurchaseRefunded, PurchaseRefused, PurchaseStatusInput, PurchaseStatusResult, RecoveryBeginResult, RecoveryCompleteResult, WaitForPurchaseInput, isPurchaseCredited, isPurchaseExpired, isPurchaseRefunded, isPurchaseRefused, nothingWasCharged };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { A as ApproveResult, C as ConfirmReceiptResult, M as MountCheckoutOptions, a as CheckoutMountHandle, b as ClientConfig, c as CallOptions, L as LinkDeviceResult, P as PendingCollectResult, D as DestinationsQuery, d as DestinationsResult, B as BalanceResult, E as EnrollmentBeginResult, e as EnrollmentVerifyResult, R as RecoveryBeginResult, f as RecoveryCompleteResult } from './types-CBxpXgAM.js';
2
- export { g as BalanceRow, h as DestinationGame, I as InvoError, i as InvoErrorInfo, j as InvoHooks, k as InvoRequestInfo, l as InvoResponseInfo, m as PendingCollectItem, n as Rail, V as VerificationMethod } from './types-CBxpXgAM.js';
1
+ import { A as ApproveResult, C as ConfirmReceiptResult, P as PurchaseStatusResult, a as PurchaseCredited, b as PurchaseExpired, c as PurchaseRefunded, d as PurchaseRefused, e as CheckoutClientConfig, H as Http, f as PurchaseStatusInput, g as CallOptions, W as WaitForPurchaseInput, M as MountCheckoutOptions, h as CheckoutMountHandle, i as ClientConfig, L as LinkDeviceResult, j as PendingCollectResult, D as DestinationsQuery, k as DestinationsResult, B as BalanceResult, E as EnrollmentBeginResult, l as EnrollmentVerifyResult, R as RecoveryBeginResult, m as RecoveryCompleteResult } from './types-DSLGe_0Z.js';
2
+ export { n as BalanceRow, o as CheckoutPurchaseStatus, p as DestinationGame, I as InvoError, q as InvoErrorInfo, r as InvoHooks, s as InvoRequestInfo, t as InvoResponseInfo, u as PendingCollectItem, v as PurchaseRefusalReason, w as Rail, V as VerificationMethod } from './types-DSLGe_0Z.js';
3
3
 
4
4
  /** The four device-approval flows (`begin.flow`). */
5
5
  type HostedFlow = "transfer" | "send" | "send_receipt" | "transfer_receipt";
@@ -94,6 +94,65 @@ interface ApproveHostedOptions {
94
94
  signal?: AbortSignal;
95
95
  }
96
96
 
97
+ /**
98
+ * The purchase status read: mapping and the guards that go with it.
99
+ *
100
+ * WHY THE ENDPOINT EXISTS. A hosted checkout used to be able to charge a buyer in full,
101
+ * refuse the credit, answer `200` on every route, and close the page on nothing: no coins,
102
+ * no error, no receipt. `GET /api/checkout/sessions/<id>` is INVO's fix for that silence.
103
+ * It always has something true to say, including the case where INVO has the buyer's money
104
+ * and the buyer does not have their coins.
105
+ *
106
+ * ONE RULE RUNS THROUGH THIS FILE: `terminal` is INVO's answer, never ours. It is read
107
+ * straight off the response and never recomputed from `status`, so a status a future
108
+ * backend introduces cannot make a build pinned to this release decide a purchase
109
+ * finished, or finished WELL, on its own.
110
+ */
111
+
112
+ /**
113
+ * The purchase was charged and the coins are in the balance. Show `coinsCredited`,
114
+ * `currencyName` and `newBalance` when it is not null, and close on the buyer's action
115
+ * rather than automatically.
116
+ *
117
+ * It narrows the SHAPE of a result; it is not a way to ask whether polling is over. Use
118
+ * `result.terminal` for that. A status this build does not recognise answers `false` here,
119
+ * so an unknown terminal value is never read as a success.
120
+ */
121
+ declare function isPurchaseCredited(r: PurchaseStatusResult): r is PurchaseCredited;
122
+ /**
123
+ * This purchase will not credit. Show `message` verbatim, show `orderId`, and show
124
+ * **Contact support**. Never close silently. Offer a Try again only when
125
+ * {@link nothingWasCharged} is true.
126
+ */
127
+ declare function isPurchaseRefused(r: PurchaseStatusResult): r is PurchaseRefused;
128
+ /** The money went back to the buyer (a refund, or a reversal by their bank). */
129
+ declare function isPurchaseRefunded(r: PurchaseStatusResult): r is PurchaseRefunded;
130
+ /** The checkout was never paid and can no longer be paid. Offer a new checkout. */
131
+ declare function isPurchaseExpired(r: PurchaseStatusResult): r is PurchaseExpired;
132
+ /**
133
+ * True when INVO has said, in this exact result, that no money was taken: an `expired`
134
+ * checkout, or a refusal coded `PAYMENT_DECLINED` / `PAYMENT_CANCELLED`. Those are the
135
+ * outcomes to put a **Try again** on.
136
+ *
137
+ * FALSE FOR EVERYTHING ELSE, INCLUDING A CODE THIS BUILD HAS NEVER SEEN. Every other
138
+ * refusal happened AFTER the card was charged, and inviting that buyer to pay a second
139
+ * time is the worst thing the page can do. When this is false and the purchase is refused,
140
+ * offer Contact support with the order id and nothing else.
141
+ */
142
+ declare function nothingWasCharged(r: PurchaseStatusResult): boolean;
143
+
144
+ /**
145
+ * @invonetwork/web-sdk — BROWSER entry.
146
+ *
147
+ * InvoClient holds only the short-lived, game-scoped player token (minted
148
+ * server-side by InvoServer.mintPlayerToken) and runs the passkey ceremonies:
149
+ * enroll, approve a send/transfer, and recipient self-claim. It never sees the
150
+ * game secret.
151
+ *
152
+ * Currency purchase has NO browser method — it is server-initiated; the browser
153
+ * only redirects to the checkoutUrl/paymentUrl the server returns.
154
+ */
155
+
97
156
  declare class PlatformCommerceClient {
98
157
  /**
99
158
  * Embed INVO's hosted checkout in an iframe and listen for completion.
@@ -115,6 +174,81 @@ declare class PlatformCommerceClient {
115
174
  */
116
175
  mountCheckout(el: string | HTMLElement, checkoutUrl: string, opts?: MountCheckoutOptions): CheckoutMountHandle;
117
176
  }
177
+ /**
178
+ * Reads what happened to a hosted-checkout currency purchase.
179
+ *
180
+ * Reach it as `invo.checkout` on an {@link InvoClient}, or construct it on its own for a
181
+ * page that has no player token (a return page after the redirect, for instance):
182
+ *
183
+ * ```ts
184
+ * const checkout = new CheckoutClient({ baseUrl: "https://invo.network" });
185
+ * const result = await checkout.waitForPurchase({ sessionId, sessionToken });
186
+ * ```
187
+ *
188
+ * THE CREDENTIAL IS THE SESSION TOKEN, not the player token and not the game secret, so
189
+ * this class needs neither. The session id in the path is an identifier: it says which
190
+ * purchase is being asked about and on its own reads nothing.
191
+ */
192
+ declare class CheckoutClient {
193
+ private readonly http;
194
+ constructor(config: CheckoutClientConfig);
195
+ /**
196
+ * Wrap an `Http` the owning client already built, so `invo.checkout` shares that
197
+ * client's baseUrl, timeout, retry budget and observability hooks.
198
+ *
199
+ * @internal Not part of the public API; it takes an internal type and may change.
200
+ */
201
+ static _withHttp(http: Http): CheckoutClient;
202
+ /**
203
+ * Read a purchase's status once.
204
+ *
205
+ * Answers `200` with a {@link PurchaseStatusResult} for every state of the purchase,
206
+ * including "we have your money and your coins are not there". There is no tenant gate
207
+ * on it: a partner suspended after a buyer's card was charged is exactly the case it
208
+ * exists for.
209
+ *
210
+ * Throws an {@link InvoError} on `401` (no token, bad signature, or a card-setup token:
211
+ * `err.isWrongSessionPurpose`), `403` (a valid token for a DIFFERENT session:
212
+ * `err.isCheckoutSessionMismatch`) and `410` (the token is more than 24 hours past its
213
+ * expiry: `err.isCheckoutSessionExpired`; show the buyer the order id you already have
214
+ * and a Contact support link).
215
+ *
216
+ * Storefront (in-client) purchases are keyed on the partner's own purchase reference
217
+ * rather than on a checkout session, so a read by session id finds nothing and answers
218
+ * `pending`. Do not conclude from that that such a purchase never happened.
219
+ */
220
+ getPurchaseStatus(input: PurchaseStatusInput, opts?: CallOptions): Promise<PurchaseStatusResult>;
221
+ /**
222
+ * Poll {@link getPurchaseStatus} until INVO says the purchase is finished, and return
223
+ * that final result.
224
+ *
225
+ * ```ts
226
+ * const result = await invo.checkout.waitForPurchase({
227
+ * sessionId, sessionToken,
228
+ * intervalMs: 1500,
229
+ * timeoutMs: 300_000,
230
+ * signal: controller.signal,
231
+ * onUpdate: (r) => render(r), // keep the modal open on every non-terminal read
232
+ * });
233
+ * if (isPurchaseCredited(result)) showCoins(result.coinsCredited, result.currencyName);
234
+ * else if (result.message) showMessage(result.message, result.orderId); // verbatim
235
+ * ```
236
+ *
237
+ * IT STOPS ON `result.terminal` AND ON NOTHING ELSE. `terminal` is INVO's word, read off
238
+ * the response; this loop never recomputes it from `status`, so a status a later backend
239
+ * introduces cannot end a wait here as a success. `paid_pending_credit` is deliberately
240
+ * not terminal and is never promoted to a failure by age: INVO's reconciler recovers a
241
+ * stalled credit, and telling a buyer they lost money they are about to receive would
242
+ * be a fresh lie in place of the old silence.
243
+ *
244
+ * A transient failure (network, timeout, 429, 5xx) is polled through rather than raised;
245
+ * a `401`, `403` or `410` is raised at once. On the cap it returns the LAST result it
246
+ * read, whose `terminal` is false. Nothing is guessed and nothing is thrown, so the page
247
+ * keeps showing the buyer what INVO last said. If it never got a single answer, the last
248
+ * transport failure is thrown.
249
+ */
250
+ waitForPurchase(input: WaitForPurchaseInput): Promise<PurchaseStatusResult>;
251
+ }
118
252
  declare class InvoClient {
119
253
  private readonly http;
120
254
  private auth;
@@ -129,6 +263,15 @@ declare class InvoClient {
129
263
  * {@link PlatformCommerceClient}.
130
264
  */
131
265
  readonly platformCommerce: PlatformCommerceClient;
266
+ /**
267
+ * Read what happened to a hosted-checkout currency purchase:
268
+ * `invo.checkout.getPurchaseStatus({ sessionId, sessionToken })` once, or
269
+ * `invo.checkout.waitForPurchase({ ... })` until INVO says it is finished.
270
+ *
271
+ * It authenticates with the SESSION token, not this client's player token, so a page
272
+ * that has no player token can build a {@link CheckoutClient} directly instead.
273
+ */
274
+ readonly checkout: CheckoutClient;
132
275
  constructor(config: ClientConfig);
133
276
  private assertWebAuthn;
134
277
  /**
@@ -296,4 +439,4 @@ declare class InvoClient {
296
439
  private confirmReceipt;
297
440
  }
298
441
 
299
- export { type ApproveHostedOptions, type ApproveHostedResult, ApproveResult, BalanceResult, CallOptions, CheckoutMountHandle, ClientConfig, ConfirmReceiptResult, DestinationsQuery, DestinationsResult, EnrollmentBeginResult, type EnrollmentDecision, type EnrollmentRespond, EnrollmentVerifyResult, type HostedApprovalStatus, type HostedEnrollment, type HostedEnrollmentInput, type HostedFlow, InvoClient, LinkDeviceResult, MountCheckoutOptions, PendingCollectResult, PlatformCommerceClient, RecoveryBeginResult, RecoveryCompleteResult };
442
+ export { type ApproveHostedOptions, type ApproveHostedResult, ApproveResult, BalanceResult, CallOptions, CheckoutClient, CheckoutClientConfig, CheckoutMountHandle, ClientConfig, ConfirmReceiptResult, DestinationsQuery, DestinationsResult, EnrollmentBeginResult, type EnrollmentDecision, type EnrollmentRespond, EnrollmentVerifyResult, type HostedApprovalStatus, type HostedEnrollment, type HostedEnrollmentInput, type HostedFlow, InvoClient, LinkDeviceResult, MountCheckoutOptions, PendingCollectResult, PlatformCommerceClient, PurchaseCredited, PurchaseExpired, PurchaseRefunded, PurchaseRefused, PurchaseStatusInput, PurchaseStatusResult, RecoveryBeginResult, RecoveryCompleteResult, WaitForPurchaseInput, isPurchaseCredited, isPurchaseExpired, isPurchaseRefunded, isPurchaseRefused, nothingWasCharged };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { InvoError, assertSecureBaseUrl, Http, toDestinationsResult } from './chunk-L4A6OV54.js';
2
- export { InvoError } from './chunk-L4A6OV54.js';
1
+ import { InvoError, assertSecureBaseUrl, Http, toDestinationsResult } from './chunk-ZDBU3L4T.js';
2
+ export { InvoError } from './chunk-ZDBU3L4T.js';
3
3
 
4
4
  // src/shared/webauthn.ts
5
5
  function malformedOptions(field) {
@@ -685,6 +685,49 @@ async function runHostedApproval(opts, api, deps = {}) {
685
685
  });
686
686
  }
687
687
 
688
+ // src/shared/purchase-status.ts
689
+ function str(v) {
690
+ return typeof v === "string" ? v : v === null || v === void 0 ? null : String(v);
691
+ }
692
+ function toPurchaseStatusResult(raw, sessionId) {
693
+ return {
694
+ status: String(raw["status"] ?? ""),
695
+ // INVO SAYS, AND ONLY AN EXPLICIT `true` SAYS IT. A missing or malformed field reads
696
+ // false, which keeps a poll running; the alternative, guessing terminality from
697
+ // `status`, is how an old SDK declares a future status finished.
698
+ terminal: raw["terminal"] === true,
699
+ orderId: str(raw["order_id"]),
700
+ sessionId: String(raw["session_id"] ?? sessionId),
701
+ coinsCredited: str(raw["coins_credited"]),
702
+ transactionId: str(raw["transaction_id"]),
703
+ newBalance: str(raw["new_balance"]),
704
+ reasonCode: str(raw["reason_code"]),
705
+ message: str(raw["message"]),
706
+ amountChargedUsd: str(raw["amount_charged_usd"]),
707
+ listedUsd: str(raw["listed_usd"]),
708
+ currencyName: str(raw["currency_name"]),
709
+ raw
710
+ };
711
+ }
712
+ function isPurchaseCredited(r) {
713
+ return r.status === "credited";
714
+ }
715
+ function isPurchaseRefused(r) {
716
+ return r.status === "refused";
717
+ }
718
+ function isPurchaseRefunded(r) {
719
+ return r.status === "refunded";
720
+ }
721
+ function isPurchaseExpired(r) {
722
+ return r.status === "expired";
723
+ }
724
+ var NOTHING_CHARGED_REASONS = /* @__PURE__ */ new Set(["PAYMENT_DECLINED", "PAYMENT_CANCELLED"]);
725
+ function nothingWasCharged(r) {
726
+ if (r.status === "expired") return true;
727
+ if (r.status !== "refused") return false;
728
+ return r.reasonCode !== null && NOTHING_CHARGED_REASONS.has(r.reasonCode);
729
+ }
730
+
688
731
  // src/index.ts
689
732
  function toPendingCollectItem(row) {
690
733
  return {
@@ -816,6 +859,163 @@ var PlatformCommerceClient = class {
816
859
  };
817
860
  }
818
861
  };
862
+ var DEFAULT_PURCHASE_POLL_INTERVAL_MS = 1500;
863
+ var DEFAULT_PURCHASE_POLL_TIMEOUT_MS = 18e4;
864
+ function pollSleep(ms, signal) {
865
+ return new Promise((resolve) => {
866
+ if (signal?.aborted) return resolve();
867
+ const timer = setTimeout(done, ms);
868
+ const onAbort = () => done();
869
+ function done() {
870
+ clearTimeout(timer);
871
+ signal?.removeEventListener("abort", onAbort);
872
+ resolve();
873
+ }
874
+ signal?.addEventListener("abort", onAbort, { once: true });
875
+ });
876
+ }
877
+ function isTransientPollFailure(err) {
878
+ if (!(err instanceof InvoError)) return false;
879
+ if (err.code === "ABORTED") return false;
880
+ return err.status === 0 || err.status === 429 || err.status >= 500;
881
+ }
882
+ var CheckoutClient = class _CheckoutClient {
883
+ constructor(config) {
884
+ if (!config?.baseUrl) throw new Error("CheckoutClient requires a `baseUrl`.");
885
+ assertSecureBaseUrl(config.baseUrl);
886
+ this.http = new Http({
887
+ baseUrl: config.baseUrl,
888
+ timeoutMs: config.timeoutMs,
889
+ fetchImpl: config.fetch,
890
+ maxRetries: config.maxRetries,
891
+ retryBaseDelayMs: config.retryBaseDelayMs,
892
+ hooks: config.hooks
893
+ });
894
+ }
895
+ /**
896
+ * Wrap an `Http` the owning client already built, so `invo.checkout` shares that
897
+ * client's baseUrl, timeout, retry budget and observability hooks.
898
+ *
899
+ * @internal Not part of the public API; it takes an internal type and may change.
900
+ */
901
+ static _withHttp(http) {
902
+ const client = Object.create(_CheckoutClient.prototype);
903
+ client.http = http;
904
+ return client;
905
+ }
906
+ /**
907
+ * Read a purchase's status once.
908
+ *
909
+ * Answers `200` with a {@link PurchaseStatusResult} for every state of the purchase,
910
+ * including "we have your money and your coins are not there". There is no tenant gate
911
+ * on it: a partner suspended after a buyer's card was charged is exactly the case it
912
+ * exists for.
913
+ *
914
+ * Throws an {@link InvoError} on `401` (no token, bad signature, or a card-setup token:
915
+ * `err.isWrongSessionPurpose`), `403` (a valid token for a DIFFERENT session:
916
+ * `err.isCheckoutSessionMismatch`) and `410` (the token is more than 24 hours past its
917
+ * expiry: `err.isCheckoutSessionExpired`; show the buyer the order id you already have
918
+ * and a Contact support link).
919
+ *
920
+ * Storefront (in-client) purchases are keyed on the partner's own purchase reference
921
+ * rather than on a checkout session, so a read by session id finds nothing and answers
922
+ * `pending`. Do not conclude from that that such a purchase never happened.
923
+ */
924
+ async getPurchaseStatus(input, opts) {
925
+ const sessionId = String(input?.sessionId ?? "").trim();
926
+ const sessionToken = String(input?.sessionToken ?? "").trim();
927
+ if (!sessionId) {
928
+ throw new InvoError({
929
+ message: "getPurchaseStatus requires `sessionId` (from createCheckout).",
930
+ code: "INVALID_INPUT",
931
+ status: 0
932
+ });
933
+ }
934
+ if (!sessionToken) {
935
+ throw new InvoError({
936
+ message: "getPurchaseStatus requires `sessionToken`. The session token is the credential; the id in the path is not.",
937
+ code: "INVALID_INPUT",
938
+ status: 0
939
+ });
940
+ }
941
+ const raw = await this.http.get(
942
+ `/api/checkout/sessions/${encodeURIComponent(sessionId)}`,
943
+ { kind: "bearer", token: sessionToken },
944
+ { signal: opts?.signal }
945
+ );
946
+ return toPurchaseStatusResult(raw, sessionId);
947
+ }
948
+ /**
949
+ * Poll {@link getPurchaseStatus} until INVO says the purchase is finished, and return
950
+ * that final result.
951
+ *
952
+ * ```ts
953
+ * const result = await invo.checkout.waitForPurchase({
954
+ * sessionId, sessionToken,
955
+ * intervalMs: 1500,
956
+ * timeoutMs: 300_000,
957
+ * signal: controller.signal,
958
+ * onUpdate: (r) => render(r), // keep the modal open on every non-terminal read
959
+ * });
960
+ * if (isPurchaseCredited(result)) showCoins(result.coinsCredited, result.currencyName);
961
+ * else if (result.message) showMessage(result.message, result.orderId); // verbatim
962
+ * ```
963
+ *
964
+ * IT STOPS ON `result.terminal` AND ON NOTHING ELSE. `terminal` is INVO's word, read off
965
+ * the response; this loop never recomputes it from `status`, so a status a later backend
966
+ * introduces cannot end a wait here as a success. `paid_pending_credit` is deliberately
967
+ * not terminal and is never promoted to a failure by age: INVO's reconciler recovers a
968
+ * stalled credit, and telling a buyer they lost money they are about to receive would
969
+ * be a fresh lie in place of the old silence.
970
+ *
971
+ * A transient failure (network, timeout, 429, 5xx) is polled through rather than raised;
972
+ * a `401`, `403` or `410` is raised at once. On the cap it returns the LAST result it
973
+ * read, whose `terminal` is false. Nothing is guessed and nothing is thrown, so the page
974
+ * keeps showing the buyer what INVO last said. If it never got a single answer, the last
975
+ * transport failure is thrown.
976
+ */
977
+ async waitForPurchase(input) {
978
+ const intervalMs = Math.max(0, input?.intervalMs ?? DEFAULT_PURCHASE_POLL_INTERVAL_MS);
979
+ const timeoutMs = Math.max(0, input?.timeoutMs ?? DEFAULT_PURCHASE_POLL_TIMEOUT_MS);
980
+ const maxAttempts = input?.maxAttempts === void 0 ? Number.POSITIVE_INFINITY : Math.max(1, input.maxAttempts);
981
+ const deadline = Date.now() + timeoutMs;
982
+ const signal = input?.signal;
983
+ let last;
984
+ let lastFailure;
985
+ for (let attempts = 0; ; ) {
986
+ if (signal?.aborted) {
987
+ throw new InvoError({
988
+ message: "waitForPurchase was aborted",
989
+ code: "ABORTED",
990
+ status: 0
991
+ });
992
+ }
993
+ attempts += 1;
994
+ try {
995
+ const result = await this.getPurchaseStatus(input, { signal });
996
+ last = result;
997
+ lastFailure = void 0;
998
+ try {
999
+ input?.onUpdate?.(result);
1000
+ } catch {
1001
+ }
1002
+ if (result.terminal) return result;
1003
+ } catch (err) {
1004
+ if (!isTransientPollFailure(err)) throw err;
1005
+ lastFailure = err;
1006
+ }
1007
+ if (attempts >= maxAttempts) break;
1008
+ if (Date.now() + intervalMs >= deadline) break;
1009
+ await pollSleep(intervalMs, signal);
1010
+ }
1011
+ if (last) return last;
1012
+ throw lastFailure instanceof Error ? lastFailure : new InvoError({
1013
+ message: "waitForPurchase could not read the purchase status before the cap.",
1014
+ code: "PURCHASE_STATUS_UNAVAILABLE",
1015
+ status: 0
1016
+ });
1017
+ }
1018
+ };
819
1019
  var InvoClient = class {
820
1020
  constructor(config) {
821
1021
  /**
@@ -840,6 +1040,7 @@ var InvoClient = class {
840
1040
  });
841
1041
  this.auth = { kind: "bearer", token: config.token };
842
1042
  this.refreshToken = config.refreshToken;
1043
+ this.checkout = CheckoutClient._withHttp(this.http);
843
1044
  }
844
1045
  assertWebAuthn() {
845
1046
  if (typeof navigator === "undefined" || !navigator.credentials) {
@@ -1224,6 +1425,6 @@ var InvoClient = class {
1224
1425
  }
1225
1426
  };
1226
1427
 
1227
- export { InvoClient, PlatformCommerceClient };
1428
+ export { CheckoutClient, InvoClient, PlatformCommerceClient, isPurchaseCredited, isPurchaseExpired, isPurchaseRefunded, isPurchaseRefused, nothingWasCharged };
1228
1429
  //# sourceMappingURL=index.js.map
1229
1430
  //# sourceMappingURL=index.js.map
package/dist/server.cjs CHANGED
@@ -671,6 +671,33 @@ var InvoError = class _InvoError extends Error {
671
671
  get isInvalidInput() {
672
672
  return this.code === "INVALID_INPUT";
673
673
  }
674
+ // ---- Checkout session reads (the purchase status read) ----
675
+ /**
676
+ * True when a session token was refused because it belongs to a DIFFERENT checkout
677
+ * session than the id in the path (`SESSION_MISMATCH`, 403). The token is the
678
+ * credential and the id is only a label, so the two have to agree; pair a `sessionId`
679
+ * with the `sessionToken` minted for it.
680
+ */
681
+ get isCheckoutSessionMismatch() {
682
+ return this.code === "SESSION_MISMATCH";
683
+ }
684
+ /**
685
+ * True when a token minted to SAVE A CARD was used where a purchase token belongs
686
+ * (`WRONG_SESSION_PURPOSE`, 401). A card setup session settles nothing and has no
687
+ * purchase to report on.
688
+ */
689
+ get isWrongSessionPurpose() {
690
+ return this.code === "WRONG_SESSION_PURPOSE";
691
+ }
692
+ /**
693
+ * True when a checkout session token is too far past its expiry to answer with
694
+ * (`SESSION_EXPIRED`, 410). A lapsed token still reads its own purchase for a bounded
695
+ * window, because a charge outlives a 15 minute link; past that, show the buyer the
696
+ * order id you already hold and a Contact support link rather than a blank screen.
697
+ */
698
+ get isCheckoutSessionExpired() {
699
+ return this.code === "SESSION_EXPIRED";
700
+ }
674
701
  /** Seconds to wait before retrying, when the backend throttled the call (429 `retry_after`). */
675
702
  get retryAfter() {
676
703
  const v = this.bodyObject()["retry_after"];
@@ -954,7 +981,7 @@ function toDestinationsResult(raw, direction) {
954
981
  }
955
982
 
956
983
  // src/version.ts
957
- var SDK_VERSION = "3.10.0";
984
+ var SDK_VERSION = "3.11.0";
958
985
 
959
986
  // src/shared/types.ts
960
987
  function isRefundPendingApproval(r) {
@@ -1163,6 +1190,19 @@ function assertE164(value, label) {
1163
1190
  throw invalidInput(label, value, 'must be an E.164 phone number, e.g. "+15555550100"');
1164
1191
  }
1165
1192
  }
1193
+ function sessionTokenFromCreateCheckout(raw, checkoutUrl) {
1194
+ const field = raw["session_token"];
1195
+ if (typeof field === "string" && field.trim()) return field;
1196
+ return sessionTokenFromCheckoutUrl(checkoutUrl);
1197
+ }
1198
+ function sessionTokenFromCheckoutUrl(checkoutUrl) {
1199
+ try {
1200
+ const value = new URL(checkoutUrl).searchParams.get("session");
1201
+ return value && value.trim() ? value : void 0;
1202
+ } catch {
1203
+ return void 0;
1204
+ }
1205
+ }
1166
1206
  function toOrderDetails(raw) {
1167
1207
  return {
1168
1208
  order: raw["order"] ?? {},
@@ -2720,11 +2760,16 @@ var InvoServer = class {
2720
2760
  { signal: opts?.signal }
2721
2761
  // not idempotent — never auto-retried
2722
2762
  );
2763
+ const checkoutUrl = requireField(raw["checkout_url"], "checkout_url", raw);
2723
2764
  return {
2724
2765
  sessionId: String(raw["session_id"] ?? ""),
2725
- checkoutUrl: requireField(raw["checkout_url"], "checkout_url", raw),
2766
+ checkoutUrl,
2726
2767
  expiresAt: String(raw["expires_at"] ?? ""),
2727
2768
  expiresInSeconds: Number(raw["expires_in_seconds"] ?? 0),
2769
+ // INVO's own `session_token` field, falling back to the `checkout_url` query string
2770
+ // for a backend older than commit 856fa266. Either way a server that wants to read
2771
+ // the purchase status later does not have to parse a URL itself.
2772
+ sessionToken: sessionTokenFromCreateCheckout(raw, checkoutUrl),
2728
2773
  raw
2729
2774
  };
2730
2775
  }