@invonetwork/web-sdk 3.6.0 → 3.8.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/server.js CHANGED
@@ -1,7 +1,9 @@
1
- import { InvoError, assertSecureBaseUrl, Http, toDestinationsResult } from './chunk-MBKE6ULW.js';
2
- export { InvoError } from './chunk-MBKE6ULW.js';
1
+ import { InvoError, assertSecureBaseUrl, Http, toDestinationsResult } from './chunk-HYGBTUEJ.js';
2
+ export { InvoError } from './chunk-HYGBTUEJ.js';
3
3
  import { createHmac, timingSafeEqual } from 'crypto';
4
4
 
5
+ // src/version.ts
6
+ var SDK_VERSION = "3.8.0";
5
7
  var DEFAULT_TOLERANCE_SEC = 300;
6
8
  var ENCODER = new TextEncoder();
7
9
  function toBytes(body) {
@@ -167,7 +169,7 @@ async function hmacHexSubtle(secret, message) {
167
169
  }
168
170
 
169
171
  // src/server.ts
170
- var DEFAULT_UA = "invonetwork-web-sdk/3.0.0 (+https://invo.network)";
172
+ var DEFAULT_UA = `invonetwork-web-sdk/${SDK_VERSION} (+https://invo.network)`;
171
173
  var MAX_USD_AMOUNT = 999.99;
172
174
  var MAX_ITEM_PRICE = 999999.99;
173
175
  function invalidInput(label, value, why) {
@@ -304,6 +306,133 @@ function toPhoneShareApproveResult(raw) {
304
306
  raw
305
307
  };
306
308
  }
309
+ var DEVICE_APPROVAL_FLOWS = /* @__PURE__ */ new Set([
310
+ "transfer",
311
+ "send",
312
+ "send_receipt",
313
+ "transfer_receipt"
314
+ ]);
315
+ var DEVICE_APPROVAL_CHANNELS = /* @__PURE__ */ new Set([
316
+ "qr",
317
+ "app_browser",
318
+ "popup"
319
+ ]);
320
+ var DEVICE_POLL_OUTCOME_TOKENS = /* @__PURE__ */ new Set([
321
+ "authorization_pending",
322
+ "slow_down",
323
+ "expired_token",
324
+ "access_denied"
325
+ ]);
326
+ function deviceApprovalSettlePath(flow, transactionId) {
327
+ const id = encodeURIComponent(transactionId);
328
+ switch (flow) {
329
+ case "transfer":
330
+ return `/api/sdk/transfers/${id}/approve`;
331
+ case "send":
332
+ return `/api/sdk/send/${id}/approve`;
333
+ case "send_receipt":
334
+ return `/api/sdk/send/${id}/confirm-receipt`;
335
+ case "transfer_receipt":
336
+ return `/api/sdk/transfers/${id}/confirm-receipt`;
337
+ }
338
+ }
339
+ var DEVICE_SETTLED_STATUSES = {
340
+ // Sender's approve: anything from "approved, awaiting the claim" onwards.
341
+ transfer: /* @__PURE__ */ new Set([
342
+ "pending_claim",
343
+ "verified",
344
+ "pin_verified_awaiting_claim",
345
+ "completed",
346
+ "distributed"
347
+ ]),
348
+ send: /* @__PURE__ */ new Set([
349
+ "pending_claim",
350
+ "verified",
351
+ "pin_verified_awaiting_claim",
352
+ "completed",
353
+ "distributed"
354
+ ]),
355
+ // Recipient's collect: only a finished transaction is past it. `pending_claim` and
356
+ // `verified` are this step's own gate statuses, not states beyond it.
357
+ send_receipt: /* @__PURE__ */ new Set(["completed", "distributed"]),
358
+ transfer_receipt: /* @__PURE__ */ new Set(["completed", "distributed"])
359
+ };
360
+ function isPastThisStep(flow, currentStatus) {
361
+ return DEVICE_SETTLED_STATUSES[flow].has(currentStatus.trim().toLowerCase());
362
+ }
363
+ function assertPlayerToken(playerToken) {
364
+ if (typeof playerToken !== "string" || !playerToken.trim()) {
365
+ throw invalidInput("playerToken", playerToken, "is required (the player's session token, not the game secret)");
366
+ }
367
+ }
368
+ function assertDeviceApprovalFlow(flow) {
369
+ if (typeof flow !== "string" || !DEVICE_APPROVAL_FLOWS.has(flow)) {
370
+ throw invalidInput("flow", flow, 'must be "transfer" | "send" | "send_receipt" | "transfer_receipt"');
371
+ }
372
+ }
373
+ function toDeviceApprovalGrant(raw) {
374
+ return {
375
+ deviceCode: requireField(raw["device_code"], "device_code", raw),
376
+ userCode: String(raw["user_code"] ?? ""),
377
+ verificationUri: String(raw["verification_uri"] ?? ""),
378
+ verificationUriComplete: requireField(raw["verification_uri_complete"], "verification_uri_complete", raw),
379
+ expiresIn: Number(raw["expires_in"] ?? 0) || 0,
380
+ interval: Math.max(1, Number(raw["interval"] ?? 5) || 5),
381
+ channel: String(raw["channel"] ?? "qr"),
382
+ raw
383
+ };
384
+ }
385
+ function toDeviceApprovalEnrollment(raw) {
386
+ return {
387
+ state: String(raw["state"] ?? ""),
388
+ deviceLabel: String(raw["device_label"] ?? ""),
389
+ matchCode: String(raw["match_code"] ?? ""),
390
+ recovery: raw["recovery"] === true,
391
+ requestedAt: raw["requested_at"] ?? null,
392
+ raw
393
+ };
394
+ }
395
+ function toDevicePollOutcome(token, body) {
396
+ const interval = Number(body["interval"]);
397
+ const enrollment = body["enrollment"];
398
+ return {
399
+ status: token,
400
+ interval: Number.isFinite(interval) && interval > 0 ? interval : void 0,
401
+ enrollment: enrollment && typeof enrollment === "object" ? toDeviceApprovalEnrollment(enrollment) : void 0,
402
+ raw: body
403
+ };
404
+ }
405
+ function toDeviceApprovalSettleResult(raw, input) {
406
+ const holdReason = raw["error_code"] ?? raw["code"];
407
+ return {
408
+ status: String(raw["status"] ?? ""),
409
+ transactionId: String(raw["transaction_id"] ?? input.transactionId),
410
+ flow: input.flow,
411
+ alreadySettled: false,
412
+ next: raw["next"],
413
+ claimCode: raw["claim_code"],
414
+ claimCodeExpiresAt: raw["claim_code_expires_at"],
415
+ amountReceived: raw["amount_received"] == null ? void 0 : String(raw["amount_received"]),
416
+ holdReason: typeof holdReason === "string" ? holdReason : void 0,
417
+ risk: raw["risk"],
418
+ guardianApproval: raw["guardian_approval"] ?? void 0,
419
+ pollEndpoint: raw["poll_endpoint"],
420
+ raw
421
+ };
422
+ }
423
+ function sleepFor(ms, signal) {
424
+ return new Promise((resolve) => {
425
+ if (signal?.aborted) return resolve();
426
+ const timer = setTimeout(done, ms);
427
+ const onAbort = () => done();
428
+ function done() {
429
+ clearTimeout(timer);
430
+ signal?.removeEventListener("abort", onAbort);
431
+ resolve();
432
+ }
433
+ signal?.addEventListener("abort", onAbort, { once: true });
434
+ });
435
+ }
307
436
  function toCurrencyBalance(row) {
308
437
  return {
309
438
  currencyId: row["currency_id"] ?? "",
@@ -520,6 +649,855 @@ var PlatformCommerceServer = class {
520
649
  };
521
650
  }
522
651
  };
652
+ var SUBSCRIPTION_MAX_USD = 999999.99;
653
+ var SUBSCRIPTION_INTERVALS = /* @__PURE__ */ new Set(["month", "year"]);
654
+ var SANDBOX_FAILURE_OUTCOMES = /* @__PURE__ */ new Set([
655
+ "card_declined",
656
+ "insufficient_funds",
657
+ "error"
658
+ ]);
659
+ function assertClientRequestId(value, label) {
660
+ if (typeof value !== "string" || !value.trim()) throw invalidInput(label, value, "is required");
661
+ if (value.length > 255) throw invalidInput(label, value, "must be at most 255 characters");
662
+ if (/^sub_/i.test(value)) throw invalidInput(label, value, 'must not begin with "sub_" (reserved)');
663
+ }
664
+ function assertSubscriptionId(value) {
665
+ if (typeof value !== "string" || !value.trim()) {
666
+ throw invalidInput("subscriptionId", value, "is required");
667
+ }
668
+ }
669
+ function subscriptionMoney(value, label) {
670
+ const n = parseMoney(value, SUBSCRIPTION_MAX_USD, label);
671
+ return typeof value === "number" ? n.toFixed(2) : value;
672
+ }
673
+ function toSavedCard(row) {
674
+ if (!row || typeof row !== "object") return null;
675
+ const r = row;
676
+ return {
677
+ id: Number(r["id"]),
678
+ lastFour: String(r["last_four"] ?? ""),
679
+ brand: String(r["brand"] ?? ""),
680
+ expMonth: Number(r["exp_month"] ?? 0),
681
+ expYear: Number(r["exp_year"] ?? 0),
682
+ createdAt: String(r["created_at"] ?? ""),
683
+ raw: r
684
+ };
685
+ }
686
+ function nullableString(v) {
687
+ return v == null ? null : String(v);
688
+ }
689
+ function toSubscription(row) {
690
+ const r = row && typeof row === "object" ? row : {};
691
+ const share = r["revenue_share"];
692
+ const consent = r["consent"] ?? {};
693
+ return {
694
+ subscriptionId: String(r["subscription_id"] ?? ""),
695
+ gameId: String(r["game_id"] ?? ""),
696
+ playerId: Number(r["player_id"] ?? 0),
697
+ clientRequestId: String(r["client_request_id"] ?? ""),
698
+ status: String(r["status"] ?? ""),
699
+ amountUsd: String(r["amount_usd"] ?? ""),
700
+ pendingAmountUsd: nullableString(r["pending_amount_usd"]),
701
+ interval: String(r["interval"] ?? "month"),
702
+ intervalCount: Number(r["interval_count"] ?? 1),
703
+ itemId: String(r["item_id"] ?? ""),
704
+ itemName: nullableString(r["item_name"]),
705
+ currentPeriodStart: String(r["current_period_start"] ?? ""),
706
+ currentPeriodEnd: String(r["current_period_end"] ?? ""),
707
+ periodSeq: Number(r["period_seq"] ?? 0),
708
+ nextChargeAt: nullableString(r["next_charge_at"]),
709
+ cancelAtPeriodEnd: r["cancel_at_period_end"] === true,
710
+ trialEnd: nullableString(r["trial_end"]),
711
+ canceledAt: nullableString(r["canceled_at"]),
712
+ endedAt: nullableString(r["ended_at"]),
713
+ walletOnly: r["wallet_only"] === true,
714
+ hasPaymentMethod: r["has_payment_method"] === true,
715
+ fundingRail: String(r["funding_rail"] ?? "card"),
716
+ steamAgreementStatus: nullableString(r["steam_agreement_status"]),
717
+ metadata: r["metadata"] && typeof r["metadata"] === "object" ? r["metadata"] : null,
718
+ consent: {
719
+ consent_at: nullableString(consent["consent_at"]),
720
+ consent_ip: nullableString(consent["consent_ip"]),
721
+ consent_user_agent: nullableString(consent["consent_user_agent"]),
722
+ disclosed_amount_usd: nullableString(consent["disclosed_amount_usd"]),
723
+ disclosed_interval: nullableString(consent["disclosed_interval"]),
724
+ terms_version: nullableString(consent["terms_version"])
725
+ },
726
+ createdAt: String(r["created_at"] ?? ""),
727
+ updatedAt: String(r["updated_at"] ?? ""),
728
+ revenueShare: share && typeof share === "object" ? {
729
+ recipientPlayerId: Number(share["recipient_player_id"] ?? 0),
730
+ percent: String(share["percent"] ?? ""),
731
+ // Attribution only: INVO never pays the recipient. Read the wire value, never assume.
732
+ settledByInvo: share["settled_by_invo"] === true
733
+ } : null,
734
+ paidThrough: nullableString(r["paid_through"]),
735
+ amountCoinsEstimate: r["amount_coins_estimate"] == null ? void 0 : String(r["amount_coins_estimate"]),
736
+ raw: r
737
+ };
738
+ }
739
+ function toFirstCharge(row) {
740
+ const r = row && typeof row === "object" ? row : {};
741
+ return {
742
+ status: String(r["status"] ?? "pending"),
743
+ amountUsd: nullableString(r["amount_usd"]),
744
+ paidPeriodSeq: typeof r["paid_period_seq"] === "number" ? r["paid_period_seq"] : null,
745
+ paidThrough: nullableString(r["paid_through"]),
746
+ failureCode: nullableString(r["failure_code"]),
747
+ nextRetryAt: nullableString(r["next_retry_at"]),
748
+ confirmationUrl: nullableString(r["confirmation_url"]),
749
+ expiresAt: nullableString(r["expires_at"]),
750
+ message: nullableString(r["message"]),
751
+ raw: r
752
+ };
753
+ }
754
+ function toSubscriptionResult(raw) {
755
+ return {
756
+ status: String(raw["status"] ?? ""),
757
+ idempotentReplay: raw["idempotent_replay"] === true,
758
+ subscription: toSubscription(raw["subscription"]),
759
+ card: toSavedCard(raw["card"]),
760
+ firstCharge: toFirstCharge(raw["first_charge"]),
761
+ warning: typeof raw["warning"] === "string" ? raw["warning"] : void 0,
762
+ raw
763
+ };
764
+ }
765
+ function toSandboxClockState(row) {
766
+ if (!row || typeof row !== "object") return null;
767
+ const r = row;
768
+ return {
769
+ status: String(r["status"] ?? ""),
770
+ periodSeq: Number(r["period_seq"] ?? 0),
771
+ currentPeriodStart: nullableString(r["current_period_start"]),
772
+ currentPeriodEnd: nullableString(r["current_period_end"]),
773
+ nextChargeAt: nullableString(r["next_charge_at"]),
774
+ trialEnd: nullableString(r["trial_end"]),
775
+ cancelAtPeriodEnd: r["cancel_at_period_end"] === true,
776
+ walletOnly: r["wallet_only"] === true,
777
+ hasPaymentMethod: r["has_payment_method"] === true,
778
+ amountUsd: String(r["amount_usd"] ?? ""),
779
+ raw: r
780
+ };
781
+ }
782
+ function optNumber(v) {
783
+ return typeof v === "number" && Number.isFinite(v) ? v : void 0;
784
+ }
785
+ function toSandboxClockResult(raw) {
786
+ const before = toSandboxClockState(raw["before"]);
787
+ const after = toSandboxClockState(raw["after"]);
788
+ const stats = raw["engine_stats"];
789
+ return {
790
+ status: String(raw["status"] ?? ""),
791
+ action: String(raw["action"] ?? ""),
792
+ // advance-clock reports before/after rather than a `subscription` block; surface
793
+ // `after` there so every tool answers "where is the clock now" in one place.
794
+ subscription: toSandboxClockState(raw["subscription"]) ?? after,
795
+ before: before ?? void 0,
796
+ after: after ?? void 0,
797
+ intervals: optNumber(raw["intervals"]),
798
+ intervalsAppliedToWindow: optNumber(raw["intervals_applied_to_window"]),
799
+ windowMoved: typeof raw["window_moved"] === "boolean" ? raw["window_moved"] : void 0,
800
+ windowAlreadyElapsed: typeof raw["window_already_elapsed"] === "boolean" ? raw["window_already_elapsed"] : void 0,
801
+ engineStats: stats && typeof stats === "object" ? stats : void 0,
802
+ periodSeq: optNumber(raw["period_seq"]),
803
+ attemptNo: optNumber(raw["attempt_no"]),
804
+ amountUsd: raw["amount_usd"] == null ? void 0 : String(raw["amount_usd"]),
805
+ amountCoins: raw["amount_coins"] == null ? void 0 : String(raw["amount_coins"]),
806
+ retired: typeof raw["retired"] === "boolean" ? raw["retired"] : void 0,
807
+ retryBudgetUsed: optNumber(raw["retry_budget_used"]),
808
+ retryScheduleDays: Array.isArray(raw["retry_schedule_days"]) ? raw["retry_schedule_days"].map(Number) : void 0,
809
+ retriesRemaining: optNumber(raw["retries_remaining"]),
810
+ authChallengesUsed: optNumber(raw["auth_challenges_used"]),
811
+ maxAuthChallenges: optNumber(raw["max_auth_challenges"]),
812
+ downgradedToDecline: typeof raw["downgraded_to_decline"] === "boolean" ? raw["downgraded_to_decline"] : void 0,
813
+ note: typeof raw["note"] === "string" ? raw["note"] : void 0,
814
+ raw
815
+ };
816
+ }
817
+ function subscriptionBaseBody(input) {
818
+ assertClientRequestId(input.clientRequestId, "clientRequestId");
819
+ for (const [k, v] of [
820
+ ["playerEmail", input.playerEmail],
821
+ ["playerName", input.playerName],
822
+ ["itemId", input.itemId]
823
+ ]) {
824
+ if (typeof v !== "string" || !v.trim()) throw invalidInput(k, v, "is required");
825
+ }
826
+ if (input.interval !== void 0 && !SUBSCRIPTION_INTERVALS.has(input.interval)) {
827
+ throw invalidInput("interval", input.interval, 'must be "month" or "year"');
828
+ }
829
+ if (input.playerPhone !== void 0) assertE164(input.playerPhone, "playerPhone");
830
+ const body = {
831
+ client_request_id: input.clientRequestId,
832
+ player_email: input.playerEmail,
833
+ player_name: input.playerName,
834
+ item_id: input.itemId,
835
+ amount_usd: subscriptionMoney(input.amountUsd, "amountUsd")
836
+ };
837
+ if (input.playerPhone) body["player_phone"] = input.playerPhone;
838
+ if (input.itemName) body["item_name"] = input.itemName;
839
+ if (input.interval) body["interval"] = input.interval;
840
+ if (input.metadata) body["metadata"] = input.metadata;
841
+ if (input.consent) {
842
+ const c = input.consent;
843
+ const consent = {};
844
+ if (c.consentAt !== void 0) consent["consent_at"] = c.consentAt;
845
+ if (c.consentIp !== void 0) consent["consent_ip"] = c.consentIp;
846
+ if (c.consentUserAgent !== void 0) consent["consent_user_agent"] = c.consentUserAgent;
847
+ if (c.disclosedAmountUsd !== void 0) consent["disclosed_amount_usd"] = c.disclosedAmountUsd;
848
+ if (c.disclosedInterval !== void 0) consent["disclosed_interval"] = c.disclosedInterval;
849
+ if (c.termsVersion !== void 0) consent["terms_version"] = c.termsVersion;
850
+ body["consent"] = consent;
851
+ }
852
+ if (input.revenueShare) {
853
+ const s = input.revenueShare;
854
+ const hasEmail = typeof s.recipientPlayerEmail === "string" && s.recipientPlayerEmail.trim() !== "";
855
+ const hasId = s.recipientPlayerId != null;
856
+ if (hasEmail === hasId) {
857
+ throw invalidInput(
858
+ "revenueShare",
859
+ s,
860
+ "requires EXACTLY ONE of recipientPlayerEmail or recipientPlayerId"
861
+ );
862
+ }
863
+ const share = {
864
+ percent: typeof s.percent === "number" ? s.percent.toFixed(2) : s.percent
865
+ };
866
+ if (hasEmail) share["recipient_player_email"] = s.recipientPlayerEmail;
867
+ else share["recipient_player_id"] = s.recipientPlayerId;
868
+ body["revenue_share"] = share;
869
+ }
870
+ return body;
871
+ }
872
+ var SubscriptionsServer = class {
873
+ constructor(http, auth) {
874
+ this.http = http;
875
+ this.auth = auth;
876
+ }
877
+ /**
878
+ * Create a CARD-rail subscription. **Charges the first period before responding**
879
+ * (unless it is a trial), so expect the call to take as long as a card charge.
880
+ *
881
+ * Branch on `result.firstCharge.status`: `paid` (grant until `paidThrough`),
882
+ * `requires_action` (NOTHING charged; send the member to `confirmationUrl`),
883
+ * `skipped_trial` (grant trial access until `subscription.trialEnd`), `failed` (in
884
+ * dunning; INVO retries at `nextRetryAt`), `pending` (wait for the event).
885
+ *
886
+ * Idempotent on `clientRequestId`: a repeat returns HTTP 200 with the identical shape
887
+ * and `idempotentReplay: true`, and NOTHING is charged again. **On any timeout or 5xx,
888
+ * replay the same key before you do anything else**; a fresh key inside a retry loop
889
+ * lands on `409 ACTIVE_SUBSCRIPTION_EXISTS` (`err.isActiveSubscriptionExists`,
890
+ * `err.existingSubscriptionId`) at best and a second subscription at worst. Same key
891
+ * with different terms is `err.isIdempotentReplayMismatch` (`err.mismatchedFields`).
892
+ *
893
+ * Card selection: `playerCardId` names one (from `cards.list`); omitted, INVO attaches
894
+ * the member's newest unexpired saved card; `walletOnly: true` never charges a card.
895
+ * Requires the game to be `live` (`err.isGameNotLive`).
896
+ */
897
+ async create(input, opts) {
898
+ const body = subscriptionBaseBody(input);
899
+ if (input.intervalCount !== void 0) {
900
+ if (!Number.isInteger(input.intervalCount) || input.intervalCount < 1 || input.intervalCount > 36) {
901
+ throw invalidInput("intervalCount", input.intervalCount, "must be an integer 1..36");
902
+ }
903
+ body["interval_count"] = input.intervalCount;
904
+ }
905
+ if (input.trialDays !== void 0) {
906
+ if (!Number.isInteger(input.trialDays) || input.trialDays < 1 || input.trialDays > 365) {
907
+ throw invalidInput("trialDays", input.trialDays, "must be an integer 1..365");
908
+ }
909
+ body["trial_days"] = input.trialDays;
910
+ }
911
+ if (input.trialEnd !== void 0) {
912
+ if (typeof input.trialEnd !== "string" || Number.isNaN(Date.parse(input.trialEnd))) {
913
+ throw invalidInput("trialEnd", input.trialEnd, "must be an ISO 8601 timestamp");
914
+ }
915
+ body["trial_end"] = input.trialEnd;
916
+ }
917
+ if (input.walletOnly !== void 0) {
918
+ if (typeof input.walletOnly !== "boolean") {
919
+ throw invalidInput("walletOnly", input.walletOnly, "must be a boolean");
920
+ }
921
+ body["wallet_only"] = input.walletOnly;
922
+ }
923
+ if (input.playerCardId !== void 0) {
924
+ if (!Number.isInteger(input.playerCardId) || input.playerCardId < 1) {
925
+ throw invalidInput("playerCardId", input.playerCardId, "must be a positive integer card id (from cards.list)");
926
+ }
927
+ if (input.walletOnly === true) {
928
+ throw invalidInput("playerCardId", input.playerCardId, "cannot be combined with walletOnly: true");
929
+ }
930
+ body["player_card_id"] = input.playerCardId;
931
+ }
932
+ const raw = await this.http.post(
933
+ "/api/subscriptions/subscribe",
934
+ body,
935
+ this.auth,
936
+ // Idempotent on client_request_id: a lost-response retry REPLAYS the row (200,
937
+ // idempotent_replay: true) and never charges twice. Replay before retry.
938
+ { idempotent: true, signal: opts?.signal }
939
+ );
940
+ return toSubscriptionResult(raw);
941
+ }
942
+ /** Read one subscription. `404 SUBSCRIPTION_NOT_FOUND` for an id that is not your game's. */
943
+ async get(subscriptionId, options, opts) {
944
+ assertSubscriptionId(subscriptionId);
945
+ const qs = options?.includePlayer ? "?include_player=true" : "";
946
+ const raw = await this.http.get(
947
+ `/api/subscriptions/${encodeURIComponent(subscriptionId)}${qs}`,
948
+ this.auth,
949
+ { signal: opts?.signal }
950
+ );
951
+ return {
952
+ subscription: toSubscription(raw["subscription"]),
953
+ player: raw["player"] && typeof raw["player"] === "object" ? raw["player"] : void 0,
954
+ raw
955
+ };
956
+ }
957
+ /**
958
+ * List a member's subscriptions, newest first, paged (`limit` 1..100, `offset`
959
+ * 0..100000). `status` filters; `"live"` expands to the four live statuses and may be
960
+ * mixed in (`["live", "canceled"]`). A player who does not exist yet is an empty list
961
+ * with `totalCount: 0`, not a 404.
962
+ */
963
+ async listForPlayer(playerEmail, options, opts) {
964
+ if (typeof playerEmail !== "string" || !playerEmail.trim()) {
965
+ throw invalidInput("playerEmail", playerEmail, "is required");
966
+ }
967
+ const q = new URLSearchParams();
968
+ q.set("player_email", playerEmail);
969
+ if (options?.status !== void 0) {
970
+ const list = Array.isArray(options.status) ? options.status : [options.status];
971
+ if (list.length) q.set("status", list.join(","));
972
+ }
973
+ if (options?.includePlayer) q.set("include_player", "true");
974
+ if (options?.limit != null) {
975
+ if (!Number.isInteger(options.limit) || options.limit < 1 || options.limit > 100) {
976
+ throw invalidInput("limit", options.limit, "must be an integer 1..100");
977
+ }
978
+ q.set("limit", String(options.limit));
979
+ }
980
+ if (options?.offset != null) {
981
+ if (!Number.isInteger(options.offset) || options.offset < 0 || options.offset > 1e5) {
982
+ throw invalidInput("offset", options.offset, "must be an integer 0..100000");
983
+ }
984
+ q.set("offset", String(options.offset));
985
+ }
986
+ const raw = await this.http.get(
987
+ `/api/subscriptions/player?${q.toString()}`,
988
+ this.auth,
989
+ { signal: opts?.signal }
990
+ );
991
+ const rows = Array.isArray(raw["subscriptions"]) ? raw["subscriptions"] : [];
992
+ const p = raw["pagination"] ?? {};
993
+ return {
994
+ playerEmail: String(raw["player_email"] ?? playerEmail),
995
+ subscriptions: rows.map(toSubscription),
996
+ pagination: {
997
+ totalCount: Number(p["total_count"] ?? rows.length),
998
+ limit: Number(p["limit"] ?? 50),
999
+ offset: Number(p["offset"] ?? 0),
1000
+ hasMore: p["has_more"] === true
1001
+ },
1002
+ raw
1003
+ };
1004
+ }
1005
+ /**
1006
+ * Cancel. `atPeriodEnd` defaults to `true`: the subscription stays live with
1007
+ * `cancelAtPeriodEnd: true` and is retired at `paidThrough` without another charge.
1008
+ * If nothing has been paid (or the paid window has elapsed) an at-period-end cancel is
1009
+ * **downgraded to immediate**: read `terminatedImmediately`. `atPeriodEnd: false` ends
1010
+ * it now. Revoke access at `accessUntil`.
1011
+ *
1012
+ * Cancelling an already-terminal subscription is a 200 with `alreadyCanceled: true`
1013
+ * (never thrown), so a batch reconciler needs no special case; that is also what makes
1014
+ * a lost-response retry safe. One `subscription.canceled` event fires at request time.
1015
+ * Never blocked by a maintenance pause.
1016
+ */
1017
+ async cancel(subscriptionId, options, opts) {
1018
+ assertSubscriptionId(subscriptionId);
1019
+ const body = {};
1020
+ if (options?.atPeriodEnd !== void 0) {
1021
+ if (typeof options.atPeriodEnd !== "boolean") {
1022
+ throw invalidInput("atPeriodEnd", options.atPeriodEnd, "must be a boolean");
1023
+ }
1024
+ body["at_period_end"] = options.atPeriodEnd;
1025
+ }
1026
+ if (options?.reason !== void 0) {
1027
+ if (typeof options.reason !== "string" || options.reason.length > 500) {
1028
+ throw invalidInput("reason", options.reason, "must be a string of at most 500 characters");
1029
+ }
1030
+ body["reason"] = options.reason;
1031
+ }
1032
+ const raw = await this.http.post(
1033
+ `/api/subscriptions/${encodeURIComponent(subscriptionId)}/cancel`,
1034
+ body,
1035
+ this.auth,
1036
+ // Safe to retry: a repeat on an already-canceled row is a 200 (already_canceled: true).
1037
+ { idempotent: true, signal: opts?.signal }
1038
+ );
1039
+ return {
1040
+ status: String(raw["status"] ?? ""),
1041
+ alreadyCanceled: raw["already_canceled"] === true,
1042
+ finalStatus: typeof raw["final_status"] === "string" ? raw["final_status"] : void 0,
1043
+ cancelAtPeriodEnd: raw["cancel_at_period_end"] === true,
1044
+ effectiveAt: nullableString(raw["effective_at"]),
1045
+ currentPeriodEnd: nullableString(raw["current_period_end"]),
1046
+ accessUntil: nullableString(raw["access_until"]),
1047
+ paidThrough: nullableString(raw["paid_through"]),
1048
+ terminatedImmediately: raw["terminated_immediately"] === true,
1049
+ downgradeReason: typeof raw["downgrade_reason"] === "string" ? raw["downgrade_reason"] : void 0,
1050
+ message: typeof raw["message"] === "string" ? raw["message"] : void 0,
1051
+ steamAgreementStatus: "steam_agreement_status" in raw ? nullableString(raw["steam_agreement_status"]) : void 0,
1052
+ steamAgreementCanceled: typeof raw["steam_agreement_canceled"] === "boolean" ? raw["steam_agreement_canceled"] : void 0,
1053
+ subscription: raw["subscription"] ? toSubscription(raw["subscription"]) : null,
1054
+ raw
1055
+ };
1056
+ }
1057
+ /**
1058
+ * Stage a price change. Applied on the NEXT successful renewal (the current window is
1059
+ * billed at the old price first; no proration). Sending the current price clears a
1060
+ * staged change (`changeQueued: false`). The billed price appears on that period's
1061
+ * `subscription.renewed`; there is no `amount_changed` event.
1062
+ *
1063
+ * Steam: an increase is refused (`err.isSteamReauthorizationRequired`; start a new
1064
+ * Steam subscription at the new price), a decrease stages. An increase to more than
1065
+ * double the last agreed price, or above 500.00, is staged but never applied: raise
1066
+ * prices in steps. `err.isSubscriptionTerminal` on a canceled/expired row.
1067
+ */
1068
+ async changeAmount(subscriptionId, amountUsd, opts) {
1069
+ assertSubscriptionId(subscriptionId);
1070
+ const amount = subscriptionMoney(amountUsd, "amountUsd");
1071
+ const raw = await this.http.post(
1072
+ `/api/subscriptions/${encodeURIComponent(subscriptionId)}/amount`,
1073
+ { amount_usd: amount },
1074
+ this.auth,
1075
+ // Setting a price is naturally idempotent: the same value again is the same state.
1076
+ { idempotent: true, signal: opts?.signal }
1077
+ );
1078
+ return {
1079
+ status: String(raw["status"] ?? ""),
1080
+ oldAmountUsd: String(raw["old_amount_usd"] ?? ""),
1081
+ newAmountUsd: String(raw["new_amount_usd"] ?? amount),
1082
+ pendingAmountUsd: nullableString(raw["pending_amount_usd"]),
1083
+ changeQueued: raw["change_queued"] === true,
1084
+ appliesFrom: nullableString(raw["applies_from"]),
1085
+ appliesFromPeriodSeq: Number(raw["applies_from_period_seq"] ?? 0),
1086
+ paidThrough: nullableString(raw["paid_through"]),
1087
+ currentPeriodEnd: nullableString(raw["current_period_end"]),
1088
+ prorated: raw["prorated"] === true,
1089
+ subscription: raw["subscription"] ? toSubscription(raw["subscription"]) : null,
1090
+ raw
1091
+ };
1092
+ }
1093
+ /**
1094
+ * Card subscriptions only. Attach a card (`{ playerCardId }`, an `id` from
1095
+ * `cards.list` belonging to this player, unexpired) or make the subscription wallet-only
1096
+ * (`{ walletOnly: true }`). On a wallet-only subscription pass `walletOnly: false`
1097
+ * beside the card to convert it back. The new card is used from the next charge,
1098
+ * including a pending retry in dunning.
1099
+ *
1100
+ * `err.isNotACardSubscription` on Steam; `err.isSubscriptionTerminal` on a terminal row.
1101
+ */
1102
+ async setPaymentMethod(subscriptionId, input, opts) {
1103
+ assertSubscriptionId(subscriptionId);
1104
+ const body = {};
1105
+ if ("playerCardId" in input && input.playerCardId !== void 0) {
1106
+ if (!Number.isInteger(input.playerCardId) || input.playerCardId < 1) {
1107
+ throw invalidInput("playerCardId", input.playerCardId, "must be a positive integer card id (from cards.list)");
1108
+ }
1109
+ body["player_card_id"] = input.playerCardId;
1110
+ if (input.walletOnly !== void 0) body["wallet_only"] = input.walletOnly;
1111
+ } else if (input.walletOnly === true) {
1112
+ body["wallet_only"] = true;
1113
+ } else {
1114
+ throw invalidInput("input", input, "requires { playerCardId } or { walletOnly: true }");
1115
+ }
1116
+ const raw = await this.http.post(
1117
+ `/api/subscriptions/${encodeURIComponent(subscriptionId)}/payment-method`,
1118
+ body,
1119
+ this.auth,
1120
+ // Attaching the same card twice is the same state: safe to retry.
1121
+ { idempotent: true, signal: opts?.signal }
1122
+ );
1123
+ return {
1124
+ status: String(raw["status"] ?? ""),
1125
+ replaced: raw["replaced"] === true,
1126
+ walletOnly: raw["wallet_only"] === true,
1127
+ card: toSavedCard(raw["card"]),
1128
+ subscription: raw["subscription"] ? toSubscription(raw["subscription"]) : null,
1129
+ raw
1130
+ };
1131
+ }
1132
+ /**
1133
+ * Refund a billed period (card rail). Idempotent on `clientRequestId`: a repeat returns
1134
+ * the stored receipt with `idempotentReplay: true` and moves nothing.
1135
+ *
1136
+ * A full refund returns the card charge and reclaims the coins that charge minted
1137
+ * (`balanceDeltaCoins` is signed and can be negative); a partial refund credits the
1138
+ * wallet in coins at the 10:1 peg. Your revenue is reversed for the refunded portion
1139
+ * (`partnerRevenueReversedUsd`); INVO's fee is retained. The subscription is NOT
1140
+ * cancelled by a refund. Refunds of Steam-CHARGED periods are not supported yet; do not
1141
+ * call this on them.
1142
+ *
1143
+ * Refusals: `NO_PAID_PERIOD` (409, nothing collected yet), `PERIOD_NOT_REFUNDABLE`,
1144
+ * `ALREADY_REFUNDED` (`err.isAlreadyRefunded`), `AMOUNT_EXCEEDS_REMAINING` (body carries
1145
+ * `remaining_refundable_usd`), `err.isFlowPaused`.
1146
+ */
1147
+ async refund(subscriptionId, input, opts) {
1148
+ assertSubscriptionId(subscriptionId);
1149
+ assertClientRequestId(input.clientRequestId, "clientRequestId");
1150
+ const body = { client_request_id: input.clientRequestId };
1151
+ if (input.periodSeq !== void 0) {
1152
+ if (!Number.isInteger(input.periodSeq) || input.periodSeq < 1) {
1153
+ throw invalidInput("periodSeq", input.periodSeq, "must be an integer >= 1");
1154
+ }
1155
+ body["period_seq"] = input.periodSeq;
1156
+ }
1157
+ if (input.amountUsd !== void 0) body["amount_usd"] = subscriptionMoney(input.amountUsd, "amountUsd");
1158
+ if (input.reason !== void 0) {
1159
+ if (typeof input.reason !== "string" || input.reason.length > 500) {
1160
+ throw invalidInput("reason", input.reason, "must be a string of at most 500 characters");
1161
+ }
1162
+ body["reason"] = input.reason;
1163
+ }
1164
+ const raw = await this.http.post(
1165
+ `/api/subscriptions/${encodeURIComponent(subscriptionId)}/refund`,
1166
+ body,
1167
+ this.auth,
1168
+ // Idempotent on client_request_id: a lost-response retry returns the stored receipt.
1169
+ { idempotent: true, signal: opts?.signal }
1170
+ );
1171
+ const attr = raw["revenue_share_attribution"];
1172
+ const a = attr && typeof attr === "object" ? attr : null;
1173
+ return {
1174
+ status: String(raw["status"] ?? ""),
1175
+ idempotentReplay: raw["idempotent_replay"] === true,
1176
+ refundKey: nullableString(raw["refund_key"]),
1177
+ clientRequestId: nullableString(raw["client_request_id"]) ?? input.clientRequestId,
1178
+ subscriptionId: String(raw["subscription_id"] ?? subscriptionId),
1179
+ periodSeq: raw["period_seq"] == null ? null : Number(raw["period_seq"]),
1180
+ transactionId: nullableString(raw["transaction_id"]),
1181
+ refundedAmountUsd: nullableString(raw["refunded_amount_usd"]),
1182
+ totalRefundedAmountUsd: nullableString(raw["total_refunded_amount_usd"]),
1183
+ remainingRefundableUsd: nullableString(raw["remaining_refundable_usd"]),
1184
+ isFullRefund: raw["is_full_refund"] === true,
1185
+ fundingShape: nullableString(raw["funding_shape"]),
1186
+ balanceDeltaCoins: nullableString(raw["balance_delta_coins"]),
1187
+ cardRefundedUsd: nullableString(raw["card_refunded_usd"]),
1188
+ // Neutral field only; the vendor-named sibling is deliberately not read.
1189
+ processorRefundReference: nullableString(raw["processor_refund_reference"]),
1190
+ processorRefundAdopted: raw["processor_refund_adopted"] === true,
1191
+ invoFeeRetained: raw["invo_fee_retained"] === true,
1192
+ partnerRevenueReversedUsd: nullableString(raw["partner_revenue_reversed_usd"]),
1193
+ partnerRevenueReversalMode: nullableString(raw["partner_revenue_reversal_mode"]),
1194
+ reason: nullableString(raw["reason"]),
1195
+ refundedAt: nullableString(raw["refunded_at"]),
1196
+ newBalance: nullableString(raw["new_balance"]),
1197
+ revenueShareAttribution: a ? {
1198
+ recipientPlayerId: Number(a["recipient_player_id"] ?? 0),
1199
+ percent: String(a["percent"] ?? ""),
1200
+ originalAttributedAmountUsd: String(a["original_attributed_amount_usd"] ?? ""),
1201
+ refundedAttributedAmountUsd: String(a["refunded_attributed_amount_usd"] ?? ""),
1202
+ netAttributedAmountUsd: String(a["net_attributed_amount_usd"] ?? ""),
1203
+ settledByInvo: a["settled_by_invo"] === true,
1204
+ raw: a
1205
+ } : null,
1206
+ note: typeof raw["note"] === "string" ? raw["note"] : void 0,
1207
+ raw
1208
+ };
1209
+ }
1210
+ /**
1211
+ * Start a STEAM-rail subscription: creates it in `pending_steam_authorization`, opens
1212
+ * period 1 for the full price and starts the Steam authorisation. Nothing is charged
1213
+ * until the member authorises and you call {@link steamFinalize}. Idempotent on
1214
+ * `clientRequestId`; a replay answers with the row's CURRENT status (which may already
1215
+ * be `active`, `canceled` or `expired`).
1216
+ *
1217
+ * `userSession: "client"` (default): the Steam overlay presents the authorisation inside
1218
+ * the game; match the Steam client callback's `order_id` against `steamOrderId` (never
1219
+ * `steamTransid`). `"web"`: open `steamCheckoutUrl` as a TOP-LEVEL window (it cannot be
1220
+ * framed); requires `playerIp`, the MEMBER's address. Show `amountCoins`: what one
1221
+ * period is worth for THIS member depends on their country and is fixed at init.
1222
+ *
1223
+ * A pending authorisation for the same player and item with the SAME terms is handed
1224
+ * back (`pendingReuse: true`, no new agreement): finalize that one. With DIFFERENT
1225
+ * terms the call throws `409 STEAM_AUTHORIZATION_PENDING` (`err.isSteamAuthorizationPending`,
1226
+ * `err.existingSubscriptionId`): finalize or cancel the pending one first.
1227
+ *
1228
+ * Not available on Steam, refused before the network: trials, `walletOnly`, card
1229
+ * fields, `intervalCount` other than 1. Backend refusals worth branching on:
1230
+ * `err.isSteamChannelRequired` (409, wrong channel key), `err.isActiveSubscriptionExists`,
1231
+ * `err.isSteamRailNotEntitled` (403), `err.isSteamNotConfigured` (503),
1232
+ * `err.isPartnerBillingNotSetUp` / `isPartnerSettlementUnavailable` (409),
1233
+ * `AMOUNT_TOO_SMALL_FOR_STEAM` (400). When a Steam-side failure abandons the row after
1234
+ * creation the body carries the abandoned `subscription_id`; retry with a NEW key.
1235
+ */
1236
+ async steamInit(input, opts) {
1237
+ const body = subscriptionBaseBody(input);
1238
+ if (!/^[0-9]+$/.test(String(input.steamId ?? ""))) {
1239
+ throw invalidInput("steamId", input.steamId, "must be the member's numeric 64-bit Steam id");
1240
+ }
1241
+ if (input.userSession !== void 0 && input.userSession !== "client" && input.userSession !== "web") {
1242
+ throw invalidInput("userSession", input.userSession, 'must be "client" or "web"');
1243
+ }
1244
+ if (input.userSession === "web" && !input.playerIp) {
1245
+ throw new InvoError({
1246
+ message: `playerIp is required when userSession is "web" \u2014 the MEMBER's IP, not your server's.`,
1247
+ code: "MISSING_PLAYER_IP",
1248
+ status: 0
1249
+ });
1250
+ }
1251
+ if (input.intervalCount !== void 0 && input.intervalCount !== 1) {
1252
+ throw invalidInput("intervalCount", input.intervalCount, "must be 1 on the Steam rail (monthly and yearly only)");
1253
+ }
1254
+ const forbidden = input;
1255
+ for (const k of ["trialDays", "trialEnd", "walletOnly", "playerCardId"]) {
1256
+ if (forbidden[k] !== void 0) {
1257
+ throw invalidInput(k, forbidden[k], "is not available on the Steam rail");
1258
+ }
1259
+ }
1260
+ body["steamid"] = String(input.steamId);
1261
+ if (input.userSession) body["usersession"] = input.userSession;
1262
+ if (input.playerIp) body["player_ip"] = input.playerIp;
1263
+ if (input.intervalCount !== void 0) body["interval_count"] = input.intervalCount;
1264
+ const raw = await this.http.post(
1265
+ "/api/subscriptions/steam/init",
1266
+ body,
1267
+ this.auth,
1268
+ // Idempotent on client_request_id: a replay returns the row's current status.
1269
+ { idempotent: true, signal: opts?.signal }
1270
+ );
1271
+ return {
1272
+ status: String(raw["status"] ?? ""),
1273
+ subscriptionStatus: String(raw["subscription_status"] ?? raw["status"] ?? ""),
1274
+ idempotentReplay: raw["idempotent_replay"] === true,
1275
+ pendingReuse: raw["pending_reuse"] === true,
1276
+ subscription: toSubscription(raw["subscription"]),
1277
+ subscriptionId: String(raw["subscription_id"] ?? ""),
1278
+ orderId: String(raw["order_id"] ?? ""),
1279
+ steamOrderId: String(raw["steam_order_id"] ?? ""),
1280
+ steamTransid: String(raw["steam_transid"] ?? ""),
1281
+ steamCheckoutUrl: nullableString(raw["steam_checkout_url"]),
1282
+ amountUsd: String(raw["amount_usd"] ?? ""),
1283
+ amountCoins: String(raw["amount_coins"] ?? ""),
1284
+ steamChargeUsd: String(raw["steam_charge_usd"] ?? ""),
1285
+ recurringAmountUsd: String(raw["recurring_amount_usd"] ?? ""),
1286
+ firstCharge: toFirstCharge(raw["first_charge"]),
1287
+ message: String(raw["message"] ?? ""),
1288
+ raw
1289
+ };
1290
+ }
1291
+ /**
1292
+ * Finalize a Steam subscription after the member has authorised: INVO verifies with
1293
+ * Steam, captures period 1, records the agreement and settles period 1 exactly as a
1294
+ * renewal. Idempotent: a repeat returns `alreadyProcessed: true` with
1295
+ * `idempotentReplay: true` (treat as success; never thrown).
1296
+ *
1297
+ * **Finalize is your call.** Steam does not tell INVO the member authorised; call this
1298
+ * after the overlay or checkout closes, and again if it threw `err.isNotAuthorized`
1299
+ * (409 `status: "not_authorized"`: the normal wait state). The member has 24 hours.
1300
+ * A 200 with `warning` means Steam charged but period 1 could not settle in one step:
1301
+ * the money is taken, do not retry the charge, watch for `subscription.renewed`.
1302
+ * In sandbox this does not call Steam (`sandboxAutoApproved: true`).
1303
+ *
1304
+ * Other refusals: `err.isSubscriptionTerminal`, `NOT_A_STEAM_SUBSCRIPTION`,
1305
+ * `NO_STEAM_AUTHORIZATION`, `err.isSteamAppChanged` (409); 502/503 are transient.
1306
+ */
1307
+ async steamFinalize(subscriptionId, opts) {
1308
+ assertSubscriptionId(subscriptionId);
1309
+ const raw = await this.http.post(
1310
+ "/api/subscriptions/steam/finalize",
1311
+ { subscription_id: subscriptionId },
1312
+ this.auth,
1313
+ // Idempotent: a repeat replays the finalised row (already_processed: true).
1314
+ { idempotent: true, signal: opts?.signal }
1315
+ );
1316
+ return {
1317
+ ...toSubscriptionResult(raw),
1318
+ alreadyProcessed: raw["already_processed"] === true,
1319
+ steamAgreementStatus: nullableString(raw["steam_agreement_status"]),
1320
+ sandboxAutoApproved: raw["sandbox_auto_approved"] === true
1321
+ };
1322
+ }
1323
+ };
1324
+ var CardsServer = class {
1325
+ constructor(http, auth) {
1326
+ this.http = http;
1327
+ this.auth = auth;
1328
+ }
1329
+ /**
1330
+ * Begin saving a card (charges nothing). The player must already exist in this game
1331
+ * (`404 PLAYER_NOT_FOUND`). Idempotent on `setupReference`: resend the same value on a
1332
+ * retry and you get the same setup back (`409 SETUP_REFERENCE_REUSED` if you reuse it
1333
+ * with different parameters).
1334
+ *
1335
+ * With `paymentMethodId` (a card tokenised on the client) INVO confirms server-side
1336
+ * and answers `succeeded` with the `card`, or `requires_action` with a `clientSecret`
1337
+ * for the card form to run the cardholder authentication. Without it, INVO answers
1338
+ * `requires_confirmation` / `requires_payment_method` with a `clientSecret`: confirm on
1339
+ * the client, then call {@link confirmSetup}. Send tokens only, never raw card numbers
1340
+ * (`RAW_CARD_NOT_SUPPORTED`).
1341
+ */
1342
+ async beginSetup(input, opts) {
1343
+ if (typeof input.playerEmail !== "string" || !input.playerEmail.trim()) {
1344
+ throw invalidInput("playerEmail", input.playerEmail, "is required");
1345
+ }
1346
+ if (typeof input.setupReference !== "string" || !/^[A-Za-z0-9._:-]{1,200}$/.test(input.setupReference)) {
1347
+ throw invalidInput("setupReference", input.setupReference, "must be 1-200 characters of A-Z a-z 0-9 . _ : -");
1348
+ }
1349
+ const body = {
1350
+ player_email: input.playerEmail,
1351
+ setup_reference: input.setupReference
1352
+ };
1353
+ if (input.paymentMethodId) body["payment_method_id"] = input.paymentMethodId;
1354
+ const raw = await this.http.post(
1355
+ "/api/currency-purchases/setup-intent",
1356
+ body,
1357
+ this.auth,
1358
+ // Idempotent on setup_reference: a retry returns the same setup, never a second one.
1359
+ { idempotent: true, signal: opts?.signal }
1360
+ );
1361
+ return {
1362
+ status: String(raw["status"] ?? ""),
1363
+ setupIntentId: requireField(raw["setup_intent_id"], "setup_intent_id", raw),
1364
+ clientSecret: typeof raw["client_secret"] === "string" ? raw["client_secret"] : void 0,
1365
+ publishableKey: typeof raw["publishable_key"] === "string" ? raw["publishable_key"] : void 0,
1366
+ card: toSavedCard(raw["card"]),
1367
+ alreadySaved: raw["already_saved"] === true,
1368
+ message: typeof raw["message"] === "string" ? raw["message"] : void 0,
1369
+ raw
1370
+ };
1371
+ }
1372
+ /**
1373
+ * Finish a client-confirmed setup and save the card. Idempotent on `setupIntentId`.
1374
+ * While the client has not finished, this throws a 400 with body
1375
+ * `status: "still_requires_action"`. On `500 CARD_PERSIST_FAILED` (authorised but not
1376
+ * recorded) retry this call with the same `setupIntentId`.
1377
+ */
1378
+ async confirmSetup(input, opts) {
1379
+ if (typeof input.setupIntentId !== "string" || !input.setupIntentId.trim()) {
1380
+ throw invalidInput("setupIntentId", input.setupIntentId, "is required (from beginSetup)");
1381
+ }
1382
+ const raw = await this.http.post(
1383
+ "/api/currency-purchases/setup-intent/confirm",
1384
+ { setup_intent_id: input.setupIntentId },
1385
+ this.auth,
1386
+ { idempotent: true, signal: opts?.signal }
1387
+ // keyed by setup_intent_id: safe to retry
1388
+ );
1389
+ return {
1390
+ status: String(raw["status"] ?? ""),
1391
+ setupIntentId: String(raw["setup_intent_id"] ?? input.setupIntentId),
1392
+ card: toSavedCard(raw["card"]),
1393
+ alreadySaved: raw["already_saved"] === true,
1394
+ raw
1395
+ };
1396
+ }
1397
+ /**
1398
+ * A member's unexpired saved cards, newest first. An unknown player is `{ cards: [] }`.
1399
+ * The `id` is the value you pass as `playerCardId`; INVO never returns processor
1400
+ * identifiers for a card. Served from a short cache (about 60 s); a card saved through
1401
+ * `beginSetup` / `confirmSetup` appears immediately.
1402
+ */
1403
+ async list(playerEmail, opts) {
1404
+ if (typeof playerEmail !== "string" || !playerEmail.trim()) {
1405
+ throw invalidInput("playerEmail", playerEmail, "is required");
1406
+ }
1407
+ const raw = await this.http.get(
1408
+ `/api/currency-purchases/player-cards?player_email=${encodeURIComponent(playerEmail)}`,
1409
+ this.auth,
1410
+ { signal: opts?.signal }
1411
+ );
1412
+ const rows = Array.isArray(raw["cards"]) ? raw["cards"] : [];
1413
+ return {
1414
+ cards: rows.map(toSavedCard).filter((c) => c !== null),
1415
+ raw
1416
+ };
1417
+ }
1418
+ };
1419
+ var SandboxSubscriptionsServer = class {
1420
+ constructor(http, auth, clockKey) {
1421
+ this.http = http;
1422
+ this.auth = auth;
1423
+ this.clockKey = clockKey;
1424
+ }
1425
+ async call(subscriptionId, tool, body, opts) {
1426
+ assertSubscriptionId(subscriptionId);
1427
+ if (typeof this.clockKey !== "string" || !this.clockKey.trim()) {
1428
+ throw invalidInput(
1429
+ "sandboxClockKey",
1430
+ this.clockKey,
1431
+ 'is required for invo.sandbox.subscriptions.* \u2014 pass it to new InvoServer({ sandboxClockKey }) from the sandbox console (Game Settings, "Sandbox clock key")'
1432
+ );
1433
+ }
1434
+ const raw = await this.http.post(
1435
+ // Relative to baseUrl, which already ends in /sandbox. NOT under /api.
1436
+ `/subscriptions/${encodeURIComponent(subscriptionId)}/${tool}`,
1437
+ body,
1438
+ this.auth,
1439
+ { signal: opts?.signal, headers: { "X-Sandbox-Clock-Key": this.clockKey } }
1440
+ // never auto-retried
1441
+ );
1442
+ return toSandboxClockResult(raw);
1443
+ }
1444
+ /**
1445
+ * Make the next period due now. `intervals` 0..60, default 1. `0` makes it due without
1446
+ * moving the window (use it to trigger a retry). `N` on a never-paid subscription
1447
+ * (a trial, a fresh row) also moves the window back by up to N intervals; once anything
1448
+ * has been paid the window stays put (`intervalsAppliedToWindow: 0`). No window is ever
1449
+ * billed twice. Then `forceRenewal`, or wait for the next sweep (within a minute or two).
1450
+ * `409 SUBSCRIPTION_NOT_LIVE` on a terminal or pending row.
1451
+ */
1452
+ async advanceClock(subscriptionId, intervals = 1, opts) {
1453
+ if (!Number.isInteger(intervals) || intervals < 0 || intervals > 60) {
1454
+ throw invalidInput("intervals", intervals, "must be an integer 0..60");
1455
+ }
1456
+ return this.call(subscriptionId, "advance-clock", { intervals }, opts);
1457
+ }
1458
+ /**
1459
+ * Run the renewal immediately. **Charges the test card** (or the Steam stand-in): the
1460
+ * real money path, wallet read, shortfall, mint, spend, split, `subscription.renewed`,
1461
+ * and on failure the real dunning. Read `engineStats` (`renewed: 1` on success). A
1462
+ * cancel-at-period-end row answers `action: "retired-at-period-end"`, `retired: true`.
1463
+ * `409 PERIOD_TOO_FAR_AHEAD` means you forced twice without advancing the clock.
1464
+ */
1465
+ async forceRenewal(subscriptionId, opts) {
1466
+ return this.call(subscriptionId, "force-renewal", {}, opts);
1467
+ }
1468
+ /**
1469
+ * Synthesise a failed attempt and run real dunning. No charge. `outcome` defaults to
1470
+ * `card_declined`. Returns `retryBudgetUsed`, `retryScheduleDays` (e.g. `[2, 3, 2]`),
1471
+ * `retriesRemaining`. Call it four times to walk `active` through `past_due` to `expired`
1472
+ * and watch the events. Does not model a Steam refusal.
1473
+ */
1474
+ async forceFailure(subscriptionId, outcome = "card_declined", options, opts) {
1475
+ if (!SANDBOX_FAILURE_OUTCOMES.has(outcome)) {
1476
+ throw invalidInput("outcome", outcome, 'must be "card_declined" | "insufficient_funds" | "error"');
1477
+ }
1478
+ const body = { outcome };
1479
+ if (options?.failureCode !== void 0) body["failure_code"] = options.failureCode;
1480
+ if (options?.failureMessage !== void 0) body["failure_message"] = options.failureMessage;
1481
+ return this.call(subscriptionId, "force-failure", body, opts);
1482
+ }
1483
+ /**
1484
+ * Synthesise a cardholder authentication challenge: moves the subscription to
1485
+ * `awaiting_authentication` (no charge). Returns `authChallengesUsed`,
1486
+ * `maxAuthChallenges` (2) and `downgradedToDecline`. It does NOT mint a confirmation
1487
+ * link; to exercise the link and the `subscription.authentication_required` event use a
1488
+ * test card that requires authentication, then `forceRenewal`.
1489
+ */
1490
+ async forceAuthChallenge(subscriptionId, options, opts) {
1491
+ const body = {};
1492
+ if (options?.failureMessage !== void 0) body["failure_message"] = options.failureMessage;
1493
+ return this.call(subscriptionId, "force-auth-challenge", body, opts);
1494
+ }
1495
+ };
1496
+ var SandboxServer = class {
1497
+ constructor(http, auth, clockKey) {
1498
+ this.subscriptions = new SandboxSubscriptionsServer(http, auth, clockKey);
1499
+ }
1500
+ };
523
1501
  var InvoServer = class {
524
1502
  constructor(config) {
525
1503
  if (!config.gameSecret) throw new Error("InvoServer requires a `gameSecret`.");
@@ -537,6 +1515,9 @@ var InvoServer = class {
537
1515
  });
538
1516
  this.auth = { kind: "game-secret", secret: config.gameSecret };
539
1517
  this.platformCommerce = new PlatformCommerceServer(this.http, this.auth);
1518
+ this.subscriptions = new SubscriptionsServer(this.http, this.auth);
1519
+ this.cards = new CardsServer(this.http, this.auth);
1520
+ this.sandbox = new SandboxServer(this.http, this.auth, config.sandboxClockKey);
540
1521
  }
541
1522
  /**
542
1523
  * Mint a short-lived, game-scoped player token to hand to the browser InvoClient.
@@ -1368,6 +2349,299 @@ var InvoServer = class {
1368
2349
  );
1369
2350
  return { approved: raw["approved"] === true, raw };
1370
2351
  }
2352
+ // ---- Device approval grant (RFC 8628) — consoles, TVs, native Steam / desktop ----
2353
+ //
2354
+ // These take the PLAYER TOKEN explicitly: on a console the game server minted it and
2355
+ // holds it, and every call below authenticates with it — the game secret is never
2356
+ // sent. The grant is a FACTOR. `beginDeviceApproval` + `pollDeviceApproval` reaching
2357
+ // `approved` settles NOTHING; `approveWithDeviceCode` is the step that moves the money.
2358
+ /**
2359
+ * Stage 1 — start a device approval for ONE transaction (RFC 8628 §3.1/§3.2).
2360
+ *
2361
+ * Returns the grant: render `verificationUriComplete` as the QR (print `userCode`
2362
+ * under it for a TV with no camera), keep `deviceCode` on your server, then poll.
2363
+ * A repeat `begin` while an earlier grant is merely PENDING supersedes it (fresh code;
2364
+ * a page still open on the old one is told to scan again). A grant the player already
2365
+ * APPROVED blocks a new `begin` for its window with `409 DEVICE_APPROVAL_ALREADY_PENDING`
2366
+ * (`err.isDeviceApprovalAlreadyPending`, `err.deviceApprovalExpiresAt`) — the missing
2367
+ * step there is `approveWithDeviceCode`, not a new code.
2368
+ *
2369
+ * For `transfer` / `send` the backend also pushes the transaction's own approval
2370
+ * window past the grant's expiry, so an approval at minute nine cannot land on a
2371
+ * transfer that has already been refunded. Auth: the player token. `channel: "popup"`
2372
+ * is browser-only (`InvoClient.approveHosted`) and is refused before the network.
2373
+ */
2374
+ async beginDeviceApproval(input, opts) {
2375
+ assertPlayerToken(input.playerToken);
2376
+ if (typeof input.transactionId !== "string" || !input.transactionId.trim()) {
2377
+ throw invalidInput("transactionId", input.transactionId, "is required");
2378
+ }
2379
+ assertDeviceApprovalFlow(input.flow);
2380
+ const channel = input.channel ?? "qr";
2381
+ if (!DEVICE_APPROVAL_CHANNELS.has(channel)) {
2382
+ throw invalidInput("channel", channel, 'must be "qr" | "app_browser" ("popup" is browser-only)');
2383
+ }
2384
+ if (channel === "popup") {
2385
+ throw new InvoError({
2386
+ message: `channel "popup" is browser-only \u2014 the page must call begin itself so its Origin becomes the popup's opener. Use InvoClient.approveHosted() there; server-side use "qr" or "app_browser".`,
2387
+ code: "INVALID_INPUT",
2388
+ status: 0
2389
+ });
2390
+ }
2391
+ const raw = await this.http.post(
2392
+ "/api/sdk/approvals/device/begin",
2393
+ { transaction_id: input.transactionId, flow: input.flow, channel },
2394
+ { kind: "bearer", token: input.playerToken },
2395
+ // PLAYER token — never the game secret
2396
+ // Safe to retry: a lost-response retry supersedes the unseen pending grant with a
2397
+ // fresh code (one live grant per transaction + flow either way).
2398
+ { idempotent: true, signal: opts?.signal }
2399
+ );
2400
+ return toDeviceApprovalGrant(raw);
2401
+ }
2402
+ /**
2403
+ * Stage 3 — one poll (RFC 8628 §3.4/§3.5). Call it no faster than `interval` seconds.
2404
+ *
2405
+ * Returns `status`:
2406
+ * - `authorization_pending` — keep polling. While a first-time phone waits on your
2407
+ * screen, `enrollment` is present: show "Set up INVO on <deviceLabel>? Code
2408
+ * <matchCode>" and answer with `confirmDeviceEnrollment`.
2409
+ * - `slow_down` — add 5 s to your interval, then resume.
2410
+ * - `approved` — **now call `approveWithDeviceCode`**. Nothing has moved yet.
2411
+ * - `access_denied` — the player declined; do not retry silently.
2412
+ * - `expired_token` — the grant lapsed; `beginDeviceApproval` again.
2413
+ * Throws `InvoError` for `invalid_grant` (`err.code === "invalid_grant"`: unknown code,
2414
+ * or not this player's — one answer for both, deliberately) and for transport failures
2415
+ * after the retry budget (429 / 5xx are retried: this is an idempotent read).
2416
+ */
2417
+ async pollDeviceApproval(input, opts) {
2418
+ assertPlayerToken(input.playerToken);
2419
+ if (typeof input.deviceCode !== "string" || !input.deviceCode.trim()) {
2420
+ throw invalidInput("deviceCode", input.deviceCode, "is required (from beginDeviceApproval)");
2421
+ }
2422
+ let raw;
2423
+ try {
2424
+ raw = await this.http.post(
2425
+ "/api/sdk/approvals/device/poll",
2426
+ { device_code: input.deviceCode },
2427
+ { kind: "bearer", token: input.playerToken },
2428
+ { idempotent: true, signal: opts?.signal }
2429
+ // a read; safe to retry
2430
+ );
2431
+ } catch (err) {
2432
+ if (err instanceof InvoError && err.status === 400 && typeof err.code === "string" && DEVICE_POLL_OUTCOME_TOKENS.has(err.code)) {
2433
+ const body = err.body && typeof err.body === "object" ? err.body : {};
2434
+ return toDevicePollOutcome(err.code, body);
2435
+ }
2436
+ throw err;
2437
+ }
2438
+ return {
2439
+ status: "approved",
2440
+ transactionId: raw["transaction_id"],
2441
+ flow: raw["flow"],
2442
+ approvedAt: raw["approved_at"] ?? null,
2443
+ raw
2444
+ };
2445
+ }
2446
+ /**
2447
+ * Stage 3b — answer the on-screen match-code prompt for a first-time phone.
2448
+ *
2449
+ * `approve` = "yes, the phone I just scanned with shows this code" (the phone then
2450
+ * creates its INVO passkey and approves); `deny` ends the whole grant — the next poll
2451
+ * answers `access_denied`. Answered once: `409 DEVICE_APPROVAL_ENROLLMENT_ALREADY_DECIDED`
2452
+ * means the backup email got there first — take the prompt down quietly.
2453
+ * `409 DEVICE_APPROVAL_NO_ENROLLMENT_PENDING`: no phone has asked. Not auto-retried.
2454
+ */
2455
+ async confirmDeviceEnrollment(input, opts) {
2456
+ assertPlayerToken(input.playerToken);
2457
+ if (typeof input.deviceCode !== "string" || !input.deviceCode.trim()) {
2458
+ throw invalidInput("deviceCode", input.deviceCode, "is required (from beginDeviceApproval)");
2459
+ }
2460
+ if (input.decision !== "approve" && input.decision !== "deny") {
2461
+ throw invalidInput("decision", input.decision, 'must be "approve" or "deny"');
2462
+ }
2463
+ const raw = await this.http.post(
2464
+ "/api/sdk/approvals/device/confirm-enrollment",
2465
+ { device_code: input.deviceCode, decision: input.decision },
2466
+ { kind: "bearer", token: input.playerToken },
2467
+ { signal: opts?.signal }
2468
+ // a decision — never auto-retried
2469
+ );
2470
+ return { status: String(raw["status"] ?? ""), raw };
2471
+ }
2472
+ /**
2473
+ * Stage 4 — THE MONEY STEP. Once the poll says `approved`, call this with the same
2474
+ * player token and the grant's `deviceCode`. Routes by `flow`:
2475
+ *
2476
+ * transfer → POST /api/sdk/transfers/{id}/approve
2477
+ * send → POST /api/sdk/send/{id}/approve
2478
+ * send_receipt → POST /api/sdk/send/{id}/confirm-receipt
2479
+ * transfer_receipt → POST /api/sdk/transfers/{id}/confirm-receipt
2480
+ *
2481
+ * The grant proves WHO approved; this call runs every gate the in-app passkey approve
2482
+ * runs (guardian, risk, recovery cooldown) and moves the money. A grant that is never
2483
+ * followed by this call moves nothing, and is consumed by nothing.
2484
+ *
2485
+ * Result: `status: "approved"` + `next: "pending_claim"` (transfer/send; `claimCode`
2486
+ * on a transfer) or `status: "completed"` + `amountReceived` (receipt flows). A 202
2487
+ * hold returns `holdReason` (money held, not refused). A repeat call after the code was
2488
+ * consumed returns `status: "not_pending"` with `currentStatus` and `alreadySettled`
2489
+ * — the backend's `TRANSACTION_NOT_PENDING` mapped into a result rather than thrown,
2490
+ * because for this call it is the normal answer to "did my earlier attempt land?".
2491
+ *
2492
+ * Throws `InvoError`: `err.isDeviceApprovalNotApproved` (400 — wrong/foreign code,
2493
+ * wrong flow, or the poll never said approved), `err.isPasskeyRecoveryCooldown` (403,
2494
+ * money-out after a passkey recovery — `err.retryAfterAt`), guardian terminal states
2495
+ * (410). Never auto-retried: the device_code is a single-use factor.
2496
+ *
2497
+ * **A FAILURE HERE IS AMBIGUOUS ABOUT THE MONEY.** The backend commits the transfer and
2498
+ * *then* builds its 200 by reading the transaction back, so a fault raised after that
2499
+ * commit answers `SEND_APPROVE_FAILED` / `TRANSFER_APPROVE_FAILED` /
2500
+ * `CONFIRM_RECEIPT_FAILED` (`err.isSettleFault`, `err.errorRef`) for money that already
2501
+ * moved. A `status === 0` (timeout, connection dropped) is ambiguous for the same
2502
+ * reason, and this call is deliberately not auto-retried. So on either: read
2503
+ * `getTransferStatus` / `getSendStatus`, or wait for the `transfer.claim_pending`
2504
+ * webhook, BEFORE you tell the player it failed — and never auto-start a replacement
2505
+ * transaction.
2506
+ */
2507
+ async approveWithDeviceCode(input, opts) {
2508
+ assertPlayerToken(input.playerToken);
2509
+ if (typeof input.transactionId !== "string" || !input.transactionId.trim()) {
2510
+ throw invalidInput("transactionId", input.transactionId, "is required");
2511
+ }
2512
+ assertDeviceApprovalFlow(input.flow);
2513
+ if (typeof input.deviceCode !== "string" || !input.deviceCode.trim()) {
2514
+ throw invalidInput("deviceCode", input.deviceCode, "is required (from beginDeviceApproval)");
2515
+ }
2516
+ let raw;
2517
+ try {
2518
+ raw = await this.http.post(
2519
+ deviceApprovalSettlePath(input.flow, input.transactionId),
2520
+ { device_code: input.deviceCode },
2521
+ { kind: "bearer", token: input.playerToken },
2522
+ // PLAYER token — never the game secret
2523
+ { signal: opts?.signal }
2524
+ // NOT idempotent — the device_code is single-use; never auto-retried
2525
+ );
2526
+ } catch (err) {
2527
+ if (err instanceof InvoError && err.isTransactionNotPending) {
2528
+ const body = err.body && typeof err.body === "object" ? err.body : {};
2529
+ const currentStatus = err.currentTransactionStatus ?? "";
2530
+ return {
2531
+ status: "not_pending",
2532
+ transactionId: input.transactionId,
2533
+ flow: input.flow,
2534
+ alreadySettled: currentStatus !== "" && isPastThisStep(input.flow, currentStatus),
2535
+ currentStatus: currentStatus || void 0,
2536
+ raw: body
2537
+ };
2538
+ }
2539
+ throw err;
2540
+ }
2541
+ return toDeviceApprovalSettleResult(raw, input);
2542
+ }
2543
+ /**
2544
+ * Convenience only — stages 3 and 4 in one call, for a server that can hold the loop
2545
+ * open (a per-request worker, a job). Polls `pollDeviceApproval` on `interval`, adds
2546
+ * 5 s on `slow_down`, forwards the poll's `enrollment` to `onEnrollment` (answer with
2547
+ * `respond`), and on `approved` calls `approveWithDeviceCode` — THEN resolves.
2548
+ * `respond` is best-effort: a prompt the grant has outlived (`expired_token`,
2549
+ * `invalid_grant`) or that was already answered elsewhere resolves quietly rather than
2550
+ * rejecting, because callers fire it from UI code without awaiting it.
2551
+ * You still call `beginDeviceApproval` yourself first, because your game has to draw
2552
+ * the QR between begin and the first poll.
2553
+ *
2554
+ * Resolves `{ status: "approved", settlement }` | `denied` | `expired` | `aborted`.
2555
+ * Rejects on `invalid_grant`, on a refused approve (e.g. `PASSKEY_RECOVERY_COOLDOWN`),
2556
+ * and after 5 consecutive transport failures on the poll.
2557
+ *
2558
+ * **Record the attempt in your own store BEFORE you call this.** It blocks for as long
2559
+ * as the player takes and then moves money from inside the loop, so if your process
2560
+ * dies between the approve call and its response, a row you wrote first — plus
2561
+ * `getTransferStatus` / `getSendStatus` — is the only way to learn whether the money
2562
+ * moved. Servers that must not block a request use the three calls directly and keep
2563
+ * `deviceCode` in their own store.
2564
+ *
2565
+ * `respond` (handed to `onEnrollment`) is best-effort: a prompt the grant has outlived
2566
+ * resolves quietly rather than rejecting. Any other confirm-enrollment refusal
2567
+ * propagates, so `await` it if you want to see one.
2568
+ */
2569
+ async completeDeviceApproval(input, opts) {
2570
+ assertPlayerToken(input.playerToken);
2571
+ if (typeof input.transactionId !== "string" || !input.transactionId.trim()) {
2572
+ throw invalidInput("transactionId", input.transactionId, "is required");
2573
+ }
2574
+ assertDeviceApprovalFlow(input.flow);
2575
+ if (typeof input.deviceCode !== "string" || !input.deviceCode.trim()) {
2576
+ throw invalidInput("deviceCode", input.deviceCode, "is required (from beginDeviceApproval)");
2577
+ }
2578
+ const signal = input.signal ?? opts?.signal;
2579
+ const { playerToken, deviceCode } = input;
2580
+ let interval = Math.max(1, Number(input.interval) || 5);
2581
+ let lastPoll;
2582
+ let lastEnrollmentKey = null;
2583
+ let transientFailures = 0;
2584
+ const MAX_TRANSIENT = 5;
2585
+ const respond = async (decision) => {
2586
+ try {
2587
+ await this.confirmDeviceEnrollment({ playerToken, deviceCode, decision }, { signal });
2588
+ } catch (err) {
2589
+ if (err instanceof InvoError && (err.code === "DEVICE_APPROVAL_ENROLLMENT_ALREADY_DECIDED" || err.code === "DEVICE_APPROVAL_NO_ENROLLMENT_PENDING" || err.code === "expired_token" || err.code === "invalid_grant")) {
2590
+ return;
2591
+ }
2592
+ throw err;
2593
+ }
2594
+ };
2595
+ const publishEnrollment = (e) => {
2596
+ if (!input.onEnrollment) return;
2597
+ const key = e ? `${e.state}|${e.matchCode}|${e.deviceLabel}|${e.recovery}` : null;
2598
+ if (key === lastEnrollmentKey) return;
2599
+ lastEnrollmentKey = key;
2600
+ input.onEnrollment(e ?? null, respond);
2601
+ };
2602
+ for (; ; ) {
2603
+ await sleepFor(interval * 1e3, signal);
2604
+ if (signal?.aborted) return { status: "aborted", lastPoll };
2605
+ let poll;
2606
+ try {
2607
+ poll = await this.pollDeviceApproval({ playerToken, deviceCode }, { signal });
2608
+ } catch (err) {
2609
+ if (signal?.aborted) return { status: "aborted", lastPoll };
2610
+ const transient = err instanceof InvoError && (err.status === 0 || err.status === 429 || err.status >= 500);
2611
+ if (transient && ++transientFailures < MAX_TRANSIENT) {
2612
+ const ra = err instanceof InvoError && err.status === 429 ? err.retryAfter : void 0;
2613
+ if (typeof ra === "number" && ra > interval) interval = ra;
2614
+ continue;
2615
+ }
2616
+ throw err;
2617
+ }
2618
+ transientFailures = 0;
2619
+ lastPoll = poll;
2620
+ switch (poll.status) {
2621
+ case "authorization_pending":
2622
+ if (poll.interval) interval = poll.interval;
2623
+ publishEnrollment(poll.enrollment);
2624
+ continue;
2625
+ case "slow_down":
2626
+ interval = Math.max(interval + 5, poll.interval ?? 0);
2627
+ continue;
2628
+ case "expired_token":
2629
+ publishEnrollment(void 0);
2630
+ return { status: "expired", lastPoll };
2631
+ case "access_denied":
2632
+ publishEnrollment(void 0);
2633
+ return { status: "denied", lastPoll };
2634
+ case "approved": {
2635
+ publishEnrollment(void 0);
2636
+ const settlement = await this.approveWithDeviceCode(
2637
+ { playerToken, transactionId: input.transactionId, flow: input.flow, deviceCode },
2638
+ { signal }
2639
+ );
2640
+ return { status: "approved", settlement, lastPoll };
2641
+ }
2642
+ }
2643
+ }
2644
+ }
1371
2645
  toInitiateResult(raw) {
1372
2646
  const vm = raw["verification_method"];
1373
2647
  const guardian = raw["guardian_approval"];
@@ -1380,6 +2654,6 @@ var InvoServer = class {
1380
2654
  }
1381
2655
  };
1382
2656
 
1383
- export { InvoServer, PlatformCommerceServer, createWebhookHandler, verifyWebhook, verifyWebhookAsync };
2657
+ export { CardsServer, InvoServer, PlatformCommerceServer, SDK_VERSION, SandboxServer, SandboxSubscriptionsServer, SubscriptionsServer, createWebhookHandler, verifyWebhook, verifyWebhookAsync };
1384
2658
  //# sourceMappingURL=server.js.map
1385
2659
  //# sourceMappingURL=server.js.map