@invonetwork/web-sdk 3.29.1 → 3.30.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.
Files changed (36) hide show
  1. package/CHANGELOG.md +1432 -1397
  2. package/README.md +2954 -2923
  3. package/dist/{chunk-YONO4JE5.js → chunk-664RAO2T.js} +25 -5
  4. package/dist/chunk-BIK6UXY7.js +6 -0
  5. package/dist/chunk-QDHOPJFL.js +1634 -0
  6. package/dist/{chunk-VP3OK4J4.js → chunk-TSTP2CWA.js} +471 -3
  7. package/dist/game-server.cjs +269 -2
  8. package/dist/game-server.d.cts +40 -6
  9. package/dist/game-server.d.ts +40 -6
  10. package/dist/game-server.js +252 -7
  11. package/dist/game.cjs +2677 -9
  12. package/dist/game.d.cts +78 -4
  13. package/dist/game.d.ts +78 -4
  14. package/dist/game.js +558 -3
  15. package/dist/hosted-approval-DcY4U2RN.d.cts +96 -0
  16. package/dist/hosted-approval-DiKmtjEh.d.ts +96 -0
  17. package/dist/index.d.cts +7 -96
  18. package/dist/index.d.ts +7 -96
  19. package/dist/index.js +2 -1635
  20. package/dist/loyalty-events-CmDw2ZoR.d.cts +40 -0
  21. package/dist/loyalty-events-CmDw2ZoR.d.ts +40 -0
  22. package/dist/{server-BYY6tM6X.d.ts → server-B0mvlGFY.d.ts} +17 -2
  23. package/dist/{server-Bxo_wgHx.d.cts → server-DEh9wjF2.d.cts} +17 -2
  24. package/dist/server.cjs +22 -1
  25. package/dist/server.d.cts +4 -3
  26. package/dist/server.d.ts +4 -3
  27. package/dist/server.js +3 -4
  28. package/dist/{types-_lIm74kd.d.cts → types-BTbZicgj.d.cts} +1 -40
  29. package/dist/{types-_lIm74kd.d.ts → types-BTbZicgj.d.ts} +1 -40
  30. package/dist/{types-CLyJDuXd.d.cts → types-jUxfYjiD.d.cts} +64 -1
  31. package/dist/{types-CLyJDuXd.d.ts → types-jUxfYjiD.d.ts} +64 -1
  32. package/dist/{version-DOaYbHu7.d.cts → version-DfVkILOj.d.cts} +1 -1
  33. package/dist/{version-DOaYbHu7.d.ts → version-DfVkILOj.d.ts} +1 -1
  34. package/package.json +91 -91
  35. package/dist/chunk-6CN236QH.js +0 -473
  36. package/dist/chunk-VOGZZ6QS.js +0 -6
package/dist/game.cjs CHANGED
@@ -1112,8 +1112,41 @@ var InvoError = class _InvoError extends Error {
1112
1112
  return this.body && typeof this.body === "object" ? this.body : {};
1113
1113
  }
1114
1114
  };
1115
+ function errorFromResponse(status, body, requestId) {
1116
+ let message = `INVO request failed (HTTP ${status})`;
1117
+ let code;
1118
+ let rawCode;
1119
+ let publicCode;
1120
+ if (body && typeof body === "object") {
1121
+ const b = body;
1122
+ if (typeof b["code"] === "string") rawCode = b["code"];
1123
+ else if (typeof b["error_code"] === "string") rawCode = b["error_code"];
1124
+ if (typeof b["error_code_public"] === "string") publicCode = b["error_code_public"];
1125
+ code = publicCode ?? rawCode;
1126
+ if (typeof b["error"] === "string") message = b["error"];
1127
+ else if (typeof b["message"] === "string") message = b["message"];
1128
+ if (!code && typeof b["error"] === "string" && /^(flow_paused|spending_limit_exceeded|receiver_not_enrolled_use_claim_code|no_channel_on_file|rate_limited|service_unavailable|authorization_pending|slow_down|expired_token|access_denied|invalid_grant)$/.test(
1129
+ b["error"]
1130
+ )) {
1131
+ code = b["error"];
1132
+ if (typeof b["message"] === "string" && b["message"]) message = b["message"];
1133
+ }
1134
+ } else if (typeof body === "string" && body.trim()) {
1135
+ message = body;
1136
+ }
1137
+ return new InvoError({ message, code, rawCode, publicCode, status, body, requestId });
1138
+ }
1115
1139
 
1116
1140
  // src/shared/loyalty-events.ts
1141
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
1142
+ var ISO_WITH_ZONE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})$/;
1143
+ function invalid(label, value, why) {
1144
+ return new InvoError({
1145
+ message: `${label} ${why} (got ${JSON.stringify(value)}).`,
1146
+ code: "INVALID_INPUT",
1147
+ status: 0
1148
+ });
1149
+ }
1117
1150
  function newEventId() {
1118
1151
  const c = globalThis.crypto;
1119
1152
  if (c && typeof c.randomUUID === "function") return c.randomUUID();
@@ -1127,11 +1160,2092 @@ function newEventId() {
1127
1160
  status: 0
1128
1161
  });
1129
1162
  }
