@invonetwork/web-sdk 3.29.0 → 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 -1389
  2. package/README.md +2954 -2923
  3. package/dist/{chunk-FJR44FKW.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 +295 -15
  8. package/dist/game-server.d.cts +49 -9
  9. package/dist/game-server.d.ts +49 -9
  10. package/dist/game-server.js +278 -20
  11. package/dist/game.cjs +2680 -9
  12. package/dist/game.d.cts +78 -4
  13. package/dist/game.d.ts +78 -4
  14. package/dist/game.js +561 -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-Dnx5jxS4.d.ts → server-B0mvlGFY.d.ts} +17 -2
  23. package/dist/{server-UZ38eD2p.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.ts → types-BTbZicgj.d.cts} +1 -40
  29. package/dist/{types-_lIm74kd.d.cts → types-BTbZicgj.d.ts} +1 -40
  30. package/dist/{types-CoW9LopI.d.cts → types-jUxfYjiD.d.cts} +76 -1
  31. package/dist/{types-CoW9LopI.d.ts → types-jUxfYjiD.d.ts} +76 -1
  32. package/dist/{version-xyYQO5hp.d.cts → version-DfVkILOj.d.cts} +1 -1
  33. package/dist/{version-xyYQO5hp.d.ts → version-DfVkILOj.d.ts} +1 -1
  34. package/package.json +1 -1
  35. package/dist/chunk-6CN236QH.js +0 -473
  36. package/dist/chunk-KZJABBVT.js +0 -6
