@invonetwork/web-sdk 3.26.1 → 3.27.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.
@@ -0,0 +1,3681 @@
1
+ import { assertSecureBaseUrl, Http, toRequestPhoneChangeResult, toPhoneChangeRequest, receiptFields, creditFields, toLoyaltyCardsResult, toDestinationsResult } from './chunk-6CN236QH.js';
2
+ import { SDK_VERSION } from './chunk-3YDO7GSH.js';
3
+ import { InvoError, buildGameEventBody, toReportGameEventResult } from './chunk-VP3OK4J4.js';
4
+ import { createHmac, timingSafeEqual } from 'crypto';
5
+
6
+ // src/payouts.ts
7
+ var AMOUNT = /^\d+(\.\d{1,2})?$/;
8
+ function invalidInput(label, value, why) {
9
+ return new InvoError({
10
+ message: `${label} ${why} (got ${JSON.stringify(value)}).`,
11
+ code: "INVALID_INPUT",
12
+ status: 0
13
+ });
14
+ }
15
+ function requireText(label, value) {
16
+ if (typeof value !== "string" || !value.trim()) throw invalidInput(label, value, "is required");
17
+ return value.trim();
18
+ }
19
+ function amountString(value) {
20
+ const s = typeof value === "number" ? Number.isFinite(value) ? String(value) : "" : String(value ?? "").trim();
21
+ if (!AMOUNT.test(s) || Number(s) <= 0) {
22
+ throw invalidInput("amountUsd", value, "must be a positive amount with at most two decimal places");
23
+ }
24
+ return s;
25
+ }
26
+ function query(params) {
27
+ const parts = [];
28
+ for (const [k, v] of Object.entries(params)) {
29
+ if (v === void 0 || v === "") continue;
30
+ parts.push(`${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`);
31
+ }
32
+ return parts.length ? `?${parts.join("&")}` : "";
33
+ }
34
+ function payeePath(payeeId) {
35
+ return `/api/partner-payees/${encodeURIComponent(requireText("payeeId", payeeId))}`;
36
+ }
37
+ function payoutId(id) {
38
+ if (!Number.isInteger(id) || id <= 0) throw invalidInput("payoutId", id, "must be a positive integer");
39
+ return id;
40
+ }
41
+ var PayoutsServer = class {
42
+ constructor(http, auth) {
43
+ this.http = http;
44
+ this.auth = auth;
45
+ }
46
+ /**
47
+ * Register a creator (`POST /api/partner-payees`). INVO emails the creator a link to INVO's
48
+ * own page to give INVO their identity, tax and bank details. `invite.sent` is `false` when
49
+ * INVO did not email the link (`invite.error_code` says why); the creator is registered
50
+ * either way. Refusals: `409 PARTNER_REFERENCE_CONFLICT`, `400 INVALID_INPUT`,
51
+ * `400 COUNTRY_NOT_SUPPORTED`.
52
+ */
53
+ async registerPayee(input, opts) {
54
+ if (input.payeeType !== "individual" && input.payeeType !== "business") {
55
+ throw invalidInput("payeeType", input.payeeType, 'must be "individual" or "business"');
56
+ }
57
+ const raw = await this.http.post(
58
+ "/api/partner-payees",
59
+ {
60
+ partner_reference: requireText("partnerReference", input.partnerReference),
61
+ legal_name: requireText("legalName", input.legalName),
62
+ email: requireText("email", input.email),
63
+ country: requireText("country", input.country),
64
+ payee_type: input.payeeType
65
+ },
66
+ this.auth,
67
+ { idempotent: true, signal: opts?.signal }
68
+ );
69
+ return {
70
+ payee: raw["payee"],
71
+ invite: raw["invite"],
72
+ duplicate: raw["duplicate"] === true,
73
+ raw
74
+ };
75
+ }
76
+ /** This game's creators, newest first (`GET /api/partner-payees`). */
77
+ async listPayees(q = {}, opts) {
78
+ const raw = await this.http.get(
79
+ `/api/partner-payees${query({ limit: q.limit, offset: q.offset, status: q.status })}`,
80
+ this.auth,
81
+ { signal: opts?.signal }
82
+ );
83
+ return {
84
+ total: Number(raw["total"] ?? 0),
85
+ limit: Number(raw["limit"] ?? 0),
86
+ offset: Number(raw["offset"] ?? 0),
87
+ items: raw["items"] ?? [],
88
+ raw
89
+ };
90
+ }
91
+ /** One creator (`GET /api/partner-payees/{payeeId}`); `404 NOT_FOUND` if not this game's. */
92
+ async getPayee(payeeId, opts) {
93
+ const raw = await this.http.get(payeePath(payeeId), this.auth, {
94
+ signal: opts?.signal
95
+ });
96
+ return raw["payee"];
97
+ }
98
+ /**
99
+ * Email the creator a new link (`POST /api/partner-payees/{payeeId}/resend-invite`); the old
100
+ * link stops working. Allowed while the creator is `invited`, `rejected` or `expired`
101
+ * (`409 INVITE_NOT_NEEDED` otherwise); `409 PAYEE_ERASED`; `429 INVITE_RATE_LIMITED` with
102
+ * `retry_after_seconds`. If INVO asked the creator to update their details, the resend sends
103
+ * INVO's update notice again. Never auto-retried.
104
+ */
105
+ async resendPayeeInvite(payeeId, opts) {
106
+ const raw = await this.http.post(
107
+ `${payeePath(payeeId)}/resend-invite`,
108
+ void 0,
109
+ this.auth,
110
+ { signal: opts?.signal }
111
+ );
112
+ return raw["invite"];
113
+ }
114
+ /**
115
+ * Remove a creator from your program (`POST /api/partner-payees/{payeeId}/remove`, 3.26.0).
116
+ * The status becomes `closed`. `409 PAYEE_HAS_PAYOUTS_IN_FLIGHT` while a payout to them is in
117
+ * progress, `409 ALREADY_CLOSED`, `409 PAYEE_NOT_CLOSABLE`. Not a block: the same person can
118
+ * be registered again under a new reference. Never auto-retried.
119
+ */
120
+ async removePayee(payeeId, opts) {
121
+ const raw = await this.http.post(
122
+ `${payeePath(payeeId)}/remove`,
123
+ void 0,
124
+ this.auth,
125
+ { signal: opts?.signal }
126
+ );
127
+ return raw["payee"];
128
+ }
129
+ /**
130
+ * Ask INVO to pay out (`POST /api/partner-payouts/request`). Send exactly one of `payeeId`
131
+ * (INVO pays that verified creator's bank account) or `bankAccountId` (your own verified bank
132
+ * account). The money comes from the earnings INVO owes your game, and the payout fee is
133
+ * taken from the payout. Creator refusals: `404 PAYEE_NOT_FOUND`, `409 PAYEE_NOT_VERIFIED`,
134
+ * `409 PAYEE_VERIFICATION_EXPIRED`, `409 PAYEE_BANK_NOT_VERIFIED`, `409 PAYEE_CLOSED`,
135
+ * `409 PAYEE_TERMS_NOT_ACCEPTED` (the creator hasn't accepted INVO's current Payee Terms yet),
136
+ * `409 PAYEE_NOT_PAYABLE` (can't be paid right now; no action needed; try again later),
137
+ * `409 IDEMPOTENCY_KEY_REUSED`. The first payout to a creator registered with the game key
138
+ * carries `owner_confirmation_required: true`. Retried safely only when `clientRequestId` is
139
+ * set.
140
+ */
141
+ async requestPayout(input, opts) {
142
+ if (input.payeeId !== void 0 && input.bankAccountId !== void 0) {
143
+ throw invalidInput("bankAccountId", input.bankAccountId, "must not be sent with payeeId");
144
+ }
145
+ const body = {
146
+ amount_usd: amountString(input.amountUsd),
147
+ contact_email: requireText("contactEmail", input.contactEmail)
148
+ };
149
+ if (input.payeeId !== void 0) body["payee_id"] = requireText("payeeId", input.payeeId);
150
+ if (input.bankAccountId !== void 0) body["bank_account_id"] = input.bankAccountId;
151
+ if (input.clientRequestId !== void 0) body["client_request_id"] = requireText("clientRequestId", input.clientRequestId);
152
+ if (input.partnerNote !== void 0) body["partner_note"] = input.partnerNote;
153
+ if (input.additionalEmails !== void 0) body["additional_emails"] = input.additionalEmails;
154
+ const raw = await this.http.post("/api/partner-payouts/request", body, this.auth, {
155
+ idempotent: input.clientRequestId !== void 0,
156
+ signal: opts?.signal
157
+ });
158
+ return {
159
+ payout: raw["payout_request"],
160
+ duplicate: raw["duplicate"] === true,
161
+ raw
162
+ };
163
+ }
164
+ /** One payout (`GET /api/partner-payouts/{payoutId}`). */
165
+ async getPayout(payoutIdValue, opts) {
166
+ const raw = await this.http.get(
167
+ `/api/partner-payouts/${payoutId(payoutIdValue)}`,
168
+ this.auth,
169
+ { signal: opts?.signal }
170
+ );
171
+ return raw["payout_request"];
172
+ }
173
+ /** Your payouts (`GET /api/partner-payouts`), optionally one creator's (`payeeId`). */
174
+ async listPayouts(q = {}, opts) {
175
+ const raw = await this.http.get(
176
+ `/api/partner-payouts${query({ limit: q.limit, offset: q.offset, status: q.status, payee_id: q.payeeId })}`,
177
+ this.auth,
178
+ { signal: opts?.signal }
179
+ );
180
+ return { total: Number(raw["total"] ?? 0), items: raw["items"] ?? [], raw };
181
+ }
182
+ /**
183
+ * Cancel a creator payout that is still `requested`
184
+ * (`POST /api/partner-payouts/{payoutId}/cancel`). Anything past `requested` is
185
+ * `409 PAYOUT_NOT_CANCELLABLE`; a payout to your own bank is `404 NOT_FOUND`.
186
+ */
187
+ async cancelPayout(payoutIdValue, opts) {
188
+ const raw = await this.http.post(
189
+ `/api/partner-payouts/${payoutId(payoutIdValue)}/cancel`,
190
+ void 0,
191
+ this.auth,
192
+ { signal: opts?.signal }
193
+ );
194
+ return raw["payout_request"] ?? raw["payout"];
195
+ }
196
+ };
197
+
198
+ // src/shared/types.ts
199
+ function isRefundPendingApproval(r) {
200
+ return r.status === "pending_approval";
201
+ }
202
+ var DEFAULT_TOLERANCE_SEC = 300;
203
+ var ENCODER = new TextEncoder();
204
+ function toBytes(body) {
205
+ return typeof body === "string" ? ENCODER.encode(body) : body;
206
+ }
207
+ function concatBytes(a, b) {
208
+ const out = new Uint8Array(a.length + b.length);
209
+ out.set(a, 0);
210
+ out.set(b, a.length);
211
+ return out;
212
+ }
213
+ function webhookError(message, code) {
214
+ return new InvoError({ message, code, status: 0 });
215
+ }
216
+ function parseSignatureHeader(header) {
217
+ let t = "";
218
+ const sigs = [];
219
+ for (const part of header.split(",")) {
220
+ const idx = part.indexOf("=");
221
+ if (idx === -1) continue;
222
+ const key = part.slice(0, idx).trim();
223
+ const val = part.slice(idx + 1).trim();
224
+ if (key === "t") t = val;
225
+ else if (key === "v1" && val) sigs.push(val);
226
+ }
227
+ return { t, sigs };
228
+ }
229
+ function hmacHex(secret, message) {
230
+ return createHmac("sha256", secret).update(message).digest("hex");
231
+ }
232
+ function safeEqualHexNode(a, b) {
233
+ const ba = Buffer.from(a, "utf8");
234
+ const bb = Buffer.from(b, "utf8");
235
+ if (ba.length !== bb.length) return false;
236
+ return timingSafeEqual(ba, bb);
237
+ }
238
+ function safeEqualHex(a, b) {
239
+ if (a.length !== b.length) return false;
240
+ let diff = 0;
241
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
242
+ return diff === 0;
243
+ }
244
+ function prepareVerification(rawBody, signatureHeader, secret, opts) {
245
+ if (!signatureHeader) {
246
+ throw webhookError("Missing X-Invo-Signature header.", "WEBHOOK_SIGNATURE_MISSING");
247
+ }
248
+ const secrets = (Array.isArray(secret) ? secret : [secret]).filter(Boolean);
249
+ if (secrets.length === 0) {
250
+ throw webhookError("A signing secret is required to verify webhooks.", "WEBHOOK_SECRET_MISSING");
251
+ }
252
+ const { t, sigs } = parseSignatureHeader(signatureHeader);
253
+ if (!t || sigs.length === 0) {
254
+ throw webhookError("Malformed X-Invo-Signature header.", "WEBHOOK_MALFORMED");
255
+ }
256
+ const ts = Number(t);
257
+ const now = opts.nowSec ?? Math.floor(Date.now() / 1e3);
258
+ const tolerance = opts.toleranceSec ?? DEFAULT_TOLERANCE_SEC;
259
+ if (!Number.isFinite(ts) || Math.abs(now - ts) > tolerance) {
260
+ throw webhookError(
261
+ `Webhook timestamp outside the ${tolerance}s tolerance (replay guard).`,
262
+ "WEBHOOK_TIMESTAMP_EXPIRED"
263
+ );
264
+ }
265
+ const bodyBytes = toBytes(rawBody);
266
+ const message = concatBytes(ENCODER.encode(`${t}.`), bodyBytes);
267
+ return { secrets, sigs, message, bodyBytes };
268
+ }
269
+ function finalizeEvent(bodyBytes) {
270
+ let parsed;
271
+ try {
272
+ parsed = JSON.parse(new TextDecoder().decode(bodyBytes));
273
+ } catch {
274
+ throw webhookError("Webhook body is not valid JSON.", "WEBHOOK_MALFORMED");
275
+ }
276
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed) || typeof parsed.event_type !== "string") {
277
+ throw webhookError("Webhook body is not a valid event object.", "WEBHOOK_MALFORMED");
278
+ }
279
+ return parsed;
280
+ }
281
+ function verifyWebhook(rawBody, signatureHeader, secret, opts = {}) {
282
+ const { secrets, sigs, message, bodyBytes } = prepareVerification(
283
+ rawBody,
284
+ signatureHeader,
285
+ secret,
286
+ opts
287
+ );
288
+ const matched = secrets.some((s) => {
289
+ const expected = hmacHex(s, message);
290
+ return sigs.some((sig) => safeEqualHexNode(sig, expected));
291
+ });
292
+ if (!matched) {
293
+ throw webhookError("Webhook signature verification failed.", "WEBHOOK_SIGNATURE_INVALID");
294
+ }
295
+ return finalizeEvent(bodyBytes);
296
+ }
297
+ async function verifyWebhookAsync(rawBody, signatureHeader, secret, opts = {}) {
298
+ const { secrets, sigs, message, bodyBytes } = prepareVerification(
299
+ rawBody,
300
+ signatureHeader,
301
+ secret,
302
+ opts
303
+ );
304
+ for (const s of secrets) {
305
+ const expected = await hmacHexSubtle(s, message);
306
+ if (sigs.some((sig) => safeEqualHex(sig, expected))) {
307
+ return finalizeEvent(bodyBytes);
308
+ }
309
+ }
310
+ throw webhookError("Webhook signature verification failed.", "WEBHOOK_SIGNATURE_INVALID");
311
+ }
312
+ function createWebhookHandler(opts) {
313
+ return async (request) => {
314
+ const raw = await request.text();
315
+ let event;
316
+ try {
317
+ event = await verifyWebhookAsync(raw, request.headers.get("x-invo-signature"), opts.secret, {
318
+ toleranceSec: opts.toleranceSec
319
+ });
320
+ } catch (e) {
321
+ const err = e instanceof InvoError ? e : new InvoError({ message: String(e), status: 0 });
322
+ if (opts.onError) {
323
+ try {
324
+ const r = await opts.onError(err, request);
325
+ if (r instanceof Response) return r;
326
+ } catch {
327
+ }
328
+ }
329
+ return new Response(err.code ?? "invalid_signature", { status: 400 });
330
+ }
331
+ try {
332
+ await opts.onEvent(event, {
333
+ // Prefer the signature-covered body field over the (unauthenticated, optional)
334
+ // header — the body value is HMAC-verified and always present.
335
+ idempotencyKey: event.idempotency_key ?? request.headers.get("x-invo-idempotency-key"),
336
+ request
337
+ });
338
+ } catch {
339
+ return new Response("handler_error", { status: 500 });
340
+ }
341
+ return new Response(null, { status: 200 });
342
+ };
343
+ }
344
+ async function hmacHexSubtle(secret, message) {
345
+ const subtle = globalThis.crypto?.subtle;
346
+ if (!subtle) {
347
+ throw webhookError(
348
+ "Web Crypto (crypto.subtle) is unavailable in this runtime.",
349
+ "WEBHOOK_UNSUPPORTED"
350
+ );
351
+ }
352
+ const key = await subtle.importKey(
353
+ "raw",
354
+ ENCODER.encode(secret),
355
+ { name: "HMAC", hash: "SHA-256" },
356
+ false,
357
+ ["sign"]
358
+ );
359
+ const sig = await subtle.sign("HMAC", key, message);
360
+ const bytes = new Uint8Array(sig);
361
+ let hex = "";
362
+ for (let i = 0; i < bytes.length; i++) hex += bytes[i].toString(16).padStart(2, "0");
363
+ return hex;
364
+ }
365
+
366
+ // src/server.ts
367
+ var DEFAULT_UA = `invonetwork-web-sdk/${SDK_VERSION} (+https://invo.network)`;
368
+ var MAX_USD_AMOUNT = 999999.99;
369
+ var MAX_ITEM_PRICE = 999999.99;
370
+ var MAX_ACKNOWLEDGED_TOTAL_USD = 9999999999e-2;
371
+ function assertAcknowledgedTotal(value) {
372
+ parseMoney(value, MAX_ACKNOWLEDGED_TOTAL_USD, "acknowledgedTotalUsd");
373
+ }
374
+ function optionalDecimalString(v) {
375
+ return v == null ? void 0 : String(v);
376
+ }
377
+ function nullableDecimalString(raw, fallback, key) {
378
+ for (const src of [raw, fallback]) {
379
+ if (Object.prototype.hasOwnProperty.call(src, key)) {
380
+ const v = src[key];
381
+ if (v === null) return null;
382
+ if (v !== void 0) return String(v);
383
+ }
384
+ }
385
+ return void 0;
386
+ }
387
+ function toMinPurchaseWarning(v) {
388
+ if (!v || typeof v !== "object" || Array.isArray(v)) return void 0;
389
+ const r = v;
390
+ return {
391
+ code: String(r["code"] ?? ""),
392
+ minUsd: r["min_usd"] == null ? "" : String(r["min_usd"]),
393
+ enforcedFrom: r["enforced_from"] == null ? "" : String(r["enforced_from"]),
394
+ ...typeof r["message"] === "string" && r["message"] ? { message: r["message"] } : {},
395
+ ...typeof r["enforced"] === "boolean" ? { enforced: r["enforced"] } : {},
396
+ raw: r
397
+ };
398
+ }
399
+ function minPurchaseWarningField(raw) {
400
+ const w = toMinPurchaseWarning(raw["min_purchase_warning"]);
401
+ return w === void 0 ? {} : { minPurchaseWarning: w };
402
+ }
403
+ function toQuoteBreakdown(row) {
404
+ const r = row && typeof row === "object" ? row : {};
405
+ const nullable = (v) => v == null ? null : String(v);
406
+ return {
407
+ subtotalUsd: String(r["subtotal_usd"] ?? ""),
408
+ taxUsd: String(r["tax_usd"] ?? "0.00"),
409
+ taxTreatment: nullable(r["tax_treatment"]),
410
+ taxNote: String(r["tax_note"] ?? ""),
411
+ taxRatePct: nullable(r["tax_rate_pct"]),
412
+ taxJurisdiction: nullable(r["tax_jurisdiction"]),
413
+ processingFeeUsd: String(r["processing_fee_usd"] ?? ""),
414
+ processingFeeNote: String(r["processing_fee_note"] ?? ""),
415
+ totalUsd: String(r["total_usd"] ?? ""),
416
+ coins: String(r["coins"] ?? ""),
417
+ currencyName: String(r["currency_name"] ?? ""),
418
+ raw: r
419
+ };
420
+ }
421
+ function toUnacknowledgedOutcome(row, quote = {}) {
422
+ if (!row || typeof row !== "object") return null;
423
+ const r = row;
424
+ return {
425
+ chargeTotalUsd: String(r["charge_total_usd"] ?? ""),
426
+ processingFeeUsd: String(r["processing_fee_usd"] ?? ""),
427
+ coins: String(r["coins"] ?? ""),
428
+ feeTakenFrom: String(r["fee_taken_from"] ?? unacknowledgedFeeFallback(r, quote)),
429
+ ...Object.prototype.hasOwnProperty.call(r, "partner_fee_usd") ? { partnerFeeUsd: r["partner_fee_usd"] == null ? null : String(r["partner_fee_usd"]) } : {}
430
+ };
431
+ }
432
+ function unacknowledgedFeeFallback(row, quote) {
433
+ const breakdown = quote["breakdown"];
434
+ const hasPartnerFee = row["partner_fee_usd"] != null || quote["partner_fee_usd"] != null || !!breakdown && typeof breakdown === "object" && breakdown["partner_fee_usd"] != null;
435
+ return hasPartnerFee ? "partner" : "coins";
436
+ }
437
+ function toCurrencyPurchaseQuote(raw) {
438
+ const breakdown = toQuoteBreakdown(raw["breakdown"]);
439
+ return {
440
+ totalUsd: requireField(raw["total_usd"], "total_usd", raw),
441
+ amountCents: Number(raw["amount_cents"] ?? 0),
442
+ // Top-level since 2026-09-23; the breakdown has always carried the same figures.
443
+ subtotalUsd: String(raw["subtotal_usd"] ?? breakdown.subtotalUsd),
444
+ processingFeeUsd: String(raw["processing_fee_usd"] ?? breakdown.processingFeeUsd),
445
+ coins: String(raw["coins"] ?? breakdown.coins),
446
+ currencyName: String(raw["currency_name"] ?? breakdown.currencyName),
447
+ breakdown,
448
+ ...raw["fee_taken_from"] != null ? { feeTakenFrom: String(raw["fee_taken_from"]) } : {},
449
+ ifUnacknowledged: toUnacknowledgedOutcome(raw["if_unacknowledged"], raw),
450
+ ...pricingFields(raw, breakdown.raw),
451
+ raw
452
+ };
453
+ }
454
+ function pricingFields(raw, fallback = {}) {
455
+ const out = {};
456
+ const partnerFee = nullableDecimalString(raw, fallback, "partner_fee_usd");
457
+ if (partnerFee !== void 0) out.partnerFeeUsd = partnerFee;
458
+ const intlFee = nullableDecimalString(raw, fallback, "international_card_fee_usd");
459
+ if (intlFee !== void 0) out.internationalCardFeeUsd = intlFee;
460
+ const warning = toMinPurchaseWarning(raw["min_purchase_warning"] ?? fallback["min_purchase_warning"]);
461
+ if (warning !== void 0) out.minPurchaseWarning = warning;
462
+ return out;
463
+ }
464
+ function invalidInput2(label, value, why) {
465
+ return new InvoError({
466
+ message: `${label} ${why} (got ${JSON.stringify(value)}).`,
467
+ code: "INVALID_INPUT",
468
+ status: 0
469
+ });
470
+ }
471
+ var PLAIN_DECIMAL = /^\d+(\.\d{1,2})?$/;
472
+ function parseMoney(value, max, label) {
473
+ let n;
474
+ if (typeof value === "number") {
475
+ if (!Number.isFinite(value) || !PLAIN_DECIMAL.test(String(value))) {
476
+ throw invalidInput2(label, value, "must be a positive decimal with at most 2 places");
477
+ }
478
+ n = value;
479
+ } else {
480
+ if (!PLAIN_DECIMAL.test(value)) {
481
+ throw invalidInput2(label, value, "must be a plain decimal value with at most 2 places");
482
+ }
483
+ n = Number(value);
484
+ }
485
+ if (!Number.isFinite(n) || n <= 0 || n > max) {
486
+ throw invalidInput2(label, value, `must be > 0 and <= ${max}`);
487
+ }
488
+ return n;
489
+ }
490
+ function assertUsdAmount(usdAmount) {
491
+ parseMoney(usdAmount, MAX_USD_AMOUNT, "usdAmount");
492
+ }
493
+ var E164 = /^\+[1-9]\d{1,14}$/;
494
+ function assertE164(value, label) {
495
+ if (typeof value !== "string" || !E164.test(value)) {
496
+ throw invalidInput2(label, value, 'must be an E.164 phone number, e.g. "+15555550100"');
497
+ }
498
+ }
499
+ function sessionTokenFromCreateCheckout(raw, checkoutUrl) {
500
+ const field = raw["session_token"];
501
+ if (typeof field === "string" && field.trim()) return field;
502
+ return sessionTokenFromCheckoutUrl(checkoutUrl);
503
+ }
504
+ function sessionTokenFromCheckoutUrl(checkoutUrl) {
505
+ try {
506
+ const value = new URL(checkoutUrl).searchParams.get("session");
507
+ return value && value.trim() ? value : void 0;
508
+ } catch {
509
+ return void 0;
510
+ }
511
+ }
512
+ function toOrderDetails(raw) {
513
+ return {
514
+ order: raw["order"] ?? {},
515
+ financialSummary: raw["financial_summary"] ?? {},
516
+ statusTimeline: raw["status_timeline"] ?? null,
517
+ ...receiptFields(raw),
518
+ raw
519
+ };
520
+ }
521
+ function toLinkedEmail(row) {
522
+ return {
523
+ email: String(row["email"] ?? ""),
524
+ primary: row["primary"] === true,
525
+ verifiedAt: row["verified_at"] ?? null
526
+ };
527
+ }
528
+ function toInboundPendingItem(row) {
529
+ return {
530
+ transactionId: String(row["transaction_id"] ?? ""),
531
+ flow: String(row["flow"] ?? ""),
532
+ amount: String(row["amount"] ?? ""),
533
+ netAmount: String(row["net_amount"] ?? ""),
534
+ sourceGameId: row["source_game_id"] ?? "",
535
+ sourceGame: String(row["source_game"] ?? ""),
536
+ toPhone: String(row["to_phone"] ?? ""),
537
+ toIdentityId: row["to_identity_id"] ?? null,
538
+ createdAt: String(row["created_at"] ?? ""),
539
+ claimCodeExpiresAt: String(row["claim_code_expires_at"] ?? ""),
540
+ raw: row
541
+ };
542
+ }
543
+ function toSmsVerifyResult(raw) {
544
+ return {
545
+ status: String(raw["status"] ?? ""),
546
+ transactionId: String(raw["transaction_id"] ?? ""),
547
+ claimCode: raw["claim_code"],
548
+ newBalance: raw["new_balance"] ?? null,
549
+ orderId: raw["order_id"],
550
+ raw
551
+ };
552
+ }
553
+ function toClaimResult(raw) {
554
+ const status = String(raw["status"] ?? "");
555
+ return {
556
+ status,
557
+ transactionId: raw["transaction_id"],
558
+ newBalance: raw["new_balance"] ?? null,
559
+ currencyName: raw["currency_name"],
560
+ orderId: raw["order_id"],
561
+ needsAccountSelection: status === "needs_account_selection",
562
+ candidates: Array.isArray(raw["candidates"]) ? raw["candidates"] : void 0,
563
+ raw
564
+ };
565
+ }
566
+ function toTransactionStatus(raw) {
567
+ return {
568
+ transactionId: String(raw["transaction_id"] ?? ""),
569
+ transactionType: String(raw["transaction_type"] ?? ""),
570
+ transactionStatus: String(raw["transaction_status"] ?? ""),
571
+ verificationState: String(raw["verification_state"] ?? ""),
572
+ amount: raw["amount"] ?? null,
573
+ netAmount: raw["net_amount"] ?? null,
574
+ currencyId: raw["currency_id"] ?? "",
575
+ orderId: raw["order_id"],
576
+ toPhone: raw["to_phone"],
577
+ toIdentityId: raw["to_identity_id"] ?? null,
578
+ ...typeof raw["expiry_reason"] === "string" && raw["expiry_reason"] ? { expiryReason: raw["expiry_reason"] } : {},
579
+ raw
580
+ };
581
+ }
582
+ function assertPageLimit(limit) {
583
+ if (limit === void 0) return;
584
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1) {
585
+ throw invalidInput2("limit", limit, "must be a positive integer (INVO caps it at 100)");
586
+ }
587
+ }
588
+ function assertCursor(cursor) {
589
+ if (cursor === void 0) return;
590
+ if (typeof cursor !== "string" || !cursor.trim()) {
591
+ throw invalidInput2("cursor", cursor, "must be the previous page's nextCursor");
592
+ }
593
+ }
594
+ function strOrNull(v) {
595
+ return v == null ? null : String(v);
596
+ }
597
+ function toPlayerActivityEntry(raw) {
598
+ const ccy = raw["currency"] && typeof raw["currency"] === "object" ? raw["currency"] : {};
599
+ const cg = raw["counterparty_game"];
600
+ const cgo = cg && typeof cg === "object" ? cg : null;
601
+ return {
602
+ id: String(raw["id"] ?? ""),
603
+ type: String(raw["type"] ?? ""),
604
+ direction: String(raw["direction"] ?? ""),
605
+ amount: strOrNull(raw["amount"]),
606
+ amountUnit: String(raw["amount_unit"] ?? "currency"),
607
+ currency: {
608
+ currencyId: ccy["currency_id"] ?? null,
609
+ currencyName: strOrNull(ccy["currency_name"])
610
+ },
611
+ status: String(raw["status"] ?? ""),
612
+ statusDetail: strOrNull(raw["status_detail"]),
613
+ expiryReason: strOrNull(raw["expiry_reason"]) || null,
614
+ counterpartyGame: cgo ? { gameId: String(cgo["game_id"] ?? ""), gameName: strOrNull(cgo["game_name"]) } : null,
615
+ createdAt: strOrNull(raw["created_at"]),
616
+ completedAt: strOrNull(raw["completed_at"]),
617
+ orderId: strOrNull(raw["order_id"]),
618
+ // Additive fee fields (backend 2026-10-12): set only when INVO sent the key.
619
+ ..."fee_amount" in raw ? { feeAmount: strOrNull(raw["fee_amount"]) } : {},
620
+ ..."net_amount" in raw ? { netAmount: strOrNull(raw["net_amount"]) } : {},
621
+ ..."gross_amount" in raw ? { grossAmount: strOrNull(raw["gross_amount"]) } : {},
622
+ raw
623
+ };
624
+ }
625
+ function toPlatformOrderStatus(raw, fallbackOrderId) {
626
+ return {
627
+ orderId: raw["order_id"] ?? fallbackOrderId ?? "",
628
+ status: String(raw["status"] ?? ""),
629
+ gameCurrencyAmount: raw["game_currency_amount"] ?? null,
630
+ usdAmount: raw["usd_amount"] ?? null,
631
+ paymentMethod: raw["payment_method"],
632
+ createdAt: raw["created_at"],
633
+ ...receiptFields(raw),
634
+ raw
635
+ };
636
+ }
637
+ function nextCursorOf(raw) {
638
+ const c = raw["next_cursor"];
639
+ return typeof c === "string" && c ? c : null;
640
+ }
641
+ function toGuardianApprovalStatus(raw) {
642
+ const approval = raw["approval"] ?? {};
643
+ return {
644
+ state: String(approval["state"] ?? ""),
645
+ approvalId: approval["approval_id"],
646
+ transactionId: approval["transaction_id"],
647
+ expiresAt: approval["expires_at"],
648
+ decidedAt: approval["decided_at"],
649
+ decisionSource: approval["decision_source"],
650
+ actionDescription: approval["action_description"],
651
+ raw
652
+ };
653
+ }
654
+ function toPhoneShareInitiateResult(raw) {
655
+ return {
656
+ approvalId: raw["approval_id"],
657
+ codeSent: typeof raw["code_sent"] === "boolean" ? raw["code_sent"] : void 0,
658
+ expiresAt: raw["expires_at"],
659
+ alreadyApproved: typeof raw["already_approved"] === "boolean" ? raw["already_approved"] : void 0,
660
+ raw
661
+ };
662
+ }
663
+ function toPhoneShareApproveResult(raw) {
664
+ return {
665
+ approvalId: raw["approval_id"],
666
+ approved: typeof raw["approved"] === "boolean" ? raw["approved"] : void 0,
667
+ alreadyApproved: typeof raw["already_approved"] === "boolean" ? raw["already_approved"] : void 0,
668
+ expiresAt: raw["expires_at"],
669
+ raw
670
+ };
671
+ }
672
+ var DEVICE_APPROVAL_FLOWS = /* @__PURE__ */ new Set([
673
+ "transfer",
674
+ "send",
675
+ "send_receipt",
676
+ "transfer_receipt"
677
+ ]);
678
+ var DEVICE_APPROVAL_CHANNELS = /* @__PURE__ */ new Set([
679
+ "qr",
680
+ "app_browser",
681
+ "popup"
682
+ ]);
683
+ var DEVICE_POLL_OUTCOME_TOKENS = /* @__PURE__ */ new Set([
684
+ "authorization_pending",
685
+ "slow_down",
686
+ "expired_token",
687
+ "access_denied"
688
+ ]);
689
+ function deviceApprovalSettlePath(flow, transactionId) {
690
+ const id = encodeURIComponent(transactionId);
691
+ switch (flow) {
692
+ case "transfer":
693
+ return `/api/sdk/transfers/${id}/approve`;
694
+ case "send":
695
+ return `/api/sdk/send/${id}/approve`;
696
+ case "send_receipt":
697
+ return `/api/sdk/send/${id}/confirm-receipt`;
698
+ case "transfer_receipt":
699
+ return `/api/sdk/transfers/${id}/confirm-receipt`;
700
+ }
701
+ }
702
+ var DEVICE_SETTLED_STATUSES = {
703
+ // Sender's approve: anything from "approved, awaiting the claim" onwards.
704
+ transfer: /* @__PURE__ */ new Set([
705
+ "pending_claim",
706
+ "verified",
707
+ "pin_verified_awaiting_claim",
708
+ "completed",
709
+ "distributed"
710
+ ]),
711
+ send: /* @__PURE__ */ new Set([
712
+ "pending_claim",
713
+ "verified",
714
+ "pin_verified_awaiting_claim",
715
+ "completed",
716
+ "distributed"
717
+ ]),
718
+ // Recipient's collect: only a finished transaction is past it. `pending_claim` and
719
+ // `verified` are this step's own gate statuses, not states beyond it.
720
+ send_receipt: /* @__PURE__ */ new Set(["completed", "distributed"]),
721
+ transfer_receipt: /* @__PURE__ */ new Set(["completed", "distributed"])
722
+ };
723
+ function isPastThisStep(flow, currentStatus) {
724
+ return DEVICE_SETTLED_STATUSES[flow].has(currentStatus.trim().toLowerCase());
725
+ }
726
+ function assertPlayerToken(playerToken) {
727
+ if (typeof playerToken !== "string" || !playerToken.trim()) {
728
+ throw invalidInput2("playerToken", playerToken, "is required (the player's session token, not the game secret)");
729
+ }
730
+ }
731
+ function assertDeviceApprovalFlow(flow) {
732
+ if (typeof flow !== "string" || !DEVICE_APPROVAL_FLOWS.has(flow)) {
733
+ throw invalidInput2("flow", flow, 'must be "transfer" | "send" | "send_receipt" | "transfer_receipt"');
734
+ }
735
+ }
736
+ function toDeviceApprovalGrant(raw) {
737
+ return {
738
+ deviceCode: requireField(raw["device_code"], "device_code", raw),
739
+ userCode: String(raw["user_code"] ?? ""),
740
+ verificationUri: String(raw["verification_uri"] ?? ""),
741
+ verificationUriComplete: requireField(raw["verification_uri_complete"], "verification_uri_complete", raw),
742
+ expiresIn: Number(raw["expires_in"] ?? 0) || 0,
743
+ interval: Math.max(1, Number(raw["interval"] ?? 5) || 5),
744
+ channel: String(raw["channel"] ?? "qr"),
745
+ raw
746
+ };
747
+ }
748
+ function toDeviceApprovalEnrollment(raw) {
749
+ return {
750
+ state: String(raw["state"] ?? ""),
751
+ deviceLabel: String(raw["device_label"] ?? ""),
752
+ matchCode: String(raw["match_code"] ?? ""),
753
+ recovery: raw["recovery"] === true,
754
+ requestedAt: raw["requested_at"] ?? null,
755
+ raw
756
+ };
757
+ }
758
+ function toDevicePollOutcome(token, body) {
759
+ const interval = Number(body["interval"]);
760
+ const enrollment = body["enrollment"];
761
+ return {
762
+ status: token,
763
+ interval: Number.isFinite(interval) && interval > 0 ? interval : void 0,
764
+ enrollment: enrollment && typeof enrollment === "object" ? toDeviceApprovalEnrollment(enrollment) : void 0,
765
+ raw: body
766
+ };
767
+ }
768
+ function toDeviceApprovalSettleResult(raw, input) {
769
+ const holdReason = raw["error_code"] ?? raw["code"];
770
+ return {
771
+ status: String(raw["status"] ?? ""),
772
+ transactionId: String(raw["transaction_id"] ?? input.transactionId),
773
+ flow: input.flow,
774
+ alreadySettled: false,
775
+ next: raw["next"],
776
+ claimCode: raw["claim_code"],
777
+ claimCodeExpiresAt: raw["claim_code_expires_at"],
778
+ amountReceived: raw["amount_received"] == null ? void 0 : String(raw["amount_received"]),
779
+ holdReason: typeof holdReason === "string" ? holdReason : void 0,
780
+ risk: raw["risk"],
781
+ guardianApproval: raw["guardian_approval"] ?? void 0,
782
+ pollEndpoint: raw["poll_endpoint"],
783
+ raw
784
+ };
785
+ }
786
+ function sleepFor(ms, signal) {
787
+ return new Promise((resolve) => {
788
+ if (signal?.aborted) return resolve();
789
+ const timer = setTimeout(done, ms);
790
+ const onAbort = () => done();
791
+ function done() {
792
+ clearTimeout(timer);
793
+ signal?.removeEventListener("abort", onAbort);
794
+ resolve();
795
+ }
796
+ signal?.addEventListener("abort", onAbort, { once: true });
797
+ });
798
+ }
799
+ function toCurrencyBalance(row) {
800
+ return {
801
+ currencyId: row["currency_id"] ?? "",
802
+ currencyName: String(row["currency_name"] ?? ""),
803
+ currencySymbol: String(row["currency_symbol"] ?? ""),
804
+ availableBalance: String(row["available_balance"] ?? ""),
805
+ reservedBalance: String(row["reserved_balance"] ?? ""),
806
+ totalBalance: String(row["total_balance"] ?? ""),
807
+ lastTransaction: row["last_transaction"],
808
+ raw: row
809
+ };
810
+ }
811
+ function playerTokenFields(raw) {
812
+ const out = {};
813
+ if (typeof raw["player_token"] === "string" && raw["player_token"]) {
814
+ out.playerToken = raw["player_token"];
815
+ if (typeof raw["player_token_expires_at"] === "string") {
816
+ out.playerTokenExpiresAt = raw["player_token_expires_at"];
817
+ }
818
+ }
819
+ return out;
820
+ }
821
+ function requireField(value, field, raw) {
822
+ const s = value == null ? "" : String(value);
823
+ if (!s) {
824
+ throw new InvoError({
825
+ message: `INVO response was missing the required \`${field}\` field.`,
826
+ code: "INVALID_RESPONSE",
827
+ status: 0,
828
+ body: raw
829
+ });
830
+ }
831
+ return s;
832
+ }
833
+ var FUNDING_SOURCES = /* @__PURE__ */ new Set(["balance", "card"]);
834
+ var CARD_MIN_USD = 0.5;
835
+ var PlatformCommerceServer = class {
836
+ constructor(http, auth) {
837
+ this.http = http;
838
+ this.auth = auth;
839
+ }
840
+ /**
841
+ * Create a purchase. The funding source is resolved server-side under lock — the client
842
+ * can request `"balance"` or `"card"`, but the backend verifies the real balance before
843
+ * value moves.
844
+ *
845
+ * - `fundingSource: "balance"` → settles synchronously; result `status:"success"` with
846
+ * `newBalance`/`financialBreakdown`. `totalPrice` is the tenant's network-currency amount.
847
+ * - `fundingSource: "card"` → result `status:"requires_payment"` + `checkoutUrl`/`sessionId`.
848
+ * Send the buyer to `checkoutUrl` — INVO's hosted page owns the card form, wallets,
849
+ * billing address, and 3-D Secure (there is NO billing address in this request, and no
850
+ * client payment code to write; optionally embed via
851
+ * `InvoClient.platformCommerce.mountCheckout`). `totalPrice` is USD, at least $0.50;
852
+ * the maximum is an INVO setting ($100,000.00 by default) and is enforced on the
853
+ * request, not here, so read the live figure off `ABOVE_CARD_MAXIMUM` rather than
854
+ * pinning one.
855
+ * The sale is real only on the `platform_commerce.purchased` webhook — never on the
856
+ * client return.
857
+ *
858
+ * Idempotency on `clientRequestId`: the balance leg throws a 409
859
+ * (`err.isDuplicateRequest`) on a duplicate; the card leg REPLAYS the same checkout
860
+ * session (`idempotentReplay: true`) — a lost response is safely recovered by retrying
861
+ * with the SAME `clientRequestId`. A non-platform tenant throws
862
+ * `err.isNotPlatformTenant` (403).
863
+ */
864
+ async purchase(input, opts) {
865
+ const required = [
866
+ ["clientRequestId", input.clientRequestId],
867
+ ["playerEmail", input.playerEmail],
868
+ ["playerName", input.playerName],
869
+ ["itemId", input.itemId],
870
+ ["itemName", input.itemName]
871
+ ];
872
+ for (const [k, v] of required) {
873
+ if (typeof v !== "string" || !v.trim()) throw invalidInput2(k, v, "is required");
874
+ }
875
+ if (!FUNDING_SOURCES.has(input.fundingSource)) {
876
+ throw invalidInput2("fundingSource", input.fundingSource, 'must be "balance" or "card"');
877
+ }
878
+ if (!Number.isInteger(input.itemQuantity) || input.itemQuantity < 1 || input.itemQuantity > 1e3) {
879
+ throw invalidInput2("itemQuantity", input.itemQuantity, "must be an integer 1..1000");
880
+ }
881
+ const unit = parseMoney(input.unitPrice, MAX_ITEM_PRICE, "unitPrice");
882
+ const total = parseMoney(input.totalPrice, MAX_ITEM_PRICE, "totalPrice");
883
+ const expectedCents = Math.round(unit * input.itemQuantity * 100);
884
+ const totalCents = Math.round(total * 100);
885
+ if (Math.abs(totalCents - expectedCents) > 1) {
886
+ throw invalidInput2(
887
+ "totalPrice",
888
+ input.totalPrice,
889
+ `must equal unitPrice \xD7 itemQuantity (\xB10.01): ${unit} \xD7 ${input.itemQuantity}`
890
+ );
891
+ }
892
+ if (input.fundingSource === "card") {
893
+ if (total < CARD_MIN_USD) {
894
+ throw new InvoError({
895
+ message: `Card purchases must be at least $${CARD_MIN_USD.toFixed(2)}.`,
896
+ code: "BELOW_STRIPE_MINIMUM",
897
+ publicCode: "BELOW_CARD_MINIMUM",
898
+ status: 0,
899
+ body: { min_usd: CARD_MIN_USD.toFixed(2) }
900
+ });
901
+ }
902
+ }
903
+ if (input.playerPhone !== void 0) assertE164(input.playerPhone, "playerPhone");
904
+ const body = {
905
+ client_request_id: input.clientRequestId,
906
+ funding_source: input.fundingSource,
907
+ player_email: input.playerEmail,
908
+ player_name: input.playerName,
909
+ item_id: input.itemId,
910
+ item_name: input.itemName,
911
+ item_quantity: input.itemQuantity,
912
+ unit_price: input.unitPrice,
913
+ total_price: input.totalPrice
914
+ };
915
+ if (input.playerPhone) body["player_phone"] = input.playerPhone;
916
+ if (input.itemDescription) body["item_description"] = input.itemDescription;
917
+ if (input.itemCategory) body["item_category"] = input.itemCategory;
918
+ if (input.successUrl) body["success_url"] = input.successUrl;
919
+ if (input.cancelUrl) body["cancel_url"] = input.cancelUrl;
920
+ if (input.metadata) body["metadata"] = input.metadata;
921
+ const raw = await this.http.post(
922
+ "/api/platform-commerce/purchase",
923
+ body,
924
+ this.auth,
925
+ // Safe to retry: balance dedupes (dup → 409); card REPLAYS the same session.
926
+ { idempotent: true, signal: opts?.signal }
927
+ );
928
+ const status = String(raw["status"] ?? "");
929
+ if (status === "requires_payment") {
930
+ requireField(raw["checkout_url"], "checkout_url", raw);
931
+ } else {
932
+ requireField(raw["order_id"], "order_id", raw);
933
+ }
934
+ const expiresAtRaw = raw["expires_at"];
935
+ return {
936
+ status,
937
+ fundingSource: String(raw["funding_source"] ?? input.fundingSource),
938
+ orderId: raw["order_id"] ?? void 0,
939
+ transactionId: raw["transaction_id"],
940
+ newBalance: raw["new_balance"] ?? null,
941
+ previousBalance: raw["previous_balance"] ?? null,
942
+ currencyName: raw["currency_name"],
943
+ financialBreakdown: raw["financial_breakdown"],
944
+ sessionId: raw["session_id"],
945
+ checkoutUrl: raw["checkout_url"],
946
+ expiresAt: typeof expiresAtRaw === "number" ? expiresAtRaw : void 0,
947
+ amountUsd: raw["amount_usd"] ?? null,
948
+ idempotentReplay: raw["idempotent_replay"] === true,
949
+ ...minPurchaseWarningField(raw),
950
+ raw
951
+ };
952
+ }
953
+ /** Poll an order's status: `completed` (balance immediately; card after the webhook),
954
+ * `pending_payment` (card awaiting confirmation), or `refunded`. */
955
+ async getStatus(orderId, opts) {
956
+ if (orderId == null || String(orderId).trim() === "") {
957
+ throw invalidInput2("orderId", orderId, "is required");
958
+ }
959
+ const raw = await this.http.get(
960
+ `/api/platform-commerce/purchase-status/${encodeURIComponent(String(orderId))}`,
961
+ this.auth,
962
+ { signal: opts?.signal }
963
+ );
964
+ return toPlatformOrderStatus(raw, orderId);
965
+ }
966
+ /**
967
+ * One player's Platform Commerce purchases in your app, newest first, one page at a time
968
+ * (`GET /api/platform-commerce/purchase-history`). Each entry carries exactly the fields
969
+ * `getStatus` returns for that order (including `receiptNumber` / `receiptUrl` on a
970
+ * Merchant of Record card sale once issued). Pass `nextCursor` back as `cursor` for the
971
+ * next page; it is `null` on the last one. `iteratePurchaseHistory` walks every page.
972
+ *
973
+ * Refusals (`InvoError`; this route reports its code in `error_code`, surfaced as
974
+ * `err.code`): a blank `playerEmail` or a bad `limit` / `cursor` throws `INVALID_INPUT`
975
+ * before the network; `400 INVALID_INPUT`, `400 INVALID_CURSOR` (a cursor from another
976
+ * player), `404 PLAYER_NOT_FOUND` (`err.isPlayerNotFound`), `403` for a non-platform
977
+ * tenant (`err.isNotPlatformTenant`), `429` (back off; `err.retryAfter`). A GET, so
978
+ * transient failures are retried automatically.
979
+ */
980
+ async getPurchaseHistory(query2, opts) {
981
+ if (typeof query2?.playerEmail !== "string" || !query2.playerEmail.trim()) {
982
+ throw invalidInput2("playerEmail", query2?.playerEmail, "is required");
983
+ }
984
+ assertPageLimit(query2.limit);
985
+ assertCursor(query2.cursor);
986
+ const q = new URLSearchParams();
987
+ q.set("player_email", query2.playerEmail.trim());
988
+ if (query2.limit !== void 0) q.set("limit", String(query2.limit));
989
+ if (query2.cursor !== void 0) q.set("cursor", query2.cursor);
990
+ const raw = await this.http.get(
991
+ `/api/platform-commerce/purchase-history?${q.toString()}`,
992
+ this.auth,
993
+ { signal: opts?.signal }
994
+ );
995
+ const purchases = Array.isArray(raw["purchases"]) ? raw["purchases"].map((r) => toPlatformOrderStatus(r)) : [];
996
+ const nextCursor = nextCursorOf(raw);
997
+ return {
998
+ playerEmail: String(raw["player_email"] ?? query2.playerEmail.trim()),
999
+ gameId: String(raw["game_id"] ?? ""),
1000
+ purchases,
1001
+ limit: typeof raw["limit"] === "number" ? raw["limit"] : purchases.length,
1002
+ hasMore: raw["has_more"] === true && nextCursor !== null,
1003
+ nextCursor,
1004
+ raw
1005
+ };
1006
+ }
1007
+ /**
1008
+ * Async iterator over ALL of a player's Platform Commerce purchases, newest first: pages
1009
+ * through `getPurchaseHistory` by `nextCursor`, yielding one order at a time.
1010
+ *
1011
+ * ```ts
1012
+ * for await (const order of invo.platformCommerce.iteratePurchaseHistory({ playerEmail })) { … }
1013
+ * ```
1014
+ */
1015
+ async *iteratePurchaseHistory(query2, opts) {
1016
+ let cursor;
1017
+ const seen = /* @__PURE__ */ new Set();
1018
+ for (; ; ) {
1019
+ const page = await this.getPurchaseHistory(
1020
+ { playerEmail: query2.playerEmail, limit: query2.pageSize, cursor },
1021
+ opts
1022
+ );
1023
+ for (const row of page.purchases) yield row;
1024
+ if (!page.hasMore || page.nextCursor === null || seen.has(page.nextCursor)) return;
1025
+ seen.add(page.nextCursor);
1026
+ cursor = page.nextCursor;
1027
+ }
1028
+ }
1029
+ /**
1030
+ * Refund a completed purchase. Provide EXACTLY ONE of `orderId` or `clientRequestId`.
1031
+ * INVO retains its fee — the customer is made whole (balance re-credit or card refund)
1032
+ * minus that fee. Idempotent on the order: a second refund throws a 409
1033
+ * (`err.isAlreadyRefunded`) — treat that as "already done", not a failure.
1034
+ */
1035
+ async refund(input, opts) {
1036
+ const hasOrder = input.orderId != null && String(input.orderId).trim() !== "";
1037
+ const hasReq = typeof input.clientRequestId === "string" && input.clientRequestId.trim() !== "";
1038
+ if (hasOrder === hasReq) {
1039
+ throw new InvoError({
1040
+ message: "refund requires EXACTLY ONE of orderId or clientRequestId.",
1041
+ code: "INVALID_INPUT",
1042
+ status: 0
1043
+ });
1044
+ }
1045
+ const body = {};
1046
+ if (hasOrder) body["order_id"] = input.orderId;
1047
+ else body["client_request_id"] = input.clientRequestId;
1048
+ if (input.reason) body["reason"] = input.reason;
1049
+ if (input.refundRemaining === true) body["refund_remaining"] = true;
1050
+ if (input.confirmAdditionalRefund === true) body["confirm_additional_refund"] = true;
1051
+ const raw = await this.http.post(
1052
+ "/api/platform-commerce/refund",
1053
+ body,
1054
+ this.auth,
1055
+ // Idempotent on the order: a lost-response retry re-refunds nothing (backend 409s
1056
+ // "already refunded"), so a transient 5xx/network retry is safe.
1057
+ { idempotent: true, signal: opts?.signal }
1058
+ );
1059
+ const fundingSource = raw["funding_source"];
1060
+ return {
1061
+ status: String(raw["status"] ?? ""),
1062
+ orderId: raw["order_id"] ?? void 0,
1063
+ fundingSource,
1064
+ transactionId: raw["transaction_id"],
1065
+ // Backend key differs per leg: `refunded_amount` (balance) / `refunded_amount_usd` (card).
1066
+ refundedAmount: raw["refunded_amount"] ?? raw["refunded_amount_usd"] ?? null,
1067
+ // The refund HTTP response carries no unit; derive it (card → USD). The balance leg's
1068
+ // unit is the tenant's network currency, not present here — left undefined.
1069
+ amountUnit: raw["amount_unit"] ?? (fundingSource === "card" ? "usd" : void 0),
1070
+ // Balance leg: the canonical post-refund balance. Card leg: the processor's refund id.
1071
+ newBalance: raw["new_balance"] ?? null,
1072
+ // Neutral field first — the backend emits `processor_refund_reference`
1073
+ // alongside the vendor-named one for exactly this reason.
1074
+ processorRefundId: raw["processor_refund_reference"] ?? raw["stripe_refund_id"],
1075
+ feeRetained: raw["fee_retained"] === true,
1076
+ // Refunds in parts only (absent on a one-shot full refund).
1077
+ ...typeof raw["partial_refund"] === "boolean" ? { partialRefund: raw["partial_refund"] } : {},
1078
+ ...raw["adopted"] === true ? { adopted: true } : {},
1079
+ ...raw["refunded_total_usd"] != null ? { refundedTotalUsd: String(raw["refunded_total_usd"]) } : {},
1080
+ ...raw["charge_total_usd"] != null ? { chargeTotalUsd: String(raw["charge_total_usd"]) } : {},
1081
+ ...raw["remaining_usd"] != null ? { remainingUsd: String(raw["remaining_usd"]) } : {},
1082
+ // 2026-09 pricing, card leg only: the card fee stays charged to the partner on a refund.
1083
+ ...raw["card_fee_charged_to_partner_usd"] != null ? { cardFeeChargedToPartnerUsd: String(raw["card_fee_charged_to_partner_usd"]) } : {},
1084
+ ...raw["partner_debited_usd"] != null ? { partnerDebitedUsd: String(raw["partner_debited_usd"]) } : {},
1085
+ raw
1086
+ };
1087
+ }
1088
+ };
1089
+ var SUBSCRIPTION_MAX_USD = 999999.99;
1090
+ var SUBSCRIPTION_INTERVALS = /* @__PURE__ */ new Set(["month", "year"]);
1091
+ var SANDBOX_FAILURE_OUTCOMES = /* @__PURE__ */ new Set([
1092
+ "card_declined",
1093
+ "insufficient_funds",
1094
+ "error"
1095
+ ]);
1096
+ function assertClientRequestId(value, label) {
1097
+ if (typeof value !== "string" || !value.trim()) throw invalidInput2(label, value, "is required");
1098
+ if (value.length > 255) throw invalidInput2(label, value, "must be at most 255 characters");
1099
+ if (/^sub_/i.test(value)) throw invalidInput2(label, value, 'must not begin with "sub_" (reserved)');
1100
+ }
1101
+ function assertSubscriptionId(value) {
1102
+ if (typeof value !== "string" || !value.trim()) {
1103
+ throw invalidInput2("subscriptionId", value, "is required");
1104
+ }
1105
+ }
1106
+ function subscriptionMoney(value, label) {
1107
+ const n = parseMoney(value, SUBSCRIPTION_MAX_USD, label);
1108
+ return typeof value === "number" ? n.toFixed(2) : value;
1109
+ }
1110
+ function toSavedCard(row) {
1111
+ if (!row || typeof row !== "object") return null;
1112
+ const r = row;
1113
+ return {
1114
+ id: Number(r["id"]),
1115
+ lastFour: String(r["last_four"] ?? ""),
1116
+ brand: String(r["brand"] ?? ""),
1117
+ expMonth: Number(r["exp_month"] ?? 0),
1118
+ expYear: Number(r["exp_year"] ?? 0),
1119
+ createdAt: String(r["created_at"] ?? ""),
1120
+ raw: r
1121
+ };
1122
+ }
1123
+ function nullableString(v) {
1124
+ return v == null ? null : String(v);
1125
+ }
1126
+ function optionalString(r, key) {
1127
+ return key in r ? nullableString(r[key]) : void 0;
1128
+ }
1129
+ function toCheckoutWarnings(v) {
1130
+ if (!Array.isArray(v)) return void 0;
1131
+ return v.filter((w) => !!w && typeof w === "object").map((w) => {
1132
+ const out = { code: String(w["code"] ?? ""), message: String(w["message"] ?? "") };
1133
+ if (Array.isArray(w["fields"])) out.fields = w["fields"].map(String);
1134
+ return out;
1135
+ });
1136
+ }
1137
+ function toRefundWarnings(v) {
1138
+ if (!Array.isArray(v)) return void 0;
1139
+ return v.filter((w) => !!w && typeof w === "object").map((w) => ({ code: String(w["code"] ?? ""), message: String(w["message"] ?? "") }));
1140
+ }
1141
+ function toRefundResult(raw, subscriptionId, clientRequestId) {
1142
+ const attr = raw["revenue_share_attribution"];
1143
+ const a = attr && typeof attr === "object" ? attr : null;
1144
+ const base = {
1145
+ status: String(raw["status"] ?? ""),
1146
+ idempotentReplay: raw["idempotent_replay"] === true,
1147
+ refundKey: nullableString(raw["refund_key"]),
1148
+ clientRequestId: nullableString(raw["client_request_id"]) ?? clientRequestId,
1149
+ subscriptionId: String(raw["subscription_id"] ?? subscriptionId),
1150
+ periodSeq: raw["period_seq"] == null ? null : Number(raw["period_seq"]),
1151
+ transactionId: nullableString(raw["transaction_id"]),
1152
+ refundedAmountUsd: nullableString(raw["refunded_amount_usd"]),
1153
+ totalRefundedAmountUsd: nullableString(raw["total_refunded_amount_usd"]),
1154
+ remainingRefundableUsd: nullableString(raw["remaining_refundable_usd"]),
1155
+ isFullRefund: raw["is_full_refund"] === true,
1156
+ fundingShape: nullableString(raw["funding_shape"]),
1157
+ balanceDeltaCoins: nullableString(raw["balance_delta_coins"]),
1158
+ cardRefundedUsd: nullableString(raw["card_refunded_usd"]),
1159
+ // Neutral field only; the vendor-named sibling is deliberately not read.
1160
+ processorRefundReference: nullableString(raw["processor_refund_reference"]),
1161
+ processorRefundAdopted: raw["processor_refund_adopted"] === true,
1162
+ invoFeeRetained: raw["invo_fee_retained"] === true,
1163
+ partnerRevenueReversedUsd: nullableString(raw["partner_revenue_reversed_usd"]),
1164
+ partnerRevenueReversalMode: nullableString(raw["partner_revenue_reversal_mode"]),
1165
+ reason: nullableString(raw["reason"]),
1166
+ refundedAt: nullableString(raw["refunded_at"]),
1167
+ newBalance: nullableString(raw["new_balance"]),
1168
+ revenueShareAttribution: a ? {
1169
+ recipientPlayerId: Number(a["recipient_player_id"] ?? 0),
1170
+ percent: String(a["percent"] ?? ""),
1171
+ originalAttributedAmountUsd: String(a["original_attributed_amount_usd"] ?? ""),
1172
+ refundedAttributedAmountUsd: String(a["refunded_attributed_amount_usd"] ?? ""),
1173
+ netAttributedAmountUsd: String(a["net_attributed_amount_usd"] ?? ""),
1174
+ settledByInvo: a["settled_by_invo"] === true,
1175
+ raw: a
1176
+ } : null,
1177
+ note: typeof raw["note"] === "string" ? raw["note"] : void 0,
1178
+ // ---- additive (2026-09-17): undefined when the body predates them ----
1179
+ warnings: toRefundWarnings(raw["warnings"]),
1180
+ subscriptionCanceled: "subscription_canceled" in raw ? raw["subscription_canceled"] === true : void 0,
1181
+ subscriptionStatus: optionalString(raw, "subscription_status"),
1182
+ processingFeeUsd: optionalString(raw, "processing_fee_usd"),
1183
+ processingFeeBasis: optionalString(raw, "processing_fee_basis"),
1184
+ processingFeeBorneBy: optionalString(raw, "processing_fee_borne_by"),
1185
+ processingFeeTransactionId: optionalString(raw, "processing_fee_transaction_id"),
1186
+ partnerTotalReversedUsd: optionalString(raw, "partner_total_reversed_usd"),
1187
+ // ---- additive (2026-09-28, D-PRICE-012): undefined on a receipt stored before it ----
1188
+ cardFeeChargedToPartnerUsd: optionalString(raw, "card_fee_charged_to_partner_usd"),
1189
+ partnerDebitedUsd: optionalString(raw, "partner_debited_usd"),
1190
+ initiation: optionalString(raw, "initiation"),
1191
+ refundRequestId: optionalString(raw, "refund_request_id"),
1192
+ raw
1193
+ };
1194
+ if (base.status === "pending_approval") {
1195
+ const pending = {
1196
+ ...base,
1197
+ status: "pending_approval",
1198
+ requestId: String(raw["request_id"] ?? raw["refund_request_id"] ?? ""),
1199
+ requestStatus: String(raw["request_status"] ?? ""),
1200
+ requestedAmountUsd: nullableString(raw["requested_amount_usd"]),
1201
+ requestedAt: nullableString(raw["requested_at"]),
1202
+ dailyCapUsd: nullableString(raw["daily_cap_usd"]),
1203
+ executedTodayUsd: nullableString(raw["executed_today_usd"]),
1204
+ message: nullableString(raw["message"])
1205
+ };
1206
+ return pending;
1207
+ }
1208
+ return base;
1209
+ }
1210
+ function toSubscription(row) {
1211
+ const r = row && typeof row === "object" ? row : {};
1212
+ const share = r["revenue_share"];
1213
+ const consent = r["consent"] ?? {};
1214
+ return {
1215
+ subscriptionId: String(r["subscription_id"] ?? ""),
1216
+ gameId: String(r["game_id"] ?? ""),
1217
+ playerId: Number(r["player_id"] ?? 0),
1218
+ clientRequestId: String(r["client_request_id"] ?? ""),
1219
+ status: String(r["status"] ?? ""),
1220
+ amountUsd: String(r["amount_usd"] ?? ""),
1221
+ pendingAmountUsd: nullableString(r["pending_amount_usd"]),
1222
+ interval: String(r["interval"] ?? "month"),
1223
+ intervalCount: Number(r["interval_count"] ?? 1),
1224
+ itemId: String(r["item_id"] ?? ""),
1225
+ itemName: nullableString(r["item_name"]),
1226
+ currentPeriodStart: String(r["current_period_start"] ?? ""),
1227
+ currentPeriodEnd: String(r["current_period_end"] ?? ""),
1228
+ periodSeq: Number(r["period_seq"] ?? 0),
1229
+ nextChargeAt: nullableString(r["next_charge_at"]),
1230
+ cancelAtPeriodEnd: r["cancel_at_period_end"] === true,
1231
+ trialEnd: nullableString(r["trial_end"]),
1232
+ trialAmountUsd: nullableString(r["trial_amount_usd"]),
1233
+ canceledAt: nullableString(r["canceled_at"]),
1234
+ endedAt: nullableString(r["ended_at"]),
1235
+ walletOnly: r["wallet_only"] === true,
1236
+ hasPaymentMethod: r["has_payment_method"] === true,
1237
+ fundingRail: String(r["funding_rail"] ?? "card"),
1238
+ steamAgreementStatus: nullableString(r["steam_agreement_status"]),
1239
+ metadata: r["metadata"] && typeof r["metadata"] === "object" ? r["metadata"] : null,
1240
+ consent: {
1241
+ consent_at: nullableString(consent["consent_at"]),
1242
+ consent_ip: nullableString(consent["consent_ip"]),
1243
+ consent_user_agent: nullableString(consent["consent_user_agent"]),
1244
+ disclosed_amount_usd: nullableString(consent["disclosed_amount_usd"]),
1245
+ disclosed_interval: nullableString(consent["disclosed_interval"]),
1246
+ terms_version: nullableString(consent["terms_version"]),
1247
+ disclosed_trial_amount_usd: nullableString(consent["disclosed_trial_amount_usd"]),
1248
+ disclosed_trial_days: typeof consent["disclosed_trial_days"] === "number" ? consent["disclosed_trial_days"] : null,
1249
+ disclosed_trial_end: nullableString(consent["disclosed_trial_end"])
1250
+ },
1251
+ createdAt: String(r["created_at"] ?? ""),
1252
+ updatedAt: String(r["updated_at"] ?? ""),
1253
+ revenueShare: share && typeof share === "object" ? {
1254
+ recipientPlayerId: Number(share["recipient_player_id"] ?? 0),
1255
+ percent: String(share["percent"] ?? ""),
1256
+ // Attribution only: INVO never pays the recipient. Read the wire value, never assume.
1257
+ settledByInvo: share["settled_by_invo"] === true
1258
+ } : null,
1259
+ paidThrough: nullableString(r["paid_through"]),
1260
+ amountCoinsEstimate: r["amount_coins_estimate"] == null ? void 0 : String(r["amount_coins_estimate"]),
1261
+ // Present (possibly null) only on create/finalize bodies from 2026-09-23 on.
1262
+ ..."trial_amount_coins_estimate" in r ? { trialAmountCoinsEstimate: nullableString(r["trial_amount_coins_estimate"]) } : {},
1263
+ // `include_player` puts these two ON the object (there is no separate block).
1264
+ ..."player_email" in r ? { playerEmail: nullableString(r["player_email"]) } : {},
1265
+ ..."player_name" in r ? { playerName: nullableString(r["player_name"]) } : {},
1266
+ raw: r
1267
+ };
1268
+ }
1269
+ function toFirstCharge(row) {
1270
+ const r = row && typeof row === "object" ? row : {};
1271
+ return {
1272
+ status: String(r["status"] ?? "pending"),
1273
+ amountUsd: nullableString(r["amount_usd"]),
1274
+ paidPeriodSeq: typeof r["paid_period_seq"] === "number" ? r["paid_period_seq"] : null,
1275
+ paidThrough: nullableString(r["paid_through"]),
1276
+ failureCode: nullableString(r["failure_code"]),
1277
+ nextRetryAt: nullableString(r["next_retry_at"]),
1278
+ confirmationUrl: nullableString(r["confirmation_url"]),
1279
+ expiresAt: nullableString(r["expires_at"]),
1280
+ message: nullableString(r["message"]),
1281
+ ...receiptFields(r),
1282
+ raw: r
1283
+ };
1284
+ }
1285
+ function toSubscriptionResult(raw) {
1286
+ return {
1287
+ status: String(raw["status"] ?? ""),
1288
+ idempotentReplay: raw["idempotent_replay"] === true,
1289
+ subscription: toSubscription(raw["subscription"]),
1290
+ card: toSavedCard(raw["card"]),
1291
+ firstCharge: toFirstCharge(raw["first_charge"]),
1292
+ warning: typeof raw["warning"] === "string" ? raw["warning"] : void 0,
1293
+ raw
1294
+ };
1295
+ }
1296
+ function toSandboxClockState(row) {
1297
+ if (!row || typeof row !== "object") return null;
1298
+ const r = row;
1299
+ return {
1300
+ status: String(r["status"] ?? ""),
1301
+ periodSeq: Number(r["period_seq"] ?? 0),
1302
+ currentPeriodStart: nullableString(r["current_period_start"]),
1303
+ currentPeriodEnd: nullableString(r["current_period_end"]),
1304
+ nextChargeAt: nullableString(r["next_charge_at"]),
1305
+ trialEnd: nullableString(r["trial_end"]),
1306
+ cancelAtPeriodEnd: r["cancel_at_period_end"] === true,
1307
+ walletOnly: r["wallet_only"] === true,
1308
+ hasPaymentMethod: r["has_payment_method"] === true,
1309
+ amountUsd: String(r["amount_usd"] ?? ""),
1310
+ raw: r
1311
+ };
1312
+ }
1313
+ function optNumber(v) {
1314
+ return typeof v === "number" && Number.isFinite(v) ? v : void 0;
1315
+ }
1316
+ function toSandboxClockResult(raw) {
1317
+ const before = toSandboxClockState(raw["before"]);
1318
+ const after = toSandboxClockState(raw["after"]);
1319
+ const stats = raw["engine_stats"];
1320
+ return {
1321
+ status: String(raw["status"] ?? ""),
1322
+ action: String(raw["action"] ?? ""),
1323
+ // advance-clock reports before/after rather than a `subscription` block; surface
1324
+ // `after` there so every tool answers "where is the clock now" in one place.
1325
+ subscription: toSandboxClockState(raw["subscription"]) ?? after,
1326
+ before: before ?? void 0,
1327
+ after: after ?? void 0,
1328
+ intervals: optNumber(raw["intervals"]),
1329
+ intervalsAppliedToWindow: optNumber(raw["intervals_applied_to_window"]),
1330
+ windowMoved: typeof raw["window_moved"] === "boolean" ? raw["window_moved"] : void 0,
1331
+ windowAlreadyElapsed: typeof raw["window_already_elapsed"] === "boolean" ? raw["window_already_elapsed"] : void 0,
1332
+ engineStats: stats && typeof stats === "object" ? stats : void 0,
1333
+ periodSeq: optNumber(raw["period_seq"]),
1334
+ attemptNo: optNumber(raw["attempt_no"]),
1335
+ amountUsd: raw["amount_usd"] == null ? void 0 : String(raw["amount_usd"]),
1336
+ amountCoins: raw["amount_coins"] == null ? void 0 : String(raw["amount_coins"]),
1337
+ retired: typeof raw["retired"] === "boolean" ? raw["retired"] : void 0,
1338
+ retryBudgetUsed: optNumber(raw["retry_budget_used"]),
1339
+ retryScheduleDays: Array.isArray(raw["retry_schedule_days"]) ? raw["retry_schedule_days"].map(Number) : void 0,
1340
+ retriesRemaining: optNumber(raw["retries_remaining"]),
1341
+ authChallengesUsed: optNumber(raw["auth_challenges_used"]),
1342
+ maxAuthChallenges: optNumber(raw["max_auth_challenges"]),
1343
+ downgradedToDecline: typeof raw["downgraded_to_decline"] === "boolean" ? raw["downgraded_to_decline"] : void 0,
1344
+ note: typeof raw["note"] === "string" ? raw["note"] : void 0,
1345
+ raw
1346
+ };
1347
+ }
1348
+ function subscriptionBaseBody(input) {
1349
+ assertClientRequestId(input.clientRequestId, "clientRequestId");
1350
+ for (const [k, v] of [
1351
+ ["playerEmail", input.playerEmail],
1352
+ ["playerName", input.playerName],
1353
+ ["itemId", input.itemId]
1354
+ ]) {
1355
+ if (typeof v !== "string" || !v.trim()) throw invalidInput2(k, v, "is required");
1356
+ }
1357
+ if (input.interval !== void 0 && !SUBSCRIPTION_INTERVALS.has(input.interval)) {
1358
+ throw invalidInput2("interval", input.interval, 'must be "month" or "year"');
1359
+ }
1360
+ if (input.playerPhone !== void 0) assertE164(input.playerPhone, "playerPhone");
1361
+ const body = {
1362
+ client_request_id: input.clientRequestId,
1363
+ player_email: input.playerEmail,
1364
+ player_name: input.playerName,
1365
+ item_id: input.itemId,
1366
+ amount_usd: subscriptionMoney(input.amountUsd, "amountUsd")
1367
+ };
1368
+ if (input.playerPhone) body["player_phone"] = input.playerPhone;
1369
+ if (input.itemName) body["item_name"] = input.itemName;
1370
+ if (input.interval) body["interval"] = input.interval;
1371
+ if (input.metadata) body["metadata"] = input.metadata;
1372
+ if (input.consent) {
1373
+ const c = input.consent;
1374
+ const consent = {};
1375
+ if (c.consentAt !== void 0) consent["consent_at"] = c.consentAt;
1376
+ if (c.consentIp !== void 0) consent["consent_ip"] = c.consentIp;
1377
+ if (c.consentUserAgent !== void 0) consent["consent_user_agent"] = c.consentUserAgent;
1378
+ if (c.disclosedAmountUsd !== void 0) consent["disclosed_amount_usd"] = c.disclosedAmountUsd;
1379
+ if (c.disclosedInterval !== void 0) consent["disclosed_interval"] = c.disclosedInterval;
1380
+ if (c.termsVersion !== void 0) consent["terms_version"] = c.termsVersion;
1381
+ if (c.disclosedTrialAmountUsd !== void 0) consent["disclosed_trial_amount_usd"] = c.disclosedTrialAmountUsd;
1382
+ if (c.disclosedTrialDays !== void 0) consent["disclosed_trial_days"] = c.disclosedTrialDays;
1383
+ if (c.disclosedTrialEnd !== void 0) consent["disclosed_trial_end"] = c.disclosedTrialEnd;
1384
+ body["consent"] = consent;
1385
+ }
1386
+ if (input.revenueShare) {
1387
+ const s = input.revenueShare;
1388
+ const hasEmail = typeof s.recipientPlayerEmail === "string" && s.recipientPlayerEmail.trim() !== "";
1389
+ const hasId = s.recipientPlayerId != null;
1390
+ if (hasEmail === hasId) {
1391
+ throw invalidInput2(
1392
+ "revenueShare",
1393
+ s,
1394
+ "requires EXACTLY ONE of recipientPlayerEmail or recipientPlayerId"
1395
+ );
1396
+ }
1397
+ const share = {
1398
+ percent: typeof s.percent === "number" ? s.percent.toFixed(2) : s.percent
1399
+ };
1400
+ if (hasEmail) share["recipient_player_email"] = s.recipientPlayerEmail;
1401
+ else share["recipient_player_id"] = s.recipientPlayerId;
1402
+ body["revenue_share"] = share;
1403
+ }
1404
+ return body;
1405
+ }
1406
+ var SubscriptionsServer = class {
1407
+ constructor(http, auth) {
1408
+ this.http = http;
1409
+ this.auth = auth;
1410
+ }
1411
+ /**
1412
+ * Create a CARD-rail subscription. **Charges the first period before responding**
1413
+ * (unless it is a trial), so expect the call to take as long as a card charge.
1414
+ *
1415
+ * Branch on `result.firstCharge.status`: `paid` (grant until `paidThrough`),
1416
+ * `requires_action` (NOTHING charged; send the member to `confirmationUrl`),
1417
+ * `skipped_trial` (grant trial access until `subscription.trialEnd`), `failed` (in
1418
+ * dunning; INVO retries at `nextRetryAt`), `pending` (wait for the event).
1419
+ *
1420
+ * Idempotent on `clientRequestId`: a repeat returns HTTP 200 with the identical shape
1421
+ * and `idempotentReplay: true`, and NOTHING is charged again. **On any timeout or 5xx,
1422
+ * replay the same key before you do anything else**; a fresh key inside a retry loop
1423
+ * lands on `409 ACTIVE_SUBSCRIPTION_EXISTS` (`err.isActiveSubscriptionExists`,
1424
+ * `err.existingSubscriptionId`) at best and a second subscription at worst. Same key
1425
+ * with different terms is `err.isIdempotentReplayMismatch` (`err.mismatchedFields`).
1426
+ *
1427
+ * Card only (since 2026-09-17): the card is charged the full price every period and the
1428
+ * member's coin wallet never pays and never moves. Card selection: `playerCardId` names one
1429
+ * (from `cards.list`); omitted, INVO attaches the member's newest unexpired saved card. With
1430
+ * no saved card the subscription is still created (201) but `firstCharge` is `failed` with
1431
+ * `failureCode: "no_payment_method"`, whatever the member's balance: save a card first.
1432
+ * `walletOnly: true` is deprecated: it never charges a card, so such a subscription can never
1433
+ * be paid (`failureCode: "wallet_only"`).
1434
+ *
1435
+ * PAID TRIAL: send `trialAmountUsd` with `trialDays` or `trialEnd` (for example $1.00 for 7
1436
+ * days, then `amountUsd` monthly). Period 1 is charged the trial price inside this call, so a
1437
+ * usable saved card is required (`400 PAYMENT_METHOD_REQUIRED`, `err.isPaymentMethodRequired`),
1438
+ * `firstCharge` reports the trial charge (never `skipped_trial`), and a refused trial charge
1439
+ * ends the subscription at once (`expired`, no retry). Other refusals:
1440
+ * `err.isTrialAmountRequiresTrial`, `err.isTrialAmountNotSupportedForFunding`,
1441
+ * `err.isTrialAmountInvalid` (below $0.50, or not less than `amountUsd`),
1442
+ * `err.isConsentDisclosedTrialInvalid`.
1443
+ * Requires the game to be `live` (`err.isGameNotLive`).
1444
+ */
1445
+ async create(input, opts) {
1446
+ const body = subscriptionBaseBody(input);
1447
+ if (input.intervalCount !== void 0) {
1448
+ if (!Number.isInteger(input.intervalCount) || input.intervalCount < 1 || input.intervalCount > 36) {
1449
+ throw invalidInput2("intervalCount", input.intervalCount, "must be an integer 1..36");
1450
+ }
1451
+ body["interval_count"] = input.intervalCount;
1452
+ }
1453
+ if (input.trialDays !== void 0) {
1454
+ if (!Number.isInteger(input.trialDays) || input.trialDays < 1 || input.trialDays > 365) {
1455
+ throw invalidInput2("trialDays", input.trialDays, "must be an integer 1..365");
1456
+ }
1457
+ body["trial_days"] = input.trialDays;
1458
+ }
1459
+ if (input.trialEnd !== void 0) {
1460
+ if (typeof input.trialEnd !== "string" || Number.isNaN(Date.parse(input.trialEnd))) {
1461
+ throw invalidInput2("trialEnd", input.trialEnd, "must be an ISO 8601 timestamp");
1462
+ }
1463
+ body["trial_end"] = input.trialEnd;
1464
+ }
1465
+ if (input.trialAmountUsd !== void 0) {
1466
+ if (input.trialDays === void 0 && input.trialEnd === void 0) {
1467
+ throw new InvoError({
1468
+ message: "trialAmountUsd requires a trial: send trialDays or trialEnd with it.",
1469
+ code: "TRIAL_AMOUNT_REQUIRES_TRIAL",
1470
+ status: 0
1471
+ });
1472
+ }
1473
+ if (input.walletOnly === true) {
1474
+ throw new InvoError({
1475
+ message: "trialAmountUsd is only available on card-funded subscriptions; it cannot be combined with walletOnly: true.",
1476
+ code: "TRIAL_AMOUNT_NOT_SUPPORTED_FOR_FUNDING",
1477
+ status: 0
1478
+ });
1479
+ }
1480
+ body["trial_amount_usd"] = subscriptionMoney(input.trialAmountUsd, "trialAmountUsd");
1481
+ }
1482
+ if (input.walletOnly !== void 0) {
1483
+ if (typeof input.walletOnly !== "boolean") {
1484
+ throw invalidInput2("walletOnly", input.walletOnly, "must be a boolean");
1485
+ }
1486
+ body["wallet_only"] = input.walletOnly;
1487
+ }
1488
+ if (input.playerCardId !== void 0) {
1489
+ if (!Number.isInteger(input.playerCardId) || input.playerCardId < 1) {
1490
+ throw invalidInput2("playerCardId", input.playerCardId, "must be a positive integer card id (from cards.list)");
1491
+ }
1492
+ if (input.walletOnly === true) {
1493
+ throw invalidInput2("playerCardId", input.playerCardId, "cannot be combined with walletOnly: true");
1494
+ }
1495
+ body["player_card_id"] = input.playerCardId;
1496
+ }
1497
+ const raw = await this.http.post(
1498
+ "/api/subscriptions/subscribe",
1499
+ body,
1500
+ this.auth,
1501
+ // Idempotent on client_request_id: a lost-response retry REPLAYS the row (200,
1502
+ // idempotent_replay: true) and never charges twice. Replay before retry.
1503
+ { idempotent: true, signal: opts?.signal }
1504
+ );
1505
+ return toSubscriptionResult(raw);
1506
+ }
1507
+ /** Read one subscription. `404 SUBSCRIPTION_NOT_FOUND` for an id that is not your game's. */
1508
+ async get(subscriptionId, options, opts) {
1509
+ assertSubscriptionId(subscriptionId);
1510
+ const qs = options?.includePlayer ? "?include_player=true" : "";
1511
+ const raw = await this.http.get(
1512
+ `/api/subscriptions/${encodeURIComponent(subscriptionId)}${qs}`,
1513
+ this.auth,
1514
+ { signal: opts?.signal }
1515
+ );
1516
+ const subscription = toSubscription(raw["subscription"]);
1517
+ const row = subscription.raw;
1518
+ const player = "player_email" in row || "player_name" in row ? { player_email: row["player_email"] ?? null, player_name: row["player_name"] ?? null } : void 0;
1519
+ return { subscription, player, raw };
1520
+ }
1521
+ /**
1522
+ * List a member's subscriptions, newest first, paged (`limit` 1..100, `offset`
1523
+ * 0..100000). `status` filters; `"live"` expands to the four live statuses and may be
1524
+ * mixed in (`["live", "canceled"]`). A player who does not exist yet is an empty list
1525
+ * with `totalCount: 0`, not a 404.
1526
+ */
1527
+ async listForPlayer(playerEmail, options, opts) {
1528
+ if (typeof playerEmail !== "string" || !playerEmail.trim()) {
1529
+ throw invalidInput2("playerEmail", playerEmail, "is required");
1530
+ }
1531
+ const q = new URLSearchParams();
1532
+ q.set("player_email", playerEmail);
1533
+ if (options?.status !== void 0) {
1534
+ const list = Array.isArray(options.status) ? options.status : [options.status];
1535
+ if (list.length) q.set("status", list.join(","));
1536
+ }
1537
+ if (options?.includePlayer) q.set("include_player", "true");
1538
+ if (options?.limit != null) {
1539
+ if (!Number.isInteger(options.limit) || options.limit < 1 || options.limit > 100) {
1540
+ throw invalidInput2("limit", options.limit, "must be an integer 1..100");
1541
+ }
1542
+ q.set("limit", String(options.limit));
1543
+ }
1544
+ if (options?.offset != null) {
1545
+ if (!Number.isInteger(options.offset) || options.offset < 0 || options.offset > 1e5) {
1546
+ throw invalidInput2("offset", options.offset, "must be an integer 0..100000");
1547
+ }
1548
+ q.set("offset", String(options.offset));
1549
+ }
1550
+ const raw = await this.http.get(
1551
+ `/api/subscriptions/player?${q.toString()}`,
1552
+ this.auth,
1553
+ { signal: opts?.signal }
1554
+ );
1555
+ const rows = Array.isArray(raw["subscriptions"]) ? raw["subscriptions"] : [];
1556
+ const p = raw["pagination"] ?? {};
1557
+ return {
1558
+ playerEmail: String(raw["player_email"] ?? playerEmail),
1559
+ subscriptions: rows.map(toSubscription),
1560
+ pagination: {
1561
+ totalCount: Number(p["total_count"] ?? rows.length),
1562
+ limit: Number(p["limit"] ?? 50),
1563
+ offset: Number(p["offset"] ?? 0),
1564
+ hasMore: p["has_more"] === true
1565
+ },
1566
+ raw
1567
+ };
1568
+ }
1569
+ /**
1570
+ * Cancel. `atPeriodEnd` defaults to `true`: the subscription stays live with
1571
+ * `cancelAtPeriodEnd: true` and is retired at `paidThrough` without another charge.
1572
+ * If nothing has been paid (or the paid window has elapsed) an at-period-end cancel is
1573
+ * **downgraded to immediate**: read `terminatedImmediately`. `atPeriodEnd: false` ends
1574
+ * it now. Revoke access at `accessUntil`.
1575
+ *
1576
+ * Cancelling an already-terminal subscription is a 200 with `alreadyCanceled: true`
1577
+ * (never thrown), so a batch reconciler needs no special case; that is also what makes
1578
+ * a lost-response retry safe. One `subscription.canceled` event fires at request time.
1579
+ * Never blocked by a maintenance pause.
1580
+ */
1581
+ async cancel(subscriptionId, options, opts) {
1582
+ assertSubscriptionId(subscriptionId);
1583
+ const body = {};
1584
+ if (options?.atPeriodEnd !== void 0) {
1585
+ if (typeof options.atPeriodEnd !== "boolean") {
1586
+ throw invalidInput2("atPeriodEnd", options.atPeriodEnd, "must be a boolean");
1587
+ }
1588
+ body["at_period_end"] = options.atPeriodEnd;
1589
+ }
1590
+ if (options?.reason !== void 0) {
1591
+ if (typeof options.reason !== "string" || options.reason.length > 500) {
1592
+ throw invalidInput2("reason", options.reason, "must be a string of at most 500 characters");
1593
+ }
1594
+ body["reason"] = options.reason;
1595
+ }
1596
+ const raw = await this.http.post(
1597
+ `/api/subscriptions/${encodeURIComponent(subscriptionId)}/cancel`,
1598
+ body,
1599
+ this.auth,
1600
+ // Safe to retry: a repeat on an already-canceled row is a 200 (already_canceled: true).
1601
+ { idempotent: true, signal: opts?.signal }
1602
+ );
1603
+ return {
1604
+ status: String(raw["status"] ?? ""),
1605
+ alreadyCanceled: raw["already_canceled"] === true,
1606
+ finalStatus: typeof raw["final_status"] === "string" ? raw["final_status"] : void 0,
1607
+ cancelAtPeriodEnd: raw["cancel_at_period_end"] === true,
1608
+ effectiveAt: nullableString(raw["effective_at"]),
1609
+ currentPeriodEnd: nullableString(raw["current_period_end"]),
1610
+ accessUntil: nullableString(raw["access_until"]),
1611
+ paidThrough: nullableString(raw["paid_through"]),
1612
+ terminatedImmediately: raw["terminated_immediately"] === true,
1613
+ downgradeReason: typeof raw["downgrade_reason"] === "string" ? raw["downgrade_reason"] : void 0,
1614
+ message: typeof raw["message"] === "string" ? raw["message"] : void 0,
1615
+ steamAgreementStatus: "steam_agreement_status" in raw ? nullableString(raw["steam_agreement_status"]) : void 0,
1616
+ steamAgreementCanceled: typeof raw["steam_agreement_canceled"] === "boolean" ? raw["steam_agreement_canceled"] : void 0,
1617
+ subscription: raw["subscription"] ? toSubscription(raw["subscription"]) : null,
1618
+ raw
1619
+ };
1620
+ }
1621
+ /**
1622
+ * Stage a price change. Applied on the NEXT successful renewal (the current window is
1623
+ * billed at the old price first; no proration). Sending the current price clears a
1624
+ * staged change (`changeQueued: false`). The billed price appears on that period's
1625
+ * `subscription.renewed`; there is no `amount_changed` event.
1626
+ *
1627
+ * Steam: an increase is refused (`err.isSteamReauthorizationRequired`; start a new
1628
+ * Steam subscription at the new price), a decrease stages. An increase to more than
1629
+ * double the last agreed price, or above 25000.00, is staged but never applied: raise
1630
+ * prices in steps. `err.isSubscriptionTerminal` on a canceled/expired row.
1631
+ */
1632
+ async changeAmount(subscriptionId, amountUsd, opts) {
1633
+ assertSubscriptionId(subscriptionId);
1634
+ const amount = subscriptionMoney(amountUsd, "amountUsd");
1635
+ const raw = await this.http.post(
1636
+ `/api/subscriptions/${encodeURIComponent(subscriptionId)}/amount`,
1637
+ { amount_usd: amount },
1638
+ this.auth,
1639
+ // Setting a price is naturally idempotent: the same value again is the same state.
1640
+ { idempotent: true, signal: opts?.signal }
1641
+ );
1642
+ return {
1643
+ status: String(raw["status"] ?? ""),
1644
+ oldAmountUsd: String(raw["old_amount_usd"] ?? ""),
1645
+ newAmountUsd: String(raw["new_amount_usd"] ?? amount),
1646
+ pendingAmountUsd: nullableString(raw["pending_amount_usd"]),
1647
+ changeQueued: raw["change_queued"] === true,
1648
+ appliesFrom: nullableString(raw["applies_from"]),
1649
+ appliesFromPeriodSeq: Number(raw["applies_from_period_seq"] ?? 0),
1650
+ paidThrough: nullableString(raw["paid_through"]),
1651
+ currentPeriodEnd: nullableString(raw["current_period_end"]),
1652
+ prorated: raw["prorated"] === true,
1653
+ subscription: raw["subscription"] ? toSubscription(raw["subscription"]) : null,
1654
+ raw
1655
+ };
1656
+ }
1657
+ /**
1658
+ * Card subscriptions only. Attach a card (`{ playerCardId }`, an `id` from
1659
+ * `cards.list` belonging to this player, unexpired) or make the subscription wallet-only
1660
+ * (`{ walletOnly: true }`, deprecated: a wallet-only card subscription can never be paid).
1661
+ * On a wallet-only subscription pass `walletOnly: false` beside the card to convert it
1662
+ * back. The new card is used from the next charge, including a pending retry in dunning.
1663
+ *
1664
+ * `err.isNotACardSubscription` on Steam; `err.isSubscriptionTerminal` on a terminal row.
1665
+ */
1666
+ async setPaymentMethod(subscriptionId, input, opts) {
1667
+ assertSubscriptionId(subscriptionId);
1668
+ const body = {};
1669
+ if ("playerCardId" in input && input.playerCardId !== void 0) {
1670
+ if (!Number.isInteger(input.playerCardId) || input.playerCardId < 1) {
1671
+ throw invalidInput2("playerCardId", input.playerCardId, "must be a positive integer card id (from cards.list)");
1672
+ }
1673
+ body["player_card_id"] = input.playerCardId;
1674
+ if (input.walletOnly !== void 0) body["wallet_only"] = input.walletOnly;
1675
+ } else if (input.walletOnly === true) {
1676
+ body["wallet_only"] = true;
1677
+ } else {
1678
+ throw invalidInput2("input", input, "requires { playerCardId } or { walletOnly: true }");
1679
+ }
1680
+ const raw = await this.http.post(
1681
+ `/api/subscriptions/${encodeURIComponent(subscriptionId)}/payment-method`,
1682
+ body,
1683
+ this.auth,
1684
+ // Attaching the same card twice is the same state: safe to retry.
1685
+ { idempotent: true, signal: opts?.signal }
1686
+ );
1687
+ return {
1688
+ status: String(raw["status"] ?? ""),
1689
+ replaced: raw["replaced"] === true,
1690
+ walletOnly: raw["wallet_only"] === true,
1691
+ card: toSavedCard(raw["card"]),
1692
+ subscription: raw["subscription"] ? toSubscription(raw["subscription"]) : null,
1693
+ raw
1694
+ };
1695
+ }
1696
+ /**
1697
+ * Refund a billed period (card rail). Idempotent on `clientRequestId`: a repeat returns
1698
+ * the stored receipt with `idempotentReplay: true` and moves nothing.
1699
+ *
1700
+ * **Branch on `status`.** `"refunded"` (HTTP 200): the refund ran. `"pending_approval"`
1701
+ * (HTTP 202): the refund would exceed the game's daily self-serve limit per UTC day (by
1702
+ * default never lower than the largest single subscription charge, so a single period
1703
+ * always runs unless INVO set a lower limit for the game), NOTHING moved, and INVO reviews it as a refund request (`requestId`); the
1704
+ * outcome arrives as `subscription.refund_approved` (sent together with
1705
+ * `subscription.refunded`, and `subscription.canceled` on a full refund, in any order) or
1706
+ * `subscription.refund_rejected`. The 202 carries every receipt field with nothing moved
1707
+ * (`refundedAmountUsd` is `"0.00"`; `totalRefundedAmountUsd` and `remainingRefundableUsd`
1708
+ * carry the period's real values). Check it with {@link isRefundPendingApproval}.
1709
+ *
1710
+ * A card-only period (every card period charged since 2026-09-17) is refunded in cash, full
1711
+ * or partial: `cardRefundedUsd` equals the amount and `balanceDeltaCoins` is `"0.00"`. A
1712
+ * period charged before that keeps the earlier rule: a full refund returns the card charge
1713
+ * and reclaims the coins it minted (`balanceDeltaCoins` is signed), a partial refund
1714
+ * credits coins. Your revenue is reversed for the refunded portion
1715
+ * (`partnerRevenueReversedUsd`), INVO's fee is retained, and on a card refund you bear the
1716
+ * whole refunded amount, INVO's card fee included (`cardFeeChargedToPartnerUsd`;
1717
+ * `partnerDebitedUsd` is the sum; since 2026-09-28, with no separate processor fee:
1718
+ * `processingFeeUsd` reads `"0.00"`). **A full refund
1719
+ * cancels the subscription** (`subscriptionCanceled`, and a `subscription.canceled` event
1720
+ * with `cancel_cause: "full_refund"`, sent together with `subscription.refunded` in any
1721
+ * order); a partial one does not. INVO emails the member.
1722
+ * Refunds run within 30 days of the period's charge. Send a `reason`: it is recommended now
1723
+ * and will be required later (`warnings` says so when it is missing).
1724
+ *
1725
+ * Refusals: `err.isRefundsNotEnabled` (403), `err.isRefundWindowClosed` (409),
1726
+ * `err.isRefundRequestPending` (409, `err.refundRequestId`), `err.isRefundRequestRejected`
1727
+ * (409, use a new key), `err.isConcurrentRequest` (409, retry with the same key),
1728
+ * `err.isRefundMismatch` (502, contact INVO), `NO_PAID_PERIOD` (409, nothing collected yet),
1729
+ * `PERIOD_NOT_REFUNDABLE`, `ALREADY_REFUNDED` (`err.isAlreadyRefunded`),
1730
+ * `AMOUNT_EXCEEDS_REMAINING` (body carries `remaining_refundable_usd`),
1731
+ * `err.isSteamRefundNotSupported`, `err.isFlowPaused`.
1732
+ */
1733
+ async refund(subscriptionId, input, opts) {
1734
+ assertSubscriptionId(subscriptionId);
1735
+ assertClientRequestId(input.clientRequestId, "clientRequestId");
1736
+ const body = { client_request_id: input.clientRequestId };
1737
+ if (input.periodSeq !== void 0) {
1738
+ if (!Number.isInteger(input.periodSeq) || input.periodSeq < 1) {
1739
+ throw invalidInput2("periodSeq", input.periodSeq, "must be an integer >= 1");
1740
+ }
1741
+ body["period_seq"] = input.periodSeq;
1742
+ }
1743
+ if (input.amountUsd !== void 0) body["amount_usd"] = subscriptionMoney(input.amountUsd, "amountUsd");
1744
+ if (input.reason !== void 0) {
1745
+ if (typeof input.reason !== "string" || input.reason.length > 500) {
1746
+ throw invalidInput2("reason", input.reason, "must be a string of at most 500 characters");
1747
+ }
1748
+ body["reason"] = input.reason;
1749
+ }
1750
+ const raw = await this.http.post(
1751
+ `/api/subscriptions/${encodeURIComponent(subscriptionId)}/refund`,
1752
+ body,
1753
+ this.auth,
1754
+ // Idempotent on client_request_id: a lost-response retry returns the stored receipt.
1755
+ { idempotent: true, signal: opts?.signal }
1756
+ );
1757
+ return toRefundResult(raw, subscriptionId, input.clientRequestId);
1758
+ }
1759
+ /**
1760
+ * Start a STEAM-rail subscription: creates it in `pending_steam_authorization`, opens
1761
+ * period 1 for the full price and starts the Steam authorisation. Nothing is charged
1762
+ * until the member authorises and you call {@link steamFinalize}. Idempotent on
1763
+ * `clientRequestId`; a replay answers with the row's CURRENT status (which may already
1764
+ * be `active`, `canceled` or `expired`).
1765
+ *
1766
+ * `userSession: "client"` (default): the Steam overlay presents the authorisation inside
1767
+ * the game; match the Steam client callback's `order_id` against `steamOrderId` (never
1768
+ * `steamTransid`). `"web"`: open `steamCheckoutUrl` as a TOP-LEVEL window (it cannot be
1769
+ * framed); requires `playerIp`, the MEMBER's address. Show `amountCoins`: what one
1770
+ * period is worth for THIS member depends on their country and is fixed at init.
1771
+ *
1772
+ * A pending authorisation for the same player and item with the SAME terms is handed
1773
+ * back (`pendingReuse: true`, no new agreement): finalize that one. With DIFFERENT
1774
+ * terms the call throws `409 STEAM_AUTHORIZATION_PENDING` (`err.isSteamAuthorizationPending`,
1775
+ * `err.existingSubscriptionId`): finalize or cancel the pending one first.
1776
+ *
1777
+ * Not available on Steam, refused before the network: trials, `walletOnly`, card
1778
+ * fields, `intervalCount` other than 1. Backend refusals worth branching on:
1779
+ * `err.isSteamChannelRequired` (409, wrong channel key), `err.isActiveSubscriptionExists`,
1780
+ * `err.isSteamRailNotEntitled` (403), `err.isSteamNotConfigured` (503),
1781
+ * `err.isPartnerBillingNotSetUp` / `isPartnerSettlementUnavailable` (409),
1782
+ * `AMOUNT_TOO_SMALL_FOR_STEAM` (400). When a Steam-side failure abandons the row after
1783
+ * creation the body carries the abandoned `subscription_id`; retry with a NEW key.
1784
+ */
1785
+ async steamInit(input, opts) {
1786
+ const body = subscriptionBaseBody(input);
1787
+ if (!/^[0-9]+$/.test(String(input.steamId ?? ""))) {
1788
+ throw invalidInput2("steamId", input.steamId, "must be the member's numeric 64-bit Steam id");
1789
+ }
1790
+ if (input.userSession !== void 0 && input.userSession !== "client" && input.userSession !== "web") {
1791
+ throw invalidInput2("userSession", input.userSession, 'must be "client" or "web"');
1792
+ }
1793
+ if (input.userSession === "web" && !input.playerIp) {
1794
+ throw new InvoError({
1795
+ message: `playerIp is required when userSession is "web" \u2014 the MEMBER's IP, not your server's.`,
1796
+ code: "MISSING_PLAYER_IP",
1797
+ status: 0
1798
+ });
1799
+ }
1800
+ if (input.intervalCount !== void 0 && input.intervalCount !== 1) {
1801
+ throw invalidInput2("intervalCount", input.intervalCount, "must be 1 on the Steam rail (monthly and yearly only)");
1802
+ }
1803
+ const forbidden = input;
1804
+ if (forbidden["trialAmountUsd"] !== void 0) {
1805
+ throw new InvoError({
1806
+ message: "trialAmountUsd is only available on card-funded subscriptions (subscriptions.create). Steam subscriptions have no trials.",
1807
+ code: "TRIAL_AMOUNT_NOT_SUPPORTED_FOR_FUNDING",
1808
+ status: 0
1809
+ });
1810
+ }
1811
+ for (const k of ["trialDays", "trialEnd", "walletOnly", "playerCardId"]) {
1812
+ if (forbidden[k] !== void 0) {
1813
+ throw invalidInput2(k, forbidden[k], "is not available on the Steam rail");
1814
+ }
1815
+ }
1816
+ body["steamid"] = String(input.steamId);
1817
+ if (input.userSession) body["usersession"] = input.userSession;
1818
+ if (input.playerIp) body["player_ip"] = input.playerIp;
1819
+ if (input.intervalCount !== void 0) body["interval_count"] = input.intervalCount;
1820
+ const raw = await this.http.post(
1821
+ "/api/subscriptions/steam/init",
1822
+ body,
1823
+ this.auth,
1824
+ // Idempotent on client_request_id: a replay returns the row's current status.
1825
+ { idempotent: true, signal: opts?.signal }
1826
+ );
1827
+ return {
1828
+ status: String(raw["status"] ?? ""),
1829
+ subscriptionStatus: String(raw["subscription_status"] ?? raw["status"] ?? ""),
1830
+ idempotentReplay: raw["idempotent_replay"] === true,
1831
+ pendingReuse: raw["pending_reuse"] === true,
1832
+ subscription: toSubscription(raw["subscription"]),
1833
+ subscriptionId: String(raw["subscription_id"] ?? ""),
1834
+ orderId: String(raw["order_id"] ?? ""),
1835
+ steamOrderId: String(raw["steam_order_id"] ?? ""),
1836
+ steamTransid: String(raw["steam_transid"] ?? ""),
1837
+ steamCheckoutUrl: nullableString(raw["steam_checkout_url"]),
1838
+ amountUsd: String(raw["amount_usd"] ?? ""),
1839
+ amountCoins: String(raw["amount_coins"] ?? ""),
1840
+ steamChargeUsd: String(raw["steam_charge_usd"] ?? ""),
1841
+ recurringAmountUsd: String(raw["recurring_amount_usd"] ?? ""),
1842
+ firstCharge: toFirstCharge(raw["first_charge"]),
1843
+ message: String(raw["message"] ?? ""),
1844
+ raw
1845
+ };
1846
+ }
1847
+ /**
1848
+ * Finalize a Steam subscription after the member has authorised: INVO verifies with
1849
+ * Steam, captures period 1, records the agreement and settles period 1 exactly as a
1850
+ * renewal. Idempotent: a repeat returns `alreadyProcessed: true` with
1851
+ * `idempotentReplay: true` (treat as success; never thrown).
1852
+ *
1853
+ * **Finalize is your call.** Steam does not tell INVO the member authorised; call this
1854
+ * after the overlay or checkout closes, and again if it threw `err.isNotAuthorized`
1855
+ * (409 `status: "not_authorized"`: the normal wait state). The member has 24 hours.
1856
+ * A 200 with `warning` means Steam charged but period 1 could not settle in one step:
1857
+ * the money is taken, do not retry the charge, watch for `subscription.renewed`.
1858
+ * In sandbox this does not call Steam (`sandboxAutoApproved: true`).
1859
+ *
1860
+ * Other refusals: `err.isSubscriptionTerminal`, `NOT_A_STEAM_SUBSCRIPTION`,
1861
+ * `NO_STEAM_AUTHORIZATION`, `err.isSteamAppChanged` (409); 502/503 are transient.
1862
+ */
1863
+ async steamFinalize(subscriptionId, opts) {
1864
+ assertSubscriptionId(subscriptionId);
1865
+ const raw = await this.http.post(
1866
+ "/api/subscriptions/steam/finalize",
1867
+ { subscription_id: subscriptionId },
1868
+ this.auth,
1869
+ // Idempotent: a repeat replays the finalised row (already_processed: true).
1870
+ { idempotent: true, signal: opts?.signal }
1871
+ );
1872
+ return {
1873
+ ...toSubscriptionResult(raw),
1874
+ alreadyProcessed: raw["already_processed"] === true,
1875
+ steamAgreementStatus: nullableString(raw["steam_agreement_status"]),
1876
+ sandboxAutoApproved: raw["sandbox_auto_approved"] === true
1877
+ };
1878
+ }
1879
+ };
1880
+ var SCRIPT_SCHEME = /^\s*(javascript|data|vbscript):/i;
1881
+ var CardsServer = class {
1882
+ constructor(http, auth) {
1883
+ this.http = http;
1884
+ this.auth = auth;
1885
+ }
1886
+ /**
1887
+ * Mint a short-lived session for the INVO-hosted card page and return its URL. THE
1888
+ * RECOMMENDED WAY TO SAVE A CARD FOR A SUBSCRIPTION: two server-to-server calls (this
1889
+ * one, then `cards.list`) and one redirect. No browser code, no processor script, no
1890
+ * client secret; INVO can change card processor without you changing anything.
1891
+ *
1892
+ * A member this game already knows needs only `playerEmail`. A BRAND-NEW member (a
1893
+ * first-time signup, for example before a paid trial) is created here when you also
1894
+ * send `playerName` (and optionally `playerPhone`), exactly as `subscriptions.create`
1895
+ * creates one: same phone-share gate, same wallet binding. Without `playerName` an
1896
+ * unknown member is `err.isPlayerNotFound` (404) and nothing is created. A known member
1897
+ * is never re-created or renamed by this call; `playerName` / `playerPhone` are used
1898
+ * only when the member is new. Send the member to `result.cardSetupUrl` top-level (do
1899
+ * not frame it). The page says in words that no money moves, saves the card, and then
1900
+ * redirects to `successUrl` (or shows "Card saved" when you gave none). The saved card
1901
+ * appears in {@link list} immediately, carries the off-session consent a subscription
1902
+ * needs, and is indistinguishable from one saved any other way. There is no event for
1903
+ * a saved card; `cards.list` is the signal.
1904
+ *
1905
+ * The session lives 10 minutes (entering a card is one sitting); mint it when the
1906
+ * member is about to use it. The link may be reloaded freely before the save; once the
1907
+ * card is saved the link is spent and reopening it returns the same card again.
1908
+ * `successUrl` is redirected to verbatim (nothing appended) and `metadata` is stored on
1909
+ * the session and not returned anywhere today, so put your own correlation id in
1910
+ * `successUrl`.
1911
+ *
1912
+ * Refusals: `err.isInvalidPlayerEmail` (400, a non-email string; a missing or blank
1913
+ * `playerEmail` is refused here first with `status: 0`), `err.isPlayerNotFound` (404),
1914
+ * `err.isInvalidInput` (400: a script-scheme `successUrl` / `cancelUrl`, or, when the
1915
+ * member is new, a `playerName` over 255 characters or a `playerPhone` over 30; the SDK
1916
+ * refuses script schemes, a blank or over-long `playerName` and a non-E.164
1917
+ * `playerPhone` first with `status: 0`), `err.isPhoneShareApprovalRequired` (409, creating the member needs the
1918
+ * existing phone owner's approval; same body as `subscriptions.create`),
1919
+ * `err.isPlayerCreateFailed` (503, the member could not be created; call again),
1920
+ * 401 / 403 on the key or the game (body `{ message }`, no code), 503 when card setup
1921
+ * is not available right now. Never auto-retried: each call mints a fresh link, so on a
1922
+ * timeout call it again.
1923
+ */
1924
+ async createSetupSession(input, opts) {
1925
+ if (typeof input.playerEmail !== "string" || !input.playerEmail.trim()) {
1926
+ throw invalidInput2("playerEmail", input.playerEmail, "is required");
1927
+ }
1928
+ for (const [label, value] of [
1929
+ ["successUrl", input.successUrl],
1930
+ ["cancelUrl", input.cancelUrl]
1931
+ ]) {
1932
+ if (value === void 0) continue;
1933
+ if (typeof value !== "string" || !value.trim()) throw invalidInput2(label, value, "must be a non-empty URL");
1934
+ if (SCRIPT_SCHEME.test(value)) throw invalidInput2(label, value, "must not use a script scheme");
1935
+ }
1936
+ if (input.metadata !== void 0 && (input.metadata === null || typeof input.metadata !== "object" || Array.isArray(input.metadata))) {
1937
+ throw invalidInput2("metadata", input.metadata, "must be a plain object");
1938
+ }
1939
+ if (input.playerName !== void 0) {
1940
+ if (typeof input.playerName !== "string" || !input.playerName.trim()) {
1941
+ throw invalidInput2("playerName", input.playerName, "must be a non-empty string");
1942
+ }
1943
+ if (input.playerName.trim().length > 255) throw invalidInput2("playerName", input.playerName, "must be at most 255 characters");
1944
+ }
1945
+ if (input.playerPhone !== void 0) assertE164(input.playerPhone, "playerPhone");
1946
+ const body = { player_email: input.playerEmail };
1947
+ if (input.playerName) body["player_name"] = input.playerName;
1948
+ if (input.playerPhone) body["player_phone"] = input.playerPhone;
1949
+ if (input.successUrl) body["success_url"] = input.successUrl;
1950
+ if (input.cancelUrl) body["cancel_url"] = input.cancelUrl;
1951
+ if (input.metadata) body["metadata"] = input.metadata;
1952
+ const raw = await this.http.post(
1953
+ "/api/checkout/card-setup-sessions",
1954
+ body,
1955
+ this.auth,
1956
+ { signal: opts?.signal }
1957
+ // not idempotent: every call mints a new session (same rule as createCheckout)
1958
+ );
1959
+ return {
1960
+ sessionId: String(raw["session_id"] ?? ""),
1961
+ // Load-bearing: the member must be sent here. A 2xx without it is a broken response.
1962
+ cardSetupUrl: requireField(raw["card_setup_url"], "card_setup_url", raw),
1963
+ expiresAt: String(raw["expires_at"] ?? ""),
1964
+ raw
1965
+ };
1966
+ }
1967
+ /**
1968
+ * THE PROCESSOR-BOUND ALTERNATIVE to {@link createSetupSession}. Use it only if you
1969
+ * already run a card form in your own client against INVO's current card processor:
1970
+ * the `clientSecret` it hands back can only be consumed by that processor's client
1971
+ * library, so the browser code you write for it will need rework when INVO changes
1972
+ * processor. `createSetupSession` does not have that problem.
1973
+ *
1974
+ * Begin saving a card (charges nothing). The player must already exist in this game
1975
+ * (`404 PLAYER_NOT_FOUND`). Idempotent on `setupReference`: resend the same value on a
1976
+ * retry and you get the same setup back (`409 SETUP_REFERENCE_REUSED` if you reuse it
1977
+ * with different parameters).
1978
+ *
1979
+ * With `paymentMethodId` (a card tokenised on the client) INVO confirms server-side
1980
+ * and answers `succeeded` with the `card`, or `requires_action` with a `clientSecret`
1981
+ * for the card form to run the cardholder authentication. Without it, INVO answers
1982
+ * `requires_confirmation` / `requires_payment_method` with a `clientSecret`: confirm on
1983
+ * the client, then call {@link confirmSetup}. Send tokens only, never raw card numbers
1984
+ * (`RAW_CARD_NOT_SUPPORTED`).
1985
+ */
1986
+ async beginSetup(input, opts) {
1987
+ if (typeof input.playerEmail !== "string" || !input.playerEmail.trim()) {
1988
+ throw invalidInput2("playerEmail", input.playerEmail, "is required");
1989
+ }
1990
+ if (typeof input.setupReference !== "string" || !/^[A-Za-z0-9._:-]{1,200}$/.test(input.setupReference)) {
1991
+ throw invalidInput2("setupReference", input.setupReference, "must be 1-200 characters of A-Z a-z 0-9 . _ : -");
1992
+ }
1993
+ const body = {
1994
+ player_email: input.playerEmail,
1995
+ setup_reference: input.setupReference
1996
+ };
1997
+ if (input.paymentMethodId) body["payment_method_id"] = input.paymentMethodId;
1998
+ const raw = await this.http.post(
1999
+ "/api/currency-purchases/setup-intent",
2000
+ body,
2001
+ this.auth,
2002
+ // Idempotent on setup_reference: a retry returns the same setup, never a second one.
2003
+ { idempotent: true, signal: opts?.signal }
2004
+ );
2005
+ return {
2006
+ status: String(raw["status"] ?? ""),
2007
+ setupIntentId: requireField(raw["setup_intent_id"], "setup_intent_id", raw),
2008
+ clientSecret: typeof raw["client_secret"] === "string" ? raw["client_secret"] : void 0,
2009
+ publishableKey: typeof raw["publishable_key"] === "string" ? raw["publishable_key"] : void 0,
2010
+ card: toSavedCard(raw["card"]),
2011
+ alreadySaved: raw["already_saved"] === true,
2012
+ message: typeof raw["message"] === "string" ? raw["message"] : void 0,
2013
+ raw
2014
+ };
2015
+ }
2016
+ /**
2017
+ * The second half of the processor-bound alternative (see {@link beginSetup}); not
2018
+ * needed on the {@link createSetupSession} path, where INVO's page completes the save.
2019
+ *
2020
+ * Finish a client-confirmed setup and save the card. Idempotent on `setupIntentId`.
2021
+ * While the client has not finished, this throws a 400 with body
2022
+ * `status: "still_requires_action"`. On `500 CARD_PERSIST_FAILED` (authorised but not
2023
+ * recorded) retry this call with the same `setupIntentId`.
2024
+ */
2025
+ async confirmSetup(input, opts) {
2026
+ if (typeof input.setupIntentId !== "string" || !input.setupIntentId.trim()) {
2027
+ throw invalidInput2("setupIntentId", input.setupIntentId, "is required (from beginSetup)");
2028
+ }
2029
+ const raw = await this.http.post(
2030
+ "/api/currency-purchases/setup-intent/confirm",
2031
+ { setup_intent_id: input.setupIntentId },
2032
+ this.auth,
2033
+ { idempotent: true, signal: opts?.signal }
2034
+ // keyed by setup_intent_id: safe to retry
2035
+ );
2036
+ return {
2037
+ status: String(raw["status"] ?? ""),
2038
+ setupIntentId: String(raw["setup_intent_id"] ?? input.setupIntentId),
2039
+ card: toSavedCard(raw["card"]),
2040
+ alreadySaved: raw["already_saved"] === true,
2041
+ raw
2042
+ };
2043
+ }
2044
+ /**
2045
+ * A member's unexpired saved cards, newest first. An unknown player is `{ cards: [] }`.
2046
+ * The `id` is the value you pass as `playerCardId`; INVO never returns processor
2047
+ * identifiers for a card. Served from a short cache (about 60 s); a card saved through
2048
+ * the hosted card page (`createSetupSession`) or through `beginSetup` / `confirmSetup`
2049
+ * appears immediately. This read is the signal that the hosted page saved a card.
2050
+ */
2051
+ async list(playerEmail, opts) {
2052
+ if (typeof playerEmail !== "string" || !playerEmail.trim()) {
2053
+ throw invalidInput2("playerEmail", playerEmail, "is required");
2054
+ }
2055
+ const raw = await this.http.get(
2056
+ `/api/currency-purchases/player-cards?player_email=${encodeURIComponent(playerEmail)}`,
2057
+ this.auth,
2058
+ { signal: opts?.signal }
2059
+ );
2060
+ const rows = Array.isArray(raw["cards"]) ? raw["cards"] : [];
2061
+ return {
2062
+ cards: rows.map(toSavedCard).filter((c) => c !== null),
2063
+ raw
2064
+ };
2065
+ }
2066
+ };
2067
+ var SandboxSubscriptionsServer = class {
2068
+ constructor(http, auth, clockKey) {
2069
+ this.http = http;
2070
+ this.auth = auth;
2071
+ this.clockKey = clockKey;
2072
+ }
2073
+ async call(subscriptionId, tool, body, opts) {
2074
+ assertSubscriptionId(subscriptionId);
2075
+ if (typeof this.clockKey !== "string" || !this.clockKey.trim()) {
2076
+ throw invalidInput2(
2077
+ "sandboxClockKey",
2078
+ this.clockKey,
2079
+ 'is required for invo.sandbox.subscriptions.* \u2014 pass it to new InvoServer({ sandboxClockKey }) from the sandbox console (Game Settings, "Sandbox clock key")'
2080
+ );
2081
+ }
2082
+ const raw = await this.http.post(
2083
+ // Relative to baseUrl, which already ends in /sandbox. NOT under /api.
2084
+ `/subscriptions/${encodeURIComponent(subscriptionId)}/${tool}`,
2085
+ body,
2086
+ this.auth,
2087
+ { signal: opts?.signal, headers: { "X-Sandbox-Clock-Key": this.clockKey } }
2088
+ // never auto-retried
2089
+ );
2090
+ return toSandboxClockResult(raw);
2091
+ }
2092
+ /**
2093
+ * Make the next period due now. `intervals` 0..60, default 1. `0` makes it due without
2094
+ * moving the window (use it to trigger a retry). `N` on a never-paid subscription
2095
+ * (a trial, a fresh row) also moves the window back by up to N intervals; once anything
2096
+ * has been paid the window stays put (`intervalsAppliedToWindow: 0`). No window is ever
2097
+ * billed twice. Then `forceRenewal`, or wait for the next sweep (within a minute or two).
2098
+ * `409 SUBSCRIPTION_NOT_LIVE` on a terminal or pending row.
2099
+ */
2100
+ async advanceClock(subscriptionId, intervals = 1, opts) {
2101
+ if (!Number.isInteger(intervals) || intervals < 0 || intervals > 60) {
2102
+ throw invalidInput2("intervals", intervals, "must be an integer 0..60");
2103
+ }
2104
+ return this.call(subscriptionId, "advance-clock", { intervals }, opts);
2105
+ }
2106
+ /**
2107
+ * Run the renewal immediately. **Charges the test card** (or the Steam stand-in): the
2108
+ * real money path (card: the full price; Steam: wallet first, then the shortfall), mint,
2109
+ * spend, split, `subscription.renewed`,
2110
+ * and on failure the real dunning. Read `engineStats` (`renewed: 1` on success). A
2111
+ * cancel-at-period-end row answers `action: "retired-at-period-end"`, `retired: true`.
2112
+ * `409 PERIOD_TOO_FAR_AHEAD` means you forced twice without advancing the clock.
2113
+ */
2114
+ async forceRenewal(subscriptionId, opts) {
2115
+ return this.call(subscriptionId, "force-renewal", {}, opts);
2116
+ }
2117
+ /**
2118
+ * Synthesise a failed attempt and run real dunning. No charge. `outcome` defaults to
2119
+ * `card_declined`. Returns `retryBudgetUsed`, `retryScheduleDays` (e.g. `[2, 3, 2]`),
2120
+ * `retriesRemaining`. Call it four times to walk `active` through `past_due` to `expired`
2121
+ * and watch the events. Does not model a Steam refusal.
2122
+ */
2123
+ async forceFailure(subscriptionId, outcome = "card_declined", options, opts) {
2124
+ if (!SANDBOX_FAILURE_OUTCOMES.has(outcome)) {
2125
+ throw invalidInput2("outcome", outcome, 'must be "card_declined" | "insufficient_funds" | "error"');
2126
+ }
2127
+ const body = { outcome };
2128
+ if (options?.failureCode !== void 0) body["failure_code"] = options.failureCode;
2129
+ if (options?.failureMessage !== void 0) body["failure_message"] = options.failureMessage;
2130
+ return this.call(subscriptionId, "force-failure", body, opts);
2131
+ }
2132
+ /**
2133
+ * Synthesise a cardholder authentication challenge: moves the subscription to
2134
+ * `awaiting_authentication` (no charge). Returns `authChallengesUsed`,
2135
+ * `maxAuthChallenges` (2) and `downgradedToDecline`. It does NOT mint a confirmation
2136
+ * link; to exercise the link and the `subscription.authentication_required` event use a
2137
+ * test card that requires authentication, then `forceRenewal`.
2138
+ */
2139
+ async forceAuthChallenge(subscriptionId, options, opts) {
2140
+ const body = {};
2141
+ if (options?.failureMessage !== void 0) body["failure_message"] = options.failureMessage;
2142
+ return this.call(subscriptionId, "force-auth-challenge", body, opts);
2143
+ }
2144
+ };
2145
+ var SandboxServer = class {
2146
+ constructor(http, auth, clockKey) {
2147
+ this.subscriptions = new SandboxSubscriptionsServer(http, auth, clockKey);
2148
+ }
2149
+ };
2150
+ var InvoServer = class {
2151
+ constructor(config) {
2152
+ if (!config.gameSecret) throw new Error("InvoServer requires a `gameSecret`.");
2153
+ if (!config.baseUrl) throw new Error("InvoServer requires a `baseUrl`.");
2154
+ assertSecureBaseUrl(config.baseUrl);
2155
+ this.http = new Http({
2156
+ baseUrl: config.baseUrl,
2157
+ timeoutMs: config.timeoutMs,
2158
+ fetchImpl: config.fetch,
2159
+ userAgent: DEFAULT_UA,
2160
+ // must be a non-blocked UA (handoff doc §9)
2161
+ maxRetries: config.maxRetries,
2162
+ retryBaseDelayMs: config.retryBaseDelayMs,
2163
+ hooks: config.hooks
2164
+ });
2165
+ this.auth = { kind: "game-secret", secret: config.gameSecret };
2166
+ this.platformCommerce = new PlatformCommerceServer(this.http, this.auth);
2167
+ this.subscriptions = new SubscriptionsServer(this.http, this.auth);
2168
+ this.cards = new CardsServer(this.http, this.auth);
2169
+ this.sandbox = new SandboxServer(this.http, this.auth, config.sandboxClockKey);
2170
+ this.payouts = new PayoutsServer(this.http, this.auth);
2171
+ }
2172
+ /**
2173
+ * Mint a short-lived, game-scoped player token to hand to the browser InvoClient.
2174
+ *
2175
+ * For a player who already exists in your game, this is a session mint: INVO looks the
2176
+ * player up by `playerEmail` and returns a token for their identity. `playerPhone` and
2177
+ * `playerName` do not change an existing player.
2178
+ *
2179
+ * For a player who is NOT in your game yet: without `playerPhone` INVO answers 404
2180
+ * (`err.isPlayerNotFound`); with `playerPhone` INVO creates the player and the result
2181
+ * carries `created: true`, so a first-time receiver can collect without buying first.
2182
+ * Use `registerPlayer` when you want creation to be explicit.
2183
+ *
2184
+ * `phoneMismatch: true` means the existing player has a different phone than the one
2185
+ * you passed; the token is still for that player and their phone is unchanged
2186
+ * (`updatePlayerPhone` changes it). A phone already held by another email is a 409
2187
+ * (`err.isPhoneShareRefused`).
2188
+ */
2189
+ async mintPlayerToken(input, opts) {
2190
+ if (typeof input.playerEmail !== "string" || !input.playerEmail.trim()) {
2191
+ throw invalidInput2("playerEmail", input.playerEmail, "is required");
2192
+ }
2193
+ const body = { player_email: input.playerEmail };
2194
+ if (input.playerPhone !== void 0) {
2195
+ assertE164(input.playerPhone, "playerPhone");
2196
+ body["player_phone"] = input.playerPhone;
2197
+ }
2198
+ if (input.playerName !== void 0) {
2199
+ if (typeof input.playerName !== "string") {
2200
+ throw invalidInput2("playerName", input.playerName, "must be a string");
2201
+ }
2202
+ body["player_name"] = input.playerName;
2203
+ }
2204
+ const raw = await this.http.post(
2205
+ "/api/sdk/player-token",
2206
+ body,
2207
+ this.auth,
2208
+ // Safe to retry: a re-mint issues a fresh token, and a create that already happened
2209
+ // answers the retry for the existing player.
2210
+ { idempotent: true, signal: opts?.signal }
2211
+ );
2212
+ const out = {
2213
+ token: requireField(raw["token"], "token", raw),
2214
+ expiresAt: String(raw["expires_at"] ?? ""),
2215
+ identityId: String(raw["identity_id"] ?? "")
2216
+ };
2217
+ if (raw["created"] === true) out.created = true;
2218
+ if (raw["phone_mismatch"] === true) out.phoneMismatch = true;
2219
+ return out;
2220
+ }
2221
+ /**
2222
+ * Create a player in your game without moving money (`POST /api/sdk/players`), so a
2223
+ * first-time receiver can collect in-game. Sends no message to the player.
2224
+ *
2225
+ * Returns `status: "created"` (new) or `"exists"` (already in your game with that
2226
+ * phone), with a player token when INVO can issue one. Refusals: 409
2227
+ * `err.isPhoneMismatch` (already in your game with a different phone; use
2228
+ * `updatePlayerPhone`), 409 `err.isPhoneShareRefused` (the phone belongs to another
2229
+ * email), 400 `INVALID_INPUT` / `INVALID_PHONE`, 429 (`err.retryAfter`).
2230
+ */
2231
+ async registerPlayer(input, opts) {
2232
+ if (typeof input.playerEmail !== "string" || !input.playerEmail.trim()) {
2233
+ throw invalidInput2("playerEmail", input.playerEmail, "is required");
2234
+ }
2235
+ assertE164(input.playerPhone, "playerPhone");
2236
+ const body = {
2237
+ player_email: input.playerEmail,
2238
+ player_phone: input.playerPhone
2239
+ };
2240
+ if (input.playerName !== void 0) {
2241
+ if (typeof input.playerName !== "string") {
2242
+ throw invalidInput2("playerName", input.playerName, "must be a string");
2243
+ }
2244
+ body["player_name"] = input.playerName;
2245
+ }
2246
+ const raw = await this.http.post(
2247
+ "/api/sdk/players",
2248
+ body,
2249
+ this.auth,
2250
+ // Find-or-create, no money: a retry after a create answers "exists".
2251
+ { idempotent: true, signal: opts?.signal }
2252
+ );
2253
+ const status = requireField(raw["status"], "status", raw);
2254
+ return {
2255
+ status: status === "created" ? "created" : "exists",
2256
+ identityId: String(raw["identity_id"] ?? ""),
2257
+ ...playerTokenFields(raw),
2258
+ raw
2259
+ };
2260
+ }
2261
+ /**
2262
+ * Set a player's phone from your server (`POST /api/sdk/players/phone`). A phone change
2263
+ * can give the player a new INVO identity: `identityRekeyed: true`, and the result
2264
+ * carries a fresh `playerToken` for it (tokens minted before the change are then out
2265
+ * of date).
2266
+ *
2267
+ * Refusals: 409 `err.isPhoneChangeRequiresVerification` (the player has secured this
2268
+ * account, so the change needs the player's own confirmation: call `requestPhoneChange`;
2269
+ * `err.changeRequestEndpoint` names the route), 409 `err.isPhoneShareRefused` (the
2270
+ * number belongs to another email), 409 `err.isPendingTransfersToOldPhone` /
2271
+ * `err.isPendingTransfersToNewPhone` (transfers to the current or the new number are still
2272
+ * waiting to be collected), 404 `err.isPlayerNotFound`, 400 `INVALID_INPUT` / `INVALID_PHONE`, 429
2273
+ * (`err.retryAfter`), 503 (could not be checked right now; try again shortly).
2274
+ *
2275
+ * Never auto-retried: a retry after a change that landed would answer `"unchanged"` and
2276
+ * hide `identityRekeyed`.
2277
+ */
2278
+ async updatePlayerPhone(input, opts) {
2279
+ if (typeof input.playerEmail !== "string" || !input.playerEmail.trim()) {
2280
+ throw invalidInput2("playerEmail", input.playerEmail, "is required");
2281
+ }
2282
+ assertE164(input.newPhone, "newPhone");
2283
+ const raw = await this.http.post(
2284
+ "/api/sdk/players/phone",
2285
+ { player_email: input.playerEmail, new_phone: input.newPhone },
2286
+ this.auth,
2287
+ { signal: opts?.signal }
2288
+ );
2289
+ const status = requireField(raw["status"], "status", raw);
2290
+ return {
2291
+ status: status === "updated" ? "updated" : "unchanged",
2292
+ identityRekeyed: raw["identity_rekeyed"] === true,
2293
+ identityId: String(raw["identity_id"] ?? ""),
2294
+ ...playerTokenFields(raw),
2295
+ raw
2296
+ };
2297
+ }
2298
+ /**
2299
+ * Ask the player to confirm a new phone number
2300
+ * (`POST /api/sdk/players/phone/change-requests`, HTTP 202). Use it when `updatePlayerPhone`
2301
+ * answers 409 `err.isPhoneChangeRequiresVerification`.
2302
+ *
2303
+ * Nothing about the player changes here. INVO emails the player a code and a link to a
2304
+ * page on INVO's site, and the player confirms there (plus their passkey on that page, or
2305
+ * an approval on their enrolled device, when they have one: see `confirmation`). Your game
2306
+ * never collects the code and never receives the link: do not ask the player for it.
2307
+ * Follow up with `getPhoneChange`, or wait for the `player.phone_changed` webhook.
2308
+ *
2309
+ * Refusals carry `err.code`, for example 409 `PHONE_SAME`, `PHONE_IN_USE_BY_ANOTHER_PLAYER`,
2310
+ * `PENDING_TRANSFERS_TO_NEW_PHONE` (`err.isPendingTransfersToNewPhone`),
2311
+ * `PENDING_TRANSFERS_TO_OLD_PHONE` (`err.isPendingTransfersToOldPhone`),
2312
+ * `CHANGE_REQUEST_IN_PROGRESS` (`err.isChangeRequestInProgress`), `PHONE_CHANGE_LOCKED`
2313
+ * (`err.isPhoneChangeLocked`), `PHONE_CHANGE_RECOVERY_COOLDOWN`
2314
+ * (`err.isPhoneChangeRecoveryCooldown`), `STEP_UP_UNAVAILABLE`, `WALLET_SECURED`,
2315
+ * `PHONE_NOT_SET`;
2316
+ * 429 `err.isTooManyChangeRequests`; 404 `err.isPlayerNotFound`; 503
2317
+ * `err.isPhoneChangeUnavailable`.
2318
+ *
2319
+ * Never auto-retried: a new request replaces your earlier pending one and sends the player
2320
+ * another email.
2321
+ */
2322
+ async requestPhoneChange(input, opts) {
2323
+ if (typeof input.playerEmail !== "string" || !input.playerEmail.trim()) {
2324
+ throw invalidInput2("playerEmail", input.playerEmail, "is required");
2325
+ }
2326
+ assertE164(input.newPhone, "newPhone");
2327
+ const raw = await this.http.post(
2328
+ "/api/sdk/players/phone/change-requests",
2329
+ { player_email: input.playerEmail, new_phone: input.newPhone },
2330
+ this.auth,
2331
+ { signal: opts?.signal }
2332
+ );
2333
+ return toRequestPhoneChangeResult(raw);
2334
+ }
2335
+ /**
2336
+ * Read a change request your game created
2337
+ * (`GET /api/sdk/players/phone/change-requests/{changeRequestId}`). `status` is `pending`,
2338
+ * `confirmed`, `expired`, `cancelled`, `refused` or `denied`. A request another game
2339
+ * created, or an unknown id, is 404 `err.isChangeRequestNotFound`. Poll sparingly, or wait
2340
+ * for the `player.phone_changed` webhook.
2341
+ */
2342
+ async getPhoneChange(changeRequestId, opts) {
2343
+ if (typeof changeRequestId !== "string" || !changeRequestId.trim()) {
2344
+ throw invalidInput2("changeRequestId", changeRequestId, "is required");
2345
+ }
2346
+ const raw = await this.http.get(
2347
+ `/api/sdk/players/phone/change-requests/${encodeURIComponent(changeRequestId)}`,
2348
+ this.auth,
2349
+ { signal: opts?.signal }
2350
+ );
2351
+ return toPhoneChangeRequest(raw);
2352
+ }
2353
+ /**
2354
+ * Initiate a cross-game currency SEND. Inspect result.verificationMethod.
2355
+ *
2356
+ * Steam titles: can throw a 409 `err.isSteamValueNonTransferable` (moving more than the
2357
+ * player's non-Steam balance to a non-Steam destination — cap at `err.steamTransferableMax`)
2358
+ * or `err.isNonSteamValueIntoSteamBlocked` (non-Steam value into a Steam title). Prevent both
2359
+ * up front with `DestinationGame.acceptsSteamOriginValue`.
2360
+ */
2361
+ async initiateSend(input, opts) {
2362
+ const raw = await this.http.post(
2363
+ "/api/currency-sends/initiate-send",
2364
+ {
2365
+ client_request_id: input.clientRequestId,
2366
+ sender_player_name: input.senderPlayerName,
2367
+ sender_player_email: input.senderPlayerEmail,
2368
+ sender_player_phone: input.senderPlayerPhone,
2369
+ receiver_player_email: input.receiverPlayerEmail,
2370
+ receiver_player_phone: input.receiverPlayerPhone,
2371
+ receiving_game_id: input.receivingGameId,
2372
+ amount: input.amount
2373
+ },
2374
+ this.auth,
2375
+ { idempotent: true, signal: opts?.signal }
2376
+ // client_request_id makes this safe to retry (backend dedupes)
2377
+ );
2378
+ return this.toInitiateResult(raw);
2379
+ }
2380
+ /** Initiate a cross-game TRANSFER. Inspect result.verificationMethod. Can throw the same
2381
+ * Steam-policy 409s as {@link initiateSend} (`isSteamValueNonTransferable` /
2382
+ * `isNonSteamValueIntoSteamBlocked`). */
2383
+ async initiateTransfer(input, opts) {
2384
+ const raw = await this.http.post(
2385
+ "/api/transfers/initiate-transfer",
2386
+ {
2387
+ client_request_id: input.clientRequestId,
2388
+ source_player_name: input.sourcePlayerName,
2389
+ source_player_email: input.sourcePlayerEmail,
2390
+ source_player_phone: input.sourcePlayerPhone,
2391
+ target_player_email: input.targetPlayerEmail,
2392
+ target_player_phone: input.targetPlayerPhone,
2393
+ target_game_id: input.targetGameId,
2394
+ amount: input.amount
2395
+ },
2396
+ this.auth,
2397
+ { idempotent: true, signal: opts?.signal }
2398
+ // client_request_id makes this safe to retry (backend dedupes)
2399
+ );
2400
+ return this.toInitiateResult(raw);
2401
+ }
2402
+ /** Create a hosted checkout session (the recommended purchase path). Open the
2403
+ * returned checkoutUrl in a WebView/redirect or an iframe; the INVO-hosted page
2404
+ * handles cards, saved cards, and 3-D Secure. Crediting is server-side via the
2405
+ * purchase.completed webhook. */
2406
+ async createCheckout(input, opts) {
2407
+ if (typeof input.playerEmail !== "string" || !input.playerEmail.trim()) {
2408
+ throw invalidInput2("playerEmail", input.playerEmail, "is required");
2409
+ }
2410
+ assertUsdAmount(input.usdAmount);
2411
+ const body = {
2412
+ player_email: input.playerEmail,
2413
+ usd_amount: input.usdAmount
2414
+ };
2415
+ if (input.rail) body["rail"] = input.rail;
2416
+ if (input.successUrl) body["success_url"] = input.successUrl;
2417
+ if (input.cancelUrl) body["cancel_url"] = input.cancelUrl;
2418
+ if (input.metadata) body["metadata"] = input.metadata;
2419
+ const raw = await this.http.post(
2420
+ "/api/checkout/sessions",
2421
+ body,
2422
+ this.auth,
2423
+ { signal: opts?.signal }
2424
+ // not idempotent — never auto-retried
2425
+ );
2426
+ const checkoutUrl = requireField(raw["checkout_url"], "checkout_url", raw);
2427
+ return {
2428
+ sessionId: String(raw["session_id"] ?? ""),
2429
+ checkoutUrl,
2430
+ expiresAt: String(raw["expires_at"] ?? ""),
2431
+ expiresInSeconds: Number(raw["expires_in_seconds"] ?? 0),
2432
+ // INVO's own `session_token` field, falling back to the `checkout_url` query string
2433
+ // for a backend older than commit 856fa266. Either way a server that wants to read
2434
+ // the purchase status later does not have to parse a URL itself.
2435
+ sessionToken: sessionTokenFromCreateCheckout(raw, checkoutUrl),
2436
+ warnings: toCheckoutWarnings(raw["warnings"]),
2437
+ ...minPurchaseWarningField(raw),
2438
+ raw
2439
+ };
2440
+ }
2441
+ /**
2442
+ * Direct purchase via the rail selector. Use when you need a specific rail.
2443
+ * - rail "platform" (default): standard card. May return status "requires_action"
2444
+ * (run client-side 3-D Secure with clientSecret, then call confirmPayment).
2445
+ * - rail "game": returns status "pending_payment" + paymentUrl (redirect the browser).
2446
+ * - rail "steam": NOT a browser flow — the backend returns WRONG_RAIL_ENDPOINT.
2447
+ *
2448
+ * INVO's card fee (3.5% + $0.30 on Open, 5.5% + $0.50 on Merchant of Record, plus 1.5% of
2449
+ * the listed price (before tax) on a card issued outside the US) is charged to you, the partner. The player
2450
+ * pays the listed price (plus any tax) and receives the listed coins. Card purchases only;
2451
+ * purchases through a third-party storefront or payment rail are unaffected. Two shapes,
2452
+ * chosen by what you send:
2453
+ * - with `acknowledgedTotalUsd` (the `totalUsd` from {@link quoteCurrencyPurchase}): the
2454
+ * card is never charged more than that total, and the coins are priced off `usdAmount`.
2455
+ * An older, higher fee-inclusive total is accepted and the true, lower total charged. A
2456
+ * total below what INVO would charge now throws `409 QUOTE_STALE` (`err.isQuoteStale`);
2457
+ * nothing was charged.
2458
+ * - without it: the card is charged exactly `usdAmount`, never more.
2459
+ *
2460
+ * From 2026-10-27 a card purchase under INVO's minimum card purchase ($2.99) throws
2461
+ * `400 BELOW_CARD_MINIMUM` (`err.isBelowCardMinimum`, `err.minUsd`, `err.enforcedFrom`);
2462
+ * until then it is accepted with `minPurchaseWarning`. `AMOUNT_BELOW_FEE` is no longer
2463
+ * returned.
2464
+ *
2465
+ * A `success` result reports `processingFeeUsd` (`"0.00"`), `feeTakenFrom` (`"partner"`),
2466
+ * `partnerFeeUsd`, `internationalCardFeeUsd` (`"0.00"` on a US card or one whose country
2467
+ * is unknown; both `null` if the fee could not be booked yet, which INVO does shortly after),
2468
+ * `coinsCredited` and `chargeTotalUsd`, each as INVO sent it.
2469
+ */
2470
+ async purchaseCurrency(input, opts) {
2471
+ if (typeof input.playerEmail !== "string" || !input.playerEmail.trim()) {
2472
+ throw invalidInput2("playerEmail", input.playerEmail, "is required");
2473
+ }
2474
+ assertUsdAmount(input.usdAmount);
2475
+ if (!input.purchaseReference) {
2476
+ throw new InvoError({
2477
+ message: "purchaseReference is required (idempotency key for the purchase).",
2478
+ code: "MISSING_PURCHASE_REFERENCE",
2479
+ status: 0
2480
+ });
2481
+ }
2482
+ if (input.rail === "steam") {
2483
+ throw new InvoError({
2484
+ message: 'rail "steam" is not a /purchase-currency flow \u2014 use steamPacks() / steamInitPurchase() / steamFinalizePurchase().',
2485
+ code: "WRONG_RAIL_ENDPOINT",
2486
+ status: 0
2487
+ });
2488
+ }
2489
+ const body = {
2490
+ player_email: input.playerEmail,
2491
+ usd_amount: input.usdAmount,
2492
+ purchase_reference: input.purchaseReference
2493
+ };
2494
+ if (input.acknowledgedTotalUsd !== void 0) {
2495
+ assertAcknowledgedTotal(input.acknowledgedTotalUsd);
2496
+ body["acknowledged_total_usd"] = input.acknowledgedTotalUsd;
2497
+ }
2498
+ if (input.rail) body["rail"] = input.rail;
2499
+ if (input.paymentMethodId) body["payment_method_id"] = input.paymentMethodId;
2500
+ if (input.savedCardId) body["saved_card_id"] = input.savedCardId;
2501
+ if (input.playerName) body["player_name"] = input.playerName;
2502
+ if (input.playerPhone) body["player_phone"] = input.playerPhone;
2503
+ if (input.metadata) body["metadata"] = input.metadata;
2504
+ if (input.country) body["country"] = input.country;
2505
+ if (input.subdivision) body["subdivision"] = input.subdivision;
2506
+ const raw = await this.http.post(
2507
+ "/api/currency-purchases/purchase-currency",
2508
+ body,
2509
+ this.auth,
2510
+ { idempotent: true, signal: opts?.signal }
2511
+ // purchase_reference makes this safe to retry (backend dedupes)
2512
+ );
2513
+ return {
2514
+ status: String(raw["status"] ?? ""),
2515
+ clientSecret: raw["client_secret"],
2516
+ paymentIntentId: raw["payment_intent_id"],
2517
+ paymentUrl: raw["payment_url"],
2518
+ transactionId: raw["transaction_id"],
2519
+ orderId: raw["order_id"],
2520
+ newBalance: raw["new_balance"] ?? null,
2521
+ processingFeeUsd: optionalDecimalString(raw["processing_fee_usd"]),
2522
+ feeTakenFrom: optionalDecimalString(raw["fee_taken_from"]),
2523
+ coinsCredited: optionalDecimalString(raw["coins_credited"]),
2524
+ chargeTotalUsd: optionalDecimalString(raw["charge_total_usd"]),
2525
+ ...pricingFields(raw),
2526
+ ...receiptFields(raw),
2527
+ raw
2528
+ };
2529
+ }
2530
+ /**
2531
+ * What a card purchase of coins will cost, BEFORE charging for it. Moves no money and
2532
+ * creates nothing, so it is safe to call on every price render (`POST
2533
+ * /api/currency-purchases/quote`, authenticated by your game secret like the purchase).
2534
+ *
2535
+ * The player pays the listed price plus any tax (when you pass `country`) and receives the
2536
+ * listed coins: `totalUsd` carries no card fee, and `processingFeeUsd` is `"0.00"`. INVO's
2537
+ * card fee (3.5% + $0.30 on Open, 5.5% + $0.50 on Merchant of Record) is charged to you;
2538
+ * `partnerFeeUsd` carries it when INVO sends it. $10.00 quotes a $10.00 total, 100.00 coins
2539
+ * at the default 10 per USD, and a $0.65 partner fee on Open. Show the player `totalUsd`,
2540
+ * then send the same figure back as `acknowledgedTotalUsd` on {@link purchaseCurrency}; the
2541
+ * card is never charged more than that. `ifUnacknowledged` shows the purchase without the
2542
+ * acknowledgement (the card charged exactly `usdAmount`), or `null` when INVO sends none.
2543
+ * `minPurchaseWarning` is set while an amount under INVO's minimum card purchase is still
2544
+ * accepted. Card purchases only; purchases through a third-party storefront or payment
2545
+ * rail are unaffected.
2546
+ *
2547
+ * Refusals: `400 INVALID_INPUT` (amount missing, not above zero, or above INVO's card
2548
+ * maximum), `400 CURRENCY_NOT_CONFIGURED`, `503 RATE_UNAVAILABLE`.
2549
+ */
2550
+ async quoteCurrencyPurchase(input, opts) {
2551
+ assertUsdAmount(input.usdAmount);
2552
+ const body = {
2553
+ player_email: input.playerEmail,
2554
+ usd_amount: input.usdAmount
2555
+ };
2556
+ if (input.country) body["country"] = input.country;
2557
+ if (input.subdivision) body["subdivision"] = input.subdivision;
2558
+ const raw = await this.http.post(
2559
+ "/api/currency-purchases/quote",
2560
+ body,
2561
+ this.auth,
2562
+ { idempotent: true, signal: opts?.signal }
2563
+ // a read: it moves no money and creates nothing
2564
+ );
2565
+ return toCurrencyPurchaseQuote(raw);
2566
+ }
2567
+ /**
2568
+ * Complete the card-rail 3-D Secure step after the client finished card action.
2569
+ * `status: "success"` means the payment succeeded; tell the buyer the purchase is complete
2570
+ * only when `credited` is `true` (see {@link ConfirmPaymentResult.credited}).
2571
+ */
2572
+ async confirmPayment(input, opts) {
2573
+ const body = { payment_intent_id: input.paymentIntentId };
2574
+ if (input.orderId) body["order_id"] = input.orderId;
2575
+ const raw = await this.http.post(
2576
+ "/api/currency-purchases/confirm-payment",
2577
+ body,
2578
+ this.auth,
2579
+ { idempotent: true, signal: opts?.signal }
2580
+ // keyed by payment_intent_id — safe to retry
2581
+ );
2582
+ return {
2583
+ status: String(raw["status"] ?? ""),
2584
+ transactionId: raw["transaction_id"],
2585
+ newBalance: raw["new_balance"] ?? null,
2586
+ ...creditFields(raw),
2587
+ raw
2588
+ };
2589
+ }
2590
+ /** Fetch purchase status (order + financial summary + timeline). */
2591
+ async getOrderDetails(query2, opts) {
2592
+ if (!query2.orderId && !query2.transactionId) {
2593
+ throw new InvoError({
2594
+ message: "getOrderDetails requires an `orderId` or `transactionId`.",
2595
+ code: "INVALID_INPUT",
2596
+ status: 0
2597
+ });
2598
+ }
2599
+ const q = new URLSearchParams();
2600
+ if (query2.orderId) q.set("order_id", query2.orderId);
2601
+ if (query2.transactionId) q.set("transaction_id", query2.transactionId);
2602
+ const raw = await this.http.get(
2603
+ `/api/currency-purchases/order-details?${q.toString()}`,
2604
+ this.auth,
2605
+ { signal: opts?.signal }
2606
+ );
2607
+ return toOrderDetails(raw);
2608
+ }
2609
+ /**
2610
+ * The Steam packs INVO sells, and what each contains for one player.
2611
+ *
2612
+ * The PRICE is identical for every player and is INVO's to set; the
2613
+ * `currencyAmount` varies by country. Render it verbatim — never compute
2614
+ * currency from the sticker price (VAT and the storefront's revenue share
2615
+ * come out of the sticker before currency is derived), and never cache one
2616
+ * answer for all players. Without `steamid` the quote assumes no VAT — the
2617
+ * most any pack yields; the purchase itself always re-derives.
2618
+ *
2619
+ * Refusals: `err.isSteamRailNotEntitled` (403). A missing Steam
2620
+ * registration does NOT refuse here — packs deliberately answers with the
2621
+ * no-VAT catalogue and lets the PURCHASE be what refuses; the only 503 is
2622
+ * the rail being disabled platform-wide, whose body carries no error code.
2623
+ */
2624
+ async steamPacks(query2, opts) {
2625
+ const qs = query2?.steamid ? `?steamid=${encodeURIComponent(query2.steamid)}` : "";
2626
+ const raw = await this.http.get(
2627
+ `/api/currency-purchases/steam/packs${qs}`,
2628
+ this.auth,
2629
+ { signal: opts?.signal }
2630
+ );
2631
+ const packs = Array.isArray(raw["packs"]) ? raw["packs"] : [];
2632
+ return {
2633
+ packs: packs.map((p) => ({
2634
+ packId: String(p["pack_id"] ?? ""),
2635
+ label: String(p["label"] ?? ""),
2636
+ priceUsd: String(p["price_usd"] ?? ""),
2637
+ currencyAmount: String(p["currency_amount"] ?? "")
2638
+ })),
2639
+ country: raw["country"] ?? null,
2640
+ vatRatePct: String(raw["vat_rate_pct"] ?? "0"),
2641
+ raw
2642
+ };
2643
+ }
2644
+ /**
2645
+ * Start a Steam micro-transaction. The player then authorizes — in the Steam
2646
+ * overlay (`usersession: "client"`, the default) or on Steam's hosted
2647
+ * checkout page (`usersession: "web"`, returned as `steamCheckoutUrl`; open
2648
+ * it as a TOP-LEVEL tab, never an iframe; requires `playerIp`). After
2649
+ * authorization, call {@link steamFinalizePurchase} with the returned
2650
+ * `orderId`.
2651
+ *
2652
+ * Idempotent on `purchaseReference`, with one wire subtlety: a resend does
2653
+ * not replay the original body — it answers **409 `DUPLICATE_REQUEST`**
2654
+ * whose body carries the existing `order_id` (read it from `err.body`).
2655
+ * Never double-charges. Retries — including manual retries after a 409 —
2656
+ * MUST reuse the reference; a fresh one is a second intended purchase. For
2657
+ * WEB sessions, persist `steamCheckoutUrl` from the first success: the 409
2658
+ * body does not repeat it.
2659
+ *
2660
+ * Refusals worth branching on: `err.isPartnerCreditUnavailable` (409, the
2661
+ * studio's settlement float cannot cover it — plain failure toast, do NOT
2662
+ * hot-poll), `err.isPartnerRailSuspended` (409, terminal from the game's
2663
+ * seat), `err.isPartnerBillingNotSetUp` (409), `err.isUnknownSteamPack`
2664
+ * (400 — re-fetch `steamPacks()`), `err.isSteamNotConfigured` (503),
2665
+ * `err.isSteamRailNotEntitled` (403), `err.isMissingPlayerIp` (400),
2666
+ * `err.isDuplicateRequest` (409).
2667
+ */
2668
+ async steamInitPurchase(input, opts) {
2669
+ if (typeof input.playerEmail !== "string" || !input.playerEmail.trim()) {
2670
+ throw invalidInput2("playerEmail", input.playerEmail, "is required");
2671
+ }
2672
+ if (!/^[0-9]+$/.test(String(input.steamid ?? ""))) {
2673
+ throw invalidInput2("steamid", input.steamid, "must be the player's numeric 64-bit Steam id");
2674
+ }
2675
+ if (!input.packId) throw invalidInput2("packId", input.packId, "is required \u2014 fetch steamPacks()");
2676
+ if (!input.purchaseReference) {
2677
+ throw new InvoError({
2678
+ message: "purchaseReference is required (idempotency key, unique per intended purchase).",
2679
+ code: "MISSING_PURCHASE_REFERENCE",
2680
+ status: 0
2681
+ });
2682
+ }
2683
+ if (input.usersession === "web" && !input.playerIp) {
2684
+ throw new InvoError({
2685
+ message: `playerIp is required when usersession is "web" \u2014 the PLAYER's IP, not your server's.`,
2686
+ code: "MISSING_PLAYER_IP",
2687
+ status: 0
2688
+ });
2689
+ }
2690
+ const body = {
2691
+ player_email: input.playerEmail,
2692
+ steamid: String(input.steamid),
2693
+ pack_id: input.packId,
2694
+ purchase_reference: input.purchaseReference
2695
+ };
2696
+ if (input.usersession) body["usersession"] = input.usersession;
2697
+ if (input.playerIp) body["player_ip"] = input.playerIp;
2698
+ if (input.playerName) body["player_name"] = input.playerName;
2699
+ if (input.metadata) body["metadata"] = input.metadata;
2700
+ const raw = await this.http.post(
2701
+ "/api/currency-purchases/steam/init-purchase",
2702
+ body,
2703
+ this.auth,
2704
+ { idempotent: true, signal: opts?.signal }
2705
+ // purchase_reference dedupes server-side
2706
+ );
2707
+ return {
2708
+ status: String(raw["status"] ?? ""),
2709
+ orderId: String(raw["order_id"] ?? ""),
2710
+ steamTransid: raw["steam_transid"],
2711
+ steamCheckoutUrl: raw["steam_checkout_url"] ?? void 0,
2712
+ packId: raw["pack_id"],
2713
+ chargedUsd: raw["charged_usd"],
2714
+ currencyAmount: raw["currency_amount"],
2715
+ raw
2716
+ };
2717
+ }
2718
+ /**
2719
+ * Capture an authorized Steam transaction and credit the player.
2720
+ *
2721
+ * Idempotent: a retry or duplicate returns `alreadyProcessed: true` and
2722
+ * never credits twice. Poller taxonomy — NOT every 409 means "not yet":
2723
+ *
2724
+ * - `err.isSteamAuthorizationPending` — the player has not approved yet
2725
+ * (Steam still reports Init). Wait / poll again. THE NORMAL STATE.
2726
+ * - `err.isSteamAuthorizationDead` — Failed / Refunded / Chargedback.
2727
+ * STOP polling; no later call can succeed.
2728
+ * - `err.isSteamAppChanged` (409) — the title's registration changed under
2729
+ * the order. Terminal for this order.
2730
+ * - 502 / 503 — transient; retry.
2731
+ *
2732
+ * A missed finalize is not a lost credit: INVO's reconciler independently
2733
+ * detects the authorized transaction and credits, on a delay.
2734
+ */
2735
+ async steamFinalizePurchase(input, opts) {
2736
+ if (!input.orderId) throw invalidInput2("orderId", input.orderId, "is required (from steamInitPurchase)");
2737
+ const raw = await this.http.post(
2738
+ "/api/currency-purchases/steam/finalize-purchase",
2739
+ { order_id: input.orderId },
2740
+ this.auth,
2741
+ { idempotent: true, signal: opts?.signal }
2742
+ // backend replays a completed order
2743
+ );
2744
+ return {
2745
+ status: String(raw["status"] ?? ""),
2746
+ orderId: raw["order_id"] ?? void 0,
2747
+ transactionId: raw["transaction_id"] ?? void 0,
2748
+ newBalance: raw["new_balance"] ?? null,
2749
+ alreadyProcessed: raw["already_processed"] === true,
2750
+ ...creditFields(raw),
2751
+ raw
2752
+ };
2753
+ }
2754
+ /**
2755
+ * Buy an in-game item by SPENDING the player's existing game currency (§4.8).
2756
+ * No real money, no payment rail, no passkey — it's a balance debit, authenticated
2757
+ * server-side by the game secret. Idempotent on clientRequestId (a duplicate throws
2758
+ * a 409 InvoError; check err.isDuplicateRequest). Insufficient balance throws a 400
2759
+ * (err.isInsufficientBalance; required_amount/current_balance on err.body). Grant the
2760
+ * item to your inventory off the `item.purchased` webhook, not just this response.
2761
+ */
2762
+ async purchaseItem(input, opts) {
2763
+ const required = [
2764
+ ["clientRequestId", input.clientRequestId],
2765
+ ["playerEmail", input.playerEmail],
2766
+ ["playerName", input.playerName],
2767
+ ["itemId", input.itemId],
2768
+ ["itemName", input.itemName]
2769
+ ];
2770
+ for (const [k, v] of required) {
2771
+ if (typeof v !== "string" || !v.trim()) throw invalidInput2(k, v, "is required");
2772
+ }
2773
+ if (!Number.isInteger(input.itemQuantity) || input.itemQuantity < 1 || input.itemQuantity > 1e3) {
2774
+ throw invalidInput2("itemQuantity", input.itemQuantity, "must be an integer 1..1000");
2775
+ }
2776
+ const unit = parseMoney(input.unitPrice, MAX_ITEM_PRICE, "unitPrice");
2777
+ const total = parseMoney(input.totalPrice, MAX_ITEM_PRICE, "totalPrice");
2778
+ const expectedCents = Math.round(unit * input.itemQuantity * 100);
2779
+ const totalCents = Math.round(total * 100);
2780
+ if (Math.abs(totalCents - expectedCents) > 1) {
2781
+ throw invalidInput2(
2782
+ "totalPrice",
2783
+ input.totalPrice,
2784
+ `must equal unitPrice \xD7 itemQuantity (\xB10.01): ${unit} \xD7 ${input.itemQuantity}`
2785
+ );
2786
+ }
2787
+ const body = {
2788
+ client_request_id: input.clientRequestId,
2789
+ player_email: input.playerEmail,
2790
+ player_name: input.playerName,
2791
+ item_id: input.itemId,
2792
+ item_name: input.itemName,
2793
+ item_quantity: input.itemQuantity,
2794
+ unit_price: input.unitPrice,
2795
+ total_price: input.totalPrice
2796
+ };
2797
+ if (input.playerPhone) body["player_phone"] = input.playerPhone;
2798
+ if (input.itemDescription) body["item_description"] = input.itemDescription;
2799
+ if (input.itemCategory) body["item_category"] = input.itemCategory;
2800
+ const raw = await this.http.post(
2801
+ "/api/item-purchases/purchase-item",
2802
+ body,
2803
+ this.auth,
2804
+ { idempotent: true, signal: opts?.signal }
2805
+ // client_request_id makes this safe to retry (dup → 409)
2806
+ );
2807
+ return {
2808
+ status: String(raw["status"] ?? ""),
2809
+ transactionId: requireField(raw["transaction_id"], "transaction_id", raw),
2810
+ orderId: requireField(raw["order_id"], "order_id", raw),
2811
+ newBalance: raw["new_balance"] ?? null,
2812
+ previousBalance: raw["previous_balance"] ?? null,
2813
+ currencyName: String(raw["currency_name"] ?? ""),
2814
+ financialBreakdown: raw["financial_breakdown"],
2815
+ raw
2816
+ };
2817
+ }
2818
+ /** Paginated item-purchase history for a player (§4.8 companion read). */
2819
+ async getItemPurchaseHistory(query2, opts) {
2820
+ if (typeof query2.playerEmail !== "string" || !query2.playerEmail.trim()) {
2821
+ throw invalidInput2("playerEmail", query2.playerEmail, "is required");
2822
+ }
2823
+ const q = new URLSearchParams();
2824
+ q.set("player_email", query2.playerEmail);
2825
+ if (query2.limit != null) q.set("limit", String(query2.limit));
2826
+ if (query2.offset != null) q.set("offset", String(query2.offset));
2827
+ const raw = await this.http.get(
2828
+ `/api/item-purchases/player-purchase-history?${q.toString()}`,
2829
+ this.auth,
2830
+ { signal: opts?.signal }
2831
+ );
2832
+ return {
2833
+ history: Array.isArray(raw["item_purchase_history"]) ? raw["item_purchase_history"] : [],
2834
+ pagination: raw["pagination"] ?? {},
2835
+ raw
2836
+ };
2837
+ }
2838
+ /** Look up one item order by EXACTLY ONE of orderId | transactionId | clientRequestId
2839
+ * (§4.8). Use clientRequestId for saga/recovery: "did this purchase actually complete?" */
2840
+ async getItemOrderDetails(query2, opts) {
2841
+ const provided = [query2.orderId, query2.transactionId, query2.clientRequestId].filter(
2842
+ (v) => typeof v === "string" && v.trim()
2843
+ );
2844
+ if (provided.length !== 1) {
2845
+ throw new InvoError({
2846
+ message: "getItemOrderDetails requires EXACTLY ONE of orderId, transactionId, or clientRequestId.",
2847
+ code: "INVALID_INPUT",
2848
+ status: 0
2849
+ });
2850
+ }
2851
+ const q = new URLSearchParams();
2852
+ if (query2.orderId) q.set("order_id", query2.orderId);
2853
+ if (query2.transactionId) q.set("transaction_id", query2.transactionId);
2854
+ if (query2.clientRequestId) q.set("client_request_id", query2.clientRequestId);
2855
+ const raw = await this.http.get(
2856
+ `/api/item-purchases/order-details?${q.toString()}`,
2857
+ this.auth,
2858
+ { signal: opts?.signal }
2859
+ );
2860
+ return toOrderDetails(raw);
2861
+ }
2862
+ /**
2863
+ * Async iterator over a player's entire item-purchase history — pages through
2864
+ * `getItemPurchaseHistory` (limit/offset) until exhausted, yielding one row at a time.
2865
+ *
2866
+ * ```ts
2867
+ * for await (const row of invo.iterateItemPurchaseHistory({ playerEmail })) { … }
2868
+ * ```
2869
+ */
2870
+ async *iterateItemPurchaseHistory(query2, opts) {
2871
+ if (typeof query2.playerEmail !== "string" || !query2.playerEmail.trim()) {
2872
+ throw invalidInput2("playerEmail", query2.playerEmail, "is required");
2873
+ }
2874
+ const pageSize = typeof query2.pageSize === "number" && query2.pageSize > 0 ? Math.floor(query2.pageSize) : 50;
2875
+ let yielded = 0;
2876
+ for (let offset = 0; ; offset += pageSize) {
2877
+ const { history, pagination } = await this.getItemPurchaseHistory(
2878
+ { playerEmail: query2.playerEmail, limit: pageSize, offset },
2879
+ opts
2880
+ );
2881
+ if (history.length === 0) return;
2882
+ for (const row of history) yield row;
2883
+ yielded += history.length;
2884
+ if (history.length < pageSize) return;
2885
+ const p = pagination;
2886
+ const total = Number(p?.["total_count"] ?? p?.["total"]);
2887
+ if (Number.isFinite(total) && yielded >= total) return;
2888
+ }
2889
+ }
2890
+ /**
2891
+ * One merged, newest-first list of a player's money activity in your game, one page at a
2892
+ * time (`GET /api/sdk/players/activity`): currency purchases, item purchases, Platform
2893
+ * Commerce purchases, sends and transfers, in both directions. Only rows where your game
2894
+ * is a party through this player are listed; the other side of a cross-game send or
2895
+ * transfer is named by game only (`counterpartyGame`).
2896
+ *
2897
+ * An inbound (`direction: "in"`) send or transfer is listed as soon as it names this
2898
+ * player, in ANY status (awaiting collection, completed, expired, refunded): read `status`
2899
+ * and `statusDetail` before treating it as credited. `direction` is `"in"` / `"out"` /
2900
+ * `"self"`, not the `"incoming"` / `"outgoing"` of the per-type history reads.
2901
+ *
2902
+ * Pass `nextCursor` back as `cursor` (with the same `types`) for the next page; it is
2903
+ * `null` on the last one. `iteratePlayerActivity` walks every page.
2904
+ *
2905
+ * Refusals (`InvoError`): a blank `playerEmail` or a bad `limit` / `cursor` / `types`
2906
+ * throws `INVALID_INPUT` before the network; `400 INVALID_INPUT` (for example an unknown
2907
+ * kind in `types`), `400 INVALID_CURSOR` (a cursor from another player or other `types`),
2908
+ * `401 INVALID_GAME_SECRET`, `404 PLAYER_NOT_FOUND` (`err.isPlayerNotFound`),
2909
+ * `500 PLAYER_ACTIVITY_FAILED` (retry later), `429` (back off; `err.retryAfter`). A GET, so
2910
+ * transient failures are retried automatically.
2911
+ */
2912
+ async getPlayerActivity(query2, opts) {
2913
+ if (typeof query2?.playerEmail !== "string" || !query2.playerEmail.trim()) {
2914
+ throw invalidInput2("playerEmail", query2?.playerEmail, "is required");
2915
+ }
2916
+ assertPageLimit(query2.limit);
2917
+ assertCursor(query2.cursor);
2918
+ if (query2.types !== void 0) {
2919
+ if (!Array.isArray(query2.types) || query2.types.some((t) => typeof t !== "string" || !t.trim() || t.includes(","))) {
2920
+ throw invalidInput2("types", query2.types, "must be an array of activity kinds");
2921
+ }
2922
+ }
2923
+ const q = new URLSearchParams();
2924
+ q.set("player_email", query2.playerEmail.trim());
2925
+ if (query2.limit !== void 0) q.set("limit", String(query2.limit));
2926
+ if (query2.cursor !== void 0) q.set("cursor", query2.cursor);
2927
+ if (query2.types && query2.types.length > 0) {
2928
+ q.set("types", query2.types.map((t) => t.trim()).join(","));
2929
+ }
2930
+ const raw = await this.http.get(
2931
+ `/api/sdk/players/activity?${q.toString()}`,
2932
+ this.auth,
2933
+ { signal: opts?.signal }
2934
+ );
2935
+ const activity = Array.isArray(raw["activity"]) ? raw["activity"].map(toPlayerActivityEntry) : [];
2936
+ const nextCursor = nextCursorOf(raw);
2937
+ return {
2938
+ playerEmail: String(raw["player_email"] ?? query2.playerEmail.trim()),
2939
+ gameId: String(raw["game_id"] ?? ""),
2940
+ types: Array.isArray(raw["types"]) ? raw["types"].map(String) : [],
2941
+ activity,
2942
+ limit: typeof raw["limit"] === "number" ? raw["limit"] : activity.length,
2943
+ hasMore: raw["has_more"] === true && nextCursor !== null,
2944
+ nextCursor,
2945
+ raw
2946
+ };
2947
+ }
2948
+ /**
2949
+ * Async iterator over a player's ENTIRE activity, newest first: pages through
2950
+ * `getPlayerActivity` by `nextCursor`, yielding one row at a time.
2951
+ *
2952
+ * ```ts
2953
+ * for await (const row of invo.iteratePlayerActivity({ playerEmail, types: ["send", "transfer"] })) { … }
2954
+ * ```
2955
+ */
2956
+ async *iteratePlayerActivity(query2, opts) {
2957
+ let cursor;
2958
+ const seen = /* @__PURE__ */ new Set();
2959
+ for (; ; ) {
2960
+ const page = await this.getPlayerActivity(
2961
+ { playerEmail: query2.playerEmail, types: query2.types, limit: query2.pageSize, cursor },
2962
+ opts
2963
+ );
2964
+ for (const row of page.activity) yield row;
2965
+ if (!page.hasMore || page.nextCursor === null || seen.has(page.nextCursor)) return;
2966
+ seen.add(page.nextCursor);
2967
+ cursor = page.nextCursor;
2968
+ }
2969
+ }
2970
+ /**
2971
+ * Read a player's currency balances by email (server-side, game-secret).
2972
+ *
2973
+ * NOTE: lookup is by EMAIL only. There is no by-id balance route on the backend
2974
+ * (`playerId` is a per-game internal id), so passing `playerId` throws — use the
2975
+ * browser `InvoClient.getBalance()` (token-authed, identity from the token) for a
2976
+ * client-side read, or `playerEmail` here server-side.
2977
+ */
2978
+ async getPlayerBalance(query2, opts) {
2979
+ let path;
2980
+ if (typeof query2.playerEmail === "string" && query2.playerEmail.trim()) {
2981
+ path = `/api/player-balances/player/by-email/${encodeURIComponent(query2.playerEmail)}`;
2982
+ } else if (query2.playerId != null && String(query2.playerId).trim()) {
2983
+ throw new InvoError({
2984
+ message: "getPlayerBalance is by playerEmail only \u2014 there is no by-id balance route. Use InvoClient.getBalance() client-side (player token), or pass playerEmail here.",
2985
+ code: "INVALID_INPUT",
2986
+ status: 0
2987
+ });
2988
+ } else {
2989
+ throw new InvoError({
2990
+ message: "getPlayerBalance requires a playerEmail.",
2991
+ code: "INVALID_INPUT",
2992
+ status: 0
2993
+ });
2994
+ }
2995
+ const raw = await this.http.get(path, this.auth, { signal: opts?.signal });
2996
+ const rows = Array.isArray(raw["balances"]) ? raw["balances"] : [];
2997
+ return {
2998
+ player: raw["player"] ?? {},
2999
+ balances: rows.map(toCurrencyBalance),
3000
+ summary: raw["summary"] ?? {},
3001
+ raw
3002
+ };
3003
+ }
3004
+ /**
3005
+ * One player's loyalty cards, read by your SERVER with the game secret: the same cards
3006
+ * the player sees through `InvoClient.getMyRewards()`, for the player with this email in
3007
+ * your game. Each step carries `state` and `progress` (`{ current, target }`, or `null`
3008
+ * when the number could not be read this time: render `state` alone then). Rewards carry
3009
+ * their masked code only; a code is never returned here.
3010
+ *
3011
+ * Refusals (all `InvoError`): a blank email throws `INVALID_INPUT` before the network;
3012
+ * `400 INVALID_PLAYER_EMAIL` (`err.isInvalidPlayerEmail`), `401 INVALID_GAME_SECRET` for a missing or wrong key, or
3013
+ * a per-channel key (this read takes the game's server secret only), `404 PLAYER_NOT_FOUND`
3014
+ * (`err.isPlayerNotFound`: no player with this email in this game), `429` (back off;
3015
+ * `err.retryAfter`). Also `409 NO_TENANT` (the game is not set up for loyalty), `503`
3016
+ * (temporarily unavailable) and `502` / `504` (the loyalty service could not be reached or
3017
+ * timed out): retry later. A GET, so transient failures are retried automatically.
3018
+ */
3019
+ async getPlayerRewards(playerEmail, opts) {
3020
+ if (typeof playerEmail !== "string" || !playerEmail.trim()) {
3021
+ throw invalidInput2("playerEmail", playerEmail, "is required");
3022
+ }
3023
+ const raw = await this.http.get(
3024
+ `/api/sdk/loyalty/players/rewards?player_email=${encodeURIComponent(playerEmail.trim())}`,
3025
+ this.auth,
3026
+ { signal: opts?.signal }
3027
+ );
3028
+ return toLoyaltyCardsResult(raw);
3029
+ }
3030
+ /**
3031
+ * Report a gameplay event for one player to INVO's loyalty engine from your SERVER
3032
+ * (`POST /api/sdk/loyalty/server-events`, game secret). Server-reported events are the
3033
+ * ones trusted for rewards. Use it for sessions, level milestones and custom events
3034
+ * registered in the console (see {@link GameEventType}); currency steps are tracked by
3035
+ * INVO itself and are never reported.
3036
+ *
3037
+ * Idempotent on `eventId`: pass your own UUID, or let the SDK generate one, and reuse the
3038
+ * returned `eventId` if you retry. Transient failures (429, 5xx) are retried with it.
3039
+ *
3040
+ * Refusals (all `InvoError`): `INVALID_INPUT` before the network for a non-`game.*` type,
3041
+ * a malformed `eventId`, an `occurredAt` without a timezone or a non-object payload;
3042
+ * `400 RESERVED_EVENT_TYPE` / `EVENT_TYPE_NOT_ALLOWED`; `401 INVALID_GAME_SECRET`;
3043
+ * `404 PLAYER_NOT_FOUND` (`err.isPlayerNotFound`); `422 validation_failed` (for example an
3044
+ * unregistered `event_name`).
3045
+ */
3046
+ async reportGameEvent(input, opts) {
3047
+ if (!input || typeof input.playerEmail !== "string" || !input.playerEmail.trim()) {
3048
+ throw invalidInput2("playerEmail", input?.playerEmail, "is required");
3049
+ }
3050
+ const { body, eventId } = buildGameEventBody(input);
3051
+ body["player_email"] = input.playerEmail.trim();
3052
+ const raw = await this.http.post(
3053
+ "/api/sdk/loyalty/server-events",
3054
+ body,
3055
+ this.auth,
3056
+ // event_id makes this safe to retry: INVO counts one event per id.
3057
+ { idempotent: true, signal: opts?.signal }
3058
+ );
3059
+ return toReportGameEventResult(raw ?? {}, eventId);
3060
+ }
3061
+ /**
3062
+ * List LIVE, unclaimed inbound sends/transfers addressed to a player at YOUR game —
3063
+ * the source of truth for a "you have X to collect" badge. Pass the player's email
3064
+ * or phone. Match `toPhone` to the logged-in player (don't require `toIdentityId`,
3065
+ * which is null when the phone maps to more than one of your players). Pairs with the
3066
+ * `transfer.claim_pending` webhook (the webhook is the wake-up; this is the list).
3067
+ */
3068
+ async getInboundPending(query2, opts) {
3069
+ const hasEmail = typeof query2.playerEmail === "string" && query2.playerEmail.trim();
3070
+ const hasPhone = typeof query2.playerPhone === "string" && query2.playerPhone.trim();
3071
+ if (!hasEmail && !hasPhone) {
3072
+ throw invalidInput2("query", query2, "requires a playerEmail or playerPhone");
3073
+ }
3074
+ const q = new URLSearchParams();
3075
+ if (hasEmail) q.set("player_email", query2.playerEmail.trim());
3076
+ if (hasPhone) q.set("player_phone", query2.playerPhone.trim());
3077
+ const raw = await this.http.get(
3078
+ `/api/transfers/inbound-pending?${q.toString()}`,
3079
+ this.auth,
3080
+ { signal: opts?.signal }
3081
+ );
3082
+ const rows = Array.isArray(raw["inbound_pending"]) ? raw["inbound_pending"] : [];
3083
+ return { inboundPending: rows.map(toInboundPendingItem), raw };
3084
+ }
3085
+ /**
3086
+ * Look up a player's linked wallet identities (SERVER-only, game-secret). Game-scoped:
3087
+ * returns wallet members that also have a Player row on this game. Provide a `playerEmail`
3088
+ * or `playerPhone` (phone wins if both). No in-game match (backend 404) returns
3089
+ * `notFound: true` with empty `emails` — not an error.
3090
+ *
3091
+ * ⚠️ Returns first-party PII (emails/phones) — never expose this to the browser.
3092
+ */
3093
+ async getLinkedIdentities(query2, opts) {
3094
+ const phone = typeof query2.playerPhone === "string" && query2.playerPhone.trim() ? query2.playerPhone.trim() : "";
3095
+ const email = typeof query2.playerEmail === "string" && query2.playerEmail.trim() ? query2.playerEmail.trim() : "";
3096
+ if (!phone && !email) {
3097
+ throw invalidInput2("query", query2, "requires a playerEmail or playerPhone");
3098
+ }
3099
+ const q = new URLSearchParams();
3100
+ if (phone) q.set("player_phone", phone);
3101
+ else q.set("player_email", email);
3102
+ let raw;
3103
+ try {
3104
+ raw = await this.http.get(
3105
+ `/api/wallet/identities?${q.toString()}`,
3106
+ this.auth,
3107
+ { signal: opts?.signal }
3108
+ );
3109
+ } catch (e) {
3110
+ if (e instanceof InvoError && e.status === 404) {
3111
+ const raw404 = e.body && typeof e.body === "object" ? e.body : {};
3112
+ return { walletUserId: null, primaryEmail: "", primaryPhone: "", isMinor: false, emails: [], notFound: true, raw: raw404 };
3113
+ }
3114
+ throw e;
3115
+ }
3116
+ const emails = Array.isArray(raw["emails"]) ? raw["emails"].map(toLinkedEmail) : [];
3117
+ return {
3118
+ walletUserId: raw["wallet_user_id"] ?? null,
3119
+ primaryEmail: String(raw["primary_email"] ?? ""),
3120
+ primaryPhone: String(raw["primary_phone"] ?? ""),
3121
+ isMinor: raw["is_minor"] === true,
3122
+ emails,
3123
+ notFound: false,
3124
+ raw
3125
+ };
3126
+ }
3127
+ /**
3128
+ * Complete a TRANSFER's SMS-PIN step — the LAST-RESORT fallback for a sender who has
3129
+ * no passkey.
3130
+ *
3131
+ * @deprecated The SMS-PIN path is being phased out and a future major version will
3132
+ * remove this method. **Passkeys are the gold standard for authorizing money movement**
3133
+ * — an SMS PIN is a shared secret on a channel exposed to SIM swap and interception,
3134
+ * and it is not a peer of a WebAuthn assertion. When `initiate*` returns
3135
+ * `verificationMethod: "sms"` it is telling you the sender has no passkey: prompt
3136
+ * `InvoClient.enrollPasskey()` and then approve with
3137
+ * `InvoClient.approveTransfer(transactionId)`. Reach for this method only when the user
3138
+ * cannot enroll (unsupported device) or declines. Still fully functional — this
3139
+ * annotation changes documentation only, not behavior.
3140
+ *
3141
+ * NOT idempotent — each attempt is counted server-side, so this is never auto-retried.
3142
+ * A bad PIN throws a 400 InvoError carrying `attempts_remaining` on `err.body`; a
3143
+ * blocked recipient throws 429 (`sms_verification_blocked`).
3144
+ */
3145
+ async verifySmsTransfer(transactionId, smsPin, opts) {
3146
+ if (typeof transactionId !== "string" || !transactionId.trim()) {
3147
+ throw invalidInput2("transactionId", transactionId, "is required");
3148
+ }
3149
+ if (typeof smsPin !== "string" || !smsPin.trim()) {
3150
+ throw invalidInput2("smsPin", smsPin, "is required");
3151
+ }
3152
+ const raw = await this.http.post(
3153
+ "/api/transfers/verify-sms",
3154
+ { transaction_id: transactionId, sms_pin: smsPin },
3155
+ this.auth,
3156
+ { signal: opts?.signal }
3157
+ // NOT idempotent — attempts are counted; never auto-retried
3158
+ );
3159
+ return toSmsVerifyResult(raw);
3160
+ }
3161
+ /**
3162
+ * Complete a SEND's SMS-PIN step — the LAST-RESORT fallback for a sender who has no
3163
+ * passkey. See {@link verifySmsTransfer}.
3164
+ *
3165
+ * @deprecated The SMS-PIN path is being phased out and a future major version will
3166
+ * remove this method. Prompt `InvoClient.enrollPasskey()` and approve with
3167
+ * `InvoClient.approveSend(transactionId)` instead; use this only when the user cannot
3168
+ * enroll or declines. Documentation only — behavior is unchanged.
3169
+ */
3170
+ async verifySmsSend(transactionId, smsPin, opts) {
3171
+ if (typeof transactionId !== "string" || !transactionId.trim()) {
3172
+ throw invalidInput2("transactionId", transactionId, "is required");
3173
+ }
3174
+ if (typeof smsPin !== "string" || !smsPin.trim()) {
3175
+ throw invalidInput2("smsPin", smsPin, "is required");
3176
+ }
3177
+ const raw = await this.http.post(
3178
+ "/api/currency-sends/verify-sms",
3179
+ { transaction_id: transactionId, sms_pin: smsPin },
3180
+ this.auth,
3181
+ { signal: opts?.signal }
3182
+ // NOT idempotent — attempts are counted; never auto-retried
3183
+ );
3184
+ return toSmsVerifyResult(raw);
3185
+ }
3186
+ /**
3187
+ * Claim an inbound TRANSFER by its claim code, crediting one of this game's currencies.
3188
+ * NOT idempotent. A 200 may come back as `needsAccountSelection` (the recipient phone
3189
+ * maps to >1 of your players) — inspect `result.candidates` and re-submit with
3190
+ * `targetPlayerId`. Errors surface via InvoError (404 unknown code, 403 phone mismatch,
3191
+ * 400 not-claimable/expired/wrong-value, 409 `err.isPhoneShareApprovalRequired`, …).
3192
+ */
3193
+ async claimTransfer(input, opts) {
3194
+ const body = {
3195
+ claim_code: input.claimCode,
3196
+ target_player_name: input.targetPlayerName,
3197
+ target_player_email: input.targetPlayerEmail,
3198
+ target_player_phone: input.targetPlayerPhone,
3199
+ target_currency_id: input.targetCurrencyId
3200
+ };
3201
+ if (input.targetPlayerId != null) body["target_player_id"] = input.targetPlayerId;
3202
+ const raw = await this.http.post(
3203
+ "/api/transfers/claim-transfer",
3204
+ body,
3205
+ this.auth,
3206
+ { signal: opts?.signal }
3207
+ // NOT idempotent — never auto-retried
3208
+ );
3209
+ return toClaimResult(raw);
3210
+ }
3211
+ /**
3212
+ * Claim an inbound SEND by its claim code. NOT idempotent. May return
3213
+ * `needsAccountSelection` (multi-account phone) — re-submit with `receiverPlayerId`.
3214
+ * See claimTransfer for the error surface.
3215
+ */
3216
+ async claimCurrency(input, opts) {
3217
+ const body = {
3218
+ claim_code: input.claimCode,
3219
+ receiver_player_name: input.receiverPlayerName,
3220
+ receiver_player_email: input.receiverPlayerEmail,
3221
+ receiver_player_phone: input.receiverPlayerPhone
3222
+ };
3223
+ if (input.receiverPlayerId != null) body["receiver_player_id"] = input.receiverPlayerId;
3224
+ const raw = await this.http.post(
3225
+ "/api/currency-sends/claim-currency",
3226
+ body,
3227
+ this.auth,
3228
+ { signal: opts?.signal }
3229
+ // NOT idempotent — never auto-retried
3230
+ );
3231
+ return toClaimResult(raw);
3232
+ }
3233
+ /** Read a TRANSFER's status (verification_state + amounts + destination). */
3234
+ async getTransferStatus(transactionId, opts) {
3235
+ if (typeof transactionId !== "string" || !transactionId.trim()) {
3236
+ throw invalidInput2("transactionId", transactionId, "is required");
3237
+ }
3238
+ const raw = await this.http.get(
3239
+ `/api/transfers/${encodeURIComponent(transactionId)}/status`,
3240
+ this.auth,
3241
+ { signal: opts?.signal }
3242
+ );
3243
+ return toTransactionStatus(raw);
3244
+ }
3245
+ /** Read a SEND's status (adds fees, game names, claim_info, … on `raw`). */
3246
+ async getSendStatus(transactionId, opts) {
3247
+ if (typeof transactionId !== "string" || !transactionId.trim()) {
3248
+ throw invalidInput2("transactionId", transactionId, "is required");
3249
+ }
3250
+ const raw = await this.http.get(
3251
+ `/api/currency-sends/${encodeURIComponent(transactionId)}/status`,
3252
+ this.auth,
3253
+ { signal: opts?.signal }
3254
+ );
3255
+ return toTransactionStatus(raw);
3256
+ }
3257
+ /**
3258
+ * Poll a transaction's guardian approval status (minor/guardian flow). The retry
3259
+ * layer already retries the 503 (`{status:"unavailable"}`) for this idempotent GET;
3260
+ * a missing approval throws a 404 InvoError (`{status:"not_found"}`).
3261
+ */
3262
+ async getGuardianApprovalStatus(transactionId, opts) {
3263
+ if (typeof transactionId !== "string" || !transactionId.trim()) {
3264
+ throw invalidInput2("transactionId", transactionId, "is required");
3265
+ }
3266
+ const raw = await this.http.get(
3267
+ `/api/transactions/${encodeURIComponent(transactionId)}/approval-status`,
3268
+ this.auth,
3269
+ { signal: opts?.signal }
3270
+ );
3271
+ return toGuardianApprovalStatus(raw);
3272
+ }
3273
+ /**
3274
+ * List the games/tenants a player can send/transfer to FROM `sourceGameId`, with
3275
+ * display metadata inline (name, icon, currency, min/max limits) — one call, no
3276
+ * per-game lookup. SERVER variant (game-secret) of the browser `InvoClient.getDestinations`;
3277
+ * the source game is passed explicitly rather than inferred from a player token. Rows
3278
+ * share the browser shape. Idempotent (a POST read — safe to retry).
3279
+ */
3280
+ async getDestinations(query2, opts) {
3281
+ if (query2.sourceGameId == null || String(query2.sourceGameId).trim() === "") {
3282
+ throw invalidInput2("sourceGameId", query2.sourceGameId, "is required");
3283
+ }
3284
+ const direction = query2.direction ?? "transfer";
3285
+ const path = direction === "send" ? "/api/currency-sends/available-destinations" : "/api/transfers/available-destinations";
3286
+ const raw = await this.http.post(
3287
+ path,
3288
+ { source_game_id: query2.sourceGameId },
3289
+ this.auth,
3290
+ { idempotent: true, signal: opts?.signal }
3291
+ // a POST read — no side effect, safe to retry
3292
+ );
3293
+ return toDestinationsResult(raw, direction);
3294
+ }
3295
+ /**
3296
+ * Phone-share OTP handshake — resolves a 409 `PHONE_SHARE_APPROVAL_REQUIRED`.
3297
+ *
3298
+ * These three endpoints are UNAUTHENTICATED (phone-owner-driven: no game secret,
3299
+ * no player token) — a partner backend relays the handshake. The triggering 409
3300
+ * carries `approval_id, expires_at, code_sent, existing_account_hints[], next_endpoint`.
3301
+ *
3302
+ * `phoneShareInitiate` is the fallback OTP send (use when the 409 didn't already
3303
+ * dispatch a code). NOT idempotent — never auto-retried. OTP TTL ~10 min.
3304
+ */
3305
+ async phoneShareInitiate(input, opts) {
3306
+ if (typeof input.phone !== "string" || !input.phone.trim()) {
3307
+ throw invalidInput2("phone", input.phone, "is required");
3308
+ }
3309
+ if (typeof input.email !== "string" || !input.email.trim()) {
3310
+ throw invalidInput2("email", input.email, "is required");
3311
+ }
3312
+ const raw = await this.http.post(
3313
+ "/api/wallet/phone-share/initiate",
3314
+ { phone: input.phone, email: input.email },
3315
+ { kind: "none" },
3316
+ // UNAUTHENTICATED — phone-owner-driven; send no auth header
3317
+ { signal: opts?.signal }
3318
+ // NOT idempotent — sends an OTP; never auto-retried
3319
+ );
3320
+ return toPhoneShareInitiateResult(raw);
3321
+ }
3322
+ /**
3323
+ * Approve a phone-share with the OTP the phone owner received. On success the grant
3324
+ * is stored server-side, keyed by (phone, requesting_email) and auto-consumed — the
3325
+ * caller simply RE-ISSUES the identical original request. UNAUTHENTICATED. NOT
3326
+ * idempotent (attempts are counted) — never auto-retried.
3327
+ */
3328
+ async phoneShareApprove(input, opts) {
3329
+ if (typeof input.approvalId !== "string" || !input.approvalId.trim()) {
3330
+ throw invalidInput2("approvalId", input.approvalId, "is required");
3331
+ }
3332
+ if (typeof input.otp !== "string" || !input.otp.trim()) {
3333
+ throw invalidInput2("otp", input.otp, "is required");
3334
+ }
3335
+ const raw = await this.http.post(
3336
+ "/api/wallet/phone-share/approve",
3337
+ { approval_id: input.approvalId, otp: input.otp },
3338
+ { kind: "none" },
3339
+ // UNAUTHENTICATED — phone-owner-driven; send no auth header
3340
+ { signal: opts?.signal }
3341
+ // NOT idempotent — OTP attempts are counted; never auto-retried
3342
+ );
3343
+ return toPhoneShareApproveResult(raw);
3344
+ }
3345
+ /**
3346
+ * Poll whether a phone-share (phone, requesting_email) pair is approved yet.
3347
+ * UNAUTHENTICATED, idempotent GET. `approved:true` means the original request can
3348
+ * be re-issued.
3349
+ */
3350
+ async phoneShareStatus(input, opts) {
3351
+ if (typeof input.phone !== "string" || !input.phone.trim()) {
3352
+ throw invalidInput2("phone", input.phone, "is required");
3353
+ }
3354
+ if (typeof input.email !== "string" || !input.email.trim()) {
3355
+ throw invalidInput2("email", input.email, "is required");
3356
+ }
3357
+ const q = new URLSearchParams();
3358
+ q.set("phone", input.phone);
3359
+ q.set("email", input.email);
3360
+ const raw = await this.http.get(
3361
+ `/api/wallet/phone-share/status?${q.toString()}`,
3362
+ { kind: "none" },
3363
+ // UNAUTHENTICATED — phone-owner-driven; send no auth header
3364
+ { signal: opts?.signal }
3365
+ );
3366
+ return { approved: raw["approved"] === true, raw };
3367
+ }
3368
+ // ---- Device approval grant (RFC 8628) — consoles, TVs, native Steam / desktop ----
3369
+ //
3370
+ // These take the PLAYER TOKEN explicitly: on a console the game server minted it and
3371
+ // holds it, and every call below authenticates with it — the game secret is never
3372
+ // sent. The grant is a FACTOR. `beginDeviceApproval` + `pollDeviceApproval` reaching
3373
+ // `approved` settles NOTHING; `approveWithDeviceCode` is the step that moves the money.
3374
+ /**
3375
+ * Stage 1 — start a device approval for ONE transaction (RFC 8628 §3.1/§3.2).
3376
+ *
3377
+ * Returns the grant: render `verificationUriComplete` as the QR (print `userCode`
3378
+ * under it for a TV with no camera), keep `deviceCode` on your server, then poll.
3379
+ * A repeat `begin` while an earlier grant is merely PENDING supersedes it (fresh code;
3380
+ * a page still open on the old one is told to scan again). A grant the player already
3381
+ * APPROVED blocks a new `begin` for its window with `409 DEVICE_APPROVAL_ALREADY_PENDING`
3382
+ * (`err.isDeviceApprovalAlreadyPending`, `err.deviceApprovalExpiresAt`) — the missing
3383
+ * step there is `approveWithDeviceCode`, not a new code.
3384
+ *
3385
+ * For `transfer` / `send` the backend also pushes the transaction's own approval
3386
+ * window past the grant's expiry, so an approval at minute nine cannot land on a
3387
+ * transfer that has already been refunded. Auth: the player token. `channel: "popup"`
3388
+ * is browser-only (`InvoClient.approveHosted`) and is refused before the network.
3389
+ */
3390
+ async beginDeviceApproval(input, opts) {
3391
+ assertPlayerToken(input.playerToken);
3392
+ if (typeof input.transactionId !== "string" || !input.transactionId.trim()) {
3393
+ throw invalidInput2("transactionId", input.transactionId, "is required");
3394
+ }
3395
+ assertDeviceApprovalFlow(input.flow);
3396
+ const channel = input.channel ?? "qr";
3397
+ if (!DEVICE_APPROVAL_CHANNELS.has(channel)) {
3398
+ throw invalidInput2("channel", channel, 'must be "qr" | "app_browser" ("popup" is browser-only)');
3399
+ }
3400
+ if (channel === "popup") {
3401
+ throw new InvoError({
3402
+ message: `channel "popup" is browser-only \u2014 the page must call begin itself so its Origin becomes the popup's opener. Use InvoClient.approveHosted() there; server-side use "qr" or "app_browser".`,
3403
+ code: "INVALID_INPUT",
3404
+ status: 0
3405
+ });
3406
+ }
3407
+ const raw = await this.http.post(
3408
+ "/api/sdk/approvals/device/begin",
3409
+ { transaction_id: input.transactionId, flow: input.flow, channel },
3410
+ { kind: "bearer", token: input.playerToken },
3411
+ // PLAYER token — never the game secret
3412
+ // Safe to retry: a lost-response retry supersedes the unseen pending grant with a
3413
+ // fresh code (one live grant per transaction + flow either way).
3414
+ { idempotent: true, signal: opts?.signal }
3415
+ );
3416
+ return toDeviceApprovalGrant(raw);
3417
+ }
3418
+ /**
3419
+ * Stage 3 — one poll (RFC 8628 §3.4/§3.5). Call it no faster than `interval` seconds.
3420
+ *
3421
+ * Returns `status`:
3422
+ * - `authorization_pending` — keep polling. While a first-time phone waits on your
3423
+ * screen, `enrollment` is present: show "Set up INVO on <deviceLabel>? Code
3424
+ * <matchCode>" and answer with `confirmDeviceEnrollment`.
3425
+ * - `slow_down` — add 5 s to your interval, then resume.
3426
+ * - `approved` — **now call `approveWithDeviceCode`**. Nothing has moved yet.
3427
+ * - `access_denied` — the player declined; do not retry silently.
3428
+ * - `expired_token` — the grant lapsed; `beginDeviceApproval` again.
3429
+ * Throws `InvoError` for `invalid_grant` (`err.code === "invalid_grant"`: unknown code,
3430
+ * or not this player's — one answer for both, deliberately) and for transport failures
3431
+ * after the retry budget (429 / 5xx are retried: this is an idempotent read).
3432
+ */
3433
+ async pollDeviceApproval(input, opts) {
3434
+ assertPlayerToken(input.playerToken);
3435
+ if (typeof input.deviceCode !== "string" || !input.deviceCode.trim()) {
3436
+ throw invalidInput2("deviceCode", input.deviceCode, "is required (from beginDeviceApproval)");
3437
+ }
3438
+ let raw;
3439
+ try {
3440
+ raw = await this.http.post(
3441
+ "/api/sdk/approvals/device/poll",
3442
+ { device_code: input.deviceCode },
3443
+ { kind: "bearer", token: input.playerToken },
3444
+ { idempotent: true, signal: opts?.signal }
3445
+ // a read; safe to retry
3446
+ );
3447
+ } catch (err) {
3448
+ if (err instanceof InvoError && err.status === 400 && typeof err.code === "string" && DEVICE_POLL_OUTCOME_TOKENS.has(err.code)) {
3449
+ const body = err.body && typeof err.body === "object" ? err.body : {};
3450
+ return toDevicePollOutcome(err.code, body);
3451
+ }
3452
+ throw err;
3453
+ }
3454
+ return {
3455
+ status: "approved",
3456
+ transactionId: raw["transaction_id"],
3457
+ flow: raw["flow"],
3458
+ approvedAt: raw["approved_at"] ?? null,
3459
+ raw
3460
+ };
3461
+ }
3462
+ /**
3463
+ * Stage 3b — answer the on-screen match-code prompt for a first-time phone.
3464
+ *
3465
+ * `approve` = "yes, the phone I just scanned with shows this code" (the phone then
3466
+ * creates its INVO passkey and approves); `deny` ends the whole grant — the next poll
3467
+ * answers `access_denied`. Answered once: `409 DEVICE_APPROVAL_ENROLLMENT_ALREADY_DECIDED`
3468
+ * means the backup email got there first — take the prompt down quietly.
3469
+ * `409 DEVICE_APPROVAL_NO_ENROLLMENT_PENDING`: no phone has asked. Not auto-retried.
3470
+ */
3471
+ async confirmDeviceEnrollment(input, opts) {
3472
+ assertPlayerToken(input.playerToken);
3473
+ if (typeof input.deviceCode !== "string" || !input.deviceCode.trim()) {
3474
+ throw invalidInput2("deviceCode", input.deviceCode, "is required (from beginDeviceApproval)");
3475
+ }
3476
+ if (input.decision !== "approve" && input.decision !== "deny") {
3477
+ throw invalidInput2("decision", input.decision, 'must be "approve" or "deny"');
3478
+ }
3479
+ const raw = await this.http.post(
3480
+ "/api/sdk/approvals/device/confirm-enrollment",
3481
+ { device_code: input.deviceCode, decision: input.decision },
3482
+ { kind: "bearer", token: input.playerToken },
3483
+ { signal: opts?.signal }
3484
+ // a decision — never auto-retried
3485
+ );
3486
+ return { status: String(raw["status"] ?? ""), raw };
3487
+ }
3488
+ /**
3489
+ * Stage 4 — THE MONEY STEP. Once the poll says `approved`, call this with the same
3490
+ * player token and the grant's `deviceCode`. Routes by `flow`:
3491
+ *
3492
+ * transfer → POST /api/sdk/transfers/{id}/approve
3493
+ * send → POST /api/sdk/send/{id}/approve
3494
+ * send_receipt → POST /api/sdk/send/{id}/confirm-receipt
3495
+ * transfer_receipt → POST /api/sdk/transfers/{id}/confirm-receipt
3496
+ *
3497
+ * The grant proves WHO approved; this call runs every gate the in-app passkey approve
3498
+ * runs (guardian, risk, recovery cooldown) and moves the money. A grant that is never
3499
+ * followed by this call moves nothing, and is consumed by nothing.
3500
+ *
3501
+ * Result: `status: "approved"` + `next: "pending_claim"` (transfer/send; `claimCode`
3502
+ * on a transfer) or `status: "completed"` + `amountReceived` (receipt flows). A 202
3503
+ * hold returns `holdReason` (money held, not refused). A repeat call after the code was
3504
+ * consumed returns `status: "not_pending"` with `currentStatus` and `alreadySettled`
3505
+ * — the backend's `TRANSACTION_NOT_PENDING` mapped into a result rather than thrown,
3506
+ * because for this call it is the normal answer to "did my earlier attempt land?".
3507
+ *
3508
+ * Throws `InvoError`: `err.isDeviceApprovalNotApproved` (400 — wrong/foreign code,
3509
+ * wrong flow, or the poll never said approved), `err.isPasskeyRecoveryCooldown` (403,
3510
+ * money-out after a passkey recovery — `err.retryAfterAt`), `err.isPlayerTokenStale`
3511
+ * (403, the player token predates the sender's phone being added: re-mint, or use the
3512
+ * initiate's `playerToken`, and retry once), guardian terminal states (410). Never
3513
+ * auto-retried: the device_code is a single-use factor.
3514
+ *
3515
+ * **A FAILURE HERE IS AMBIGUOUS ABOUT THE MONEY.** The backend commits the transfer and
3516
+ * *then* builds its 200 by reading the transaction back, so a fault raised after that
3517
+ * commit answers `SEND_APPROVE_FAILED` / `TRANSFER_APPROVE_FAILED` /
3518
+ * `CONFIRM_RECEIPT_FAILED` (`err.isSettleFault`, `err.errorRef`) for money that already
3519
+ * moved. A `status === 0` (timeout, connection dropped) is ambiguous for the same
3520
+ * reason, and this call is deliberately not auto-retried. So on either: read
3521
+ * `getTransferStatus` / `getSendStatus`, or wait for the `transfer.claim_pending`
3522
+ * webhook, BEFORE you tell the player it failed — and never auto-start a replacement
3523
+ * transaction.
3524
+ */
3525
+ async approveWithDeviceCode(input, opts) {
3526
+ assertPlayerToken(input.playerToken);
3527
+ if (typeof input.transactionId !== "string" || !input.transactionId.trim()) {
3528
+ throw invalidInput2("transactionId", input.transactionId, "is required");
3529
+ }
3530
+ assertDeviceApprovalFlow(input.flow);
3531
+ if (typeof input.deviceCode !== "string" || !input.deviceCode.trim()) {
3532
+ throw invalidInput2("deviceCode", input.deviceCode, "is required (from beginDeviceApproval)");
3533
+ }
3534
+ let raw;
3535
+ try {
3536
+ raw = await this.http.post(
3537
+ deviceApprovalSettlePath(input.flow, input.transactionId),
3538
+ { device_code: input.deviceCode },
3539
+ { kind: "bearer", token: input.playerToken },
3540
+ // PLAYER token — never the game secret
3541
+ { signal: opts?.signal }
3542
+ // NOT idempotent — the device_code is single-use; never auto-retried
3543
+ );
3544
+ } catch (err) {
3545
+ if (err instanceof InvoError && err.isTransactionNotPending) {
3546
+ const body = err.body && typeof err.body === "object" ? err.body : {};
3547
+ const currentStatus = err.currentTransactionStatus ?? "";
3548
+ return {
3549
+ status: "not_pending",
3550
+ transactionId: input.transactionId,
3551
+ flow: input.flow,
3552
+ alreadySettled: currentStatus !== "" && isPastThisStep(input.flow, currentStatus),
3553
+ currentStatus: currentStatus || void 0,
3554
+ raw: body
3555
+ };
3556
+ }
3557
+ throw err;
3558
+ }
3559
+ return toDeviceApprovalSettleResult(raw, input);
3560
+ }
3561
+ /**
3562
+ * Convenience only — stages 3 and 4 in one call, for a server that can hold the loop
3563
+ * open (a per-request worker, a job). Polls `pollDeviceApproval` on `interval`, adds
3564
+ * 5 s on `slow_down`, forwards the poll's `enrollment` to `onEnrollment` (answer with
3565
+ * `respond`), and on `approved` calls `approveWithDeviceCode` — THEN resolves.
3566
+ * `respond` is best-effort: a prompt the grant has outlived (`expired_token`,
3567
+ * `invalid_grant`) or that was already answered elsewhere resolves quietly rather than
3568
+ * rejecting, because callers fire it from UI code without awaiting it.
3569
+ * You still call `beginDeviceApproval` yourself first, because your game has to draw
3570
+ * the QR between begin and the first poll.
3571
+ *
3572
+ * Resolves `{ status: "approved", settlement }` | `denied` | `expired` | `aborted`.
3573
+ * Rejects on `invalid_grant`, on a refused approve (e.g. `PASSKEY_RECOVERY_COOLDOWN`),
3574
+ * and after 5 consecutive transport failures on the poll.
3575
+ *
3576
+ * **Record the attempt in your own store BEFORE you call this.** It blocks for as long
3577
+ * as the player takes and then moves money from inside the loop, so if your process
3578
+ * dies between the approve call and its response, a row you wrote first — plus
3579
+ * `getTransferStatus` / `getSendStatus` — is the only way to learn whether the money
3580
+ * moved. Servers that must not block a request use the three calls directly and keep
3581
+ * `deviceCode` in their own store.
3582
+ *
3583
+ * `respond` (handed to `onEnrollment`) is best-effort: a prompt the grant has outlived
3584
+ * resolves quietly rather than rejecting. Any other confirm-enrollment refusal
3585
+ * propagates, so `await` it if you want to see one.
3586
+ */
3587
+ async completeDeviceApproval(input, opts) {
3588
+ assertPlayerToken(input.playerToken);
3589
+ if (typeof input.transactionId !== "string" || !input.transactionId.trim()) {
3590
+ throw invalidInput2("transactionId", input.transactionId, "is required");
3591
+ }
3592
+ assertDeviceApprovalFlow(input.flow);
3593
+ if (typeof input.deviceCode !== "string" || !input.deviceCode.trim()) {
3594
+ throw invalidInput2("deviceCode", input.deviceCode, "is required (from beginDeviceApproval)");
3595
+ }
3596
+ const signal = input.signal ?? opts?.signal;
3597
+ const { playerToken, deviceCode } = input;
3598
+ let interval = Math.max(1, Number(input.interval) || 5);
3599
+ let lastPoll;
3600
+ let lastEnrollmentKey = null;
3601
+ let transientFailures = 0;
3602
+ const MAX_TRANSIENT = 5;
3603
+ const respond = async (decision) => {
3604
+ try {
3605
+ await this.confirmDeviceEnrollment({ playerToken, deviceCode, decision }, { signal });
3606
+ } catch (err) {
3607
+ if (err instanceof InvoError && (err.code === "DEVICE_APPROVAL_ENROLLMENT_ALREADY_DECIDED" || err.code === "DEVICE_APPROVAL_NO_ENROLLMENT_PENDING" || err.code === "expired_token" || err.code === "invalid_grant")) {
3608
+ return;
3609
+ }
3610
+ throw err;
3611
+ }
3612
+ };
3613
+ const publishEnrollment = (e) => {
3614
+ if (!input.onEnrollment) return;
3615
+ const key = e ? `${e.state}|${e.matchCode}|${e.deviceLabel}|${e.recovery}` : null;
3616
+ if (key === lastEnrollmentKey) return;
3617
+ lastEnrollmentKey = key;
3618
+ input.onEnrollment(e ?? null, respond);
3619
+ };
3620
+ for (; ; ) {
3621
+ await sleepFor(interval * 1e3, signal);
3622
+ if (signal?.aborted) return { status: "aborted", lastPoll };
3623
+ let poll;
3624
+ try {
3625
+ poll = await this.pollDeviceApproval({ playerToken, deviceCode }, { signal });
3626
+ } catch (err) {
3627
+ if (signal?.aborted) return { status: "aborted", lastPoll };
3628
+ const transient = err instanceof InvoError && (err.status === 0 || err.status === 429 || err.status >= 500);
3629
+ if (transient && ++transientFailures < MAX_TRANSIENT) {
3630
+ const ra = err instanceof InvoError && err.status === 429 ? err.retryAfter : void 0;
3631
+ if (typeof ra === "number" && ra > interval) interval = ra;
3632
+ continue;
3633
+ }
3634
+ throw err;
3635
+ }
3636
+ transientFailures = 0;
3637
+ lastPoll = poll;
3638
+ switch (poll.status) {
3639
+ case "authorization_pending":
3640
+ if (poll.interval) interval = poll.interval;
3641
+ publishEnrollment(poll.enrollment);
3642
+ continue;
3643
+ case "slow_down":
3644
+ interval = Math.max(interval + 5, poll.interval ?? 0);
3645
+ continue;
3646
+ case "expired_token":
3647
+ publishEnrollment(void 0);
3648
+ return { status: "expired", lastPoll };
3649
+ case "access_denied":
3650
+ publishEnrollment(void 0);
3651
+ return { status: "denied", lastPoll };
3652
+ case "approved": {
3653
+ publishEnrollment(void 0);
3654
+ const settlement = await this.approveWithDeviceCode(
3655
+ { playerToken, transactionId: input.transactionId, flow: input.flow, deviceCode },
3656
+ { signal }
3657
+ );
3658
+ return { status: "approved", settlement, lastPoll };
3659
+ }
3660
+ }
3661
+ }
3662
+ }
3663
+ toInitiateResult(raw) {
3664
+ const vm = raw["verification_method"];
3665
+ const guardian = raw["guardian_approval"];
3666
+ return {
3667
+ transactionId: String(raw["transaction_id"] ?? ""),
3668
+ verificationMethod: guardian ? void 0 : vm === "in_app" || vm === "sms" ? vm : void 0,
3669
+ guardianApproval: guardian ?? void 0,
3670
+ ...raw["identity_rekeyed"] === true ? { identityRekeyed: true } : {},
3671
+ ...playerTokenFields(raw),
3672
+ ...typeof raw["identity_id"] === "string" && raw["identity_id"] ? { identityId: raw["identity_id"] } : {},
3673
+ ...typeof raw["claim_delivery_planned"] === "string" && raw["claim_delivery_planned"] ? { claimDeliveryPlanned: raw["claim_delivery_planned"] } : {},
3674
+ raw
3675
+ };
3676
+ }
3677
+ };
3678
+
3679
+ export { CardsServer, InvoServer, PayoutsServer, PlatformCommerceServer, SandboxServer, SandboxSubscriptionsServer, SubscriptionsServer, createWebhookHandler, isRefundPendingApproval, verifyWebhook, verifyWebhookAsync };
3680
+ //# sourceMappingURL=chunk-2DYTV74W.js.map
3681
+ //# sourceMappingURL=chunk-2DYTV74W.js.map