1130
- bytes[6] = bytes[6] & 15 | 64;
1131
- bytes[8] = bytes[8] & 63 | 128;
1132
- const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
1133
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
1134
- }
1163
+ bytes[6] = bytes[6] & 15 | 64;
1164
+ bytes[8] = bytes[8] & 63 | 128;
1165
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
1166
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
1167
+ }
1168
+ function buildGameEventBody(input) {
1169
+ if (!input || typeof input !== "object") throw invalid("input", input, "must be an object");
1170
+ const { eventType, payload } = input;
1171
+ if (typeof eventType !== "string" || !eventType.startsWith("game.") || eventType.length > 120) {
1172
+ throw invalid("eventType", eventType, "must be a game.* event type");
1173
+ }
1174
+ const eventId = input.eventId === void 0 ? newEventId() : input.eventId;
1175
+ if (typeof eventId !== "string" || !UUID.test(eventId)) {
1176
+ throw invalid("eventId", eventId, "must be a UUID");
1177
+ }
1178
+ const body = { event_type: eventType, event_id: eventId };
1179
+ if (input.occurredAt !== void 0) {
1180
+ const at = input.occurredAt instanceof Date ? input.occurredAt.toISOString() : input.occurredAt;
1181
+ if (typeof at !== "string" || !ISO_WITH_ZONE.test(at) || Number.isNaN(Date.parse(at))) {
1182
+ throw invalid("occurredAt", input.occurredAt, "must be ISO 8601 with a timezone, or a Date");
1183
+ }
1184
+ body["occurred_at"] = at;
1185
+ }
1186
+ if (payload !== void 0) {
1187
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
1188
+ throw invalid("payload", payload, "must be a plain object");
1189
+ }
1190
+ body["payload"] = payload;
1191
+ } else {
1192
+ body["payload"] = {};
1193
+ }
1194
+ return { body, eventId };
1195
+ }
1196
+ function toReportGameEventResult(raw, eventId) {
1197
+ const echoed = raw["event_id"];
1198
+ return {
1199
+ accepted: true,
1200
+ eventId: typeof echoed === "string" && echoed ? echoed : eventId,
1201
+ raw
1202
+ };
1203
+ }
1204
+
1205
+ // src/shared/http.ts
1206
+ var DEFAULT_TIMEOUT = 3e4;
1207
+ var MAX_RETRY_AFTER_MS = 2e4;
1208
+ function assertSecureBaseUrl(baseUrl) {
1209
+ let u;
1210
+ try {
1211
+ u = new URL(baseUrl);
1212
+ } catch {
1213
+ throw new Error(`Invalid baseUrl: ${baseUrl}`);
1214
+ }
1215
+ const isLocal = u.hostname === "localhost" || u.hostname === "127.0.0.1" || u.hostname === "[::1]";
1216
+ if (u.protocol === "https:" || u.protocol === "http:" && isLocal) return;
1217
+ throw new Error(
1218
+ `baseUrl must use https:// (got "${u.protocol}//"). Plaintext would expose the token/secret on the wire.`
1219
+ );
1220
+ }
1221
+ var _Http = class _Http {
1222
+ constructor(opts) {
1223
+ this.baseUrl = opts.baseUrl.replace(/\/+$/, "");
1224
+ this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT;
1225
+ const f = opts.fetchImpl ?? globalThis.fetch;
1226
+ if (typeof f !== "function") {
1227
+ throw new Error(
1228
+ "No fetch implementation available. Use Node >=18, or pass `fetch` in the config."
1229
+ );
1230
+ }
1231
+ this.fetchImpl = f.bind(globalThis);
1232
+ this.userAgent = opts.userAgent;
1233
+ this.maxRetries = Math.max(0, opts.maxRetries ?? 2);
1234
+ this.retryBaseDelayMs = opts.retryBaseDelayMs ?? 250;
1235
+ this.hooks = opts.hooks;
1236
+ }
1237
+ /**
1238
+ * @param opts.idempotent - mark this POST safe to auto-retry (it carries an
1239
+ * idempotency key, or has no side effect). Default false: non-idempotent POSTs
1240
+ * (e.g. single-use WebAuthn assertions) are NEVER auto-retried.
1241
+ */
1242
+ async post(path, body, auth, opts) {
1243
+ return this.request("POST", path, body, auth, opts?.idempotent ?? false, opts?.signal, opts?.headers);
1244
+ }
1245
+ // GET is always idempotent → safe to retry.
1246
+ async get(path, auth, opts) {
1247
+ return this.request("GET", path, void 0, auth, true, opts?.signal, opts?.headers);
1248
+ }
1249
+ authHeaders(auth) {
1250
+ switch (auth.kind) {
1251
+ case "game-secret":
1252
+ return { "X-Game-Secret-Key": auth.secret };
1253
+ case "bearer":
1254
+ return { Authorization: `Bearer ${auth.token}` };
1255
+ case "none":
1256
+ return {};
1257
+ }
1258
+ }
1259
+ async request(method, path, body, auth, idempotent, signal, extraHeaders) {
1260
+ const url = `${this.baseUrl}${path}`;
1261
+ const headers = {
1262
+ Accept: "application/json",
1263
+ ...this.authHeaders(auth),
1264
+ // Per-call extras (e.g. the sandbox clock key) — never able to override the auth header.
1265
+ ...extraHeaders ?? {},
1266
+ ...this.authHeaders(auth)
1267
+ };
1268
+ if (this.userAgent) headers["User-Agent"] = this.userAgent;
1269
+ if (body !== void 0) headers["Content-Type"] = "application/json";
1270
+ const payload = body !== void 0 ? JSON.stringify(body) : void 0;
1271
+ for (let attempt = 0; ; attempt++) {
1272
+ if (signal?.aborted) throw abortError(path);
1273
+ const start = Date.now();
1274
+ this.fire("onRequest", { method, url, attempt });
1275
+ const controller = new AbortController();
1276
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
1277
+ const onAbort = () => controller.abort();
1278
+ signal?.addEventListener("abort", onAbort, { once: true });
1279
+ let res;
1280
+ let networkError;
1281
+ try {
1282
+ res = await this.fetchImpl(url, {
1283
+ method,
1284
+ headers,
1285
+ body: payload,
1286
+ signal: controller.signal,
1287
+ redirect: "manual"
1288
+ });
1289
+ } catch (err) {
1290
+ networkError = new InvoError({
1291
+ message: err instanceof Error && err.name === "AbortError" ? `Request to ${path} timed out after ${this.timeoutMs}ms` : `Network error calling ${path}: ${err?.message ?? err}`,
1292
+ status: 0,
1293
+ body: null
1294
+ });
1295
+ } finally {
1296
+ clearTimeout(timer);
1297
+ signal?.removeEventListener("abort", onAbort);
1298
+ }
1299
+ if (networkError) {
1300
+ if (signal?.aborted) throw abortError(path);
1301
+ const willRetry = idempotent && attempt < this.maxRetries;
1302
+ this.fire("onError", { method, url, attempt, error: networkError, willRetry });
1303
+ if (willRetry) {
1304
+ await sleep(this.backoff(attempt), signal);
1305
+ continue;
1306
+ }
1307
+ throw networkError;
1308
+ }
1309
+ if (res.type === "opaqueredirect" || res.status >= 300 && res.status < 400) {
1310
+ throw new InvoError({
1311
+ message: `Refused to follow a redirect from ${path} \u2014 credentials are never re-sent to a redirected URL.`,
1312
+ code: "UNEXPECTED_REDIRECT",
1313
+ status: res.status || 0,
1314
+ body: null
1315
+ });
1316
+ }
1317
+ const requestId = pickRequestId(res.headers);
1318
+ const text = await res.text();
1319
+ let parsed = null;
1320
+ if (text) {
1321
+ try {
1322
+ parsed = JSON.parse(text);
1323
+ } catch {
1324
+ parsed = text;
1325
+ }
1326
+ }
1327
+ this.fire("onResponse", {
1328
+ method,
1329
+ url,
1330
+ attempt,
1331
+ status: res.status,
1332
+ durationMs: Date.now() - start,
1333
+ requestId
1334
+ });
1335
+ if (!res.ok) {
1336
+ const err = errorFromResponse(res.status, parsed, requestId);
1337
+ let wait;
1338
+ if (idempotent && attempt < this.maxRetries && _Http.RETRIABLE_STATUS.has(res.status)) {
1339
+ if (res.status === 429) {
1340
+ const ra = retryAfterMs(parsed, res.headers);
1341
+ wait = ra === void 0 ? this.backoff(attempt) : ra <= MAX_RETRY_AFTER_MS ? ra : void 0;
1342
+ } else {
1343
+ wait = this.backoff(attempt);
1344
+ }
1345
+ }
1346
+ this.fire("onError", { method, url, attempt, error: err, willRetry: wait !== void 0 });
1347
+ if (wait !== void 0) {
1348
+ await sleep(wait, signal);
1349
+ continue;
1350
+ }
1351
+ throw err;
1352
+ }
1353
+ return parsed ?? {};
1354
+ }
1355
+ }
1356
+ /** Invoke an observability hook, swallowing any error it throws (best-effort). */
1357
+ fire(name, info) {
1358
+ const hook = this.hooks?.[name];
1359
+ if (!hook) return;
1360
+ try {
1361
+ hook(info);
1362
+ } catch {
1363
+ }
1364
+ }
1365
+ /** Exponential backoff with full jitter: base * 2^attempt, randomized. */
1366
+ backoff(attempt) {
1367
+ const ceil = this.retryBaseDelayMs * 2 ** attempt;
1368
+ return Math.floor(Math.random() * ceil) + this.retryBaseDelayMs;
1369
+ }
1370
+ };
1371
+ /** HTTP statuses worth retrying — rate limit + transient gateway/server errors. */
1372
+ _Http.RETRIABLE_STATUS = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
1373
+ var Http = _Http;
1374
+ function sleep(ms, signal) {
1375
+ return new Promise((resolve) => {
1376
+ if (signal?.aborted) return resolve();
1377
+ const timer = setTimeout(done, ms);
1378
+ const onAbort = () => done();
1379
+ function done() {
1380
+ clearTimeout(timer);
1381
+ signal?.removeEventListener("abort", onAbort);
1382
+ resolve();
1383
+ }
1384
+ signal?.addEventListener("abort", onAbort, { once: true });
1385
+ });
1386
+ }
1387
+ function abortError(path) {
1388
+ return new InvoError({ message: `Request to ${path} was aborted`, code: "ABORTED", status: 0 });
1389
+ }
1390
+ function pickRequestId(headers) {
1391
+ if (!headers || typeof headers.get !== "function") return void 0;
1392
+ return headers.get("x-invo-request-id") ?? headers.get("x-request-id") ?? void 0;
1393
+ }
1394
+ function retryAfterMs(parsed, headers) {
1395
+ if (parsed && typeof parsed === "object") {
1396
+ const v = parsed["retry_after"];
1397
+ const n = typeof v === "string" ? v.trim() === "" ? NaN : Number(v) : v;
1398
+ if (typeof n === "number" && Number.isFinite(n) && n >= 0) return n * 1e3;
1399
+ }
1400
+ const header = headers && typeof headers.get === "function" ? headers.get("retry-after") : null;
1401
+ if (header) {
1402
+ const n = Number(header);
1403
+ if (Number.isFinite(n) && n >= 0) return n * 1e3;
1404
+ }
1405
+ return void 0;
1406
+ }
1407
+
1408
+ // src/shared/webauthn.ts
1409
+ function malformedOptions(field) {
1410
+ return new InvoError({
1411
+ message: `Malformed WebAuthn options from the backend: missing/invalid \`${field}\`.`,
1412
+ code: "WEBAUTHN_OPTIONS_MALFORMED",
1413
+ status: 0
1414
+ });
1415
+ }
1416
+ function b64urlToBuffer(value) {
1417
+ const pad = value.length % 4 === 0 ? "" : "=".repeat(4 - value.length % 4);
1418
+ const b64 = value.replace(/-/g, "+").replace(/_/g, "/") + pad;
1419
+ const bin = atob(b64);
1420
+ const bytes = new Uint8Array(bin.length);
1421
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
1422
+ return bytes.buffer;
1423
+ }
1424
+ function bufferToB64url(buf) {
1425
+ const bytes = new Uint8Array(buf);
1426
+ let bin = "";
1427
+ for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
1428
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1429
+ }
1430
+ function descriptorsToBinary(list) {
1431
+ return (list ?? []).map((d) => {
1432
+ const out = {
1433
+ id: b64urlToBuffer(d.id),
1434
+ type: d.type
1435
+ };
1436
+ if (d.transports) out.transports = d.transports;
1437
+ return out;
1438
+ });
1439
+ }
1440
+ function toCreationOptions(json) {
1441
+ if (typeof json?.["challenge"] !== "string") throw malformedOptions("challenge");
1442
+ if (typeof json["user"]?.id !== "string") throw malformedOptions("user.id");
1443
+ const opts = {
1444
+ ...json,
1445
+ challenge: b64urlToBuffer(json["challenge"]),
1446
+ user: {
1447
+ ...json["user"],
1448
+ id: b64urlToBuffer(json["user"].id)
1449
+ }
1450
+ };
1451
+ if (json["excludeCredentials"]) {
1452
+ opts.excludeCredentials = descriptorsToBinary(json["excludeCredentials"]);
1453
+ }
1454
+ return opts;
1455
+ }
1456
+ function toRequestOptions(json) {
1457
+ if (typeof json?.["challenge"] !== "string") throw malformedOptions("challenge");
1458
+ const opts = {
1459
+ ...json,
1460
+ challenge: b64urlToBuffer(json["challenge"])
1461
+ };
1462
+ if (json["allowCredentials"]) {
1463
+ opts.allowCredentials = descriptorsToBinary(json["allowCredentials"]);
1464
+ }
1465
+ return opts;
1466
+ }
1467
+ function registrationToJSON(cred) {
1468
+ const r = cred.response;
1469
+ return {
1470
+ id: cred.id,
1471
+ rawId: bufferToB64url(cred.rawId),
1472
+ type: cred.type,
1473
+ authenticatorAttachment: cred.authenticatorAttachment ?? void 0,
1474
+ clientExtensionResults: cred.getClientExtensionResults(),
1475
+ response: {
1476
+ clientDataJSON: bufferToB64url(r.clientDataJSON),
1477
+ attestationObject: bufferToB64url(r.attestationObject),
1478
+ transports: typeof r.getTransports === "function" ? r.getTransports() : void 0
1479
+ }
1480
+ };
1481
+ }
1482
+ function assertionToJSON(cred) {
1483
+ const r = cred.response;
1484
+ return {
1485
+ id: cred.id,
1486
+ rawId: bufferToB64url(cred.rawId),
1487
+ type: cred.type,
1488
+ authenticatorAttachment: cred.authenticatorAttachment ?? void 0,
1489
+ clientExtensionResults: cred.getClientExtensionResults(),
1490
+ response: {
1491
+ clientDataJSON: bufferToB64url(r.clientDataJSON),
1492
+ authenticatorData: bufferToB64url(r.authenticatorData),
1493
+ signature: bufferToB64url(r.signature),
1494
+ userHandle: r.userHandle ? bufferToB64url(r.userHandle) : null
1495
+ }
1496
+ };
1497
+ }
1498
+
1499
+ // src/shared/destinations.ts
1500
+ function toDestinationGame(row) {
1501
+ const s = (k) => row[k] === void 0 || row[k] === null ? void 0 : String(row[k]);
1502
+ return {
1503
+ gameId: row["game_id"] ?? "",
1504
+ gameName: String(row["game_name"] ?? ""),
1505
+ tenantType: s("tenant_type"),
1506
+ developerName: s("developer_name"),
1507
+ publisherName: s("publisher_name"),
1508
+ genre: s("genre"),
1509
+ platform: s("platform"),
1510
+ gameStatus: s("game_status"),
1511
+ gameIcon: s("game_icon"),
1512
+ gamePoster: s("game_poster"),
1513
+ gameUrl: s("game_url"),
1514
+ gameDescription: s("game_description"),
1515
+ currencyName: String(row["currency_name"] ?? ""),
1516
+ currencySymbol: String(row["currency_symbol"] ?? ""),
1517
+ currencySymbolUrl: s("currency_symbol_url"),
1518
+ minimumTransfer: String(row["minimum_transfer"] ?? ""),
1519
+ maximumTransfer: String(row["maximum_transfer"] ?? ""),
1520
+ acceptsSteamOriginValue: row["accepts_steam_origin_value"] === true,
1521
+ raw: row
1522
+ };
1523
+ }
1524
+ function toDestinationsResult(raw, direction) {
1525
+ const games = Array.isArray(raw["available_games"]) ? raw["available_games"] : [];
1526
+ return {
1527
+ status: String(raw["status"] ?? ""),
1528
+ sourceGameId: raw["source_game_id"] ?? "",
1529
+ sourceGameName: String(raw["source_game_name"] ?? ""),
1530
+ sourceGameIcon: raw["source_game_icon"],
1531
+ sourceCurrencyName: String(raw["source_currency_name"] ?? ""),
1532
+ sourceCurrencyIcon: raw["source_currency_icon"],
1533
+ universalTransfers: raw["universal_transfers"] === true,
1534
+ transferMode: String(raw["transfer_mode"] ?? ""),
1535
+ availableGames: games.map(toDestinationGame),
1536
+ totalDestinations: Number(raw["total_destinations"] ?? games.length),
1537
+ direction: String(raw["direction"] ?? direction),
1538
+ linkedGameIds: Array.isArray(raw["linked_game_ids"]) ? raw["linked_game_ids"] : void 0,
1539
+ raw
1540
+ };
1541
+ }
1542
+
1543
+ // src/shared/hosted-approval.ts
1544
+ var HOSTED_FLOWS = [
1545
+ "transfer",
1546
+ "send",
1547
+ "send_receipt",
1548
+ "transfer_receipt"
1549
+ ];
1550
+ var HOSTED_MESSAGE_TYPE = "invo.approval";
1551
+ var MAX_EXPIRES_IN_S = 24 * 24 * 60 * 60;
1552
+ var CONFIRM_QUIET_CODES = /* @__PURE__ */ new Set([
1553
+ "DEVICE_APPROVAL_ENROLLMENT_ALREADY_DECIDED",
1554
+ "DEVICE_APPROVAL_NO_ENROLLMENT_PENDING"
1555
+ ]);
1556
+ var MAX_TRANSIENT_POLL_FAILURES = 5;
1557
+ function derivePlatformOrigin(verificationUriComplete, explicit) {
1558
+ let u;
1559
+ try {
1560
+ u = new URL(verificationUriComplete);
1561
+ } catch {
1562
+ throw new InvoError({
1563
+ message: "begin returned no absolute verification_uri_complete.",
1564
+ code: "UNEXPECTED_RESPONSE",
1565
+ status: 0
1566
+ });
1567
+ }
1568
+ const isLocal = u.hostname === "localhost" || u.hostname === "127.0.0.1" || u.hostname === "[::1]";
1569
+ if (u.protocol !== "https:" && !(u.protocol === "http:" && isLocal)) {
1570
+ throw new InvoError({
1571
+ message: "The hosted approval page must be https (plaintext would let any page forge the wake-up).",
1572
+ code: "INVALID_INPUT",
1573
+ status: 0
1574
+ });
1575
+ }
1576
+ if (explicit !== void 0 && u.origin !== explicit) {
1577
+ throw new InvoError({
1578
+ message: `platformOrigin (${explicit}) does not match the hosted page's origin (${u.origin}).`,
1579
+ code: "INVALID_INPUT",
1580
+ status: 0
1581
+ });
1582
+ }
1583
+ return u.origin;
1584
+ }
1585
+ function normalizeEnrollment(input) {
1586
+ if (!input || typeof input !== "object") return null;
1587
+ const state = typeof input.state === "string" ? input.state : "";
1588
+ if (!state) return null;
1589
+ const label = input.device_label ?? input.deviceLabel;
1590
+ const code = input.match_code ?? input.matchCode;
1591
+ const at = input.requested_at ?? input.requestedAt;
1592
+ return {
1593
+ state,
1594
+ deviceLabel: typeof label === "string" && label ? label : "your phone",
1595
+ matchCode: typeof code === "string" ? code : "",
1596
+ requestedAt: typeof at === "string" ? at : void 0,
1597
+ raw: input
1598
+ };
1599
+ }
1600
+ var BRAND = "#4f46e5";
1601
+ var FONT = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif";
1602
+ var MONO = "ui-monospace, SFMono-Regular, Menlo, Consolas, 'Liberation Mono', monospace";
1603
+ var PROMPT_IDS = {
1604
+ root: "invo-hosted-enrollment",
1605
+ title: "invo-hosted-enrollment-title",
1606
+ code: "invo-hosted-enrollment-code",
1607
+ yes: "invo-hosted-enrollment-yes",
1608
+ no: "invo-hosted-enrollment-no",
1609
+ stop: "invo-hosted-enrollment-stop",
1610
+ error: "invo-hosted-enrollment-error"
1611
+ };
1612
+ var HostedEnrollmentPrompt = class {
1613
+ constructor() {
1614
+ this.handlers = { respond: async () => {
1615
+ }, renderPrompt: true };
1616
+ this.enrollment = null;
1617
+ /** The last match code the player answered, so a stale poll can't re-ask it. */
1618
+ this.decided = null;
1619
+ this.root = null;
1620
+ this.previousFocus = null;
1621
+ this.keyHandler = null;
1622
+ this.busy = false;
1623
+ }
1624
+ get current() {
1625
+ return this.enrollment;
1626
+ }
1627
+ configure(handlers) {
1628
+ this.handlers = handlers;
1629
+ this.decided = null;
1630
+ if (this.enrollment) this.render();
1631
+ }
1632
+ update(input) {
1633
+ let next = normalizeEnrollment(input);
1634
+ if (next && next.state === "awaiting_screen" && this.decided && this.decided.code === next.matchCode) {
1635
+ next = this.decided.decision === "approve" ? { ...next, state: "confirmed" } : null;
1636
+ }
1637
+ const changed = this.enrollment === null !== (next === null) || this.enrollment && next && (this.enrollment.state !== next.state || this.enrollment.matchCode !== next.matchCode || this.enrollment.deviceLabel !== next.deviceLabel);
1638
+ this.enrollment = next;
1639
+ if (changed) this.handlers.onEnrollment?.(next, this.handlers.respond);
1640
+ this.render();
1641
+ }
1642
+ clear() {
1643
+ this.update(null);
1644
+ }
1645
+ // --- rendering ---
1646
+ render() {
1647
+ if (typeof document === "undefined") return;
1648
+ const e = this.enrollment;
1649
+ const visible = this.handlers.renderPrompt && e && (e.state === "awaiting_screen" || e.state === "confirmed");
1650
+ if (!visible || !e) {
1651
+ this.unmount();
1652
+ return;
1653
+ }
1654
+ this.mount();
1655
+ const root = this.root;
1656
+ root.innerHTML = "";
1657
+ root.appendChild(e.state === "awaiting_screen" ? this.buildPrompt(e) : this.buildFinishing(e));
1658
+ this.focusInitial(e.state);
1659
+ }
1660
+ mount() {
1661
+ if (this.root) return;
1662
+ this.previousFocus = document.activeElement;
1663
+ const overlay = document.createElement("div");
1664
+ overlay.id = PROMPT_IDS.root;
1665
+ overlay.setAttribute("role", "dialog");
1666
+ overlay.setAttribute("aria-modal", "true");
1667
+ overlay.setAttribute("aria-labelledby", PROMPT_IDS.title);
1668
+ overlay.tabIndex = -1;
1669
+ overlay.style.cssText = [
1670
+ "position:fixed",
1671
+ "inset:0",
1672
+ "z-index:2147483000",
1673
+ "display:flex",
1674
+ "align-items:center",
1675
+ "justify-content:center",
1676
+ "padding:16px",
1677
+ "background:rgba(17,24,39,.55)",
1678
+ `font-family:${FONT}`,
1679
+ "color:#111827",
1680
+ "-webkit-font-smoothing:antialiased",
1681
+ "outline:none"
1682
+ ].join(";");
1683
+ this.keyHandler = (ev) => this.onKeyDown(ev);
1684
+ overlay.addEventListener("keydown", this.keyHandler);
1685
+ document.body.appendChild(overlay);
1686
+ this.root = overlay;
1687
+ }
1688
+ unmount() {
1689
+ if (!this.root) return;
1690
+ if (this.keyHandler) this.root.removeEventListener("keydown", this.keyHandler);
1691
+ this.root.remove();
1692
+ this.root = null;
1693
+ this.keyHandler = null;
1694
+ this.busy = false;
1695
+ const prev = this.previousFocus;
1696
+ this.previousFocus = null;
1697
+ if (prev && typeof prev.focus === "function") {
1698
+ try {
1699
+ prev.focus();
1700
+ } catch {
1701
+ }
1702
+ }
1703
+ }
1704
+ card() {
1705
+ const card = document.createElement("div");
1706
+ card.style.cssText = [
1707
+ "background:#ffffff",
1708
+ "border-radius:16px",
1709
+ "box-shadow:0 20px 60px rgba(17,24,39,.25)",
1710
+ "max-width:420px",
1711
+ "width:100%",
1712
+ "padding:28px 28px 24px",
1713
+ "box-sizing:border-box",
1714
+ "text-align:center"
1715
+ ].join(";");
1716
+ const mark = document.createElement("div");
1717
+ mark.textContent = "INVO";
1718
+ mark.setAttribute("aria-hidden", "true");
1719
+ mark.style.cssText = `font-weight:800;letter-spacing:.18em;font-size:13px;color:${BRAND};margin-bottom:14px`;
1720
+ card.appendChild(mark);
1721
+ return card;
1722
+ }
1723
+ button(id, label, primary) {
1724
+ const b = document.createElement("button");
1725
+ b.type = "button";
1726
+ b.id = id;
1727
+ b.textContent = label;
1728
+ b.style.cssText = [
1729
+ "display:block",
1730
+ "width:100%",
1731
+ "box-sizing:border-box",
1732
+ "border-radius:10px",
1733
+ "padding:12px 16px",
1734
+ "font:inherit",
1735
+ "font-size:15px",
1736
+ "font-weight:600",
1737
+ "cursor:pointer",
1738
+ "margin-top:10px",
1739
+ primary ? `background:${BRAND};color:#ffffff;border:1px solid ${BRAND}` : "background:#ffffff;color:#374151;border:1px solid #d1d5db"
1740
+ ].join(";");
1741
+ return b;
1742
+ }
1743
+ buildPrompt(e) {
1744
+ const card = this.card();
1745
+ const title = document.createElement("h2");
1746
+ title.id = PROMPT_IDS.title;
1747
+ title.textContent = `Set up INVO on ${e.deviceLabel}?`;
1748
+ title.style.cssText = "margin:0 0 14px;font-size:20px;font-weight:700;line-height:1.3";
1749
+ card.appendChild(title);
1750
+ const codeLabel = document.createElement("div");
1751
+ codeLabel.textContent = "Code";
1752
+ codeLabel.style.cssText = "font-size:12px;text-transform:uppercase;letter-spacing:.12em;color:#6b7280";
1753
+ card.appendChild(codeLabel);
1754
+ const code = document.createElement("div");
1755
+ code.id = PROMPT_IDS.code;
1756
+ code.textContent = e.matchCode;
1757
+ code.setAttribute("aria-label", `Code ${e.matchCode.split("").join(" ")}`);
1758
+ code.style.cssText = [
1759
+ `font-family:${MONO}`,
1760
+ "font-size:40px",
1761
+ "font-weight:700",
1762
+ "letter-spacing:.3em",
1763
+ "text-indent:.3em",
1764
+ "line-height:1.2",
1765
+ "margin:6px 0 16px",
1766
+ "color:#111827",
1767
+ "background:#f3f4f6",
1768
+ "border-radius:12px",
1769
+ "padding:14px 8px"
1770
+ ].join(";");
1771
+ card.appendChild(code);
1772
+ const body = document.createElement("p");
1773
+ body.textContent = "Say Yes only if the phone you just scanned/opened shows this code.";
1774
+ body.style.cssText = "margin:0 0 6px;font-size:15px;line-height:1.5;color:#374151";
1775
+ card.appendChild(body);
1776
+ const err = document.createElement("div");
1777
+ err.id = PROMPT_IDS.error;
1778
+ err.setAttribute("role", "alert");
1779
+ err.style.cssText = "min-height:18px;font-size:13px;color:#b91c1c;margin-top:4px";
1780
+ card.appendChild(err);
1781
+ const yes = this.button(PROMPT_IDS.yes, "Yes, it shows this code", true);
1782
+ yes.addEventListener("click", () => void this.decide("approve"));
1783
+ card.appendChild(yes);
1784
+ const no = this.button(PROMPT_IDS.no, "No, that is not my phone", false);
1785
+ no.addEventListener("click", () => void this.decide("deny"));
1786
+ card.appendChild(no);
1787
+ return card;
1788
+ }
1789
+ buildFinishing(e) {
1790
+ const card = this.card();
1791
+ card.style.padding = "18px 22px";
1792
+ const row = document.createElement("div");
1793
+ row.style.cssText = "display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap";
1794
+ const text = document.createElement("div");
1795
+ text.id = PROMPT_IDS.title;
1796
+ text.textContent = `Finishing on ${e.deviceLabel}\u2026`;
1797
+ text.tabIndex = -1;
1798
+ text.setAttribute("aria-live", "polite");
1799
+ text.style.cssText = "font-size:15px;color:#374151;outline:none";
1800
+ row.appendChild(text);
1801
+ const stop = document.createElement("button");
1802
+ stop.type = "button";
1803
+ stop.id = PROMPT_IDS.stop;
1804
+ stop.textContent = "Stop it, wrong code";
1805
+ stop.style.cssText = `background:none;border:0;padding:6px 0;font:inherit;font-size:14px;font-weight:600;color:${BRAND};cursor:pointer;text-decoration:underline`;
1806
+ stop.addEventListener("click", () => void this.decide("deny"));
1807
+ row.appendChild(stop);
1808
+ card.appendChild(row);
1809
+ return card;
1810
+ }
1811
+ async decide(decision) {
1812
+ if (this.busy || !this.enrollment) return;
1813
+ this.busy = true;
1814
+ this.root?.focus();
1815
+ this.setButtonsDisabled(true);
1816
+ try {
1817
+ await this.handlers.respond(decision);
1818
+ const now = this.enrollment;
1819
+ if (!now) return;
1820
+ this.decided = { code: now.matchCode, decision };
1821
+ if (decision === "deny") {
1822
+ this.update(null);
1823
+ } else if (now.state === "awaiting_screen") {
1824
+ this.update({ ...now.raw, state: "confirmed" });
1825
+ }
1826
+ } catch (err) {
1827
+ const box = this.root?.querySelector(`#${PROMPT_IDS.error}`);
1828
+ if (box) {
1829
+ box.textContent = err instanceof Error && err.message ? `Couldn't send your answer: ${err.message}` : "Couldn't send your answer. Try again.";
1830
+ }
1831
+ } finally {
1832
+ this.busy = false;
1833
+ this.setButtonsDisabled(false);
1834
+ if (this.root && this.enrollment?.state === "awaiting_screen") this.focusInitial("awaiting_screen");
1835
+ }
1836
+ }
1837
+ setButtonsDisabled(disabled) {
1838
+ this.root?.querySelectorAll("button").forEach((b) => {
1839
+ b.disabled = disabled;
1840
+ });
1841
+ }
1842
+ focusables() {
1843
+ if (!this.root) return [];
1844
+ return Array.from(this.root.querySelectorAll("button:not([disabled])"));
1845
+ }
1846
+ /** Prompt: first button. Finishing row: the text, NOT "Stop it" — a stray Enter must not deny. */
1847
+ focusInitial(state) {
1848
+ const target = state === "confirmed" ? this.root?.querySelector(`#${PROMPT_IDS.title}`) : this.focusables()[0];
1849
+ try {
1850
+ (target ?? this.root)?.focus();
1851
+ } catch {
1852
+ }
1853
+ }
1854
+ onKeyDown(ev) {
1855
+ if (ev.key === "Escape") {
1856
+ ev.preventDefault();
1857
+ void this.decide("deny");
1858
+ return;
1859
+ }
1860
+ if (ev.key !== "Tab") return;
1861
+ ev.preventDefault();
1862
+ const items = this.focusables();
1863
+ if (items.length === 0) {
1864
+ this.root?.focus();
1865
+ return;
1866
+ }
1867
+ const active = document.activeElement;
1868
+ const idx = items.indexOf(active);
1869
+ let nextIdx;
1870
+ if (idx === -1) nextIdx = ev.shiftKey ? items.length - 1 : 0;
1871
+ else nextIdx = (idx + (ev.shiftKey ? -1 : 1) + items.length) % items.length;
1872
+ items[nextIdx].focus();
1873
+ }
1874
+ };
1875
+ var COOP_HINT = "The popup was severed from this window as soon as INVO's page loaded. Your page most likely sends `Cross-Origin-Opener-Policy: same-origin`; use `same-origin-allow-popups` so the hosted page can reach window.opener. The grant is still live: the device_approval.approved webhook will tell your server.";
1876
+ var BLOCKED_HINT = "The browser blocked the popup. Nothing was started \u2014 call approveHosted() from a click handler.";
1877
+ function pollToken(err) {
1878
+ if (!(err instanceof InvoError) || err.status === 0 || err.status === 429 || err.status >= 500) return null;
1879
+ const body = err.body && typeof err.body === "object" ? err.body : {};
1880
+ const token = typeof body["error"] === "string" ? body["error"] : "";
1881
+ return { token, body };
1882
+ }
1883
+ async function runHostedApproval(opts, api, deps = {}) {
1884
+ if (typeof window === "undefined") {
1885
+ throw new InvoError({
1886
+ message: "approveHosted requires a browser window.",
1887
+ code: "DOM_UNAVAILABLE",
1888
+ status: 0
1889
+ });
1890
+ }
1891
+ if (!opts.transactionId || !String(opts.transactionId).trim()) {
1892
+ throw new Error("approveHosted requires a `transactionId`.");
1893
+ }
1894
+ if (!HOSTED_FLOWS.includes(opts.flow)) {
1895
+ throw new Error(`approveHosted: unknown flow "${String(opts.flow)}" (expected ${HOSTED_FLOWS.join(" | ")}).`);
1896
+ }
1897
+ if (opts.renderPrompt !== false && typeof document === "undefined") {
1898
+ throw new InvoError({
1899
+ message: "approveHosted needs a DOM to render the match-code prompt (or pass renderPrompt:false).",
1900
+ code: "DOM_UNAVAILABLE",
1901
+ status: 0
1902
+ });
1903
+ }
1904
+ const signal = opts.signal;
1905
+ if (signal?.aborted) return { status: "closed", popupBlocked: false };
1906
+ const open = deps.open ?? ((u, n, f) => window.open(u, n, f));
1907
+ const navigate = deps.navigate ?? ((u) => window.location.assign(u));
1908
+ const closedPollMs = deps.closedPollMs ?? 500;
1909
+ const coopGraceMs = deps.coopGraceMs ?? 1500;
1910
+ const createPrompt = deps.createPrompt ?? (() => new HostedEnrollmentPrompt());
1911
+ const width = opts.popup?.width ?? 480;
1912
+ const height = opts.popup?.height ?? 720;
1913
+ const sw = window.screen?.width ?? width;
1914
+ const sh = window.screen?.height ?? height;
1915
+ const left = Math.max(0, Math.round((sw - width) / 2));
1916
+ const top = Math.max(0, Math.round((sh - height) / 2));
1917
+ const features = `popup=yes,width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=yes`;
1918
+ const name = `invo-approval-${encodeURIComponent(String(opts.transactionId)).replace(/[^A-Za-z0-9-]/g, "")}`;
1919
+ let popup;
1920
+ try {
1921
+ popup = open("about:blank", name, features);
1922
+ } catch {
1923
+ popup = null;
1924
+ }
1925
+ const mode = opts.popupBlocked ?? "resolve";
1926
+ if (!popup && mode === "resolve") {
1927
+ return { status: "blocked", popupBlocked: true, message: BLOCKED_HINT };
1928
+ }
1929
+ let begin;
1930
+ try {
1931
+ begin = await api.begin();
1932
+ } catch (err) {
1933
+ try {
1934
+ popup?.close();
1935
+ } catch {
1936
+ }
1937
+ if (signal?.aborted || err instanceof InvoError && err.code === "ABORTED") {
1938
+ return { status: "closed", popupBlocked: false };
1939
+ }
1940
+ throw err;
1941
+ }
1942
+ const deviceCode = typeof begin["device_code"] === "string" ? begin["device_code"] : "";
1943
+ const url = typeof begin["verification_uri_complete"] === "string" ? begin["verification_uri_complete"] : "";
1944
+ if (!deviceCode || !url) {
1945
+ try {
1946
+ popup?.close();
1947
+ } catch {
1948
+ }
1949
+ const { device_code: _dc, ...safeBody } = begin;
1950
+ throw new InvoError({
1951
+ message: "begin returned no device_code / verification_uri_complete.",
1952
+ code: "UNEXPECTED_RESPONSE",
1953
+ status: 0,
1954
+ body: safeBody
1955
+ });
1956
+ }
1957
+ let origin;
1958
+ try {
1959
+ origin = derivePlatformOrigin(url, opts.platformOrigin);
1960
+ } catch (err) {
1961
+ try {
1962
+ popup?.close();
1963
+ } catch {
1964
+ }
1965
+ throw err;
1966
+ }
1967
+ const expiresIn = Math.min(
1968
+ MAX_EXPIRES_IN_S,
1969
+ Math.max(1, Number(begin["expires_in"]) || 600)
1970
+ );
1971
+ let interval = Math.max(1, Number(begin["interval"]) || 5);
1972
+ if (!popup) {
1973
+ try {
1974
+ navigate(url);
1975
+ return { status: "redirected", popupBlocked: true };
1976
+ } catch (err) {
1977
+ return {
1978
+ status: "blocked",
1979
+ popupBlocked: true,
1980
+ message: `The browser blocked the popup and the redirect fallback failed${err instanceof Error && err.message ? `: ${err.message}` : "."}`
1981
+ };
1982
+ }
1983
+ }
1984
+ const win = popup;
1985
+ try {
1986
+ const loc = win.location;
1987
+ if (loc && typeof loc.replace === "function") loc.replace(url);
1988
+ else if (loc) loc.href = url;
1989
+ } catch {
1990
+ }
1991
+ const navigatedAt = Date.now();
1992
+ try {
1993
+ win.focus?.();
1994
+ } catch {
1995
+ }
1996
+ return new Promise((resolve, reject) => {
1997
+ let settled = false;
1998
+ let prompt;
1999
+ let wake = null;
2000
+ let expiryTimer;
2001
+ let closedTimer;
2002
+ const cleanup = (closePopup) => {
2003
+ settled = true;
2004
+ window.removeEventListener("message", onMessage);
2005
+ signal?.removeEventListener("abort", onAbort);
2006
+ if (expiryTimer !== void 0) clearTimeout(expiryTimer);
2007
+ if (closedTimer !== void 0) clearInterval(closedTimer);
2008
+ prompt?.clear();
2009
+ if (closePopup && !win.closed) {
2010
+ try {
2011
+ win.close();
2012
+ } catch {
2013
+ }
2014
+ }
2015
+ wake?.();
2016
+ };
2017
+ const finish = (result, closePopup) => {
2018
+ if (settled) return;
2019
+ cleanup(closePopup);
2020
+ resolve(result);
2021
+ };
2022
+ const fail = (err) => {
2023
+ if (settled) return;
2024
+ cleanup(false);
2025
+ reject(err);
2026
+ };
2027
+ const respond = async (decision) => {
2028
+ if (settled) return;
2029
+ try {
2030
+ await api.confirmEnrollment(deviceCode, decision);
2031
+ } catch (err) {
2032
+ if (err instanceof InvoError && err.rawCode && CONFIRM_QUIET_CODES.has(err.rawCode)) {
2033
+ prompt?.update(null);
2034
+ return;
2035
+ }
2036
+ throw err;
2037
+ }
2038
+ wake?.();
2039
+ };
2040
+ const ensurePrompt = () => {
2041
+ if (!prompt) {
2042
+ prompt = createPrompt();
2043
+ prompt.configure({
2044
+ respond,
2045
+ onEnrollment: opts.onEnrollment,
2046
+ renderPrompt: opts.renderPrompt !== false
2047
+ });
2048
+ }
2049
+ return prompt;
2050
+ };
2051
+ const showEnrollment = (input) => {
2052
+ const e = input && typeof input === "object" ? input : null;
2053
+ if (e) ensurePrompt().update(e);
2054
+ else prompt?.update(null);
2055
+ };
2056
+ const onMessage = (event) => {
2057
+ if (event.origin !== origin) return;
2058
+ if (event.source && event.source !== win) return;
2059
+ const data = event.data;
2060
+ if (!data || typeof data !== "object" || data.type !== HOSTED_MESSAGE_TYPE) return;
2061
+ wake?.();
2062
+ };
2063
+ const onAbort = () => finish({ status: "closed", popupBlocked: false }, true);
2064
+ const pause = (ms) => new Promise((r) => {
2065
+ const t = setTimeout(() => {
2066
+ wake = null;
2067
+ r();
2068
+ }, ms);
2069
+ wake = () => {
2070
+ clearTimeout(t);
2071
+ wake = null;
2072
+ r();
2073
+ };
2074
+ });
2075
+ window.addEventListener("message", onMessage);
2076
+ signal?.addEventListener("abort", onAbort, { once: true });
2077
+ expiryTimer = setTimeout(() => finish({ status: "expired", popupBlocked: false }, false), expiresIn * 1e3);
2078
+ closedTimer = setInterval(() => {
2079
+ if (!win.closed) return;
2080
+ if (Date.now() - navigatedAt < coopGraceMs) {
2081
+ finish({ status: "blocked", popupBlocked: true, message: COOP_HINT }, false);
2082
+ } else {
2083
+ finish({ status: "closed", popupBlocked: false }, false);
2084
+ }
2085
+ }, closedPollMs);
2086
+ void (async () => {
2087
+ let transientFailures = 0;
2088
+ while (!settled) {
2089
+ await pause(interval * 1e3);
2090
+ if (settled) return;
2091
+ let raw;
2092
+ try {
2093
+ raw = await api.poll(deviceCode);
2094
+ } catch (err) {
2095
+ if (settled) return;
2096
+ const p = pollToken(err);
2097
+ if (!p) {
2098
+ if (++transientFailures >= MAX_TRANSIENT_POLL_FAILURES) return fail(err);
2099
+ const ra = err instanceof InvoError && err.status === 429 ? err.retryAfter : void 0;
2100
+ if (typeof ra === "number" && ra > interval) interval = Math.min(ra, MAX_EXPIRES_IN_S);
2101
+ continue;
2102
+ }
2103
+ transientFailures = 0;
2104
+ const bodyInterval = Number(p.body["interval"]);
2105
+ switch (p.token) {
2106
+ case "authorization_pending":
2107
+ if (bodyInterval > 0) interval = bodyInterval;
2108
+ showEnrollment(p.body["enrollment"]);
2109
+ continue;
2110
+ case "slow_down":
2111
+ interval = Math.max(interval + 5, bodyInterval > 0 ? bodyInterval : 0);
2112
+ continue;
2113
+ case "expired_token":
2114
+ return finish({ status: "expired", popupBlocked: false }, false);
2115
+ case "access_denied":
2116
+ return finish({ status: "denied", popupBlocked: false }, false);
2117
+ default:
2118
+ return fail(err);
2119
+ }
2120
+ }
2121
+ if (settled) return;
2122
+ if (raw["status"] !== "approved") continue;
2123
+ try {
2124
+ const approval = await api.approve(deviceCode);
2125
+ if (settled) return;
2126
+ finish({ status: "approved", popupBlocked: false, approval }, true);
2127
+ } catch (err) {
2128
+ fail(err);
2129
+ }
2130
+ return;
2131
+ }
2132
+ })();
2133
+ });
2134
+ }
2135
+
2136
+ // src/shared/receipt-fields.ts
2137
+ function receiptFields(raw) {
2138
+ const n = raw["receipt_number"];
2139
+ if (typeof n !== "string" || n === "") return {};
2140
+ const u = raw["receipt_url"];
2141
+ return typeof u === "string" && u !== "" ? { receiptNumber: n, receiptUrl: u } : { receiptNumber: n };
2142
+ }
2143
+
2144
+ // src/shared/purchase-status.ts
2145
+ function str(v) {
2146
+ return typeof v === "string" ? v : v === null || v === void 0 ? null : String(v);
2147
+ }
2148
+ function toPurchaseStatusResult(raw, sessionId) {
2149
+ return {
2150
+ status: String(raw["status"] ?? ""),
2151
+ // INVO SAYS, AND ONLY AN EXPLICIT `true` SAYS IT. A missing or malformed field reads
2152
+ // false, which keeps a poll running; the alternative, guessing terminality from
2153
+ // `status`, is how an old SDK declares a future status finished.
2154
+ terminal: raw["terminal"] === true,
2155
+ orderId: str(raw["order_id"]),
2156
+ sessionId: String(raw["session_id"] ?? sessionId),
2157
+ coinsCredited: str(raw["coins_credited"]),
2158
+ transactionId: str(raw["transaction_id"]),
2159
+ newBalance: str(raw["new_balance"]),
2160
+ reasonCode: str(raw["reason_code"]),
2161
+ message: str(raw["message"]),
2162
+ amountChargedUsd: str(raw["amount_charged_usd"]),
2163
+ listedUsd: str(raw["listed_usd"]),
2164
+ currencyName: str(raw["currency_name"]),
2165
+ ...receiptFields(raw),
2166
+ raw
2167
+ };
2168
+ }
2169
+
2170
+ // src/shared/loyalty.ts
2171
+ var obj = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : {};
2172
+ var rows = (v) => Array.isArray(v) ? v.filter((r) => r && typeof r === "object" && !Array.isArray(r)) : [];
2173
+ var str2 = (v) => v === void 0 || v === null ? "" : String(v);
2174
+ var strOrNull = (v) => v === void 0 || v === null ? null : String(v);
2175
+ var numOrNull = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
2176
+ var int = (v, fallback = 0) => typeof v === "number" && Number.isFinite(v) ? v : fallback;
2177
+ var passThrough = (v) => v;
2178
+ function toLoyaltyStepProgress(value) {
2179
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
2180
+ const v = value;
2181
+ const current = v["current"];
2182
+ const target = v["target"];
2183
+ if (!Number.isInteger(current) || !Number.isInteger(target)) return null;
2184
+ return { current, target };
2185
+ }
2186
+ function toStep(row) {
2187
+ return {
2188
+ stepId: strOrNull(row["step_id"]),
2189
+ index: int(row["index"]),
2190
+ action: str2(row["action"]),
2191
+ label: str2(row["label"]),
2192
+ summary: str2(row["summary"]),
2193
+ windowHours: numOrNull(row["window_hours"]),
2194
+ state: str2(row["state"]),
2195
+ progress: toLoyaltyStepProgress(row["progress"]),
2196
+ raw: row
2197
+ };
2198
+ }
2199
+ function toCardReward(row) {
2200
+ return {
2201
+ vaultEntryId: str2(row["vault_entry_id"]),
2202
+ rewardId: str2(row["reward_id"]),
2203
+ state: str2(row["state"]),
2204
+ unlockedAt: str2(row["unlocked_at"]),
2205
+ expiresAt: str2(row["expires_at"]),
2206
+ redeemedAt: strOrNull(row["redeemed_at"]),
2207
+ codeMasked: strOrNull(row["code_masked"]),
2208
+ canRedeem: row["can_redeem"] === true,
2209
+ canRevealAgain: row["can_reveal_again"] === true,
2210
+ revealUntil: strOrNull(row["reveal_until"]),
2211
+ raw: row
2212
+ };
2213
+ }
2214
+ function toLoyaltyCard(row) {
2215
+ const brand = obj(row["brand"]);
2216
+ const reward = obj(row["reward"]);
2217
+ const steps = rows(row["steps"]).map(toStep);
2218
+ return {
2219
+ cardVersion: passThrough(row["card_version"]),
2220
+ mode: str2(row["mode"]),
2221
+ programId: strOrNull(row["program_id"]),
2222
+ questId: strOrNull(row["quest_id"]),
2223
+ questVersion: numOrNull(row["quest_version"]),
2224
+ campaignId: strOrNull(row["campaign_id"]),
2225
+ title: str2(row["title"]),
2226
+ description: str2(row["description"]),
2227
+ brand: { name: strOrNull(brand["name"]), logoUrl: strOrNull(brand["logo_url"]) },
2228
+ artUrl: strOrNull(row["art_url"]),
2229
+ reward: { rewardId: strOrNull(reward["reward_id"]), name: strOrNull(reward["name"]) },
2230
+ orderMode: str2(row["order_mode"]),
2231
+ status: str2(row["status"]),
2232
+ startsAt: strOrNull(row["starts_at"]),
2233
+ endsAt: strOrNull(row["ends_at"]),
2234
+ completionHours: numOrNull(row["completion_hours"]),
2235
+ completionNote: strOrNull(row["completion_note"]),
2236
+ windowEndsAt: strOrNull(row["window_ends_at"]),
2237
+ completedAt: strOrNull(row["completed_at"]),
2238
+ stepsRequired: passThrough(row["steps_required"]),
2239
+ stepsComplete: passThrough(row["steps_complete"]),
2240
+ steps,
2241
+ rewards: rows(row["rewards"]).map(toCardReward),
2242
+ raw: row
2243
+ };
2244
+ }
2245
+ function toLoyaltyCardsResult(raw) {
2246
+ return {
2247
+ cardVersion: passThrough(raw["card_version"]),
2248
+ cards: rows(raw["cards"]).map(toLoyaltyCard),
2249
+ raw
2250
+ };
2251
+ }
2252
+ function toVaultEntry(row) {
2253
+ return {
2254
+ vaultEntryId: str2(row["vault_entry_id"]),
2255
+ rewardRef: str2(row["reward_ref"]),
2256
+ programId: str2(row["program_id"]),
2257
+ questId: strOrNull(row["quest_id"]),
2258
+ units: str2(row["units"]),
2259
+ state: str2(row["state"]),
2260
+ unlockedAt: strOrNull(row["unlocked_at"]),
2261
+ expiresAt: strOrNull(row["expires_at"]),
2262
+ redeemedAt: strOrNull(row["redeemed_at"]),
2263
+ codeMasked: strOrNull(row["code_masked"]),
2264
+ raw: row
2265
+ };
2266
+ }
2267
+ function toLoyaltyVaultResult(raw) {
2268
+ return { items: rows(raw["items"]).map(toVaultEntry), raw };
2269
+ }
2270
+ function toRedeemRewardResult(raw, vaultEntryId) {
2271
+ return {
2272
+ vaultEntryId: str2(raw["vault_entry_id"] ?? vaultEntryId),
2273
+ rewardRef: str2(raw["reward_ref"]),
2274
+ state: str2(raw["state"]),
2275
+ redeemedAt: strOrNull(raw["redeemed_at"]),
2276
+ code: strOrNull(raw["code"]),
2277
+ codeMasked: strOrNull(raw["code_masked"]),
2278
+ revealedAgain: raw["revealed_again"] === true,
2279
+ revealUntil: strOrNull(raw["reveal_until"]),
2280
+ raw
2281
+ };
2282
+ }
2283
+ function toRewardsPageLink(raw) {
2284
+ return { url: str2(raw["url"]), expiresAt: str2(raw["expires_at"]), raw };
2285
+ }
2286
+
2287
+ // src/shared/phone-change.ts
2288
+ function phoneChangeSignalMessage(changeRequestId, nonce, timestamp, decision = "approve") {
2289
+ const action = decision === "deny" ? "phone-change-deny" : "phone-change";
2290
+ return `${action}|${changeRequestId}|${nonce}|${Math.trunc(timestamp)}`;
2291
+ }
2292
+ function requireField(value, field, raw) {
2293
+ const s = value == null ? "" : String(value);
2294
+ if (!s) {
2295
+ throw new InvoError({
2296
+ message: `INVO response was missing the required \`${field}\` field.`,
2297
+ code: "INVALID_RESPONSE",
2298
+ status: 0,
2299
+ body: raw
2300
+ });
2301
+ }
2302
+ return s;
2303
+ }
2304
+ var str3 = (v) => v == null ? "" : String(v);
2305
+ var strOrNull2 = (v) => typeof v === "string" ? v : v == null ? null : String(v);
2306
+ function toPhoneChangeApprovalsResult(raw) {
2307
+ const rows2 = Array.isArray(raw["approvals"]) ? raw["approvals"] : [];
2308
+ const approvals = rows2.filter((r) => r && typeof r === "object").map((r) => ({
2309
+ changeRequestId: str3(r["change_request_id"]),
2310
+ gameName: strOrNull2(r["game_name"]),
2311
+ oldPhoneMasked: strOrNull2(r["old_phone_masked"]),
2312
+ newPhoneMasked: strOrNull2(r["new_phone_masked"]),
2313
+ expiresAt: strOrNull2(r["expires_at"])
2314
+ }));
2315
+ return { approvals, raw };
2316
+ }
2317
+ function toApprovePhoneChangeResult(raw, changeRequestId) {
2318
+ const id = str3(raw["change_request_id"] ?? changeRequestId);
2319
+ const status = requireField(raw["status"], "status", raw);
2320
+ if (status === "denied") {
2321
+ return { status: "denied", changeRequestId: id, raw };
2322
+ }
2323
+ if (status !== "confirmed") {
2324
+ throw new InvoError({
2325
+ message: `INVO answered an unexpected phone change status \`${status}\`.`,
2326
+ code: "INVALID_RESPONSE",
2327
+ status: 0,
2328
+ body: raw
2329
+ });
2330
+ }
2331
+ const out = {
2332
+ status: "confirmed",
2333
+ changeRequestId: id,
2334
+ identityId: str3(raw["identity_id"]),
2335
+ previousIdentityId: str3(raw["previous_identity_id"]),
2336
+ playersUpdated: Number(raw["players_updated"] ?? 0) || 0,
2337
+ verifiedPhone: raw["verified_phone"] === true,
2338
+ raw
2339
+ };
2340
+ if (typeof raw["player_token"] === "string" && raw["player_token"]) {
2341
+ out.playerToken = raw["player_token"];
2342
+ if (typeof raw["player_token_expires_at"] === "string") {
2343
+ out.playerTokenExpiresAt = raw["player_token_expires_at"];
2344
+ }
2345
+ }
2346
+ return out;
2347
+ }
2348
+
2349
+ // src/index.ts
2350
+ function clientInvalidInput(message) {
2351
+ return new InvoError({ message, code: "INVALID_INPUT", status: 0 });
2352
+ }
2353
+ function randomNonce() {
2354
+ const c = globalThis.crypto;
2355
+ if (!c || typeof c.getRandomValues !== "function") {
2356
+ throw clientInvalidInput(
2357
+ "No secure random source in this environment; pass a deviceSignal you built yourself."
2358
+ );
2359
+ }
2360
+ const bytes = c.getRandomValues(new Uint8Array(16));
2361
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
2362
+ }
2363
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
2364
+ function toPendingCollectItem(row) {
2365
+ return {
2366
+ transferId: String(row["transfer_id"] ?? ""),
2367
+ kind: String(row["kind"] ?? ""),
2368
+ flow: String(row["flow"] ?? ""),
2369
+ amount: row["amount"] ?? null,
2370
+ currency: String(row["currency"] ?? ""),
2371
+ counterpartyGame: String(row["counterparty_game"] ?? ""),
2372
+ expiresAt: row["expires_at"] ?? null,
2373
+ stepUpRequired: row["step_up_required"] === true,
2374
+ held: row["held"] === true,
2375
+ holdReason: row["hold_reason"] ?? null,
2376
+ raw: row
2377
+ };
2378
+ }
2379
+ function toBalanceRow(row) {
2380
+ return {
2381
+ currencyId: row["currency_id"] ?? "",
2382
+ currencyName: String(row["currency_name"] ?? ""),
2383
+ currencySymbol: row["currency_symbol"] ?? null,
2384
+ currencySymbolUrl: row["currency_symbol_url"] ?? null,
2385
+ availableBalance: String(row["available_balance"] ?? ""),
2386
+ reservedBalance: String(row["reserved_balance"] ?? ""),
2387
+ totalBalance: String(row["total_balance"] ?? ""),
2388
+ raw: row
2389
+ };
2390
+ }
2391
+ function toApproveResult(raw, transactionId) {
2392
+ const holdReason = raw["error_code"] ?? raw["code"];
2393
+ return {
2394
+ status: String(raw["status"] ?? ""),
2395
+ next: String(raw["next"] ?? ""),
2396
+ transactionId: String(raw["transaction_id"] ?? transactionId),
2397
+ claimCode: raw["claim_code"],
2398
+ claimCodeExpiresAt: raw["claim_code_expires_at"],
2399
+ holdReason: typeof holdReason === "string" ? holdReason : void 0,
2400
+ risk: raw["risk"],
2401
+ guardianApproval: raw["guardian_approval"] ?? void 0,
2402
+ pollEndpoint: raw["poll_endpoint"],
2403
+ ...typeof raw["claim_delivery"] === "string" && raw["claim_delivery"] ? { claimDelivery: raw["claim_delivery"] } : {},
2404
+ raw
2405
+ };
2406
+ }
2407
+ function toConfirmReceiptResult(raw) {
2408
+ const holdReason = raw["error_code"] ?? raw["code"];
2409
+ return {
2410
+ status: String(raw["status"] ?? ""),
2411
+ holdReason: typeof holdReason === "string" ? holdReason : void 0,
2412
+ raw
2413
+ };
2414
+ }
2415
+ var PlatformCommerceClient = class {
2416
+ /**
2417
+ * Embed INVO's hosted checkout in an iframe and listen for completion.
2418
+ *
2419
+ * ```ts
2420
+ * const handle = invo.platformCommerce.mountCheckout("#checkout", checkoutUrl, {
2421
+ * onComplete: () => showProcessing(), // then reconcile server-side
2422
+ * });
2423
+ * // later: handle.destroy();
2424
+ * ```
2425
+ *
2426
+ * Or skip the helper and redirect: `location.href = checkoutUrl` (the buyer returns to
2427
+ * the `successUrl`/`cancelUrl` you passed to the server `purchase()`).
2428
+ *
2429
+ * `onComplete` fires on the page's `INVO_CHECKOUT_COMPLETE` postMessage -- accepted ONLY
2430
+ * from the checkout URL's own origin (any other window could forge the event). It is a
2431
+ * UX signal: the sale is REAL only on the `platform_commerce.purchased` webhook, never
2432
+ * on this client event.
2433
+ */
2434
+ mountCheckout(el2, checkoutUrl, opts) {
2435
+ if (typeof document === "undefined" || typeof window === "undefined") {
2436
+ throw new InvoError({
2437
+ message: "mountCheckout requires a browser DOM (window/document).",
2438
+ code: "DOM_UNAVAILABLE",
2439
+ status: 0
2440
+ });
2441
+ }
2442
+ if (!checkoutUrl || !checkoutUrl.trim()) {
2443
+ throw new Error("mountCheckout requires the server-returned `checkoutUrl`.");
2444
+ }
2445
+ let checkoutOrigin;
2446
+ try {
2447
+ const u = new URL(checkoutUrl);
2448
+ const isLocal = u.hostname === "localhost" || u.hostname === "127.0.0.1";
2449
+ if (u.protocol !== "https:" && !(u.protocol === "http:" && isLocal)) {
2450
+ throw new Error("not https");
2451
+ }
2452
+ checkoutOrigin = u.origin;
2453
+ } catch {
2454
+ throw new InvoError({
2455
+ message: "mountCheckout requires an absolute https checkoutUrl.",
2456
+ code: "INVALID_INPUT",
2457
+ status: 0
2458
+ });
2459
+ }
2460
+ const container = typeof el2 === "string" ? document.querySelector(el2) : el2;
2461
+ if (!container) {
2462
+ throw new InvoError({
2463
+ message: `mountCheckout could not find the container "${String(el2)}".`,
2464
+ code: "MOUNT_NOT_FOUND",
2465
+ status: 0
2466
+ });
2467
+ }
2468
+ const iframe = document.createElement("iframe");
2469
+ iframe.src = checkoutUrl;
2470
+ iframe.title = opts?.title ?? "INVO checkout";
2471
+ if (opts?.className) iframe.className = opts.className;
2472
+ iframe.style.width = "100%";
2473
+ iframe.style.border = "0";
2474
+ iframe.allow = "payment";
2475
+ const onMessage = (event) => {
2476
+ if (event.origin !== checkoutOrigin) return;
2477
+ if (iframe.contentWindow && event.source !== iframe.contentWindow) return;
2478
+ const msg = event.data;
2479
+ if (!msg || msg.type !== "INVO_CHECKOUT_COMPLETE") return;
2480
+ opts?.onComplete?.(
2481
+ msg.data && typeof msg.data === "object" ? msg.data : {}
2482
+ );
2483
+ };
2484
+ window.addEventListener("message", onMessage);
2485
+ container.appendChild(iframe);
2486
+ return {
2487
+ iframe,
2488
+ destroy() {
2489
+ window.removeEventListener("message", onMessage);
2490
+ iframe.remove();
2491
+ }
2492
+ };
2493
+ }
2494
+ };
2495
+ var DEFAULT_PURCHASE_POLL_INTERVAL_MS = 1500;
2496
+ var DEFAULT_PURCHASE_POLL_TIMEOUT_MS = 18e4;
2497
+ function pollSleep(ms, signal) {
2498
+ return new Promise((resolve) => {
2499
+ if (signal?.aborted) return resolve();
2500
+ const timer = setTimeout(done, ms);
2501
+ const onAbort = () => done();
2502
+ function done() {
2503
+ clearTimeout(timer);
2504
+ signal?.removeEventListener("abort", onAbort);
2505
+ resolve();
2506
+ }
2507
+ signal?.addEventListener("abort", onAbort, { once: true });
2508
+ });
2509
+ }
2510
+ function isTransientPollFailure(err) {
2511
+ if (!(err instanceof InvoError)) return false;
2512
+ if (err.code === "ABORTED") return false;
2513
+ return err.status === 0 || err.status === 429 || err.status >= 500;
2514
+ }
2515
+ var CheckoutClient = class _CheckoutClient {
2516
+ constructor(config) {
2517
+ if (!config?.baseUrl) throw new Error("CheckoutClient requires a `baseUrl`.");
2518
+ assertSecureBaseUrl(config.baseUrl);
2519
+ this.http = new Http({
2520
+ baseUrl: config.baseUrl,
2521
+ timeoutMs: config.timeoutMs,
2522
+ fetchImpl: config.fetch,
2523
+ maxRetries: config.maxRetries,
2524
+ retryBaseDelayMs: config.retryBaseDelayMs,
2525
+ hooks: config.hooks
2526
+ });
2527
+ }
2528
+ /**
2529
+ * Wrap an `Http` the owning client already built, so `invo.checkout` shares that
2530
+ * client's baseUrl, timeout, retry budget and observability hooks.
2531
+ *
2532
+ * @internal Not part of the public API; it takes an internal type and may change.
2533
+ */
2534
+ static _withHttp(http) {
2535
+ const client = Object.create(_CheckoutClient.prototype);
2536
+ client.http = http;
2537
+ return client;
2538
+ }
2539
+ /**
2540
+ * Read a purchase's status once.
2541
+ *
2542
+ * Answers `200` with a {@link PurchaseStatusResult} for every state of the purchase,
2543
+ * including "we have your money and your coins are not there". There is no tenant gate
2544
+ * on it: a partner suspended after a buyer's card was charged is exactly the case it
2545
+ * exists for.
2546
+ *
2547
+ * Throws an {@link InvoError} on `401` (no token, bad signature, or a card-setup token:
2548
+ * `err.isWrongSessionPurpose`), `403` (a valid token for a DIFFERENT session:
2549
+ * `err.isCheckoutSessionMismatch`) and `410` (the token is more than 24 hours past its
2550
+ * expiry: `err.isCheckoutSessionExpired`; show the buyer the order id you already have
2551
+ * and a Contact support link).
2552
+ *
2553
+ * Storefront (in-client) purchases are keyed on the partner's own purchase reference
2554
+ * rather than on a checkout session, so a read by session id finds nothing and answers
2555
+ * `pending`. Do not conclude from that that such a purchase never happened.
2556
+ */
2557
+ async getPurchaseStatus(input, opts) {
2558
+ const sessionId = String(input?.sessionId ?? "").trim();
2559
+ const sessionToken = String(input?.sessionToken ?? "").trim();
2560
+ if (!sessionId) {
2561
+ throw new InvoError({
2562
+ message: "getPurchaseStatus requires `sessionId` (from createCheckout).",
2563
+ code: "INVALID_INPUT",
2564
+ status: 0
2565
+ });
2566
+ }
2567
+ if (!sessionToken) {
2568
+ throw new InvoError({
2569
+ message: "getPurchaseStatus requires `sessionToken`. The session token is the credential; the id in the path is not.",
2570
+ code: "INVALID_INPUT",
2571
+ status: 0
2572
+ });
2573
+ }
2574
+ const raw = await this.http.get(
2575
+ `/api/checkout/sessions/${encodeURIComponent(sessionId)}`,
2576
+ { kind: "bearer", token: sessionToken },
2577
+ { signal: opts?.signal }
2578
+ );
2579
+ return toPurchaseStatusResult(raw, sessionId);
2580
+ }
2581
+ /**
2582
+ * Poll {@link getPurchaseStatus} until INVO says the purchase is finished, and return
2583
+ * that final result.
2584
+ *
2585
+ * ```ts
2586
+ * const result = await invo.checkout.waitForPurchase({
2587
+ * sessionId, sessionToken,
2588
+ * intervalMs: 1500,
2589
+ * timeoutMs: 300_000,
2590
+ * signal: controller.signal,
2591
+ * onUpdate: (r) => render(r), // keep the modal open on every non-terminal read
2592
+ * });
2593
+ * if (isPurchaseCredited(result)) showCoins(result.coinsCredited, result.currencyName);
2594
+ * else if (result.message) showMessage(result.message, result.orderId); // verbatim
2595
+ * ```
2596
+ *
2597
+ * IT STOPS ON `result.terminal` AND ON NOTHING ELSE. `terminal` is INVO's word, read off
2598
+ * the response; this loop never recomputes it from `status`, so a status a later backend
2599
+ * introduces cannot end a wait here as a success. `paid_pending_credit` is deliberately
2600
+ * not terminal and is never promoted to a failure by age: INVO's reconciler recovers a
2601
+ * stalled credit, and telling a buyer they lost money they are about to receive would
2602
+ * be a fresh lie in place of the old silence.
2603
+ *
2604
+ * A transient failure (network, timeout, 429, 5xx) is polled through rather than raised;
2605
+ * a `401`, `403` or `410` is raised at once. On the cap it returns the LAST result it
2606
+ * read, whose `terminal` is false. Nothing is guessed and nothing is thrown, so the page
2607
+ * keeps showing the buyer what INVO last said. If it never got a single answer, the last
2608
+ * transport failure is thrown.
2609
+ */
2610
+ async waitForPurchase(input) {
2611
+ const intervalMs = Math.max(0, input?.intervalMs ?? DEFAULT_PURCHASE_POLL_INTERVAL_MS);
2612
+ const timeoutMs = Math.max(0, input?.timeoutMs ?? DEFAULT_PURCHASE_POLL_TIMEOUT_MS);
2613
+ const maxAttempts = input?.maxAttempts === void 0 ? Number.POSITIVE_INFINITY : Math.max(1, input.maxAttempts);
2614
+ const deadline = Date.now() + timeoutMs;
2615
+ const signal = input?.signal;
2616
+ let last;
2617
+ let lastFailure;
2618
+ for (let attempts = 0; ; ) {
2619
+ if (signal?.aborted) {
2620
+ throw new InvoError({
2621
+ message: "waitForPurchase was aborted",
2622
+ code: "ABORTED",
2623
+ status: 0
2624
+ });
2625
+ }
2626
+ attempts += 1;
2627
+ try {
2628
+ const result = await this.getPurchaseStatus(input, { signal });
2629
+ last = result;
2630
+ lastFailure = void 0;
2631
+ try {
2632
+ input?.onUpdate?.(result);
2633
+ } catch {
2634
+ }
2635
+ if (result.terminal) return result;
2636
+ } catch (err) {
2637
+ if (!isTransientPollFailure(err)) throw err;
2638
+ lastFailure = err;
2639
+ }
2640
+ if (attempts >= maxAttempts) break;
2641
+ if (Date.now() + intervalMs >= deadline) break;
2642
+ await pollSleep(intervalMs, signal);
2643
+ }
2644
+ if (last) return last;
2645
+ throw lastFailure instanceof Error ? lastFailure : new InvoError({
2646
+ message: "waitForPurchase could not read the purchase status before the cap.",
2647
+ code: "PURCHASE_STATUS_UNAVAILABLE",
2648
+ status: 0
2649
+ });
2650
+ }
2651
+ };
2652
+ var InvoClient = class {
2653
+ constructor(config) {
2654
+ /**
2655
+ * Platform Commerce (ecommerce) hosted-checkout embed. Use after
2656
+ * `InvoServer.platformCommerce.purchase({ fundingSource: "card" })` returns a
2657
+ * `checkoutUrl` — either redirect the buyer there, or embed it with
2658
+ * `mountCheckout`. No card element, no processor dependency. See
2659
+ * {@link PlatformCommerceClient}.
2660
+ */
2661
+ this.platformCommerce = new PlatformCommerceClient();
2662
+ if (!config.token) throw new Error("InvoClient requires a player `token`.");
2663
+ if (!config.baseUrl) throw new Error("InvoClient requires a `baseUrl`.");
2664
+ assertSecureBaseUrl(config.baseUrl);
2665
+ this.http = new Http({
2666
+ baseUrl: config.baseUrl,
2667
+ timeoutMs: config.timeoutMs,
2668
+ fetchImpl: config.fetch,
2669
+ maxRetries: config.maxRetries,
2670
+ retryBaseDelayMs: config.retryBaseDelayMs,
2671
+ hooks: config.hooks
2672
+ // Browser: do NOT set User-Agent (forbidden header); the browser's own UA is fine.
2673
+ });
2674
+ this.auth = { kind: "bearer", token: config.token };
2675
+ this.refreshToken = config.refreshToken;
2676
+ this.checkout = CheckoutClient._withHttp(this.http);
2677
+ }
2678
+ assertWebAuthn() {
2679
+ if (typeof navigator === "undefined" || !navigator.credentials) {
2680
+ throw new Error("WebAuthn is not available in this environment (browser required).");
2681
+ }
2682
+ }
2683
+ /**
2684
+ * Enroll a passkey for the token's identity (register/begin -> create() -> register/complete).
2685
+ * Gates: `ENROLLMENT_REQUIRES_AUTHORIZATION` → {@link enrollmentBegin} OTP grant;
2686
+ * `ENROLLMENT_REQUIRES_PROOF` → {@link linkDevice}, or {@link recoveryBegin} when the
2687
+ * player lost/deleted the old passkey ("Lost or replaced your passkey?").
2688
+ */
2689
+ async enrollPasskey(opts) {
2690
+ this.assertWebAuthn();
2691
+ const signal = opts?.signal;
2692
+ return this.withTokenRetry(async () => {
2693
+ const options = await this.post(
2694
+ "/api/sdk/webauthn/register/begin",
2695
+ void 0,
2696
+ signal
2697
+ );
2698
+ const cred = await navigator.credentials.create({
2699
+ publicKey: toCreationOptions(options),
2700
+ signal
2701
+ });
2702
+ if (!cred) throw new Error("Passkey creation was cancelled or returned no credential.");
2703
+ const raw = await this.post(
2704
+ "/api/sdk/webauthn/register/complete",
2705
+ { credential: registrationToJSON(cred) },
2706
+ signal
2707
+ );
2708
+ return { status: String(raw["status"] ?? ""), device: raw["device"] ?? null, raw };
2709
+ });
2710
+ }
2711
+ async approveHosted(opts) {
2712
+ const txn = String(opts.transactionId ?? "");
2713
+ const id = encodeURIComponent(txn);
2714
+ const signal = opts.signal;
2715
+ const api = {
2716
+ begin: () => this.withTokenRetry(
2717
+ () => this.post(
2718
+ "/api/sdk/approvals/device/begin",
2719
+ { transaction_id: txn, flow: opts.flow, channel: "popup" },
2720
+ signal
2721
+ )
2722
+ ),
2723
+ poll: (deviceCode) => this.withTokenRetry(
2724
+ () => this.post(
2725
+ "/api/sdk/approvals/device/poll",
2726
+ { device_code: deviceCode },
2727
+ signal
2728
+ )
2729
+ ),
2730
+ confirmEnrollment: (deviceCode, decision) => this.withTokenRetry(
2731
+ () => this.post(
2732
+ "/api/sdk/approvals/device/confirm-enrollment",
2733
+ { device_code: deviceCode, decision },
2734
+ signal
2735
+ )
2736
+ ),
2737
+ approve: (deviceCode) => this.withTokenRetry(async () => {
2738
+ const body = { device_code: deviceCode };
2739
+ switch (opts.flow) {
2740
+ case "transfer":
2741
+ return toApproveResult(
2742
+ await this.post(`/api/sdk/transfers/${id}/approve`, body, signal),
2743
+ txn
2744
+ );
2745
+ case "send":
2746
+ return toApproveResult(
2747
+ await this.post(`/api/sdk/send/${id}/approve`, body, signal),
2748
+ txn
2749
+ );
2750
+ case "send_receipt":
2751
+ return toConfirmReceiptResult(
2752
+ await this.post(`/api/sdk/send/${id}/confirm-receipt`, body, signal)
2753
+ );
2754
+ case "transfer_receipt":
2755
+ return toConfirmReceiptResult(
2756
+ await this.post(`/api/sdk/transfers/${id}/confirm-receipt`, body, signal)
2757
+ );
2758
+ default:
2759
+ throw new Error(`approveHosted: unknown flow "${String(opts.flow)}".`);
2760
+ }
2761
+ })
2762
+ };
2763
+ return runHostedApproval(opts, api);
2764
+ }
2765
+ /**
2766
+ * Approve a SEND with the player's passkey.
2767
+ *
2768
+ * Throws 403 `err.isPlayerTokenStale` when the player token predates a change to the
2769
+ * sender's identity (their phone was added on the initiate). Not retried automatically,
2770
+ * because this call moves money: re-mint the player token (or use the `playerToken`
2771
+ * your server got back from `initiateSend`) and retry once.
2772
+ */
2773
+ async approveSend(transactionId, opts) {
2774
+ return this.approve("send", transactionId, opts);
2775
+ }
2776
+ /** Approve a TRANSFER with the player's passkey (returns the sender's claim code). Same
2777
+ * `err.isPlayerTokenStale` handling as {@link approveSend}: re-mint and retry once. */
2778
+ async approveTransfer(transactionId, opts) {
2779
+ return this.approve("transfers", transactionId, opts);
2780
+ }
2781
+ /**
2782
+ * Recipient self-claims a SEND with their passkey.
2783
+ *
2784
+ * May throw a 409 with `err.isPhoneShareApprovalRequired` when the receiver phone is
2785
+ * contested (the collecting identity isn't yet authorized for it). NOT a failure — the
2786
+ * money is held and the phone owner is texted to approve. Show `err.message`
2787
+ * (`err.phoneShareLast4` names the phone), then **retry this same call** once approved
2788
+ * (it then succeeds idempotently); on denial/expiry the backend refunds the sender.
2789
+ */
2790
+ async confirmReceiptSend(transactionId, opts) {
2791
+ return this.confirmReceipt("send", transactionId, opts);
2792
+ }
2793
+ /** Recipient self-claims a TRANSFER with their passkey. Can throw the same phone-share
2794
+ * 409 as {@link confirmReceiptSend} (`err.isPhoneShareApprovalRequired`) — handle it the
2795
+ * same way: show `err.message`, retry after the phone owner approves. */
2796
+ async confirmReceiptTransfer(transactionId, opts) {
2797
+ return this.confirmReceipt("transfers", transactionId, opts);
2798
+ }
2799
+ /**
2800
+ * Phone changes waiting for THIS player's enrolled device to approve
2801
+ * (`GET /api/sdk/players/phone/change-approvals`, player token). A row appears after the
2802
+ * player entered the emailed code on INVO's page for a change whose `confirmation` is
2803
+ * `"email_code_and_device"`. Show each one ("Approve changing your number to
2804
+ * ***-***-0123?") and answer it with {@link approvePhoneChange}. Read-only.
2805
+ */
2806
+ async listPhoneChangeApprovals(opts) {
2807
+ return this.withTokenRetry(async () => {
2808
+ const raw = await this.get(
2809
+ "/api/sdk/players/phone/change-approvals",
2810
+ opts?.signal
2811
+ );
2812
+ return toPhoneChangeApprovalsResult(raw);
2813
+ });
2814
+ }
2815
+ /**
2816
+ * Approve (or, with `decision: "deny"`, decline) a phone change from the player's enrolled
2817
+ * device (`POST /api/sdk/players/phone/change-requests/{id}/approve`, player token).
2818
+ *
2819
+ * The device key signs `phone-change|<changeRequestId>|<nonce>|<timestamp>` to approve or
2820
+ * `phone-change-deny|<changeRequestId>|<nonce>|<timestamp>` to decline (`timestamp` in
2821
+ * epoch seconds). Either pass `sign`, and the SDK makes a fresh nonce and timestamp, builds
2822
+ * that message and asks you for the base64 signature; or pass a `deviceSignal` you signed
2823
+ * yourself (build the message with {@link phoneChangeSignalMessage}). This is a device key
2824
+ * registered with INVO, not a passkey.
2825
+ *
2826
+ * `status: "confirmed"` means the change is applied: store `identityId` and use
2827
+ * `playerToken` (tokens minted before the change are stale). `status: "denied"` means
2828
+ * nothing changed. Refusals: 409 `err.isChangeRequestNotReady` (the player has not entered
2829
+ * the code on INVO's page yet), 409 `err.isChangeRequestNotPending` (`err.changeRequestStatus`),
2830
+ * 409 `err.isDeviceEnrolledAfterRequest` (this device was set up after the change was
2831
+ * requested; approve on the earlier device, or the game creates a new request), 409
2832
+ * `err.isPhoneChangeRecoveryCooldown` (a recent sign-in recovery; retry later, declining
2833
+ * still works), 404 `err.isChangeRequestNotFound`, 401 `err.isDeviceSignalRejected`, 403
2834
+ * `DEVICE_REQUIRES_ELEVATION`, or any refusal of the change itself (for example
2835
+ * `err.isPendingTransfersToOldPhone`).
2836
+ */
2837
+ async approvePhoneChange(changeRequestId, input, opts) {
2838
+ if (typeof changeRequestId !== "string" || !changeRequestId.trim()) {
2839
+ throw clientInvalidInput("changeRequestId is required.");
2840
+ }
2841
+ if (!input || typeof input.deviceFingerprint !== "string" || !input.deviceFingerprint.trim()) {
2842
+ throw clientInvalidInput("deviceFingerprint is required.");
2843
+ }
2844
+ const decision = input.decision ?? "approve";
2845
+ if (decision !== "approve" && decision !== "deny") {
2846
+ throw clientInvalidInput('decision must be "approve" or "deny".');
2847
+ }
2848
+ const hasSignal = input.deviceSignal !== void 0;
2849
+ const hasSigner = typeof input.sign === "function";
2850
+ if (hasSignal === hasSigner) {
2851
+ throw clientInvalidInput("Pass exactly one of deviceSignal or sign.");
2852
+ }
2853
+ if (hasSignal) {
2854
+ const sig = input.deviceSignal;
2855
+ if (!sig || typeof sig.nonce !== "string" || !sig.nonce || typeof sig.timestamp !== "number" || !Number.isInteger(sig.timestamp) || typeof sig.signature !== "string" || !sig.signature) {
2856
+ throw clientInvalidInput(
2857
+ "deviceSignal needs a nonce (string), an integer epoch-seconds timestamp and a base64 signature."
2858
+ );
2859
+ }
2860
+ }
2861
+ const id = encodeURIComponent(changeRequestId);
2862
+ const signal = opts?.signal;
2863
+ return this.withTokenRetry(async () => {
2864
+ let deviceSignal;
2865
+ if (hasSignal) {
2866
+ const sig = input.deviceSignal;
2867
+ deviceSignal = {
2868
+ transfer_id: changeRequestId,
2869
+ nonce: sig.nonce,
2870
+ timestamp: sig.timestamp,
2871
+ signature: sig.signature
2872
+ };
2873
+ } else {
2874
+ const nonce = randomNonce();
2875
+ const timestamp = Math.floor(Date.now() / 1e3);
2876
+ const signature = await input.sign(
2877
+ phoneChangeSignalMessage(changeRequestId, nonce, timestamp, decision)
2878
+ );
2879
+ if (typeof signature !== "string" || !signature) {
2880
+ throw clientInvalidInput("sign must return the base64 signature as a non-empty string.");
2881
+ }
2882
+ deviceSignal = { transfer_id: changeRequestId, nonce, timestamp, signature };
2883
+ }
2884
+ const raw = await this.post(
2885
+ `/api/sdk/players/phone/change-requests/${id}/approve`,
2886
+ { device_fingerprint: input.deviceFingerprint, device_signal: deviceSignal, decision },
2887
+ signal
2888
+ );
2889
+ return toApprovePhoneChangeResult(raw, changeRequestId);
2890
+ });
2891
+ }
2892
+ /**
2893
+ * Interchangeable methods (§4.6): prove an *already-enrolled* method (e.g. the
2894
+ * INVO app device key) to authorize adding a new partner passkey. The returned
2895
+ * single-use grant lets a subsequent enrollPasskey() succeed instead of being
2896
+ * blocked with ENROLLMENT_REQUIRES_PROOF.
2897
+ *
2898
+ * begin -> navigator.credentials.get() -> complete with { link_id, webauthn_assertion }.
2899
+ *
2900
+ * Call it with no arguments: `await invo.linkDevice()`. THE SERVER MINTS THE
2901
+ * LINK ID, so there is nothing for the caller to supply. The parameter is kept
2902
+ * (optional, and sent but ignored by the server) so that code written against
2903
+ * 3.10 and earlier, which had to pass a placeholder, keeps compiling and
2904
+ * working unchanged.
2905
+ */
2906
+ async linkDevice(linkId, opts) {
2907
+ this.assertWebAuthn();
2908
+ const signal = opts?.signal;
2909
+ return this.withTokenRetry(async () => {
2910
+ const begin = await this.post(
2911
+ "/api/sdk/device/link/webauthn/begin",
2912
+ // The server ignores the body and mints its own id; `linkId` travels only
2913
+ // for callers who still pass one.
2914
+ linkId ? { link_id: linkId } : {},
2915
+ signal
2916
+ );
2917
+ const cred = await navigator.credentials.get({
2918
+ publicKey: toRequestOptions(begin.options),
2919
+ signal
2920
+ });
2921
+ if (!cred) throw new Error("Passkey assertion was cancelled or returned no credential.");
2922
+ const raw = await this.post(
2923
+ "/api/sdk/device/link/webauthn/complete",
2924
+ { link_id: begin.link_id, webauthn_assertion: assertionToJSON(cred) },
2925
+ signal
2926
+ );
2927
+ return { status: String(raw["status"] ?? ""), raw };
2928
+ });
2929
+ }
2930
+ /**
2931
+ * List the player's own pending items to collect (browser, player-token). Each row's
2932
+ * `kind` tells you which action to call: `"identity_gate"` → `approve*` (you initiated);
2933
+ * `"receiving_confirm"` → `confirmReceipt*` (a peer sent to you). PII-free — no claim
2934
+ * code or phone (those are only on the server-side `getInboundPending`).
2935
+ */
2936
+ async getPendingCollect(opts) {
2937
+ return this.withTokenRetry(async () => {
2938
+ const raw = await this.get(
2939
+ "/api/sdk/transfers/pending",
2940
+ opts?.signal
2941
+ );
2942
+ const rows2 = Array.isArray(raw["pending"]) ? raw["pending"] : [];
2943
+ return { pending: rows2.map(toPendingCollectItem), raw };
2944
+ });
2945
+ }
2946
+ /**
2947
+ * List the games/tenants this player can send/transfer to, with display metadata
2948
+ * inline (name, icon, currency, min/max limits) — one call, no per-game lookup.
2949
+ * Source game is the token's own game. Player-token (browser).
2950
+ */
2951
+ async getDestinations(query, opts) {
2952
+ const direction = query?.direction ?? "transfer";
2953
+ return this.withTokenRetry(async () => {
2954
+ const raw = await this.get(
2955
+ `/api/sdk/destinations?direction=${encodeURIComponent(direction)}`,
2956
+ opts?.signal
2957
+ );
2958
+ return toDestinationsResult(raw, direction);
2959
+ });
2960
+ }
2961
+ /**
2962
+ * The player's balances for the token's game (browser, player-token). Amounts are
2963
+ * decimal strings. A player who hasn't transacted here yet returns `200` with an empty
2964
+ * `balances` array (show 0.00) — not an error; a `404 GAME_NOT_FOUND` (bad game/token)
2965
+ * throws. Rows include the currency symbol + icon URL (each may be null).
2966
+ */
2967
+ async getBalance(opts) {
2968
+ return this.withTokenRetry(async () => {
2969
+ const raw = await this.get("/api/sdk/balance", opts?.signal);
2970
+ const rows2 = Array.isArray(raw["balances"]) ? raw["balances"] : [];
2971
+ const summary = raw["summary"] ?? {};
2972
+ return {
2973
+ gameId: raw["game_id"] ?? "",
2974
+ gameName: String(raw["game_name"] ?? ""),
2975
+ balances: rows2.map(toBalanceRow),
2976
+ totalValue: String(summary["total_value"] ?? "0"),
2977
+ currencyCount: Number(summary["currency_count"] ?? rows2.length),
2978
+ hasFunds: summary["has_funds"] === true,
2979
+ raw
2980
+ };
2981
+ });
2982
+ }
2983
+ // ---- Loyalty and rewards (player token) ----
2984
+ /**
2985
+ * The signed-in player's loyalty cards in this game: one card per program, each step with
2986
+ * its `state` and `progress` (`{ current, target }`, or `null` when the number could not
2987
+ * be read this time: render `state` alone then), and the rewards the player unlocked.
2988
+ * A card never carries a code; a redeemed reward shows its mask. Your server reads the
2989
+ * same cards for any of your players with `InvoServer.getPlayerRewards(playerEmail)`.
2990
+ */
2991
+ async getMyRewards(opts) {
2992
+ return this.withTokenRetry(async () => {
2993
+ const raw = await this.get("/api/sdk/loyalty/me/card", opts?.signal);
2994
+ return toLoyaltyCardsResult(raw);
2995
+ });
2996
+ }
2997
+ /** Every reward the signed-in player holds or held, newest first. Codes are masked. */
2998
+ async getMyVault(opts) {
2999
+ return this.withTokenRetry(async () => {
3000
+ const raw = await this.get("/api/sdk/loyalty/me/vault", opts?.signal);
3001
+ return toLoyaltyVaultResult(raw);
3002
+ });
3003
+ }
3004
+ /**
3005
+ * Redeem one unlocked reward and return its code. This is the only response that
3006
+ * carries a code: show it straight away and never log, cache or store it. Calling again
3007
+ * for a reward this player already redeemed shows the code once more while the card's
3008
+ * `canRevealAgain` is true (`revealedAgain: true`). Never auto-retried.
3009
+ *
3010
+ * Refusals: `409 already_redeemed` (`err.isRewardAlreadyRedeemed`), `404
3011
+ * vault_entry_not_found` (`err.isRewardNotFound`), `410 vault_entry_expired`
3012
+ * (`err.isRewardExpired`), `409 inventory_exhausted` / `409 conflict`
3013
+ * (`err.isRewardUnavailable`: no units or codes left, or the reward is reserved or revoked).
3014
+ */
3015
+ async redeemReward(vaultEntryId, opts) {
3016
+ if (typeof vaultEntryId !== "string" || !UUID_RE.test(vaultEntryId.trim())) {
3017
+ throw new InvoError({
3018
+ message: `vaultEntryId must be a reward's vaultEntryId (got ${JSON.stringify(vaultEntryId)}).`,
3019
+ code: "INVALID_INPUT",
3020
+ status: 0
3021
+ });
3022
+ }
3023
+ const id = vaultEntryId.trim();
3024
+ return this.withTokenRetry(async () => {
3025
+ const raw = await this.post(
3026
+ `/api/sdk/loyalty/me/vault/${encodeURIComponent(id)}/redeem`,
3027
+ void 0,
3028
+ opts?.signal
3029
+ );
3030
+ return toRedeemRewardResult(raw, id);
3031
+ });
3032
+ }
3033
+ /**
3034
+ * A short-lived link to INVO's hosted "My rewards" page for the signed-in player: their
3035
+ * cards, progress and rewards, with a Redeem button. Open `url` in a browser or web view
3036
+ * (it cannot be embedded in an iframe). Ask for a fresh link each time the player opens
3037
+ * the page; never share or store it.
3038
+ */
3039
+ async getRewardsPageLink(opts) {
3040
+ return this.withTokenRetry(async () => {
3041
+ const raw = await this.post(
3042
+ "/api/sdk/loyalty/me/rewards-page",
3043
+ void 0,
3044
+ opts?.signal
3045
+ );
3046
+ return toRewardsPageLink(raw);
3047
+ });
3048
+ }
3049
+ /**
3050
+ * Report a gameplay event for the signed-in player to INVO's loyalty engine
3051
+ * (`POST /api/sdk/loyalty/events`, player token). Use it for sessions, milestones and
3052
+ * registered custom events (see {@link GameEventType}). Events your SERVER reports with
3053
+ * `InvoServer.reportGameEvent` are the ones trusted for rewards; prefer those when a
3054
+ * reward depends on the event.
3055
+ *
3056
+ * Pass your own `eventId` (a UUID) or reuse the returned one if you retry, so INVO counts
3057
+ * the event once. Not auto-retried from the browser.
3058
+ *
3059
+ * Refusals: `INVALID_INPUT` before the network (non-`game.*` type, malformed `eventId`,
3060
+ * `occurredAt` without a timezone, non-object payload); `400 RESERVED_EVENT_TYPE` /
3061
+ * `EVENT_TYPE_NOT_ALLOWED`; `401 SDK_TOKEN_MISSING` / `SDK_TOKEN_WRONG_SCOPE`;
3062
+ * `422 validation_failed`.
3063
+ */
3064
+ async reportGameEvent(input, opts) {
3065
+ const { body, eventId } = buildGameEventBody(input);
3066
+ return this.withTokenRetry(async () => {
3067
+ const raw = await this.post("/api/sdk/loyalty/events", body, opts?.signal);
3068
+ return toReportGameEventResult(raw ?? {}, eventId);
3069
+ });
3070
+ }
3071
+ /**
3072
+ * First-enrollment OTP grant (§4.2). When `enrollPasskey()` throws
3073
+ * `ENROLLMENT_REQUIRES_AUTHORIZATION` (`err.isEnrollmentAuthorizationRequired`), call
3074
+ * this to send a 6-digit code to the player's phone + email on file, collect the code,
3075
+ * call `enrollmentVerify(code)`, then RETRY the SAME `enrollPasskey()` —
3076
+ * `register/complete` auto-consumes the server-side grant (30-min TTL). For
3077
+ * `ENROLLMENT_REQUIRES_PROOF` (`err.isEnrollmentProofRequired`) use `linkDevice`
3078
+ * (player still has the other method) or `recoveryBegin`/`recoveryComplete`
3079
+ * (player lost/deleted their passkey).
3080
+ */
3081
+ async enrollmentBegin(opts) {
3082
+ return this.withTokenRetry(async () => {
3083
+ const raw = await this.post(
3084
+ "/api/sdk/device/enrollment/begin",
3085
+ void 0,
3086
+ opts?.signal
3087
+ );
3088
+ return {
3089
+ status: String(raw["status"] ?? ""),
3090
+ channels: Array.isArray(raw["channels"]) ? raw["channels"] : [],
3091
+ raw
3092
+ };
3093
+ });
3094
+ }
3095
+ /** Verify the enrollment OTP (see {@link enrollmentBegin}); on success, retry `enrollPasskey()`. */
3096
+ async enrollmentVerify(code, opts) {
3097
+ if (!code || !code.trim()) throw new Error("enrollmentVerify requires the OTP `code`.");
3098
+ return this.withTokenRetry(async () => {
3099
+ const raw = await this.post(
3100
+ "/api/sdk/device/enrollment/verify",
3101
+ { code },
3102
+ opts?.signal
3103
+ );
3104
+ return { status: String(raw["status"] ?? ""), raw };
3105
+ });
3106
+ }
3107
+ /**
3108
+ * Passkey recovery — "Lost or replaced your passkey?". Deleting a passkey on the
3109
+ * device never tells the server the key is gone, so the next `enrollPasskey()` is
3110
+ * blocked by the anti-takeover gate with `ENROLLMENT_REQUIRES_PROOF`
3111
+ * (`err.isEnrollmentProofRequired`). When the player can't prove the old method
3112
+ * (they deleted/lost it — otherwise prefer `linkDevice`), run:
3113
+ *
3114
+ * 1. `recoveryBegin()` — sends a one-time code to the phone/email on file
3115
+ * (422 `no_channel_on_file`, 429 `rate_limited` at 5/10min).
3116
+ * 2. `recoveryComplete(code)` — deactivates the stale server-side passkey and
3117
+ * authorizes a fresh enrollment (400 `ENROLLMENT_CODE_INVALID` on a wrong/
3118
+ * expired code — attempt-capped; let the user retry or resend).
3119
+ * 3. Immediately retry the SAME `enrollPasskey()` — it now succeeds.
3120
+ *
3121
+ * The owner also gets an out-of-band "your passkey was reset" SMS/email — that's
3122
+ * the intended tamper alert; surface nothing special for it.
3123
+ *
3124
+ * ⚠ 24-HOUR MONEY COOLDOWN: a recovery-enrolled passkey logs in and COLLECTS
3125
+ * funds immediately, but `approveSend`/`approveTransfer` throw
3126
+ * `PASSKEY_RECOVERY_COOLDOWN` (403; `err.isPasskeyRecoveryCooldown`,
3127
+ * `err.retryAfterAt`) for 24h — SIM-swap protection. Show the pause message with
3128
+ * the timestamp; do not retry-loop it.
3129
+ *
3130
+ * If the OS itself fails to SAVE a new passkey ("there is a problem saving your
3131
+ * passkey"), have the user delete the stale entry in their password manager first
3132
+ * (iPhone: Settings → Passwords; Android: Google Password Manager; Windows:
3133
+ * Settings → Accounts → Passkeys).
3134
+ */
3135
+ async recoveryBegin(opts) {
3136
+ return this.withTokenRetry(async () => {
3137
+ const raw = await this.post(
3138
+ "/api/sdk/device/recover/begin",
3139
+ void 0,
3140
+ opts?.signal
3141
+ );
3142
+ return {
3143
+ status: String(raw["status"] ?? ""),
3144
+ channels: Array.isArray(raw["channels"]) ? raw["channels"] : [],
3145
+ raw
3146
+ };
3147
+ });
3148
+ }
3149
+ /** Verify the recovery code (see {@link recoveryBegin}); on success, call `enrollPasskey()`. */
3150
+ async recoveryComplete(code, opts) {
3151
+ if (!code || !code.trim()) throw new Error("recoveryComplete requires the one-time `code`.");
3152
+ return this.withTokenRetry(async () => {
3153
+ const raw = await this.post(
3154
+ "/api/sdk/device/recover/complete",
3155
+ { code },
3156
+ opts?.signal
3157
+ );
3158
+ return {
3159
+ status: String(raw["status"] ?? ""),
3160
+ deactivatedCount: Number(raw["deactivated_count"] ?? 0),
3161
+ next: typeof raw["next"] === "string" ? raw["next"] : void 0,
3162
+ raw
3163
+ };
3164
+ });
3165
+ }
3166
+ // --- internals ---
3167
+ /** POST with the current player token. Token-expiry retry is handled one level
3168
+ * up by withTokenRetry (which re-runs the whole ceremony, not a single call). */
3169
+ async post(path, body, signal) {
3170
+ return this.http.post(path, body, this.auth, { signal });
3171
+ }
3172
+ async get(path, signal) {
3173
+ return this.http.get(path, this.auth, { signal });
3174
+ }
3175
+ /**
3176
+ * Run a whole flow, retrying it ONCE if any call fails with SDK_TOKEN_EXPIRED
3177
+ * and a `refreshToken` hook is configured. We re-run the entire begin→get→
3178
+ * complete ceremony (not just the failed call) so the retry always uses a fresh,
3179
+ * unconsumed challenge — never replaying a single-use WebAuthn assertion (§4.4).
3180
+ * The refresh is single-flighted so concurrent expiries trigger one re-mint.
3181
+ */
3182
+ async withTokenRetry(run) {
3183
+ try {
3184
+ return await run();
3185
+ } catch (err) {
3186
+ if (err instanceof InvoError && err.isTokenExpired && await this.tryRefresh()) {
3187
+ return await run();
3188
+ }
3189
+ throw err;
3190
+ }
3191
+ }
3192
+ async tryRefresh() {
3193
+ if (!this.refreshToken) return false;
3194
+ if (!this.refreshInFlight) {
3195
+ this.refreshInFlight = Promise.resolve(this.refreshToken()).finally(() => {
3196
+ this.refreshInFlight = void 0;
3197
+ });
3198
+ }
3199
+ const fresh = await this.refreshInFlight;
3200
+ if (!fresh) return false;
3201
+ this.auth = { kind: "bearer", token: fresh };
3202
+ return true;
3203
+ }
3204
+ async runAssertion(beginPath, beginBody, signal) {
3205
+ this.assertWebAuthn();
3206
+ const options = await this.post(beginPath, beginBody, signal);
3207
+ const cred = await navigator.credentials.get({
3208
+ publicKey: toRequestOptions(options),
3209
+ signal
3210
+ });
3211
+ if (!cred) throw new Error("Passkey assertion was cancelled or returned no credential.");
3212
+ return assertionToJSON(cred);
3213
+ }
3214
+ async approve(flow, transactionId, opts) {
3215
+ const id = encodeURIComponent(transactionId);
3216
+ const signal = opts?.signal;
3217
+ return this.withTokenRetry(async () => {
3218
+ const assertion = await this.runAssertion(
3219
+ `/api/sdk/${flow}/${id}/approve/webauthn/begin`,
3220
+ void 0,
3221
+ signal
3222
+ );
3223
+ const raw = await this.post(
3224
+ `/api/sdk/${flow}/${id}/approve`,
3225
+ { webauthn_assertion: assertion },
3226
+ signal
3227
+ );
3228
+ return toApproveResult(raw, transactionId);
3229
+ });
3230
+ }
3231
+ async confirmReceipt(flow, transactionId, opts) {
3232
+ const id = encodeURIComponent(transactionId);
3233
+ const signal = opts?.signal;
3234
+ return this.withTokenRetry(async () => {
3235
+ const assertion = await this.runAssertion(
3236
+ `/api/sdk/${flow}/${id}/confirm-receipt/webauthn/begin`,
3237
+ void 0,
3238
+ signal
3239
+ );
3240
+ const raw = await this.post(
3241
+ `/api/sdk/${flow}/${id}/confirm-receipt`,
3242
+ { webauthn_assertion: assertion },
3243
+ signal
3244
+ );
3245
+ return toConfirmReceiptResult(raw);
3246
+ });
3247
+ }
3248
+ };
1135
3249
 
