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