@invonetwork/web-sdk 3.32.0 → 3.34.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.
@@ -30,7 +30,84 @@ var path__namespace = /*#__PURE__*/_interopNamespace(path);
30
30
  var PRODUCTION_BASE_URL = "https://invo.network";
31
31
  var SANDBOX_BASE_URL = "https://sandbox.invo.network/sandbox";
32
32
  var DEMO_KEY_PREFIX = "ivsdk_demo_";
33
+ var TEST_KEY_PREFIX = "ivsdk_test_";
34
+ var LIVE_KEY_PREFIX = "ivsdk_live_";
33
35
  var KEY_ENVIRONMENT_PATH = "/api/sdk/key-environment";
36
+ function environmentFromKeyPrefix(gameSecret) {
37
+ if (typeof gameSecret !== "string") return null;
38
+ if (gameSecret.startsWith(LIVE_KEY_PREFIX)) return "production";
39
+ if (gameSecret.startsWith(TEST_KEY_PREFIX) || gameSecret.startsWith(DEMO_KEY_PREFIX)) return "sandbox";
40
+ return null;
41
+ }
42
+ function environmentForBaseUrl(baseUrl) {
43
+ if (typeof baseUrl !== "string" || !baseUrl.trim()) return null;
44
+ let url;
45
+ try {
46
+ url = new URL(baseUrl.trim());
47
+ } catch {
48
+ return null;
49
+ }
50
+ const host = url.hostname.toLowerCase().replace(/\.$/, "");
51
+ if (host === "sandbox.invo.network") return "sandbox";
52
+ if (host === "invo.network" || host === "www.invo.network") {
53
+ const first = url.pathname.split("/").filter(Boolean)[0]?.toLowerCase();
54
+ return first === "sandbox" ? "sandbox" : "production";
55
+ }
56
+ return null;
57
+ }
58
+ var KeyEnvironmentMismatchError = class extends Error {
59
+ constructor(message, keyEnvironment, configuredEnvironment) {
60
+ super(message);
61
+ this.name = "KeyEnvironmentMismatchError";
62
+ this.keyEnvironment = keyEnvironment;
63
+ this.configuredEnvironment = configuredEnvironment;
64
+ }
65
+ };
66
+ function strictKeyEnvironment(gameSecret) {
67
+ if (typeof gameSecret !== "string") return null;
68
+ if (gameSecret.startsWith(LIVE_KEY_PREFIX)) return "production";
69
+ if (gameSecret.startsWith(TEST_KEY_PREFIX)) return "sandbox";
70
+ return null;
71
+ }
72
+ function describeKey(env) {
73
+ return env === "production" ? `a live key (${LIVE_KEY_PREFIX})` : `a test key (${TEST_KEY_PREFIX})`;
74
+ }
75
+ function fixFor(keyEnv) {
76
+ return keyEnv === "production" ? `Use ${PRODUCTION_BASE_URL}, or a test key.` : `Use ${SANDBOX_BASE_URL}, or a live key.`;
77
+ }
78
+ function displayUrl(baseUrl) {
79
+ try {
80
+ const u = new URL(baseUrl.trim());
81
+ return `${u.protocol}//${u.host}${u.pathname}`.replace(/\/+$/, "");
82
+ } catch {
83
+ return "(the configured URL)";
84
+ }
85
+ }
86
+ function assertKeyMatchesBaseUrl(gameSecret, baseUrl, setting = "baseUrl") {
87
+ const keyEnv = strictKeyEnvironment(gameSecret);
88
+ if (!keyEnv) return;
89
+ const urlEnv = environmentForBaseUrl(baseUrl);
90
+ if (!urlEnv || urlEnv === keyEnv) return;
91
+ const where = urlEnv === "production" ? "production" : "the sandbox";
92
+ const shown = displayUrl(String(baseUrl));
93
+ throw new KeyEnvironmentMismatchError(
94
+ `This is ${describeKey(keyEnv)} but ${setting} points at ${where} ${shown}. ${fixFor(keyEnv)}`,
95
+ keyEnv,
96
+ urlEnv
97
+ );
98
+ }
99
+ function assertKeyMatchesEnvironment(gameSecret, environment, setting = "INVO_ENV", rawValue) {
100
+ const keyEnv = strictKeyEnvironment(gameSecret);
101
+ if (!keyEnv || keyEnv === environment) return;
102
+ const other = keyEnv === "production" ? "a test key" : "a live key";
103
+ const raw = rawValue?.trim();
104
+ const shown = raw && raw.toLowerCase() !== environment ? `"${raw}" (read as ${environment})` : environment;
105
+ throw new KeyEnvironmentMismatchError(
106
+ `This is ${describeKey(keyEnv)} but ${setting} is ${shown}. Remove ${setting} (the key picks the environment), or use ${other}.`,
107
+ keyEnv,
108
+ environment
109
+ );
110
+ }
34
111
  var EnvironmentUnknownError = class extends Error {
35
112
  constructor(message) {
36
113
  super(message);
@@ -59,7 +136,8 @@ async function ask(baseUrl, gameSecret, fetchImpl) {
59
136
  }
60
137
  function resolveEnvironment(gameSecret, opts = {}) {
61
138
  if (!gameSecret) return Promise.reject(new Error("A game secret is required."));
62
- if (isDemoKey(gameSecret)) return Promise.resolve("sandbox");
139
+ const byPrefix = environmentFromKeyPrefix(gameSecret);
140
+ if (byPrefix) return Promise.resolve(byPrefix);
63
141
  const hit = cache.get(gameSecret);
64
142
  if (hit) return hit;
65
143
  const fetchImpl = opts.fetch ?? ((input, init) => fetch(input, init));
@@ -441,6 +519,36 @@ var InvoError = class _InvoError extends Error {
441
519
  get isPaymentsPaused() {
442
520
  return this.code === "PAYMENTS_PAUSED";
443
521
  }
522
+ /** The key belongs to the other INVO environment (`KEY_FOR_OTHER_ENVIRONMENT`, 401;
523
+ * additive, 3.34.0): a test key (`ivsdk_test_`) sent to production, or a live key
524
+ * (`ivsdk_live_`) sent to the sandbox. Never retried. Use the key for the environment
525
+ * you are calling, or point the SDK at the environment the key is for. The code is
526
+ * matched on any code field (`code`, `rawCode`, `publicCode`, or the body's
527
+ * `error_code` / `code`), since the 401 may carry a different `code`. */
528
+ get isKeyForOtherEnvironment() {
529
+ const C = "KEY_FOR_OTHER_ENVIRONMENT";
530
+ const b = this.bodyObject();
531
+ return this.code === C || this.rawCode === C || this.publicCode === C || b["error_code"] === C || b["code"] === C;
532
+ }
533
+ /** A buyer-approved balance purchase cannot start (`BALANCE_UNAVAILABLE`, 400; 3.33.0):
534
+ * the buyer is unknown here or their balance is short. One answer on purpose; the
535
+ * balance is never disclosed. Offer another way to pay. */
536
+ get isBalanceUnavailable() {
537
+ return this.code === "BALANCE_UNAVAILABLE";
538
+ }
539
+ /** Buyer approval is not available (`APPROVAL_NOT_AVAILABLE`, 503 or 409; 3.33.0). */
540
+ get isApprovalNotAvailable() {
541
+ return this.code === "APPROVAL_NOT_AVAILABLE";
542
+ }
543
+ /** No buyer-approved purchase with that id in your store (`APPROVAL_NOT_FOUND`, 404). */
544
+ get isApprovalNotFound() {
545
+ return this.code === "APPROVAL_NOT_FOUND";
546
+ }
547
+ /** `cancelApproval` on an approval that already ended (`APPROVAL_ALREADY_ENDED`, 409).
548
+ * Read it with `getApproval`: it may have completed. */
549
+ get isApprovalAlreadyEnded() {
550
+ return this.code === "APPROVAL_ALREADY_ENDED";
551
+ }
444
552
  /** True when init-purchase was given a `packId` that is not in INVO's Steam
445
553
  * catalogue (`UNKNOWN_STEAM_PACK`, 400). The error body's
446
554
  * `valid_pack_ids` lists what exists; re-fetch `steamPacks()` — the
@@ -1742,7 +1850,7 @@ function toPhoneChangeRequest(raw) {
1742
1850
  }
1743
1851
 
1744
1852
  // src/version.ts
1745
- var SDK_VERSION = "3.32.0";
1853
+ var SDK_VERSION = "3.34.0";
1746
1854
 
1747
1855
  // src/payouts.ts
1748
1856
  var AMOUNT = /^\d+(\.\d{1,2})?$/;
@@ -2287,6 +2395,23 @@ function toPlayerActivityEntry(raw) {
2287
2395
  raw
2288
2396
  };
2289
2397
  }
2398
+ function toPlatformApproval(raw) {
2399
+ const s = (k) => raw[k] == null ? null : String(raw[k]);
2400
+ const meta = raw["metadata"];
2401
+ return {
2402
+ approvalId: String(raw["approval_id"] ?? ""),
2403
+ clientRequestId: String(raw["client_request_id"] ?? ""),
2404
+ status: String(raw["status"] ?? ""),
2405
+ reason: s("reason"),
2406
+ totalPrice: s("total_price"),
2407
+ orderId: raw["order_id"] ?? null,
2408
+ transactionId: s("transaction_id"),
2409
+ expiresAt: s("expires_at"),
2410
+ decidedAt: s("decided_at"),
2411
+ metadata: meta && typeof meta === "object" && !Array.isArray(meta) ? meta : {},
2412
+ raw
2413
+ };
2414
+ }
2290
2415
  function toPlatformOrderStatus(raw, fallbackOrderId) {
2291
2416
  return {
2292
2417
  orderId: raw["order_id"] ?? fallbackOrderId ?? "",
@@ -2593,6 +2718,10 @@ var PlatformCommerceServer = class {
2593
2718
  if (input.successUrl) body["success_url"] = input.successUrl;
2594
2719
  if (input.cancelUrl) body["cancel_url"] = input.cancelUrl;
2595
2720
  if (input.metadata) body["metadata"] = input.metadata;
2721
+ if (input.requirePlayerApproval === true) {
2722
+ body["require_player_approval"] = true;
2723
+ if (input.returnUrl) body["return_url"] = input.returnUrl;
2724
+ }
2596
2725
  const raw = await this.http.post(
2597
2726
  "/api/platform-commerce/purchase",
2598
2727
  body,
@@ -2601,7 +2730,9 @@ var PlatformCommerceServer = class {
2601
2730
  { idempotent: true, signal: opts?.signal }
2602
2731
  );
2603
2732
  const status = String(raw["status"] ?? "");
2604
- if (status === "requires_payment") {
2733
+ if (status === "pending_approval") {
2734
+ requireField2(raw["approval_id"], "approval_id", raw);
2735
+ } else if (status === "requires_payment") {
2605
2736
  requireField2(raw["checkout_url"], "checkout_url", raw);
2606
2737
  } else {
2607
2738
  requireField2(raw["order_id"], "order_id", raw);
@@ -2622,9 +2753,39 @@ var PlatformCommerceServer = class {
2622
2753
  amountUsd: raw["amount_usd"] ?? null,
2623
2754
  idempotentReplay: raw["idempotent_replay"] === true,
2624
2755
  ...minPurchaseWarningField(raw),
2756
+ ...raw["approval_id"] != null ? { approvalId: String(raw["approval_id"]) } : {},
2757
+ ..."approval_url" in raw ? { approvalUrl: raw["approval_url"] ?? null } : {},
2625
2758
  raw
2626
2759
  };
2627
2760
  }
2761
+ /** Read a buyer-approved purchase (3.33.0) by `approvalId` or by your `clientRequestId`
2762
+ * (exactly one). A fallback to the webhooks: `completed` carries `orderId`; an ending
2763
+ * without a sale carries `reason`. Throws `err.isApprovalNotFound` (404). */
2764
+ async getApproval(key, opts) {
2765
+ const id = key?.approvalId;
2766
+ const crid = key?.clientRequestId;
2767
+ if (Boolean(id) === Boolean(crid)) {
2768
+ throw invalidInput2("approvalId", id, "provide exactly one of approvalId or clientRequestId");
2769
+ }
2770
+ const path2 = id ? `/api/platform-commerce/approvals/${encodeURIComponent(String(id))}` : `/api/platform-commerce/approvals?${new URLSearchParams({ client_request_id: String(crid) }).toString()}`;
2771
+ const raw = await this.http.get(path2, this.auth, { signal: opts?.signal });
2772
+ return toPlatformApproval(raw);
2773
+ }
2774
+ /** Withdraw a buyer-approved purchase that is still waiting (3.33.0).
2775
+ * `platform_commerce.declined` follows with reason `cancelled`. Throws
2776
+ * `err.isApprovalAlreadyEnded` (409) when it had already ended. */
2777
+ async cancelApproval(approvalId, opts) {
2778
+ if (typeof approvalId !== "string" || !approvalId.trim()) {
2779
+ throw invalidInput2("approvalId", approvalId, "is required");
2780
+ }
2781
+ const raw = await this.http.post(
2782
+ `/api/platform-commerce/approvals/${encodeURIComponent(approvalId)}/cancel`,
2783
+ {},
2784
+ this.auth,
2785
+ { idempotent: true, signal: opts?.signal }
2786
+ );
2787
+ return toPlatformApproval(raw);
2788
+ }
2628
2789
  /** Poll an order's status: `completed` (balance immediately; card after the webhook),
2629
2790
  * `pending_payment` (card awaiting confirmation), or `refunded`. Once the sale has settled,
2630
2791
  * `invoFeeUsd` / `partnerShareUsd` say what INVO kept and what you earned (additive). */
@@ -3851,6 +4012,7 @@ var InvoServer = class {
3851
4012
  if (!config.gameSecret) throw new Error("InvoServer requires a `gameSecret`.");
3852
4013
  if (!config.baseUrl) throw new Error("InvoServer requires a `baseUrl`.");
3853
4014
  assertSecureBaseUrl(config.baseUrl);
4015
+ assertKeyMatchesBaseUrl(config.gameSecret.trim(), config.baseUrl);
3854
4016
  this.http = new Http({
3855
4017
  baseUrl: config.baseUrl,
3856
4018
  timeoutMs: config.timeoutMs,
@@ -6341,7 +6503,9 @@ function invoGameServerFromEnv(options) {
6341
6503
  const env = options.env;
6342
6504
  const secret = env["INVO_GAME_SECRET"]?.trim() ?? "";
6343
6505
  const forced = env["INVO_ENV"]?.trim().toLowerCase();
6344
- const known = forced ? forced === "production" ? "production" : "sandbox" : env["INVO_BASE_URL"] || !secret || isDemoKey(secret) ? "sandbox" : null;
6506
+ const forcedEnv = forced ? forced === "production" ? "production" : "sandbox" : null;
6507
+ const prefixEnv = isDemoKey(secret) ? null : environmentFromKeyPrefix(secret);
6508
+ const known = forcedEnv ? forcedEnv : prefixEnv ? prefixEnv : env["INVO_BASE_URL"] || !secret || isDemoKey(secret) ? "sandbox" : null;
6345
6509
  const state = { environment: known };
6346
6510
  const sandboxNow = () => state.environment === "sandbox";
6347
6511
  const envNow = () => state.environment ?? "resolving";
@@ -6358,9 +6522,11 @@ function invoGameServerFromEnv(options) {
6358
6522
  if (missing.length) {
6359
6523
  return { server: setupRequiredServer(options.economy, missing, sandboxNow(), options.basePath, demo), missing, sandbox: sandboxNow(), environment: envNow(), demo };
6360
6524
  }
6525
+ if (forcedEnv) assertKeyMatchesEnvironment(secret, forcedEnv, "INVO_ENV", env["INVO_ENV"]);
6526
+ assertKeyMatchesBaseUrl(secret, env["INVO_BASE_URL"], "INVO_BASE_URL");
6361
6527
  const baseFetch = options.fetch ?? ((input, init) => fetch(input, init));
6362
6528
  const projectId = demoProject?.projectId ?? ((options.projectId ?? env["INVO_PROJECT_ID"])?.trim() || void 0);
6363
- const explicitBase = env["INVO_BASE_URL"] || (forced ? state.environment === "production" ? PRODUCTION_BASE_URL : SANDBOX_BASE_URL : "");
6529
+ const explicitBase = env["INVO_BASE_URL"] || (forced || prefixEnv ? state.environment === "production" ? PRODUCTION_BASE_URL : SANDBOX_BASE_URL : "");
6364
6530
  const resolveNow = () => resolveEnvironment(secret, { fetch: baseFetch }).then((e) => {
6365
6531
  state.environment = e;
6366
6532
  return e;
@@ -6556,15 +6722,20 @@ exports.EnvironmentUnknownError = EnvironmentUnknownError;
6556
6722
  exports.GameServerError = GameServerError;
6557
6723
  exports.InvoError = InvoError;
6558
6724
  exports.InvoServer = InvoServer;
6725
+ exports.KeyEnvironmentMismatchError = KeyEnvironmentMismatchError;
6726
+ exports.LIVE_KEY_PREFIX = LIVE_KEY_PREFIX;
6559
6727
  exports.PRODUCTION_BASE_URL = PRODUCTION_BASE_URL;
6560
6728
  exports.SANDBOX_BASE_URL = SANDBOX_BASE_URL;
6561
6729
  exports.SDK_VERSION = SDK_VERSION;
6730
+ exports.TEST_KEY_PREFIX = TEST_KEY_PREFIX;
6562
6731
  exports.baseUrlForKey = baseUrlForKey;
6563
6732
  exports.createFileGameStore = createFileGameStore;
6564
6733
  exports.createInvoGameServer = createInvoGameServer;
6565
6734
  exports.createMemoryGameStore = createMemoryGameStore;
6566
6735
  exports.demoPhoneFor = demoPhoneFor;
6567
6736
  exports.emptyGameState = emptyGameState;
6737
+ exports.environmentForBaseUrl = environmentForBaseUrl;
6738
+ exports.environmentFromKeyPrefix = environmentFromKeyPrefix;
6568
6739
  exports.invoGameServerFromEnv = invoGameServerFromEnv;
6569
6740
  exports.isDemoKey = isDemoKey;
6570
6741
  exports.isValidProjectId = isValidProjectId;
@@ -1,9 +1,9 @@
1
- import { I as InvoServer, a as InvoEnvironment } from './server-jAn9dNM3.cjs';
2
- export { D as DEMO_KEY_PREFIX, E as EnvironmentUnknownError, P as PRODUCTION_BASE_URL, S as SANDBOX_BASE_URL, b as baseUrlForKey, i as isDemoKey, r as resolveEnvironment, v as verifyInvoSignature } from './server-jAn9dNM3.cjs';
1
+ import { I as InvoServer, a as InvoEnvironment } from './server-ZnCyLWA2.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-ZnCyLWA2.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-CaPHNjOU.cjs';
6
- export { S as SDK_VERSION } from './version-CqwGhQXV.cjs';
5
+ export { I as InvoError } from './types-Ctn8N2_l.cjs';
6
+ export { S as SDK_VERSION } from './version-Ce_pLpJf.cjs';
7
7
  import './loyalty-events-CmDw2ZoR.cjs';
8
8
 
9
9
  interface StoredPlayer {
@@ -217,12 +217,16 @@ interface InvoGameServerSetup {
217
217
  * game itself stays playable.
218
218
  *
219
219
  * - `INVO_GAME_SECRET` (required): your INVO key. The environment follows the key (3.28.0): the
220
- * public demo key (`ivsdk_demo_...`) is the sandbox; any other key is looked up once with
221
- * `GET /api/sdk/key-environment`. Going live is swapping this key, nothing else.
220
+ * public demo key (`ivsdk_demo_...`) and test keys (`ivsdk_test_...`, 3.34.0) are the sandbox,
221
+ * live keys (`ivsdk_live_...`, 3.34.0) are production, and any other key is looked up once
222
+ * with `GET /api/sdk/key-environment`. Going live is swapping this key, nothing else.
222
223
  * - `INVO_WEBHOOK_SECRET` (required): the webhook signing secret; several, comma-separated, while rotating
223
224
  * - `INVO_PROJECT_ID`: this copy's project id, when `projectId` is not passed
224
- * - `INVO_ENV`: `sandbox` or `production`, only to override the key-based choice
225
- * - `INVO_BASE_URL`: override the API base (rarely needed)
225
+ * - `INVO_ENV`: `sandbox` or `production`, only to override the key-based choice. With a live
226
+ * or test key it must agree with the key, or this throws `KeyEnvironmentMismatchError`.
227
+ * - `INVO_BASE_URL`: override the API base (rarely needed). With a live or test key, an INVO
228
+ * host for the other environment throws `KeyEnvironmentMismatchError`; any other host
229
+ * (your own proxy) is not checked.
226
230
  * - `PUBLIC_URL`: the game's public origin, for checkout return links
227
231
  */
228
232
  declare function invoGameServerFromEnv(options: InvoGameServerFromEnvOptions): InvoGameServerSetup;
@@ -1,9 +1,9 @@
1
- import { I as InvoServer, a as InvoEnvironment } from './server-B-KKg5P0.js';
2
- export { D as DEMO_KEY_PREFIX, E as EnvironmentUnknownError, P as PRODUCTION_BASE_URL, S as SANDBOX_BASE_URL, b as baseUrlForKey, i as isDemoKey, r as resolveEnvironment, v as verifyInvoSignature } from './server-B-KKg5P0.js';
1
+ import { I as InvoServer, a as InvoEnvironment } from './server-CtXpytKt.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-CtXpytKt.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-CaPHNjOU.js';
6
- export { S as SDK_VERSION } from './version-CqwGhQXV.js';
5
+ export { I as InvoError } from './types-Ctn8N2_l.js';
6
+ export { S as SDK_VERSION } from './version-Ce_pLpJf.js';
7
7
  import './loyalty-events-CmDw2ZoR.js';
8
8
 
9
9
  interface StoredPlayer {
@@ -217,12 +217,16 @@ interface InvoGameServerSetup {
217
217
  * game itself stays playable.
218
218
  *
219
219
  * - `INVO_GAME_SECRET` (required): your INVO key. The environment follows the key (3.28.0): the
220
- * public demo key (`ivsdk_demo_...`) is the sandbox; any other key is looked up once with
221
- * `GET /api/sdk/key-environment`. Going live is swapping this key, nothing else.
220
+ * public demo key (`ivsdk_demo_...`) and test keys (`ivsdk_test_...`, 3.34.0) are the sandbox,
221
+ * live keys (`ivsdk_live_...`, 3.34.0) are production, and any other key is looked up once
222
+ * with `GET /api/sdk/key-environment`. Going live is swapping this key, nothing else.
222
223
  * - `INVO_WEBHOOK_SECRET` (required): the webhook signing secret; several, comma-separated, while rotating
223
224
  * - `INVO_PROJECT_ID`: this copy's project id, when `projectId` is not passed
224
- * - `INVO_ENV`: `sandbox` or `production`, only to override the key-based choice
225
- * - `INVO_BASE_URL`: override the API base (rarely needed)
225
+ * - `INVO_ENV`: `sandbox` or `production`, only to override the key-based choice. With a live
226
+ * or test key it must agree with the key, or this throws `KeyEnvironmentMismatchError`.
227
+ * - `INVO_BASE_URL`: override the API base (rarely needed). With a live or test key, an INVO
228
+ * host for the other environment throws `KeyEnvironmentMismatchError`; any other host
229
+ * (your own proxy) is not checked.
226
230
  * - `PUBLIC_URL`: the game's public origin, for checkout return links
227
231
  */
228
232
  declare function invoGameServerFromEnv(options: InvoGameServerFromEnvOptions): InvoGameServerSetup;
@@ -1,8 +1,8 @@
1
- import { isDemoKey, SANDBOX_BASE_URL, PRODUCTION_BASE_URL, InvoServer, resolveEnvironment, verifyWebhook } from './chunk-RPGRRZFY.js';
2
- export { DEMO_KEY_PREFIX, EnvironmentUnknownError, InvoServer, PRODUCTION_BASE_URL, SANDBOX_BASE_URL, baseUrlForKey, isDemoKey, resolveEnvironment, verifyInvoSignature } from './chunk-RPGRRZFY.js';
3
- export { SDK_VERSION } from './chunk-LVVPRVPU.js';
4
- import { InvoError } from './chunk-QEJB6HC7.js';
5
- export { InvoError } from './chunk-QEJB6HC7.js';
1
+ import { isDemoKey, SANDBOX_BASE_URL, environmentFromKeyPrefix, assertKeyMatchesEnvironment, assertKeyMatchesBaseUrl, PRODUCTION_BASE_URL, InvoServer, resolveEnvironment, verifyWebhook } from './chunk-D2AUZRYS.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-D2AUZRYS.js';
3
+ export { SDK_VERSION } from './chunk-73ZVDQZV.js';
4
+ import { InvoError } from './chunk-R65CANFG.js';
5
+ export { InvoError } from './chunk-R65CANFG.js';
6
6
  import { createHash, randomBytes } from 'crypto';
7
7
  import { promises, readFileSync, mkdirSync, writeFileSync } from 'fs';
8
8
  import * as path from 'path';
@@ -954,7 +954,9 @@ function invoGameServerFromEnv(options) {
954
954
  const env = options.env;
955
955
  const secret = env["INVO_GAME_SECRET"]?.trim() ?? "";
956
956
  const forced = env["INVO_ENV"]?.trim().toLowerCase();
957
- const known = forced ? forced === "production" ? "production" : "sandbox" : env["INVO_BASE_URL"] || !secret || isDemoKey(secret) ? "sandbox" : null;
957
+ const forcedEnv = forced ? forced === "production" ? "production" : "sandbox" : null;
958
+ const prefixEnv = isDemoKey(secret) ? null : environmentFromKeyPrefix(secret);
959
+ const known = forcedEnv ? forcedEnv : prefixEnv ? prefixEnv : env["INVO_BASE_URL"] || !secret || isDemoKey(secret) ? "sandbox" : null;
958
960
  const state = { environment: known };
959
961
  const sandboxNow = () => state.environment === "sandbox";
960
962
  const envNow = () => state.environment ?? "resolving";
@@ -971,9 +973,11 @@ function invoGameServerFromEnv(options) {
971
973
  if (missing.length) {
972
974
  return { server: setupRequiredServer(options.economy, missing, sandboxNow(), options.basePath, demo), missing, sandbox: sandboxNow(), environment: envNow(), demo };
973
975
  }
976
+ if (forcedEnv) assertKeyMatchesEnvironment(secret, forcedEnv, "INVO_ENV", env["INVO_ENV"]);
977
+ assertKeyMatchesBaseUrl(secret, env["INVO_BASE_URL"], "INVO_BASE_URL");
974
978
  const baseFetch = options.fetch ?? ((input, init) => fetch(input, init));
975
979
  const projectId = demoProject?.projectId ?? ((options.projectId ?? env["INVO_PROJECT_ID"])?.trim() || void 0);
976
- const explicitBase = env["INVO_BASE_URL"] || (forced ? state.environment === "production" ? PRODUCTION_BASE_URL : SANDBOX_BASE_URL : "");
980
+ const explicitBase = env["INVO_BASE_URL"] || (forced || prefixEnv ? state.environment === "production" ? PRODUCTION_BASE_URL : SANDBOX_BASE_URL : "");
977
981
  const resolveNow = () => resolveEnvironment(secret, { fetch: baseFetch }).then((e) => {
978
982
  state.environment = e;
979
983
  return e;
package/dist/game.cjs CHANGED
@@ -347,6 +347,36 @@ var InvoError = class _InvoError extends Error {
347
347
  get isPaymentsPaused() {
348
348
  return this.code === "PAYMENTS_PAUSED";
349
349
  }
350
+ /** The key belongs to the other INVO environment (`KEY_FOR_OTHER_ENVIRONMENT`, 401;
351
+ * additive, 3.34.0): a test key (`ivsdk_test_`) sent to production, or a live key
352
+ * (`ivsdk_live_`) sent to the sandbox. Never retried. Use the key for the environment
353
+ * you are calling, or point the SDK at the environment the key is for. The code is
354
+ * matched on any code field (`code`, `rawCode`, `publicCode`, or the body's
355
+ * `error_code` / `code`), since the 401 may carry a different `code`. */
356
+ get isKeyForOtherEnvironment() {
357
+ const C = "KEY_FOR_OTHER_ENVIRONMENT";
358
+ const b = this.bodyObject();
359
+ return this.code === C || this.rawCode === C || this.publicCode === C || b["error_code"] === C || b["code"] === C;
360
+ }
361
+ /** A buyer-approved balance purchase cannot start (`BALANCE_UNAVAILABLE`, 400; 3.33.0):
362
+ * the buyer is unknown here or their balance is short. One answer on purpose; the
363
+ * balance is never disclosed. Offer another way to pay. */
364
+ get isBalanceUnavailable() {
365
+ return this.code === "BALANCE_UNAVAILABLE";
366
+ }
367
+ /** Buyer approval is not available (`APPROVAL_NOT_AVAILABLE`, 503 or 409; 3.33.0). */
368
+ get isApprovalNotAvailable() {
369
+ return this.code === "APPROVAL_NOT_AVAILABLE";
370
+ }
371
+ /** No buyer-approved purchase with that id in your store (`APPROVAL_NOT_FOUND`, 404). */
372
+ get isApprovalNotFound() {
373
+ return this.code === "APPROVAL_NOT_FOUND";
374
+ }
375
+ /** `cancelApproval` on an approval that already ended (`APPROVAL_ALREADY_ENDED`, 409).
376
+ * Read it with `getApproval`: it may have completed. */
377
+ get isApprovalAlreadyEnded() {
378
+ return this.code === "APPROVAL_ALREADY_ENDED";
379
+ }
350
380
  /** True when init-purchase was given a `packId` that is not in INVO's Steam
351
381
  * catalogue (`UNKNOWN_STEAM_PACK`, 400). The error body's
352
382
  * `valid_pack_ids` lists what exists; re-fetch `steamPacks()` — the
@@ -4864,7 +4894,7 @@ function mountInvoUI(container, economy, options = {}) {
4864
4894
  }
4865
4895
 
4866
4896
  // src/version.ts
4867
- var SDK_VERSION = "3.32.0";
4897
+ var SDK_VERSION = "3.34.0";
4868
4898
 
4869
4899
  exports.InvoGameEconomy = InvoGameEconomy;
4870
4900
  exports.InvoGameError = InvoGameError;
package/dist/game.d.cts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { i as GamePlayer, q as GameWallet, c as GameCatalog, k as GamePurchase, h as GameItemPurchase, n as GameTransferKind, d as GameCatalogItem, f as GameCurrencyBalance, p as GameTransferStatus, m as GameTransferInput, o as GameTransferStart } from './types-jUxfYjiD.cjs';
2
2
  export { e as GameCheckout, G as GameCurrencyKind, b as GameEconomyConfig, g as GameErrorBody, j as GamePremiumPack, a as GamePurchaseStatus, l as GameSession } from './types-jUxfYjiD.cjs';
3
- import { A as ApproveHostedResult } from './hosted-approval-li0XZFz-.cjs';
4
- import { D as DestinationGame, P as PendingCollectItem } from './types-CaPHNjOU.cjs';
5
- export { S as SDK_VERSION } from './version-CqwGhQXV.cjs';
3
+ import { A as ApproveHostedResult } from './hosted-approval-C1hQvbu6.cjs';
4
+ import { D as DestinationGame, P as PendingCollectItem } from './types-Ctn8N2_l.cjs';
5
+ export { S as SDK_VERSION } from './version-Ce_pLpJf.cjs';
6
6
 
7
7
  /**
8
8
  * INVO game economy client (3.27.0), the browser half. It talks ONLY to your game server
package/dist/game.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { i as GamePlayer, q as GameWallet, c as GameCatalog, k as GamePurchase, h as GameItemPurchase, n as GameTransferKind, d as GameCatalogItem, f as GameCurrencyBalance, p as GameTransferStatus, m as GameTransferInput, o as GameTransferStart } from './types-jUxfYjiD.js';
2
2
  export { e as GameCheckout, G as GameCurrencyKind, b as GameEconomyConfig, g as GameErrorBody, j as GamePremiumPack, a as GamePurchaseStatus, l as GameSession } from './types-jUxfYjiD.js';
3
- import { A as ApproveHostedResult } from './hosted-approval-ICho9KsV.js';
4
- import { D as DestinationGame, P as PendingCollectItem } from './types-CaPHNjOU.js';
5
- export { S as SDK_VERSION } from './version-CqwGhQXV.js';
3
+ import { A as ApproveHostedResult } from './hosted-approval-CFlj4UQE.js';
4
+ import { D as DestinationGame, P as PendingCollectItem } from './types-Ctn8N2_l.js';
5
+ export { S as SDK_VERSION } from './version-Ce_pLpJf.js';
6
6
 
7
7
  /**
8
8
  * INVO game economy client (3.27.0), the browser half. It talks ONLY to your game server
package/dist/game.js CHANGED
@@ -1,6 +1,6 @@
1
- import { InvoClient } from './chunk-2XOKKKFR.js';
2
- export { SDK_VERSION } from './chunk-LVVPRVPU.js';
3
- import { newEventId } from './chunk-QEJB6HC7.js';
1
+ import { InvoClient } from './chunk-DMTNU5PM.js';
2
+ export { SDK_VERSION } from './chunk-73ZVDQZV.js';
3
+ import { newEventId } from './chunk-R65CANFG.js';
4
4
 
5
5
  // src/game/client.ts
6
6
  var InvoGameError = class extends Error {
@@ -1,4 +1,4 @@
1
- import { A as ApproveResult, j as ConfirmReceiptResult } from './types-CaPHNjOU.cjs';
1
+ import { A as ApproveResult, j as ConfirmReceiptResult } from './types-Ctn8N2_l.cjs';
2
2
 
3
3
  /** The four device-approval flows (`begin.flow`). */
4
4
  type HostedFlow = "transfer" | "send" | "send_receipt" | "transfer_receipt";
@@ -1,4 +1,4 @@
1
- import { A as ApproveResult, j as ConfirmReceiptResult } from './types-CaPHNjOU.js';
1
+ import { A as ApproveResult, j as ConfirmReceiptResult } from './types-Ctn8N2_l.js';
2
2
 
3
3
  /** The four device-approval flows (`begin.flow`). */
4
4
  type HostedFlow = "transfer" | "send" | "send_receipt" | "transfer_receipt";
package/dist/index.cjs CHANGED
@@ -347,6 +347,36 @@ var InvoError = class _InvoError extends Error {
347
347
  get isPaymentsPaused() {
348
348
  return this.code === "PAYMENTS_PAUSED";
349
349
  }
350
+ /** The key belongs to the other INVO environment (`KEY_FOR_OTHER_ENVIRONMENT`, 401;
351
+ * additive, 3.34.0): a test key (`ivsdk_test_`) sent to production, or a live key
352
+ * (`ivsdk_live_`) sent to the sandbox. Never retried. Use the key for the environment
353
+ * you are calling, or point the SDK at the environment the key is for. The code is
354
+ * matched on any code field (`code`, `rawCode`, `publicCode`, or the body's
355
+ * `error_code` / `code`), since the 401 may carry a different `code`. */
356
+ get isKeyForOtherEnvironment() {
357
+ const C = "KEY_FOR_OTHER_ENVIRONMENT";
358
+ const b = this.bodyObject();
359
+ return this.code === C || this.rawCode === C || this.publicCode === C || b["error_code"] === C || b["code"] === C;
360
+ }
361
+ /** A buyer-approved balance purchase cannot start (`BALANCE_UNAVAILABLE`, 400; 3.33.0):
362
+ * the buyer is unknown here or their balance is short. One answer on purpose; the
363
+ * balance is never disclosed. Offer another way to pay. */
364
+ get isBalanceUnavailable() {
365
+ return this.code === "BALANCE_UNAVAILABLE";
366
+ }
367
+ /** Buyer approval is not available (`APPROVAL_NOT_AVAILABLE`, 503 or 409; 3.33.0). */
368
+ get isApprovalNotAvailable() {
369
+ return this.code === "APPROVAL_NOT_AVAILABLE";
370
+ }
371
+ /** No buyer-approved purchase with that id in your store (`APPROVAL_NOT_FOUND`, 404). */
372
+ get isApprovalNotFound() {
373
+ return this.code === "APPROVAL_NOT_FOUND";
374
+ }
375
+ /** `cancelApproval` on an approval that already ended (`APPROVAL_ALREADY_ENDED`, 409).
376
+ * Read it with `getApproval`: it may have completed. */
377
+ get isApprovalAlreadyEnded() {
378
+ return this.code === "APPROVAL_ALREADY_ENDED";
379
+ }
350
380
  /** True when init-purchase was given a `packId` that is not in INVO's Steam
351
381
  * catalogue (`UNKNOWN_STEAM_PACK`, 400). The error body's
352
382
  * `valid_pack_ids` lists what exists; re-fetch `steamPacks()` — the
package/dist/index.d.cts CHANGED
@@ -1,7 +1,7 @@
1
- import { a as PurchaseStatusResult, b as PurchaseCredited, c as PurchaseExpired, d as PurchaseRefunded, e as PurchaseRefused, C as CheckoutClientConfig, H as Http, f as PurchaseStatusInput, g as CallOptions, W as WaitForPurchaseInput, M as MountCheckoutOptions, h as CheckoutMountHandle, i as ClientConfig, A as ApproveResult, j as ConfirmReceiptResult, k as PhoneChangeApprovalsResult, l as ApprovePhoneChangeInput, m as ApprovePhoneChangeResult, L as LinkDeviceResult, n as PendingCollectResult, o as DestinationsQuery, p as DestinationsResult, B as BalanceResult, q as LoyaltyCardsResult, r as LoyaltyVaultResult, R as RedeemRewardResult, s as RewardsPageLink, E as EnrollmentBeginResult, t as EnrollmentVerifyResult, u as RecoveryBeginResult, v as RecoveryCompleteResult } from './types-CaPHNjOU.cjs';
2
- export { w as BalanceRow, x as CheckoutPurchaseStatus, y as ClaimDelivery, D as DestinationGame, I as InvoError, z as InvoErrorInfo, F as InvoHooks, G as InvoRequestInfo, J as InvoResponseInfo, K as LoyaltyCard, N as LoyaltyCardReward, O as LoyaltyCardStep, Q as LoyaltyRewardState, S as LoyaltyStepProgress, T as LoyaltyStepState, U as LoyaltyVaultEntry, P as PendingCollectItem, V as PhoneChangeApproval, X as PhoneChangeDeviceSignal, Y as PurchaseRefusalReason, Z as Rail, _ as VerificationMethod } from './types-CaPHNjOU.cjs';
3
- import { a as ApproveHostedOptions, A as ApproveHostedResult } from './hosted-approval-li0XZFz-.cjs';
4
- export { E as EnrollmentDecision, b as EnrollmentRespond, H as HostedApprovalStatus, c as HostedEnrollment, d as HostedEnrollmentInput, e as HostedFlow } from './hosted-approval-li0XZFz-.cjs';
1
+ import { a as PurchaseStatusResult, b as PurchaseCredited, c as PurchaseExpired, d as PurchaseRefunded, e as PurchaseRefused, C as CheckoutClientConfig, H as Http, f as PurchaseStatusInput, g as CallOptions, W as WaitForPurchaseInput, M as MountCheckoutOptions, h as CheckoutMountHandle, i as ClientConfig, A as ApproveResult, j as ConfirmReceiptResult, k as PhoneChangeApprovalsResult, l as ApprovePhoneChangeInput, m as ApprovePhoneChangeResult, L as LinkDeviceResult, n as PendingCollectResult, o as DestinationsQuery, p as DestinationsResult, B as BalanceResult, q as LoyaltyCardsResult, r as LoyaltyVaultResult, R as RedeemRewardResult, s as RewardsPageLink, E as EnrollmentBeginResult, t as EnrollmentVerifyResult, u as RecoveryBeginResult, v as RecoveryCompleteResult } from './types-Ctn8N2_l.cjs';
2
+ export { w as BalanceRow, x as CheckoutPurchaseStatus, y as ClaimDelivery, D as DestinationGame, I as InvoError, z as InvoErrorInfo, F as InvoHooks, G as InvoRequestInfo, J as InvoResponseInfo, K as LoyaltyCard, N as LoyaltyCardReward, O as LoyaltyCardStep, Q as LoyaltyRewardState, S as LoyaltyStepProgress, T as LoyaltyStepState, U as LoyaltyVaultEntry, P as PendingCollectItem, V as PhoneChangeApproval, X as PhoneChangeDeviceSignal, Y as PurchaseRefusalReason, Z as Rail, _ as VerificationMethod } from './types-Ctn8N2_l.cjs';
3
+ import { a as ApproveHostedOptions, A as ApproveHostedResult } from './hosted-approval-C1hQvbu6.cjs';
4
+ export { E as EnrollmentDecision, b as EnrollmentRespond, H as HostedApprovalStatus, c as HostedEnrollment, d as HostedEnrollmentInput, e as HostedFlow } from './hosted-approval-C1hQvbu6.cjs';
5
5
  import { R as ReportGameEventInput, a as ReportGameEventResult } from './loyalty-events-CmDw2ZoR.cjs';
6
6
  export { G as GameEventType } from './loyalty-events-CmDw2ZoR.cjs';
7
7
 
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { a as PurchaseStatusResult, b as PurchaseCredited, c as PurchaseExpired, d as PurchaseRefunded, e as PurchaseRefused, C as CheckoutClientConfig, H as Http, f as PurchaseStatusInput, g as CallOptions, W as WaitForPurchaseInput, M as MountCheckoutOptions, h as CheckoutMountHandle, i as ClientConfig, A as ApproveResult, j as ConfirmReceiptResult, k as PhoneChangeApprovalsResult, l as ApprovePhoneChangeInput, m as ApprovePhoneChangeResult, L as LinkDeviceResult, n as PendingCollectResult, o as DestinationsQuery, p as DestinationsResult, B as BalanceResult, q as LoyaltyCardsResult, r as LoyaltyVaultResult, R as RedeemRewardResult, s as RewardsPageLink, E as EnrollmentBeginResult, t as EnrollmentVerifyResult, u as RecoveryBeginResult, v as RecoveryCompleteResult } from './types-CaPHNjOU.js';
2
- export { w as BalanceRow, x as CheckoutPurchaseStatus, y as ClaimDelivery, D as DestinationGame, I as InvoError, z as InvoErrorInfo, F as InvoHooks, G as InvoRequestInfo, J as InvoResponseInfo, K as LoyaltyCard, N as LoyaltyCardReward, O as LoyaltyCardStep, Q as LoyaltyRewardState, S as LoyaltyStepProgress, T as LoyaltyStepState, U as LoyaltyVaultEntry, P as PendingCollectItem, V as PhoneChangeApproval, X as PhoneChangeDeviceSignal, Y as PurchaseRefusalReason, Z as Rail, _ as VerificationMethod } from './types-CaPHNjOU.js';
3
- import { a as ApproveHostedOptions, A as ApproveHostedResult } from './hosted-approval-ICho9KsV.js';
4
- export { E as EnrollmentDecision, b as EnrollmentRespond, H as HostedApprovalStatus, c as HostedEnrollment, d as HostedEnrollmentInput, e as HostedFlow } from './hosted-approval-ICho9KsV.js';
1
+ import { a as PurchaseStatusResult, b as PurchaseCredited, c as PurchaseExpired, d as PurchaseRefunded, e as PurchaseRefused, C as CheckoutClientConfig, H as Http, f as PurchaseStatusInput, g as CallOptions, W as WaitForPurchaseInput, M as MountCheckoutOptions, h as CheckoutMountHandle, i as ClientConfig, A as ApproveResult, j as ConfirmReceiptResult, k as PhoneChangeApprovalsResult, l as ApprovePhoneChangeInput, m as ApprovePhoneChangeResult, L as LinkDeviceResult, n as PendingCollectResult, o as DestinationsQuery, p as DestinationsResult, B as BalanceResult, q as LoyaltyCardsResult, r as LoyaltyVaultResult, R as RedeemRewardResult, s as RewardsPageLink, E as EnrollmentBeginResult, t as EnrollmentVerifyResult, u as RecoveryBeginResult, v as RecoveryCompleteResult } from './types-Ctn8N2_l.js';
2
+ export { w as BalanceRow, x as CheckoutPurchaseStatus, y as ClaimDelivery, D as DestinationGame, I as InvoError, z as InvoErrorInfo, F as InvoHooks, G as InvoRequestInfo, J as InvoResponseInfo, K as LoyaltyCard, N as LoyaltyCardReward, O as LoyaltyCardStep, Q as LoyaltyRewardState, S as LoyaltyStepProgress, T as LoyaltyStepState, U as LoyaltyVaultEntry, P as PendingCollectItem, V as PhoneChangeApproval, X as PhoneChangeDeviceSignal, Y as PurchaseRefusalReason, Z as Rail, _ as VerificationMethod } from './types-Ctn8N2_l.js';
3
+ import { a as ApproveHostedOptions, A as ApproveHostedResult } from './hosted-approval-CFlj4UQE.js';
4
+ export { E as EnrollmentDecision, b as EnrollmentRespond, H as HostedApprovalStatus, c as HostedEnrollment, d as HostedEnrollmentInput, e as HostedFlow } from './hosted-approval-CFlj4UQE.js';
5
5
  import { R as ReportGameEventInput, a as ReportGameEventResult } from './loyalty-events-CmDw2ZoR.js';
6
6
  export { G as GameEventType } from './loyalty-events-CmDw2ZoR.js';
7
7
 
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export { CheckoutClient, InvoClient, PlatformCommerceClient } from './chunk-2XOKKKFR.js';
2
- export { InvoError, isPurchaseCredited, isPurchaseExpired, isPurchaseRefunded, isPurchaseRefused, nothingWasCharged, phoneChangeSignalMessage } from './chunk-QEJB6HC7.js';
1
+ export { CheckoutClient, InvoClient, PlatformCommerceClient } from './chunk-DMTNU5PM.js';
2
+ export { InvoError, isPurchaseCredited, isPurchaseExpired, isPurchaseRefunded, isPurchaseRefused, nothingWasCharged, phoneChangeSignalMessage } from './chunk-R65CANFG.js';
3
3
  //# sourceMappingURL=index.js.map
4
4
  //# sourceMappingURL=index.js.map