@invonetwork/web-sdk 3.34.1 → 3.35.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.
@@ -1335,6 +1335,108 @@ var InvoError = class _InvoError extends Error {
1335
1335
  get isRateLimited() {
1336
1336
  return this.code === "RATE_LIMITED" || this.code === "rate_limited" || this.status === 429;
1337
1337
  }
1338
+ // ---- Apple In-App Purchase (verifyApplePurchase / appleProducts, 3.35.0) ----
1339
+ //
1340
+ // Apple has already charged the player when verifyApplePurchase runs. Decide whether to
1341
+ // call StoreKit's Transaction.finish() with shouldFinishAppleTransaction() (or `finish`),
1342
+ // not with these: among the errors only APPLE_TRANSACTION_REVOKED,
1343
+ // APPLE_TRANSACTION_ALREADY_USED and APPLE_TRANSACTION_TOO_OLD are finished.
1344
+ /**
1345
+ * The body's boolean `finish` (additive, 3.35.0), sent on every `verifyApplePurchase`
1346
+ * answer: `true` when the game should call StoreKit's `Transaction.finish()` for this
1347
+ * refusal (nothing can ever be delivered), `false` when it should leave the transaction
1348
+ * unfinished and retry. `undefined` when the body carries none (any other endpoint, an
1349
+ * older backend, or a network error); `shouldFinishAppleTransaction(err)` then falls back
1350
+ * to the error code.
1351
+ */
1352
+ get finish() {
1353
+ const f = this.bodyObject()["finish"];
1354
+ return typeof f === "boolean" ? f : void 0;
1355
+ }
1356
+ /** Not a genuine Apple transaction (`APPLE_SIGNATURE_INVALID`, 400). Leave it unfinished. */
1357
+ get isAppleSignatureInvalid() {
1358
+ return this.code === "APPLE_SIGNATURE_INVALID";
1359
+ }
1360
+ /** Another app's transaction: the bundle id (or Apple ID) is not this game's
1361
+ * (`APPLE_BUNDLE_MISMATCH`, 400). */
1362
+ get isAppleBundleMismatch() {
1363
+ return this.code === "APPLE_BUNDLE_MISMATCH";
1364
+ }
1365
+ /** The transaction's environment is not accepted here (`APPLE_ENVIRONMENT_NOT_ALLOWED`, 400).
1366
+ * The INVO sandbox takes only Sandbox transactions; Xcode StoreKit-testing transactions are
1367
+ * never accepted, because Apple does not sign them. */
1368
+ get isAppleEnvironmentNotAllowed() {
1369
+ return this.code === "APPLE_ENVIRONMENT_NOT_ALLOWED";
1370
+ }
1371
+ /** Only consumable products buy currency (`APPLE_PRODUCT_TYPE_UNSUPPORTED`, 400). */
1372
+ get isAppleProductTypeUnsupported() {
1373
+ return this.code === "APPLE_PRODUCT_TYPE_UNSUPPORTED";
1374
+ }
1375
+ /** The product id is not registered for this game (`APPLE_PRODUCT_UNKNOWN`, 400). Register
1376
+ * it in the INVO console and retry; keep the transaction unfinished meanwhile. */
1377
+ get isAppleProductUnknown() {
1378
+ return this.code === "APPLE_PRODUCT_UNKNOWN";
1379
+ }
1380
+ /** `metadata` was refused (`INVALID_METADATA`, 400). Fix the request and retry. */
1381
+ get isInvalidMetadata() {
1382
+ return this.code === "INVALID_METADATA";
1383
+ }
1384
+ /** A Sandbox purchase on INVO production by an account not on the game's App Review list
1385
+ * (`APPLE_REVIEW_ACCOUNT_REQUIRED`, 403). */
1386
+ get isAppleReviewAccountRequired() {
1387
+ return this.code === "APPLE_REVIEW_ACCOUNT_REQUIRED";
1388
+ }
1389
+ /** Apple refunded or revoked the transaction (`APPLE_TRANSACTION_REVOKED`, 409). Nothing can
1390
+ * ever be delivered for it: **finish it** (`finish: true`). */
1391
+ get isAppleTransactionRevoked() {
1392
+ return this.code === "APPLE_TRANSACTION_REVOKED";
1393
+ }
1394
+ /** The transaction was already credited in another INVO game
1395
+ * (`APPLE_TRANSACTION_ALREADY_USED`, 409). Terminal: **finish it** (`finish: true`). */
1396
+ get isAppleTransactionAlreadyUsed() {
1397
+ return this.code === "APPLE_TRANSACTION_ALREADY_USED";
1398
+ }
1399
+ /** Bought before the game sold through INVO (`APPLE_TRANSACTION_TOO_OLD`, 409). Terminal:
1400
+ * **finish it** (`finish: true`). */
1401
+ get isAppleTransactionTooOld() {
1402
+ return this.code === "APPLE_TRANSACTION_TOO_OLD";
1403
+ }
1404
+ /** The product's coins are out of proportion to its signed price, or over the per-purchase
1405
+ * maximum (`APPLE_VALUE_EXCEEDS_PRICE`, 409). Fix the product mapping and retry. */
1406
+ get isAppleValueExceedsPrice() {
1407
+ return this.code === "APPLE_VALUE_EXCEEDS_PRICE";
1408
+ }
1409
+ /** The transaction's `appAccountToken` is not the one you sent: it was made for a
1410
+ * different player (`APPLE_ACCOUNT_TOKEN_MISMATCH`, 409). */
1411
+ get isAppleAccountTokenMismatch() {
1412
+ return this.code === "APPLE_ACCOUNT_TOKEN_MISMATCH";
1413
+ }
1414
+ /** The game's Apple configuration is missing or turned off (`APPLE_NOT_CONFIGURED`, 409).
1415
+ * Retry once it is set up. */
1416
+ get isAppleNotConfigured() {
1417
+ return this.code === "APPLE_NOT_CONFIGURED";
1418
+ }
1419
+ /** Production has not yet confirmed you own the App Store app (`APPLE_NOT_VERIFIED`, 409).
1420
+ * Point App Store Server Notifications at INVO; retry once verified. */
1421
+ get isAppleNotVerified() {
1422
+ return this.code === "APPLE_NOT_VERIFIED";
1423
+ }
1424
+ /** Today's App Review purchase cap on production is reached (`APPLE_REVIEW_PURCHASE_LIMIT`,
1425
+ * 429). */
1426
+ get isAppleReviewPurchaseLimit() {
1427
+ return this.code === "APPLE_REVIEW_PURCHASE_LIMIT";
1428
+ }
1429
+ /** Verified and held, not refused (`APPLE_CREDIT_PENDING`, 503): the coins will credit on a
1430
+ * later retry. Keep the transaction unfinished and retry; StoreKit also redelivers it. */
1431
+ get isAppleCreditPending() {
1432
+ return this.code === "APPLE_CREDIT_PENDING";
1433
+ }
1434
+ /** A card purchase (`purchaseCurrency`) was made with a key on the Apple rail
1435
+ * (`WRONG_RAIL_ENDPOINT`, 400, `status: "use_apple_endpoint"`). Use
1436
+ * `verifyApplePurchase` for that key. */
1437
+ get isAppleEndpointRequired() {
1438
+ return this.code === "WRONG_RAIL_ENDPOINT" && this.bodyObject()["status"] === "use_apple_endpoint";
1439
+ }
1338
1440
  /** `body` as a plain object, or `{}` if it's a string/number/null (non-JSON responses).
1339
1441
  * The `in` operator throws on primitives, so callers must go through this. */
1340
1442
  bodyObject() {
@@ -1660,6 +1762,49 @@ function toPurchaseStatusResult(raw, sessionId) {
1660
1762
  };
1661
1763
  }
1662
1764
 
1765
+ // src/shared/apple.ts
1766
+ var FINISHED_STATUSES = /* @__PURE__ */ new Set(["credited", "already_credited"]);
1767
+ function nullableString(v) {
1768
+ return v === null || v === void 0 ? null : String(v);
1769
+ }
1770
+ function toNumber(v) {
1771
+ const n = typeof v === "number" ? v : Number(v);
1772
+ return Number.isFinite(n) ? n : 0;
1773
+ }
1774
+ function toAppleProductsResult(raw) {
1775
+ const rows2 = Array.isArray(raw["products"]) ? raw["products"] : [];
1776
+ return {
1777
+ bundleId: String(raw["bundle_id"] ?? ""),
1778
+ canSell: raw["can_sell"] === true,
1779
+ unavailableReason: nullableString(raw["unavailable_reason"]),
1780
+ products: rows2.map((p) => ({
1781
+ productId: String(p["product_id"] ?? ""),
1782
+ coins: toNumber(p["coins"]),
1783
+ label: String(p["label"] ?? p["product_id"] ?? ""),
1784
+ priceUsd: nullableString(p["price_usd"]),
1785
+ active: p["active"] !== false,
1786
+ // Fail closed: only an explicit `true` offers the product.
1787
+ available: p["available"] === true,
1788
+ unavailableReason: nullableString(p["unavailable_reason"])
1789
+ })),
1790
+ raw
1791
+ };
1792
+ }
1793
+ function toApplePurchaseResult(raw) {
1794
+ return {
1795
+ status: String(raw["status"] ?? ""),
1796
+ orderId: String(raw["order_id"] ?? ""),
1797
+ transactionId: String(raw["transaction_id"] ?? ""),
1798
+ productId: String(raw["product_id"] ?? ""),
1799
+ coins: toNumber(raw["coins"]),
1800
+ balance: nullableString(raw["balance"]),
1801
+ environment: String(raw["environment"] ?? ""),
1802
+ testMode: raw["test_mode"] === true,
1803
+ finish: typeof raw["finish"] === "boolean" ? raw["finish"] : FINISHED_STATUSES.has(String(raw["status"] ?? "")),
1804
+ raw
1805
+ };
1806
+ }
1807
+
1663
1808
  // src/shared/loyalty.ts
1664
1809
  var obj = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : {};
1665
1810
  var rows = (v) => Array.isArray(v) ? v.filter((r) => r && typeof r === "object" && !Array.isArray(r)) : [];
@@ -2957,11 +3102,11 @@ function toSavedCard(row) {
2957
3102
  raw: r
2958
3103
  };
2959
3104
  }
