@invonetwork/web-sdk 3.7.0 → 3.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.cjs CHANGED
@@ -348,6 +348,7 @@ var InvoError = class _InvoError extends Error {
348
348
  * instead of the backend's vocabulary. Only `Init` (and an absent status)
349
349
  * can mean "not yet"; every named status that is not Init is an outcome. */
350
350
  get isSteamAuthorizationPending() {
351
+ if (this.code === "STEAM_AUTHORIZATION_PENDING") return true;
351
352
  const b = this.body;
352
353
  if (!b || b["status"] !== "not_authorized") return false;
353
354
  const st = String(b["steam_status"] ?? "").toLowerCase();
@@ -470,6 +471,102 @@ var InvoError = class _InvoError extends Error {
470
471
  const v = this.bodyObject()["error_ref"];
471
472
  return typeof v === "string" && v ? v : void 0;
472
473
  }
474
+ // ---- Subscriptions ----
475
+ /**
476
+ * True when a create (`subscriptions.create` / `steamInit`) was refused because the
477
+ * player already has a LIVE subscription to this `itemId` (`ACTIVE_SUBSCRIPTION_EXISTS`,
478
+ * 409). Use `existingSubscriptionId`. This is what you hit if you regenerate
479
+ * `clientRequestId` inside a retry loop: replay the same key instead.
480
+ */
481
+ get isActiveSubscriptionExists() {
482
+ return this.code === "ACTIVE_SUBSCRIPTION_EXISTS";
483
+ }
484
+ /**
485
+ * The `subscription_id` a create refusal names: the LIVE subscription on
486
+ * `ACTIVE_SUBSCRIPTION_EXISTS`, the PENDING Steam row on `STEAM_AUTHORIZATION_PENDING`,
487
+ * or the abandoned (now `expired`) row when a Steam-side failure abandoned it after creation.
488
+ */
489
+ get existingSubscriptionId() {
490
+ const v = this.bodyObject()["subscription_id"];
491
+ return typeof v === "string" && v ? v : void 0;
492
+ }
493
+ /**
494
+ * True when the same `clientRequestId` was replayed for the same player and item but
495
+ * with DIFFERENT material terms (`IDEMPOTENT_REPLAY_MISMATCH`, 409). See
496
+ * `mismatchedFields` (any of `amount_usd`, `interval`, `interval_count`, `wallet_only`,
497
+ * `funding_rail`). To change terms use `changeAmount` / `setPaymentMethod`; to create a
498
+ * new subscription use a new key.
499
+ */
500
+ get isIdempotentReplayMismatch() {
501
+ return this.code === "IDEMPOTENT_REPLAY_MISMATCH";
502
+ }
503
+ /** The `mismatched_fields` on an `IDEMPOTENT_REPLAY_MISMATCH` 409. */
504
+ get mismatchedFields() {
505
+ const v = this.bodyObject()["mismatched_fields"];
506
+ return Array.isArray(v) ? v.filter((x) => typeof x === "string") : [];
507
+ }
508
+ /**
509
+ * True when `changeAmount` tried to RAISE the price of a Steam subscription
510
+ * (`STEAM_REAUTHORIZATION_REQUIRED`, 409). The member consented to a ceiling; start a
511
+ * new Steam subscription at the new price and cancel this one. Decreases stage normally.
512
+ * The body carries `current_amount_usd` and `requested_amount_usd`.
513
+ */
514
+ get isSteamReauthorizationRequired() {
515
+ return this.code === "STEAM_REAUTHORIZATION_REQUIRED";
516
+ }
517
+ /** True when `setPaymentMethod` was called on a Steam subscription (`NOT_A_CARD_SUBSCRIPTION`, 409). A rail is fixed at creation. */
518
+ get isNotACardSubscription() {
519
+ return this.code === "NOT_A_CARD_SUBSCRIPTION";
520
+ }
521
+ /**
522
+ * True when a Steam subscription was started with a key for a non-Steam channel
523
+ * (`STEAM_CHANNEL_REQUIRED`, 409). Use the primary game key or the `steam` channel key.
524
+ */
525
+ get isSteamChannelRequired() {
526
+ return this.code === "STEAM_CHANNEL_REQUIRED";
527
+ }
528
+ /**
529
+ * True when `subscriptions.refund` targeted a period that was charged through Steam
530
+ * (`STEAM_REFUND_NOT_SUPPORTED`, 409). Refunds of Steam-charged periods are not
531
+ * supported yet; periods of a Steam subscription that the wallet covered entirely
532
+ * remain refundable in coins.
533
+ */
534
+ get isSteamRefundNotSupported() {
535
+ return this.code === "STEAM_REFUND_NOT_SUPPORTED";
536
+ }
537
+ /** True when the subscription is `canceled` or `expired` and the call cannot apply (`SUBSCRIPTION_TERMINAL`, 409). Start a new one. */
538
+ get isSubscriptionTerminal() {
539
+ return this.code === "SUBSCRIPTION_TERMINAL";
540
+ }
541
+ /**
542
+ * True when `subscriptions.steamFinalize` was called before the member completed the
543
+ * Steam authorisation (409, body `status: "not_authorized"`, with `steam_status`).
544
+ * THE NORMAL WAIT STATE: call finalize again after the overlay or checkout closes.
545
+ * The member has 24 hours; after that the row expires.
546
+ */
547
+ get isNotAuthorized() {
548
+ return this.bodyObject()["status"] === "not_authorized";
549
+ }
550
+ /**
551
+ * True when a sandbox clock call was refused for a missing, wrong or never-issued
552
+ * `X-Sandbox-Clock-Key` (`SANDBOX_CLOCK_UNAUTHORIZED`, 401). Reveal or rotate the key on
553
+ * the game's Game Settings page in the sandbox console.
554
+ */
555
+ get isSandboxClockUnauthorized() {
556
+ return this.code === "SANDBOX_CLOCK_UNAUTHORIZED";
557
+ }
558
+ /**
559
+ * True when INVO has paused this flow for maintenance (503): `flow_paused` on create /
560
+ * amount / payment-method / Steam init / card setup, `FLOW_PAUSED` on refund and the
561
+ * sandbox clock. Retry later WITH THE SAME idempotency key.
562
+ */
563
+ get isFlowPaused() {
564
+ return this.code === "flow_paused" || this.code === "FLOW_PAUSED";
565
+ }
566
+ /** True when a create was refused because the game is not `live` (`GAME_NOT_LIVE`, 403). Make it live in the console. */
567
+ get isGameNotLive() {
568
+ return this.code === "GAME_NOT_LIVE";
569
+ }
473
570
  /** Seconds to wait before retrying, when the backend throttled the call (429 `retry_after`). */
474
571
  get retryAfter() {
475
572
  const v = this.bodyObject()["retry_after"];
@@ -543,11 +640,11 @@ var _Http = class _Http {
543
640
  * (e.g. single-use WebAuthn assertions) are NEVER auto-retried.
544
641
  */
545
642
  async post(path, body, auth, opts) {
546
- return this.request("POST", path, body, auth, opts?.idempotent ?? false, opts?.signal);
643
+ return this.request("POST", path, body, auth, opts?.idempotent ?? false, opts?.signal, opts?.headers);
547
644
  }
548
645
  // GET is always idempotent → safe to retry.
549
646
  async get(path, auth, opts) {
550
- return this.request("GET", path, void 0, auth, true, opts?.signal);
647
+ return this.request("GET", path, void 0, auth, true, opts?.signal, opts?.headers);
551
648
  }
552
649
  authHeaders(auth) {
553
650
  switch (auth.kind) {
@@ -559,10 +656,13 @@ var _Http = class _Http {
559
656
  return {};
560
657
  }
561
658
  }
562
- async request(method, path, body, auth, idempotent, signal) {
659
+ async request(method, path, body, auth, idempotent, signal, extraHeaders) {
563
660
  const url = `${this.baseUrl}${path}`;
564
661
  const headers = {
565
662
  Accept: "application/json",
663
+ ...this.authHeaders(auth),
664
+ // Per-call extras (e.g. the sandbox clock key) — never able to override the auth header.
665
+ ...extraHeaders ?? {},
566
666
  ...this.authHeaders(auth)
567
667
  };
568
668
  if (this.userAgent) headers["User-Agent"] = this.userAgent;
@@ -748,6 +848,9 @@ function toDestinationsResult(raw, direction) {
748
848
  raw
749
849
  };
750
850
  }
851
+
852
+ // src/version.ts
853
+ var SDK_VERSION = "3.8.0";
751
854
  var DEFAULT_TOLERANCE_SEC = 300;
752
855
  var ENCODER = new TextEncoder();
753
856
  function toBytes(body) {
@@ -913,7 +1016,7 @@ async function hmacHexSubtle(secret, message) {
913
1016
  }
914
1017
 
915
1018
  // src/server.ts
916
- var DEFAULT_UA = "invonetwork-web-sdk/3.0.0 (+https://invo.network)";
1019
+ var DEFAULT_UA = `invonetwork-web-sdk/${SDK_VERSION} (+https://invo.network)`;
917
1020
  var MAX_USD_AMOUNT = 999.99;
918
1021
  var MAX_ITEM_PRICE = 999999.99;
919
1022
  function invalidInput(label, value, why) {
@@ -1393,6 +1496,855 @@ var PlatformCommerceServer = class {
1393
1496
  };
1394
1497
  }
1395
1498
  };
1499
+ var SUBSCRIPTION_MAX_USD = 999999.99;
1500
+ var SUBSCRIPTION_INTERVALS = /* @__PURE__ */ new Set(["month", "year"]);
1501
+ var SANDBOX_FAILURE_OUTCOMES = /* @__PURE__ */ new Set([
1502
+ "card_declined",
1503
+ "insufficient_funds",
1504
+ "error"
1505
+ ]);
1506
+ function assertClientRequestId(value, label) {
1507
+ if (typeof value !== "string" || !value.trim()) throw invalidInput(label, value, "is required");
1508
+ if (value.length > 255) throw invalidInput(label, value, "must be at most 255 characters");
1509
+ if (/^sub_/i.test(value)) throw invalidInput(label, value, 'must not begin with "sub_" (reserved)');
1510
+ }
1511
+ function assertSubscriptionId(value) {
1512
+ if (typeof value !== "string" || !value.trim()) {
1513
+ throw invalidInput("subscriptionId", value, "is required");
1514
+ }
1515
+ }
1516
+ function subscriptionMoney(value, label) {
1517
+ const n = parseMoney(value, SUBSCRIPTION_MAX_USD, label);
1518
+ return typeof value === "number" ? n.toFixed(2) : value;
1519
+ }
1520
+ function toSavedCard(row) {
1521
+ if (!row || typeof row !== "object") return null;
1522
+ const r = row;
1523
+ return {
1524
+ id: Number(r["id"]),
1525
+ lastFour: String(r["last_four"] ?? ""),
1526
+ brand: String(r["brand"] ?? ""),
1527
+ expMonth: Number(r["exp_month"] ?? 0),
1528
+ expYear: Number(r["exp_year"] ?? 0),
1529
+ createdAt: String(r["created_at"] ?? ""),
1530
+ raw: r
1531
+ };
1532
+ }
1533
+ function nullableString(v) {
1534
+ return v == null ? null : String(v);
1535
+ }
1536
+ function toSubscription(row) {
1537
+ const r = row && typeof row === "object" ? row : {};
1538
+ const share = r["revenue_share"];
1539
+ const consent = r["consent"] ?? {};
1540
+ return {
1541
+ subscriptionId: String(r["subscription_id"] ?? ""),
1542
+ gameId: String(r["game_id"] ?? ""),
1543
+ playerId: Number(r["player_id"] ?? 0),
1544
+ clientRequestId: String(r["client_request_id"] ?? ""),
1545
+ status: String(r["status"] ?? ""),
1546
+ amountUsd: String(r["amount_usd"] ?? ""),
1547
+ pendingAmountUsd: nullableString(r["pending_amount_usd"]),
1548
+ interval: String(r["interval"] ?? "month"),
1549
+ intervalCount: Number(r["interval_count"] ?? 1),
1550
+ itemId: String(r["item_id"] ?? ""),
1551
+ itemName: nullableString(r["item_name"]),
1552
+ currentPeriodStart: String(r["current_period_start"] ?? ""),
1553
+ currentPeriodEnd: String(r["current_period_end"] ?? ""),
1554
+ periodSeq: Number(r["period_seq"] ?? 0),
1555
+ nextChargeAt: nullableString(r["next_charge_at"]),
1556
+ cancelAtPeriodEnd: r["cancel_at_period_end"] === true,
1557
+ trialEnd: nullableString(r["trial_end"]),
1558
+ canceledAt: nullableString(r["canceled_at"]),
1559
+ endedAt: nullableString(r["ended_at"]),
1560
+ walletOnly: r["wallet_only"] === true,
1561
+ hasPaymentMethod: r["has_payment_method"] === true,
1562
+ fundingRail: String(r["funding_rail"] ?? "card"),
1563
+ steamAgreementStatus: nullableString(r["steam_agreement_status"]),
1564
+ metadata: r["metadata"] && typeof r["metadata"] === "object" ? r["metadata"] : null,
1565
+ consent: {
1566
+ consent_at: nullableString(consent["consent_at"]),
1567
+ consent_ip: nullableString(consent["consent_ip"]),
1568
+ consent_user_agent: nullableString(consent["consent_user_agent"]),
1569
+ disclosed_amount_usd: nullableString(consent["disclosed_amount_usd"]),
1570
+ disclosed_interval: nullableString(consent["disclosed_interval"]),
1571
+ terms_version: nullableString(consent["terms_version"])
1572
+ },
1573
+ createdAt: String(r["created_at"] ?? ""),
1574
+ updatedAt: String(r["updated_at"] ?? ""),
1575
+ revenueShare: share && typeof share === "object" ? {
1576
+ recipientPlayerId: Number(share["recipient_player_id"] ?? 0),
1577
+ percent: String(share["percent"] ?? ""),
1578
+ // Attribution only: INVO never pays the recipient. Read the wire value, never assume.
1579
+ settledByInvo: share["settled_by_invo"] === true
1580
+ } : null,
1581
+ paidThrough: nullableString(r["paid_through"]),
1582
+ amountCoinsEstimate: r["amount_coins_estimate"] == null ? void 0 : String(r["amount_coins_estimate"]),
1583
+ raw: r
1584
+ };
1585
+ }
1586
+ function toFirstCharge(row) {
1587
+ const r = row && typeof row === "object" ? row : {};
1588
+ return {
1589
+ status: String(r["status"] ?? "pending"),
1590
+ amountUsd: nullableString(r["amount_usd"]),
1591
+ paidPeriodSeq: typeof r["paid_period_seq"] === "number" ? r["paid_period_seq"] : null,
1592
+ paidThrough: nullableString(r["paid_through"]),
1593
+ failureCode: nullableString(r["failure_code"]),
1594
+ nextRetryAt: nullableString(r["next_retry_at"]),
1595
+ confirmationUrl: nullableString(r["confirmation_url"]),
1596
+ expiresAt: nullableString(r["expires_at"]),
1597
+ message: nullableString(r["message"]),
1598
+ raw: r
1599
+ };
1600
+ }
1601
+ function toSubscriptionResult(raw) {
1602
+ return {
1603
+ status: String(raw["status"] ?? ""),
1604
+ idempotentReplay: raw["idempotent_replay"] === true,
1605
+ subscription: toSubscription(raw["subscription"]),
1606
+ card: toSavedCard(raw["card"]),
1607
+ firstCharge: toFirstCharge(raw["first_charge"]),
1608
+ warning: typeof raw["warning"] === "string" ? raw["warning"] : void 0,
1609
+ raw
1610
+ };
1611
+ }
1612
+ function toSandboxClockState(row) {
1613
+ if (!row || typeof row !== "object") return null;
1614
+ const r = row;
1615
+ return {
1616
+ status: String(r["status"] ?? ""),
1617
+ periodSeq: Number(r["period_seq"] ?? 0),
1618
+ currentPeriodStart: nullableString(r["current_period_start"]),
1619
+ currentPeriodEnd: nullableString(r["current_period_end"]),
1620
+ nextChargeAt: nullableString(r["next_charge_at"]),
1621
+ trialEnd: nullableString(r["trial_end"]),
1622
+ cancelAtPeriodEnd: r["cancel_at_period_end"] === true,
1623
+ walletOnly: r["wallet_only"] === true,
1624
+ hasPaymentMethod: r["has_payment_method"] === true,
1625
+ amountUsd: String(r["amount_usd"] ?? ""),
1626
+ raw: r
1627
+ };
1628
+ }
1629
+ function optNumber(v) {
1630
+ return typeof v === "number" && Number.isFinite(v) ? v : void 0;
1631
+ }
1632
+ function toSandboxClockResult(raw) {
1633
+ const before = toSandboxClockState(raw["before"]);
1634
+ const after = toSandboxClockState(raw["after"]);
1635
+ const stats = raw["engine_stats"];
1636
+ return {
1637
+ status: String(raw["status"] ?? ""),
1638
+ action: String(raw["action"] ?? ""),
1639
+ // advance-clock reports before/after rather than a `subscription` block; surface
1640
+ // `after` there so every tool answers "where is the clock now" in one place.
1641
+ subscription: toSandboxClockState(raw["subscription"]) ?? after,
1642
+ before: before ?? void 0,
1643
+ after: after ?? void 0,
1644
+ intervals: optNumber(raw["intervals"]),
1645
+ intervalsAppliedToWindow: optNumber(raw["intervals_applied_to_window"]),
1646
+ windowMoved: typeof raw["window_moved"] === "boolean" ? raw["window_moved"] : void 0,
1647
+ windowAlreadyElapsed: typeof raw["window_already_elapsed"] === "boolean" ? raw["window_already_elapsed"] : void 0,
1648
+ engineStats: stats && typeof stats === "object" ? stats : void 0,
1649
+ periodSeq: optNumber(raw["period_seq"]),
1650
+ attemptNo: optNumber(raw["attempt_no"]),
1651
+ amountUsd: raw["amount_usd"] == null ? void 0 : String(raw["amount_usd"]),
1652
+ amountCoins: raw["amount_coins"] == null ? void 0 : String(raw["amount_coins"]),
1653
+ retired: typeof raw["retired"] === "boolean" ? raw["retired"] : void 0,
1654
+ retryBudgetUsed: optNumber(raw["retry_budget_used"]),
1655
+ retryScheduleDays: Array.isArray(raw["retry_schedule_days"]) ? raw["retry_schedule_days"].map(Number) : void 0,
1656
+ retriesRemaining: optNumber(raw["retries_remaining"]),
1657
+ authChallengesUsed: optNumber(raw["auth_challenges_used"]),
1658
+ maxAuthChallenges: optNumber(raw["max_auth_challenges"]),
1659
+ downgradedToDecline: typeof raw["downgraded_to_decline"] === "boolean" ? raw["downgraded_to_decline"] : void 0,
1660
+ note: typeof raw["note"] === "string" ? raw["note"] : void 0,
1661
+ raw
1662
+ };
1663
+ }
1664
+ function subscriptionBaseBody(input) {
1665
+ assertClientRequestId(input.clientRequestId, "clientRequestId");
1666
+ for (const [k, v] of [
1667
+ ["playerEmail", input.playerEmail],
1668
+ ["playerName", input.playerName],
1669
+ ["itemId", input.itemId]
1670
+ ]) {
1671
+ if (typeof v !== "string" || !v.trim()) throw invalidInput(k, v, "is required");
1672
+ }
1673
+ if (input.interval !== void 0 && !SUBSCRIPTION_INTERVALS.has(input.interval)) {
1674
+ throw invalidInput("interval", input.interval, 'must be "month" or "year"');
1675
+ }
1676
+ if (input.playerPhone !== void 0) assertE164(input.playerPhone, "playerPhone");
1677
+ const body = {
1678
+ client_request_id: input.clientRequestId,
1679
+ player_email: input.playerEmail,
1680
+ player_name: input.playerName,
1681
+ item_id: input.itemId,
1682
+ amount_usd: subscriptionMoney(input.amountUsd, "amountUsd")
1683
+ };
1684
+ if (input.playerPhone) body["player_phone"] = input.playerPhone;
1685
+ if (input.itemName) body["item_name"] = input.itemName;
1686
+ if (input.interval) body["interval"] = input.interval;
1687
+ if (input.metadata) body["metadata"] = input.metadata;
1688
+ if (input.consent) {
1689
+ const c = input.consent;
1690
+ const consent = {};
1691
+ if (c.consentAt !== void 0) consent["consent_at"] = c.consentAt;
1692
+ if (c.consentIp !== void 0) consent["consent_ip"] = c.consentIp;
1693
+ if (c.consentUserAgent !== void 0) consent["consent_user_agent"] = c.consentUserAgent;
1694
+ if (c.disclosedAmountUsd !== void 0) consent["disclosed_amount_usd"] = c.disclosedAmountUsd;
1695
+ if (c.disclosedInterval !== void 0) consent["disclosed_interval"] = c.disclosedInterval;
1696
+ if (c.termsVersion !== void 0) consent["terms_version"] = c.termsVersion;
1697
+ body["consent"] = consent;
1698
+ }
1699
+ if (input.revenueShare) {
1700
+ const s = input.revenueShare;
1701
+ const hasEmail = typeof s.recipientPlayerEmail === "string" && s.recipientPlayerEmail.trim() !== "";
1702
+ const hasId = s.recipientPlayerId != null;
1703
+ if (hasEmail === hasId) {
1704
+ throw invalidInput(
1705
+ "revenueShare",
1706
+ s,
1707
+ "requires EXACTLY ONE of recipientPlayerEmail or recipientPlayerId"
1708
+ );
1709
+ }
1710
+ const share = {
1711
+ percent: typeof s.percent === "number" ? s.percent.toFixed(2) : s.percent
1712
+ };
1713
+ if (hasEmail) share["recipient_player_email"] = s.recipientPlayerEmail;
1714
+ else share["recipient_player_id"] = s.recipientPlayerId;
1715
+ body["revenue_share"] = share;
1716
+ }
1717
+ return body;
1718
+ }
1719
+ var SubscriptionsServer = class {
1720
+ constructor(http, auth) {
1721
+ this.http = http;
1722
+ this.auth = auth;
1723
+ }
1724
+ /**
1725
+ * Create a CARD-rail subscription. **Charges the first period before responding**
1726
+ * (unless it is a trial), so expect the call to take as long as a card charge.
1727
+ *
1728
+ * Branch on `result.firstCharge.status`: `paid` (grant until `paidThrough`),
1729
+ * `requires_action` (NOTHING charged; send the member to `confirmationUrl`),
1730
+ * `skipped_trial` (grant trial access until `subscription.trialEnd`), `failed` (in
1731
+ * dunning; INVO retries at `nextRetryAt`), `pending` (wait for the event).
1732
+ *
1733
+ * Idempotent on `clientRequestId`: a repeat returns HTTP 200 with the identical shape
1734
+ * and `idempotentReplay: true`, and NOTHING is charged again. **On any timeout or 5xx,
1735
+ * replay the same key before you do anything else**; a fresh key inside a retry loop
1736
+ * lands on `409 ACTIVE_SUBSCRIPTION_EXISTS` (`err.isActiveSubscriptionExists`,
1737
+ * `err.existingSubscriptionId`) at best and a second subscription at worst. Same key
1738
+ * with different terms is `err.isIdempotentReplayMismatch` (`err.mismatchedFields`).
1739
+ *
1740
+ * Card selection: `playerCardId` names one (from `cards.list`); omitted, INVO attaches
1741
+ * the member's newest unexpired saved card; `walletOnly: true` never charges a card.
1742
+ * Requires the game to be `live` (`err.isGameNotLive`).
1743
+ */
1744
+ async create(input, opts) {
1745
+ const body = subscriptionBaseBody(input);
1746
+ if (input.intervalCount !== void 0) {
1747
+ if (!Number.isInteger(input.intervalCount) || input.intervalCount < 1 || input.intervalCount > 36) {
1748
+ throw invalidInput("intervalCount", input.intervalCount, "must be an integer 1..36");
1749
+ }
1750
+ body["interval_count"] = input.intervalCount;
1751
+ }
1752
+ if (input.trialDays !== void 0) {
1753
+ if (!Number.isInteger(input.trialDays) || input.trialDays < 1 || input.trialDays > 365) {
1754
+ throw invalidInput("trialDays", input.trialDays, "must be an integer 1..365");
1755
+ }
1756
+ body["trial_days"] = input.trialDays;
1757
+ }
1758
+ if (input.trialEnd !== void 0) {
1759
+ if (typeof input.trialEnd !== "string" || Number.isNaN(Date.parse(input.trialEnd))) {
1760
+ throw invalidInput("trialEnd", input.trialEnd, "must be an ISO 8601 timestamp");
1761
+ }
1762
+ body["trial_end"] = input.trialEnd;
1763
+ }
1764
+ if (input.walletOnly !== void 0) {
1765
+ if (typeof input.walletOnly !== "boolean") {
1766
+ throw invalidInput("walletOnly", input.walletOnly, "must be a boolean");
1767
+ }
1768
+ body["wallet_only"] = input.walletOnly;
1769
+ }
1770
+ if (input.playerCardId !== void 0) {
1771
+ if (!Number.isInteger(input.playerCardId) || input.playerCardId < 1) {
1772
+ throw invalidInput("playerCardId", input.playerCardId, "must be a positive integer card id (from cards.list)");
1773
+ }
1774
+ if (input.walletOnly === true) {
1775
+ throw invalidInput("playerCardId", input.playerCardId, "cannot be combined with walletOnly: true");
1776
+ }
1777
+ body["player_card_id"] = input.playerCardId;
1778
+ }
1779
+ const raw = await this.http.post(
1780
+ "/api/subscriptions/subscribe",
1781
+ body,
1782
+ this.auth,
1783
+ // Idempotent on client_request_id: a lost-response retry REPLAYS the row (200,
1784
+ // idempotent_replay: true) and never charges twice. Replay before retry.
1785
+ { idempotent: true, signal: opts?.signal }
1786
+ );
1787
+ return toSubscriptionResult(raw);
1788
+ }
1789
+ /** Read one subscription. `404 SUBSCRIPTION_NOT_FOUND` for an id that is not your game's. */
1790
+ async get(subscriptionId, options, opts) {
1791
+ assertSubscriptionId(subscriptionId);
1792
+ const qs = options?.includePlayer ? "?include_player=true" : "";
1793
+ const raw = await this.http.get(
1794
+ `/api/subscriptions/${encodeURIComponent(subscriptionId)}${qs}`,
1795
+ this.auth,
1796
+ { signal: opts?.signal }
1797
+ );
1798
+ return {
1799
+ subscription: toSubscription(raw["subscription"]),
1800
+ player: raw["player"] && typeof raw["player"] === "object" ? raw["player"] : void 0,
1801
+ raw
1802
+ };
1803
+ }
1804
+ /**
1805
+ * List a member's subscriptions, newest first, paged (`limit` 1..100, `offset`
1806
+ * 0..100000). `status` filters; `"live"` expands to the four live statuses and may be
1807
+ * mixed in (`["live", "canceled"]`). A player who does not exist yet is an empty list
1808
+ * with `totalCount: 0`, not a 404.
1809
+ */
1810
+ async listForPlayer(playerEmail, options, opts) {
1811
+ if (typeof playerEmail !== "string" || !playerEmail.trim()) {
1812
+ throw invalidInput("playerEmail", playerEmail, "is required");
1813
+ }
1814
+ const q = new URLSearchParams();
1815
+ q.set("player_email", playerEmail);
1816
+ if (options?.status !== void 0) {
1817
+ const list = Array.isArray(options.status) ? options.status : [options.status];
1818
+ if (list.length) q.set("status", list.join(","));
1819
+ }
1820
+ if (options?.includePlayer) q.set("include_player", "true");
1821
+ if (options?.limit != null) {
1822
+ if (!Number.isInteger(options.limit) || options.limit < 1 || options.limit > 100) {
1823
+ throw invalidInput("limit", options.limit, "must be an integer 1..100");
1824
+ }
1825
+ q.set("limit", String(options.limit));
1826
+ }
1827
+ if (options?.offset != null) {
1828
+ if (!Number.isInteger(options.offset) || options.offset < 0 || options.offset > 1e5) {
1829
+ throw invalidInput("offset", options.offset, "must be an integer 0..100000");
1830
+ }
1831
+ q.set("offset", String(options.offset));
1832
+ }
1833
+ const raw = await this.http.get(
1834
+ `/api/subscriptions/player?${q.toString()}`,
1835
+ this.auth,
1836
+ { signal: opts?.signal }
1837
+ );
1838
+ const rows = Array.isArray(raw["subscriptions"]) ? raw["subscriptions"] : [];
1839
+ const p = raw["pagination"] ?? {};
1840
+ return {
1841
+ playerEmail: String(raw["player_email"] ?? playerEmail),
1842
+ subscriptions: rows.map(toSubscription),
1843
+ pagination: {
1844
+ totalCount: Number(p["total_count"] ?? rows.length),
1845
+ limit: Number(p["limit"] ?? 50),
1846
+ offset: Number(p["offset"] ?? 0),
1847
+ hasMore: p["has_more"] === true
1848
+ },
1849
+ raw
1850
+ };
1851
+ }
1852
+ /**
1853
+ * Cancel. `atPeriodEnd` defaults to `true`: the subscription stays live with
1854
+ * `cancelAtPeriodEnd: true` and is retired at `paidThrough` without another charge.
1855
+ * If nothing has been paid (or the paid window has elapsed) an at-period-end cancel is
1856
+ * **downgraded to immediate**: read `terminatedImmediately`. `atPeriodEnd: false` ends
1857
+ * it now. Revoke access at `accessUntil`.
1858
+ *
1859
+ * Cancelling an already-terminal subscription is a 200 with `alreadyCanceled: true`
1860
+ * (never thrown), so a batch reconciler needs no special case; that is also what makes
1861
+ * a lost-response retry safe. One `subscription.canceled` event fires at request time.
1862
+ * Never blocked by a maintenance pause.
1863
+ */
1864
+ async cancel(subscriptionId, options, opts) {
1865
+ assertSubscriptionId(subscriptionId);
1866
+ const body = {};
1867
+ if (options?.atPeriodEnd !== void 0) {
1868
+ if (typeof options.atPeriodEnd !== "boolean") {
1869
+ throw invalidInput("atPeriodEnd", options.atPeriodEnd, "must be a boolean");
1870
+ }
1871
+ body["at_period_end"] = options.atPeriodEnd;
1872
+ }
1873
+ if (options?.reason !== void 0) {
1874
+ if (typeof options.reason !== "string" || options.reason.length > 500) {
1875
+ throw invalidInput("reason", options.reason, "must be a string of at most 500 characters");
1876
+ }
1877
+ body["reason"] = options.reason;
1878
+ }
1879
+ const raw = await this.http.post(
1880
+ `/api/subscriptions/${encodeURIComponent(subscriptionId)}/cancel`,
1881
+ body,
1882
+ this.auth,
1883
+ // Safe to retry: a repeat on an already-canceled row is a 200 (already_canceled: true).
1884
+ { idempotent: true, signal: opts?.signal }
1885
+ );
1886
+ return {
1887
+ status: String(raw["status"] ?? ""),
1888
+ alreadyCanceled: raw["already_canceled"] === true,
1889
+ finalStatus: typeof raw["final_status"] === "string" ? raw["final_status"] : void 0,
1890
+ cancelAtPeriodEnd: raw["cancel_at_period_end"] === true,
1891
+ effectiveAt: nullableString(raw["effective_at"]),
1892
+ currentPeriodEnd: nullableString(raw["current_period_end"]),
1893
+ accessUntil: nullableString(raw["access_until"]),
1894
+ paidThrough: nullableString(raw["paid_through"]),
1895
+ terminatedImmediately: raw["terminated_immediately"] === true,
1896
+ downgradeReason: typeof raw["downgrade_reason"] === "string" ? raw["downgrade_reason"] : void 0,
1897
+ message: typeof raw["message"] === "string" ? raw["message"] : void 0,
1898
+ steamAgreementStatus: "steam_agreement_status" in raw ? nullableString(raw["steam_agreement_status"]) : void 0,
1899
+ steamAgreementCanceled: typeof raw["steam_agreement_canceled"] === "boolean" ? raw["steam_agreement_canceled"] : void 0,
1900
+ subscription: raw["subscription"] ? toSubscription(raw["subscription"]) : null,
1901
+ raw
1902
+ };
1903
+ }
1904
+ /**
1905
+ * Stage a price change. Applied on the NEXT successful renewal (the current window is
1906
+ * billed at the old price first; no proration). Sending the current price clears a
1907
+ * staged change (`changeQueued: false`). The billed price appears on that period's
1908
+ * `subscription.renewed`; there is no `amount_changed` event.
1909
+ *
1910
+ * Steam: an increase is refused (`err.isSteamReauthorizationRequired`; start a new
1911
+ * Steam subscription at the new price), a decrease stages. An increase to more than
1912
+ * double the last agreed price, or above 25000.00, is staged but never applied: raise
1913
+ * prices in steps. `err.isSubscriptionTerminal` on a canceled/expired row.
1914
+ */
1915
+ async changeAmount(subscriptionId, amountUsd, opts) {
1916
+ assertSubscriptionId(subscriptionId);
1917
+ const amount = subscriptionMoney(amountUsd, "amountUsd");
1918
+ const raw = await this.http.post(
1919
+ `/api/subscriptions/${encodeURIComponent(subscriptionId)}/amount`,
1920
+ { amount_usd: amount },
1921
+ this.auth,
1922
+ // Setting a price is naturally idempotent: the same value again is the same state.
1923
+ { idempotent: true, signal: opts?.signal }
1924
+ );
1925
+ return {
1926
+ status: String(raw["status"] ?? ""),
1927
+ oldAmountUsd: String(raw["old_amount_usd"] ?? ""),
1928
+ newAmountUsd: String(raw["new_amount_usd"] ?? amount),
1929
+ pendingAmountUsd: nullableString(raw["pending_amount_usd"]),
1930
+ changeQueued: raw["change_queued"] === true,
1931
+ appliesFrom: nullableString(raw["applies_from"]),
1932
+ appliesFromPeriodSeq: Number(raw["applies_from_period_seq"] ?? 0),
1933
+ paidThrough: nullableString(raw["paid_through"]),
1934
+ currentPeriodEnd: nullableString(raw["current_period_end"]),
1935
+ prorated: raw["prorated"] === true,
1936
+ subscription: raw["subscription"] ? toSubscription(raw["subscription"]) : null,
1937
+ raw
1938
+ };
1939
+ }
1940
+ /**
1941
+ * Card subscriptions only. Attach a card (`{ playerCardId }`, an `id` from
1942
+ * `cards.list` belonging to this player, unexpired) or make the subscription wallet-only
1943
+ * (`{ walletOnly: true }`). On a wallet-only subscription pass `walletOnly: false`
1944
+ * beside the card to convert it back. The new card is used from the next charge,
1945
+ * including a pending retry in dunning.
1946
+ *
1947
+ * `err.isNotACardSubscription` on Steam; `err.isSubscriptionTerminal` on a terminal row.
1948
+ */
1949
+ async setPaymentMethod(subscriptionId, input, opts) {
1950
+ assertSubscriptionId(subscriptionId);
1951
+ const body = {};
1952
+ if ("playerCardId" in input && input.playerCardId !== void 0) {
1953
+ if (!Number.isInteger(input.playerCardId) || input.playerCardId < 1) {
1954
+ throw invalidInput("playerCardId", input.playerCardId, "must be a positive integer card id (from cards.list)");
1955
+ }
1956
+ body["player_card_id"] = input.playerCardId;
1957
+ if (input.walletOnly !== void 0) body["wallet_only"] = input.walletOnly;
1958
+ } else if (input.walletOnly === true) {
1959
+ body["wallet_only"] = true;
1960
+ } else {
1961
+ throw invalidInput("input", input, "requires { playerCardId } or { walletOnly: true }");
1962
+ }
1963
+ const raw = await this.http.post(
1964
+ `/api/subscriptions/${encodeURIComponent(subscriptionId)}/payment-method`,
1965
+ body,
1966
+ this.auth,
1967
+ // Attaching the same card twice is the same state: safe to retry.
1968
+ { idempotent: true, signal: opts?.signal }
1969
+ );
1970
+ return {
1971
+ status: String(raw["status"] ?? ""),
1972
+ replaced: raw["replaced"] === true,
1973
+ walletOnly: raw["wallet_only"] === true,
1974
+ card: toSavedCard(raw["card"]),
1975
+ subscription: raw["subscription"] ? toSubscription(raw["subscription"]) : null,
1976
+ raw
1977
+ };
1978
+ }
1979
+ /**
1980
+ * Refund a billed period (card rail). Idempotent on `clientRequestId`: a repeat returns
1981
+ * the stored receipt with `idempotentReplay: true` and moves nothing.
1982
+ *
1983
+ * A full refund returns the card charge and reclaims the coins that charge minted
1984
+ * (`balanceDeltaCoins` is signed and can be negative); a partial refund credits the
1985
+ * wallet in coins at the 10:1 peg. Your revenue is reversed for the refunded portion
1986
+ * (`partnerRevenueReversedUsd`); INVO's fee is retained. The subscription is NOT
1987
+ * cancelled by a refund. Refunds of Steam-CHARGED periods are not supported yet; do not
1988
+ * call this on them.
1989
+ *
1990
+ * Refusals: `NO_PAID_PERIOD` (409, nothing collected yet), `PERIOD_NOT_REFUNDABLE`,
1991
+ * `ALREADY_REFUNDED` (`err.isAlreadyRefunded`), `AMOUNT_EXCEEDS_REMAINING` (body carries
1992
+ * `remaining_refundable_usd`), `err.isFlowPaused`.
1993
+ */
1994
+ async refund(subscriptionId, input, opts) {
1995
+ assertSubscriptionId(subscriptionId);
1996
+ assertClientRequestId(input.clientRequestId, "clientRequestId");
1997
+ const body = { client_request_id: input.clientRequestId };
1998
+ if (input.periodSeq !== void 0) {
1999
+ if (!Number.isInteger(input.periodSeq) || input.periodSeq < 1) {
2000
+ throw invalidInput("periodSeq", input.periodSeq, "must be an integer >= 1");
2001
+ }
2002
+ body["period_seq"] = input.periodSeq;
2003
+ }
2004
+ if (input.amountUsd !== void 0) body["amount_usd"] = subscriptionMoney(input.amountUsd, "amountUsd");
2005
+ if (input.reason !== void 0) {
2006
+ if (typeof input.reason !== "string" || input.reason.length > 500) {
2007
+ throw invalidInput("reason", input.reason, "must be a string of at most 500 characters");
2008
+ }
2009
+ body["reason"] = input.reason;
2010
+ }
2011
+ const raw = await this.http.post(
2012
+ `/api/subscriptions/${encodeURIComponent(subscriptionId)}/refund`,
2013
+ body,
2014
+ this.auth,
2015
+ // Idempotent on client_request_id: a lost-response retry returns the stored receipt.
2016
+ { idempotent: true, signal: opts?.signal }
2017
+ );
2018
+ const attr = raw["revenue_share_attribution"];
2019
+ const a = attr && typeof attr === "object" ? attr : null;
2020
+ return {
2021
+ status: String(raw["status"] ?? ""),
2022
+ idempotentReplay: raw["idempotent_replay"] === true,
2023
+ refundKey: nullableString(raw["refund_key"]),
2024
+ clientRequestId: nullableString(raw["client_request_id"]) ?? input.clientRequestId,
2025
+ subscriptionId: String(raw["subscription_id"] ?? subscriptionId),
2026
+ periodSeq: raw["period_seq"] == null ? null : Number(raw["period_seq"]),
2027
+ transactionId: nullableString(raw["transaction_id"]),
2028
+ refundedAmountUsd: nullableString(raw["refunded_amount_usd"]),
2029
+ totalRefundedAmountUsd: nullableString(raw["total_refunded_amount_usd"]),
2030
+ remainingRefundableUsd: nullableString(raw["remaining_refundable_usd"]),
2031
+ isFullRefund: raw["is_full_refund"] === true,
2032
+ fundingShape: nullableString(raw["funding_shape"]),
2033
+ balanceDeltaCoins: nullableString(raw["balance_delta_coins"]),
2034
+ cardRefundedUsd: nullableString(raw["card_refunded_usd"]),
2035
+ // Neutral field only; the vendor-named sibling is deliberately not read.
2036
+ processorRefundReference: nullableString(raw["processor_refund_reference"]),
2037
+ processorRefundAdopted: raw["processor_refund_adopted"] === true,
2038
+ invoFeeRetained: raw["invo_fee_retained"] === true,
2039
+ partnerRevenueReversedUsd: nullableString(raw["partner_revenue_reversed_usd"]),
2040
+ partnerRevenueReversalMode: nullableString(raw["partner_revenue_reversal_mode"]),
2041
+ reason: nullableString(raw["reason"]),
2042
+ refundedAt: nullableString(raw["refunded_at"]),
2043
+ newBalance: nullableString(raw["new_balance"]),
2044
+ revenueShareAttribution: a ? {
2045
+ recipientPlayerId: Number(a["recipient_player_id"] ?? 0),
2046
+ percent: String(a["percent"] ?? ""),
2047
+ originalAttributedAmountUsd: String(a["original_attributed_amount_usd"] ?? ""),
2048
+ refundedAttributedAmountUsd: String(a["refunded_attributed_amount_usd"] ?? ""),
2049
+ netAttributedAmountUsd: String(a["net_attributed_amount_usd"] ?? ""),
2050
+ settledByInvo: a["settled_by_invo"] === true,
2051
+ raw: a
2052
+ } : null,
2053
+ note: typeof raw["note"] === "string" ? raw["note"] : void 0,
2054
+ raw
2055
+ };
2056
+ }
2057
+ /**
2058
+ * Start a STEAM-rail subscription: creates it in `pending_steam_authorization`, opens
2059
+ * period 1 for the full price and starts the Steam authorisation. Nothing is charged
2060
+ * until the member authorises and you call {@link steamFinalize}. Idempotent on
2061
+ * `clientRequestId`; a replay answers with the row's CURRENT status (which may already
2062
+ * be `active`, `canceled` or `expired`).
2063
+ *
2064
+ * `userSession: "client"` (default): the Steam overlay presents the authorisation inside
2065
+ * the game; match the Steam client callback's `order_id` against `steamOrderId` (never
2066
+ * `steamTransid`). `"web"`: open `steamCheckoutUrl` as a TOP-LEVEL window (it cannot be
2067
+ * framed); requires `playerIp`, the MEMBER's address. Show `amountCoins`: what one
2068
+ * period is worth for THIS member depends on their country and is fixed at init.
2069
+ *
2070
+ * A pending authorisation for the same player and item with the SAME terms is handed
2071
+ * back (`pendingReuse: true`, no new agreement): finalize that one. With DIFFERENT
2072
+ * terms the call throws `409 STEAM_AUTHORIZATION_PENDING` (`err.isSteamAuthorizationPending`,
2073
+ * `err.existingSubscriptionId`): finalize or cancel the pending one first.
2074
+ *
2075
+ * Not available on Steam, refused before the network: trials, `walletOnly`, card
2076
+ * fields, `intervalCount` other than 1. Backend refusals worth branching on:
2077
+ * `err.isSteamChannelRequired` (409, wrong channel key), `err.isActiveSubscriptionExists`,
2078
+ * `err.isSteamRailNotEntitled` (403), `err.isSteamNotConfigured` (503),
2079
+ * `err.isPartnerBillingNotSetUp` / `isPartnerSettlementUnavailable` (409),
2080
+ * `AMOUNT_TOO_SMALL_FOR_STEAM` (400). When a Steam-side failure abandons the row after
2081
+ * creation the body carries the abandoned `subscription_id`; retry with a NEW key.
2082
+ */
2083
+ async steamInit(input, opts) {
2084
+ const body = subscriptionBaseBody(input);
2085
+ if (!/^[0-9]+$/.test(String(input.steamId ?? ""))) {
2086
+ throw invalidInput("steamId", input.steamId, "must be the member's numeric 64-bit Steam id");
2087
+ }
2088
+ if (input.userSession !== void 0 && input.userSession !== "client" && input.userSession !== "web") {
2089
+ throw invalidInput("userSession", input.userSession, 'must be "client" or "web"');
2090
+ }
2091
+ if (input.userSession === "web" && !input.playerIp) {
2092
+ throw new InvoError({
2093
+ message: `playerIp is required when userSession is "web" \u2014 the MEMBER's IP, not your server's.`,
2094
+ code: "MISSING_PLAYER_IP",
2095
+ status: 0
2096
+ });
2097
+ }
2098
+ if (input.intervalCount !== void 0 && input.intervalCount !== 1) {
2099
+ throw invalidInput("intervalCount", input.intervalCount, "must be 1 on the Steam rail (monthly and yearly only)");
2100
+ }
2101
+ const forbidden = input;
2102
+ for (const k of ["trialDays", "trialEnd", "walletOnly", "playerCardId"]) {
2103
+ if (forbidden[k] !== void 0) {
2104
+ throw invalidInput(k, forbidden[k], "is not available on the Steam rail");
2105
+ }
2106
+ }
2107
+ body["steamid"] = String(input.steamId);
2108
+ if (input.userSession) body["usersession"] = input.userSession;
2109
+ if (input.playerIp) body["player_ip"] = input.playerIp;
2110
+ if (input.intervalCount !== void 0) body["interval_count"] = input.intervalCount;
2111
+ const raw = await this.http.post(
2112
+ "/api/subscriptions/steam/init",
2113
+ body,
2114
+ this.auth,
2115
+ // Idempotent on client_request_id: a replay returns the row's current status.
2116
+ { idempotent: true, signal: opts?.signal }
2117
+ );
2118
+ return {
2119
+ status: String(raw["status"] ?? ""),
2120
+ subscriptionStatus: String(raw["subscription_status"] ?? raw["status"] ?? ""),
2121
+ idempotentReplay: raw["idempotent_replay"] === true,
2122
+ pendingReuse: raw["pending_reuse"] === true,
2123
+ subscription: toSubscription(raw["subscription"]),
2124
+ subscriptionId: String(raw["subscription_id"] ?? ""),
2125
+ orderId: String(raw["order_id"] ?? ""),
2126
+ steamOrderId: String(raw["steam_order_id"] ?? ""),
2127
+ steamTransid: String(raw["steam_transid"] ?? ""),
2128
+ steamCheckoutUrl: nullableString(raw["steam_checkout_url"]),
2129
+ amountUsd: String(raw["amount_usd"] ?? ""),
2130
+ amountCoins: String(raw["amount_coins"] ?? ""),
2131
+ steamChargeUsd: String(raw["steam_charge_usd"] ?? ""),
2132
+ recurringAmountUsd: String(raw["recurring_amount_usd"] ?? ""),
2133
+ firstCharge: toFirstCharge(raw["first_charge"]),
2134
+ message: String(raw["message"] ?? ""),
2135
+ raw
2136
+ };
2137
+ }
2138
+ /**
2139
+ * Finalize a Steam subscription after the member has authorised: INVO verifies with
2140
+ * Steam, captures period 1, records the agreement and settles period 1 exactly as a
2141
+ * renewal. Idempotent: a repeat returns `alreadyProcessed: true` with
2142
+ * `idempotentReplay: true` (treat as success; never thrown).
2143
+ *
2144
+ * **Finalize is your call.** Steam does not tell INVO the member authorised; call this
2145
+ * after the overlay or checkout closes, and again if it threw `err.isNotAuthorized`
2146
+ * (409 `status: "not_authorized"`: the normal wait state). The member has 24 hours.
2147
+ * A 200 with `warning` means Steam charged but period 1 could not settle in one step:
2148
+ * the money is taken, do not retry the charge, watch for `subscription.renewed`.
2149
+ * In sandbox this does not call Steam (`sandboxAutoApproved: true`).
2150
+ *
2151
+ * Other refusals: `err.isSubscriptionTerminal`, `NOT_A_STEAM_SUBSCRIPTION`,
2152
+ * `NO_STEAM_AUTHORIZATION`, `err.isSteamAppChanged` (409); 502/503 are transient.
2153
+ */
2154
+ async steamFinalize(subscriptionId, opts) {
2155
+ assertSubscriptionId(subscriptionId);
2156
+ const raw = await this.http.post(
2157
+ "/api/subscriptions/steam/finalize",
2158
+ { subscription_id: subscriptionId },
2159
+ this.auth,
2160
+ // Idempotent: a repeat replays the finalised row (already_processed: true).
2161
+ { idempotent: true, signal: opts?.signal }
2162
+ );
2163
+ return {
2164
+ ...toSubscriptionResult(raw),
2165
+ alreadyProcessed: raw["already_processed"] === true,
2166
+ steamAgreementStatus: nullableString(raw["steam_agreement_status"]),
2167
+ sandboxAutoApproved: raw["sandbox_auto_approved"] === true
2168
+ };
2169
+ }
2170
+ };
2171
+ var CardsServer = class {
2172
+ constructor(http, auth) {
2173
+ this.http = http;
2174
+ this.auth = auth;
2175
+ }
2176
+ /**
2177
+ * Begin saving a card (charges nothing). The player must already exist in this game
2178
+ * (`404 PLAYER_NOT_FOUND`). Idempotent on `setupReference`: resend the same value on a
2179
+ * retry and you get the same setup back (`409 SETUP_REFERENCE_REUSED` if you reuse it
2180
+ * with different parameters).
2181
+ *
2182
+ * With `paymentMethodId` (a card tokenised on the client) INVO confirms server-side
2183
+ * and answers `succeeded` with the `card`, or `requires_action` with a `clientSecret`
2184
+ * for the card form to run the cardholder authentication. Without it, INVO answers
2185
+ * `requires_confirmation` / `requires_payment_method` with a `clientSecret`: confirm on
2186
+ * the client, then call {@link confirmSetup}. Send tokens only, never raw card numbers
2187
+ * (`RAW_CARD_NOT_SUPPORTED`).
2188
+ */
2189
+ async beginSetup(input, opts) {
2190
+ if (typeof input.playerEmail !== "string" || !input.playerEmail.trim()) {
2191
+ throw invalidInput("playerEmail", input.playerEmail, "is required");
2192
+ }
2193
+ if (typeof input.setupReference !== "string" || !/^[A-Za-z0-9._:-]{1,200}$/.test(input.setupReference)) {
2194
+ throw invalidInput("setupReference", input.setupReference, "must be 1-200 characters of A-Z a-z 0-9 . _ : -");
2195
+ }
2196
+ const body = {
2197
+ player_email: input.playerEmail,
2198
+ setup_reference: input.setupReference
2199
+ };
2200
+ if (input.paymentMethodId) body["payment_method_id"] = input.paymentMethodId;
2201
+ const raw = await this.http.post(
2202
+ "/api/currency-purchases/setup-intent",
2203
+ body,
2204
+ this.auth,
2205
+ // Idempotent on setup_reference: a retry returns the same setup, never a second one.
2206
+ { idempotent: true, signal: opts?.signal }
2207
+ );
2208
+ return {
2209
+ status: String(raw["status"] ?? ""),
2210
+ setupIntentId: requireField(raw["setup_intent_id"], "setup_intent_id", raw),
2211
+ clientSecret: typeof raw["client_secret"] === "string" ? raw["client_secret"] : void 0,
2212
+ publishableKey: typeof raw["publishable_key"] === "string" ? raw["publishable_key"] : void 0,
2213
+ card: toSavedCard(raw["card"]),
2214
+ alreadySaved: raw["already_saved"] === true,
2215
+ message: typeof raw["message"] === "string" ? raw["message"] : void 0,
2216
+ raw
2217
+ };
2218
+ }
2219
+ /**
2220
+ * Finish a client-confirmed setup and save the card. Idempotent on `setupIntentId`.
2221
+ * While the client has not finished, this throws a 400 with body
2222
+ * `status: "still_requires_action"`. On `500 CARD_PERSIST_FAILED` (authorised but not
2223
+ * recorded) retry this call with the same `setupIntentId`.
2224
+ */
2225
+ async confirmSetup(input, opts) {
2226
+ if (typeof input.setupIntentId !== "string" || !input.setupIntentId.trim()) {
2227
+ throw invalidInput("setupIntentId", input.setupIntentId, "is required (from beginSetup)");
2228
+ }
2229
+ const raw = await this.http.post(
2230
+ "/api/currency-purchases/setup-intent/confirm",
2231
+ { setup_intent_id: input.setupIntentId },
2232
+ this.auth,
2233
+ { idempotent: true, signal: opts?.signal }
2234
+ // keyed by setup_intent_id: safe to retry
2235
+ );
2236
+ return {
2237
+ status: String(raw["status"] ?? ""),
2238
+ setupIntentId: String(raw["setup_intent_id"] ?? input.setupIntentId),
2239
+ card: toSavedCard(raw["card"]),
2240
+ alreadySaved: raw["already_saved"] === true,
2241
+ raw
2242
+ };
2243
+ }
2244
+ /**
2245
+ * A member's unexpired saved cards, newest first. An unknown player is `{ cards: [] }`.
2246
+ * The `id` is the value you pass as `playerCardId`; INVO never returns processor
2247
+ * identifiers for a card. Served from a short cache (about 60 s); a card saved through
2248
+ * `beginSetup` / `confirmSetup` appears immediately.
2249
+ */
2250
+ async list(playerEmail, opts) {
2251
+ if (typeof playerEmail !== "string" || !playerEmail.trim()) {
2252
+ throw invalidInput("playerEmail", playerEmail, "is required");
2253
+ }
2254
+ const raw = await this.http.get(
2255
+ `/api/currency-purchases/player-cards?player_email=${encodeURIComponent(playerEmail)}`,
2256
+ this.auth,
2257
+ { signal: opts?.signal }
2258
+ );
2259
+ const rows = Array.isArray(raw["cards"]) ? raw["cards"] : [];
2260
+ return {
2261
+ cards: rows.map(toSavedCard).filter((c) => c !== null),
2262
+ raw
2263
+ };
2264
+ }
2265
+ };
2266
+ var SandboxSubscriptionsServer = class {
2267
+ constructor(http, auth, clockKey) {
2268
+ this.http = http;
2269
+ this.auth = auth;
2270
+ this.clockKey = clockKey;
2271
+ }
2272
+ async call(subscriptionId, tool, body, opts) {
2273
+ assertSubscriptionId(subscriptionId);
2274
+ if (typeof this.clockKey !== "string" || !this.clockKey.trim()) {
2275
+ throw invalidInput(
2276
+ "sandboxClockKey",
2277
+ this.clockKey,
2278
+ 'is required for invo.sandbox.subscriptions.* \u2014 pass it to new InvoServer({ sandboxClockKey }) from the sandbox console (Game Settings, "Sandbox clock key")'
2279
+ );
2280
+ }
2281
+ const raw = await this.http.post(
2282
+ // Relative to baseUrl, which already ends in /sandbox. NOT under /api.
2283
+ `/subscriptions/${encodeURIComponent(subscriptionId)}/${tool}`,
2284
+ body,
2285
+ this.auth,
2286
+ { signal: opts?.signal, headers: { "X-Sandbox-Clock-Key": this.clockKey } }
2287
+ // never auto-retried
2288
+ );
2289
+ return toSandboxClockResult(raw);
2290
+ }
2291
+ /**
2292
+ * Make the next period due now. `intervals` 0..60, default 1. `0` makes it due without
2293
+ * moving the window (use it to trigger a retry). `N` on a never-paid subscription
2294
+ * (a trial, a fresh row) also moves the window back by up to N intervals; once anything
2295
+ * has been paid the window stays put (`intervalsAppliedToWindow: 0`). No window is ever
2296
+ * billed twice. Then `forceRenewal`, or wait for the next sweep (within a minute or two).
2297
+ * `409 SUBSCRIPTION_NOT_LIVE` on a terminal or pending row.
2298
+ */
2299
+ async advanceClock(subscriptionId, intervals = 1, opts) {
2300
+ if (!Number.isInteger(intervals) || intervals < 0 || intervals > 60) {
2301
+ throw invalidInput("intervals", intervals, "must be an integer 0..60");
2302
+ }
2303
+ return this.call(subscriptionId, "advance-clock", { intervals }, opts);
2304
+ }
2305
+ /**
2306
+ * Run the renewal immediately. **Charges the test card** (or the Steam stand-in): the
2307
+ * real money path, wallet read, shortfall, mint, spend, split, `subscription.renewed`,
2308
+ * and on failure the real dunning. Read `engineStats` (`renewed: 1` on success). A
2309
+ * cancel-at-period-end row answers `action: "retired-at-period-end"`, `retired: true`.
2310
+ * `409 PERIOD_TOO_FAR_AHEAD` means you forced twice without advancing the clock.
2311
+ */
2312
+ async forceRenewal(subscriptionId, opts) {
2313
+ return this.call(subscriptionId, "force-renewal", {}, opts);
2314
+ }
2315
+ /**
2316
+ * Synthesise a failed attempt and run real dunning. No charge. `outcome` defaults to
2317
+ * `card_declined`. Returns `retryBudgetUsed`, `retryScheduleDays` (e.g. `[2, 3, 2]`),
2318
+ * `retriesRemaining`. Call it four times to walk `active` through `past_due` to `expired`
2319
+ * and watch the events. Does not model a Steam refusal.
2320
+ */
2321
+ async forceFailure(subscriptionId, outcome = "card_declined", options, opts) {
2322
+ if (!SANDBOX_FAILURE_OUTCOMES.has(outcome)) {
2323
+ throw invalidInput("outcome", outcome, 'must be "card_declined" | "insufficient_funds" | "error"');
2324
+ }
2325
+ const body = { outcome };
2326
+ if (options?.failureCode !== void 0) body["failure_code"] = options.failureCode;
2327
+ if (options?.failureMessage !== void 0) body["failure_message"] = options.failureMessage;
2328
+ return this.call(subscriptionId, "force-failure", body, opts);
2329
+ }
2330
+ /**
2331
+ * Synthesise a cardholder authentication challenge: moves the subscription to
2332
+ * `awaiting_authentication` (no charge). Returns `authChallengesUsed`,
2333
+ * `maxAuthChallenges` (2) and `downgradedToDecline`. It does NOT mint a confirmation
2334
+ * link; to exercise the link and the `subscription.authentication_required` event use a
2335
+ * test card that requires authentication, then `forceRenewal`.
2336
+ */
2337
+ async forceAuthChallenge(subscriptionId, options, opts) {
2338
+ const body = {};
2339
+ if (options?.failureMessage !== void 0) body["failure_message"] = options.failureMessage;
2340
+ return this.call(subscriptionId, "force-auth-challenge", body, opts);
2341
+ }
2342
+ };
2343
+ var SandboxServer = class {
2344
+ constructor(http, auth, clockKey) {
2345
+ this.subscriptions = new SandboxSubscriptionsServer(http, auth, clockKey);
2346
+ }
2347
+ };
1396
2348
  var InvoServer = class {
1397
2349
  constructor(config) {
1398
2350
  if (!config.gameSecret) throw new Error("InvoServer requires a `gameSecret`.");
@@ -1410,6 +2362,9 @@ var InvoServer = class {
1410
2362
  });
1411
2363
  this.auth = { kind: "game-secret", secret: config.gameSecret };
1412
2364
  this.platformCommerce = new PlatformCommerceServer(this.http, this.auth);
2365
+ this.subscriptions = new SubscriptionsServer(this.http, this.auth);
2366
+ this.cards = new CardsServer(this.http, this.auth);
2367
+ this.sandbox = new SandboxServer(this.http, this.auth, config.sandboxClockKey);
1413
2368
  }
1414
2369
  /**
1415
2370
  * Mint a short-lived, game-scoped player token to hand to the browser InvoClient.
@@ -2546,9 +3501,14 @@ var InvoServer = class {
2546
3501
  }
2547
3502
  };
2548
3503
 
3504
+ exports.CardsServer = CardsServer;
2549
3505
  exports.InvoError = InvoError;
2550
3506
  exports.InvoServer = InvoServer;
2551
3507
  exports.PlatformCommerceServer = PlatformCommerceServer;
3508
+ exports.SDK_VERSION = SDK_VERSION;
3509
+ exports.SandboxServer = SandboxServer;
3510
+ exports.SandboxSubscriptionsServer = SandboxSubscriptionsServer;
3511
+ exports.SubscriptionsServer = SubscriptionsServer;
2552
3512
  exports.createWebhookHandler = createWebhookHandler;
2553
3513
  exports.verifyWebhook = verifyWebhook;
2554
3514
  exports.verifyWebhookAsync = verifyWebhookAsync;