1136
3250
  // src/game/client.ts
1137
3251
  var InvoGameError = class extends Error {
@@ -1142,6 +3256,15 @@ var InvoGameError = class extends Error {
1142
3256
  this.status = status;
1143
3257
  }
1144
3258
  };
3259
+ var TRANSFERS_UNKNOWN = {
3260
+ enabled: false,
3261
+ reason: "checking",
3262
+ demo: false,
3263
+ scope: "network",
3264
+ recipientFields: { email: "optional", phone: "required" },
3265
+ apiBaseUrl: null,
3266
+ approval: "passkey"
3267
+ };
1145
3268
  var InvoGameEconomy = class {
1146
3269
  constructor(options = {}) {
1147
3270
  this.player = null;
@@ -1154,6 +3277,8 @@ var InvoGameEconomy = class {
1154
3277
  this.pendingEarn = 0;
1155
3278
  this.pendingEarnReason = "earned in play";
1156
3279
  this.earnTimer = null;
3280
+ this.transferStatusCache = null;
3281
+ this.transferClient = null;
1157
3282
  this.base = (options.baseUrl ?? "/api/invo").replace(/\/+$/, "");
1158
3283
  this.storage = options.storage === void 0 ? safeLocalStorage() : options.storage;
1159
3284
  this.storageKey = options.storageKey ?? "invo.game.session";
@@ -1161,6 +3286,7 @@ var InvoGameEconomy = class {
1161
3286
  this.earnFlushMs = options.earnFlushMs ?? 750;
1162
3287
  this.pollMs = options.purchasePollMs ?? 2e3;
1163
3288
  this.purchaseTimeoutMs = options.purchaseTimeoutMs ?? 15 * 60 * 1e3;
3289
+ this.invoFetch = options.invoFetch;
1164
3290
  }
1165
3291
  /** Subscribe; returns the unsubscribe function. */
1166
3292
  on(type, listener) {
@@ -1334,7 +3460,7 @@ var InvoGameEconomy = class {
1334
3460
  const started = Date.now();
1335
3461
  let closedAt = null;
1336
3462
  for (; ; ) {
1337
- await sleep(this.pollMs);
3463
+ await sleep2(this.pollMs);
1338
3464
  let p = null;
1339
3465
  try {
1340
3466
  p = await this.request("GET", `/purchases/${encodeURIComponent(purchaseRef)}`);
@@ -1410,7 +3536,146 @@ var InvoGameEconomy = class {
1410
3536
  return null;
1411
3537
  }
1412
3538
  }
3539
+ // ---------------------------------------------------------------- transfers and sends (3.30.0)
3540
+ /**
3541
+ * Whether players can move currency to other players here, who can receive, and which
3542
+ * recipient details to ask for. Cached; pass `true` to ask the server again.
3543
+ */
3544
+ transferStatus(refresh = false) {
3545
+ if (!this.transferStatusCache || refresh) {
3546
+ this.transferStatusCache = this.request("GET", "/transfers/status").catch(() => {
3547
+ this.transferStatusCache = null;
3548
+ return TRANSFERS_UNKNOWN;
3549
+ });
3550
+ }
3551
+ return this.transferStatusCache;
3552
+ }
3553
+ /**
3554
+ * Get ready to transfer: fetches the short-lived INVO player token the approval and collect
3555
+ * calls use. {@link transferDestinations} and {@link pendingTransfers} call it for you; the
3556
+ * approve and collect calls need it done BEFORE the click, so the INVO window can open.
3557
+ */
3558
+ async prepareTransfers() {
3559
+ if (this.transferClient) return;
3560
+ const minted = await this.request("POST", "/transfers/token");
3561
+ if (!minted.apiBaseUrl) throw new InvoGameError("TRANSFERS_UNAVAILABLE", "Transfers aren't available right now. Try again in a moment.", 503);
3562
+ this.useTransferToken(minted.token, minted.apiBaseUrl);
3563
+ }
3564
+ useTransferToken(token, baseUrl) {
3565
+ this.transferClient = new InvoClient({
3566
+ token,
3567
+ baseUrl,
3568
+ ...this.invoFetch ? { fetch: this.invoFetch } : {},
3569
+ refreshToken: async () => (await this.request("POST", "/transfers/token")).token
3570
+ });
3571
+ }
3572
+ /**
3573
+ * Where this player can send: this game first (send rail only), then every INVO game the
3574
+ * destination list offers, each with its currency and per-transfer limits.
3575
+ */
3576
+ async transferDestinations() {
3577
+ await this.prepareTransfers();
3578
+ const result = await this.transferClient.getDestinations({ direction: "send" });
3579
+ const here = {
3580
+ gameId: result.sourceGameId,
3581
+ gameName: result.sourceGameName,
3582
+ currencyName: result.sourceCurrencyName,
3583
+ currencySymbol: "",
3584
+ minimumTransfer: "",
3585
+ maximumTransfer: "",
3586
+ acceptsSteamOriginValue: true,
3587
+ raw: {},
3588
+ thisGame: true,
3589
+ kinds: ["send"]
3590
+ };
3591
+ const others = result.availableGames.filter((g) => String(g.gameId) !== String(result.sourceGameId)).map((g) => ({ ...g, thisGame: false, kinds: ["transfer", "send"] }));
3592
+ return [here, ...others];
3593
+ }
3594
+ /**
3595
+ * Start a transfer or send on the server. Nothing moves yet: call {@link approveTransfer}
3596
+ * from the player's next click to open INVO's passkey page.
3597
+ */
3598
+ async startTransfer(input) {
3599
+ await this.prepareTransfers();
3600
+ const started = await this.request("POST", "/transfers", {
3601
+ ...input,
3602
+ kind: input.kind ?? "transfer",
3603
+ clientRequestId: input.clientRequestId ?? newEventId()
3604
+ });
3605
+ if (started.playerToken) {
3606
+ const status = await this.transferStatus();
3607
+ if (status.apiBaseUrl) this.useTransferToken(started.playerToken, status.apiBaseUrl);
3608
+ }
3609
+ return started;
3610
+ }
3611
+ /**
3612
+ * The sender approves. With a real key this opens INVO's hosted passkey page, so CALL IT
3613
+ * DIRECTLY FROM A CLICK (the browser only allows the window from a user gesture). On the
3614
+ * public demo key (`approval: "sandbox"`) the game server approves it in INVO's demo sandbox.
3615
+ */
3616
+ approveTransfer(start) {
3617
+ if (start.approval === "sandbox") {
3618
+ return this.sandboxStep(
3619
+ start.transactionId,
3620
+ start.kind,
3621
+ "out",
3622
+ () => this.request("POST", `/transfers/${encodeURIComponent(start.transactionId)}/approve`).then((r) => ({ claimCode: r.claimCode }))
3623
+ );
3624
+ }
3625
+ return this.hosted(start.transactionId, start.kind, start.kind, "out");
3626
+ }
3627
+ /** Transfers and sends waiting for this player: ones sent to them, and ones they still need to approve. */
3628
+ async pendingTransfers() {
3629
+ if ((await this.transferStatus()).approval === "sandbox") {
3630
+ return (await this.request("GET", "/transfers/pending")).pending;
3631
+ }
3632
+ await this.prepareTransfers();
3633
+ return (await this.transferClient.getPendingCollect()).pending;
3634
+ }
3635
+ /**
3636
+ * Settle a pending item on INVO's hosted page: collect one sent to this player, or approve
3637
+ * one they started. CALL THIS DIRECTLY FROM A CLICK.
3638
+ */
3639
+ collectTransfer(item, approval = "passkey") {
3640
+ const kind = item.flow === "send" ? "send" : "transfer";
3641
+ const incoming = item.kind === "receiving_confirm";
3642
+ if (approval === "sandbox") {
3643
+ const id = encodeURIComponent(item.transferId);
3644
+ return incoming ? this.sandboxStep(item.transferId, kind, "in", () => this.request("POST", `/transfers/${id}/collect`).then((r) => {
3645
+ this.setWallet(r.wallet);
3646
+ return { claimCode: null };
3647
+ })) : this.sandboxStep(item.transferId, kind, "out", () => this.request("POST", `/transfers/${id}/approve`).then((r) => ({ claimCode: r.claimCode })));
3648
+ }
3649
+ return this.hosted(item.transferId, kind, incoming ? kind === "send" ? "send_receipt" : "transfer_receipt" : kind, incoming ? "in" : "out");
3650
+ }
3651
+ /** A demo-sandbox step done by the game server, reported like the hosted page's result. */
3652
+ async sandboxStep(transactionId, kind, direction, run) {
3653
+ const { claimCode } = await run();
3654
+ if (direction === "out") await this.refresh().catch(() => void 0);
3655
+ this.emit("transfer", { transactionId, kind, direction, status: "approved", claimCode, holdReason: null });
3656
+ return { status: "approved", popupBlocked: false, approval: { claimCode } };
3657
+ }
3658
+ hosted(transactionId, kind, flow, direction) {
3659
+ const client = this.transferClient;
3660
+ if (!client) {
3661
+ return Promise.reject(new InvoGameError("TRANSFERS_NOT_READY", "Call prepareTransfers() before the click that approves.", 0));
3662
+ }
3663
+ return client.approveHosted({ transactionId, flow }).then(async (result) => {
3664
+ const approval = result.approval ?? null;
3665
+ if (result.status === "approved") await this.refresh().catch(() => void 0);
3666
+ this.emit("transfer", {
3667
+ transactionId,
3668
+ kind,
3669
+ direction,
3670
+ status: result.status,
3671
+ claimCode: approval?.claimCode ?? null,
3672
+ holdReason: approval?.holdReason ?? null
3673
+ });
3674
+ return result;
3675
+ });
3676
+ }
1413
3677
  clearSession() {
3678
+ this.transferClient = null;
1414
3679
  this.token = null;
1415
3680
  this.player = null;
1416
3681
  this.wallet = null;
@@ -1461,7 +3726,7 @@ var InvoGameEconomy = class {
1461
3726
  return parsed;
1462
3727
  }
1463
3728
  };
1464
- function sleep(ms) {
3729
+ function sleep2(ms) {
1465
3730
  return new Promise((r) => setTimeout(r, ms));
1466
3731
  }
1467
3732
  function safeLocalStorage() {
@@ -1495,6 +3760,7 @@ var ICONS = {
1495
3760
  info: stroke('<circle cx="12" cy="12" r="9"/><path d="M12 11v5M12 8h.01"/>', 14),
1496
3761
  alert: stroke('<path d="M12 3l10 18H2L12 3z"/><path d="M12 10v4M12 17h.01"/>', 14),
1497
3762
  copy: stroke('<rect x="9" y="9" width="12" height="12" rx="2.5"/><path d="M5 15V5a2 2 0 0 1 2-2h8"/>', 13),
3763
+ arrows: stroke('<path d="M4 8h13l-4-4M20 16H7l4 4"/>', 16),
1498
3764
  external: stroke('<path d="M14 4h6v6M20 4l-9 9"/><path d="M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5"/>', 13)
1499
3765
  };
1500
3766
  var svgId = 0;
@@ -1654,6 +3920,33 @@ var CSS = `
1654
3920
  @keyframes invo-toast{from{opacity:0;transform:translateY(12px) scale(.97)}to{opacity:1;transform:none}}
1655
3921
  @keyframes invo-toast-out{to{opacity:0;transform:translateY(8px) scale(.98)}}
1656
3922
 
3923
+ .invo-ui [hidden]{display:none!important}
3924
+ .invo-hero{display:flex;gap:14px;align-items:center;padding:16px;border-radius:18px;margin-bottom:16px;background:radial-gradient(120% 140% at 0% 0%,rgba(244,192,74,.14),transparent 60%),rgba(255,255,255,.03);border:1px solid var(--invo-line)}
3925
+ .invo-hero-ico{display:grid;place-items:center;width:46px;height:46px;flex:none;border-radius:14px;color:#1A1405;background:linear-gradient(150deg,#FFE6A3,var(--invo-gold) 55%,#C98E1C);box-shadow:inset 0 1px 0 rgba(255,255,255,.6),0 10px 24px -8px rgba(244,192,74,.7)}
3926
+ .invo-hero-ico svg{width:22px;height:22px}
3927
+ .invo-hero.locked .invo-hero-ico{color:var(--invo-muted);background:rgba(255,255,255,.06);box-shadow:none}
3928
+ .invo-hero b{display:block;font-size:15px;margin-bottom:3px}.invo-hero span{color:var(--invo-muted);font-size:13px;line-height:1.5}
3929
+ .invo-livechip{display:inline-flex;align-items:center;height:24px;padding:0 10px;margin-bottom:10px;border-radius:999px;font:800 10px/1 var(--invo-font);letter-spacing:.14em;text-transform:uppercase;color:var(--invo-gold);background:rgba(244,192,74,.1);border:1px solid rgba(244,192,74,.35)}
3930
+ .invo-seg{display:grid;grid-template-columns:1fr 1fr;gap:4px;padding:4px;margin-bottom:14px;border-radius:13px;background:rgba(0,0,0,.28);border:1px solid var(--invo-line)}
3931
+ .invo-seg button{padding:9px 10px;border:0;border-radius:9px;background:transparent;color:var(--invo-muted);font:600 13px var(--invo-font);cursor:pointer;text-align:left}
3932
+ .invo-seg button small{display:block;margin-top:2px;font-weight:500;font-size:11.5px;color:var(--invo-muted);opacity:.85}
3933
+ .invo-seg button[aria-pressed=true]{color:var(--invo-text);background:var(--invo-surface);box-shadow:inset 0 1px 0 rgba(255,255,255,.07),0 4px 14px -4px rgba(0,0,0,.6)}
3934
+ .invo-amount{position:relative}.invo-amount .invo-input{padding-left:14px;padding-right:84px;font-variant-numeric:tabular-nums}
3935
+ .invo-amount em{position:absolute;right:14px;top:50%;transform:translateY(-50%);font-style:normal;font-weight:700;color:var(--invo-gold);font-size:13px;pointer-events:none}
3936
+ .invo-hint{margin:-6px 0 14px;color:var(--invo-muted);font-size:12px;line-height:1.5}
3937
+ select.invo-input{appearance:none;-webkit-appearance:none;cursor:pointer;background-image:linear-gradient(45deg,transparent 50%,var(--invo-muted) 50%),linear-gradient(135deg,var(--invo-muted) 50%,transparent 50%);background-position:calc(100% - 20px) 50%,calc(100% - 14px) 50%;background-size:6px 6px;background-repeat:no-repeat;padding-left:14px;padding-right:36px}
3938
+ .invo-review{border-radius:18px;padding:4px 16px;margin-bottom:16px;background:rgba(255,255,255,.03);border:1px solid var(--invo-line)}
3939
+ .invo-review-row{display:flex;justify-content:space-between;gap:12px;padding:12px 0;border-bottom:1px solid var(--invo-line);font-size:14px;color:var(--invo-muted)}
3940
+ .invo-review-row:last-child{border-bottom:0}.invo-review-row b{color:var(--invo-text);text-align:right;word-break:break-word}
3941
+ .invo-big{font:800 36px/1 var(--invo-font);letter-spacing:-.03em;color:var(--invo-gold);margin:6px 0 14px;font-variant-numeric:tabular-nums}
3942
+ .invo-claim{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-top:14px;padding:12px 14px;border-radius:14px;background:rgba(0,0,0,.35);border:1px dashed rgba(244,192,74,.45);font:700 18px ui-monospace,SFMono-Regular,Consolas,monospace;letter-spacing:.12em;color:var(--invo-gold)}
3943
+ .invo-claim small{font:600 11px var(--invo-font);letter-spacing:.08em;text-transform:uppercase;color:var(--invo-muted)}
3944
+ .invo-tlist{display:flex;flex-direction:column;gap:10px}
3945
+ .invo-titem{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:14px 16px;border-radius:16px;background:var(--invo-surface);border:1px solid var(--invo-line);animation:invo-rise .35s var(--invo-ease) backwards}
3946
+ .invo-titem b{display:block;font-size:15px;font-variant-numeric:tabular-nums}.invo-titem span{color:var(--invo-muted);font-size:12.5px}
3947
+ .invo-done{text-align:center;padding:4px 0}.invo-done .invo-hero-ico{margin:0 auto 14px;width:56px;height:56px;border-radius:18px}
3948
+ .invo-done h3{margin:0 0 6px;font-size:20px;letter-spacing:-.02em}
3949
+ .invo-hbtn.locked svg{opacity:.55}
1657
3950
  @media (max-width:560px){
1658
3951
  .invo-hbtn .invo-label{display:none}.invo-hbtn{padding:0 10px}.invo-account[data-initial]::before{margin:0 -3px}
1659
3952
  .invo-pill{padding:0 10px 0 8px;gap:6px}.invo-hud .invo-badge .invo-label{display:none}.invo-hud .invo-badge{padding:0 8px}
@@ -1726,9 +4019,14 @@ function mountInvoUI(container, economy, options = {}) {
1726
4019
  shopBtn.type = "button";
1727
4020
  shopBtn.append(svg(ICONS.bag), el("span", "invo-label", "Shop"));
1728
4021
  shopBtn.hidden = !!options.hideShopButton;
4022
+ const transferBtn = el("button", "invo-btn invo-hbtn");
4023
+ transferBtn.type = "button";
4024
+ transferBtn.append(svg(ICONS.arrows), el("span", "invo-label", "Transfer"));
4025
+ transferBtn.title = "Send to another player, or collect what was sent to you.";
4026
+ transferBtn.hidden = !!options.hideTransferButton;
1729
4027
  const accountBtn = el("button", "invo-btn invo-hbtn invo-account");
1730
4028
  accountBtn.type = "button";
1731
- hud.append(sandboxBadge, premiumPill, softPill, el("span", "invo-sep"), shopBtn, accountBtn);
4029
+ hud.append(sandboxBadge, premiumPill, softPill, el("span", "invo-sep"), shopBtn, transferBtn, accountBtn);
1732
4030
  root.append(hud);
1733
4031
  const toasts = el("div", "invo-toasts");
1734
4032
  toasts.setAttribute("role", "status");
@@ -2121,8 +4419,374 @@ function mountInvoUI(container, economy, options = {}) {
2121
4419
  card.append(foot);
2122
4420
  return card;
2123
4421
  }
4422
+ function hero(iconSvg, title, text, locked = false) {
4423
+ const box = el("div", `invo-hero${locked ? " locked" : ""}`);
4424
+ const words = el("div");
4425
+ words.append(el("b", void 0, title), el("span", void 0, text));
4426
+ box.append(svg(iconSvg, "invo-hero-ico"), words);
4427
+ return box;
4428
+ }
4429
+ function transfersLocked(status) {
4430
+ openDialog(
4431
+ { title: `Send ${premiumName()} to anyone`, eyebrow: "Transfers", subtitle: "Move currency to a friend in this game or another INVO game, approved with a passkey.", narrow: true },
4432
+ (body) => {
4433
+ const ok = el("button", "invo-btn block", "Got it");
4434
+ ok.type = "button";
4435
+ ok.onclick = () => close();
4436
+ body.append(
4437
+ el("span", "invo-livechip", status.reason === "checking" ? "One moment" : "Live only"),
4438
+ hero(
4439
+ ICONS.lock,
4440
+ status.reason === "checking" ? "Checking this game's INVO key" : "Available when this game goes live",
4441
+ status.reason === "sandbox" ? "This game is on a sandbox key. Transfers switch on by themselves with the production key. To try them first, set INVO_TRANSFERS=on." : status.reason === "checking" ? "Try again in a moment." : "Transfers are switched off for this game.",
4442
+ true
4443
+ ),
4444
+ ok
4445
+ );
4446
+ }
4447
+ );
4448
+ }
4449
+ async function openTransfers(tab = "send") {
4450
+ if (economy.setupRequired) return openSetup();
4451
+ const status = await economy.transferStatus();
4452
+ if (!status.enabled) return transfersLocked(status);
4453
+ if (!economy.signedIn) return openSignIn(() => void openTransfers(tab));
4454
+ openDialog(
4455
+ {
4456
+ title: `Send ${premiumName()} to anyone`,
4457
+ eyebrow: "Transfers",
4458
+ subtitle: status.scope === "project" ? "Transfers work between players of this project." : "To a friend here or in any other INVO game. You approve each one with your passkey.",
4459
+ narrow: true
4460
+ },
4461
+ (body) => {
4462
+ const tabs = el("div", "invo-tabs");
4463
+ tabs.setAttribute("role", "tablist");
4464
+ const pane = el("div");
4465
+ const tabFor = (key, label) => {
4466
+ const b = el("button", "invo-tab", label);
4467
+ b.type = "button";
4468
+ b.setAttribute("role", "tab");
4469
+ b.setAttribute("aria-selected", String(key === tab));
4470
+ b.onclick = () => {
4471
+ tabs.querySelectorAll(".invo-tab").forEach((n) => n.setAttribute("aria-selected", "false"));
4472
+ b.setAttribute("aria-selected", "true");
4473
+ void (key === "send" ? sendPane(pane, status) : collectPane(pane, status.approval));
4474
+ };
4475
+ tabs.append(b);
4476
+ };
4477
+ tabFor("send", "Send");
4478
+ tabFor("collect", "Collect");
4479
+ body.append(tabs, pane);
4480
+ void (tab === "send" ? sendPane(pane, status) : collectPane(pane, status.approval));
4481
+ }
4482
+ );
4483
+ }
4484
+ function paneLoading(pane, text) {
4485
+ const row = el("div", "invo-status");
4486
+ row.append(el("span", "invo-spinner"), el("span", void 0, text));
4487
+ pane.replaceChildren(row);
4488
+ }
4489
+ function paneFailed(pane, message, retry) {
4490
+ const again = el("button", "invo-btn block", "Try again");
4491
+ again.type = "button";
4492
+ again.onclick = retry;
4493
+ pane.replaceChildren(el("div", "invo-error", message), again);
4494
+ }
4495
+ const draft = { kind: "transfer", gameId: "", amount: "", email: "", phone: "", myPhone: "", needMyPhone: false };
4496
+ async function sendPane(pane, status) {
4497
+ paneLoading(pane, "Finding where you can send\u2026");
4498
+ let games;
4499
+ try {
4500
+ games = await economy.transferDestinations();
4501
+ } catch (err) {
4502
+ return paneFailed(pane, err instanceof Error ? err.message : "Couldn't load destinations.", () => void sendPane(pane, status));
4503
+ }
4504
+ if (!pane.isConnected) return;
4505
+ const form = el("form");
4506
+ form.noValidate = true;
4507
+ const pick = () => games.find((g) => String(g.gameId) === game.value) ?? games[0];
4508
+ const seg = el("div", "invo-seg");
4509
+ const segButton = (kind, title, note) => {
4510
+ const b = el("button");
4511
+ b.type = "button";
4512
+ b.setAttribute("aria-pressed", String(draft.kind === kind));
4513
+ b.append(document.createTextNode(title), el("small", void 0, note));
4514
+ b.onclick = () => {
4515
+ if (draft.kind === kind) return;
4516
+ draft.kind = kind;
4517
+ void sendPane(pane, status);
4518
+ };
4519
+ seg.append(b);
4520
+ };
4521
+ segButton("transfer", "Transfer", "They collect with a passkey or a claim code");
4522
+ segButton("send", "Send", "They can collect from a link INVO sends");
4523
+ const field = (label, hint, control, iconSvg) => {
4524
+ const wrap = el("div", "invo-field");
4525
+ const l = el("label");
4526
+ l.append(document.createTextNode(label));
4527
+ if (hint) l.append(el("small", void 0, hint));
4528
+ if (iconSvg) {
4529
+ const box = el("div", "invo-inwrap");
4530
+ box.append(svg(iconSvg), control);
4531
+ wrap.append(l, box);
4532
+ } else {
4533
+ wrap.append(l, control);
4534
+ }
4535
+ form.append(wrap);
4536
+ return wrap;
4537
+ };
4538
+ const game = el("select", "invo-input");
4539
+ for (const g of games) {
4540
+ const o = el("option", void 0, g.thisGame ? `A player in this game \xB7 ${g.currencyName}` : `${g.gameName} \xB7 ${g.currencyName}`);
4541
+ o.value = String(g.gameId);
4542
+ game.append(o);
4543
+ }
4544
+ if (draft.gameId && games.some((g) => String(g.gameId) === draft.gameId)) game.value = draft.gameId;
4545
+ field("Send to", "", game);
4546
+ const limits = el("p", "invo-hint");
4547
+ form.append(limits);
4548
+ form.append(seg);
4549
+ const amountBox = el("div", "invo-amount");
4550
+ const amount = el("input", "invo-input");
4551
+ amount.inputMode = "decimal";
4552
+ amount.placeholder = "0";
4553
+ amount.value = draft.amount;
4554
+ amountBox.append(amount, el("em", void 0, premiumName()));
4555
+ const have = economy.balance("premium")?.balance;
4556
+ field("Amount", have === null || have === void 0 ? "" : `you have ${formatAmount(have)}`, amountBox);
4557
+ const email = el("input", "invo-input");
4558
+ email.type = "email";
4559
+ email.placeholder = "friend@example.com";
4560
+ email.autocomplete = "off";
4561
+ email.value = draft.email;
4562
+ const phone = el("input", "invo-input");
4563
+ phone.type = "tel";
4564
+ phone.placeholder = "+1 555 555 0111";
4565
+ phone.autocomplete = "off";
4566
+ phone.value = draft.phone;
4567
+ if (status.recipientFields.phone === "required") field("Friend's phone", "required", phone, ICONS.phone);
4568
+ field(
4569
+ "Friend's email",
4570
+ status.recipientFields.email === "required" ? "the one they sign in with" : "optional",
4571
+ email,
4572
+ ICONS.mail
4573
+ );
4574
+ const myPhone = el("input", "invo-input");
4575
+ myPhone.type = "tel";
4576
+ myPhone.placeholder = "+1 555 555 0100";
4577
+ myPhone.autocomplete = "tel";
4578
+ myPhone.value = draft.myPhone;
4579
+ field("Your phone", "as on your INVO account", myPhone, ICONS.phone).hidden = !draft.needMyPhone;
4580
+ const showLimits = () => {
4581
+ const g = pick();
4582
+ seg.hidden = g.thisGame;
4583
+ if (g.thisGame) draft.kind = "send";
4584
+ const range = g.minimumTransfer && g.maximumTransfer ? `${g.minimumTransfer} to ${g.maximumTransfer} per transfer. ` : "";
4585
+ limits.textContent = g.thisGame ? `To another player of this game. INVO's network fee is 10%.` : `${g.gameName} accepts ${range}INVO's network fee is 10%.` + (status.demo ? ` In this demo, ${g.gameName} can't collect it, so it's refunded after 24 hours.` : "");
4586
+ };
4587
+ game.onchange = () => {
4588
+ const was = draft.kind;
4589
+ showLimits();
4590
+ seg.querySelectorAll("button").forEach((b, i) => b.setAttribute("aria-pressed", String((i === 0 ? "transfer" : "send") === draft.kind)));
4591
+ if (was !== draft.kind) draft.gameId = game.value;
4592
+ };
4593
+ showLimits();
4594
+ if (status.demo) {
4595
+ const note = el("div", "invo-callout");
4596
+ note.append(svg(ICONS.info), el("span", void 0, "Demo sandbox: transfers work between players of this project, and approving needs no passkey. On your live key, players confirm each one with their passkey."));
4597
+ form.append(note);
4598
+ }
4599
+ const error = el("div", "invo-error");
4600
+ const next = el("button", "invo-btn gold block", "Review");
4601
+ next.type = "submit";
4602
+ next.style.marginTop = "14px";
4603
+ form.append(error, next);
4604
+ form.onsubmit = (e) => {
4605
+ e.preventDefault();
4606
+ Object.assign(draft, { gameId: game.value, amount: amount.value.trim(), email: email.value.trim(), phone: phone.value.trim(), myPhone: myPhone.value.trim() });
4607
+ const g = pick();
4608
+ if (g.thisGame) draft.kind = "send";
4609
+ const n = Number(draft.amount);
4610
+ if (!(n > 0)) return void (error.textContent = "Enter an amount greater than zero.");
4611
+ const balance = economy.balance("premium")?.balance;
4612
+ if (balance !== null && balance !== void 0 && n > balance) {
4613
+ return void (error.textContent = `You have ${formatAmount(balance)} ${premiumName()}.`);
4614
+ }
4615
+ if (g.minimumTransfer && g.maximumTransfer && (n < Number(g.minimumTransfer) || n > Number(g.maximumTransfer))) {
4616
+ return void (error.textContent = `${g.gameName} accepts ${g.minimumTransfer} to ${g.maximumTransfer} per transfer.`);
4617
+ }
4618
+ if (status.recipientFields.email === "required" && !draft.email) return void (error.textContent = "Enter your friend's email.");
4619
+ if (status.recipientFields.phone === "required" && !draft.phone) return void (error.textContent = "Enter your friend's phone.");
4620
+ reviewPane(pane, status, g);
4621
+ };
4622
+ pane.replaceChildren(form);
4623
+ amount.focus({ preventScroll: true });
4624
+ }
4625
+ function reviewPane(pane, status, game) {
4626
+ const what = `${draft.amount} ${premiumName()}`;
4627
+ const wrap = el("div");
4628
+ wrap.append(el("div", "invo-eyebrow", draft.kind === "send" ? "Review send" : "Review transfer"), el("div", "invo-big", what));
4629
+ const table = el("div", "invo-review");
4630
+ const row = (k, v) => {
4631
+ const r = el("div", "invo-review-row");
4632
+ r.append(document.createTextNode(k), el("b", void 0, v));
4633
+ table.append(r);
4634
+ };
4635
+ row("To", [draft.email, status.recipientFields.phone === "required" ? draft.phone : ""].filter(Boolean).join(" \xB7 "));
4636
+ row("In", game.thisGame ? `This game (${game.currencyName})` : `${game.gameName} (${game.currencyName})`);
4637
+ row("Network fee", "10%, shared by both games and INVO");
4638
+ const error = el("div", "invo-error");
4639
+ const send = el("button", "invo-btn gold block", draft.kind === "send" ? "Send" : "Transfer");
4640
+ send.type = "button";
4641
+ const edit = el("button", "invo-btn block", "Edit");
4642
+ edit.type = "button";
4643
+ edit.style.marginTop = "10px";
4644
+ edit.onclick = () => void sendPane(pane, status);
4645
+ send.onclick = async () => {
4646
+ send.disabled = true;
4647
+ send.classList.add("busy");
4648
+ error.textContent = "";
4649
+ try {
4650
+ const started = await economy.startTransfer({
4651
+ kind: draft.kind,
4652
+ targetGameId: game.gameId,
4653
+ amount: draft.amount,
4654
+ recipientEmail: draft.email || void 0,
4655
+ recipientPhone: status.recipientFields.phone === "required" ? draft.phone : void 0,
4656
+ senderPhone: draft.myPhone || void 0
4657
+ });
4658
+ if (started.guardianPending) {
4659
+ return donePane(pane, "Waiting for a guardian", "A parent or guardian has been emailed to approve it. Nothing moves until they do.", null);
4660
+ }
4661
+ approvePane(
4662
+ pane,
4663
+ `Approve ${draft.kind === "send" ? "sending" : "transferring"} ${what}`,
4664
+ status.approval,
4665
+ () => economy.approveTransfer(started),
4666
+ (result) => {
4667
+ const claim = result.approval?.claimCode ?? null;
4668
+ donePane(
4669
+ pane,
4670
+ draft.kind === "send" ? "Sent" : "Transferred",
4671
+ game.thisGame ? `${what} is on its way. Your friend collects it from Transfer \u2192 Collect.` : `${what} is on its way. Your friend collects it in ${game.gameName}.`,
4672
+ // The demo collects with the claim code on the server; only a real transfer needs it shown.
4673
+ status.approval === "sandbox" ? null : claim
4674
+ );
4675
+ Object.assign(draft, { amount: "", email: "", phone: "" });
4676
+ }
4677
+ );
4678
+ } catch (err) {
4679
+ if (err instanceof InvoGameError && err.code === "SENDER_PHONE_REQUIRED") {
4680
+ draft.needMyPhone = true;
4681
+ void sendPane(pane, status);
4682
+ return;
4683
+ }
4684
+ error.textContent = err instanceof Error ? err.message : "That didn't go through.";
4685
+ } finally {
4686
+ send.disabled = false;
4687
+ send.classList.remove("busy");
4688
+ }
4689
+ };
4690
+ wrap.append(table, error, send, edit);
4691
+ pane.replaceChildren(wrap);
4692
+ }
4693
+ function approvePane(pane, title, approval, approve, onApproved, verb = "Approve") {
4694
+ const sandbox = approval === "sandbox";
4695
+ const error = el("div", "invo-error");
4696
+ const go = el("button", "invo-btn gold block", sandbox ? `${verb} (sandbox)` : `${verb} with passkey`);
4697
+ go.type = "button";
4698
+ go.onclick = () => {
4699
+ go.disabled = true;
4700
+ go.classList.add("busy");
4701
+ error.textContent = "";
4702
+ approve().then((result) => {
4703
+ if (result.status === "approved") {
4704
+ const hold = result.approval?.holdReason;
4705
+ if (hold) return donePane(pane, "On hold", "INVO is reviewing this one. It completes on its own and you'll both be told.", null);
4706
+ return onApproved(result);
4707
+ }
4708
+ error.textContent = result.status === "denied" ? "You declined on INVO's page. Nothing moved." : result.status === "expired" ? "That approval expired. Try again." : result.status === "closed" ? "INVO's window was closed. Nothing moved." : result.message ?? "Your browser blocked INVO's window. Allow pop-ups for this site and try again.";
4709
+ }).catch((err) => {
4710
+ error.textContent = err instanceof Error ? err.message : "Approval failed.";
4711
+ }).finally(() => {
4712
+ go.disabled = false;
4713
+ go.classList.remove("busy");
4714
+ });
4715
+ };
4716
+ const secure = el("p", "invo-secure");
4717
+ secure.append(svg(ICONS.lock), document.createTextNode(sandbox ? "Demo sandbox \xB7 test currency only" : "Secured by INVO passkeys"));
4718
+ pane.replaceChildren(
4719
+ hero(
4720
+ ICONS.arrows,
4721
+ title,
4722
+ sandbox ? "Demo sandbox: this approves without a passkey. With your live key, INVO opens a secure window and the player confirms with their fingerprint, face or screen lock." : "INVO opens a secure window. Confirm with your fingerprint, face or screen lock. First time? It sets up your INVO passkey in seconds."
4723
+ ),
4724
+ error,
4725
+ go,
4726
+ secure
4727
+ );
4728
+ }
4729
+ function donePane(pane, title, message, claimCode) {
4730
+ const wrap = el("div", "invo-done");
4731
+ wrap.append(svg(ICONS.check, "invo-hero-ico"), el("h3", void 0, title), el("p", "invo-sub", message));
4732
+ if (claimCode) {
4733
+ const code = el("div", "invo-claim");
4734
+ code.append(el("span", void 0, claimCode), el("small", void 0, "Claim code"));
4735
+ wrap.append(code, el("p", "invo-hint", "If your friend can't collect in their game, they can use this code."));
4736
+ }
4737
+ const ok = el("button", "invo-btn block", "Done");
4738
+ ok.type = "button";
4739
+ ok.style.marginTop = "16px";
4740
+ ok.onclick = () => close();
4741
+ wrap.append(ok);
4742
+ pane.replaceChildren(wrap);
4743
+ }
4744
+ async function collectPane(pane, approval) {
4745
+ paneLoading(pane, "Checking for transfers\u2026");
4746
+ let items;
4747
+ try {
4748
+ items = await economy.pendingTransfers();
4749
+ } catch (err) {
4750
+ return paneFailed(pane, err instanceof Error ? err.message : "Couldn't check.", () => void collectPane(pane, approval));
4751
+ }
4752
+ if (!pane.isConnected) return;
4753
+ if (!items.length) {
4754
+ pane.replaceChildren(el("div", "invo-empty", "Nothing to collect right now."));
4755
+ return;
4756
+ }
4757
+ const list = el("div", "invo-tlist");
4758
+ for (const item of items) {
4759
+ const incoming = item.kind === "receiving_confirm";
4760
+ const what = `${item.amount ?? ""} ${item.currency}`.trim();
4761
+ const row = el("div", "invo-titem");
4762
+ const words = el("div");
4763
+ words.append(el("b", void 0, what), el("span", void 0, incoming ? `From ${item.counterpartyGame}` : `Waiting for your approval \xB7 to ${item.counterpartyGame}`));
4764
+ const act = el("button", "invo-btn gold sm", incoming ? "Collect" : "Approve");
4765
+ act.type = "button";
4766
+ if (item.held) {
4767
+ act.disabled = true;
4768
+ act.textContent = "On hold";
4769
+ }
4770
+ act.onclick = () => approvePane(
4771
+ pane,
4772
+ incoming ? `Collect ${what}` : `Approve ${what}`,
4773
+ approval,
4774
+ () => economy.collectTransfer(item, approval),
4775
+ () => donePane(pane, incoming ? "Collected" : "Approved", incoming ? `${what}, less INVO's 10% network fee, is in your wallet.` : `${what} is on its way.`, null),
4776
+ incoming ? "Collect" : "Approve"
4777
+ );
4778
+ row.append(words, act);
4779
+ list.append(row);
4780
+ }
4781
+ pane.replaceChildren(list);
4782
+ }
2124
4783
  plus.onclick = () => openBuyCurrency();
2125
4784
  shopBtn.onclick = () => openShop();
4785
+ transferBtn.onclick = () => void openTransfers();
4786
+ void economy.transferStatus().then((s) => {
4787
+ transferBtn.classList.toggle("locked", !s.enabled);
4788
+ if (!s.enabled) transferBtn.replaceChildren(svg(ICONS.lock), el("span", "invo-label", "Transfer"));
4789
+ });
2126
4790
  accountBtn.onclick = async () => {
2127
4791
  if (economy.setupRequired) return openSetup();
2128
4792
  if (!economy.signedIn) return openSignIn();
@@ -2145,6 +4809,9 @@ function mountInvoUI(container, economy, options = {}) {
2145
4809
  // Popup and redirect checkouts both end here, so the confirmation shows exactly once.
2146
4810
  economy.on("purchase", (u) => {
2147
4811
  if (u.status === "credited") toast(`+${formatAmount(u.credited)} ${premiumName()} added`, "success");
4812
+ }),
4813
+ economy.on("transfer", (t2) => {
4814
+ if (t2.status === "approved" && !t2.holdReason) toast(t2.direction === "in" ? "Collected" : t2.kind === "send" ? "Sent" : "Transfer approved", "success");
2148
4815
  })
2149
4816
  ];
2150
4817
  renderHud();
@@ -2153,6 +4820,7 @@ function mountInvoUI(container, economy, options = {}) {
2153
4820
  openShop,
2154
4821
  openBuyCurrency,
2155
4822
  openSignIn: () => openSignIn(),
4823
+ openTransfers: (tab) => void openTransfers(tab),
2156
4824
  close,
2157
4825
  toast,
2158
4826
  destroy() {
@@ -2165,7 +4833,7 @@ function mountInvoUI(container, economy, options = {}) {
2165
4833
  }
2166
4834
 
2167
4835
  // src/version.ts
2168
- var SDK_VERSION = "3.29.1";
4836
+ var SDK_VERSION = "3.30.0";
2169
4837
 
2170
4838
  exports.InvoGameEconomy = InvoGameEconomy;
2171
4839
  exports.InvoGameError = InvoGameError;