2960
- function nullableString(v) {
3105
+ function nullableString2(v) {
2961
3106
  return v == null ? null : String(v);
2962
3107
  }
2963
3108
  function optionalString(r, key) {
2964
- return key in r ? nullableString(r[key]) : void 0;
3109
+ return key in r ? nullableString2(r[key]) : void 0;
2965
3110
  }
2966
3111
  function toCheckoutWarnings(v) {
2967
3112
  if (!Array.isArray(v)) return void 0;
@@ -2981,27 +3126,27 @@ function toRefundResult(raw, subscriptionId, clientRequestId) {
2981
3126
  const base = {
2982
3127
  status: String(raw["status"] ?? ""),
2983
3128
  idempotentReplay: raw["idempotent_replay"] === true,
2984
- refundKey: nullableString(raw["refund_key"]),
2985
- clientRequestId: nullableString(raw["client_request_id"]) ?? clientRequestId,
3129
+ refundKey: nullableString2(raw["refund_key"]),
3130
+ clientRequestId: nullableString2(raw["client_request_id"]) ?? clientRequestId,
2986
3131
  subscriptionId: String(raw["subscription_id"] ?? subscriptionId),
2987
3132
  periodSeq: raw["period_seq"] == null ? null : Number(raw["period_seq"]),
2988
- transactionId: nullableString(raw["transaction_id"]),
2989
- refundedAmountUsd: nullableString(raw["refunded_amount_usd"]),
2990
- totalRefundedAmountUsd: nullableString(raw["total_refunded_amount_usd"]),
2991
- remainingRefundableUsd: nullableString(raw["remaining_refundable_usd"]),
3133
+ transactionId: nullableString2(raw["transaction_id"]),
3134
+ refundedAmountUsd: nullableString2(raw["refunded_amount_usd"]),
3135
+ totalRefundedAmountUsd: nullableString2(raw["total_refunded_amount_usd"]),
3136
+ remainingRefundableUsd: nullableString2(raw["remaining_refundable_usd"]),
2992
3137
  isFullRefund: raw["is_full_refund"] === true,
2993
- fundingShape: nullableString(raw["funding_shape"]),
2994
- balanceDeltaCoins: nullableString(raw["balance_delta_coins"]),
2995
- cardRefundedUsd: nullableString(raw["card_refunded_usd"]),
3138
+ fundingShape: nullableString2(raw["funding_shape"]),
3139
+ balanceDeltaCoins: nullableString2(raw["balance_delta_coins"]),
3140
+ cardRefundedUsd: nullableString2(raw["card_refunded_usd"]),
2996
3141
  // Neutral field only; the vendor-named sibling is deliberately not read.
2997
- processorRefundReference: nullableString(raw["processor_refund_reference"]),
3142
+ processorRefundReference: nullableString2(raw["processor_refund_reference"]),
2998
3143
  processorRefundAdopted: raw["processor_refund_adopted"] === true,
2999
3144
  invoFeeRetained: raw["invo_fee_retained"] === true,
3000
- partnerRevenueReversedUsd: nullableString(raw["partner_revenue_reversed_usd"]),
3001
- partnerRevenueReversalMode: nullableString(raw["partner_revenue_reversal_mode"]),
3002
- reason: nullableString(raw["reason"]),
3003
- refundedAt: nullableString(raw["refunded_at"]),
3004
- newBalance: nullableString(raw["new_balance"]),
3145
+ partnerRevenueReversedUsd: nullableString2(raw["partner_revenue_reversed_usd"]),
3146
+ partnerRevenueReversalMode: nullableString2(raw["partner_revenue_reversal_mode"]),
3147
+ reason: nullableString2(raw["reason"]),
3148
+ refundedAt: nullableString2(raw["refunded_at"]),
3149
+ newBalance: nullableString2(raw["new_balance"]),
3005
3150
  revenueShareAttribution: a ? {
3006
3151
  recipientPlayerId: Number(a["recipient_player_id"] ?? 0),
3007
3152
  percent: String(a["percent"] ?? ""),
@@ -3034,11 +3179,11 @@ function toRefundResult(raw, subscriptionId, clientRequestId) {
3034
3179
  status: "pending_approval",
3035
3180
  requestId: String(raw["request_id"] ?? raw["refund_request_id"] ?? ""),
3036
3181
  requestStatus: String(raw["request_status"] ?? ""),
3037
- requestedAmountUsd: nullableString(raw["requested_amount_usd"]),
3038
- requestedAt: nullableString(raw["requested_at"]),
3039
- dailyCapUsd: nullableString(raw["daily_cap_usd"]),
3040
- executedTodayUsd: nullableString(raw["executed_today_usd"]),
3041
- message: nullableString(raw["message"])
3182
+ requestedAmountUsd: nullableString2(raw["requested_amount_usd"]),
3183
+ requestedAt: nullableString2(raw["requested_at"]),
3184
+ dailyCapUsd: nullableString2(raw["daily_cap_usd"]),
3185
+ executedTodayUsd: nullableString2(raw["executed_today_usd"]),
3186
+ message: nullableString2(raw["message"])
3042
3187
  };
3043
3188
  return pending;
3044
3189
  }
@@ -3055,35 +3200,35 @@ function toSubscription(row) {
3055
3200
  clientRequestId: String(r["client_request_id"] ?? ""),
3056
3201
  status: String(r["status"] ?? ""),
3057
3202
  amountUsd: String(r["amount_usd"] ?? ""),
3058
- pendingAmountUsd: nullableString(r["pending_amount_usd"]),
3203
+ pendingAmountUsd: nullableString2(r["pending_amount_usd"]),
3059
3204
  interval: String(r["interval"] ?? "month"),
3060
3205
  intervalCount: Number(r["interval_count"] ?? 1),
3061
3206
  itemId: String(r["item_id"] ?? ""),
3062
- itemName: nullableString(r["item_name"]),
3207
+ itemName: nullableString2(r["item_name"]),
3063
3208
  currentPeriodStart: String(r["current_period_start"] ?? ""),
3064
3209
  currentPeriodEnd: String(r["current_period_end"] ?? ""),
3065
3210
  periodSeq: Number(r["period_seq"] ?? 0),
3066
- nextChargeAt: nullableString(r["next_charge_at"]),
3211
+ nextChargeAt: nullableString2(r["next_charge_at"]),
3067
3212
  cancelAtPeriodEnd: r["cancel_at_period_end"] === true,
3068
- trialEnd: nullableString(r["trial_end"]),
3069
- trialAmountUsd: nullableString(r["trial_amount_usd"]),
3070
- canceledAt: nullableString(r["canceled_at"]),
3071
- endedAt: nullableString(r["ended_at"]),
3213
+ trialEnd: nullableString2(r["trial_end"]),
3214
+ trialAmountUsd: nullableString2(r["trial_amount_usd"]),
3215
+ canceledAt: nullableString2(r["canceled_at"]),
3216
+ endedAt: nullableString2(r["ended_at"]),
3072
3217
  walletOnly: r["wallet_only"] === true,
3073
3218
  hasPaymentMethod: r["has_payment_method"] === true,
3074
3219
  fundingRail: String(r["funding_rail"] ?? "card"),
3075
- steamAgreementStatus: nullableString(r["steam_agreement_status"]),
3220
+ steamAgreementStatus: nullableString2(r["steam_agreement_status"]),
3076
3221
  metadata: r["metadata"] && typeof r["metadata"] === "object" ? r["metadata"] : null,
3077
3222
  consent: {
3078
- consent_at: nullableString(consent["consent_at"]),
3079
- consent_ip: nullableString(consent["consent_ip"]),
3080
- consent_user_agent: nullableString(consent["consent_user_agent"]),
3081
- disclosed_amount_usd: nullableString(consent["disclosed_amount_usd"]),
3082
- disclosed_interval: nullableString(consent["disclosed_interval"]),
3083
- terms_version: nullableString(consent["terms_version"]),
3084
- disclosed_trial_amount_usd: nullableString(consent["disclosed_trial_amount_usd"]),
3223
+ consent_at: nullableString2(consent["consent_at"]),
3224
+ consent_ip: nullableString2(consent["consent_ip"]),
3225
+ consent_user_agent: nullableString2(consent["consent_user_agent"]),
3226
+ disclosed_amount_usd: nullableString2(consent["disclosed_amount_usd"]),
3227
+ disclosed_interval: nullableString2(consent["disclosed_interval"]),
3228
+ terms_version: nullableString2(consent["terms_version"]),
3229
+ disclosed_trial_amount_usd: nullableString2(consent["disclosed_trial_amount_usd"]),
3085
3230
  disclosed_trial_days: typeof consent["disclosed_trial_days"] === "number" ? consent["disclosed_trial_days"] : null,
3086
- disclosed_trial_end: nullableString(consent["disclosed_trial_end"])
3231
+ disclosed_trial_end: nullableString2(consent["disclosed_trial_end"])
3087
3232
  },
3088
3233
  createdAt: String(r["created_at"] ?? ""),
3089
3234
  updatedAt: String(r["updated_at"] ?? ""),
@@ -3093,13 +3238,13 @@ function toSubscription(row) {
3093
3238
  // Attribution only: INVO never pays the recipient. Read the wire value, never assume.
3094
3239
  settledByInvo: share["settled_by_invo"] === true
3095
3240
  } : null,
3096
- paidThrough: nullableString(r["paid_through"]),
3241
+ paidThrough: nullableString2(r["paid_through"]),
3097
3242
  amountCoinsEstimate: r["amount_coins_estimate"] == null ? void 0 : String(r["amount_coins_estimate"]),
3098
3243
  // Present (possibly null) only on create/finalize bodies from 2026-09-23 on.
3099
- ..."trial_amount_coins_estimate" in r ? { trialAmountCoinsEstimate: nullableString(r["trial_amount_coins_estimate"]) } : {},
3244
+ ..."trial_amount_coins_estimate" in r ? { trialAmountCoinsEstimate: nullableString2(r["trial_amount_coins_estimate"]) } : {},
3100
3245
  // `include_player` puts these two ON the object (there is no separate block).
3101
- ..."player_email" in r ? { playerEmail: nullableString(r["player_email"]) } : {},
3102
- ..."player_name" in r ? { playerName: nullableString(r["player_name"]) } : {},
3246
+ ..."player_email" in r ? { playerEmail: nullableString2(r["player_email"]) } : {},
3247
+ ..."player_name" in r ? { playerName: nullableString2(r["player_name"]) } : {},
3103
3248
  raw: r
3104
3249
  };
3105
3250
  }
@@ -3107,14 +3252,14 @@ function toFirstCharge(row) {
3107
3252
  const r = row && typeof row === "object" ? row : {};
3108
3253
  return {
3109
3254
  status: String(r["status"] ?? "pending"),
3110
- amountUsd: nullableString(r["amount_usd"]),
3255
+ amountUsd: nullableString2(r["amount_usd"]),
3111
3256
  paidPeriodSeq: typeof r["paid_period_seq"] === "number" ? r["paid_period_seq"] : null,
3112
- paidThrough: nullableString(r["paid_through"]),
3113
- failureCode: nullableString(r["failure_code"]),
3114
- nextRetryAt: nullableString(r["next_retry_at"]),
3115
- confirmationUrl: nullableString(r["confirmation_url"]),
3116
- expiresAt: nullableString(r["expires_at"]),
3117
- message: nullableString(r["message"]),
3257
+ paidThrough: nullableString2(r["paid_through"]),
3258
+ failureCode: nullableString2(r["failure_code"]),
3259
+ nextRetryAt: nullableString2(r["next_retry_at"]),
3260
+ confirmationUrl: nullableString2(r["confirmation_url"]),
3261
+ expiresAt: nullableString2(r["expires_at"]),
3262
+ message: nullableString2(r["message"]),
3118
3263
  ...receiptFields(r),
3119
3264
  raw: r
3120
3265
  };
@@ -3136,10 +3281,10 @@ function toSandboxClockState(row) {
3136
3281
  return {
3137
3282
  status: String(r["status"] ?? ""),
3138
3283
  periodSeq: Number(r["period_seq"] ?? 0),
3139
- currentPeriodStart: nullableString(r["current_period_start"]),
3140
- currentPeriodEnd: nullableString(r["current_period_end"]),
3141
- nextChargeAt: nullableString(r["next_charge_at"]),
3142
- trialEnd: nullableString(r["trial_end"]),
3284
+ currentPeriodStart: nullableString2(r["current_period_start"]),
3285
+ currentPeriodEnd: nullableString2(r["current_period_end"]),
3286
+ nextChargeAt: nullableString2(r["next_charge_at"]),
3287
+ trialEnd: nullableString2(r["trial_end"]),
3143
3288
  cancelAtPeriodEnd: r["cancel_at_period_end"] === true,
3144
3289
  walletOnly: r["wallet_only"] === true,
3145
3290
  hasPaymentMethod: r["has_payment_method"] === true,
@@ -3442,14 +3587,14 @@ var SubscriptionsServer = class {
3442
3587
  alreadyCanceled: raw["already_canceled"] === true,
3443
3588
  finalStatus: typeof raw["final_status"] === "string" ? raw["final_status"] : void 0,
3444
3589
  cancelAtPeriodEnd: raw["cancel_at_period_end"] === true,
3445
- effectiveAt: nullableString(raw["effective_at"]),
3446
- currentPeriodEnd: nullableString(raw["current_period_end"]),
3447
- accessUntil: nullableString(raw["access_until"]),
3448
- paidThrough: nullableString(raw["paid_through"]),
3590
+ effectiveAt: nullableString2(raw["effective_at"]),
3591
+ currentPeriodEnd: nullableString2(raw["current_period_end"]),
3592
+ accessUntil: nullableString2(raw["access_until"]),
3593
+ paidThrough: nullableString2(raw["paid_through"]),
3449
3594
  terminatedImmediately: raw["terminated_immediately"] === true,
3450
3595
  downgradeReason: typeof raw["downgrade_reason"] === "string" ? raw["downgrade_reason"] : void 0,
3451
3596
  message: typeof raw["message"] === "string" ? raw["message"] : void 0,
3452
- steamAgreementStatus: "steam_agreement_status" in raw ? nullableString(raw["steam_agreement_status"]) : void 0,
3597
+ steamAgreementStatus: "steam_agreement_status" in raw ? nullableString2(raw["steam_agreement_status"]) : void 0,
3453
3598
  steamAgreementCanceled: typeof raw["steam_agreement_canceled"] === "boolean" ? raw["steam_agreement_canceled"] : void 0,
3454
3599
  subscription: raw["subscription"] ? toSubscription(raw["subscription"]) : null,
3455
3600
  raw
@@ -3480,12 +3625,12 @@ var SubscriptionsServer = class {
3480
3625
  status: String(raw["status"] ?? ""),
3481
3626
  oldAmountUsd: String(raw["old_amount_usd"] ?? ""),
3482
3627
  newAmountUsd: String(raw["new_amount_usd"] ?? amount),
3483
- pendingAmountUsd: nullableString(raw["pending_amount_usd"]),
3628
+ pendingAmountUsd: nullableString2(raw["pending_amount_usd"]),
3484
3629
  changeQueued: raw["change_queued"] === true,
3485
- appliesFrom: nullableString(raw["applies_from"]),
3630
+ appliesFrom: nullableString2(raw["applies_from"]),
3486
3631
  appliesFromPeriodSeq: Number(raw["applies_from_period_seq"] ?? 0),
3487
- paidThrough: nullableString(raw["paid_through"]),
3488
- currentPeriodEnd: nullableString(raw["current_period_end"]),
3632
+ paidThrough: nullableString2(raw["paid_through"]),
3633
+ currentPeriodEnd: nullableString2(raw["current_period_end"]),
3489
3634
  prorated: raw["prorated"] === true,
3490
3635
  subscription: raw["subscription"] ? toSubscription(raw["subscription"]) : null,
3491
3636
  raw
@@ -3671,7 +3816,7 @@ var SubscriptionsServer = class {
3671
3816
  orderId: String(raw["order_id"] ?? ""),
3672
3817
  steamOrderId: String(raw["steam_order_id"] ?? ""),
3673
3818
  steamTransid: String(raw["steam_transid"] ?? ""),
3674
- steamCheckoutUrl: nullableString(raw["steam_checkout_url"]),
3819
+ steamCheckoutUrl: nullableString2(raw["steam_checkout_url"]),
3675
3820
  amountUsd: String(raw["amount_usd"] ?? ""),
3676
3821
  amountCoins: String(raw["amount_coins"] ?? ""),
3677
3822
  steamChargeUsd: String(raw["steam_charge_usd"] ?? ""),
@@ -3709,7 +3854,7 @@ var SubscriptionsServer = class {
3709
3854
  return {
3710
3855
  ...toSubscriptionResult(raw),
3711
3856
  alreadyProcessed: raw["already_processed"] === true,
3712
- steamAgreementStatus: nullableString(raw["steam_agreement_status"]),
3857
+ steamAgreementStatus: nullableString2(raw["steam_agreement_status"]),
3713
3858
  sandboxAutoApproved: raw["sandbox_auto_approved"] === true
3714
3859
  };
3715
3860
  }
@@ -4633,6 +4778,81 @@ var InvoServer = class {
4633
4778
  raw
4634
4779
  };
4635
4780
  }
4781
+ /**
4782
+ * The App Store products registered for this game, and whether INVO will sell each one
4783
+ * right now. Call it with the game's iOS key **before every purchase** and offer only
4784
+ * products with `available: true`: Apple charges the player before INVO sees the
4785
+ * purchase, so this is the only point where INVO can say no. Ask StoreKit for exactly the
4786
+ * `productId`s listed.
4787
+ *
4788
+ * `unavailableReason` (per product, and for the whole game when `canSell` is `false`):
4789
+ * `APPLE_NOT_VERIFIED`, `PARTNER_BILLING_NOT_SET_UP`, `PARTNER_RAIL_SUSPENDED`,
4790
+ * `PARTNER_CREDIT_UNAVAILABLE`.
4791
+ *
4792
+ * Refusals: `err.isAppleNotConfigured` (409, no Apple configuration or turned off),
4793
+ * `err.isRailChannelMismatch` (409, the key is not an iOS key on the Apple rail).
4794
+ */
4795
+ async appleProducts(opts) {
4796
+ const raw = await this.http.get(
4797
+ "/api/currency-purchases/apple/products",
4798
+ this.auth,
4799
+ { signal: opts?.signal }
4800
+ );
4801
+ return toAppleProductsResult(raw);
4802
+ }
4803
+ /**
4804
+ * Verify a StoreKit 2 transaction and credit its coins, once. Call it from your game
4805
+ * SERVER, never the device, after StoreKit returns a verified transaction, with the
4806
+ * game's iOS key. Send `Transaction.jwsRepresentation` unchanged as `signedTransaction`.
4807
+ *
4808
+ * Then decide `Transaction.finish()` with {@link shouldFinishAppleTransaction}, passing
4809
+ * the result or the thrown error. It reads INVO's `finish` flag, which every answer carries
4810
+ * (`result.finish`, `err.finish`): `true` for `credited`, `already_credited` and the terminal
4811
+ * errors `isAppleTransactionRevoked`, `isAppleTransactionAlreadyUsed` and
4812
+ * `isAppleTransactionTooOld`. On anything else leave the transaction unfinished and
4813
+ * retry: StoreKit redelivers it, and a retry with the same signed transaction never credits
4814
+ * twice (a replay answers `already_credited`, with `balance` `null` unless you name the
4815
+ * same player). Safe to auto-retry for the same reason.
4816
+ *
4817
+ * Refusals: `isAppleSignatureInvalid`, `isAppleBundleMismatch`,
4818
+ * `isAppleEnvironmentNotAllowed`, `isAppleProductTypeUnsupported`, `isAppleProductUnknown`,
4819
+ * `isInvalidMetadata` / `isInvalidInput` (400); `isAppleReviewAccountRequired` (403);
4820
+ * `isAppleTransactionRevoked`, `isAppleTransactionAlreadyUsed`, `isAppleTransactionTooOld`,
4821
+ * `isAppleValueExceedsPrice`, `isAppleAccountTokenMismatch`, `isAppleNotConfigured`,
4822
+ * `isAppleNotVerified`, `isRailChannelMismatch` (409); `isAppleReviewPurchaseLimit` (429);
4823
+ * `isAppleCreditPending` (503, verified and held: retry; also while payments are paused);
4824
+ * and the usual game-key refusals, which carry no `finish` (treated as not finished).
4825
+ */
4826
+ async verifyApplePurchase(input, opts) {
4827
+ if (typeof input?.playerEmail !== "string" || !input.playerEmail.trim()) {
4828
+ throw invalidInput2("playerEmail", input?.playerEmail, "is required");
4829
+ }
4830
+ if (typeof input.signedTransaction !== "string" || !input.signedTransaction.trim()) {
4831
+ throw invalidInput2(
4832
+ "signedTransaction",
4833
+ typeof input.signedTransaction === "string" ? "(empty)" : input.signedTransaction,
4834
+ "is required: StoreKit's Transaction.jwsRepresentation"
4835
+ );
4836
+ }
4837
+ if (input.appAccountToken !== void 0 && (typeof input.appAccountToken !== "string" || !input.appAccountToken || input.appAccountToken.length > 64)) {
4838
+ throw invalidInput2("appAccountToken", input.appAccountToken, "must be the UUID string the game set");
4839
+ }
4840
+ const body = {
4841
+ player_email: input.playerEmail,
4842
+ signed_transaction: input.signedTransaction
4843
+ };
4844
+ if (input.appAccountToken !== void 0) body["app_account_token"] = input.appAccountToken;
4845
+ if (input.playerName) body["player_name"] = input.playerName;
4846
+ if (input.metadata) body["metadata"] = input.metadata;
4847
+ const raw = await this.http.post(
4848
+ "/api/currency-purchases/apple/verify-purchase",
4849
+ body,
4850
+ this.auth,
4851
+ { idempotent: true, signal: opts?.signal }
4852
+ // INVO credits each Apple transaction once
4853
+ );
4854
+ return toApplePurchaseResult(raw);
4855
+ }
4636
4856
  /**
4637
4857
  * Buy an in-game item by SPENDING the player's existing game currency (§4.8).
4638
4858
  * No real money, no payment rail, no passkey — it's a balance debit, authenticated
@@ -5794,7 +6014,7 @@ function grant(state, playerId, itemId, quantity) {
5794
6014
  const inv = (_a = state.inventory)[playerId] ?? (_a[playerId] = {});
5795
6015
  inv[itemId] = (inv[itemId] ?? 0) + quantity;
5796
6016
  }
5797
- function toNumber(v) {
6017
+ function toNumber2(v) {
5798
6018
  if (typeof v === "number" && Number.isFinite(v)) return v;
5799
6019
  if (typeof v === "string" && v.trim() && Number.isFinite(Number(v))) return Number(v);
5800
6020
  return null;
@@ -5843,7 +6063,7 @@ function createInvoGameServer(options) {
5843
6063
  const res = await invo.getPlayerBalance({ playerEmail: player.email });
5844
6064
  const want = economy.premium.name.toLowerCase();
5845
6065
  const row = res.balances.find((b) => b.currencyName.toLowerCase() === want) ?? res.balances[0];
5846
- premium = row ? toNumber(row.availableBalance) ?? 0 : 0;
6066
+ premium = row ? toNumber2(row.availableBalance) ?? 0 : 0;
5847
6067
  } catch (err) {
5848
6068
  if (err instanceof InvoError && err.status === 404) premium = 0;
5849
6069
  else log("warn", "premium balance unavailable", { playerId: player.id, code: err.code });
@@ -5997,7 +6217,7 @@ function createInvoGameServer(options) {
5997
6217
  const purchase = s.purchases[p.purchaseRef];
5998
6218
  if (!purchase || purchase.status !== "pending") return purchase ?? null;
5999
6219
  if (result.status === "credited") {
6000
- const amount = toNumber(result.coinsCredited) ?? 0;
6220
+ const amount = toNumber2(result.coinsCredited) ?? 0;
6001
6221
  const orderId = result.orderId ?? "";
6002
6222
  const ref = `order:${orderId}`;
6003
6223
  if (orderId && !s.ledgerRefs[ref]) {
@@ -6039,7 +6259,7 @@ function createInvoGameServer(options) {
6039
6259
  switch (event.event_type) {
6040
6260
  case "purchase.completed": {
6041
6261
  if (metadata["source"] === "subscription_renewal") return "ignored";
6042
- const amount = toNumber(data["currency_amount"]) ?? 0;
6262
+ const amount = toNumber2(data["currency_amount"]) ?? 0;
6043
6263
  const owner = purchase?.playerId ?? playerId;
6044
6264
  if (owner) {
6045
6265
  addLedger(s, { playerId: owner, currency: "premium", amount, reason: "premium purchase (INVO)", ref: `order:${orderId}`, at });
@@ -6076,11 +6296,11 @@ function createInvoGameServer(options) {
6076
6296
  const itemId = String(data["item_id"] ?? "");
6077
6297
  const item = itemsById.get(itemId);
6078
6298
  if (!txId || !playerId || !item || s.ledgerRefs[`item:${txId}`]) return "noop";
6079
- const qty = Math.max(1, Math.trunc(toNumber(data["item_quantity"]) ?? 1));
6299
+ const qty = Math.max(1, Math.trunc(toNumber2(data["item_quantity"]) ?? 1));
6080
6300
  const owned = s.inventory[playerId]?.[itemId] ?? 0;
6081
6301
  const granted = Math.min(qty, Math.max(0, (item.maxOwned ?? 1) - owned));
6082
6302
  if (granted > 0) grant(s, playerId, itemId, granted);
6083
- addLedger(s, { playerId, currency: "premium", amount: -(toNumber(data["total_price"]) ?? item.price * qty), reason: `item ${itemId} (webhook)`, ref: `item:${txId}`, at });
6303
+ addLedger(s, { playerId, currency: "premium", amount: -(toNumber2(data["total_price"]) ?? item.price * qty), reason: `item ${itemId} (webhook)`, ref: `item:${txId}`, at });
6084
6304
  return "granted";
6085
6305
  }
6086
6306
  default:
@@ -6169,7 +6389,7 @@ function createInvoGameServer(options) {
6169
6389
  s.idempotency[idemKey] = { at: iso(), result: prior };
6170
6390
  });
6171
6391
  log("info", "item bought", { playerId: player.id, itemId: item.id, currency: "premium", transactionId: invoResult.transactionId });
6172
- return json(200, { ...prior, replayed: false, wallet: await readWallet(player, toNumber(invoResult.newBalance)) });
6392
+ return json(200, { ...prior, replayed: false, wallet: await readWallet(player, toNumber2(invoResult.newBalance)) });
6173
6393
  }
6174
6394
  async function earn(request) {
6175
6395
  const { player } = await sessionPlayer(request);
@@ -1,8 +1,8 @@
1
- import { I as InvoServer, a as InvoEnvironment } from './server-A1s7zqzG.cjs';
2
- export { D as DEMO_KEY_PREFIX, E as EnvironmentUnknownError, K as KeyEnvironmentMismatchError, L as LIVE_KEY_PREFIX, P as PRODUCTION_BASE_URL, S as SANDBOX_BASE_URL, T as TEST_KEY_PREFIX, b as baseUrlForKey, e as environmentForBaseUrl, c as environmentFromKeyPrefix, i as isDemoKey, r as resolveEnvironment, v as verifyInvoSignature } from './server-A1s7zqzG.cjs';
1
+ import { I as InvoServer, a as InvoEnvironment } from './server-DF-BZU0B.cjs';
2
+ export { D as DEMO_KEY_PREFIX, E as EnvironmentUnknownError, K as KeyEnvironmentMismatchError, L as LIVE_KEY_PREFIX, P as PRODUCTION_BASE_URL, S as SANDBOX_BASE_URL, T as TEST_KEY_PREFIX, b as baseUrlForKey, e as environmentForBaseUrl, c as environmentFromKeyPrefix, i as isDemoKey, r as resolveEnvironment, v as verifyInvoSignature } from './server-DF-BZU0B.cjs';
3
3
  import { G as GameCurrencyKind, a as GamePurchaseStatus, b as GameEconomyConfig } from './types-jUxfYjiD.cjs';
4
4
  export { c as GameCatalog, d as GameCatalogItem, e as GameCheckout, f as GameCurrencyBalance, g as GameErrorBody, h as GameItemPurchase, i as GamePlayer, j as GamePremiumPack, k as GamePurchase, l as GameSession, m as GameTransferInput, n as GameTransferKind, o as GameTransferStart, p as GameTransferStatus, q as GameWallet } from './types-jUxfYjiD.cjs';
5
- export { I as InvoError } from './types-B4J9Ifd2.cjs';
5
+ export { I as InvoError } from './types-Dv0UavA9.cjs';
6
6
  export { S as SDK_VERSION } from './version-DB2wgiPY.cjs';
7
7
  import './loyalty-events-CmDw2ZoR.cjs';
8
8
 
@@ -1,8 +1,8 @@
1
- import { I as InvoServer, a as InvoEnvironment } from './server-JARGQrat.js';
2
- export { D as DEMO_KEY_PREFIX, E as EnvironmentUnknownError, K as KeyEnvironmentMismatchError, L as LIVE_KEY_PREFIX, P as PRODUCTION_BASE_URL, S as SANDBOX_BASE_URL, T as TEST_KEY_PREFIX, b as baseUrlForKey, e as environmentForBaseUrl, c as environmentFromKeyPrefix, i as isDemoKey, r as resolveEnvironment, v as verifyInvoSignature } from './server-JARGQrat.js';
1
+ import { I as InvoServer, a as InvoEnvironment } from './server-CMJHOmYL.js';
2
+ export { D as DEMO_KEY_PREFIX, E as EnvironmentUnknownError, K as KeyEnvironmentMismatchError, L as LIVE_KEY_PREFIX, P as PRODUCTION_BASE_URL, S as SANDBOX_BASE_URL, T as TEST_KEY_PREFIX, b as baseUrlForKey, e as environmentForBaseUrl, c as environmentFromKeyPrefix, i as isDemoKey, r as resolveEnvironment, v as verifyInvoSignature } from './server-CMJHOmYL.js';
3
3
  import { G as GameCurrencyKind, a as GamePurchaseStatus, b as GameEconomyConfig } from './types-jUxfYjiD.js';
4
4
  export { c as GameCatalog, d as GameCatalogItem, e as GameCheckout, f as GameCurrencyBalance, g as GameErrorBody, h as GameItemPurchase, i as GamePlayer, j as GamePremiumPack, k as GamePurchase, l as GameSession, m as GameTransferInput, n as GameTransferKind, o as GameTransferStart, p as GameTransferStatus, q as GameWallet } from './types-jUxfYjiD.js';
5
- export { I as InvoError } from './types-B4J9Ifd2.js';
5
+ export { I as InvoError } from './types-Dv0UavA9.js';
6
6
  export { S as SDK_VERSION } from './version-DB2wgiPY.js';
7
7
  import './loyalty-events-CmDw2ZoR.js';
8
8
 
@@ -1,8 +1,8 @@
1
- import { isDemoKey, SANDBOX_BASE_URL, environmentFromKeyPrefix, assertKeyMatchesEnvironment, assertKeyMatchesBaseUrl, PRODUCTION_BASE_URL, InvoServer, resolveEnvironment, verifyWebhook } from './chunk-MJXQ3Q7C.js';
2
- export { DEMO_KEY_PREFIX, EnvironmentUnknownError, InvoServer, KeyEnvironmentMismatchError, LIVE_KEY_PREFIX, PRODUCTION_BASE_URL, SANDBOX_BASE_URL, TEST_KEY_PREFIX, baseUrlForKey, environmentForBaseUrl, environmentFromKeyPrefix, isDemoKey, resolveEnvironment, verifyInvoSignature } from './chunk-MJXQ3Q7C.js';
1
+ import { isDemoKey, SANDBOX_BASE_URL, environmentFromKeyPrefix, assertKeyMatchesEnvironment, assertKeyMatchesBaseUrl, PRODUCTION_BASE_URL, InvoServer, resolveEnvironment, verifyWebhook } from './chunk-XN6MCLQV.js';
2
+ export { DEMO_KEY_PREFIX, EnvironmentUnknownError, InvoServer, KeyEnvironmentMismatchError, LIVE_KEY_PREFIX, PRODUCTION_BASE_URL, SANDBOX_BASE_URL, TEST_KEY_PREFIX, baseUrlForKey, environmentForBaseUrl, environmentFromKeyPrefix, isDemoKey, resolveEnvironment, verifyInvoSignature } from './chunk-XN6MCLQV.js';
3
3
  export { SDK_VERSION } from './chunk-6763YM7P.js';
4
- import { InvoError } from './chunk-3BR7URPM.js';
5
- export { InvoError } from './chunk-3BR7URPM.js';
4
+ import { InvoError } from './chunk-BGCSSWVL.js';
5
+ export { InvoError } from './chunk-BGCSSWVL.js';
6
6
  import { createHash, randomBytes } from 'crypto';
7
7
  import { promises, readFileSync, mkdirSync, writeFileSync } from 'fs';
8
8
  import * as path from 'path';