@@ -0,0 +1,1634 @@
1
+ import { InvoError, assertSecureBaseUrl, Http, toPhoneChangeApprovalsResult, phoneChangeSignalMessage, toApprovePhoneChangeResult, toDestinationsResult, toLoyaltyCardsResult, toLoyaltyVaultResult, toRedeemRewardResult, toRewardsPageLink, buildGameEventBody, toReportGameEventResult, receiptFields } from './chunk-TSTP2CWA.js';
2
+
3
+ // src/shared/webauthn.ts
4
+ function malformedOptions(field) {
5
+ return new InvoError({
6
+ message: `Malformed WebAuthn options from the backend: missing/invalid \`${field}\`.`,
7
+ code: "WEBAUTHN_OPTIONS_MALFORMED",
8
+ status: 0
9
+ });
10
+ }
11
+ function b64urlToBuffer(value) {
12
+ const pad = value.length % 4 === 0 ? "" : "=".repeat(4 - value.length % 4);
13
+ const b64 = value.replace(/-/g, "+").replace(/_/g, "/") + pad;
14
+ const bin = atob(b64);
15
+ const bytes = new Uint8Array(bin.length);
16
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
17
+ return bytes.buffer;
18
+ }
19
+ function bufferToB64url(buf) {
20
+ const bytes = new Uint8Array(buf);
21
+ let bin = "";
22
+ for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
23
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
24
+ }
25
+ function descriptorsToBinary(list) {
26
+ return (list ?? []).map((d) => {
27
+ const out = {
28
+ id: b64urlToBuffer(d.id),
29
+ type: d.type
30
+ };
31
+ if (d.transports) out.transports = d.transports;
32
+ return out;
33
+ });
34
+ }
35
+ function toCreationOptions(json) {
36
+ if (typeof json?.["challenge"] !== "string") throw malformedOptions("challenge");
37
+ if (typeof json["user"]?.id !== "string") throw malformedOptions("user.id");
38
+ const opts = {
39
+ ...json,
40
+ challenge: b64urlToBuffer(json["challenge"]),
41
+ user: {
42
+ ...json["user"],
43
+ id: b64urlToBuffer(json["user"].id)
44
+ }
45
+ };
46
+ if (json["excludeCredentials"]) {
47
+ opts.excludeCredentials = descriptorsToBinary(json["excludeCredentials"]);
48
+ }
49
+ return opts;
50
+ }
51
+ function toRequestOptions(json) {
52
+ if (typeof json?.["challenge"] !== "string") throw malformedOptions("challenge");
53
+ const opts = {
54
+ ...json,
55
+ challenge: b64urlToBuffer(json["challenge"])
56
+ };
57
+ if (json["allowCredentials"]) {
58
+ opts.allowCredentials = descriptorsToBinary(json["allowCredentials"]);
59
+ }
60
+ return opts;
61
+ }
62
+ function registrationToJSON(cred) {
63
+ const r = cred.response;
64
+ return {
65
+ id: cred.id,
66
+ rawId: bufferToB64url(cred.rawId),
67
+ type: cred.type,
68
+ authenticatorAttachment: cred.authenticatorAttachment ?? void 0,
69
+ clientExtensionResults: cred.getClientExtensionResults(),
70
+ response: {
71
+ clientDataJSON: bufferToB64url(r.clientDataJSON),
72
+ attestationObject: bufferToB64url(r.attestationObject),
73
+ transports: typeof r.getTransports === "function" ? r.getTransports() : void 0
74
+ }
75
+ };
76
+ }
77
+ function assertionToJSON(cred) {
78
+ const r = cred.response;
79
+ return {
80
+ id: cred.id,
81
+ rawId: bufferToB64url(cred.rawId),
82
+ type: cred.type,
83
+ authenticatorAttachment: cred.authenticatorAttachment ?? void 0,
84
+ clientExtensionResults: cred.getClientExtensionResults(),
85
+ response: {
86
+ clientDataJSON: bufferToB64url(r.clientDataJSON),
87
+ authenticatorData: bufferToB64url(r.authenticatorData),
88
+ signature: bufferToB64url(r.signature),
89
+ userHandle: r.userHandle ? bufferToB64url(r.userHandle) : null
90
+ }
91
+ };
92
+ }
93
+
94
+ // src/shared/hosted-approval.ts
95
+ var HOSTED_FLOWS = [
96
+ "transfer",
97
+ "send",
98
+ "send_receipt",
99
+ "transfer_receipt"
100
+ ];
101
+ var HOSTED_MESSAGE_TYPE = "invo.approval";
102
+ var MAX_EXPIRES_IN_S = 24 * 24 * 60 * 60;
103
+ var CONFIRM_QUIET_CODES = /* @__PURE__ */ new Set([
104
+ "DEVICE_APPROVAL_ENROLLMENT_ALREADY_DECIDED",
105
+ "DEVICE_APPROVAL_NO_ENROLLMENT_PENDING"
106
+ ]);
107
+ var MAX_TRANSIENT_POLL_FAILURES = 5;
108
+ function derivePlatformOrigin(verificationUriComplete, explicit) {
109
+ let u;
110
+ try {
111
+ u = new URL(verificationUriComplete);
112
+ } catch {
113
+ throw new InvoError({
114
+ message: "begin returned no absolute verification_uri_complete.",
115
+ code: "UNEXPECTED_RESPONSE",
116
+ status: 0
117
+ });
118
+ }
119
+ const isLocal = u.hostname === "localhost" || u.hostname === "127.0.0.1" || u.hostname === "[::1]";
120
+ if (u.protocol !== "https:" && !(u.protocol === "http:" && isLocal)) {
121
+ throw new InvoError({
122
+ message: "The hosted approval page must be https (plaintext would let any page forge the wake-up).",
123
+ code: "INVALID_INPUT",
124
+ status: 0
125
+ });
126
+ }
127
+ if (explicit !== void 0 && u.origin !== explicit) {
128
+ throw new InvoError({
129
+ message: `platformOrigin (${explicit}) does not match the hosted page's origin (${u.origin}).`,
130
+ code: "INVALID_INPUT",
131
+ status: 0
132
+ });
133
+ }
134
+ return u.origin;
135
+ }
136
+ function normalizeEnrollment(input) {
137
+ if (!input || typeof input !== "object") return null;
138
+ const state = typeof input.state === "string" ? input.state : "";
139
+ if (!state) return null;
140
+ const label = input.device_label ?? input.deviceLabel;
141
+ const code = input.match_code ?? input.matchCode;
142
+ const at = input.requested_at ?? input.requestedAt;
143
+ return {
144
+ state,
145
+ deviceLabel: typeof label === "string" && label ? label : "your phone",
146
+ matchCode: typeof code === "string" ? code : "",
147
+ requestedAt: typeof at === "string" ? at : void 0,
148
+ raw: input
149
+ };
150
+ }
151
+ var BRAND = "#4f46e5";
152
+ var FONT = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif";
153
+ var MONO = "ui-monospace, SFMono-Regular, Menlo, Consolas, 'Liberation Mono', monospace";
154
+ var PROMPT_IDS = {
155
+ root: "invo-hosted-enrollment",
156
+ title: "invo-hosted-enrollment-title",
157
+ code: "invo-hosted-enrollment-code",
158
+ yes: "invo-hosted-enrollment-yes",
159
+ no: "invo-hosted-enrollment-no",
160
+ stop: "invo-hosted-enrollment-stop",
161
+ error: "invo-hosted-enrollment-error"
162
+ };
163
+ var HostedEnrollmentPrompt = class {
164
+ constructor() {
165
+ this.handlers = { respond: async () => {
166
+ }, renderPrompt: true };
167
+ this.enrollment = null;
168
+ /** The last match code the player answered, so a stale poll can't re-ask it. */
169
+ this.decided = null;
170
+ this.root = null;
171
+ this.previousFocus = null;
172
+ this.keyHandler = null;
173
+ this.busy = false;
174
+ }
175
+ get current() {
176
+ return this.enrollment;
177
+ }
178
+ configure(handlers) {
179
+ this.handlers = handlers;
180
+ this.decided = null;
181
+ if (this.enrollment) this.render();
182
+ }
183
+ update(input) {
184
+ let next = normalizeEnrollment(input);
185
+ if (next && next.state === "awaiting_screen" && this.decided && this.decided.code === next.matchCode) {
186
+ next = this.decided.decision === "approve" ? { ...next, state: "confirmed" } : null;
187
+ }
188
+ 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);
189
+ this.enrollment = next;
190
+ if (changed) this.handlers.onEnrollment?.(next, this.handlers.respond);
191
+ this.render();
192
+ }
193
+ clear() {
194
+ this.update(null);
195
+ }
196
+ // --- rendering ---
197
+ render() {
198
+ if (typeof document === "undefined") return;
199
+ const e = this.enrollment;
200
+ const visible = this.handlers.renderPrompt && e && (e.state === "awaiting_screen" || e.state === "confirmed");
201
+ if (!visible || !e) {
202
+ this.unmount();
203
+ return;
204
+ }
205
+ this.mount();
206
+ const root = this.root;
207
+ root.innerHTML = "";
208
+ root.appendChild(e.state === "awaiting_screen" ? this.buildPrompt(e) : this.buildFinishing(e));
209
+ this.focusInitial(e.state);
210
+ }
211
+ mount() {
212
+ if (this.root) return;
213
+ this.previousFocus = document.activeElement;
214
+ const overlay = document.createElement("div");
215
+ overlay.id = PROMPT_IDS.root;
216
+ overlay.setAttribute("role", "dialog");
217
+ overlay.setAttribute("aria-modal", "true");
218
+ overlay.setAttribute("aria-labelledby", PROMPT_IDS.title);
219
+ overlay.tabIndex = -1;
220
+ overlay.style.cssText = [
221
+ "position:fixed",
222
+ "inset:0",
223
+ "z-index:2147483000",
224
+ "display:flex",
225
+ "align-items:center",
226
+ "justify-content:center",
227
+ "padding:16px",
228
+ "background:rgba(17,24,39,.55)",
229
+ `font-family:${FONT}`,
230
+ "color:#111827",
231
+ "-webkit-font-smoothing:antialiased",
232
+ "outline:none"
233
+ ].join(";");
234
+ this.keyHandler = (ev) => this.onKeyDown(ev);
235
+ overlay.addEventListener("keydown", this.keyHandler);
236
+ document.body.appendChild(overlay);
237
+ this.root = overlay;
238
+ }
239
+ unmount() {
240
+ if (!this.root) return;
241
+ if (this.keyHandler) this.root.removeEventListener("keydown", this.keyHandler);
242
+ this.root.remove();
243
+ this.root = null;
244
+ this.keyHandler = null;
245
+ this.busy = false;
246
+ const prev = this.previousFocus;
247
+ this.previousFocus = null;
248
+ if (prev && typeof prev.focus === "function") {
249
+ try {
250
+ prev.focus();
251
+ } catch {
252
+ }
253
+ }
254
+ }
255
+ card() {
256
+ const card = document.createElement("div");
257
+ card.style.cssText = [
258
+ "background:#ffffff",
259
+ "border-radius:16px",
260
+ "box-shadow:0 20px 60px rgba(17,24,39,.25)",
261
+ "max-width:420px",
262
+ "width:100%",
263
+ "padding:28px 28px 24px",
264
+ "box-sizing:border-box",
265
+ "text-align:center"
266
+ ].join(";");
267
+ const mark = document.createElement("div");
268
+ mark.textContent = "INVO";
269
+ mark.setAttribute("aria-hidden", "true");
270
+ mark.style.cssText = `font-weight:800;letter-spacing:.18em;font-size:13px;color:${BRAND};margin-bottom:14px`;
271
+ card.appendChild(mark);
272
+ return card;
273
+ }
274
+ button(id, label, primary) {
275
+ const b = document.createElement("button");
276
+ b.type = "button";
277
+ b.id = id;
278
+ b.textContent = label;
279
+ b.style.cssText = [
280
+ "display:block",
281
+ "width:100%",
282
+ "box-sizing:border-box",
283
+ "border-radius:10px",
284
+ "padding:12px 16px",
285
+ "font:inherit",
286
+ "font-size:15px",
287
+ "font-weight:600",
288
+ "cursor:pointer",
289
+ "margin-top:10px",
290
+ primary ? `background:${BRAND};color:#ffffff;border:1px solid ${BRAND}` : "background:#ffffff;color:#374151;border:1px solid #d1d5db"
291
+ ].join(";");
292
+ return b;
293
+ }
294
+ buildPrompt(e) {
295
+ const card = this.card();
296
+ const title = document.createElement("h2");
297
+ title.id = PROMPT_IDS.title;
298
+ title.textContent = `Set up INVO on ${e.deviceLabel}?`;
299
+ title.style.cssText = "margin:0 0 14px;font-size:20px;font-weight:700;line-height:1.3";
300
+ card.appendChild(title);
301
+ const codeLabel = document.createElement("div");
302
+ codeLabel.textContent = "Code";
303
+ codeLabel.style.cssText = "font-size:12px;text-transform:uppercase;letter-spacing:.12em;color:#6b7280";
304
+ card.appendChild(codeLabel);
305
+ const code = document.createElement("div");
306
+ code.id = PROMPT_IDS.code;
307
+ code.textContent = e.matchCode;
308
+ code.setAttribute("aria-label", `Code ${e.matchCode.split("").join(" ")}`);
309
+ code.style.cssText = [
310
+ `font-family:${MONO}`,
311
+ "font-size:40px",
312
+ "font-weight:700",
313
+ "letter-spacing:.3em",
314
+ "text-indent:.3em",
315
+ "line-height:1.2",
316
+ "margin:6px 0 16px",
317
+ "color:#111827",
318
+ "background:#f3f4f6",
319
+ "border-radius:12px",
320
+ "padding:14px 8px"
321
+ ].join(";");
322
+ card.appendChild(code);
323
+ const body = document.createElement("p");
324
+ body.textContent = "Say Yes only if the phone you just scanned/opened shows this code.";
325
+ body.style.cssText = "margin:0 0 6px;font-size:15px;line-height:1.5;color:#374151";
326
+ card.appendChild(body);
327
+ const err = document.createElement("div");
328
+ err.id = PROMPT_IDS.error;
329
+ err.setAttribute("role", "alert");
330
+ err.style.cssText = "min-height:18px;font-size:13px;color:#b91c1c;margin-top:4px";
331
+ card.appendChild(err);
332
+ const yes = this.button(PROMPT_IDS.yes, "Yes, it shows this code", true);
333
+ yes.addEventListener("click", () => void this.decide("approve"));
334
+ card.appendChild(yes);
335
+ const no = this.button(PROMPT_IDS.no, "No, that is not my phone", false);
336
+ no.addEventListener("click", () => void this.decide("deny"));
337
+ card.appendChild(no);
338
+ return card;
339
+ }
340
+ buildFinishing(e) {
341
+ const card = this.card();
342
+ card.style.padding = "18px 22px";
343
+ const row = document.createElement("div");
344
+ row.style.cssText = "display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap";
345
+ const text = document.createElement("div");
346
+ text.id = PROMPT_IDS.title;
347
+ text.textContent = `Finishing on ${e.deviceLabel}\u2026`;
348
+ text.tabIndex = -1;
349
+ text.setAttribute("aria-live", "polite");
350
+ text.style.cssText = "font-size:15px;color:#374151;outline:none";
351
+ row.appendChild(text);
352
+ const stop = document.createElement("button");
353
+ stop.type = "button";
354
+ stop.id = PROMPT_IDS.stop;
355
+ stop.textContent = "Stop it, wrong code";
356
+ 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`;
357
+ stop.addEventListener("click", () => void this.decide("deny"));
358
+ row.appendChild(stop);
359
+ card.appendChild(row);
360
+ return card;
361
+ }
362
+ async decide(decision) {
363
+ if (this.busy || !this.enrollment) return;
364
+ this.busy = true;
365
+ this.root?.focus();
366
+ this.setButtonsDisabled(true);
367
+ try {
368
+ await this.handlers.respond(decision);
369
+ const now = this.enrollment;
370
+ if (!now) return;
371
+ this.decided = { code: now.matchCode, decision };
372
+ if (decision === "deny") {
373
+ this.update(null);
374
+ } else if (now.state === "awaiting_screen") {
375
+ this.update({ ...now.raw, state: "confirmed" });
376
+ }
377
+ } catch (err) {
378
+ const box = this.root?.querySelector(`#${PROMPT_IDS.error}`);
379
+ if (box) {
380
+ box.textContent = err instanceof Error && err.message ? `Couldn't send your answer: ${err.message}` : "Couldn't send your answer. Try again.";
381
+ }
382
+ } finally {
383
+ this.busy = false;
384
+ this.setButtonsDisabled(false);
385
+ if (this.root && this.enrollment?.state === "awaiting_screen") this.focusInitial("awaiting_screen");
386
+ }
387
+ }
388
+ setButtonsDisabled(disabled) {
389
+ this.root?.querySelectorAll("button").forEach((b) => {
390
+ b.disabled = disabled;
391
+ });
392
+ }
393
+ focusables() {
394
+ if (!this.root) return [];
395
+ return Array.from(this.root.querySelectorAll("button:not([disabled])"));
396
+ }
397
+ /** Prompt: first button. Finishing row: the text, NOT "Stop it" — a stray Enter must not deny. */
398
+ focusInitial(state) {
399
+ const target = state === "confirmed" ? this.root?.querySelector(`#${PROMPT_IDS.title}`) : this.focusables()[0];
400
+ try {
401
+ (target ?? this.root)?.focus();
402
+ } catch {
403
+ }
404
+ }
405
+ onKeyDown(ev) {
406
+ if (ev.key === "Escape") {
407
+ ev.preventDefault();
408
+ void this.decide("deny");
409
+ return;
410
+ }
411
+ if (ev.key !== "Tab") return;
412
+ ev.preventDefault();
413
+ const items = this.focusables();
414
+ if (items.length === 0) {
415
+ this.root?.focus();
416
+ return;
417
+ }
418
+ const active = document.activeElement;
419
+ const idx = items.indexOf(active);
420
+ let nextIdx;
421
+ if (idx === -1) nextIdx = ev.shiftKey ? items.length - 1 : 0;
422
+ else nextIdx = (idx + (ev.shiftKey ? -1 : 1) + items.length) % items.length;
423
+ items[nextIdx].focus();
424
+ }
425
+ };
426
+ 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.";
427
+ var BLOCKED_HINT = "The browser blocked the popup. Nothing was started \u2014 call approveHosted() from a click handler.";
428
+ function pollToken(err) {
429
+ if (!(err instanceof InvoError) || err.status === 0 || err.status === 429 || err.status >= 500) return null;
430
+ const body = err.body && typeof err.body === "object" ? err.body : {};
431
+ const token = typeof body["error"] === "string" ? body["error"] : "";
432
+ return { token, body };
433
+ }
434
+ async function runHostedApproval(opts, api, deps = {}) {
435
+ if (typeof window === "undefined") {
436
+ throw new InvoError({
437
+ message: "approveHosted requires a browser window.",
438
+ code: "DOM_UNAVAILABLE",
439
+ status: 0
440
+ });
441
+ }
442
+ if (!opts.transactionId || !String(opts.transactionId).trim()) {
443
+ throw new Error("approveHosted requires a `transactionId`.");
444
+ }
445
+ if (!HOSTED_FLOWS.includes(opts.flow)) {
446
+ throw new Error(`approveHosted: unknown flow "${String(opts.flow)}" (expected ${HOSTED_FLOWS.join(" | ")}).`);
447
+ }
448
+ if (opts.renderPrompt !== false && typeof document === "undefined") {
449
+ throw new InvoError({
450
+ message: "approveHosted needs a DOM to render the match-code prompt (or pass renderPrompt:false).",
451
+ code: "DOM_UNAVAILABLE",
452
+ status: 0
453
+ });
454
+ }
455
+ const signal = opts.signal;
456
+ if (signal?.aborted) return { status: "closed", popupBlocked: false };
457
+ const open = deps.open ?? ((u, n, f) => window.open(u, n, f));
458
+ const navigate = deps.navigate ?? ((u) => window.location.assign(u));
459
+ const closedPollMs = deps.closedPollMs ?? 500;
460
+ const coopGraceMs = deps.coopGraceMs ?? 1500;
461
+ const createPrompt = deps.createPrompt ?? (() => new HostedEnrollmentPrompt());
462
+ const width = opts.popup?.width ?? 480;
463
+ const height = opts.popup?.height ?? 720;
464
+ const sw = window.screen?.width ?? width;
465
+ const sh = window.screen?.height ?? height;
466
+ const left = Math.max(0, Math.round((sw - width) / 2));
467
+ const top = Math.max(0, Math.round((sh - height) / 2));
468
+ const features = `popup=yes,width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=yes`;
469
+ const name = `invo-approval-${encodeURIComponent(String(opts.transactionId)).replace(/[^A-Za-z0-9-]/g, "")}`;
470
+ let popup;
471
+ try {
472
+ popup = open("about:blank", name, features);
473
+ } catch {
474
+ popup = null;
475
+ }
476
+ const mode = opts.popupBlocked ?? "resolve";
477
+ if (!popup && mode === "resolve") {
478
+ return { status: "blocked", popupBlocked: true, message: BLOCKED_HINT };
479
+ }
480
+ let begin;
481
+ try {
482
+ begin = await api.begin();
483
+ } catch (err) {
484
+ try {
485
+ popup?.close();
486
+ } catch {
487
+ }
488
+ if (signal?.aborted || err instanceof InvoError && err.code === "ABORTED") {
489
+ return { status: "closed", popupBlocked: false };
490
+ }
491
+ throw err;
492
+ }
493
+ const deviceCode = typeof begin["device_code"] === "string" ? begin["device_code"] : "";
494
+ const url = typeof begin["verification_uri_complete"] === "string" ? begin["verification_uri_complete"] : "";
495
+ if (!deviceCode || !url) {
496
+ try {
497
+ popup?.close();
498
+ } catch {
499
+ }
500
+ const { device_code: _dc, ...safeBody } = begin;
501
+ throw new InvoError({
502
+ message: "begin returned no device_code / verification_uri_complete.",
503
+ code: "UNEXPECTED_RESPONSE",
504
+ status: 0,
505
+ body: safeBody
506
+ });
507
+ }
508
+ let origin;
509
+ try {
510
+ origin = derivePlatformOrigin(url, opts.platformOrigin);
511
+ } catch (err) {
512
+ try {
513
+ popup?.close();
514
+ } catch {
515
+ }
516
+ throw err;
517
+ }
518
+ const expiresIn = Math.min(
519
+ MAX_EXPIRES_IN_S,
520
+ Math.max(1, Number(begin["expires_in"]) || 600)
521
+ );
522
+ let interval = Math.max(1, Number(begin["interval"]) || 5);
523
+ if (!popup) {
524
+ try {
525
+ navigate(url);
526
+ return { status: "redirected", popupBlocked: true };
527
+ } catch (err) {
528
+ return {
529
+ status: "blocked",
530
+ popupBlocked: true,
531
+ message: `The browser blocked the popup and the redirect fallback failed${err instanceof Error && err.message ? `: ${err.message}` : "."}`
532
+ };
533
+ }
534
+ }
535
+ const win = popup;
536
+ try {
537
+ const loc = win.location;
538
+ if (loc && typeof loc.replace === "function") loc.replace(url);
539
+ else if (loc) loc.href = url;
540
+ } catch {
541
+ }
542
+ const navigatedAt = Date.now();
543
+ try {
544
+ win.focus?.();
545
+ } catch {
546
+ }
547
+ return new Promise((resolve, reject) => {
548
+ let settled = false;
549
+ let prompt;
550
+ let wake = null;
551
+ let expiryTimer;
552
+ let closedTimer;
553
+ const cleanup = (closePopup) => {
554
+ settled = true;
555
+ window.removeEventListener("message", onMessage);
556
+ signal?.removeEventListener("abort", onAbort);
557
+ if (expiryTimer !== void 0) clearTimeout(expiryTimer);
558
+ if (closedTimer !== void 0) clearInterval(closedTimer);
559
+ prompt?.clear();
560
+ if (closePopup && !win.closed) {
561
+ try {
562
+ win.close();
563
+ } catch {
564
+ }
565
+ }
566
+ wake?.();
567
+ };
568
+ const finish = (result, closePopup) => {
569
+ if (settled) return;
570
+ cleanup(closePopup);
571
+ resolve(result);
572
+ };
573
+ const fail = (err) => {
574
+ if (settled) return;
575
+ cleanup(false);
576
+ reject(err);
577
+ };
578
+ const respond = async (decision) => {
579
+ if (settled) return;
580
+ try {
581
+ await api.confirmEnrollment(deviceCode, decision);
582
+ } catch (err) {
583
+ if (err instanceof InvoError && err.rawCode && CONFIRM_QUIET_CODES.has(err.rawCode)) {
584
+ prompt?.update(null);
585
+ return;
586
+ }
587
+ throw err;
588
+ }
589
+ wake?.();
590
+ };
591
+ const ensurePrompt = () => {
592
+ if (!prompt) {
593
+ prompt = createPrompt();
594
+ prompt.configure({
595
+ respond,
596
+ onEnrollment: opts.onEnrollment,
597
+ renderPrompt: opts.renderPrompt !== false
598
+ });
599
+ }
600
+ return prompt;
601
+ };
602
+ const showEnrollment = (input) => {
603
+ const e = input && typeof input === "object" ? input : null;
604
+ if (e) ensurePrompt().update(e);
605
+ else prompt?.update(null);
606
+ };
607
+ const onMessage = (event) => {
608
+ if (event.origin !== origin) return;
609
+ if (event.source && event.source !== win) return;
610
+ const data = event.data;
611
+ if (!data || typeof data !== "object" || data.type !== HOSTED_MESSAGE_TYPE) return;
612
+ wake?.();
613
+ };
614
+ const onAbort = () => finish({ status: "closed", popupBlocked: false }, true);
615
+ const pause = (ms) => new Promise((r) => {
616
+ const t = setTimeout(() => {
617
+ wake = null;
618
+ r();
619
+ }, ms);
620
+ wake = () => {
621
+ clearTimeout(t);
622
+ wake = null;
623
+ r();
624
+ };
625
+ });
626
+ window.addEventListener("message", onMessage);
627
+ signal?.addEventListener("abort", onAbort, { once: true });
628
+ expiryTimer = setTimeout(() => finish({ status: "expired", popupBlocked: false }, false), expiresIn * 1e3);
629
+ closedTimer = setInterval(() => {
630
+ if (!win.closed) return;
631
+ if (Date.now() - navigatedAt < coopGraceMs) {
632
+ finish({ status: "blocked", popupBlocked: true, message: COOP_HINT }, false);
633
+ } else {
634
+ finish({ status: "closed", popupBlocked: false }, false);
635
+ }
636
+ }, closedPollMs);
637
+ void (async () => {
638
+ let transientFailures = 0;
639
+ while (!settled) {
640
+ await pause(interval * 1e3);
641
+ if (settled) return;
642
+ let raw;
643
+ try {
644
+ raw = await api.poll(deviceCode);
645
+ } catch (err) {
646
+ if (settled) return;
647
+ const p = pollToken(err);
648
+ if (!p) {
649
+ if (++transientFailures >= MAX_TRANSIENT_POLL_FAILURES) return fail(err);
650
+ const ra = err instanceof InvoError && err.status === 429 ? err.retryAfter : void 0;
651
+ if (typeof ra === "number" && ra > interval) interval = Math.min(ra, MAX_EXPIRES_IN_S);
652
+ continue;
653
+ }
654
+ transientFailures = 0;
655
+ const bodyInterval = Number(p.body["interval"]);
656
+ switch (p.token) {
657
+ case "authorization_pending":
658
+ if (bodyInterval > 0) interval = bodyInterval;
659
+ showEnrollment(p.body["enrollment"]);
660
+ continue;
661
+ case "slow_down":
662
+ interval = Math.max(interval + 5, bodyInterval > 0 ? bodyInterval : 0);
663
+ continue;
664
+ case "expired_token":
665
+ return finish({ status: "expired", popupBlocked: false }, false);
666
+ case "access_denied":
667
+ return finish({ status: "denied", popupBlocked: false }, false);
668
+ default:
669
+ return fail(err);
670
+ }
671
+ }
672
+ if (settled) return;
673
+ if (raw["status"] !== "approved") continue;
674
+ try {
675
+ const approval = await api.approve(deviceCode);
676
+ if (settled) return;
677
+ finish({ status: "approved", popupBlocked: false, approval }, true);
678
+ } catch (err) {
679
+ fail(err);
680
+ }
681
+ return;
682
+ }
683
+ })();
684
+ });
685
+ }
686
+
687
+ // src/shared/purchase-status.ts
688
+ function str(v) {
689
+ return typeof v === "string" ? v : v === null || v === void 0 ? null : String(v);
690
+ }
691
+ function toPurchaseStatusResult(raw, sessionId) {
692
+ return {
693
+ status: String(raw["status"] ?? ""),
694
+ // INVO SAYS, AND ONLY AN EXPLICIT `true` SAYS IT. A missing or malformed field reads
695
+ // false, which keeps a poll running; the alternative, guessing terminality from
696
+ // `status`, is how an old SDK declares a future status finished.
697
+ terminal: raw["terminal"] === true,
698
+ orderId: str(raw["order_id"]),
699
+ sessionId: String(raw["session_id"] ?? sessionId),
700
+ coinsCredited: str(raw["coins_credited"]),
701
+ transactionId: str(raw["transaction_id"]),
702
+ newBalance: str(raw["new_balance"]),
703
+ reasonCode: str(raw["reason_code"]),
704
+ message: str(raw["message"]),
705
+ amountChargedUsd: str(raw["amount_charged_usd"]),
706
+ listedUsd: str(raw["listed_usd"]),
707
+ currencyName: str(raw["currency_name"]),
708
+ ...receiptFields(raw),
709
+ raw
710
+ };
711
+ }
712
+ function isPurchaseCredited(r) {
713
+ return r.status === "credited";
714
+ }
715
+ function isPurchaseRefused(r) {
716
+ return r.status === "refused";
717
+ }
718
+ function isPurchaseRefunded(r) {
719
+ return r.status === "refunded";
720
+ }
721
+ function isPurchaseExpired(r) {
722
+ return r.status === "expired";
723
+ }
724
+ var NOTHING_CHARGED_REASONS = /* @__PURE__ */ new Set(["PAYMENT_DECLINED", "PAYMENT_CANCELLED"]);
725
+ function nothingWasCharged(r) {
726
+ if (r.status === "expired") return true;
727
+ if (r.status !== "refused") return false;
728
+ return r.reasonCode !== null && NOTHING_CHARGED_REASONS.has(r.reasonCode);
729
+ }
730
+
731
+ // src/index.ts
732
+ function clientInvalidInput(message) {
733
+ return new InvoError({ message, code: "INVALID_INPUT", status: 0 });
734
+ }
735
+ function randomNonce() {
736
+ const c = globalThis.crypto;
737
+ if (!c || typeof c.getRandomValues !== "function") {
738
+ throw clientInvalidInput(
739
+ "No secure random source in this environment; pass a deviceSignal you built yourself."
740
+ );
741
+ }
742
+ const bytes = c.getRandomValues(new Uint8Array(16));
743
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
744
+ }
745
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
746
+ function toPendingCollectItem(row) {
747
+ return {
748
+ transferId: String(row["transfer_id"] ?? ""),
749
+ kind: String(row["kind"] ?? ""),
750
+ flow: String(row["flow"] ?? ""),
751
+ amount: row["amount"] ?? null,
752
+ currency: String(row["currency"] ?? ""),
753
+ counterpartyGame: String(row["counterparty_game"] ?? ""),
754
+ expiresAt: row["expires_at"] ?? null,
755
+ stepUpRequired: row["step_up_required"] === true,
756
+ held: row["held"] === true,
757
+ holdReason: row["hold_reason"] ?? null,
758
+ raw: row
759
+ };
760
+ }
761
+ function toBalanceRow(row) {
762
+ return {
763
+ currencyId: row["currency_id"] ?? "",
764
+ currencyName: String(row["currency_name"] ?? ""),
765
+ currencySymbol: row["currency_symbol"] ?? null,
766
+ currencySymbolUrl: row["currency_symbol_url"] ?? null,
767
+ availableBalance: String(row["available_balance"] ?? ""),
768
+ reservedBalance: String(row["reserved_balance"] ?? ""),
769
+ totalBalance: String(row["total_balance"] ?? ""),
770
+ raw: row
771
+ };
772
+ }
773
+ function toApproveResult(raw, transactionId) {
774
+ const holdReason = raw["error_code"] ?? raw["code"];
775
+ return {
776
+ status: String(raw["status"] ?? ""),
777
+ next: String(raw["next"] ?? ""),
778
+ transactionId: String(raw["transaction_id"] ?? transactionId),
779
+ claimCode: raw["claim_code"],
780
+ claimCodeExpiresAt: raw["claim_code_expires_at"],
781
+ holdReason: typeof holdReason === "string" ? holdReason : void 0,
782
+ risk: raw["risk"],
783
+ guardianApproval: raw["guardian_approval"] ?? void 0,
784
+ pollEndpoint: raw["poll_endpoint"],
785
+ ...typeof raw["claim_delivery"] === "string" && raw["claim_delivery"] ? { claimDelivery: raw["claim_delivery"] } : {},
786
+ raw
787
+ };
788
+ }
789
+ function toConfirmReceiptResult(raw) {
790
+ const holdReason = raw["error_code"] ?? raw["code"];
791
+ return {
792
+ status: String(raw["status"] ?? ""),
793
+ holdReason: typeof holdReason === "string" ? holdReason : void 0,
794
+ raw
795
+ };
796
+ }
797
+ var PlatformCommerceClient = class {
798
+ /**
799
+ * Embed INVO's hosted checkout in an iframe and listen for completion.
800
+ *
801
+ * ```ts
802
+ * const handle = invo.platformCommerce.mountCheckout("#checkout", checkoutUrl, {
803
+ * onComplete: () => showProcessing(), // then reconcile server-side
804
+ * });
805
+ * // later: handle.destroy();
806
+ * ```
807
+ *
808
+ * Or skip the helper and redirect: `location.href = checkoutUrl` (the buyer returns to
809
+ * the `successUrl`/`cancelUrl` you passed to the server `purchase()`).
810
+ *
811
+ * `onComplete` fires on the page's `INVO_CHECKOUT_COMPLETE` postMessage -- accepted ONLY
812
+ * from the checkout URL's own origin (any other window could forge the event). It is a
813
+ * UX signal: the sale is REAL only on the `platform_commerce.purchased` webhook, never
814
+ * on this client event.
815
+ */
816
+ mountCheckout(el, checkoutUrl, opts) {
817
+ if (typeof document === "undefined" || typeof window === "undefined") {
818
+ throw new InvoError({
819
+ message: "mountCheckout requires a browser DOM (window/document).",
820
+ code: "DOM_UNAVAILABLE",
821
+ status: 0
822
+ });
823
+ }
824
+ if (!checkoutUrl || !checkoutUrl.trim()) {
825
+ throw new Error("mountCheckout requires the server-returned `checkoutUrl`.");
826
+ }
827
+ let checkoutOrigin;
828
+ try {
829
+ const u = new URL(checkoutUrl);
830
+ const isLocal = u.hostname === "localhost" || u.hostname === "127.0.0.1";
831
+ if (u.protocol !== "https:" && !(u.protocol === "http:" && isLocal)) {
832
+ throw new Error("not https");
833
+ }
834
+ checkoutOrigin = u.origin;
835
+ } catch {
836
+ throw new InvoError({
837
+ message: "mountCheckout requires an absolute https checkoutUrl.",
838
+ code: "INVALID_INPUT",
839
+ status: 0
840
+ });
841
+ }
842
+ const container = typeof el === "string" ? document.querySelector(el) : el;
843
+ if (!container) {
844
+ throw new InvoError({
845
+ message: `mountCheckout could not find the container "${String(el)}".`,
846
+ code: "MOUNT_NOT_FOUND",
847
+ status: 0
848
+ });
849
+ }
850
+ const iframe = document.createElement("iframe");
851
+ iframe.src = checkoutUrl;
852
+ iframe.title = opts?.title ?? "INVO checkout";
853
+ if (opts?.className) iframe.className = opts.className;
854
+ iframe.style.width = "100%";
855
+ iframe.style.border = "0";
856
+ iframe.allow = "payment";
857
+ const onMessage = (event) => {
858
+ if (event.origin !== checkoutOrigin) return;
859
+ if (iframe.contentWindow && event.source !== iframe.contentWindow) return;
860
+ const msg = event.data;
861
+ if (!msg || msg.type !== "INVO_CHECKOUT_COMPLETE") return;
862
+ opts?.onComplete?.(
863
+ msg.data && typeof msg.data === "object" ? msg.data : {}
864
+ );
865
+ };
866
+ window.addEventListener("message", onMessage);
867
+ container.appendChild(iframe);
868
+ return {
869
+ iframe,
870
+ destroy() {
871
+ window.removeEventListener("message", onMessage);
872
+ iframe.remove();
873
+ }
874
+ };
875
+ }
876
+ };
877
+ var DEFAULT_PURCHASE_POLL_INTERVAL_MS = 1500;
878
+ var DEFAULT_PURCHASE_POLL_TIMEOUT_MS = 18e4;
879
+ function pollSleep(ms, signal) {
880
+ return new Promise((resolve) => {
881
+ if (signal?.aborted) return resolve();
882
+ const timer = setTimeout(done, ms);
883
+ const onAbort = () => done();
884
+ function done() {
885
+ clearTimeout(timer);
886
+ signal?.removeEventListener("abort", onAbort);
887
+ resolve();
888
+ }
889
+ signal?.addEventListener("abort", onAbort, { once: true });
890
+ });
891
+ }
892
+ function isTransientPollFailure(err) {
893
+ if (!(err instanceof InvoError)) return false;
894
+ if (err.code === "ABORTED") return false;
895
+ return err.status === 0 || err.status === 429 || err.status >= 500;
896
+ }
897
+ var CheckoutClient = class _CheckoutClient {
898
+ constructor(config) {
899
+ if (!config?.baseUrl) throw new Error("CheckoutClient requires a `baseUrl`.");
900
+ assertSecureBaseUrl(config.baseUrl);
901
+ this.http = new Http({
902
+ baseUrl: config.baseUrl,
903
+ timeoutMs: config.timeoutMs,
904
+ fetchImpl: config.fetch,
905
+ maxRetries: config.maxRetries,
906
+ retryBaseDelayMs: config.retryBaseDelayMs,
907
+ hooks: config.hooks
908
+ });
909
+ }
910
+ /**
911
+ * Wrap an `Http` the owning client already built, so `invo.checkout` shares that
912
+ * client's baseUrl, timeout, retry budget and observability hooks.
913
+ *
914
+ * @internal Not part of the public API; it takes an internal type and may change.
915
+ */
916
+ static _withHttp(http) {
917
+ const client = Object.create(_CheckoutClient.prototype);
918
+ client.http = http;
919
+ return client;
920
+ }
921
+ /**
922
+ * Read a purchase's status once.
923
+ *
924
+ * Answers `200` with a {@link PurchaseStatusResult} for every state of the purchase,
925
+ * including "we have your money and your coins are not there". There is no tenant gate
926
+ * on it: a partner suspended after a buyer's card was charged is exactly the case it
927
+ * exists for.
928
+ *
929
+ * Throws an {@link InvoError} on `401` (no token, bad signature, or a card-setup token:
930
+ * `err.isWrongSessionPurpose`), `403` (a valid token for a DIFFERENT session:
931
+ * `err.isCheckoutSessionMismatch`) and `410` (the token is more than 24 hours past its
932
+ * expiry: `err.isCheckoutSessionExpired`; show the buyer the order id you already have
933
+ * and a Contact support link).
934
+ *
935
+ * Storefront (in-client) purchases are keyed on the partner's own purchase reference
936
+ * rather than on a checkout session, so a read by session id finds nothing and answers
937
+ * `pending`. Do not conclude from that that such a purchase never happened.
938
+ */
939
+ async getPurchaseStatus(input, opts) {
940
+ const sessionId = String(input?.sessionId ?? "").trim();
941
+ const sessionToken = String(input?.sessionToken ?? "").trim();
942
+ if (!sessionId) {
943
+ throw new InvoError({
944
+ message: "getPurchaseStatus requires `sessionId` (from createCheckout).",
945
+ code: "INVALID_INPUT",
946
+ status: 0
947
+ });
948
+ }
949
+ if (!sessionToken) {
950
+ throw new InvoError({
951
+ message: "getPurchaseStatus requires `sessionToken`. The session token is the credential; the id in the path is not.",
952
+ code: "INVALID_INPUT",
953
+ status: 0
954
+ });
955
+ }
956
+ const raw = await this.http.get(
957
+ `/api/checkout/sessions/${encodeURIComponent(sessionId)}`,
958
+ { kind: "bearer", token: sessionToken },
959
+ { signal: opts?.signal }
960
+ );
961
+ return toPurchaseStatusResult(raw, sessionId);
962
+ }
963
+ /**
964
+ * Poll {@link getPurchaseStatus} until INVO says the purchase is finished, and return
965
+ * that final result.
966
+ *
967
+ * ```ts
968
+ * const result = await invo.checkout.waitForPurchase({
969
+ * sessionId, sessionToken,
970
+ * intervalMs: 1500,
971
+ * timeoutMs: 300_000,
972
+ * signal: controller.signal,
973
+ * onUpdate: (r) => render(r), // keep the modal open on every non-terminal read
974
+ * });
975
+ * if (isPurchaseCredited(result)) showCoins(result.coinsCredited, result.currencyName);
976
+ * else if (result.message) showMessage(result.message, result.orderId); // verbatim
977
+ * ```
978
+ *
979
+ * IT STOPS ON `result.terminal` AND ON NOTHING ELSE. `terminal` is INVO's word, read off
980
+ * the response; this loop never recomputes it from `status`, so a status a later backend
981
+ * introduces cannot end a wait here as a success. `paid_pending_credit` is deliberately
982
+ * not terminal and is never promoted to a failure by age: INVO's reconciler recovers a
983
+ * stalled credit, and telling a buyer they lost money they are about to receive would
984
+ * be a fresh lie in place of the old silence.
985
+ *
986
+ * A transient failure (network, timeout, 429, 5xx) is polled through rather than raised;
987
+ * a `401`, `403` or `410` is raised at once. On the cap it returns the LAST result it
988
+ * read, whose `terminal` is false. Nothing is guessed and nothing is thrown, so the page
989
+ * keeps showing the buyer what INVO last said. If it never got a single answer, the last
990
+ * transport failure is thrown.
991
+ */
992
+ async waitForPurchase(input) {
993
+ const intervalMs = Math.max(0, input?.intervalMs ?? DEFAULT_PURCHASE_POLL_INTERVAL_MS);
994
+ const timeoutMs = Math.max(0, input?.timeoutMs ?? DEFAULT_PURCHASE_POLL_TIMEOUT_MS);
995
+ const maxAttempts = input?.maxAttempts === void 0 ? Number.POSITIVE_INFINITY : Math.max(1, input.maxAttempts);
996
+ const deadline = Date.now() + timeoutMs;
997
+ const signal = input?.signal;
998
+ let last;
999
+ let lastFailure;
1000
+ for (let attempts = 0; ; ) {
1001
+ if (signal?.aborted) {
1002
+ throw new InvoError({
1003
+ message: "waitForPurchase was aborted",
1004
+ code: "ABORTED",
1005
+ status: 0
1006
+ });
1007
+ }
1008
+ attempts += 1;
1009
+ try {
1010
+ const result = await this.getPurchaseStatus(input, { signal });
1011
+ last = result;
1012
+ lastFailure = void 0;
1013
+ try {
1014
+ input?.onUpdate?.(result);
1015
+ } catch {
1016
+ }
1017
+ if (result.terminal) return result;
1018
+ } catch (err) {
1019
+ if (!isTransientPollFailure(err)) throw err;
1020
+ lastFailure = err;
1021
+ }
1022
+ if (attempts >= maxAttempts) break;
1023
+ if (Date.now() + intervalMs >= deadline) break;
1024
+ await pollSleep(intervalMs, signal);
1025
+ }
1026
+ if (last) return last;
1027
+ throw lastFailure instanceof Error ? lastFailure : new InvoError({
1028
+ message: "waitForPurchase could not read the purchase status before the cap.",
1029
+ code: "PURCHASE_STATUS_UNAVAILABLE",
1030
+ status: 0
1031
+ });
1032
+ }
1033
+ };
1034
+ var InvoClient = class {
1035
+ constructor(config) {
1036
+ /**
1037
+ * Platform Commerce (ecommerce) hosted-checkout embed. Use after
1038
+ * `InvoServer.platformCommerce.purchase({ fundingSource: "card" })` returns a
1039
+ * `checkoutUrl` — either redirect the buyer there, or embed it with
1040
+ * `mountCheckout`. No card element, no processor dependency. See
1041
+ * {@link PlatformCommerceClient}.
1042
+ */
1043
+ this.platformCommerce = new PlatformCommerceClient();
1044
+ if (!config.token) throw new Error("InvoClient requires a player `token`.");
1045
+ if (!config.baseUrl) throw new Error("InvoClient requires a `baseUrl`.");
1046
+ assertSecureBaseUrl(config.baseUrl);
1047
+ this.http = new Http({
1048
+ baseUrl: config.baseUrl,
1049
+ timeoutMs: config.timeoutMs,
1050
+ fetchImpl: config.fetch,
1051
+ maxRetries: config.maxRetries,
1052
+ retryBaseDelayMs: config.retryBaseDelayMs,
1053
+ hooks: config.hooks
1054
+ // Browser: do NOT set User-Agent (forbidden header); the browser's own UA is fine.
1055
+ });
1056
+ this.auth = { kind: "bearer", token: config.token };
1057
+ this.refreshToken = config.refreshToken;
1058
+ this.checkout = CheckoutClient._withHttp(this.http);
1059
+ }
1060
+ assertWebAuthn() {
1061
+ if (typeof navigator === "undefined" || !navigator.credentials) {
1062
+ throw new Error("WebAuthn is not available in this environment (browser required).");
1063
+ }
1064
+ }
1065
+ /**
1066
+ * Enroll a passkey for the token's identity (register/begin -> create() -> register/complete).
1067
+ * Gates: `ENROLLMENT_REQUIRES_AUTHORIZATION` → {@link enrollmentBegin} OTP grant;
1068
+ * `ENROLLMENT_REQUIRES_PROOF` → {@link linkDevice}, or {@link recoveryBegin} when the
1069
+ * player lost/deleted the old passkey ("Lost or replaced your passkey?").
1070
+ */
1071
+ async enrollPasskey(opts) {
1072
+ this.assertWebAuthn();
1073
+ const signal = opts?.signal;
1074
+ return this.withTokenRetry(async () => {
1075
+ const options = await this.post(
1076
+ "/api/sdk/webauthn/register/begin",
1077
+ void 0,
1078
+ signal
1079
+ );
1080
+ const cred = await navigator.credentials.create({
1081
+ publicKey: toCreationOptions(options),
1082
+ signal
1083
+ });
1084
+ if (!cred) throw new Error("Passkey creation was cancelled or returned no credential.");
1085
+ const raw = await this.post(
1086
+ "/api/sdk/webauthn/register/complete",
1087
+ { credential: registrationToJSON(cred) },
1088
+ signal
1089
+ );
1090
+ return { status: String(raw["status"] ?? ""), device: raw["device"] ?? null, raw };
1091
+ });
1092
+ }
1093
+ async approveHosted(opts) {
1094
+ const txn = String(opts.transactionId ?? "");
1095
+ const id = encodeURIComponent(txn);
1096
+ const signal = opts.signal;
1097
+ const api = {
1098
+ begin: () => this.withTokenRetry(
1099
+ () => this.post(
1100
+ "/api/sdk/approvals/device/begin",
1101
+ { transaction_id: txn, flow: opts.flow, channel: "popup" },
1102
+ signal
1103
+ )
1104
+ ),
1105
+ poll: (deviceCode) => this.withTokenRetry(
1106
+ () => this.post(
1107
+ "/api/sdk/approvals/device/poll",
1108
+ { device_code: deviceCode },
1109
+ signal
1110
+ )
1111
+ ),
1112
+ confirmEnrollment: (deviceCode, decision) => this.withTokenRetry(
1113
+ () => this.post(
1114
+ "/api/sdk/approvals/device/confirm-enrollment",
1115
+ { device_code: deviceCode, decision },
1116
+ signal
1117
+ )
1118
+ ),
1119
+ approve: (deviceCode) => this.withTokenRetry(async () => {
1120
+ const body = { device_code: deviceCode };
1121
+ switch (opts.flow) {
1122
+ case "transfer":
1123
+ return toApproveResult(
1124
+ await this.post(`/api/sdk/transfers/${id}/approve`, body, signal),
1125
+ txn
1126
+ );
1127
+ case "send":
1128
+ return toApproveResult(
1129
+ await this.post(`/api/sdk/send/${id}/approve`, body, signal),
1130
+ txn
1131
+ );
1132
+ case "send_receipt":
1133
+ return toConfirmReceiptResult(
1134
+ await this.post(`/api/sdk/send/${id}/confirm-receipt`, body, signal)
1135
+ );
1136
+ case "transfer_receipt":
1137
+ return toConfirmReceiptResult(
1138
+ await this.post(`/api/sdk/transfers/${id}/confirm-receipt`, body, signal)
1139
+ );
1140
+ default:
1141
+ throw new Error(`approveHosted: unknown flow "${String(opts.flow)}".`);
1142
+ }
1143
+ })
1144
+ };
1145
+ return runHostedApproval(opts, api);
1146
+ }
1147
+ /**
1148
+ * Approve a SEND with the player's passkey.
1149
+ *
1150
+ * Throws 403 `err.isPlayerTokenStale` when the player token predates a change to the
1151
+ * sender's identity (their phone was added on the initiate). Not retried automatically,
1152
+ * because this call moves money: re-mint the player token (or use the `playerToken`
1153
+ * your server got back from `initiateSend`) and retry once.
1154
+ */
1155
+ async approveSend(transactionId, opts) {
1156
+ return this.approve("send", transactionId, opts);
1157
+ }
1158
+ /** Approve a TRANSFER with the player's passkey (returns the sender's claim code). Same
1159
+ * `err.isPlayerTokenStale` handling as {@link approveSend}: re-mint and retry once. */
1160
+ async approveTransfer(transactionId, opts) {
1161
+ return this.approve("transfers", transactionId, opts);
1162
+ }
1163
+ /**
1164
+ * Recipient self-claims a SEND with their passkey.
1165
+ *
1166
+ * May throw a 409 with `err.isPhoneShareApprovalRequired` when the receiver phone is
1167
+ * contested (the collecting identity isn't yet authorized for it). NOT a failure — the
1168
+ * money is held and the phone owner is texted to approve. Show `err.message`
1169
+ * (`err.phoneShareLast4` names the phone), then **retry this same call** once approved
1170
+ * (it then succeeds idempotently); on denial/expiry the backend refunds the sender.
1171
+ */
1172
+ async confirmReceiptSend(transactionId, opts) {
1173
+ return this.confirmReceipt("send", transactionId, opts);
1174
+ }
1175
+ /** Recipient self-claims a TRANSFER with their passkey. Can throw the same phone-share
1176
+ * 409 as {@link confirmReceiptSend} (`err.isPhoneShareApprovalRequired`) — handle it the
1177
+ * same way: show `err.message`, retry after the phone owner approves. */
1178
+ async confirmReceiptTransfer(transactionId, opts) {
1179
+ return this.confirmReceipt("transfers", transactionId, opts);
1180
+ }
1181
+ /**
1182
+ * Phone changes waiting for THIS player's enrolled device to approve
1183
+ * (`GET /api/sdk/players/phone/change-approvals`, player token). A row appears after the
1184
+ * player entered the emailed code on INVO's page for a change whose `confirmation` is
1185
+ * `"email_code_and_device"`. Show each one ("Approve changing your number to
1186
+ * ***-***-0123?") and answer it with {@link approvePhoneChange}. Read-only.
1187
+ */
1188
+ async listPhoneChangeApprovals(opts) {
1189
+ return this.withTokenRetry(async () => {
1190
+ const raw = await this.get(
1191
+ "/api/sdk/players/phone/change-approvals",
1192
+ opts?.signal
1193
+ );
1194
+ return toPhoneChangeApprovalsResult(raw);
1195
+ });
1196
+ }
1197
+ /**
1198
+ * Approve (or, with `decision: "deny"`, decline) a phone change from the player's enrolled
1199
+ * device (`POST /api/sdk/players/phone/change-requests/{id}/approve`, player token).
1200
+ *
1201
+ * The device key signs `phone-change|<changeRequestId>|<nonce>|<timestamp>` to approve or
1202
+ * `phone-change-deny|<changeRequestId>|<nonce>|<timestamp>` to decline (`timestamp` in
1203
+ * epoch seconds). Either pass `sign`, and the SDK makes a fresh nonce and timestamp, builds
1204
+ * that message and asks you for the base64 signature; or pass a `deviceSignal` you signed
1205
+ * yourself (build the message with {@link phoneChangeSignalMessage}). This is a device key
1206
+ * registered with INVO, not a passkey.
1207
+ *
1208
+ * `status: "confirmed"` means the change is applied: store `identityId` and use
1209
+ * `playerToken` (tokens minted before the change are stale). `status: "denied"` means
1210
+ * nothing changed. Refusals: 409 `err.isChangeRequestNotReady` (the player has not entered
1211
+ * the code on INVO's page yet), 409 `err.isChangeRequestNotPending` (`err.changeRequestStatus`),
1212
+ * 409 `err.isDeviceEnrolledAfterRequest` (this device was set up after the change was
1213
+ * requested; approve on the earlier device, or the game creates a new request), 409
1214
+ * `err.isPhoneChangeRecoveryCooldown` (a recent sign-in recovery; retry later, declining
1215
+ * still works), 404 `err.isChangeRequestNotFound`, 401 `err.isDeviceSignalRejected`, 403
1216
+ * `DEVICE_REQUIRES_ELEVATION`, or any refusal of the change itself (for example
1217
+ * `err.isPendingTransfersToOldPhone`).
1218
+ */
1219
+ async approvePhoneChange(changeRequestId, input, opts) {
1220
+ if (typeof changeRequestId !== "string" || !changeRequestId.trim()) {
1221
+ throw clientInvalidInput("changeRequestId is required.");
1222
+ }
1223
+ if (!input || typeof input.deviceFingerprint !== "string" || !input.deviceFingerprint.trim()) {
1224
+ throw clientInvalidInput("deviceFingerprint is required.");
1225
+ }
1226
+ const decision = input.decision ?? "approve";
1227
+ if (decision !== "approve" && decision !== "deny") {
1228
+ throw clientInvalidInput('decision must be "approve" or "deny".');
1229
+ }
1230
+ const hasSignal = input.deviceSignal !== void 0;
1231
+ const hasSigner = typeof input.sign === "function";
1232
+ if (hasSignal === hasSigner) {
1233
+ throw clientInvalidInput("Pass exactly one of deviceSignal or sign.");
1234
+ }
1235
+ if (hasSignal) {
1236
+ const sig = input.deviceSignal;
1237
+ if (!sig || typeof sig.nonce !== "string" || !sig.nonce || typeof sig.timestamp !== "number" || !Number.isInteger(sig.timestamp) || typeof sig.signature !== "string" || !sig.signature) {
1238
+ throw clientInvalidInput(
1239
+ "deviceSignal needs a nonce (string), an integer epoch-seconds timestamp and a base64 signature."
1240
+ );
1241
+ }
1242
+ }
1243
+ const id = encodeURIComponent(changeRequestId);
1244
+ const signal = opts?.signal;
1245
+ return this.withTokenRetry(async () => {
1246
+ let deviceSignal;
1247
+ if (hasSignal) {
1248
+ const sig = input.deviceSignal;
1249
+ deviceSignal = {
1250
+ transfer_id: changeRequestId,
1251
+ nonce: sig.nonce,
1252
+ timestamp: sig.timestamp,
1253
+ signature: sig.signature
1254
+ };
1255
+ } else {
1256
+ const nonce = randomNonce();
1257
+ const timestamp = Math.floor(Date.now() / 1e3);
1258
+ const signature = await input.sign(
1259
+ phoneChangeSignalMessage(changeRequestId, nonce, timestamp, decision)
1260
+ );
1261
+ if (typeof signature !== "string" || !signature) {
1262
+ throw clientInvalidInput("sign must return the base64 signature as a non-empty string.");
1263
+ }
1264
+ deviceSignal = { transfer_id: changeRequestId, nonce, timestamp, signature };
1265
+ }
1266
+ const raw = await this.post(
1267
+ `/api/sdk/players/phone/change-requests/${id}/approve`,
1268
+ { device_fingerprint: input.deviceFingerprint, device_signal: deviceSignal, decision },
1269
+ signal
1270
+ );
1271
+ return toApprovePhoneChangeResult(raw, changeRequestId);
1272
+ });
1273
+ }
1274
+ /**
1275
+ * Interchangeable methods (§4.6): prove an *already-enrolled* method (e.g. the
1276
+ * INVO app device key) to authorize adding a new partner passkey. The returned
1277
+ * single-use grant lets a subsequent enrollPasskey() succeed instead of being
1278
+ * blocked with ENROLLMENT_REQUIRES_PROOF.
1279
+ *
1280
+ * begin -> navigator.credentials.get() -> complete with { link_id, webauthn_assertion }.
1281
+ *
1282
+ * Call it with no arguments: `await invo.linkDevice()`. THE SERVER MINTS THE
1283
+ * LINK ID, so there is nothing for the caller to supply. The parameter is kept
1284
+ * (optional, and sent but ignored by the server) so that code written against
1285
+ * 3.10 and earlier, which had to pass a placeholder, keeps compiling and
1286
+ * working unchanged.
1287
+ */
1288
+ async linkDevice(linkId, opts) {
1289
+ this.assertWebAuthn();
1290
+ const signal = opts?.signal;
1291
+ return this.withTokenRetry(async () => {
1292
+ const begin = await this.post(
1293
+ "/api/sdk/device/link/webauthn/begin",
1294
+ // The server ignores the body and mints its own id; `linkId` travels only
1295
+ // for callers who still pass one.
1296
+ linkId ? { link_id: linkId } : {},
1297
+ signal
1298
+ );
1299
+ const cred = await navigator.credentials.get({
1300
+ publicKey: toRequestOptions(begin.options),
1301
+ signal
1302
+ });
1303
+ if (!cred) throw new Error("Passkey assertion was cancelled or returned no credential.");
1304
+ const raw = await this.post(
1305
+ "/api/sdk/device/link/webauthn/complete",
1306
+ { link_id: begin.link_id, webauthn_assertion: assertionToJSON(cred) },
1307
+ signal
1308
+ );
1309
+ return { status: String(raw["status"] ?? ""), raw };
1310
+ });
1311
+ }
1312
+ /**
1313
+ * List the player's own pending items to collect (browser, player-token). Each row's
1314
+ * `kind` tells you which action to call: `"identity_gate"` → `approve*` (you initiated);
1315
+ * `"receiving_confirm"` → `confirmReceipt*` (a peer sent to you). PII-free — no claim
1316
+ * code or phone (those are only on the server-side `getInboundPending`).
1317
+ */
1318
+ async getPendingCollect(opts) {
1319
+ return this.withTokenRetry(async () => {
1320
+ const raw = await this.get(
1321
+ "/api/sdk/transfers/pending",
1322
+ opts?.signal
1323
+ );
1324
+ const rows = Array.isArray(raw["pending"]) ? raw["pending"] : [];
1325
+ return { pending: rows.map(toPendingCollectItem), raw };
1326
+ });
1327
+ }
1328
+ /**
1329
+ * List the games/tenants this player can send/transfer to, with display metadata
1330
+ * inline (name, icon, currency, min/max limits) — one call, no per-game lookup.
1331
+ * Source game is the token's own game. Player-token (browser).
1332
+ */
1333
+ async getDestinations(query, opts) {
1334
+ const direction = query?.direction ?? "transfer";
1335
+ return this.withTokenRetry(async () => {
1336
+ const raw = await this.get(
1337
+ `/api/sdk/destinations?direction=${encodeURIComponent(direction)}`,
1338
+ opts?.signal
1339
+ );
1340
+ return toDestinationsResult(raw, direction);
1341
+ });
1342
+ }
1343
+ /**
1344
+ * The player's balances for the token's game (browser, player-token). Amounts are
1345
+ * decimal strings. A player who hasn't transacted here yet returns `200` with an empty
1346
+ * `balances` array (show 0.00) — not an error; a `404 GAME_NOT_FOUND` (bad game/token)
1347
+ * throws. Rows include the currency symbol + icon URL (each may be null).
1348
+ */
1349
+ async getBalance(opts) {
1350
+ return this.withTokenRetry(async () => {
1351
+ const raw = await this.get("/api/sdk/balance", opts?.signal);
1352
+ const rows = Array.isArray(raw["balances"]) ? raw["balances"] : [];
1353
+ const summary = raw["summary"] ?? {};
1354
+ return {
1355
+ gameId: raw["game_id"] ?? "",
1356
+ gameName: String(raw["game_name"] ?? ""),
1357
+ balances: rows.map(toBalanceRow),
1358
+ totalValue: String(summary["total_value"] ?? "0"),
1359
+ currencyCount: Number(summary["currency_count"] ?? rows.length),
1360
+ hasFunds: summary["has_funds"] === true,
1361
+ raw
1362
+ };
1363
+ });
1364
+ }
1365
+ // ---- Loyalty and rewards (player token) ----
1366
+ /**
1367
+ * The signed-in player's loyalty cards in this game: one card per program, each step with
1368
+ * its `state` and `progress` (`{ current, target }`, or `null` when the number could not
1369
+ * be read this time: render `state` alone then), and the rewards the player unlocked.
1370
+ * A card never carries a code; a redeemed reward shows its mask. Your server reads the
1371
+ * same cards for any of your players with `InvoServer.getPlayerRewards(playerEmail)`.
1372
+ */
1373
+ async getMyRewards(opts) {
1374
+ return this.withTokenRetry(async () => {
1375
+ const raw = await this.get("/api/sdk/loyalty/me/card", opts?.signal);
1376
+ return toLoyaltyCardsResult(raw);
1377
+ });
1378
+ }
1379
+ /** Every reward the signed-in player holds or held, newest first. Codes are masked. */
1380
+ async getMyVault(opts) {
1381
+ return this.withTokenRetry(async () => {
1382
+ const raw = await this.get("/api/sdk/loyalty/me/vault", opts?.signal);
1383
+ return toLoyaltyVaultResult(raw);
1384
+ });
1385
+ }
1386
+ /**
1387
+ * Redeem one unlocked reward and return its code. This is the only response that
1388
+ * carries a code: show it straight away and never log, cache or store it. Calling again
1389
+ * for a reward this player already redeemed shows the code once more while the card's
1390
+ * `canRevealAgain` is true (`revealedAgain: true`). Never auto-retried.
1391
+ *
1392
+ * Refusals: `409 already_redeemed` (`err.isRewardAlreadyRedeemed`), `404
1393
+ * vault_entry_not_found` (`err.isRewardNotFound`), `410 vault_entry_expired`
1394
+ * (`err.isRewardExpired`), `409 inventory_exhausted` / `409 conflict`
1395
+ * (`err.isRewardUnavailable`: no units or codes left, or the reward is reserved or revoked).
1396
+ */
1397
+ async redeemReward(vaultEntryId, opts) {
1398
+ if (typeof vaultEntryId !== "string" || !UUID_RE.test(vaultEntryId.trim())) {
1399
+ throw new InvoError({
1400
+ message: `vaultEntryId must be a reward's vaultEntryId (got ${JSON.stringify(vaultEntryId)}).`,
1401
+ code: "INVALID_INPUT",
1402
+ status: 0
1403
+ });
1404
+ }
1405
+ const id = vaultEntryId.trim();
1406
+ return this.withTokenRetry(async () => {
1407
+ const raw = await this.post(
1408
+ `/api/sdk/loyalty/me/vault/${encodeURIComponent(id)}/redeem`,
1409
+ void 0,
1410
+ opts?.signal
1411
+ );
1412
+ return toRedeemRewardResult(raw, id);
1413
+ });
1414
+ }
1415
+ /**
1416
+ * A short-lived link to INVO's hosted "My rewards" page for the signed-in player: their
1417
+ * cards, progress and rewards, with a Redeem button. Open `url` in a browser or web view
1418
+ * (it cannot be embedded in an iframe). Ask for a fresh link each time the player opens
1419
+ * the page; never share or store it.
1420
+ */
1421
+ async getRewardsPageLink(opts) {
1422
+ return this.withTokenRetry(async () => {
1423
+ const raw = await this.post(
1424
+ "/api/sdk/loyalty/me/rewards-page",
1425
+ void 0,
1426
+ opts?.signal
1427
+ );
1428
+ return toRewardsPageLink(raw);
1429
+ });
1430
+ }
1431
+ /**
1432
+ * Report a gameplay event for the signed-in player to INVO's loyalty engine
1433
+ * (`POST /api/sdk/loyalty/events`, player token). Use it for sessions, milestones and
1434
+ * registered custom events (see {@link GameEventType}). Events your SERVER reports with
1435
+ * `InvoServer.reportGameEvent` are the ones trusted for rewards; prefer those when a
1436
+ * reward depends on the event.
1437
+ *
1438
+ * Pass your own `eventId` (a UUID) or reuse the returned one if you retry, so INVO counts
1439
+ * the event once. Not auto-retried from the browser.
1440
+ *
1441
+ * Refusals: `INVALID_INPUT` before the network (non-`game.*` type, malformed `eventId`,
1442
+ * `occurredAt` without a timezone, non-object payload); `400 RESERVED_EVENT_TYPE` /
1443
+ * `EVENT_TYPE_NOT_ALLOWED`; `401 SDK_TOKEN_MISSING` / `SDK_TOKEN_WRONG_SCOPE`;
1444
+ * `422 validation_failed`.
1445
+ */
1446
+ async reportGameEvent(input, opts) {
1447
+ const { body, eventId } = buildGameEventBody(input);
1448
+ return this.withTokenRetry(async () => {
1449
+ const raw = await this.post("/api/sdk/loyalty/events", body, opts?.signal);
1450
+ return toReportGameEventResult(raw ?? {}, eventId);
1451
+ });
1452
+ }
1453
+ /**
1454
+ * First-enrollment OTP grant (§4.2). When `enrollPasskey()` throws
1455
+ * `ENROLLMENT_REQUIRES_AUTHORIZATION` (`err.isEnrollmentAuthorizationRequired`), call
1456
+ * this to send a 6-digit code to the player's phone + email on file, collect the code,
1457
+ * call `enrollmentVerify(code)`, then RETRY the SAME `enrollPasskey()` —
1458
+ * `register/complete` auto-consumes the server-side grant (30-min TTL). For
1459
+ * `ENROLLMENT_REQUIRES_PROOF` (`err.isEnrollmentProofRequired`) use `linkDevice`
1460
+ * (player still has the other method) or `recoveryBegin`/`recoveryComplete`
1461
+ * (player lost/deleted their passkey).
1462
+ */
1463
+ async enrollmentBegin(opts) {
1464
+ return this.withTokenRetry(async () => {
1465
+ const raw = await this.post(
1466
+ "/api/sdk/device/enrollment/begin",
1467
+ void 0,
1468
+ opts?.signal
1469
+ );
1470
+ return {
1471
+ status: String(raw["status"] ?? ""),
1472
+ channels: Array.isArray(raw["channels"]) ? raw["channels"] : [],
1473
+ raw
1474
+ };
1475
+ });
1476
+ }
1477
+ /** Verify the enrollment OTP (see {@link enrollmentBegin}); on success, retry `enrollPasskey()`. */
1478
+ async enrollmentVerify(code, opts) {
1479
+ if (!code || !code.trim()) throw new Error("enrollmentVerify requires the OTP `code`.");
1480
+ return this.withTokenRetry(async () => {
1481
+ const raw = await this.post(
1482
+ "/api/sdk/device/enrollment/verify",
1483
+ { code },
1484
+ opts?.signal
1485
+ );
1486
+ return { status: String(raw["status"] ?? ""), raw };
1487
+ });
1488
+ }
1489
+ /**
1490
+ * Passkey recovery — "Lost or replaced your passkey?". Deleting a passkey on the
1491
+ * device never tells the server the key is gone, so the next `enrollPasskey()` is
1492
+ * blocked by the anti-takeover gate with `ENROLLMENT_REQUIRES_PROOF`
1493
+ * (`err.isEnrollmentProofRequired`). When the player can't prove the old method
1494
+ * (they deleted/lost it — otherwise prefer `linkDevice`), run:
1495
+ *
1496
+ * 1. `recoveryBegin()` — sends a one-time code to the phone/email on file
1497
+ * (422 `no_channel_on_file`, 429 `rate_limited` at 5/10min).
1498
+ * 2. `recoveryComplete(code)` — deactivates the stale server-side passkey and
1499
+ * authorizes a fresh enrollment (400 `ENROLLMENT_CODE_INVALID` on a wrong/
1500
+ * expired code — attempt-capped; let the user retry or resend).
1501
+ * 3. Immediately retry the SAME `enrollPasskey()` — it now succeeds.
1502
+ *
1503
+ * The owner also gets an out-of-band "your passkey was reset" SMS/email — that's
1504
+ * the intended tamper alert; surface nothing special for it.
1505
+ *
1506
+ * ⚠ 24-HOUR MONEY COOLDOWN: a recovery-enrolled passkey logs in and COLLECTS
1507
+ * funds immediately, but `approveSend`/`approveTransfer` throw
1508
+ * `PASSKEY_RECOVERY_COOLDOWN` (403; `err.isPasskeyRecoveryCooldown`,
1509
+ * `err.retryAfterAt`) for 24h — SIM-swap protection. Show the pause message with
1510
+ * the timestamp; do not retry-loop it.
1511
+ *
1512
+ * If the OS itself fails to SAVE a new passkey ("there is a problem saving your
1513
+ * passkey"), have the user delete the stale entry in their password manager first
1514
+ * (iPhone: Settings → Passwords; Android: Google Password Manager; Windows:
1515
+ * Settings → Accounts → Passkeys).
1516
+ */
1517
+ async recoveryBegin(opts) {
1518
+ return this.withTokenRetry(async () => {
1519
+ const raw = await this.post(
1520
+ "/api/sdk/device/recover/begin",
1521
+ void 0,
1522
+ opts?.signal
1523
+ );
1524
+ return {
1525
+ status: String(raw["status"] ?? ""),
1526
+ channels: Array.isArray(raw["channels"]) ? raw["channels"] : [],
1527
+ raw
1528
+ };
1529
+ });
1530
+ }
1531
+ /** Verify the recovery code (see {@link recoveryBegin}); on success, call `enrollPasskey()`. */
1532
+ async recoveryComplete(code, opts) {
1533
+ if (!code || !code.trim()) throw new Error("recoveryComplete requires the one-time `code`.");
1534
+ return this.withTokenRetry(async () => {
1535
+ const raw = await this.post(
1536
+ "/api/sdk/device/recover/complete",
1537
+ { code },
1538
+ opts?.signal
1539
+ );
1540
+ return {
1541
+ status: String(raw["status"] ?? ""),
1542
+ deactivatedCount: Number(raw["deactivated_count"] ?? 0),
1543
+ next: typeof raw["next"] === "string" ? raw["next"] : void 0,
1544
+ raw
1545
+ };
1546
+ });
1547
+ }
1548
+ // --- internals ---
1549
+ /** POST with the current player token. Token-expiry retry is handled one level
1550
+ * up by withTokenRetry (which re-runs the whole ceremony, not a single call). */
1551
+ async post(path, body, signal) {
1552
+ return this.http.post(path, body, this.auth, { signal });
1553
+ }
1554
+ async get(path, signal) {
1555
+ return this.http.get(path, this.auth, { signal });
1556
+ }
1557
+ /**
1558
+ * Run a whole flow, retrying it ONCE if any call fails with SDK_TOKEN_EXPIRED
1559
+ * and a `refreshToken` hook is configured. We re-run the entire begin→get→
1560
+ * complete ceremony (not just the failed call) so the retry always uses a fresh,
1561
+ * unconsumed challenge — never replaying a single-use WebAuthn assertion (§4.4).
1562
+ * The refresh is single-flighted so concurrent expiries trigger one re-mint.
1563
+ */
1564
+ async withTokenRetry(run) {
1565
+ try {
1566
+ return await run();
1567
+ } catch (err) {
1568
+ if (err instanceof InvoError && err.isTokenExpired && await this.tryRefresh()) {
1569
+ return await run();
1570
+ }
1571
+ throw err;
1572
+ }
1573
+ }
1574
+ async tryRefresh() {
1575
+ if (!this.refreshToken) return false;
1576
+ if (!this.refreshInFlight) {
1577
+ this.refreshInFlight = Promise.resolve(this.refreshToken()).finally(() => {
1578
+ this.refreshInFlight = void 0;
1579
+ });
1580
+ }
1581
+ const fresh = await this.refreshInFlight;
1582
+ if (!fresh) return false;
1583
+ this.auth = { kind: "bearer", token: fresh };
1584
+ return true;
1585
+ }
1586
+ async runAssertion(beginPath, beginBody, signal) {
1587
+ this.assertWebAuthn();
1588
+ const options = await this.post(beginPath, beginBody, signal);
1589
+ const cred = await navigator.credentials.get({
1590
+ publicKey: toRequestOptions(options),
1591
+ signal
1592
+ });
1593
+ if (!cred) throw new Error("Passkey assertion was cancelled or returned no credential.");
1594
+ return assertionToJSON(cred);
1595
+ }
1596
+ async approve(flow, transactionId, opts) {
1597
+ const id = encodeURIComponent(transactionId);
1598
+ const signal = opts?.signal;
1599
+ return this.withTokenRetry(async () => {
1600
+ const assertion = await this.runAssertion(
1601
+ `/api/sdk/${flow}/${id}/approve/webauthn/begin`,
1602
+ void 0,
1603
+ signal
1604
+ );
1605
+ const raw = await this.post(
1606
+ `/api/sdk/${flow}/${id}/approve`,
1607
+ { webauthn_assertion: assertion },
1608
+ signal
1609
+ );
1610
+ return toApproveResult(raw, transactionId);
1611
+ });
1612
+ }
1613
+ async confirmReceipt(flow, transactionId, opts) {
1614
+ const id = encodeURIComponent(transactionId);
1615
+ const signal = opts?.signal;
1616
+ return this.withTokenRetry(async () => {
1617
+ const assertion = await this.runAssertion(
1618
+ `/api/sdk/${flow}/${id}/confirm-receipt/webauthn/begin`,
1619
+ void 0,
1620
+ signal
1621
+ );
1622
+ const raw = await this.post(
1623
+ `/api/sdk/${flow}/${id}/confirm-receipt`,
1624
+ { webauthn_assertion: assertion },
1625
+ signal
1626
+ );
1627
+ return toConfirmReceiptResult(raw);
1628
+ });
1629
+ }
1630
+ };
1631
+
1632
+ export { CheckoutClient, InvoClient, PlatformCommerceClient, isPurchaseCredited, isPurchaseExpired, isPurchaseRefunded, isPurchaseRefused, nothingWasCharged };
1633
+ //# sourceMappingURL=chunk-QDHOPJFL.js.map
1634
+ //# sourceMappingURL=chunk-QDHOPJFL.js.map