@invonetwork/web-sdk 3.5.0 → 3.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,6 +1,8 @@
1
1
  'use strict';
2
2
 
3
3
  // src/shared/errors.ts
4
+ var LEGACY_NOT_PENDING_RE = /^transaction not pending\b|\bcannot be confirmed\b/i;
5
+ var LEGACY_CURRENT_STATUS_RE = /\((?:current )?status:\s*([^)]+)\)/i;
4
6
  var InvoError = class _InvoError extends Error {
5
7
  constructor(args) {
6
8
  super(args.message);
@@ -381,6 +383,91 @@ var InvoError = class _InvoError extends Error {
381
383
  get isAlreadyRefunded() {
382
384
  return this.code === "ALREADY_REFUNDED" || this.status === 409 && /already\s+refunded/i.test(this.message);
383
385
  }
386
+ /**
387
+ * True when an approve / confirm-receipt was refused because the transaction is no
388
+ * longer awaiting that step (`TRANSACTION_NOT_PENDING`, 400). `approveWithDeviceCode`
389
+ * maps this into a non-throwing `status: "not_pending"` result; you meet it as a thrown
390
+ * error only from a raw call. Usually "already done" (a repeat call with a device_code
391
+ * that was consumed the first time) — read `currentTransactionStatus`, do not retry-loop.
392
+ *
393
+ * The message fallback is for OLDER BACKEND RELEASES. The stable
394
+ * `TRANSACTION_NOT_PENDING` code was added on 2026-09-04; before that the same four
395
+ * endpoints answered `{"status":"error","message":"Transaction not pending PIN
396
+ * verification (current status: …)"}` — or, on the two receipt flows, "…cannot be
397
+ * confirmed (current status: …)" — with **no machine code at all**. An integrator
398
+ * running against an older deployment must still be able to tell "already done" from a
399
+ * real refusal without string-matching in their own code, so the string-matching lives
400
+ * here, once.
401
+ *
402
+ * That fallback is deliberately narrow, because it is guessing. It requires all three
403
+ * of: HTTP 400, one of those two phrases, AND a readable status clause. "cannot be
404
+ * confirmed" is an ordinary English phrase that some future refusal could reasonably
405
+ * use, so a phrase match ALONE must never be able to tell a caller that money moved —
406
+ * and with the clause required, `currentStatus` is always populated on this path, which
407
+ * is what actually decides `alreadySettled`.
408
+ */
409
+ get isTransactionNotPending() {
410
+ if (this.code === "TRANSACTION_NOT_PENDING") return true;
411
+ return this.status === 400 && LEGACY_NOT_PENDING_RE.test(this.message) && LEGACY_CURRENT_STATUS_RE.test(this.message);
412
+ }
413
+ /**
414
+ * The `current_status` a `TRANSACTION_NOT_PENDING` refusal reports (e.g. `pending_claim`,
415
+ * `completed`, `expired`).
416
+ *
417
+ * Falls back to the `(current status: …)` clause inside the message, which is where the
418
+ * older releases described above put it — they carried no `current_status` field.
419
+ */
420
+ get currentTransactionStatus() {
421
+ const v = this.bodyObject()["current_status"];
422
+ if (typeof v === "string" && v) return v;
423
+ const m = LEGACY_CURRENT_STATUS_RE.exec(this.message);
424
+ const parsed = m?.[1]?.trim();
425
+ return parsed ? parsed : void 0;
426
+ }
427
+ /**
428
+ * True when the approve endpoint did not accept the `device_code`
429
+ * (`DEVICE_APPROVAL_NOT_APPROVED`, 400): unknown, another player's, bound to a
430
+ * different transaction or FLOW, or not yet approved. Deliberately one answer for all
431
+ * of those (no oracle). Check the `flow` you passed matches the one you began with,
432
+ * and that the poll actually said `approved` before you called approve.
433
+ */
434
+ get isDeviceApprovalNotApproved() {
435
+ return this.code === "DEVICE_APPROVAL_NOT_APPROVED";
436
+ }
437
+ /**
438
+ * True when `beginDeviceApproval` was refused because an APPROVED grant for this
439
+ * transaction and flow is still inside its window (`DEVICE_APPROVAL_ALREADY_PENDING`,
440
+ * 409). The player already approved — you are missing the approve call, not a new
441
+ * code. If you still hold the `device_code`, call `approveWithDeviceCode`; otherwise
442
+ * `begin` works again after `deviceApprovalExpiresAt`. (A merely PENDING earlier grant
443
+ * does not 409 — `begin` supersedes it with a fresh code.)
444
+ */
445
+ get isDeviceApprovalAlreadyPending() {
446
+ return this.code === "DEVICE_APPROVAL_ALREADY_PENDING";
447
+ }
448
+ /** ISO time the blocking approved grant's window closes (`expires_at` on a `DEVICE_APPROVAL_ALREADY_PENDING` 409). */
449
+ get deviceApprovalExpiresAt() {
450
+ const v = this.bodyObject()["expires_at"];
451
+ return typeof v === "string" && v ? v : void 0;
452
+ }
453
+ /**
454
+ * True when a settle call failed on INVO's side rather than being refused by a rule
455
+ * (`SEND_APPROVE_FAILED` / `TRANSFER_APPROVE_FAILED` / `CONFIRM_RECEIPT_FAILED`, 400).
456
+ *
457
+ * A fault, never a rule and never retryable. Show a neutral failure and report
458
+ * {@link errorRef} — do not treat it as a decision about the player or the money.
459
+ */
460
+ get isSettleFault() {
461
+ return this.code === "SEND_APPROVE_FAILED" || this.code === "TRANSFER_APPROVE_FAILED" || this.code === "CONFIRM_RECEIPT_FAILED";
462
+ }
463
+ /**
464
+ * The `error_ref` a settle fault carries. It names the exact server log line, so quoting
465
+ * it to INVO support gets the cause in one message instead of a description of symptoms.
466
+ */
467
+ get errorRef() {
468
+ const v = this.bodyObject()["error_ref"];
469
+ return typeof v === "string" && v ? v : void 0;
470
+ }
384
471
  /** Seconds to wait before retrying, when the backend throttled the call (429 `retry_after`). */
385
472
  get retryAfter() {
386
473
  const v = this.bodyObject()["retry_after"];
@@ -404,7 +491,7 @@ function errorFromResponse(status, body, requestId) {
404
491
  code = typeof b["error_code_public"] === "string" ? b["error_code_public"] : rawCode;
405
492
  if (typeof b["error"] === "string") message = b["error"];
406
493
  else if (typeof b["message"] === "string") message = b["message"];
407
- 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)$/.test(
494
+ 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(
408
495
  b["error"]
409
496
  )) {
410
497
  code = b["error"];
@@ -751,6 +838,599 @@ function toDestinationsResult(raw, direction) {
751
838
  };
752
839
  }
753
840
 
841
+ // src/shared/hosted-approval.ts
842
+ var HOSTED_FLOWS = [
843
+ "transfer",
844
+ "send",
845
+ "send_receipt",
846
+ "transfer_receipt"
847
+ ];
848
+ var HOSTED_MESSAGE_TYPE = "invo.approval";
849
+ var MAX_EXPIRES_IN_S = 24 * 24 * 60 * 60;
850
+ var CONFIRM_QUIET_CODES = /* @__PURE__ */ new Set([
851
+ "DEVICE_APPROVAL_ENROLLMENT_ALREADY_DECIDED",
852
+ "DEVICE_APPROVAL_NO_ENROLLMENT_PENDING"
853
+ ]);
854
+ var MAX_TRANSIENT_POLL_FAILURES = 5;
855
+ function derivePlatformOrigin(verificationUriComplete, explicit) {
856
+ let u;
857
+ try {
858
+ u = new URL(verificationUriComplete);
859
+ } catch {
860
+ throw new InvoError({
861
+ message: "begin returned no absolute verification_uri_complete.",
862
+ code: "UNEXPECTED_RESPONSE",
863
+ status: 0
864
+ });
865
+ }
866
+ const isLocal = u.hostname === "localhost" || u.hostname === "127.0.0.1" || u.hostname === "[::1]";
867
+ if (u.protocol !== "https:" && !(u.protocol === "http:" && isLocal)) {
868
+ throw new InvoError({
869
+ message: "The hosted approval page must be https (plaintext would let any page forge the wake-up).",
870
+ code: "INVALID_INPUT",
871
+ status: 0
872
+ });
873
+ }
874
+ if (explicit !== void 0 && u.origin !== explicit) {
875
+ throw new InvoError({
876
+ message: `platformOrigin (${explicit}) does not match the hosted page's origin (${u.origin}).`,
877
+ code: "INVALID_INPUT",
878
+ status: 0
879
+ });
880
+ }
881
+ return u.origin;
882
+ }
883
+ function normalizeEnrollment(input) {
884
+ if (!input || typeof input !== "object") return null;
885
+ const state = typeof input.state === "string" ? input.state : "";
886
+ if (!state) return null;
887
+ const label = input.device_label ?? input.deviceLabel;
888
+ const code = input.match_code ?? input.matchCode;
889
+ const at = input.requested_at ?? input.requestedAt;
890
+ return {
891
+ state,
892
+ deviceLabel: typeof label === "string" && label ? label : "your phone",
893
+ matchCode: typeof code === "string" ? code : "",
894
+ requestedAt: typeof at === "string" ? at : void 0,
895
+ raw: input
896
+ };
897
+ }
898
+ var BRAND = "#4f46e5";
899
+ var FONT = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif";
900
+ var MONO = "ui-monospace, SFMono-Regular, Menlo, Consolas, 'Liberation Mono', monospace";
901
+ var PROMPT_IDS = {
902
+ root: "invo-hosted-enrollment",
903
+ title: "invo-hosted-enrollment-title",
904
+ code: "invo-hosted-enrollment-code",
905
+ yes: "invo-hosted-enrollment-yes",
906
+ no: "invo-hosted-enrollment-no",
907
+ stop: "invo-hosted-enrollment-stop",
908
+ error: "invo-hosted-enrollment-error"
909
+ };
910
+ var HostedEnrollmentPrompt = class {
911
+ constructor() {
912
+ this.handlers = { respond: async () => {
913
+ }, renderPrompt: true };
914
+ this.enrollment = null;
915
+ /** The last match code the player answered, so a stale poll can't re-ask it. */
916
+ this.decided = null;
917
+ this.root = null;
918
+ this.previousFocus = null;
919
+ this.keyHandler = null;
920
+ this.busy = false;
921
+ }
922
+ get current() {
923
+ return this.enrollment;
924
+ }
925
+ configure(handlers) {
926
+ this.handlers = handlers;
927
+ this.decided = null;
928
+ if (this.enrollment) this.render();
929
+ }
930
+ update(input) {
931
+ let next = normalizeEnrollment(input);
932
+ if (next && next.state === "awaiting_screen" && this.decided && this.decided.code === next.matchCode) {
933
+ next = this.decided.decision === "approve" ? { ...next, state: "confirmed" } : null;
934
+ }
935
+ 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);
936
+ this.enrollment = next;
937
+ if (changed) this.handlers.onEnrollment?.(next, this.handlers.respond);
938
+ this.render();
939
+ }
940
+ clear() {
941
+ this.update(null);
942
+ }
943
+ // --- rendering ---
944
+ render() {
945
+ if (typeof document === "undefined") return;
946
+ const e = this.enrollment;
947
+ const visible = this.handlers.renderPrompt && e && (e.state === "awaiting_screen" || e.state === "confirmed");
948
+ if (!visible || !e) {
949
+ this.unmount();
950
+ return;
951
+ }
952
+ this.mount();
953
+ const root = this.root;
954
+ root.innerHTML = "";
955
+ root.appendChild(e.state === "awaiting_screen" ? this.buildPrompt(e) : this.buildFinishing(e));
956
+ this.focusInitial(e.state);
957
+ }
958
+ mount() {
959
+ if (this.root) return;
960
+ this.previousFocus = document.activeElement;
961
+ const overlay = document.createElement("div");
962
+ overlay.id = PROMPT_IDS.root;
963
+ overlay.setAttribute("role", "dialog");
964
+ overlay.setAttribute("aria-modal", "true");
965
+ overlay.setAttribute("aria-labelledby", PROMPT_IDS.title);
966
+ overlay.tabIndex = -1;
967
+ overlay.style.cssText = [
968
+ "position:fixed",
969
+ "inset:0",
970
+ "z-index:2147483000",
971
+ "display:flex",
972
+ "align-items:center",
973
+ "justify-content:center",
974
+ "padding:16px",
975
+ "background:rgba(17,24,39,.55)",
976
+ `font-family:${FONT}`,
977
+ "color:#111827",
978
+ "-webkit-font-smoothing:antialiased",
979
+ "outline:none"
980
+ ].join(";");
981
+ this.keyHandler = (ev) => this.onKeyDown(ev);
982
+ overlay.addEventListener("keydown", this.keyHandler);
983
+ document.body.appendChild(overlay);
984
+ this.root = overlay;
985
+ }
986
+ unmount() {
987
+ if (!this.root) return;
988
+ if (this.keyHandler) this.root.removeEventListener("keydown", this.keyHandler);
989
+ this.root.remove();
990
+ this.root = null;
991
+ this.keyHandler = null;
992
+ this.busy = false;
993
+ const prev = this.previousFocus;
994
+ this.previousFocus = null;
995
+ if (prev && typeof prev.focus === "function") {
996
+ try {
997
+ prev.focus();
998
+ } catch {
999
+ }
1000
+ }
1001
+ }
1002
+ card() {
1003
+ const card = document.createElement("div");
1004
+ card.style.cssText = [
1005
+ "background:#ffffff",
1006
+ "border-radius:16px",
1007
+ "box-shadow:0 20px 60px rgba(17,24,39,.25)",
1008
+ "max-width:420px",
1009
+ "width:100%",
1010
+ "padding:28px 28px 24px",
1011
+ "box-sizing:border-box",
1012
+ "text-align:center"
1013
+ ].join(";");
1014
+ const mark = document.createElement("div");
1015
+ mark.textContent = "INVO";
1016
+ mark.setAttribute("aria-hidden", "true");
1017
+ mark.style.cssText = `font-weight:800;letter-spacing:.18em;font-size:13px;color:${BRAND};margin-bottom:14px`;
1018
+ card.appendChild(mark);
1019
+ return card;
1020
+ }
1021
+ button(id, label, primary) {
1022
+ const b = document.createElement("button");
1023
+ b.type = "button";
1024
+ b.id = id;
1025
+ b.textContent = label;
1026
+ b.style.cssText = [
1027
+ "display:block",
1028
+ "width:100%",
1029
+ "box-sizing:border-box",
1030
+ "border-radius:10px",
1031
+ "padding:12px 16px",
1032
+ "font:inherit",
1033
+ "font-size:15px",
1034
+ "font-weight:600",
1035
+ "cursor:pointer",
1036
+ "margin-top:10px",
1037
+ primary ? `background:${BRAND};color:#ffffff;border:1px solid ${BRAND}` : "background:#ffffff;color:#374151;border:1px solid #d1d5db"
1038
+ ].join(";");
1039
+ return b;
1040
+ }
1041
+ buildPrompt(e) {
1042
+ const card = this.card();
1043
+ const title = document.createElement("h2");
1044
+ title.id = PROMPT_IDS.title;
1045
+ title.textContent = `Set up INVO on ${e.deviceLabel}?`;
1046
+ title.style.cssText = "margin:0 0 14px;font-size:20px;font-weight:700;line-height:1.3";
1047
+ card.appendChild(title);
1048
+ const codeLabel = document.createElement("div");
1049
+ codeLabel.textContent = "Code";
1050
+ codeLabel.style.cssText = "font-size:12px;text-transform:uppercase;letter-spacing:.12em;color:#6b7280";
1051
+ card.appendChild(codeLabel);
1052
+ const code = document.createElement("div");
1053
+ code.id = PROMPT_IDS.code;
1054
+ code.textContent = e.matchCode;
1055
+ code.setAttribute("aria-label", `Code ${e.matchCode.split("").join(" ")}`);
1056
+ code.style.cssText = [
1057
+ `font-family:${MONO}`,
1058
+ "font-size:40px",
1059
+ "font-weight:700",
1060
+ "letter-spacing:.3em",
1061
+ "text-indent:.3em",
1062
+ "line-height:1.2",
1063
+ "margin:6px 0 16px",
1064
+ "color:#111827",
1065
+ "background:#f3f4f6",
1066
+ "border-radius:12px",
1067
+ "padding:14px 8px"
1068
+ ].join(";");
1069
+ card.appendChild(code);
1070
+ const body = document.createElement("p");
1071
+ body.textContent = "Say Yes only if the phone you just scanned/opened shows this code.";
1072
+ body.style.cssText = "margin:0 0 6px;font-size:15px;line-height:1.5;color:#374151";
1073
+ card.appendChild(body);
1074
+ const err = document.createElement("div");
1075
+ err.id = PROMPT_IDS.error;
1076
+ err.setAttribute("role", "alert");
1077
+ err.style.cssText = "min-height:18px;font-size:13px;color:#b91c1c;margin-top:4px";
1078
+ card.appendChild(err);
1079
+ const yes = this.button(PROMPT_IDS.yes, "Yes, it shows this code", true);
1080
+ yes.addEventListener("click", () => void this.decide("approve"));
1081
+ card.appendChild(yes);
1082
+ const no = this.button(PROMPT_IDS.no, "No, that is not my phone", false);
1083
+ no.addEventListener("click", () => void this.decide("deny"));
1084
+ card.appendChild(no);
1085
+ return card;
1086
+ }
1087
+ buildFinishing(e) {
1088
+ const card = this.card();
1089
+ card.style.padding = "18px 22px";
1090
+ const row = document.createElement("div");
1091
+ row.style.cssText = "display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap";
1092
+ const text = document.createElement("div");
1093
+ text.id = PROMPT_IDS.title;
1094
+ text.textContent = `Finishing on ${e.deviceLabel}\u2026`;
1095
+ text.tabIndex = -1;
1096
+ text.setAttribute("aria-live", "polite");
1097
+ text.style.cssText = "font-size:15px;color:#374151;outline:none";
1098
+ row.appendChild(text);
1099
+ const stop = document.createElement("button");
1100
+ stop.type = "button";
1101
+ stop.id = PROMPT_IDS.stop;
1102
+ stop.textContent = "Stop it, wrong code";
1103
+ 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`;
1104
+ stop.addEventListener("click", () => void this.decide("deny"));
1105
+ row.appendChild(stop);
1106
+ card.appendChild(row);
1107
+ return card;
1108
+ }
1109
+ async decide(decision) {
1110
+ if (this.busy || !this.enrollment) return;
1111
+ this.busy = true;
1112
+ this.root?.focus();
1113
+ this.setButtonsDisabled(true);
1114
+ try {
1115
+ await this.handlers.respond(decision);
1116
+ const now = this.enrollment;
1117
+ if (!now) return;
1118
+ this.decided = { code: now.matchCode, decision };
1119
+ if (decision === "deny") {
1120
+ this.update(null);
1121
+ } else if (now.state === "awaiting_screen") {
1122
+ this.update({ ...now.raw, state: "confirmed" });
1123
+ }
1124
+ } catch (err) {
1125
+ const box = this.root?.querySelector(`#${PROMPT_IDS.error}`);
1126
+ if (box) {
1127
+ box.textContent = err instanceof Error && err.message ? `Couldn't send your answer: ${err.message}` : "Couldn't send your answer. Try again.";
1128
+ }
1129
+ } finally {
1130
+ this.busy = false;
1131
+ this.setButtonsDisabled(false);
1132
+ if (this.root && this.enrollment?.state === "awaiting_screen") this.focusInitial("awaiting_screen");
1133
+ }
1134
+ }
1135
+ setButtonsDisabled(disabled) {
1136
+ this.root?.querySelectorAll("button").forEach((b) => {
1137
+ b.disabled = disabled;
1138
+ });
1139
+ }
1140
+ focusables() {
1141
+ if (!this.root) return [];
1142
+ return Array.from(this.root.querySelectorAll("button:not([disabled])"));
1143
+ }
1144
+ /** Prompt: first button. Finishing row: the text, NOT "Stop it" — a stray Enter must not deny. */
1145
+ focusInitial(state) {
1146
+ const target = state === "confirmed" ? this.root?.querySelector(`#${PROMPT_IDS.title}`) : this.focusables()[0];
1147
+ try {
1148
+ (target ?? this.root)?.focus();
1149
+ } catch {
1150
+ }
1151
+ }
1152
+ onKeyDown(ev) {
1153
+ if (ev.key === "Escape") {
1154
+ ev.preventDefault();
1155
+ void this.decide("deny");
1156
+ return;
1157
+ }
1158
+ if (ev.key !== "Tab") return;
1159
+ ev.preventDefault();
1160
+ const items = this.focusables();
1161
+ if (items.length === 0) {
1162
+ this.root?.focus();
1163
+ return;
1164
+ }
1165
+ const active = document.activeElement;
1166
+ const idx = items.indexOf(active);
1167
+ let nextIdx;
1168
+ if (idx === -1) nextIdx = ev.shiftKey ? items.length - 1 : 0;
1169
+ else nextIdx = (idx + (ev.shiftKey ? -1 : 1) + items.length) % items.length;
1170
+ items[nextIdx].focus();
1171
+ }
1172
+ };
1173
+ 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.";
1174
+ var BLOCKED_HINT = "The browser blocked the popup. Nothing was started \u2014 call approveHosted() from a click handler.";
1175
+ function pollToken(err) {
1176
+ if (!(err instanceof InvoError) || err.status === 0 || err.status === 429 || err.status >= 500) return null;
1177
+ const body = err.body && typeof err.body === "object" ? err.body : {};
1178
+ const token = typeof body["error"] === "string" ? body["error"] : "";
1179
+ return { token, body };
1180
+ }
1181
+ async function runHostedApproval(opts, api, deps = {}) {
1182
+ if (typeof window === "undefined") {
1183
+ throw new InvoError({
1184
+ message: "approveHosted requires a browser window.",
1185
+ code: "DOM_UNAVAILABLE",
1186
+ status: 0
1187
+ });
1188
+ }
1189
+ if (!opts.transactionId || !String(opts.transactionId).trim()) {
1190
+ throw new Error("approveHosted requires a `transactionId`.");
1191
+ }
1192
+ if (!HOSTED_FLOWS.includes(opts.flow)) {
1193
+ throw new Error(`approveHosted: unknown flow "${String(opts.flow)}" (expected ${HOSTED_FLOWS.join(" | ")}).`);
1194
+ }
1195
+ if (opts.renderPrompt !== false && typeof document === "undefined") {
1196
+ throw new InvoError({
1197
+ message: "approveHosted needs a DOM to render the match-code prompt (or pass renderPrompt:false).",
1198
+ code: "DOM_UNAVAILABLE",
1199
+ status: 0
1200
+ });
1201
+ }
1202
+ const signal = opts.signal;
1203
+ if (signal?.aborted) return { status: "closed", popupBlocked: false };
1204
+ const open = deps.open ?? ((u, n, f) => window.open(u, n, f));
1205
+ const navigate = deps.navigate ?? ((u) => window.location.assign(u));
1206
+ const closedPollMs = deps.closedPollMs ?? 500;
1207
+ const coopGraceMs = deps.coopGraceMs ?? 1500;
1208
+ const createPrompt = deps.createPrompt ?? (() => new HostedEnrollmentPrompt());
1209
+ const width = opts.popup?.width ?? 480;
1210
+ const height = opts.popup?.height ?? 720;
1211
+ const sw = window.screen?.width ?? width;
1212
+ const sh = window.screen?.height ?? height;
1213
+ const left = Math.max(0, Math.round((sw - width) / 2));
1214
+ const top = Math.max(0, Math.round((sh - height) / 2));
1215
+ const features = `popup=yes,width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=yes`;
1216
+ const name = `invo-approval-${encodeURIComponent(String(opts.transactionId)).replace(/[^A-Za-z0-9-]/g, "")}`;
1217
+ let popup;
1218
+ try {
1219
+ popup = open("about:blank", name, features);
1220
+ } catch {
1221
+ popup = null;
1222
+ }
1223
+ const mode = opts.popupBlocked ?? "resolve";
1224
+ if (!popup && mode === "resolve") {
1225
+ return { status: "blocked", popupBlocked: true, message: BLOCKED_HINT };
1226
+ }
1227
+ let begin;
1228
+ try {
1229
+ begin = await api.begin();
1230
+ } catch (err) {
1231
+ try {
1232
+ popup?.close();
1233
+ } catch {
1234
+ }
1235
+ if (signal?.aborted || err instanceof InvoError && err.code === "ABORTED") {
1236
+ return { status: "closed", popupBlocked: false };
1237
+ }
1238
+ throw err;
1239
+ }
1240
+ const deviceCode = typeof begin["device_code"] === "string" ? begin["device_code"] : "";
1241
+ const url = typeof begin["verification_uri_complete"] === "string" ? begin["verification_uri_complete"] : "";
1242
+ if (!deviceCode || !url) {
1243
+ try {
1244
+ popup?.close();
1245
+ } catch {
1246
+ }
1247
+ const { device_code: _dc, ...safeBody } = begin;
1248
+ throw new InvoError({
1249
+ message: "begin returned no device_code / verification_uri_complete.",
1250
+ code: "UNEXPECTED_RESPONSE",
1251
+ status: 0,
1252
+ body: safeBody
1253
+ });
1254
+ }
1255
+ let origin;
1256
+ try {
1257
+ origin = derivePlatformOrigin(url, opts.platformOrigin);
1258
+ } catch (err) {
1259
+ try {
1260
+ popup?.close();
1261
+ } catch {
1262
+ }
1263
+ throw err;
1264
+ }
1265
+ const expiresIn = Math.min(
1266
+ MAX_EXPIRES_IN_S,
1267
+ Math.max(1, Number(begin["expires_in"]) || 600)
1268
+ );
1269
+ let interval = Math.max(1, Number(begin["interval"]) || 5);
1270
+ if (!popup) {
1271
+ try {
1272
+ navigate(url);
1273
+ return { status: "redirected", popupBlocked: true };
1274
+ } catch (err) {
1275
+ return {
1276
+ status: "blocked",
1277
+ popupBlocked: true,
1278
+ message: `The browser blocked the popup and the redirect fallback failed${err instanceof Error && err.message ? `: ${err.message}` : "."}`
1279
+ };
1280
+ }
1281
+ }
1282
+ const win = popup;
1283
+ try {
1284
+ const loc = win.location;
1285
+ if (loc && typeof loc.replace === "function") loc.replace(url);
1286
+ else if (loc) loc.href = url;
1287
+ } catch {
1288
+ }
1289
+ const navigatedAt = Date.now();
1290
+ try {
1291
+ win.focus?.();
1292
+ } catch {
1293
+ }
1294
+ return new Promise((resolve, reject) => {
1295
+ let settled = false;
1296
+ let prompt;
1297
+ let wake = null;
1298
+ let expiryTimer;
1299
+ let closedTimer;
1300
+ const cleanup = (closePopup) => {
1301
+ settled = true;
1302
+ window.removeEventListener("message", onMessage);
1303
+ signal?.removeEventListener("abort", onAbort);
1304
+ if (expiryTimer !== void 0) clearTimeout(expiryTimer);
1305
+ if (closedTimer !== void 0) clearInterval(closedTimer);
1306
+ prompt?.clear();
1307
+ if (closePopup && !win.closed) {
1308
+ try {
1309
+ win.close();
1310
+ } catch {
1311
+ }
1312
+ }
1313
+ wake?.();
1314
+ };
1315
+ const finish = (result, closePopup) => {
1316
+ if (settled) return;
1317
+ cleanup(closePopup);
1318
+ resolve(result);
1319
+ };
1320
+ const fail = (err) => {
1321
+ if (settled) return;
1322
+ cleanup(false);
1323
+ reject(err);
1324
+ };
1325
+ const respond = async (decision) => {
1326
+ if (settled) return;
1327
+ try {
1328
+ await api.confirmEnrollment(deviceCode, decision);
1329
+ } catch (err) {
1330
+ if (err instanceof InvoError && err.rawCode && CONFIRM_QUIET_CODES.has(err.rawCode)) {
1331
+ prompt?.update(null);
1332
+ return;
1333
+ }
1334
+ throw err;
1335
+ }
1336
+ wake?.();
1337
+ };
1338
+ const ensurePrompt = () => {
1339
+ if (!prompt) {
1340
+ prompt = createPrompt();
1341
+ prompt.configure({
1342
+ respond,
1343
+ onEnrollment: opts.onEnrollment,
1344
+ renderPrompt: opts.renderPrompt !== false
1345
+ });
1346
+ }
1347
+ return prompt;
1348
+ };
1349
+ const showEnrollment = (input) => {
1350
+ const e = input && typeof input === "object" ? input : null;
1351
+ if (e) ensurePrompt().update(e);
1352
+ else prompt?.update(null);
1353
+ };
1354
+ const onMessage = (event) => {
1355
+ if (event.origin !== origin) return;
1356
+ if (event.source && event.source !== win) return;
1357
+ const data = event.data;
1358
+ if (!data || typeof data !== "object" || data.type !== HOSTED_MESSAGE_TYPE) return;
1359
+ wake?.();
1360
+ };
1361
+ const onAbort = () => finish({ status: "closed", popupBlocked: false }, true);
1362
+ const pause = (ms) => new Promise((r) => {
1363
+ const t = setTimeout(() => {
1364
+ wake = null;
1365
+ r();
1366
+ }, ms);
1367
+ wake = () => {
1368
+ clearTimeout(t);
1369
+ wake = null;
1370
+ r();
1371
+ };
1372
+ });
1373
+ window.addEventListener("message", onMessage);
1374
+ signal?.addEventListener("abort", onAbort, { once: true });
1375
+ expiryTimer = setTimeout(() => finish({ status: "expired", popupBlocked: false }, false), expiresIn * 1e3);
1376
+ closedTimer = setInterval(() => {
1377
+ if (!win.closed) return;
1378
+ if (Date.now() - navigatedAt < coopGraceMs) {
1379
+ finish({ status: "blocked", popupBlocked: true, message: COOP_HINT }, false);
1380
+ } else {
1381
+ finish({ status: "closed", popupBlocked: false }, false);
1382
+ }
1383
+ }, closedPollMs);
1384
+ void (async () => {
1385
+ let transientFailures = 0;
1386
+ while (!settled) {
1387
+ await pause(interval * 1e3);
1388
+ if (settled) return;
1389
+ let raw;
1390
+ try {
1391
+ raw = await api.poll(deviceCode);
1392
+ } catch (err) {
1393
+ if (settled) return;
1394
+ const p = pollToken(err);
1395
+ if (!p) {
1396
+ if (++transientFailures >= MAX_TRANSIENT_POLL_FAILURES) return fail(err);
1397
+ const ra = err instanceof InvoError && err.status === 429 ? err.retryAfter : void 0;
1398
+ if (typeof ra === "number" && ra > interval) interval = Math.min(ra, MAX_EXPIRES_IN_S);
1399
+ continue;
1400
+ }
1401
+ transientFailures = 0;
1402
+ const bodyInterval = Number(p.body["interval"]);
1403
+ switch (p.token) {
1404
+ case "authorization_pending":
1405
+ if (bodyInterval > 0) interval = bodyInterval;
1406
+ showEnrollment(p.body["enrollment"]);
1407
+ continue;
1408
+ case "slow_down":
1409
+ interval = Math.max(interval + 5, bodyInterval > 0 ? bodyInterval : 0);
1410
+ continue;
1411
+ case "expired_token":
1412
+ return finish({ status: "expired", popupBlocked: false }, false);
1413
+ case "access_denied":
1414
+ return finish({ status: "denied", popupBlocked: false }, false);
1415
+ default:
1416
+ return fail(err);
1417
+ }
1418
+ }
1419
+ if (settled) return;
1420
+ if (raw["status"] !== "approved") continue;
1421
+ try {
1422
+ const approval = await api.approve(deviceCode);
1423
+ if (settled) return;
1424
+ finish({ status: "approved", popupBlocked: false, approval }, true);
1425
+ } catch (err) {
1426
+ fail(err);
1427
+ }
1428
+ return;
1429
+ }
1430
+ })();
1431
+ });
1432
+ }
1433
+
754
1434
  // src/index.ts
755
1435
  function toPendingCollectItem(row) {
756
1436
  return {
@@ -779,6 +1459,29 @@ function toBalanceRow(row) {
779
1459
  raw: row
780
1460
  };
781
1461
  }
1462
+ function toApproveResult(raw, transactionId) {
1463
+ const holdReason = raw["error_code"] ?? raw["code"];
1464
+ return {
1465
+ status: String(raw["status"] ?? ""),
1466
+ next: String(raw["next"] ?? ""),
1467
+ transactionId: String(raw["transaction_id"] ?? transactionId),
1468
+ claimCode: raw["claim_code"],
1469
+ claimCodeExpiresAt: raw["claim_code_expires_at"],
1470
+ holdReason: typeof holdReason === "string" ? holdReason : void 0,
1471
+ risk: raw["risk"],
1472
+ guardianApproval: raw["guardian_approval"] ?? void 0,
1473
+ pollEndpoint: raw["poll_endpoint"],
1474
+ raw
1475
+ };
1476
+ }
1477
+ function toConfirmReceiptResult(raw) {
1478
+ const holdReason = raw["error_code"] ?? raw["code"];
1479
+ return {
1480
+ status: String(raw["status"] ?? ""),
1481
+ holdReason: typeof holdReason === "string" ? holdReason : void 0,
1482
+ raw
1483
+ };
1484
+ }
782
1485
  var PlatformCommerceClient = class {
783
1486
  /**
784
1487
  * Embed INVO's hosted checkout in an iframe and listen for completion.
@@ -917,6 +1620,60 @@ var InvoClient = class {
917
1620
  return { status: String(raw["status"] ?? ""), device: raw["device"] ?? null, raw };
918
1621
  });
919
1622
  }
1623
+ async approveHosted(opts) {
1624
+ const txn = String(opts.transactionId ?? "");
1625
+ const id = encodeURIComponent(txn);
1626
+ const signal = opts.signal;
1627
+ const api = {
1628
+ begin: () => this.withTokenRetry(
1629
+ () => this.post(
1630
+ "/api/sdk/approvals/device/begin",
1631
+ { transaction_id: txn, flow: opts.flow, channel: "popup" },
1632
+ signal
1633
+ )
1634
+ ),
1635
+ poll: (deviceCode) => this.withTokenRetry(
1636
+ () => this.post(
1637
+ "/api/sdk/approvals/device/poll",
1638
+ { device_code: deviceCode },
1639
+ signal
1640
+ )
1641
+ ),
1642
+ confirmEnrollment: (deviceCode, decision) => this.withTokenRetry(
1643
+ () => this.post(
1644
+ "/api/sdk/approvals/device/confirm-enrollment",
1645
+ { device_code: deviceCode, decision },
1646
+ signal
1647
+ )
1648
+ ),
1649
+ approve: (deviceCode) => this.withTokenRetry(async () => {
1650
+ const body = { device_code: deviceCode };
1651
+ switch (opts.flow) {
1652
+ case "transfer":
1653
+ return toApproveResult(
1654
+ await this.post(`/api/sdk/transfers/${id}/approve`, body, signal),
1655
+ txn
1656
+ );
1657
+ case "send":
1658
+ return toApproveResult(
1659
+ await this.post(`/api/sdk/send/${id}/approve`, body, signal),
1660
+ txn
1661
+ );
1662
+ case "send_receipt":
1663
+ return toConfirmReceiptResult(
1664
+ await this.post(`/api/sdk/send/${id}/confirm-receipt`, body, signal)
1665
+ );
1666
+ case "transfer_receipt":
1667
+ return toConfirmReceiptResult(
1668
+ await this.post(`/api/sdk/transfers/${id}/confirm-receipt`, body, signal)
1669
+ );
1670
+ default:
1671
+ throw new Error(`approveHosted: unknown flow "${String(opts.flow)}".`);
1672
+ }
1673
+ })
1674
+ };
1675
+ return runHostedApproval(opts, api);
1676
+ }
920
1677
  /** Approve a SEND with the player's passkey. */
921
1678
  async approveSend(transactionId, opts) {
922
1679
  return this.approve("send", transactionId, opts);
@@ -1184,19 +1941,7 @@ var InvoClient = class {
1184
1941
  { webauthn_assertion: assertion },
1185
1942
  signal
1186
1943
  );
1187
- const holdReason = raw["error_code"] ?? raw["code"];
1188
- return {
1189
- status: String(raw["status"] ?? ""),
1190
- next: String(raw["next"] ?? ""),
1191
- transactionId: String(raw["transaction_id"] ?? transactionId),
1192
- claimCode: raw["claim_code"],
1193
- claimCodeExpiresAt: raw["claim_code_expires_at"],
1194
- holdReason: typeof holdReason === "string" ? holdReason : void 0,
1195
- risk: raw["risk"],
1196
- guardianApproval: raw["guardian_approval"] ?? void 0,
1197
- pollEndpoint: raw["poll_endpoint"],
1198
- raw
1199
- };
1944
+ return toApproveResult(raw, transactionId);
1200
1945
  });
1201
1946
  }
1202
1947
  async confirmReceipt(flow, transactionId, opts) {
@@ -1213,12 +1958,7 @@ var InvoClient = class {
1213
1958
  { webauthn_assertion: assertion },
1214
1959
  signal
1215
1960
  );
1216
- const holdReason = raw["error_code"] ?? raw["code"];
1217
- return {
1218
- status: String(raw["status"] ?? ""),
1219
- holdReason: typeof holdReason === "string" ? holdReason : void 0,
1220
- raw
1221
- };
1961
+ return toConfirmReceiptResult(raw);
1222
1962
  });
1223
1963
  }
1224
1964
  };